程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python game programming (pyGame)

編輯:Python

Hello everyone , I meet you again , I'm your friend, Quan Jun .

install Pygame

pip install pygame
C:\Users> pip install pygame
Collecting pygame
Downloading https://files.pythonhosted.org/packages/3e/f5/feabd88a2856ec86166a897b62bfad828bfe7a94a27cbd7ebf07fd
70399/pygame-1.9.4-cp37-cp37m-win_amd64.whl (4.2MB)
100% |██████████████████████████| 4.2MB 6.6MB/s
Installing collected packages: pygam
Successfully installed pygame-1.9.4 

Pygame Common modules

Module name

function

pygame.cdrom

Visit the CD-ROM drive

pygame.cursors

Load cursor

pygame.display

Access to display devices

pygame.draw

Draw shape 、 Lines and points

pygame.event

Manage events

pygame.font

Using fonts

pygame.image

Load and store pictures

pygame.joystick

Use game consoles or something like that

pygame.key

Read keyboard keys

pygame.mixer

voice

pygame.mouse

mouse

pygame.movie

Play the video

pygame.music

Play the audio

pygame.overlay

Visit advanced video overlay

pygame.rect

Manage rectangular areas

pygame.scrap

Local clipboard access

pygame.sndarray

Operate sound data

pygame.sprite

Operate moving image

pygame.surface

Manage images and screens

pygame.surfarray

Manage dot matrix image data

pygame.time

Manage time and frame information

pygame.transform

Zoom and move the image

A simple example :

import pygame
import sys
pygame.init() # initialization pygame
size = width, height = 320, 240 # Set window size
screen = pygame.display.set_mode(size) # Display window
while True: # Loop to make sure the window is always on
for event in pygame.event.get(): # Traverse all events
if event.type == pygame.QUIT: # If you click close window , The exit
sys.exit()
pygame.quit() # sign out pygame

Execution results :

Make a jumping ball game

Create a game window , Then create a small ball in the window . Move the ball at a certain speed , When the ball touches the edge of the game window , Ball bounce , Continue to move and follow the steps below to realize this function :

Create game window

1. Create a game window , Width and height are set to 640*480. The code is as follows :

import sys
import pygame
pygame.init() # initialization pygame
size = width, height = 640, 480 # Set window size
screen = pygame.display.set_mode() # Display window 

In the above code , First, import. pygame modular , And then call init() Method initialization pygame modular , Next , Set the width and height of the window , Finally using display Module display form .

display Common methods of modules

Method name

function

pygame.display.init()

initialization display modular

pygame.display.quit()

end display modular

pygame.display.get_init()

If display The module has been initialized , Then return to True

pygame.display.set_mode()

Initialize an interface to be displayed

pygame.display.get_surface()

Get current Surface object

pygame.display.flip()

Update the entire... To be displayed Surface Object to screen

pygame.display.update()

Update part of the content to the screen , If there are no parameters , Then with flip Function the same ( Last article )

Keep window display

2. After running the code in the first step, a black window will appear in a flash , This is because after the program is executed , It will automatically turn off . If you want to keep the window displayed , Need to use while True Keep the program running , Besides , You also need to set the close button . The specific code is as follows :

import pygame
import sys
pygame.init() # initialization pygame
size = width, height = 320, 240 # Set window size
screen = pygame.display.set_mode(size) # Display window
while True: # Loop to make sure the window is always on
for event in pygame.event.get(): # Traverse all events
if event.type == pygame.QUIT: # If you click close window , The exit
sys.exit()
pygame.quit() # sign out pygame

Polling event detection has been added to the above code .pygame.event.get() Can get the event queue , Use for...in Traversal Events , And then according to type Property to determine the event type . The event handling method here is the same as GUI similar , Such as event.type be equal to pygame.QUIT Indicates that a shutdown has been detected pygame Window events ,pygame.KEYDOWN Indicates a keyboard press event ,pygame.MOUSEBUTTONDOWN Indicates mouse down event, etc .

Load game pictures

Pictures used in the development process

3. Add a small ball in the window . Let's get one ready ball.png picture , Then load the picture , Finally, the picture is displayed in the window , The specific code is as follows :

