Snake game (based on Python)

Don't talk nonsense and go directly to the code , this wave will directly stabilize everyone's mood.

import pygame, sys, random, time
from pygame.locals import *  # 从pygame模块导入常用的函数和常量
#定义颜色变量
black_colour = pygame.Color(0, 0, 0)
white_colour = pygame.Color(255, 255, 255)
red_colour = pygame.Color(255,0 , 0)
grey_colour = pygame.Color(150, 150, 150)
light_colour = pygame.Color(220,220,220)
#定义游戏结束函数
def GameOver(gamesurface):
    # 设置提示字体的格式
    GameOver_font = pygame.font.SysFont("MicrosoftYaHei", 45)
    # 设置提示字体的颜色
    GameOver_colour = GameOver_font.render('GameOver', True, grey_colour)#只能英文
    # 设置提示位置
    GameOver_location = GameOver_colour.get_rect()
    GameOver_location.midtop = (310, 200)
    # 绑定以上设置到句柄
    gamesurface.blit(GameOver_colour, GameOver_location)
    # 提示运行信息
    pygame.display.flip()
    # 休眠5秒
    time.sleep(3)
    # 退出游戏
    pygame.quit()
    # 退出程序
    sys.exit()
#定义主函数
def main():
    # 初始化pygame,为使用硬件做准备
    pygame.init()
    pygame.time.Clock()
    ftpsClock = pygame.time.Clock()
    # 创建一个窗口
    gamesurface = pygame.display.set_mode((640, 480))
    # 设置窗口的标题
    pygame.display.set_caption('贪吃蛇 snake')
    # 初始化变量
    # 初始化贪吃蛇的起始位置
    snakeposition = [100, 100]
    # 初始化贪吃蛇的长度
    snakelength = [[100, 100], [80, 100], [60, 100]]
    # 初始化目标方块的位置
    square_purpose = [300, 300]
    # 初始化一个数来判断目标方块是否存在
    square_position = 1
    # 初始化方向,用来使贪吃蛇移动
    derection = "right"
    change_derection = derection
    pygame.mixer.music.load("a.mp3")
    # 进行游戏主循环
    while True:
        if pygame.mixer.music.get_busy() == False :
            pygame.mixer.music.play()
        # 检测按键等pygame事件
        for event in pygame.event.get():
            if event.type == QUIT:
                # 接收到退出事件后,退出程序
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                # 判断键盘事件,用w,s,a,d来表示上下左右
                if event.key == K_RIGHT or event.key == ord('d'):
                    change_derection = "right"
                if event.key == K_LEFT or event.key == ord('a'):
                    change_derection = "left"
                if event.key == K_UP or event.key == ord('w'):
                    change_derection = "up"
                if event.key == K_DOWN or event.key == ord('s'):
                    change_derection = "down"
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
        # 判断移动的方向是否相反
        if change_derection == 'left' and not derection == 'right':
            derection = change_derection
        if change_derection == 'right' and not derection == 'left':
            derection = change_derection
        if change_derection == 'up' and not derection == 'down':
            derection = change_derection
        if change_derection == 'down' and not derection == 'up':
            derection = change_derection
        # 根据方向,改变坐标
        if derection == 'left':
            snakeposition[0] -= 20
        if derection == 'right':
            snakeposition[0] += 20
        if derection == 'up':
            snakeposition[1] -= 20
        if derection == 'down':
            snakeposition[1] += 20
        # 增加蛇的长度
        snakelength.insert(0, list(snakeposition))
        # 判断是否吃掉目标方块
        if snakeposition[0] == square_purpose[0] and snakeposition[1] == square_purpose[1]:
            square_position = 0
        else:
            snakelength.pop()
        # 重新生成目标方块
        if square_position == 0:
            # 随机生成x,y,扩大二十倍,在窗口范围内
            x = random.randrange(1, 32)
            y = random.randrange(1, 24)
            square_purpose = [int(x * 20), int(y * 20)]
            square_position = 1
        # 绘制pygame显示层
        gamesurface.fill(white_colour)
        for position in snakelength:
            pygame.draw.rect(gamesurface, light_colour, Rect(position[0], position[1], 20, 20))
            pygame.draw.rect(gamesurface, red_colour, Rect(square_purpose[0], square_purpose[1], 20, 20))
            pygame.draw.rect(gamesurface, black_colour, Rect(snakeposition[0], snakeposition[1], 20, 20))
        # 刷新pygame显示层
        pygame.display.flip()
        # 判断是否死亡
        if snakeposition[0] < 0 or snakeposition[0] > 620:
            GameOver(gamesurface)
        if snakeposition[1] < 0 or snakeposition[1] > 460:
            GameOver(gamesurface)
        for snakebody in snakelength[1:]:
            if snakeposition[0] == snakebody[0] and snakeposition[1] == snakebody[1]:
                GameOver(gamesurface)
        # 显示分数
        # 显示速度
        score = 0
        speed = 5
        if len(snakelength)>3:
            score = len(snakelength) - 3
            speed = speed + score/4
        score_font = pygame.font.Font(None, 36)
        score_text1 = score_font.render('Score: '+ str(score), True, (0, 0, 0))
        score_text2 = score_font.render('Speed: '+ str(speed), True, (0, 0, 0))
        text_rect1 = score_text1.get_rect()
        text_rect2 = score_text2.get_rect()
        text_rect1.topleft = [10, 10]
        text_rect2.topright = [630, 10]
        gamesurface.blit(score_text1, text_rect1)
        gamesurface.blit(score_text2, text_rect2)
       # 更新屏幕(因为分数或者速度及时变化得以屏幕所显改变)
        pygame.display.update()
        ticks = pygame.time.get_ticks()
        ftpsClock.tick(speed)
        
