Python's pygame writes a snake game

Title python-pygame mini game – Snake.

1. First, we need to import the modules to be used:

import pygame, sys, random
from pygame.locals import *

The pygame.locals module contains various constants used by pygame, and its contents are automatically placed into the namespace of the Pygame module.

2. After the module is imported, we can first define the colors that will be used, and define them according to your preferences:

define color

pinkColor = pygame.Color(255, 182, 193)
blackColor = pygame.Color(0, 0, 0)
whiteColor = pygame.Color(255, 255, 255)

pygame.Color() is an object used to describe the color,

Color(name) -> Color
Color(r, g, b , a) -> Color
Color(rgbvalue) –>Color

Methods & properties of the Color object

pygame.Color.r: get or set the red value of the Color object
pygame.Color.g: get or set the green value of the Color object
pygame.Color.b: get or set the blue value of the Color object
pygame.Color.a: get Or set the alpha value of the Color object
pygame.Color.cmy: Get or set the cmy value of the Color object
pygame.Color.hsva: Get or set the hsav value of the Color object
pygame.Color.hsla: Get or set the hsla value of the Color object
pygame .Color.i 1i2i3: Get or set the I1I2I3 description of the Color object
pygame.Color.normalize: Return the RGBA (display channel) value of a Color object
pygame.Color.correct gamma: The Color object requests a certain gamma value
pygame.Color.set length: Set the value of the element in the Color object to 1, 2, 3, or 4

3. When the game is over, we need to exit the game, so we need to define a function for the game to exit. It is very simple, that is, exit the pygame window first, and then exit the program:

# 定义游戏结束的函数
def gameover():
    # 退出pygame窗口
    pygame.quit()
    # 退出程序
    sys.exit()

4. After defining the end function, we need to define an entry function for entering the game. The main code of the game is written in it:

def main():
    # 初始化
    pygame.init()
    # 定义一个变量来控制速度
    time_clock = pygame.time.Clock()

    # 创建窗口,定义标题
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption("贪吃蛇")

First of all, we need to initialize pygame, create a game window, and define a variable used to control the speed by the way. This variable is used for the movement of the snake.

5. Then initialize some variables used by snakes and food, and regard the entire interface as many small squares of 20x20, and each square represents a unit

# 定义蛇的初始化变量
    snakePosition = [100, 100]  # 蛇头位置
    # 定义一个贪吃蛇的长度列表,其中有几个元素就代表有几段身体,这里我们定义5段身体
    snakeSegments = [[100, 100], [80, 100], [60, 100], [40, 100], [20, 100]]

    # 初始化食物位置
    foodPostion = [300, 300]
   
    # 食物数量,0表示被吃了,1表示没被吃
    foodTotal = 1
    
    # 初始方向,向右
    direction = 'right'
    # 定义一个改变方向的变量,按键
    changeDirection = direction

6. After the data is initialized, use the while loop to listen to events, and make the snake move forward through continuous loops

while True:
        # 从队列中获取事件
        for event in pygame.event.get():
            # 判断是否为退出事件
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # 按键事件
            elif event.type == KEYDOWN:
                # 如果是右键头或者是d,蛇向右移动
                if event.key == K_RIGHT or event.key == K_d:
                    changeDirection = 'right'
                # 如果是左键头或者是a,蛇向左移动
                if event.key == K_LEFT or event.key == K_a:
                    changeDirection = 'left'
                if event.key == K_UP or event.key == K_w:
                    changeDirection = 'up'
                if event.key == K_DOWN or event.key == K_s:
                    changeDirection = 'down'
                # 对应键盘上的Esc键,表示退出
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))

KEYDOWN is a keyboard key event, and K_RIGHT, K_LEFT, K_d, K_a, etc. represent the corresponding keys on the keyboard.

7. Confirm the moving direction of the snake. It cannot move in the opposite direction. For example, if the snake is moving to the right at this time, you cannot control it to move to the left, only up or down

# 确认方向,判断是否输入了反方向运动
        if changeDirection == 'right' and not direction == 'left':
            direction = changeDirection
        if changeDirection == 'left' and not direction == 'right':
            direction = changeDirection
        if changeDirection == 'up' and not direction == 'down':
            direction = changeDirection
        if changeDirection == 'down' and not direction == 'up':
            direction = changeDirection

8. Determine the movement of the snake head through the addition and subtraction of pixels. Adding and subtracting 20px up or down is equivalent to moving up and down one step

 # 根据方向移动蛇头
        if direction == 'right':
            snakePosition[0] += 20
        if direction == 'left':
            snakePosition[0] -= 20
        if direction == 'up':
            snakePosition[1] -= 20
        if direction == 'down':
            snakePosition[1] += 20
        # 增加蛇的长度
        snakeSegments.insert(0, list(snakePosition))
        # 判断是否吃到食物
        if snakePosition[0] == foodPostion[0] and snakePosition[1] == foodPostion[1]:
            foodTotal = 0
        else:
            snakeSegments.pop()  # 每次将最后一单位蛇身剔除列表
        # 如果食物为0 重新生成食物
        if foodTotal == 0:
            x = random.randrange(1, 32)
            y = random.randrange(1, 24)
            foodPostion = [int(x * 20), int(y * 20)]
            foodTotal = 1
        # 绘制pygame显示层
        screen.fill(blackColor)

