我正在尝试通过创建带有块的简单“ shmup”游戏来学习如何使用pygame。运行代码时,不会显示任何错误,但是游戏似乎并未检测到精灵之间的碰撞。我使用不正确吗? 任何帮助,不胜感激。如果可以轻松运行自己的代码,因为没有使用外部文件,则应该可以。
hits = pygame.sprite.spritecollide(player,mobs, False)
if hits:
running = False
所有代码:
import pygame
import random
import time
pygame.init()
pygame.mixer.init()
width = 480
height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
#initialise pygame and create window
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption("Shoot 'Em Up!")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self): #this is mandatory, it loads the built in sprite
function/code
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 #thi section makes the sprite move, sets x speed
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -5
if keystate[pygame.K_RIGHT]:
self.speedx = 5
self.rect.x += self.speedx
# sets the boundaries of screen
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(0, width - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
#randomising angle of movement
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 < -30 or
self.rect.right > width + 30:
self.rect.x = random.randrange(0, width - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(3, 8)
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group() #make a spearte group for mobs to enable
collisions between groups
player = Player()
all_sprites.add(player)
# spawning the mobs
for i in range (8): #start with spawning 8
m = Mob()
all_sprites.add(m)
mobs.add
#Game Loop
running = True
while running:
clock.tick(60) #keep running at the right speed
for event in pygame.event.get(): #process events (inputs)
if event.type == pygame.QUIT: #check for closing of window
running = False
#update
all_sprites.update()
# check to see if a mob hit a player
hits = pygame.sprite.spritecollide(player,mobs, False) # which sprites
do you want to check for collisisons
if hits:
running = False
#render
screen.fill(black)
all_sprites.draw(screen) #where to draw sprites in the group
pygame.display.flip()
pygame.quit()
答案 0 :(得分:0)
您只需将Mob
实例m
添加到mobs
子画面组:
for i in range (8): #start with spawning 8
m = Mob()
all_sprites.add(m)
mobs.add(m) # Add `m` to the group.