无法在pygame中使用精灵绘制飞扬鸟类的支柱

时间:2018-02-11 09:52:02

标签: python pygame sprite

我正在使用pygame制作一个有趣的鸟类克隆游戏。我想通过使用Sprite.draw绘制支柱。我创建了一个Pillar类,并在屏幕左侧使用两个矩形p_upperp_lower对其进行初始化,并在update函数的帮助下向右侧移动精灵。但屏幕只显示p_lower支柱。有人可以帮忙吗?

enter image description here

class Pillar(pygame.sprite.Sprite):
    # the "h" parameter is height of upper pillar upto gap
    # "w" is the width of the pillar
    # pillar is coming from left to right
    def __init__(self, w, h, gap):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface((w, h))
        self.image.fill(green)
        self.p_upper = self.rect = self.image.get_rect()
        self.p_upper.topleft = (-w, 0)

        self.image = pygame.Surface((w, HEIGHT - (h + gap)))
        self.image.fill(green)
        self.p_lower = self.rect = self.image.get_rect()
        self.p_lower.topleft = (-w, h + gap)

    def update(self):
        self.p_upper.x += 1
        self.p_lower.x += 1

2 个答案:

答案 0 :(得分:1)

由于以下两行:

self.p_upper = self.rect = self.image.get_rect()

和...

self.p_lower = self.rect = self.image.get_rect()

这些都抓住了对self.rect的相同引用。第一行运行并将rect引用分配给p_upper。然后将相同的引用分配给p_lower。因为它是相同的参考,当您更新下方矩形的位置时,您实际上正在更新两者。

答案 1 :(得分:0)

使用由两个rects和images组成的sprite不是解决此问题的好方法。我建议用自己的图像和rect创建两个独立的精灵。要同时创建两个精灵实例并将它们添加到精灵组,您可以编写一个简短函数,如本例所示:

import pygame as pg
from pygame.math import Vector2


green = pg.Color('green')
HEIGHT = 480

class Pillar(pg.sprite.Sprite):

    def __init__(self, x, y, w, h):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((w, h))
        self.image.fill(green)
        self.rect = self.image.get_rect(topleft=(x, y))

    def update(self):
        self.rect.x += 1


def create_pillars(w, h, gap, sprite_group):
    sprite_group.add(Pillar(0, 0, w, h-gap))
    sprite_group.add(Pillar(0, HEIGHT-(h+gap), w, h+gap))


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    create_pillars(50, 170, 0, all_sprites)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_a:
                    create_pillars(50, 170, 15, all_sprites)
                elif event.key == pg.K_s:
                    create_pillars(50, 170, 30, all_sprites)
                elif event.key == pg.K_d:
                    create_pillars(50, 100, -60, all_sprites)

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()