Add high scores and game restart

This commit is contained in:
Gabriel Augendre 2018-04-29 20:58:38 +02:00
parent 7142c86211
commit 6c12408417
No known key found for this signature in database
GPG key ID: F360212F958357D4
2 changed files with 80 additions and 55 deletions

View file

@ -8,3 +8,5 @@ TILE_SIZE = 20
RESOLUTION = MAP_SIZE[0] * TILE_SIZE, MAP_SIZE[1] * TILE_SIZE
INITIAL_SNAKE_SIZE = 3
SCORES_FILE = 'scores.snake'

27
main.py
View file

@ -1,13 +1,15 @@
import logging
import os
import pickle
import pygame
from pygame import locals as pglocals
from config import RESOLUTION, SNAKE_COLOR, BACKGROUND_COLOR, FONT_COLOR, INITIAL_SNAKE_SIZE
from config import RESOLUTION, SNAKE_COLOR, BACKGROUND_COLOR, FONT_COLOR, INITIAL_SNAKE_SIZE, SCORES_FILE
from objects import Snake, Apple
from utils import get_score_text, Direction
logging.basicConfig(level=logging.WARNING)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
pygame.init()
@ -24,7 +26,15 @@ def main():
screen = pygame.display.set_mode(RESOLUTION) # type: pygame.Surface
pygame.display.set_caption('Snake')
scores = []
if os.path.isfile(SCORES_FILE):
with open(SCORES_FILE, 'rb') as scores_file:
scores = pickle.load(scores_file)
logger.info(f'High scores : {scores}')
while True:
screen.fill(BACKGROUND_COLOR)
snake = Snake()
screen.fill(SNAKE_COLOR, snake.head)
apple = Apple()
@ -54,6 +64,11 @@ def main():
dirty_rects = snake.move(screen, apple)
if snake.dead:
logger.info(f'Vous avez perdu ! Score : {score}')
scores.append(score)
scores = sorted(scores, reverse=True)[:3]
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):
@ -86,10 +101,18 @@ def main():
pygame.display.flip()
while True:
restart = False
for event in pygame.event.get():
if event.type == pglocals.QUIT:
logger.info('Received QUIT event')
logger.info(f'High scores : {scores}')
return
if event.type == pglocals.KEYDOWN:
if event.key == pglocals.K_r:
logger.debug('Restarting game')
restart = True
if restart:
break
clock.tick(5)