当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
射击 第 1-3 课:图像精灵
北大博士小姐姐:分享压箱底干货 | 五招提高学习效率
设计思维的“布道者”
Static routing principle and configuration
Desensitize data
倍福PLC和C#通过ADS通信传输bool类型变量
太空射击 Part 2-3: 子弹与敌人碰撞处理
雷达导论PART VII.3 SAR图像的形成和处理
OpenCV图像处理(上)几何变换+形态学操作
谈谈学习和工作——钱学森
Is it safe to open an account with Guosen Securities software? Will the information be leaked?
Are there any academic requirements for career transfer software testing? Is there really no way out below junior college?
MySQL - composite query external connection
SAR成像之点目标仿真(一)—— 数学模型
EasyGBS平臺出現錄像無法播放並存在RTMP重複推流現象,是什麼原因?
图像处理 图像特征提取与描述
倍福PLC和C#通过ADS通信定时刷新IO
4D天线阵列布局设计
OpenCV图像处理(下) 边缘检测+模板匹配+霍夫变换
北汇信息12岁啦|Happy Birthday








