Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

python - How to use time.sleep in pygame?

So i am trying to display an image, wait 1 second and then display another image. I'm making a matching game, so in my code I'm trying to say that if two images don't match, I want to change the image to just a preset generic one. So my code for that would look something like this:

if True:
    self.content = self.image
    time.sleep(1)
    self.content = Tile.cover

self.content is a variable for what is being displayed, self.image is the image that displays, and then Tile.cover is the generic image that covers the other one. Yet whenever I do this the code skips the first line, and just sets the image to Tile.cover, why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updated on 18/03/2019.

In Pygame, you have to use pygame.time.wait() instead of python's time.sleep().

It takes time in milliseconds:

pygame.time.wait(1000)

The reason for not using time.sleep is because it will block pygame's event loop and so pygame will not be able to process other events.




Old answer

Following is the older version of this answer which was marked accepted. It is outdated and, most probably, incorrect.

The behaviour which you're getting is due to the way time.sleep()

Example:

I want you to try the following code in your console:

>>> import time
>>> 
>>> def foo():
        print "before sleep"
        time.sleep(1)
        print "after sleep"
>>> 
>>> # Now call foo()
>>> foo()

Did you observe what happened during the output?

>>> # Output on calling foo()
... # Pause for 1 second
... 'before sleep'
... 'after sleep'

This is what is happening with your code too. First it sleeps, then it updates self.content to self.image and Time.cover at the same time.

Fix:

To fix the code in the example above, you can use sys.stdout.flush().

>>> def foo():
        print "before sleep"
        sys.stdout.flush()
        time.sleep(1)
        sys.stdout.flush()
        print "after sleep"

>>> foo()
... 'before sleep'
... # pause for 1 second
... 'after sleep'

Disclaimer:

I haven't tried sys.stdout.flush() with Pygame so I can't say if it will work for you, but you can try.

There seems to be a working solution on this SO question: How to wait some time in pygame?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...