Extract functions to display end screen and save score

This commit is contained in:
Gabriel Augendre 2018-04-30 22:00:46 +02:00
parent 04b341b046
commit f25dfddbfc
No known key found for this signature in database
GPG key ID: F360212F958357D4

65
main.py
View file

@ -98,30 +98,8 @@ def main():
# Run faster as snake grows # Run faster as snake grows
clock.tick(min(30, 10 - INITIAL_SNAKE_SIZE + len(snake.slots))) clock.tick(min(30, 10 - INITIAL_SNAKE_SIZE + len(snake.slots)))
screen.fill(BACKGROUND_COLOR) display_end_screen(screen, score)
scores = save_score(score, scores)
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')
restart = False restart = False
while not restart: while not restart:
@ -141,5 +119,44 @@ def main():
clock.tick(5) 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__': if __name__ == '__main__':
main() main()