Python Snake Game: Code & Tutorial

by Admin 35 views
Python Snake Game: Code & Tutorial

Hey guys! Ready to dive into creating a classic game with Python? We're talking about the legendary Snake game! This tutorial will guide you through building your very own version using Python. So, fire up your IDE, and let's get coding!

Setting Up the Game Environment

Before we jump into the code, we need to set up our game environment. This involves installing the pygame library, which will handle the graphics and user input for our game. If you don't have it already, you can install it using pip:

pip install pygame

Once you have Pygame installed, you're ready to start coding the Snake game. We'll begin by creating the game window and handling basic game events.

Let's start by importing the necessary libraries and initializing Pygame. We'll also define some constants for the screen width, height, and the size of each snake segment. These constants will help us manage the game's appearance and behavior.

import pygame
import time
import random

pygame.init()

# Define colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

# Set display dimensions
display_width = 600
display_height = 400

display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Snake Game')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)

In this initial setup, we've imported the pygame, time, and random modules. We've also defined colors using RGB values, set the display dimensions, and created the game window using pygame.display.set_mode(). The game window's title is set to 'Snake Game' using pygame.display.set_caption(). We've also initialized a clock to control the game's speed and defined variables for the snake block size and speed. Finally, we've created font objects for displaying text in the game.

This foundational code sets the stage for building the rest of the game. With the environment set up, we can move on to implementing the game logic and drawing the snake and food on the screen.

Implementing the Snake

Now, let's define the functions needed to draw the snake on the screen and update its position. The snake will be represented as a list of coordinates, with each coordinate representing a segment of the snake's body. We'll create a function to draw the snake and another to update its position based on the player's input.

First, we need a function to display the score. This function will render the score text on the screen using the font we defined earlier.

def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, white)
    display.blit(value, [0, 0])

Next, we define the function to draw the snake. This function takes the snake's body as a list of coordinates and draws a rectangle for each segment.

def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(display, green, [x[0], x[1], snake_block, snake_block])

Now, let's create the main game loop. This loop will handle user input, update the game state, and draw the game elements on the screen. The game loop will continue until the player quits the game or the snake collides with the boundaries or itself.

def gameLoop():  # defining gameloop function
    game_over = False
    game_close = False

    x1 = display_width / 2
    y1 = display_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            display.fill(blue)
            message("You Lost! Press C-Play Again or Q-Quit", red)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        display.fill(blue)
        pygame.draw.rect(display, red, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if abs(x1 - foodx) < snake_block and abs(y1 - foody) < snake_block:
            foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()

In the gameLoop function, we initialize the game variables, such as the snake's starting position, speed, and length. We also generate the initial position of the food. The main game loop continues until the game_over variable is set to True. Inside the loop, we handle user input using pygame.event.get(). If the player presses an arrow key, we update the snake's direction accordingly. We also check for collisions with the boundaries or the snake's own body. If a collision occurs, we set game_close to True and display a message. If the snake eats the food, we increase its length and generate a new food position. Finally, we draw the snake and food on the screen and update the display.

Adding Game Over Logic

To make the game more engaging, we need to implement the game over logic. This involves displaying a message when the player loses and providing options to play again or quit the game. We'll create a function to display the message and handle the player's input.

Let's define a function to display a message on the screen. This function will take the message text and color as input and render the text in the center of the screen.

def message(msg, color):
    mesg = font_style.render(msg, True, color)
    display.blit(mesg, [display_width / 6, display_height / 3])

In the gameLoop function, when game_close is True, we display the game over message and the player's score. We also provide options to play again (by pressing 'C') or quit the game (by pressing 'Q'). If the player chooses to play again, we call the gameLoop function to start a new game. If the player chooses to quit, we set game_over to True to exit the main game loop.

Putting It All Together

Now that we have all the components of the game, let's put them together and run the game.

Here's the complete code for the Snake game:

import pygame
import time
import random

pygame.init()

# Define colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

# Set display dimensions
display_width = 600
display_height = 400

display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Snake Game')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)


def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, white)
    display.blit(value, [0, 0])



def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(display, green, [x[0], x[1], snake_block, snake_block])



def message(msg, color):
    mesg = font_style.render(msg, True, color)
    display.blit(mesg, [display_width / 6, display_height / 3])



def gameLoop():
    game_over = False
    game_close = False

    x1 = display_width / 2
    y1 = display_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            display.fill(blue)
            message("You Lost! Press C-Play Again or Q-Quit", red)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        display.fill(blue)
        pygame.draw.rect(display, red, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if abs(x1 - foodx) < snake_block and abs(y1 - foody) < snake_block:
            foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()


gameLoop()

Save this code in a file named snake.py and run it using the command python snake.py. You should see the Snake game window appear, and you can start playing the game using the arrow keys.

Enhancements and Further Exploration

Congratulations! You've built your own Snake game in Python. But the fun doesn't have to stop here. There are many ways you can enhance the game and explore new features. Here are a few ideas:

  • Add different difficulty levels: You can adjust the snake's speed to create different difficulty levels.
  • Implement power-ups: Add power-ups that give the snake special abilities, such as temporary invincibility or increased speed.
  • Create a high score system: Save the player's high score to a file and display it in the game.
  • Add sound effects: Incorporate sound effects for actions like eating food or colliding with the boundaries.
  • Design different snake and food shapes: Experiment with different shapes and colors to customize the game's appearance.

By implementing these enhancements, you can take your Snake game to the next level and create a truly unique and engaging experience. So, keep coding and exploring, and have fun!

Conclusion

In this tutorial, we've walked through the process of creating a classic Snake game using Python and the Pygame library. We've covered the essential concepts, such as setting up the game environment, implementing the snake, handling user input, adding game over logic, and enhancing the game with new features. By following this tutorial, you've gained valuable experience in game development and learned how to use Pygame to create interactive games.

Now that you have a solid understanding of the basics, you can continue to explore more advanced game development techniques and create even more complex and exciting games. Remember, the key to success is to keep practicing and experimenting. So, don't be afraid to try new things and push your creative boundaries. With dedication and perseverance, you can become a skilled game developer and bring your ideas to life. Happy coding, and have fun creating games!