Python simply implements the snake game

Article Directory###

1. Introduction to the pygame library###

PyPoice is a Python wrapper module of the SDL multimedia library. It contains Python functions and classes that allow SDL to support CDROM, audio and video output, keyboard, mouse, and joystick input.
Pygame is a game library written using the SDL library. It is a set of Python program modules used to develop game software. SDL, the full name of Simple DirectMedia Layer, is written in C, but it can also be developed in C++. Of course, there are many other languages. Pygame is a library that uses it in Python. pygame allows you to create feature-rich games and multimedia programs in Python programs. It is a highly portable module that can support multiple operating systems. It is very suitable for developing small games.

2. Installation of pygame library###

Command line pip installation, change domestic source

pip install pygame -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

3. Python code to achieve greedy snake game###

Use python's pygame third-party library and object-oriented programming methods to implement a simple snake-eating game. It can also be packaged into an exe with pyinstaller, so that you can click on it or share it with others when you want to play.

import pygame
import sys
import random
from pygame.locals import*classSnake(object):

 # Make the background and colors of the snake and fruit,0-255,0,0,0,Is for black, 255, 255, 255 for white
 def __init__(self):
  self.black = pygame.Color(0,0,0)
  self.red = pygame.Color(255,0,0)
  self.white = pygame.Color(255,255,255)

 def gameover(self):
  pygame.quit()
  sys.exit()

 def initialize(self):
  pygame.init()
  # Define the speed of snake movement
  clock = pygame.time.Clock()
  # Define a game interface
  playSurface = pygame.display.set_mode((800,600))
  # Set interface name
  pygame.display.set_caption('python greedy snake game')
  # Initialize variables
  snakePosition =[80,80]  #The starting position of the greedy snake, the first parameter is the distance in the horizontal direction, and the latter parameter is the distance in the vertical direction.
  # The length of the snake is set to three hundred squares, and the length of each square is 25
  snakebody =[[80,80],[60,80],[40,80]]
  targetPosition =[200,400]  #Initial position of the block
  targetflag =1       #Define a mark to determine whether the fruit has been eaten
  direction ='right'  #Initialize the direction of movement
  changeDirection = direction  #Change direction variable
  self.main(snakebody, targetPosition, targetflag, direction, changeDirection, snakePosition, playSurface, clock)

 def main(self, snakebody, targetPosition, targetflag, direction, changeDirection, snakePosition, playSurface, clock):while True:
   # Use loops to get all events in pygame
   for event in pygame.event.get():if event.type == QUIT:
     pygame.quit()
     sys.exit()
    # Create a keyboard event
    elif event.type == KEYDOWN:
     # Determine the direction of the keyboard
     if event.key == K_RIGHT:
      changeDirection ='right'print('To the right')if event.key == K_LEFT:
      changeDirection ='left'print("left")if event.key == K_DOWN:print('down')
      changeDirection ='down'if event.key == K_UP:print('up')
      changeDirection ='up'
     # Determine whether the esc key is pressed
     if event.key == K_ESCAPE:
      pygame.event.post(pygame.event.Event(QUIT))

   # Determine the direction of the snake
   if changeDirection =='left' and not direction =='right':
    direction = changeDirection
   if changeDirection =='right' and not direction =='left':
    direction = changeDirection
   if changeDirection =='down' and not direction =='up':
    direction = changeDirection
   if changeDirection =='up' and not direction =='down':
    direction = changeDirection
   # Move the snake head position according to the direction
   if direction =='right':
    snakePosition[0]+=20if direction =='left':
    snakePosition[0]-=20if direction =='up':
    snakePosition[1]-=20if direction =='down':
    snakePosition[1]+=20

   # Increase the length of the snake
   # Judge whether the snake has eaten the fruit
   snakebody.insert(0,list(snakePosition))if snakePosition[0]== targetPosition[0] and snakePosition[1]== targetPosition[1]:
    targetflag =0else:
    snakebody.pop()
   # Randomly generate a new square
   if targetflag ==0:
    x = random.randrange(1,40)  #horizontal direction
    y = random.randrange(1,30)  #Vertical direction
    targetPosition =[int(x *20),int(y *20)]
    targetflag =1
   # Draw a display
   playSurface.fill(self.black)  #background
   for position in snakebody:
    pygame.draw.rect(playSurface, self.white,Rect(position[0], position[1],20,20))  #Snake body
    pygame.draw.rect(playSurface, self.red,Rect(targetPosition[0], targetPosition[1],20,20))  #fruit
   # game over
   pygame.display.flip()if snakePosition[0]>900 or snakePosition[0]<0:
    snake.gameover()
   elif snakePosition[1]>800 or snakePosition[1]<0:
    snake.gameover()for i in snakebody[1:]:if snakePosition[0]== i[0] and snakePosition[1]== i[1]:
     snake.gameover()

   # Control the game speed, the larger the value, the faster the speed
   clock.tick(5)

