Write a simple Snake game in python

I don't know how many students are like me. Their initial motivation for programming is to make a game for themselves?

Although Python is not a "game oriented" language, it also has its own game engine. pygame is the most commonly used. In addition, there is a well-known game engine, cocos2d. Its original version was based on python, cocos2d python. We have had cases of these two engines, and pygame has done a more detailed introductory tutorial - the little game "hit the plane". See the link at the end of the article.

Today, I want to share with you a little game called "greedy snake" written by pygame:

The little game "greedy snake" is a frequent visitor in programming learning because:

1. simple. The most basic game elements only need snakes and food. (there are still three elements needed to fight a plane. What are they respectively?) Direction, as long as four fixed directions are up, down, left, right.

2. there are basic data structures and object-oriented ideas in it. Game development itself will use many object-oriented concepts, and the snake's body is a natural "linked list" structure, which is very suitable for practicing data structure.

Another interesting point is that the word Python means Python in English. Greedy snake can be regarded as a "game of the same name".

In many schools, the homework of the program development course will have the topic of greedy snake, and students often ask us about our relevant code. (Nokia phones also have a passion for this game.) Before that, I had made a Python version of snake wars, which was developed based on cocos2d Python. But that's a little complicated for beginners. This is a simple version more suitable for beginners developed by our teaching assistant @ Qingfeng Xiaozhu.

For the detailed description of the whole development process and code, we have written them in the document and uploaded github together. Students who need it can download the exercise by themselves, try to change the speed and color of the snake, add more food, etc. (for the address, please reply to the keyword snake in the programming classroom of official account crossing)

Here is a brief introduction:

This code is developed based on pygame, so please ensure that pygame has been successfully installed in your Python before running. Then run mysnake Py to start the game.

In addition to the final code, we also specially decomposed several py files in the process for the students who want to develop their own reference.

Development ideas

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

The main tasks in the main cycle of the game are as follows:

  1. Get keyboard events
  2. Draw background
  3. Update snake location
  4. Draw snakes and food
  5. collision detection
  6. screen refresh

Snake and food are drawn through the Surface object in pygame to draw grids of different colors.

The snake's body uses Rect object and is saved through list.

Snake movement is the core operation of the game. We do not choose to modify the position of the snake. Instead, each time we move, we add a head node according to the direction of the snake, move a node forward in other positions, and delete the tail node. This is tantamount to realizing the movement of the snake. If you eat food, add nodes at the tail to achieve growth.

To do collision detection in the game, use pygame's colliderect. We have to judge: 1 Did you hit the wall? 2. did you hit yourself? 3. did you hit the food? And then do different treatments

The core code of the game main loop:


while going:
    lastt = clock.tick(60) # Frame rate 60
    dt += lastt # Cumulative time
    c += 1
    # 0 keyboard press and other event responses
    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 # Press up 1 and the current direction is not down 0, then up
            elif event.key == K_DOWN and validDirect != 1: direct = 0 # Up 1, down 0
            elif event.key == K_LEFT and validDirect != 2: direct = 3 # Left 3, right 2
            elif event.key == K_RIGHT and validDirect != 3: direct = 2 
    # 0.1 draw a full screen black background
    screen.fill(black)
    # 1 judge whether to move
    if dt > interval: # Move interval
        validDirect = direct
        dt = 0 # Initialization time
        endPop = s.move(snake,direct)
    # 1.1 draw a snake
    for i in snake:
        screen.blit(s.ball, i)
    # 2 draw lines
    b.drawGrid(screen)
    # 3.1 score update
    scoret=b.scoref.render(str(score), True, (255, 255, 255)) # Real time score
    screen.blit(scoret, (0, 0)) # Real time score
    scoret2=b.scoref.render('best:'+str(best), True, (255, 255, 255)) # Best score
    screen.blit(scoret2, (width-6*edge, 0)) # Best score
    # 3.2 food
    screen.blit(f.food, foodr) # Update the position of food(Surface object) according to fr(Rect object), and draw
    # 4 judge impact
    clli = s.strike(snake,foodr)
    if clli == 0: # Hit the wall and hit yourself
        going = False
    elif clli == 1: # Eat fruit
        snake.append(endPop) # grow a tail
        score += 1
        if not f.get_foodpos(foodr,snake): going = False # Generate a new food location. If the full screen is occupied, exit
    # 5 screen refresh
    pygame.display.flip() # display graphics

The complete code and detailed description are relatively long, so they are not all posted here. You can download the project to the local site and view and run it. To obtain the project address, please reply to the keyword greedy snake in the programming classroom of official account crossing

The code in the text is completed by Qingfeng Xiaozhu. If the students who act on the code have any questions, they can directly find him in the Q & a group for discussion.

There are also two previous related articles for reference:

Crossin g: Python implementation of the popular game "snake wars"

Programming classroom at Crossin - PyGame

------

Learn together and go far!

Welcome to Crossin's programming classroom

Tags: Python

Posted by deadonarrival on Tue, 31 May 2022 07:17:22 +0530