(Underdepths) Pass 2

This commit is contained in:
AlexKucera committed 2026-08-12 18:44:04 +02:00
1 parent 6c2eef0019
commit b76eb550c9
37 files changed
+5590

No files matched your search

View File
Whitespace-only changes.
+95
View File
@@ -0,0 +1,95 @@
"""Enemy entities.
Stats come from data/enemies.ENEMIES when available (phase 3+); otherwise the
inline fallback roster mirrors plan.md exactly so phase 1 is self-contained.
"""
from dataclasses import dataclass
# Inline fallback roster (mirrors plan.md Enemy Roster).
_FALLBACK_ENEMIES = {
"rat": {
"name": "Rat", "hp": 8, "power": 3, "armor": 0, "speed": 1,
"behavior": "wander", "xp": 5, "glyph": "r", "color": (150, 100, 50),
},
"goblin": {
"name": "Goblin", "hp": 15, "power": 5, "armor": 1, "speed": 1,
"behavior": "chase", "xp": 12, "glyph": "g", "color": (70, 180, 80),
},
"skeleton_archer": {
"name": "Skeleton Archer", "hp": 12, "power": 4, "ranged_power": 6,
"armor": 1, "speed": 1, "behavior": "ranged", "xp": 15,
"glyph": "s", "color": (210, 210, 210),
},
"orc_warrior": {
"name": "Orc Warrior", "hp": 30, "power": 8, "armor": 3, "speed": 1,
"behavior": "flee", "xp": 25, "glyph": "o", "color": (140, 40, 40),
},
"wraith": {
"name": "Wraith", "hp": 20, "power": 10, "armor": 0, "speed": 2,
"behavior": "phase", "xp": 30, "glyph": "w", "color": (160, 90, 210),
},
"green_slime": {
"name": "Green Slime", "hp": 18, "power": 5, "armor": 1, "speed": 1,
"behavior": "split", "xp": 18, "glyph": "j", "color": (100, 220, 100),
},
"ancient_dragon": {
"name": "Ancient Dragon", "hp": 120, "power": 15, "armor": 8, "speed": 1,
"behavior": "chase", "xp": 200, "glyph": "D", "color": (235, 50, 50),
},
"small_slime": {
"name": "Small Slime", "hp": 9, "power": 3, "armor": 1, "speed": 1,
"behavior": "wander", "xp": 6, "glyph": "i", "color": (130, 230, 130),
},
}
try: # phase 3 provides the authoritative roster.
from data.enemies import ENEMIES # type: ignore
except Exception: # pragma: no cover - phase 1 fallback
ENEMIES = _FALLBACK_ENEMIES
@dataclass(slots=True)
class Enemy:
x: int
y: int
name: str
glyph: str
color: tuple
kind: str
hp: int
max_hp: int
power: int
armor: int
speed: int
behavior: str
xp: int
is_alive: bool = True
last_known_pos: object = None
ranged_power: int = 0
can_split: bool = False
blocks: bool = True
def make_enemy(kind: str, x: int, y: int) -> Enemy:
spec = ENEMIES.get(kind) or _FALLBACK_ENEMIES.get(kind)
if spec is None:
raise KeyError(f"unknown enemy kind: {kind!r}")
behavior = spec["behavior"]
return Enemy(
x=x,
y=y,
name=spec.get("name", kind.replace("_", " ").title()),
glyph=spec.get("glyph", kind[0]),
color=tuple(spec.get("color", (200, 200, 200))),
kind=kind,
hp=spec["hp"],
max_hp=spec["hp"],
power=spec["power"],
armor=int(spec.get("armor", 0)),
speed=int(spec.get("speed", 1)),
behavior=behavior,
xp=spec["xp"],
ranged_power=int(spec.get("ranged_power", 0)),
can_split=bool(spec.get("can_split", behavior == "split")),
)
+35
View File
@@ -0,0 +1,35 @@
"""Base entities: geometric Rect and the generic Entity."""
from dataclasses import dataclass
@dataclass(slots=True)
class Rect:
x: int
y: int
w: int
h: int
@property
def center(self) -> tuple[int, int]:
return (self.x + self.w // 2, self.y + self.h // 2)
def intersects(self, other: "Rect") -> bool:
# True when the two rectangles' interiors overlap (strict inequalities).
return (
self.x < other.x + other.w
and self.x + self.w > other.x
and self.y < other.y + other.h
and self.y + self.h > other.y
)
@dataclass(slots=True)
class Entity:
x: int
y: int
name: str
glyph: str
color: tuple
blocks: bool = True
is_alive: bool = True
+71
View File
@@ -0,0 +1,71 @@
"""Item entities: weapons, armor, potions, scrolls.
An ``Item`` is both a world object (it sits on a floor tile until picked up)
and an inventory object (it carries the stats/effect the player uses). The
``category`` field is the single dispatch key: equipment slots accept only
"weapon"/"armor", quaffing accepts only "potion", reading accepts only "scroll".
"""
from __future__ import annotations
from dataclasses import dataclass, field
from data.constants import COLORS
from data.items import ITEMS
__all__ = ["Item", "make_item"]
_VALID_CATEGORIES = ("weapon", "armor", "potion", "scroll")
# Roguelike-conventional glyphs/colors per category, used when an ITEMS entry
# does not override them.
_CATEGORY_GLYPHS = {
"weapon": "/",
"armor": "[",
"potion": "!",
"scroll": "?",
}
_CATEGORY_COLORS = {
"weapon": COLORS["weapon"],
"armor": COLORS["armor_item"],
"potion": COLORS["potion"],
"scroll": COLORS["scroll"],
}
@dataclass(slots=True)
class Item:
name: str
category: str
x: int
y: int
stats: dict = field(default_factory=dict)
effect: dict = field(default_factory=dict)
glyph: str = "?"
color: tuple = (200, 200, 200)
blocks: bool = False
is_alive: bool = True
def make_item(name: str, x: int, y: int) -> Item:
"""Construct an ``Item`` from the ``ITEMS`` catalog.
``stats``/``effect`` are copied so per-instance mutation (e.g. a cooldown
scribbled onto an equipped item) never leaks back into the catalog.
"""
spec = ITEMS.get(name)
if spec is None:
raise KeyError(f"unknown item: {name!r}")
category = spec["category"]
if category not in _VALID_CATEGORIES:
raise ValueError(f"{name!r} has invalid category {category!r}")
return Item(
name=name,
category=category,
x=x,
y=y,
stats=dict(spec.get("stats", {})),
effect=dict(spec.get("effect", {})),
glyph=spec.get("glyph", _CATEGORY_GLYPHS[category]),
color=tuple(spec.get("color", _CATEGORY_COLORS[category])),
)
+301
View File
@@ -0,0 +1,301 @@
"""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)