pygame
pygame
import time
import random
pygame.init()
# Dimensions de la fenêtre
largeur = 800
hauteur = 600
# Couleurs
noir = pygame.Color(0, 0, 0)
blanc = pygame.Color(255, 255, 255)
rouge = pygame.Color(255, 0, 0)
vert = pygame.Color(0, 255, 0)
# Initialisation de la fenêtre
fenetre = pygame.display.set_mode((largeur, hauteur))
pygame.display.set_caption('Snake Game')
# Paramètres du jeu
snake_pos = [100, 50]
snake_corps = [[100, 50], [90, 50], [80, 50]]
direction = 'DROITE'
changement_direction = direction
# Pomme
pomme_pos = [random.randrange(1, (largeur//10)) * 10,
random.randrange(1, (hauteur//10)) * 10]
pomme_spawn = True
def notre_snake(snake_corps):
for pos in snake_corps:
pygame.draw.rect(fenetre, vert, pygame.Rect(pos[0], pos[1], 10, 10))
def notre_pomme(pos):
pygame.draw.rect(fenetre, rouge, pygame.Rect(pos[0], pos[1], 10, 10))
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and changement_direction != 'GAUCHE':
direction = 'DROITE'
if event.key == pygame.K_LEFT and changement_direction != 'DROITE':
direction = 'GAUCHE'
if event.key == pygame.K_UP and changement_direction != 'BAS':
direction = 'HAUT'
if event.key == pygame.K_DOWN and changement_direction != 'HAUT':
direction = 'BAS'
if direction == 'DROITE':
snake_pos[0] += 10
if direction == 'GAUCHE':
snake_pos[0] -= 10
if direction == 'HAUT':
snake_pos[1] -= 10
if direction == 'BAS':
snake_pos[1] += 10
snake_corps.insert(0, list(snake_pos))
if snake_pos[0] == pomme_pos[0] and snake_pos[1] == pomme_pos[1]:
pomme_spawn = False
else:
snake_corps.pop()
if not pomme_spawn:
pomme_pos = [random.randrange(1, (largeur//10)) * 10,
random.randrange(1, (hauteur//10)) * 10]
pomme_spawn = True
fenetre.fill(noir)
notre_pomme(pomme_pos)
notre_snake(snake_corps)
pygame.display.update()
changement_direction = direction
clock.tick(15)