当前位置:网站首页>Space shooting part 1: player spirit and control
Space shooting part 1: player spirit and control
2022-07-23 13:16:00 【acktomas】
Space shooting Part 1: Player sprites and controls
Let's make our first game ! In this series of courses , We will use Python and Pygame Build a complete game . It applies to already known Python Basic knowledge and hope to deepen the understanding of Python Beginners who understand and learn the basic knowledge of programming games .
Start
If you're not ready , Please return and complete the related Pygame introduction The first lesson of . We will use the [pygame template.py](https://github.com/kidscancode/gamedev/blob/master/tutorials/pygame template.py) The program is the starting point of this course .
In this series , We're going to make a “Shmup” or “Shoot 'em up” Style games . In our case , We will be pilots of a small spacecraft , Try to survive when meteors and other objects fly towards us .
First , Save with a new name pygame template.py file . such , When you need other new games , You can still have templates . I choose to save as :shmup.py.
First , Let's change the game setting to the value of the game we are making :
WIDTH = 480
HEIGHT = 600
FPS = 60
This will be a “ Vertical mode ” game , This means that the height of the window is greater than the width . This is also an action game , So we want to make sure our FPS High enough , So that the fast-moving Genie looks like it can move smoothly .60 It's pretty good .
Player spirit
The first component we want to add is a wizard representing players . Final , This will be a spaceship , But when you first started , Ignore the graphics a little , It would be easier to use a normal rectangle for all sprites . Just focus on putting the genie on the screen and moving it the way you want , Then you can replace the rectangle with beautiful artwork .
The following is the beginning of our player wizard :
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 40))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
We have chosen for players 50x40 Pixel size , And its rect Locate at the bottom center of the screen . We also created a speedx attribute , Used to track players in x Direction ( about ) Moving speed of . If you are not sure about these operations , Please refer to the previous use Elvish Course .
For our Sprite Of update() Method , That is, the code that will be executed in every frame of the game , We want to move at any speed Sprite:
def update(self):
self.rect.x += self.speedx
Now? , We can generate our elves , To make sure we see it on the screen :
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
Don't forget it , Every sprite you create must be added to all_sprites In the group , To update and draw it on the screen .
motion / control
This will be a keyboard controlled game , So we want players to press Left or Right Arrow keys move ( If you will , You can also use a and d).
When we consider using buttons in games , That means we need to talk about event :
- Options 1: In our event queue , We can define two events ( One for each key ), Each event will change the player's speed accordingly :
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.speedx = -8
if event.key == pygame.K_RIGHT:
player.speedx = 8
The problem with this approach is , Although pressing the key will make the player move , But I can't stop ! We need to add two more KEYUP event , Set the speed back 0.
- Options 2: We tell sprite Throughout Set its speed to
0, UnlessLEFTorRIGHTKey pressed . This will make the player sprite move more smoothly , And simpler coding :
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -8
if keystate[pygame.K_RIGHT]:
self.speedx = 8
self.rect.x += self.speedx
take speedx Each frame is set to 0, then pygame.key.get_pressed() Check whether the key is pressed . It will generate a dictionary for each key on the keyboard , Its value is True or False Indicates whether the key is currently pressed or lifted . If any key we want is pressed , We will set the speed accordingly .
Stay on the screen
Last , We need to make sure our Genie doesn't leave the screen . We will show players the spirit of update() Method to add the following :
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
Now? , If rect Move to the left or right edge of the screen , It will stop . Another option is to surround the screen - When it hits the edge, it transmits the spirit from one side to the other - But for this game , It's more suitable to stop at the edge .
Conclusion
Here is the complete code for this step :
# KidsCanCode - Game Development with Pygame video series
# Shmup game - part 1
# Video link: https://www.youtube.com/watch?v=nGufy7weyGY
# Player sprite and movement
import pygame
import random
WIDTH = 480
HEIGHT = 600
FPS = 60
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Shmup!")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 40))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -8
if keystate[pygame.K_RIGHT]:
self.speedx = 8
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# 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
all_sprites.update()
# Draw / render
screen.fill(BLACK)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
In the next lesson , We will add some enemy elves for players to avoid .
The first 2 part : enemy sprite
边栏推荐
- 在GPU上运行MATLAB程序
- PostgreSQL k8s deployment template
- 倍福PLC和C#通过ADS通信传输String数组类型变量
- Image processing image feature extraction and description
- HCIA----01互联网的初认识
- 国信证券软件开户是安全吗?信息会不会泄露?
- Quelle est la raison pour laquelle la plate - forme easygbs ne peut pas lire l'enregistrement vidéo et a un phénomène de streaming répété rtmp?
- 时间复杂度总结(Ο是渐进上界,Ω是渐进下界,p,np,np-hard,NPC问题)
- 倍福PLC和C#通过ADS通信传输bool类型变量
- CORTEX-A系列处理器
猜你喜欢
随机推荐
【JZOF】09用两个栈实现队列
OpenVPN deployment
EasyGBS平台出现录像无法播放并存在RTMP重复推流现象,是什么原因?
Opencv image processing (medium) image smoothing + histogram
机器学习:李航-统计学习方法(二)感知机+代码实现(原始+对偶形式)
成功 万象奥科与CODESYS技术联合调测
沟通绩效业绩不佳的 11 个提示
使用vscode进行远程编辑和调试
软件测试岗位饱和了?自动化测试是新一代‘offer’技能
从List<Map>中截取指定的范围数据集合
数据进行脱敏
Signal integrity (SI) power integrity (PI) learning notes (XXXI) power distribution network (III)
Jenkins持续集成报错stderr: fatal: unsafe repository (‘/home/water/water‘ is owned by someone else)
OpenCV 视频操作
PostgreSQL k8s deployment template
SAR成像之点目标仿真(三)—— 仿真结果分析
What happens when you enter the web address and the web page is displayed
Is it safe to open an account with Guosen Securities software? Will the information be leaked?
Common scheduled cron expressions for scheduled tasks
How to prevent repeated payment of orders?