import pygame
import sys
pygame.init() # initialization pygame
size = width, height = 640, 480 # Set window size
screen = pygame.display.set_mode(size) # Display window
color = (0, 0, 0) # Set the color
ball = pygame.image.load('ball.png') # Loading pictures
ballrect = ball.get_rect() # Gets the rectangular area
while True: # Loop to make sure the window is always on
for event in pygame.event.get(): # Traverse all events
if event.type == pygame.QUIT: # If you click close window , The exit
sys.exit()
screen.fill(color) # Fill color ( Set to 0, It's the same whether you execute this line of code or not )
screen.blit(ball, ballrect) # Draw the picture on the window
pygame.display.flip() # Update display all
pygame.quit() # sign out pygame

Use... In the above code iamge Modular load() Method load image , Return value ball It's a Surface object .Surface It is used to represent pictures pygame object , It's OK for one Surface Object to paint 、 deformation 、 Copy and other operations . in fact , The screen is just a Surface,pygame.display.set_mode() You return to a screen Surface object . If you will ball This Surface Objects draw to screen Surface object , Need to use blit() Method , Finally using display Modular flip() Method to update the entire to be displayed Surface Object to screen .

Surface Common methods of objects

Method name

function

pygame.Surface.blit()

Draw one image onto another

pygame.Surface.convert()

Convert the pixel format of the image

pygame.Surface.convert_alpha()

Convert the pixel format of the image , contain alpha Channel conversion

pygame.Surface.fill()

Fill... With color Surface

pygame.Surface.get_rect()

obtain Surface The rectangular area of

Move picture

4. Now let the ball move ,ball.get_rect() Method return value ballrect It's a Rect object , The object has one move() Method can be used to move a rectangle .move(x, y) Function has two arguments , The first parameter is X The distance the axis moves , The second parameter is Y The distance the axis moves . In the upper left corner of the window is (0, 0), If it is move(100, 50) It's moving left 100 Move down 50.

To keep the ball moving , take move() Function added to while Within the loop , The specific code is as follows :

import pygame
import sys
pygame.init() # initialization pygame
size = width, height = 640, 480 # Set window size
screen = pygame.display.set_mode(size) # Display window
color = (0, 0, 0) # Set the color
ball = pygame.image.load('ball.png') # Loading pictures
ballrect = ball.get_rect() # Gets the rectangular area
speed = [5, 5] # Set the of the move X Axis 、Y Axis
while True: # Loop to make sure the window is always on
for event in pygame.event.get(): # Traverse all events
if event.type == pygame.QUIT: # If you click close window , The exit
sys.exit()
ballrect = ballrect.move(speed) # Move the ball
screen.fill(color) # Fill color ( Set to 0, It's the same whether you execute this line of code or not )
screen.blit(ball, ballrect) # Draw the picture on the window
pygame.display.flip() # Update display all
pygame.quit() # sign out pygame

collision detection

5. Run the above code , I found that the ball flashed across the screen , here , The ball didn't really disappear , Instead, move out of the form , At this point, you need to add the collision detection function . When the ball collides with any edge of the form , Change the moving direction of the ball , The specific code is as follows :

import pygame
import sys
pygame.init() # initialization pygame
size = width, height = 640, 480 # Set window size
screen = pygame.display.set_mode(size) # Display window
color = (0, 0, 0) # Set the color
ball = pygame.image.load('ball.png') # Loading pictures
ballrect = ball.get_rect() # Gets the rectangular area
speed = [5, 5] # Set the of the move X Axis 、Y Axis
while True: # Loop to make sure the window is always on
for event in pygame.event.get(): # Traverse all events
if event.type == pygame.QUIT: # If you click close window , The exit
sys.exit()
ballrect = ballrect.move(speed) # Move the ball
# Hit the left and right edges
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
# Hit the upper and lower edges
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(color) # Fill color ( Set to 0, It's the same whether you execute this line of code or not )
screen.blit(ball, ballrect) # Draw the picture on the window
pygame.display.flip() # Update display all
pygame.quit() # sign out pygame

In the above code , Added collision detection function . If you touch the left and right edges , change X Axis data is negative , If you hit the upper and lower edges , change Y Axis data is negative .

Limit movement speed

6. Running the above code looks like a lot of balls , This is because the time to run the above code is very short , The illusion of running fast , Use pygame Of time modular , Use pygame Before the clock , Must be created first Clock An instance of an object , And then in while Set how often to run in the loop .

