2

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)
Beatdown
  • 187
  • 2
  • 7
  • 20
  • 1
    Typically when making a game, you can think about it like a state machine. On each update to the state machine you usually perform updates based on what the user inputs are, and how much time has passed since the last update. Typically the games main while loop (or engine) will run these steps: 1) Update the state machine, 2) Draw all of the game entities, 3) sleep for a fixed amount of time. This way everything updates at once, everything is drawn all at once, and the amount of time in between each frame is constant. – flakes Jun 20 '22 at 17:06
  • 1
    In this case part of your update could be something like `time_since_collision` which once set, is decremented on each update of the statemachine. Only when the state machine reaches a zero value for this value will something be changed. – flakes Jun 20 '22 at 17:07

1 Answers1

1

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))
The Thonnu
  • 3,578
  • 2
  • 8
  • 30