当前位置:网站首页>Space shooting part 2-2: enemy spirit
Space shooting part 2-2: enemy spirit
2022-07-23 13:16:00 【acktomas】
Space shooting Part 2-2: enemy sprite
This is us. “Shmup” Project No 2 part ! In this lesson , We will add some enemy elves for players to avoid . 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 .
enemy sprite
At this point , We don't need to worry about our enemy elves What is it? , We just want them to appear on the screen . You may think your game is about spaceships avoiding meteors or unicorns avoiding flying pizza - In terms of code , It doesn't matter .
Remember that , We will name the enemy's Genie as a common name in the code . The fact proved that , For general objects that move in the game , There is a perfect word :Mob.
We'll start by defining sprite attributes :
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
The key here is to choose a suitable Mob Where it appears . We don't want them to just pop up , So we choose one at the top y value (y<0), And one between the two sides x The random value .
Now? , about update(), We can move the genie quickly , But when the spirit disappears from the bottom ? We can delete this wizard , Then generate another wizard , Or you can get exactly the same effect by moving the sprite back to a random position above the top :
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
Generate enemies
We will hope to have many enemies , So we will build a new mobs Group to control all enemies . This will also make our programming easier in the next steps . then , We generate some Mob And add it to the Group :
player = Player()
all_sprites.add(player)
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
Now you should have an endless stream Mob Get off the screen , Just like this. :

This is good , But let Mob It's a little boring to move directly down . Let us in x Add a little movement in the direction :
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
self.speedx = random.randrange(-3, 3)
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
Please note that , We need to change if Statement so that in Mob Regenerate when leaving the screen Mob. Moving diagonally Mob Left the side before leaving the bottom , So we need to be Mob Reset it quickly when you leave the screen .
Your game should now look like this :
In the next lesson , We will learn how to detect when two elves collide with each other ( Collision ), And enable players to Mob Shoot .
The complete code of this part
# KidsCanCode - Game Development with Pygame video series
# Shmup game - part 2
# Video link: https://www.youtube.com/watch?v=-5GNbL33hz0
# Enemy sprites
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
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
self.speedx = random.randrange(-3, 3)
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
# 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()
The first 3 part : Collision ( And bullets )
边栏推荐
猜你喜欢

互联网时代下,如何精细化用户运营?

Signal integrity (SI) power integrity (PI) learning notes (32) power distribution network (4)

VLAN的划分以及通过DHCP给所有主机自动分配IP,以及通信全网可达

4D天线阵列布局设计

基于redis+lua进行限流

Convert the specified seconds to minutes and seconds

MySQL - composite query external connection

C语言-大端存储和小端存储

Summary of time complexity( Ο Is the asymptotic upper bound, Ω is the asymptotic lower bound, P, NP, NP hard, NPC problem)

Outlook tutorial, how to switch calendar views and create meetings in outlook?
随机推荐
Rhcsa - - parcourir le contenu du fichier, couper, uniq, trier, utiliser les commandes.tr
redis分布式锁实践
[ACTF2020 新生赛]BackupFile 1
Common CMD commands to quickly open programs
CAN控制器的位同步过程
Uncaught (in promise) Neo4jError: WebSocket connection failure. Due to security constraints in your
C language - big end storage and small end storage
com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value:
Opencv image processing (Part 1): geometric transformation + morphological operation
倍福PLC和C#通过ADS通信传输结构体类型变量
Liveness, readiness and startup probes
MySQL - composite query external connection
雷达导论PART VII.3 SAR图像的形成和处理
EasyGBS平台出现录像无法播放并存在RTMP重复推流现象,是什么原因?
Helm installing rancher
互联网时代下,如何精细化用户运营?
【JZOF】11旋转数组的最小数字
将集合使用流进行分页
HCIA----06 OSPF
雷达导论PART VII.2 成像方法