Create Snake game in Pygame

Your Apply link is Loading :




Introduction:

Pygame is an open-source Python library for creating games and multimedia applications. It is built on top of the SDL library, which provides access to the hardware and graphics capabilities of the underlying system. Pygame is easy to use, highly customizable, and has a large community of developers contributing to its development.

One of the classic games that can be created with Pygame is the Snake game. This game has been around for decades, and it is still popular today. The objective of the game is to control a snake that moves around the screen, eating food and growing longer. The player must avoid running into the walls or the snake’s own body, which would cause the game to end.

In this tutorial, we will create a simple version of the Snake game using Pygame. We will cover the basics of Pygame and demonstrate how to create a game loop, display graphics, handle user input, and implement collision detection. We will also show how to add sound effects and keep score. By the end of this tutorial, you will have a working Snake game that you can play and customize to your liking.

Setting up the Environment:

Before we start creating the game, we need to set up our development environment. We will assume that you have Python 3 installed on your system. If you do not have Pygame installed, you can install it using pip, the Python package installer. Open a terminal or command prompt and type the following command:

pip install pygame

This will install the latest version of Pygame. Once Pygame is installed, we can start creating our game.

Creating the Game Window:

The first step in creating a game with Pygame is to create a game window. The game window is the main graphical interface for the game, where the graphics will be displayed and user input will be handled.

To create a game window in Pygame, we need to import the Pygame library and initialize it. We also need to define the size of the window and the title that will be displayed in the title bar. We can do this by creating a new Pygame display surface using the pygame.display.set_mode() function:

import pygame
pygame.init()
# Define the size of the game window
window_size = (640, 480)
# Set the title of the game window
pygame.display.set_caption('Snake Game')
# Create the game window
screen = pygame.display.set_mode(window_size)

In this code, we import the Pygame library and initialize it using the pygame.init() function. We then define the size of the game window as a tuple of width and height (in this case, 640 pixels wide and 480 pixels tall). We set the title of the game window using the pygame.display.set_caption() function, and finally, we create the game window using the pygame.display.set_mode() function and assign it to the screen variable.

We can test that our game window is working by running the following code:

# Run the game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # Fill the screen with white
    screen.fill((255, 255, 255))
    # Update the display
    pygame.display.update()
# Quit Pygame
pygame.quit()

This code creates a game loop that runs until the user closes the game window. In each iteration of the loop, we check for any events that have occurred (such as the user closing the window) and update the display. We also fill the screen with white using the screen.fill() function.

When we run this code, we should see a white game window with the title “Snake Game” in the title bar. The game window will remain open until the user closes it.

Displaying the Snake:

Now that we have a game window, we can start displaying the snake on the screen. In the Snake game, the snake is represented by a series of rectangles that are linked together. We will use Pygame’s built-in Rect class to represent the snake’s segments.In this code, we define the size of each segment of the snake and the starting position of the snake as a list of tuples. We then create a list of Rect objects using the pygame.Rect() function and add them to the snake_segments list.

# Define the size of each segment of the snake
segment_size = 20
# Define the starting position of the snake
snake_position = [(segment_size * 3, segment_size),
                  (segment_size * 2, segment_size),
                  (segment_size, segment_size)]
# Create a list of Rect objects to represent the snake's segments
snake_segments = []
for pos in snake_position:
    segment = pygame.Rect(pos[0], pos[1], segment_size, segment_size)
    snake_segments.append(segment)

We can now draw the snake on the screen by looping through the snake_segments list and calling the pygame.draw.rect() function for each segment.

# Draw the snake on the screen
for segment in snake_segments:
    pygame.draw.rect(screen, (0, 255, 0), segment)

In this code, we loop through the snake_segments list and call the pygame.draw.rect() function for each segment. We pass the screen object as the first argument to specify where to draw the rectangle, a tuple of RGB values (0, 255, 0) to specify the color of the rectangle (in this case, green), and the Rect object representing the position and size of the rectangle.

When we run this code, we should see a green snake displayed on the screen.

Moving the Snake:

Now that we have a snake displayed on the screen, we need to be able to move it. In the Snake game, the snake moves continuously in a single direction until the player changes its direction.

To move the snake in Pygame, we need to update the positions of its segments. We will do this by removing the last segment of the snake and adding a new segment to the front of the snake in the direction it is moving.

# Define the starting direction of the snake
direction = "right"
# Define the speed of the snake
speed = 1
# Move the snake
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # Move the snake in the current direction
    if direction == "right":
        new_head = snake_segments[0].move(segment_size * speed, 0)
    elif direction == "left":
        new_head = snake_segments[0].move(-segment_size * speed, 0)
    elif direction == "up":
        new_head = snake_segments[0].move(0, -segment_size * speed)
    elif direction == "down":
        new_head = snake_segments[0].move(0, segment_size * speed)
    # Add the new head to the front of the snake
    snake_segments.insert(0, new_head)
    # Remove the last segment of the snake
    snake_segments.pop()

