当前位置:网站首页>Get started with pyGame
Get started with pyGame
2022-07-18 02:40:00 【Steal the mask and run away】
Recent learning pygame I've got the module , Because the official documents are in English , Translation reading is not very friendly , So I found a lot of them on the Internet pygame Knowledge sharing of modules , A brief summary is here , I hope it will be helpful to the little partners who study together .
(1) WeChat official account : Na translation station ( There are more detailed pygame The tutorial is accompanied by relevant practical exercises )
(2) WeChat official account : Data help Club( Brief content )
(3) Personal blog site :https://www.xin3721.com/python3/( This article is from this author , It is also the best one for me to understand briefly , As sharing )
(4) Official documents :https://www.pygame.org/docs/
The goal is
- Project preparation
- Use
pygameCreate a graphics window - understand Images And realize image rendering
- understand Game cycle and Game clock
- understand spirit and Spirit group
Project preparation
- newly build Aircraft battle project
- Create a new one
hm_01_pygame introduction .py - Import Game material pictures
The first impression of the game
- Some of the A still image Drawn to the Game window in
- according to User interaction Or other circumstances , Move These images , Produce animation
- according to Between images Whether there is overlap , Judge Whether the enemy plane has been destroyed Other information
01. Use pygame Create a graphics window
Subsection objectives
- Game initialization and exit
- Understand the coordinate system in the game
- Create the main game window
- Simple game loop
The picture material can be draw To The window of the game On , Before developing a game, you need to know How to create a game window !
1.1 Game initialization and exit
- To use
pygameBefore all the functions provided , Need to callinitMethod - Before the end of the game, you need to call
quitMethod
| Method | explain |
|---|---|
pygame.init() | Import and initialize all pygame modular , Before using other modules , Must call first init Method |
pygame.quit() | Uninstall all pygame modular , Call before the game ends ! |

import pygame
pygame.init()
# Game code ...
pygame.quit()
1.2 Understand the coordinate system in the game
- Coordinate system
- origin stay top left corner
(0, 0) - x Axis Horizontally to Right , Gradually increase
- y Axis In a vertical direction Next , Gradually increase
- origin stay top left corner

In the game , All visible elements are represented by Rectangular area to describe the location
- To describe a rectangular area, there are four elements :
(x, y) (width, height)
- To describe a rectangular area, there are four elements :
pygameA special class is providedpygame.RectUsed to describe Rectangular area
Rect(x, y, width, height) -> Rect

Tips
pygame.RectIt's a special class , It just encapsulates some digital calculations- Don't execute
pygame.init()Methods can also be used directly
Case drills
demand
- Definition
hero_rectRectangular description The position and size of the hero - Output heroic Coordinate origin (
xandy) - Output heroic Size ( Width and Height )
hero_rect = pygame.Rect(100, 500, 120, 126)
print(" Coordinate origin %d %d" % (hero_rect.x, hero_rect.y))
print(" Hero size %d %d" % (hero_rect.width, hero_rect.height))
# size Property will return the rectangle ( wide , high ) Tuples
print(" Hero size %d %d" % hero_rect.size)
1.3 Create the main game window
pygameThere is a special modularpygame.displayUsed to create 、 management Game window
| Method | explain |
|---|---|
pygame.display.set_mode() | Initialize the game display window |
pygame.display.update() | Refresh the screen content display , Use later |
set_mode Method
set_mode(resolution=(0,0), flags=0, depth=0) -> Surface
- effect —— Create a game display window
- Parameters
resolutionSpecifies the of the screenwideandhigh, The window size created by default is consistent with the screen sizeflagsParameter specifies additional options for the screen , For example, whether the screen is full or not , By default, there is no need to passdepthThe parameter represents the number of bits of the color , Default auto match
- Return value
- temporary It can be understood as The screen of the game , Elements of the game All need to be drawn to The screen of the game On
- Be careful : Variable records must be used
set_modemethod ! because : All subsequent image rendering is based on this return result
# Create the main game window
screen = pygame.display.set_mode((480, 700))
1.4 Simple game loop
In order to make the game program start , No immediate exit , Usually add a... In the game program Game cycle
So-called Game cycle It's just one. Infinite loop
stay Create game window code below , Add an infinite loop
- Be careful : The game window does not need to be created repeatedly
# Create the main game window
screen = pygame.display.set_mode((480, 700))
# Game cycle
while True:
pass
02. understand Images And realize image rendering
In the game , Can see Game elements Most of them are Images
- image file Initially saved on disk , If needed , First step Need Is loaded into memory
On the screen See the content of an image , There are three steps to follow :
- Use
pygame.image.load()Load image data - Use Game screen object , call
blitMethod Draw the image to the specified position - call
pygame.display.update()Method to update the display of the entire screen
- Use

