-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
645 lines (565 loc) · 24 KB
/
Copy pathmain.py
File metadata and controls
645 lines (565 loc) · 24 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
from player import Player
from enemy import Enemy, spawn_enemy
import random
import time
import json
import os
from colorama import Fore, Back, Style, init
init(autoreset=True)
def save_game(player):
data = {
"name":player.name,
"health":player.health,
"level":player.level,
"xp":player.xp,
"xp_to_next":player.xp_to_next,
"stat_points":player.stat_points,
"strength":player.strength,
"defense":player.defense,
"mana":player.mana,
"inventory":player.inventory,
"spells":player.spells,
"location":player.location
}
with open("savefile.json", "w") as f:
json.dump(data, f)
print("Game saved successfully.")
def load_game():
if not os.path.exists("savefile.json"):
print("No save file found.")
return None
with open("savefile.json", "r") as f:
data = json.load(f)
from player import Player
player = Player(data["name"])
player.health = data["health"]
player.level = data["level"]
player.xp = data["xp"]
player.xp_to_next = data["xp_to_next"]
player.stat_points = data["stat_points"]
player.strength = data["strength"]
player.defense = data["defense"]
player.mana = data["mana"]
player.inventory = data["inventory"]
player.spells = data["spells"]
player.location = data.get("location", "entrance")
print("Game loaded successfully.")
return player
# === Game World ===
rooms = {
"entrance": {
"description": "You stand before a moss-covered dungeon entrance. A chill wind blows from within.",
"long_description": "You stand at the dungeon's threshold. Behind you lies safety, ahead lies darkness and danger.",
"items": ["sword"],
"exits": {"north": "hallway"}
},
"hallway": {
"description": "A narrow hallway lit by flickering torches.",
"long_description": "The stone walls are cracked, and you hear distant scratching. A skeleton blocks your path!",
"enemy": "skeleton",
"items": [],
"exits": {"south": "entrance", "east": "armory", "north": "goblin_den"}
},
"armory": {
"description": "An abandoned armory with broken weapon racks. Something is still usable in here",
"long_description": "Rusty weapons litter the floor. You spot a usable shield among the debris.",
"items": ["shield", "potion"],
"exits": {"west": "hallway"}
},
"goblin_den": {
"description": "The air smells foul. This must be a goblin nest.",
"long_description": "Bones and trash cover the floor. A goblin snarls at you from the shadows!",
"enemy": "goblin",
"items": ["scroll_fireball"],
"exits": {"south": "hallway", "north": "chasm"}
},
"chasm": {
"description": "A deep chasm separates you from a glowing bridge.",
"long_description": "A brittle wooden bridge crosses a black void. A zombie brute stands on the far side!",
"enemy": "zombie brute",
"items": [],
"exits": {"south": "goblin_den", "north": "ice_caves"}
},
"ice_caves": {
"description": "The temperature drops rapidly. Ice covers every surface.",
"long_description": "You enter the frozen halls of the ice caves. An ice spirit drifts silently toward you.",
"enemy": "ice spirit",
"items": ["scroll_ice_spike"],
"exits": {"south": "chasm", "east": "frost_guardpost"}
},
"frost_guardpost": {
"description": "A ruined guard station, frostbitten and half-buried in snow.",
"long_description": "The remains of armor are frozen to the ground. A shield knight challenges your advance.",
"enemy": "shield knight",
"items": [],
"exits": {"west": "ice_caves", "north": "golem_passage"}
},
"golem_passage": {
"description": "A wide stone tunnel resonates with deep vibrations.",
"long_description": "Footsteps echo loudly. A frost golem stomps toward you with icy fury.",
"enemy": "frost golem",
"items": ["potion"],
"exits": {"south": "frost_guardpost", "north": "wraith_sanctum"}
},
"wraith_sanctum": {
"description": "The walls flicker with magical flames.",
"long_description": "Unholy fire burns in braziers around the room. A flame wraith hisses in fury!",
"enemy": "flame wraith",
"items": ["scroll_lightning_bolt"],
"exits": {"south": "golem_passage", "east": "sentinel_gate"}
},
"sentinel_gate": {
"description": "A sealed gate pulses with arcane energy.",
"long_description": "An arcane sentinel guards the gate with unwavering focus.",
"enemy": "arcane sentinel",
"items": ["scroll_arcane_blast"],
"exits": {"west": "wraith_sanctum", "north": "throne_room"}
},
"throne_room": {
"description": "An enormous throne looms at the end of the chamber.",
"long_description": "The corrupted king glares at you from the throne, power radiating from his form.",
"enemy": "corrupted king",
"items": [],
"exits": {"south": "sentinel_gate"}
}
}
# === Command Functions ===
def take_item(arg, player):
item = arg.strip().lower()
item_database = {
"sword": "A sharp blade with a leather wrapped handle.",
"potion": "A glowing red vial that restores health.",
"map": "A tattered map of the dungeon with scribbled notes.",
"scroll_fireball": "A magical scroll that teaches the spell Fireball.",
"scroll_ice": "A magical scroll that teaches the spell Ice Spike.",
"scroll_lightning": "A powerful scroll that crackles with energy - Lightning Bolt!",
"scroll_mana_surge": "A glowing scroll that restores magical energy - Mana Surge!",
"scroll_arcane": "A rare scroll that teaches Arcane Blast.",
"shield": "A sturdy shield that may block enemy attacks."
}
current_room = rooms[player.location]
if item not in current_room["items"]:
print(f"There is no {item} here.")
return
if len(player.inventory) >= 5 and item not in player.inventory:
print("Your inventory is full. You can't carry any more unique items.")
return
if item in player.inventory:
player.inventory[item]["count"] += 1
else:
player.inventory[item] = {
"desc": item_database[item],
"count": 1
}
current_room["items"].remove(item)
if item.startswith("scroll_"):
spell_name = item.replace("scroll_", "").replace("_", "").title()
print(f"You picked up the Scroll of {spell_name}!")
else:
print(f"You picked up {item}.")
def examine_item(arg, player):
item = arg.strip().lower()
if item in player.inventory:
print(f"{item.capitalize()}: {player.inventory[item]}.")
else:
print(f"You don't have a {item}.")
def drop_item(arg, player):
item = arg.strip().lower()
if item in player.inventory:
del player.inventory[item]
rooms[player.location]["items"].append(item)
print(f"You dropped the {item}.")
print("Items now in room:")
for room_item in rooms[player.location]["items"]:
print(f"- {room_item}")
else:
print("That item isn't in your inventory.")
def draw_bar(label, current, max_val, bar_length=20, color=Fore.GREEN):
filled_length = int(bar_length * current / max_val)
empty_length = bar_length - filled_length
filled = "█" * filled_length
empty = "░" * empty_length
return f"{label}: {color}{filled}{Style.RESET_ALL}{empty} {current}/{max_val}"
def show_inv(arg, player):
if not player.inventory:
print("Your inventory is empty.")
else:
print(f"Inventory ({len(player.inventory)}/5 unique items):")
for item, data in player.inventory.items():
print(f"- {item.capitalize()} x{data['count']}: {data['desc']}")
def use_item(arg, player):
item = arg.strip().lower()
if item not in player.inventory:
print(f"You don't have a {item}.")
elif item == "potion":
heal_amount = 15
player.health += heal_amount
if player.health > 100:
player.health = 100
print("You used a potion and felt a surge of energy!")
print(draw_bar("Health", player.health, 100, color=Fore.RED))
player.inventory[item]["count"] -= 1
if player.inventory[item]["count"] <= 0:
del player.inventory[item]
elif item.startswith("scroll_"):
spell_name = item.replace("scroll_", "").replace("_", " ")
if spell_name in player.spells:
print(f"You already know {spell_name.title()}. You carefully put the scroll back.")
return
player.spells.append(spell_name)
print(f"You read the scroll and learned the spell {spell_name.title()}!")
player.inventory[item]["count"] -= 1
if player.inventory[item]["count"] <= 0:
del player.inventory[item]
else:
print(f"You already know {spell_name.title()}.")
else:
print(f"The {item} can't be used right now.")
def show_help(arg, player):
print("\nAvailable Commands:")
print("- move [direction] → Move to a different room (north, south, east, west)")
print("- take [item] → Pick up an item in the room")
print("- drop [item] → Drop an item from your inventory")
print("- examine [item] → View the description of an item in your inventory")
print("- use [item] → Use an item (like a potion)")
print("- inventory → View all items you're carrying")
print("- look → Inspect the current room for items and exits")
print("- fight → Engage an enemy if one is present in the room")
print("- stats → View your level, XP, and attributes ")
print("- help → Show this list of commands")
print("- quit → Exit the game")
def move(arg, player):
direction = arg.strip().lower()
current_room = rooms[player.location]
if direction in current_room["exits"]:
new_location = current_room["exits"][direction]
player.location = new_location
new_room = rooms[new_location]
print(f"\nYou moved {direction} to the {new_location}.")
print(new_room["description"])
if new_room["items"]:
print(f"You see the following items: {', '.join(new_room['items'])}")
else:
print("There are no items here.")
enemy_name = new_room.get("enemy")
if isinstance(enemy_name, str):
enemy_obj = spawn_enemy(enemy_name)
new_room["enemy"] = enemy_obj # update the room to hold the Enemy object now
print(f"A {enemy_obj.name} stands in your way!")
print("Type 'fight' if you're feeling brave.... or stupid.")
else:
print("You can't go that way.")
def player_look(args, player):
room = rooms[player.location]
print(room["description"])
if room["items"]:
for items in room["items"]:
print(f"You see {items}.")
for direction in room["exits"]:
print(f"There is a path {direction}.")
else:
print("There are no items in here.")
print("Exits:")
for direction in room["exits"]:
print(f"- {direction.capitalize()}")
import time # make sure this is at the top of your file
def fight(args, player):
current_room = rooms[player.location]
enemy = current_room.get("enemy")
spell_actions = {
"fireball": {"mana_cost": 5, "base_damage": 25, "effect": "burn", "chance": 0.3},
"ice spike": {"mana_cost": 7, "base_damage": 30, "effect": "stun", "chance": 0.25},
"lightning bolt": {"mana_cost": 10, "base_damage": 40},
"heal": {"mana_cost": 5, "heal": 20},
"mana_surge": {"mana_cost": 0, "mana_restore": 10},
"arcane_blast": {"mana_cost": 8, "base_damage": 20, "target": "all"}
}
if not enemy:
print("There's no one to fight here.")
return
print(f"A {enemy.name} appears! Prepare for battle!")
time.sleep(1.5)
if enemy.name.lower() == "corrupted king":
print('\nThe Corrupted King glares down at you from his throne of bones.')
time.sleep(1.5)
print('"Another hero come to die... Let me show you the price of defiance."')
time.sleep(2)
while enemy.is_alive() and player.health > 0:
print(draw_bar("Health", player.health, 100, color=Fore.RED))
print(draw_bar("Mana", player.mana, player.max_mana, color=Fore.BLUE))
print("\nWhat will you do?")
if enemy.status_effect == "burn":
print(f"The {enemy.name} takes 5 burn damage.")
enemy.hp -= 5
enemy.status_duration -= 1
time.sleep(1)
if enemy.status_duration <= 0:
enemy.status_effect = None
options = {"1": "quick", "2": "charged", "3": "potion", "4": "run"}
menu_num = 5
for spell in player.spells:
options[str(menu_num)] = spell
menu_num += 1
print("1. Quick Attack")
print("2. Charged Attack")
print("3. Use Potion")
print("4. Run")
if player.spells:
print("\nSpells:")
num = 5
for spell in player.spells:
s = spell_actions.get(spell, {})
mana = s.get("mana_cost", "?")
print(f"{num}. {spell.title()} ({mana} mana)")
num += 1
choice = input("> ").strip()
action = options.get(choice)
if action == "quick":
base = 10
damage = player.cal_damage(base)
print(f"You quickly slash the {enemy.name}!")
time.sleep(1)
elif action == "charged":
if player.attack_cooldowns["charge"] > 0:
turns_left = player.attack_cooldowns["charge"]
print(f"⚠️ Charged Attack is still cooling down: {turns_left} turn(s) remaining.")
time.sleep(1)
continue
base = 20
damage = player.cal_damage(base)
print(f"You unleash a powerful attack on the {enemy.name}!")
player.attack_cooldowns["charge"] = 2
time.sleep(1)
elif action == "potion":
if "potion" not in player.inventory:
print("You can't use what you don't have...")
time.sleep(1)
continue
player.health += 15
if player.health > 100:
player.health = 100
print("You used a potion and felt a surge of energy!")
del player.inventory["potion"]
time.sleep(1)
continue
elif action == "run":
print(f"You ran away! The {enemy.name} mocks your cowardice!")
time.sleep(1)
return
elif action in spell_actions:
spell = spell_actions[action]
cost = spell.get("mana_cost", 0)
if player.mana < cost:
print("Not enough mana!")
print(draw_bar("Mana", player.mana, player.max_mana, color=Fore.BLUE))
time.sleep(1)
continue
player.mana -= cost
if "base_damage" in spell:
damage = player.cal_damage(spell["base_damage"])
print(f"You cast {action.title()} and deal {damage} damage!")
enemy.hp -= damage
time.sleep(1)
if "effect" in spell and random.random() < spell.get("chance", 0):
enemy.status_effect = spell["effect"]
enemy.status_duration = 2
print(f"The {enemy.name} is now affected by {spell['effect']}!")
time.sleep(1)
if "heal" in spell:
player.health += spell["heal"]
if player.health > 100:
player.health = 100
print(f"You restored {spell['heal']} HP.")
time.sleep(1)
if "mana_restore" in spell:
player.mana += spell["mana_restore"]
if player.mana > player.max_mana:
player.mana = player.max_mana
print(f"You restored {spell['mana_restore']} mana.")
time.sleep(1)
continue
else:
print("Invalid action!")
time.sleep(1)
continue
enemy.hp -= damage
if enemy.hp < 0:
enemy.hp = 0
enemy.hp = max(0, enemy.hp)
print(f"{enemy.name} HP is now {enemy.hp}.")
time.sleep(1)
if enemy.is_alive():
taunt = enemy.get_taunt()
if taunt:
print(f'{enemy.name} says: "{taunt}"')
time.sleep(1)
if not enemy.is_alive():
if enemy.name.lower() == "corrupted king" and not getattr(enemy, "phase_two", False):
print("\nThe Corrupted King falls to one knee, laughing darkly...")
time.sleep(1.5)
print('"You think this is over? This body is just a vessel!"')
time.sleep(2)
enemy.hp = 80
enemy.damage += 10
enemy.phase_two = True
enemy.taunts.append("I am eternal!")
return
else:
print(f"You defeated the {enemy.name}!")
time.sleep(1.5)
if enemy.name.lower() == "skeleton":
print("With the skeleton defeated, you notice a narrow hallway leading east.")
time.sleep(1.5)
print("You hear metal clinking in the distance — could be an armory?")
time.sleep(1.5)
if enemy.name.lower() == "corrupted king":
print("\nAs the Corrupted King crumbles, the dungeon begins to tremble...")
time.sleep(1.5)
print("Dark magic unravels in the air, releasing a shockwave of light.")
time.sleep(1.5)
print("His throne of bones collapses into dust beneath your feet.")
time.sleep(2)
print("\nYou have done it.")
time.sleep(1)
print("The evil has been vanquished.")
time.sleep(1)
print("Peace will return to the land once more...")
time.sleep(2)
print("\n🏆 You have WON the game. Thank you for playing! 🏆\n")
exit()
current_room["enemy"] = None
player.xp += enemy.xp_reward
print(f"You gained {enemy.xp_reward} XP.")
time.sleep(1)
while player.xp >= player.xp_to_next and player.level < player.max_lvl:
player.xp -= player.xp_to_next
player.level += 1
player.stat_points += 1
player.xp_to_next = int(player.xp_to_next * 1.25)
print(f"\n*** You leveled up to level {player.level}! ***")
print("You earned 1 stat point. Use 'stats' to spend them.")
time.sleep(1.5)
return
print(f"The {enemy.name} prepares to strike!")
time.sleep(1)
if enemy.status_effect == "stun":
print(f"The {enemy.name} is stunned and can't attack!")
time.sleep(1)
enemy.status_duration -= 1
if enemy.status_duration <= 0:
enemy.status_effect = None
else:
block_choice = input("Do you want to try to block? (y/n): ").strip().lower()
if block_choice == "y":
if "shield" in player.inventory:
if random.random() < 0.5:
print("You block all damage!")
damage_taken = 0
else:
print("You tried to block, but the blow landed!")
damage_taken = enemy.damage
else:
reduced = int(enemy.damage * random.uniform(0.3, 0.5))
print(f"You absorb some of the blow, taking {reduced} damage.")
damage_taken = reduced
else:
damage_taken = enemy.damage
print(f"You take {damage_taken} damage.")
player.health -= damage_taken
time.sleep(1)
if player.health <= 0:
print(f"You were defeated by the {enemy.name}")
time.sleep(1.5)
return
if player.attack_cooldowns["charge"] > 0:
player.attack_cooldowns["charge"] -= 1
def show_stats(args, player):
print("\n====== Player Stats ======")
print(f"Level: {player.level}")
print(f"XP: {player.xp}/{player.xp_to_next}")
print(f"Stat Points Available: {player.stat_points}")
print(f"Strength: {player.strength}/10")
print(f"Defense: {player.defense}/10")
print(f"Mana: {player.mana}/30")
print(f"========================")
def spend_stats(player):
if player.stat_points <= 0:
return
spend = input("You have stat points. Spend them now? (y/n): ").strip().lower()
if spend != "y":
print("Okay, you can spend them later.")
return
while player.stat_points > 0:
print(f"\nYou have {player.stat_points} stat point(s) remaining.")
print("1. Strength")
print("2. Defense")
print("3. Mana")
print("4. Cancel")
choice = input("Choose a stat to upgrade (1-4): ").strip()
if choice == "1" and player.strength < player.max_stat:
player.strength += 1
player.stat_points -= 1
print(f"Strength increased to {player.strength}!")
elif choice == "2" and player.defense < player.max_stat:
player.defense += 1
player.stat_points -= 1
print(f"Defense increased to {player.defense}!")
elif choice == "3" and player.mana < player.max_mana * 10:
player.max_mana += 10
player.mana += 10
if player.mana > player.max_mana:
player.mana = player.max_mana
player.stat_points -= 1
print(f"Mana increased to {player.mana}!")
elif choice == "4":
print("Canceled stat upgrade.")
break
else:
print("Invalid choice or stat is already maxed.")
# === Main Game Loop ===
def main():
print("1. New Game")
print("2. Load Game")
choice = input("Choose an option: ").strip()
if choice == "2":
player = load_game()
if not player:
print("No save found. Starting a new game.")
name = input("What is your name, adventurer? ")
player = Player(name)
else:
name = input("What is your name, adventurer? ")
player = Player(name)
print(f"\nWelcome, {player.name}! Type 'help' to see available commands.\n")
print(rooms[player.location]["long_description"])
print("\nYou see a sword lying nearby. Try typing: take sword")
print("Type 'look' anytime to inspect your surroundings.")
commands = {
"take": take_item,
"examine": examine_item,
"drop": drop_item,
"inventory": show_inv,
"use": use_item,
"move": move,
"look": player_look,
"fight": fight,
"stats": show_stats,
"help": show_help,
"spend": lambda arg, player: spend_stats(player),
"save": lambda arg, player: save_game(player),
"quit": None
}
while True:
choice = input("\nWhat would you like to do? ").lower().strip()
parts = choice.split(" ", 1)
command = parts[0]
argument = parts[1] if len(parts) > 1 else ""
if command == "quit":
print("Goodbye, adventurer!")
break
elif command in commands:
commands[command](argument, player)
else:
print("Invalid command.")
if __name__ == "__main__":
main()