A Display Name
A Display Name

Reputation: 367

How can I move the turtle every few seconds without using time.sleep()?

I'm making a Tetris like game, with turtle.

When the block goes down, I use time.sleep() to make it wait for a few seconds before it goes down. But, the time.sleep() make the ENTIRE code stop, I want only the defintion to stop:

def moveDown():
    time.sleep(2)
    turtle(sety(100)
    time.sleep(2)
    turtle.sety(0)
    time.sleep(2)
    turtle.sety(-100)
    time.sleep(2)
    turtle.sety(-200)
    setBlock()

I don't want the ENTIRE code to stop, because the player needs to use the left and right keys to navigate around the screen. So, how would I achieve this? Sorry if this was very rambley and muddled.

Upvotes: 1

Views: 3917

Answers (2)

Tom Myddeltyn
Tom Myddeltyn

Reputation: 1375

What is going on with time.sleep() is that it is what is known as a "blocking call" meaning that when it is called, your process will not proceed until it is done. You need to have another thread/process to run in the background to cause it to move. Something like this:

def moveDown():
    turtle.sety(turtle.ycor())
    if moveable:
        screen.ontimer(moveDown, 2000) #ms

Then elsewhere in your code:

...
    moveable=True
    moveDown()
...

Then stop it with:

...
    moveable=False
...

That is a very simplistic example (based off the python.org example)

Upvotes: 1

user342194
user342194

Reputation: 1

time.clock() can report the number of seconds since it has started so you can check against it to see if you will allow the user to input commands for a certain interval once it is on the bottom

import time
junk = time.clock()
pause_at_bottom = 0.5
## code till it hits the bottom
at_bottom = time.clock()
while time.clock() < (at_bottom + pause_at_bottom):
    ## code to run while at the bottom
## code to run once time has elapsed at bottom

Upvotes: 0

Related Questions