In this code, we define the starting direction of the snake as “right” and the speed of the snake as 1 (in units of segment_size). We then create a

while loop that will run continuously until the running variable is set to False. Inside the loop, we use a for loop to handle events, such as quitting the game by clicking the close button on the game window.

Next, we move the snake in the current direction by creating a new Rect object representing the position of the new head of the snake. We use the move() method of the first segment of the snake_segments list to move the head in the appropriate direction. For example, if the direction is “right”, we move the head to the right by adding segment_size * speed to its x-coordinate.

We then add the new head to the front of the snake_segments list using the insert() method. Finally, we remove the last segment of the snake using the pop() method.

We can now update the game loop to include the code to draw the snake on the screen.

In this code, we first clear the screen by filling it with white using the fill() method of the screen object. We then loop through the snake_segments list and call the pygame.draw.rect() function for each segment to draw the snake on the screen.

Finally, we call the pygame.display.update() function to update the display with the new frame.

# Move the snake
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # Move the snake in the current direction
    if direction == "right":
        new_head = snake_segments[0].move(segment_size * speed, 0)
    elif direction == "left":
        new_head = snake_segments[0].move(-segment_size * speed, 0)
    elif direction == "up":
        new_head = snake_segments[0].move(0, -segment_size * speed)
    elif direction == "down":
        new_head = snake_segments[0].move(0, segment_size * speed)
    # Add the new head to the front of the snake
    snake_segments.insert(0, new_head)
    # Remove the last segment of the snake
    snake_segments.pop()
    # Draw the snake on the screen
    screen.fill((255, 255, 255))
    for segment in snake_segments:
        pygame.draw.rect(screen, (0, 255, 0), segment)
    pygame.display.update()

Controlling the Snake:

The snake can be controlled by the player using the arrow keys on the keyboard. We will use Pygame’s event handling system to detect when an arrow key is pressed and change the direction of the snake accordingly.

In this code, we loop through the events using the pygame.event.get() function. If the QUIT event is detected, we set running to False to exit the game loop.

If a key is pressed, we check which key was pressed using the event.key attribute. If the right arrow key is pressed and the current direction of the snake is not “left” (i.e., the snakeis not already moving to the left), we set the direction of the snake to “right”. We do the same for the other arrow keys, making sure to check that the new direction is not opposite to the current direction of the snake.

# Control the snake with the arrow keys
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_RIGHT and direction != "left":
            direction = "right"
        elif event.key == pygame.K_LEFT and direction != "right":
            direction = "left"
        elif event.key == pygame.K_UP and direction != "down":
            direction = "up"
        elif event.key == pygame.K_DOWN and direction != "up":
            direction = "down"

Growing the Snake:

Next, we will implement the mechanism to grow the snake when it eats food. We will first define a variable called ate_food to keep track of whether the snake has eaten food in the current frame.

We will then check if the head of the snake (snake_segments[0]) has collided with the food (food_rect) using the colliderect() method of Rect objects. If there is a collision, we set ate_food to True and create a new segment for the snake at the position of the food.

