Files
agentic-labs-challenge/underdepths/engine/actions.py
T
2026-08-13 07:28:55 +02:00

264 lines
8.0 KiB
Python

"""Player actions: pure functions that mutate a GameSession and log.
Each turn-costing action resolves its effect, then calls _end_turn which ticks
the player's effect timers, advances the turn counter, runs every living enemy's
turn (the entity list is snapshotted first so slime splits / deaths can't corrupt
the loop), recomputes FOV, and flips the session to "dead" or "victory" when
warranted. Actions never raise on a valid game state.
"""
from __future__ import annotations
import random
from typing import TYPE_CHECKING
from data.constants import BOSS_FLOOR, LOG_MAX, STRENGTH_POWER_BONUS
from engine.combat import attack
from engine.map_gen import walkable
from entities.enemy import Enemy
from entities.item import Item
from ai.behaviors import enemy_turn, on_enemy_death
if TYPE_CHECKING:
from engine.game_state import GameSession
from engine.map_gen import GameMap
_DRAGON_NAME = "Ancient Dragon"
def _enemy_at(cmap: GameMap, x: int, y: int) -> Enemy | None:
for e in cmap.entities:
if isinstance(e, Enemy) and e.hp > 0 and e.x == x and e.y == y:
return e
return None
def _remove_entity(cmap: GameMap, entity: object) -> None:
ents = cmap.entities
for i, e in enumerate(ents):
if e is entity:
del ents[i]
return
def _trim_log(sess: GameSession) -> None:
if len(sess.log) > LOG_MAX:
del sess.log[: len(sess.log) - LOG_MAX]
def _check_player_death(sess: GameSession) -> None:
if sess.player.hp <= 0:
sess.player.hp = 0
sess.state = "dead"
sess.log.append("You have died.")
def _check_victory(sess: GameSession) -> None:
# The dragon only ever exists on the boss floor; once it is gone there is
# nothing left to conquer, so the empty boss floor means victory.
if sess.current_floor != BOSS_FLOOR:
return
if sess.state != "playing":
return
dragon_alive = any(
isinstance(e, Enemy) and e.name == _DRAGON_NAME and e.hp > 0
for e in sess.current_map.entities
)
if not dragon_alive:
sess.state = "victory"
sess.log.append("You slew the Ancient Dragon! You conquer the Underdepths!")
def _run_enemies(sess: GameSession) -> None:
cmap = sess.current_map
enemies = [e for e in cmap.entities if isinstance(e, Enemy) and e.hp > 0]
for e in enemies:
if sess.state != "playing":
break
if e.hp <= 0:
continue
enemy_turn(e, sess)
def _end_turn(sess: GameSession) -> None:
if sess.state != "playing":
return
sess.player.tick_timers(sess.log)
sess.turn += 1
_run_enemies(sess)
sess.recompute_fov()
_check_player_death(sess)
_check_victory(sess)
_trim_log(sess)
def try_move(sess: GameSession, dx: int, dy: int) -> None:
if sess.state != "playing":
return
p = sess.player
cmap = sess.current_map
nx, ny = p.x + dx, p.y + dy
target = _enemy_at(cmap, nx, ny)
if target is not None:
attack(p, target, sess.log)
if target.hp <= 0:
p.gain_xp(target.xp_value, sess.log)
_remove_entity(cmap, target)
on_enemy_death(target, sess)
_end_turn(sess)
return
if walkable(cmap, nx, ny):
p.x, p.y = nx, ny
_end_turn(sess)
return
# Bumping a wall costs no turn.
def pickup(sess: GameSession) -> None:
if sess.state != "playing":
return
p = sess.player
cmap = sess.current_map
for e in list(cmap.entities):
if isinstance(e, Item) and e.x == p.x and e.y == p.y:
_remove_entity(cmap, e)
p.inventory.append(e)
sess.log.append(f"You pick up the {e.name}.")
_end_turn(sess)
return
sess.log.append("There is nothing here to pick up.")
def descend(sess: GameSession) -> None:
if sess.state != "playing":
return
cmap = sess.current_map
p = sess.player
if cmap.stairs_down is None:
sess.log.append("There are no stairs here.")
return
if (p.x, p.y) != cmap.stairs_down:
sess.log.append("You must stand on the stairs to descend.")
return
if sess.current_floor >= len(sess.dungeon) - 1:
return
sess.current_floor += 1
nxt = sess.current_map
if nxt.rooms:
sx, sy = nxt.rooms[0].center()
else:
tile = next(
((x, y) for y in range(nxt.height) for x in range(nxt.width) if nxt.tiles[y][x] == 1),
(p.x, p.y),
)
sx, sy = tile
p.x, p.y = sx, sy
sess.log.append(f"You descend to floor {sess.current_floor + 1}.")
# Arriving on a fresh floor is a free look: tick timers + advance the turn
# but do not let enemies act before the player has moved.
sess.player.tick_timers(sess.log)
sess.turn += 1
sess.recompute_fov()
_check_player_death(sess)
_trim_log(sess)
def use_item(sess: GameSession, index: int) -> None:
if sess.state != "playing":
return
p = sess.player
if index < 0 or index >= len(p.inventory):
sess.log.append("You have no such item.")
return
item = p.inventory[index]
kind, sub = item.kind, item.sub
if kind == "potion":
if sub == "healing":
amount = min(item.heal, p.max_hp - p.hp)
p.hp += amount
sess.log.append(f"You quaff the {item.name} and recover {amount} HP.")
elif sub == "strength":
p.timers["strength"] = item.duration
sess.log.append(
f"A surge of strength courses through you! (+{STRENGTH_POWER_BONUS} power for {item.duration} turns)"
)
elif sub == "invisibility":
p.timers["invisibility"] = item.duration
sess.log.append(f"You drink the {item.name} and fade from sight.")
else:
sess.log.append(f"Nothing happens with the {item.name}.")
return
elif kind == "scroll":
if sub == "fireball":
_fireball(sess, p.x, p.y, item.damage, item.radius)
elif sub == "teleport":
_teleport(sess)
elif sub == "mapping":
for row in sess.current_map.explored:
for i in range(len(row)):
row[i] = True
sess.log.append("The scroll reveals the entire floor!")
else:
sess.log.append(f"Nothing happens with the {item.name}.")
return
else:
sess.log.append(f"You can't quaff or read the {item.name}.")
return
p.inventory.pop(index)
_end_turn(sess)
def equip(sess: GameSession, index: int) -> None:
if sess.state != "playing":
return
p = sess.player
if index < 0 or index >= len(p.inventory):
sess.log.append("You have no such item.")
return
item = p.inventory[index]
if item.kind not in ("weapon", "armor"):
sess.log.append(f"You can't equip the {item.name}.")
return
p.inventory.pop(index)
p.equip_item(item)
sess.log.append(f"You equip the {item.name}.")
_end_turn(sess)
def _fireball(sess: GameSession, cx: int, cy: int, damage: int, radius: int) -> None:
sess.log.append("A fireball erupts!")
cmap = sess.current_map
hit_any = False
for e in list(cmap.entities):
if isinstance(e, Enemy) and e.hp > 0 and max(abs(e.x - cx), abs(e.y - cy)) <= radius:
e.hp -= damage
sess.log.append(f"The fireball burns the {e.name} for {damage} damage.")
hit_any = True
if e.hp <= 0:
sess.player.gain_xp(e.xp_value, sess.log)
_remove_entity(cmap, e)
on_enemy_death(e, sess)
if not hit_any:
sess.log.append("The flames find no target.")
def _teleport(sess: GameSession) -> None:
cmap = sess.current_map
tiles = [
(x, y)
for y in range(cmap.height)
for x in range(cmap.width)
if cmap.tiles[y][x] == 1
]
if not tiles:
sess.log.append("The scroll fizzles.")
return
nx, ny = random.choice(tiles)
sess.player.x, sess.player.y = nx, ny
sess.log.append("You teleport across the floor!")