257 lines
8.9 KiB
Python
257 lines
8.9 KiB
Python
"""Gameplay actions: pure functions that mutate a GameSession (plan.md §6, §9).
|
|
|
|
`try_move` is the turn driver — a successful move or attack advances the turn,
|
|
runs enemy AI, recomputes FOV, ticks effect timers, and checks for death.
|
|
`pickup` / `descend` / `use_item` / `equip` are resolution actions; they log and
|
|
mutate but leave turn advancement to the caller so item use stays deterministic
|
|
(a potion must not let an enemy sneak in a hit between quaff and the HP check).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from data import constants as C
|
|
from ai.behaviors import on_death, take_enemy_turn
|
|
from engine.combat import attack
|
|
from engine import game_state
|
|
from engine.game_state import recompute_fov
|
|
from engine.map_gen import is_walkable
|
|
from entities.enemy import Enemy
|
|
from entities.item import Item
|
|
from entities.player import Effect
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Movement / melee
|
|
# --------------------------------------------------------------------------- #
|
|
def try_move(session, dx: int, dy: int) -> bool:
|
|
"""Move the player by (dx, dy) or melee an enemy there. Returns whether the
|
|
player acted (and thus a turn elapsed)."""
|
|
player = session.player
|
|
floor = session.dungeon[session.current_floor]
|
|
nx, ny = player.x + dx, player.y + dy
|
|
|
|
if not (0 <= nx < floor.width and 0 <= ny < floor.height):
|
|
return False
|
|
if dx or dy:
|
|
player.facing = _facing(dx, dy)
|
|
|
|
target = _enemy_at(floor, nx, ny)
|
|
if target is not None:
|
|
res = attack(player, target, rng=session.rng, log=session.log)
|
|
if res["killed"]:
|
|
on_death(target, session)
|
|
_end_turn(session)
|
|
return True
|
|
|
|
if floor.tiles[ny][nx] == 1 and not _blocked_at(floor, nx, ny):
|
|
player.x, player.y = nx, ny
|
|
_end_turn(session)
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
def _end_turn(session) -> None:
|
|
"""One turn elapsed: counter up, FOV, enemy turns, effect timers, death."""
|
|
session.turn += 1
|
|
recompute_fov(session)
|
|
_enemy_turns(session)
|
|
_tick_effects(session)
|
|
if session.player.hp <= 0 and session.state == "playing":
|
|
game_state.mark_dead(session)
|
|
session.log.append("You have died.")
|
|
|
|
|
|
def _enemy_turns(session) -> None:
|
|
floor = session.dungeon[session.current_floor]
|
|
for e in list(floor.entities):
|
|
if isinstance(e, Enemy) and e.hp > 0:
|
|
take_enemy_turn(e, session, rng=session.rng)
|
|
if session.player.hp <= 0:
|
|
return
|
|
|
|
|
|
def _tick_effects(session) -> None:
|
|
player = session.player
|
|
if not player.effects:
|
|
return
|
|
remaining: list = []
|
|
for eff in player.effects:
|
|
eff.duration -= 1
|
|
if eff.duration > 0:
|
|
remaining.append(eff)
|
|
elif eff.kind == "invisibility":
|
|
player.invisible = False
|
|
session.log.append("You fade back into view.")
|
|
player.effects = remaining
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Pickup / descend
|
|
# --------------------------------------------------------------------------- #
|
|
def pickup(session) -> bool:
|
|
"""Move the item under the player into inventory. False if nothing there."""
|
|
player = session.player
|
|
floor = session.dungeon[session.current_floor]
|
|
for e in list(floor.entities):
|
|
if isinstance(e, Item) and e.x == player.x and e.y == player.y:
|
|
floor.entities.remove(e)
|
|
player.inventory.append(e)
|
|
session.log.append(f"You pick up the {e.name}.")
|
|
return True
|
|
session.log.append("There is nothing here to pick up.")
|
|
return False
|
|
|
|
|
|
def descend(session) -> bool:
|
|
"""Descend the stairs the player stands on. False if not on stairs / last floor."""
|
|
player = session.player
|
|
floor = session.dungeon[session.current_floor]
|
|
if (player.x, player.y) != floor.stairs_down:
|
|
session.log.append("There are no stairs here.")
|
|
return False
|
|
if session.current_floor >= C.FLOORS - 1:
|
|
return False # no descent past the boss floor
|
|
|
|
session.current_floor += 1
|
|
new_floor = session.dungeon[session.current_floor]
|
|
spawn = new_floor.rooms[0].center if new_floor.rooms else _first_walkable(new_floor)
|
|
if not is_walkable(new_floor, *spawn):
|
|
spawn = _first_walkable(new_floor)
|
|
player.x, player.y = spawn
|
|
recompute_fov(session)
|
|
session.log.append(f"You descend to floor {session.current_floor + 1}.")
|
|
return True
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Use / equip
|
|
# --------------------------------------------------------------------------- #
|
|
def use_item(session, item) -> None:
|
|
"""Apply a potion/scroll, or equip a weapon/armor. Consumes consumables."""
|
|
if item.item_type == "potion":
|
|
_use_potion(session, item)
|
|
_consume(session, item)
|
|
elif item.item_type == "scroll":
|
|
_use_scroll(session, item)
|
|
_consume(session, item)
|
|
elif item.item_type in ("weapon", "armor"):
|
|
equip(session, item)
|
|
else:
|
|
session.log.append(f"You can't use the {item.name}.")
|
|
|
|
|
|
def equip(session, item) -> None:
|
|
"""Place an equippable in its slot; the previous item returns to inventory."""
|
|
player = session.player
|
|
if item.item_type not in ("weapon", "armor"):
|
|
session.log.append(f"You can't equip the {item.name}.")
|
|
return
|
|
slot = item.item_type
|
|
old = player.equipped.get(slot)
|
|
player.equipped[slot] = item
|
|
if item in player.inventory:
|
|
player.inventory.remove(item)
|
|
if old is not None:
|
|
player.inventory.append(old)
|
|
session.log.append(f"You unequip the {old.name}.")
|
|
session.log.append(f"You equip the {item.name}.")
|
|
|
|
|
|
def _use_potion(session, item) -> None:
|
|
player = session.player
|
|
if item.subtype == "healing":
|
|
amount = item.stats.get("heal", 30)
|
|
player.hp = min(player.max_hp, player.hp + amount)
|
|
session.log.append(f"You quaff a Healing Potion and recover {amount} HP.")
|
|
elif item.subtype == "strength":
|
|
player.effects.append(Effect(
|
|
kind="strength",
|
|
power=item.stats.get("power", 5),
|
|
duration=item.stats.get("duration", 20),
|
|
))
|
|
session.log.append("Your muscles surge! (+5 power for 20 turns)")
|
|
elif item.subtype == "invisibility":
|
|
player.effects.append(Effect(
|
|
kind="invisibility",
|
|
duration=item.stats.get("duration", 15),
|
|
))
|
|
player.invisible = True
|
|
session.log.append("You fade from sight!")
|
|
|
|
|
|
def _use_scroll(session, item) -> None:
|
|
player = session.player
|
|
floor = session.dungeon[session.current_floor]
|
|
if item.subtype == "fireball":
|
|
radius = item.stats.get("radius", 3)
|
|
dmg = item.stats.get("damage", 20)
|
|
hit = [e for e in floor.entities
|
|
if isinstance(e, Enemy)
|
|
and max(abs(e.x - player.x), abs(e.y - player.y)) <= radius]
|
|
for e in hit:
|
|
e.hp -= dmg
|
|
session.log.append(f"The fireball erupts! {len(hit)} foe(s) burn for {dmg} damage.")
|
|
for e in hit:
|
|
if e.hp <= 0:
|
|
on_death(e, session)
|
|
elif item.subtype == "teleport":
|
|
targets = [
|
|
(x, y) for y in range(floor.height) for x in range(floor.width)
|
|
if floor.tiles[y][x] == 1
|
|
and (x, y) != (player.x, player.y)
|
|
and not _blocked_at(floor, x, y)
|
|
]
|
|
if targets:
|
|
player.x, player.y = session.rng.choice(targets)
|
|
recompute_fov(session)
|
|
session.log.append("The world blurs — you teleport across the floor!")
|
|
elif item.subtype == "mapping":
|
|
for y in range(floor.height):
|
|
for x in range(floor.width):
|
|
if floor.tiles[y][x] == 1:
|
|
floor.explored[y][x] = True
|
|
session.log.append("A complete map of this floor floods your mind!")
|
|
|
|
|
|
def _consume(session, item) -> None:
|
|
if item in session.player.inventory:
|
|
session.player.inventory.remove(item)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# helpers
|
|
# --------------------------------------------------------------------------- #
|
|
def _enemy_at(floor, x: int, y: int):
|
|
for e in floor.entities:
|
|
if isinstance(e, Enemy) and e.x == x and e.y == y:
|
|
return e
|
|
return None
|
|
|
|
|
|
def _blocked_at(floor, x: int, y: int) -> bool:
|
|
"""True if a blocking entity (enemy) occupies (x, y). Items never block."""
|
|
for e in floor.entities:
|
|
if isinstance(e, Enemy) and e.x == x and e.y == y:
|
|
return True
|
|
return False
|
|
|
|
|
|
def _first_walkable(game_map) -> tuple[int, int]:
|
|
for y in range(game_map.height):
|
|
for x in range(game_map.width):
|
|
if game_map.tiles[y][x] == 1:
|
|
return (x, y)
|
|
return (1, 1)
|
|
|
|
|
|
def _facing(dx: int, dy: int) -> str:
|
|
if dy < 0:
|
|
return "up"
|
|
if dy > 0:
|
|
return "down"
|
|
if dx < 0:
|
|
return "left"
|
|
if dx > 0:
|
|
return "right"
|
|
return "down"
|