In PyGame, how do I move an image every 3 seconds without using the sleep function?… here is a solution to the problem.
In PyGame, how do I move an image every 3 seconds without using the sleep function?
Recently I learned some basic Python, so I’m using PyGame to write a game to improve my programming skills.
In my game, I want to move an image of a monster every 3 seconds, and at the same time I can aim at it with the mouse and shoot it with the mouse click.
At first I tried to use time.sleep(3) and found that it paused the entire program and could not click to shoot monsters for 3 seconds.
So do you have any solutions?
Thanks in advance! 🙂
Finally solved this problem with the help of everyone. 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()
Solution
Pygame has a clock class that can be used in place of a python time module.
Here is a usage example:
clock = pygame.time.Clock()
time_counter = 0
while True:
time_counter = clock.tick()
if time_counter > 3000:
enemy.move()
time_counter = 0