【问题标题】:In PyGame, how to move an image every 3 seconds without using the sleep function?在 PyGame 中,如何在不使用睡眠功能的情况下每 3 秒移动一次图像?
【发布时间】:2014-07-29 08:26:39
【问题描述】:

最近我学习了一些基本的 Python,所以我正在使用 PyGame 编写一个游戏来提高我的编程技能。

在我的游戏中,我想每 3 秒移动一次怪物的图像,同时我可以用鼠标瞄准它并点击鼠标射击它。

一开始我尝试使用time.sleep(3),结果发现它暂停了整个程序,并且在3秒内我无法点击射击怪物。

那么你有什么解决办法吗?

提前致谢! :)


在你们的帮助下,我终于解决了这个问题。太感谢了! 这是我的代码的一部分:

import random, pygame, time

x = 0
t = time.time()
while True:

    screen = pygame.display.set_mode((1200,640))
    screen.blit(bg,(0,0))

    if time.time() > t + 3:
        x = random.randrange(0,1050)
        t = time.time()

    screen.blit(angel,(x,150))

    pygame.display.flip() 

【问题讨论】:

  • 在另一个线程中使用time.sleep(3)
  • 如果您的游戏在循环中运行,那么只需在该循环中设置一个检查函数来检查current_time = last_saved +3 : move, last_saved=current_time
  • * current_time >= last_saved + 3 以防万一出现延迟并达到current - last = 4 或类似名称。
  • +1 @indivisible 没有完全考虑清楚。 @Alex Ling import datetime datetime.datetime.now() 将为您提供当前时间。

标签: python pygame


【解决方案1】:

我想这行得通,但我觉得这样做会更 Pythonic。

import random, pygame

clock = pygame.time.Clock()
FPS = 26 #Or whatever number you want
loops_num = 0
while True:

    screen = pygame.display.set_mode((1200,640))
    screen.blit(bg,(0,0))

    if loops_num % (FPS * 3) == 0:
        enemy.move()

    screen.blit(angel,(x,150))

    pygame.display.flip()
    loops_num += 1
    clock.tick(FPS)

或者如 Bartlomiej Lewandowski 所说,他的回答也很棒。

【讨论】:

    【解决方案2】:

    Pygame 有一个时钟类,可以用来代替 python 时间模块。

    这是一个示例用法:

    clock = pygame.time.Clock()
    
    time_counter = 0
    
    while True:
        time_counter = clock.tick()
        if time_counter > 3000:
            enemy.move()
            time_counter = 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      相关资源
      最近更新 更多