๐Ÿ๐ŸŽฎ Slither to Success: A Detailed Tutorial on Creating Your Own Version of Snake ๐Ÿš€๐ŸŒŸ (Part 16 of Game Dev Series)

ยท

5 min read

A Detailed Tutorial on Creating Your Own Version of Snake

Ah, the classic Snake game! For many of us, it was our first foray into gaming, whether on an old-school Nokia mobile or on Google games. Simplicity, yet with a steadily increasing level of difficulty, makes Snake a delightfully addictive game. But have you ever wondered how it works behind the scenes? Let's dive into creating our own version of Snake using Python and the Pygame library. Strap in, folks, it's time to bring the 90s back!

1. Setting Up

First, you'll need to have Python and Pygame installed. Python can be downloaded from the official Python website, and Pygame can be installed using pip by running pip install pygame in your terminal.

Next, create a new Python file and import Pygame and sys (a built-in module that we will use to exit the game):


import pygame
import sys

2. Creating the Game Screen

Every Pygame application creates a surface that represents a screen. Let's create a screen of 800x600 pixels.


SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

3. Initializing the Snake and Apple

Our Snake will be a list of rectangles (representing the segments), and the apple will be another rectangle. Let's initialize them:


snake = [pygame.Rect(50, 50, 20, 20)]  # Start with a single segment
apple = pygame.Rect(300, 200, 20, 20)

4. Setting the Direction of Movement

We'll create a variable direction to keep track of the Snake's current direction:


direction = 'RIGHT'

5. The Game Loop

Every Pygame application runs an event loop that listens for events like keyboard inputs.


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and direction != 'DOWN':
                direction = 'UP'
            elif event.key == pygame.K_DOWN and direction != 'UP':
                direction = 'DOWN'
            elif event.key == pygame.K_LEFT and direction != 'RIGHT':
                direction = 'LEFT'
            elif event.key == pygame.K_RIGHT and direction != 'LEFT':
                direction = 'RIGHT'

This loop first checks if the user has clicked on the close button (QUIT event). If they have, it exits the program. If a key is pressed (KEYDOWN event), it checks which key was pressed and sets the direction accordingly.

6. Moving the Snake

Still, within the game loop, we'll add code to move the snake in the current direction:


if direction == 'UP':
    new_head = pygame.Rect(snake[0].x, snake[0].y - 20, 20, 20)
elif direction == 'DOWN':
    new_head = pygame.Rect(snake[0].x, snake[0].y + 20, 20, 20)
elif direction == 'LEFT':
    new_head = pygame.Rect(snake[0].x - 20, snake[0].y, 20, 20)
elif direction == 'RIGHT':
    new_head = pygame.Rect(snake[0].x + 20, snake[0].y, 20, 20)

snake.insert(0, new_head)

Each time this code runs, it creates a new rectangle in front of the head of the snake (in the current direction of movement), and adds it to the front of the snake list.

7. Game Over Conditions

The game should end if the snake hits the boundary of the screen or if it hits itself. Add this code to the game loop to handle these conditions:


if (snake[0].x < 0 or snake[0].y < 0 or snake[0].x >= SCREEN_WIDTH or snake[0].y >= SCREEN_HEIGHT or
    snake[0] in snake[1:]):
    pygame.quit()
    sys.exit()

8. Eating the Apple

If the snake eats the apple (i.e., the head of the snake collides with the apple), we need to generate a new apple at a random location. We also should not remove the last segment of the snake, making it grow longer. Add this code to the game loop:


if snake[0].colliderect(apple):
    apple.x = random.randrange(0, SCREEN_WIDTH, 20)
    apple.y = random.randrange(0, SCREEN_HEIGHT, 20)
else:
    snake.pop()

9. Drawing Everything

Finally, within the game loop, we need to draw the snake and apple on the screen:


screen.fill((0, 0, 0))  # Fill the screen with black
for segment in snake:
    pygame.draw.rect(screen, (0, 255, 0), segment)  # Draw the snake
pygame.draw.rect(screen, (255, 0, 0), apple)  # Draw the apple
pygame.display.update()  # Update the display

10. Controlling the Game Speed

To control the speed of the game, we will use a game clock. Initialize it before the game loop:


clock = pygame.time.Clock()

And then, at the end of your game loop, add:


clock.tick(20)  # This will ensure the game runs at 20 frames per second

Conclusion

And there you have it! You've just coded your version of the classic Snake game in Python. Isn't it fascinating to learn the underlying logic of the games we love and recreate them ourselves? The joy of playing a game you've built from scratch is unparalleled, and we hope this tutorial adds to that joy. Keep learning, keep exploring, and keep coding!

FAQs

1. What is Pygame? Pygame is a Python library designed for making video games. It provides the functionality necessary for game development, such as handling keyboard and mouse events, displaying images and shapes, and playing sounds.

2. What is the game loop? The game loop is the core structure of a game program, where the game's logic runs. It listens for events, updates the game state, and renders the game on the screen.

3. Why does the Snake game end if the snake hits itself? This is one of the rules of the Snake game that increases its difficulty. As the snake grows longer with each apple eaten, avoiding the snake's own body becomes challenging.

4. Can I modify this code to add more features to the game? Absolutely! You can introduce various features like multiple apples, obstacles, power-ups, or even a multiplayer mode. It's all part of the fun of game development.

5. What other games can I build as a beginner? You can try building other classic games like Pong, Tetris, or Space Invaders. These will help you understand different game mechanics and broaden your game development skills.

Did you find this article valuable?

Support Learn!Things by becoming a sponsor. Any amount is appreciated!

ย