Coding Education STEM Uncategorized

Creating Magic 8 Ball Game in Python

Howdy! If you’re getting tired of Magic 8 ball game implementations in different languages, I have good news. I’ll stop (for now) with this last variant…this, in Python.

The simplest, quickest code block happens to be in Python…as far as logic goes. In order to do graphics, animation, sound stuff, it’s not that great as it’s made for simplifying data crunching and complex math computations, not really for eye-candy games. However, for Magic 8 Ball type of application, it’s sufficient and efficient (without the bells and whistles).

Gameplay: Here’s a quick clip of this app in action…

Source Code & Explanation: 

I used Thonny IDE for Python which is freely available among many others. Better yet, there are online Python compilers as well that won’t require any local installation hassle (but are somewhat limited in advanced library support). As with C++, we have to include (import in Python) the proper libraries (modules in Python) that we’ll use. sys is most often necessary, and since we’ll be using randomization function, we’ll also need random module.  All the imports are:

import sys
import random

Here’s the full source that’s beautifully compact!

This is not a language course blog, so I won’t go into explaining syntax (there are plethora of free learning resources on the web), but let me highlight a few things…

We have 10 strings stored into an array, and pick a random one by random object’s choice method. In C/C++, we used a modulus operator but in Python, random picking is simpler. The whole program runs until ‘q’ is entered to quit. There are many ways to control the loop, but here I opted for a simple flag variable called gameON. Keep playing as long it’s True (and I set it to True by default).

Challenge: Can you rewrite this without using an array? Can you find a more compact way to accomplish this in Python?

Look for implementation and variations in other languages in my posts here.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top