How to use sleep with the same function?

Viewed 36

I am trying to build an ant colony simulator. I'd like for each 'ant' to destroy each block of sand it collides with after 3 seconds.

I have tried doing this in a variety of ways, the easiest being time.sleep(3), however this causes my entire program to stop.

I understand that I will probably have to use threading, but I'm unsure how to properly implement it in my code.

collision function:

def collision(cells, sprite, size):
    for row, col in np.ndindex(cells.shape):
        hitbox = pg.Rect(col * size, row * size, size + 1, size + 1)

        if pg.Rect.colliderect(sprite.rect, hitbox):
            if cells[row, col] == 1:
                sprite.stop_moving = True
                time.sleep(3)
                cells[row, col] = 0
                sprite.stop_moving = False

calling in main():

        if running:
            cells = update(screen, cells, 10)

            # Check collision on each sprite
            for sprite in all_sprites:
                collision(cells, sprite, 10)
1 Answers

At the start of your program:

import threading

Somewhere in your code:

def destroy_block(row, col):
    time.sleep(3)
    cells[row, col] = 0          # If this is wrong, replace this
    sprite.stop_moving = False   # with your code to destroy block

When you want to destroy a block (inside the collision function)

threading.Thread(target=destroy_block, args=(row, col))
Related