60 lines of Python code to achieve the greedy snake to break through and upgrade. Few people can go to the tenth level (with source code and finished products)

Posted by garyr on Mon, 22 Nov 2021 07:11:41 +0100

1, Foreword

< < click me to get the file of [can be run directly], or slide to the end of the text to get it<<

< < click me to get the file of [can be run directly], or slide to the end of the text to get it<<

2, Realization effect

Personal record

3, Environmental requirements

  1. python 3+
  2. pygame package installation command: open cmd input: pip install pygame

4, Source code and finished product sharing





1. Scan the code at the bottom of the full version of the source code, reply: greedy Snake source code, get it;
2. You can directly run the version, scan the code below, and reply: greedy Snake game to obtain;

The snake's body judgment logic and food code are as follows:

import pygame,sys,random
SCREEN,dirction_node = 600, {pygame.K_LEFT:['left',-25],pygame.K_RIGHT:['right',25],pygame.K_UP:['top',-25],pygame.K_DOWN:['top',25]}  # Screen size, definition of movement
class Snake:  # Snakes
    def __init__(self):  # Initialize various required attributes [default right / body block x5 at the beginning]
        self.dirction, self.body = pygame.K_RIGHT, []
        [self.add_node() for _ in range(5)]
    def add_node(self):
        node = pygame.Rect(((self.body[0].left, self.body[0].top) if self.body else (0, 0)) + (25, 25))  # Add snake block at any time
        setattr(node, dirction_node[self.dirction][0], getattr(node, dirction_node[self.dirction][0]) + dirction_node[self.dirction][1])
        self.body.insert(0, node)
    def is_dead(self):
        body_h = self.body[0]
        if body_h.x not in range(SCREEN) or body_h.y not in range(SCREEN) or body_h in self.body[1:]:  # If you hit a wall or yourself, you will die
            return True
    def move(self):
        self.add_node()
        self.body.pop()
    def change_direction(self, curkey):  # Change the direction, but the left, right, up and down cannot be changed in the opposite direction
        LR, UD = [pygame.K_LEFT, pygame.K_RIGHT], [pygame.K_UP, pygame.K_DOWN]
        if curkey in LR + UD:
            if not ((curkey in LR) and (self.dirction in LR) or (curkey in UD) and (self.dirction in UD)):
                self.dirction = curkey
class Food:  # Food category
    def __init__(self):
        self.rect = pygame.Rect(-25, 0, 25, 25)
    def remove(self):
        self.rect.x = -25
    def set(self):
        if self.rect.x == -25:
            allpos = [pos for pos in range(75, SCREEN - 75, 25)]  # The distance between the generated food and the wall is 75 ~ SCREEN-55
            self.rect.left, self.rect.top = random.choice(allpos), random.choice(allpos)
def show_text(screen, pos, text, color, font_size=30):
    cur_font = pygame.font.SysFont("SimHei", font_size)  # Set text style
    text_fmt = cur_font.render(text, True, color)  # Set text content
    screen.blit(text_fmt, pos)  # Draw text

5, Summary

In this way, we have gracefully lifted the veil of pygame from 0! You can use this to do something interesting

Of course, this may not be difficult. It's easy for old birds to say (don't spray).

But it is especially suitable for novices to practice. Of course, this code will expire if it can be saved for how long. So please hurry up and try! If you feel you can, please give love and praise!

Of course, this is just the beginning of my brain hole, and the fun is still behind!

Python is a high-level programming language with interpretive, object-oriented and dynamic data types.

Python was invented by Guido van Rossum at the end of 1989, and the first public release was released in 1991.

Like Perl, Python source code also follows the GPL(GNU General Public License) protocol.

It is officially announced that the update of Python 2 will be stopped on January 1, 2020.

Python 2.7 was identified as the last Python 2.x version.

Python is a high-level scripting language that combines interpretability, compilation, interactivity and object-oriented.

Python's design has strong readability. Compared with other languages, it often uses English keywords and some punctuation symbols in other languages. It has more characteristic syntax structure than other languages.

Topics: Python