/
ap1k
/
PyGame_Practice
Обзор
Документация
Войти
/
ap1k
/
PyGame_Practice
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/core/game_state.py
91 строка
3 KB
Roman
The all game
27 май 2025, 15:26
27 май 2025, 15:26
4ea7de9
Код
Авторство
О чём код?
""" GameState class - manages the state of the game Implements the Singleton pattern to ensure only one state instance exists """ import json import os class GameState: """ Game state manager implementing Singleton pattern Responsible for tracking game statistics and state """ _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(GameState, cls).__new__(cls) cls._instance._initialized = False return cls._instance def __init__(self): if self._initialized: return # Game statistics self.score = 0 self.enemies_destroyed = 0 self.time_played = 0 self.current_weapon = 0 # Index of the current weapon # Game state flags self.game_over = False self.paused = False # Leaderboard self.leaderboard = [] self.load_leaderboard() self._initialized = True def reset(self): """Reset the game state for a new game""" self.score = 0 self.enemies_destroyed = 0 self.time_played = 0 self.current_weapon = 0 self.game_over = False self.paused = False def load_leaderboard(self): """Load the leaderboard from a JSON file""" leaderboard_path = "leaderboard.json" if os.path.exists(leaderboard_path): try: with open(leaderboard_path, 'r') as f: self.leaderboard = json.load(f) except (json.JSONDecodeError, IOError): # If there's an error loading the file, start with an empty leaderboard self.leaderboard = [] else: # If the file doesn't exist, start with an empty leaderboard self.leaderboard = [] def save_leaderboard(self): """Save the leaderboard to a JSON file""" leaderboard_path = "leaderboard.json" try: with open(leaderboard_path, 'w') as f: json.dump(self.leaderboard, f) except IOError: print("Error saving leaderboard") def add_to_leaderboard(self, player_name): """Add the current score to the leaderboard""" entry = { "name": player_name, "score": self.score, "enemies": self.enemies_destroyed, "time": self.time_played } # Add the entry and sort the leaderboard by score (descending) self.leaderboard.append(entry) self.leaderboard.sort(key=lambda x: x["score"], reverse=True) # Keep only the top 10 scores if len(self.leaderboard) > 10: self.leaderboard = self.leaderboard[:10] # Save the updated leaderboard self.save_leaderboard()