"""The player adventurer: stats, inventory, equipment, leveling, item use. Equipment is source-of-truth: a weapon/armor sits in its slot and the ``total_*`` accessors fold in its bonuses (plus any active timed effect). Combat code reads those accessors when present so equipped gear and buffs always matter. Quaffing/reading consumes the inventory item and applies its effect. """ from __future__ import annotations import random as _random from dataclasses import dataclass, field from data.constants import ( LEVEL_HP_GAIN, LEVEL_POWER_GAIN, LEVEL_XP, PLAYER_BASE, TILE_FLOOR, ) __all__ = ["Player", "make_player"] @dataclass(slots=True) class Player: x: int y: int hp: int = PLAYER_BASE["hp"] max_hp: int = PLAYER_BASE["max_hp"] power: int = PLAYER_BASE["power"] armor: int = PLAYER_BASE["armor"] accuracy: int = PLAYER_BASE["accuracy"] evasion: int = PLAYER_BASE["evasion"] crit_chance: float = PLAYER_BASE["crit_chance"] speed: int = PLAYER_BASE["speed"] level: int = 1 xp: int = 0 inventory: list = field(default_factory=list) weapon: object = None armor_item: object = None effects: dict = field(default_factory=dict) name: str = "Adventurer" glyph: str = "@" color: tuple = (255, 255, 255) blocks: bool = True is_alive: bool = True # -- derived stats ------------------------------------------------------- def _weapon_stats(self) -> dict: if self.weapon is None: return {} stats = getattr(self.weapon, "stats", None) return stats if isinstance(stats, dict) else {} def _armor_stats(self) -> dict: if self.armor_item is None: return {} stats = getattr(self.armor_item, "stats", None) return stats if isinstance(stats, dict) else {} def total_power(self) -> int: bonus = int(self._weapon_stats().get("power", 0)) if self.effects.get("strength", 0) > 0: bonus += int(self.effects.get("strength_power", 5)) return self.power + bonus def total_armor(self) -> int: return self.armor + int(self._armor_stats().get("armor", 0)) def total_crit_chance(self) -> float: return max(0.0, self.crit_chance + float(self._weapon_stats().get("crit_chance", 0.0))) def total_evasion(self) -> float: return self.evasion + float(self._armor_stats().get("evasion", 0.0)) # -- progression --------------------------------------------------------- def gain_xp(self, amount: int, log: list | None = None) -> None: if amount <= 0: return self.xp += amount if log is not None: log.append(f"You gain {amount} XP.") # LEVEL_XP[level] is the cumulative threshold to advance past `level`. while self.level < len(LEVEL_XP) and self.xp >= LEVEL_XP[self.level]: self.level_up(log) def level_up(self, log: list | None = None) -> None: idx = self.level - 1 hp_gain = LEVEL_HP_GAIN[idx] if 0 <= idx < len(LEVEL_HP_GAIN) else 0 pow_gain = LEVEL_POWER_GAIN[idx] if 0 <= idx < len(LEVEL_POWER_GAIN) else 0 self.max_hp += hp_gain self.power += pow_gain self.level += 1 self.hp = self.max_hp # full heal on level up if log is not None: log.append( f"You reach level {self.level}! (HP +{hp_gain}, Power +{pow_gain})" ) # -- equipment ----------------------------------------------------------- def equip(self, item, log: list | None = None): """Place ``item`` in its slot; return the displaced item (now in inventory). Non-equippable categories are refused (the item is left untouched). """ category = getattr(item, "category", None) previous = None if category == "weapon": previous = self.weapon self.weapon = item elif category == "armor": previous = self.armor_item self.armor_item = item else: if log is not None: log.append(f"You can't equip the {getattr(item, 'name', 'item')}.") return None if previous is not None: self.inventory.append(previous) if log is not None: log.append(f"You unequip {getattr(previous, 'name', 'item')}.") if log is not None: log.append(f"You equip {getattr(item, 'name', 'item')}.") return previous def heal(self, amount: int) -> int: if amount <= 0: return self.hp self.hp = min(self.max_hp, self.hp + amount) return self.hp # -- timed effects ------------------------------------------------------- def tick_effects(self, log: list | None = None) -> None: """Advance one turn: decrement active timers and report expirations.""" for key in ("strength", "invisibility"): remaining = self.effects.get(key, 0) if remaining > 0: remaining -= 1 self.effects[key] = remaining if remaining == 0 and log is not None: if key == "strength": log.append("Your surge of strength fades.") elif key == "invisibility": log.append("You flicker back into view.") # -- potions ------------------------------------------------------------- def quaff(self, potion_idx: int, log: list | None = None): """Drink the potion at ``inventory[potion_idx]`` and consume it.""" if not isinstance(potion_idx, int) or not (0 <= potion_idx < len(self.inventory)): if log is not None: log.append("You have nothing to quaff.") return None item = self.inventory[potion_idx] if getattr(item, "category", None) != "potion": if log is not None: log.append(f"You can't drink the {item.name}.") return None eff = dict(getattr(item, "effect", {}) or {}) kind = eff.get("kind") if kind == "heal": amount = int(eff.get("amount", 0)) before = self.hp self.heal(amount) if log is not None: log.append(f"You drink {item.name} and recover {self.hp - before} HP.") elif kind == "strength": duration = int(eff.get("duration", 20)) self.effects["strength"] = duration self.effects["strength_power"] = int(eff.get("power", 5)) if log is not None: log.append( f"You feel mighty! +{self.effects['strength_power']} power " f"for {duration} turns." ) elif kind == "invisibility": duration = int(eff.get("duration", 15)) self.effects["invisibility"] = duration if log is not None: log.append(f"You drink {item.name} and fade from sight for {duration} turns.") else: if log is not None: log.append(f"The {item.name} has no effect.") self.inventory.pop(potion_idx) return item # -- scrolls ------------------------------------------------------------- def read_scroll(self, scroll_idx: int, ctx=None, log: list | None = None, target=None): """Read the scroll at ``inventory[scroll_idx]`` and consume it. ``ctx`` provides the current floor for teleport/mapping/fireball. It may be a session-like object (``.dungeon`` + ``.current_floor``) or a plain ``GameMap``. ``target`` is an optional ``(x, y)`` fireball epicentre; when omitted the fireball centres on the player. """ if not isinstance(scroll_idx, int) or not (0 <= scroll_idx < len(self.inventory)): if log is not None: log.append("You have nothing to read.") return None item = self.inventory[scroll_idx] if getattr(item, "category", None) != "scroll": if log is not None: log.append(f"You can't read the {item.name}.") return None eff = dict(getattr(item, "effect", {}) or {}) kind = eff.get("kind") floor = self._floor_from(ctx) if kind == "fireball": centre = target if isinstance(target, tuple) and len(target) == 2 else (self.x, self.y) self._cast_fireball(centre, int(eff.get("radius", 3)), int(eff.get("damage", 20)), floor, log) elif kind == "teleport": self._cast_teleport(floor, log) elif kind == "mapping": self._reveal_floor(floor, log) else: if log is not None: log.append(f"The {item.name} crumbles to dust, doing nothing.") self.inventory.pop(scroll_idx) return item # -- scroll helpers ------------------------------------------------------ @staticmethod def _floor_from(ctx): if ctx is None: return None if hasattr(ctx, "dungeon") and hasattr(ctx, "current_floor"): try: return ctx.dungeon[ctx.current_floor] except Exception: return None if hasattr(ctx, "tiles") and hasattr(ctx, "width"): return ctx return None def _cast_fireball(self, centre, radius, damage, floor, log) -> None: if floor is None: if log is not None: log.append("The scroll ignites harmlessly.") return cx, cy = centre hit = [] for e in list(getattr(floor, "entities", [])): if not getattr(e, "is_alive", True) or not hasattr(e, "behavior"): continue if max(abs(e.x - cx), abs(e.y - cy)) <= radius: e.hp -= damage hit.append(e) named = ", ".join(getattr(e, "name", "enemy") for e in hit) or "nothing" if log is not None: log.append(f"A fireball erupts! {named} hit for {damage} damage.") # Resolve kills: award XP, drop corpses, split slimes. from engine.combat import handle_enemy_death for e in hit: if getattr(e, "hp", 1) <= 0: handle_enemy_death(e, self, floor, log) def _cast_teleport(self, floor, log) -> None: if floor is None: if log is not None: log.append("The scroll fizzles.") return occupied = { (e.x, e.y) for e in getattr(floor, "entities", []) if getattr(e, "blocks", False) and e is not self } walkable = [ (x, y) for y in range(floor.height) for x in range(floor.width) if floor.tiles[y][x] == TILE_FLOOR and (x, y) not in occupied ] if not walkable: if log is not None: log.append("The scroll fizzles.") return self.x, self.y = _random.choice(walkable) if log is not None: log.append("You blink across the dungeon!") def _reveal_floor(self, floor, log) -> None: if floor is None or not hasattr(floor, "explored"): if log is not None: log.append("The scroll fizzles.") return for y in range(floor.height): row = floor.explored[y] for x in range(floor.width): row[x] = True if log is not None: log.append("The dungeon layout sears into your mind!") def make_player(x: int, y: int) -> Player: return Player(x=x, y=y)