You are on page 1of 3

Week 11 - Home Work

Follow the steps to finish the snake game

#Step 1: Import required modules


import pygame
import sys
import random

#Step 2: Initialize Pygame


pygame.init()

#Step 3: Set up the game window


window_size = 400
cell_size = 20
window = pygame.display.set_mode((window_size, window_size))
pygame.display.set_caption("Snake Game")

#Step 4:Define colors


black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)

#Step 5: Define directions


UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)

#Step 6: Initialize game variables


snake = [(100, 100)]
direction = RIGHT
food = (0, 0)

#Step 7: Function to spawn food at a random position


def spawn_food():
global food
food = (random.randint(0, window_size // cell_size - 1) * cell_size,
random.randint(0, window_size // cell_size - 1) * cell_size)
#Step 8: Main game loop
clock = pygame.time.Clock()
running = True

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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
#step 9: Move the snake
x, y = snake[0]
x += direction[0] * cell_size
y += direction[1] * cell_size
snake.insert(0, (x, y))

#Step 10: Check for collisions


if x < 0 or x >= window_size or y < 0 or y >= window_size or snake[0] in snake[1:]:
running = False

#Step 11:Check if the snake ate food


if snake[0] == food:
spawn_food()
else:
snake.pop()

#Step 12: Draw the window


window.fill(black)
for segment in snake:
pygame.draw.rect(window, white, (segment[0], segment[1], cell_size, cell_size))
pygame.draw.rect(window, red, (food[0], food[1], cell_size, cell_size))
pygame.display.flip()

clock.tick(5) # Adjust the speed of the snake

#Step 13: Quit Pygame


pygame.quit()

You might also like