【问题标题】:Looping issue while attempting to add a growing bar to my game尝试向我的游戏添加不断增长的条时出现循环问题
【发布时间】:2018-02-11 02:26:57
【问题描述】:

该栏应在 5 秒后慢慢填满,但用户应该无法在这 5 秒内点击它。我将如何同时实现这两个目标?

amount = 1
barlength = 102
while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            (x, y) = pygame.mouse.get_pos()
            if x < 200 and x > 100 and y < 200 and y > 100 and amount > 0:
                currenttime = time.clock()
                print (currenttime)
                while time.clock() < currenttime + 5:
                    #untilfull = timez/barlength
                    pygame.draw.rect(DISPLAYSURF, (0, 0, 0), pygame.Rect(20, 20, barlength, 40))

【问题讨论】:

标签: python python-2.7 pygame


【解决方案1】:

您不能在游戏循环中做任何事情来阻止循环运行一段时间。您必须将绘图代码移到事件循环之外。否则,这将导致您的游戏在操作系统中显示为冻结状态。您需要在循环之外或作为事件的结果(例如按下特定键)设置currenttime 的值。不要使用while 循环来检查时间,只需使用普通的if 语句即可。因为游戏循环(外层while 循环)一直在运行,所以if 语句会一直运行。

关于使条形变长,将条形长度乘以自currenttime 以来的时间量,然后除以 5。

另外,我建议使用time.time() 而不是分配currenttime,这只是当前的unix 时间戳(以秒为单位)。

类似...

pygame.Rect(20, 20, int(barlength * (time.time() - currenttime) / 5), 40)

【讨论】:

  • 谢谢!我做了它,所以如果你在所需的框内单击它会增长,但每次点击它只会部分增加......我将如何让它所以我点击,然后它会增长,而不是我必须产生点击框。我尝试使用循环来执行此操作,但这些循环会阻止游戏运行。如果您想通读它,我会将我的代码放在我最初帖子中的代码之上。我的问题只出现在第 70-79 行。感谢大家的帮助!
猜你喜欢
  • 2022-12-10
  • 2021-03-16
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多