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wIC8vIEZQUyk=
import pygame
import sys
import random
Initialize Pygame
pygame.init()
Set up some constants
WIDTH, HEIGHT = 640, 480
BLOCK_SIZE = 20
FPS = 10
Set up some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Snake Game')
Set up the font
font = pygame.font.Font(None, 36)
Set up the snake and food
snake = [(200, 200), (220, 200), (240, 200)]
food = (400, 300)
Set up the direction
direction = 'RIGHT'
Game loop
while True:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'DOWN':
direction = 'UP'
elif event.key == pygame.K_DOWN and direction != 'UP':
direction = 'DOWN'
elif event.key == pygame.K_LEFT and direction != 'RIGHT':
direction = 'LEFT'
elif event.key == pygame.K_RIGHT and direction != 'LEFT':
direction = 'RIGHT'
# Move the snake
head = snake[-1]
if direction == 'UP':
new_head = (head[0], head[1] - BLOCK_SIZE)
elif direction == 'DOWN':
new_head = (head[0], head[1] + BLOCK_SIZE)
elif direction == 'LEFT':
new_head = (head[0] - BLOCK_SIZE, head[1])
elif direction == 'RIGHT':
new_head = (head[0] + BLOCK_SIZE, head[1])
snake.append(new_head)
# Check for collision with food
if snake[-1] == food:
food = (random.randint(0, WIDTH - BLOCK_SIZE) // BLOCK_SIZE * BLOCK_SIZE,
random.randint(0, HEIGHT - BLOCK_SIZE) // BLOCK_SIZE * BLOCK_SIZE)
else:
snake.pop(0)
# Check for collision with wall or self
if (snake[-1][0] < 0 or snake[-1][0] >= WIDTH or
snake[-1][1] < 0 or snake[-1][1] >= HEIGHT or
snake[-1] in snake[:-1]):
pygame.quit()
sys.exit()
# Draw everything
screen.fill(BLACK)
for x, y in snake:
pygame.draw.rect(screen, GREEN, (x, y, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(screen, RED, (food[0], food[1], BLOCK_SIZE, BLOCK_SIZE))
text = font.render(f'Score: {len(snake)}', True, WHITE)
screen.blit(text, (10, 10))
# Update the display
pygame.display.flip()
# Cap the frame rate
pygame.time.delay(1000 // FPS)