Merge branch 'master' into 'ladders'
# Conflicts: # squirrelbattle/game.py # squirrelbattle/interfaces.py # squirrelbattle/tests/game_test.py
This commit is contained in:
@ -4,7 +4,9 @@
|
||||
from enum import Enum, auto
|
||||
from math import sqrt
|
||||
from random import choice, randint
|
||||
from typing import List, Optional, Any, Tuple
|
||||
from typing import List, Optional, Any, Dict, Tuple
|
||||
from queue import PriorityQueue
|
||||
from functools import reduce
|
||||
|
||||
from .display.texturepack import TexturePack
|
||||
from .translations import gettext as _
|
||||
@ -12,7 +14,7 @@ from .translations import gettext as _
|
||||
|
||||
class Logs:
|
||||
"""
|
||||
The logs object stores the messages to display. It is encapsulating a list
|
||||
The logs object stores the messages to display. It encapsulates a list
|
||||
of such messages, to allow multiple pointers to keep track of it even if
|
||||
the list was to be reassigned.
|
||||
"""
|
||||
@ -32,7 +34,7 @@ class Logs:
|
||||
|
||||
class Map:
|
||||
"""
|
||||
Object that represents a Map with its width, height
|
||||
The Map object represents a with its width, height
|
||||
and tiles, that have their custom properties.
|
||||
"""
|
||||
floor: int
|
||||
@ -61,14 +63,17 @@ class Map:
|
||||
|
||||
def add_entity(self, entity: "Entity") -> None:
|
||||
"""
|
||||
Register a new entity in the map.
|
||||
Registers a new entity in the map.
|
||||
"""
|
||||
self.entities.append(entity)
|
||||
if entity.is_familiar():
|
||||
self.entities.insert(1, entity)
|
||||
else:
|
||||
self.entities.append(entity)
|
||||
entity.map = self
|
||||
|
||||
def remove_entity(self, entity: "Entity") -> None:
|
||||
"""
|
||||
Unregister an entity from the map.
|
||||
Unregisters an entity from the map.
|
||||
"""
|
||||
if entity in self.entities:
|
||||
self.entities.remove(entity)
|
||||
@ -88,7 +93,7 @@ class Map:
|
||||
def entity_is_present(self, y: int, x: int) -> bool:
|
||||
"""
|
||||
Indicates that the tile at the coordinates (y, x) contains a killable
|
||||
entity
|
||||
entity.
|
||||
"""
|
||||
return 0 <= y < self.height and 0 <= x < self.width and \
|
||||
any(entity.x == x and entity.y == y and entity.is_friendly()
|
||||
@ -97,7 +102,8 @@ class Map:
|
||||
@staticmethod
|
||||
def load(filename: str) -> "Map":
|
||||
"""
|
||||
Read a file that contains the content of a map, and build a Map object.
|
||||
Reads a file that contains the content of a map,
|
||||
and builds a Map object.
|
||||
"""
|
||||
with open(filename, "r") as f:
|
||||
file = f.read()
|
||||
@ -106,7 +112,7 @@ class Map:
|
||||
@staticmethod
|
||||
def load_from_string(content: str) -> "Map":
|
||||
"""
|
||||
Load a map represented by its characters and build a Map object.
|
||||
Loads a map represented by its characters and builds a Map object.
|
||||
"""
|
||||
lines = content.split("\n")
|
||||
first_line = lines[0]
|
||||
@ -122,7 +128,7 @@ class Map:
|
||||
@staticmethod
|
||||
def load_dungeon_from_string(content: str) -> List[List["Tile"]]:
|
||||
"""
|
||||
Transforms a string into the list of corresponding tiles
|
||||
Transforms a string into the list of corresponding tiles.
|
||||
"""
|
||||
lines = content.split("\n")
|
||||
tiles = [[Tile.from_ascii_char(c)
|
||||
@ -131,7 +137,7 @@ class Map:
|
||||
|
||||
def draw_string(self, pack: TexturePack) -> str:
|
||||
"""
|
||||
Draw the current map as a string object that can be rendered
|
||||
Draws the current map as a string object that can be rendered
|
||||
in the window.
|
||||
"""
|
||||
return "\n".join("".join(tile.char(pack) for tile in line)
|
||||
@ -139,7 +145,7 @@ class Map:
|
||||
|
||||
def spawn_random_entities(self, count: int) -> None:
|
||||
"""
|
||||
Put randomly {count} entities on the map, where it is available.
|
||||
Puts randomly {count} entities on the map, only on empty ground tiles.
|
||||
"""
|
||||
for ignored in range(count):
|
||||
while True:
|
||||
@ -151,16 +157,19 @@ class Map:
|
||||
entity.move(y, x)
|
||||
self.add_entity(entity)
|
||||
|
||||
def tick(self) -> None:
|
||||
def tick(self, p: Any) -> None:
|
||||
"""
|
||||
Trigger all entity events.
|
||||
Triggers all entity events.
|
||||
"""
|
||||
for entity in self.entities:
|
||||
entity.act(self)
|
||||
if entity.is_familiar():
|
||||
entity.act(p, self)
|
||||
else:
|
||||
entity.act(self)
|
||||
|
||||
def save_state(self) -> dict:
|
||||
"""
|
||||
Saves the map's attributes to a dictionary
|
||||
Saves the map's attributes to a dictionary.
|
||||
"""
|
||||
d = dict()
|
||||
d["width"] = self.width
|
||||
@ -177,7 +186,7 @@ class Map:
|
||||
|
||||
def load_state(self, d: dict) -> None:
|
||||
"""
|
||||
Loads the map's attributes from a dictionary
|
||||
Loads the map's attributes from a dictionary.
|
||||
"""
|
||||
self.width = d["width"]
|
||||
self.height = d["height"]
|
||||
@ -194,7 +203,7 @@ class Map:
|
||||
|
||||
class Tile(Enum):
|
||||
"""
|
||||
The internal representation of the tiles of the map
|
||||
The internal representation of the tiles of the map.
|
||||
"""
|
||||
EMPTY = auto()
|
||||
WALL = auto()
|
||||
@ -204,7 +213,7 @@ class Tile(Enum):
|
||||
@staticmethod
|
||||
def from_ascii_char(ch: str) -> "Tile":
|
||||
"""
|
||||
Maps an ascii character to its equivalent in the texture pack
|
||||
Maps an ascii character to its equivalent in the texture pack.
|
||||
"""
|
||||
for tile in Tile:
|
||||
if tile.char(TexturePack.ASCII_PACK) == ch:
|
||||
@ -214,7 +223,7 @@ class Tile(Enum):
|
||||
def char(self, pack: TexturePack) -> str:
|
||||
"""
|
||||
Translates a Tile to the corresponding character according
|
||||
to the texture pack
|
||||
to the texture pack.
|
||||
"""
|
||||
val = getattr(pack, self.name)
|
||||
return val[0] if isinstance(val, tuple) else val
|
||||
@ -241,19 +250,20 @@ class Tile(Enum):
|
||||
|
||||
def can_walk(self) -> bool:
|
||||
"""
|
||||
Check if an entity (player or not) can move in this tile.
|
||||
Checks if an entity (player or not) can move in this tile.
|
||||
"""
|
||||
return not self.is_wall() and self != Tile.EMPTY
|
||||
|
||||
|
||||
class Entity:
|
||||
"""
|
||||
An Entity object represents any entity present on the map
|
||||
An Entity object represents any entity present on the map.
|
||||
"""
|
||||
y: int
|
||||
x: int
|
||||
name: str
|
||||
map: Map
|
||||
paths: Dict[Tuple[int, int], Tuple[int, int]]
|
||||
|
||||
# noinspection PyShadowingBuiltins
|
||||
def __init__(self, y: int = 0, x: int = 0, name: Optional[str] = None,
|
||||
@ -262,11 +272,12 @@ class Entity:
|
||||
self.x = x
|
||||
self.name = name
|
||||
self.map = map
|
||||
self.paths = None
|
||||
|
||||
def check_move(self, y: int, x: int, move_if_possible: bool = False)\
|
||||
-> bool:
|
||||
"""
|
||||
Checks if moving to (y,x) is authorized
|
||||
Checks if moving to (y,x) is authorized.
|
||||
"""
|
||||
free = self.map.is_free(y, x)
|
||||
if free and move_if_possible:
|
||||
@ -275,7 +286,7 @@ class Entity:
|
||||
|
||||
def move(self, y: int, x: int) -> bool:
|
||||
"""
|
||||
Moves an entity to (y,x) coordinates
|
||||
Moves an entity to (y,x) coordinates.
|
||||
"""
|
||||
self.y = y
|
||||
self.x = x
|
||||
@ -283,49 +294,100 @@ class Entity:
|
||||
|
||||
def move_up(self, force: bool = False) -> bool:
|
||||
"""
|
||||
Moves the entity up one tile, if possible
|
||||
Moves the entity up one tile, if possible.
|
||||
"""
|
||||
return self.move(self.y - 1, self.x) if force else \
|
||||
self.check_move(self.y - 1, self.x, True)
|
||||
|
||||
def move_down(self, force: bool = False) -> bool:
|
||||
"""
|
||||
Moves the entity down one tile, if possible
|
||||
Moves the entity down one tile, if possible.
|
||||
"""
|
||||
return self.move(self.y + 1, self.x) if force else \
|
||||
self.check_move(self.y + 1, self.x, True)
|
||||
|
||||
def move_left(self, force: bool = False) -> bool:
|
||||
"""
|
||||
Moves the entity left one tile, if possible
|
||||
Moves the entity left one tile, if possible.
|
||||
"""
|
||||
return self.move(self.y, self.x - 1) if force else \
|
||||
self.check_move(self.y, self.x - 1, True)
|
||||
|
||||
def move_right(self, force: bool = False) -> bool:
|
||||
"""
|
||||
Moves the entity right one tile, if possible
|
||||
Moves the entity right one tile, if possible.
|
||||
"""
|
||||
return self.move(self.y, self.x + 1) if force else \
|
||||
self.check_move(self.y, self.x + 1, True)
|
||||
|
||||
def recalculate_paths(self, max_distance: int = 12) -> None:
|
||||
"""
|
||||
Uses Dijkstra algorithm to calculate best paths for other entities to
|
||||
go to this entity. If self.paths is None, does nothing.
|
||||
"""
|
||||
if self.paths is None:
|
||||
return
|
||||
distances = []
|
||||
predecessors = []
|
||||
# four Dijkstras, one for each adjacent tile
|
||||
for dir_y, dir_x in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
|
||||
queue = PriorityQueue()
|
||||
new_y, new_x = self.y + dir_y, self.x + dir_x
|
||||
if not 0 <= new_y < self.map.height or \
|
||||
not 0 <= new_x < self.map.width or \
|
||||
not self.map.tiles[new_y][new_x].can_walk():
|
||||
continue
|
||||
queue.put(((1, 0), (new_y, new_x)))
|
||||
visited = [(self.y, self.x)]
|
||||
distances.append({(self.y, self.x): (0, 0), (new_y, new_x): (1, 0)})
|
||||
predecessors.append({(new_y, new_x): (self.y, self.x)})
|
||||
while not queue.empty():
|
||||
dist, (y, x) = queue.get()
|
||||
if dist[0] >= max_distance or (y, x) in visited:
|
||||
continue
|
||||
visited.append((y, x))
|
||||
for diff_y, diff_x in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
|
||||
new_y, new_x = y + diff_y, x + diff_x
|
||||
if not 0 <= new_y < self.map.height or \
|
||||
not 0 <= new_x < self.map.width or \
|
||||
not self.map.tiles[new_y][new_x].can_walk():
|
||||
continue
|
||||
new_distance = (dist[0] + 1,
|
||||
dist[1] + (not self.map.is_free(y, x)))
|
||||
if not (new_y, new_x) in distances[-1] or \
|
||||
distances[-1][(new_y, new_x)] > new_distance:
|
||||
predecessors[-1][(new_y, new_x)] = (y, x)
|
||||
distances[-1][(new_y, new_x)] = new_distance
|
||||
queue.put((new_distance, (new_y, new_x)))
|
||||
# For each tile that is reached by at least one Dijkstra, sort the
|
||||
# different paths by distance to the player. For the technical bits :
|
||||
# The reduce function is a fold starting on the first element of the
|
||||
# iterable, and we associate the points to their distance, sort
|
||||
# along the distance, then only keep the points.
|
||||
self.paths = {}
|
||||
for y, x in reduce(set.union,
|
||||
[set(p.keys()) for p in predecessors], set()):
|
||||
self.paths[(y, x)] = [p for d, p in sorted(
|
||||
[(distances[i][(y, x)], predecessors[i][(y, x)])
|
||||
for i in range(len(distances)) if (y, x) in predecessors[i]])]
|
||||
|
||||
def act(self, m: Map) -> None:
|
||||
"""
|
||||
Define the action of the entity that is ran each tick.
|
||||
Defines the action the entity will do at each tick.
|
||||
By default, does nothing.
|
||||
"""
|
||||
pass
|
||||
|
||||
def distance_squared(self, other: "Entity") -> int:
|
||||
"""
|
||||
Get the square of the distance to another entity.
|
||||
Useful to check distances since square root takes time.
|
||||
Gives the square of the distance to another entity.
|
||||
Useful to check distances since taking the square root takes time.
|
||||
"""
|
||||
return (self.y - other.y) ** 2 + (self.x - other.x) ** 2
|
||||
|
||||
def distance(self, other: "Entity") -> float:
|
||||
"""
|
||||
Get the cartesian distance to another entity.
|
||||
Gives the cartesian distance to another entity.
|
||||
"""
|
||||
return sqrt(self.distance_squared(other))
|
||||
|
||||
@ -348,6 +410,13 @@ class Entity:
|
||||
"""
|
||||
return isinstance(self, FriendlyEntity)
|
||||
|
||||
def is_familiar(self) -> bool:
|
||||
"""
|
||||
Is this entity a familiar?
|
||||
"""
|
||||
from squirrelbattle.entities.friendly import Familiar
|
||||
return isinstance(self, Familiar)
|
||||
|
||||
def is_merchant(self) -> bool:
|
||||
"""
|
||||
Is this entity a merchant?
|
||||
@ -357,29 +426,34 @@ class Entity:
|
||||
|
||||
@property
|
||||
def translated_name(self) -> str:
|
||||
"""
|
||||
Translates the name of entities.
|
||||
"""
|
||||
return _(self.name.replace("_", " "))
|
||||
|
||||
@staticmethod
|
||||
def get_all_entity_classes() -> list:
|
||||
"""
|
||||
Returns all entities subclasses
|
||||
Returns all entities subclasses.
|
||||
"""
|
||||
from squirrelbattle.entities.items import BodySnatchPotion, Bomb, Heart
|
||||
from squirrelbattle.entities.monsters import Tiger, Hedgehog, \
|
||||
Rabbit, TeddyBear
|
||||
from squirrelbattle.entities.friendly import Merchant, Sunflower
|
||||
from squirrelbattle.entities.friendly import Merchant, Sunflower, \
|
||||
Trumpet
|
||||
return [BodySnatchPotion, Bomb, Heart, Hedgehog, Rabbit, TeddyBear,
|
||||
Sunflower, Tiger, Merchant]
|
||||
Sunflower, Tiger, Merchant, Trumpet]
|
||||
|
||||
@staticmethod
|
||||
def get_all_entity_classes_in_a_dict() -> dict:
|
||||
"""
|
||||
Returns all entities subclasses in a dictionary
|
||||
Returns all entities subclasses in a dictionary.
|
||||
"""
|
||||
from squirrelbattle.entities.player import Player
|
||||
from squirrelbattle.entities.monsters import Tiger, Hedgehog, Rabbit, \
|
||||
TeddyBear
|
||||
from squirrelbattle.entities.friendly import Merchant, Sunflower
|
||||
from squirrelbattle.entities.friendly import Merchant, Sunflower, \
|
||||
Trumpet
|
||||
from squirrelbattle.entities.items import BodySnatchPotion, Bomb, \
|
||||
Heart, Sword
|
||||
return {
|
||||
@ -394,11 +468,12 @@ class Entity:
|
||||
"Merchant": Merchant,
|
||||
"Sunflower": Sunflower,
|
||||
"Sword": Sword,
|
||||
"Trumpet": Trumpet,
|
||||
}
|
||||
|
||||
def save_state(self) -> dict:
|
||||
"""
|
||||
Saves the coordinates of the entity
|
||||
Saves the coordinates of the entity.
|
||||
"""
|
||||
d = dict()
|
||||
d["x"] = self.x
|
||||
@ -410,7 +485,7 @@ class Entity:
|
||||
class FightingEntity(Entity):
|
||||
"""
|
||||
A FightingEntity is an entity that can fight, and thus has a health,
|
||||
level and stats
|
||||
level and stats.
|
||||
"""
|
||||
maxhealth: int
|
||||
health: int
|
||||
@ -437,11 +512,15 @@ class FightingEntity(Entity):
|
||||
|
||||
@property
|
||||
def dead(self) -> bool:
|
||||
"""
|
||||
Is this entity dead ?
|
||||
"""
|
||||
return self.health <= 0
|
||||
|
||||
def hit(self, opponent: "FightingEntity") -> str:
|
||||
"""
|
||||
Deals damage to the opponent, based on the stats
|
||||
The entity deals damage to the opponent
|
||||
based on their respective stats.
|
||||
"""
|
||||
return _("{name} hits {opponent}.")\
|
||||
.format(name=_(self.translated_name.capitalize()),
|
||||
@ -450,7 +529,8 @@ class FightingEntity(Entity):
|
||||
|
||||
def take_damage(self, attacker: "Entity", amount: int) -> str:
|
||||
"""
|
||||
Take damage from the attacker, based on the stats
|
||||
The entity takes damage from the attacker
|
||||
based on their respective stats.
|
||||
"""
|
||||
self.health -= amount
|
||||
if self.health <= 0:
|
||||
@ -463,20 +543,20 @@ class FightingEntity(Entity):
|
||||
|
||||
def die(self) -> None:
|
||||
"""
|
||||
If a fighting entity has no more health, it dies and is removed
|
||||
If a fighting entity has no more health, it dies and is removed.
|
||||
"""
|
||||
self.map.remove_entity(self)
|
||||
|
||||
def keys(self) -> list:
|
||||
"""
|
||||
Returns a fighting entity's specific attributes
|
||||
Returns a fighting entity's specific attributes.
|
||||
"""
|
||||
return ["name", "maxhealth", "health", "level", "strength",
|
||||
"intelligence", "charisma", "dexterity", "constitution"]
|
||||
|
||||
def save_state(self) -> dict:
|
||||
"""
|
||||
Saves the state of the entity into a dictionary
|
||||
Saves the state of the entity into a dictionary.
|
||||
"""
|
||||
d = super().save_state()
|
||||
for name in self.keys():
|
||||
@ -486,7 +566,7 @@ class FightingEntity(Entity):
|
||||
|
||||
class FriendlyEntity(FightingEntity):
|
||||
"""
|
||||
Friendly entities are living entities which do not attack the player
|
||||
Friendly entities are living entities which do not attack the player.
|
||||
"""
|
||||
dialogue_option: list
|
||||
|
||||
@ -497,7 +577,7 @@ class FriendlyEntity(FightingEntity):
|
||||
|
||||
def keys(self) -> list:
|
||||
"""
|
||||
Returns a friendly entity's specific attributes
|
||||
Returns a friendly entity's specific attributes.
|
||||
"""
|
||||
return ["maxhealth", "health"]
|
||||
|
||||
@ -508,7 +588,7 @@ class InventoryHolder(Entity):
|
||||
|
||||
def translate_inventory(self, inventory: list) -> list:
|
||||
"""
|
||||
Translate the JSON-state of the inventory into a list of the items in
|
||||
Translates the JSON save of the inventory into a list of the items in
|
||||
the inventory.
|
||||
"""
|
||||
for i in range(len(inventory)):
|
||||
@ -518,7 +598,7 @@ class InventoryHolder(Entity):
|
||||
|
||||
def dict_to_inventory(self, item_dict: dict) -> Entity:
|
||||
"""
|
||||
Translate a dict object that contains the state of an item
|
||||
Translates a dictionnary that contains the state of an item
|
||||
into an item object.
|
||||
"""
|
||||
entity_classes = self.get_all_entity_classes_in_a_dict()
|
||||
@ -528,7 +608,7 @@ class InventoryHolder(Entity):
|
||||
|
||||
def save_state(self) -> dict:
|
||||
"""
|
||||
We save the inventory of the merchant formatted as JSON
|
||||
The inventory of the merchant is saved in a JSON format.
|
||||
"""
|
||||
d = super().save_state()
|
||||
d["hazel"] = self.hazel
|
||||
@ -537,19 +617,19 @@ class InventoryHolder(Entity):
|
||||
|
||||
def add_to_inventory(self, obj: Any) -> None:
|
||||
"""
|
||||
Adds an object to inventory
|
||||
Adds an object to the inventory.
|
||||
"""
|
||||
self.inventory.append(obj)
|
||||
|
||||
def remove_from_inventory(self, obj: Any) -> None:
|
||||
"""
|
||||
Removes an object from the inventory
|
||||
Removes an object from the inventory.
|
||||
"""
|
||||
self.inventory.remove(obj)
|
||||
|
||||
def change_hazel_balance(self, hz: int) -> None:
|
||||
"""
|
||||
Change the number of hazel the entity has by hz. hz is negative
|
||||
when the player loses money and positive when he gains money
|
||||
Changes the number of hazel the entity has by hz. hz is negative
|
||||
when the entity loses money and positive when it gains money.
|
||||
"""
|
||||
self.hazel += hz
|
||||
|
Reference in New Issue
Block a user