2
votes

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

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.

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.

So do you have any solution for this?

Thanks in advance! :)


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() 
2
Use time.sleep(3) in another thread? - kay
If your game is running in a loop, then just have a check function in that loop that checks if current_time = last_saved +3 : move, last_saved=current_time - 1478963
* current_time >= last_saved + 3 Just in case there's a delay and it hits current - last = 4 or similar. - indivisible
+1 @indivisible didn't fully think it through. @Alex Ling import datetime datetime.datetime.now() will get you the current time. - 1478963

2 Answers

2
votes

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

Here is an example usage:

clock = pygame.time.Clock()

time_counter = 0

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

I guess that works, but I feel think it would be more pythonic to do this.

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)

Or what Bartlomiej Lewandowski said, his answer is great also.