Mini Project: The Magic 8-Ball

Grade 4, page 10 of 11. A one-minute read.

Remember the random number homework from Grade 3? Let's use it to build a fortune teller. Ask it a yes-or-no question and it'll give you a (completely random, totally unscientific) answer.

magic8ball.js
const question = "Will I become a great programmer?";
const roll = Math.floor(Math.random() * 6) + 1;
let answer;

switch (roll) {
  case 1:
    answer = "It is certain. ✨";
    break;
  case 2:
    answer = "Ask again after a snack. 🍪";
    break;
  case 3:
    answer = "Signs point to yes. 👉";
    break;
  case 4:
    answer = "My sources say no. 🙅";
    break;
  case 5:
    answer = "Definitely, if you finish your homework. 📚";
    break;
  default:
    answer = "The spirits are confused. Try again. 👻";
}

console.log(`🎱 You asked: "${question}"`);
console.log(`🎱 The Magic 8-Ball says: ${answer}`);

Output

🎱 You asked: "Will I become a great programmer?"
🎱 The Magic 8-Ball says: Signs point to yes. 👉

(For the record, the real answer is yes. You don't need a magic ball to know that.)

Excellent work! Your programs can now make decisions. In Grade 5, we'll teach them to do something computers are incredibly good at, and humans find incredibly boring: repeating things.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning