This repository has been archived on 2026-06-15. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
The-Adventure-Game/classes/GameBoard.py
T

143 lines
4.5 KiB
Python

from classes.SavedState import SavedState
import my_helpers.myPickle as my_pickle
from simple_term_menu import TerminalMenu
from tabulate import tabulate
import logging
import sys, os, re
LOGGING = logging.getLogger(__name__)
class GameBoard:
def __init__(self, config:dict, save_state_file:dict, map_file:dict):
self.config = config
self.save_state_file = save_state_file
self.map_file = map_file
def make_dict_list_into_table(self, dict_list:dict, change_by_key=None, ignore_keys:list[str]=[]):
dict_keys = list(dict_list.keys())
keys = list(dict_list[dict_keys[0]].keys())
table = [dict_keys]
for key in keys:
row = []
if not key in ignore_keys:
row.append(key)
for element in dict_list.values():
if change_by_key != None:
element[key] = change_by_key(key, element)
row.append(element[key])
table.append(row)
return tabulate(table, headers='firstrow', tablefmt='grid')
def change_character_key(self, key, element):
if key == "fixed_type":
if not element[key]:
return None
return element[key]
def print_story(self, story:str):
print(story)
def create_character(self, player_config:dict, message:str):
self.print_story(message)
while True:
try:
characte_name = input("Enter Character Name: ")
if re.match("[a-zA-Z]", characte_name):
break
except KeyboardInterrupt as e:
LOGGING.debug(e)
sys.exit(1)
print(self.make_dict_list_into_table(player_config["species"], change_by_key=lambda key, element: self.change_character_key(key, element)))
select_species = list(player_config["species"].keys())
m = TerminalMenu(select_species, title='Select a Species')
selection = m.show()
characte_species = player_config["species"][select_species[selection]]
characte_species["name"] = select_species[selection]
if not characte_species["fixed_type"]:
types = [ x["name"] for x in player_config["types"] ]
m = TerminalMenu(types, title='Select a Type')
selection = m.show()
characte_type = (types[selection])
else:
characte_type = characte_species["fixed_type"]
return {
"name": characte_name,
"species": characte_species,
"type": characte_type
}
def find_save_state(self):
if os.path.exists(self.save_state_file['path']):
saved_state:SavedState = self.load_from_file(self.save_state_file)
else:
saved_state = SavedState()
player = self.create_character(self.config["player"], self.config["create_character_message"])
saved_state.add_player(player)
self.save_to_file(saved_state, self.save_state_file)
print()
self.map = self.load_from_file(self.map_file)
self.saved_state = saved_state
return saved_state
def load_from_file(self, file_options):
LOGGING.debug(f"Loading from file: {file_options}")
if os.path.exists(file_options["path"]):
with open(file_options["path"], "rb") as f:
data = my_pickle.load(f, file_options['compression'], None)
LOGGING.debug(f"Loaded {data}")
return data
else:
raise FileNotFoundError(f"Could not load map file: {file_options['path']}")
def save_to_file(self, obj, file_options):
LOGGING.debug(f"Saving Object {obj} To file: {file_options}")
os.makedirs(os.path.dirname(file_options["path"]), exist_ok=True)
with open(file_options["path"], "wb") as f:
my_pickle.dump(obj, f, file_options['compression'], None)
def by_the_place(self):
is_by_a_place = self.saved_state.get_place()
LOGGING.debug(is_by_a_place)
if is_by_a_place:
return self.map[self.saved_state.get_chapter()]["Places"][is_by_a_place]
return self.map[self.saved_state.get_chapter()]["World"][self.saved_state.get_story_moves()]
def replace_keyword_into_place_story(self, place:dict):
story:str = place['story']
story.replace("SPECIES", self.saved_state.get_player().get_species_name())
story.replace("CHARACTER_NAME", self.saved_state.get_player().get_name())
return story
def user_input(self):
while True:
try:
place = self.by_the_place()
LOGGING.debug(place)
print(self.replace_keyword_into_place_story(place))
print()
choice = input(f"{place['name']} || What do you like to do? ")
if choice != None:
break
LOGGING.debug(choice)
self.check_user_input(choice)
except KeyboardInterrupt:
break
def check_user_input(self, choice:str):
pass