Using Python to make age-old games, 5 minutes to achieve snake!


The text and pictures of this article are from the Internet, only for learning and communication, and do not have any commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time

This article is from Tencent cloud by Python sophomore
As a classic little game, snake came out as early as 1976. I first came into contact with it in my parents’ Nokia mobile phone.
Although the history of the snake is relatively long, but it has a very tenacious vitality, keep enduring, one of the important reasons is that the game manufacturers continue to update and iterate. Now, this game has become very rich in game scenes and rules.

Next, let’s take a look at how to simply implement this small game through python.


  • There should be the main interface of the game, snake and food;
  • It can control the snake to move and get food;
  • After eating the food, the snake increases its length and score, and the food disappears and randomly generates new food;
  • The game ends when the snake touches the surrounding boundary or its own body.

Environmental Science

  • Operating system: Windows
  • Python version: 3.6
  • Modules involved: sys, random, pyGame


First, install the third-party library pyGame and use pip to install pyGame.

The main interface of the game

SCREEN_X = 500
SCREEN_Y = 500
screen_size = (SCREEN_X, SCREEN_Y)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_ Capture ('snake eating ')


A snake eater


def __init__(self):
    self.dirction = pygame.K_RIGHT
    self.body = []



def addNode(self):
    left, top = (0, 0)
    if self.body:
        left, top = (self.body[0].left, self.body[0].top)
    node = pygame.Rect(left, top, 20, 20)
    if self.dirction == pygame.K_LEFT:
        node.left -= 20
    elif self.dirction == pygame.K_RIGHT:
        node.left += 20
    elif self.dirction == pygame.K_UP: -= 20
    elif self.dirction == pygame.K_DOWN: += 20
    self.body.insert(0, node)

def delNode(self):


Change direction

def changeDirection(self, curkey):
    LR = [pygame.K_LEFT, pygame.K_RIGHT]
    UD = [pygame.K_UP, pygame.K_DOWN]
    if curkey in LR + UD:
        if (curkey in LR) and (self.dirction in LR):
        if (curkey in UD) and (self.dirction in UD):
        self.dirction = curkey


Death judgment

def isDead(self):
    #Hit the wall
    if self.body[0].x not in range(SCREEN_X):
        return True
    if self.body[0].y not in range(SCREEN_Y):
        return True
    #Hit yourself
    if self.body[0] in self.body[1:]:
        return True
    return False



Put food in

def set(self):
    if self.rect.x == -20:
        allpos = []
        for pos in range(20, SCREEN_X - 20, 20):
        self.rect.left = random.choice(allpos) = random.choice(allpos)


Eat the food

def remove(self):
    self.rect.x = -20


≠ text display

Display method

def show_text(screen, pos, text, color, font_bold=False, font_size=30, font_italic=False):
    #Set text size
    cur_ font =  pygame.font.SysFont (song style, font)_ size)
    #Set content
    text_fmt = cur_font.render(text, 1, color)
    #Draw text
    screen.blit(text_fmt, pos)


Show score

show_text(screen, (50, 400), 'scores: ' + str(scores), (103, 213, 213))


Display death alert

show_text(screen, (150, 50), 'GAME OVER', (227, 29, 18), False, 50)
show_text(screen, (140, 100), "Press space to try again", (0, 0, 22), False, 30)


Get food

When the greedy snake eats the food and increases the length and score of the snake, the food disappears and is put in again.

if food.rect == snake.body[0]:
    scores += 1

#Put food in


The final effect



Package with pyinstall,

Recommended Today

Practice analysis of rust built-in trait: partialeq and EQ

Abstract:Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. This article is shared from Huawei cloud community《Analysis of rust built-in trait: partialeq and EQ》Author: debugzhang Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. Some traits can be automatically […]