Sebastian Anving
Sebastian Anving

Reputation: 23

How to make a Python function sleep some time while the rest of the game continues?

This is what I tried:

if len(wormCoords) > 2:
    time.sleep(4)
    del wormCoords[-1]

but then the whole game (I'm doing a simple "snake" game) sleeps for 4 seconds before removing the last part of the snake. The plan is to each 4 seconds remove the last part of the snake so that you constantly have to eat apples(when you do, the snake grows by one) otherwise you'll die (the snake gets hungry and starves).

The full code is to be find here: http://inventwithpython.com/pygame/chapter6.html but I am doing some changes with it.

Upvotes: 2

Views: 911

Answers (3)

Geoff Reedy
Geoff Reedy

Reputation: 36011

The right thing to do here is set a timer event using this in the setup code (after the line HEAD = 0)

SHRINKSNAKE = pygame.USEREVENT+0

this goes in the runGame function after direction = RIGHT

pygame.time.set_timer(SHRINKSNAKE, 4*1000)

and this in the event handling loop in runGame before the line elif event.type == KEYDOWN: the elifs should line up

elif event.type == SHRINKSNAKE:
  if len(wormCoords) > 2:
    del wormCoords[-1]

For more details check the documentation on pygame.time.set_timer

Upvotes: 4

Mark Hildreth
Mark Hildreth

Reputation: 43061

Check out the pygame.time.set_timer function. This allows you to cause an event to be triggered every few milliseconds that you can handle with your typical event handling mechanism (just like you handle mouse move, keyboard, draw, etc). Read the pygame.event docs for more info on handling the events.

Upvotes: 2

Stephan
Stephan

Reputation: 1037

If you don't want the rest of your application to pause when calling "sleep", you'll need to use threads (see http://docs.python.org/library/threading.html). Since the "wormCoords" variable will need to be shared between threads, you'll need to take proper care when updating it to avoid a race condition.

Upvotes: -1

Related Questions