Tips : To see the results drawn on the screen , You have to call
pygame.display.update()Method
Code walkthrough I —— Draw the background image
demand
- load
background.pngCreate a background - take background Drawn on the screen
(0, 0)Location - Call the screen update to display the background image
# Draw the background image
# 1> Load image
bg = pygame.image.load("./images/background.png")
# 2> Draw on the screen
screen.blit(bg, (0, 0))
# 3> Update display
pygame.display.update()
Code walkthrough II —— Draw a hero image
demand
- load
me1.pngCreate a hero plane - take Hero plane Drawn on the screen
(200, 500)Location - Call the screen update to display the aircraft image
# 1> Load image
hero = pygame.image.load("./images/me1.png")
# 2> Draw on the screen
screen.blit(hero, (200, 500))
# 3> Update display
pygame.display.update()
Transparent image
pngThe format of the image is supported transparent Of- When drawing an image , Transparent areas Nothing will be shown
- But if There is already content below , Meeting through Transparent areas Show it
understand update() The role of methods
Can be in
screenObject complete allblitAfter method , Unified call oncedisplay.updateMethod , It can also be on the screen See the final drawing result
Use
display.set_mode()CreatedscreenObject is a Screen data object in memory- It can be understood as Oil Painting Of canvas
screen.blitMethod can draw a lot on the canvas Images- for example : hero 、 Enemy planes flying in and out 、 The bullet …
- These images There may be Will each other Overlap or overlay
display.update()Will canvas Of final result Draw on the screen , This can Improve screen rendering efficiency , Increase the fluency of the game
Case adjustment
# Draw the background image
# 1> Load image
bg = pygame.image.load("./images/background.png")
# 2> Draw on the screen
screen.blit(bg, (0, 0))
# Draw a hero image
# 1> Load image
hero = pygame.image.load("./images/me1.png")
# 2> Draw on the screen
screen.blit(hero, (200, 500))
# 3> Update display - update Method will put all the results drawn before , Update to the screen window at one time
pygame.display.update()
03. understand Game cycle and Game clock
Now? Hero plane It has been drawn on the screen , How can we make the plane move ?
3.1 The principle of animation in the game
Follow The movie The principle is similar , Animation effects in the game , Essentially, Fast Draw on the screen Images
- The movie will be multiple Still film continuity 、 Fast Playback of , Produce a coherent visual effect !
Usually on the computer Draw per second 60 Time , Can achieve very continuity The high quality Animation effect of
- The result of each plot is called frame Frame


3.2 Game cycle
The two components of the game
The beginning of the game cycle Means The official start of the game

