Move variables and triggers to be defined in the database

* Variables are now defined in the database, rather than the game
  itself.
* Triggers are now defined in the database, rather than hidden away in a
  method in the game. Custom triggers can now be added as well, in case
  a game needs more complex behavior that isn't necessarily available in
  the base library.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2021-11-18 17:32:45 -08:00
parent 0f6433eabd
commit ff5d4484fe
3 changed files with 31 additions and 20 deletions

View File

@@ -1,6 +1,6 @@
import dataclasses
import textwrap
from typing import Any, MutableMapping, Match, Optional, Sequence
from typing import Any, MutableMapping, List, Match, Optional, Sequence
from agame.action import Action
from agame.color import colorize
from agame.item import Item, ItemInst
@@ -20,6 +20,21 @@ class Database:
items: MutableMapping[str, Item] = dataclasses.field(default_factory=dict)
# All rooms available to the game.
rooms: MutableMapping[str, Room] = dataclasses.field(default_factory=dict)
# All variables available to the game.
vars: MutableMapping[str, Any] = dataclasses.field(default_factory=dict)
# All triggers available to the game.
triggers: List[Trigger] = dataclasses.field(
default_factory=lambda: [
GetTrigger(),
UseTrigger(),
PutTrigger(),
LookTrigger(),
ReadTrigger(),
OpenTrigger(),
CloseTrigger(),
GoTrigger(),
]
)
def add_item(self, item: Item):
self.items[item.id] = item
@@ -35,6 +50,12 @@ class Database:
for room in rooms:
self.add_room(room)
def add_var(self, var: str, value: Any):
self.vars[var] = value
def add_trigger(self, trigger: Trigger):
self.triggers += [trigger]
@dataclasses.dataclass
class Game:
@@ -44,28 +65,15 @@ class Game:
room: Room
# Player inventory.
inventory: MutableMapping[str, ItemInst] = dataclasses.field(default_factory=dict)
# Variables.
vars: MutableMapping[str, Any] = dataclasses.field(default_factory=dict)
def run_command(self, line: str):
line = line.strip()
if not line:
return
triggers: Sequence[Trigger] = [
GetTrigger(),
UseTrigger(),
PutTrigger(),
LookTrigger(),
ReadTrigger(),
OpenTrigger(),
CloseTrigger(),
GoTrigger(),
]
trigger = None
match: Optional[Match] = None
for t in triggers:
for t in self.database.triggers:
match = t.pattern().fullmatch(line)
if match:
trigger = t
@@ -128,3 +136,8 @@ class Game:
def items(self):
"Shortcut property for `game.database.items`."
return self.database.items
@property
def vars(self):
"Shortcut property for `game.database.vars`."
return self.database.vars

View File

@@ -14,5 +14,4 @@ from . import vars
game = Game(
database=database,
room=database.rooms["cabin_inside"],
vars=vars.vars,
)

View File

@@ -1,8 +1,7 @@
"""
Define all game variables here.
"""
from . import database
vars = {
"cabin_door_open": False,
"mailbox_open": False,
}
database.add_var("cabin_door_open", False)
database.add_var("mailbox_open", False)