Create game engine class
This commit is contained in:
parent
26a3c13b06
commit
715592c38f
35
engine.py
Normal file
35
engine.py
Normal 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
21
main.py
@ -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__":
|
||||
|
Loading…
Reference in New Issue
Block a user