当前位置:网站首页>Shooting lesson 1-01: Introduction
Shooting lesson 1-01: Introduction
2022-07-23 13:16:00 【acktomas】
Shooting The first 1-1 course : introduction
This is our tutorial series “ Use Pygame Develop games ” Of the 1 part . It is suitable for game development and improvement Python Beginners interested in coding skills / Intermediate programmer .
What is? Pygame?
Pygame It's a “ Game library ” - A set of tools to help programmers make games . Some of them are :
- Graphics and animation
- voice ( Including music )
- control ( keyboard 、 mouse 、 Game controller, etc )
Game cycle
The core of every game is a cycle , We call it “ Game cycle ”. This cycle keeps running , Over and over again , Do all the things that make the game work . Every time the game goes through this cycle , Called frame .
Every frame , A lot of different things can happen , But they can be organized into three different categories :
1. Process input ( Or event )
Anything the game needs to respond to . These may be keyboard keys , Mouse movement, etc .
2. Update game
Change anything that needs to be changed on the framework . If a character is in the air , Gravity needs to pull it down . If two objects collide with each other , They need to explode .
3. Rendering ( Or draw )
In this step , We will draw everything on the screen . background 、 role 、 Menus or any other content that players need to view must be drawn in the correct position on the screen .
The clock
Another important aspect of the cycle is to control the running speed of the whole cycle . You may have heard of the term FPS, It represents frames per second . This means how many times per second this cycle should occur . It's important , Because you don't want the game to run too fast or too slow . You don't want it to run at different speeds on different computers .
structure Pygame Templates
Now we know what it takes to make the game work , We can start writing some code . First , We will make a simple pygame Program , In addition to opening a window and running the game loop , Don't do anything? . For anything you want to make pygame For projects , This will be a good starting point .
At the top of the program , We will import the required libraries , And set some variables for game options :
# Pygame Templates - Game framework
import pygame
import random
WIDTH = 360 # Game window width
HEIGHT = 480 # Game window height
FPS = 30 # Frames per second
Next we need to open the game window :
# initialization pygame, create a window
pygame.init()
pygame.mixer.init() # for sound
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
pygame.init() It's startup pygame and “ initialization ”. Will create a game screen . Last , We have created a system that can ensure that the game is what we want FPS Running screen clock
Next is the game cycle :
# Game cycle
running = True
while running:
# Process input (events)
# Update
# Render (draw)
This is our game cycle , It is a loop controlled by variables . If we want the game to end , Just set up running = False It will end the cycle . Now we can fill each part with some basic code .``
Rendering / The drawing part
We will start from *“ draw *” Part of it . We don't have any code yet , But we can fill the screen with solid colors . So , We need to discuss how computers deal with colors .
The computer screen is made up of pixels , These pixels have 3 Parts of : Red 、 Green and blue . The degree to which each part is lit determines the color of the pixel , As shown below :

Each of the three primary colors can have a color between 0( close ) and 255(100% open ) Between the value of the , Therefore, each of the three primary colors has 256 There are two different possibilities . Here are some examples of some colors you can make :

