Skip to content

Commit 27fd204

Browse files
committed
Оптимизация
1 parent 61ef080 commit 27fd204

9 files changed

+59
-51
lines changed

CHANGELOG.md

+8-2
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,22 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [1.2.2]
9+
10+
### Изменено
11+
12+
- Оптизированы некоторые части кода, в том числе события и состояние игры
13+
814
## [1.2.1] - 2023-11-24
915

1016
[1.2.1]: https://github.com/kotazzz/krpg/compare/1.2.0...1.2.1
1117

12-
## Изменено
18+
### Изменено
1319

1420
- Перенесены некоторые данные в файлы data/
1521
- Обработка параметров запуска перенесена в `__main__.py`
1622

17-
## Добавлено
23+
### Добавлено
1824

1925
- Добавлены инструменты сборки, позволяющие автоматизировать процесс установки версии
2026
- Теперь black являются частью зависимостей

CODE_OF_CONDUCT.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,13 @@ the community.
116116

117117
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118118
version 2.0, available at
119-
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
119+
<https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.
120120

121121
Community Impact Guidelines were inspired by [Mozilla's code of conduct
122122
enforcement ladder](https://github.com/mozilla/diversity).
123123

124124
[homepage]: https://www.contributor-covenant.org
125125

126126
For answers to common questions about this code of conduct, see the FAQ at
127-
https://www.contributor-covenant.org/faq. Translations are available at
128-
https://www.contributor-covenant.org/translations.
127+
<https://www.contributor-covenant.org/faq>. Translations are available at
128+
<https://www.contributor-covenant.org/translations>.

krpg/actions.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -109,10 +109,9 @@ def get_actions(self) -> list[Action]:
109109
actions.extend(self.actions)
110110
names = {}
111111
for action in actions:
112-
if action.name not in names:
113-
names[action.name] = action
114-
else:
112+
if action.name in names:
115113
raise Exception(f"Same names: {names[action.name]} and {action}")
114+
names[action.name] = action
116115
return actions
117116

118117
def __repr__(self):

krpg/battle.py

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ def predict(self, player: Entity, enemy: Entity) -> int:
3636
# player, enemy - Entity
3737
# actions: 0 - attack, 1 - defend
3838
# Rule format: ([...expressions (str)], action, weight)
39+
# TODO: Lambda functions
3940
rules = [
4041
# If enemy have 50%+ hp, then attack
4142
(["enemy.hp / enemy.max_hp >= 0.5"], 0, 1),

krpg/builder.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -206,10 +206,7 @@ def build_action(self, command: Section):
206206
name, description = command.args
207207
block = self.game.executer.create_block(command)
208208

209-
def new_command(game: Game):
210-
block.run()
211-
212-
return action(name, description)(new_command)
209+
return action(name, description)(block.run)
213210

214211
def build_triggers(self, triggers: Section | None):
215212
# Build triggers for a location in the game

krpg/events.py

+24-27
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,46 @@
11
from collections import defaultdict
2+
from enum import StrEnum, auto
23
from typing import Callable
34

45

5-
class Events:
6+
class Events(StrEnum):
67
# clock.py
7-
TIMEPASS = "timepass" # minutes: int
8-
NEWDAY = "newday" # day: int
8+
TIMEPASS = auto() # minutes: int
9+
NEWDAY = auto() # day: int
910

1011
# game.py
11-
SAVE = "save" # -
12-
LOAD = "load" # successcb=None
13-
STATE_CHANGE = "state_change" # state: str
14-
COMMAND = "command" # command: str
12+
SAVE = auto() # -
13+
LOAD = auto() # successcb=None
14+
STATE_CHANGE = auto() # state: str
15+
COMMAND = auto() # command: str
1516

1617
# player.py
17-
PICKUP = "pickup" # item: Item, amount: int
18-
ADD_MONEY = "add_money" # amount: int, new_balance: int
19-
REMOVE_MONEY = "remove_money" # amount: int, new_balance: int
20-
ADD_FREE = "add_free" # amount: int, new_balance: int
21-
REMOVE_FREE = "remove_free" # amount: int, new_balance: int
22-
HEAL = "heal" # amount: int
23-
DAMAGE = "damage" # amount: int
24-
DEAD = "dead" # -
18+
PICKUP = auto() # item: Item, amount: int
19+
ADD_MONEY = auto() # amount: int, new_balance: int
20+
REMOVE_MONEY = auto() # amount: int, new_balance: int
21+
ADD_FREE = auto() # amount: int, new_balance: int
22+
REMOVE_FREE = auto() # amount: int, new_balance: int
23+
HEAL = auto() # amount: int
24+
DAMAGE = auto() # amount: int
25+
DEAD = auto() # -
2526

2627
# world.py
27-
WORLD_ITEM_TAKE = "world_item_take" # item_id: str, remain: int
28-
WORLD_ITEM_DROP = "world_item_drop" # item_id: str, count: int
29-
MOVE = "move" # before: Location, after: Location
28+
WORLD_ITEM_TAKE = auto() # item_id: str, remain: int
29+
WORLD_ITEM_DROP = auto() # item_id: str, count: int
30+
MOVE = auto() # before: Location, after: Location
3031

3132
# settings.py
32-
SETTING_CHANGE = "setting_change" # setting: str, value: Any
33+
SETTING_CHANGE = auto() # setting: str, value: Any
3334

3435
# battle.py
35-
KILL = "kill" # monster_id: str
36+
KILL = auto() # monster_id: str
3637

3738
# quests.py
38-
QUEST_START = "quest_start" # quest_id: str
39+
QUEST_START = auto() # quest_id: str
3940

4041
# nps.py
41-
NPC_MEET = "npc_meet" # npc_id: str
42-
NPC_STATE = "npc_state" # npc_id: str, state: str
42+
NPC_MEET = auto() # npc_id: str
43+
NPC_STATE = auto() # npc_id: str, state: str
4344

4445

4546
class EventHandler:
@@ -48,9 +49,6 @@ def __init__(self, *lookup: object):
4849
for obj in lookup:
4950
self.lookup(obj)
5051

51-
def lock(self):
52-
self._lock = True
53-
5452
def listen(self, event: str, callback: Callable):
5553
self.listeners[event].append(callback)
5654

@@ -63,7 +61,6 @@ def lookup(self, obj: object):
6361
def dispatch(self, event: str, *args, **kwargs):
6462
for listener in self.listeners["*"] + self.listeners["event"]:
6563
listener(event, *args, **kwargs)
66-
6764
if event not in ["*", "event"]:
6865
for listener in self.listeners[event]:
6966
listener(*args, **kwargs)

krpg/executer.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def print_block_command(game: Game):
9191

9292
self.print_block_command = print_block_command
9393

94-
def run(self, from_start: bool = True):
94+
def run(self, from_start: bool = True, *args, **kwargs):
9595
"""
9696
Runs the block of code.
9797

krpg/game.py

+18-11
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,21 @@
3333
from krpg.settings import Settings
3434
from krpg.stats import StatsManager
3535
from krpg.world import World
36+
from enum import Enum
3637

3738

39+
class GameState(Enum):
40+
NONE = 0
41+
PLAYING = 1
42+
EXIT = 2
43+
DEAD = 3
44+
3845
class Game:
3946
savers: dict[str, set[callable, callable]] = {}
4047

4148
def __init__(self, debug_mode: bool = False):
4249
self.version = __version__
43-
self.state = "none"
50+
self.state = GameState.NONE
4451
self.console = KrpgConsole()
4552
self.log = self.console.log
4653
self.set_debug(debug_mode)
@@ -128,7 +135,7 @@ def main_menu(self):
128135
self.console.set_bar(
129136
f"[magenta]K[/][red]-[/][blue]R[/][yellow]P[/][green]G[/] {random.choice(BRAND_COLORS)}{self.version}[/]"
130137
)
131-
while self.state != "playing":
138+
while self.state != GameState.PLAYING:
132139
menu = {
133140
"start": "Начать новую игру",
134141
"load": "Загрузить сохранение",
@@ -172,7 +179,7 @@ def main_menu(self):
172179
self.executer.create_block(init).run()
173180
self.world.set()
174181
self.world.current.locked = False
175-
self.events.dispatch(Events.STATE_CHANGE, state="playing")
182+
self.events.dispatch(Events.STATE_CHANGE, state=GameState.PLAYING)
176183

177184
elif select == "load":
178185
self.new_game()
@@ -185,15 +192,15 @@ def main_menu(self):
185192
def playing(self):
186193

187194
try:
188-
while self.state == "playing":
195+
while self.state == GameState.PLAYING:
189196
self.console.set_bar(f"[yellow]{self.player.name}[/]")
190197
actions = self.actions.get_actions()
191198
cmds_data = {cmd.name: cmd.description for cmd in actions}
192199
cmd = self.console.prompt(1, cmds_data)
193200
self.events.dispatch(Events.COMMAND, command=cmd)
194201
except KeyboardInterrupt:
195202
self.console.print("[red]Выход из игры[/]")
196-
self.state = "None"
203+
self.state = GameState.NONE
197204

198205
def timestamp(self):
199206
return int(time.time()) - TIMESHIFT
@@ -219,12 +226,12 @@ def deco(*args, **kwargs):
219226
)
220227

221228
def on_dead(self):
222-
self.events.dispatch(Events.STATE_CHANGE, "dead")
229+
self.events.dispatch(Events.STATE_CHANGE, GameState.DEAD)
223230

224-
def on_state_change(self, state):
231+
def on_state_change(self, state: GameState):
225232
old = self.state
226233
self.state = state
227-
if old != "playing" and state == "playing":
234+
if old != GameState.PLAYING and state == GameState.PLAYING:
228235
self.playing()
229236

230237
def on_save(self):
@@ -273,7 +280,7 @@ def on_load(self):
273280
self.log.exception(e)
274281
else:
275282
self.console.print("[green]Игра загружена[/]")
276-
self.events.dispatch(Events.STATE_CHANGE, state="playing")
283+
self.events.dispatch(Events.STATE_CHANGE, state=GameState.PLAYING)
277284
return
278285

279286
def on_event(self, event, *args, **kwargs):
@@ -306,7 +313,7 @@ def show_logo(self):
306313
"{0}│ ╰─╮{1} {2}│ ╭──╮ │{3}│ ╭───╯{4}│ ││ │\n"
307314
"{0}│ ╭─╮ │{1} {2}│ │ │ │{3}│ │ {4}│ ╰╯ │\n"
308315
"{0}╰───╯ ╰─╯{1} {2}╰───╯ ╰─╯{3}╰───╯ {4}╰───────╯\n".format(
309-
*clrs
316+
*BRAND_COLORS
310317
)
311318
)
312319
)
@@ -364,7 +371,7 @@ def action_guide(game: Game):
364371

365372
@action("exit", "Выйти из игры", "Игра")
366373
def action_exit(game: Game):
367-
game.state = "exit"
374+
game.state = GameState.EXIT
368375

369376
@action("save", "Сохранить игру", "Игра")
370377
def action_save(game: Game):

krpg/world.py

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313

1414
class Location:
15+
1516
def __init__(self, id: str, name: str, description: str):
1617
self.id = id
1718
self.name = name

0 commit comments

Comments
 (0)