【发布时间】:2019-04-09 08:44:18
【问题描述】:
我目前正在创建一个程序,其中一个圆圈将向左移动,停留 3 秒,然后移动到屏幕右侧。但是,当尝试在那里实施此解决方案时:In PyGame, how to move an image every 3 seconds without using the sleep function?,它不起作用。如果有人能告诉我我在做什么,我将不胜感激。
这是我的代码:
import pygame, sys, time, random
from pygame.locals import *
currentPosition = [300, 368]
def moveLeft():
currentPosition[0] -= 1
def moveRight():
currentPosition[0] += 1
pygame.init()
windowCalibration = pygame.display.set_mode((0,0))
WHITE = (255, 255, 255)
windowCalibration.fill(WHITE)
pygame.display.set_caption("Eye calibration")
pygame.draw.circle(windowCalibration, (0,0,0), currentPosition, 10)
done = False
circleIsIdle = True
clock = pygame.time.Clock()
time_counter = 0
def stopCircle():
circleIsIdle = True
while circleIsIdle:
time_counter = clock.tick()
if time_counter > 3000:
time_counter = 0
circleIsIdle = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
while currentPosition[0] >= 10:
moveLeft()
windowCalibration.fill(WHITE)
pygame.draw.circle(windowCalibration, (0,0,0), currentPosition, 10)
pygame.display.update()
stopCircle()
while currentPosition[0] <= 1350:
moveRight()
windowCalibration.fill(WHITE)
pygame.draw.circle(windowCalibration, (0,0,0), currentPosition, 10)
pygame.display.update()
stopCircle()
done = True
【问题讨论】:
-
我想你忘记了
time_counter = clock.tick()中的+= -
在
while not done中,您应该只使用一次pygame.display.update()- 在循环结束时。这样它应该运行更顺畅。但问题是while circleIsIdle:停止while not done并且它无法检查您是否按下ESC。在游戏中你不应该使用其他需要较长时间的while。 -
感谢@Pygasm。这解决了我的问题。