1
0
Fork 0

Create game engine class

This commit is contained in:
Timothy Warren 2022-01-06 11:28:03 -05:00
parent 26a3c13b06
commit 715592c38f
2 changed files with 41 additions and 15 deletions

35
engine.py Normal file
View File

@ -0,0 +1,35 @@
from typing import Set, Iterable, Any
from tcod.context import Context
from tcod.console import Console
from actions import EscapeAction, MovementAction
from entity import Entity
from input_handlers import EventHandler
class Engine:
def __init__(self, entities: Set[Entity], event_handler: EventHandler, player: Entity):
self.entities = entities
self.event_handler = event_handler
self.player = player
def handle_events(self, events: Iterable[Any]) -> None:
for event in events:
action = self.event_handler.dispatch(event)
if action is None:
continue
if isinstance(action, MovementAction):
self.player.move(dx=action.dx, dy=action.dy)
elif isinstance(action, EscapeAction):
raise SystemExit()
def render(self, console: Console, context: Context) -> None:
for entity in self.entities:
console.print(entity.x, entity.y, entity.char, fg=entity.color)
# Actually output to screen
context.present(console)
console.clear()

21
main.py
View File

@ -1,7 +1,7 @@
#!/usr/bin/env python3
import tcod
from actions import EscapeAction, MovementAction
from engine import Engine
from entity import Entity
from input_handlers import EventHandler
@ -23,6 +23,8 @@ def main() -> None:
npc = Entity(int(screen_width / 2 - 5), int(screen_height / 2), "@", (255, 255, 0))
entities = {npc, player}
engine = Engine(entities, event_handler, player)
with tcod.context.new_terminal(
screen_width,
screen_height,
@ -32,22 +34,11 @@ def main() -> None:
) as context:
root_console = tcod.Console(screen_width, screen_height, order="F")
while True:
root_console.print(x=player.x, y=player.y, string=player.char, fg=player.color)
engine.render(root_console, context)
# Actually display on the screen
context.present(root_console)
root_console.clear()
events = tcod.event.wait()
for event in tcod.event.wait():
action = event_handler.dispatch(event)
if action is None:
continue
if isinstance(action, MovementAction):
player.move(dx=action.dx, dy=action.dy)
elif isinstance(action, EscapeAction):
raise SystemExit()
engine.handle_events(events)
if __name__ == "__main__":