Timer function
game
object has a timer method: set_timer()
, it suspends the execution of a function for the given number of seconds.
set_timer(n, func, arg1, arg2...)
the parameters for set_timer()
are:
n
, delayed time in secondsfunc
, the function to be executed after the delayarg1, arg2
... the arguments to be supplied tofunc
We can use the timer to design a series of actions, such as one function runs first, after a few seconds, another function runs.
Example 1:
Suppose we have two predefined functions: fOne()
and fTwo()
:
def fOne():
print('first action')
def fTwo():
print('second action')
In a program, we like to call fOne()
to execute first, then wait 2 seconds and call fTwo()
to execute.
To do this, we will define another function, fMain(), in this function, fOne()
is called first, then the timer game.set_timer()
is called, in timer we can call fTwo()
as one input argument in the following way:
def fMain():
fOne()
game.set_timer(2, fTwo)
the timer has two parameters: (2, fTwo)
, the first is a number 2
, referring to the delay time in seconds; next is a function fTwo
(name only, without trailing parentheses), that's going to be called after delayed time.
Let call fMain()
and 'run' the program, see the results in the console:
fMain()
# a printed message showed right away:
first action
# 2 seconds later, another message:
second action
Example 2:
If the delayed function has parameters, then the input values should be provided in the timer
def fThree(a,b):
print('third action, a number result: ', a + b)
First call fOne()
, then delay 3 seconds and call fThree
with input 3,5
fOne()
game.set_timer(3, fThree, 3, 5)
Run and see the console results, right away there is the message:
first action
# after 3 seconds, another message shows
third action, a number result: 8