free-tech

How to write snake game in Python


 you will find in this article the snippet code and also the explanation

code:


import pygame
import time

# Initialize pygame
pygame.init()

# Set the window size
win_size = (500, 500)

# Create the window
win = pygame.display.set_mode(win_size)

# Set the title of the window
pygame.display.set_caption("Snake Game")

# Set the initial position of the snake
snake_pos = [250, 250]

# Set the initial speed of the snake
snake_speed = 5

# Set the initial direction of the snake
snake_dir = "up"

# Set the initial length of the snake
snake_length = [[250, 250], [240, 250], [230, 250]]

# Run the game loop
while True:
    # Check for events
    for event in pygame.event.get():
        # Exit the game if the user clicks the X button
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        
        # Update the direction of the snake when the user presses an arrow key
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and snake_dir != "down":
                snake_dir = "up"
            elif event.key == pygame.K_DOWN and snake_dir != "up":
                snake_dir = "down"
            elif event.key == pygame.K_LEFT and snake_dir != "right":
                snake_dir = "left"
            elif event.key == pygame.K_RIGHT and snake_dir != "left":
                snake_dir = "right"

    # Move the snake
    if snake_dir == "up":
        snake_pos[1] -= snake_speed
    elif snake_dir == "down":
        snake_pos[1] += snake_speed
    elif snake_dir == "left":
        snake_pos[0] -= snake_speed
    elif snake_dir == "right":
        snake_pos[0] += snake_speed

    # Add the new position of the snake to the snake_length list
    snake_length.insert(0, list(snake_pos))

    # Remove the last position of the snake from the snake_length list
    snake_length.pop()

    # Fill the background color of the window
    win.fill((255, 255, 255))

    # Draw the snake
    for pos in snake_length:
        pygame.draw.rect(win, (0, 0, 0), pygame.Rect(pos[0], pos[1], 10, 10))

    # Update the display
    pygame.display.update()

    # Wait for a short time
    time.sleep(0.1)

Explanation:


  1. The first step is to import the pygame and time modules. pygame is a library that provides functionality for creating games, while time is used to control the speed of the game.
  2. Next, pygame.init() is called to initialize all pygame modules.
  3. The window size is set to (500, 500) and the window is created using pygame.display.set_mode(win_size).
  4. The title of the window is set to "Snake Game" using pygame.display.set_caption("Snake Game").
  5. The initial position of the snake is set to [250, 250], the initial speed is set to 5, and the initial direction is set to "up". The initial length of the snake is set to [[250, 250], [240, 250], [230, 250]].
  6. The game loop begins with a while loop that runs indefinitely. Inside the loop, a for loop is used to check for events, specifically the QUIT event which is triggered when the user clicks the X button to close the window. If the QUIT event is detected, the game quits.
  7. The snake's position is then updated based on its current direction. If the direction is "up", the y-coordinate is decremented by the snake's speed. If the direction is "down", the y-coordinate is incremented by the snake's speed. If the direction is "left", the x-coordinate is decremented by the snake's speed. If the direction is "right", the x-coordinate is incremented by the snake's speed.
  8. The new position of the snake is then added to the beginning of the snake_length list, and the last position of the snake is removed from the list. This simulates the snake moving on the screen.
  9. The background color of the window is filled with white using win.fill((255, 255, 255)), and the snake is drawn on the screen using a for loop that iterates through the snake_length list. The pygame.draw.rect() function is used to draw a rectangle for each position in the list.
  10. The display is updated using pygame.display.update(), and the program waits for a short time using time.sleep(0.1) before looping again.

Similar Articles


Card image

20 Must-have plugins for PyCharm in 2022

Card image

How to set default python as python3 on macOS ?

Card image

get RAM memory information with python