Python Game Day 01: Snake Game

Python Game Day 01: Snake GamePython Game Day 01: Snake Game

1. Preparation

Before you start writing code, you need to ensure that Python and the `pygame` library are installed. If you haven’t installed `pygame`, you can do so using the following command in the cmd terminal:

pip install pygame

2. Snake Game Code

Here is the complete code:

import pygame
import random
import time

# Initialize pygame
pygame.init()

# Set window size
width = 800
height = 600

# Set colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

# Set game window
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

# Set frame rate
clock = pygame.time.Clock()
snake_speed = 15

# Define snake size
snake_block = 20

# Font settings
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)

def show_score(score):
    """Display score"""
    value = score_font.render("nums: " + str(score), True, white)
    window.blit(value, [10, 10])

def draw_snake(snake_block, snake_list):
    """Draw snake"""
    for block in snake_list:
        pygame.draw.rect(window, green, [block[0], block[1], snake_block, snake_block])

def message(msg, color):
    """Display message"""
    mesg = font_style.render(msg, True, color)
    window.blit(mesg, [width / 6, height / 3])

def game_loop():
    """Main game loop"""
    game_over = False
    game_close = False

    # Initialize snake position and length
    x1 = width / 2
    y1 = height / 2
    x1_change = 0
    y1_change = 0
    snake_list = []
    length_of_snake = 1

    # Food position
    foodx = round(random.randrange(0, width - snake_block) / snake_block) * snake_block
    foody = round(random.randrange(0, height - snake_block) / snake_block) * snake_block

    while not game_over:
        while game_close:
            # Game over screen
            window.fill(black)
            message("game over!  Q break or C continue", red)
            show_score(length_of_snake - 1)
            pygame.display.update()

            # Check for key presses
            for event in pygame.event.get():
                if event.type == pygame.QUIT:  # Check for window close event
                    game_over = True
                    game_close = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        game_loop()

        # Check for key presses
        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # Check for window close event
                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

        # Check for collisions
        if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
            game_close = True

        # Update snake position
        x1 += x1_change
        y1 += y1_change
        window.fill(black)
        pygame.draw.rect(window, red, [foodx, foody, snake_block, snake_block])
        snake_head = []
        snake_head.append(x1)
        snake_head.append(y1)
        snake_list.append(snake_head)

        # Control snake length
        if len(snake_list) > length_of_snake:
            del snake_list[0]

        # Check if snake collides with itself
        for block in snake_list[:-1]:
            if block == snake_head:
                game_close = True

        # Draw snake
        draw_snake(snake_block, snake_list)
        show_score(length_of_snake - 1)
        pygame.display.update()

        # Check if food is eaten
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, width - snake_block) / snake_block) * snake_block
            foody = round(random.randrange(0, height - snake_block) / snake_block) * snake_block
            length_of_snake += 1

        # Control frame rate
        clock.tick(snake_speed)

    # Exit game
    pygame.quit()
    quit()

# Start game
game_loop()

3. Code Analysis

### Initialize the game window, creating a game window with a width of 800 pixels and a height of 600 pixels, and setting the window title.

window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

### Set colors, defining some commonly used colors for later use.

black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

### Snake movement and control, this part of the code listens for keyboard events and updates the snake’s movement direction based on the player’s key presses.

for event in pygame.event.get():
    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

### Food generation, using the `random` module to randomly generate the food’s position, ensuring that the food does not appear on the snake’s body.

foodx = round(random.randrange(0, width - snake_block) / snake_block) * snake_block
foody = round(random.randrange(0, height - snake_block) / snake_block) * snake_block

### Collision detection, checking if the snake collides with the walls. If it does, the game ends.

if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
    game_close = True

### Check if the snake collides with its own body. If it does, the game ends.

for block in snake_list[:-1]:
    if block == snake_head:
        game_close = True

### Score display, displaying the current score in the top left corner of the game window.

def show_score(score):
    value = score_font.render("Score: " + str(score), True, white)
    window.blit(value, [10, 10])

The source code for this lesson is available in the group materials of the study group. Follow the public account and reply with “study” to join the group and receive the source code for this lesson’s case.

Leave a Comment