Role of game cycle
Make sure the game Will not exit directly
Change image position —— Animation effect
- every other
1 / 60 secondMove the position of all the images - call
pygame.display.update()Update screen display
- every other
Detect user interaction —— Key 、 Mouse, etc. …
3.3 Game clock
pygameA special class is providedpygame.time.ClockIt is very convenient to set the screen drawing speed —— Refresh frame rateTo use Clock object Two steps are needed. :
- 1) stay Game initialization Create a Clock object
- 2) stay Game cycle Let the clock object call
tick( Frame rate )Method
tickThe method will be based on Last called time , Automatic setting Game cycle Delay in
# 3. Create a game clock object
clock = pygame.time.Clock()
i = 0
# Game cycle
while True:
# Set the screen refresh frame rate
clock.tick(60)
print(i)
i += 1
3.4 Simple animation of Heroes
demand
- stay Game initialization Define a
pygame.RectThe variable records the hero's initial position - stay Game cycle Every time hero Of
y - 1—— Move up y <= 0Move the hero to the bottom of the screen
Tips :
- Every time you call
update()Before method , Need to put All the game images are redrawn- And it should The first Redraw background image
# 4. Define the hero's initial position
hero_rect = pygame.Rect(150, 500, 102, 126)
while True:
# You can specify the frequency of code execution inside the loop body
clock.tick(60)
# Update hero location
hero_rect.y -= 1
# If you move out of the screen , Move the top of the hero to the bottom of the screen
if hero_rect.y <= 0:
hero_rect.y = 700
# Draw a background picture
screen.blit(bg, (0, 0))
# Draw a hero image
screen.blit(hero, hero_rect)
# Update display
pygame.display.update()
Homework
- Heroes fly up , When After the hero completely flies out of the screen from above
- Move the plane to the bottom of the screen
if hero_rect.y + hero_rect.height <= 0:
hero_rect.y = 700
Tips
RectProperties ofbottom = y + height
if hero_rect.bottom <= 0:
hero_rect.y = 700
3.5 In the game cycle monitor event
event event
- After the game starts , What the user does for the game
- for example : Click the close button , The click of a mouse , Press the keyboard …
monitor
- stay Game cycle in , Judge users Specific operation
Only Capture To the user's specific operation , In order to make a targeted response
Code implementation
pygamePass throughpygame.event.get()You can get What the user is currently doing Of List of events- Users can do many things at the same time
Tips : This code is very fixed , Almost all
pygameGame capital Be the same in essentials while differing in minor points !
# Game cycle
while True:
# Set the screen refresh frame rate
clock.tick(60)
# Event monitoring
for event in pygame.event.get():
# Judge whether the user has clicked the close button
if event.type == pygame.QUIT:
print(" Quit the game ...")
pygame.quit()
# Just exit the system
exit()
04. understand spirit and Spirit group
4.1 spirit and Spirit group
In the case just completed , Image loading 、 Position change 、 The plot Programmers need to write code to deal with
To simplify development steps ,
pygame Two classes are provided :
pygame.sprite.Sprite—— Storage Image data image and Location rect Of objectpygame.sprite.Group

spirit
In game development , Usually put The object that displays the image It's called spirit
Spritespirit There are two important attributes
imageThe image to displayrectThe image should be displayed on the screen
default
update()Method did nothing- Subclasses can override this method , Every time the screen is refreshed , Update wizard location
Be careful :
pygame.sprite.SpriteIt didn't provideimageandrectTwo attributes- Need programmers from
pygame.sprite.SpriteParturient - And in Subclass Of Initialization method in , Set up
imageandrectattribute
- Need programmers from
Spirit group
One Spirit group It can contain more than one spirit object
Call the
update()Method- Sure Automatically call Every elf in the Group Of
update()Method
- Sure Automatically call Every elf in the Group Of
Call the
draw( Screen objects )Method- Can be Every elf in the Group Of
imageDraw onrectLocation
- Can be Every elf in the Group Of
Group(*sprites) -> Group
Be careful : You still need to call
pygame.display.update()To see the final result on the screen
4.2 Derived sprite subclass
- newly build
plane_sprites.pyfile - Definition
GameSpriteInherited frompygame.sprite.Sprite
Be careful
- If the Parent class No
object - In rewriting Initialization method when , must do First
super()Click the parent class__init__Method - Ensure the implementation of... In the parent class
__init__The code can be executed normally

