263 lines
9.4 KiB
Python
263 lines
9.4 KiB
Python
from __future__ import annotations
|
|
|
|
import random
|
|
from dataclasses import dataclass, field
|
|
|
|
from ai.behaviors import split_on_death, take_turn
|
|
from data.constants import (
|
|
FIREBALL_DAMAGE,
|
|
FIREBALL_RADIUS,
|
|
FINAL_FLOOR,
|
|
HEAL_AMOUNT,
|
|
INVISIBILITY_TURNS,
|
|
STRENGTH_BONUS,
|
|
STRENGTH_TURNS,
|
|
)
|
|
from data.items import ITEM_CATALOG
|
|
from engine.combat import attack, award_xp, log_message
|
|
from engine.fov import compute_fov
|
|
from engine.map_gen import GameMap, generate_map
|
|
from entities.enemy import Enemy
|
|
from entities.item import Item
|
|
from entities.player import Player
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class GameSession:
|
|
"""Single source of truth for all mutable state."""
|
|
|
|
player: Player
|
|
dungeon: list[GameMap]
|
|
current_floor: int
|
|
log: list[str] = field(default_factory=list)
|
|
turn: int = 0
|
|
state: str = "playing"
|
|
rng: random.Random = field(default_factory=random.Random)
|
|
|
|
@classmethod
|
|
def new_game(cls, seed: int | None = None) -> GameSession:
|
|
rng = random.Random(seed)
|
|
dungeon = [generate_map(floor_index=floor, seed=rng.randrange(2**32)) for floor in range(FINAL_FLOOR + 1)]
|
|
first = dungeon[0]
|
|
session = cls(
|
|
player=Player(x=first.spawn[0], y=first.spawn[1]),
|
|
dungeon=dungeon,
|
|
current_floor=0,
|
|
rng=rng,
|
|
)
|
|
session.update_fov()
|
|
log_message(session.log, "You descend into the Underdepths. Good luck.")
|
|
return session
|
|
|
|
@property
|
|
def current_map(self) -> GameMap:
|
|
return self.dungeon[self.current_floor]
|
|
|
|
def update_fov(self) -> None:
|
|
compute_fov(self.current_map, self.player.x, self.player.y)
|
|
|
|
def entity_at(self, x: int, y: int) -> Enemy | None:
|
|
return next(
|
|
(
|
|
entity
|
|
for entity in self.current_map.entities
|
|
if isinstance(entity, Enemy) and entity.alive and entity.position == (x, y)
|
|
),
|
|
None,
|
|
)
|
|
|
|
def items_at(self, x: int, y: int) -> list[Item]:
|
|
return [
|
|
entity
|
|
for entity in self.current_map.entities
|
|
if isinstance(entity, Item) and entity.position == (x, y)
|
|
]
|
|
|
|
# -- player actions -------------------------------------------------
|
|
|
|
def player_move_or_attack(self, dx: int, dy: int) -> None:
|
|
if self.state != "playing":
|
|
return
|
|
target = self.player.x + dx, self.player.y + dy
|
|
enemy = self.entity_at(*target)
|
|
if enemy is not None:
|
|
died = attack(self.player, enemy, self.log, rng=self.rng)
|
|
if died:
|
|
self._on_enemy_death(enemy)
|
|
elif self.current_map.is_walkable(*target):
|
|
self.player.move(dx, dy)
|
|
self.end_turn()
|
|
|
|
def pickup(self) -> bool:
|
|
items = self.items_at(self.player.x, self.player.y)
|
|
if not items:
|
|
return False
|
|
item = items[0]
|
|
self.current_map.entities.remove(item)
|
|
item.x, item.y = 0, 0
|
|
self.player.inventory.append(item)
|
|
log_message(self.log, f"You pick up the {item.name}.")
|
|
return True
|
|
|
|
def equip(self, item: Item) -> bool:
|
|
if item not in self.player.inventory:
|
|
return False
|
|
if item.category == "weapon":
|
|
old = self.player.equipped_weapon
|
|
self.player.equipped_weapon = item
|
|
elif item.category == "armor":
|
|
old = self.player.equipped_armor
|
|
self.player.equipped_armor = item
|
|
else:
|
|
return False
|
|
self.player.inventory.remove(item)
|
|
item.x, item.y = 0, 0
|
|
if old is not None:
|
|
self.player.inventory.append(old)
|
|
log_message(self.log, f"You equip the {item.name}.")
|
|
return True
|
|
|
|
def quaff(self, item: Item) -> bool:
|
|
if item.category != "potion" or item not in self.player.inventory:
|
|
return False
|
|
player = self.player
|
|
if item.effect == "heal":
|
|
healed = player.heal(HEAL_AMOUNT)
|
|
log_message(self.log, f"You quaff the {item.name}. You recover {healed} HP.")
|
|
elif item.effect == "strength":
|
|
player.strength_turns = STRENGTH_TURNS
|
|
log_message(
|
|
self.log,
|
|
f"You quaff the {item.name}. Your power surges (+{STRENGTH_BONUS} for {STRENGTH_TURNS} turns).",
|
|
)
|
|
elif item.effect == "invisibility":
|
|
player.invisible_turns = INVISIBILITY_TURNS
|
|
log_message(
|
|
self.log,
|
|
f"You drink the {item.name} and fade from sight for {INVISIBILITY_TURNS} turns.",
|
|
)
|
|
else:
|
|
return False
|
|
player.inventory.remove(item)
|
|
self.end_turn()
|
|
return True
|
|
|
|
def read_scroll(self, item: Item) -> bool:
|
|
if item.category != "scroll" or item not in self.player.inventory:
|
|
return False
|
|
effect = item.effect
|
|
player = self.player
|
|
game_map = self.current_map
|
|
if effect == "fireball":
|
|
log_message(self.log, "The scroll erupts in a ball of flame!")
|
|
for entity in list(game_map.entities):
|
|
if not isinstance(entity, Enemy) or not entity.alive:
|
|
continue
|
|
dist = ((entity.x - player.x) ** 2 + (entity.y - player.y) ** 2) ** 0.5
|
|
if dist > FIREBALL_RADIUS:
|
|
continue
|
|
entity.hp -= FIREBALL_DAMAGE
|
|
log_message(self.log, f"The {entity.name} is scorched for {FIREBALL_DAMAGE} damage!")
|
|
if entity.hp <= 0:
|
|
log_message(
|
|
self.log, f"You defeated the {entity.name}! (+{entity.xp_reward} XP)"
|
|
)
|
|
award_xp(player, entity.xp_reward, self.log)
|
|
self._on_enemy_death(entity)
|
|
elif effect == "teleport":
|
|
options = [
|
|
(x, y)
|
|
for y in range(game_map.height)
|
|
for x in range(game_map.width)
|
|
if game_map.is_walkable(x, y)
|
|
and self.entity_at(x, y) is None
|
|
and (x, y) != player.position
|
|
]
|
|
if options:
|
|
player.x, player.y = self.rng.choice(options)
|
|
log_message(self.log, "The world twists — you blink to a distant place.")
|
|
elif effect == "mapping":
|
|
for row in game_map.explored:
|
|
for i in range(len(row)):
|
|
row[i] = 1
|
|
log_message(self.log, "Knowledge of the floor floods your mind.")
|
|
else:
|
|
return False
|
|
player.inventory.remove(item)
|
|
self.end_turn()
|
|
return True
|
|
|
|
def descend(self) -> bool:
|
|
if self.current_map.stairs_down != self.player.position:
|
|
return False
|
|
if self.current_floor >= FINAL_FLOOR:
|
|
return False
|
|
self.current_floor += 1
|
|
spawn = self.current_map.spawn
|
|
self.player.x, self.player.y = spawn
|
|
log_message(self.log, f"You descend to floor {self.current_floor + 1}.")
|
|
self.end_turn()
|
|
return True
|
|
|
|
# -- turn engine -----------------------------------------------------
|
|
|
|
def end_turn(self) -> None:
|
|
if self.state != "playing":
|
|
return
|
|
self.turn += 1
|
|
if self.player.strength_turns > 0:
|
|
self.player.strength_turns -= 1
|
|
if self.player.invisible_turns > 0:
|
|
self.player.invisible_turns -= 1
|
|
for enemy in [e for e in self.current_map.entities if isinstance(e, Enemy) and e.alive]:
|
|
take_turn(enemy, self.player, self.current_map, self.turn, self.log, rng=self.rng)
|
|
if self.player.hp <= 0:
|
|
self.state = "dead"
|
|
log_message(self.log, "You die...")
|
|
self.update_fov()
|
|
|
|
def _on_enemy_death(self, enemy: Enemy) -> None:
|
|
self.current_map.entities.remove(enemy)
|
|
copies = split_on_death(enemy)
|
|
candidates = [
|
|
copy.position for copy in copies
|
|
] + [
|
|
enemy.position,
|
|
(enemy.x, enemy.y - 1),
|
|
(enemy.x, enemy.y + 1),
|
|
(enemy.x - 1, enemy.y - 1),
|
|
(enemy.x + 1, enemy.y - 1),
|
|
(enemy.x - 1, enemy.y + 1),
|
|
(enemy.x + 1, enemy.y + 1),
|
|
]
|
|
free = [
|
|
position for position in dict.fromkeys(candidates)
|
|
if self.current_map.is_walkable(*position) and self.entity_at(*position) is None
|
|
]
|
|
for copy, position in zip(copies, free):
|
|
copy.x, copy.y = position
|
|
self.current_map.entities.append(copy)
|
|
if copies and free:
|
|
log_message(self.log, f"The {enemy.name} splits into {min(len(copies), len(free))}!")
|
|
if enemy.key == "ancient_dragon":
|
|
self.state = "victory"
|
|
log_message(self.log, "You slew the Ancient Dragon! You conquered Underdepths.")
|
|
|
|
|
|
def find_heavy_weapon(dungeon: list[GameMap]) -> Item | None:
|
|
"""First Battle Axe / War Hammer placed anywhere in the dungeon floors 0-8."""
|
|
for game_map in dungeon[:FINAL_FLOOR]:
|
|
for entity in game_map.entities:
|
|
if isinstance(entity, Item) and entity.key in ("battle_axe", "war_hammer"):
|
|
return entity
|
|
return None
|
|
|
|
|
|
if __name__ == "__main__":
|
|
session = GameSession.new_game(seed=1)
|
|
assert session.state == "playing"
|
|
assert len(session.dungeon) == 10
|
|
session.player_move_or_attack(0, 0) # bump into nothing: still a turn
|
|
assert session.turn == 1
|
|
print("game_state self-check: PASS")
|