2022-2023/1NSI/00_Projets/snake_corr.py

181 lines
5.2 KiB
Python

"""
Snake pour l'ISN
"""
import pygame
from random import randint
def draw_grid():
""" Dessine la grille """
for i in range(COLUMN+1):
pygame.draw.line(screen, WHITE, (i*CELLSIZE, 0), (i*CELLSIZE, ROW*CELLSIZE))
for i in range(ROW+1):
pygame.draw.line(screen, WHITE, (0, i*CELLSIZE), (COLUMN*CELLSIZE, i*CELLSIZE))
def draw_snake(snake):
""" Dessine le serpent """
for i, j in snake:
top_left = (i * CELLSIZE, j * CELLSIZE)
pygame.draw.rect(screen, GREEN, (*top_left, CELLSIZE, CELLSIZE))
def draw_cherry(cherry):
""" Dessine les cherry (bonus) """
center = (int((cherry[0] + 0.5) * CELLSIZE), int((cherry[1] + 0.5) * CELLSIZE))
radius = int(0.5*CELLSIZE)
pygame.draw.circle(screen, RED, center, radius)
def draw_right(score):
""" Dessine la partie droite de la fenête """
width_right_bar = s_width - COLUMN*CELLSIZE
top_left_right_bar = (COLUMN*CELLSIZE, 0)
title = TITLEFONT.render("SNAKE", True, WHITE)
title_rect = title.get_rect()
title_rect.centerx = int(top_left_right_bar[0] + width_right_bar/2)
title_rect.centery = 50
screen.blit(title, title_rect)
score_text = "Score " + str(score)
score = TEXTFONT.render(score_text, True, WHITE)
score_rect = score.get_rect()
score_rect.centerx = int(top_left_right_bar[0] + width_right_bar/2)
score_rect.centery = 100
screen.blit(score, score_rect)
def random_place(row, col):
""" Retourne un lieu aléatoire sur la grille """
return [randint(0, row-1), randint(0, col-1)]
def move_snake(snake, snake_direction, growing):
""" Retourne la nouvelle position du snake
Si growing est True, on ne supprime par le dernier élément de la queue pour que le serpent grandisse
L'idée est de trouver les coordonnées de la nouvelle tête (new_head) puis de coller le corp du serpent (en supprimant la dernière partie si l'on veut que le serpent de grandisse pas.
"""
new_head = [snake[0][0] + snake_direction[0], snake[0][1] + snake_direction[1]]
if growing:
return [new_head] + snake
else:
# [:-1] permet de dire que l'on veut la liste sauf le dernier élément.
return [new_head] + snake[:-1]
def is_out(snake):
""" Retourne True si le snake est sorti de la grille """
# le snake[0] est la tête du serpent.
return snake[0][0] > COLUMN or \
snake[0][0] < 0 or \
snake[0][1] > ROW or\
snake[0][1] < 0
def is_eating_queue(snake):
""" Retourne True si le serpent se mort la queue """
# On se demande si la tête du serpent est dans (in) la queue dans ce cas il se mort la queue
return snake[0] in snake[1:]
def is_eating(snake, cherry):
""" Retroune True si le snake mange la cherry"""
return snake[0] == cherry
# Call this function so the Pygame library can initialize itself
pygame.init()
# --- Globals ---
# Colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
# font
TITLEFONT = pygame.font.SysFont(None, 48)
TEXTFONT = pygame.font.SysFont(None, 30)
# THE GRID
ROW = 20
COLUMN = 20
# CELL
CELLSIZE = 20
# Create an 800x600 sized screen
s_width = COLUMN * CELLSIZE + 200
s_height = ROW * CELLSIZE + 1
screen = pygame.display.set_mode([s_width, s_height])
# Set the title of the window
pygame.display.set_caption('Snake')
clock = pygame.time.Clock()
# The snake
snake = [[5, 5], [4, 5], [3, 5]]
snake_direction = [1, 0]
# The cherry
cherry = random_place(ROW, COLUMN)
# The score
score = 0
growing = False
running = True
while running:
# Event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
# On empèche que le snake fasse demi tour
if event.key == pygame.K_UP:
if snake_direction != [0, 1]:
snake_direction = [0, -1]
elif event.key == pygame.K_DOWN:
if snake_direction != [0, -1]:
snake_direction = [0, 1]
elif event.key == pygame.K_LEFT:
if snake_direction != [1, 0]:
snake_direction = [-1, 0]
elif event.key == pygame.K_RIGHT:
if snake_direction != [-1, 0]:
snake_direction = [1, 0]
# Move the snake
if growing:
snake = move_snake(snake, snake_direction, True)
growing = False
else:
snake = move_snake(snake, snake_direction, False)
# Draw elements
screen.fill(BLACK)
draw_grid()
draw_right(score)
draw_snake(snake)
draw_cherry(cherry)
# Flip screen
pygame.display.flip()
if is_eating(snake, cherry):
score = score + 1
growing = True
cherry = random_place(ROW, COLUMN)
# loosing!
if is_out(snake) or is_eating_queue(snake):
screen.fill(BLACK)
text = TITLEFONT.render('You loose!!', True, BLACK,WHITE)
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(text, textRect)
pygame.display.flip()
pygame.time.wait(1000)
running = False
# Pause
clock.tick(2)
pygame.quit()