attribute
imageSprite image , Useimage_nameloadrectSprite size , The default image size isspeedSpirit movement speed , The default is1
Method
updateCall... Within the game loop each time the screen is updated- Let the elves
self.rect.y += self.speed
- Let the elves
Tips
imageOfget_rect()Method , Can return pygame.Rect(0, 0, Image width , High image ) The object of
import pygame
class GameSprite(pygame.sprite.Sprite):
""" Game wizard base class """
def __init__(self, image_name, speed=1):
# Call the initialization method of the parent class
super().__init__()
# Load image
self.image = pygame.image.load(image_name)
# Set dimensions
self.rect = self.image.get_rect()
# Record speed
self.speed = speed
def update(self, *args):
# Move vertically by default
self.rect.y += self.speed
4.3 Use Game Genie and Spirit group Create enemy aircraft
demand
- Use the just derived Game Genie and Spirit group establish Enemy planes flying in and out And realize enemy aircraft animation
step
Use
fromImportplane_spritesmodularfromThe imported module can Use it directlyimportThe imported module needs to pass Module name . To use
stay Game initialization establish Sprite objects and Sprite group objects
stay In the game cycle Give Way Spirit group Respectively called
update()anddraw(screen)Method
duty
- spirit
- encapsulation Images image、 Location rect and Speed speed
- Provide
update()Method , According to the needs of the game , Update location rect
- Spirit group
- contain Multiple Sprite objects
updateMethod , Let all sprites in the sprite group callupdateMethod to update the locationdraw(screen)Method , stayscreenDraw all the sprites in the sprite group on
Implementation steps
- Import
plane_spritesmodular
from plane_sprites import *
- Modify the initialization code
# Create enemy spirit and spirit group
enemy1 = GameSprite("./images/enemy1.png")
enemy2 = GameSprite("./images/enemy1.png", 2)
enemy2.rect.x = 200
enemy_group = pygame.sprite.Group(enemy1, enemy2)
- Modify the code of the game cycle
# Let the enemy crew call update and draw Method
enemy_group.update()
enemy_group.draw(screen)
# Update screen display
pygame.display.update()
边栏推荐
- 实现意识的远程直接电磁通信,东大团队联合新加坡国大等构建电磁脑机超表面,有望成为全新通信范式
- Custom paging and labeling encapsulation
- 缓存雪崩、缓存击穿、缓存穿透
- Fragment(四)常见问题
- Use iceberg in CDP to pressurize the data Lake warehouse
- 云呐-动环监控水浸绳,非定位水浸监测绳
- 1、OLED简单驱动
- Unemployed after graduation?
- Golang problem summary
- [design topics] project summary of graduation project based on STM32 - 350 cases
猜你喜欢

Kotlin Sealed 是什么?为什么 Google 都用

【综合笔试题】难度 2/5,递归运用及前缀和优化

云呐-动环监控水浸绳,非定位水浸监测绳

Landing DDD (7) - some misunderstandings in tactical design

竟然如此简单,DataBinding 和 ViewBinding
![[comprehensive pen test] difficulty 2/5, recursive application, prefix and optimization](/img/eb/fad095522129d13be7675a50e77af7.png)
[comprehensive pen test] difficulty 2/5, recursive application, prefix and optimization

Google recommends using sealed and remotemediator in projects

神奇宝贝 眼前一亮的 Jetpack + MVVM 极简实战

Redis uses pipeline

03 key control LED
随机推荐
Yunna computer room dynamic environment monitoring expansion scheme
Dragon lizard community recruitment Promotion Ambassador & experience officer| Everyone can participate in open source
2022-04-21 unity foundation 2 - important content of monobehavior
[design topics] project summary of graduation project based on STM32 - 350 cases
MQTT---Connect
1、OLED简单驱动
二分查找(下)
three. JS infinite running VR games
MySQL的隔离级别
2022-04-18 C Part 4 - Advanced
2022-04-18 introduction to unity 2 - how unity works
Fragment(三)ViewPager中使用Fragment
阿里云物联网平台搭建
558. Intersection Quadtree: simple question récursive
2022-04-21 unity foundation 1 - 3D mathematics
【福利活动】给你的代码叠个 Buff!点击“茶”收好礼
箭头函数与箭头函数的区别
如何在项目中封装 Kotlin + Android Databinding
Google 推荐在项目中使用 sealed 和 RemoteMediator
04 exit interrupt detection key