You can find the total number of colors that the computer can display by multiplication :
>>> 256 * 256 * 256 = 16,777,216
Now we have learned about color , Let's define some at the top of the program :
# Colors (R, G, B)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
Then we can fill the screen with black .
# draw 、 Rendering
screen.fill(BLACK)
For the working mode of computer display , It is not enough . Changing the pixels on the screen means having the graphics card tell the monitor to change the actual pixels . In terms of computers , It's a very, very slow process . therefore , If you want to draw a lot of things on the screen , It may take a long time to draw them all . We can call it Double buffering Something that solves this problem in a smart way . It sounds fancy , But it actually just means :
Imagine , We have a double-sided whiteboard , You can flip to show one side or the other . The front will be the display ( The screen the player sees ), And the back is hidden , Only computers can “ notice ” it . Each frame , All our paintings are on the back . then , When we're done , We flip the board over and show the new frame . This means that we only do a slow process , Talk to the monitor every frame once , Instead of doing everything on the screen .
All this is in pygame It happens automatically in . You just need to tell it to flip the whiteboard when you finish drawing . actually , The command is even named :flip()
# draw 、 Rendering
screen.fill(BLACK)
# Flip the display after drawing everything
pygame.display.flip()
If you try to draw something after flipping , They will not appear on the screen !flip()
Input / Event part
We haven't played yet , So we can't accurately say the keyboard or mouse buttons or other control events we want to monitor .
If you try to run the program now , You will find yourself having problems : Unable to close window ! Click “X” It doesn't work . That's because this is an event , We need to tell our program to listen for this event and let it exit the game .
Events can happen at any time . If the player clicks “ Jump ” Button , What should I do ? Don't ignore this input , Players will feel frustrated . therefore ,Pygame All you do is save all the events that have occurred since the last frame . such , Even players quickly smash many keys , You can also record all these buttons . All events are stored in a list , So we run a loop to see all the events :for
for event in pygame.event.get():
# Check the screen close event
if event.type == pygame.QUIT:
running = False
Pygame There are many events . pygame.QUIT Yes, click “X” What happened when , So we set up running=False, The game cycle will end .
Control the screen refresh rate
We're not here yet “ to update ” Put anything in the section , But we still need to use our settings to control the speed . We can do that :FPS
while running:
# Make sure to cycle at a normal rate
clock.tick(FPS)
The order tells pygame How long does each cycle take , Then pause for how long , So that the whole cycle ( That is, the whole frame ) Last for the right time . If we set it to 30, It means that we want the frame to last 1⁄30 or 0.03 second . for example , If our loop code ( to update , Drawing etc. ) It only needs 0.01 second , that pygame Will wait for 0.02 second .tick() FPS
Conclusion
Last , Let's make sure that when the game cycle ends , We will actually destroy the game window . We do this by putting it at the end of the code . So our final pygame The template looks like this :pygame.quit()
# Pygame template - skeleton for a new pygame project
import pygame
import random
WIDTH = 360
HEIGHT = 480
FPS = 30
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
# Draw / render
screen.fill(BLACK)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
Congratulations on ! You have an effective Pygame Templates . Save this file with a good name , So you can start a new one every time Pygame Reuse it for projects .pygame template.py
In the next tutorial , We will use this template to learn how to draw and move objects on the screen .
边栏推荐
猜你喜欢

【JZOF】12矩阵中的路径

4D毫米波雷达硬件系统架构

图像处理 图像特征提取与描述

Functional testing to automated testing, sharing ten years of automated testing experience

倍福PLC和C#通过ADS通信传输int类型变量

Uncaught (in promise) Neo4jError: WebSocket connection failure. Due to security constraints in your

SAR成像之点目标仿真(二)—— Matlab仿真

C language - big end storage and small end storage

Software testing jobs saturated? Automated testing is a new generation of 'offer' skills

Hcia---03 ENSP usage, DHCP, router
随机推荐
EasyGBS平臺出現錄像無法播放並存在RTMP重複推流現象,是什麼原因?
User and group management, file permissions
Current limiting based on redis+lua
[ACTF2020 新生赛]BackupFile 1
Intégrité du signal (si) intégrité de l'alimentation électrique (PI) notes d'apprentissage (32) Réseau de distribution d'énergie (4)
倍福PLC和C#通过ADS通信传输String类型
What happens when you enter the web address and the web page is displayed
4D毫米波雷达硬件系统架构
设计思维的“布道者”
Opencv image processing (medium) image smoothing + histogram
编译与预处理
信號完整性(SI)電源完整性(PI)學習筆記(三十二)電源分配網路(四)
倍福PLC和C#通过ADS通信定时刷新IO
Redis distributed lock practice
软件测试岗位饱和了?自动化测试是新一代‘offer’技能
机器学习:李航-统计学习方法(二)感知机+代码实现(原始+对偶形式)
倍福PLC和C#通过ADS通信传输bool类型变量
Machine learning: Li Hang - statistical learning method (II) perceptron + code implementation (primitive + dual form)
【离线语音专题④】安信可VC离线语音开发板二次开发语音控制LED灯
时间复杂度总结(Ο是渐进上界,Ω是渐进下界,p,np,np-hard,NPC问题)