squirrel-battle/dungeonbattle/menus.py

90 lines
2.5 KiB
Python
Raw Normal View History

2020-11-11 21:22:33 +00:00
import sys
2020-11-08 22:26:54 +00:00
from enum import Enum
2020-11-11 21:45:15 +00:00
from typing import Any, Optional
2020-11-11 21:22:33 +00:00
from .enums import GameMode, KeyValues
from .settings import Settings
2020-11-06 15:40:43 +00:00
2020-11-06 15:20:07 +00:00
class Menu:
2020-11-06 17:11:59 +00:00
values: list
2020-11-06 15:40:43 +00:00
def __init__(self):
2020-11-06 15:20:07 +00:00
self.position = 0
2020-11-06 17:11:59 +00:00
def go_up(self) -> None:
self.position = max(0, self.position - 1)
def go_down(self) -> None:
self.position = min(len(self.values) - 1, self.position + 1)
2020-11-06 17:25:02 +00:00
def validate(self) -> Any:
2020-11-06 15:40:43 +00:00
return self.values[self.position]
2020-11-06 17:11:59 +00:00
2020-11-06 15:40:43 +00:00
class MainMenuValues(Enum):
2020-11-08 21:59:11 +00:00
START = 'Jouer'
SETTINGS = 'Paramètres'
EXIT = 'Quitter'
2020-11-06 15:40:43 +00:00
2020-11-10 19:22:53 +00:00
def __str__(self):
return self.value
2020-11-06 17:11:59 +00:00
2020-11-06 15:40:43 +00:00
class MainMenu(Menu):
2020-11-06 17:11:59 +00:00
values = [e for e in MainMenuValues]
2020-11-06 15:40:43 +00:00
2020-11-11 21:22:33 +00:00
def handle_key_pressed(self, key: KeyValues, game: Any) -> None:
"""
In the main menu, we can navigate through options.
"""
if key == KeyValues.DOWN:
self.go_down()
if key == KeyValues.UP:
self.go_up()
if key == KeyValues.ENTER:
option = self.validate()
if option == MainMenuValues.START:
game.state = GameMode.PLAY
elif option == MainMenuValues.SETTINGS:
game.state = GameMode.SETTINGS
elif option == MainMenuValues.EXIT:
sys.exit(0)
2020-11-11 19:36:43 +00:00
class SettingsMenu(Menu):
waiting_for_key: bool = False
2020-11-11 19:36:43 +00:00
def update_values(self, settings: Settings) -> None:
s = settings.dumps_to_string()
2020-11-11 19:36:43 +00:00
self.values = s[6:-2].replace("\"", "").split(",\n ")
2020-11-11 21:45:15 +00:00
def handle_key_pressed(self, key: Optional[KeyValues], raw_key: str,
game: Any) -> None:
2020-11-11 21:22:33 +00:00
"""
For now, in the settings mode, we can only go backwards.
"""
if not self.waiting_for_key:
if key == KeyValues.SPACE:
game.state = GameMode.MAINMENU
if key == KeyValues.DOWN:
self.go_down()
if key == KeyValues.UP:
self.go_up()
if key == KeyValues.ENTER:
option = self.validate().split(": ")[0]
if option != "TEXTURE_PACK":
self.waiting_for_key = True
else:
2020-11-11 21:22:33 +00:00
option = self.validate().split(": ")[0]
setattr(game.settings, option, raw_key)
game.settings.write_settings()
self.update_values(game.settings)
self.waiting_for_key = False
2020-11-11 21:22:33 +00:00
2020-11-06 15:40:43 +00:00
2020-11-06 17:32:51 +00:00
class ArbitraryMenu(Menu):
2020-11-06 17:11:59 +00:00
def __init__(self, values: list):
2020-11-06 17:32:51 +00:00
super().__init__()
2020-11-06 17:11:59 +00:00
self.values = values