I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

Magic 8-ball

From Rosetta Code
Task
Magic 8-ball
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Create Magic 8-Ball.


See details at:   Magic 8-Ball.


Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



8080 Assembly[edit]

bdos:		equ	5	; CP/M calls 
puts: equ 9
gets: equ 10
org 100h
lxi d,message ; Print message
mvi c,puts
call bdos
question: lxi d,prompt ; Ask for question
mvi c,puts
call bdos
lxi d,bufdef ; Read answer
mvi c,gets
call bdos
lxi d,newline ; Print newline
mvi c,puts
call bdos
lxi h,buf ; XOR the question w/ the RNG state
mvi b,20
xorouter: lxi d,xabcdat + 1
mvi c,3
xorinner: ldax d
xra m
stax d
inx d
inx h
dcr c
jnz xorinner
dcr b
jnz xorouter
getrnd: call xabcrand ; Generate random number <20
ani 1fh
cpi 20
jnc getrnd
inr a
mov b,a ; That is the number of the message
lxi h,responses ; Skip that many strings
mvi a,'$'
skipstring: cmp m
inx h
jnz skipstring
dcr b
jnz skipstring
xchg ; Print the chosen string
mvi c,puts
call bdos
jmp question ; Get another question
;; RNG to make it a little less predictable
xabcrand: lxi h,xabcdat
inr m  ; X++
mov a,m  ; X,
inx h  ;
xra m  ; ^ C,
inx h  ;
xra m  ; ^ A,
mov m,a  ; -> A
inx h
add m  ; + B,
mov m,a  ; -> B
rar  ; >>1
dcx h
xra m  ; ^ A,
dcx h
add m  ; + C
mov m,a  ; -> C
ret
;; Strings
message: db 'Magic 8 Ball$'
newline: db 13,10,'$'
prompt: db 13,10,13,10,'What is your question? '
;; The possible responses
responses: db '$It is certain$It is decidedly so$Without a doubt$'
db 'Yes, definitely$You may rely on it$As I see it, yes$'
db 'Most likely$Outlook good$Signs point to yes$Yes$'
db 'Reply hazy, try again$Ask again later$'
db 'Better not tell you now$Cannot predict now$'
db 'Concentrate and ask again$Don',39,'t bet on it$'
db 'My reply is no$My sources say no$Outlook not so good$'
db 'Very doubtful$'
;; Variables
bufdef: db 60,0 ; 60 = 20*3
buf: equ $ ; question will be XOR'ed with the RNG state
xabcdat: equ buf + 60 ; Point RNG data into uninitialized memory,
; to make it more exciting.
 

Ada[edit]

 
 
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Numerics.Discrete_Random;
 
 
procedure Main is
 
 
--Creation of type with all the possible answers
--
type Possible_Answers_Type is (It_Is_Certain, It_Is_Decidedly_So, Without_A_Doubt,
Yes_Definitely, You_May_Rely_On_It, As_I_See_It, Yes_Most_Likely,
Outlook_Good, Signs_Point_To_Yes, Yes_Reply_Hazy,
Try_Again, Ask_Again_Later, Better_Not_Tell_You_Now,
Cannot_Predict_Now, Concentrate_And_Ask_Again,
Dont_Bet_On_It, My_Reply_Is_No, My_Sources_Say_No,
Outlook_Not_So_Good, Very_Doubtful);
---------------------------------------------------------------------
 
 
-- Variable declaration
Answer  : Possible_Answers_Type := Possible_Answers_Type'First;
User_Question : String := " ";
 
-----------------------------------------------------------------------------
 
 
--Randomizer
--
package Random_Answer is new Ada.Numerics.Discrete_Random (Possible_Answers_Type);
use Random_Answer;
G : Generator;
 
begin
 
Reset (G); -- Starts the generator in a unique state in each run
 
--User get provides question
Put_Line ("Welcome."); New_Line;
 
Put_Line ("WARNING!!! Please remember that there's no need to shake your device for this program to work, and shaking your device could damage it");
New_Line;
 
