TwiddleLab / Code / How a Programmer Thinks
Build a Mini-game
What you will learn
- input() asks the player to type something. It always gives back text.
- int() turns text like "50" into the number 50, so you can compare it.
- A game loop repeats ask, compare, answer. A found flag makes it stop asking after a win.
- Halving makes 7 tries always enough for 1 to 100, and 10 for 1 to 1000.
How the lesson goes
Final level: a real game, about 12 lines long.
Play it first. The computer picked a number from 1 to 100. You have 7 tries.
First, plan the game.
Put the stations in order. The last one sends it back for another try.
Watch one game run: secret 37, guesses 50, 25, 37.
Step through. Watch found, and what happens after the win.
The new pieces have names.
input() waits for the player to type, then gives back what they typed. Always as text, even if it looks like a number.
int() turns text like "13" into the number 13. Then you can compare it or add to it.
print() shows text, and can show several things separated by commas.
The game loop repeats ask, compare, answer. random_number(1, 100) is a ready-made helper that picks the secret. Watch this run.
Build the heart of your game.
Put the lines in order. Run plays a test game with the guesses 50 and 37.
A friend's version crashes after the first guess.
Run it, read the message, fix the line that reads the guess.
Classic level: add the hints.
Drag each print line into the right branch, then run a test game.
Challenge level: what try limit is fair?
A perfect player always guesses the middle. Find the smallest limit where they never lose.
Two bots play your game 20 times each.
Run them, compare the averages, then tap the better strategy.
The secret is 37 and the player types 50. Which line prints?
Tap the print line that runs.
Your friend picks from 1 to 1000. Set a fair try limit.
Drag the pin to the smallest limit a perfect player never loses with.
Pass it to a friend.
Your game, with your limit. Hand over the screen, or play it yourself.
Previous lesson: Functions: Name a Recipe · Part of the course: How a Programmer Thinks
Lessons are interactive and need JavaScript. Turn it on to play them.