ysn-rfd/text-dataset-tiny-code-script-py-format
USED of tahamajs/medicine_ds_persian for .parquet file USED of Alijafarixcs2/persian-it-llama2-2k for .parquet file USED of Abirate/english_quotes for .jsonl file NEW FILES (05/12/2025) NEW FILES (12/26/2025) NEW FILES (02/15/2026)
31.6k
1#!/usr/bin/env python32"""3██████╗ ███████╗███████╗███████╗██████╗ █████╗ ██████╗ ███████╗4██╔══██╗██╔════╝██╔════╝██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔════╝5██████╔╝█████╗ █████╗ █████╗ ██████╔╝███████║██████╔╝█████╗ 6██╔══██╗██╔══╝ ██╔══╝ ██╔══╝ ██╔══██╗██╔══██║██╔══██╗██╔══╝ 7██║ ██║███████╗██║ ███████╗██║ ██║██║ ██║██║ ██║███████╗8╚═╝ ╚═╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝9 10A hyper-structured, enterprise-grade dungeon crawler simulation with:11- Procedural dungeon generation (Recursive Division Algorithm)12- A* Pathfinding for enemy AI13- Component-Based Entity System14- JSON Save/Load with cryptographic signing15- Multithreaded event handling16- Comprehensive error logging17- State machine architecture18- Type hints and docstring documentation19----------------------------------------------20 21Developer: YSNRFD22Telegram: @ysnrfd23"""24 25import json26import time27import threading28import logging29import hashlib30import hmac31import secrets32from enum import Enum, auto33from heapq import heappop, heappush34from typing import (35 Dict, 36 List, 37 Tuple, 38 Optional, 39 Set, 40 Any, 41 Callable, 42 TypeVar, 43 Generic,44 cast45)46 47# =============================================================================48# CONFIGURATION & CONSTANTS49# =============================================================================50SECRET_KEY = secrets.token_bytes(32)51LOG_FILE = "dungeon_crawler.log"52SAVE_FILE = "game_state.encrypted"53MAX_ROOMS = 1554ROOM_MIN_SIZE = 455ROOM_MAX_SIZE = 856ENEMY_SPAWN_RATE = 0.357ITEM_SPAWN_RATE = 0.2558 59# =============================================================================60# LOGGING SETUP61# =============================================================================62logging.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)70logger = logging.getLogger("DungeonCrawler")71 72# =============================================================================73# CUSTOM EXCEPTIONS74# =============================================================================75class DungeonGenerationError(Exception):76 """Raised when dungeon generation fails"""77 pass78 79class SaveFileCorruptedError(Exception):80 """Raised when save file integrity check fails"""81 pass82 83class InvalidGameStateError(Exception):84 """Raised when game state violates business rules"""85 pass86 87# =============================================================================88# ENUMERATIONS89# =============================================================================90class Direction(Enum):91 NORTH = auto()92 EAST = auto()93 SOUTH = auto()94 WEST = auto()95 96class ItemType(Enum):97 WEAPON = auto()98 ARMOR = auto()99 POTION = auto()100 QUEST = auto()101 102class EntityState(Enum):103 IDLE = auto()104 PATROLLING = auto()105 CHASING = auto()106 COMBAT = auto()107 DEAD = auto()108 109# =============================================================================110# GEOMETRY & MATH UTILITIES111# =============================================================================112T = TypeVar('T')113class BoundedQueue(Generic[T]):114 """Thread-safe bounded queue with priority support"""115 def __init__(self, max_size: int = 10):116 self.max_size = max_size117 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 134class Vector2D:135 """Immutable 2D coordinate system"""136 __slots__ = ('x', 'y')137 138 def __init__(self, x: int, y: int):139 self.x = x140 self.y = y141 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 False151 return self.x == other.x and self.y == other.y152 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 COMPONENTS161# =============================================================================162class Room:163 """Represents a dungeon room with spatial properties"""164 def __init__(self, origin: Vector2D, width: int, height: int):165 self.origin = origin166 self.width = width167 self.height = height168 self.connections: Dict[Direction, 'Room'] = {}169 self.items: List['Item'] = []170 self.enemies: List['Enemy'] = []171 self.explored = False172 173 @property174 def center(self) -> Vector2D:175 return Vector2D(176 self.origin.x + self.width // 2,177 self.origin.y + self.height // 2178 )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 and184 self.origin.x + self.width >= other.origin.x and185 self.origin.y <= other.origin.y + other.height and186 self.origin.y + self.height >= other.origin.y187 )188 189class Dungeon:190 """Procedurally generated dungeon using recursive division"""191 def __init__(self, width: int, height: int):192 self.width = width193 self.height = height194 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 rooms208 self._connect_rooms()209 210 # Place player and exit211 if not self.rooms:212 raise DungeonGenerationError("No rooms generated")213 214 self.player_start = self.rooms[0].center215 self.exit = self.rooms[-1].center216 217 # Populate with items and enemies218 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 return226 227 # Randomly choose split position228 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 rooms232 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 rooms237 if not any(new_room.intersects(r) for r in self.rooms):238 self.rooms.append(new_room)239 240 # Carve room into tile map241 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] = True245 246 # Recursively divide remaining space247 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 corridor259 x1, y1 = room_a.center.x, room_a.center.y260 x2, y2 = room_b.center.x, room_b.center.y261 262 # Carve horizontal then vertical263 for x in range(min(x1, x2), max(x1, x2) + 1):264 self.tiles[x][y1] = True265 for y in range(min(y1, y2), max(y1, y2) + 1):266 self.tiles[x2][y] = True267 268 # Record connection269 room_a.connections[Direction.EAST] = room_b270 room_b.connections[Direction.WEST] = room_a271 272 def _populate_dungeon(self) -> None:273 """Populate dungeon with items and enemies"""274 for room in self.rooms:275 # Enemies276 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 # Items284 if random.random() < ITEM_SPAWN_RATE:285 item = Item.create_random(room.center)286 room.items.append(item)287 288class 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 = position292 self.item_type = item_type293 self.name = name294 self.value = value295 self.equipped = False296 297 @classmethod298 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.equipped334 }335 336 @staticmethod337 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 here343 raise ValueError(f"Unknown item type: {data['type']}")344 345class Weapon(Item):346 def __init__(self, position: Vector2D, name: str, damage: int):347 super().__init__(position, ItemType.WEAPON, name, damage)348 self.damage = damage349 350class Armor(Item):351 def __init__(self, position: Vector2D, name: str, defense: int):352 super().__init__(position, ItemType.ARMOR, name, defense)353 self.defense = defense354 355class 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_amount359 360class 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_value364 365# =============================================================================366# ENTITY SYSTEM367# =============================================================================368class Entity:369 """Base class for all game entities"""370 def __init__(self, position: Vector2D):371 self.position = position372 self.components: Dict[str, Any] = {}373 374 def add_component(self, name: str, component: Any) -> None:375 self.components[name] = component376 377 def get_component(self, name: str) -> Optional[Any]:378 return self.components.get(name)379 380class CombatStats:381 """Component for combat-related statistics"""382 def __init__(self, hp: int, max_hp: int, attack: int, defense: int):383 self.hp = hp384 self.max_hp = max_hp385 self.attack = attack386 self.defense = defense387 388class Inventory:389 """Component for inventory management"""390 def __init__(self, capacity: int = 10):391 self.capacity = capacity392 self.items: List[Item] = []393 self.equipped: Dict[ItemType, Optional[Item]] = {394 ItemType.WEAPON: None,395 ItemType.ARMOR: None396 }397 398 def add_item(self, item: Item) -> bool:399 if len(self.items) >= self.capacity:400 return False401 self.items.append(item)402 return True403 404 def equip_item(self, item: Item) -> bool:405 if item.item_type not in self.equipped:406 return False407 if item.item_type == ItemType.WEAPON or item.item_type == ItemType.ARMOR:408 self.equipped[item.item_type] = item409 item.equipped = True410 return True411 return False412 413class 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 = 0420 self.level = 1421 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_damage427 logger.info(f"Player took {actual_damage} damage. HP: {combat.hp}/{combat.max_hp}")428 return combat.hp <= 0429 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 435class 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 = name442 self.default_hp = hp443 self.default_attack = attack444 self.default_defense = defense445 446class 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_type451 self.state = EntityState.PATROLLING452 self.path: List[Vector2D] = []453 self.vision_range = 5454 self.add_component("combat", CombatStats(455 enemy_type.default_hp,456 enemy_type.default_hp,457 enemy_type.default_attack,458 enemy_type.default_defense459 ))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.CHASING467 else:468 self.state = EntityState.PATROLLING469 470 # Pathfinding logic471 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 path475 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 continue491 492 closed_set.add(current)493 for direction in [Vector2D(0, -1), Vector2D(1, 0), Vector2D(0, 1), Vector2D(-1, 0)]:494 neighbor = current + direction495 if (496 0 <= neighbor.x < dungeon.width and497 0 <= neighbor.y < dungeon.height and498 dungeon.tiles[neighbor.x][neighbor.y] and499 neighbor not in closed_set500 ):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 found506 507# =============================================================================508# GAME STATE MANAGEMENT509# =============================================================================510class GameState(Enum):511 MAIN_MENU = auto()512 PLAYING = auto()513 PAUSED = auto()514 GAME_OVER = auto()515 VICTORY = auto()516 517class GameContext:518 """Holds global game state and services"""519 def __init__(self):520 self.state = GameState.MAIN_MENU521 self.dungeon = Dungeon(80, 40)522 self.player = Player(Vector2D(0, 0))523 self.enemies: List[Enemy] = []524 self.current_room: Optional[Room] = None525 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 = 0530 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.level548 },549 'dungeon': {550 'width': self.dungeon.width,551 'height': self.dungeon.height552 },553 'timestamp': time.time()554 }555 556 # Serialize and sign557 serialized = json.dumps(state).encode()558 signature = hmac.new(SECRET_KEY, serialized, hashlib.sha256).digest()559 encrypted = serialized + signature560 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 signature574 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 state582 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 raise593 594# =============================================================================595# MAIN GAME LOOP596# =============================================================================597class Game:598 """Main game controller with state machine architecture"""599 def __init__(self):600 self.context = GameContext()601 self.running = True602 self.frame_count = 0603 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_start610 611 # Spawn enemies612 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.PLAYING617 self._main_loop()618 619 def _main_loop(self) -> None:620 """Primary game loop with fixed timestep"""621 TARGET_FPS = 60622 TIME_PER_FRAME = 1.0 / TARGET_FPS623 last_time = time.time()624 625 while self.running:626 current_time = time.time()627 elapsed = current_time - last_time628 629 if elapsed >= TIME_PER_FRAME:630 last_time = current_time631 632 # Process input633 self._handle_input()634 635 # Update game state636 self._update(elapsed)637 638 # Render frame639 self._render()640 641 # FPS calculation642 self.frame_count += 1643 if current_time - self.last_fps_update > 1.0:644 self.context.fps = self.frame_count645 self.frame_count = 0646 self.last_fps_update = current_time647 648 def _handle_input(self) -> None:649 """Process player input (simulated here)"""650 if self.context.state != GameState.PLAYING:651 return652 653 # Simulate movement (in real game would use actual input)654 direction = random.choice([655 Vector2D(0, -1), # Up656 Vector2D(1, 0), # Right657 Vector2D(0, 1), # Down658 Vector2D(-1, 0) # Left659 ])660 new_pos = self.context.player.position + direction661 662 # Validate movement663 if (664 0 <= new_pos.x < self.context.dungeon.width and665 0 <= new_pos.y < self.context.dungeon.height and666 self.context.dungeon.tiles[new_pos.x][new_pos.y]667 ):668 self.context.player.position = new_pos669 670 def _update(self, delta_time: float) -> None:671 """Update all game systems"""672 # Update enemies673 for enemy in self.context.enemies[:]:674 enemy.update_ai(self.context.player.position, self.context.dungeon)675 676 # Combat check677 if enemy.position == self.context.player.position:678 enemy.get_component("combat").hp -= self.context.player.get_component("combat").attack679 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 transitions684 if self.context.player.position == self.context.dungeon.exit:685 self.context.state = GameState.VICTORY686 logger.info("Player reached the exit! Victory!")687 self.running = False688 689 if self.context.player.get_component("combat").hp <= 0:690 self.context.state = GameState.GAME_OVER691 logger.info("Player has died. Game over.")692 self.running = False693 694 def _render(self) -> None:695 """Render game state (simulated here)"""696 # In a real implementation, this would draw to a screen697 if self.frame_count % 30 == 0: # Every half second at 60 FPS698 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 POINT705# =============================================================================706def main() -> None:707 """Application entry point with full error handling"""708 game = None709 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 725if __name__ == "__main__":726 main()727 