def save(): # Delete old save file if any PlayerData.delete() # Init dictionary to save savedData = { 'player': Player.get(), 'time_saved': time.time(), 'grid': screens.game.map.grid.Grid.get(), 'story': story.getCurrent() } # Generate json text data json_data = json.dumps(savedData) # Generate and set UUID fileid = str(uuid.uuid3(uuid.NAMESPACE_URL, json_data)) Player.fileid = fileid # Save to file File('./appdata/saves/{}.json'.format(fileid)).writeJson(savedData) # Cool beep sound.saved.play(withVolume=0.5) # Tell user game is saved Alert(type='notify', title='Game Saved', content='You have saved the game.').do()
class Enemy: enemies = File('./gamefiles/enemies.json').readJson() stats = None name = None Enemy = dict() @staticmethod def load(name: str): # Set the enemy Enemy.name = name Enemy.Enemy = Enemy.enemies[name].copy() Enemy.stats = Stats(damage=Enemy.Enemy['stats']['damage'].copy(), defence=Enemy.Enemy['stats']['defence'], health=Enemy.Enemy['stats']['health'].copy()) # Set multiplier if Enemy.enemies['day_saturation'] == -1: saturation = 0 else: saturation = ( (Player.stats.day // Enemy.enemies['day_saturation']) * 0.15) Enemy.stats.multiply(Enemy.enemies['start_multiplier'] + saturation) @staticmethod def reset(): Enemy.stats = None Enemy.name = None Enemy.Enemy = dict()
def add() -> int: # Store data is dict win_data = { 'nickname': Player.nickname, 'win_time': time.time(), 'difficulty': Player.difficulty, 'days': Player.stats.day } # Generate json text data json_data = json.dumps(win_data) # Generate UUID based on win data rankid = str(uuid.uuid3(uuid.NAMESPACE_URL, json_data)) # Add to leaderboard data PlayerRank.rankData[rankid] = win_data # Sort the rank based on days PlayerRank.rankData = dict( sorted(PlayerRank.rankData.items(), key=lambda x: x[1]['days'])) # playerRank.save() # Save updated back to file File(filepath).writeJson(PlayerRank.rankData) return rankid
class Difficulty: modes = File('./gamefiles/difficulty.json').readJson() @staticmethod def set(mode: str = None): # Get current difficulty current_mode = Difficulty.get(mode) # Settings for attack Enemy.enemies['run_chance'] = current_mode['run'] Enemy.enemies['appear_chance'] = current_mode['enemy'] Enemy.enemies['start_multiplier'] = current_mode['start_multiplier'] Enemy.enemies['day_saturation'] = current_mode['day_saturation'] for name, chance in current_mode['enemy_chance'].items(): Enemy.enemies[name]['chance'] = chance # Settings for orb Orb.change = current_mode['orb_change'] # Settings for rest rest.maxGain = current_mode['rest_gain'] @staticmethod def get(mode=None) -> dict: # Gets the difficulty settings if mode == None: return Difficulty.modes[Player.difficulty] if type(mode) == int: return Difficulty.modes[Difficulty.getName(mode)] else: return Difficulty.modes[mode] @staticmethod def getName(index: int) -> str: # Gets the difficulty name return list(Difficulty.modes.keys())[index] @staticmethod def updateName(index: int): difficulty_item = screens.new_game.options.difficulty # Get name of mode difficulty_item.index = (difficulty_item.index + index) % len( Difficulty.modes) # Set mode text difficulty_item.mode.setText(Difficulty.getName(difficulty_item.index)) @staticmethod def setName(index: int): difficulty_item = screens.new_game.options.difficulty # Get name of mode difficulty_item.index = index # Set mode text difficulty_item.mode.setText(Difficulty.getName(index))
def rename(newname, rankid) -> str: # Remove the rank with old name update_rank = PlayerRank.rankData[rankid].copy() del PlayerRank.rankData[rankid] # Change name and add back rank update_rank['nickname'] = newname Player.nickname = newname new_rankid = str( uuid.uuid3(uuid.NAMESPACE_URL, json.dumps(update_rank))) PlayerRank.rankData[new_rankid] = update_rank # Sort the rank based on days PlayerRank.rankData = dict( sorted(PlayerRank.rankData.items(), key=lambda x: x[1]['days'])) # Save the updated nickname data File(filepath).writeJson(PlayerRank.rankData) return new_rankid
def check(): # Ensure that leaderboard data is not tempered with checkedData = PlayerRank.rankData.copy() missmatch = False for rankid, data in PlayerRank.rankData.items(): # Generate json text data json_data = json.dumps(data) # Check UUID match checkid = str(uuid.uuid3(uuid.NAMESPACE_URL, json_data)) if checkid != rankid: del checkedData[rankid] missmatch = True logger.warning( 'Leaderboard data with rankid {} is tempered. Removing...'. format(rankid)) # Reload data without those tempered with if missmatch: PlayerRank.rankData = checkedData File(filepath).writeJson(PlayerRank.rankData)
from code.logic.player import Player from code.logic.orb import Orb from code.logic.story import story from code.logic.difficulty import Difficulty from code.logic.store import Store ################# # Setup logging # ################# filename = os.path.basename(__file__).split('.')[0] logger = log.get_logger(filename) # Ensure that saves folder is created File('./appdata/saves/').createPath() ################## # Gameplay logic # ################## class PlayerData: @staticmethod def new(): Grid = screens.game.map.grid.Grid # Check if nickname is valid if not screens.new_game.options.nickname.text.validateText(): return # Unload previous states
for name, messages in stories.items(): setattr(self, name, message(name, messages)) def __getattr__(self, name): try: return self.__dict__[name] except: logger.error('Error getting story {}'.format(name), exc_info=True) return self.__dict__['_default'] def getCurrent(self) -> str: return screens.game.info.story.message.text def setCurrent(self, Message: str): screens.game.info.story.message.setText(Message) class message(coreFunc): def __init__(self, name: str, messages: list): self.name = name self.messages = messages def display(self, *placeholder): # Show the selected story to game screen message = random.choice(self.messages) screens.game.info.story.message.setText(message.format(*placeholder)) # Get stories story = Story(File('./gamefiles/stories.json').readJson())
class PlayerRank: # Get leaderboard data rankData = File(filepath).readJson(dict()) @staticmethod def check(): # Ensure that leaderboard data is not tempered with checkedData = PlayerRank.rankData.copy() missmatch = False for rankid, data in PlayerRank.rankData.items(): # Generate json text data json_data = json.dumps(data) # Check UUID match checkid = str(uuid.uuid3(uuid.NAMESPACE_URL, json_data)) if checkid != rankid: del checkedData[rankid] missmatch = True logger.warning( 'Leaderboard data with rankid {} is tempered. Removing...'. format(rankid)) # Reload data without those tempered with if missmatch: PlayerRank.rankData = checkedData File(filepath).writeJson(PlayerRank.rankData) @staticmethod def add() -> int: # Store data is dict win_data = { 'nickname': Player.nickname, 'win_time': time.time(), 'difficulty': Player.difficulty, 'days': Player.stats.day } # Generate json text data json_data = json.dumps(win_data) # Generate UUID based on win data rankid = str(uuid.uuid3(uuid.NAMESPACE_URL, json_data)) # Add to leaderboard data PlayerRank.rankData[rankid] = win_data # Sort the rank based on days PlayerRank.rankData = dict( sorted(PlayerRank.rankData.items(), key=lambda x: x[1]['days'])) # playerRank.save() # Save updated back to file File(filepath).writeJson(PlayerRank.rankData) return rankid @staticmethod def rename(newname, rankid) -> str: # Remove the rank with old name update_rank = PlayerRank.rankData[rankid].copy() del PlayerRank.rankData[rankid] # Change name and add back rank update_rank['nickname'] = newname Player.nickname = newname new_rankid = str( uuid.uuid3(uuid.NAMESPACE_URL, json.dumps(update_rank))) PlayerRank.rankData[new_rankid] = update_rank # Sort the rank based on days PlayerRank.rankData = dict( sorted(PlayerRank.rankData.items(), key=lambda x: x[1]['days'])) # Save the updated nickname data File(filepath).writeJson(PlayerRank.rankData) return new_rankid @staticmethod def getPos() -> int: for postion, data in enumerate(PlayerRank.rankData.values(), 1): # Found postion in data if data['nickname'] == Player.nickname and data[ 'days'] == Player.stats.day: return postion # Not found return -1 @staticmethod def showList(page: int = 1): # Unload first screens.leaderboard.unload() # Load the background screens.leaderboard.loadBackground() # Set board paging page = Board.setPage(screen='leaderboard', number_of_files=len(PlayerRank.rankData), page=page) # Set board next and back arrows Board.arrowsState('leaderboard') # Load up board screens.leaderboard.board.load(withItems='all', refresh=True) # No leaderboard if len(PlayerRank.rankData) == 0: screens.leaderboard.display() return # Get data list_data = list(PlayerRank.rankData.values()) # Load up list for i in range(4): current_postion = (i + (page - 1) * 4) # Number of leaderboard less than 4 page if current_postion > len(PlayerRank.rankData) - 1: break # Set list surface base on savefile data list_surface = screens.leaderboard['list_{}'.format(i + 1)] # Set state based on rank if current_postion + 1 <= 3: list_surface.rank.switchState('Special', False) else: list_surface.rank.switchState('', False) # Update data list_surface.rank.postion.setText(str(current_postion + 1), withDisplay=False) list_surface.rank.nickname.setText(str( list_data[current_postion]['nickname']), withDisplay=False) list_surface.rank.days.setText(str( list_data[current_postion]['days']), withDisplay=False) # load the list surface list_surface.load(withItems=['rank'], refresh=True) # Display new list screens.leaderboard.display() @staticmethod def updateList(page: int): PlayerRank.showList(int(Board.currentPage('leaderboard')) + page)