import pygame
import sys
pygame.init() # initialization pygame
size = width, height = 640, 480 # Set window size
screen = pygame.display.set_mode(size) # Display window
color = (0, 0, 0) # Set the color
ball = pygame.image.load('ball.png') # Loading pictures
ballrect = ball.get_rect() # Gets the rectangular area
speed = [5, 5] # Set the of the move X Axis 、Y Axis
clock = pygame.time.Clock() # Set the clock
while True: # Loop to make sure the window is always on
clock.tick(60) # To perform a second 60 Time
for event in pygame.event.get(): # Traverse all events
if event.type == pygame.QUIT: # If you click close window , The exit
sys.exit()
ballrect = ballrect.move(speed) # Move the ball
# Hit the left and right edges
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
# Hit the upper and lower edges
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(color) # Fill color ( Set to 0, It's the same whether you execute this line of code or not )
screen.blit(ball, ballrect) # Draw the picture on the window
pygame.display.flip() # Update display all
pygame.quit() # sign out pygame

Development Flappy Bird game

Flappy Bird Is a bird flying game , One finger controls and presses the bird to fly up .

analysis stay Flappy Bird In the game , There are two main objects : Little bird 、 The Conduit . You can create Brid Classes and Pineline Class to represent the two objects respectively . Birds can avoid the pipe by moving up and down , So in Brid class bridUpdate() Method , Realize the up and down movement of birds , In order to reflect the characteristics of the bird flying forward , You can move the pipe all the way to the left , It's like a bird flying forward in the window . So in Pineline Class updatePipeline() Method , Move the pipe to the left . Also created 3 A function :createMap() Function to draw a map ;checkDead() Function is used to judge the life state of a bird ;getResult() Function to get the final score . Finally, instantiate and call related methods in the main logic , Realize corresponding functions .

Build the main frame

# -*- coding:utf-8 -*-
import sys # Import sys modular
import pygame # Import pygame modular
import random
class Bird(object):
""" Define a bird """
def __init__(self):
""" Define initialization method """
pass
def birdUpdate(self):
pass
class Pipeline(object):
""" Define a pipe class """
def __init__(self):
""" Define initialization method """
def updatePipeline(self):
""" Move horizontally """
def createMap():
""" Define how to create a map """
screen.fill((255, 255, 255)) # Fill color (screen It hasn't been defined yet. Don't worry )
screen.blit(background, (0, 0)) # Fill in the background
pygame.display.update() # Update display
if __name__ == '__main__':
pygame.init() # initialization pygame
size = width, height = 400, 650 # Set window size
screen = pygame.display.set_mode(size) # Display window
clock = pygame.time.Clock() # Set the clock
Pipeline = Pipeline() # Instantiate the pipe class
while True:
clock.tick(60) # To perform a second 60 Time
# Polling Events
for event in pygame.event.get():
if event.type == pygame.QUIT: # If an event is detected, close the window
sys.exit()
background = pygame.image.load("assets/background.png") # Load background image
createMap()
pygame.quit() # sign out 

Execution results :

Pictures used in the development process

Create a bird class 、 Create a pipe class 、 Calculate the score 、 collision detection

