Initialize Pygame
pygame.init()
Set up display
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
CELL_SIZE = 20
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Snake Game')
Set up the clock for controlling frame rate
clock = pygame.time.Clock()
Define basic colors
BLACK = pygame.Color(0, 0, 0)
GREEN = pygame.Color(0, 255, 0)
RED = pygame.Color(255, 0, 0)
Define directions as vectors
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
class Snake:
def init(self):
# Initialize the snake's starting position and direction
self.positions = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.length = 1
def move(self):
# Move the snake in the current direction
head_x, head_y = self.positions[0]
delta_x, delta_y = self.direction
new_head = ((head_x + delta_x * CELL_SIZE) % WINDOW_WIDTH,
(head_y + delta_y * CELL_SIZE) % WINDOW_HEIGHT)
# Check for collision with self
if new_head in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new_head)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
# Reset the snake to the initial state
self.__init__()
def draw(self, surface):
# Draw the snake on the given surface
for position in self.positions:
rect = pygame.Rect(position[0], position[1], CELL_SIZE, CELL_SIZE)
pygame.draw.rect(surface, GREEN, rect)
def handle_keys(self):
# Handle user input for direction changes
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 or event.key == pygame.K_w) and self.direction != DOWN:
self.direction = UP
elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and self.direction != UP:
self.direction = DOWN
elif (event.key == pygame.K_LEFT or event.key == pygame.K_a) and self.direction != RIGHT:
self.direction = LEFT
elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and self.direction != LEFT:
self.direction = RIGHT
class Food:
def init(self):
# Initialize the food at a random position
self.position = (0, 0)
self.color = RED
self.randomize_position()
def randomize_position(self):
# Place the food at a random location
self.position = (
random.randint(0, (WINDOW_WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE,
random.randint(0, (WINDOW_HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
)
def draw(self, surface):
# Draw the food on the given surface
rect = pygame.Rect(self.position[0], self.position[1], CELL_SIZE, CELL_SIZE)
pygame.draw.rect(surface, self.color, rect)
def main():
# Main game loop
snake = Snake()
food = Food()
while True:
# Handle events and move snake
snake.handle_keys()
snake.move()
# Check if the snake has eaten the food
if snake.positions[0] == food.position:
snake.length += 1
food.randomize_position()
# Draw everything
screen.fill(BLACK)
snake.draw(screen)
food.draw(screen)
pygame.display.flip()
# Control the game speed
clock.tick(10)
if name == 'main':
main()
</code>