Files
2026-08-16 19:10:31 +02:00

261 lines
9.4 KiB
Python

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")