ysn-rfd commited on
Commit
7a4812b
·
verified ·
1 Parent(s): c00c444

Upload 3 files

Browse files
DCE-main-game-python/LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2025 ysnrfd
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to use,
5
+ copy, modify, and distribute the Software, subject to the following conditions:
6
+
7
+ 1. The copyright notice, this permission notice, and all attribution information
8
+ regarding the original author (ysnrfd) must be preserved in their entirety
9
+ and must not be removed, altered, or obscured in any copies or derivative works.
10
+
11
+ 2. Any modifications or derivative works must be clearly documented in a "CHANGELOG" or
12
+ "NOTICE" file included with the Software. This documentation must include a detailed
13
+ description of the changes made, the date of the modification, and the identity of
14
+ the modifier.
15
+
16
+ 3. The Software is provided "as is", without warranty of any kind, express or implied.
17
+ The author shall not be liable for any damages arising from use of the Software.
18
+
19
+ 4. Any attempt to remove or alter the original attribution or copyright information
20
+ constitutes a violation of this license and may result in legal action.
DCE-main-game-python/README.md ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DCE
2
+
3
+ # 🕹️ Dungeon-Crawler-Engine
4
+
5
+ Modular dungeon crawler simulation for **AI-driven gameplay**, **pathfinding experiments**, and **cryptographic save testing**.
6
+ **Under development** by **YSNRFD**
7
+
8
+ ---
9
+
10
+ ## 🧠 DCE_ysnrfd – Procedural Dungeon Crawler Engine with AI & Secure Save System
11
+
12
+ [![Python](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://www.python.org/)
13
+ [![Game Engine](https://img.shields.io/badge/Engine-Modular-lightgreen.svg)]()
14
+ [![Save System](https://img.shields.io/badge/Saves-Cryptographically%20Signed-critical.svg)]()
15
+
16
+ ---
17
+
18
+ ## 🚀 Overview
19
+
20
+ **DCE_ysnrfd** is an extensible, modular dungeon crawler simulation built in pure Python.
21
+ It includes a secure save/load system using cryptographic HMACs, procedurally generated dungeons, an intelligent A\* enemy AI, and a structured turn-based system.
22
+ Perfect for prototyping **game mechanics**, **AI behavior**, and **simulation loops**.
23
+
24
+ This project is for **educational purposes**, AI/ML pathfinding demos, and ethical development only.
25
+
26
+ ---
27
+
28
+ ## ✨ Features
29
+
30
+ - 🧱 **Procedural Dungeon Generation**
31
+ Uses recursive division with controlled randomness to generate interconnected dungeon layouts.
32
+
33
+ - 🧠 **A\* Pathfinding**
34
+ Enemies use a priority queue with Manhattan heuristics for navigation and targeting.
35
+
36
+ - ⚙️ **Component-Based Entity System**
37
+ Players, enemies, and items are all modeled with clean, modular class structures.
38
+
39
+ - 🔒 **Cryptographic Save/Load**
40
+ Uses HMAC-SHA256 to verify save integrity. Saves are rejected if tampered.
41
+
42
+ - ⏱️ **Turn-Based State Machine**
43
+ Robust finite state system for clean transitions (menu → gameplay → endgame).
44
+
45
+ - 🧃 **Inventory & Items System**
46
+ Supports armor, weapons, potions, and quest items with metadata and effects.
47
+
48
+ - 📜 **Type-Hinted & Extensible**
49
+ Fully annotated for IDE support and future expansion.
50
+
51
+ - 📓 **Verbose Logging System**
52
+ Game states and events are logged to `dungeon_crawler.log`.
53
+
54
+ ---
55
+
56
+ ## 📦 Installation
57
+
58
+ **1. Clone the repository**
59
+
60
+ ```bash
61
+ git clone https://github.com/ysnrfd/DCE.git
62
+ cd DCE-main
63
+ ```
64
+
65
+ **2. Run the program**
66
+
67
+ Linux:
68
+ ```python
69
+ python3 dungeon_crawler.py
70
+ ```
71
+ Windows:
72
+ ```python
73
+ python dungeon_crawler.py
74
+ ```
75
+
76
+
77
+
78
+
79
+ ## 🔧 Usage Examples
80
+
81
+ **Run the main game loop**
82
+ ```python
83
+ python dungeon_crawler.py
84
+ ```
85
+
86
+ **Use the map generation module alone**
87
+
88
+ ```python
89
+ from dungeon_crawler import DungeonGenerator
90
+ map_data = DungeonGenerator(width=40, height=20).generate()
91
+ print(map_data)
92
+ ```
93
+
94
+ **Save and verify game state**
95
+
96
+ ```python
97
+ from dungeon_crawler import SaveSystem, GameState
98
+
99
+ state = GameState(...)
100
+ SaveSystem.save(state, "game_state.encrypted")
101
+ verified = SaveSystem.load("game_state.encrypted")
102
+ ```
103
+
104
+
105
+ ## 📂 Project Structure
106
+ ```structure
107
+ dungeon-crawler-engine/
108
+ │── dungeon_crawler.py # Main game engine
109
+ │── #dungeon_crawler.log # Log output
110
+ │── #game_state.encrypted # Cryptographically signed game save
111
+ │── README.md
112
+ │── LICENSE
113
+ ```
114
+
115
+
116
+ ## 🔐 Save System Details
117
+ - **Based on HMAC-SHA256 with secret key**
118
+
119
+ - **Includes timestamp and anti-replay protection**
120
+
121
+ - **Invalid or tampered saves are automatically discarded**
122
+
123
+
124
+ ## 🧠 Algorithms & Internals
125
+ - **Pathfinding: A with open/closed sets, priority queues (heapq)**
126
+
127
+ - **Dungeon Generation: Recursive division + random room linking**
128
+
129
+ - **State Machine: Enum-based game states and transitions**
130
+
131
+ - **Secure Save: JSON serialization + hmac + secrets**
132
+
133
+
134
+ ## 🛣️ Roadmap
135
+ **✅ Cryptographic save/load system**
136
+
137
+ **✅ Procedural generation engine**
138
+
139
+ **✅ A pathfinding and enemy AI**
140
+
141
+ **🔲 GUI version with Pygame or Pyxel**
142
+
143
+ **🔲 Quest/dialogue system**
144
+
145
+ **🔲 Plugin API for modding**
146
+
147
+ **🔲 Fog of war and minimap**
148
+
149
+
150
+
151
+ ## ⚠️ Ethical Usage Notice
152
+ This engine is intended for learning, game prototyping, and academic experiments only.
153
+ You are not permitted to use this code in unethical simulations or closed-source game repackaging without preserving attribution.
154
+
155
+ ## 📝 License
156
+ This project is licensed under the **YSNRFD License.**
157
+ You are free to fork and build upon it with proper credit and within ethical guidelines.
158
+ Redistribution without credit is strictly forbidden.
159
+
160
+ ## 👨‍💻 Author
161
+ **Developer: YSNRFD**
162
+ **Telegram: @ysnrfd**
163
+
164
+ ## ⭐ Support This Project
165
+ **If you enjoyed this project or learned something useful, please star it on GitHub and share it with others!**
DCE-main-game-python/dungeon_crawler.py ADDED
@@ -0,0 +1,726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ ██████╗ ███████╗███████╗███████╗██████╗ █████╗ ██████╗ ███████╗
4
+ ██╔══██╗██╔════╝██╔════╝██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔════╝
5
+ ██████╔╝█████╗ █████╗ █████╗ ██████╔╝███████║██████╔╝█████╗
6
+ ██╔══██╗██╔══╝ ██╔══╝ ██╔══╝ ██╔══██╗██╔══██║██╔══██╗██╔══╝
7
+ ██║ ██║███████╗██║ ███████╗██║ ██║██║ ██║██║ ██║███████╗
8
+ ╚═╝ ╚═╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
9
+
10
+ A hyper-structured, enterprise-grade dungeon crawler simulation with:
11
+ - Procedural dungeon generation (Recursive Division Algorithm)
12
+ - A* Pathfinding for enemy AI
13
+ - Component-Based Entity System
14
+ - JSON Save/Load with cryptographic signing
15
+ - Multithreaded event handling
16
+ - Comprehensive error logging
17
+ - State machine architecture
18
+ - Type hints and docstring documentation
19
+ ----------------------------------------------
20
+
21
+ Developer: YSNRFD
22
+ Telegram: @ysnrfd
23
+ """
24
+
25
+ import json
26
+ import time
27
+ import threading
28
+ import logging
29
+ import hashlib
30
+ import hmac
31
+ import secrets
32
+ from enum import Enum, auto
33
+ from heapq import heappop, heappush
34
+ from typing import (
35
+ Dict,
36
+ List,
37
+ Tuple,
38
+ Optional,
39
+ Set,
40
+ Any,
41
+ Callable,
42
+ TypeVar,
43
+ Generic,
44
+ cast
45
+ )
46
+
47
+ # =============================================================================
48
+ # CONFIGURATION & CONSTANTS
49
+ # =============================================================================
50
+ SECRET_KEY = secrets.token_bytes(32)
51
+ LOG_FILE = "dungeon_crawler.log"
52
+ SAVE_FILE = "game_state.encrypted"
53
+ MAX_ROOMS = 15
54
+ ROOM_MIN_SIZE = 4
55
+ ROOM_MAX_SIZE = 8
56
+ ENEMY_SPAWN_RATE = 0.3
57
+ ITEM_SPAWN_RATE = 0.25
58
+
59
+ # =============================================================================
60
+ # LOGGING SETUP
61
+ # =============================================================================
62
+ logging.basicConfig(
63
+ level=logging.INFO,
64
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
65
+ handlers=[
66
+ logging.FileHandler(LOG_FILE),
67
+ logging.StreamHandler()
68
+ ]
69
+ )
70
+ logger = logging.getLogger("DungeonCrawler")
71
+
72
+ # =============================================================================
73
+ # CUSTOM EXCEPTIONS
74
+ # =============================================================================
75
+ class DungeonGenerationError(Exception):
76
+ """Raised when dungeon generation fails"""
77
+ pass
78
+
79
+ class SaveFileCorruptedError(Exception):
80
+ """Raised when save file integrity check fails"""
81
+ pass
82
+
83
+ class InvalidGameStateError(Exception):
84
+ """Raised when game state violates business rules"""
85
+ pass
86
+
87
+ # =============================================================================
88
+ # ENUMERATIONS
89
+ # =============================================================================
90
+ class Direction(Enum):
91
+ NORTH = auto()
92
+ EAST = auto()
93
+ SOUTH = auto()
94
+ WEST = auto()
95
+
96
+ class ItemType(Enum):
97
+ WEAPON = auto()
98
+ ARMOR = auto()
99
+ POTION = auto()
100
+ QUEST = auto()
101
+
102
+ class EntityState(Enum):
103
+ IDLE = auto()
104
+ PATROLLING = auto()
105
+ CHASING = auto()
106
+ COMBAT = auto()
107
+ DEAD = auto()
108
+
109
+ # =============================================================================
110
+ # GEOMETRY & MATH UTILITIES
111
+ # =============================================================================
112
+ T = TypeVar('T')
113
+ class BoundedQueue(Generic[T]):
114
+ """Thread-safe bounded queue with priority support"""
115
+ def __init__(self, max_size: int = 10):
116
+ self.max_size = max_size
117
+ self._queue: List[Tuple[int, T]] = []
118
+ self._lock = threading.RLock()
119
+
120
+ def push(self, priority: int, item: T) -> None:
121
+ with self._lock:
122
+ heappush(self._queue, (priority, item))
123
+ if len(self._queue) > self.max_size:
124
+ self._queue.pop()
125
+
126
+ def pop(self) -> T:
127
+ with self._lock:
128
+ return heappop(self._queue)[1]
129
+
130
+ def clear(self) -> None:
131
+ with self._lock:
132
+ self._queue.clear()
133
+
134
+ class Vector2D:
135
+ """Immutable 2D coordinate system"""
136
+ __slots__ = ('x', 'y')
137
+
138
+ def __init__(self, x: int, y: int):
139
+ self.x = x
140
+ self.y = y
141
+
142
+ def __add__(self, other: 'Vector2D') -> 'Vector2D':
143
+ return Vector2D(self.x + other.x, self.y + other.y)
144
+
145
+ def __sub__(self, other: 'Vector2D') -> 'Vector2D':
146
+ return Vector2D(self.x - other.x, self.y - other.y)
147
+
148
+ def __eq__(self, other: object) -> bool:
149
+ if not isinstance(other, Vector2D):
150
+ return False
151
+ return self.x == other.x and self.y == other.y
152
+
153
+ def __hash__(self) -> int:
154
+ return hash((self.x, self.y))
155
+
156
+ def __repr__(self) -> str:
157
+ return f"Vector2D({self.x}, {self.y})"
158
+
159
+ # =============================================================================
160
+ # GAME CORE COMPONENTS
161
+ # =============================================================================
162
+ class Room:
163
+ """Represents a dungeon room with spatial properties"""
164
+ def __init__(self, origin: Vector2D, width: int, height: int):
165
+ self.origin = origin
166
+ self.width = width
167
+ self.height = height
168
+ self.connections: Dict[Direction, 'Room'] = {}
169
+ self.items: List['Item'] = []
170
+ self.enemies: List['Enemy'] = []
171
+ self.explored = False
172
+
173
+ @property
174
+ def center(self) -> Vector2D:
175
+ return Vector2D(
176
+ self.origin.x + self.width // 2,
177
+ self.origin.y + self.height // 2
178
+ )
179
+
180
+ def intersects(self, other: 'Room') -> bool:
181
+ """Check if this room intersects with another room"""
182
+ return (
183
+ self.origin.x <= other.origin.x + other.width and
184
+ self.origin.x + self.width >= other.origin.x and
185
+ self.origin.y <= other.origin.y + other.height and
186
+ self.origin.y + self.height >= other.origin.y
187
+ )
188
+
189
+ class Dungeon:
190
+ """Procedurally generated dungeon using recursive division"""
191
+ def __init__(self, width: int, height: int):
192
+ self.width = width
193
+ self.height = height
194
+ self.rooms: List[Room] = []
195
+ self.tiles: List[List[bool]] = [
196
+ [False for _ in range(height)]
197
+ for _ in range(width)
198
+ ]
199
+ self.player_start = Vector2D(0, 0)
200
+ self.exit = Vector2D(0, 0)
201
+
202
+ def generate(self) -> None:
203
+ """Generate dungeon using recursive division algorithm"""
204
+ start_time = time.time()
205
+ self._recursive_division(0, 0, self.width, self.height)
206
+
207
+ # Connect all rooms
208
+ self._connect_rooms()
209
+
210
+ # Place player and exit
211
+ if not self.rooms:
212
+ raise DungeonGenerationError("No rooms generated")
213
+
214
+ self.player_start = self.rooms[0].center
215
+ self.exit = self.rooms[-1].center
216
+
217
+ # Populate with items and enemies
218
+ self._populate_dungeon()
219
+
220
+ logger.info(f"Dungeon generated in {time.time() - start_time:.4f}s")
221
+
222
+ def _recursive_division(self, x: int, y: int, w: int, h: int) -> None:
223
+ """Recursive division algorithm for room generation"""
224
+ if w <= ROOM_MIN_SIZE * 2 or h <= ROOM_MIN_SIZE * 2:
225
+ return
226
+
227
+ # Randomly choose split position
228
+ split_x = x + ROOM_MIN_SIZE + random.randint(0, w - ROOM_MIN_SIZE * 2)
229
+ split_y = y + ROOM_MIN_SIZE + random.randint(0, h - ROOM_MIN_SIZE * 2)
230
+
231
+ # Create rooms
232
+ room_w = random.randint(ROOM_MIN_SIZE, min(ROOM_MAX_SIZE, w // 2))
233
+ room_h = random.randint(ROOM_MIN_SIZE, min(ROOM_MAX_SIZE, h // 2))
234
+ new_room = Room(Vector2D(split_x, split_y), room_w, room_h)
235
+
236
+ # Check intersection with existing rooms
237
+ if not any(new_room.intersects(r) for r in self.rooms):
238
+ self.rooms.append(new_room)
239
+
240
+ # Carve room into tile map
241
+ for i in range(new_room.origin.x, new_room.origin.x + new_room.width):
242
+ for j in range(new_room.origin.y, new_room.origin.y + new_room.height):
243
+ if 0 <= i < self.width and 0 <= j < self.height:
244
+ self.tiles[i][j] = True
245
+
246
+ # Recursively divide remaining space
247
+ self._recursive_division(x, y, split_x - x, split_y - y)
248
+ self._recursive_division(split_x, y, w - (split_x - x), split_y - y)
249
+ self._recursive_division(x, split_y, split_x - x, h - (split_y - y))
250
+ self._recursive_division(split_x, split_y, w - (split_x - x), h - (split_y - y))
251
+
252
+ def _connect_rooms(self) -> None:
253
+ """Connect all rooms with corridors"""
254
+ for i in range(len(self.rooms) - 1):
255
+ room_a = self.rooms[i]
256
+ room_b = self.rooms[i + 1]
257
+
258
+ # Horizontal corridor
259
+ x1, y1 = room_a.center.x, room_a.center.y
260
+ x2, y2 = room_b.center.x, room_b.center.y
261
+
262
+ # Carve horizontal then vertical
263
+ for x in range(min(x1, x2), max(x1, x2) + 1):
264
+ self.tiles[x][y1] = True
265
+ for y in range(min(y1, y2), max(y1, y2) + 1):
266
+ self.tiles[x2][y] = True
267
+
268
+ # Record connection
269
+ room_a.connections[Direction.EAST] = room_b
270
+ room_b.connections[Direction.WEST] = room_a
271
+
272
+ def _populate_dungeon(self) -> None:
273
+ """Populate dungeon with items and enemies"""
274
+ for room in self.rooms:
275
+ # Enemies
276
+ if random.random() < ENEMY_SPAWN_RATE:
277
+ enemy = Enemy(
278
+ position=room.center,
279
+ enemy_type=random.choice(list(EnemyType))
280
+ )
281
+ room.enemies.append(enemy)
282
+
283
+ # Items
284
+ if random.random() < ITEM_SPAWN_RATE:
285
+ item = Item.create_random(room.center)
286
+ room.items.append(item)
287
+
288
+ class Item:
289
+ """Base class for all in-game items"""
290
+ def __init__(self, position: Vector2D, item_type: ItemType, name: str, value: int):
291
+ self.position = position
292
+ self.item_type = item_type
293
+ self.name = name
294
+ self.value = value
295
+ self.equipped = False
296
+
297
+ @classmethod
298
+ def create_random(cls, position: Vector2D) -> 'Item':
299
+ """Factory method for random item generation"""
300
+ item_type = random.choice(list(ItemType))
301
+ if item_type == ItemType.WEAPON:
302
+ return Weapon(
303
+ position,
304
+ f"{random.choice(['Iron', 'Steel', 'Mithril'])} {random.choice(['Sword', 'Axe', 'Dagger'])}",
305
+ random.randint(5, 15)
306
+ )
307
+ elif item_type == ItemType.ARMOR:
308
+ return Armor(
309
+ position,
310
+ f"{random.choice(['Leather', 'Chainmail', 'Plate'])} {random.choice(['Armor', 'Helmet', 'Shield'])}",
311
+ random.randint(3, 10)
312
+ )
313
+ elif item_type == ItemType.POTION:
314
+ return Potion(
315
+ position,
316
+ f"{random.choice(['Healing', 'Mana', 'Strength'])} Potion",
317
+ random.randint(10, 30)
318
+ )
319
+ else:
320
+ return QuestItem(
321
+ position,
322
+ f"{random.choice(['Ancient', 'Cursed', 'Sacred'])} {random.choice(['Artifact', 'Relic', 'Scroll'])}",
323
+ random.randint(50, 100)
324
+ )
325
+
326
+ def to_dict(self) -> Dict[str, Any]:
327
+ """Serialize item to dictionary"""
328
+ return {
329
+ 'type': self.__class__.__name__,
330
+ 'position': (self.position.x, self.position.y),
331
+ 'name': self.name,
332
+ 'value': self.value,
333
+ 'equipped': self.equipped
334
+ }
335
+
336
+ @staticmethod
337
+ def from_dict( Dict[str, Any]) -> 'Item':
338
+ """Deserialize item from dictionary"""
339
+ position = Vector2D(data['position'][0], data['position'][1])
340
+ if data['type'] == 'Weapon':
341
+ return Weapon(position, data['name'], data['value'])
342
+ # ... other types would be handled here
343
+ raise ValueError(f"Unknown item type: {data['type']}")
344
+
345
+ class Weapon(Item):
346
+ def __init__(self, position: Vector2D, name: str, damage: int):
347
+ super().__init__(position, ItemType.WEAPON, name, damage)
348
+ self.damage = damage
349
+
350
+ class Armor(Item):
351
+ def __init__(self, position: Vector2D, name: str, defense: int):
352
+ super().__init__(position, ItemType.ARMOR, name, defense)
353
+ self.defense = defense
354
+
355
+ class Potion(Item):
356
+ def __init__(self, position: Vector2D, name: str, heal_amount: int):
357
+ super().__init__(position, ItemType.POTION, name, heal_amount)
358
+ self.heal_amount = heal_amount
359
+
360
+ class QuestItem(Item):
361
+ def __init__(self, position: Vector2D, name: str, quest_value: int):
362
+ super().__init__(position, ItemType.QUEST, name, quest_value)
363
+ self.quest_value = quest_value
364
+
365
+ # =============================================================================
366
+ # ENTITY SYSTEM
367
+ # =============================================================================
368
+ class Entity:
369
+ """Base class for all game entities"""
370
+ def __init__(self, position: Vector2D):
371
+ self.position = position
372
+ self.components: Dict[str, Any] = {}
373
+
374
+ def add_component(self, name: str, component: Any) -> None:
375
+ self.components[name] = component
376
+
377
+ def get_component(self, name: str) -> Optional[Any]:
378
+ return self.components.get(name)
379
+
380
+ class CombatStats:
381
+ """Component for combat-related statistics"""
382
+ def __init__(self, hp: int, max_hp: int, attack: int, defense: int):
383
+ self.hp = hp
384
+ self.max_hp = max_hp
385
+ self.attack = attack
386
+ self.defense = defense
387
+
388
+ class Inventory:
389
+ """Component for inventory management"""
390
+ def __init__(self, capacity: int = 10):
391
+ self.capacity = capacity
392
+ self.items: List[Item] = []
393
+ self.equipped: Dict[ItemType, Optional[Item]] = {
394
+ ItemType.WEAPON: None,
395
+ ItemType.ARMOR: None
396
+ }
397
+
398
+ def add_item(self, item: Item) -> bool:
399
+ if len(self.items) >= self.capacity:
400
+ return False
401
+ self.items.append(item)
402
+ return True
403
+
404
+ def equip_item(self, item: Item) -> bool:
405
+ if item.item_type not in self.equipped:
406
+ return False
407
+ if item.item_type == ItemType.WEAPON or item.item_type == ItemType.ARMOR:
408
+ self.equipped[item.item_type] = item
409
+ item.equipped = True
410
+ return True
411
+ return False
412
+
413
+ class Player(Entity):
414
+ """Player character with advanced state management"""
415
+ def __init__(self, position: Vector2D):
416
+ super().__init__(position)
417
+ self.add_component("combat", CombatStats(100, 100, 10, 5))
418
+ self.add_component("inventory", Inventory())
419
+ self.experience = 0
420
+ self.level = 1
421
+
422
+ def take_damage(self, amount: int) -> bool:
423
+ """Apply damage and return if entity is dead"""
424
+ combat = cast(CombatStats, self.get_component("combat"))
425
+ actual_damage = max(1, amount - combat.defense)
426
+ combat.hp -= actual_damage
427
+ logger.info(f"Player took {actual_damage} damage. HP: {combat.hp}/{combat.max_hp}")
428
+ return combat.hp <= 0
429
+
430
+ def heal(self, amount: int) -> None:
431
+ combat = cast(CombatStats, self.get_component("combat"))
432
+ combat.hp = min(combat.max_hp, combat.hp + amount)
433
+ logger.info(f"Player healed for {amount}. HP: {combat.hp}/{combat.max_hp}")
434
+
435
+ class EnemyType(Enum):
436
+ GOBLIN = ("Goblin", 30, 5, 2)
437
+ ORC = ("Orc", 50, 8, 4)
438
+ TROLL = ("Troll", 80, 12, 6)
439
+
440
+ def __init__(self, name: str, hp: int, attack: int, defense: int):
441
+ self.display_name = name
442
+ self.default_hp = hp
443
+ self.default_attack = attack
444
+ self.default_defense = defense
445
+
446
+ class Enemy(Entity):
447
+ """Enemy with state-based AI behavior"""
448
+ def __init__(self, position: Vector2D, enemy_type: EnemyType):
449
+ super().__init__(position)
450
+ self.enemy_type = enemy_type
451
+ self.state = EntityState.PATROLLING
452
+ self.path: List[Vector2D] = []
453
+ self.vision_range = 5
454
+ self.add_component("combat", CombatStats(
455
+ enemy_type.default_hp,
456
+ enemy_type.default_hp,
457
+ enemy_type.default_attack,
458
+ enemy_type.default_defense
459
+ ))
460
+
461
+ def update_ai(self, player_pos: Vector2D, dungeon: Dungeon) -> None:
462
+ """Update enemy state based on player position"""
463
+ distance = abs(player_pos.x - self.position.x) + abs(player_pos.y - self.position.y)
464
+
465
+ if distance <= self.vision_range:
466
+ self.state = EntityState.CHASING
467
+ else:
468
+ self.state = EntityState.PATROLLING
469
+
470
+ # Pathfinding logic
471
+ if self.state == EntityState.CHASING and (not self.path or random.random() < 0.1):
472
+ self.path = self._find_path(player_pos, dungeon)
473
+
474
+ # Move along path
475
+ if self.path:
476
+ self.position = self.path.pop(0)
477
+
478
+ def _find_path(self, target: Vector2D, dungeon: Dungeon) -> List[Vector2D]:
479
+ """A* pathfinding implementation"""
480
+ open_set = BoundedQueue()
481
+ open_set.push(0, (self.position, []))
482
+ closed_set: Set[Vector2D] = set()
483
+
484
+ while open_set:
485
+ current, path = open_set.pop()
486
+ if current == target:
487
+ return path[1:] # Skip first position (current)
488
+
489
+ if current in closed_set:
490
+ continue
491
+
492
+ closed_set.add(current)
493
+ for direction in [Vector2D(0, -1), Vector2D(1, 0), Vector2D(0, 1), Vector2D(-1, 0)]:
494
+ neighbor = current + direction
495
+ if (
496
+ 0 <= neighbor.x < dungeon.width and
497
+ 0 <= neighbor.y < dungeon.height and
498
+ dungeon.tiles[neighbor.x][neighbor.y] and
499
+ neighbor not in closed_set
500
+ ):
501
+ new_path = path + [neighbor]
502
+ priority = len(new_path) + abs(neighbor.x - target.x) + abs(neighbor.y - target.y)
503
+ open_set.push(priority, (neighbor, new_path))
504
+
505
+ return [] # No path found
506
+
507
+ # =============================================================================
508
+ # GAME STATE MANAGEMENT
509
+ # =============================================================================
510
+ class GameState(Enum):
511
+ MAIN_MENU = auto()
512
+ PLAYING = auto()
513
+ PAUSED = auto()
514
+ GAME_OVER = auto()
515
+ VICTORY = auto()
516
+
517
+ class GameContext:
518
+ """Holds global game state and services"""
519
+ def __init__(self):
520
+ self.state = GameState.MAIN_MENU
521
+ self.dungeon = Dungeon(80, 40)
522
+ self.player = Player(Vector2D(0, 0))
523
+ self.enemies: List[Enemy] = []
524
+ self.current_room: Optional[Room] = None
525
+ self.event_queue = BoundedQueue[Callable[[], None]]()
526
+ self.thread = threading.Thread(target=self._process_events, daemon=True)
527
+ self.thread.start()
528
+ self.last_update = time.time()
529
+ self.fps = 0
530
+
531
+ def _process_events(self) -> None:
532
+ """Process queued events in separate thread"""
533
+ while True:
534
+ try:
535
+ event = self.event_queue.pop()
536
+ event()
537
+ except IndexError:
538
+ time.sleep(0.01)
539
+
540
+ def save_game(self) -> None:
541
+ """Save game state with cryptographic integrity check"""
542
+ start_time = time.time()
543
+ state = {
544
+ 'player': {
545
+ 'position': (self.player.position.x, self.player.position.y),
546
+ 'health': self.player.get_component("combat").hp,
547
+ 'level': self.player.level
548
+ },
549
+ 'dungeon': {
550
+ 'width': self.dungeon.width,
551
+ 'height': self.dungeon.height
552
+ },
553
+ 'timestamp': time.time()
554
+ }
555
+
556
+ # Serialize and sign
557
+ serialized = json.dumps(state).encode()
558
+ signature = hmac.new(SECRET_KEY, serialized, hashlib.sha256).digest()
559
+ encrypted = serialized + signature
560
+
561
+ with open(SAVE_FILE, 'wb') as f:
562
+ f.write(encrypted)
563
+
564
+ logger.info(f"Game saved in {time.time() - start_time:.4f}s")
565
+
566
+ def load_game(self) -> None:
567
+ """Load game state with integrity verification"""
568
+ start_time = time.time()
569
+ try:
570
+ with open(SAVE_FILE, 'rb') as f:
571
+ data = f.read()
572
+
573
+ # Verify signature
574
+ serialized = data[:-32]
575
+ signature = data[-32:]
576
+ if not hmac.compare_digest(hmac.new(SECRET_KEY, serialized, hashlib.sha256).digest(), signature):
577
+ raise SaveFileCorruptedError("Signature mismatch")
578
+
579
+ state = json.loads(serialized)
580
+
581
+ # Reconstruct game state
582
+ self.player.position = Vector2D(
583
+ state['player']['position'][0],
584
+ state['player']['position'][1]
585
+ )
586
+ self.player.get_component("combat").hp = state['player']['health']
587
+ self.player.level = state['player']['level']
588
+
589
+ logger.info(f"Game loaded in {time.time() - start_time:.4f}s")
590
+ except Exception as e:
591
+ logger.error(f"Failed to load game: {str(e)}")
592
+ raise
593
+
594
+ # =============================================================================
595
+ # MAIN GAME LOOP
596
+ # =============================================================================
597
+ class Game:
598
+ """Main game controller with state machine architecture"""
599
+ def __init__(self):
600
+ self.context = GameContext()
601
+ self.running = True
602
+ self.frame_count = 0
603
+ self.last_fps_update = time.time()
604
+
605
+ def start(self) -> None:
606
+ """Initialize and start the game loop"""
607
+ logger.info("Starting game engine...")
608
+ self.context.dungeon.generate()
609
+ self.context.player.position = self.context.dungeon.player_start
610
+
611
+ # Spawn enemies
612
+ for room in self.context.dungeon.rooms:
613
+ for enemy in room.enemies:
614
+ self.context.enemies.append(enemy)
615
+
616
+ self.context.state = GameState.PLAYING
617
+ self._main_loop()
618
+
619
+ def _main_loop(self) -> None:
620
+ """Primary game loop with fixed timestep"""
621
+ TARGET_FPS = 60
622
+ TIME_PER_FRAME = 1.0 / TARGET_FPS
623
+ last_time = time.time()
624
+
625
+ while self.running:
626
+ current_time = time.time()
627
+ elapsed = current_time - last_time
628
+
629
+ if elapsed >= TIME_PER_FRAME:
630
+ last_time = current_time
631
+
632
+ # Process input
633
+ self._handle_input()
634
+
635
+ # Update game state
636
+ self._update(elapsed)
637
+
638
+ # Render frame
639
+ self._render()
640
+
641
+ # FPS calculation
642
+ self.frame_count += 1
643
+ if current_time - self.last_fps_update > 1.0:
644
+ self.context.fps = self.frame_count
645
+ self.frame_count = 0
646
+ self.last_fps_update = current_time
647
+
648
+ def _handle_input(self) -> None:
649
+ """Process player input (simulated here)"""
650
+ if self.context.state != GameState.PLAYING:
651
+ return
652
+
653
+ # Simulate movement (in real game would use actual input)
654
+ direction = random.choice([
655
+ Vector2D(0, -1), # Up
656
+ Vector2D(1, 0), # Right
657
+ Vector2D(0, 1), # Down
658
+ Vector2D(-1, 0) # Left
659
+ ])
660
+ new_pos = self.context.player.position + direction
661
+
662
+ # Validate movement
663
+ if (
664
+ 0 <= new_pos.x < self.context.dungeon.width and
665
+ 0 <= new_pos.y < self.context.dungeon.height and
666
+ self.context.dungeon.tiles[new_pos.x][new_pos.y]
667
+ ):
668
+ self.context.player.position = new_pos
669
+
670
+ def _update(self, delta_time: float) -> None:
671
+ """Update all game systems"""
672
+ # Update enemies
673
+ for enemy in self.context.enemies[:]:
674
+ enemy.update_ai(self.context.player.position, self.context.dungeon)
675
+
676
+ # Combat check
677
+ if enemy.position == self.context.player.position:
678
+ enemy.get_component("combat").hp -= self.context.player.get_component("combat").attack
679
+ if enemy.get_component("combat").hp <= 0:
680
+ self.context.enemies.remove(enemy)
681
+ logger.info(f"Defeated {enemy.enemy_type.display_name}!")
682
+
683
+ # Check game state transitions
684
+ if self.context.player.position == self.context.dungeon.exit:
685
+ self.context.state = GameState.VICTORY
686
+ logger.info("Player reached the exit! Victory!")
687
+ self.running = False
688
+
689
+ if self.context.player.get_component("combat").hp <= 0:
690
+ self.context.state = GameState.GAME_OVER
691
+ logger.info("Player has died. Game over.")
692
+ self.running = False
693
+
694
+ def _render(self) -> None:
695
+ """Render game state (simulated here)"""
696
+ # In a real implementation, this would draw to a screen
697
+ if self.frame_count % 30 == 0: # Every half second at 60 FPS
698
+ logger.debug(
699
+ f"Rendering frame... Player at {self.context.player.position}, "
700
+ f"Enemies: {len(self.context.enemies)}, FPS: {self.context.fps}"
701
+ )
702
+
703
+ # =============================================================================
704
+ # ENTRY POINT
705
+ # =============================================================================
706
+ def main() -> None:
707
+ """Application entry point with full error handling"""
708
+ game = None
709
+ try:
710
+ logger.info("Initializing game...")
711
+ game = Game()
712
+ game.start()
713
+ logger.info("Game loop exited cleanly")
714
+ except Exception as e:
715
+ logger.exception("Critical error in game loop")
716
+ if game and game.context.state == GameState.PLAYING:
717
+ try:
718
+ game.context.save_game()
719
+ logger.info("Saved game state before crash")
720
+ except Exception as save_error:
721
+ logger.error(f"Failed to save game after crash: {str(save_error)}")
722
+ finally:
723
+ logger.info("Shutting down game engine")
724
+
725
+ if __name__ == "__main__":
726
+ main()