Python writing small games three into the simplest and most simple greedy snake writing

This time, I will make the simplest prototype game of greedy snake, that is, a small snake moves on the screen. We can control the moving direction of the snake, but we cannot eat, and the snake will not grow up. But with the basics, is the full version of Snake still far away? Isn't that the same thing as the two people greedy for snakes?

Make a simple one first, and then release the less simple, but still crude, standard Snake and Two-player Snake when you have a chance.

First of all, the various configuration parameters of pygam directly use the previous configuration, and more refunds and less supplements.

import random
import time
import pygame


fps = 30
fps_clock = pygame.time.Clock()
screen_width = 640
screen_height = 480

display = pygame.display.set_mode((screen_width, screen_height), 0, 32)
pygame.display.set_caption('贪食蛇')
tile_size = 20
tile_width = 20
tile_height = 20

#横纵间距
x_margin = 100
y_margin = 100

#列
columns = int((screen_width - 100) / 20)
#行
rows = int((screen_height - 100) / 20)
directions = ['up', 'down', 'left', 'right']

#配色RGB
white = 'white'
black = 'black'
bg_color = 'sky blue'
border_color = white


if __name__ == '__main__':

    while True:
        display.fill(bg_color)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

        pygame.display.update()
        fps_clock.tick(fps)

Basic configuration functions, routine operations of board games.

Running the game gets an azure canvas with nothing.

Please add a picture description

Next, draw a two-dimensional chessboard on the canvas, which is the venue for the snake to move. Here we have several options, and here I choose the simplest way, that is, the entire chessboard does not correspond to a two-dimensional list, and only creates a list for the snake itself, which is used to store the body of the snake.

Start by drawing a large chessboard.

def draw_chest():
    for i in range(rows + 1):
        pygame.draw.line(display, border_color, (x_margin/2, y_margin/2 + i * tile_size),
                         (x_margin/2 + (columns * tile_size), y_margin/2 + i * tile_size), 2)

    for j in range(columns + 1):
        pygame.draw.line(display, border_color, (x_margin/2 + j * tile_size, y_margin/2),
                         (x_margin/2 + j * tile_size, y_margin/2 + (rows * tile_size)), 2)

Then call it in the main loop, and then run the program.

Please add a picture description

The exercise space of the Snake has already appeared.

Create a list to store the snake's body. The default length of the snake is 3. The specific size can be modified according to your own preferences, I will write 3.

Then it is necessary to generate the first position of the snake's body based on these two values. For example, the first position of the snake body we generated is [3][3], then a small square is drawn corresponding to the coordinate position corresponding to [3][3] on the screen, and the default snake body is Extending to the right, then the body parameters of the snake are [3][3],[3][4],[3][5]

Considering that the snake randomly appears in certain places on the screen, the body of the snake is generated to take care of all parties. The range of random numbers is as follows:

Create a list outside the main loop, add a body, and keep the body in the center of the frame.

snake_body = []
    snake_x = random.randint(5, rows - 5)
    snake_y = random.randint(5, columns - 5)
    snake_body.append([snake_x, snake_y])
    snake_body.append([snake_x, snake_y + 1])
    snake_body.append([snake_x, snake_y + 2])
    return snake_body

To draw the snake's body, write a drawing function.

def draw_snake_shape(shapes):
    for shape in shapes:
        left_position = shape[1] * tile_size + x_margin/2
        top_position = shape[0] * tile_size + y_margin/2
        # 画出整个身体背景色
        pygame.draw.rect(display, body_color, (left_position, top_position, tile_size, tile_size))
        # 画出内部颜色
        pygame.draw.rect(display, inter_body_color, (left_position+4, top_position+4, tile_size-8, tile_size-8))

Called in the main loop, run the game, each run, the snake is in a different position, and does not appear on the edge.

Please add a picture description

The next step is to get the snake moving.

The core idea of ​​making the snake move is to add and delete the coordinate values ​​in snake_body according to the current direction of the snake. For example, if the next movement direction of the snake is up, then confirm that the current up direction is legal, that is, one step up will not reach the boundary, or it is currently going down, then we get a new coordinate point and add Go to snake_body, and delete the last data in the list at the same time, because there are currently no apples to eat.

First define a function to judge whether the next coordinate point is legal.

def is_right_direction(body, x_location, y_location):
    valid_direction = False
    if 0 <= x_location <= rows-1 and 0 <= y_location <= columns - 1:
        valid_direction = True
    return valid_direction

Add a program in the main loop to handle the operation of the snake body list when the snake moves in a fixed direction.

First, before entering the main loop, get the current direction to move

direction = directions[random.randint(0, 3)]

    while True:

Inside the main loop, add code to handle body movement

#未按下按键时,默认的初识移动方向
        new_body_location = (None, None)
        match direction:
            case 'left':
                new_body_location = snake_body[0][0], snake_body[0][1] - 1
            case 'right':
                new_body_location = snake_body[0][0], snake_body[0][1] + 1
            case 'up':
                new_body_location = snake_body[0][0] - 1, snake_body[0][1]
            case 'down':
                new_body_location = snake_body[0][0] + 1, snake_body[0][1]
        snake_body.insert(0, new_body_location)
        del snake_body[-1]

Run the program at this time, and the snake will move to the edge of the screen as quickly as lightning.

Please add a picture description

There is no time to take screenshots, because our refresh rate is 30 frames per second, so it is too fast, there are many solutions at this time, the simplest one is to modify the refresh rate, for example, if it is changed to 2, then you will see that the snake is slow moved. It's very simple. You can also consider doing timing in the moving part, or doing cumulative delay and so on. Here I modified fps=2.

Please add a picture description

Next add the control part, this part is very simple.

In the button part, set the up, down, left, and right buttons to control the direction. At the same time, it should be noted that the greedy snake cannot turn around directly.

#键盘控制改变贪食蛇的方向
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT and direction != 'right':
                    direction = 'left'
                elif event.key == pygame.K_RIGHT and direction != 'left':
                    direction = 'right'
                elif event.key == pygame.K_UP and direction != 'down':
                    direction = 'up'
                elif event.key == pygame.K_DOWN and direction != 'up':
                    direction = 'down'

Game over mechanism, that is, the snake hits the border and the game ends.

        if is_right_direction(snake_body, new_body_location[0], new_body_location[1]):
            snake_body.insert(0, new_body_location)
            del snake_body[-1]
        else:
            snake_body = []
            snake_x = random.randint(5, columns - 5)
            snake_y = random.randint(5, rows - 5)
            snake_body.append([snake_x, snake_y])
            snake_body.append([snake_x, snake_y + 1])
            snake_body.append([snake_x, snake_y + 2])

The Snake at the frame level is finished. If you add a small apple and increase the physical condition, you will have a complete Snake. Add another tail-chasing mechanism, and a new snake can be used for two-player battles.

to be continued…

Guess you like

Origin blog.csdn.net/jackwsd/article/details/126468074