-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWOM.py
More file actions
4876 lines (4104 loc) · 222 KB
/
WOM.py
File metadata and controls
4876 lines (4104 loc) · 222 KB
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import time
import os
import pickle
import sys
from typing import List, Dict, Optional, Tuple
from colorama import Fore, Style, init
# Initialize colorama
init(autoreset=True)
# Check if script is being run directly or through the launcher
if __name__ == "__main__":
launcher_env = os.environ.get("LAUNCHER_ACTIVE")
if not launcher_env:
print(f"{Fore.RED}This game should be launched through the launch.py launcher.")
print(f"{Fore.YELLOW}Please run 'python launch.py' to access all games.")
input("Press Enter to exit...")
print(f"{Fore.BLUE}Made by andy64lol{Style.RESET_ALL}")
sys.exit(0)
# Add GOLD color for trophy/medal display
if not hasattr(Fore, 'GOLD'):
setattr(Fore, 'GOLD', Fore.YELLOW)
# Clear screen function that works across different platforms
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
# File-based save system
SAVE_DIR = "wom_saves"
CHAMPIONS_FILE = os.path.join(SAVE_DIR, "champions.pickle")
# Initialize save directory
def init_database():
"""Initialize the save directory and files"""
try:
# Create save directory if it doesn't exist
os.makedirs(SAVE_DIR, exist_ok=True)
# Create empty champions file if it doesn't exist
if not os.path.exists(CHAMPIONS_FILE):
with open(CHAMPIONS_FILE, 'wb') as f:
pickle.dump([], f)
return True
except Exception as e:
print(f"{Fore.RED}Error initializing save system: {e}{Style.RESET_ALL}")
return False
# Get save file path for a player
def get_save_path(player_name, save_name):
"""Get the file path for a save file"""
return os.path.join(SAVE_DIR, f"{player_name}_{save_name}.pickle")
# Game constants
MAX_MONSTER_LEVEL = 50
MAX_INVENTORY_SIZE = 20
CATCH_BASE_RATE = 0.4
WILD_ENCOUNTER_RATE = 0.3
FUSION_LEVEL_REQUIREMENT = 25
# Move class for attacks
class Move:
def __init__(self, name: str, type_: str, power: int, accuracy: float, description: str):
self.name = name
self.type = type_
self.power = power
self.accuracy = accuracy
self.description = description
def __str__(self) -> str:
return f"{self.name} ({self.type}) - Power: {self.power}, Accuracy: {int(self.accuracy*100)}%"
# Item class for inventory items
class Item:
def __init__(self, name: str, description: str, effect: str, value: int):
self.name = name
self.description = description
self.effect = effect
self.value = value
def __str__(self) -> str:
return f"{self.name} - {self.description}"
# Monster class
class Monster:
def __init__(self, name: str, type_: str, base_hp: int, base_attack: int,
base_defense: int, base_speed: int, moves: List[Move],
description: str, level: int = 5, is_fusion: bool = False,
fusion_components: Optional[List[str]] = None, variant: Optional[str] = None,
rarity: Optional[str] = None):
self.name = name
self.type = type_
self.base_hp = base_hp
self.base_attack = base_attack
self.base_defense = base_defense
self.base_speed = base_speed
self.moves = moves
self.description = description
self.level = level
self.exp = 0
self.exp_to_level = level * 20
self.is_fusion = is_fusion
self.fusion_components = fusion_components or []
# Variant attributes (Omega, Alpha, Corrupted, Crystal, Dominant)
self.variant = variant
self.can_evolve = variant is None # Variants cannot evolve
# Rarity system - assign rarity based on monster name if not provided
self.rarity = rarity or self._determine_rarity()
# Shiny attribute for special variants
self.is_shiny = variant and 'shiny' in variant.lower() if variant else False
# Apply variant stat adjustments if needed
if variant:
self.apply_variant_bonuses()
# Calculated stats
self.calculate_stats()
self.current_hp = self.max_hp
def _determine_rarity(self) -> str:
"""Determine monster rarity based on its name"""
# Define rarity categories based on monster names
legendary_names = ["Chronodrake", "Celestius", "Pyrovern", "Gemdrill", "Shadowclaw", "Tempestus",
"Terraquake", "Luminary", "Chronos", "Spatium", "Cosmix", "Shadowlord", "Vitalia",
"Phantomos", "Moltenking", "Prismatic", "Ancientone", "Deathwarden", "Oceanmaster",
"Stormruler", "Sandstorm", "Frostlord", "Mechagon", "Worldtree", "Voidking", "Nebula",
"Doomreaper"]
rare_names = ["Rockbehemoth", "Psyowl", "Drakeling", "Tornadash", "Volcanix", "Abyssal", "Spectralord",
"Pyrothane", "Crystalking", "Templeguard", "Banshee", "Leviathor", "Skydragon", "Mirageous",
"Glacialtitan", "Cybernetic", "Naturelord", "Starhawk", "Infernus", "Terravore",
"Dreadspirit", "Aquabyss", "Stormrage", "Netherbeast", "Crystallord", "Technocore",
"Forestguard", "Voidreaper"]
uncommon_names = ["Floracat", "Emberbear", "Coralfish", "Boltfox", "Frostbite", "Shadowpaw", "Fairybell",
"Brawlcub", "Aquafin", "Blazehound", "Groundmole", "Thunderwing", "Psyowl", "Vinewhip",
"Glacierclaw", "Metalbeak", "Lavahound", "Gemguard", "Mysticfox", "Ghosthowl", "Tidalwave",
"Stormbird", "Dunestrider", "Blizzardclaw", "Technowolf", "Dreamcatcher", "Voidwalker",
"Cosmicowl"]
if self.name in legendary_names:
return "legendary"
elif self.name in rare_names:
return "rare"
elif self.name in uncommon_names:
return "uncommon"
else:
return "common"
def apply_variant_bonuses(self):
"""Apply stat bonuses based on monster variant"""
variant_name = self.variant
original_name = self.name
if variant_name == "Omega":
# Omega variants have better overall stats
self.base_hp = int(self.base_hp * 1.3)
self.base_attack = int(self.base_attack * 1.3)
self.base_defense = int(self.base_defense * 1.3)
self.base_speed = int(self.base_speed * 1.3)
self.name = f"Omega {original_name}"
self.description = f"An Omega variant of {original_name}. It has superior stats in all categories."
elif variant_name == "Alpha":
# Alpha variants are leaders with balanced but higher stats
self.base_hp = int(self.base_hp * 1.2)
self.base_attack = int(self.base_attack * 1.2)
self.base_defense = int(self.base_defense * 1.2)
self.base_speed = int(self.base_speed * 1.2)
self.name = f"Alpha {original_name}"
self.description = f"An Alpha variant of {original_name}. As the leader of its species, it has well-balanced and enhanced abilities."
elif variant_name == "Corrupted":
# Corrupted variants have more attack but less defense
self.base_hp = int(self.base_hp * 1.1)
self.base_attack = int(self.base_attack * 1.5)
self.base_defense = int(self.base_defense * 0.8)
self.base_speed = int(self.base_speed * 1.2)
self.name = f"Corrupted {original_name}"
self.description = f"A Corrupted variant of {original_name}. It has been tainted by dark energy, giving it tremendous offensive power but weakening its defenses."
elif variant_name == "Crystal":
# Crystal variants have much higher defense but less attack
self.base_hp = int(self.base_hp * 1.1)
self.base_attack = int(self.base_attack * 0.9)
self.base_defense = int(self.base_defense * 1.8)
self.base_speed = int(self.base_speed * 0.8)
self.name = f"Crystal {original_name}"
self.description = f"A Crystal variant of {original_name}. Its body is encased in nearly impenetrable crystalline structures, greatly enhancing its defensive capabilities."
elif variant_name == "Dominant":
# Dominant variants have double stats but are extremely rare
self.base_hp = int(self.base_hp * 2.0)
self.base_attack = int(self.base_attack * 2.0)
self.base_defense = int(self.base_defense * 2.0)
self.base_speed = int(self.base_speed * 2.0)
self.name = f"Dominant {original_name}"
self.description = f"A Dominant variant of {original_name}. This colossal specimen dwarfs others of its kind, possessing truly extraordinary power."
def calculate_stats(self):
"""Calculate stats based on monster level and base stats"""
level_factor = 1 + (self.level / 50)
self.max_hp = int(self.base_hp * level_factor)
self.attack = int(self.base_attack * level_factor)
self.defense = int(self.base_defense * level_factor)
self.speed = int(self.base_speed * level_factor)
def gain_exp(self, amount: int) -> bool:
"""Give exp to monster, return True if leveled up"""
self.exp += amount
if self.exp >= self.exp_to_level:
self.level_up()
return True
return False
def level_up(self):
"""Level up the monster and calculate new stats"""
# Check if player has this monster in their collection (to get trainer level)
player = None
for game_obj in globals().values():
if isinstance(game_obj, Game) and hasattr(game_obj, 'player'):
player = game_obj.player
if player and hasattr(player, 'monsters'):
for monster in player.monsters:
if monster is self: # Check if this is the same object
# Found the player that owns this monster
break
# Apply trainer level cap if applicable
if player and hasattr(player, 'trainer_level'):
if self.level >= player.trainer_level:
# Monster is at or above trainer level, don't level up
print(f"{Fore.YELLOW}Warning: {self.name} cannot level up beyond your trainer level ({player.trainer_level}).{Style.RESET_ALL}")
self.exp = self.exp_to_level - 1 # Cap exp just below next level
return
self.level += 1
if self.level > MAX_MONSTER_LEVEL:
self.level = MAX_MONSTER_LEVEL
return
self.exp = self.exp - self.exp_to_level
self.exp_to_level = self.level * 20
old_max_hp = self.max_hp
self.calculate_stats()
# Heal some HP on level up (the difference plus a bit more)
hp_gain = self.max_hp - old_max_hp + int(self.max_hp * 0.1)
self.current_hp = min(self.max_hp, self.current_hp + hp_gain)
def get_colored_name(self) -> str:
"""Return the name with appropriate color based on type"""
# Dictionary of colors for each type
type_colors = {
"Grass": Fore.GREEN,
"Fire": Fore.RED,
"Water": Fore.BLUE,
"Normal": Fore.WHITE,
"Electric": Fore.YELLOW,
"Ground": Fore.LIGHTYELLOW_EX,
"Rock": Fore.LIGHTBLACK_EX,
"Ice": Fore.LIGHTCYAN_EX,
"Psychic": Fore.MAGENTA,
"Dark": Fore.BLACK,
"Fairy": Fore.LIGHTMAGENTA_EX,
"Dragon": Fore.LIGHTRED_EX,
"Flying": Fore.LIGHTBLUE_EX,
"Fighting": Fore.LIGHTRED_EX,
"Poison": Fore.MAGENTA,
"Time": Fore.CYAN,
"Space": Fore.BLUE,
"Cosmic": Fore.LIGHTMAGENTA_EX + Fore.LIGHTYELLOW_EX,
"Dread": Fore.BLACK + Fore.RED,
"Life": Fore.LIGHTGREEN_EX + Fore.WHITE,
"Ghost": Fore.WHITE + Fore.LIGHTBLACK_EX
}
if self.type in type_colors:
return f"{type_colors[self.type]}{self.name}{Style.RESET_ALL}"
else:
return self.name
def is_fainted(self) -> bool:
"""Check if monster has fainted (HP <= 0)"""
return self.current_hp <= 0
def heal(self, amount: int):
"""Heal the monster by a specific amount"""
self.current_hp = min(self.max_hp, self.current_hp + amount)
def full_heal(self):
"""Fully heal the monster"""
self.current_hp = self.max_hp
def __str__(self) -> str:
"""String representation of a monster"""
hp_percentage = self.current_hp / self.max_hp
hp_bar = "█" * int(hp_percentage * 10) + "░" * (10 - int(hp_percentage * 10))
if hp_percentage > 0.5:
hp_color = Fore.GREEN
elif hp_percentage > 0.2:
hp_color = Fore.YELLOW
else:
hp_color = Fore.RED
# Variant indicator with special color
variant_text = ""
if self.variant:
variant_colors = {
"Omega": Fore.BLUE + Style.BRIGHT,
"Alpha": Fore.RED + Style.BRIGHT,
"Corrupted": Fore.MAGENTA + Style.BRIGHT,
"Crystal": Fore.CYAN + Style.BRIGHT,
"Dominant": Fore.YELLOW + Style.BRIGHT
}
color = variant_colors.get(self.variant, Fore.WHITE)
variant_text = f" [{color}{self.variant}{Style.RESET_ALL}]"
return (f"{self.get_colored_name()}{variant_text} (Lv.{self.level}) - {self.type} Type\n"
f"HP: {hp_color}{self.current_hp}/{self.max_hp} [{hp_bar}]{Style.RESET_ALL}\n"
f"Attack: {self.attack}, Defense: {self.defense}, Speed: {self.speed}\n"
f"EXP: {self.exp}/{self.exp_to_level}")
def clone(self):
"""Create a copy of this monster"""
copy = Monster(
self.name, self.type, self.base_hp, self.base_attack,
self.base_defense, self.base_speed, self.moves,
self.description, self.level, self.is_fusion,
self.fusion_components.copy() if self.fusion_components else None,
self.variant
)
return copy
@staticmethod
def fuse(monster1: 'Monster', monster2: 'Monster') -> Optional['Monster']:
"""Fuse two monsters to create a new, more powerful monster"""
# Check if both monsters meet the level requirement
if monster1.level < FUSION_LEVEL_REQUIREMENT or monster2.level < FUSION_LEVEL_REQUIREMENT:
return None
# Create fusion name (combine parts of both names)
if len(monster1.name) > len(monster2.name):
name_parts = [monster1.name[:len(monster1.name)//2], monster2.name[len(monster2.name)//2:]]
else:
name_parts = [monster1.name[:len(monster1.name)//2], monster2.name[len(monster2.name)//2:]]
fusion_name = ''.join(name_parts)
# Determine fusion type (primary monster's type with influence from secondary)
fusion_type = monster1.type
# Combine stats (primary stats with a boost from secondary)
base_hp = int(monster1.base_hp * 1.2 + monster2.base_hp * 0.3)
base_attack = int(monster1.base_attack * 1.2 + monster2.base_attack * 0.3)
base_defense = int(monster1.base_defense * 1.2 + monster2.base_defense * 0.3)
base_speed = int(monster1.base_speed * 1.2 + monster2.base_speed * 0.3)
# Get best moves from both monsters
# Sort moves by power and take the top 4
combined_moves = monster1.moves + monster2.moves
unique_moves = []
move_names = set()
for move in sorted(combined_moves, key=lambda m: m.power, reverse=True):
if move.name not in move_names and len(unique_moves) < 4:
unique_moves.append(move)
move_names.add(move.name)
# Create fusion description
fusion_desc = f"A powerful fusion of {monster1.name} and {monster2.name}."
# Set fusion level (average of both parents, minimum 25)
fusion_level = max(FUSION_LEVEL_REQUIREMENT, (monster1.level + monster2.level) // 2)
# Create fusion components list
fusion_components = [monster1.name, monster2.name]
if monster1.is_fusion:
fusion_components.extend(monster1.fusion_components)
if monster2.is_fusion:
fusion_components.extend(monster2.fusion_components)
# Create the fusion monster
fusion = Monster(
fusion_name, fusion_type, base_hp, base_attack,
base_defense, base_speed, unique_moves,
fusion_desc, fusion_level, is_fusion=True,
fusion_components=list(set(fusion_components)) # Remove duplicates
)
return fusion
# Player class
class Player:
def __init__(self, name: str):
self.name = name
self.monsters: List[Monster] = []
self.active_monster_index = 0
self.inventory: Dict[Item, int] = {} # Item -> quantity
self.money = 500
self.location = "Hometown"
self.trainer_level = 5 # Starting level
self.exp = 0
self.exp_to_level = 100 # Initial exp needed to level up
# Initialize story progress tracking
self.story_progress = {}
# Initialize quest items
self.quest_items = []
@property
def active_monster(self) -> Optional[Monster]:
"""Get the currently active monster"""
if not self.monsters or self.active_monster_index >= len(self.monsters):
return None
return self.monsters[self.active_monster_index]
def has_usable_monster(self) -> bool:
"""Check if the player has at least one monster that can fight"""
return any(not monster.is_fainted() for monster in self.monsters)
def get_first_usable_monster_index(self) -> int:
"""Get the index of the first usable (non-fainted) monster"""
for i, monster in enumerate(self.monsters):
if not monster.is_fainted():
return i
return -1
def switch_active_monster(self, index: int) -> bool:
"""Switch active monster to the one at the given index"""
if 0 <= index < len(self.monsters):
self.active_monster_index = index
return True
return False
def add_monster(self, monster: Monster):
"""Add a monster to the player's collection"""
self.monsters.append(monster)
def add_item(self, item: Item, quantity: int = 1):
"""Add an item to the inventory"""
if item in self.inventory:
self.inventory[item] += quantity
else:
self.inventory[item] = quantity
def gain_trainer_exp(self, amount: int) -> bool:
"""Give experience to the trainer, return True if leveled up"""
self.exp += amount
if self.exp >= self.exp_to_level:
self.level_up_trainer()
return True
return False
def level_up_trainer(self):
"""Level up the trainer"""
self.trainer_level += 1
self.exp = 0
self.exp_to_level = int(self.exp_to_level * 1.2) # Each level requires more exp
print(f"{Fore.GREEN}You leveled up! You are now a level {self.trainer_level} trainer!{Style.RESET_ALL}")
print("Your monsters' maximum level is now capped at your trainer level.")
# Check if any monsters need level adjustment
for monster in self.monsters:
if monster.level > self.trainer_level:
# Don't actually decrease levels, just cap future growth
print(f"{monster.get_colored_name()} will not grow beyond level {self.trainer_level} until you level up more.")
def use_item(self, item_index: int, target_monster_index: Optional[int] = None) -> str:
"""Use an item from the inventory"""
if target_monster_index is None:
target_monster_index = self.active_monster_index
items = list(self.inventory.keys())
if 0 <= item_index < len(items):
item = items[item_index]
# Check if we have this item
if self.inventory[item] <= 0:
return f"You don't have any {item.name} left."
# Check if target monster exists
if target_monster_index >= len(self.monsters):
return "Invalid monster selected."
target_monster = self.monsters[target_monster_index]
# Apply item effect
result = ""
if item.effect == "heal":
heal_amount = item.value
old_hp = target_monster.current_hp
target_monster.heal(heal_amount)
actual_heal = target_monster.current_hp - old_hp
result = f"Restored {actual_heal} HP to {target_monster.get_colored_name()}."
elif item.effect == "revive":
if not target_monster.is_fainted():
return f"{target_monster.get_colored_name()} doesn't need to be revived."
target_monster.current_hp = int(target_monster.max_hp * (item.value / 100.0))
result = f"Revived {target_monster.get_colored_name()} with {target_monster.current_hp} HP."
elif item.effect == "catch":
# This shouldn't be used directly through inventory
result = "You can't use this item outside of battle."
return result
else:
result = f"Used {item.name} on {target_monster.get_colored_name()}."
# Consume the item
self.inventory[item] -= 1
if self.inventory[item] <= 0:
self.inventory.pop(item)
return result
return "Invalid item selected."
# Battle class
class Battle:
def __init__(self, player: Optional[Player], wild_monster: Monster):
self.player = player
self.wild_monster = wild_monster
self.turn = 0
self.is_wild = True
self.can_catch = True
self.is_finished = False
self.result = None # 'win', 'lose', 'run', 'catch'
def calculate_damage(self, attacker: Monster, defender: Monster, move: Move) -> Tuple[int, float]:
"""Calculate damage and type effectiveness for a move"""
# Check for accuracy
if random.random() > move.accuracy:
return 0, 1.0 # Miss
# Base damage formula
damage = (2 * attacker.level / 5 + 2) * move.power * (attacker.attack / defender.defense) / 50 + 2
# Critical hit (1/16 chance)
critical = 1.5 if random.random() < 0.0625 else 1.0
# Type effectiveness
effectiveness = self.calculate_type_effectiveness(move.type, defender.type)
# Random factor (0.85 to 1.0)
random_factor = random.uniform(0.85, 1.0)
# Final damage calculation
final_damage = int(damage * critical * effectiveness * random_factor)
return max(1, final_damage), effectiveness
def calculate_type_effectiveness(self, move_type: str, defender_type: str) -> float:
"""Calculate type effectiveness multiplier"""
# Type effectiveness chart
effectiveness_chart = {
# Format: attacking type -> {defending type: multiplier}
"Grass": {
"Water": 2.0, "Ground": 2.0, "Rock": 2.0,
"Fire": 0.5, "Flying": 0.5, "Poison": 0.5, "Bug": 0.5, "Dragon": 0.5
},
"Fire": {
"Grass": 2.0, "Ice": 2.0, "Bug": 2.0,
"Water": 0.5, "Rock": 0.5, "Dragon": 0.5
},
"Water": {
"Fire": 2.0, "Ground": 2.0, "Rock": 2.0,
"Grass": 0.5, "Dragon": 0.5
},
"Electric": {
"Water": 2.0, "Flying": 2.0,
"Grass": 0.5, "Ground": 0.0, "Dragon": 0.5
},
"Ice": {
"Grass": 2.0, "Ground": 2.0, "Flying": 2.0, "Dragon": 2.0,
"Fire": 0.5, "Water": 0.5
},
"Fighting": {
"Normal": 2.0, "Rock": 2.0, "Ice": 2.0, "Dark": 2.0,
"Flying": 0.5, "Poison": 0.5, "Psychic": 0.5, "Fairy": 0.5
},
"Poison": {
"Grass": 2.0, "Fairy": 2.0,
"Ground": 0.5, "Rock": 0.5, "Poison": 0.5
},
"Ground": {
"Fire": 2.0, "Electric": 2.0, "Poison": 2.0, "Rock": 2.0,
"Grass": 0.5, "Flying": 0.0
},
"Flying": {
"Grass": 2.0, "Fighting": 2.0,
"Electric": 0.5, "Rock": 0.5
},
"Psychic": {
"Fighting": 2.0, "Poison": 2.0,
"Dark": 0.0, "Psychic": 0.5
},
"Rock": {
"Fire": 2.0, "Ice": 2.0, "Flying": 2.0,
"Fighting": 0.5, "Ground": 0.5
},
"Dragon": {
"Dragon": 2.0,
"Fairy": 0.0
},
"Time": {
"Space": 2.0, "Psychic": 2.0, "Ghost": 2.0,
"Dark": 0.5, "Cosmic": 0.5
},
"Space": {
"Time": 2.0, "Fairy": 2.0, "Psychic": 2.0,
"Cosmic": 0.5, "Dragon": 0.5
},
"Cosmic": {
"Dark": 2.0, "Ghost": 2.0, "Psychic": 2.0,
"Time": 0.5, "Space": 0.5, "Dread": 0.5
},
"Dread": {
"Psychic": 2.0, "Life": 2.0, "Ghost": 2.0,
"Dark": 0.5, "Cosmic": 0.5, "Fighting": 0.5
},
"Life": {
"Water": 2.0, "Ground": 2.0, "Rock": 2.0,
"Fire": 0.5, "Dread": 0.5, "Ghost": 0.5
},
"Ghost": {
"Psychic": 2.0, "Ghost": 2.0, "Dark": 2.0,
"Normal": 0.0, "Fighting": 0.0, "Dread": 0.5
},
"Dark": {
"Psychic": 2.0, "Ghost": 2.0,
"Fighting": 0.5, "Dark": 0.5, "Fairy": 0.5
},
"Fairy": {
"Fighting": 2.0, "Dragon": 2.0, "Dark": 2.0,
"Fire": 0.5, "Poison": 0.5
}
}
# If attacker type is in the chart
if move_type in effectiveness_chart:
# If defender type is in the attackers chart
if defender_type in effectiveness_chart[move_type]:
return effectiveness_chart[move_type][defender_type]
# Same type is not very effective
if move_type == defender_type:
return 0.75
# Default effectiveness
return 1.0
def player_turn(self, command: str, argument: Optional[str] = None) -> str:
"""Handle player's turn in battle"""
if self.is_finished:
return "Battle is already over."
if not self.player:
self.is_finished = True
self.result = "lose"
return "No active player found!"
player_monster = self.player.active_monster
if player_monster is None:
self.is_finished = True
self.result = "lose"
return "You have no monsters left to battle!"
result = ""
if command == "fight":
# Use a move to attack
try:
# Ensure argument is not None before conversion
if argument is not None:
move_index = int(argument) - 1
else:
move_index = 0
if 0 <= move_index < len(player_monster.moves):
move = player_monster.moves[move_index]
damage, effectiveness = self.calculate_damage(player_monster, self.wild_monster, move)
# Apply damage
self.wild_monster.current_hp = max(0, self.wild_monster.current_hp - damage)
# Generate result message
result = f"{player_monster.get_colored_name()} used {move.name}!\n"
if damage == 0:
result += "But it missed!"
else:
if effectiveness > 1.5:
result += "It's super effective! "
elif effectiveness < 0.75:
result += "It's not very effective... "
result += f"Dealt {damage} damage to {self.wild_monster.get_colored_name()}."
# Check if wild monster fainted
if self.wild_monster.is_fainted():
exp_gained = self.wild_monster.level * 5
level_up = player_monster.gain_exp(exp_gained)
result += f"\n{self.wild_monster.get_colored_name()} fainted!"
result += f"\n{player_monster.get_colored_name()} gained {exp_gained} EXP."
if level_up:
result += f"\n{player_monster.get_colored_name()} grew to level {player_monster.level}!"
self.is_finished = True
self.result = "win"
return result
else:
return f"Invalid move number. Choose between 1 and {len(player_monster.moves)}."
except ValueError:
return "Please enter a valid move number."
elif command == "catch":
if not self.can_catch:
return "You can't catch this monster!"
# Find monster ball in inventory
monster_ball = None
for item in self.player.inventory:
if item.effect == "catch":
monster_ball = item
break
if monster_ball is None or self.player.inventory[monster_ball] <= 0:
return "You don't have any Monster Balls!"
# Consume the ball
self.player.inventory[monster_ball] -= 1
if self.player.inventory[monster_ball] <= 0:
self.player.inventory.pop(monster_ball)
# Calculate catch probability
hp_factor = 1 - (self.wild_monster.current_hp / self.wild_monster.max_hp)
level_factor = 1 - (self.wild_monster.level / MAX_MONSTER_LEVEL)
catch_rate = CATCH_BASE_RATE + (hp_factor * 0.3) + (level_factor * 0.2)
result = f"You threw a {monster_ball.name} at {self.wild_monster.get_colored_name()}!"
# Animated dots for suspense
print(result, end="")
for _ in range(3):
time.sleep(0.5)
print(".", end="", flush=True)
print()
if random.random() < catch_rate:
# Successful catch
result = f"Gotcha! {self.wild_monster.get_colored_name()} was caught!"
# Add to player's monsters
caught_monster = self.wild_monster.clone() # Clone to avoid sharing state
caught_monster.full_heal() # Heal it up
self.player.add_monster(caught_monster)
self.is_finished = True
self.result = "catch"
else:
# Failed catch
result = f"Oh no! {self.wild_monster.get_colored_name()} broke free!"
elif command == "switch":
try:
if not argument:
return "Please specify a monster number to switch to."
monster_index = int(argument) - 1
if not self.player:
return "Error: Player not available."
if not self.player.monsters:
return "You don't have any monsters to switch to."
if 0 <= monster_index < len(self.player.monsters):
if monster_index == self.player.active_monster_index:
return f"{self.player.monsters[monster_index].get_colored_name()} is already in battle!"
if self.player.monsters[monster_index].is_fainted():
return f"{self.player.monsters[monster_index].get_colored_name()} has fainted and can't battle!"
old_monster = self.player.active_monster
if not old_monster:
return "No active monster to switch from."
self.player.switch_active_monster(monster_index)
if not self.player.active_monster:
return "Failed to switch monsters."
result = f"You withdrew {old_monster.get_colored_name()} and sent out {self.player.active_monster.get_colored_name()}!"
else:
return f"Invalid monster number. Choose between 1 and {len(self.player.monsters)}."
except ValueError:
return "Please enter a valid monster number."
elif command == "item":
try:
if not argument:
return "Please specify an item number to use."
if not self.player:
return "Error: Player not available."
if not hasattr(self.player, 'inventory') or not self.player.inventory:
return "You don't have any items to use."
item_index = int(argument) - 1
items = list(self.player.inventory.keys())
if 0 <= item_index < len(items):
item = items[item_index]
if item.effect == "catch":
return "Use the 'catch' command to throw a Monster Ball."
result = self.player.use_item(item_index)
else:
return f"Invalid item number. Choose between 1 and {len(items)}."
except ValueError:
return "Please enter a valid item number."
elif command == "run":
# 80% chance to run from wild battles
if self.is_wild:
if random.random() < 0.8:
self.is_finished = True
self.result = "run"
return "Got away safely!"
else:
result = "Couldn't escape!"
else:
return "You can't run from this battle!"
else:
return "Invalid command. Try 'fight', 'catch', 'switch', 'item', or 'run'."
# If we get here, it's the wild monster's turn (unless battle ended)
if not self.is_finished:
wild_result = self.wild_monster_turn()
result += "\n\n" + wild_result
return result
def wild_monster_turn(self) -> str:
"""Handle wild monster's turn in battle"""
if not self.wild_monster:
self.is_finished = True
self.result = "win"
return "No wild monster found!"
if self.wild_monster.is_fainted():
self.is_finished = True
self.result = "win"
return f"{self.wild_monster.get_colored_name()} fainted!"
if not self.player:
self.is_finished = True
self.result = "lose"
return "No active player found!"
player_monster = self.player.active_monster
if not player_monster:
self.is_finished = True
self.result = "lose"
return "You have no active monster!"
if player_monster.is_fainted():
# Check if player has any usable monsters left
if not self.player.has_usable_monster():
self.is_finished = True
self.result = "lose"
return "All your monsters have fainted! You rush to the nearest healing center..."
# Auto-switch to next usable monster
next_index = self.player.get_first_usable_monster_index()
old_monster = player_monster
self.player.switch_active_monster(next_index)
if not self.player.active_monster:
return f"{old_monster.get_colored_name()} fainted! No other monsters available!"
return f"{old_monster.get_colored_name()} fainted! You sent out {self.player.active_monster.get_colored_name()}!"
# Choose a random move for the wild monster
move = random.choice(self.wild_monster.moves)
damage, effectiveness = self.calculate_damage(self.wild_monster, player_monster, move)
# Apply damage
player_monster.current_hp = max(0, player_monster.current_hp - damage)
# Generate result message
result = f"Wild {self.wild_monster.get_colored_name()} used {move.name}!\n"
if damage == 0:
result += "But it missed!"
else:
if effectiveness > 1.5:
result += "It's super effective! "
elif effectiveness < 0.75:
result += "It's not very effective... "
result += f"Dealt {damage} damage to {player_monster.get_colored_name()}."
# Check if player monster fainted
if player_monster.is_fainted():
result += f"\n{player_monster.get_colored_name()} fainted!"
# Check if player has any usable monsters left
if not self.player.has_usable_monster():
self.is_finished = True
self.result = "lose"
result += "\nAll your monsters have fainted! You rush to the nearest healing center..."
else:
result += "\nChoose another monster with 'switch <number>'."
return result
# Game class to handle overall game state and flow
class Game:
def __init__(self):
self.player = None
self.current_battle = None
self.running = True
self.all_monsters = self.create_all_monsters()
self.all_items = self.create_all_items()
self.locations = ["Hometown", "Forest", "Cave", "Beach", "Mountain", "Snowy Peaks", "Ancient Ruins",
"Volcanic Crater", "Crystal Caverns", "Mystic Temple", "Haunted Graveyard",
"Underwater City", "Sky Islands", "Desert Oasis", "Frozen Wasteland",
"Neon City", "Enchanted Grove", "Shadow Realm", "Celestial Observatory"]
self.turn_count = 0
self.db_available = init_database()
self.champion_battles_available = True
self.champion_battles_completed = 0
def create_all_monsters(self) -> Dict[str, Monster]:
"""Create all monster templates for the game"""
# Create moves
# Grass moves
leaf_attack = Move("Leaf Attack", "Grass", 40, 1.0, "Attacks with sharp leaves")
vine_whip = Move("Vine Whip", "Grass", 35, 1.0, "Whips the enemy with vines")
seed_bomb = Move("Seed Bomb", "Grass", 55, 0.9, "Launches explosive seeds")
leaf_storm = Move("Leaf Storm", "Grass", 70, 0.8, "Creates a storm of sharp leaves")
# Fire moves
ember = Move("Ember", "Fire", 40, 1.0, "A weak fire attack")
fire_fang = Move("Fire Fang", "Fire", 45, 0.95, "Bites with flaming fangs")
flame_thrower = Move("Flame Thrower", "Fire", 60, 0.85, "Shoots a stream of fire")
fire_blast = Move("Fire Blast", "Fire", 75, 0.8, "A powerful blast of fire")
# Water moves
water_gun = Move("Water Gun", "Water", 40, 1.0, "Shoots a jet of water")
bubble_beam = Move("Bubble Beam", "Water", 45, 0.95, "Fires bubbles at the opponent")
hydro_pump = Move("Hydro Pump", "Water", 65, 0.8, "Blasts water at high pressure")
surf = Move("Surf", "Water", 60, 0.9, "Creates a huge wave")
# Normal moves
tackle = Move("Tackle", "Normal", 35, 1.0, "A basic tackle attack")
scratch = Move("Scratch", "Normal", 30, 1.0, "Scratches with sharp claws")
body_slam = Move("Body Slam", "Normal", 50, 0.9, "Slams body into opponent")
swift = Move("Swift", "Normal", 40, 1.0, "Fires star-shaped rays that never miss")
# Electric moves
spark = Move("Spark", "Electric", 40, 1.0, "A small electric shock")
thunder_shock = Move("Thunder Shock", "Electric", 50, 0.9, "A mild electric attack")
thunderbolt = Move("Thunderbolt", "Electric", 65, 0.85, "A strong electric attack")
thunder = Move("Thunder", "Electric", 75, 0.8, "A massive lightning strike")
# Rock/Ground moves
rock_throw = Move("Rock Throw", "Rock", 50, 0.9, "Throws rocks at the target")
rock_slide = Move("Rock Slide", "Rock", 65, 0.85, "Causes rocks to slide down")
earthquake = Move("Earthquake", "Ground", 70, 0.8, "Creates a powerful earthquake")
sand_tomb = Move("Sand Tomb", "Ground", 55, 0.9, "Traps opponent in quicksand")
earth_power = Move("Earth Power", "Ground", 75, 0.85, "Releases energy from the earth")
# Ice moves
ice_shard = Move("Ice Shard", "Ice", 45, 0.95, "Shoots sharp ice shards")
ice_beam = Move("Ice Beam", "Ice", 65, 0.85, "Fires a freezing beam")
blizzard = Move("Blizzard", "Ice", 75, 0.8, "Creates a freezing snowstorm")
# Psychic moves
psybeam = Move("Psybeam", "Psychic", 55, 0.9, "Fires a strange beam")
psychic_blast = Move("Psychic Blast", "Psychic", 65, 0.85, "Strikes with psychic power")
dream_eater = Move("Dream Eater", "Psychic", 75, 0.8, "Absorbs energy from the opponent's mind")
# Dragon moves
dragon_rage = Move("Dragon Rage", "Dragon", 55, 0.9, "Releases dragon energy")
dragon_claw = Move("Dragon Claw", "Dragon", 65, 0.85, "Slashes with dragon claws")
draco_meteor = Move("Draco Meteor", "Dragon", 90, 0.75, "Summons meteors from the sky")