From f25dfddbfce2f937cc87d3e20a70c26f23efedba Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Mon, 30 Apr 2018 22:00:46 +0200 Subject: [PATCH] Extract functions to display end screen and save score --- main.py | 65 ++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 41 insertions(+), 24 deletions(-) diff --git a/main.py b/main.py index c03bd51..b602bb4 100644 --- a/main.py +++ b/main.py @@ -98,30 +98,8 @@ def main(): # Run faster as snake grows clock.tick(min(30, 10 - INITIAL_SNAKE_SIZE + len(snake.slots))) - screen.fill(BACKGROUND_COLOR) - - font = pygame.font.Font(None, 60) - text = font.render(f"PERDU ! Score : {score}", 1, FONT_COLOR) - text_rect = text.get_rect() # type: pygame.Rect - text_rect.center = screen.get_rect().center - - 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') + display_end_screen(screen, score) + scores = save_score(score, scores) restart = False while not restart: @@ -141,5 +119,44 @@ def main(): clock.tick(5) +def save_score(score, scores): + 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') + return scores + + +def display_end_screen(screen, score): + screen.fill(BACKGROUND_COLOR) + font = pygame.font.Font(None, 60) + text = font.render(f"PERDU ! Score : {score}", 1, FONT_COLOR) + text_rect = text.get_rect() # type: pygame.Rect + text_rect.center = screen.get_rect().center + screen.blit(text, text_rect) + font = pygame.font.Font(None, 30) + text = font.render(f"R pour recommencer", 1, FONT_COLOR) + text_rect = text.get_rect() # type: pygame.Rect + text_rect.center = screen.get_rect().center + text_rect.top += 45 + screen.blit(text, text_rect) + text = font.render(f"S pour les scores", 1, FONT_COLOR) + text_rect = text.get_rect() # type: pygame.Rect + text_rect.center = screen.get_rect().center + text_rect.top += 70 + screen.blit(text, text_rect) + pygame.display.flip() + + if __name__ == '__main__': main()