【问题标题】:Python - Pygame random obstacle height issuesPython - Pygame 随机障碍物高度问题
【发布时间】:2014-02-14 17:57:56
【问题描述】:

我目前正在使用 Python 3.2 在 Pygame 中重新制作“Flappy Bird”。我认为这对练习很有用,而且相对简单。然而,事实证明这很难。目前,我在绘制不同高度的矩形但将矩形保持在设置的高度时遇到问题。

这是我的管道

class Pipe:
    def __init__(self,x):
        self.drawn = True
        self.randh = random.randint(30,350)
        self.rect = Rect((x,0),(30,self.randh))

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

    def draw(self,screen):
        self.drawn = True
        pygame.draw.rect(screen,(0,130,30),self.rect)

我的while循环如下:

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))

    Pipe1 = Pipe(scrollx)

    if Pipe1.drawn == True:
        Pipe1.update()
    else:
        Pipe1 = Pipe(scrollx)
        Pipe1.draw(screen)

    scrollx -= 0.3

    pygame.display.update()

我已经为此代码苦苦挣扎了一个多星期,非常感谢您提供的任何帮助。

【问题讨论】:

  • 到底是什么问题?

标签: python pygame python-3.2 flappy-bird-clone


【解决方案1】:

我没有遵循这部分的逻辑:

Pipe1 = Pipe(scrollx)

if Pipe1.drawn == True:
    Pipe1.update()
else:
    Pipe1 = Pipe(scrollx)
    Pipe1.draw(screen)

drawn 属性在构造函数中设置为True,那么您预计何时触发else 条件?请记住,您正在每帧重新创建此管道。

您是否尝试过像画小鸟一样画管道?

编辑:给你的循环建议:

PIPE_TIME_INTERVAL = 2

pipes = []    # Keep the pipes in a list.
next_pipe_time = 0

while True:
    [... existing code to handle events and draw the bird ...]

    for pipe in pipes:
        pipe.move(10)     # You'll have to write this `move` function.
        if pipe.x < 0:    # If the pipe has moved out of the screen...
            pipes.pop(0)  # Remove it from the list.

    if current_time >= next_pipe_time:   # Find a way to get the current time/frame.
        pipes.append(Pipe())  # Create new pipe.
        next_pipe_time += PIPE_TIME_INTERVAL  # Schedule next pipe creation.

【讨论】:

  • 我打算将drawed变量设置为False,此时将绘制管道,然后因为它是True,所以它会被移动而不是绘制
  • 之前创建的管道会停止移动吗?我认为您应该为此使用计时器,而不是 Pipe 的属性。
  • 通过移动 while 循环的创建外部,我现在稍微走得更远了。现在,我要做的就是弄清楚当 Pipe1 的 x = 0 时如何循环...
  • 我已经编辑了答案以包含有关如何处理多个管道的建议。
【解决方案2】:

您在每个循环上创建一个新的Pipe,但永远不要挂在旧的上,因此每次都会获得一个新的随机高度。移动这一行:

Pipe1 = Pipe(scrollx)

while 循环之外。更好的是,有一个管道列表,您可以添加新管道并轻松更新它们。你也永远不会在Pipe 中设置self.drawn = False

另外,您正在为每个事件重置movey,请尝试:

movey = 0.8 # no need for plus 
for event in pygame.event.get():

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2020-03-22
    • 2019-04-03
    相关资源
    最近更新 更多