区分碰撞中的精灵

2024-04-29 21:55:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个类似于经典的“太空坠毁”游戏的程序,但是有多种类型的弹药,每种弹药只影响特定类型的目标。方法自我重叠的精灵()将识别任何重叠的精灵并相应地采取行动,但如何让程序检测重叠精灵是否属于特定类型?在

class Krabbypatty(games.Sprite):
LETTUCE = 1
TOMATO = 2
PATTY = 3
images = {LETTUCE : games.load_image("tamatoandpatty.bmp"),
                 TOMATO : games.load_image("lettuceandpatty.bmp"),
                 PATTY : games.load_image("lettuceandtomato.bmp") }
SPEED = 3
def __init__(self, x, y, krabbypattytype):
    super(Krabbypatty, self).__init__(
        image = Krabbypatty.images[krabbypattytype],
        x=x, y=y,
        dx = random.choice([1, -1]) * Krabbypatty.SPEED * random.random()/krabbypattytype,
        dy = random.choice([1, -1]) * Krabbypatty.SPEED * random.random()/krabbypattytype)
    self.krabbypattytype = krabbypattytype
def update(self):
    if self.top > games.screen.height:
        self.bottom = 0
    if self.bottom < 0:
        self.top = games.screen.height
    if self.left > games.screen.width:
        self.right = 0
    if self.right < 0:
        self.left = games.screen.width
    if self.overlapping_sprites:
        sprite.change_patty()
def change_patty(self):

Tags: imageself程序ifdefloadrandomscreen
3条回答

最“Pygame”的解决方案是使用pygame.sprite.Group存储精灵,pygame.sprite.groupcollide来检测某些类型的精灵是否碰撞。所以你可以为敌人创建enemy_type_a组,为可能伤害该类敌人的炮弹创建type_a_destroyers组。在

只需使用type()

例如

def update(self):
    for touch in self.overlapping_sprites:
        if type(touch) is wall:
            print("Hit a wall")
            self.horizontal_bounce()
        elif type(touch) is roof:
            print("you hit the roof")
            self.vertical_bounce()
        elif type(touch) is block:
            self.vertical_bounce()
        self.score.increase_score(10)

    if self.bottom>games.screen.height:
        self.block.end_game()

在自我重叠短跑是精灵的名单,对吧?在

尝试迭代自我重叠的精灵在

for sprite in self.overlapping_sprites:
   sprite.dosomething()

或者

^{pr2}$

我不知道精灵是什么,但我想你可以指定一个字段来跟踪它是什么类型的。 或者,如果有精灵子类型(同样,我不知道pygame或其他你正在使用的东西),你可以使用isinstance。在

if isinstance(sprite, type)

另一个关于pygame和重叠精灵的答案是:Object not behaving correctly

相关问题 更多 >