(Underdepths) Pass 7
This commit is contained in:
1 parent
13512b0476
commit
952ff4b734
39 files changed
+7988
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,436 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import random
|
||||
|
||||
from ai.behaviors import acts_this_turn, is_fleeing, spawn_splits, take_turn
|
||||
from data.constants import (
|
||||
BOW_HIT_PENALTY_PER_TILE,
|
||||
DRAGON_KEY,
|
||||
MENU_LABEL_CONTINUE,
|
||||
MENU_LABEL_HOW_TO_PLAY,
|
||||
MENU_LABEL_NEW_GAME,
|
||||
MENU_LABEL_QUIT,
|
||||
)
|
||||
from engine.combat import attack
|
||||
from engine.game_state import (
|
||||
OVERLAY_EQUIPMENT,
|
||||
OVERLAY_HELP,
|
||||
OVERLAY_INVENTORY,
|
||||
OVERLAY_QUAFF,
|
||||
OVERLAY_READ,
|
||||
STATE_DEAD,
|
||||
STATE_PLAYING,
|
||||
STATE_SAVED,
|
||||
STATE_VICTORY,
|
||||
GameSession,
|
||||
)
|
||||
from engine.map_gen import GameMap, Point
|
||||
from engine.serializers import delete_save, save_session
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item, TimedEffect, apply_scroll
|
||||
from entities.player import Player
|
||||
|
||||
_rng = random.Random()
|
||||
|
||||
VICTORY_MESSAGE = "You slew the Ancient Dragon! You conquered Underdepths."
|
||||
|
||||
|
||||
def _manhattan(a: Point, b: Point) -> int:
|
||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||
|
||||
|
||||
def _enemies(game_map: GameMap) -> list[Enemy]:
|
||||
return [entity for entity in game_map.entities if isinstance(entity, Enemy)]
|
||||
|
||||
|
||||
def _enemy_at(game_map: GameMap, position: Point) -> Enemy | None:
|
||||
return next(
|
||||
(enemy for enemy in _enemies(game_map) if enemy.alive and enemy.position == position),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _item_at(game_map: GameMap, position: Point) -> Item | None:
|
||||
return next(
|
||||
(
|
||||
entity
|
||||
for entity in game_map.entities
|
||||
if isinstance(entity, Item) and entity.position == position
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _owns(player: Player, item: Item) -> bool:
|
||||
# identity, not __eq__: stacked consumables compare equal by value
|
||||
return any(candidate is item for candidate in player.inventory)
|
||||
|
||||
|
||||
def _line_clear(game_map: GameMap, start: Point, end: Point) -> bool:
|
||||
"""Bresenham line start -> end; a wall on an interior tile blocks the shot."""
|
||||
x, y = start
|
||||
ex, ey = end
|
||||
dx, dy = abs(ex - x), -abs(ey - y)
|
||||
step_x = 1 if x < ex else -1
|
||||
step_y = 1 if y < ey else -1
|
||||
error = dx + dy
|
||||
while (x, y) != end:
|
||||
doubled = 2 * error
|
||||
if doubled >= dy:
|
||||
error += dy
|
||||
x += step_x
|
||||
if doubled <= dx:
|
||||
error += dx
|
||||
y += step_y
|
||||
if (x, y) != end and not game_map.is_walkable(x, y):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _player_died(session: GameSession) -> None:
|
||||
session.state = STATE_DEAD
|
||||
session.log_message(
|
||||
f"You died on floor {session.current_floor + 1}. "
|
||||
f"You reached level {session.player.level}."
|
||||
)
|
||||
|
||||
|
||||
def _resolve_deaths(session: GameSession) -> None:
|
||||
game_map = session.current_map
|
||||
for enemy in [enemy for enemy in _enemies(game_map) if not enemy.alive]:
|
||||
game_map.entities.remove(enemy)
|
||||
spawn_splits(enemy, game_map, _rng, session.log, avoid=session.player.position)
|
||||
if enemy.key == DRAGON_KEY:
|
||||
session.state = STATE_VICTORY
|
||||
session.log_message(VICTORY_MESSAGE)
|
||||
|
||||
|
||||
def end_turn(session: GameSession) -> None:
|
||||
"""Finish the current turn: deaths, enemy actions, timers, FOV, end states."""
|
||||
session.turn += 1
|
||||
player = session.player
|
||||
game_map = session.current_map
|
||||
# snapshot before death resolution so freshly split copies wait a full turn
|
||||
enemies = [enemy for enemy in _enemies(game_map) if enemy.alive]
|
||||
_resolve_deaths(session)
|
||||
if session.state == STATE_PLAYING and player.alive:
|
||||
session.refresh_fov()
|
||||
for enemy in enemies:
|
||||
if not player.alive:
|
||||
break
|
||||
if enemy.alive and acts_this_turn(enemy, session.turn):
|
||||
take_turn(enemy, game_map, player, _rng, session.log, session.turn)
|
||||
if player.alive:
|
||||
player.tick_effects(session.log)
|
||||
else:
|
||||
_player_died(session)
|
||||
session.refresh_fov()
|
||||
|
||||
|
||||
def move(session: GameSession, dx: int, dy: int) -> bool:
|
||||
"""Walk one tile, or melee an enemy standing there. True when a turn passed."""
|
||||
if session.state != STATE_PLAYING:
|
||||
return False
|
||||
target = (session.player.x + dx, session.player.y + dy)
|
||||
enemy = _enemy_at(session.current_map, target)
|
||||
if enemy is not None:
|
||||
attack(session.player, enemy, session.log)
|
||||
end_turn(session)
|
||||
return True
|
||||
if session.current_map.is_walkable(*target):
|
||||
session.player.x, session.player.y = target
|
||||
end_turn(session)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def pickup(session: GameSession) -> bool:
|
||||
if session.state != STATE_PLAYING:
|
||||
return False
|
||||
item = _item_at(session.current_map, session.player.position)
|
||||
if item is None:
|
||||
session.log_message("There is nothing here to pick up.")
|
||||
return False
|
||||
if not session.player.add_item(item):
|
||||
session.log_message("Your pack is full.")
|
||||
return False
|
||||
session.current_map.entities.remove(item)
|
||||
session.log_message(f"You pick up the {item.name}.")
|
||||
end_turn(session)
|
||||
return True
|
||||
|
||||
|
||||
def equip(session: GameSession, item: Item) -> bool:
|
||||
"""Equip from inventory. A menu action, so it spends no turn."""
|
||||
if not _owns(session.player, item) or not item.is_equippable:
|
||||
return False
|
||||
session.player.equip(item)
|
||||
session.log_message(f"You equip the {item.name}.")
|
||||
return True
|
||||
|
||||
|
||||
def quaff(session: GameSession, item: Item) -> bool:
|
||||
if session.state != STATE_PLAYING or not _owns(session.player, item):
|
||||
return False
|
||||
if item.category != "potion":
|
||||
return False
|
||||
player = session.player
|
||||
if item.effect == "heal":
|
||||
healed = player.heal(item.heal_amount)
|
||||
session.log_message(
|
||||
f"You quaff the {item.name}. You feel better! (+{healed} HP)"
|
||||
)
|
||||
elif item.effect == "strength":
|
||||
player.effects.append(TimedEffect("strength", item.effect_power, item.effect_turns))
|
||||
session.log_message(
|
||||
f"You quaff the {item.name}. Power surges through you! "
|
||||
f"(+{item.effect_power} for {item.effect_turns} turns)"
|
||||
)
|
||||
elif item.effect == "invisible":
|
||||
player.effects.append(TimedEffect("invisible", 0, item.effect_turns))
|
||||
session.log_message(f"You quaff the {item.name}. You fade from sight!")
|
||||
else:
|
||||
return False
|
||||
player.consume(item)
|
||||
end_turn(session)
|
||||
return True
|
||||
|
||||
|
||||
def read_scroll(session: GameSession, item: Item) -> bool:
|
||||
if session.state != STATE_PLAYING or not _owns(session.player, item):
|
||||
return False
|
||||
if item.category != "scroll":
|
||||
return False
|
||||
session.log_message(f"You read the {item.name}.")
|
||||
apply_scroll(item, session.player, session.current_map, _rng, session.log)
|
||||
session.player.consume(item)
|
||||
end_turn(session)
|
||||
return True
|
||||
|
||||
|
||||
def _bow_target(session: GameSession) -> Enemy | None:
|
||||
"""Nearest visible enemy in range, fleeing enemies preferred over chasers."""
|
||||
player = session.player
|
||||
game_map = session.current_map
|
||||
best: Enemy | None = None
|
||||
best_key: tuple[int, int] | None = None
|
||||
for enemy in _enemies(game_map):
|
||||
if not enemy.alive:
|
||||
continue
|
||||
distance = _manhattan(player.position, enemy.position)
|
||||
if not 1 <= distance <= player.bow_range:
|
||||
continue
|
||||
if not game_map.visible[enemy.y][enemy.x]:
|
||||
continue
|
||||
if not _line_clear(game_map, player.position, enemy.position):
|
||||
continue
|
||||
key = (0 if is_fleeing(enemy) else 1, distance)
|
||||
if best_key is None or key < best_key:
|
||||
best, best_key = enemy, key
|
||||
return best
|
||||
|
||||
|
||||
def fire_bow(session: GameSession) -> bool:
|
||||
"""Fire the equipped bow. True when a shot was loosed (a turn spent)."""
|
||||
if session.state != STATE_PLAYING:
|
||||
return False
|
||||
if not session.player.has_bow:
|
||||
session.log_message("You have no bow equipped.")
|
||||
return False
|
||||
target = _bow_target(session)
|
||||
if target is None:
|
||||
session.log_message("No visible enemy within bow range.")
|
||||
return False
|
||||
distance = _manhattan(session.player.position, target.position)
|
||||
attack(
|
||||
session.player,
|
||||
target,
|
||||
session.log,
|
||||
hit_bonus=-BOW_HIT_PENALTY_PER_TILE * (distance - 1),
|
||||
)
|
||||
end_turn(session)
|
||||
return True
|
||||
|
||||
|
||||
def descend(session: GameSession) -> bool:
|
||||
"""f: take the stairs underfoot; a safe no-op anywhere else."""
|
||||
if session.state != STATE_PLAYING:
|
||||
return False
|
||||
game_map = session.current_map
|
||||
if game_map.stairs_down is None or session.player.position != game_map.stairs_down:
|
||||
session.log_message("There are no stairs leading down here.")
|
||||
return False
|
||||
session.descend()
|
||||
return True
|
||||
|
||||
|
||||
def _potions(player: Player) -> list[Item]:
|
||||
return [item for item in player.inventory if item.category == "potion"]
|
||||
|
||||
|
||||
def _scrolls(player: Player) -> list[Item]:
|
||||
return [item for item in player.inventory if item.category == "scroll"]
|
||||
|
||||
|
||||
def overlay_entries(session: GameSession) -> list[tuple[str, str]]:
|
||||
"""Rows of the open item menu: (name, detail) per selectable entry."""
|
||||
player = session.player
|
||||
if session.overlay == OVERLAY_INVENTORY:
|
||||
return [(item.name, item.describe()) for item in player.inventory]
|
||||
if session.overlay == OVERLAY_QUAFF:
|
||||
return [(item.name, item.describe()) for item in _potions(player)]
|
||||
if session.overlay == OVERLAY_READ:
|
||||
return [(item.name, item.describe()) for item in _scrolls(player)]
|
||||
if session.overlay == OVERLAY_EQUIPMENT:
|
||||
entries: list[tuple[str, str]] = []
|
||||
for label, equipped in (
|
||||
("Weapon", player.equipped_weapon),
|
||||
("Armor", player.equipped_armor),
|
||||
("Boots", player.equipped_boots),
|
||||
):
|
||||
if equipped is None:
|
||||
entries.append((f"{label}: none", "-"))
|
||||
else:
|
||||
entries.append((f"{label}: {equipped.name}", equipped.describe()))
|
||||
return entries
|
||||
return []
|
||||
|
||||
|
||||
def open_overlay(session: GameSession, name: str) -> bool:
|
||||
"""Open an in-play menu; opening the same one again closes it."""
|
||||
if session.state != STATE_PLAYING:
|
||||
return False
|
||||
if session.overlay == name:
|
||||
session.overlay = None
|
||||
session.overlay_index = 0
|
||||
return True
|
||||
session.overlay = name
|
||||
session.overlay_index = 0
|
||||
return True
|
||||
|
||||
|
||||
def close_overlay(session: GameSession) -> bool:
|
||||
if session.overlay is None:
|
||||
return False
|
||||
session.overlay = None
|
||||
session.overlay_index = 0
|
||||
return True
|
||||
|
||||
|
||||
def cycle_selection(session: GameSession, delta: int) -> bool:
|
||||
if session.overlay is None:
|
||||
return False
|
||||
count = len(overlay_entries(session))
|
||||
if count == 0:
|
||||
return False
|
||||
session.overlay_index = (session.overlay_index + delta) % count
|
||||
return True
|
||||
|
||||
|
||||
def _quaff_and_close(session: GameSession, item: Item) -> bool:
|
||||
if not quaff(session, item):
|
||||
return False
|
||||
close_overlay(session)
|
||||
return True
|
||||
|
||||
|
||||
def _read_and_close(session: GameSession, item: Item) -> bool:
|
||||
if not read_scroll(session, item):
|
||||
return False
|
||||
close_overlay(session)
|
||||
return True
|
||||
|
||||
|
||||
def confirm_selection(session: GameSession) -> bool:
|
||||
"""Activate the highlighted overlay row."""
|
||||
if session.state != STATE_PLAYING or session.overlay is None:
|
||||
return False
|
||||
overlay = session.overlay
|
||||
index = session.overlay_index
|
||||
player = session.player
|
||||
if overlay == OVERLAY_HELP:
|
||||
return close_overlay(session)
|
||||
if overlay == OVERLAY_EQUIPMENT:
|
||||
if not 0 <= index < 3:
|
||||
return False
|
||||
slot = ("weapon", "armor", "boots")[index]
|
||||
if getattr(player, f"equipped_{slot}") is None:
|
||||
session.log_message(f"Nothing is equipped in the {slot} slot.")
|
||||
return False
|
||||
removed = player.unequip(slot)
|
||||
if removed is None:
|
||||
session.log_message("Your pack is full; you keep it equipped.")
|
||||
return False
|
||||
session.log_message(f"You remove the {removed.name}.")
|
||||
return True
|
||||
if overlay == OVERLAY_INVENTORY:
|
||||
if not 0 <= index < len(player.inventory):
|
||||
return False
|
||||
item = player.inventory[index]
|
||||
if item.is_equippable:
|
||||
return equip(session, item)
|
||||
if item.category == "potion":
|
||||
return _quaff_and_close(session, item)
|
||||
if item.category == "scroll":
|
||||
return _read_and_close(session, item)
|
||||
return False
|
||||
if overlay == OVERLAY_QUAFF:
|
||||
potions = _potions(player)
|
||||
if not 0 <= index < len(potions):
|
||||
return False
|
||||
return _quaff_and_close(session, potions[index])
|
||||
if overlay == OVERLAY_READ:
|
||||
scrolls = _scrolls(player)
|
||||
if not 0 <= index < len(scrolls):
|
||||
return False
|
||||
return _read_and_close(session, scrolls[index])
|
||||
return False
|
||||
|
||||
|
||||
def select_entry(session: GameSession, index: int) -> bool:
|
||||
"""Pick an overlay row by its displayed selection letter."""
|
||||
if not 0 <= index < len(overlay_entries(session)):
|
||||
return False
|
||||
session.overlay_index = index
|
||||
return confirm_selection(session)
|
||||
|
||||
|
||||
def main_menu_entries(session: GameSession) -> list[str]:
|
||||
entries = [MENU_LABEL_NEW_GAME]
|
||||
if session.save_available:
|
||||
entries.append(MENU_LABEL_CONTINUE)
|
||||
entries.extend((MENU_LABEL_HOW_TO_PLAY, MENU_LABEL_QUIT))
|
||||
return entries
|
||||
|
||||
|
||||
def move_menu_selection(session: GameSession, delta: int) -> bool:
|
||||
count = len(main_menu_entries(session))
|
||||
if count == 0:
|
||||
return False
|
||||
session.menu_index = (session.menu_index + delta) % count
|
||||
return True
|
||||
|
||||
|
||||
def save_and_quit(session: GameSession, save_path: Path | str) -> bool:
|
||||
"""S: persist the run exactly as it stands, then head for the main menu."""
|
||||
if session.state != STATE_PLAYING:
|
||||
return False
|
||||
close_overlay(session)
|
||||
session.log_message("You save your progress.")
|
||||
if not save_session(session, save_path):
|
||||
session.log_message("The save could not be written; the depths keep you.")
|
||||
return False
|
||||
session.state = STATE_SAVED
|
||||
session.save_available = True
|
||||
return True
|
||||
|
||||
|
||||
def enforce_permadeath(session: GameSession, save_path: Path | str) -> bool:
|
||||
"""A run that ended in death or victory leaves no save behind."""
|
||||
if session.state not in (STATE_DEAD, STATE_VICTORY):
|
||||
return False
|
||||
if not delete_save(save_path):
|
||||
return False
|
||||
session.save_available = False
|
||||
return True
|
||||
@@ -0,0 +1,155 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
import math
|
||||
from typing import Final
|
||||
|
||||
import pygame
|
||||
|
||||
from data.constants import AUDIO_SAMPLE_RATE, AUDIO_TONES
|
||||
|
||||
_SIZE_CODES: Final = {8: ("b", "B"), 16: ("h", "H"), 32: ("i", "I")}
|
||||
|
||||
|
||||
def sound_for_message(message: str) -> str | None:
|
||||
"""Map one log line to an effect key; None when the line stays silent."""
|
||||
if message.startswith(("You hit", "Critical hit!")):
|
||||
return "hit"
|
||||
if "misses you" in message or message.startswith("You miss"):
|
||||
return "miss"
|
||||
if "hits you" in message or "scorched" in message:
|
||||
return "hurt"
|
||||
if message.startswith(("You pick up", "You quaff", "You read", "You equip")):
|
||||
return "pickup"
|
||||
if message.startswith("You descend to floor"):
|
||||
return "stairs"
|
||||
if message.startswith("You reach level"):
|
||||
return "levelup"
|
||||
if message.startswith("You died"):
|
||||
return "death"
|
||||
if message.startswith("You slew the Ancient Dragon"):
|
||||
return "victory"
|
||||
return None
|
||||
|
||||
|
||||
class Audio:
|
||||
"""Tiny in-memory tone synth over pygame.mixer.
|
||||
|
||||
Every failure mode — no device, odd mixer format, tone build error —
|
||||
degrades to silence. Audio is feedback only and never touches game state.
|
||||
"""
|
||||
|
||||
def __init__(self, sample_rate: int = AUDIO_SAMPLE_RATE) -> None:
|
||||
self.sample_rate = sample_rate
|
||||
self.muted = False
|
||||
self.available = False
|
||||
self._sounds: dict[str, pygame.mixer.Sound] = {}
|
||||
|
||||
def init(self) -> bool:
|
||||
try:
|
||||
if pygame.mixer.get_init() is None:
|
||||
pygame.mixer.init(frequency=self.sample_rate, size=-16, channels=1)
|
||||
spec = pygame.mixer.get_init()
|
||||
sounds: dict[str, pygame.mixer.Sound] = {}
|
||||
if spec is not None:
|
||||
for name, tone in AUDIO_TONES.items():
|
||||
sound = self._build(spec, *tone)
|
||||
if sound is not None:
|
||||
sounds[name] = sound
|
||||
self._sounds = sounds
|
||||
self.available = bool(sounds)
|
||||
except Exception:
|
||||
# boundary: any mixer failure means silent play, never a crash
|
||||
self.available = False
|
||||
self._sounds = {}
|
||||
return self.available
|
||||
|
||||
def _build(
|
||||
self,
|
||||
spec: tuple[int, int, int],
|
||||
frequency: int,
|
||||
duration: float,
|
||||
volume: float,
|
||||
) -> pygame.mixer.Sound | None:
|
||||
rate, size, channels = spec
|
||||
codes = _SIZE_CODES.get(abs(size))
|
||||
if codes is None or rate <= 0 or channels <= 0:
|
||||
return None
|
||||
code = codes[0] if size < 0 else codes[1]
|
||||
peak = (1 << (abs(size) - 1)) - 1
|
||||
bias = 0 if size < 0 else peak + 1
|
||||
total = int(rate * duration)
|
||||
if total <= 0:
|
||||
return None
|
||||
fade = max(1, total // 20)
|
||||
samples = array.array(code)
|
||||
for index in range(total):
|
||||
envelope = min(1.0, index / fade, (total - 1 - index) / fade)
|
||||
value = int(
|
||||
bias
|
||||
+ volume
|
||||
* peak
|
||||
* envelope
|
||||
* math.sin(2 * math.pi * frequency * index / rate)
|
||||
)
|
||||
for _ in range(channels):
|
||||
samples.append(value)
|
||||
try:
|
||||
return pygame.mixer.Sound(buffer=samples.tobytes())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def play(self, effect: str) -> bool:
|
||||
if self.muted or not self.available:
|
||||
return False
|
||||
sound = self._sounds.get(effect)
|
||||
if sound is None:
|
||||
return False
|
||||
try:
|
||||
sound.play()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def toggle_mute(self) -> bool:
|
||||
self.muted = not self.muted
|
||||
return self.muted
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run from the repo root: python -m engine.audio
|
||||
assert sound_for_message("You hit the Goblin for 8 damage!") == "hit"
|
||||
assert sound_for_message("Critical hit! You hit the Orc for 24 damage!") == "hit"
|
||||
assert sound_for_message("You miss the Goblin") == "miss"
|
||||
assert sound_for_message("Goblin misses you") == "miss"
|
||||
assert sound_for_message("Goblin hits you for 5 damage!") == "hurt"
|
||||
assert sound_for_message("You are scorched for 15 damage!") == "hurt"
|
||||
assert sound_for_message("You pick up the Healing Potion.") == "pickup"
|
||||
assert sound_for_message("You quaff the Strength Potion.") == "pickup"
|
||||
assert sound_for_message("You equip the Hunter's Bow.") == "pickup"
|
||||
assert sound_for_message("You descend to floor 3.") == "stairs"
|
||||
assert sound_for_message("You reach level 2! (HP +10, Power +1)") == "levelup"
|
||||
assert sound_for_message("You died on floor 4. You reached level 3.") == "death"
|
||||
assert (
|
||||
sound_for_message("You slew the Ancient Dragon! You conquered Underdepths.")
|
||||
== "victory"
|
||||
)
|
||||
assert sound_for_message("The Green Slime splits into 2 smaller slimes!") is None
|
||||
|
||||
real_init = pygame.mixer.init
|
||||
|
||||
def refuse(*args: object, **kwargs: object) -> None:
|
||||
raise pygame.error("forced failure")
|
||||
|
||||
pygame.mixer.init = refuse # type: ignore[assignment]
|
||||
broken = Audio()
|
||||
assert broken.init() is False and broken.available is False
|
||||
assert broken.play("hit") is False # silent, not fatal
|
||||
assert broken.toggle_mute() is True
|
||||
pygame.mixer.init = real_init # type: ignore[assignment]
|
||||
|
||||
live = Audio()
|
||||
started = live.init()
|
||||
assert live.available == started
|
||||
live.play("hit") # must be safe on audio and audio-less machines alike
|
||||
print(f"audio self-check: PASS (mixer available: {started})")
|
||||
@@ -0,0 +1,260 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
import time
|
||||
|
||||
from data.constants import RUN_INITIAL_DELAY_MS, RUN_REPEAT_MS
|
||||
from engine.actions import move
|
||||
from engine.game_state import STATE_PLAYING, GameSession
|
||||
|
||||
Direction = tuple[int, int]
|
||||
TimeSource = Callable[[], float]
|
||||
|
||||
|
||||
def _monotonic_ms() -> float:
|
||||
return time.monotonic() * 1000.0
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class HeldKeyClock:
|
||||
"""Held-direction running for Shoes of Hermes, with no OS key repeat.
|
||||
|
||||
A fresh press takes one immediate step (the caller applies it through the
|
||||
ordinary move path). Repeats then wait initial_delay_ms and fire once per
|
||||
repeat_ms — each a complete turn — until release or stop().
|
||||
"""
|
||||
|
||||
initial_delay_ms: int = RUN_INITIAL_DELAY_MS
|
||||
repeat_ms: int = RUN_REPEAT_MS
|
||||
held: Direction | None = None
|
||||
running: bool = False
|
||||
pressed_at: float = 0.0
|
||||
repeats: int = 0
|
||||
now_ms: TimeSource = _monotonic_ms
|
||||
|
||||
def update(
|
||||
self,
|
||||
held_direction: Direction | None,
|
||||
can_run: bool,
|
||||
now: float | None = None,
|
||||
) -> Direction | None:
|
||||
"""Feed what is physically held; return a direction when a step is due."""
|
||||
current = self.now_ms() if now is None else now
|
||||
if held_direction != self.held:
|
||||
self.held = held_direction
|
||||
self.running = held_direction is not None
|
||||
self.pressed_at = current
|
||||
self.repeats = 0
|
||||
return held_direction
|
||||
if not self.running or held_direction is None or not can_run:
|
||||
return None
|
||||
due = self.pressed_at + self.initial_delay_ms + self.repeats * self.repeat_ms
|
||||
if current < due:
|
||||
return None
|
||||
self.repeats += 1
|
||||
return held_direction
|
||||
|
||||
def stop(self) -> None:
|
||||
"""End the run but keep tracking the held key; a re-press restarts."""
|
||||
self.running = False
|
||||
|
||||
|
||||
def apply_held_direction(
|
||||
session: GameSession,
|
||||
clock: HeldKeyClock,
|
||||
held_direction: Direction | None,
|
||||
now: float | None = None,
|
||||
) -> bool:
|
||||
"""One frame of held-direction input through the real move path.
|
||||
|
||||
Stops immediately (and stays stopped until a fresh press) on release, a
|
||||
blocked step, an open menu, a floor change, death, or victory.
|
||||
"""
|
||||
if session.state != STATE_PLAYING or session.overlay is not None:
|
||||
clock.update(None, False, now)
|
||||
return False
|
||||
direction = clock.update(held_direction, session.player.can_run, now)
|
||||
if direction is None:
|
||||
return False
|
||||
floor = session.current_floor
|
||||
if not move(session, *direction):
|
||||
clock.stop()
|
||||
return False
|
||||
if session.current_floor != floor or session.state != STATE_PLAYING:
|
||||
clock.stop()
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run from the repo root: python -m engine.clock
|
||||
import random
|
||||
from array import array
|
||||
from data.constants import (
|
||||
DRAGON_KEY,
|
||||
RUN_INITIAL_DELAY_MS,
|
||||
RUN_REPEAT_MS,
|
||||
TILE_WALL,
|
||||
)
|
||||
from engine.actions import close_overlay, open_overlay
|
||||
from engine.game_state import STATE_DEAD, STATE_VICTORY, GameSession
|
||||
from engine.map_gen import GameMap
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from entities.player import Player
|
||||
|
||||
assert RUN_INITIAL_DELAY_MS == 180 and RUN_REPEAT_MS == 75
|
||||
|
||||
def open_map(width: int, height: int, spawn: tuple[int, int]) -> GameMap:
|
||||
return GameMap(
|
||||
width=width,
|
||||
height=height,
|
||||
tiles=[array("b", [1] * width) for _ in range(height)],
|
||||
rooms=[],
|
||||
junctions=[],
|
||||
corridors=[],
|
||||
explored=[array("b", [0] * width) for _ in range(height)],
|
||||
visible=[array("b", [0] * width) for _ in range(height)],
|
||||
entities=[],
|
||||
stairs_down=None,
|
||||
floor_index=0,
|
||||
spawn=spawn,
|
||||
)
|
||||
|
||||
def session_on(game_map: GameMap) -> GameSession:
|
||||
session = GameSession(
|
||||
player=Player(x=game_map.spawn[0], y=game_map.spawn[1]),
|
||||
dungeon=[game_map],
|
||||
)
|
||||
session.refresh_fov()
|
||||
return session
|
||||
|
||||
def wear_shoes(session: GameSession) -> None:
|
||||
shoes = Item(key="shoes_of_hermes", category="boots", enables_running=True)
|
||||
session.player.add_item(shoes)
|
||||
session.player.equip(shoes)
|
||||
assert session.player.can_run
|
||||
|
||||
# cadence with Shoes: immediate step, silence before 180ms, then 75ms repeats
|
||||
clock = HeldKeyClock()
|
||||
assert clock.update((1, 0), True, now=0) == (1, 0)
|
||||
assert clock.update((1, 0), True, now=179) is None
|
||||
assert clock.update((1, 0), True, now=180) == (1, 0)
|
||||
assert clock.update((1, 0), True, now=254) is None
|
||||
assert clock.update((1, 0), True, now=255) == (1, 0)
|
||||
assert clock.update((1, 0), True, now=330) == (1, 0)
|
||||
|
||||
# release stops immediately; a re-press is immediate again
|
||||
assert clock.update(None, True, now=340) is None
|
||||
assert clock.update((1, 0), True, now=1000) == (1, 0)
|
||||
assert clock.update((1, 0), True, now=1179) is None
|
||||
assert clock.update((1, 0), True, now=1180) == (1, 0)
|
||||
|
||||
# without Shoes the hold moves exactly once, however long it lasts
|
||||
plain = HeldKeyClock()
|
||||
assert plain.update((0, 1), False, now=0) == (0, 1)
|
||||
assert all(
|
||||
plain.update((0, 1), False, now=t) is None for t in (16, 60, 181, 255, 900)
|
||||
)
|
||||
|
||||
# stop() silences the hold until a re-press
|
||||
halted = HeldKeyClock()
|
||||
halted.update((1, 0), True, now=0)
|
||||
halted.stop()
|
||||
assert all(
|
||||
halted.update((1, 0), True, now=t) is None for t in range(100, 400, 25)
|
||||
)
|
||||
assert halted.update(None, True, now=500) is None
|
||||
assert halted.update((1, 0), True, now=501) == (1, 0)
|
||||
|
||||
# glue: a blocked immediate step spends no turn and ends the run
|
||||
game_map = open_map(9, 9, (4, 4))
|
||||
game_map.tiles[4][5] = TILE_WALL
|
||||
session = session_on(game_map)
|
||||
clock = HeldKeyClock()
|
||||
assert apply_held_direction(session, clock, (1, 0), now=0) is False
|
||||
assert all(
|
||||
apply_held_direction(session, clock, (1, 0), now=t) is False
|
||||
for t in (180, 255, 400)
|
||||
)
|
||||
assert session.turn == 0 and session.player.position == (4, 4)
|
||||
|
||||
# glue: real running walks the corridor, one complete turn per step
|
||||
session = session_on(open_map(9, 5, (1, 2)))
|
||||
wear_shoes(session)
|
||||
clock = HeldKeyClock()
|
||||
assert apply_held_direction(session, clock, (1, 0), now=0) is True
|
||||
assert session.player.x == 2 and session.turn == 1
|
||||
assert apply_held_direction(session, clock, (1, 0), now=179) is False
|
||||
assert apply_held_direction(session, clock, (1, 0), now=180) is True
|
||||
assert session.player.x == 3 and session.turn == 2
|
||||
assert apply_held_direction(session, clock, (1, 0), now=255) is True
|
||||
assert session.player.x == 4 and session.turn == 3
|
||||
assert apply_held_direction(session, clock, None, now=260) is False # release
|
||||
assert apply_held_direction(session, clock, (1, 0), now=400) is True # re-press
|
||||
assert session.player.x == 5 and session.turn == 4
|
||||
|
||||
# glue: opening a menu freezes the run even while the key stays down
|
||||
open_overlay(session, "inventory")
|
||||
assert apply_held_direction(session, clock, (1, 0), now=580) is False
|
||||
assert session.player.x == 5
|
||||
close_overlay(session)
|
||||
assert apply_held_direction(session, clock, (1, 0), now=600) is True
|
||||
assert session.player.x == 6
|
||||
|
||||
# glue: death during a held run stops it for good
|
||||
random.seed(1)
|
||||
session = session_on(open_map(9, 5, (1, 2)))
|
||||
wear_shoes(session)
|
||||
session.player.hp = 1
|
||||
murderer = Enemy(
|
||||
x=2, y=2, name="Goblin", hp=100, max_hp=100, power=50,
|
||||
accuracy=100, crit_chance=0.0, behavior="chase",
|
||||
)
|
||||
session.current_map.entities.append(murderer)
|
||||
clock = HeldKeyClock()
|
||||
assert apply_held_direction(session, clock, (1, 0), now=0) is False # the run's one step was fatal
|
||||
assert session.state == STATE_DEAD and not session.player.alive
|
||||
assert clock.running is False
|
||||
assert apply_held_direction(session, clock, (1, 0), now=200) is False
|
||||
assert session.player.x == 1
|
||||
|
||||
# glue: victory during a held run stops it for good
|
||||
random.seed(1)
|
||||
session = session_on(open_map(9, 5, (1, 2)))
|
||||
hammer = Item(key="war_hammer", category="weapon", power=10)
|
||||
session.player.add_item(hammer)
|
||||
session.player.equip(hammer)
|
||||
dragon = Enemy(
|
||||
x=2, y=2, name="Ancient Dragon", key=DRAGON_KEY, hp=1, max_hp=1,
|
||||
)
|
||||
session.current_map.entities.append(dragon)
|
||||
clock = HeldKeyClock()
|
||||
assert apply_held_direction(session, clock, (1, 0), now=0) is False # the killing blow ends the run
|
||||
assert session.state == STATE_VICTORY
|
||||
assert clock.running is False
|
||||
assert apply_held_direction(session, clock, (1, 0), now=200) is False
|
||||
|
||||
# glue: a step that somehow leaves the floor ends the run (paranoia path)
|
||||
original_move = move
|
||||
|
||||
def descending_move(session: GameSession, dx: int, dy: int) -> bool:
|
||||
moved = original_move(session, dx, dy)
|
||||
session.current_floor += 1
|
||||
return moved
|
||||
|
||||
globals()["move"] = descending_move
|
||||
try:
|
||||
session = GameSession(
|
||||
player=Player(x=1, y=2),
|
||||
dungeon=[open_map(9, 5, (1, 2)), open_map(9, 5, (1, 2))],
|
||||
)
|
||||
session.refresh_fov()
|
||||
clock = HeldKeyClock()
|
||||
assert apply_held_direction(session, clock, (1, 0), now=0) is False
|
||||
assert session.current_floor == 1 and clock.running is False
|
||||
finally:
|
||||
globals()["move"] = original_move
|
||||
|
||||
print("clock self-check: PASS")
|
||||
@@ -0,0 +1,124 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from random import random
|
||||
from typing import Final
|
||||
|
||||
from entities.enemy import Enemy
|
||||
from entities.player import Player
|
||||
|
||||
# ponytail: combat tuning lives here, not constants.py, so parallel Phase 2
|
||||
# workers (fov/pathfinding) never touch the same file; merge later if desired.
|
||||
HIT_BASE: Final = 0.7
|
||||
HIT_PER_STAT_POINT: Final = 0.05
|
||||
HIT_MIN: Final = 0.1
|
||||
HIT_MAX: Final = 0.95
|
||||
CRIT_MULTIPLIER: Final = 2
|
||||
LOG_LIMIT: Final = 50
|
||||
|
||||
Combatant = Player | Enemy
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AttackResult:
|
||||
hit: bool = False
|
||||
crit: bool = False
|
||||
damage: int = 0
|
||||
killed: bool = False
|
||||
|
||||
|
||||
def _weapon_bonus(attacker: Combatant) -> int:
|
||||
weapon = getattr(attacker, "equipped_weapon", None)
|
||||
return max(0, getattr(weapon, "power", 0))
|
||||
|
||||
|
||||
def _attack_power(attacker: Combatant, base_power: int | None) -> int:
|
||||
if base_power is not None:
|
||||
return max(0, base_power)
|
||||
return attacker.total_power if isinstance(attacker, Player) else attacker.power
|
||||
|
||||
|
||||
def _defender_armor(defender: Combatant) -> int:
|
||||
return defender.total_armor if isinstance(defender, Player) else defender.armor
|
||||
|
||||
|
||||
def _defender_evasion(defender: Combatant) -> int:
|
||||
return (
|
||||
defender.total_evasion if isinstance(defender, Player) else defender.evasion
|
||||
)
|
||||
|
||||
|
||||
def _attacker_crit(attacker: Combatant) -> float:
|
||||
return (
|
||||
attacker.total_crit_chance
|
||||
if isinstance(attacker, Player)
|
||||
else attacker.crit_chance
|
||||
)
|
||||
|
||||
|
||||
def hit_chance(attacker: Combatant, defender: Combatant, hit_bonus: float = 0.0) -> float:
|
||||
raw = (
|
||||
HIT_BASE
|
||||
+ (attacker.accuracy - _defender_evasion(defender)) * HIT_PER_STAT_POINT
|
||||
+ hit_bonus
|
||||
)
|
||||
return min(HIT_MAX, max(HIT_MIN, raw))
|
||||
|
||||
|
||||
def _log_message(log: list[str] | None, message: str) -> None:
|
||||
if log is None:
|
||||
return
|
||||
log.append(message)
|
||||
del log[:-LOG_LIMIT]
|
||||
|
||||
|
||||
def _attacker_name(attacker: Combatant) -> str:
|
||||
return "You" if isinstance(attacker, Player) else attacker.name
|
||||
|
||||
|
||||
def _defender_name(defender: Combatant) -> str:
|
||||
return "you" if isinstance(defender, Player) else f"the {defender.name}"
|
||||
|
||||
|
||||
def attack(
|
||||
attacker: Combatant,
|
||||
defender: Combatant,
|
||||
log: list[str] | None = None,
|
||||
hit_bonus: float = 0.0,
|
||||
base_power: int | None = None,
|
||||
) -> AttackResult:
|
||||
"""Resolve one attack, mutating defender HP and appending log messages.
|
||||
|
||||
hit_bonus shifts hit chance in percentage points before clamping
|
||||
(negative for ranged distance penalties). base_power overrides the
|
||||
melee power roll (ranged weapons/archers use their fixed power).
|
||||
"""
|
||||
a = _attacker_name(attacker)
|
||||
d = _defender_name(defender)
|
||||
is_player_attacker = isinstance(attacker, Player)
|
||||
|
||||
if random() >= hit_chance(attacker, defender, hit_bonus):
|
||||
_log_message(log, f"{a} miss{'es' if not is_player_attacker else ''} {d}")
|
||||
return AttackResult()
|
||||
|
||||
power = _attack_power(attacker, base_power)
|
||||
reduced = max(0, power - _defender_armor(defender))
|
||||
crit = random() < _attacker_crit(attacker)
|
||||
damage = reduced * (CRIT_MULTIPLIER if crit else 1)
|
||||
defender.hp = max(0, defender.hp - damage)
|
||||
killed = not defender.alive
|
||||
|
||||
verb = "hit" if is_player_attacker else "hits"
|
||||
message = f"{a} {verb} {d} for {damage} damage!"
|
||||
if crit:
|
||||
message = f"Critical hit! {message}"
|
||||
_log_message(log, message)
|
||||
|
||||
if killed:
|
||||
if is_player_attacker and isinstance(defender, Enemy):
|
||||
attacker.gain_xp(defender.xp_reward, log)
|
||||
_log_message(log, f"You defeated {d}! (+{defender.xp_reward} XP)")
|
||||
else:
|
||||
_log_message(log, f"{a} defeat{'s' if not is_player_attacker else ''} {d}!")
|
||||
|
||||
return AttackResult(hit=True, crit=crit, damage=damage, killed=killed)
|
||||
@@ -0,0 +1,185 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from array import array
|
||||
from typing import Final
|
||||
|
||||
from data.constants import TILE_WALL
|
||||
from engine.map_gen import GameMap, Grid, Point
|
||||
|
||||
# ponytail: FOV tuning lives here, not constants.py, so parallel Phase 2
|
||||
# workers (pathfinding/combat) never touch the same file; merge later if desired.
|
||||
SIGHT_RADIUS: Final = 8
|
||||
|
||||
_OCTANTS: Final = (
|
||||
(1, 0, 0, -1, -1, 0, 0, 1),
|
||||
(0, 1, -1, 0, 0, -1, 1, 0),
|
||||
(0, 1, 1, 0, 0, -1, -1, 0),
|
||||
(1, 0, 0, 1, -1, 0, 0, -1),
|
||||
)
|
||||
|
||||
|
||||
def _cast_light(
|
||||
game_map: GameMap,
|
||||
cx: int,
|
||||
cy: int,
|
||||
row: int,
|
||||
start: float,
|
||||
end: float,
|
||||
radius: int,
|
||||
xx: int,
|
||||
xy: int,
|
||||
yx: int,
|
||||
yy: int,
|
||||
) -> None:
|
||||
if start < end:
|
||||
return
|
||||
new_start = 0.0
|
||||
for distance in range(row, radius + 1):
|
||||
dx = -distance - 1
|
||||
dy = -distance
|
||||
blocked = False
|
||||
while dx <= 0:
|
||||
dx += 1
|
||||
x = cx + dx * xx + dy * xy
|
||||
y = cy + dx * yx + dy * yy
|
||||
l_slope = (dx - 0.5) / (dy + 0.5)
|
||||
r_slope = (dx + 0.5) / (dy - 0.5)
|
||||
if start < r_slope:
|
||||
continue
|
||||
if end > l_slope:
|
||||
break
|
||||
if dx * dx + dy * dy <= radius * radius and game_map.in_bounds(x, y):
|
||||
game_map.visible[y][x] = 1
|
||||
game_map.explored[y][x] = 1
|
||||
if blocked:
|
||||
if game_map.tile_at(x, y) == TILE_WALL:
|
||||
new_start = r_slope
|
||||
continue
|
||||
blocked = False
|
||||
start = new_start
|
||||
elif game_map.tile_at(x, y) == TILE_WALL and distance < radius:
|
||||
_cast_light(
|
||||
game_map, cx, cy, distance + 1, start, l_slope, radius, xx, xy, yx, yy
|
||||
)
|
||||
blocked = True
|
||||
new_start = r_slope
|
||||
if blocked:
|
||||
break
|
||||
|
||||
|
||||
def compute_fov(game_map: GameMap, origin: Point, radius: int = SIGHT_RADIUS) -> None:
|
||||
"""Refresh game_map.visible via recursive shadowcasting, merging into explored.
|
||||
|
||||
Walls occlude but are themselves lit when reached by light. Visible is
|
||||
rebuilt from scratch every call; explored only ever grows. Never raises
|
||||
on any game state: an out-of-bounds origin just leaves visible cleared.
|
||||
"""
|
||||
for grid_row in game_map.visible:
|
||||
grid_row[:] = array("b", bytes(len(grid_row)))
|
||||
ox, oy = origin
|
||||
if not game_map.in_bounds(ox, oy):
|
||||
return
|
||||
game_map.visible[oy][ox] = 1
|
||||
game_map.explored[oy][ox] = 1
|
||||
for octant in range(8):
|
||||
_cast_light(
|
||||
game_map,
|
||||
ox,
|
||||
oy,
|
||||
1,
|
||||
1.0,
|
||||
0.0,
|
||||
radius,
|
||||
_OCTANTS[0][octant],
|
||||
_OCTANTS[1][octant],
|
||||
_OCTANTS[2][octant],
|
||||
_OCTANTS[3][octant],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run from the repo root: python -m engine.fov
|
||||
from data.constants import TILE_FLOOR
|
||||
from engine.map_gen import generate_map
|
||||
|
||||
def manual_map(width: int, height: int, floors: list[Point]) -> GameMap:
|
||||
tiles = [array("b", [TILE_WALL] * width) for _ in range(height)]
|
||||
for x, y in floors:
|
||||
tiles[y][x] = TILE_FLOOR
|
||||
return GameMap(
|
||||
width=width,
|
||||
height=height,
|
||||
tiles=tiles,
|
||||
rooms=[],
|
||||
junctions=[],
|
||||
corridors=[],
|
||||
explored=[array("b", [0] * width) for _ in range(height)],
|
||||
visible=[array("b", [0] * width) for _ in range(height)],
|
||||
entities=[],
|
||||
stairs_down=None,
|
||||
floor_index=0,
|
||||
spawn=floors[0],
|
||||
)
|
||||
|
||||
def lit(game_map: GameMap) -> set[Point]:
|
||||
return {
|
||||
(x, y)
|
||||
for y, row in enumerate(game_map.visible)
|
||||
for x, seen in enumerate(row)
|
||||
if seen
|
||||
}
|
||||
|
||||
def lit_floors(game_map: GameMap) -> set[Point]:
|
||||
return {point for point in lit(game_map) if game_map.tile_at(*point) == TILE_FLOOR}
|
||||
|
||||
sealed = manual_map(5, 5, [(2, 2)])
|
||||
compute_fov(sealed, (2, 2))
|
||||
assert lit_floors(sealed) == {(2, 2)}, "walled-in player must see no other floor"
|
||||
assert all(
|
||||
sealed.visible[2 + dy][2 + dx]
|
||||
for dy in (-1, 0, 1)
|
||||
for dx in (-1, 0, 1)
|
||||
if (dx, dy) != (0, 0)
|
||||
), "walls adjacent to the visible origin floor must be lit"
|
||||
|
||||
size = 19
|
||||
disc = manual_map(size, size, [(x, y) for y in range(size) for x in range(size)])
|
||||
center = (9, 9)
|
||||
compute_fov(disc, center)
|
||||
expected = {
|
||||
(x, y)
|
||||
for y in range(size)
|
||||
for x in range(size)
|
||||
if (x - center[0]) ** 2 + (y - center[1]) ** 2 <= SIGHT_RADIUS**2
|
||||
}
|
||||
assert lit(disc) == expected, "open area must light exactly the radius-8 disc"
|
||||
compute_fov(disc, (9, 16))
|
||||
assert (9, 7) not in lit(disc), "visible must be rebuilt, not accumulated"
|
||||
assert disc.explored[7][9], "previously seen tiles stay explored"
|
||||
assert disc.explored[9][9] and disc.visible[16][9]
|
||||
|
||||
corridor = manual_map(11, 3, [(x, 1) for x in range(11) if x != 5])
|
||||
compute_fov(corridor, (1, 1))
|
||||
assert (4, 1) in lit(corridor), "tile before the wall must be visible"
|
||||
assert (6, 1) not in lit(corridor), "wall must occlude the tile behind it"
|
||||
|
||||
game_map = generate_map(0, seed=0)
|
||||
compute_fov(game_map, game_map.spawn)
|
||||
ox, oy = game_map.spawn
|
||||
assert all(
|
||||
(x - ox) ** 2 + (y - oy) ** 2 <= SIGHT_RADIUS**2 for x, y in lit(game_map)
|
||||
), "no visible tile may exceed the sight radius"
|
||||
assert len(lit_floors(game_map)) > 20, "the spawn room must be broadly visible"
|
||||
far = next(
|
||||
(
|
||||
(x, y)
|
||||
for y, tiles in enumerate(game_map.tiles)
|
||||
for x, tile in enumerate(tiles)
|
||||
if tile == TILE_FLOOR and (x - ox) ** 2 + (y - oy) ** 2 > SIGHT_RADIUS**2
|
||||
),
|
||||
None,
|
||||
)
|
||||
if far is not None:
|
||||
assert far not in lit(game_map), "tiles beyond radius must stay dark"
|
||||
|
||||
print("fov self-check: PASS")
|
||||
@@ -0,0 +1,89 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from data.constants import FINAL_FLOOR, MESSAGE_LOG_LIMIT
|
||||
from engine.fov import compute_fov
|
||||
from engine.map_gen import GameMap, generate_map
|
||||
from entities.item import Item
|
||||
from entities.player import Player
|
||||
|
||||
STATE_PLAYING = "playing"
|
||||
STATE_DEAD = "dead"
|
||||
STATE_VICTORY = "victory"
|
||||
STATE_MENU = "menu"
|
||||
STATE_SAVED = "saved"
|
||||
|
||||
OVERLAY_HELP = "help"
|
||||
OVERLAY_INVENTORY = "inventory"
|
||||
OVERLAY_EQUIPMENT = "equipment"
|
||||
OVERLAY_QUAFF = "quaff"
|
||||
OVERLAY_READ = "read"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameSession:
|
||||
"""Single source of truth for all mutable state; the unit of save/load."""
|
||||
|
||||
player: Player
|
||||
dungeon: list[GameMap]
|
||||
current_floor: int = 0
|
||||
log: list[str] = field(default_factory=list)
|
||||
turn: int = 0
|
||||
state: str = STATE_PLAYING
|
||||
overlay: str | None = None
|
||||
overlay_index: int = 0
|
||||
menu_index: int = 0
|
||||
save_available: bool = False
|
||||
|
||||
@property
|
||||
def current_map(self) -> GameMap:
|
||||
return self.dungeon[self.current_floor]
|
||||
|
||||
def log_message(self, message: str) -> None:
|
||||
self.log.append(message)
|
||||
del self.log[:-MESSAGE_LOG_LIMIT]
|
||||
|
||||
def refresh_fov(self) -> None:
|
||||
compute_fov(self.current_map, self.player.position)
|
||||
|
||||
def context_prompt(self) -> str | None:
|
||||
"""The contextual key hint: pickup while on an item, descent on stairs."""
|
||||
if self.state != STATE_PLAYING or not self.dungeon:
|
||||
return None
|
||||
position = self.player.position
|
||||
game_map = self.current_map
|
||||
for entity in game_map.entities:
|
||||
if isinstance(entity, Item) and entity.position == position:
|
||||
return f"Press G to pick up the {entity.name}."
|
||||
if game_map.stairs_down == position:
|
||||
return "Press F to descend."
|
||||
return None
|
||||
|
||||
def descend(self) -> bool:
|
||||
game_map = self.current_map
|
||||
if game_map.stairs_down is None or self.player.position != game_map.stairs_down:
|
||||
return False
|
||||
self.current_floor += 1
|
||||
self.player.x, self.player.y = self.current_map.spawn
|
||||
self.refresh_fov()
|
||||
self.log_message(f"You descend to floor {self.current_floor + 1}.")
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def for_menu(cls, save_available: bool = False) -> GameSession:
|
||||
"""A menu-only session; a real dungeon arrives with the next run."""
|
||||
return cls(player=Player(), dungeon=[], state=STATE_MENU, save_available=save_available)
|
||||
|
||||
|
||||
def new_game(seed: int | None = None) -> GameSession:
|
||||
dungeon = [
|
||||
generate_map(floor, seed=None if seed is None else seed + floor)
|
||||
for floor in range(FINAL_FLOOR + 1)
|
||||
]
|
||||
spawn = dungeon[0].spawn
|
||||
session = GameSession(player=Player(x=spawn[0], y=spawn[1]), dungeon=dungeon)
|
||||
session.overlay = OVERLAY_HELP # How to Play screens the very first turn
|
||||
session.log_message("You descend into the Underdepths. Slay the dragon below.")
|
||||
session.refresh_fov()
|
||||
return session
|
||||
@@ -0,0 +1,476 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from array import array
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
import random
|
||||
|
||||
from data.constants import (
|
||||
ARENA_DRAGON_OFFSET,
|
||||
ARENA_ENTRANCE_OFFSET,
|
||||
ARENA_HEIGHT,
|
||||
ARENA_WIDTH,
|
||||
BSP_MAX_ROOMS,
|
||||
BSP_MIN_ROOMS,
|
||||
DRAGON_KEY,
|
||||
FINAL_FLOOR,
|
||||
FINAL_FLOOR_POTIONS,
|
||||
JUNCTION_SIZE,
|
||||
MAP_BORDER,
|
||||
MAP_HEIGHT,
|
||||
MAP_WIDTH,
|
||||
MAX_CORRIDOR_LENGTH,
|
||||
MAX_MAP_ATTEMPTS,
|
||||
ROOM_MARGIN,
|
||||
ROOM_MAX_HEIGHT,
|
||||
ROOM_MAX_WIDTH,
|
||||
ROOM_MIN_HEIGHT,
|
||||
ROOM_MIN_WIDTH,
|
||||
TILE_FLOOR,
|
||||
TILE_WALL,
|
||||
)
|
||||
from data.enemies import roll_floor_enemies, spawn_enemy
|
||||
from data.items import roll_floor_items, spawn_item
|
||||
from entities.entity import Entity
|
||||
|
||||
Grid = list[array]
|
||||
Point = tuple[int, int]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Rect:
|
||||
x: int
|
||||
y: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
@property
|
||||
def x2(self) -> int:
|
||||
return self.x + self.width
|
||||
|
||||
@property
|
||||
def y2(self) -> int:
|
||||
return self.y + self.height
|
||||
|
||||
@property
|
||||
def center(self) -> Point:
|
||||
return self.x + self.width // 2, self.y + self.height // 2
|
||||
|
||||
def contains(self, point: Point) -> bool:
|
||||
x, y = point
|
||||
return self.x <= x < self.x2 and self.y <= y < self.y2
|
||||
|
||||
def overlaps(self, other: Rect) -> bool:
|
||||
return not (
|
||||
self.x2 <= other.x
|
||||
or other.x2 <= self.x
|
||||
or self.y2 <= other.y
|
||||
or other.y2 <= self.y
|
||||
)
|
||||
|
||||
def tiles(self) -> set[Point]:
|
||||
return {
|
||||
(x, y)
|
||||
for y in range(self.y, self.y2)
|
||||
for x in range(self.x, self.x2)
|
||||
}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameMap:
|
||||
width: int
|
||||
height: int
|
||||
tiles: Grid
|
||||
rooms: list[Rect]
|
||||
junctions: list[Rect]
|
||||
corridors: list[list[Point]]
|
||||
explored: Grid
|
||||
visible: Grid
|
||||
entities: list[Entity]
|
||||
stairs_down: Point | None
|
||||
floor_index: int
|
||||
spawn: Point
|
||||
|
||||
def in_bounds(self, x: int, y: int) -> bool:
|
||||
return 0 <= x < self.width and 0 <= y < self.height
|
||||
|
||||
def tile_at(self, x: int, y: int) -> int:
|
||||
return self.tiles[y][x] if self.in_bounds(x, y) else TILE_WALL
|
||||
|
||||
def is_walkable(self, x: int, y: int) -> bool:
|
||||
return self.tile_at(x, y) == TILE_FLOOR
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Node:
|
||||
region: Rect
|
||||
depth: int = 0
|
||||
left: _Node | None = None
|
||||
right: _Node | None = None
|
||||
room: Rect | None = None
|
||||
|
||||
@property
|
||||
def is_leaf(self) -> bool:
|
||||
return self.left is None and self.right is None
|
||||
|
||||
|
||||
class _GenerationError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
_MIN_REGION_WIDTH = ROOM_MIN_WIDTH + ROOM_MARGIN * 2
|
||||
_MIN_REGION_HEIGHT = ROOM_MIN_HEIGHT + ROOM_MARGIN * 2
|
||||
|
||||
|
||||
def _new_grid(width: int, height: int, value: int) -> Grid:
|
||||
return [array("b", [value]) * width for _ in range(height)]
|
||||
|
||||
|
||||
def _leaves(node: _Node) -> list[_Node]:
|
||||
if node.is_leaf:
|
||||
return [node]
|
||||
result: list[_Node] = []
|
||||
if node.left is not None:
|
||||
result.extend(_leaves(node.left))
|
||||
if node.right is not None:
|
||||
result.extend(_leaves(node.right))
|
||||
return result
|
||||
|
||||
|
||||
def _can_split(node: _Node) -> bool:
|
||||
return (
|
||||
node.region.width >= _MIN_REGION_WIDTH * 2
|
||||
or node.region.height >= _MIN_REGION_HEIGHT * 2
|
||||
)
|
||||
|
||||
|
||||
def _balanced_offset(size: int, minimum: int, rng: random.Random) -> int:
|
||||
low = max(minimum, size * 2 // 5)
|
||||
high = min(size - minimum, size * 3 // 5)
|
||||
if low > high:
|
||||
low, high = minimum, size - minimum
|
||||
return rng.randint(low, high)
|
||||
|
||||
|
||||
def _split(node: _Node, rng: random.Random) -> bool:
|
||||
region = node.region
|
||||
can_vertical = region.width >= _MIN_REGION_WIDTH * 2
|
||||
can_horizontal = region.height >= _MIN_REGION_HEIGHT * 2
|
||||
if not can_vertical and not can_horizontal:
|
||||
return False
|
||||
|
||||
vertical = node.depth % 2 == 0
|
||||
if vertical and not can_vertical:
|
||||
vertical = False
|
||||
elif not vertical and not can_horizontal:
|
||||
vertical = True
|
||||
|
||||
if vertical:
|
||||
offset = _balanced_offset(region.width, _MIN_REGION_WIDTH, rng)
|
||||
first = Rect(region.x, region.y, offset, region.height)
|
||||
second = Rect(region.x + offset, region.y, region.width - offset, region.height)
|
||||
else:
|
||||
offset = _balanced_offset(region.height, _MIN_REGION_HEIGHT, rng)
|
||||
first = Rect(region.x, region.y, region.width, offset)
|
||||
second = Rect(region.x, region.y + offset, region.width, region.height - offset)
|
||||
|
||||
node.left = _Node(first, node.depth + 1)
|
||||
node.right = _Node(second, node.depth + 1)
|
||||
return True
|
||||
|
||||
|
||||
def _build_tree(rng: random.Random) -> _Node:
|
||||
root = _Node(
|
||||
Rect(
|
||||
MAP_BORDER,
|
||||
MAP_BORDER,
|
||||
MAP_WIDTH - MAP_BORDER * 2,
|
||||
MAP_HEIGHT - MAP_BORDER * 2,
|
||||
)
|
||||
)
|
||||
target = rng.randint(BSP_MIN_ROOMS, BSP_MAX_ROOMS)
|
||||
while len(_leaves(root)) < target:
|
||||
candidates = [leaf for leaf in _leaves(root) if _can_split(leaf)]
|
||||
if not candidates:
|
||||
raise _GenerationError("BSP could not reach its room target")
|
||||
largest = max(
|
||||
candidates,
|
||||
key=lambda leaf: leaf.region.width * leaf.region.height,
|
||||
)
|
||||
if not _split(largest, rng):
|
||||
raise _GenerationError("selected BSP leaf could not split")
|
||||
return root
|
||||
|
||||
|
||||
def _make_room(region: Rect, rng: random.Random) -> Rect:
|
||||
maximum_width = min(ROOM_MAX_WIDTH, region.width - ROOM_MARGIN * 2)
|
||||
maximum_height = min(ROOM_MAX_HEIGHT, region.height - ROOM_MARGIN * 2)
|
||||
width = rng.randint(ROOM_MIN_WIDTH, maximum_width)
|
||||
height = rng.randint(ROOM_MIN_HEIGHT, maximum_height)
|
||||
x = rng.randint(region.x + ROOM_MARGIN, region.x2 - width - ROOM_MARGIN)
|
||||
y = rng.randint(region.y + ROOM_MARGIN, region.y2 - height - ROOM_MARGIN)
|
||||
return Rect(x, y, width, height)
|
||||
|
||||
|
||||
def _carve_rect(tiles: Grid, rect: Rect) -> None:
|
||||
for y in range(rect.y, rect.y2):
|
||||
for x in range(rect.x, rect.x2):
|
||||
tiles[y][x] = TILE_FLOOR
|
||||
|
||||
|
||||
def _carve_path(tiles: Grid, path: list[Point]) -> None:
|
||||
for x, y in path:
|
||||
tiles[y][x] = TILE_FLOOR
|
||||
|
||||
|
||||
def _clamp(value: int, low: int, high: int) -> int:
|
||||
return max(low, min(value, high))
|
||||
|
||||
|
||||
def _closest_endpoints(first: Rect, second: Rect) -> tuple[Point, Point, bool]:
|
||||
if first.x2 <= second.x:
|
||||
first_y = _clamp(second.center[1], first.y, first.y2 - 1)
|
||||
second_y = _clamp(first_y, second.y, second.y2 - 1)
|
||||
return (first.x2 - 1, first_y), (second.x, second_y), True
|
||||
if second.x2 <= first.x:
|
||||
first_y = _clamp(second.center[1], first.y, first.y2 - 1)
|
||||
second_y = _clamp(first_y, second.y, second.y2 - 1)
|
||||
return (first.x, first_y), (second.x2 - 1, second_y), True
|
||||
if first.y2 <= second.y:
|
||||
first_x = _clamp(second.center[0], first.x, first.x2 - 1)
|
||||
second_x = _clamp(first_x, second.x, second.x2 - 1)
|
||||
return (first_x, first.y2 - 1), (second_x, second.y), False
|
||||
first_x = _clamp(second.center[0], first.x, first.x2 - 1)
|
||||
second_x = _clamp(first_x, second.x, second.x2 - 1)
|
||||
return (first_x, first.y), (second_x, second.y2 - 1), False
|
||||
|
||||
|
||||
def _ordered_path(start: Point, end: Point, horizontal_first: bool) -> list[Point]:
|
||||
path = [start]
|
||||
x, y = start
|
||||
end_x, end_y = end
|
||||
axes = ("x", "y") if horizontal_first else ("y", "x")
|
||||
for axis in axes:
|
||||
if axis == "x":
|
||||
while x != end_x:
|
||||
x += 1 if end_x > x else -1
|
||||
path.append((x, y))
|
||||
else:
|
||||
while y != end_y:
|
||||
y += 1 if end_y > y else -1
|
||||
path.append((x, y))
|
||||
return path
|
||||
|
||||
|
||||
def _junction_at(point: Point) -> Rect:
|
||||
radius = JUNCTION_SIZE // 2
|
||||
return Rect(point[0] - radius, point[1] - radius, JUNCTION_SIZE, JUNCTION_SIZE)
|
||||
|
||||
|
||||
def _contains_feature(point: Point, rooms: list[Rect], junctions: list[Rect]) -> bool:
|
||||
return any(feature.contains(point) for feature in [*rooms, *junctions])
|
||||
|
||||
|
||||
def _valid_junction(candidate: Rect, rooms: list[Rect], junctions: list[Rect]) -> bool:
|
||||
inside_border = (
|
||||
candidate.x >= MAP_BORDER
|
||||
and candidate.y >= MAP_BORDER
|
||||
and candidate.x2 <= MAP_WIDTH - MAP_BORDER
|
||||
and candidate.y2 <= MAP_HEIGHT - MAP_BORDER
|
||||
)
|
||||
return inside_border and not any(
|
||||
candidate.overlaps(feature) for feature in [*rooms, *junctions]
|
||||
)
|
||||
|
||||
|
||||
def _partition_point(
|
||||
path: list[Point],
|
||||
start_index: int,
|
||||
rooms: list[Rect],
|
||||
junctions: list[Rect],
|
||||
) -> tuple[int, Rect | None]:
|
||||
furthest = min(start_index + MAX_CORRIDOR_LENGTH, len(path) - 1)
|
||||
for index in range(furthest, start_index, -1):
|
||||
point = path[index]
|
||||
if _contains_feature(point, rooms, junctions):
|
||||
return index, None
|
||||
candidate = _junction_at(point)
|
||||
if _valid_junction(candidate, rooms, junctions):
|
||||
return index, candidate
|
||||
raise _GenerationError("corridor could not place a valid junction")
|
||||
|
||||
|
||||
def _record_route(
|
||||
tiles: Grid,
|
||||
path: list[Point],
|
||||
rooms: list[Rect],
|
||||
junctions: list[Rect],
|
||||
corridors: list[list[Point]],
|
||||
) -> None:
|
||||
start_index = 0
|
||||
while len(path) - 1 - start_index > MAX_CORRIDOR_LENGTH:
|
||||
end_index, junction = _partition_point(path, start_index, rooms, junctions)
|
||||
if junction is not None:
|
||||
junctions.append(junction)
|
||||
_carve_rect(tiles, junction)
|
||||
section = path[start_index : end_index + 1]
|
||||
corridors.append(section)
|
||||
_carve_path(tiles, section)
|
||||
start_index = end_index
|
||||
|
||||
section = path[start_index:]
|
||||
corridors.append(section)
|
||||
_carve_path(tiles, section)
|
||||
|
||||
|
||||
def _room_distance(first: Rect, second: Rect) -> int:
|
||||
start, end, _ = _closest_endpoints(first, second)
|
||||
return abs(start[0] - end[0]) + abs(start[1] - end[1])
|
||||
|
||||
|
||||
def _connect_tree(
|
||||
node: _Node,
|
||||
tiles: Grid,
|
||||
rooms: list[Rect],
|
||||
junctions: list[Rect],
|
||||
corridors: list[list[Point]],
|
||||
) -> list[Rect]:
|
||||
if node.room is not None:
|
||||
return [node.room]
|
||||
if node.left is None or node.right is None:
|
||||
raise _GenerationError("invalid BSP tree")
|
||||
|
||||
left_rooms = _connect_tree(node.left, tiles, rooms, junctions, corridors)
|
||||
right_rooms = _connect_tree(node.right, tiles, rooms, junctions, corridors)
|
||||
first, second = min(
|
||||
((first, second) for first in left_rooms for second in right_rooms),
|
||||
key=lambda pair: _room_distance(*pair),
|
||||
)
|
||||
start, end, horizontal_first = _closest_endpoints(first, second)
|
||||
_record_route(
|
||||
tiles,
|
||||
_ordered_path(start, end, horizontal_first),
|
||||
rooms,
|
||||
junctions,
|
||||
corridors,
|
||||
)
|
||||
return left_rooms + right_rooms
|
||||
|
||||
|
||||
def _generate_attempt(floor_index: int, rng: random.Random) -> GameMap:
|
||||
if floor_index == FINAL_FLOOR:
|
||||
return _generate_arena(rng)
|
||||
root = _build_tree(rng)
|
||||
tiles = _new_grid(MAP_WIDTH, MAP_HEIGHT, TILE_WALL)
|
||||
rooms: list[Rect] = []
|
||||
for leaf in _leaves(root):
|
||||
leaf.room = _make_room(leaf.region, rng)
|
||||
rooms.append(leaf.room)
|
||||
_carve_rect(tiles, leaf.room)
|
||||
|
||||
junctions: list[Rect] = []
|
||||
corridors: list[list[Point]] = []
|
||||
_connect_tree(root, tiles, rooms, junctions, corridors)
|
||||
spawn = rooms[0].center
|
||||
farthest_room = max(
|
||||
rooms[1:],
|
||||
key=lambda room: abs(room.center[0] - spawn[0])
|
||||
+ abs(room.center[1] - spawn[1]),
|
||||
)
|
||||
game_map = GameMap(
|
||||
width=MAP_WIDTH,
|
||||
height=MAP_HEIGHT,
|
||||
tiles=tiles,
|
||||
rooms=rooms,
|
||||
junctions=junctions,
|
||||
corridors=corridors,
|
||||
explored=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
|
||||
visible=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
|
||||
entities=[],
|
||||
stairs_down=farthest_room.center,
|
||||
floor_index=floor_index,
|
||||
spawn=spawn,
|
||||
)
|
||||
_populate(game_map, rng)
|
||||
return game_map
|
||||
|
||||
|
||||
def _generate_arena(rng: random.Random) -> GameMap:
|
||||
"""Floor 9: one large room, the dragon across from the entrance."""
|
||||
arena = Rect(
|
||||
(MAP_WIDTH - ARENA_WIDTH) // 2,
|
||||
(MAP_HEIGHT - ARENA_HEIGHT) // 2,
|
||||
ARENA_WIDTH,
|
||||
ARENA_HEIGHT,
|
||||
)
|
||||
tiles = _new_grid(MAP_WIDTH, MAP_HEIGHT, TILE_WALL)
|
||||
_carve_rect(tiles, arena)
|
||||
entrance = (arena.x + ARENA_ENTRANCE_OFFSET, arena.center[1])
|
||||
game_map = GameMap(
|
||||
width=MAP_WIDTH,
|
||||
height=MAP_HEIGHT,
|
||||
tiles=tiles,
|
||||
rooms=[arena],
|
||||
junctions=[],
|
||||
corridors=[],
|
||||
explored=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
|
||||
visible=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
|
||||
entities=[
|
||||
spawn_enemy(
|
||||
DRAGON_KEY,
|
||||
arena.x2 - 1 - ARENA_DRAGON_OFFSET,
|
||||
arena.center[1],
|
||||
)
|
||||
],
|
||||
stairs_down=None,
|
||||
floor_index=FINAL_FLOOR,
|
||||
spawn=entrance,
|
||||
)
|
||||
for offset in (-2, 2):
|
||||
potion = spawn_item("healing_potion", entrance[0], entrance[1] + offset)
|
||||
game_map.entities.append(potion)
|
||||
return game_map
|
||||
|
||||
|
||||
def _free_tiles(room: Rect, occupied: set[Point]) -> list[Point]:
|
||||
return [tile for tile in room.tiles() if tile not in occupied]
|
||||
|
||||
|
||||
def _populate(game_map: GameMap, rng: random.Random) -> None:
|
||||
"""Place floor items then enemies, spread round-robin over non-spawn rooms."""
|
||||
occupied = {game_map.spawn}
|
||||
if game_map.stairs_down is not None:
|
||||
occupied.add(game_map.stairs_down)
|
||||
rooms = [room for room in game_map.rooms if not room.contains(game_map.spawn)]
|
||||
if not rooms:
|
||||
rooms = list(game_map.rooms)
|
||||
rng.shuffle(rooms)
|
||||
|
||||
placements: list[tuple[Callable[[str, int, int], Entity], str]] = [
|
||||
*[(spawn_item, key) for key in roll_floor_items(game_map.floor_index, rng)],
|
||||
*[(spawn_enemy, key) for key in roll_floor_enemies(game_map.floor_index, rng)],
|
||||
]
|
||||
for index, (spawner, key) in enumerate(placements):
|
||||
free: list[Point] = []
|
||||
for shift in range(len(rooms)):
|
||||
candidate = rooms[(index + shift) % len(rooms)]
|
||||
free = _free_tiles(candidate, occupied)
|
||||
if free:
|
||||
break
|
||||
if not free:
|
||||
raise _GenerationError("population ran out of free room tiles")
|
||||
tile = rng.choice(free)
|
||||
occupied.add(tile)
|
||||
game_map.entities.append(spawner(key, tile[0], tile[1]))
|
||||
|
||||
|
||||
def generate_map(floor_index: int = 0, seed: int | None = None) -> GameMap:
|
||||
if not 0 <= floor_index <= FINAL_FLOOR:
|
||||
raise ValueError(f"floor index must be between 0 and {FINAL_FLOOR}")
|
||||
rng = random.Random(seed)
|
||||
for _ in range(MAX_MAP_ATTEMPTS):
|
||||
try:
|
||||
return _generate_attempt(floor_index, rng)
|
||||
except _GenerationError:
|
||||
continue
|
||||
raise RuntimeError(f"failed to generate floor {floor_index} after {MAX_MAP_ATTEMPTS} attempts")
|
||||
@@ -0,0 +1,161 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Collection
|
||||
from heapq import heappush, heappop
|
||||
from itertools import count
|
||||
|
||||
from engine.map_gen import GameMap, Point
|
||||
|
||||
|
||||
def _manhattan(a: Point, b: Point) -> int:
|
||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||
|
||||
|
||||
def blocked_positions(game_map: GameMap) -> set[Point]:
|
||||
return {
|
||||
entity.position
|
||||
for entity in game_map.entities
|
||||
if entity.blocks_movement
|
||||
}
|
||||
|
||||
|
||||
def _neighbors(point: Point) -> tuple[Point, Point, Point, Point]:
|
||||
x, y = point
|
||||
return (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)
|
||||
|
||||
|
||||
def _reconstruct(came_from: dict[Point, Point], goal: Point) -> list[Point]:
|
||||
path = [goal]
|
||||
while path[-1] in came_from:
|
||||
path.append(came_from[path[-1]])
|
||||
path.reverse()
|
||||
return path
|
||||
|
||||
|
||||
def astar_path(
|
||||
game_map: GameMap,
|
||||
start: Point,
|
||||
goal: Point,
|
||||
occupied: Collection[Point] | None = None,
|
||||
) -> list[Point]:
|
||||
"""A* path from start to goal, 4-directional, Manhattan heuristic.
|
||||
|
||||
Obstacles are walls and occupied tiles, so movers never stack. The start
|
||||
tile is exempt from occupancy (the mover already stands there). Callers
|
||||
chasing the player should pass enemy positions only, letting the player's
|
||||
tile stay a valid goal.
|
||||
|
||||
Returns the full path [start, ..., goal]; [] when no path exists or an
|
||||
endpoint is not a floor tile. Never raises on any game state.
|
||||
"""
|
||||
if not game_map.is_walkable(*start) or not game_map.is_walkable(*goal):
|
||||
return []
|
||||
if start == goal:
|
||||
return [start]
|
||||
|
||||
blockers = blocked_positions(game_map) if occupied is None else set(occupied)
|
||||
if goal in blockers:
|
||||
return []
|
||||
|
||||
tie = count()
|
||||
start_h = _manhattan(start, goal)
|
||||
frontier: list[tuple[int, int, int, Point]] = [(start_h, start_h, next(tie), start)]
|
||||
came_from: dict[Point, Point] = {}
|
||||
best_g: dict[Point, int] = {start: 0}
|
||||
visited: set[Point] = set()
|
||||
|
||||
while frontier:
|
||||
_, _, _, current = heappop(frontier)
|
||||
if current in visited:
|
||||
continue
|
||||
visited.add(current)
|
||||
if current == goal:
|
||||
return _reconstruct(came_from, current)
|
||||
|
||||
g_next = best_g[current] + 1
|
||||
for neighbor in _neighbors(current):
|
||||
if neighbor in visited or neighbor in blockers:
|
||||
continue
|
||||
if not game_map.is_walkable(*neighbor):
|
||||
continue
|
||||
if g_next < best_g.get(neighbor, g_next + 1):
|
||||
best_g[neighbor] = g_next
|
||||
came_from[neighbor] = current
|
||||
h = _manhattan(neighbor, goal)
|
||||
heappush(frontier, (g_next + h, h, next(tie), neighbor))
|
||||
return []
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run from the repo root: python -m engine.pathfinding
|
||||
import random
|
||||
from array import array
|
||||
|
||||
from data.constants import TILE_FLOOR, TILE_WALL
|
||||
from entities.entity import Entity
|
||||
from engine.map_gen import generate_map
|
||||
|
||||
rng = random.Random(7)
|
||||
for floor in range(5):
|
||||
game_map = generate_map(floor, seed=floor)
|
||||
occupied = blocked_positions(game_map)
|
||||
walkable = [
|
||||
(x, y)
|
||||
for y, row in enumerate(game_map.tiles)
|
||||
for x, tile in enumerate(row)
|
||||
if tile == TILE_FLOOR and (x, y) not in occupied
|
||||
]
|
||||
assert astar_path(game_map, walkable[0], walkable[0], occupied=set()) == [walkable[0]]
|
||||
for _ in range(20):
|
||||
a, b = rng.sample(walkable, 2)
|
||||
# walls-only: mobs may legitimately seal a chokepoint, so the
|
||||
# any-two-tiles contract holds on the free floor graph
|
||||
path = astar_path(game_map, a, b, occupied=set())
|
||||
assert path, f"floor {floor}: no path {a} -> {b}"
|
||||
assert path[0] == a and path[-1] == b
|
||||
assert len(set(path)) == len(path)
|
||||
assert all(
|
||||
abs(p[0] - q[0]) + abs(p[1] - q[1]) == 1
|
||||
for p, q in zip(path, path[1:])
|
||||
), "path must be 4-directionally contiguous"
|
||||
assert all(game_map.is_walkable(*p) for p in path)
|
||||
wall = next(
|
||||
(x, y)
|
||||
for y, row in enumerate(game_map.tiles)
|
||||
for x, tile in enumerate(row)
|
||||
if tile == TILE_WALL
|
||||
)
|
||||
assert astar_path(game_map, walkable[0], wall) == []
|
||||
assert astar_path(game_map, wall, walkable[0]) == []
|
||||
|
||||
def manual_map(floors: list[Point]) -> GameMap:
|
||||
tiles = [array("b", [TILE_WALL] * 5) for _ in range(5)]
|
||||
for x, y in floors:
|
||||
tiles[y][x] = TILE_FLOOR
|
||||
return GameMap(
|
||||
width=5,
|
||||
height=5,
|
||||
tiles=tiles,
|
||||
rooms=[],
|
||||
junctions=[],
|
||||
corridors=[],
|
||||
explored=[array("b", [0] * 5) for _ in range(5)],
|
||||
visible=[array("b", [0] * 5) for _ in range(5)],
|
||||
entities=[],
|
||||
stairs_down=None,
|
||||
floor_index=0,
|
||||
spawn=floors[0],
|
||||
)
|
||||
|
||||
split = manual_map([(1, 1), (3, 3)])
|
||||
assert astar_path(split, (1, 1), (3, 3)) == [], "walled-off goal must yield no path"
|
||||
|
||||
corridor = manual_map([(1, 1), (2, 1), (3, 1)])
|
||||
straight = astar_path(corridor, (1, 1), (3, 1))
|
||||
assert straight == [(1, 1), (2, 1), (3, 1)], "Manhattan-optimal length expected"
|
||||
assert astar_path(corridor, (1, 1), (3, 1), occupied={(2, 1)}) == []
|
||||
corridor.entities.append(Entity(x=2, y=1, name="Goblin"))
|
||||
assert astar_path(corridor, (1, 1), (3, 1)) == [], "entity on map must block"
|
||||
assert astar_path(corridor, (2, 1), (3, 1)) == [(2, 1), (3, 1)], "start is exempt"
|
||||
|
||||
print("pathfinding self-check: PASS")
|
||||
@@ -0,0 +1,290 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from array import array
|
||||
from base64 import b64decode, b64encode
|
||||
from dataclasses import fields
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from engine.game_state import GameSession
|
||||
from engine.map_gen import GameMap, Grid, Rect
|
||||
from entities.enemy import Enemy
|
||||
from entities.entity import Entity
|
||||
from entities.item import Item, TimedEffect
|
||||
from entities.player import Player
|
||||
|
||||
SAVE_VERSION: Final = 1
|
||||
_EQUIP_SLOTS: Final = ("equipped_weapon", "equipped_armor", "equipped_boots")
|
||||
_TUPLE_FIELDS: Final = ("last_known_position",)
|
||||
|
||||
|
||||
def _grid_to_text(grid: Grid) -> str:
|
||||
return b64encode(b"".join(row.tobytes() for row in grid)).decode("ascii")
|
||||
|
||||
|
||||
def _text_to_grid(text: str, width: int, height: int) -> Grid:
|
||||
raw = b64decode(text, validate=True)
|
||||
if len(raw) != width * height:
|
||||
raise ValueError("grid payload does not match map dimensions")
|
||||
return [array("b", raw[y * width : (y + 1) * width]) for y in range(height)]
|
||||
|
||||
|
||||
def _zero_grid(width: int, height: int) -> Grid:
|
||||
return [array("b", bytes(width)) for _ in range(height)]
|
||||
|
||||
|
||||
def _entity_to_dict(entity: Entity) -> dict:
|
||||
# generic field dump: split-spawned small slimes have no catalog template
|
||||
kind = "enemy" if isinstance(entity, Enemy) else "item"
|
||||
data: dict = {"kind": kind}
|
||||
for field_def in fields(entity):
|
||||
value = getattr(entity, field_def.name)
|
||||
data[field_def.name] = list(value) if isinstance(value, tuple) else value
|
||||
return data
|
||||
|
||||
|
||||
def _entity_from_dict(data: dict) -> Entity:
|
||||
kind = data.get("kind")
|
||||
entity_class = (
|
||||
{"enemy": Enemy, "item": Item}.get(kind) if isinstance(kind, str) else None
|
||||
)
|
||||
if entity_class is None:
|
||||
raise ValueError(f"unknown entity kind: {kind!r}")
|
||||
kwargs = {}
|
||||
for field_def in fields(entity_class):
|
||||
if field_def.name not in data:
|
||||
continue
|
||||
value = data[field_def.name]
|
||||
if field_def.name in _TUPLE_FIELDS and value is not None:
|
||||
value = tuple(value)
|
||||
kwargs[field_def.name] = value
|
||||
return entity_class(**kwargs)
|
||||
|
||||
|
||||
def _effect_to_dict(effect: TimedEffect) -> dict:
|
||||
return {field_def.name: getattr(effect, field_def.name) for field_def in fields(effect)}
|
||||
|
||||
|
||||
def _player_to_dict(player: Player) -> dict:
|
||||
data: dict = {}
|
||||
for field_def in fields(player):
|
||||
name = field_def.name
|
||||
value = getattr(player, name)
|
||||
if name == "inventory":
|
||||
value = [_entity_to_dict(item) for item in value]
|
||||
elif name in _EQUIP_SLOTS:
|
||||
value = _entity_to_dict(value) if value is not None else None
|
||||
elif name == "effects":
|
||||
value = [_effect_to_dict(effect) for effect in value]
|
||||
data[name] = value
|
||||
return data
|
||||
|
||||
|
||||
def _player_from_dict(data: dict) -> Player:
|
||||
payload = dict(data)
|
||||
payload["inventory"] = [_entity_from_dict(item) for item in payload.get("inventory", [])]
|
||||
for slot in _EQUIP_SLOTS:
|
||||
held = payload.get(slot)
|
||||
payload[slot] = _entity_from_dict(held) if held is not None else None
|
||||
payload["effects"] = [TimedEffect(**effect) for effect in payload.get("effects", [])]
|
||||
return Player(**payload)
|
||||
|
||||
|
||||
def _map_to_dict(game_map: GameMap) -> dict:
|
||||
return {
|
||||
"width": game_map.width,
|
||||
"height": game_map.height,
|
||||
"tiles": _grid_to_text(game_map.tiles),
|
||||
"explored": _grid_to_text(game_map.explored),
|
||||
"rooms": [[room.x, room.y, room.width, room.height] for room in game_map.rooms],
|
||||
"junctions": [
|
||||
[junction.x, junction.y, junction.width, junction.height]
|
||||
for junction in game_map.junctions
|
||||
],
|
||||
"corridors": [[list(point) for point in path] for path in game_map.corridors],
|
||||
"entities": [_entity_to_dict(entity) for entity in game_map.entities],
|
||||
"stairs_down": (
|
||||
list(game_map.stairs_down) if game_map.stairs_down is not None else None
|
||||
),
|
||||
"spawn": list(game_map.spawn),
|
||||
"floor_index": game_map.floor_index,
|
||||
}
|
||||
|
||||
|
||||
def _map_from_dict(data: dict) -> GameMap:
|
||||
width = data["width"]
|
||||
height = data["height"]
|
||||
return GameMap(
|
||||
width=width,
|
||||
height=height,
|
||||
tiles=_text_to_grid(data["tiles"], width, height),
|
||||
rooms=[Rect(*room) for room in data["rooms"]],
|
||||
junctions=[Rect(*junction) for junction in data["junctions"]],
|
||||
corridors=[[(x, y) for x, y in path] for path in data["corridors"]],
|
||||
explored=_text_to_grid(data["explored"], width, height),
|
||||
visible=_zero_grid(width, height),
|
||||
entities=[_entity_from_dict(entity) for entity in data["entities"]],
|
||||
stairs_down=(
|
||||
tuple(data["stairs_down"]) if data["stairs_down"] is not None else None
|
||||
),
|
||||
spawn=tuple(data["spawn"]),
|
||||
floor_index=data["floor_index"],
|
||||
)
|
||||
|
||||
|
||||
def session_to_dict(session: GameSession) -> dict:
|
||||
"""The canonical JSON form of a run; the basis of save/load equality."""
|
||||
return {
|
||||
"version": SAVE_VERSION,
|
||||
"player": _player_to_dict(session.player),
|
||||
"dungeon": [_map_to_dict(game_map) for game_map in session.dungeon],
|
||||
"current_floor": session.current_floor,
|
||||
"log": list(session.log),
|
||||
"turn": session.turn,
|
||||
"state": session.state,
|
||||
"overlay": session.overlay,
|
||||
"overlay_index": session.overlay_index,
|
||||
"menu_index": session.menu_index,
|
||||
"save_available": session.save_available,
|
||||
}
|
||||
|
||||
|
||||
def session_from_dict(data: dict) -> GameSession:
|
||||
"""Rebuild a session; trusting callers go through load_session instead."""
|
||||
session = GameSession(
|
||||
player=_player_from_dict(data["player"]),
|
||||
dungeon=[_map_from_dict(game_map) for game_map in data["dungeon"]],
|
||||
)
|
||||
session.current_floor = data["current_floor"]
|
||||
if not 0 <= session.current_floor < len(session.dungeon):
|
||||
raise ValueError("current floor outside the dungeon")
|
||||
session.log = [str(line) for line in data["log"]]
|
||||
session.turn = data["turn"]
|
||||
session.state = data["state"]
|
||||
session.overlay = data["overlay"]
|
||||
session.overlay_index = data["overlay_index"]
|
||||
session.menu_index = data["menu_index"]
|
||||
session.save_available = data["save_available"]
|
||||
session.refresh_fov() # visible is derived, never serialized
|
||||
return session
|
||||
|
||||
|
||||
def save_session(session: GameSession, path: Path | str) -> bool:
|
||||
"""Write the run atomically; failures surface as False, never exceptions."""
|
||||
try:
|
||||
payload = json.dumps(session_to_dict(session), separators=(",", ":"))
|
||||
target = Path(path)
|
||||
temporary = target.with_name(target.name + ".tmp")
|
||||
temporary.write_text(payload, encoding="utf-8")
|
||||
temporary.replace(target)
|
||||
return True
|
||||
except (OSError, TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def load_session(path: Path | str) -> GameSession | None:
|
||||
"""Restore a run; a missing or damaged file yields None."""
|
||||
try:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if not isinstance(data, dict) or data.get("version") != SAVE_VERSION:
|
||||
return None
|
||||
return session_from_dict(data)
|
||||
except (OSError, ValueError, TypeError, KeyError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def save_exists(path: Path | str) -> bool:
|
||||
return Path(path).is_file()
|
||||
|
||||
|
||||
def delete_save(path: Path | str) -> bool:
|
||||
target = Path(path)
|
||||
if not target.is_file():
|
||||
return False
|
||||
try:
|
||||
target.unlink()
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def sessions_equal(left: GameSession, right: GameSession) -> bool:
|
||||
return session_to_dict(left) == session_to_dict(right)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run from the repo root: python -m engine.serializers
|
||||
import random
|
||||
import tempfile
|
||||
|
||||
import engine.actions as actions
|
||||
from data.items import spawn_item
|
||||
from entities.enemy import Enemy
|
||||
from engine.game_state import STATE_DEAD, new_game
|
||||
|
||||
random.seed(5)
|
||||
actions._rng = random.Random(5)
|
||||
|
||||
session = new_game(seed=5)
|
||||
player = session.player
|
||||
for key in (
|
||||
"hunters_bow",
|
||||
"chain_mail",
|
||||
"shoes_of_hermes",
|
||||
"strength_potion",
|
||||
"mapping_scroll",
|
||||
):
|
||||
player.add_item(spawn_item(key, 0, 0))
|
||||
|
||||
def held(key: str) -> Item:
|
||||
return next(item for item in player.inventory if item.key == key)
|
||||
|
||||
assert actions.equip(session, held("hunters_bow"))
|
||||
assert actions.equip(session, held("chain_mail"))
|
||||
assert actions.equip(session, held("shoes_of_hermes"))
|
||||
assert actions.quaff(session, held("strength_potion")) # leaves a live timer
|
||||
enemy = next(e for e in session.current_map.entities if isinstance(e, Enemy))
|
||||
enemy.hp -= 3 # non-pristine entity state must survive the round trip
|
||||
enemy.last_known_position = (enemy.x + 1, enemy.y)
|
||||
session.turn += 7
|
||||
stairs = session.current_map.stairs_down
|
||||
assert stairs is not None
|
||||
player.x, player.y = stairs
|
||||
assert actions.descend(session) and session.current_floor == 1
|
||||
assert not actions.descend(session) # not standing on the new floor's stairs
|
||||
assert actions.open_overlay(session, "inventory")
|
||||
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
from pathlib import Path as _Path
|
||||
|
||||
save_path = _Path(folder) / "save.json"
|
||||
assert not save_exists(save_path)
|
||||
assert save_session(session, save_path) and save_exists(save_path)
|
||||
assert not save_session(session, _Path(folder) / "no" / "such" / "save.json")
|
||||
|
||||
loaded = load_session(save_path)
|
||||
assert loaded is not None and sessions_equal(session, loaded)
|
||||
assert len(loaded.dungeon) == 10 and loaded.current_floor == 1
|
||||
assert loaded.player.equipped_weapon.ranged_range == 8
|
||||
assert loaded.player.equipped_armor.armor_bonus == 4
|
||||
assert loaded.player.equipped_boots.enables_running
|
||||
assert loaded.player.effects and loaded.player.effects[0].turns_left > 0
|
||||
assert loaded.overlay == "inventory" and loaded.turn == session.turn
|
||||
assert loaded.current_map.visible[loaded.player.y][loaded.player.x]
|
||||
restored = next(e for e in loaded.dungeon[0].entities if isinstance(e, Enemy))
|
||||
assert restored.hp == enemy.hp
|
||||
assert restored.last_known_position == enemy.last_known_position
|
||||
|
||||
loaded.state = STATE_DEAD
|
||||
assert actions.enforce_permadeath(loaded, save_path)
|
||||
assert not save_exists(save_path) and not loaded.save_available
|
||||
assert not actions.enforce_permadeath(loaded, save_path)
|
||||
|
||||
save_path.write_text("{ broken json", encoding="utf-8")
|
||||
assert load_session(save_path) is None
|
||||
save_path.write_text('{"version": 99}', encoding="utf-8")
|
||||
assert load_session(save_path) is None
|
||||
save_path.unlink()
|
||||
assert load_session(save_path) is None
|
||||
print("serializers self-check: PASS")
|
||||
Reference in new issue
Block a user