This code creates a simple Snake game using the Pygame library in Python.
The game starts with a small snake moving around the screen, controlled by arrow keys, eating randomly placed food items. Each time the snake eats food, it grows longer, and the game gets faster.
The game ends if the snake collides with itself or the screen borders, and the player’s goal is to keep the snake growing as long as possible.
import pygame import sys import random # Initialize pygame pygame.init() # Set screen dimensions WIDTH = 640 HEIGHT = 480 CELL_SIZE = 20 # Colors WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # Create the game screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) # Set the game clock clock = pygame.time.Clock() def random_food_position(): return (random.randint(0, (WIDTH-CELL_SIZE)//CELL_SIZE) * CELL_SIZE, random.randint(0, (HEIGHT-CELL_SIZE)//CELL_SIZE) * CELL_SIZE) def draw_snake(snake_positions): for pos in snake_positions: pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], CELL_SIZE, CELL_SIZE)) def draw_food(food_position): pygame.draw.rect(screen, RED, pygame.Rect(food_position[0], food_position[1], CELL_SIZE, CELL_SIZE)) def main(): snake_positions = [(100, 100), (80, 100), (60, 100)] snake_direction = (20, 0) food_position = random_food_position() game_speed = 10 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake_direction != (0, 20): snake_direction = (0, -20) elif event.key == pygame.K_DOWN and snake_direction != (0, -20): snake_direction = (0, 20) elif event.key == pygame.K_LEFT and snake_direction != (20, 0): snake_direction = (-20, 0) elif event.key == pygame.K_RIGHT and snake_direction != (-20, 0): snake_direction = (20, 0) new_head = (snake_positions[0][0] + snake_direction[0], snake_positions[0][1] + snake_direction[1]) if new_head in snake_positions or new_head[0] < 0 or new_head[0] >= WIDTH or new_head[1] < 0 or new_head[1] >= HEIGHT: break snake_positions.insert(0, new_head) if new_head == food_position: food_position = random_food_position() game_speed += 1 else: snake_positions.pop() screen.fill(WHITE) draw_snake(snake_positions) draw_food(food_position) pygame.display.update() clock.tick(game_speed) if __name__ == "__main__": main()
This simple implementation of the classic Snake game uses the Pygame library in Python — here’s how I quickly lost in the game:
Here’s a brief explanation of each part of the code:
- Import libraries:
pygame
for creating the game window and handling events,sys
for system-specific parameters and functions, andrandom
for generating random numbers.
- Initialize
pygame
withpygame.init()
. - Set screen dimensions and cell size. The
WIDTH
,HEIGHT
, andCELL_SIZE
constants define the game window size and the size of each cell (both snake segments and food). - Define color constants
WHITE
,GREEN
, andRED
as RGB tuples. - Create the game screen with
pygame.display.set_mode((WIDTH, HEIGHT))
. - Set the game clock with
pygame.time.Clock()
to control the game’s frame rate. - Define the
random_food_position()
function to generate a random food position on the grid, ensuring it’s aligned with theCELL_SIZE
. - Define
draw_snake(snake_positions)
function to draw the snake’s body segments at their respective positions using green rectangles. - Define
draw_food(food_position)
function to draw the food as a red rectangle at its position. - Define the
main()
function, which contains the main game loop and logic.- Initialize the snake’s starting position, direction, food position, and game speed.
- The
while True
loop is the main game loop that runs indefinitely until the snake collides with itself or the screen borders. - Handle events like closing the game window or changing the snake’s direction using arrow keys.
- Update the snake’s position based on its current direction.
- Check for collisions with itself or the screen borders, breaking the loop if a collision occurs.
- If the snake’s head is at the food position, generate a new food position and increase the game speed. Otherwise, remove the last snake segment.
- Update the game display by filling the screen with a white background, drawing the snake and food, and updating the display.
- Control the game speed using
clock.tick(game_speed)
.
- Run the
main()
function when the script is executed by checking if__name__ == "__main__"
.