import pygame import sys import random import time pygame.init() # Set up display width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("Snake Game") # Colors black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) # Snake attributes snake_size = 20 snake_speed = 500 # Adjust the speed to your preference snake_head = [width / 2, height / 2] snake_velocity = [snake_speed, 0] snake_body = [snake_head[:]] # Initial position of the snake # Food attributes food_size = 40 food = ( random.randrange(0, width - food_size + 1, snake_size), random.randrange(0, height - food_size + 1, snake_size) ) # Score score = 0 font = pygame.font.SysFont(None, 30) # Time-based movement last_time = time.time() update_interval = 1 / 60 # Targeting 60 frames per second # Main game loop clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_UP] and snake_velocity[1] == 0: snake_velocity = [0, -snake_speed] elif keys[pygame.K_DOWN] and snake_velocity[1] == 0: snake_velocity = [0, snake_speed] elif keys[pygame.K_LEFT] and snake_velocity[0] == 0: snake_velocity = [-snake_speed, 0] elif keys[pygame.K_RIGHT] and snake_velocity[0] == 0: snake_velocity = [snake_speed, 0] # Time-based movement current_time = time.time() if current_time - last_time >= update_interval: # Update snake position snake_head[0] += snake_velocity[0] * update_interval snake_head[1] += snake_velocity[1] * update_interval # Wrap around the window snake_head[0] = snake_head[0] % width snake_head[1] = snake_head[1] % height # Check for collision with food if ( snake_head[0] < food[0] + food_size and snake_head[0] + snake_size > food[0] and snake_head[1] < food[1] + food_size and snake_head[1] + snake_size > food[1] ): food = ( random.randrange(0, width - food_size + 1, snake_size), random.randrange(0, height - food_size + 1, snake_size) ) score += 1 snake_body.append(snake_body[-1][:]) # Add a new segment to the snake # Update snake body snake_body.insert(0, snake_head[:]) snake_body.pop() last_time = current_time # Draw everything screen.fill(black) # Draw food with white border pygame.draw.rect(screen, white, (food[0], food[1], food_size, food_size)) pygame.draw.rect(screen, red, (food[0] + 1, food[1] + 1, food_size - 2, food_size - 2)) # Draw snake with random colors for each segment for segment in snake_body: random_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) pygame.draw.rect(screen, white, (segment[0], segment[1], snake_size, snake_size)) pygame.draw.rect(screen, random_color, (segment[0] + 1, segment[1] + 1, snake_size - 2, snake_size - 2)) # Display score score_text = font.render(f"Score: {score}", True, white) screen.blit(score_text, (10, 10)) pygame.display.flip() # Cap the frame rate clock.tick(60) # Cap the frame rate at 60 frames per second