ysn-rfd commited on
Commit
51281f1
·
verified ·
1 Parent(s): b7dd84a

Upload 5 files

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
  pytorch_directml_cpu_optimized_low_end_pc/dist/pytransform/_pytransform.dll filter=lfs diff=lfs merge=lfs -text
 
 
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
  pytorch_directml_cpu_optimized_low_end_pc/dist/pytransform/_pytransform.dll filter=lfs diff=lfs merge=lfs -text
61
+ Workspace/workspace-8ac4a941-39da-4676-a1bb-2758edbb4672 filter=lfs diff=lfs merge=lfs -text
Workspace/Python_Script_Text_based_RPD_Game.py ADDED
@@ -0,0 +1,1343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # TextWorld Adventure - A Complete Text-Based RPG Game
3
+ # Author: YSNRFD
4
+ # Version: 1.0.0
5
+
6
+ import os
7
+ import sys
8
+ import json
9
+ import random
10
+ import time
11
+ import pickle
12
+ import math
13
+ from enum import Enum
14
+ from typing import Dict, List, Tuple, Optional, Any, Callable
15
+ from dataclasses import dataclass, asdict
16
+ import colorama
17
+ from colorama import Fore, Back, Style
18
+
19
+ # Initialize colorama for cross-platform colored text
20
+ colorama.init()
21
+
22
+ # Game Constants
23
+ GAME_VERSION = "1.0.0"
24
+ GAME_TITLE = "TextWorld Adventure"
25
+ SAVE_FILE = "textworld_save.pkl"
26
+ CONFIG_FILE = "textworld_config.json"
27
+
28
+ # Game Enums
29
+ class ItemType(Enum):
30
+ WEAPON = "weapon"
31
+ ARMOR = "armor"
32
+ CONSUMABLE = "consumable"
33
+ QUEST = "quest"
34
+ MISC = "misc"
35
+
36
+ class SkillType(Enum):
37
+ COMBAT = "combat"
38
+ MAGIC = "magic"
39
+ STEALTH = "stealth"
40
+ SOCIAL = "social"
41
+
42
+ class DamageType(Enum):
43
+ PHYSICAL = "physical"
44
+ FIRE = "fire"
45
+ ICE = "ice"
46
+ LIGHTNING = "lightning"
47
+ POISON = "poison"
48
+
49
+ class QuestStatus(Enum):
50
+ NOT_STARTED = "not_started"
51
+ IN_PROGRESS = "in_progress"
52
+ COMPLETED = "completed"
53
+ FAILED = "failed"
54
+
55
+ # Game Data Classes
56
+ @dataclass
57
+ class Item:
58
+ id: str
59
+ name: str
60
+ description: str
61
+ item_type: ItemType
62
+ value: int
63
+ rarity: str
64
+ stats: Dict[str, int]
65
+ consumable: bool = False
66
+ stackable: bool = False
67
+ max_stack: int = 1
68
+
69
+ def use(self, player):
70
+ if self.consumable:
71
+ if "heal" in self.stats:
72
+ player.health = min(player.max_health, player.health + self.stats["heal"])
73
+ return f"You used {self.name} and restored {self.stats['heal']} health."
74
+ elif "mana" in self.stats:
75
+ player.mana = min(player.max_mana, player.mana + self.stats["mana"])
76
+ return f"You used {self.name} and restored {self.stats['mana']} mana."
77
+ return f"You can't use {self.name}."
78
+
79
+ @dataclass
80
+ class Skill:
81
+ id: str
82
+ name: str
83
+ description: str
84
+ skill_type: SkillType
85
+ level: int = 1
86
+ experience: int = 0
87
+ max_experience: int = 100
88
+
89
+ def add_experience(self, amount):
90
+ self.experience += amount
91
+ leveled_up = False
92
+ while self.experience >= self.max_experience:
93
+ self.experience -= self.max_experience
94
+ self.level += 1
95
+ self.max_experience = int(self.max_experience * 1.5)
96
+ leveled_up = True
97
+ return leveled_up
98
+
99
+ @dataclass
100
+ class Quest:
101
+ id: str
102
+ name: str
103
+ description: str
104
+ objectives: List[str]
105
+ rewards: Dict[str, Any]
106
+ status: QuestStatus = QuestStatus.NOT_STARTED
107
+ progress: Dict[str, int] = None
108
+
109
+ def __post_init__(self):
110
+ if self.progress is None:
111
+ self.progress = {obj: 0 for obj in self.objectives}
112
+
113
+ @dataclass
114
+ class NPC:
115
+ id: str
116
+ name: str
117
+ description: str
118
+ dialogue: Dict[str, List[str]]
119
+ quests: List[str]
120
+ friendly: bool = True
121
+ shop_items: List[Item] = None
122
+
123
+ def get_dialogue(self, topic="default"):
124
+ return self.dialogue.get(topic, self.dialogue.get("default", ["I have nothing to say."]))
125
+
126
+ @dataclass
127
+ class Location:
128
+ id: str
129
+ name: str
130
+ description: str
131
+ exits: Dict[str, str]
132
+ npcs: List[str]
133
+ items: List[str]
134
+ enemies: List[str]
135
+ visited: bool = False
136
+
137
+ def get_description(self, game):
138
+ desc = f"{self.name}\n{'='*len(self.name)}\n{self.description}\n\n"
139
+
140
+ if self.exits:
141
+ desc += "Exits: " + ", ".join(self.exits.keys()) + "\n"
142
+
143
+ if self.npcs:
144
+ npcs = [game.npcs[npc_id] for npc_id in self.npcs]
145
+ desc += "People here: " + ", ".join([npc.name for npc in npcs]) + "\n"
146
+
147
+ if self.items:
148
+ items = [game.items[item_id] for item_id in self.items]
149
+ desc += "Items here: " + ", ".join([item.name for item in items]) + "\n"
150
+
151
+ if self.enemies:
152
+ enemies = [game.enemies[enemy_id] for enemy_id in self.enemies]
153
+ desc += "Enemies here: " + ", ".join([enemy.name for enemy in enemies]) + "\n"
154
+
155
+ return desc
156
+
157
+ @dataclass
158
+ class Enemy:
159
+ id: str
160
+ name: str
161
+ description: str
162
+ level: int
163
+ health: int
164
+ max_health: int
165
+ attack: int
166
+ defense: int
167
+ experience: int
168
+ gold: int
169
+ loot: List[str]
170
+ abilities: List[str]
171
+
172
+ def take_damage(self, damage):
173
+ actual_damage = max(1, damage - self.defense)
174
+ self.health -= actual_damage
175
+ return actual_damage
176
+
177
+ def is_alive(self):
178
+ return self.health > 0
179
+
180
+ @dataclass
181
+ class Player:
182
+ name: str
183
+ level: int = 1
184
+ experience: int = 0
185
+ max_experience: int = 100
186
+ health: int = 100
187
+ max_health: int = 100
188
+ mana: int = 50
189
+ max_mana: int = 50
190
+ attack: int = 10
191
+ defense: int = 5
192
+ gold: int = 50
193
+ inventory: List[Dict[str, Any]] = None
194
+ equipment: Dict[str, str] = None
195
+ skills: Dict[str, Skill] = None
196
+ quests: Dict[str, Quest] = None
197
+ current_location: str = "town_square"
198
+
199
+ def __post_init__(self):
200
+ if self.inventory is None:
201
+ self.inventory = []
202
+ if self.equipment is None:
203
+ self.equipment = {"weapon": None, "armor": None, "accessory": None}
204
+ if self.skills is None:
205
+ self.skills = {
206
+ "combat": Skill("combat", "Combat", "Your skill in fighting", SkillType.COMBAT),
207
+ "magic": Skill("magic", "Magic", "Your skill in casting spells", SkillType.MAGIC),
208
+ "stealth": Skill("stealth", "Stealth", "Your skill in moving unseen", SkillType.STEALTH),
209
+ "social": Skill("social", "Social", "Your skill in interacting with others", SkillType.SOCIAL)
210
+ }
211
+ if self.quests is None:
212
+ self.quests = {}
213
+
214
+ def add_experience(self, amount):
215
+ self.experience += amount
216
+ leveled_up = False
217
+ while self.experience >= self.max_experience:
218
+ self.experience -= self.max_experience
219
+ self.level += 1
220
+ self.max_experience = int(self.max_experience * 1.5)
221
+ self.max_health += 10
222
+ self.health = self.max_health
223
+ self.max_mana += 5
224
+ self.mana = self.max_mana
225
+ self.attack += 2
226
+ self.defense += 1
227
+ leveled_up = True
228
+ return leveled_up
229
+
230
+ def add_item(self, item, quantity=1):
231
+ for inv_item in self.inventory:
232
+ if inv_item["item"].id == item.id and item.stackable:
233
+ inv_item["quantity"] += quantity
234
+ return True
235
+
236
+ self.inventory.append({"item": item, "quantity": quantity})
237
+ return True
238
+
239
+ def remove_item(self, item_id, quantity=1):
240
+ for i, inv_item in enumerate(self.inventory):
241
+ if inv_item["item"].id == item_id:
242
+ if inv_item["quantity"] <= quantity:
243
+ self.inventory.pop(i)
244
+ return True
245
+ else:
246
+ inv_item["quantity"] -= quantity
247
+ return True
248
+ return False
249
+
250
+ def get_item(self, item_id):
251
+ for inv_item in self.inventory:
252
+ if inv_item["item"].id == item_id:
253
+ return inv_item["item"]
254
+ return None
255
+
256
+ def equip_item(self, item_id):
257
+ item = self.get_item(item_id)
258
+ if not item:
259
+ return False, "You don't have that item."
260
+
261
+ if item.item_type == ItemType.WEAPON:
262
+ if self.equipment["weapon"]:
263
+ self.add_item(self.get_item(self.equipment["weapon"]))
264
+ self.equipment["weapon"] = item_id
265
+ self.attack += item.stats.get("attack", 0)
266
+ return True, f"You equipped {item.name}."
267
+
268
+ elif item.item_type == ItemType.ARMOR:
269
+ if self.equipment["armor"]:
270
+ self.add_item(self.get_item(self.equipment["armor"]))
271
+ self.equipment["armor"] = item_id
272
+ self.defense += item.stats.get("defense", 0)
273
+ return True, f"You equipped {item.name}."
274
+
275
+ return False, "You can't equip that item."
276
+
277
+ def get_total_attack(self):
278
+ total = self.attack
279
+ if self.equipment["weapon"]:
280
+ weapon = self.get_item(self.equipment["weapon"])
281
+ if weapon:
282
+ total += weapon.stats.get("attack", 0)
283
+ return total
284
+
285
+ def get_total_defense(self):
286
+ total = self.defense
287
+ if self.equipment["armor"]:
288
+ armor = self.get_item(self.equipment["armor"])
289
+ if armor:
290
+ total += armor.stats.get("defense", 0)
291
+ return total
292
+
293
+ # Game Configuration
294
+ class GameConfig:
295
+ def __init__(self):
296
+ self.settings = {
297
+ "text_speed": 0.03,
298
+ "auto_save": True,
299
+ "auto_save_interval": 300, # seconds
300
+ "color_scheme": "default",
301
+ "difficulty": "normal",
302
+ "debug_mode": False
303
+ }
304
+ self.load_config()
305
+
306
+ def load_config(self):
307
+ try:
308
+ if os.path.exists(CONFIG_FILE):
309
+ with open(CONFIG_FILE, 'r') as f:
310
+ self.settings.update(json.load(f))
311
+ except Exception as e:
312
+ print(f"Error loading config: {e}")
313
+
314
+ def save_config(self):
315
+ try:
316
+ with open(CONFIG_FILE, 'w') as f:
317
+ json.dump(self.settings, f, indent=2)
318
+ except Exception as e:
319
+ print(f"Error saving config: {e}")
320
+
321
+ def get_setting(self, key, default=None):
322
+ return self.settings.get(key, default)
323
+
324
+ def set_setting(self, key, value):
325
+ self.settings[key] = value
326
+ self.save_config()
327
+
328
+ # Plugin System
329
+ class PluginManager:
330
+ def __init__(self, game):
331
+ self.game = game
332
+ self.plugins = {}
333
+ self.hooks = {
334
+ "on_command": [],
335
+ "on_move": [],
336
+ "on_combat": [],
337
+ "on_level_up": [],
338
+ "on_quest_complete": [],
339
+ "on_item_pickup": []
340
+ }
341
+
342
+ def load_plugin(self, plugin_name):
343
+ try:
344
+ # This is a simplified plugin loader
345
+ # In a real implementation, you'd load from files
346
+ if plugin_name == "debug":
347
+ self.plugins[plugin_name] = DebugPlugin(self.game)
348
+ elif plugin_name == "hardcore":
349
+ self.plugins[plugin_name] = HardcorePlugin(self.game)
350
+ return True
351
+ except Exception as e:
352
+ print(f"Error loading plugin {plugin_name}: {e}")
353
+ return False
354
+
355
+ def register_hook(self, hook_name, callback):
356
+ if hook_name in self.hooks:
357
+ self.hooks[hook_name].append(callback)
358
+
359
+ def trigger_hook(self, hook_name, *args, **kwargs):
360
+ if hook_name in self.hooks:
361
+ for callback in self.hooks[hook_name]:
362
+ try:
363
+ callback(*args, **kwargs)
364
+ except Exception as e:
365
+ print(f"Error in hook {hook_name}: {e}")
366
+
367
+ # Base Plugin Class
368
+ class BasePlugin:
369
+ def __init__(self, game):
370
+ self.game = game
371
+ self.name = "Base Plugin"
372
+ self.version = "1.0.0"
373
+ self.description = "Base plugin class"
374
+ self.enabled = True
375
+
376
+ def initialize(self):
377
+ pass
378
+
379
+ def on_command(self, command, args):
380
+ pass
381
+
382
+ def on_move(self, from_location, to_location):
383
+ pass
384
+
385
+ def on_combat(self, player, enemy):
386
+ pass
387
+
388
+ def on_level_up(self, player):
389
+ pass
390
+
391
+ def on_quest_complete(self, quest):
392
+ pass
393
+
394
+ def on_item_pickup(self, item):
395
+ pass
396
+
397
+ # Example Plugins
398
+ class DebugPlugin(BasePlugin):
399
+ def __init__(self, game):
400
+ super().__init__(game)
401
+ self.name = "Debug Plugin"
402
+ self.description = "Adds debug commands to the game"
403
+
404
+ def initialize(self):
405
+ self.game.register_command("debug", self.debug_command)
406
+
407
+ def debug_command(self, args):
408
+ if len(args) < 1:
409
+ return "Usage: debug <command>"
410
+
411
+ cmd = args[0].lower()
412
+ if cmd == "teleport":
413
+ if len(args) < 2:
414
+ return "Usage: debug teleport <location_id>"
415
+ location_id = args[1]
416
+ if location_id in self.game.locations:
417
+ self.game.player.current_location = location_id
418
+ return f"Teleported to {self.game.locations[location_id].name}"
419
+ return "Location not found"
420
+
421
+ elif cmd == "give":
422
+ if len(args) < 2:
423
+ return "Usage: debug give <item_id>"
424
+ item_id = args[1]
425
+ if item_id in self.game.items:
426
+ self.game.player.add_item(self.game.items[item_id])
427
+ return f"Gave {self.game.items[item_id].name}"
428
+ return "Item not found"
429
+
430
+ elif cmd == "level":
431
+ if len(args) < 2:
432
+ return "Usage: debug level <amount>"
433
+ try:
434
+ amount = int(args[1])
435
+ if self.game.player.add_experience(amount):
436
+ return f"Gained {amount} experience and leveled up!"
437
+ return f"Gained {amount} experience"
438
+ except ValueError:
439
+ return "Invalid amount"
440
+
441
+ elif cmd == "heal":
442
+ self.game.player.health = self.game.player.max_health
443
+ self.game.player.mana = self.game.player.max_mana
444
+ return "Fully healed"
445
+
446
+ return "Unknown debug command"
447
+
448
+ class HardcorePlugin(BasePlugin):
449
+ def __init__(self, game):
450
+ super().__init__(game)
451
+ self.name = "Hardcore Mode"
452
+ self.description = "Makes the game more challenging"
453
+
454
+ def initialize(self):
455
+ self.game.register_hook("on_combat", self.on_combat)
456
+ self.game.register_hook("on_level_up", self.on_level_up)
457
+
458
+ def on_combat(self, player, enemy):
459
+ enemy.attack = int(enemy.attack * 1.5)
460
+ enemy.health = int(enemy.health * 1.5)
461
+ enemy.max_health = enemy.health
462
+
463
+ def on_level_up(self, player):
464
+ player.max_health = int(player.max_health * 0.8)
465
+ player.health = player.max_health
466
+
467
+ # Main Game Class
468
+ class TextWorldGame:
469
+ def __init__(self):
470
+ self.config = GameConfig()
471
+ self.plugin_manager = PluginManager(self)
472
+ self.player = None
473
+ self.locations = {}
474
+ self.items = {}
475
+ self.npcs = {}
476
+ self.enemies = {}
477
+ self.quests = {}
478
+ self.running = True
479
+ self.commands = {}
480
+ self.combat_active = False
481
+ self.current_enemy = None
482
+
483
+ self.initialize_game_data()
484
+ self.register_commands()
485
+ self.load_plugins()
486
+
487
+ def initialize_game_data(self):
488
+ # Initialize Items
489
+ self.items = {
490
+ "sword": Item("sword", "Iron Sword", "A simple iron sword", ItemType.WEAPON, 50, "common", {"attack": 5}),
491
+ "shield": Item("shield", "Wooden Shield", "A basic wooden shield", ItemType.ARMOR, 30, "common", {"defense": 3}),
492
+ "potion": Item("potion", "Health Potion", "A red potion that restores health", ItemType.CONSUMABLE, 10, "common", {"heal": 25}, consumable=True, stackable=True, max_stack=10),
493
+ "mana_potion": Item("mana_potion", "Mana Potion", "A blue potion that restores mana", ItemType.CONSUMABLE, 15, "common", {"mana": 15}, consumable=True, stackable=True, max_stack=10),
494
+ "leather_armor": Item("leather_armor", "Leather Armor", "Basic leather armor", ItemType.ARMOR, 40, "common", {"defense": 5}),
495
+ "magic_scroll": Item("magic_scroll", "Magic Scroll", "A scroll containing a magic spell", ItemType.MISC, 100, "rare", {"magic_power": 10}),
496
+ "gold_coin": Item("gold_coin", "Gold Coin", "A shiny gold coin", ItemType.MISC, 1, "common", {}, stackable=True, max_stack=999),
497
+ "dragon_sword": Item("dragon_sword", "Dragon Sword", "A legendary sword forged from dragon scales", ItemType.WEAPON, 1000, "legendary", {"attack": 20, "fire_damage": 10}),
498
+ "dragon_armor": Item("dragon_armor", "Dragon Armor", "Legendary armor made from dragon scales", ItemType.ARMOR, 1500, "legendary", {"defense": 15, "fire_resistance": 20}),
499
+ }
500
+
501
+ # Initialize Enemies
502
+ self.enemies = {
503
+ "goblin": Enemy("goblin", "Goblin", "A small green creature with sharp teeth", 1, 30, 30, 8, 2, 20, 10, ["potion"], ["bite"]),
504
+ "orc": Enemy("orc", "Orc", "A large green brute with a club", 3, 60, 60, 15, 5, 50, 25, ["sword", "potion"], ["smash"]),
505
+ "dragon": Enemy("dragon", "Dragon", "A massive fire-breathing dragon", 10, 200, 200, 30, 15, 200, 500, ["dragon_sword", "dragon_armor"], ["fire_breath", "tail_swipe"]),
506
+ "skeleton": Enemy("skeleton", "Skeleton", "An undead warrior with rusty armor", 2, 40, 40, 12, 4, 30, 15, ["gold_coin"], ["bone_throw"]),
507
+ "dark_wizard": Enemy("dark_wizard", "Dark Wizard", "A powerful spellcaster in dark robes", 5, 80, 80, 20, 8, 100, 100, ["magic_scroll", "mana_potion"], ["fireball", "lightning"]),
508
+ }
509
+
510
+ # Initialize NPCs
511
+ self.npcs = {
512
+ "merchant": NPC("merchant", "Merchant", "A friendly merchant selling various items", {
513
+ "default": ["Welcome to my shop! What can I get for you?", "I have the finest items in town!"],
514
+ "buy": ["What would you like to buy?"],
515
+ "sell": ["What would you like to sell?"],
516
+ "quest": ["I have a quest for you if you're interested."]
517
+ }, ["merchant_quest"], True, [self.items["potion"], self.items["sword"], self.items["shield"]]),
518
+
519
+ "guard": NPC("guard", "Town Guard", "A brave guard protecting the town", {
520
+ "default": ["Halt! State your business.", "The town is safe under my watch."],
521
+ "dragon": ["A dragon has been spotted in the mountains! Be careful if you go there."],
522
+ "quest": ["We need help dealing with the goblins in the forest."]
523
+ }, ["goblin_quest"], True),
524
+
525
+ "wizard": NPC("wizard", "Wizard", "A mysterious wizard with powerful magic", {
526
+ "default": ["Greetings, traveler. I sense great potential in you.", "Magic flows through the world like a river."],
527
+ "magic": ["Magic is the art of manipulating reality itself.", "Would you like to learn some spells?"],
528
+ "quest": ["I need someone to retrieve a rare artifact for me."]
529
+ }, ["wizard_quest"], True),
530
+ }
531
+
532
+ # Initialize Locations
533
+ self.locations = {
534
+ "town_square": Location("town_square", "Town Square", "The central square of the town. People are bustling about.", {
535
+ "north": "town_gate",
536
+ "east": "market",
537
+ "west": "tavern",
538
+ "south": "temple"
539
+ }, ["guard"], [], []),
540
+
541
+ "town_gate": Location("town_gate", "Town Gate", "The main entrance to the town. A large wooden gate stands open.", {
542
+ "south": "town_square",
543
+ "north": "forest_entrance"
544
+ }, [], [], []),
545
+
546
+ "market": Location("market", "Market", "A busy market with merchants selling their wares.", {
547
+ "west": "town_square"
548
+ }, ["merchant"], [], []),
549
+
550
+ "tavern": Location("tavern", "Tavern", "A cozy tavern with a warm fireplace and friendly patrons.", {
551
+ "east": "town_square"
552
+ }, [], ["potion"], []),
553
+
554
+ "temple": Location("temple", "Temple", "A peaceful temple where people come to pray and heal.", {
555
+ "north": "town_square"
556
+ }, [], [], []),
557
+
558
+ "forest_entrance": Location("forest_entrance", "Forest Entrance", "The edge of a dark forest. You can hear strange noises from within.", {
559
+ "south": "town_gate",
560
+ "north": "deep_forest",
561
+ "east": "river",
562
+ "west": "cave_entrance"
563
+ }, [], [], ["goblin"]),
564
+
565
+ "deep_forest": Location("deep_forest", "Deep Forest", "A dense forest with tall trees and little light.", {
566
+ "south": "forest_entrance",
567
+ "north": "mountain_base"
568
+ }, [], [], ["goblin", "skeleton"]),
569
+
570
+ "river": Location("river", "River", "A wide river flowing from the mountains.", {
571
+ "west": "forest_entrance",
572
+ "east": "bridge"
573
+ }, [], [], []),
574
+
575
+ "bridge": Location("bridge", "Bridge", "An old stone bridge crossing the river.", {
576
+ "west": "river",
577
+ "east": "abandoned_tower"
578
+ }, [], [], ["orc"]),
579
+
580
+ "cave_entrance": Location("cave_entrance", "Cave Entrance", "The entrance to a dark cave. You can feel cold air coming from inside.", {
581
+ "east": "forest_entrance",
582
+ "west": "cave_depths"
583
+ }, [], [], ["skeleton"]),
584
+
585
+ "cave_depths": Location("cave_depths", "Cave Depths", "The deepest part of the cave. It's dark and damp here.", {
586
+ "east": "cave_entrance"
587
+ }, [], ["magic_scroll"], ["dark_wizard"]),
588
+
589
+ "mountain_base": Location("mountain_base", "Mountain Base", "The base of a tall mountain. A path leads up.", {
590
+ "south": "deep_forest",
591
+ "north": "mountain_path"
592
+ }, [], [], []),
593
+
594
+ "mountain_path": Location("mountain_path", "Mountain Path", "A narrow path winding up the mountain.", {
595
+ "south": "mountain_base",
596
+ "north": "dragon_lair"
597
+ }, [], [], ["orc"]),
598
+
599
+ "dragon_lair": Location("dragon_lair", "Dragon Lair", "A massive cave where a dragon lives. You can feel the heat.", {
600
+ "south": "mountain_path"
601
+ }, [], [], ["dragon"]),
602
+
603
+ "abandoned_tower": Location("abandoned_tower", "Abandoned Tower", "An old tower that was once home to a powerful wizard.", {
604
+ "west": "bridge"
605
+ }, ["wizard"], [], []),
606
+ }
607
+
608
+ # Initialize Quests
609
+ self.quests = {
610
+ "merchant_quest": Quest("merchant_quest", "Merchant's Request", "The merchant needs you to deliver a package to the wizard.",
611
+ ["Deliver package to wizard"], {"experience": 100, "gold": 50}),
612
+
613
+ "goblin_quest": Quest("goblin_quest", "Goblin Problem", "The town guard needs help dealing with goblins in the forest.",
614
+ ["Defeat 3 goblins"], {"experience": 150, "gold": 75}),
615
+
616
+ "wizard_quest": Quest("wizard_quest", "Wizard's Artifact", "The wizard needs you to retrieve a magic scroll from the cave depths.",
617
+ ["Find magic scroll in cave depths"], {"experience": 200, "gold": 100, "item": "mana_potion"}),
618
+
619
+ "dragon_quest": Quest("dragon_quest", "Dragon Slayer", "A dragon terrorizes the mountains. Someone needs to defeat it.",
620
+ ["Defeat the dragon"], {"experience": 500, "gold": 500, "item": "dragon_sword"}),
621
+ }
622
+
623
+ def register_commands(self):
624
+ self.commands = {
625
+ "help": self.cmd_help,
626
+ "look": self.cmd_look,
627
+ "go": self.cmd_go,
628
+ "move": self.cmd_go,
629
+ "inventory": self.cmd_inventory,
630
+ "inv": self.cmd_inventory,
631
+ "equip": self.cmd_equip,
632
+ "unequip": self.cmd_unequip,
633
+ "use": self.cmd_use,
634
+ "take": self.cmd_take,
635
+ "get": self.cmd_take,
636
+ "drop": self.cmd_drop,
637
+ "talk": self.cmd_talk,
638
+ "attack": self.cmd_attack,
639
+ "fight": self.cmd_attack,
640
+ "quests": self.cmd_quests,
641
+ "status": self.cmd_status,
642
+ "save": self.cmd_save,
643
+ "load": self.cmd_load,
644
+ "quit": self.cmd_quit,
645
+ "exit": self.cmd_quit,
646
+ "rest": self.cmd_rest,
647
+ "skills": self.cmd_skills,
648
+ "shop": self.cmd_shop,
649
+ "buy": self.cmd_buy,
650
+ "sell": self.cmd_sell,
651
+ "map": self.cmd_map,
652
+ "clear": self.cmd_clear,
653
+ "version": self.cmd_version,
654
+ "config": self.cmd_config,
655
+ }
656
+
657
+ def load_plugins(self):
658
+ # Load default plugins
659
+ if self.config.get_setting("debug_mode", False):
660
+ self.plugin_manager.load_plugin("debug")
661
+
662
+ # Initialize all loaded plugins
663
+ for plugin in self.plugin_manager.plugins.values():
664
+ plugin.initialize()
665
+
666
+ def register_command(self, command, callback):
667
+ self.commands[command] = callback
668
+
669
+ def register_hook(self, hook_name, callback):
670
+ self.plugin_manager.register_hook(hook_name, callback)
671
+
672
+ def start(self):
673
+ self.clear_screen()
674
+ self.print_title()
675
+
676
+ # Check for save file
677
+ if os.path.exists(SAVE_FILE):
678
+ choice = self.get_input("A save file exists. Do you want to load it? (y/n): ").lower()
679
+ if choice == 'y':
680
+ self.load_game()
681
+ self.print_slow("Game loaded successfully!")
682
+ self.game_loop()
683
+ return
684
+
685
+ # Character creation
686
+ self.print_slow("Welcome to TextWorld Adventure!")
687
+ self.print_slow("Let's create your character...")
688
+
689
+ name = self.get_input("Enter your character's name: ")
690
+ while not name:
691
+ name = self.get_input("Please enter a valid name: ")
692
+
693
+ self.player = Player(name)
694
+ self.player.add_item(self.items["potion"], 3)
695
+ self.player.add_item(self.items["gold_coin"], 50)
696
+
697
+ self.print_slow(f"\nWelcome, {self.player.name}!")
698
+ self.print_slow("Your adventure begins in the Town Square.")
699
+ self.print_slow("Type 'help' for a list of commands.")
700
+
701
+ self.game_loop()
702
+
703
+ def game_loop(self):
704
+ last_auto_save = time.time()
705
+
706
+ while self.running:
707
+ # Auto-save check
708
+ if self.config.get_setting("auto_save", True):
709
+ if time.time() - last_auto_save > self.config.get_setting("auto_save_interval", 300):
710
+ self.save_game(silent=True)
711
+ last_auto_save = time.time()
712
+
713
+ # Get player input
714
+ if self.combat_active:
715
+ prompt = f"{Fore.RED}[COMBAT]{Style.RESET_ALL} What do you do? > "
716
+ else:
717
+ location = self.locations[self.player.current_location]
718
+ prompt = f"{Fore.GREEN}[{location.name}]{Style.RESET_ALL} What do you do? > "
719
+
720
+ command_input = self.get_input(prompt).strip().lower()
721
+
722
+ # Parse command
723
+ if not command_input:
724
+ continue
725
+
726
+ parts = command_input.split()
727
+ command = parts[0]
728
+ args = parts[1:] if len(parts) > 1 else []
729
+
730
+ # Trigger command hook
731
+ self.plugin_manager.trigger_hook("on_command", command, args)
732
+
733
+ # Execute command
734
+ if command in self.commands:
735
+ try:
736
+ result = self.commands[command](args)
737
+ if result:
738
+ self.print_slow(result)
739
+ except Exception as e:
740
+ self.print_slow(f"Error executing command: {e}")
741
+ else:
742
+ self.print_slow(f"Unknown command: {command}. Type 'help' for available commands.")
743
+
744
+ def cmd_help(self, args):
745
+ help_text = f"""
746
+ {Fore.CYAN}=== TextWorld Adventure Commands ==={Style.RESET_ALL}
747
+
748
+ {Fore.YELLOW}Movement:{Style.RESET_ALL}
749
+ go/move <direction> - Move in a direction (north, south, east, west)
750
+ look - Look around the current location
751
+ map - Show a simple map of the area
752
+
753
+ {Fore.YELLOW}Inventory:{Style.RESET_ALL}
754
+ inventory/inv - Show your inventory
755
+ equip <item> - Equip an item
756
+ unequip <item> - Unequip an item
757
+ use <item> - Use an item
758
+ take/get <item> - Pick up an item
759
+ drop <item> - Drop an item
760
+
761
+ {Fore.YELLOW}Combat:{Style.RESET_ALL}
762
+ attack/fight <enemy> - Attack an enemy
763
+ rest - Rest to restore health and mana
764
+
765
+ {Fore.YELLOW}NPCs:{Style.RESET_ALL}
766
+ talk <npc> - Talk to an NPC
767
+ shop - Open shop interface (if available)
768
+ buy <item> - Buy an item from shop
769
+ sell <item> - Sell an item to shop
770
+
771
+ {Fore.YELLOW}Character:{Style.RESET_ALL}
772
+ status - Show your character status
773
+ skills - Show your skills
774
+ quests - Show your active quests
775
+
776
+ {Fore.YELLOW}System:{Style.RESET_ALL}
777
+ save - Save the game
778
+ load - Load a saved game
779
+ config <setting> <value> - Change game settings
780
+ clear - Clear the screen
781
+ version - Show game version
782
+ quit/exit - Quit the game
783
+ """
784
+ return help_text
785
+
786
+ def cmd_look(self, args):
787
+ location = self.locations[self.player.current_location]
788
+ location.visited = True
789
+ return location.get_description(self)
790
+
791
+ def cmd_go(self, args):
792
+ if not args:
793
+ return "Go where? Specify a direction (north, south, east, west)."
794
+
795
+ direction = args[0].lower()
796
+ location = self.locations[self.player.current_location]
797
+
798
+ if direction not in location.exits:
799
+ return f"You can't go {direction} from here."
800
+
801
+ new_location_id = location.exits[direction]
802
+ new_location = self.locations[new_location_id]
803
+
804
+ # Trigger move hook
805
+ self.plugin_manager.trigger_hook("on_move", self.player.current_location, new_location_id)
806
+
807
+ self.player.current_location = new_location_id
808
+
809
+ # Check for enemies in new location
810
+ if new_location.enemies and random.random() < 0.5:
811
+ enemy_id = random.choice(new_location.enemies)
812
+ enemy = Enemy(**asdict(self.enemies[enemy_id]))
813
+ self.start_combat(enemy)
814
+
815
+ return new_location.get_description(self)
816
+
817
+ def cmd_inventory(self, args):
818
+ if not self.player.inventory:
819
+ return "Your inventory is empty."
820
+
821
+ inv_text = f"{Fore.CYAN}=== Inventory ==={Style.RESET_ALL}\n"
822
+
823
+ for inv_item in self.player.inventory:
824
+ item = inv_item["item"]
825
+ quantity = inv_item["quantity"]
826
+ if quantity > 1:
827
+ inv_text += f"{item.name} x{quantity} - {item.description}\n"
828
+ else:
829
+ inv_text += f"{item.name} - {item.description}\n"
830
+
831
+ # Show equipped items
832
+ inv_text += f"\n{Fore.YELLOW}=== Equipped Items ==={Style.RESET_ALL}\n"
833
+ for slot, item_id in self.player.equipment.items():
834
+ if item_id:
835
+ item = self.player.get_item(item_id)
836
+ if item:
837
+ inv_text += f"{slot.capitalize()}: {item.name}\n"
838
+
839
+ return inv_text
840
+
841
+ def cmd_equip(self, args):
842
+ if not args:
843
+ return "Equip what? Specify an item name."
844
+
845
+ item_name = " ".join(args).lower()
846
+ item = None
847
+
848
+ for inv_item in self.player.inventory:
849
+ if inv_item["item"].name.lower() == item_name:
850
+ item = inv_item["item"]
851
+ break
852
+
853
+ if not item:
854
+ return f"You don't have a {item_name}."
855
+
856
+ success, message = self.player.equip_item(item.id)
857
+ return message
858
+
859
+ def cmd_unequip(self, args):
860
+ if not args:
861
+ return "Unequip what? Specify 'weapon' or 'armor'."
862
+
863
+ slot = args[0].lower()
864
+ if slot not in self.player.equipment:
865
+ return "You can only unequip 'weapon' or 'armor'."
866
+
867
+ if not self.player.equipment[slot]:
868
+ return f"You don't have anything equipped in your {slot} slot."
869
+
870
+ item_id = self.player.equipment[slot]
871
+ item = self.player.get_item(item_id)
872
+
873
+ if item:
874
+ self.player.add_item(item)
875
+ if slot == "weapon":
876
+ self.player.attack -= item.stats.get("attack", 0)
877
+ elif slot == "armor":
878
+ self.player.defense -= item.stats.get("defense", 0)
879
+
880
+ self.player.equipment[slot] = None
881
+ return f"You unequipped {item.name}."
882
+
883
+ def cmd_use(self, args):
884
+ if not args:
885
+ return "Use what? Specify an item name."
886
+
887
+ item_name = " ".join(args).lower()
888
+ item = None
889
+
890
+ for inv_item in self.player.inventory:
891
+ if inv_item["item"].name.lower() == item_name:
892
+ item = inv_item["item"]
893
+ break
894
+
895
+ if not item:
896
+ return f"You don't have a {item_name}."
897
+
898
+ if not item.consumable:
899
+ return f"You can't use {item.name}."
900
+
901
+ result = item.use(self.player)
902
+
903
+ # Trigger item pickup hook (for use as well)
904
+ self.plugin_manager.trigger_hook("on_item_pickup", item)
905
+
906
+ if item.consumable:
907
+ self.player.remove_item(item.id)
908
+
909
+ return result
910
+
911
+ def cmd_take(self, args):
912
+ if not args:
913
+ return "Take what? Specify an item name."
914
+
915
+ item_name = " ".join(args).lower()
916
+ location = self.locations[self.player.current_location]
917
+
918
+ for item_id in location.items[:]:
919
+ item = self.items[item_id]
920
+ if item.name.lower() == item_name:
921
+ self.player.add_item(item)
922
+ location.items.remove(item_id)
923
+
924
+ # Trigger item pickup hook
925
+ self.plugin_manager.trigger_hook("on_item_pickup", item)
926
+
927
+ return f"You took {item.name}."
928
+
929
+ return f"There's no {item_name} here."
930
+
931
+ def cmd_drop(self, args):
932
+ if not args:
933
+ return "Drop what? Specify an item name."
934
+
935
+ item_name = " ".join(args).lower()
936
+ location = self.locations[self.player.current_location]
937
+
938
+ for inv_item in self.player.inventory[:]:
939
+ item = inv_item["item"]
940
+ if item.name.lower() == item_name:
941
+ self.player.remove_item(item.id)
942
+ location.items.append(item.id)
943
+ return f"You dropped {item.name}."
944
+
945
+ return f"You don't have a {item_name}."
946
+
947
+ def cmd_talk(self, args):
948
+ if not args:
949
+ return "Talk to whom? Specify an NPC name."
950
+
951
+ npc_name = " ".join(args).lower()
952
+ location = self.locations[self.player.current_location]
953
+
954
+ for npc_id in location.npcs:
955
+ npc = self.npcs[npc_id]
956
+ if npc.name.lower() == npc_name:
957
+ dialogue = npc.get_dialogue()
958
+ return f"{npc.name}: {random.choice(dialogue)}"
959
+
960
+ return f"There's no one named {npc_name} here."
961
+
962
+ def cmd_attack(self, args):
963
+ if not self.combat_active:
964
+ return "There's nothing to attack here."
965
+
966
+ if not self.current_enemy:
967
+ self.combat_active = False
968
+ return "The enemy has disappeared."
969
+
970
+ # Player attacks
971
+ player_damage = self.player.get_total_attack()
972
+ actual_damage = self.current_enemy.take_damage(player_damage)
973
+
974
+ result = f"You attack {self.current_enemy.name} for {actual_damage} damage!\n"
975
+
976
+ # Trigger combat hook
977
+ self.plugin_manager.trigger_hook("on_combat", self.player, self.current_enemy)
978
+
979
+ if not self.current_enemy.is_alive():
980
+ result += f"You defeated {self.current_enemy.name}!\n"
981
+ result += f"You gained {self.current_enemy.experience} experience and {self.current_enemy.gold} gold!\n"
982
+
983
+ # Level up check
984
+ if self.player.add_experience(self.current_enemy.experience):
985
+ result += f"LEVEL UP! You are now level {self.player.level}!\n"
986
+ # Trigger level up hook
987
+ self.plugin_manager.trigger_hook("on_level_up", self.player)
988
+
989
+ self.player.gold += self.current_enemy.gold
990
+
991
+ # Loot
992
+ if self.current_enemy.loot:
993
+ loot_item = random.choice(self.current_enemy.loot)
994
+ if loot_item in self.items:
995
+ item = self.items[loot_item]
996
+ self.player.add_item(item)
997
+ result += f"You found {item.name}!\n"
998
+
999
+ self.combat_active = False
1000
+ self.current_enemy = None
1001
+
1002
+ # Update quest progress
1003
+ self.update_quest_progress("defeat", self.current_enemy.id if self.current_enemy else "unknown")
1004
+
1005
+ return result
1006
+
1007
+ # Enemy attacks
1008
+ enemy_damage = max(1, self.current_enemy.attack - self.player.get_total_defense())
1009
+ self.player.health -= enemy_damage
1010
+ result += f"{self.current_enemy.name} attacks you for {enemy_damage} damage!\n"
1011
+
1012
+ if self.player.health <= 0:
1013
+ result += f"{Fore.RED}You have been defeated! Game Over.{Style.RESET_ALL}\n"
1014
+ self.running = False
1015
+
1016
+ return result
1017
+
1018
+ def cmd_quests(self, args):
1019
+ if not self.player.quests:
1020
+ return "You don't have any active quests."
1021
+
1022
+ quest_text = f"{Fore.CYAN}=== Active Quests ==={Style.RESET_ALL}\n"
1023
+
1024
+ for quest_id, quest in self.player.quests.items():
1025
+ if quest.status == QuestStatus.IN_PROGRESS:
1026
+ quest_text += f"{Fore.YELLOW}{quest.name}{Style.RESET_ALL}\n"
1027
+ quest_text += f" {quest.description}\n"
1028
+ quest_text += " Objectives:\n"
1029
+ for obj, progress in quest.progress.items():
1030
+ quest_text += f" - {obj}: {progress}\n"
1031
+ quest_text += "\n"
1032
+
1033
+ return quest_text
1034
+
1035
+ def cmd_status(self, args):
1036
+ status_text = f"""
1037
+ {Fore.CYAN}=== Character Status ==={Style.RESET_ALL}
1038
+ Name: {self.player.name}
1039
+ Level: {self.player.level} ({self.player.experience}/{self.player.max_experience} XP)
1040
+ Health: {self.player.health}/{self.player.max_health}
1041
+ Mana: {self.player.mana}/{self.player.max_mana}
1042
+ Attack: {self.player.get_total_attack()} (Base: {self.player.attack})
1043
+ Defense: {self.player.get_total_defense()} (Base: {self.player.defense})
1044
+ Gold: {self.player.gold}
1045
+ Location: {self.locations[self.player.current_location].name}
1046
+ """
1047
+ return status_text
1048
+
1049
+ def cmd_save(self, args):
1050
+ return self.save_game()
1051
+
1052
+ def cmd_load(self, args):
1053
+ return self.load_game()
1054
+
1055
+ def cmd_quit(self, args):
1056
+ choice = self.get_input("Are you sure you want to quit? (y/n): ").lower()
1057
+ if choice == 'y':
1058
+ self.save_game()
1059
+ self.running = False
1060
+ return "Thanks for playing TextWorld Adventure!"
1061
+ return "Continuing game..."
1062
+
1063
+ def cmd_rest(self, args):
1064
+ if self.combat_active:
1065
+ return "You can't rest during combat!"
1066
+
1067
+ location = self.locations[self.player.current_location]
1068
+
1069
+ # Can only rest in safe locations
1070
+ if location.id in ["town_square", "tavern", "temple"]:
1071
+ self.player.health = self.player.max_health
1072
+ self.player.mana = self.player.max_mana
1073
+ return "You rest and recover your health and mana."
1074
+
1075
+ # Resting in dangerous locations has a chance of encounter
1076
+ if random.random() < 0.3:
1077
+ if location.enemies:
1078
+ enemy_id = random.choice(location.enemies)
1079
+ enemy = Enemy(**asdict(self.enemies[enemy_id]))
1080
+ self.start_combat(enemy)
1081
+ return "While resting, you were ambushed!"
1082
+
1083
+ # Partial rest
1084
+ heal_amount = int(self.player.max_health * 0.3)
1085
+ mana_amount = int(self.player.max_mana * 0.3)
1086
+ self.player.health = min(self.player.max_health, self.player.health + heal_amount)
1087
+ self.player.mana = min(self.player.max_mana, self.player.mana + mana_amount)
1088
+ return f"You rest and recover {heal_amount} health and {mana_amount} mana."
1089
+
1090
+ def cmd_skills(self, args):
1091
+ skills_text = f"{Fore.CYAN}=== Skills ==={Style.RESET_ALL}\n"
1092
+
1093
+ for skill_id, skill in self.player.skills.items():
1094
+ skills_text += f"{Fore.YELLOW}{skill.name}{Style.RESET_ALL} (Level {skill.level})\n"
1095
+ skills_text += f" {skill.description}\n"
1096
+ skills_text += f" Experience: {skill.experience}/{skill.max_experience}\n\n"
1097
+
1098
+ return skills_text
1099
+
1100
+ def cmd_shop(self, args):
1101
+ location = self.locations[self.player.current_location]
1102
+
1103
+ # Find merchant in current location
1104
+ merchant = None
1105
+ for npc_id in location.npcs:
1106
+ npc = self.npcs[npc_id]
1107
+ if npc.shop_items:
1108
+ merchant = npc
1109
+ break
1110
+
1111
+ if not merchant:
1112
+ return "There's no shop here."
1113
+
1114
+ shop_text = f"{Fore.CYAN}=== {merchant.name}'s Shop ==={Style.RESET_ALL}\n"
1115
+ shop_text += "Items for sale:\n"
1116
+
1117
+ for item in merchant.shop_items:
1118
+ shop_text += f" {item.name} - {item.value} gold\n"
1119
+
1120
+ shop_text += "\nType 'buy <item>' to purchase or 'sell <item>' to sell."
1121
+ return shop_text
1122
+
1123
+ def cmd_buy(self, args):
1124
+ if not args:
1125
+ return "Buy what? Specify an item name."
1126
+
1127
+ item_name = " ".join(args).lower()
1128
+ location = self.locations[self.player.current_location]
1129
+
1130
+ # Find merchant in current location
1131
+ merchant = None
1132
+ for npc_id in location.npcs:
1133
+ npc = self.npcs[npc_id]
1134
+ if npc.shop_items:
1135
+ merchant = npc
1136
+ break
1137
+
1138
+ if not merchant:
1139
+ return "There's no shop here."
1140
+
1141
+ # Find item in shop
1142
+ for item in merchant.shop_items:
1143
+ if item.name.lower() == item_name:
1144
+ if self.player.gold >= item.value:
1145
+ self.player.gold -= item.value
1146
+ self.player.add_item(item)
1147
+ return f"You bought {item.name} for {item.value} gold."
1148
+ else:
1149
+ return f"You don't have enough gold to buy {item.name}."
1150
+
1151
+ return f"{merchant.name} doesn't have {item_name} for sale."
1152
+
1153
+ def cmd_sell(self, args):
1154
+ if not args:
1155
+ return "Sell what? Specify an item name."
1156
+
1157
+ item_name = " ".join(args).lower()
1158
+ location = self.locations[self.player.current_location]
1159
+
1160
+ # Find merchant in current location
1161
+ merchant = None
1162
+ for npc_id in location.npcs:
1163
+ npc = self.npcs[npc_id]
1164
+ if npc.shop_items:
1165
+ merchant = npc
1166
+ break
1167
+
1168
+ if not merchant:
1169
+ return "There's no shop here."
1170
+
1171
+ # Find item in inventory
1172
+ for inv_item in self.player.inventory[:]:
1173
+ item = inv_item["item"]
1174
+ if item.name.lower() == item_name:
1175
+ sell_price = int(item.value * 0.5) # Sell for half the value
1176
+ self.player.gold += sell_price
1177
+ self.player.remove_item(item.id)
1178
+ return f"You sold {item.name} for {sell_price} gold."
1179
+
1180
+ return f"You don't have a {item_name} to sell."
1181
+
1182
+ def cmd_map(self, args):
1183
+ location = self.locations[self.player.current_location]
1184
+
1185
+ # Simple ASCII map
1186
+ map_text = f"{Fore.CYAN}=== Map ==={Style.RESET_ALL}\n"
1187
+ map_text += "You are here: *\n\n"
1188
+
1189
+ # Show connected locations
1190
+ for direction, loc_id in location.exits.items():
1191
+ loc = self.locations[loc_id]
1192
+ map_text += f"{direction.capitalize()}: {loc.name}\n"
1193
+
1194
+ return map_text
1195
+
1196
+ def cmd_clear(self, args):
1197
+ self.clear_screen()
1198
+ return ""
1199
+
1200
+ def cmd_version(self, args):
1201
+ return f"{GAME_TITLE} v{GAME_VERSION}"
1202
+
1203
+ def cmd_config(self, args):
1204
+ if len(args) < 2:
1205
+ return "Usage: config <setting> <value>"
1206
+
1207
+ setting = args[0]
1208
+ value = args[1]
1209
+
1210
+ if setting == "text_speed":
1211
+ try:
1212
+ self.config.set_setting(setting, float(value))
1213
+ return f"Text speed set to {value}"
1214
+ except ValueError:
1215
+ return "Invalid value for text_speed"
1216
+
1217
+ elif setting == "auto_save":
1218
+ if value.lower() in ["true", "false"]:
1219
+ self.config.set_setting(setting, value.lower() == "true")
1220
+ return f"Auto-save set to {value}"
1221
+ return "Value must be 'true' or 'false'"
1222
+
1223
+ elif setting == "difficulty":
1224
+ if value in ["easy", "normal", "hard"]:
1225
+ self.config.set_setting(setting, value)
1226
+ return f"Difficulty set to {value}"
1227
+ return "Difficulty must be 'easy', 'normal', or 'hard'"
1228
+
1229
+ elif setting == "debug_mode":
1230
+ if value.lower() in ["true", "false"]:
1231
+ self.config.set_setting(setting, value.lower() == "true")
1232
+ if value.lower() == "true":
1233
+ self.plugin_manager.load_plugin("debug")
1234
+ return f"Debug mode set to {value}"
1235
+ return "Value must be 'true' or 'false'"
1236
+
1237
+ return f"Unknown setting: {setting}"
1238
+
1239
+ def start_combat(self, enemy):
1240
+ self.combat_active = True
1241
+ self.current_enemy = enemy
1242
+ self.print_slow(f"{Fore.RED}Combat started with {enemy.name}!{Style.RESET_ALL}")
1243
+ self.print_slow(f"{enemy.description}")
1244
+ self.print_slow(f"{enemy.name} - HP: {enemy.health}/{enemy.max_health}")
1245
+
1246
+ def update_quest_progress(self, action, target):
1247
+ for quest_id, quest in self.player.quests.items():
1248
+ if quest.status == QuestStatus.IN_PROGRESS:
1249
+ for obj in quest.objectives:
1250
+ if action in obj.lower() and target.lower() in obj.lower():
1251
+ quest.progress[obj] += 1
1252
+
1253
+ # Check if quest is complete
1254
+ if all(progress > 0 for progress in quest.progress.values()):
1255
+ quest.status = QuestStatus.COMPLETED
1256
+ self.complete_quest(quest)
1257
+
1258
+ def complete_quest(self, quest):
1259
+ self.print_slow(f"{Fore.GREEN}Quest Completed: {quest.name}{Style.RESET_ALL}")
1260
+
1261
+ # Give rewards
1262
+ if "experience" in quest.rewards:
1263
+ self.player.add_experience(quest.rewards["experience"])
1264
+ self.print_slow(f"You gained {quest.rewards['experience']} experience!")
1265
+
1266
+ if "gold" in quest.rewards:
1267
+ self.player.gold += quest.rewards["gold"]
1268
+ self.print_slow(f"You gained {quest.rewards['gold']} gold!")
1269
+
1270
+ if "item" in quest.rewards:
1271
+ item_id = quest.rewards["item"]
1272
+ if item_id in self.items:
1273
+ self.player.add_item(self.items[item_id])
1274
+ self.print_slow(f"You received {self.items[item_id].name}!")
1275
+
1276
+ # Trigger quest complete hook
1277
+ self.plugin_manager.trigger_hook("on_quest_complete", quest)
1278
+
1279
+ def save_game(self, silent=False):
1280
+ try:
1281
+ save_data = {
1282
+ "player": self.player,
1283
+ "locations": self.locations,
1284
+ "config": self.config.settings
1285
+ }
1286
+
1287
+ with open(SAVE_FILE, 'wb') as f:
1288
+ pickle.dump(save_data, f)
1289
+
1290
+ if not silent:
1291
+ return "Game saved successfully!"
1292
+ except Exception as e:
1293
+ return f"Error saving game: {e}"
1294
+
1295
+ def load_game(self):
1296
+ try:
1297
+ with open(SAVE_FILE, 'rb') as f:
1298
+ save_data = pickle.load(f)
1299
+
1300
+ self.player = save_data["player"]
1301
+ self.locations = save_data["locations"]
1302
+ self.config.settings = save_data["config"]
1303
+
1304
+ return True
1305
+ except Exception as e:
1306
+ self.print_slow(f"Error loading game: {e}")
1307
+ return False
1308
+
1309
+ def print_slow(self, text, delay=None):
1310
+ if delay is None:
1311
+ delay = self.config.get_setting("text_speed", 0.03)
1312
+
1313
+ for char in text:
1314
+ sys.stdout.write(char)
1315
+ sys.stdout.flush()
1316
+ time.sleep(delay)
1317
+ print()
1318
+
1319
+ def get_input(self, prompt):
1320
+ return input(prompt)
1321
+
1322
+ def print_title(self):
1323
+ title = f"""
1324
+ {Fore.CYAN}
1325
+ _____ _ _ _ _ _ _ _ ____ _____ ____
1326
+ | ____| \ | | | | | / \ | \ | |/ ___| ____| _ \
1327
+ | _| | \| | |_| | / _ \ | \| | | | _| | | | |
1328
+ | |___| |\ | _ |/ ___ \| |\ | |___| |___| |_| |
1329
+ |_____|_| \_|_| |_/_/ \_\_| \_|\____|_____|____/
1330
+ {Style.RESET_ALL}
1331
+ {Fore.YELLOW} A Text-Based RPG Adventure{Style.RESET_ALL}
1332
+ {Fore.GREEN} Version {GAME_VERSION}{Style.RESET_ALL}
1333
+ """
1334
+ print(title)
1335
+ time.sleep(2)
1336
+
1337
+ def clear_screen(self):
1338
+ os.system('cls' if os.name == 'nt' else 'clear')
1339
+
1340
+ # Main execution
1341
+ if __name__ == "__main__":
1342
+ game = TextWorldGame()
1343
+ game.start()
Workspace/Python_Script_Text_based_RPD_Game2.py ADDED
@@ -0,0 +1,1621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import random
5
+ import time
6
+ import math
7
+ import pickle
8
+ import importlib
9
+ from enum import Enum
10
+ from dataclasses import dataclass, field
11
+ from typing import Dict, List, Optional, Tuple, Callable, Any, Union
12
+ from abc import ABC, abstractmethod
13
+
14
+ # Color codes for terminal output
15
+ class Colors:
16
+ RESET = '\033[0m'
17
+ BLACK = '\033[30m'
18
+ RED = '\033[31m'
19
+ GREEN = '\033[32m'
20
+ YELLOW = '\033[33m'
21
+ BLUE = '\033[34m'
22
+ MAGENTA = '\033[35m'
23
+ CYAN = '\033[36m'
24
+ WHITE = '\033[37m'
25
+ BRIGHT_BLACK = '\033[90m'
26
+ BRIGHT_RED = '\033[91m'
27
+ BRIGHT_GREEN = '\033[92m'
28
+ BRIGHT_YELLOW = '\033[93m'
29
+ BRIGHT_BLUE = '\033[94m'
30
+ BRIGHT_MAGENTA = '\033[95m'
31
+ BRIGHT_CYAN = '\033[96m'
32
+ BRIGHT_WHITE = '\033[97m'
33
+ BG_BLACK = '\033[40m'
34
+ BG_RED = '\033[41m'
35
+ BG_GREEN = '\033[42m'
36
+ BG_YELLOW = '\033[43m'
37
+ BG_BLUE = '\033[44m'
38
+ BG_MAGENTA = '\033[45m'
39
+ BG_CYAN = '\033[46m'
40
+ BG_WHITE = '\033[47m'
41
+
42
+ # Game Enums
43
+ class Direction(Enum):
44
+ NORTH = "north"
45
+ SOUTH = "south"
46
+ EAST = "east"
47
+ WEST = "west"
48
+ NORTHEAST = "northeast"
49
+ NORTHWEST = "northwest"
50
+ SOUTHEAST = "southeast"
51
+ SOUTHWEST = "southwest"
52
+ UP = "up"
53
+ DOWN = "down"
54
+
55
+ class SkillType(Enum):
56
+ COMBAT = "combat"
57
+ MAGIC = "magic"
58
+ STEALTH = "stealth"
59
+ CRAFTING = "crafting"
60
+ SOCIAL = "social"
61
+ SURVIVAL = "survival"
62
+
63
+ class Weather(Enum):
64
+ CLEAR = "clear"
65
+ CLOUDY = "cloudy"
66
+ RAINY = "rainy"
67
+ STORMY = "stormy"
68
+ SNOWY = "snowy"
69
+ FOGGY = "foggy"
70
+
71
+ class TimeOfDay(Enum):
72
+ DAWN = "dawn"
73
+ MORNING = "morning"
74
+ NOON = "noon"
75
+ AFTERNOON = "afternoon"
76
+ DUSK = "dusk"
77
+ EVENING = "evening"
78
+ NIGHT = "night"
79
+ MIDNIGHT = "midnight"
80
+
81
+ # Data Classes
82
+ @dataclass
83
+ class Position:
84
+ x: int = 0
85
+ y: int = 0
86
+ z: int = 0
87
+
88
+ @dataclass
89
+ class Stats:
90
+ health: int = 100
91
+ max_health: int = 100
92
+ mana: int = 50
93
+ max_mana: int = 50
94
+ stamina: int = 100
95
+ max_stamina: int = 100
96
+ hunger: int = 100
97
+ max_hunger: int = 100
98
+ thirst: int = 100
99
+ max_thirst: int = 100
100
+ experience: int = 0
101
+ level: int = 1
102
+
103
+ def level_up(self):
104
+ self.level += 1
105
+ self.experience = 0
106
+ self.max_health += 10
107
+ self.health = self.max_health
108
+ self.max_mana += 5
109
+ self.mana = self.max_mana
110
+ self.max_stamina += 5
111
+ self.stamina = self.max_stamina
112
+
113
+ @dataclass
114
+ class Skill:
115
+ name: str
116
+ type: SkillType
117
+ level: int = 1
118
+ experience: int = 0
119
+ max_experience: int = 100
120
+
121
+ def gain_experience(self, amount: int):
122
+ self.experience += amount
123
+ while self.experience >= self.max_experience:
124
+ self.experience -= self.max_experience
125
+ self.level += 1
126
+ self.max_experience = int(self.max_experience * 1.5)
127
+ return True # Leveled up
128
+ return False
129
+
130
+ @dataclass
131
+ class Item:
132
+ id: str
133
+ name: str
134
+ description: str
135
+ value: int = 0
136
+ weight: float = 1.0
137
+ consumable: bool = False
138
+ equippable: bool = False
139
+ stackable: bool = True
140
+ max_stack: int = 99
141
+ effects: Dict[str, Any] = field(default_factory=dict)
142
+
143
+ def use(self, player):
144
+ if self.consumable:
145
+ for stat, value in self.effects.items():
146
+ if hasattr(player.stats, stat):
147
+ current = getattr(player.stats, stat)
148
+ max_stat = getattr(player.stats, f"max_{stat}")
149
+ setattr(player.stats, stat, min(max_stat, current + value))
150
+ return True
151
+ return False
152
+
153
+ @dataclass
154
+ class Weapon(Item):
155
+ damage: int = 10
156
+ damage_type: str = "physical"
157
+ two_handed: bool = False
158
+ range: int = 1
159
+
160
+ def __post_init__(self):
161
+ self.equippable = True
162
+
163
+ @dataclass
164
+ class Armor(Item):
165
+ defense: int = 5
166
+ armor_type: str = "light"
167
+ slot: str = "chest"
168
+
169
+ def __post_init__(self):
170
+ self.equippable = True
171
+
172
+ @dataclass
173
+ class Quest:
174
+ id: str
175
+ name: str
176
+ description: str
177
+ objectives: List[str]
178
+ rewards: Dict[str, Any]
179
+ completed: bool = False
180
+ active: bool = False
181
+
182
+ @dataclass
183
+ class NPC:
184
+ id: str
185
+ name: str
186
+ description: str
187
+ dialogue: Dict[str, List[str]]
188
+ location_id: str
189
+ hostile: bool = False
190
+ stats: Stats = field(default_factory=Stats)
191
+ inventory: List[Item] = field(default_factory=list)
192
+ quests: List[Quest] = field(default_factory=list)
193
+ faction: str = "neutral"
194
+
195
+ def talk(self, topic="greeting"):
196
+ if topic in self.dialogue:
197
+ return random.choice(self.dialogue[topic])
198
+ return "I don't have anything to say about that."
199
+
200
+ @dataclass
201
+ class Location:
202
+ id: str
203
+ name: str
204
+ description: str
205
+ exits: Dict[Direction, str] = field(default_factory=dict)
206
+ items: List[Item] = field(default_factory=list)
207
+ npcs: List[NPC] = field(default_factory=list)
208
+ discovered: bool = False
209
+ indoor: bool = False
210
+ position: Position = field(default_factory=Position)
211
+
212
+ def add_exit(self, direction: Direction, location_id: str):
213
+ self.exits[direction] = location_id
214
+
215
+ def add_item(self, item: Item):
216
+ self.items.append(item)
217
+
218
+ def add_npc(self, npc: NPC):
219
+ self.npcs.append(npc)
220
+
221
+ def remove_item(self, item: Item):
222
+ if item in self.items:
223
+ self.items.remove(item)
224
+ return True
225
+ return False
226
+
227
+ def remove_npc(self, npc: NPC):
228
+ if npc in self.npcs:
229
+ self.npcs.remove(npc)
230
+ return True
231
+ return False
232
+
233
+ # Plugin System
234
+ class Plugin(ABC):
235
+ @abstractmethod
236
+ def initialize(self, game):
237
+ pass
238
+
239
+ @abstractmethod
240
+ def get_commands(self) -> Dict[str, Callable]:
241
+ return {}
242
+
243
+ # Game Classes
244
+ class GameWorld:
245
+ def __init__(self):
246
+ self.locations: Dict[str, Location] = {}
247
+ self.global_time: int = 0 # Game time in minutes
248
+ self.weather: Weather = Weather.CLEAR
249
+ self.time_of_day: TimeOfDay = TimeOfDay.MORNING
250
+ self.day_count: int = 1
251
+
252
+ def add_location(self, location: Location):
253
+ self.locations[location.id] = location
254
+
255
+ def get_location(self, location_id: str) -> Optional[Location]:
256
+ return self.locations.get(location_id)
257
+
258
+ def update_time(self, minutes: int = 1):
259
+ self.global_time += minutes
260
+ # Update day count (each day is 1440 minutes)
261
+ self.day_count = (self.global_time // 1440) + 1
262
+
263
+ # Update time of day (each period is 3 hours = 180 minutes)
264
+ time_periods = list(TimeOfDay)
265
+ period_index = (self.global_time // 180) % len(time_periods)
266
+ self.time_of_day = time_periods[period_index]
267
+
268
+ # Randomly change weather
269
+ if random.random() < 0.05: # 5% chance of weather change
270
+ self.weather = random.choice(list(Weather))
271
+
272
+ def get_time_description(self) -> str:
273
+ return f"Day {self.day_count}, {self.time_of_day.value.capitalize()}, Weather: {self.weather.value.capitalize()}"
274
+
275
+ class Player:
276
+ def __init__(self, name: str):
277
+ self.name: str = name
278
+ self.location_id: str = "start"
279
+ self.stats: Stats = Stats()
280
+ self.inventory: Dict[str, Tuple[Item, int]] = {} # item_id: (item, quantity)
281
+ self.equipped: Dict[str, Item] = {} # slot: item
282
+ self.skills: Dict[str, Skill] = {
283
+ "combat": Skill("Combat", SkillType.COMBAT),
284
+ "magic": Skill("Magic", SkillType.MAGIC),
285
+ "stealth": Skill("Stealth", SkillType.STEALTH),
286
+ "crafting": Skill("Crafting", SkillType.CRAFTING),
287
+ "social": Skill("Social", SkillType.SOCIAL),
288
+ "survival": Skill("Survival", SkillType.SURVIVAL)
289
+ }
290
+ self.quests: List[Quest] = []
291
+ self.known_locations: List[str] = ["start"]
292
+ self.faction_reputation: Dict[str, int] = {}
293
+
294
+ def add_item(self, item: Item, quantity: int = 1):
295
+ if item.id in self.inventory:
296
+ current_item, current_quantity = self.inventory[item.id]
297
+ if item.stackable:
298
+ new_quantity = min(current_quantity + quantity, item.max_stack)
299
+ self.inventory[item.id] = (current_item, new_quantity)
300
+ return quantity - (new_quantity - current_quantity) # Return leftover quantity
301
+ else:
302
+ # For non-stackable items, add multiple entries
303
+ for _ in range(quantity):
304
+ self.inventory[f"{item.id}_{len(self.inventory)}"] = (item, 1)
305
+ return 0
306
+ else:
307
+ self.inventory[item.id] = (item, quantity)
308
+ return 0
309
+
310
+ def remove_item(self, item_id: str, quantity: int = 1) -> bool:
311
+ if item_id in self.inventory:
312
+ item, current_quantity = self.inventory[item_id]
313
+ if current_quantity <= quantity:
314
+ del self.inventory[item_id]
315
+ return True
316
+ else:
317
+ self.inventory[item_id] = (item, current_quantity - quantity)
318
+ return True
319
+ return False
320
+
321
+ def has_item(self, item_id: str, quantity: int = 1) -> bool:
322
+ if item_id in self.inventory:
323
+ _, current_quantity = self.inventory[item_id]
324
+ return current_quantity >= quantity
325
+ return False
326
+
327
+ def equip_item(self, item_id: str) -> bool:
328
+ if item_id in self.inventory:
329
+ item, _ = self.inventory[item_id]
330
+ if item.equippable:
331
+ # Determine slot based on item type
332
+ if isinstance(item, Weapon):
333
+ slot = "weapon"
334
+ elif isinstance(item, Armor):
335
+ slot = item.slot
336
+ else:
337
+ slot = "accessory"
338
+
339
+ # Unequip current item if any
340
+ if slot in self.equipped:
341
+ self.add_item(self.equipped[slot])
342
+
343
+ # Equip new item
344
+ self.equipped[slot] = item
345
+ self.remove_item(item_id)
346
+ return True
347
+ return False
348
+
349
+ def unequip_item(self, slot: str) -> bool:
350
+ if slot in self.equipped:
351
+ item = self.equipped[slot]
352
+ self.add_item(item)
353
+ del self.equipped[slot]
354
+ return True
355
+ return False
356
+
357
+ def get_total_defense(self) -> int:
358
+ defense = 0
359
+ for item in self.equipped.values():
360
+ if isinstance(item, Armor):
361
+ defense += item.defense
362
+ return defense
363
+
364
+ def get_total_damage(self) -> int:
365
+ damage = 5 # Base damage
366
+ if "weapon" in self.equipped:
367
+ weapon = self.equipped["weapon"]
368
+ if isinstance(weapon, Weapon):
369
+ damage = weapon.damage
370
+ return damage
371
+
372
+ def gain_experience(self, amount: int):
373
+ self.stats.experience += amount
374
+ exp_needed = self.stats.level * 100 # Simple formula
375
+ while self.stats.experience >= exp_needed:
376
+ self.stats.experience -= exp_needed
377
+ self.stats.level_up()
378
+ exp_needed = self.stats.level * 100
379
+ return True # Leveled up
380
+ return False
381
+
382
+ def add_quest(self, quest: Quest):
383
+ self.quests.append(quest)
384
+ quest.active = True
385
+
386
+ def complete_quest(self, quest_id: str) -> bool:
387
+ for quest in self.quests:
388
+ if quest.id == quest_id and quest.active and not quest.completed:
389
+ quest.completed = True
390
+ # Apply rewards
391
+ if "experience" in quest.rewards:
392
+ self.gain_experience(quest.rewards["experience"])
393
+ if "items" in quest.rewards:
394
+ for item_id, quantity in quest.rewards["items"].items():
395
+ # This would need a reference to the game world to get the actual item
396
+ pass
397
+ if "reputation" in quest.rewards:
398
+ for faction, amount in quest.rewards["reputation"].items():
399
+ if faction in self.faction_reputation:
400
+ self.faction_reputation[faction] += amount
401
+ else:
402
+ self.faction_reputation[faction] = amount
403
+ return True
404
+ return False
405
+
406
+ def update_vitals(self):
407
+ # Decrease hunger and thirst over time
408
+ self.stats.hunger = max(0, self.stats.hunger - 1)
409
+ self.stats.thirst = max(0, self.stats.thirst - 1)
410
+
411
+ # Apply effects of hunger and thirst
412
+ if self.stats.hunger == 0:
413
+ self.stats.health = max(0, self.stats.health - 2)
414
+ if self.stats.thirst == 0:
415
+ self.stats.health = max(0, self.stats.health - 3)
416
+
417
+ # Regenerate health, mana, and stamina slowly
418
+ if self.stats.health < self.stats.max_health:
419
+ self.stats.health = min(self.stats.max_health, self.stats.health + 1)
420
+ if self.stats.mana < self.stats.max_mana:
421
+ self.stats.mana = min(self.stats.max_mana, self.stats.mana + 1)
422
+ if self.stats.stamina < self.stats.max_stamina:
423
+ self.stats.stamina = min(self.stats.max_stamina, self.stats.stamina + 2)
424
+
425
+ class CombatSystem:
426
+ @staticmethod
427
+ def attack(attacker, defender):
428
+ # Calculate damage
429
+ base_damage = attacker.get_total_damage() if hasattr(attacker, 'get_total_damage') else 10
430
+
431
+ # Add some randomness
432
+ damage = max(1, base_damage + random.randint(-2, 2))
433
+
434
+ # Apply defense
435
+ defense = defender.get_total_defense() if hasattr(defender, 'get_total_defense') else 0
436
+ damage = max(1, damage - defense // 2)
437
+
438
+ # Apply damage
439
+ defender.stats.health = max(0, defender.stats.health - damage)
440
+
441
+ return damage
442
+
443
+ @staticmethod
444
+ def check_flee(player, npc) -> bool:
445
+ # Base chance to flee is 50%, modified by player's level vs NPC's level
446
+ base_chance = 0.5
447
+ level_diff = player.stats.level - npc.stats.level
448
+ chance = base_chance + (level_diff * 0.1)
449
+ chance = max(0.1, min(0.9, chance)) # Clamp between 10% and 90%
450
+
451
+ return random.random() < chance
452
+
453
+ class Game:
454
+ def __init__(self):
455
+ self.world = GameWorld()
456
+ self.player = None
457
+ self.running = True
458
+ self.plugins: Dict[str, Plugin] = {}
459
+ self.commands: Dict[str, Callable] = {}
460
+ self.combat = CombatSystem()
461
+ self.in_combat = False
462
+ self.current_opponent = None
463
+
464
+ # Initialize core commands
465
+ self.register_command("help", self.cmd_help)
466
+ self.register_command("quit", self.cmd_quit)
467
+ self.register_command("look", self.cmd_look)
468
+ self.register_command("go", self.cmd_go)
469
+ self.register_command("take", self.cmd_take)
470
+ self.register_command("inventory", self.cmd_inventory)
471
+ self.register_command("use", self.cmd_use)
472
+ self.register_command("equip", self.cmd_equip)
473
+ self.register_command("unequip", self.cmd_unequip)
474
+ self.register_command("talk", self.cmd_talk)
475
+ self.register_command("attack", self.cmd_attack)
476
+ self.register_command("flee", self.cmd_flee)
477
+ self.register_command("quests", self.cmd_quests)
478
+ self.register_command("skills", self.cmd_skills)
479
+ self.register_command("time", self.cmd_time)
480
+ self.register_command("save", self.cmd_save)
481
+ self.register_command("load", self.cmd_load)
482
+ self.register_command("wait", self.cmd_wait)
483
+ self.register_command("status", self.cmd_status)
484
+ self.register_command("drop", self.cmd_drop)
485
+ self.register_command("examine", self.cmd_examine)
486
+ self.register_command("map", self.cmd_map)
487
+ self.register_command("rest", self.cmd_rest)
488
+ self.register_command("plugins", self.cmd_plugins)
489
+
490
+ # Initialize the game world
491
+ self.initialize_world()
492
+
493
+ def register_command(self, name: str, func: Callable):
494
+ self.commands[name] = func
495
+
496
+ def load_plugin(self, plugin_path: str):
497
+ try:
498
+ spec = importlib.util.spec_from_file_location("plugin", plugin_path)
499
+ plugin_module = importlib.util.module_from_spec(spec)
500
+ spec.loader.exec_module(plugin_module)
501
+
502
+ # Get plugin class (should be named "Plugin")
503
+ if hasattr(plugin_module, "Plugin"):
504
+ plugin_class = getattr(plugin_module, "Plugin")
505
+ plugin = plugin_class()
506
+ plugin.initialize(self)
507
+
508
+ # Register plugin commands
509
+ plugin_commands = plugin.get_commands()
510
+ for name, func in plugin_commands.items():
511
+ self.register_command(name, func)
512
+
513
+ self.plugins[plugin_path] = plugin
514
+ return True
515
+ except Exception as e:
516
+ print(f"{Colors.RED}Error loading plugin: {e}{Colors.RESET}")
517
+ return False
518
+
519
+ def unload_plugin(self, plugin_path: str):
520
+ if plugin_path in self.plugins:
521
+ plugin = self.plugins[plugin_path]
522
+ plugin_commands = plugin.get_commands()
523
+
524
+ # Unregister plugin commands
525
+ for name in plugin_commands:
526
+ if name in self.commands:
527
+ del self.commands[name]
528
+
529
+ del self.plugins[plugin_path]
530
+ return True
531
+ return False
532
+
533
+ def initialize_world(self):
534
+ # Create starting location
535
+ start_location = Location(
536
+ id="start",
537
+ name="Starting Village",
538
+ description="A small village surrounded by forests and mountains. There's a path leading north to the forest and east to the mountains.",
539
+ position=Position(0, 0, 0)
540
+ )
541
+
542
+ # Create forest location
543
+ forest_location = Location(
544
+ id="forest",
545
+ name="Dark Forest",
546
+ description="A dense forest with tall trees and little light. You can hear strange sounds in the distance.",
547
+ position=Position(0, 1, 0)
548
+ )
549
+
550
+ # Create mountain location
551
+ mountain_location = Location(
552
+ id="mountain",
553
+ name="Mountain Pass",
554
+ description="A narrow path through the mountains. It's cold and windy here.",
555
+ position=Position(1, 0, 0)
556
+ )
557
+
558
+ # Create cave location
559
+ cave_location = Location(
560
+ id="cave",
561
+ name="Mysterious Cave",
562
+ description="A dark cave with glowing crystals on the walls. You can hear dripping water.",
563
+ position=Position(0, 0, -1),
564
+ indoor=True
565
+ )
566
+
567
+ # Create village shop
568
+ shop_location = Location(
569
+ id="shop",
570
+ name="Village Shop",
571
+ description="A small shop with various items for sale. The shopkeeper looks friendly.",
572
+ position=Position(-1, 0, 0),
573
+ indoor=True
574
+ )
575
+
576
+ # Connect locations
577
+ start_location.add_exit(Direction.NORTH, "forest")
578
+ start_location.add_exit(Direction.EAST, "mountain")
579
+ start_location.add_exit(Direction.WEST, "shop")
580
+
581
+ forest_location.add_exit(Direction.SOUTH, "start")
582
+ forest_location.add_exit(Direction.DOWN, "cave")
583
+
584
+ mountain_location.add_exit(Direction.WEST, "start")
585
+
586
+ cave_location.add_exit(Direction.UP, "forest")
587
+
588
+ shop_location.add_exit(Direction.EAST, "start")
589
+
590
+ # Add items to locations
591
+ # Starting village items
592
+ start_location.add_item(Item(
593
+ id="apple",
594
+ name="Apple",
595
+ description="A fresh red apple. Looks delicious.",
596
+ value=5,
597
+ consumable=True,
598
+ effects={"hunger": 20}
599
+ ))
600
+
601
+ start_location.add_item(Item(
602
+ id="bread",
603
+ name="Bread",
604
+ description="A loaf of bread. Still warm.",
605
+ value=10,
606
+ consumable=True,
607
+ effects={"hunger": 40}
608
+ ))
609
+
610
+ # Forest items
611
+ forest_location.add_item(Weapon(
612
+ id="sword",
613
+ name="Rusty Sword",
614
+ description="An old rusty sword. Better than nothing.",
615
+ value=25,
616
+ damage=15,
617
+ weight=3.0
618
+ ))
619
+
620
+ forest_location.add_item(Item(
621
+ id="herb",
622
+ name="Healing Herb",
623
+ description="A green herb with medicinal properties.",
624
+ value=15,
625
+ consumable=True,
626
+ effects={"health": 20}
627
+ ))
628
+
629
+ # Cave items
630
+ cave_location.add_item(Item(
631
+ id="crystal",
632
+ name="Magic Crystal",
633
+ description="A glowing crystal that hums with magical energy.",
634
+ value=100,
635
+ consumable=True,
636
+ effects={"mana": 50}
637
+ ))
638
+
639
+ # Shop items
640
+ shop_location.add_item(Weapon(
641
+ id="dagger",
642
+ name="Dagger",
643
+ description="A sharp dagger. Good for quick attacks.",
644
+ value=30,
645
+ damage=10,
646
+ weight=1.0
647
+ ))
648
+
649
+ shop_location.add_item(Armor(
650
+ id="leather_armor",
651
+ name="Leather Armor",
652
+ description="Simple armor made of leather. Provides basic protection.",
653
+ value=50,
654
+ defense=10,
655
+ armor_type="light",
656
+ slot="chest"
657
+ ))
658
+
659
+ # Add NPCs
660
+ # Village elder
661
+ elder = NPC(
662
+ id="elder",
663
+ name="Village Elder",
664
+ description="An old man with a long white beard and wise eyes.",
665
+ dialogue={
666
+ "greeting": [
667
+ "Welcome to our humble village, young adventurer.",
668
+ "Ah, a new face. What brings you to our village?"
669
+ ],
670
+ "quest": [
671
+ "We have a problem with wolves in the forest. Could you help us?",
672
+ "The forest to the north has become dangerous. Please investigate."
673
+ ],
674
+ "help": [
675
+ "You can use 'go [direction]' to move around.",
676
+ "Try 'talk [npc]' to interact with people."
677
+ ]
678
+ },
679
+ location_id="start"
680
+ )
681
+
682
+ # Add quest to elder
683
+ wolf_quest = Quest(
684
+ id="wolf_problem",
685
+ name="Wolf Problem",
686
+ description="Deal with the wolves in the forest.",
687
+ objectives=["Kill 5 wolves"],
688
+ rewards={
689
+ "experience": 100,
690
+ "items": {"gold": 50}
691
+ }
692
+ )
693
+ elder.quests.append(wolf_quest)
694
+
695
+ # Shopkeeper
696
+ shopkeeper = NPC(
697
+ id="shopkeeper",
698
+ name="Shopkeeper",
699
+ description="A friendly-looking person with a big smile.",
700
+ dialogue={
701
+ "greeting": [
702
+ "Welcome to my shop! Feel free to browse.",
703
+ "Hello! Looking for something special?"
704
+ ],
705
+ "buy": [
706
+ "What would you like to buy?",
707
+ "Everything here is for sale, just name it."
708
+ ],
709
+ "sell": [
710
+ "What do you want to sell me?",
711
+ "I'll give you a fair price for your items."
712
+ ]
713
+ },
714
+ location_id="shop"
715
+ )
716
+
717
+ # Forest wolf
718
+ wolf = NPC(
719
+ id="wolf",
720
+ name="Wolf",
721
+ description="A wild wolf with sharp teeth and hungry eyes.",
722
+ dialogue={},
723
+ location_id="forest",
724
+ hostile=True,
725
+ stats=Stats(health=50, max_health=50)
726
+ )
727
+
728
+ # Add NPCs to locations
729
+ start_location.add_npc(elder)
730
+ shop_location.add_npc(shopkeeper)
731
+ forest_location.add_npc(wolf)
732
+
733
+ # Add locations to world
734
+ self.world.add_location(start_location)
735
+ self.world.add_location(forest_location)
736
+ self.world.add_location(mountain_location)
737
+ self.world.add_location(cave_location)
738
+ self.world.add_location(shop_location)
739
+
740
+ def start(self):
741
+ self.clear_screen()
742
+ self.print_title()
743
+
744
+ # Character creation
745
+ name = input(f"{Colors.CYAN}Enter your character's name: {Colors.RESET}")
746
+ self.player = Player(name)
747
+
748
+ # Welcome message
749
+ self.print_wrapped(f"{Colors.GREEN}Welcome, {self.player.name}!{Colors.RESET}")
750
+ self.print_wrapped("You find yourself in a small village. Your adventure begins here.")
751
+ self.print_wrapped("Type 'help' for a list of commands.")
752
+ self.print_separator()
753
+
754
+ # Main game loop
755
+ while self.running:
756
+ if not self.in_combat:
757
+ # Update game world
758
+ self.world.update_time()
759
+ self.player.update_vitals()
760
+
761
+ # Check if player is dead
762
+ if self.player.stats.health <= 0:
763
+ self.game_over()
764
+ break
765
+
766
+ # Display location
767
+ self.display_location()
768
+
769
+ # Get player input
770
+ try:
771
+ command_input = input(f"{Colors.YELLOW}> {Colors.RESET}").strip().lower()
772
+ if not command_input:
773
+ continue
774
+
775
+ # Parse command
776
+ parts = command_input.split()
777
+ command = parts[0]
778
+ args = parts[1:] if len(parts) > 1 else []
779
+
780
+ # Execute command
781
+ if command in self.commands:
782
+ self.commands[command](args)
783
+ else:
784
+ print(f"{Colors.RED}Unknown command: {command}{Colors.RESET}")
785
+ print(f"{Colors.CYAN}Type 'help' for a list of commands.{Colors.RESET}")
786
+
787
+ except KeyboardInterrupt:
788
+ print("\nGoodbye!")
789
+ self.running = False
790
+ except EOFError:
791
+ print("\nGoodbye!")
792
+ self.running = False
793
+ except Exception as e:
794
+ print(f"{Colors.RED}Error: {e}{Colors.RESET}")
795
+
796
+ def game_over(self):
797
+ self.clear_screen()
798
+ print(f"{Colors.RED}========================================{Colors.RESET}")
799
+ print(f"{Colors.RED} GAME OVER{Colors.RESET}")
800
+ print(f"{Colors.RED}========================================{Colors.RESET}")
801
+ print(f"{Colors.WHITE}You have died.{Colors.RESET}")
802
+ print(f"{Colors.WHITE}Level reached: {self.player.stats.level}{Colors.RESET}")
803
+ print(f"{Colors.WHITE}Experience gained: {self.player.stats.experience}{Colors.RESET}")
804
+ print(f"{Colors.RED}========================================{Colors.RESET}")
805
+ self.running = False
806
+
807
+ def clear_screen(self):
808
+ os.system('cls' if os.name == 'nt' else 'clear')
809
+
810
+ def print_title(self):
811
+ print(f"{Colors.BRIGHT_CYAN}")
812
+ print("========================================")
813
+ print(" ULTIMATE OPEN WORLD GAME ")
814
+ print("========================================")
815
+ print(f"{Colors.RESET}")
816
+
817
+ def print_separator(self):
818
+ print(f"{Colors.BRIGHT_BLACK}----------------------------------------{Colors.RESET}")
819
+
820
+ def print_wrapped(self, text, width=80):
821
+ words = text.split()
822
+ lines = []
823
+ current_line = []
824
+ current_length = 0
825
+
826
+ for word in words:
827
+ if current_length + len(word) + 1 <= width:
828
+ current_line.append(word)
829
+ current_length += len(word) + 1
830
+ else:
831
+ lines.append(' '.join(current_line))
832
+ current_line = [word]
833
+ current_length = len(word)
834
+
835
+ if current_line:
836
+ lines.append(' '.join(current_line))
837
+
838
+ for line in lines:
839
+ print(line)
840
+
841
+ def display_location(self):
842
+ location = self.world.get_location(self.player.location_id)
843
+ if not location:
844
+ return
845
+
846
+ # Mark location as discovered
847
+ if not location.discovered:
848
+ location.discovered = True
849
+ if location.id not in self.player.known_locations:
850
+ self.player.known_locations.append(location.id)
851
+
852
+ # Display location name
853
+ print(f"{Colors.BRIGHT_GREEN}{location.name}{Colors.RESET}")
854
+
855
+ # Display location description
856
+ self.print_wrapped(f"{Colors.WHITE}{location.description}{Colors.RESET}")
857
+
858
+ # Display time and weather
859
+ print(f"{Colors.CYAN}{self.world.get_time_description()}{Colors.RESET}")
860
+
861
+ # Display exits
862
+ if location.exits:
863
+ exits = ", ".join([d.value for d in location.exits.keys()])
864
+ print(f"{Colors.YELLOW}Exits: {exits}{Colors.RESET}")
865
+
866
+ # Display items
867
+ if location.items:
868
+ item_names = [f"{item.name} ({quantity})" if item.stackable else item.name
869
+ for item, quantity in [(item, 1) for item in location.items]]
870
+ print(f"{Colors.GREEN}Items: {', '.join(item_names)}{Colors.RESET}")
871
+
872
+ # Display NPCs
873
+ if location.npcs:
874
+ npc_names = [npc.name for npc in location.npcs]
875
+ print(f"{Colors.MAGENTA}People: {', '.join(npc_names)}{Colors.RESET}")
876
+
877
+ self.print_separator()
878
+
879
+ # Command implementations
880
+ def cmd_help(self, args):
881
+ print(f"{Colors.CYAN}Available commands:{Colors.RESET}")
882
+ for command in sorted(self.commands.keys()):
883
+ print(f" {Colors.YELLOW}{command}{Colors.RESET}")
884
+ print(f"\n{Colors.CYAN}For more information on a command, type: help [command]{Colors.RESET}")
885
+
886
+ def cmd_quit(self, args):
887
+ print(f"{Colors.YELLOW}Are you sure you want to quit? (y/n){Colors.RESET}")
888
+ response = input("> ").strip().lower()
889
+ if response == 'y':
890
+ self.running = False
891
+
892
+ def cmd_look(self, args):
893
+ self.display_location()
894
+
895
+ def cmd_go(self, args):
896
+ if not args:
897
+ print(f"{Colors.RED}Go where?{Colors.RESET}")
898
+ return
899
+
900
+ direction_str = args[0]
901
+ try:
902
+ direction = Direction(direction_str)
903
+ except ValueError:
904
+ print(f"{Colors.RED}Invalid direction: {direction_str}{Colors.RESET}")
905
+ return
906
+
907
+ location = self.world.get_location(self.player.location_id)
908
+ if not location:
909
+ return
910
+
911
+ if direction in location.exits:
912
+ # Check for hostile NPCs that might block the way
913
+ for npc in location.npcs:
914
+ if npc.hostile and npc.stats.health > 0:
915
+ print(f"{Colors.RED}{npc.name} blocks your path!{Colors.RESET}")
916
+ self.start_combat(npc)
917
+ return
918
+
919
+ # Move to the new location
920
+ self.player.location_id = location.exits[direction]
921
+ print(f"{Colors.GREEN}You go {direction.value}.{Colors.RESET}")
922
+
923
+ # Update time (movement takes time)
924
+ self.world.update_time(5)
925
+
926
+ # Consume stamina
927
+ self.player.stats.stamina = max(0, self.player.stats.stamina - 5)
928
+
929
+ # Check for random encounters
930
+ if random.random() < 0.1: # 10% chance of random encounter
931
+ self.random_encounter()
932
+ else:
933
+ print(f"{Colors.RED}You can't go {direction.value} from here.{Colors.RESET}")
934
+
935
+ def cmd_take(self, args):
936
+ if not args:
937
+ print(f"{Colors.RED}Take what?{Colors.RESET}")
938
+ return
939
+
940
+ item_name = ' '.join(args)
941
+ location = self.world.get_location(self.player.location_id)
942
+ if not location:
943
+ return
944
+
945
+ # Find the item
946
+ for item in location.items:
947
+ if item.name.lower() == item_name.lower():
948
+ # Add to player inventory
949
+ leftover = self.player.add_item(item)
950
+ if leftover == 0:
951
+ location.remove_item(item)
952
+ print(f"{Colors.GREEN}You take the {item.name}.{Colors.RESET}")
953
+ else:
954
+ print(f"{Colors.YELLOW}You can only carry {item.max_stack} {item.name}s.{Colors.RESET}")
955
+ return
956
+
957
+ print(f"{Colors.RED}There is no {item_name} here.{Colors.RESET}")
958
+
959
+ def cmd_inventory(self, args):
960
+ if not self.player.inventory:
961
+ print(f"{Colors.YELLOW}Your inventory is empty.{Colors.RESET}")
962
+ return
963
+
964
+ print(f"{Colors.CYAN}Inventory:{Colors.RESET}")
965
+ for item_id, (item, quantity) in self.player.inventory.items():
966
+ if item.stackable:
967
+ print(f" {Colors.GREEN}{item.name} x{quantity}{Colors.RESET} - {item.description}")
968
+ else:
969
+ print(f" {Colors.GREEN}{item.name}{Colors.RESET} - {item.description}")
970
+
971
+ # Show equipped items
972
+ if self.player.equipped:
973
+ print(f"\n{Colors.CYAN}Equipped:{Colors.RESET}")
974
+ for slot, item in self.player.equipped.items():
975
+ print(f" {Colors.YELLOW}{slot}: {item.name}{Colors.RESET}")
976
+
977
+ def cmd_use(self, args):
978
+ if not args:
979
+ print(f"{Colors.RED}Use what?{Colors.RESET}")
980
+ return
981
+
982
+ item_name = ' '.join(args)
983
+
984
+ # Find the item in inventory
985
+ for item_id, (item, quantity) in self.player.inventory.items():
986
+ if item.name.lower() == item_name.lower():
987
+ if item.use(self.player):
988
+ if item.consumable:
989
+ if quantity > 1:
990
+ self.player.inventory[item_id] = (item, quantity - 1)
991
+ else:
992
+ self.player.remove_item(item_id)
993
+ print(f"{Colors.GREEN}You use the {item.name}.{Colors.RESET}")
994
+ else:
995
+ print(f"{Colors.RED}You can't use the {item.name}.{Colors.RESET}")
996
+ return
997
+
998
+ print(f"{Colors.RED}You don't have a {item_name}.{Colors.RESET}")
999
+
1000
+ def cmd_equip(self, args):
1001
+ if not args:
1002
+ print(f"{Colors.RED}Equip what?{Colors.RESET}")
1003
+ return
1004
+
1005
+ item_name = ' '.join(args)
1006
+
1007
+ # Find the item in inventory
1008
+ for item_id, (item, quantity) in self.player.inventory.items():
1009
+ if item.name.lower() == item_name.lower():
1010
+ if self.player.equip_item(item_id):
1011
+ print(f"{Colors.GREEN}You equip the {item.name}.{Colors.RESET}")
1012
+ else:
1013
+ print(f"{Colors.RED}You can't equip the {item.name}.{Colors.RESET}")
1014
+ return
1015
+
1016
+ print(f"{Colors.RED}You don't have a {item_name}.{Colors.RESET}")
1017
+
1018
+ def cmd_unequip(self, args):
1019
+ if not args:
1020
+ print(f"{Colors.RED}Unequip what?{Colors.RESET}")
1021
+ return
1022
+
1023
+ slot = args[0].lower()
1024
+
1025
+ if self.player.unequip_item(slot):
1026
+ print(f"{Colors.GREEN}You unequip your {slot}.{Colors.RESET}")
1027
+ else:
1028
+ print(f"{Colors.RED}You don't have anything equipped in that slot.{Colors.RESET}")
1029
+
1030
+ def cmd_talk(self, args):
1031
+ if not args:
1032
+ print(f"{Colors.RED}Talk to whom?{Colors.RESET}")
1033
+ return
1034
+
1035
+ npc_name = ' '.join(args)
1036
+ location = self.world.get_location(self.player.location_id)
1037
+ if not location:
1038
+ return
1039
+
1040
+ # Find the NPC
1041
+ for npc in location.npcs:
1042
+ if npc.name.lower() == npc_name.lower():
1043
+ # Get dialogue topic
1044
+ topic = "greeting"
1045
+ if len(args) > 1:
1046
+ topic = ' '.join(args[1:])
1047
+
1048
+ # Get dialogue
1049
+ dialogue = npc.talk(topic)
1050
+ print(f"{Colors.MAGENTA}{npc.name}: {dialogue}{Colors.RESET}")
1051
+
1052
+ # Check for quests
1053
+ if topic == "quest" and npc.quests:
1054
+ for quest in npc.quests:
1055
+ if not quest.completed and not any(q.id == quest.id for q in self.player.quests):
1056
+ self.player.add_quest(quest)
1057
+ print(f"{Colors.GREEN}New quest: {quest.name}{Colors.RESET}")
1058
+ print(f"{Colors.WHITE}{quest.description}{Colors.RESET}")
1059
+
1060
+ return
1061
+
1062
+ print(f"{Colors.RED}There is no one named {npc_name} here.{Colors.RESET}")
1063
+
1064
+ def cmd_attack(self, args):
1065
+ if not args:
1066
+ print(f"{Colors.RED}Attack whom?{Colors.RESET}")
1067
+ return
1068
+
1069
+ npc_name = ' '.join(args)
1070
+ location = self.world.get_location(self.player.location_id)
1071
+ if not location:
1072
+ return
1073
+
1074
+ # Find the NPC
1075
+ for npc in location.npcs:
1076
+ if npc.name.lower() == npc_name.lower():
1077
+ if not npc.hostile:
1078
+ print(f"{Colors.RED}You can't attack {npc.name}.{Colors.RESET}")
1079
+ return
1080
+
1081
+ self.start_combat(npc)
1082
+ return
1083
+
1084
+ print(f"{Colors.RED}There is no one named {npc_name} here.{Colors.RESET}")
1085
+
1086
+ def cmd_flee(self, args):
1087
+ if not self.in_combat:
1088
+ print(f"{Colors.RED}You're not in combat.{Colors.RESET}")
1089
+ return
1090
+
1091
+ if self.combat.check_flee(self.player, self.current_opponent):
1092
+ print(f"{Colors.GREEN}You successfully flee from combat.{Colors.RESET}")
1093
+ self.end_combat()
1094
+
1095
+ # Move to a random adjacent location
1096
+ location = self.world.get_location(self.player.location_id)
1097
+ if location and location.exits:
1098
+ directions = list(location.exits.keys())
1099
+ random_direction = random.choice(directions)
1100
+ self.player.location_id = location.exits[random_direction]
1101
+ print(f"{Colors.GREEN}You run away to the {random_direction.value}.{Colors.RESET}")
1102
+ else:
1103
+ print(f"{Colors.RED}You fail to flee!{Colors.RESET}")
1104
+ # Enemy gets a free attack
1105
+ damage = self.combat.attack(self.current_opponent, self.player)
1106
+ print(f"{Colors.RED}{self.current_opponent.name} attacks you for {damage} damage!{Colors.RESET}")
1107
+
1108
+ if self.player.stats.health <= 0:
1109
+ self.game_over()
1110
+
1111
+ def cmd_quests(self, args):
1112
+ if not self.player.quests:
1113
+ print(f"{Colors.YELLOW}You don't have any active quests.{Colors.RESET}")
1114
+ return
1115
+
1116
+ print(f"{Colors.CYAN}Active Quests:{Colors.RESET}")
1117
+ for quest in self.player.quests:
1118
+ if quest.active and not quest.completed:
1119
+ print(f" {Colors.YELLOW}{quest.name}{Colors.RESET}")
1120
+ print(f" {quest.description}")
1121
+ print(f" Objectives: {', '.join(quest.objectives)}")
1122
+
1123
+ print(f"\n{Colors.CYAN}Completed Quests:{Colors.RESET}")
1124
+ for quest in self.player.quests:
1125
+ if quest.completed:
1126
+ print(f" {Colors.GREEN}{quest.name}{Colors.RESET}")
1127
+
1128
+ def cmd_skills(self, args):
1129
+ print(f"{Colors.CYAN}Skills:{Colors.RESET}")
1130
+ for skill_name, skill in self.player.skills.items():
1131
+ print(f" {Colors.YELLOW}{skill.name}: Level {skill.level} ({skill.experience}/{skill.max_experience} XP){Colors.RESET}")
1132
+
1133
+ def cmd_time(self, args):
1134
+ print(f"{Colors.CYAN}{self.world.get_time_description()}{Colors.RESET}")
1135
+
1136
+ def cmd_save(self, args):
1137
+ save_name = args[0] if args else "save1"
1138
+ save_data = {
1139
+ "player": self.player,
1140
+ "world": self.world,
1141
+ "in_combat": self.in_combat,
1142
+ "current_opponent": self.current_opponent
1143
+ }
1144
+
1145
+ try:
1146
+ with open(f"{save_name}.sav", "wb") as f:
1147
+ pickle.dump(save_data, f)
1148
+ print(f"{Colors.GREEN}Game saved as {save_name}.{Colors.RESET}")
1149
+ except Exception as e:
1150
+ print(f"{Colors.RED}Failed to save game: {e}{Colors.RESET}")
1151
+
1152
+ def cmd_load(self, args):
1153
+ save_name = args[0] if args else "save1"
1154
+
1155
+ try:
1156
+ with open(f"{save_name}.sav", "rb") as f:
1157
+ save_data = pickle.load(f)
1158
+
1159
+ self.player = save_data["player"]
1160
+ self.world = save_data["world"]
1161
+ self.in_combat = save_data["in_combat"]
1162
+ self.current_opponent = save_data["current_opponent"]
1163
+
1164
+ print(f"{Colors.GREEN}Game loaded from {save_name}.{Colors.RESET}")
1165
+ except Exception as e:
1166
+ print(f"{Colors.RED}Failed to load game: {e}{Colors.RESET}")
1167
+
1168
+ def cmd_wait(self, args):
1169
+ minutes = 30 # Default wait time
1170
+ if args:
1171
+ try:
1172
+ minutes = int(args[0])
1173
+ except ValueError:
1174
+ print(f"{Colors.RED}Invalid time: {args[0]}{Colors.RESET}")
1175
+ return
1176
+
1177
+ print(f"{Colors.YELLOW}You wait for {minutes} minutes...{Colors.RESET}")
1178
+ self.world.update_time(minutes)
1179
+ self.player.update_vitals()
1180
+
1181
+ # Random events while waiting
1182
+ if random.random() < 0.2: # 20% chance of something happening
1183
+ self.random_event()
1184
+
1185
+ def cmd_status(self, args):
1186
+ print(f"{Colors.CYAN}Character Status:{Colors.RESET}")
1187
+ print(f" Name: {self.player.name}")
1188
+ print(f" Level: {self.player.stats.level}")
1189
+ print(f" Experience: {self.player.stats.experience}")
1190
+ print(f" Health: {self.player.stats.health}/{self.player.stats.max_health}")
1191
+ print(f" Mana: {self.player.stats.mana}/{self.player.stats.max_mana}")
1192
+ print(f" Stamina: {self.player.stats.stamina}/{self.player.stats.max_stamina}")
1193
+ print(f" Hunger: {self.player.stats.hunger}/{self.player.stats.max_hunger}")
1194
+ print(f" Thirst: {self.player.stats.thirst}/{self.player.stats.max_thirst}")
1195
+ print(f" Defense: {self.player.get_total_defense()}")
1196
+ print(f" Damage: {self.player.get_total_damage()}")
1197
+
1198
+ def cmd_drop(self, args):
1199
+ if not args:
1200
+ print(f"{Colors.RED}Drop what?{Colors.RESET}")
1201
+ return
1202
+
1203
+ item_name = ' '.join(args)
1204
+ location = self.world.get_location(self.player.location_id)
1205
+ if not location:
1206
+ return
1207
+
1208
+ # Find the item in inventory
1209
+ for item_id, (item, quantity) in self.player.inventory.items():
1210
+ if item.name.lower() == item_name.lower():
1211
+ # Remove from player inventory
1212
+ if self.player.remove_item(item_id):
1213
+ # Add to location
1214
+ location.add_item(item)
1215
+ print(f"{Colors.GREEN}You drop the {item.name}.{Colors.RESET}")
1216
+ return
1217
+
1218
+ print(f"{Colors.RED}You don't have a {item_name}.{Colors.RESET}")
1219
+
1220
+ def cmd_examine(self, args):
1221
+ if not args:
1222
+ print(f"{Colors.RED}Examine what?{Colors.RESET}")
1223
+ return
1224
+
1225
+ target_name = ' '.join(args)
1226
+ location = self.world.get_location(self.player.location_id)
1227
+ if not location:
1228
+ return
1229
+
1230
+ # Check items
1231
+ for item in location.items:
1232
+ if item.name.lower() == target_name.lower():
1233
+ print(f"{Colors.GREEN}{item.name}: {item.description}{Colors.RESET}")
1234
+ if isinstance(item, Weapon):
1235
+ print(f" Damage: {item.damage}, Type: {item.damage_type}")
1236
+ elif isinstance(item, Armor):
1237
+ print(f" Defense: {item.defense}, Type: {item.armor_type}, Slot: {item.slot}")
1238
+ return
1239
+
1240
+ # Check NPCs
1241
+ for npc in location.npcs:
1242
+ if npc.name.lower() == target_name.lower():
1243
+ print(f"{Colors.MAGENTA}{npc.name}: {npc.description}{Colors.RESET}")
1244
+ if npc.hostile:
1245
+ print(f" {Colors.RED}Hostile{Colors.RESET}")
1246
+ print(f" Health: {npc.stats.health}/{npc.stats.max_health}")
1247
+ return
1248
+
1249
+ print(f"{Colors.RED}There is no {target_name} here.{Colors.RESET}")
1250
+
1251
+ def cmd_map(self, args):
1252
+ print(f"{Colors.CYAN}Map of Known Locations:{Colors.RESET}")
1253
+
1254
+ # Get all known locations
1255
+ known_locations = [self.world.get_location(loc_id) for loc_id in self.player.known_locations]
1256
+ if not known_locations:
1257
+ print(f"{Colors.YELLOW}You haven't discovered any locations yet.{Colors.RESET}")
1258
+ return
1259
+
1260
+ # Find min and max coordinates
1261
+ min_x = min(loc.position.x for loc in known_locations)
1262
+ max_x = max(loc.position.x for loc in known_locations)
1263
+ min_y = min(loc.position.y for loc in known_locations)
1264
+ max_y = max(loc.position.y for loc in known_locations)
1265
+
1266
+ # Create map grid
1267
+ grid_width = max_x - min_x + 1
1268
+ grid_height = max_y - min_y + 1
1269
+ grid = [[' ' for _ in range(grid_width)] for _ in range(grid_height)]
1270
+
1271
+ # Place locations on grid
1272
+ for loc in known_locations:
1273
+ x = loc.position.x - min_x
1274
+ y = loc.position.y - min_y
1275
+
1276
+ if loc.id == self.player.location_id:
1277
+ grid[y][x] = 'X' # Player's current location
1278
+ else:
1279
+ grid[y][x] = 'O' # Other known locations
1280
+
1281
+ # Print map
1282
+ print(f"{Colors.BRIGHT_BLACK}+{'-' * grid_width}+{Colors.RESET}")
1283
+ for row in grid:
1284
+ print(f"{Colors.BRIGHT_BLACK}|{Colors.RESET}", end="")
1285
+ for cell in row:
1286
+ if cell == 'X':
1287
+ print(f"{Colors.GREEN}{cell}{Colors.RESET}", end="")
1288
+ elif cell == 'O':
1289
+ print(f"{Colors.YELLOW}{cell}{Colors.RESET}", end="")
1290
+ else:
1291
+ print(cell, end="")
1292
+ print(f"{Colors.BRIGHT_BLACK}|{Colors.RESET}")
1293
+ print(f"{Colors.BRIGHT_BLACK}+{'-' * grid_width}+{Colors.RESET}")
1294
+ print(f"{Colors.GREEN}X = Your location{Colors.RESET}")
1295
+ print(f"{Colors.YELLOW}O = Known location{Colors.RESET}")
1296
+
1297
+ def cmd_rest(self, args):
1298
+ if self.in_combat:
1299
+ print(f"{Colors.RED}You can't rest during combat!{Colors.RESET}")
1300
+ return
1301
+
1302
+ location = self.world.get_location(self.player.location_id)
1303
+ if location and not location.indoor:
1304
+ print(f"{Colors.YELLOW}Resting outdoors is not safe. You might be attacked.{Colors.RESET}")
1305
+ response = input("Continue anyway? (y/n) ").strip().lower()
1306
+ if response != 'y':
1307
+ return
1308
+
1309
+ print(f"{Colors.YELLOW}You rest for a while...{Colors.RESET}")
1310
+
1311
+ # Restore health, mana, and stamina
1312
+ self.player.stats.health = self.player.stats.max_health
1313
+ self.player.stats.mana = self.player.stats.max_mana
1314
+ self.player.stats.stamina = self.player.stats.max_stamina
1315
+
1316
+ # Advance time
1317
+ self.world.update_time(60) # Rest for 1 hour
1318
+
1319
+ # Random event chance
1320
+ if random.random() < 0.3: # 30% chance of something happening
1321
+ self.random_event()
1322
+
1323
+ def cmd_plugins(self, args):
1324
+ if not args:
1325
+ print(f"{Colors.CYAN}Loaded plugins:{Colors.RESET}")
1326
+ for plugin_path in self.plugins:
1327
+ print(f" {plugin_path}")
1328
+ return
1329
+
1330
+ command = args[0].lower()
1331
+
1332
+ if command == "load" and len(args) > 1:
1333
+ plugin_path = args[1]
1334
+ if self.load_plugin(plugin_path):
1335
+ print(f"{Colors.GREEN}Plugin loaded: {plugin_path}{Colors.RESET}")
1336
+ else:
1337
+ print(f"{Colors.RED}Failed to load plugin: {plugin_path}{Colors.RESET}")
1338
+ elif command == "unload" and len(args) > 1:
1339
+ plugin_path = args[1]
1340
+ if self.unload_plugin(plugin_path):
1341
+ print(f"{Colors.GREEN}Plugin unloaded: {plugin_path}{Colors.RESET}")
1342
+ else:
1343
+ print(f"{Colors.RED}Failed to unload plugin: {plugin_path}{Colors.RESET}")
1344
+ else:
1345
+ print(f"{Colors.RED}Usage: plugins [load|unload] [path]{Colors.RESET}")
1346
+
1347
+ # Combat methods
1348
+ def start_combat(self, opponent):
1349
+ self.in_combat = True
1350
+ self.current_opponent = opponent
1351
+
1352
+ print(f"{Colors.RED}Combat started with {opponent.name}!{Colors.RESET}")
1353
+
1354
+ # Combat loop
1355
+ while self.in_combat:
1356
+ # Display combat status
1357
+ print(f"{Colors.RED}{opponent.name}: {opponent.stats.health}/{opponent.stats.max_health} HP{Colors.RESET}")
1358
+ print(f"{Colors.GREEN}You: {self.player.stats.health}/{self.player.stats.max_health} HP{Colors.RESET}")
1359
+
1360
+ # Get player action
1361
+ try:
1362
+ action = input(f"{Colors.YELLOW}What do you do? (attack/flee/use/item): {Colors.RESET}").strip().lower()
1363
+
1364
+ if action == "attack":
1365
+ # Player attacks
1366
+ damage = self.combat.attack(self.player, opponent)
1367
+ print(f"{Colors.GREEN}You attack {opponent.name} for {damage} damage!{Colors.RESET}")
1368
+
1369
+ # Check if opponent is defeated
1370
+ if opponent.stats.health <= 0:
1371
+ print(f"{Colors.GREEN}You defeated {opponent.name}!{Colors.RESET}")
1372
+
1373
+ # Gain experience
1374
+ exp_gained = opponent.stats.level * 20
1375
+ leveled_up = self.player.gain_experience(exp_gained)
1376
+ print(f"{Colors.GREEN}You gained {exp_gained} experience!{Colors.RESET}")
1377
+ if leveled_up:
1378
+ print(f"{Colors.BRIGHT_GREEN}You leveled up! You are now level {self.player.stats.level}.{Colors.RESET}")
1379
+
1380
+ # Loot opponent
1381
+ if opponent.inventory:
1382
+ for item in opponent.inventory:
1383
+ self.player.add_item(item)
1384
+ print(f"{Colors.GREEN}You looted: {item.name}{Colors.RESET}")
1385
+
1386
+ self.end_combat()
1387
+ continue
1388
+
1389
+ # Opponent attacks
1390
+ damage = self.combat.attack(opponent, self.player)
1391
+ print(f"{Colors.RED}{opponent.name} attacks you for {damage} damage!{Colors.RESET}")
1392
+
1393
+ # Check if player is defeated
1394
+ if self.player.stats.health <= 0:
1395
+ self.game_over()
1396
+ break
1397
+
1398
+ elif action == "flee":
1399
+ if self.combat.check_flee(self.player, opponent):
1400
+ print(f"{Colors.GREEN}You successfully flee from combat.{Colors.RESET}")
1401
+ self.end_combat()
1402
+
1403
+ # Move to a random adjacent location
1404
+ location = self.world.get_location(self.player.location_id)
1405
+ if location and location.exits:
1406
+ directions = list(location.exits.keys())
1407
+ random_direction = random.choice(directions)
1408
+ self.player.location_id = location.exits[random_direction]
1409
+ print(f"{Colors.GREEN}You run away to the {random_direction.value}.{Colors.RESET}")
1410
+ else:
1411
+ print(f"{Colors.RED}You fail to flee!{Colors.RESET}")
1412
+ # Opponent gets a free attack
1413
+ damage = self.combat.attack(opponent, self.player)
1414
+ print(f"{Colors.RED}{opponent.name} attacks you for {damage} damage!{Colors.RESET}")
1415
+
1416
+ if self.player.stats.health <= 0:
1417
+ self.game_over()
1418
+ break
1419
+
1420
+ elif action == "use":
1421
+ item_name = input(f"{Colors.YELLOW}Use what item? {Colors.RESET}").strip().lower()
1422
+
1423
+ # Find the item in inventory
1424
+ for item_id, (item, quantity) in self.player.inventory.items():
1425
+ if item.name.lower() == item_name.lower():
1426
+ if item.use(self.player):
1427
+ if item.consumable:
1428
+ if quantity > 1:
1429
+ self.player.inventory[item_id] = (item, quantity - 1)
1430
+ else:
1431
+ self.player.remove_item(item_id)
1432
+ print(f"{Colors.GREEN}You use the {item.name}.{Colors.RESET}")
1433
+ else:
1434
+ print(f"{Colors.RED}You can't use the {item.name}.{Colors.RESET}")
1435
+ break
1436
+ else:
1437
+ print(f"{Colors.RED}You don't have a {item_name}.{Colors.RESET}")
1438
+
1439
+ # Opponent attacks
1440
+ damage = self.combat.attack(opponent, self.player)
1441
+ print(f"{Colors.RED}{opponent.name} attacks you for {damage} damage!{Colors.RESET}")
1442
+
1443
+ if self.player.stats.health <= 0:
1444
+ self.game_over()
1445
+ break
1446
+
1447
+ elif action == "item":
1448
+ # Use an item (same as "use")
1449
+ item_name = input(f"{Colors.YELLOW}Use what item? {Colors.RESET}").strip().lower()
1450
+
1451
+ # Find the item in inventory
1452
+ for item_id, (item, quantity) in self.player.inventory.items():
1453
+ if item.name.lower() == item_name.lower():
1454
+ if item.use(self.player):
1455
+ if item.consumable:
1456
+ if quantity > 1:
1457
+ self.player.inventory[item_id] = (item, quantity - 1)
1458
+ else:
1459
+ self.player.remove_item(item_id)
1460
+ print(f"{Colors.GREEN}You use the {item.name}.{Colors.RESET}")
1461
+ else:
1462
+ print(f"{Colors.RED}You can't use the {item.name}.{Colors.RESET}")
1463
+ break
1464
+ else:
1465
+ print(f"{Colors.RED}You don't have a {item_name}.{Colors.RESET}")
1466
+
1467
+ # Opponent attacks
1468
+ damage = self.combat.attack(opponent, self.player)
1469
+ print(f"{Colors.RED}{opponent.name} attacks you for {damage} damage!{Colors.RESET}")
1470
+
1471
+ if self.player.stats.health <= 0:
1472
+ self.game_over()
1473
+ break
1474
+
1475
+ else:
1476
+ print(f"{Colors.RED}Invalid action!{Colors.RESET}")
1477
+ # Opponent gets a free attack
1478
+ damage = self.combat.attack(opponent, self.player)
1479
+ print(f"{Colors.RED}{opponent.name} attacks you for {damage} damage!{Colors.RESET}")
1480
+
1481
+ if self.player.stats.health <= 0:
1482
+ self.game_over()
1483
+ break
1484
+
1485
+ except KeyboardInterrupt:
1486
+ print("\nGoodbye!")
1487
+ self.running = False
1488
+ break
1489
+ except EOFError:
1490
+ print("\nGoodbye!")
1491
+ self.running = False
1492
+ break
1493
+ except Exception as e:
1494
+ print(f"{Colors.RED}Error: {e}{Colors.RESET}")
1495
+
1496
+ def end_combat(self):
1497
+ self.in_combat = False
1498
+ self.current_opponent = None
1499
+
1500
+ def random_encounter(self):
1501
+ encounters = [
1502
+ {
1503
+ "message": "You encounter a wandering merchant.",
1504
+ "type": "npc",
1505
+ "npc": NPC(
1506
+ id="merchant",
1507
+ name="Wandering Merchant",
1508
+ description="A traveling merchant with a cart full of goods.",
1509
+ dialogue={
1510
+ "greeting": [
1511
+ "Hello, traveler! Care to buy something?",
1512
+ "Greetings! I have many fine wares for sale."
1513
+ ]
1514
+ },
1515
+ location_id=self.player.location_id
1516
+ )
1517
+ },
1518
+ {
1519
+ "message": "You find a treasure chest!",
1520
+ "type": "item",
1521
+ "items": [
1522
+ Item(
1523
+ id="gold",
1524
+ name="Gold",
1525
+ description="Shiny gold coins.",
1526
+ value=50,
1527
+ stackable=True
1528
+ )
1529
+ ]
1530
+ },
1531
+ {
1532
+ "message": "You are ambushed by bandits!",
1533
+ "type": "combat",
1534
+ "npc": NPC(
1535
+ id="bandit",
1536
+ name="Bandit",
1537
+ description="A dangerous-looking bandit with a weapon.",
1538
+ dialogue={},
1539
+ location_id=self.player.location_id,
1540
+ hostile=True,
1541
+ stats=Stats(health=40, max_health=40)
1542
+ )
1543
+ },
1544
+ {
1545
+ "message": "You discover a hidden path!",
1546
+ "type": "location",
1547
+ "location": Location(
1548
+ id="hidden_path",
1549
+ name="Hidden Path",
1550
+ description="A secret path that few know about.",
1551
+ position=Position(0, 0, 0)
1552
+ )
1553
+ }
1554
+ ]
1555
+
1556
+ encounter = random.choice(encounters)
1557
+ print(f"{Colors.YELLOW}{encounter['message']}{Colors.RESET}")
1558
+
1559
+ if encounter["type"] == "npc":
1560
+ location = self.world.get_location(self.player.location_id)
1561
+ if location:
1562
+ location.add_npc(encounter["npc"])
1563
+
1564
+ elif encounter["type"] == "item":
1565
+ location = self.world.get_location(self.player.location_id)
1566
+ if location:
1567
+ for item in encounter["items"]:
1568
+ location.add_item(item)
1569
+
1570
+ elif encounter["type"] == "combat":
1571
+ self.start_combat(encounter["npc"])
1572
+
1573
+ elif encounter["type"] == "location":
1574
+ self.world.add_location(encounter["location"])
1575
+ self.player.known_locations.append(encounter["location"].id)
1576
+
1577
+ def random_event(self):
1578
+ events = [
1579
+ {
1580
+ "message": "It starts to rain.",
1581
+ "effect": lambda: setattr(self.world, "weather", Weather.RAINY)
1582
+ },
1583
+ {
1584
+ "message": "The clouds part and the sun shines through.",
1585
+ "effect": lambda: setattr(self.world, "weather", Weather.CLEAR)
1586
+ },
1587
+ {
1588
+ "message": "You feel a bit hungry.",
1589
+ "effect": lambda: setattr(self.player.stats, "hunger", max(0, self.player.stats.hunger - 10))
1590
+ },
1591
+ {
1592
+ "message": "You feel a bit thirsty.",
1593
+ "effect": lambda: setattr(self.player.stats, "thirst", max(0, self.player.stats.thirst - 10))
1594
+ },
1595
+ {
1596
+ "message": "You feel refreshed.",
1597
+ "effect": lambda: setattr(self.player.stats, "stamina", min(self.player.stats.max_stamina, self.player.stats.stamina + 20))
1598
+ },
1599
+ {
1600
+ "message": "You find a coin on the ground.",
1601
+ "effect": lambda: self.player.add_item(Item(
1602
+ id="gold",
1603
+ name="Gold",
1604
+ description="A single gold coin.",
1605
+ value=1,
1606
+ stackable=True
1607
+ ))
1608
+ }
1609
+ ]
1610
+
1611
+ event = random.choice(events)
1612
+ print(f"{Colors.YELLOW}{event['message']}{Colors.RESET}")
1613
+ event["effect"]()
1614
+
1615
+ # Main function
1616
+ def main():
1617
+ game = Game()
1618
+ game.start()
1619
+
1620
+ if __name__ == "__main__":
1621
+ main()
Workspace/Python_Script_Text_based_RPD_Game3.py ADDED
File without changes
Workspace/workspace-8ac4a941-39da-4676-a1bb-2758edbb4672 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3edbcbddeb824e6724d7170c14e3192f743c7288f5848d5754aa7d30ef5d031
3
+ size 1095680
Workspace/workspace-8ac4a941-39da-4676-a1bb-2758edbb4672.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1ad739c5baf939e7c69ebdc679c88ce2c700940e22c894167318cb39ec3eeee
3
+ size 200077