Write a simple snake game in python

Introductory tutorials, case source code, learning materials, readership

Please visit:  python666.cn

Hello everyone, welcome to Crossin's programming classroom!

I don’t know how many students are like me. The motivation for the first contact with programming was to make a game for yourself?

Although Python is not a language "born for games", it also has its own game engine. The most commonly used is pygame . There is also a well-known game engine cocos2d , and its initial version is cocos2d-python based on python. We have had cases with these two engines, among which pygame has even done a more detailed introductory tutorial--the mini-game "Hit the Aircraft", see the link at the end of the article.

What I want to share with you today is a " snake " game written by pygame :

f7c93668d65a7bd389f2e272532b81c1.gif

The small game "Snake" is a frequent visitor in programming learning because:

1. Simple , the most basic game elements only need two snakes and food. (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.

2. 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 have made a Python version of " Snake Fight " before, which was developed based on cocos2d-python . But that's a bit complicated for beginners. This time, it is a simple version that is more suitable for beginners to learn, developed by our teaching assistant @清风小树.

For the detailed description of the entire development process and code, we have written it in the document and uploaded it to github. Students who need it can download and practice by themselves, and try to change the speed and color of the snake, add more food, etc. (To obtain the address, please reply to the keyword Snake in the programming classroom of the official account Crossin )

Here we give 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 mySnake.py in the code to start the game.

In addition to the final code, we also deliberately decomposed several py files in the process for reference by students who want to develop by themselves.

Development idea

Game development usually adopts object-oriented design. Here we have three classes: snake , food , and background (used to draw the grid).

The main loop of the game mainly does the following things in turn:

  1. Get keyboard events

  2. draw background

  3. Update the position of the snake 

  4. snake, food

  5. Impact checking

  6. screen refresh

The drawing of snakes and food is realized through the Surface  object in pygame  , drawing grids of different colors.

The body of the snake uses a Rect object and is saved through a list .

The movement of the snake is the core operation of this game. We did not choose to modify the position of the snake, but each time we move, we add a head node according to the forward direction of the snake, move the rest of the position forward by one node, and delete the tail node, which is equivalent to realizing the movement of the snake. If food is eaten, add nodes at the end to achieve growth.

To do collision detection in the game , just use colliderect of pygame . We have to judge: 1. Did you hit the wall? 2. Did you hit yourself? 3. Did it hit the food? Then do different processing

The core code of the game main loop:

while going:
    lastt = clock.tick(60) # 帧率 60
    dt += lastt # 累计时间
    c += 1
    # 0 键盘按压等事件响应
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_UP and validDirect != 0: direct = 1 # 按了向上 1 并且当前方向不是向下 0 ,则向上
            elif event.key == K_DOWN and validDirect != 1: direct = 0 # 向上 1 ,向下 0
            elif event.key == K_LEFT and validDirect != 2: direct = 3 # 向左 3, 向右 2
            elif event.key == K_RIGHT and validDirect != 3: direct = 2 
    # 0.1 画全屏的黑色背景
    screen.fill(black)
    # 1 判断是否移动
    if dt > interval: # 移动的时间间隔
        validDirect = direct
        dt = 0 # 初始化时间
        endPop = s.move(snake,direct)
    # 1.1 画蛇
    for i in snake:
        screen.blit(s.ball, i)
    # 2 画线条
    b.drawGrid(screen)
    # 3.1 分数更新
    scoret=b.scoref.render(str(score), True, (255, 255, 255)) # 实时得分
    screen.blit(scoret, (0, 0)) # 实时分数
    scoret2=b.scoref.render('best:'+str(best), True, (255, 255, 255)) # 最佳得分
    screen.blit(scoret2, (width-6*edge, 0)) # 最佳分数
    # 3.2 食物
    screen.blit(f.food, foodr) # 根据 fr(Rect 对象) 更新 food(Surface 对象) 位置 ,绘图
    # 4 判断撞击
    clli = s.strike(snake,foodr)
    if clli == 0: # 撞墙 撞自己
        going = False
    elif clli == 1: # 吃果实
        snake.append(endPop) # 长尾巴
        score += 1
        if not f.get_foodpos(foodr,snake): going = False # 生成 food 新位置, 如果占满全屏,则退出
    # 5 屏幕刷新
    pygame.display.flip() # 显示图形

The complete code and detailed instructions are quite long, so I won’t post them all here. You can download the project locally to view and run it. To get the address of the project, please reply to the keyword Snake in the programming classroom of the official account Crossin 

If students who take action on the code have any questions, they can directly discuss them in the Q&A group.

The code in this article was completed by Qingfeng Xiaozhu.

There are also two previous related articles for reference:

The Python implementation of the popular game "Snake Fight"

[Pygame Lesson 1] hello pygame (Reply to the keyword game to view this series of articles)


Crossin's second book " Operation on Code: Using Python and ChatGPT to Efficiently Get Excel Data Analysis " is now on the market.

Click here to view the introduction of the previous book "Action on Code: Learning Python Programming with Zero Basics"

c8f9919fa163fdeeb0304dca4d13e542.jpeg

This book explains the ideas, methods and practical applications of processing and analyzing data from the perspective of the combined use of Python and Excel. Whether you are a learner who wants to engage in data analysis or an office worker in other occupations, you can master the skills of Python to analyze data through the study of this book. The book innovatively introduces ChatGPT into teaching, uses ChatGPT to answer questions and provides practical training codes, and introduces some practical skills of using ChatGPT to assist learning, bringing a new way of learning to learners.

Readers and friends of the official account can contact me in the background after purchase and join the reader exchange group. Crossin will open the accompanying reading mode for you and answer all your questions when reading this book.

Thank you for retweeting and liking ~


_Previous article recommendation_

Treat data like objects


If you want to learn about paid quality courses and teaching Q&A services

Please reply in Crossin's programming classroom : 666

3c052ca3bce60d24a280959f6a4aba89.jpeg

Guess you like

Origin blog.csdn.net/qq_40523737/article/details/132242157