Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Labyrinth: Декоратор для классов, описывающих уникальные объекты #210

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions labyrinth_engine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
from labyrinth_engine.labyrinth import Labyrinth
from labyrinth_engine.labyrinth_object import LabyrinthObject
from labyrinth_engine.lr_types import Location, Item, Player, Creature
from labyrinth_engine.uniqueness import unique
10 changes: 10 additions & 0 deletions labyrinth_engine/labyrinth_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class LabyrinthObject:
"""

_lrtype = 'labyrinth_object'
_metadata = {}

def __init__(self):
self.turn_set = {}
Expand Down Expand Up @@ -86,6 +87,15 @@ def get_children(self, lrtype=['location', 'item', 'player', 'creature'], class_
def lrtype(self):
return self._lrtype

@property
def metadata(self):
return self._metadata

def add_meta(self, *args, **kwargs):
self._metadata.update({key: True for key in args})
self._metadata.update(kwargs)
return self._metadata

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот здесь #208 было предложено сделать внешние функции для работы с метаинформацией.
Это было сделано не просто так. Все те описанные там по этому поводу функции работают для любого объекта.
В частности, для функций. (Это можно использовать здесь #75 23 мая)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хорошо. Это, конечно, будет добавлено в LR-75. Но добавлю ещё и здесь. Но это ещё один удобный способ сохранять метаданные у класса LabyrinthObject.

def main(self):
"""
Основная функция объекта. Определяется здесь, чтобы потом не было ошибки при её вызове.
Expand Down
17 changes: 12 additions & 5 deletions labyrinth_engine/labyrinth_object.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ from typing import Any, Dict, Union, List, Callable, TypeVar

class LabyrinthObject:
labyrinth: Labyrinth

_lrtype: str
_metadata: Dict[Any, Any]

turn_set: Dict[str, Dict[str, Callable[[], Any]]]
flags: Dict[str: Any]
button_set: List[Button]
Expand All @@ -28,9 +31,9 @@ class LabyrinthObject:
def get_flag(self, flag_name: str, default: Any = ...) -> Any: ...

# Кнопки.
def new_button(self, turn: str, image: str): ...
def new_dbutton(self, turns: List[str], image: str): ...
def new_lbutton(self, turns: List[str], image: str, turn_images): ...
def new_button(self, turn: str, image: str) -> None: ...
def new_dbutton(self, turns: List[str], image: str) -> None: ...
def new_lbutton(self, turns: List[str], image: str, turn_images) -> None: ...
def get_buttons(self) -> List[Button]: ...

# Бары.
Expand All @@ -47,8 +50,12 @@ class LabyrinthObject:
key: Callable[[AnyLO], bool] = ...): ...

@property
def lrtype(self) -> str:
return self._lrtype
def lrtype(self) -> str: ...

@property
def metadata(self) -> Dict[Any, Any]: ...

def add_meta(self, *args, **kwargs) -> Dict[Any, Any]: ...

def main(self) -> None: ...

Expand Down
12 changes: 12 additions & 0 deletions labyrinth_engine/metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def add_meta(obj, *args, **kwargs):
if '_metadata' not in obj.__dict__:
obj._metadata = {}
obj._metadata.update({key: True for key in args})
obj._metadata.update(kwargs)
return obj._metadata


def get_meta(obj):
if '_metadata' not in obj.__dict__:
return {}
return obj._metadata
21 changes: 21 additions & 0 deletions labyrinth_engine/uniqueness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# декоратор для класса описывающего уникальный предмет
def unique(key):
"""
key - ключ, который будет установлен
этому уникальному объекту.
"""
def unique_decorator(cls):
old_function = cls.set_settings

def set_settings(self, *args, **kwargs):
"""
Новая функция дополнительно будет устанавливать
указанный уникальный ключ.
"""
self.labyrinth.set_unique(self, key)
return old_function(self, *args, **kwargs)
# изменяем функцию в классе.
cls.set_settings = set_settings
cls.add_meta('unique_object')
return cls
return unique_decorator
5 changes: 2 additions & 3 deletions labyrinth_objects/Vanilla/ammo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from labyrinth_engine import Item
from labyrinth_engine import Item, unique


@unique('ammo')
class Ammo(Item):
def __init__(self):
# def resetallself():
Expand All @@ -27,8 +28,6 @@ def set_settings(self, settings, locations, items, creatures, players):
self.bombs = {player: self.INIT_BOMBS_COUNT for player in players}
self.update_bars()

self.labyrinth.set_unique(self, 'ammo')

def spend(self, ammo_type, player):
if ammo_type == 'bullet':
self.bullets[player] -= 1
Expand Down
5 changes: 2 additions & 3 deletions labyrinth_objects/Vanilla/death.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from labyrinth_engine import Item
from labyrinth_engine import Item, unique


@unique('death')
class Death(Item):
def set_settings(self, settings, locations, items, creatures, players):
self.DEATH_MSG = settings['death_msg']['ru']
Expand All @@ -12,8 +13,6 @@ def set_settings(self, settings, locations, items, creatures, players):
self.death = {player: False for player in players}
self.crt_death = {creature: False for creature in creatures}

self.labyrinth.set_unique(self, 'death')

def revive(self, body, revival_msg=None):
if body.lrtype == 'player':
self.death[body] = False
Expand Down
5 changes: 2 additions & 3 deletions labyrinth_objects/Vanilla/health.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from labyrinth_engine import Item
from labyrinth_engine import Item, unique


@unique('health')
class Health(Item):
def __init__(self):
super().__init__()
Expand All @@ -23,8 +24,6 @@ def set_settings(self, settings, locations, items, creatures, players):
self.hp = {player: self.MAX_PLAYER_HEALTH for player in players}
self.creature_hp = {creature: self.MAX_CREATURE_HEALTH for creature in creatures}

self.labyrinth.set_unique(self, 'health')

self.update_health_bar()

def hurt(self, body, death_msg=None):
Expand Down