squirrel-battle/dungeonbattle/game.py

98 lines
3.0 KiB
Python

import sys
from typing import Any
from .entities.player import Player
from .interfaces import Map
from .mapdisplay import MapDisplay
from .settings import Settings
from enum import Enum, auto
from . import menus
class GameMode(Enum):
MAINMENU = auto()
PLAY = auto()
SETTINGS = auto()
INVENTORY = auto()
class KeyValues(Enum):
UP = auto()
DOWN = auto()
LEFT = auto()
RIGHT = auto()
ENTER = auto()
class Game:
INSTANCE = None
def init(self) -> None:
Game.INSTANCE = self
self.state = GameMode.MAINMENU
self.main_menu = menus.MainMenu()
self.settings = Settings()
self.settings.load_settings()
self.settings.write_settings()
def new_game(self) -> None:
# TODO generate a new map procedurally
self.m = Map.load("example_map.txt")
self.player = Player()
self.player.move(y, x)
self.m.add_entity(self.player)
self.d = MapDisplay(self.m, self.player)
@staticmethod
def load_game(filename: str) -> None:
# TODO loading map from a file
raise NotImplementedError()
def run(self, screen: Any) -> None:
while True:
screen.clear()
screen.refresh()
self.d.display(self.player.y, self.player.x)
key = screen.getkey()
self.handle_key_pressed(self.translate_key(key))
def translate_key(self, key: str) -> KeyValues:
if key in (self.settings.KEY_DOWN_SECONDARY,
self.settings.KEY_DOWN_PRIMARY):
return KeyValues.DOWN
elif key in (self.settings.KEY_LEFT_PRIMARY,
self.settings.KEY_LEFT_SECONDARY):
return KeyValues.LEFT
elif key in (self.settings.KEY_RIGHT_PRIMARY,
self.settings.KEY_RIGHT_SECONDARY):
return KeyValues.RIGHT
elif key in (self.settings.KEY_UP_PRIMARY,
self.settings.KEY_UP_SECONDARY):
return KeyValues.UP
elif key == self.settings.KEY_ENTER:
return KeyValues.ENTER
def handle_key_pressed(self, key: KeyValues) -> None:
if self.state == GameMode.PLAY:
if key == KeyValues.UP:
self.player.move_up()
if key == KeyValues.DOWN:
self.player.move_down()
if key == KeyValues.LEFT:
self.player.move_left()
if key == KeyValues.RIGHT:
self.player.move_right()
if self.state == GameMode.MAINMENU:
if key == KeyValues.DOWN:
self.main_menu.go_down()
if key == KeyValues.UP:
self.main_menu.go_up()
if key == KeyValues.ENTER:
option = self.main_menu.validate()
if option == menus.MainMenuValues.START:
self.state = GameMode.PLAY
elif option == menus.MainMenuValues.SETTINGS:
self.state = GameMode.SETTINGS
elif option == menus.MainMenuValues.EXIT:
sys.exit(0)