squirrel-battle/dungeonbattle/menus.py

113 lines
3.6 KiB
Python

import sys
from enum import Enum
from typing import Any, Optional
from .display.texturepack import TexturePack
from .enums import GameMode, KeyValues
from .settings import Settings
class Menu:
values: list
def __init__(self):
self.position = 0
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)
def validate(self) -> Any:
return self.values[self.position]
class MainMenuValues(Enum):
START = 'Jouer'
SETTINGS = 'Paramètres'
EXIT = 'Quitter'
def __str__(self):
return self.value
class MainMenu(Menu):
values = [e for e in MainMenuValues]
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)
class SettingsMenu(Menu):
waiting_for_key: bool = False
def update_values(self, settings: Settings) -> None:
self.values = []
for i, key in enumerate(settings.settings_keys):
s = settings.get_comment(key)
s += " : "
if self.waiting_for_key and i == self.position:
s += "?"
else:
s += getattr(settings, key).replace("\n", "\\n")
s += 8 * " " # Write over old text
self.values.append(s)
self.values.append("")
self.values.append("Changer le pack de textures n'aura effet")
self.values.append("qu'après avoir relancé le jeu.")
self.values.append("")
self.values.append("Retour (espace)")
def handle_key_pressed(self, key: Optional[KeyValues], raw_key: str,
game: Any) -> None:
"""
For now, in the settings mode, we can only go backwards.
"""
if not self.waiting_for_key:
if key == KeyValues.SPACE or \
key == KeyValues.ENTER and \
self.position == len(self.values) - 1:
game.state = GameMode.MAINMENU
if key == KeyValues.DOWN:
self.go_down()
if key == KeyValues.UP:
self.go_up()
if key == KeyValues.ENTER and self.position < len(self.values) - 3:
option = list(game.settings.settings_keys)[self.position]
if option == "TEXTURE_PACK":
game.settings.TEXTURE_PACK = \
TexturePack.get_next_pack_name(
game.settings.TEXTURE_PACK)
game.settings.write_settings()
self.update_values(game.settings)
else:
self.waiting_for_key = True
self.update_values(game.settings)
else:
option = list(game.settings.settings_keys)[self.position]
setattr(game.settings, option, raw_key)
game.settings.write_settings()
self.waiting_for_key = False
self.update_values(game.settings)
class ArbitraryMenu(Menu):
def __init__(self, values: list):
super().__init__()
self.values = values