# Check for collisions with food
ate_food = False
if snake_segments[0].colliderect(food_rect):
    ate_food = True
    food_rect = pygame.Rect(random.randint(0, screen_width // segment_size - 1) * segment_size,
                            random.randint(0, screen_height // segment_size - 1) * segment_size,
                            segment_size, segment_size)
    snake_segments.append(snake_segments[-1].copy())

In this code, we use the colliderect() method to check for collisions between the head of the snake and the food. If there is a collision, we set ate_food to True.

We then create a new Rect object for the food at a random position on the screen using the random.randint() function. Finally, we create a new segment for the snake by appending a copy of the last segment of the snake to the end of the snake_segments list.

If the snake has eaten food in the current frame, we do not remove the last segment of the snake in the game loop. This has the effect of growing the snake by one segment.

# Remove the last segment of the snake if the snake did not eat food
if not ate_food:
    snake_segments.pop()

In this code, we use an if statement to check if the snake has eaten food in the current frame. If not, we remove the last segment of the snake as before.

Scoring and Game Over:

To add some additional game mechanics, we will implement a scoring system and a game over condition.

We will first define a variable called score to keep track of the player’s score. We will then add 10 to the score every time the snake eats food.

# Increase the score if the snake ate food
if ate_food:
    score += 10

In this code, we use an if statement to check if the snake has eaten food in the current frame. If so, we add 10 to the score.

We will also implement a game over condition if the snake collides with the edges of the game window or with its own body. We will use the colliderect() method again to check for collisions.

# Check for collisions with the edges of the game window
if snake_segments[0].left < 0 or snake_segments[0].right > screen_width or \
        snake_segments[0].top < 0 or snake_segments[0].bottom > screen_height:
    running = False
# Check for collisions with the snake's own body
for segment in snake_segments[1:]:
    if snake_segments[0].colliderect(segment):
        running = False

In this code, we first check for collisions with the edges of the game window by comparing the left, right, top, and bottom attributes of

the head of the snake (snake_segments[0]) with the width and height of the game window. If there is a collision, we set running to False, which will exit the game loop and end the game.

We then check for collisions with the snake’s own body by iterating over all the segments of the snake except for the head (snake_segments[1:]). If the head of the snake collides with any of the other segments, we set running to False.

Displaying the Score:

To display the player’s score on the game window, we will create a pygame.font.Font object and render the score as text using the render() method. We will then blit the rendered text onto the game window.

# Create a font object
font = pygame.font.Font(None, 36)
# Render the score as text
score_text = font.render(f"Score: {score}", True, (255, 255, 255))
# Blit the score text onto the game window
screen.blit(score_text, (10, 10))

In this code, we first create a pygame.font.Font object with a font size of 36. We then use f-strings to render the score as text and set the color to white ((255, 255, 255)).

Finally, we blit the score text onto the game window at the position (10, 10).

Full Code:

Here is the full code for the Snake game in Pygame:

import pygame
import random
# Initialize Pygame
pygame.init()
# Set the dimensions of the game window
screen_width = 640
screen_height = 480
# Set the dimensions of each segment of the snake
segment_size = 20
# Set the speed of the snake
speed = 1
# Create the game window
screen = pygame.display.set_mode((screen_width, screen_height))
# Set the title of the game window
pygame.display.set_caption("Snake")
# Define colors
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
# Set the starting direction of the snake
direction = "right"
# Create the initial segments of the snake
snake_segments = [pygame.Rect(segment_size * i, 0, segment_size, segment_size)
                  for i in range(3)]
# Create the initial food
food_rect = pygame.Rect(random.randint(0, screen_width // segment_size - 1) * segment_size,
                        random.randint(0, screen_height // segment_size - 1) * segment_size,
                        segment_size, segment_size)
# Define the game loop
running = True
clock = pygame.time.Clock()
score = 0
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT and direction != "left":
                direction = "right"
            elif event.key == pygame.K_LEFT and direction != "right":
                direction = "left"
            elif event.key == pygame.K_UP and direction != "down":
                direction = "up"
            elif event.key == pygame.K_DOWN and direction != "up":
                direction = "down"
    # Move the snake
    if direction == "right":
        snake_segments.insert(0, snake_segments[0].move(segment_size * speed, 0))
    elif direction == "left":
        snake_segments.insert(0, snake_segments[0].move(-segment_size * speed,segment_size))
elif direction == "up":
snake_segments.insert(0, snake_segments[0].move(0, -segment_size * speed))
elif direction == "down":
snake_segments.insert(0, snake_segments[0].move(0, segment_size * speed))
# Check for collisions with the edges of the game window
if (snake_segments[0].left < 0 or snake_segments[0].right > screen_width or
        snake_segments[0].top < 0 or snake_segments[0].bottom > screen_height):
    running = False
# Check for collisions with the snake's own body
for segment in snake_segments[1:]:
    if snake_segments[0].colliderect(segment):
        running = False
# Check for collisions with the food
if snake_segments[0].colliderect(food_rect):
    # Increase the score
    score += 10
    # Move the food to a new location
    food_rect.left = random.randint(0, screen_width // segment_size - 1) * segment_size
    food_rect.top = random.randint(0, screen_height // segment_size - 1) * segment_size
# Clear the screen
screen.fill(black)
# Draw the snake
for segment in snake_segments:
    pygame.draw.rect(screen, green, segment)
# Draw the food
pygame.draw.rect(screen, white, food_rect)
# Display the score
font = pygame.font.Font(None, 36)
score_text = font.render(f"Score: {score}", True, white)
screen.blit(score_text, (10, 10))
# Update the game window
pygame.display.flip()
# Wait for a short amount of time to control the speed of the game
clock.tick(10)
 

Quit Pygame:

pygame.quit()

This code defines the game loop and handles events, moves the snake, checks for collisions, clears the screen, draws the snake and food, displays the score, updates the game window, and controls the speed of the game. When the game loop ends (i.e., when the player loses), Pygame is quit.

Conclusion:

In this tutorial, we have created a simple Snake game in Pygame. We have learned how to handle events, move the snake, check for collisions, draw the snake and food, display the score, update the game window, and control the speed of the game. This game is a good starting point for anyone interested in game development in Python with Pygame. By adding more features and improving the gameplay, you can create your own version of the classic Snake game.

for more videos azcodinghub.com

this post was written with the help of google

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top