You are on page 1of 2

import pygame

import random

# Constants
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
BLOCK_SIZE = 20
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

class SnakeGame:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Snake Game")
self.clock = pygame.time.Clock()
self.reset_game()
self.running = True

def reset_game(self):
self.snake = [(200, 200), (210, 200), (220, 200)]
self.direction = 'RIGHT'
self.apple = self.generate_apple()
self.score = 0

def generate_apple(self):
x = random.randrange(0, SCREEN_WIDTH-BLOCK_SIZE, BLOCK_SIZE)
y = random.randrange(0, SCREEN_HEIGHT-BLOCK_SIZE, BLOCK_SIZE)
return (x, y)

def draw_snake(self):
for segment in self.snake:
pygame.draw.rect(self.screen, GREEN, (segment[0], segment[1],
BLOCK_SIZE, BLOCK_SIZE))

def draw_apple(self):
pygame.draw.rect(self.screen, RED, (self.apple[0], self.apple[1],
BLOCK_SIZE, BLOCK_SIZE))

def move_snake(self):
head = self.snake[0]
if self.direction == 'UP':
new_head = (head[0], head[1] - BLOCK_SIZE)
elif self.direction == 'DOWN':
new_head = (head[0], head[1] + BLOCK_SIZE)
elif self.direction == 'LEFT':
new_head = (head[0] - BLOCK_SIZE, head[1])
elif self.direction == 'RIGHT':
new_head = (head[0] + BLOCK_SIZE, head[1])
self.snake.insert(0, new_head)
if new_head == self.apple:
self.apple = self.generate_apple()
self.score += 1
else:
self.snake.pop()

def check_collision(self):
head = self.snake[0]
if (
head[0] < 0 or
head[0] >= SCREEN_WIDTH or
head[1] < 0 or
head[1] >= SCREEN_HEIGHT or
head in self.snake[1:]
):
return True
return False

def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and self.direction != 'DOWN':
self.direction = 'UP'
elif event.key == pygame.K_DOWN and self.direction != 'UP':
self.direction = 'DOWN'
elif event.key == pygame.K_LEFT and self.direction != 'RIGHT':
self.direction = 'LEFT'
elif event.key == pygame.K_RIGHT and self.direction != 'LEFT':
self.direction = 'RIGHT'

def run(self):
while self.running:
self.handle_events()
if not self.running:
break
self.move_snake()
if self.check_collision():
self.reset_game()
self.screen.fill(BLACK)
self.draw_snake()
self.draw_apple()
pygame.display.update()
self.clock.tick(10)

pygame.quit()

if __name__ == "__main__":
SnakeGame().run()

You might also like