Build a Game #2
This lesson follows on from the previous one, where we create a player and a coin.
The Enemy
To create the enemy, load the ENEMY image and draw it.
Make the enemy face the coin by using the look_at function. Then use move_to to make the enemy move towards the coin.
enemy.look_at(coin) enemy.move_to(coin)
We need to also move the coin when the enemy eats it.
if enemy.collide(coin): coin.x = random(window.left, window.right) coin.y = random(window.bottom, window.top)
Our code for moving the coin is repeated three times! To solve this, create a new Python function called reset_coin. This means we can call it whenever we want the coin to move to a new random position.
The BLIP sound should play when the enemy eats the coin.
The Score
To record the score, we need a new variable that starts at 0. When the player collects the coin, we increment it, and when the enemy eats the coin, we decrement it.
Notice, we also need to write global score at the top of our loop, otherwise we can't edit the score.
score = 0 def loop(): global score # Now we can change the score ...
Let's integrate this with our game.
In the reset_coin function, we print the score to the terminal.
Drawing Text
Use the Text class to display the score on the screen.
score_text = Text(size = 30)
Then, in the reset_coin function, change text.content instead of printing.
def reset_coin(): score_text.content = "Score: " + str(score)
In our game loop, we also move the text to keep it at the top left corner of the screen, with ten pixels of space.
score_text.top = window.top - 10 score_text.left = window.left + 10
Finally, call text.draw.