我目前正在尝试制作《flappy bird》的pygame版本(比我想象的要复杂得多),并且我一直在制作随机高度的管道。有人能帮我一下吗?为了制作同样的动画,我想在屏幕的右边生成管道,并在左边删除它们。当我运行当前代码时,管道图像在左上角彼此重叠并且不移动。(这只鸟可以工作)
import pygame, random, sys
pygame.init()
icon = pygame.image.load('flappybirdicon.png')
pygame.display.set_icon(icon)
screen = pygame.display.set_mode([284, 512])
pygame.display.set_caption("Flappy Bird")
bg = pygame.image.load('flappybirdbackground.png')
bgrect = bg.get_rect()
clock = pygame.time.Clock()
pipex = 335
class Bird(pygame.sprite.Sprite):
def __init__(self, image, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.pos = [x, y]
class Pipe(pygame.sprite.Sprite):
def __init__(self, image, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.height = height
self.pos = [pipex, height]
def scroll(self):
self.rect.move_ip(-3, 0)
self.pos[0] -= 3
self.rect.center = self.pos
def draw_pipes():
pipe1_height = random.randint(115, screen.get_height())
pipe1 = Pipe('flappybirdpipe.png', pipe1_height)
pipe2_height = 397 - pipe1_height
pipe2 = Pipe('flappybirdpipe2.png', pipe2_height)
screen.blit(pipe1.image, pipe1.rect)
screen.blit(pipe2.image, pipe2.rect)
bird = Bird('flappybirdbird.png', 142, 256)
draw_pipes()
while True:
clock.tick(30)
bird.pos[1] += 5
bird.rect.center = bird.pos
screen.blit(bg, bgrect)
pipe1.scroll()
pipe2.scroll()
screen.blit(bird.image, bird.rect)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird.pos[1] -= 75
elif event.type == pygame.MOUSEBUTTONDOWN:
bird.pos[1] -= 75
我不熟悉PyGame,但看起来您没有为管道设置X坐标。你在设置高度,而不是位置。
它也看起来像你没有保存管道数据的任何地方,所以我想你的代码也导致新的管道创建/绘制每次draw_pipes()被调用,这看起来是每一帧。