pygstormgames/scoreboard.py

134 lines
4.0 KiB
Python

"""Scoreboard management module for PygStormGames.
Handles high score tracking with player names and score management.
"""
import pyglet
import time
class Scoreboard:
"""Handles score tracking and high score management."""
def __init__(self, game):
"""Initialize scoreboard system.
Args:
game (PygStormGames): Reference to main game object
"""
self.game = game
self.currentScore = 0
self.highScores = []
# Initialize high scores section in config
try:
self.game.config.localConfig.add_section("scoreboard")
except:
pass
# Load existing high scores
self._loadHighScores()
def _loadHighScores(self):
"""Load high scores from config file."""
self.highScores = []
for i in range(1, 11):
try:
score = self.game.config.get_int("scoreboard", f"score_{i}")
name = self.game.config.get_value("scoreboard", f"name_{i}", "Player")
self.highScores.append({
'name': name,
'score': score
})
except:
self.highScores.append({
'name': "Player",
'score': 0
})
# Sort high scores by score value in descending order
self.highScores.sort(key=lambda x: x['score'], reverse=True)
def get_score(self):
"""Get current score.
Returns:
int: Current score
"""
return self.currentScore
def get_high_scores(self):
"""Get list of high scores.
Returns:
list: List of high score dictionaries
"""
return self.highScores
def decrease_score(self, points=1):
"""Decrease the current score.
Args:
points (int): Points to decrease by
"""
self.currentScore -= int(points)
def increase_score(self, points=1):
"""Increase the current score.
Args:
points (int): Points to increase by
"""
self.currentScore += int(points)
def check_high_score(self):
"""Check if current score qualifies as a high score.
Returns:
int: Position (1-10) if high score, None if not
"""
for i, entry in enumerate(self.highScores):
if self.currentScore > entry['score']:
return i + 1
return None
def add_high_score(self):
"""Add current score to high scores if it qualifies.
Returns:
bool: True if score was added, False if not
"""
position = self.check_high_score()
if position is None:
return False
# Get player name
self.game.speech.speak("New high score! Enter your name:")
name = self.game.display.get_input("New high score! Enter your name:", "Player")
if name is None: # User cancelled
name = "Player"
# Insert new score at correct position
self.highScores.insert(position - 1, {
'name': name,
'score': self.currentScore
})
# Keep only top 10
self.highScores = self.highScores[:10]
# Save to config
for i, entry in enumerate(self.highScores):
self.game.config.set_value("scoreboard", f"score_{i+1}", str(entry['score']))
self.game.config.set_value("scoreboard", f"name_{i+1}", entry['name'])
# Force window refresh after dialog
self.game.display.window.dispatch_events()
self.game.speech.speak(f"Congratulations {name}! You got position {position} on the scoreboard!")
time.sleep(1)
# Make sure window is still responsive
self.game.display.window.dispatch_events()
return True