如何在不冻结窗口的情况下运行Pygame time.delay()?

时间:2018-12-06 16:41:53

标签: python python-3.x pygame

我在使用pygame时遇到了一些麻烦。我正在运行Mac High Sierra,使用Python 3,并使用Spyder作为编译器。我只是想让一个简单的动画运行,但是time.delay()函数不起作用。每当我运行我的代码时,pygame窗口都会打开,保持灰色,直到所有时间延迟都结束后才用白色填充。然后显示我的白色屏幕和圆的最终位置。

如何在不冻结pygame窗口的情况下使time.delay函数正常运行?

<h2>Accordion</h2>
<button onclick="expandAll();">Expand All</button>
<p class="accordion">Section 2</p>
<div class="panel">
  <p class="accordion">Section 1</p>
  <div class="panel">
    <p>
      content
    </p>
  </div>
</div>

<p class="accordion">Section 3</p>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

1 个答案:

答案 0 :(得分:1)

它在我的计算机上运行良好。因此很难说,但我相信问题在于代码的设计。通常,所有绘制和动画都应在主循环(while True)内进行,并且无需添加任何时间延迟。

x = 0  # keep track of the x location
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # clear the screen each time
    screen.fill([255, 255, 255])

    # draw the circle (notice the x variable wrapped in int())
    pygame.draw.circle(screen, [255, 0, 255], [int(50 + x), 50], 50, 0)

    # adjust higher or lower for faster animations
    x += 0.1

    # flip the display
    pygame.display.flip()

现在,动画与主循环同步发生。请记住,屏幕上的像素是以整数计算的,因此在绘制到屏幕上时,您执行的所有浮动操作(例如x += 0.1)都必须是int

如果您不想处理浮点数和小数,则可以将最小速度调整设置为1,而仅每隔一定帧数对其进行调整

x = 0  # keep track of the x location
frames = 0  # keep track of frames
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # clear the screen each time
    screen.fill([255, 255, 255])

    # draw the circle (notice no int() function here)
    pygame.draw.circle(screen, [255, 0, 255], [50 + x, 50], 50, 0)

    # every 50 frames, increase movement. adjust higher or lower for varying speeds
    if frames % 50 == 0:
        x += 1  # never going to be a float, minimum of 1
    frames += 1

    # flip the display
    pygame.display.flip()