04-25-2023, 05:36 PM
Python Snake Made Easy
5/5 – (1 vote)
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.
This simple implementation of the classic Snake game uses the Pygame library in Python — here’s how I quickly lost in the game:
![[Image: snake_py.gif]](https://blog.finxter.com/wp-content/uploads/2023/04/snake_py.gif)
Here’s a brief explanation of each part of the code:
5/5 – (1 vote)
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.
Code:
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:
![[Image: snake_py.gif]](https://blog.finxter.com/wp-content/uploads/2023/04/snake_py.gif)
Here’s a brief explanation of each part of the code:
- Import libraries:
- for creating the game window and handling events,Code:
pygame
- for system-specific parameters and functions, andCode:
sys
- for generating random numbers.Code:
random
- Initialize withCode:
pygame.Code:pygame.init()
- Set screen dimensions and cell size. The ,Code:
WIDTH, andCode:HEIGHTconstants define the game window size and the size of each cell (both snake segments and food).Code:CELL_SIZE
- Define color constants ,Code:
WHITE, andCode:GREENas RGB tuples.Code:RED
- Create the game screen with .Code:
pygame.display.set_mode((WIDTH, HEIGHT))
- Set the game clock with to control the game’s frame rate.Code:
pygame.time.Clock()
- Define the function to generate a random food position on the grid, ensuring it’s aligned with theCode:
random_food_position().Code:CELL_SIZE
- Define function to draw the snake’s body segments at their respective positions using green rectangles.Code:
draw_snake(snake_positions)
- Define function to draw the food as a red rectangle at its position.Code:
draw_food(food_position)
- Define the function, which contains the main game loop and logic.Code:
main()- Initialize the snake’s starting position, direction, food position, and game speed.
- The loop is the main game loop that runs indefinitely until the snake collides with itself or the screen borders.Code:
while True
- 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 .Code:
clock.tick(game_speed)
- Initialize the snake’s starting position, direction, food position, and game speed.
- Run the function when the script is executed by checking ifCode:
main().Code:__name__ == "__main__"

