【问题标题】:how to update the Pygame display inside a while loop inside the main loop如何在主循环内的while循环内更​​新Pygame显示
【发布时间】:2021-06-25 05:28:03
【问题描述】:

一个程序,您单击鼠标,然后从点 1 到 2 出现一个框,框 1 移动到框 2

当框移动时,while 循环中的“更新”似乎不会更新屏幕

相关代码(不是全部):

frames = 0
speed = 20

def distance(x, y, x1, y1):
    distance_ = x - x1, y - y1
    return distance_

while True:
    frames += 1

    if box_two_x is not None:
        pygame.draw.rect(win, (255, 0, 255), (box_two_x, box_two_y, 13, 13))

    while distance(box_one_x, box_one_y, box_two_x, box_two_y)[1] != 0:
        frames += 1
        if frames % speed == 0:
            box_one_y += 1
            pygame.display.update()

如果我需要提供有关代码或问题的更多上下文,请随时询问。

附言我试过的

  • 在 if 语句之前移动更新
  • 调用函数更新屏幕
  • 将整个代码放在函数中的第二个 while 语句之后
  • 在 if 语句中绘制正方形(在 while 循环中)

【问题讨论】:

  • 试试 pygame.display.flip()
  • 我以前试过,有什么具体的地方吗?
  • 不要尝试在应用程序循环中使用循环来控制游戏!

标签: python pygame


【解决方案1】:

不要尝试在应用程序循环中使用循环来控制游戏。使用应用程序循环:

frames = 0
speed = 20

def distance(x, y, x1, y1):
    distance_ = x - x1, y - y1
    return distance_

while True:
    frames += 1

    if box_two_x is not None:
        pygame.draw.rect(win, (255, 0, 255), (box_two_x, box_two_y, 13, 13))

    if distance(box_one_x, box_one_y, box_two_x, box_two_y)[1] != 0:
        if frames % speed == 0:
            box_one_y += 1
            
    pygame.display.update()

使用pygame.time.Clock 控制每秒帧数,从而控制游戏速度。

pygame.time.Clock 对象的方法tick() 以这种方式延迟游戏,即循环的每次迭代消耗相同的时间段。见pygame.time.Clock.tick()

这个方法应该每帧调用一次。

clock = pygame.time.Clock()

def distance(x, y, x1, y1):
    distance_ = x - x1, y - y1
    return distance_

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    if distance(box_one_x, box_one_y, box_two_x, box_two_y)[1] != 0:
        box_one_y += 1

    win.fill(0)

    # [...]

    if box_two_x is not None:
        pygame.draw.rect(win, (255, 0, 255), (box_two_x, box_two_y, 13, 13))

    pygame.display.update()
    clock.tick(60)

典型的 PyGame 应用程序循环必须:

【讨论】:

  • 绝对出色,而且工作;但只有一个问题。为什么要删除我的 raise SystemExit?来吧,你就是不好玩!
猜你喜欢
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 2021-09-18
相关资源
最近更新 更多