import pygame
import sys
import random
class Bird(object):
""" Define a bird """
def __init__(self):
""" Define initialization method """
self.birdRect = pygame.Rect(65, 50, 50, 50) # Bird rectangle
# Define the of birds 3 A list of States
self.birdStatus = [pygame.image.load("assets/1.png"),
pygame.image.load("assets/2.png"),
pygame.image.load("assets/dead.png")]
self.status = 0 # Default flight status
self.birdX = 120 # Where the birds are X Axis coordinates , That is, the speed of flying to the right
self.birdY = 350 # Where the birds are Y Axis coordinates , That is, up and down flight altitude
self.jump = False # By default, the bird will land automatically
self.jumpSpeed = 10 # Jump height
self.gravity = 5 # gravity
self.dead = False # The default bird life state is alive
def birdUpdate(self):
if self.jump:
# Bird Jump
self.jumpSpeed -= 1 # Velocity decline , Rising more and more slowly
self.birdY -= self.jumpSpeed # bird Y Axis coordinates decrease , The bird rises
else:
# Birds fall
self.gravity += 0.2 # Increasing gravity , Falling faster and faster
self.birdY += self.gravity # bird Y Axis coordinates increase , The bird falls
self.birdRect[1] = self.birdY # change Y Axis position
class Pipeline(object):
""" Define a pipe class """
def __init__(self):
""" Define initialization method """
self.wallx = 400 # Where the pipeline is located X Axis coordinates
self.pineUp = pygame.image.load("assets/top.png")
self.pineDown = pygame.image.load("assets/bottom.png")
def updatePipeline(self):
"""" Pipeline movement method """
self.wallx -= 5 # The Conduit X Axis coordinates decrease , That is, the pipe moves to the left
# When the pipeline runs to a certain position , That is, the bird flies over the pipe , Score plus 1, And reset the pipeline
if self.wallx < -80:
global score
score += 1
self.wallx = 400
def createMap():
""" Define how to create a map """
screen.fill((255, 255, 255)) # Fill color
screen.blit(background, (0, 0)) # Fill in the background
# Show pipe
screen.blit(Pipeline.pineUp, (Pipeline.wallx, -300)) # Upper pipe coordinate position
screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500)) # Lower pipe coordinate position
Pipeline.updatePipeline() # Pipeline movement
# Show birds
if Bird.dead: # Pipe impact status
Bird.status = 2
elif Bird.jump: # Takeoff status
Bird.status = 1
screen.blit(Bird.birdStatus[Bird.status], (Bird.birdX, Bird.birdY)) # Set the coordinates of the bird
Bird.birdUpdate() # Bird movement
# Show scores
screen.blit(font.render('Score:' + str(score), -1, (255, 255, 255)), (100, 50)) # Set the color and coordinate position
pygame.display.update() # Update display
def checkDead():
# Rectangular position of the upper tube
upRect = pygame.Rect(Pipeline.wallx, -300,
Pipeline.pineUp.get_width() - 10,
Pipeline.pineUp.get_height())
# Rectangular position of the lower tube
downRect = pygame.Rect(Pipeline.wallx, 500,
Pipeline.pineDown.get_width() - 10,
Pipeline.pineDown.get_height())
# Check whether the bird collides with the upper and lower pipes
if upRect.colliderect(Bird.birdRect) or downRect.colliderect(Bird.birdRect):
Bird.dead = True
# Check whether the bird flies out of the upper and lower boundaries
if not 0 < Bird.birdRect[1] < height:
Bird.dead = True
return True
else:
return False
def getResutl():
final_text1 = "Game Over"
final_text2 = "Your final score is: " + str(score)
ft1_font = pygame.font.SysFont("Arial", 70) # Set the font of the first line of text
ft1_surf = font.render(final_text1, 1, (242, 3, 36)) # Set the color of the first line of text
ft2_font = pygame.font.SysFont("Arial", 50) # Set the font of the second line of text
ft2_surf = font.render(final_text2, 1, (253, 177, 6)) # Set the color of the second line of text
screen.blit(ft1_surf, [screen.get_width() / 2 - ft1_surf.get_width() / 2, 100]) # Set the display position of the first line of text
screen.blit(ft2_surf, [screen.get_width() / 2 - ft2_surf.get_width() / 2, 200]) # Set the display position of the second line of text
pygame.display.flip() # Update the entire... To be displayed Surface Object to screen
if __name__ == '__main__':
""" The main program """
pygame.init() # initialization pygame
pygame.font.init() # Initialize font
font = pygame.font.SysFont("Arial", 50) # Set font and size
size = width, height = 400, 650 # Settings window
screen = pygame.display.set_mode(size) # Display window
clock = pygame.time.Clock() # Set the clock
Pipeline = Pipeline() # Instantiate the pipe class
Bird = Bird() # Instantiate birds
score = 0
while True:
clock.tick(60) # To perform a second 60 Time
# Polling Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not Bird.dead:
Bird.jump = True # jumping
Bird.gravity = 5 # gravity
Bird.jumpSpeed = 10 # Jump speed
background = pygame.image.load("assets/background.png") # Load background image
if checkDead(): # Check the life state of the bird
getResutl() # If the bird dies , Display the total score of the game
else:
createMap() # Create map
pygame.quit()

Execution results :

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/151683.html Link to the original text :https://javaforall.cn


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved