在 PyGame 中,如何在不使用睡眠功能的情况下每 3 秒移动一次图像? [英] In PyGame, how to move an image every 3 seconds without using the sleep function?

查看:25
本文介绍了在 PyGame 中,如何在不使用睡眠功能的情况下每 3 秒移动一次图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Recently I've learned some basic Python, so I am writing a game using PyGame to enhance my programming skills.

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

In my game, I want to move an image of a monster every 3 seconds, at the same time I can aim it with my mouse and click the mouse to shoot it.

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

At the beginning I tried to use time.sleep(3), but it turned out that it pause the whole program, and I can't click to shoot the monster during the 3 seconds.

你有什么解决办法吗?

提前致谢!:)

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

Finally I solved the problem with the help of you guys. Thank you so much! Here is part of my code:

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() 

推荐答案

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

Pygame has a clock class that can be used instead of the python time module.

这是一个示例用法:

clock = pygame.time.Clock()

time_counter = 0

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

这篇关于在 PyGame 中,如何在不使用睡眠功能的情况下每 3 秒移动一次图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