Teach you to use Python to write a snake game (pygame, with source code)

Snake is one of the most popular arcade games of all time. In this game, the main goal of the player is to catch the maximum number of fruits without hitting or hitting the wall. Consider creating a snake game as a challenge when learning Python or Pygame. This is one of the best beginner-friendly projects that every novice programmer should pick up. Learning to build video games is fun and fun learning.

We will use Pygame to create this snake game. Pygame is an open source library designed for making video games. It has a built-in graphics and sound library. It's also beginner-friendly and cross-platform.

Simple, the most basic game elements only need two snakes and food to proceed. (Three elements are needed to fly a plane. Think about what they are?) For directions, you only need 4 fixed directions of up, down, left, and right.
There are basic data structures and object-oriented ideas in it. Game development itself will use a lot of object-oriented concepts, and the snake's body is a natural "linked list" structure, which is very suitable for practicing data structures. Another interesting point is that the word Python means python in English, and Snake Snake can be regarded as a "game of the same name". Many school assignments in program development courses will have snake-eating topics, and students often ask about our related codes. (Nokia mobile phones also have a soft spot for this game.) I made a Python version of "Snake Fight" before, which was developed based on cocos2d-python. But that's a bit complicated for beginners.
Here we make a brief introduction:
this code is developed based on pygame, so please make sure that pygame has been successfully installed in your Python before running. Then directly run game2.py in the code to start the game. In addition to the final code, we also decomposed several py files in the process for reference by students who want to develop by themselves.
Let's first analyze what points need to be paid attention to when writing this game.
1. How does the snake represent?
We can divide the entire game area into small grids. A group of small grids connected together form a "snake". We can use different colors to represent them. Means "snake".
We can use coordinates to represent each small square, and the range of X-axis and Y-axis can be set. Use a list to store the coordinates of the "snake body", then a "snake" will come out, and finally it only needs to be displayed in different colors.
2. How does the snake move?
The first reaction is to move each small square forward one space like an earthworm, but it is very troublesome to realize. It was stuck here from the beginning.
Imagine the greedy snake we have played. Every time the "snake" moves, it feels like it moves forward as a whole. Exclude the "action" of the "snake" in your mind, and think carefully about the "snake" before and after moving. In fact, except for the head and tail, the other parts have not changed at all. That's easy, adding the coordinates of the next space to the beginning of the list and removing the last element of the list is equivalent to moving the snake forward one space.
3. How to determine the end of the game?
If the "snake" moves beyond the scope of the game area or touches itself, it will be considered a loss. The range of the axis coordinates is predetermined, and it is easy to judge if it exceeds the range. So how do you judge when you meet yourself?
If the picture of the "snake" moving in your mind is really difficult, but in the code, our "snake" is a list, then we only need to judge whether the coordinates of the next grid are included in the "snake" Wouldn't it be on the list?
With these questions sorted out, we can start coding.
 

Official account: Daily Healing Series, get more related resources!


There are several important objects in pygame, which are
pygame.display—set scene display, including page size, page title, page update (refresh), etc.;
pygame.time—set all time-related settings, game frame rate, The duration of the game, etc.;
pygame.event – ​​set up event-related processing, such as mouse click events, keyboard press events, etc.;
pygame.draw – draw graphics to the interface.

The steps are:

1. Build the initial framework and draw the scene

To make the Snake game, the first step is to build an initial interface, including setting the size of the interface, setting the closing interface event, setting the frame rate, rendering the page background and updating the page, etc. The specific code is as follows:

# 游戏初始化
pygame.init()

# 游戏窗口大小
window_width = 800
window_height = 600

# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)

# 设置游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')

2. Draw the position of the snake head, food and snake body

To put it simply, it is to determine the position of the snake head and the food, the code is as follows:

# 蛇头坐标
snake_x = window_width / 2
snake_y = window_height / 2

# 蛇身列表
snake_body = [[snake_x, snake_y]]

# 食物坐标
food_x = round(random.randrange(0, window_width - 20) / 20) * 20
food_y = round(random.randrange(0, window_height - 20) / 20) * 20

3. Create a function to display the player's score.

  • In this function, first we need to create a font object, that is, the font color will appear here.
  • We then use render to create a background surface that we change every time our score is updated.
  • Create a rectangle object for the text surface object (the text will be refreshed here)
score = 0

# 游戏结束标志
game_over = False

