import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Set up the screen
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Snake Game")
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Snake and food variables
snake_block = 20
snake_speed = 15
x_snake = screen_width / 2
y_snake = screen_height / 2
snake_x = [x_snake]
snake_y = [y_snake]
food_x = random.randint(0, (screen_width // snake_block) - 1) * snake_block
food_y = random.randint(0, (screen_height // snake_block) - 1) * snake_block
# Directions
direction_x = 1
direction_y = 0
clock = pygame.time.Clock()
while True:
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_LEFT and direction_x != -1:
direction_x = -1
direction_y = 0
elif event.key == pygame.K_RIGHT and direction_x != 1:
direction_x = 1
direction_y = 0
elif event.key == pygame.K_UP and direction_y != 1:
direction_y = -1
direction_x = 0
elif event.key == pygame.K_DOWN and direction_y != -1:
direction_y = 1
direction_x = 0
# Move snake
x_snake += direction_x * snake_block
y_snake += direction_y * snake_block
# Check if snake hits the wall
if x_snake < 0 or x_snake >= screen_width - snake_block or y_snake < 0 or y_snake >= screen_height - snake_block:
game_over = True
# Check if snake eats food
if x_snake == food_x and y_snake == food_y:
food_x = random.randint(0, (screen_width // snake_block) - 1) * snake_block
food_y = random.randint(0, (screen_height // snake_block) - 1) * snake_block
snake_speed = snake_speed // 2
# Update snake's position
for i in range(len(snake_x)-1, 0, -1):
x_snake = snake_x[i]
y_snake = snake_y[i]
# Check if snake collides with itself
head = [x_snake, y_snake]
body = list(zip(snake_x, snake_y))
if head in body:
game_over = True
# Draw the background
screen.fill(BLACK)
# Draw food
pygame.draw.rect(screen, RED, (food_x, food_y, snake_block, snake_block))
# Draw snake
for i in range(len(snake_x)):
if i == 0:
color = GREEN
else:
color = BLACK
pygame.draw.rect(screen, color,
(snake_x[i], snake_y[i], snake_block, snake_block))
# Control speed
clock.tick(snake_speed)
# Check game over
if game_over:
break
pygame.display.flip()
pygame.quit()