The Magic 8-Ball toy
You shake it, and one of 20 answers floats up in the window.
12GAME PROJECTS · MAGIC 8-BALL
Ask a yes-or-no question and get a surprise answer, picked by chance.
IN REAL LIFE
These toys feel like magic, but they only pick by chance.
You shake it, and one of 20 answers floats up in the window.
Each cookie hides a message. Which one you get is luck.
You pick colors and numbers, then open a flap with a funny answer.
Just a game: The ball cannot see the future. random.choice picks an answer by chance, like pulling a paper from a hat.
THE PLAN
Each step uses something you already learned.
A list keeps every answer the ball can give.
[ ] append
A function picks one answer with random.choice and returns it.
def random.choice return
A while loop keeps asking with input() until the player types bye.
while input() !=
After the loop, print a goodbye. It always runs last.
print()
RUN IT
Guess first. Then run real Python and check.
The answers are random, but some things are sure. Look at PyBot's answers.
PyBot's answers: two questions, then bye
How many times does Python show "The ball says:"?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Run it twice. The answers may change, but the number of answers stays the same.
BUILD IT
The answers are random, so these goals check things that are always the same.
The ball only has two answers. Add "Maybe." to the list.
['Yes!', 'No way.', 'Maybe.'] TrueOUTPUT
shake() picks an answer but never gives it back, so reply is None. Fix the function.
TrueOUTPUT
PyBot fixed the answer to test the loop. It should answer until bye, but it stops at once. Fix the while.
Your question: Will I fly? The ball says: Maybe. Your question: bye Bye!OUTPUT
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
random.choice(answers)What does this give back?
def shake():
return random.choice(answers)
print("The ball says:", shake())What does return do here?
while question != "bye":The player types: Bye
Does the loop stop?
question = input("Your question: ")
while question != "bye":Why is there an input() before the while?
The ball says: Yes!
Will it really happen?
You ask "Will I win?" two times.
Will the ball give the same answer?
In the big game, the player types bye at the end.
Which line can you be sure Python shows last?
Want a fresh start? Clear only this page.
random.choice picks from a list, a function returns the pick, and while keeps the game going. It cannot see the future.