import pygame
import random
# Initialize pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 600, 400
BLOCK_SIZE = 20
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# Colors
WHITE = (255, 255, 255)
GREEN = (0, 200, 0)
RED = (200, 0, 0)
BLACK = (0, 0, 0)
# Clock
clock = pygame.time.Clock()
FPS = 10
# Font
font = pygame.font.SysFont(None, 30)
def draw_snake(snake):
for block in snake:
pygame.draw.rect(screen, GREEN, (*block, BLOCK_SIZE, BLOCK_SIZE))
def draw_food(food):
pygame.draw.rect(screen, RED, (*food, BLOCK_SIZE, BLOCK_SIZE))
def show_score(score):
text = font.render(f"Score: {score}", True, WHITE)
screen.blit(text, [10, 10])
def game_loop():
snake = [(100, 100)]
direction = (BLOCK_SIZE, 0)
food = (
random.randrange(0, WIDTH, BLOCK_SIZE),
random.randrange(0, HEIGHT, BLOCK_SIZE),
)
score = 0
running = True
while running:
screen.fill(BLACK)
# Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction = (-BLOCK_SIZE, 0)
elif event.key == pygame.K_RIGHT:
direction = (BLOCK_SIZE, 0)
elif event.key == pygame.K_UP:
direction = (0, -BLOCK_SIZE)
elif event.key == pygame.K_DOWN:
direction = (0, BLOCK_SIZE)
# Move snake
head_x = snake[0][0] + direction[0]