import pygame
import sys
import random
pygame.init()
WIDTH = 800
HEIGHT = 600
GRID_SIZE = 20
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
snake = [(GRID_SIZE * 5, GRID_SIZE * 5)]
snake_dir = (GRID_SIZE, 0)
food = (GRID_SIZE * 10, GRID_SIZE * 10)
clock = pygame.time.Clock()
def draw_snake():
for segment in snake:
pygame.draw.rect(screen, GREEN, pygame.Rect(segment[0], segment[1], GRID_SIZE, GRID_SIZE))
def draw_food():
pygame.draw.rect(screen, RED, pygame.Rect(food[0], food[1], GRID_SIZE, GRID_SIZE))
def move_snake():
global snake
new_head = (snake[0][0] + snake_dir[0], snake[0][1] + snake_dir[1])
snake.insert(0, new_head)
snake.pop()
def check_collision():
if snake[0] == food:
return True
return False
def generate_food():
return (random.randint(0, WIDTH // GRID_SIZE - 1) * GRID_SIZE, random.randint(0, HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
def game_over():
for segment in snake[1:]:
if snake[0] == segment:
return True
if snake[0][0] < 0 or snake[0][0] >= WIDTH or snake[0][1] < 0 or snake[0][1] >= HEIGHT:
return True
return False
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_UP and snake_dir != (0, GRID_SIZE):
snake_dir = (0, -GRID_SIZE)
elif event.key == pygame.K_DOWN and snake_dir != (0, -GRID_SIZE):
snake_dir = (0, GRID_SIZE)
elif event.key == pygame.K_LEFT and snake_dir != (GRID_SIZE, 0):
snake_dir = (-GRID_SIZE, 0)
elif event.key == pygame.K_RIGHT and snake_dir != (-GRID_SIZE, 0):
snake_dir = (GRID_SIZE, 0)
screen.fill(WHITE)
draw_snake()
draw_food()
move_snake()
pygame.display.flip()
clock.tick(10)
if check_collision():
food = generate_food()
snake.append(snake[-1])
elif game_over():
break