diff --git a/config.py b/config.py index 7647084..16b28b1 100644 --- a/config.py +++ b/config.py @@ -10,4 +10,6 @@ RESOLUTION = MAP_RESOLUTION[0], MAP_RESOLUTION[1] + 50 INITIAL_SNAKE_SIZE = 3 +MAX_HIGH_SCORES_COUNT = 10 + SCORES_FILE = 'scores.snake' diff --git a/main.py b/main.py index b80e13e..c03bd51 100644 --- a/main.py +++ b/main.py @@ -1,13 +1,14 @@ import logging import os import pickle +from tkinter import Tk, simpledialog, messagebox import pygame from pygame import locals as pglocals from config import (RESOLUTION, MAP_RESOLUTION, SNAKE_COLOR, BACKGROUND_COLOR, FONT_COLOR, - INITIAL_SNAKE_SIZE, SCORES_FILE) + INITIAL_SNAKE_SIZE, SCORES_FILE, MAX_HIGH_SCORES_COUNT) from objects import Snake, Apple from utils import get_score_text, Direction @@ -33,7 +34,7 @@ def main(): with open(SCORES_FILE, 'rb') as scores_file: scores = pickle.load(scores_file) - logger.info(f'High scores : {scores}') + logger.info(f'Previous high scores : {scores}') while True: screen.fill(BACKGROUND_COLOR) @@ -76,11 +77,6 @@ def main(): dirty_rects = snake.move(screen, apple) if snake.dead: logger.info(f'Vous avez perdu ! Score : {score}') - scores.append({'player': 'PLAYER 1', 'score': score}) - scores = sorted(scores, key=lambda x: x['score'], reverse=True)[:20] - logger.info(f'High scores : {scores}') - with open(SCORES_FILE, 'wb') as scores_file: - pickle.dump(scores, scores_file) break if snake.head.colliderect(apple.rect): @@ -112,6 +108,21 @@ def main(): screen.blit(text, text_rect) pygame.display.flip() + Tk().wm_withdraw() # to hide the main window + username = simpledialog.askstring( + "Enregistrer le score", + f"Entrez votre nom d'utilisateur ou laissez vide pour ne pas enregistrer." + ) + if username: + scores.append({'player': username, 'score': score}) + logger.info(f'Saving {username}: {score}') + scores = sorted(scores, key=lambda x: x['score'], reverse=True)[:MAX_HIGH_SCORES_COUNT] + logger.info(f'New high scores : {scores}') + with open(SCORES_FILE, 'wb') as scores_file: + pickle.dump(scores, scores_file) + else: + logger.debug('Not saving score') + restart = False while not restart: for event in pygame.event.get(): @@ -123,6 +134,9 @@ def main(): if event.key == pglocals.K_r: logger.info('Restarting game') restart = True + elif event.key == pglocals.K_s: + scores_str = '\n'.join(map(lambda s: f"{s['player']} : {s['score']}", scores)) + messagebox.showinfo("Tableau des scores", scores_str) clock.tick(5)