-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.py
896 lines (774 loc) · 34.7 KB
/
generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
import random
import sqlite3 as sq
import numpy as np
#Dictionary with rules of have many spells are known to class at his level
class_known_spells = {
"Artificer": {"quantity": "{intelligence_modifier} + {level}", "max_level": [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]},
"Barbarian": {"quantity": [], "max_level": []}, #no spells for class at all
"Bard": {"quantity": [4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 15, 16, 18, 19, 19, 20, 22, 22, 22], "max_level": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9]},
"Cleric": {"quantity": "{wisdom_modifier} + {level}", "max_level": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9]},
"Druid": {"quantity": "{wisdom_modifier} + {level}", "max_level": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9]},
"Fighter": {"quantity": [], "max_level": []}, #no spells for class at all
"Monk": {"quantity": [], "max_level": []}, #no spells for class at all
"Paladin": {"quantity": "{charisma_modifier} + ceil(0.5*{level})", "max_level": [0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]},
"Ranger": {"quantity": [0, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11], "max_level": [0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]},
"Rogue": {"quantity": [], "max_level": []}, #no spells for class at all
"Sorcerer": {"quantity": [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12, 13, 13, 14, 14, 15, 15, 15, 15], "max_level": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9]},
"Warlock": {"quantity": [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15], "max_level": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]},
"Wizard": {"quantity": "{intelligence_modifier} + {level}", "max_level": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9]},
}
def get_quantity(mod, level, class_name):
match class_name:
case "Artificer":
return mod + level
case "Cleric":
return mod + level
case "Druid":
return mod + level
case "Paladin":
return mod + int(level/2)
case "Wizard":
return mod + level
#Dictionary with rules of have many cantrips are known to class at his level
class_known_cantrips = {
"Artificer": {"quantity": [2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4]},
"Barbarian": {"quantity": []}, #can't cast as far as i see
"Bard": {"quantity": [2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]},
"Cleric": {"quantity": [3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]},
"Druid": {"quantity": [2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]},
"Fighter": {"quantity": []}, #can't cast as far as i see
"Monk": {"quantity": []}, #can't cast as far as i see
"Paladin": {"quantity": []}, #can't cast as far as i see
"Ranger": {"quantity": []}, #can't cast as far as i see
"Rogue": {"quantity": []}, #can't cast as far as i see
"Sorcerer": {"quantity": [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]},
"Warlock": {"quantity": [2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]},
"Wizard": {"quantity": [3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]},
}
# Dictionary mapping D&D classes to their main and secondary characteristics
class_characteristics = {
"Artificer": {"main": "Intelligence", "secondary": "Constitution"},
"Barbarian": {"main": "Strength", "secondary": "Constitution"},
"Bard": {"main": "Charisma", "secondary": "Dexterity"},
"Cleric": {"main": "Wisdom", "secondary": "Constitution"},
"Druid": {"main": "Wisdom", "secondary": "Dexterity"},
"Fighter": {"main": "Strength", "secondary": "Constitution"},
"Monk": {"main": "Dexterity", "secondary": "Wisdom"},
"Paladin": {"main": "Strength", "secondary": "Charisma"},
"Ranger": {"main": "Dexterity", "secondary": "Wisdom"},
"Rogue": {"main": "Dexterity", "secondary": "Intelligence"},
"Sorcerer": {"main": "Charisma", "secondary": "Constitution"},
"Warlock": {"main": "Charisma", "secondary": "Wisdom"},
"Wizard": {"main": "Intelligence", "secondary": "Wisdom"},
}
# Dictionary mapping the code above to correctly work with db
db_mapping_characteristics = {
"Strength": "str",
"Dexterity": "dex",
"Constitution": "con",
"Intelligence": "int",
"Wisdom": "wis",
"Charisma": "cha"
}
race_feats = {
"Dwarf": {"main": "Constitution", "secondary": None},
"Elf": {"main": "Dexterity", "secondary": None},
"Halfling": {"main": "Dexterity", "secondary": None},
"Human": {"main": None, "secondary": None}, #all +1
"Aasimar": {"main": "Charisma", "secondary": None},
"Dragonborn": {"main": "Strength", "secondary": "Charisma"},
"Gnome": {"main": "Intelligence", "secondary": None},
"Goliath": {"main": "Strength", "secondary": "Constitution"},
"Orc": {"main": "Strength", "secondary": "Constitution"},
"Tiefling": {"main": "Charisma", "secondary": "Intelligence"},
"Aarakocra": {"main": "Dexterity", "secondary": "Wisdom"},
"Bugbear": {"main": "Strength", "secondary": "Dexterity"},
"Centaur": {"main": "Strength", "secondary": "Wisdom"},
"Air Genasi": {"main": "Dexterity", "secondary": "Wisdom"},
"Changeling": {"main": "Charisma", "secondary": None},
"Earth Genasi": {"main": "Constitution", "secondary": "Strength"},
"Deep Gnome": {"main": "Intelligence", "secondary": "Dexterity"},
"Duergar": {"main": "Strength", "secondary": "Constitution"},
"Eladrin": {"main": "Dexterity", "secondary": "Charisma"},
"Firbolg": {"main": "Wisdom", "secondary": "Strength"},
"Fire Genasi": {"main": "Intelligence", "secondary": "Charisma"},
"Githyanki": {"main": "Strength", "secondary": "Intelligence"},
"Githzerai": {"main": "Wisdom", "secondary": "Intelligence"},
"Goblin": {"main": "Dexterity", "secondary": "Constitution"},
"Hobgoblin": {"main": "Strength", "secondary": "Intelligence"},
"Haregon": {"main": "Dexterity", "secondary": "Constitution"},
"Kenku": {"main": "Dexterity", "secondary": "Wisdom"},
"Kobold": {"main": "Dexterity", "secondary": "Intelligence"},
"Lizardfolk": {"main": "Constitution", "secondary": "Wisdom"},
"Sea Elf": {"main": "Dexterity", "secondary": "Wisdom"},
"Shadar-kai": {"main": "Dexterity", "secondary": "Charisma"},
"Shifter": {"main": "Dexterity", "secondary": "Strength"},
"Tabaxi": {"main": "Dexterity", "secondary": "Charisma"},
"Tortle": {"main": "Constitution", "secondary": None},
"Triton": {"main": "Constitution", "secondary": "Charisma"},
"Water Genasi": {"main": "Wisdom", "secondary": "Constitution"},
"Yuan-ti": {"main": "Charisma", "secondary": "Intelligence"},
"Kender": {"main": "Dexterity", "secondary": "Charisma"},
"Astral Elf": {"main": "Dexterity", "secondary": "Intelligence"},
"Autognome": {"main": "Constitution", "secondary": "Intelligence"},
"Giff": {"main": "Strength", "secondary": "Constitution"},
"Hadozee": {"main": "Dexterity", "secondary": "Strength"},
"Plasmoid": {"main": "Constitution", "secondary": None},
"Thri-kreen": {"main": "Dexterity", "secondary": "Wisdom"},
"Owlin": {"main": "Wisdom", "secondary": "Dexterity"},
"Lineages": {"main": None, "secondary": None}, # Comment: Multiple characteristics
"Leonin": {"main": "Strength", "secondary": "Constitution"},
"Satyr": {"main": "Charisma", "secondary": "Dexterity"},
"Kalashtar": {"main": "Wisdom", "secondary": "Charisma"},
"Warforged": {"main": "Constitution", "secondary": "Strength"},
"Verdan": {"main": "Charisma", "secondary": "Constitution"},
"Loxodon": {"main": "Constitution", "secondary": "Strength"},
"Minotaur": {"main": "Strength", "secondary": "Constitution"},
"Simic Hybrid": {"main": "Constitution", "secondary": "Intelligence"},
"Vedalken": {"main": "Intelligence", "secondary": "Wisdom"},
"Feral Tiefling": {"main": "Dexterity", "secondary": "Charisma"},
"Locathah": {"main": "Wisdom", "secondary": "Constitution"},
"Grung": {"main": "Dexterity", "secondary": "Constitution"},
"Gith": {"main": "Intelligence", "secondary": "Wisdom"},
"Half-Elf": {"main": "Charisma", "secondary": None}, #choose +1
"Half-Orc": {"main": "Strength", "secondary": "Constitution"},
"Bearfolk": {"main": "Strength", "secondary": "Constitution"},
"Darakhul": {"main": "Constitution", "secondary": "Charisma"},
"Erina": {"main": "Charisma", "secondary": "Dexterity"},
"Quickstep": {"main": "Dexterity", "secondary": "Charisma"},
"Ratatosk": {"main": "Dexterity", "secondary": "Wisdom"},
"Satarre": {"main": "Charisma", "secondary": "Intelligence"},
"Shade": {"main": "Dexterity", "secondary": "Charisma"},
"Shadow Goblin": {"main": "Dexterity", "secondary": "Charisma"},
"Naga": {"main": "Wisdom", "secondary": "Intelligence"},
"Fairy": {"main": "Charisma", "secondary": None},
"Nymph": {"main": "Charisma", "secondary": "Wisdom"},
"Siren": {"main": "Charisma", "secondary": "Dexterity"},
"Ravenfolk": {"main": "Wisdom", "secondary": "Dexterity"},
"Medusa": {"main": "Charisma", "secondary": "Dexterity"},
"Mindflayer": {"main": "Intelligence", "secondary": "Charisma"},
"Awakened": {"main": "Intelligence", "secondary": "Wisdom"},
}
background_feats = {
"Acolyte": {"main": "Wisdom", "secondary": "Charisma"},
"Charlatan": {"main": "Dexterity", "secondary": "Intelligence"},
"Criminal": {"main": "Dexterity", "secondary": "Charisma"},
"Entertainer": {"main": "Charisma", "secondary": "Dexterity"},
"Folk Hero": {"main": "Strength", "secondary": "Charisma"},
"Guild Artisan": {"main": "Intelligence", "secondary": "Charisma"},
"Hermit": {"main": "Wisdom", "secondary": "Intelligence"},
"Noble": {"main": "Charisma", "secondary": "Intelligence"},
"Outlander": {"main": "Strength", "secondary": "Wisdom"},
"Sage": {"main": "Intelligence", "secondary": "Wisdom"},
"Sailor": {"main": "Strength", "secondary": "Dexterity"},
"Soldier": {"main": "Strength", "secondary": "Constitution"},
"Urchin": {"main": "Dexterity", "secondary": "Wisdom"},
"Inheritor": {"main": None, "secondary": None}, # Comment: Multiple characteristics
"Feylost": {"main": "Charisma", "secondary": "Wisdom"},
"City Watch": {"main": "Wisdom", "secondary": "Charisma"},
"Far Traveler": {"main": "Charisma", "secondary": "Intelligence"},
"Mercenary Veteran": {"main": "Strength", "secondary": "Constitution"},
"Haunted One": {"main": "Wisdom", "secondary": "Charisma"},
"Recluse": {"main": "Intelligence", "secondary": "Wisdom"},
"Urban Bounty Hunter": {"main": "Dexterity", "secondary": "Charisma"},
}
subclass_dict = {
"Artificer": [
"Alchemist",
"Armorer",
"Battle Smith",
"Artillerist",
],
"Barbarian": [
"Berserker",
"Totem Warrior",
"Ancestral Guardian",
"Storm Herald",
"Zealot",
"Beast",
],
"Bard": [
"Lore",
"Valor",
"Swords",
"College of Whispers",
"Glamour",
"Creation",
],
"Cleric": [
"Life",
"Light",
"Nature",
"War",
"Trickery",
"Knowledge",
"Arcana",
"Forge",
"Grave",
],
"Druid": [
"Circle of the Moon",
"Circle of the Land",
"Circle of Spores",
"Circle of Stars",
"Circle of Wildfire",
],
"Fighter": [
"Champion",
"Battle Master",
"Eldritch Knight",
"Arcane Archer",
"Cavalier",
"Samurai",
"Rune Knight",
"Echo Knight",
],
"Monk": [
"Way of the Open Hand",
"Way of Shadow",
"Way of the Four Elements",
"Way of the Drunken Master",
"Way of the Kensei",
"Way of the Astral Self",
"Way of the Sun Soul",
],
"Paladin": [
"Oath of Devotion",
"Oath of the Ancients",
"Oath of Vengeance",
"Oath of Conquest",
"Oath of Redemption",
"Oath of Glory",
"Oath of the Crown",
],
"Ranger": [
"Hunter",
"Beast Master",
"Gloom Stalker",
"Horizon Walker",
"Monster Slayer",
],
"Rogue": [
"Thief",
"Assassin",
"Arcane Trickster",
"Inquisitive",
"Mastermind",
"Swashbuckler",
"Phantom",
"Soulknife",
],
"Sorcerer": [
"Draconic Bloodline",
"Wild Magic",
"Divine Soul",
"Shadow Magic",
"Storm Sorcery",
"Aberrant Mind",
"Clockwork Soul",
],
"Warlock": [
"The Archfey",
"The Fiend",
"The Great Old One",
"The Celestial",
"The Hexblade",
"The Fathomless",
"The Genie",
],
"Wizard": [
"School of Abjuration",
"School of Conjuration",
"School of Divination",
"School of Enchantment",
"School of Evocation",
"School of Illusion",
"School of Necromancy",
"School of Transmutation",
"School of War Magic",
],
}
# Inside the database the names for subclasses are indexes for ttg.club
db_mapping_subclasses = {
'Alchemist': 'alchemist',
'Armorer': 'armorer',
'Battle Smith': 'battle_smith',
'Artillerist': 'artillerist',
'Berserker': 'berserker',
'Totem Warrior': 'totem_warrior',
'Ancestral Guardian': 'ancestral_guardian',
'Storm Herald': 'storm_herald',
'Zealot': 'zealot',
'Beast': 'beast',
'Lore': 'lore',
'Valor': 'valor',
'Swords': 'swords',
'College of Whispers': 'whispers',
'Glamour': 'glamour',
'Creation': 'creation',
'Life': "life",
'Light': 'light',
'Nature': 'nature',
'War': 'war',
'Trickery': 'trickery',
'Knowledge': 'knowledge',
'Arcana': 'arcana',
'Forge': 'forge',
'Grave': 'grave',
'Circle of the Moon': 'moon',
'Circle of the Land': 'land',
'Circle of Spores': 'spores',
'Circle of Stars': 'stars',
'Circle of Wildfire': 'wildfire',
'Champion': 'champion',
'Battle Master': 'battle_master',
'Eldritch Knight': 'eldritch_knight',
'Arcane Archer': 'arcane_archer',
'Cavalier': 'cavalier',
'Samurai': 'samurai',
'Rune Knight': 'rune_knight',
'Echo Knight': 'echo',
'Way of the Open Hand': 'open_hand',
'Way of Shadow': 'shadow',
'Way of the Four Elements': 'four_elements',
'Way of the Drunken Master': 'drunken_master',
'Way of the Kensei': 'kensei',
'Way of the Astral Self': 'astral_self',
'Way of the Sun Soul': 'sun_soul',
'Oath of Devotion': 'devotion',
'Oath of the Ancients': 'ancients',
'Oath of Vengeance': 'vengeance',
'Oath of Conquest': 'conquest',
'Oath of Redemption': 'redemption',
'Oath of Glory': 'glory',
'Oath of the Crown': 'crown',
'Hunter': 'hunter',
'Beast Master': 'beast_master',
'Gloom Stalker': 'gloom_stalker',
'Horizon Walker': 'horizon_walker',
'Monster Slayer': 'monster_slayer',
'Thief': 'thief',
'Assassin': 'assassin',
'Arcane Trickster': 'arcane_trickster',
'Inquisitive': 'inquisitive',
'Mastermind': 'mastermind',
'Swashbuckler': 'swashbuckler',
'Phantom': 'phantom',
'Soulknife': 'soulknife',
'Draconic Bloodline': 'draconic',
'Wild Magic': 'wild_magic',
'Divine Soul': 'devine_soul',
'Shadow Magic': 'shadow',
'Storm Sorcery': 'storm',
'Aberrant Mind': 'aberrant_mind',
'Clockwork Soul': 'clockwork_soul',
'The Archfey': 'archfey',
'The Fiend': 'fiend',
'The Great Old One': 'great_old_one',
'The Celestial': 'celestial',
'The Hexblade': 'hexblade',
'The Fathomless': 'fathomless',
'The Genie': 'genie',
'School of Abjuration': 'abjuration',
'School of Conjuration': 'conjuration',
'School of Divination': 'divination',
'School of Enchantment': 'enchantment',
'School of Evocation': 'evocation',
'School of Illusion': 'illusion',
'School of Necromancy': 'necromancy',
'School of Transmutation': 'transmutation',
'School of War Magic': 'warmage',
}
def roll_ability_scores():
"""Roll 4d6 and drop the lowest die to generate an ability score."""
scores = []
for _ in range(6):
roll = sorted([random.randint(1, 6) for _ in range(4)])
score = sum(roll[1:]) # Drop the lowest die
scores.append(score)
return scores
def calculate_modifier(score):
"""Calculate the ability modifier from the ability score."""
return (score - 10) // 2
def get_characteristics(character_class):
"""Return the main and secondary characteristics for the given character class."""
return class_characteristics.get(character_class, None)
def get_optimal_race(character_class):
"""Return the character race that is most associated with the given character class."""
if character_class not in class_characteristics:
return "Unknown character class"
class_feats = class_characteristics[character_class]
main_feat = class_feats["main"]
secondary_feat = class_feats["secondary"]
best_races = []
optimal_races = []
for race, feats in race_feats.items():
if feats["main"] == main_feat and feats["secondary"] == secondary_feat:
best_races.append(race)
if feats["main"] == main_feat:
optimal_races.append(race)
elif feats["secondary"] == secondary_feat:
optimal_races.append(race)
if not optimal_races and not best_races:
return "No optimal race found for this class"
if not best_races:
return optimal_races
return best_races
def get_character_class(character_race):
"""Return the character class that is most associated with the given character race."""
if character_race not in race_feats:
return "Unknown character race"
race_feats_data = race_feats[character_race]
main_feat = race_feats_data["main"]
secondary_feat = race_feats_data["secondary"]
best_classes = []
optimal_classes = []
for character_class, feats in class_characteristics.items():
if feats["main"] == main_feat and feats["secondary"] == secondary_feat:
best_classes.append(character_class)
if feats["main"] == main_feat:
optimal_classes.append(character_class)
elif feats["secondary"] == secondary_feat:
optimal_classes.append(character_class)
if not optimal_classes and not best_classes:
return "No optimal class found for this race"
if not best_classes:
return optimal_classes
return best_classes
def get_random_background():
backgrounds = list(background_feats)
return [backgrounds[random.randint(0, len(backgrounds) - 1)]]
def get_character_background(character_race, character_class):
"""Return the character background that is most associated with the given character race and class."""
if character_race not in race_feats or character_class not in class_characteristics:
return get_random_background()
race_feats_data = race_feats[character_race]
class_feats_data = class_characteristics[character_class]
race_main_feat = race_feats_data["main"]
race_secondary_feat = race_feats_data["secondary"]
class_main_feat = class_feats_data["main"]
class_secondary_feat = class_feats_data["secondary"]
optimal_backgrounds = []
suboptimal_backgrounds = []
for background, traits in background_feats.items():
main_feat_full_match = traits["main"] == class_main_feat and traits["main"] == race_main_feat
main_feat_half_match = traits["main"] == class_main_feat or traits["main"] == race_main_feat
secondary_feat_full_match = traits["secondary"] == class_secondary_feat and traits["secondary"] == race_secondary_feat
secondary_feat_half_match = traits["secondary"] == class_secondary_feat or traits["secondary"] == race_secondary_feat
if main_feat_full_match and secondary_feat_full_match:
optimal_backgrounds.append(background)
if main_feat_half_match and secondary_feat_half_match or main_feat_full_match or secondary_feat_full_match:
suboptimal_backgrounds.append(background)
if optimal_backgrounds:
return optimal_backgrounds
if suboptimal_backgrounds:
return suboptimal_backgrounds
return get_random_background()
def generate_character_attributes(character_class):
"""Generate random gender, age, and subclass for a character."""
# List of genders
genders = ["Male", "Female", "Not stated"]
# Generate a random gender
gender = random.choice(genders)
# Generate a random age (example ranges, can be adjusted based on race/class)
age = abs(np.random.normal(20, 30))
if age < 18:
age += 18
age = int(age)
# Personality traits (examples, can be expanded)
personality_traits = [
"Lawful Good", "Neutral Good", "Chaotic Good",
"Lawful Neutral", "True Neutral", "Chaotic Neutral",
"Lawful Evil", "Neutral Evil", "Chaotic Evil",
]
# Generate a random personality trait
personality_trait = random.choice(personality_traits)
# Check if the provided class is valid and get its subclasses
if character_class not in subclass_dict:
return "Unknown character class"
# Choose a random subclass from the provided class
subclass = random.choice(subclass_dict[character_class])
return {
"Gender": gender,
"Age": age,
"Subclass": subclass,
"Personality Trait": personality_trait
}
def get_random_class():
"""Randomly select a character class from the predefined classes."""
classes = list(subclass_dict.keys())
return random.choice(classes)
def get_random_race():
"""Randomly select a character race from the predefined races."""
races = list(race_feats.keys())
return random.choice(races)
def add_race_and_background_bonuses(assigned_scores, character_race, character_background):
"""Add racial and background bonuses to the character's ability scores."""
# Define the mapping of ability names to their respective indices in the list
ability_indices = {
"Strength": 0,
"Dexterity": 1,
"Constitution": 2,
"Intelligence": 3,
"Wisdom": 4,
"Charisma": 5
}
# Add race bonuses
if character_race in race_feats:
main_ability = race_feats[character_race]["main"]
secondary_ability = race_feats[character_race]["secondary"]
# Apply bonuses (assuming +2 for main and +1 for secondary)
if main_ability != None:
assigned_scores[ability_indices[main_ability]] += 2
if secondary_ability != None:
assigned_scores[ability_indices[secondary_ability]] += 1
# Add background bonuses
if character_background in background_feats:
main_ability = background_feats[character_background]["main"]
secondary_ability = background_feats[character_background]["secondary"]
# Apply bonuses (assuming +2 for main and +1 for secondary)
if main_ability != None:
assigned_scores[ability_indices[main_ability]] += 2
if secondary_ability != None:
assigned_scores[ability_indices[secondary_ability]] += 1
return assigned_scores
def automatic_choose_spells(sorted_spell_list, class_name, level, scores):
number_of_spells = class_known_spells[class_name]
if len(number_of_spells['quantity']) == 0:
spell_limit = 0
elif len(number_of_spells['quantity']) == 20:
spell_limit = number_of_spells['quantity'][level-1]
else:
#print(scores)
mod = (number_of_spells['quantity'].split('_')[0][1:]).capitalize()
mod = calculate_modifier(scores[mod])
spell_limit = get_quantity(mod, level, class_name)
if len(sorted_spell_list) > spell_limit:
#print(f"{spell_limit=}") #TESTING
best_spells = sorted_spell_list[-int(spell_limit/4):]
random.shuffle(sorted_spell_list)
random.shuffle(sorted_spell_list)
final_spell_list = set([*sorted_spell_list, *best_spells][-spell_limit:])
#print(len(final_spell_list))
return final_spell_list
#print(sorted_spell_list)
#random.shuffle(list(spells.keys()))
return sorted_spell_list[-spell_limit:]
# Create query to db to fetch list of spells
def get_spells(class_name, subclass_name, level, scores):
"""Create query to db to fetch list of spells"""
db = sq.connect("app/dnd_test.db") #change according to db file path
cur = db.cursor()
number_of_spells = class_known_spells[class_name]
if len(number_of_spells['max_level']) == 0:
spell_level = 0
else:
spell_level = number_of_spells['max_level'][level-1]
#print(spell_limit)
#print(spell_level)
subclass_name = db_mapping_subclasses[subclass_name]
query = """
SELECT spell_name, rating
FROM spells
WHERE (classes LIKE ? OR subclasses LIKE ?)
AND level <= ?;
"""
cur.execute(query, (f"%{class_name.lower()}%", f"%{subclass_name}%", spell_level))
output = cur.fetchall()
#print(output)
spells = {row[0]: row[1] for row in output}
if len(list(spells.keys())) == 0:
return []
#print(f"{len(spells)=}")
#print(spells.keys())
sorted_spell_list = [k for k, v in sorted(spells.items(), key=lambda item: item[1])]
return sorted_spell_list
def random_generation():
character = {}
# Get user input
#character_class = input("Enter your D&D character class: ").strip().title()
#Generate random class
character_class = get_random_class()
# Get characteristics
characteristics = get_characteristics(character_class)
main_characteristics = characteristics["main"]
secondary_characteristics = characteristics["secondary"]
# Output results
if characteristics:
#print(f"\nClass: {character_class}") # CLASS
character["Class"] = character_class
#print(f"Main Characteristic: {main_characteristics}") # MAIN CHARACTERISTIC
character["Main Characteristic"] = main_characteristics
#print(f"Secondary Characteristic: {secondary_characteristics}") # SECONDARY CHARACTERISTIC
character["Secondary Characteristic"] = secondary_characteristics
# Generate optimal race for class
optimal_race = get_optimal_race(character_class)
random.shuffle(optimal_race)
character_race = optimal_race[0]
#print(f"Race: {character_race}") # RACE
character["Race"] = character_race
# Generate random subclass, age and gender
for key, value in generate_character_attributes(character_class).items():
#print(f"{key}: {value}") # GENDER, AGE, SUBCLASS, PERSONALITY TRAIT
character[key] = value
# Generate optimal background for race and class
optimal_background = get_character_background(character_race, character_class)
random.shuffle(optimal_background)
character_background = optimal_background[0]
#print(f"Background: {character_background}") # BACKGROUND
character["Background"] = character_background
# Roll ability scores
scores = roll_ability_scores()
ability_names = ["Strength", "Dexterity", "Constitution", "Intelligence", "Wisdom", "Charisma"]
# Sort scores to find the highest and second highest
sorted_scores = sorted(scores)
main_score = sorted_scores[-1]
secondary_score = sorted_scores[-2]
#print("\nRolled Scores:")
#print(*sorted_scores)
# Assign the highest and second-highest scores to main and secondary characteristics
main_index = ability_names.index(main_characteristics)
secondary_index = ability_names.index(secondary_characteristics)
# Create a new scores list with main and secondary scores assigned
assigned_scores = [0 for _ in range(6)]
assigned_scores[main_index] = main_score
assigned_scores[secondary_index] = secondary_score
# Fill in the remaining scores randomly
remaining_scores = sorted_scores[:-2]
random.shuffle(remaining_scores)
# Assign remaining scores to the rest of the ability scores
for i in range(6):
if assigned_scores[i] == 0:
assigned_scores[i] = remaining_scores.pop(0)
# Add race and background bonuses
assigned_scores = add_race_and_background_bonuses(assigned_scores, character_race, character_background)
# Control that each of assigned scores not more than 20
#print("\nAssigned Ability Scores:")
ability_modifiers = {}
for name, score in zip(ability_names, assigned_scores):
ability_modifiers.update({name: score})
character[name] = f"{score} (modifier: {calculate_modifier(score)})"
# Level?)
level = random.randint(1, 20)
#print(f"\nLevel: {level}")
character["Level"] = level
# Spells
character_subclass = character["Subclass"]
spells = get_spells(character_class, character_subclass, level, ability_modifiers)
chosen_spells = automatic_choose_spells(spells, character_class, level, ability_modifiers)
character["Spells"] = chosen_spells
"""if len(spells):
#print(f"\nSpells for {character_class}, {character_subclass}:")
for spell in spells:
print(spell.replace('_', ' ').capitalize())
else:
print(f"\nNo spells provided for {character_class}, {character_subclass}")"""
else:
print("Failed trying to generate character.")
return character
def guided_generation(character_race, character_class, character_subclass, character_background, character_level):
# Get all input information
"""print("\nPlease choose your race - if you don't want to choose just type None")
character_race = str(input())
print("Please choose your class - if you don't want to choose just type None")
character_class = str(input())
print("Choose your subclass - if you don't want to choose just type None")
character_subclass = str(input())
print("Please choose your background - if you don't want to choose just type None")
character_background = str(input())"""
character = {}
#Generate additional information
if character_race.lower() == "random" and character_class.lower() == "random":
character_race = get_random_race()
elif character_race.lower() == "random" and character_class.lower() != "random":
optimal_race = get_optimal_race(character_class)
random.shuffle(optimal_race)
character_race = optimal_race[0]
elif character_race.lower() != "random" and character_class.lower() == "random":
optimal_class = get_character_class(character_race)
random.shuffle(optimal_class)
character_class = optimal_class[0]
if character_background.lower() == "random":
optimal_background = get_character_background(character_race, character_class)
random.shuffle(optimal_background)
character_background = optimal_background[0]
if character_subclass.lower() == "random":
character_subclass = random.choice(subclass_dict[character_class])
#print("\nYour Character:")
# Get characteristics
characteristics = get_characteristics(character_class)
main_characteristics = characteristics["main"]
secondary_characteristics = characteristics["secondary"]
# Output results
if characteristics:
#print(f"\nClass: {character_class}")
character["Class"] = character_class
#print(f"Main Characteristic: {characteristics['main']}")
character["Main Characteristic"] = characteristics["main"]
#print(f"Secondary Characteristic: {characteristics['secondary']}")
character["Secondary Characteristic"] = characteristics["secondary"]
#print(f"\nRace: {character_race}")
character["Race"] = character_race
for key, value in generate_character_attributes(character_class).items():
if key == "Subclass":
#print(f"{key}: {character_subclass}")
character[key] = character_subclass
else:
#print(f"{key}: {value}")
character[key] = value
#print(f"Background: {character_background}")
character["Background"] = character_background
# Roll ability scores
scores = roll_ability_scores()
ability_names = ["Strength", "Dexterity", "Constitution", "Intelligence", "Wisdom", "Charisma"]
# Sort scores to find the highest and second highest
sorted_scores = sorted(scores)
main_score = sorted_scores[-1]
secondary_score = sorted_scores[-2]
#print("\nRolled Scores:")
#print(*sorted_scores)
# Assign the highest and second highest scores to main and secondary characteristics
main_index = ability_names.index(main_characteristics)
secondary_index = ability_names.index(secondary_characteristics)
# Create a new scores list with main and secondary scores assigned
# Create a new scores list with main and secondary scores assigned
assigned_scores = [0 for _ in range(6)]
assigned_scores[main_index] = main_score
assigned_scores[secondary_index] = secondary_score
# Fill in the remaining scores randomly
remaining_scores = sorted_scores[:-2]
random.shuffle(remaining_scores)
# Assign remaining scores to the rest of the ability scores
for i in range(6):
if assigned_scores[i] == 0:
assigned_scores[i] = remaining_scores.pop(0)
# Add race and background bonuses
assigned_scores = add_race_and_background_bonuses(assigned_scores, character_race, character_background)
# Control that each of assigned scores not more than 20
#print("\nAssigned Ability Scores:")
ability_modifiers = {}
for name, score in zip(ability_names, assigned_scores):
ability_modifiers.update({name: score})
#print(f"{name}: {score} (Modifier: {calculate_modifier(score)})")
character[name] = f"{score} (modifier: {calculate_modifier(score)})"
character["Modifiers"] = ability_modifiers
if character_level.lower() == 'random':
character["Level"] = random.randint(1, 20)
else:
character["Level"] = int(character_level)
else:
print("Failed trying to generate character.")
return character
def main():
print("Welcome to the D&D Character Generator!")
print("Please choose generation mode: random(1) or guided(2)")
random_generation()
""" mode = int(input())
if mode == 1:
random_genaration()
elif mode == 2:
guided_generation()
else:
print("Please choose correct mode!")"""
if __name__ == "__main__":
main()