Improve your game
Section 8: The project: the guess-the-number gameLesson 8.3 · ⏱ 10 min
- Let the player choose the level: from 1 to 10 or to 100.
- Allow only 5 tries, and when they run out tell them the number.
- At the end ask them: do you want to play again?
📌 Note
🎉 You finished the Robo Python course! Next step: the Robo Web course, or programming the Arduino in code in Robo Maker.
📌 Another example: the best score
We play twice, and keep the smallest number of tries.
When the program asks, we type: 1, then 2, then 3, then 4, then 5, then 1, then 2, then 3, then 4, then 5.
import random
random.seed(5)
best = None
for game in range(2):
secret = random.randint(1, 5)
tries = 0
while True:
tries = tries + 1
if int(input("Guess 1 to 5: ")) == secret:
break
print("game", game + 1, ":", tries, "tries")
if best is None or tries < best:
best = tries
print("Best:", best)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Guess 1 to 5: 1 Guess 1 to 5: 2 Guess 1 to 5: 3 Guess 1 to 5: 4 Guess 1 to 5: 5 game 1 : 5 tries Guess 1 to 5: 1 Guess 1 to 5: 2 Guess 1 to 5: 3 game 2 : 3 tries Best: 3
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Print a message that changes with the number of tries (excellent if it is 3 or less).
👀 Show the solution🙈 Hide the solution
When the program asks, we type: 2.
tries = int(input("Tries: "))
if tries <= 3:
print("Excellent!")
else:
print("Good, try again")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Tries: 2 Excellent!
Result: Excellent!
Medium
Ask: do you want to play again? (yes/no).
👀 Show the solution🙈 Hide the solution
When the program asks, we type: yes, then yes, then no.
games = 0
while True:
games = games + 1
print("Game", games)
if input("Again? ") != "yes":
break
print("Bye after", games, "games")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Game 1 Again? yes Game 2 Again? yes Game 3 Again? no Bye after 3 games
Result: Bye after 3 games
Hard
A difficulty level: easy (1–10) or hard (1–100).
👀 Show the solution🙈 Hide the solution
When the program asks, we type: hard.
import random
random.seed(1)
level = input("easy or hard? ")
top = 10 if level == "easy" else 100
secret = random.randint(1, top)
print("I picked a number from 1 to", top)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗easy or hard? hard I picked a number from 1 to 100
Result: I picked a number from 1 to 100