if __name__ == "__main__":
    main()

For similar basic mini-games, different programming languages ​​can be used to write them. First, ensure the integrity of the code, and then create some personalized content based on the foundation of integrity.

First of all, we need to know what we want to do and how to do it . After clarifying these concepts, we should organize our thinking and start thinking about what to write before and after, and what to write in between.

Let me share my mental journey in text form:

1. Preliminary thinking and preparation
for this type of small game When we first came into contact with mobile phones, that is, the old version of Nokia, this game gradually became a must for daily entertainment, but with the popularity of smart phones and the advent of the Internet age , The greedy snake has gradually evolved, but we should understand the essence of the greedy snake.
We can try to recall the page after Snake entered the game. For example, there is a small snake first, which is similar to a Python list. There is no rule in the order of this list. It is the display length len, and then randomly generates a point (with key value), control the snake by controlling the arrow keys, make the snake close to the point, and finally "collect" the point, that is, integrate, so that the length of the snake increases. With the growth of the snake's body, it is the list len
,
and it can display"game over"., given a fixed position (x, y, z) in a window, assuming that the snake appears at this point, determine the shape of the snake: square, the head of the snake can be a list, and elements can be added at will. In the second step, the point
that
appearsis to
move the snake
by "w, a, s, d" or "up, down, right, left" to move the snake. When writing code, you can try to press a key to execute it directly There is no need to enter again to confirm, restrictions: the snake cannot move in the opposite direction
. The fourth step,
add a list to the head of the snake at the fusion point of the snake, and add elements to the list. As the snake steps into this point, the key value of this point will enter In the list, the len (list) increases, so that the snake looks longer
Step 5, the snake dies
Through the game process, we know that there will be four situations in which the snake dies. 1. Touching the wall is also the four edges of the window at this time; 2. Touching 'your own body'; 3. Filling the entire created window. ", 4. When we first press the 'up' key or 'w' and then press the 'down' or 's' key, it can be understood that the snake touches its body and dies

Details: black bottom of the window, white body of the snake, random point (can be multiple) red, the snake eats food, which is the list fusion element record, and finally the score obtained in this game is obtained through the initial length len and the final death length len. The little snake head can be a list, and elements can be added at will.

All of the above are executed in the same window

2. Code display part (above code)

The background music part can be selected at will, and bloggers cannot upload it here.

3. Explanation part
① My work is: Snake Snake (hereinafter referred to as snake)
② The function I realized is: first generate a fixed-length snake god and snake head through the given coordinates in the window, and then randomly generate a raspberry or A coordinate point, and then change the direction of the snake by controlling the up, down, left, and right direction keys or the w, a, s, d keys. After each change of direction, it will move in a straight line according to the changed direction, and randomly generate raspberries at the snake head coordinate point. When the points overlap, it is judged that the snake has eaten food at this time, and then the food is randomly generated. As the snake eats the food, the snake body gradually increases in speed and the score also increases. By running the code generation window, these things can be see directly. The core of the work is the third-party library-pygame library, creating windows, drawing and refreshing the pygame display layer, displaying scores and speeds inside the window, and updating the screen. (As a reminder, when we use a third-party library, try to go to the IDLE window and type "import library name" to check. After typing, press the enter key to display the version number of the library, which means that the library has been installed. Otherwise, you need to manually go to the network. Type "pip install library name" in the command window to install)
③ Features of the work: (partially restore the original Snake that appeared on the "elderly machine") For the small game Snake, I was relatively familiar with it when I was young Many, before the popularization of smartphones, small games such as Snake may have accompanied us in our childhood. In my impression, the games at that time were not as complicated and changeable as they are now, but they were the mainstream entertainment items at that time, including Sokoban, Tetris, Lianliankan, etc. The code of this game is very open, so the implementation of the arrow keys is generally the same. The special feature of this work may be that the speed starts to increase as the snake eats food (speed is adjustable) and the score and score are displayed on the window interface. Speed, the tension and excitement brought by the visual sense increase with the visible speed, and at the same time, the screen refresh makes the score display let us know the progress of our game at any time. The last is the appearance of background music (can be changed). Playing games is to relax and entertain and kill time. We can slow down the game speed while listening to a soothing song or speed up the speed while changing the background music to a fast-paced song. Let our eyes, ears, and brain feel at the same time, which is more helpful to experience the fun of the game.
④ Problems encountered: Many problems have been solved. For example, in order to speed up the game, change the original routine and add an if judgment statement, such as the score and speed are displayed in the window and the code for updating the screen at the end is also with the help of classmates. The next is completed. One way to solve the problem is to constantly try and make mistakes, check information, and discuss with classmates. Among them, the discussion with classmates is the most direct, because in the process of writing programs, you have your own opinions and solutions to problems encountered, so you can’t solve the problems you encounter. The problem might not be the problem. In addition, when we look up information or paste codes, we must understand the meaning, not just "sticky food", then the course design will violate the original intention.

It is near the end of this sharing, and I hope everyone will benefit from it. Finally, I would like to say: get started and think more , talent in the computer industry is out of the question, only hard work and hard work, come on, encourage each other.

 

Guess you like

Origin blog.csdn.net/m0_58366299/article/details/127385358