Put_Line ("What's your question? ");
Get (Item => User_Question); New_Line;
 
 
--Output Answer
Answer := (Random (G)); --Assigns random answer to variable Answer
 
Put (Answer'Image); --Prints Answer
 
end Main;
 
 
Output:
Welcome.

WARNING!!!  Please remember that there's no need to shake your device for this program to work, and shaking your device could damage it

What's your question? 
Should I have an apple

MY_SOURCES_SAY_NO


ALGOL 68[edit]

BEGIN
[]STRING answers = ("It is certain.", "It is decidedly so.",
"Without a doubt.", "Yes - definitely.", "You may rely on it.",
"As I see it, yes.", "Most likely.", "Outlook good.",
"Yes.", "Signs point to yes.", "Reply hazy, try again.",
"Ask again later.", "Better not tell you now.", "Cannot predict now.",
"Concentrate and ask again.", "Don't count on it.", "My reply is no.",
"My sources say no.", "Outlook not so good.", "Very doubtful.");
DO
REF STRING question := LOC STRING;
print("Your question: ");
read((question, new line));
print((answers[ENTIER (random * UPB answers) + 1], new line))
OD
END

AutoHotkey[edit]

answers := [
(join
"It is certain", "It is decidedly so", "Without a doubt","Yes, definitely",
"You may rely on it", "As I see it, yes","Most likely", "Outlook good",
"Signs point to yes", "Yes","Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now","Concentrate and ask again",
"Don't bet on it","My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
)]
Ask:
InputBox, Question, Magic 8-Ball, Please ask your question or a blank line to quit.,,, 130
Random, rnd, 1, 20
if !question
ExitApp
MsgBox % answers[rnd]
gosub, Ask
return

AWK[edit]

 
# syntax: GAWK -f MAGIC_8-BALL.AWK
BEGIN {
# Ten answers are affirmative, five are non-committal, and five are negative.
arr[++i] = "It is certain"
arr[++i] = "It is decidedly so"
arr[++i] = "Without a doubt"
arr[++i] = "Yes, definitely"
arr[++i] = "You may rely on it"
arr[++i] = "As I see it, yes"
arr[++i] = "Most likely"
arr[++i] = "Outlook good"
arr[++i] = "Signs point to yes"
arr[++i] = "Yes"
arr[++i] = "Reply hazy, try again"
arr[++i] = "Ask again later"
arr[++i] = "Better not tell you now"
arr[++i] = "Cannot predict now"
arr[++i] = "Concentrate and ask again"
arr[++i] = "Don't bet on it"
arr[++i] = "My reply is no"
arr[++i] = "My sources say no"
arr[++i] = "Outlook not so good"
arr[++i] = "Very doubtful"
srand()
printf("Please enter your question or a blank line to quit.\n")
while (1) {
printf("\n? ")
getline ans
if (ans ~ /^ *$/) {
break
}
printf("%s\n",arr[int(rand()*i)+1])
}
exit(0)
}
 
Output:
Please enter your question or a blank line to quit.

? will you still love me tomorrow
Yes, definitely

?

C[edit]

Translation of: Kotlin
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main() {
char *question = NULL;
size_t len = 0;
ssize_t read;
const char* answers[20] = {
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
};
srand(time(NULL));
printf("Please enter your question or a blank line to quit.\n");
while (1) {
printf("\n? : ");
read = getline(&question, &len, stdin);
if (read < 2) break;
printf("\n%s\n", answers[rand() % 20]);
}
if (question) free(question);
return 0;
}
Output:

Sample session :

Please enter your question or a blank line to quit.

? : Will May win the next UK election?

It is certain

? : Do flying saucers really exist?

Signs point to yes

? : Will humans ever colonize Mars?

It is decidedly so

? : 

C++[edit]

#include <array>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
 
int main()
{
constexpr std::array<const char*, 20> answers = {
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."
};
 
std::string input;
std::srand(std::time(nullptr));
while (true) {
std::cout << "\n? : ";
std::getline(std::cin, input);
 
if (input.empty()) {
break;
}
 
std::cout << answers[std::rand() % answers.size()] << '\n';
}
}

C#[edit]

 
using System;
 
namespace newProg
{
 
class Program
{
static void Main(string[] args)
{
string[] answers =
{
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes – definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."
};
 
while (true)
{
Random rnd = new Random();
int result = rnd.Next(0, 19);
 
Console.WriteLine("Magic 8 Ball! Ask question and hit a key for the answer!");
 
string inp = Console.ReadLine();
 
Console.WriteLine(answers[result]);
 
}
}
}
}
 
 
 

Clojure[edit]

 
(def responses
["It is certain" "It is decidedly so" "Without a doubt"
"Yes, definitely" "You may rely on it" "As I see it, yes"
"Most likely" "Outlook good" "Signs point to yes" "Yes"
"Reply hazy, try again" "Ask again later"
"Better not tell you now" "Cannot predict now"
"Concentrate and ask again" "Don't bet on it"
"My reply is no" "My sources say no" "Outlook not so good"
"Very doubtful"])
 
(do
(println "Ask a question. ")
(read-line)
(println (rand-nth responses)))
 

Commodore BASIC[edit]

 
10 dim f$(20):for i=1 to 20:read f$(i):next
20 print chr$(147);chr$(14)
30 print "Press any key to reveal your fortune."
40 print:print "Press Q to quit.":print
50 fo=int(rnd(1)*20)+1:get k$:if k$="" then 50
60 if k$="q" then print "Good luck!":end
70 print "Your fortune reads:"
80 print spc(5);f$(fo):print
90 print "Again? (Y/N)"
100 get k$:if k$="" then 100
110 if k$="y" then goto 20
120 end
1000 data "It is certain.","It is decidedly so."
1010 data "Without a doubt.","Yes ??? definitely."
1020 data "You may rely on it.","As I see it, yes."
1030 data "Most likely.","Outlook good.","Yes."
1040 data "Signs point to yes.","Reply hazy, try again."
1050 data "Ask again later.","Better not tell you now."
1060 data "Cannot predict now.","Concentrate and ask again."
1070 data "Don't count on it.","My reply is no."
1080 data "My sources say no.","Outlook not so good."
1090 data "Very doubtful."
 

Factor[edit]

USING: io kernel random sequences ;
IN: rosetta-code.magic-8-ball
 
CONSTANT: phrases {
"It is certain" "It is decidedly so" "Without a doubt"
"Yes, definitely" "You may rely on it" "As I see it, yes"
"Most likely" "Outlook good" "Signs point to yes" "Yes"
"Reply hazy, try again" "Ask again later"
"Better not tell you now" "Cannot predict now"
"Concentrate and ask again" "Don't bet on it"
"My reply is no" "My sources say no" "Outlook not so good"
"Very doubtful"
}
 
"Please enter your question or a blank line to quit." print
 
[ "? : " write flush readln empty? [ f ]
[ phrases random print t ] if ] loop
Output:
Please enter your question or a blank line to quit.
? : Are there more than 10^57 grains of sand in the universe?
Yes
? : Are cats secretly alien spies?

Signs point to yes
? : Am I a genius?
Outlook not so good
? :

FreeBASIC[edit]

dim as string answer(0 to 19) = { "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes – definitely.",_
"You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.",_
"Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.",_
"Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.",_
"My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful." }
 
dim as string question
randomize timer
 
print "Q to quit."
do
input "What would you like to know? ", question
if ucase(question)="Q" then exit do
print answer(int(rnd*20))
print
loop

Forth[edit]

ANS/ISO FORTH, GNU FORTH
This example defines CASE: ;CASE that create a vector table. VECTORS compiles a specific number of execution vectors into memory from the data stack. Responses are created as executable routines that return their Execution token to the Forth Data Stack. The responses are retrieved from the data stack and compiled into a vector table, after which it is trivial for RANDOM to select any response.

\ magic eight ball Rosetta Code
INCLUDE RANDOM.FS
DECIMAL
: CASE: ( -- -7) CREATE  ;
: ;CASE ( n -- ) DOES> SWAP CELLS + @ EXECUTE ;
 
: VECTORS 0 DO , LOOP ;
 
:NONAME ." It is certain" ;
:NONAME ." It is decidedly so" ;
:NONAME ." Without a doubt" ;
:NONAME ." Yes, definitely" ;
:NONAME ." You may rely on it" ;
:NONAME ." As I see it, yes." ;
:NONAME ." Most likely" ;
:NONAME ." Outlook good" ;
:NONAME ." Signs point to yes." ;
:NONAME ." Yes." ;
:NONAME ." Reply hazy, try again" ;
:NONAME ." Ask again later" ;
:NONAME ." Better not tell you now" ;
:NONAME ." Cannot predict now" ;
:NONAME ." Concentrate and ask again" ;
:NONAME ." Don't bet on it" ;
:NONAME ." My reply is no"  ;
:NONAME ." My sources say no" ;
:NONAME ." Outlook not so good" ;
:NONAME ." Very doubtful" ;
 
CASE: MAGIC8BALL 20 VECTORS  ;CASE
 
: GO
CR ." Please enter your question or a blank line to quit."
BEGIN CR ." ? :" PAD 80 ACCEPT 0>
WHILE CR 19 RANDOM MAGIC8BALL CR
REPEAT ;
Test at the console
 ok
GO
Please enter your question or a blank line to quit.
? :AM I ALIVE
Very doubtful

? :CAN YOU PREDICT THE FUTURE
Outlook not so good

? :ARE YOU VALUABLE
Yes, definitely

? :CAN YOU TELL ME SOMETHING GOOD
Don't bet on it

? :

Go[edit]

Translation of: Kotlin
package main
 
import (
"bufio"
"bytes"
"fmt"
"log"
"math/rand"
"os"
"time"
)
 
func main() {
rand.Seed(time.Now().UnixNano())
answers := [...]string{
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful",
}
const prompt = "\n? : "
fmt.Print("Please enter your question or a blank line to quit.\n" + prompt)
sc := bufio.NewScanner(os.Stdin)
for sc.Scan() {
question := sc.Bytes()
question = bytes.TrimSpace(question)
if len(question) == 0 {
break
}
answer := answers[rand.Intn(len(answers))]
fmt.Printf("\n%s\n"+prompt, answer)
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
}
Output:
Please enter your question or a blank line to quit.

? : Will Trump win the next US election?

As I see it, yes

? : Is it true that we live in a multiverse?

Yes

? : Will the singularity occur before 2030?

My reply is no

? : 

Haskell[edit]

import           System.Random (getStdRandom, randomR)
import Control.Monad (forever)
 
answers :: [String]
answers =
[ "It is certain"
, "It is decidedly so"
, "Without a doubt"
, "Yes, definitely"
, "You may rely on it"
, "As I see it, yes"
, "Most likely"
, "Outlook good"
, "Signs point to yes"
, "Yes"
, "Reply hazy, try again"
, "Ask again later"
, "Better not tell you now"
, "Cannot predict now"
, "Concentrate and ask again"
, "Don't bet on it"
, "My reply is no"
, "My sources say no"
, "Outlook not so good"
, "Very doubtful"]
 
main :: IO ()
main = do
putStrLn "Hello. The Magic 8 Ball knows all. Type your question."
forever $ do
getLine
n <- getStdRandom (randomR (0, pred $ length answers))
putStrLn $ answers !! n

J[edit]

Any array should work as the possible answers for the left (x) argument to eight_ball .

 
NB. translated from awk
 
prompt=: [: 1!:1 [: 1: echo
 
ANSWERS=: [;._2'It is certain"It is decidedly so"Without a doubt"Yes, definitely"You may rely on it"As I see it, yes"Most likely"Outlook good"Signs point to yes"Yes"Reply hazy, try again"Ask again later"Better not tell you now"Cannot predict now"Concentrate and ask again"Don''t bet on it"My reply is no"My sources say no"Outlook not so good"Very doubtful"'
 
eight_ball=: ANSWERS&$: :(dyad define)
while. 0 < # prompt 'Please enter your question or a blank line to quit.' do.
echo ({~ [email protected]:#) x
end.
)
 
   eight_ball''
Please enter your question or a blank line to quit.
Will I finish on time?
Cannot predict now       
Please enter your question or a blank line to quit.
Will he?
My reply is no           
Please enter your question or a blank line to quit.

Java[edit]

 
import java.util.Random;
import java.util.Scanner;
 
public class MagicEightBall {
 
public static void main(String[] args) {
new MagicEightBall().run();
}
 
private static String[] ANSWERS = new String[] {"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.",
"You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
"Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
"Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful. "};
 
public void run() {
Random random = new Random();
System.out.printf("Hello. The Magic 8 Ball knows all. Type your question.%n%n");
try ( Scanner in = new Scanner(System.in); ) {
System.out.printf("? ");
while ( (in.nextLine()).length() > 0 ) {
System.out.printf("8 Ball Response:  %s%n", ANSWERS[random.nextInt(ANSWERS.length)]);
System.out.printf("? ");
}
}
System.out.printf("%n8 Ball Done. Bye.");
}
}
 
Output:
Hello.  The Magic 8 Ball knows all.  Type your question.

?  Is this task hard?
8 Ball Response:  Very doubtful. 
?  Can you code the Magic 8 Ball task?
8 Ball Response:  As I see it, yes.
?  Are the other Magic 8 Ball programs better?
8 Ball Response:  Don't count on it.
?  

8 Ball Done.  Bye.

JavaScript[edit]

 
//console
var answers = [ "It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"])
 
console.log("ASK ANY QUESTION TO THE MAGIC 8-BALL AND YOU SHALL RECEIVE AN ANSWER!")
 
for(;;){
var answer = prompt("question:")
console.log(answer)
console.log(answers[Math.floor(Math.random()*answers.length)]);
}
 
Output:
"ASK ANY QUESTION TO THE MAGIC 8-BALL AND YOU SHALL RECEIVE AN ANSWER!"

"Is this code going to work?"

"Most likely"

Julia[edit]

const responses = ["It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely",
"Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again",
"Ask again later", "Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it", "My reply is no",
"My sources say no", "Outlook not so good", "Very doubtful"]
 
while true
println("Ask a question (blank to exit):")
if !occursin(r"[a-zA-Z]", readline(stdin))
break
end
println(rand(responses))
end
 
Output:
Ask a question (blank to exit):
Will there be an eclipse tomorrow?
Outlook good
Ask a question (blank to exit):
Is that a fact?
Reply hazy, try again

Kotlin[edit]

// Version 1.2.40
 
import java.util.Random
 
fun main(args: Array<String>) {
val answers = listOf(
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
)
val rand = Random()
println("Please enter your question or a blank line to quit.")
while (true) {
print("\n? : ")
val question = readLine()!!
if (question.trim() == "") return
val answer = answers[rand.nextInt(20)]
println("\n$answer")
}
}
Output:

Sample session :

Please enter your question or a blank line to quit.

? : Will Trump win the next US election?

Outlook not so good

? : Is it true that we live in a multiverse?

It is certain

? : Will the singularity occur before 2030?

Reply hazy, try again

? : Will the singularity occur before 2030?

Signs point to yes

? : 

Liberty BASIC[edit]

data "It is certain","It is decidedly so","Without a doubt","Yes - definitely",_
"You may rely on it","As I see it, yes","Most likely","Outlook good","Yes",_
"Signs point to yes","Reply hazy, try again","Ask again later","Better not tell you now",_
"Cannot predict now","Concentrate and ask again","Don't count on it","My reply is no",_
"My sources say no","Outlook not so good","Very doubtful"
 
dim c$(20)
for a = 1 to 20
read b$
c$(a) = b$
next a
 
[loop]
input "Type your question: ";a$
if a$="" then end
d=int(rnd(1)*20)+1
print "Answer: ";c$(d)
goto [loop]
 
Output:

Sample session :

Type your question: Will you still love me tomorrow?
Answer: Ask again later
Type your question: Should I take an umbrella?
Answer: You may rely on it
Type your question:

Locomotive Basic[edit]

10 mode 2:defint a-z:randomize time
20 input "Your question (hit Return to quit)";i$
30 if i$="" then print "Goodbye!":end
40 q=1+19*rnd
50 on q gosub 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290
60 goto 20
100 print "It is certain":return
110 print "It is decidedly so":return
120 print "Without a doubt":return
130 print "Yes, definitely":return
140 print "You may rely on it":return
150 print "As I see it, yes":return
160 print "Most likely":return
170 print "Outlook good":return
180 print "Signs point to yes":return
190 print "Yes":return
200 print "Reply hazy, try again":return
210 print "Ask again later":return
220 print "Better not tell you now":return
230 print "Cannot predict now":return
240 print "Concentrate and ask again":return
250 print "Don't bet on it":return
260 print "My reply is no":return
270 print "My sources say no":return
280 print "Outlook not so good":return
290 print "Very doubtful":return

M2000 Interpreter[edit]

 
Module Magic.8.Ball {
answers=("It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful")
Print "Please enter your question or a blank line to quit."
{
Line Input A$
Print
A$=trim$(A$)
If A$="" Then Exit
Print Array$(answers, Random(0, 19))
Loop
}
}
Magic.8.Ball
 

min[edit]

Works with: min version 0.19.6
randomize   ; Seed the RNG with current timestamp.
 
(
"It is certain" "It is decidedly so" "Without a doubt"
"Yes, definitely" "You may rely on it" "As I see it, yes"
"Most likely" "Outlook good" "Signs point to yes" "Yes"
"Reply hazy, try again" "Ask again later"
"Better not tell you now" "Cannot predict now"
"Concentrate and ask again" "Don't bet on it"
"My reply is no" "My sources say no" "Outlook not so good"
"Very doubtful"
) =phrases
 
(phrases dup size pred random get puts!) :answer
 
(true) ("Ask a question" ask answer) while
Output:
Ask a question: Will concatenative programming catch on?
Outlook not so good
Ask a question: How about functional programming?
Concentrate and ask again
Ask a question: ^C

MiniScript[edit]

answers = ["It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"]
print "Ask your question and the Magic 8 Ball will give you the answer!"
input "What is your question?"
print answers[rnd * answers.len]
Output:
Ask your question and the Magic 8 Ball will give you the answer!
What is your question? Are we there yet?
Cannot predict now

ooRexx[edit]

 
/* REXX */
a=.array~of("It is certain", "It is decidedly so", "Without a doubt",,
"Yes, definitely", "You may rely on it", "As I see it, yes",,
"Most likely", "Outlook good", "Signs point to yes", "Yes",,
"Reply hazy, try again", "Ask again later",,
"Better not tell you now", "Cannot predict now",,
"Concentrate and ask again", "Don't bet on it",,
"My reply is no", "My sources say no", "Outlook not so good",,
"Very doubtful")
Do Forever
Say 'your question:'
Parse Pull q
If q='' Then Leave
Say a[random(1,20)]
Say ''
End
Output:
your question:
will it rain tonight
Concentrate and ask again

your question:
will it rain tonight
You may rely on it

your question:

Perl[edit]

@a = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely',
'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',
'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later',
'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',
"Don't bet on it", 'My reply is no', 'My sources say no', 'Outlook not so good',
'Very doubtful');
 
while () {
print 'Enter your question:';
last unless <> =~ /\w/;
print @a[int rand @a], "\n";
}

Phix[edit]

constant answers = {"As I see it, yes", "Ask again later", "You may rely on it",
"Without a doubt", "Don't bet on it", "Outlook not so good",
"Signs point to yes", "It is decidedly so", "It is certain",
"Better not tell you now", "My reply is no", "Outlook good",
"Concentrate and ask again", "Reply hazy, try again", "Yes",
"Most likely", "Cannot predict now", "My sources say maybe",
"My sources say no", "Yes, definitely", "Yes, probably not",
"Very doubtful", "Your question has already been answered"}
 
string s = prompt_string("Please enter your question or a blank line to quit:")
if s!="" then printf(1,"%s\n",{answers[rand(length(answers))]}) end if

PHP[edit]

CLI[edit]

<?php
 
$fortunes = array(
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes, definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Signs point to yes",
"Yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't bet on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"
);
 
/*
* Prompt the user at the CLI for the command
*/

function cli_prompt( $prompt='> ', $default=false ) {
 
// keep asking until a non-empty response is given
do {
// display the prompt
echo $prompt;
 
// read input and remove CRLF
$cmd = chop( fgets( STDIN ) );
 
} while ( empty( $default ) and empty( $cmd ) );
 
return $cmd ?: $default;
 
}
 
$question = cli_prompt( 'What is your question? ' );
 
echo 'Q: ', $question, PHP_EOL;
 
echo 'A: ', $fortunes[ array_rand( $fortunes ) ], PHP_EOL;
 
Output:
$ php 8ball.php
What is your question? Are we together forever and never to part?
Q: Are we together forever and never to part?
A: Without a doubt

$ php 8ball.php
What is your question? Are we together forever we two?
Q: Are we together forever we two?
A: Don't bet on it

$ php 8ball.php
What is your question? Will I move heaven and earth to be together forever with you?
Q: Will I move heaven and earth to be together forever with you?
A: It is certain

Python[edit]

import random
 
s = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely',
'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',
'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later',
'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',
"Don't bet on it", 'My reply is no', 'My sources say no', 'Outlook not so good',
'Very doubtful')
 
q_and_a = {}
 
while True:
question = input('Ask your question:')
if len(question) == 0: break
 
answer = random.choice(s)
 
if question in q_and_a:
print('Your question has already been answered')
else:
q_and_a[question] = answer
print(answer)
Output:
Ask your question:Is python the best language ever?
Better not tell you now
Ask your question:You are really not helping your case here.
Very doubtful
Ask your question:So, no?
Signs point to yes
Ask your question:So, no?
Your question has already been answered
Ask your question:

Racket[edit]

(define eight-ball-responses
(list "It is certain" "It is decidedly so" "Without a doubt" "Yes definitely" "You may rely on it"
"As I see it, yes" "Most likely" "Outlook good" "Yes" "Signs point to yes"
"Reply hazy try again" "Ask again later" "Better not tell you now" "Cannot predict now"
"Concentrate and ask again"
"Don't count on it" "My reply is no" "My sources say no" "Outlook not so good"
"Very doubtful"))
 
(define ((answer-picker answers)) (sequence-ref answers (random (sequence-length answers))))
 
(define magic-eightball (answer-picker eight-ball-responses))
 
(module+ main
(let loop ()
(display "What do you want to know\n?")
(read-line)
(displayln (magic-eightball))
(loop)))
Output:

We'll see if it's right.

Raku[edit]

(formerly Perl 6)

Works with: Rakudo version 2018.03
put 'Please enter your question or a blank line to quit.';
 
["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely",
"You may rely on it", "As I see it, yes", "Most likely", "Outlook good",
"Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now", "Concentrate and ask again",
"Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"].roll.put while prompt('? : ').chars;

Output very similar to C, Kotlin and zkl examples.

REXX[edit]

version 1[edit]

 
/* REXX */
Call mk_a "It is certain", "It is decidedly so", "Without a doubt",,
"Yes, definitely", "You may rely on it", "As I see it, yes",,
"Most likely", "Outlook good", "Signs point to yes", "Yes",,
"Reply hazy, try again", "Ask again later",,
"Better not tell you now", "Cannot predict now",,
"Concentrate and ask again", "Don't bet on it",,
"My reply is no", "My sources say no", "Outlook not so good",,
"Very doubtful"
Do Forever
Say 'your question:'
Parse Pull q
If q='' Then Leave
z=random(1,a.0)
Say a.z
Say ''
End
Exit
mk_a:
a.0=arg()
Do i=1 To a.0
a.i=arg(i)
End
Return
 
Output:
your question:
will it rain tonight
My reply is no

your question:
will it rain tonight
Signs point to yes

your question:

version 2[edit]

This REXX version is modeled after the   Ring   entry.

The method used is to translate all blanks to pseudo-blanks, then extract and show a random phrase   (after translating the pseudo-blanks back to blanks).

Also, this REXX version appends a period to the phrase as per the (linked) documentation.

/*REXX program simulates the  "shaking"  of a  "Magic 8-ball"  and displaying an answer.*/
$="It is certain ÷It is decidedly so ÷Without a doubt÷Yes, definitely÷Signs point to yes",
"÷You may rely on it÷ As I see it, yes÷My reply is no÷Outlook good÷Outlook not so good",
"÷Yes÷Ask again later÷Better not tell you now÷Cannot predict now÷Reply hazy, try again",
"÷Concentrate and ask again÷Don't bet on it÷Most likely÷My sources say no÷Very doubtful"
 
say space(translate(word(translate(translate($, '┼', " "), , '÷'), random(1, 20)), ,"┼")).
output   when invoking the REXX program:
Reply hazy, try again.

Ring[edit]

 
# Project : Magic 8-Ball
 
answers = ["It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"]
index = random(len(answers)-1)+1
see answers[index] + nl
 

Output:

It is certain

Rust[edit]

Library: rand
extern crate rand;
 
use rand::prelude::*;
use std::io;
 
fn main() {
let answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes, definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Signs point to yes",
"Yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't bet on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
];
let mut rng = rand::thread_rng();
let mut input_line = String::new();
 
println!("Please enter your question or a blank line to quit.\n");
loop {
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
if input_line.trim() == "" {
break;
}
println!("{}\n", answers.choose(&mut rng).unwrap());
input_line.clear();
}
}
Output:
Will Keanu Reeves die in my life time?
Yes, definitely

Should I warn him?
Cannot predict now

Can I extend my life time to extend his?
Most likely

Tiny BASIC[edit]

10 PRINT "Concentrate hard on your question, then tell me your favorite number."
20 INPUT N
30 REM in lieu of a random number generator
40 IF N<0 THEN LET N=-N
50 IF N<20 THEN GOTO 1000+N*10
60 LET N=N-20
70 GOTO 50
1000 PRINT "It is certain."
1005 END
1010 PRINT "It is decidedly so."
1015 END
1020 PRINT "Without a doubt."
1025 END
1030 PRINT "Yes - definitely."
1035 END
1040 PRINT "You may rely on it."
1045 END
1050 PRINT "As I see it, yes."
1055 END
1060 PRINT "Most likely."
1065 END
1070 PRINT "Outlook good."
1075 END
1080 PRINT "Yes."
1085 END
1090 PRINT "Signs point to yes."
1095 END
1100 PRINT "Reply hazy, try again."
1105 END
1110 PRINT "Ask again later."
1115 END
1120 PRINT "Better not tell you now."
1125 END
1130 PRINT "Cannot predict now."
1135 END
1140 PRINT "Concentrate and ask again."
1145 END
1150 PRINT "Don't count on it."
1155 END
1160 PRINT "My reply is no."
1165 END
1170 PRINT "My sources say no."
1175 END
1180 PRINT "Outlook not so good."
1185 END
1190 PRINT "Very doubtful."

Wren[edit]

Translation of: Kotlin
import "random" for Random
import "io" for Stdin, Stdout
 
var answers = [
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
]
var rand = Random.new()
System.print("Please enter your question or a blank line to quit.")
while (true) {
System.write("\n? : ")
Stdout.flush()
var question = Stdin.readLine()
if (question.trim() == "") return
var answer = answers[rand.int(20)]
System.print("\n%(answer)")
}
Output:

Sample session:

Please enter your question or a blank line to quit.

? : Will Trump win the next US election?

My sources say no

? : Is it true that we live in a multiverse?

Yes, definitely

? : Will the singularity occur before 2030?

Without a doubt

? : 

zkl[edit]

Translation of: Raku
answers:=T(
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
);
println("Please enter your question or a blank line to quit.");
while(ask("? : ")){ println(answers[(0).random(answers.len())]) }
Output:
lease enter your question or a blank line to quit.
? : will it rain today 
It is certain
? : where is Turkey
Yes
? : what is the price of milk
It is decidedly so
? : who is Elton John
Most likely
? :