60-second countdown!
You have most of your Space Turtle Chomp game developed now. However, at the moment, it can go on forever. Like most games, what you can do is set a time limit for the game duration, again this is simple to do.
Step 1.
Move to the top of your code and import the time module with the other imports:
import timeStep 2.
Move down to the just below the # Set speed variable section and add:
# Set game time limit for 1 minute (60 seconds)
timeout = time.time() + 10*6Note
Note: We set our game timeout to six lots of 10 seconds for a 1-minute game. We could set it to 5 for 30 seconds or 5*5 for 25 seconds.
Step 3.
Move to the top of the while true section and add the following:
gametime = 0
if gametime == 6 or time.time() > timeout:
break
gametime = gametime - 1Note
You set a variable called gametime and set it to 0. The if statement then runs the loop until gametime == 6.
Step 4.
Save your game as kbgame11 and run your Module
You should now have 60 seconds to chomp more space cabbages than your computer opponent before the game ends. The last thing you can do for your game as part of this tutorial is have the game display who wins at the end of 60 seconds.
Step 5.
Move to the very end of your code and add the following if statement and argument. This time the text is not indented until after the if statement:
if (int(score) > int(comp_score)):
mypen.setposition(0, 0)
mypen.color("yellow")
mypen.write("Game Over: You WIN", False, align="center", font=("Arial", 28, "normal"))
else:
mypen.setposition(0, 0)
mypen.color("yellow")
mypen.write("Game Over: You LOSE", False, align="center", font=("Arial", 28, "normal"))The if statement compares your score (player) against the opponent’s score (comp_score). If your score is higher, it prints the ‘You Win’ message, and if it is lower, it prints the ‘You Lose’ message.
If you run your code now, the game will quit before you can actually read the message. Let’s add a delay so we can see the message.
delay = input("Press Enter to finish.")Your code should look like this:
Windows kbgame11.py
Mac kbgame11.py
That is the end of today’s tutorial, if you got through all of it in 1 day well done that is an awesome effort but it doesn’t matter if you didn’t as the tutorial is online and you can still access it from home. Don’t forget to join our She Codes online community to keep in touch with your mentors and ask for help.
Challenge!
If you enjoyed this and wanted to continue practising, other things you might want to try is
- Making multiple opponents using the List [] function like you did for food
- Setting a start option at the beginning of the game
- Setting a play again option at the end
- Setting up an easy, medium, and hard option for the game