# 游戏时钟
clock = pygame.time.Clock()

# 游戏循环
while not game_over:
    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:
                direction = 'LEFT'
            elif event.key == pygame.K_RIGHT:
                direction = 'RIGHT'
            elif event.key == pygame.K_UP:
                direction = 'UP'
            elif event.key == pygame.K_DOWN:
                direction = 'DOWN'

    if direction == 'LEFT':
        snake_x -= snake_speed
    elif direction == 'RIGHT':
        snake_x += snake_speed
    elif direction == 'UP':
        snake_y -= snake_speed
    elif direction == 'DOWN':
        snake_y += snake_speed

4. In addition, the game enters a loop, constantly updating the snake body and scores

code show as below:

 # 绘制背景
    window.fill(black)

    # 绘制蛇身
    for segment in snake_body:
        pygame.draw.rect(window, green, [segment[0], segment[1], 20, 20])

    # 绘制食物
    pygame.draw.rect(window, red, [food_x, food_y, 20, 20])

    # 更新蛇身
    snake_head = [snake_x, snake_y]
    snake_body.append(snake_head)
    if len(snake_body) > score + 1:
        del snake_body[0]

    # 检测蛇与食物的碰撞
    if snake_x == food_x and snake_y == food_y:
        score += 1
        food_x = round(random.randrange(0, window_width - 20) / 20) * 20
        food_y = round(random.randrange(0, window_height - 20) / 20) * 20

    # 检测蛇头与蛇身的碰撞
    for segment in snake_body[:-1]:
        if segment == snake_head:
            game_over = True

    # 检测蛇是否超出边界
    if snake_x >= window_width or snake_x < 0 or snake_y >= window_height or snake_y < 0:
        game_over = True

    # 刷新游戏窗口
    pygame.display.update()

5. I won't say much, the complete code is as follows:

import pygame
import random

# 游戏初始化
pygame.init()

# 游戏窗口大小
window_width = 800
window_height = 600

# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)

# 设置游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')

# 蛇头坐标
snake_x = window_width / 2
snake_y = window_height / 2

# 蛇身列表
snake_body = [[snake_x, snake_y]]

# 食物坐标
food_x = round(random.randrange(0, window_width - 20) / 20) * 20
food_y = round(random.randrange(0, window_height - 20) / 20) * 20

# 蛇移动速度
snake_speed = 20

# 方向
direction = 'RIGHT'

# 分数
score = 0

# 游戏结束标志
game_over = False

# 游戏时钟
clock = pygame.time.Clock()

# 游戏循环
while not game_over:
    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:
                direction = 'LEFT'
            elif event.key == pygame.K_RIGHT:
                direction = 'RIGHT'
            elif event.key == pygame.K_UP:
                direction = 'UP'
            elif event.key == pygame.K_DOWN:
                direction = 'DOWN'

    if direction == 'LEFT':
        snake_x -= snake_speed
    elif direction == 'RIGHT':
        snake_x += snake_speed
    elif direction == 'UP':
        snake_y -= snake_speed
    elif direction == 'DOWN':
        snake_y += snake_speed

    # 绘制背景
    window.fill(black)

    # 绘制蛇身
    for segment in snake_body:
        pygame.draw.rect(window, green, [segment[0], segment[1], 20, 20])

    # 绘制食物
    pygame.draw.rect(window, red, [food_x, food_y, 20, 20])

    # 更新蛇身
    snake_head = [snake_x, snake_y]
    snake_body.append(snake_head)
    if len(snake_body) > score + 1:
        del snake_body[0]

    # 检测蛇与食物的碰撞
    if snake_x == food_x and snake_y == food_y:
        score += 1
        food_x = round(random.randrange(0, window_width - 20) / 20) * 20
        food_y = round(random.randrange(0, window_height - 20) / 20) * 20

    # 检测蛇头与蛇身的碰撞
    for segment in snake_body[:-1]:
        if segment == snake_head:
            game_over = True

    # 检测蛇是否超出边界
    if snake_x >= window_width or snake_x < 0 or snake_y >= window_height or snake_y < 0:
        game_over = True

    # 刷新游戏窗口
    pygame.display.update()

    # 控制游戏帧率
    clock.tick(10)

# 游戏结束,退出
pygame.quit()

Official account: Daily Healing Series, get more related resources! Contains a variety of programming games and explanations

Guess you like

Origin blog.csdn.net/qq_72290695/article/details/131356187