A4 - Timers
Often in a game, we want something to happen after a certain period of time.
Beginner game programmers will often try to put a time.sleep statement somewhere to achieve this,
only to realize this completely freezes the game.
in OArcade, the solution is to use the oa.set_timer function. It accepts two arguments:
- The time in seconds to wait
- A reference to a function/method to call after that amount of time has passed.
We can see an example of this in the Fly sprite:
def on_step(self):
# ... (Irrelevant stuff) ...
if colliding_player:
colliding_player.take_damage(2)
self.movement_state = "retreat"
oa.set_timer(3, self.reset_movement_state)
# ... (Irrelevant stuff) ...
def reset_movement_state(self):
self.movement_state = "towards player"
Here, after the fly has collided with a player, it moves into the "retreat" state and sets a timer to called the reset_movement_state method after three seconds.
Main Task
Download this fireball image and put it into the images folder within your game.
Add the following code to the end of sprites.py:
class FireBall(oa.Sprite):
def on_create(self):
self.visual = "images/fireball.png"
self.layer = cc.Layers.MOVING_GAME_OBJECTS
self.change_x = 8
def on_step(self):
# If we've gone off screen, remove ourself from the game.
if refs.cur_view.world_camera.point_in_view(int(self.x), int(self.y)) == False:
self.kill()
In level_1.py, add the following method to your Level_1 class:
def spawn_fireball(self):
# Choose a y-value for the fireball within a 200 pixel range of the player
y = int(self.player.y + random.randint(-200, 200))
FireBall(-10, y)
In the on_create method in the Level_1 class, set a timer to call self.spawn_fireball after two seconds.
Finally, copy the same line to the end of the spawn_fireball method you pasted in earlier, which should then create a loop of fireballs spawning every two seconds.
Extended Task
Find another way to integrate a timer into the game. For example, maybe an enemy will do something every ___ number of seconds.