Coding Education STEM

Creating Magic 8 Ball Game in C/C++

I’ll continue with the Magic 8 ball theme in this coding series. Previously, I posted a fun implementation in Scratch here. If you’re not familiar with it, that’s the best place to start as it has visual aspects and a video clip.

This time, I’ll implement the same concept in C/C++ (mostly in C++). To avoid unnecessary distraction, I’m not going to spend too much time on the bells-and-whistles here as with Windows graphical UI and additional libraries, so let’s keep it as a console application.

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

Source Code & Explanation: 

I used Dev-C++ compiler 5.11 for this which is freely available. As it’s actually C++, we have to include the proper libraries that we’ll use. string for string manipulation and ctime for randomization. All the includes are (and namespace is required):

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

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 and pick a random one by using % (modulus operator) essentially ensuring that the random generator is scoped within 10 (inclusive).(You’ll have to modify that depending on your number of answers)

Then we just output the hard-coded string according to the number returned. Nothing elegant here on purpose to keep it really simple to read (better would be to use either an array, or dictionary, tuple, or any key-value pair-like data structure. See my other implementations linked below).

The do-while loop goes forever unless ‘Q’ or ‘q’ (in most high-level languages, you have to explicitly account for case-sensitivity because ‘q’ is NOT same as ‘Q’ in terms of character code).

Challenge: Can you rewrite using simple graphical Windows application? Can you simulate a Windows app just as the JavaScript web application I showed earlier with input box and a button?

Look for implementation in other languages, including Python in my posts here.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top