snake =Snake()
snake.initialize()

4. pyinstaller is packaged into exe

PyInstaller is a cross-platform Python application packaging tool that supports the three mainstream platforms of Windows/Linux/MacOS. It can package Python scripts and their Python interpreters into executable files, allowing end users to install Python without the need to install Python. Execute the application.

pyinstaller installation

pip install pyinstaller -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

pyinstaller packages python program
The simplest use of PyInstaller only needs to specify the script file as the program entry. After PyInstaller executes the packaging program, the following files and directories will be created in the current directory: main.spec file, whose prefix is the same as the script name, and specifies various parameters required for packaging; build subdirectory, which stores the generated files during packaging Temporary Files. The warnxxxx.txt file records warning/error information during the generation process. If there is a problem with PyInstaller running, you need to check the warnxxxx.txt file to get the details of the error. The xref-xxxx.html file outputs the module dependency graph obtained by PyInstaller analysis script. The dist subdirectory stores the final files generated. If you use the single file mode, there will only be a single executable file; if you use the directory mode, there will be a subdirectory with the same name as the script, and within it are the real executable files and auxiliary files.

Enter the following code on the command line:

pyinstaller -F -i Icon file path.py file path

Find the exe program with the icon in the dist folder, double-click to run it, and enter the game when it runs normally, indicating that the packaging program is successful.

Recommended Posts

Python simply implements the snake game
Python implements the brick-and-mortar game
Python implements the source code of the snake game
python3 simply implements the combined design pattern
Python implements tic-tac-toe game
Python implements Tetris game
Python implements minesweeper game
Python implements guessing game
python guess the word game
Python implements WeChat airplane game
Python implements word guessing game
Python implements a guessing game
Python implements digital bomb game
Python realizes the guessing game
Python implements simple tic-tac-toe game
How Python implements the mail function
Python3 implements the singleton design pattern
Python implements the steepest descent method
Python implements the actual banking system
Python implements digital bomb game program
How Python implements the timer function
Python implements the aircraft war project
Python solves the Tower of Hanoi game
Python implements the sum of fractional sequences
Python basic actual combat-guess the age game
python implements the gradient method python the fastest descent method
Python realizes the greedy snake double battle
Python implements AI automatic version greedy snake
2.1 The Python Interpreter (python interpreter)
Python implements the shuffling of the cards in Doudizhu
Python writes the game implementation of fishing master
Use python to realize the aircraft war game
Python implements Super Mario
Realize the tank battle game with Python | Dry Post
Python implements man-machine gobang
Python, PyGame game project
Python implements image stitching
Python implements scanning tools
Consolidate the Python foundation (2)
Python implements threshold regression
Python implements minesweeper games
Python implements electronic dictionary
Realize the tank battle game with Python | Dry Post
Consolidate the foundation of Python (4)
Python implements simple tank battle
Python3 realizes airplane war game
Python implements udp chat window
Consolidate the foundation of Python(6)
Ubuntu install the latest Python 3.
Python implements parking management system
Python realizes apple eating game
Python implements TCP file transfer
The difference between Python extensions
Python numpy implements rolling case
OpenCV Python implements puzzle games
Consolidate the foundation of Python(5)
Python implements password strength verification
Python implements car management system
Python implements code block folding
Python implements panoramic image stitching
Python implements SMTP mail sending