(Underdepths): First pass
This commit is contained in:
31 files changed
+3554
No files matched your search
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
|
||||
from data.constants import (
|
||||
CRITICAL_DAMAGE_MULTIPLIER,
|
||||
GAME_STATE_DEAD,
|
||||
GAME_STATE_VICTORY,
|
||||
HIT_ACCURACY_SCALE,
|
||||
HIT_BASE_CHANCE,
|
||||
HIT_MAX_CHANCE,
|
||||
HIT_MIN_CHANCE,
|
||||
)
|
||||
from engine.game_state import GameSession, award_xp
|
||||
from entities.enemy import Enemy
|
||||
from entities.player import Player
|
||||
|
||||
Combatant = Player | Enemy
|
||||
|
||||
|
||||
def calculate_hit_chance(attacker: Combatant, defender: Combatant) -> float:
|
||||
chance = HIT_BASE_CHANCE + (attacker.accuracy - defender.evasion) * HIT_ACCURACY_SCALE
|
||||
return min(HIT_MAX_CHANCE, max(HIT_MIN_CHANCE, chance))
|
||||
|
||||
|
||||
def calculate_damage(
|
||||
attacker: Combatant,
|
||||
defender: Combatant,
|
||||
weapon_bonus: int = 0,
|
||||
critical: bool = False,
|
||||
) -> int:
|
||||
reduced = max(0, attacker.power + weapon_bonus - defender.armor)
|
||||
return reduced * (CRITICAL_DAMAGE_MULTIPLIER if critical else 1)
|
||||
|
||||
|
||||
def attack(
|
||||
session: GameSession,
|
||||
attacker: Combatant,
|
||||
defender: Combatant,
|
||||
weapon_bonus: int = 0,
|
||||
rng: random.Random | None = None,
|
||||
) -> int:
|
||||
roller = rng or session.roller()
|
||||
if roller.random() >= calculate_hit_chance(attacker, defender):
|
||||
if rng is None:
|
||||
session.save_roller(roller)
|
||||
session.add_message(f"{_subject(attacker)} {_verb(attacker, 'miss')} {_object(defender)}")
|
||||
return 0
|
||||
|
||||
critical = roller.random() < attacker.crit_chance
|
||||
if rng is None:
|
||||
session.save_roller(roller)
|
||||
damage = calculate_damage(attacker, defender, weapon_bonus, critical)
|
||||
defender.hp -= damage
|
||||
prefix = "Critical hit! " if critical else ""
|
||||
session.add_message(
|
||||
f"{prefix}{_subject(attacker)} {_verb(attacker, 'hit')} {_object(defender)} "
|
||||
f"for {damage} damage!"
|
||||
)
|
||||
if defender.hp <= 0:
|
||||
handle_death(session, defender)
|
||||
return damage
|
||||
|
||||
|
||||
def handle_death(session: GameSession, defender: Combatant) -> None:
|
||||
if isinstance(defender, Player):
|
||||
session.state = GAME_STATE_DEAD
|
||||
session.add_message("You died!")
|
||||
return
|
||||
|
||||
if defender in session.current_map.entities:
|
||||
session.current_map.entities.remove(defender)
|
||||
session.add_message(f"You defeated the {defender.name}! (+{defender.xp_reward} XP)")
|
||||
award_xp(session, defender.xp_reward)
|
||||
if defender.behavior == "split":
|
||||
from ai.behaviors import spawn_split_copies
|
||||
|
||||
spawn_split_copies(session, defender)
|
||||
if defender.name == "Ancient Dragon":
|
||||
session.state = GAME_STATE_VICTORY
|
||||
session.add_message("You slew the Ancient Dragon! You conquered Underdepths.")
|
||||
|
||||
|
||||
def _subject(combatant: Combatant) -> str:
|
||||
return "You" if isinstance(combatant, Player) else combatant.name
|
||||
|
||||
|
||||
def _object(combatant: Combatant) -> str:
|
||||
return "you" if isinstance(combatant, Player) else f"the {combatant.name}"
|
||||
|
||||
|
||||
def _verb(combatant: Combatant, verb: str) -> str:
|
||||
if isinstance(combatant, Player):
|
||||
return verb
|
||||
return "misses" if verb == "miss" else f"{verb}s"
|
||||
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from data.constants import FOV_RADIUS, TILE_FLOOR
|
||||
from engine.map_gen import GameMap
|
||||
|
||||
_OCTANTS: tuple[tuple[int, int, int, int], ...] = (
|
||||
(1, 0, 0, 1),
|
||||
(0, 1, 1, 0),
|
||||
(0, -1, 1, 0),
|
||||
(-1, 0, 0, 1),
|
||||
(-1, 0, 0, -1),
|
||||
(0, -1, -1, 0),
|
||||
(0, 1, -1, 0),
|
||||
(1, 0, 0, -1),
|
||||
)
|
||||
|
||||
|
||||
def compute_fov(
|
||||
game_map: GameMap,
|
||||
origin_x: int,
|
||||
origin_y: int,
|
||||
radius: int = FOV_RADIUS,
|
||||
) -> None:
|
||||
for index in range(len(game_map.visible)):
|
||||
game_map.visible[index] = 0
|
||||
if not game_map.in_bounds(origin_x, origin_y):
|
||||
return
|
||||
|
||||
_mark_visible(game_map, origin_x, origin_y)
|
||||
for xx, xy, yx, yy in _OCTANTS:
|
||||
_cast_light(game_map, origin_x, origin_y, 1, 1.0, 0.0, radius, xx, xy, yx, yy)
|
||||
|
||||
for index, visible in enumerate(game_map.visible):
|
||||
if visible:
|
||||
game_map.explored[index] = 1
|
||||
|
||||
|
||||
def _cast_light(
|
||||
game_map: GameMap,
|
||||
origin_x: int,
|
||||
origin_y: int,
|
||||
row: int,
|
||||
start_slope: float,
|
||||
end_slope: float,
|
||||
radius: int,
|
||||
xx: int,
|
||||
xy: int,
|
||||
yx: int,
|
||||
yy: int,
|
||||
) -> None:
|
||||
if start_slope < end_slope:
|
||||
return
|
||||
|
||||
radius_squared = radius * radius
|
||||
next_start_slope = start_slope
|
||||
for distance in range(row, radius + 1):
|
||||
blocked = False
|
||||
delta_y = -distance
|
||||
for delta_x in range(-distance, 1):
|
||||
map_x = origin_x + delta_x * xx + delta_y * xy
|
||||
map_y = origin_y + delta_x * yx + delta_y * yy
|
||||
left_slope = (delta_x - 0.5) / (delta_y + 0.5)
|
||||
right_slope = (delta_x + 0.5) / (delta_y - 0.5)
|
||||
|
||||
if start_slope < right_slope:
|
||||
continue
|
||||
if end_slope > left_slope:
|
||||
break
|
||||
|
||||
in_bounds = game_map.in_bounds(map_x, map_y)
|
||||
opaque = not in_bounds or game_map.tiles[game_map.index(map_x, map_y)] != TILE_FLOOR
|
||||
if in_bounds and delta_x * delta_x + delta_y * delta_y <= radius_squared:
|
||||
_mark_visible(game_map, map_x, map_y)
|
||||
|
||||
if blocked:
|
||||
if opaque:
|
||||
next_start_slope = right_slope
|
||||
continue
|
||||
blocked = False
|
||||
start_slope = next_start_slope
|
||||
elif opaque and distance < radius:
|
||||
blocked = True
|
||||
_cast_light(
|
||||
game_map,
|
||||
origin_x,
|
||||
origin_y,
|
||||
distance + 1,
|
||||
start_slope,
|
||||
left_slope,
|
||||
radius,
|
||||
xx,
|
||||
xy,
|
||||
yx,
|
||||
yy,
|
||||
)
|
||||
next_start_slope = right_slope
|
||||
|
||||
if blocked:
|
||||
break
|
||||
|
||||
|
||||
def _mark_visible(game_map: GameMap, x: int, y: int) -> None:
|
||||
game_map.visible[game_map.index(x, y)] = 1
|
||||
@@ -0,0 +1,274 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from ast import literal_eval
|
||||
from dataclasses import dataclass
|
||||
|
||||
from data.constants import (
|
||||
FLOOR_COUNT,
|
||||
GAME_STATE_PLAYING,
|
||||
INVENTORY_CAPACITY,
|
||||
LEVEL_HP_GAINS,
|
||||
LEVEL_POWER_GAINS,
|
||||
LEVEL_THRESHOLDS,
|
||||
MESSAGE_LOG_LIMIT,
|
||||
STRENGTH_BONUS,
|
||||
)
|
||||
from engine.fov import compute_fov
|
||||
from engine.map_gen import GameMap, generate_dungeon
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from entities.player import Player, create_player
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameSession:
|
||||
player: Player
|
||||
dungeon: list[GameMap]
|
||||
current_floor: int
|
||||
log: list[str]
|
||||
turn: int
|
||||
state: str
|
||||
rng_state: str
|
||||
|
||||
@property
|
||||
def current_map(self) -> GameMap:
|
||||
return self.dungeon[self.current_floor]
|
||||
|
||||
def add_message(self, message: str) -> None:
|
||||
self.log.append(message)
|
||||
del self.log[:-MESSAGE_LOG_LIMIT]
|
||||
|
||||
def roller(self) -> random.Random:
|
||||
roller = random.Random()
|
||||
roller.setstate(_decode_rng_state(self.rng_state))
|
||||
return roller
|
||||
|
||||
def save_roller(self, roller: random.Random) -> None:
|
||||
self.rng_state = _encode_rng_state(roller.getstate())
|
||||
|
||||
|
||||
def _encode_rng_state(state: object) -> str:
|
||||
return repr(state)
|
||||
|
||||
|
||||
def _decode_rng_state(encoded: str) -> tuple[object, ...]:
|
||||
return literal_eval(encoded)
|
||||
|
||||
def new_game(seed: int | None = None) -> GameSession:
|
||||
rng = random.Random(seed)
|
||||
dungeon = [generate_dungeon(floor_index, rng) for floor_index in range(FLOOR_COUNT)]
|
||||
spawn_x, spawn_y = dungeon[0].spawn
|
||||
session = GameSession(
|
||||
player=create_player(spawn_x, spawn_y),
|
||||
dungeon=dungeon,
|
||||
current_floor=0,
|
||||
log=["You enter the Underdepths."],
|
||||
turn=0,
|
||||
state=GAME_STATE_PLAYING,
|
||||
rng_state=_encode_rng_state(rng.getstate()),
|
||||
)
|
||||
compute_fov(session.current_map, spawn_x, spawn_y)
|
||||
return session
|
||||
|
||||
|
||||
def pickup_item(session: GameSession) -> bool:
|
||||
item = next(
|
||||
(
|
||||
entity
|
||||
for entity in session.current_map.entities
|
||||
if isinstance(entity, Item) and entity.position == session.player.position
|
||||
),
|
||||
None,
|
||||
)
|
||||
if item is None:
|
||||
session.add_message("There is nothing here to pick up.")
|
||||
return False
|
||||
if len(session.player.inventory) >= INVENTORY_CAPACITY:
|
||||
session.add_message("Your inventory is full.")
|
||||
return False
|
||||
session.current_map.entities.remove(item)
|
||||
session.player.inventory.append(item)
|
||||
session.add_message(f"You pick up the {item.name}.")
|
||||
return True
|
||||
|
||||
|
||||
def equip_item(session: GameSession, item: Item) -> bool:
|
||||
player = session.player
|
||||
if item not in player.inventory or item.category not in {"weapon", "armor"}:
|
||||
session.add_message(f"You cannot equip the {item.name}.")
|
||||
return False
|
||||
slot = "weapon" if item.category == "weapon" else "armor_item"
|
||||
current = getattr(player, slot)
|
||||
player.inventory.remove(item)
|
||||
if current is not None:
|
||||
_apply_equipment(player, current, -1)
|
||||
player.inventory.append(current)
|
||||
setattr(player, slot, item)
|
||||
_apply_equipment(player, item, 1)
|
||||
session.add_message(f"You equip the {item.name}.")
|
||||
return True
|
||||
|
||||
|
||||
def use_item(
|
||||
session: GameSession,
|
||||
item: Item,
|
||||
target: tuple[int, int] | None = None,
|
||||
rng: random.Random | None = None,
|
||||
) -> bool:
|
||||
if item not in session.player.inventory or item.category not in {"potion", "scroll"}:
|
||||
session.add_message(f"You cannot use the {item.name}.")
|
||||
return False
|
||||
if item.effect == "fireball" and target is None:
|
||||
session.add_message("Choose a target for the fireball.")
|
||||
return False
|
||||
|
||||
roller = rng or session.roller()
|
||||
used = _apply_item_effect(session, item, target, roller)
|
||||
if used:
|
||||
session.player.inventory.remove(item)
|
||||
if rng is None:
|
||||
session.save_roller(roller)
|
||||
return used
|
||||
|
||||
|
||||
def award_xp(session: GameSession, amount: int) -> int:
|
||||
player = session.player
|
||||
player.xp += amount
|
||||
levels_gained = 0
|
||||
while player.level <= len(LEVEL_THRESHOLDS) and player.xp >= LEVEL_THRESHOLDS[player.level - 1]:
|
||||
index = player.level - 1
|
||||
hp_gain = LEVEL_HP_GAINS[index]
|
||||
power_gain = LEVEL_POWER_GAINS[index]
|
||||
player.level += 1
|
||||
player.max_hp += hp_gain
|
||||
player.power += power_gain
|
||||
player.hp = player.max_hp
|
||||
levels_gained += 1
|
||||
session.add_message(
|
||||
f"You reach level {player.level}! (HP +{hp_gain}, Power +{power_gain})"
|
||||
)
|
||||
return levels_gained
|
||||
|
||||
|
||||
def tick_player_effects(session: GameSession) -> None:
|
||||
player = session.player
|
||||
if player.strength_turns > 0:
|
||||
player.strength_turns -= 1
|
||||
if player.strength_turns == 0:
|
||||
player.power -= STRENGTH_BONUS
|
||||
session.add_message("Your supernatural strength fades.")
|
||||
if player.invisibility_turns > 0:
|
||||
player.invisibility_turns -= 1
|
||||
if player.invisibility_turns == 0:
|
||||
session.add_message("You become visible again.")
|
||||
|
||||
|
||||
def descend_floor(session: GameSession) -> bool:
|
||||
if session.current_map.stairs_down is None or session.player.position != session.current_map.stairs_down:
|
||||
session.add_message("There are no stairs here.")
|
||||
return False
|
||||
if session.current_floor + 1 >= len(session.dungeon):
|
||||
session.add_message("There is nowhere deeper to descend.")
|
||||
return False
|
||||
session.current_floor += 1
|
||||
session.player.x, session.player.y = session.current_map.spawn
|
||||
session.add_message(f"You descend to floor {session.current_floor + 1}.")
|
||||
return True
|
||||
|
||||
|
||||
def _apply_equipment(player: Player, item: Item, direction: int) -> None:
|
||||
player.power += item.power_bonus * direction
|
||||
player.armor += item.armor_bonus * direction
|
||||
player.crit_chance += item.crit_bonus * direction
|
||||
player.evasion += item.evasion_bonus * direction
|
||||
|
||||
|
||||
def _apply_item_effect(
|
||||
session: GameSession,
|
||||
item: Item,
|
||||
target: tuple[int, int] | None,
|
||||
roller: random.Random,
|
||||
) -> bool:
|
||||
player = session.player
|
||||
if item.effect == "healing":
|
||||
healed = min(item.amount, player.max_hp - player.hp)
|
||||
player.hp += healed
|
||||
session.add_message(f"You drink the {item.name} and recover {healed} HP.")
|
||||
elif item.effect == "strength":
|
||||
if player.strength_turns == 0:
|
||||
player.power += item.amount
|
||||
player.strength_turns = item.duration
|
||||
session.add_message(f"Power surges through you for {item.duration} turns.")
|
||||
elif item.effect == "invisibility":
|
||||
player.invisibility_turns = item.duration
|
||||
session.add_message(f"You vanish from sight for {item.duration} turns.")
|
||||
elif item.effect == "fireball" and target is not None:
|
||||
_cast_fireball(session, target, item.amount, item.radius)
|
||||
elif item.effect == "teleport":
|
||||
occupied = {
|
||||
entity.position
|
||||
for entity in session.current_map.entities
|
||||
if isinstance(entity, Enemy) and entity.hp > 0
|
||||
}
|
||||
choices = [
|
||||
(x, y)
|
||||
for y in range(session.current_map.height)
|
||||
for x in range(session.current_map.width)
|
||||
if session.current_map.is_floor(x, y) and (x, y) not in occupied
|
||||
and (x, y) != player.position
|
||||
]
|
||||
if not choices:
|
||||
session.add_message("The teleport spell fizzles.")
|
||||
return False
|
||||
player.x, player.y = roller.choice(choices)
|
||||
session.add_message("Space twists and you teleport across the floor.")
|
||||
elif item.effect == "mapping":
|
||||
for index in range(len(session.current_map.explored)):
|
||||
session.current_map.explored[index] = 1
|
||||
session.add_message("The scroll reveals the entire floor.")
|
||||
else:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _cast_fireball(
|
||||
session: GameSession, target: tuple[int, int], damage: int, radius: int
|
||||
) -> None:
|
||||
from engine.combat import handle_death
|
||||
|
||||
session.add_message(f"A fireball explodes at {target}!")
|
||||
for entity in list(session.current_map.entities):
|
||||
if not isinstance(entity, Enemy) or entity.hp <= 0:
|
||||
continue
|
||||
dx = entity.x - target[0]
|
||||
dy = entity.y - target[1]
|
||||
if dx * dx + dy * dy > radius * radius:
|
||||
continue
|
||||
entity.hp -= damage
|
||||
session.add_message(f"The {entity.name} takes {damage} fire damage!")
|
||||
if entity.hp <= 0:
|
||||
handle_death(session, entity)
|
||||
|
||||
|
||||
def move_player(session: GameSession, dx: int, dy: int) -> bool:
|
||||
target = session.player.x + dx, session.player.y + dy
|
||||
enemy = next(
|
||||
(
|
||||
entity
|
||||
for entity in session.current_map.entities
|
||||
if isinstance(entity, Enemy) and entity.position == target and entity.hp > 0
|
||||
),
|
||||
None,
|
||||
)
|
||||
if enemy is not None:
|
||||
from engine.combat import attack
|
||||
|
||||
attack(session, session.player, enemy)
|
||||
elif session.current_map.is_floor(*target):
|
||||
session.player.x, session.player.y = target
|
||||
else:
|
||||
return False
|
||||
tick_player_effects(session)
|
||||
session.turn += 1
|
||||
return True
|
||||
@@ -0,0 +1,284 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from array import array
|
||||
from dataclasses import dataclass
|
||||
|
||||
from data.constants import (
|
||||
BSP_MAX_SPLITS,
|
||||
BSP_MIN_SPLITS,
|
||||
BOSS_ARENA_HEIGHT,
|
||||
BOSS_ARENA_WIDTH,
|
||||
BOSS_FLOOR,
|
||||
FLOOR_SPAWN_COUNTS,
|
||||
MAP_HEIGHT,
|
||||
MAP_WIDTH,
|
||||
ROOM_MARGIN,
|
||||
ROOM_MAX_HEIGHT,
|
||||
ROOM_MAX_WIDTH,
|
||||
ROOM_MIN_HEIGHT,
|
||||
ROOM_MIN_WIDTH,
|
||||
TILE_FLOOR,
|
||||
TILE_WALL,
|
||||
)
|
||||
from entities.entity import Entity
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Rect:
|
||||
x: int
|
||||
y: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
@property
|
||||
def right(self) -> int:
|
||||
return self.x + self.width
|
||||
|
||||
@property
|
||||
def bottom(self) -> int:
|
||||
return self.y + self.height
|
||||
|
||||
@property
|
||||
def center(self) -> tuple[int, int]:
|
||||
return self.x + self.width // 2, self.y + self.height // 2
|
||||
|
||||
def intersects(self, other: Rect) -> bool:
|
||||
return not (
|
||||
self.right <= other.x
|
||||
or other.right <= self.x
|
||||
or self.bottom <= other.y
|
||||
or other.bottom <= self.y
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameMap:
|
||||
width: int
|
||||
height: int
|
||||
tiles: array[int]
|
||||
rooms: list[Rect]
|
||||
explored: array[int]
|
||||
visible: array[int]
|
||||
entities: list[Entity]
|
||||
stairs_down: tuple[int, int] | None
|
||||
spawn: tuple[int, int]
|
||||
floor_index: int
|
||||
|
||||
def index(self, x: int, y: int) -> int:
|
||||
return y * self.width + x
|
||||
|
||||
def in_bounds(self, x: int, y: int) -> bool:
|
||||
return 0 <= x < self.width and 0 <= y < self.height
|
||||
|
||||
def is_floor(self, x: int, y: int) -> bool:
|
||||
return self.in_bounds(x, y) and self.tiles[self.index(x, y)] == TILE_FLOOR
|
||||
|
||||
def ascii(self) -> str:
|
||||
rows: list[str] = []
|
||||
for y in range(self.height):
|
||||
row: list[str] = []
|
||||
for x in range(self.width):
|
||||
position = (x, y)
|
||||
if position == self.spawn:
|
||||
row.append("@")
|
||||
elif position == self.stairs_down:
|
||||
row.append(">")
|
||||
else:
|
||||
row.append("." if self.is_floor(x, y) else "#")
|
||||
rows.append("".join(row))
|
||||
return "\n".join(rows)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Node:
|
||||
region: Rect
|
||||
depth: int
|
||||
left: _Node | None = None
|
||||
right: _Node | None = None
|
||||
room: Rect | None = None
|
||||
|
||||
@property
|
||||
def is_leaf(self) -> bool:
|
||||
return self.left is None
|
||||
|
||||
|
||||
_MIN_REGION_WIDTH = ROOM_MIN_WIDTH + ROOM_MARGIN * 2
|
||||
_MIN_REGION_HEIGHT = ROOM_MIN_HEIGHT + ROOM_MARGIN * 2
|
||||
|
||||
|
||||
def _split(node: _Node, rng: random.Random) -> bool:
|
||||
can_split_vertical = node.region.width >= _MIN_REGION_WIDTH * 2
|
||||
can_split_horizontal = node.region.height >= _MIN_REGION_HEIGHT * 2
|
||||
if not can_split_vertical and not can_split_horizontal:
|
||||
return False
|
||||
|
||||
split_vertical = node.depth % 2 == 0
|
||||
if split_vertical and not can_split_vertical:
|
||||
split_vertical = False
|
||||
elif not split_vertical and not can_split_horizontal:
|
||||
split_vertical = True
|
||||
|
||||
region = node.region
|
||||
if split_vertical:
|
||||
offset = rng.randint(_MIN_REGION_WIDTH, region.width - _MIN_REGION_WIDTH)
|
||||
first = Rect(region.x, region.y, offset, region.height)
|
||||
second = Rect(region.x + offset, region.y, region.width - offset, region.height)
|
||||
else:
|
||||
offset = rng.randint(_MIN_REGION_HEIGHT, region.height - _MIN_REGION_HEIGHT)
|
||||
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 _carve_tile(game_map: GameMap, x: int, y: int) -> None:
|
||||
game_map.tiles[game_map.index(x, y)] = TILE_FLOOR
|
||||
|
||||
|
||||
def _carve_room(game_map: GameMap, room: Rect) -> None:
|
||||
for y in range(room.y, room.bottom):
|
||||
for x in range(room.x, room.right):
|
||||
_carve_tile(game_map, x, y)
|
||||
|
||||
|
||||
def _carve_corridor(
|
||||
game_map: GameMap,
|
||||
start: tuple[int, int],
|
||||
end: tuple[int, int],
|
||||
rng: random.Random,
|
||||
) -> None:
|
||||
x1, y1 = start
|
||||
x2, y2 = end
|
||||
corner = (x2, y1) if rng.random() < 0.5 else (x1, y2)
|
||||
for x in range(min(x1, corner[0]), max(x1, corner[0]) + 1):
|
||||
_carve_tile(game_map, x, y1)
|
||||
for y in range(min(y1, corner[1]), max(y1, corner[1]) + 1):
|
||||
_carve_tile(game_map, corner[0], y)
|
||||
for x in range(min(corner[0], x2), max(corner[0], x2) + 1):
|
||||
_carve_tile(game_map, x, y2)
|
||||
for y in range(min(corner[1], y2), max(corner[1], y2) + 1):
|
||||
_carve_tile(game_map, x2, y)
|
||||
|
||||
|
||||
def _carve_tree(game_map: GameMap, node: _Node, rng: random.Random) -> tuple[int, int]:
|
||||
if node.is_leaf:
|
||||
region = node.region
|
||||
room_width = rng.randint(ROOM_MIN_WIDTH, min(ROOM_MAX_WIDTH, region.width - ROOM_MARGIN * 2))
|
||||
room_height = rng.randint(ROOM_MIN_HEIGHT, min(ROOM_MAX_HEIGHT, region.height - ROOM_MARGIN * 2))
|
||||
room = Rect(
|
||||
rng.randint(region.x + ROOM_MARGIN, region.right - room_width - ROOM_MARGIN),
|
||||
rng.randint(region.y + ROOM_MARGIN, region.bottom - room_height - ROOM_MARGIN),
|
||||
room_width,
|
||||
room_height,
|
||||
)
|
||||
node.room = room
|
||||
game_map.rooms.append(room)
|
||||
_carve_room(game_map, room)
|
||||
return room.center
|
||||
|
||||
if node.left is None or node.right is None:
|
||||
raise RuntimeError("invalid BSP tree")
|
||||
left_center = _carve_tree(game_map, node.left, rng)
|
||||
right_center = _carve_tree(game_map, node.right, rng)
|
||||
_carve_corridor(game_map, left_center, right_center, rng)
|
||||
return left_center
|
||||
|
||||
|
||||
def generate_dungeon(floor_index: int = 0, rng: random.Random | None = None) -> GameMap:
|
||||
rng = rng or random.Random()
|
||||
if floor_index == BOSS_FLOOR:
|
||||
return _generate_boss_arena(rng)
|
||||
|
||||
root = _Node(Rect(1, 1, MAP_WIDTH - 2, MAP_HEIGHT - 2), 0)
|
||||
leaves = [root]
|
||||
for _ in range(rng.randint(BSP_MIN_SPLITS, BSP_MAX_SPLITS)):
|
||||
candidates = [leaf for leaf in leaves if _split_possible(leaf)]
|
||||
if not candidates:
|
||||
break
|
||||
leaf = max(candidates, key=lambda candidate: candidate.region.width * candidate.region.height)
|
||||
leaves.remove(leaf)
|
||||
if _split(leaf, rng):
|
||||
if leaf.left is None or leaf.right is None:
|
||||
raise RuntimeError("BSP split did not create children")
|
||||
leaves.extend((leaf.left, leaf.right))
|
||||
|
||||
game_map = _empty_map(floor_index)
|
||||
_carve_tree(game_map, root, rng)
|
||||
game_map.spawn = game_map.rooms[0].center
|
||||
game_map.stairs_down = max(
|
||||
(room.center for room in game_map.rooms),
|
||||
key=lambda center: abs(center[0] - game_map.spawn[0]) + abs(center[1] - game_map.spawn[1]),
|
||||
)
|
||||
_spawn_content(game_map, rng)
|
||||
return game_map
|
||||
|
||||
|
||||
def _empty_map(floor_index: int) -> GameMap:
|
||||
size = MAP_WIDTH * MAP_HEIGHT
|
||||
return GameMap(
|
||||
width=MAP_WIDTH,
|
||||
height=MAP_HEIGHT,
|
||||
tiles=array("B", [TILE_WALL]) * size,
|
||||
rooms=[],
|
||||
explored=array("B", [0]) * size,
|
||||
visible=array("B", [0]) * size,
|
||||
entities=[],
|
||||
stairs_down=None,
|
||||
spawn=(0, 0),
|
||||
floor_index=floor_index,
|
||||
)
|
||||
|
||||
|
||||
def _generate_boss_arena(rng: random.Random) -> GameMap:
|
||||
from data.enemies import create_enemy
|
||||
from data.items import create_item
|
||||
|
||||
game_map = _empty_map(BOSS_FLOOR)
|
||||
arena = Rect(
|
||||
rng.randint(1, MAP_WIDTH - BOSS_ARENA_WIDTH - 1),
|
||||
rng.randint(1, MAP_HEIGHT - BOSS_ARENA_HEIGHT - 1),
|
||||
BOSS_ARENA_WIDTH,
|
||||
BOSS_ARENA_HEIGHT,
|
||||
)
|
||||
game_map.rooms.append(arena)
|
||||
_carve_room(game_map, arena)
|
||||
entrance_x = arena.x + 1
|
||||
entrance_y = arena.y + arena.height // 2
|
||||
game_map.spawn = (entrance_x, entrance_y)
|
||||
game_map.entities.append(create_enemy("Ancient Dragon", arena.right - 2, entrance_y))
|
||||
potion_positions = ((entrance_x + 1, entrance_y - 1), (entrance_x + 1, entrance_y + 1))
|
||||
game_map.entities.extend(create_item("Healing Potion", x, y) for x, y in potion_positions)
|
||||
return game_map
|
||||
|
||||
|
||||
def _spawn_content(game_map: GameMap, rng: random.Random) -> None:
|
||||
from data.enemies import create_enemy, enemy_names_for_floor
|
||||
from data.items import create_item, item_names_for_floor
|
||||
|
||||
minimum_enemies, maximum_enemies, minimum_items, maximum_items = FLOOR_SPAWN_COUNTS[game_map.floor_index]
|
||||
enemy_count = rng.randint(minimum_enemies, maximum_enemies)
|
||||
item_count = rng.randint(minimum_items, maximum_items)
|
||||
blocked = {game_map.spawn, game_map.stairs_down}
|
||||
positions = [
|
||||
(x, y)
|
||||
for y in range(game_map.height)
|
||||
for x in range(game_map.width)
|
||||
if game_map.is_floor(x, y) and (x, y) not in blocked
|
||||
]
|
||||
rng.shuffle(positions)
|
||||
enemy_names = enemy_names_for_floor(game_map.floor_index)
|
||||
item_names = item_names_for_floor(game_map.floor_index)
|
||||
for position in positions[:enemy_count]:
|
||||
game_map.entities.append(create_enemy(rng.choice(enemy_names), *position))
|
||||
for position in positions[enemy_count : enemy_count + item_count]:
|
||||
game_map.entities.append(create_item(rng.choice(item_names), *position))
|
||||
|
||||
|
||||
def _split_possible(node: _Node) -> bool:
|
||||
return (
|
||||
node.region.width >= _MIN_REGION_WIDTH * 2
|
||||
or node.region.height >= _MIN_REGION_HEIGHT * 2
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
from collections.abc import Iterable, Iterator
|
||||
|
||||
from engine.map_gen import GameMap
|
||||
|
||||
Position = tuple[int, int]
|
||||
|
||||
|
||||
def manhattan_distance(start: Position, goal: Position) -> int:
|
||||
return abs(start[0] - goal[0]) + abs(start[1] - goal[1])
|
||||
|
||||
|
||||
def _neighbors(position: Position) -> Iterator[Position]:
|
||||
x, y = position
|
||||
yield x, y - 1
|
||||
yield x - 1, y
|
||||
yield x + 1, y
|
||||
yield x, y + 1
|
||||
|
||||
|
||||
def _reconstruct_path(
|
||||
came_from: dict[Position, Position], start: Position, goal: Position
|
||||
) -> list[Position]:
|
||||
path: list[Position] = []
|
||||
current = goal
|
||||
while current != start:
|
||||
path.append(current)
|
||||
current = came_from[current]
|
||||
path.reverse()
|
||||
return path
|
||||
|
||||
|
||||
def find_path(
|
||||
game_map: GameMap,
|
||||
start: Position,
|
||||
goal: Position,
|
||||
occupied: Iterable[Position] = (),
|
||||
) -> list[Position]:
|
||||
"""Return cardinal steps after start through goal, or an empty list if unreachable."""
|
||||
if start == goal or not game_map.is_floor(*start) or not game_map.is_floor(*goal):
|
||||
return []
|
||||
|
||||
blocked = set(occupied)
|
||||
blocked.discard(start)
|
||||
frontier: list[tuple[int, int, Position]] = [
|
||||
(manhattan_distance(start, goal), 0, start)
|
||||
]
|
||||
came_from: dict[Position, Position] = {}
|
||||
costs = {start: 0}
|
||||
|
||||
while frontier:
|
||||
_, cost, current = heapq.heappop(frontier)
|
||||
if cost != costs.get(current):
|
||||
continue
|
||||
if current == goal:
|
||||
return _reconstruct_path(came_from, start, goal)
|
||||
|
||||
for neighbor in _neighbors(current):
|
||||
if neighbor in blocked or not game_map.is_floor(*neighbor):
|
||||
continue
|
||||
new_cost = cost + 1
|
||||
known_cost = costs.get(neighbor)
|
||||
if known_cost is not None and new_cost >= known_cost:
|
||||
continue
|
||||
costs[neighbor] = new_cost
|
||||
came_from[neighbor] = current
|
||||
priority = new_cost + manhattan_distance(neighbor, goal)
|
||||
heapq.heappush(frontier, (priority, new_cost, neighbor))
|
||||
|
||||
return []
|
||||
@@ -0,0 +1,187 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from array import array
|
||||
from dataclasses import fields
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from data.constants import FLOOR_COUNT, SAVE_FILENAME
|
||||
from engine.fov import compute_fov
|
||||
from engine.game_state import GameSession
|
||||
from engine.map_gen import GameMap, Rect
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from entities.player import Player
|
||||
|
||||
SAVE_VERSION = 1
|
||||
DEFAULT_SAVE_PATH = Path(__file__).resolve().parents[1] / SAVE_FILENAME
|
||||
|
||||
|
||||
def _field_data(value: object) -> dict[str, Any]:
|
||||
return {field.name: getattr(value, field.name) for field in fields(value)}
|
||||
|
||||
|
||||
def _item_to_dict(item: Item) -> dict[str, Any]:
|
||||
return _field_data(item)
|
||||
|
||||
|
||||
def _item_from_dict(data: Mapping[str, Any]) -> Item:
|
||||
values = dict(data)
|
||||
values["color"] = tuple(values["color"])
|
||||
return Item(**values)
|
||||
|
||||
|
||||
def _enemy_to_dict(enemy: Enemy) -> dict[str, Any]:
|
||||
return _field_data(enemy)
|
||||
|
||||
|
||||
def _enemy_from_dict(data: Mapping[str, Any]) -> Enemy:
|
||||
values = dict(data)
|
||||
values["color"] = tuple(values["color"])
|
||||
if values.get("last_known_position") is not None:
|
||||
values["last_known_position"] = tuple(values["last_known_position"])
|
||||
return Enemy(**values)
|
||||
|
||||
|
||||
def _player_to_dict(player: Player) -> dict[str, Any]:
|
||||
data = _field_data(player)
|
||||
data["inventory"] = [_item_to_dict(item) for item in player.inventory]
|
||||
data["weapon"] = _item_to_dict(player.weapon) if player.weapon else None
|
||||
data["armor_item"] = _item_to_dict(player.armor_item) if player.armor_item else None
|
||||
return data
|
||||
|
||||
|
||||
def _player_from_dict(data: Mapping[str, Any]) -> Player:
|
||||
values = dict(data)
|
||||
values["color"] = tuple(values["color"])
|
||||
values["inventory"] = [_item_from_dict(item) for item in values["inventory"]]
|
||||
values["weapon"] = _item_from_dict(values["weapon"]) if values.get("weapon") else None
|
||||
values["armor_item"] = (
|
||||
_item_from_dict(values["armor_item"]) if values.get("armor_item") else None
|
||||
)
|
||||
return Player(**values)
|
||||
|
||||
|
||||
def _map_to_dict(game_map: GameMap) -> dict[str, Any]:
|
||||
entities = []
|
||||
for entity in game_map.entities:
|
||||
if isinstance(entity, Enemy):
|
||||
entities.append({"type": "enemy", "data": _enemy_to_dict(entity)})
|
||||
elif isinstance(entity, Item):
|
||||
entities.append({"type": "item", "data": _item_to_dict(entity)})
|
||||
else:
|
||||
raise TypeError(f"unsupported entity type: {type(entity).__name__}")
|
||||
return {
|
||||
"width": game_map.width,
|
||||
"height": game_map.height,
|
||||
"tiles": list(game_map.tiles),
|
||||
"rooms": [_field_data(room) for room in game_map.rooms],
|
||||
"explored": list(game_map.explored),
|
||||
"entities": entities,
|
||||
"stairs_down": game_map.stairs_down,
|
||||
"spawn": game_map.spawn,
|
||||
"floor_index": game_map.floor_index,
|
||||
}
|
||||
|
||||
|
||||
def _map_from_dict(data: Mapping[str, Any]) -> GameMap:
|
||||
entities = []
|
||||
for entry in data["entities"]:
|
||||
kind = entry["type"]
|
||||
if kind == "enemy":
|
||||
entities.append(_enemy_from_dict(entry["data"]))
|
||||
elif kind == "item":
|
||||
entities.append(_item_from_dict(entry["data"]))
|
||||
else:
|
||||
raise ValueError(f"unknown entity type: {kind!r}")
|
||||
width = int(data["width"])
|
||||
height = int(data["height"])
|
||||
tiles = array("B", data["tiles"])
|
||||
explored = array("B", data["explored"])
|
||||
if len(tiles) != width * height or len(explored) != width * height:
|
||||
raise ValueError("save contains an invalid map grid")
|
||||
stairs = data.get("stairs_down")
|
||||
return GameMap(
|
||||
width=width,
|
||||
height=height,
|
||||
tiles=tiles,
|
||||
rooms=[Rect(**room) for room in data["rooms"]],
|
||||
explored=explored,
|
||||
visible=array("B", [0]) * (width * height),
|
||||
entities=entities,
|
||||
stairs_down=tuple(stairs) if stairs is not None else None,
|
||||
spawn=tuple(data["spawn"]),
|
||||
floor_index=int(data["floor_index"]),
|
||||
)
|
||||
|
||||
|
||||
def session_to_dict(session: GameSession) -> dict[str, Any]:
|
||||
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,
|
||||
"rng_state": session.rng_state,
|
||||
}
|
||||
|
||||
|
||||
def session_from_dict(data: Mapping[str, Any]) -> GameSession:
|
||||
try:
|
||||
if data.get("version") != SAVE_VERSION:
|
||||
raise ValueError("unsupported save version")
|
||||
dungeon = [_map_from_dict(game_map) for game_map in data["dungeon"]]
|
||||
current_floor = int(data["current_floor"])
|
||||
if len(dungeon) != FLOOR_COUNT or not 0 <= current_floor < len(dungeon):
|
||||
raise ValueError("save must contain all ten floors and a valid current floor")
|
||||
session = GameSession(
|
||||
player=_player_from_dict(data["player"]),
|
||||
dungeon=dungeon,
|
||||
current_floor=current_floor,
|
||||
log=[str(message) for message in data["log"]],
|
||||
turn=int(data["turn"]),
|
||||
state=str(data["state"]),
|
||||
rng_state=str(data["rng_state"]),
|
||||
)
|
||||
except (KeyError, TypeError, OverflowError) as error:
|
||||
raise ValueError("save file is malformed") from error
|
||||
compute_fov(session.current_map, session.player.x, session.player.y)
|
||||
return session
|
||||
|
||||
|
||||
def save_game(session: GameSession, path: str | Path = DEFAULT_SAVE_PATH) -> Path:
|
||||
destination = Path(path)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = destination.with_suffix(destination.suffix + ".tmp")
|
||||
try:
|
||||
temporary.write_text(
|
||||
json.dumps(session_to_dict(session), separators=(",", ":")),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temporary.replace(destination)
|
||||
except OSError:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise
|
||||
return destination
|
||||
|
||||
|
||||
def load_game(path: str | Path = DEFAULT_SAVE_PATH) -> GameSession:
|
||||
source = Path(path)
|
||||
try:
|
||||
data = json.loads(source.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as error:
|
||||
raise ValueError(f"could not load save: {error}") from error
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("save root must be an object")
|
||||
return session_from_dict(data)
|
||||
|
||||
|
||||
def delete_save(path: str | Path = DEFAULT_SAVE_PATH) -> None:
|
||||
Path(path).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def save_exists(path: str | Path = DEFAULT_SAVE_PATH) -> bool:
|
||||
return Path(path).is_file()
|
||||
Reference in new issue
Block a user