9. Set the color length and width of the snake and food

   for position in snakeSegments:  # 蛇身为白色
            # 化蛇
            pygame.draw.rect(screen, pinkColor, Rect(position[0], position[1], 20, 20))
            pygame.draw.rect(screen, whiteColor, Rect(foodPostion[0], foodPostion[1], 20, 20))

10. Update the display to the screen surface

pygame.display.flip()

11. Determine whether the game is over

		# 判断游戏是否结束
        if snakePosition[0] > 620 or snakePosition[0] < 0:
            gameover()
        elif snakePosition[1] > 460 or snakePosition[1] < 0:
            gameover()
        # 如果碰到自己的身体
        for body in snakeSegments[1:]:
            if snakePosition[0] == body[0] and snakePosition[1] == body[1]:
                gameover()

        # 控制游戏速度
        time_clock.tick(5)

12. Entry function

if __name__ == '__main__':
    main()

**Then you can run the code, as shown below
insert image description here
insert image description here

full code **

import pygame, sys, random
from pygame.locals import *


# 定义颜色
pinkColor = pygame.Color(255, 182, 193)
blackColor = pygame.Color(0, 0, 0)
whiteColor = pygame.Color(255, 255, 255)


# 定义游戏结束的函数
def gameover():
    pygame.quit()
    sys.exit()


def main():
    # 初始化
    pygame.init()
    # 定义一个变量来控制速度
    time_clock = pygame.time.Clock()

    # 创建窗口,定义标题
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption("贪吃蛇")

    # 定义蛇的初始化变量
    snakePosition = [100, 100]  # 蛇头位置
    # 定义一个贪吃蛇的长度列表,其中有几个元素就代表有几段身体
    snakeSegments = [[100, 100], [80, 100], [60, 100], [40, 100], [20, 100]]
    # 初始化食物位置
    foodPostion = [300, 300]
    # 食物数量,1是没被吃,0是被吃了
    foodTotal = 1
    # 初始方向,向右
    direction = 'right'
    # 定义一个改变方向的变量,按键
    changeDirection = direction

    # 通过键盘控制蛇的运动
    while True:
        # 从队列中获取事件
        for event in pygame.event.get():
            # 判断是否为退出事件
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # 按键事件
            elif event.type == KEYDOWN:
                # 如果是右键头或者是d,蛇向右移动
                if event.key == K_RIGHT or event.key == K_d:
                    changeDirection = 'right'
                # 如果是左键头或者是a,蛇向左移动
                if event.key == K_LEFT or event.key == K_a:
                    changeDirection = 'left'
                if event.key == K_UP or event.key == K_w:
                    changeDirection = 'up'
                if event.key == K_DOWN or event.key == K_s:
                    changeDirection = 'down'
                # 对应键盘上的Esc键,表示退出
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))

        # 确认方向,判断是否输入了反方向运动
        if changeDirection == 'right' and not direction == 'left':
            direction = changeDirection
        if changeDirection == 'left' and not direction == 'right':
            direction = changeDirection
        if changeDirection == 'up' and not direction == 'down':
            direction = changeDirection
        if changeDirection == 'down' and not direction == 'up':
            direction = changeDirection

        # 根据方向移动蛇头
        if direction == 'right':
            snakePosition[0] += 20
        if direction == 'left':
            snakePosition[0] -= 20
        if direction == 'up':
            snakePosition[1] -= 20
        if direction == 'down':
            snakePosition[1] += 20

        # 增加蛇的长度
        snakeSegments.insert(0, list(snakePosition))
        # 判断是否吃到食物
        if snakePosition[0] == foodPostion[0] and snakePosition[1] == foodPostion[1]:
            foodTotal = 0
        else:
            snakeSegments.pop()  # 每次将最后一单位蛇身剔除列表

        # 如果食物为0 重新生成食物
        if foodTotal == 0:
            x = random.randrange(1, 32)
            y = random.randrange(1, 24)
            foodPostion = [int(x * 20), int(y * 20)]
            foodTotal = 1

        # 绘制pygame显示层
        screen.fill(blackColor)


        for position in snakeSegments:  # 蛇身为白色
            # 化蛇
            pygame.draw.rect(screen, pinkColor, Rect(position[0], position[1], 20, 20))
            pygame.draw.rect(screen, whiteColor, Rect(foodPostion[0], foodPostion[1], 20, 20))

        # 更新显示到屏幕表面
        pygame.display.flip()

        # 判断游戏是否结束
        if snakePosition[0] > 620 or snakePosition[0] < 0:
            gameover()
        elif snakePosition[1] > 460 or snakePosition[1] < 0:
            gameover()
        # 如果碰到自己的身体
        for body in snakeSegments[1:]:
            if snakePosition[0] == body[0] and snakePosition[1] == body[1]:
                gameover()

        # 控制游戏速度
        time_clock.tick(5)



#  启动入口函数
if __name__ == '__main__':
    main()

Guess you like

Origin blog.csdn.net/lishihuijava/article/details/107390198