如何在Pygame中创建重复出现的不同矩形?

2024-09-22 16:36:31 发布

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

作为Pygame的初学者和Python的相对初学者(大约4个月的知识),我认为尝试重新创建流行的手机应用程序“Flappy Bird”会是一个很好的实践。如何保持一个矩形滚动,同时绘制另一个使用相同功能滚动的矩形?这可能吗?可能有一种方法可以解决这个问题,但是我学习这个模块还不到7个小时:这是我目前为止在Python3.2中编写的代码。(不包括进口)

def drawPipe():
    randh = random.randint(40,270)
    scrollx -=0.2
    pygame.draw.rect(screen, (0,150,30), Rect((scrollx,0),(30,340)))


bif = "BG.jpg"
mif = "bird.png"

pygame.init()
screen = pygame.display.set_mode((640,900),0,32)

background = pygame.image.load(bif).convert()
bird = pygame.image.load(mif).convert_alpha()

pygame.display.set_caption("Flappy Bird")
pygame.display.set_icon(bird)

x,y = 320,0
movex, movey = 0,0

scrollx = 640

while True:
    for event in pygame.event.get():
        movey = +0.8
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_SPACE:
                movey = -2


    x += movex
    y += movey


    screen.blit(background,(0,0))
    screen.blit(bird,(x,y))

    drawPipe()


    pygame.display.update()

谢谢你的帮助!在


Tags: eventdisplayscreenpygame矩形set初学者bird
1条回答
网友
1楼 · 发布于 2024-09-22 16:36:31

你应该首先创建你想在游戏中拥有的对象,一个操作是绘制它们。在

因此,与其使用一个绘制管道和滚动的函数,不如沿着以下几行来实现:

class Pipe:

def __init__(self,x,height):
    self.rect = Rect((x,0),(30,height))

def update():
    self.rect.move_ip(-2,0)

def draw(screen):
    pygame.draw.rect(screen,color,self.rect)

之后在游戏中你可以:

^{pr2}$

稍后,您可以只删除不在屏幕上的管道,并在移除管道时附加新管道。在

相关问题 更多 >