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.
Command line pip installation, change domestic source
pip install pygame -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
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()
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