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



11l

Translation of: Python
V 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’]

Set[String] qs

L
   V question = input(‘Ask your question:’)
   I question.empty
      L.break

   V answer = random:choice(s)

   I question C qs
      print(‘Your question has already been answered’)
   E
      qs.add(question)
      print(answer)

8080 Assembly

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.

8086 Assembly

This procedure when run displays a random Magic 8-Ball phrase (the list was shortened to 16 different phrases to simplify the random number generation) and outputs it to the console, then exits back to MS-DOS. A 32 bit Xorshift routine was used to create the random numbers, and it was seeded using the computer's current time.

.model small
.stack 1024

.data
UserRam BYTE 256 DUP(0)
xorshift32_state_lo equ UserRam
xorshift32_state_hi equ UserRam+2

Ans0 byte "It is certain.",0
Ans1 byte "It is decidedly so.",0
Ans2 byte "Signs point to yes.",0
Ans3 byte "You can rely on it.",0
Ans4 byte "Most likely.",0
Ans5 byte "Cannot predict now.",0
Ans6 byte "Reply hazy, try again.",0
Ans7 byte "Outlook not so good.",0
Ans8 byte "My sources say no.",0
Ans9 byte "Very doubtful.",0
AnsA byte "Without a doubt.",0
AnsB byte "Outlook good.",0
AnsC byte "Ask again later.",0
AnsD byte "Better not tell you now.",0
AnsE byte "Don't count on it.",0
AnsF byte "Yes.",0

AnswerLookup word Ans0,Ans1,Ans2,Ans3,Ans4,Ans5,Ans6,Ans7
	     word Ans8,Ans9,AnsA,AnsB,AnsC,AnsD,AnsE,AnsF
.code

start:

	mov ax,@data
	mov ds,ax
	
	mov ax,@code
	mov es,ax

	
	CLD	;have LODSB,MOVSB,STOSB,etc. auto-increment
	
	mov ax,03h
	int 10h        ;sets video mode to MS-DOS text mode. Which the program is already in, so this just clears the screen.
	
	mov ah,2Ch
	int 21h         ;returns hour:minute in cx, second:100ths of second in dx
        mov word ptr [ds:xorshift32_state_lo],dx
        mov word ptr [ds:xorshift32_state_hi],cx
	
	call doXorshift32 ;uses the above memory locations as input. Do it three times just to mix it up some more
	call doXorshift32
	call doXorshift32
	
	mov ax,word ptr[ds:xorshift32_state_lo] ;get the random output from the RNG
	and al,0Fh		
	;keep only the bottom nibble of al, there are only 16 possible messages.
	mov bx,offset AnswerLookup
	call XLATW
	;translates AX using a table of words as a lookup table.
	mov si,ax         ;use this looked-up value as the source index for our text.
	call PrintString  ;print to the screen
	
	mov ax,4C00h
	int 21h        ;return to DOS

XLATW:
;input: ds:bx = the table you wish to look up
;AL= the raw index into this table as if it were byte data.
;So don't left shift prior to calling this.
;AH is destroyed.
		SHL AL,1
		mov ah,al	;copy AL to AH
		XLAT		;returns low byte in al
		inc ah
		xchg al,ah	;XLAT only works with AL
		XLAT		;returns high byte in al (old ah)
		xchg al,ah
		;now the word is loaded into ax, big-endian.
		ret
Output:

This is the output after three separate runs of the program.

Cannot predict now.
Signs point to yes.
Better not tell you now.

Action!

PROC Main()
  DEFINE PTR="CARD"
  DEFINE COUNT="20"
  CHAR ARRAY s(256)
  PTR ARRAY a(COUNT)
  BYTE i

  a(0)="It is certain."
  a(1)="It is decidedly so."
  a(2)="Without a doubt."
  a(3)="Yes - definitely."
  a(4)="You may rely on it."
  a(5)="As I see it, yes."
  a(6)="Most likely."
  a(7)="Outlook good."
  a(8)="Yes."
  a(9)="Signs point to yes."
  a(10)="Reply hazy, try again."
  a(11)="Ask again later."
  a(12)="Better not tell you now."
  a(13)="Cannot predict now."
  a(14)="Concentrate and ask again."
  a(15)="Don't count on it."
  a(16)="My reply is no."
  a(17)="My sources say no."
  a(18)="Outlook not so good."
  a(19)="Very doubtful."

  DO
    PrintE("Enter your question or blank to exit:")
    InputS(s)
    IF s(0)=0 THEN
      EXIT
    FI
    i=Rand(COUNT)
    PrintE(a(i))
    PutE()
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

Enter your question or blank to exit:
Do you know me?
Signs point to yes.

Enter your question or blank to exit:
Is Action! your favorite language?
Yes.

Enter your question or blank to exit:
Is Atari the best 8-bit computer?
Very doubtful.

Enter your question or blank to exit:
Are you kidding me?
Concentrate and ask again.

Ada

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

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

AppleScript

 set the answers to {"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"}

display dialog some item of the answers

Applesoft BASIC

Translation of: Commodore BASIC
 0  DIM F$(19): FOR I = 0 TO 19: READ F$(I): NEXT :M$ =  CHR$ (13): DEF  FN U(K) = K - 32 * (K > 95): FOR Q = 0 TO 1: HOME : PRINT M$" PRESS ANY KEY TO REVEAL YOUR FORTUNE."M$M$" PRESS Q TO QUIT."M$M$" ";:FO =  INT ( RND (1) * 20): GET K$
 1 K$ =  CHR$ ( FN U( ASC (K$))):Q = K$ = "Q": IF  NOT Q THEN  HOME : PRINT M$" YOUR FORTUNE READS:"M$M$ SPC( 5);F$(FO)M$M$" AGAIN? (Y/N) ";: GET K$:K$ =  CHR$ ( FN U( ASC (K$))):Q = K$ <  > "Y"
 2  NEXT Q: 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."
 3  DATA "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."

Arturo

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"
]

while ø [
    input "Ask a question: "
    print sample answers
]
Output:
Ask a question: Do you believe it's gonna rain today?
It is decidedly so
Ask a question: Really?
You may rely on it

AutoHotkey

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

# 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

?


BASIC

BASIC256

Translation of: QBasic
dim answer$(20)
answer$[0] = "It is certain."
answer$[1] = "It is decidedly so."
answer$[2] = "Without a doubt."
answer$[3] = "Yes - definitely."
answer$[4] = "You may rely on it."
answer$[5] = "As I see it, yes."
answer$[6] = "Most likely."
answer$[7] = "Outlook good."
answer$[8] = "Yes."
answer$[9] = "Signs point to yes."
answer$[10] = "Reply hazy, try again."
answer$[11] = "Ask again later."
answer$[12] = "Better not tell you now."
answer$[13] = "Cannot predict now."
answer$[14] = "Concentrate and ask again."
answer$[15] = "Don't count on it."
answer$[16] = "My reply is no."
answer$[17] = "My sources say no."
answer$[18] = "Outlook not so good."
answer$[19] = "Very doubtful."

print "Q to quit."
while True
	input string "What would you like to know? ", question$
	if upper(question$) = "Q" then exit while
	print answer$[int(rand * answer$[?])]
	print
end while
end

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
Translation of: Commodore BASIC
100 cls
110 data "It is certain.","It is decidedly so."
120 data "Without a doubt.","Yes - definitely."
130 data "You may rely on it.","As I see it, yes."
140 data "Most likely.","Outlook good."
150 data "Yes.","Signs point to yes."
160 data "Reply hazy, try again.","Ask again later."
170 data "Better not tell you now.","Cannot predict now."
180 data "Concentrate and ask again.","Don't count on it."
190 data "My reply is no.","My sources say no."
200 data "Outlook not so good.","Very doubtful."
210 dim m8ball$(20)
220 for i = 0 to 19
230   read m8ball$(i)
240 next i
250 randomize timer
260 input "What would you like to know? ",q$
270 print m8ball$(int(rnd(20)))
280 end

IS-BASIC

100 PROGRAM "Magic8.bas"
110 RANDOMIZE 
120 STRING ANSWER$(1 TO 20)*26
130 FOR I=1 TO 20
140   READ ANSWER$(I)
150 NEXT 
160 CLEAR SCREEN
170 PRINT "Magic 8-ball":PRINT "Q to quit.":PRINT 
180 DO 
190   INPUT PROMPT "What would you like to know? ":QUESTION$
200   IF LCASE$(QUESTION$)="q" THEN EXIT DO
210   PRINT ANSWER$(RND(20)+1):PRINT 
220 LOOP 
230 DATA It is certain.,It is decidedly so.,Without a doubt.
240 DATA Yes - definitely.,You may rely on it.,"As I see it, yes."
250 DATA Most likely.,Outlook good.,Yes.
260 DATA Signs point to yes.,"Reply hazy, try again.",Ask again later.
270 DATA Better not tell you now.,Cannot predict now.,Concentrate and ask again.
280 DATA Don't count on it.,My reply is no.,My sources say no.
290 DATA Outlook not so good.,Very doubtful.

MSX Basic

Works with: MSX BASIC version any
Translation of: Commodore BASIC
100 CLS
110 DATA "It is certain.","It is decidedly so."
120 DATA "Without a doubt.","Yes - definitely."
130 DATA "You may rely on it.","As I see it, yes."
140 DATA "Most likely.","Outlook good."
150 DATA "Yes.","Signs point to yes."
160 DATA "Reply hazy, try again.","Ask again later."
170 DATA "Better not tell you now.","Cannot predict now."
180 DATA "Concentrate and ask again.","Don't count on it."
190 DATA "My reply is no.","My sources say no."
200 DATA "Outlook not so good.","Very doubtful."
210 DIM m$(20)
220 FOR i = 0 TO 19
230   READ m$(i)
240 NEXT i
260 INPUT "What would you like to know? "; q$
270 PRINT m$(INT(RND(20)))
280 END

QBasic

Works with: QBasic
Works with: QuickBasic version 4.5
DIM answer$(19)
FOR i = 0 TO UBOUND(answer$): READ answer$(i): NEXT i
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 * UBOUND(answer$)))
    PRINT
LOOP
END

DATA "It is certain.","It is decidedly so."
DATA "Without a doubt.","Yes – definitely."
DATA "You may rely on it.","As I see it, yes."
DATA "Most likely.","Outlook good.","Yes."
DATA "Signs point to yes.","Reply hazy, try again."
DATA "Ask again later.","Better not tell you now."
DATA "Cannot predict now.","Concentrate and ask again."
DATA "Don't count on it.","My reply is no."
DATA "My sources say no.","Outlook not so good."
DATA "Very doubtful."

Quite BASIC

The MSX Basic solution works without any changes.

True BASIC

Translation of: QBasic
DIM answer$(20)
FOR i = 1 to ubound(answer$)
    READ answer$(i)
NEXT i
DATA "It is certain.", "It is decidedly so."
DATA "Without a doubt.", "Yes – definitely."
DATA "You may rely on it.", "As I see it, yes."
DATA "Most likely.", "Outlook good.", "Yes."
DATA "Signs point to yes.", "Reply hazy, try again."
DATA "Ask again later.", "Better not tell you now."
DATA "Cannot predict now.", "Concentrate and ask again."
DATA "Don't count on it.", "My reply is no."
DATA "My sources say no.", "Outlook not so good."
DATA "Very doubtful."

RANDOMIZE
PRINT "Q to quit."
DO
   INPUT prompt "What would you like to know? ": question$
   IF ucase$(question$) = "Q" then EXIT DO
   PRINT answer$(int(rnd*ubound(answer$)))
   PRINT
LOOP
END

Yabasic

Translation of: QBasic
dim answer$(19)
for i = 0 to arraysize(answer$(),1): read answer$(i): next i

print "Q to quit."
do
    input "What would you like to know? " question$
    if upper$(question$) = "Q" then end : fi
    print answer$(int(ran(arraysize(answer$(),1))))
    print
loop

data "It is certain.","It is decidedly so."
data "Without a doubt.","Yes – definitely."
data "You may rely on it.","As I see it, yes."
data "Most likely.","Outlook good.","Yes."
data "Signs point to yes.","Reply hazy, try again."
data "Ask again later.","Better not tell you now."
data "Cannot predict now.","Concentrate and ask again."
data "Don//t count on it.","My reply is no."
data "My sources say no.","Outlook not so good."
data "Very doubtful."


C

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++

#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#

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]);

            }
        }
    }
}

CFEngine

#!/var/cfengine/bin/cf-agent --no-lock
bundle agent __main__
{
  methods: "rosettacode_org:magic_8_ball";
}
body file control
{
      namespace => "rosettacode_org";
}
bundle agent magic_8_ball
{
  vars:
      "_responses"
        slist => {
                   "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",
        };
      "_selected_response"
        int => randomint( 0, length( _responses) ),
        unless => isvariable( "$(this.namespace):$(this.promiser)" );

      "_consideration_time"
        int => randomint( 3, 5),
        unless => isvariable( "$(this.namespace):$(this.promiser)" );

  commands:
      "/bin/sleep $(_consideration_time)"
        inform => "false",
        handle => "consider",
        depends_on => { "think" },
        comment => "This magic 8 ball takes a few seconds to consider the answer
                    after you bring your question to mind.";

  reports:
      "Think about your question ..."
        handle => "think";

      "Response: $(with)"
        with => nth( _responses, $(_selected_response) ),
        depends_on => { "consider" };
}

See https://docs.cfengine.com/docs/master/examples.html for a more complete example and introduction.

Clojure

(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)))

CMake

CMAKE_MINIMUM_REQUIRED(VERSION 3.6)

PROJECT(EightBall)

SET(CMAKE_DISABLE_SOURCE_CHANGES ON)
SET(CMAKE_DISABLE_IN_SOURCE_BUILD ON)

LIST(APPEND RESPONSES "It is certain." "It is decidedly so." "Without a doubt.")
LIST(APPEND RESPONSES "Yes - definitely." "You may rely on it.")
LIST(APPEND RESPONSES "As I see it yes." "Most likely." "Outlook good.")
LIST(APPEND RESPONSES "Yes." "Signs point to yes." "Reply hazy try again.")
LIST(APPEND RESPONSES "Ask again later." "Better not tell you now.")
LIST(APPEND RESPONSES "Cannot predict now." "Concentrate and ask again.")
LIST(APPEND RESPONSES "Don't count on it." "My reply is no.")
LIST(APPEND RESPONSES "My sources say no." "Outlook not so good." "Very doubtful.")

FUNCTION(RANDOM_RESPONSE)
    STRING(RANDOM LENGTH 1 ALPHABET 01 TENS)
    STRING(RANDOM LENGTH 1 ALPHABET 0123456789 UNITS)
    MATH(EXPR INDEX "${TENS}${UNITS}")
    LIST(GET RESPONSES ${INDEX} RESPONSE)
    MESSAGE(STATUS "Question: ${QUESTION}")
    MESSAGE(STATUS "Response: ${RESPONSE}")
ENDFUNCTION(RANDOM_RESPONSE)

OPTION(QUESTION "User's input question" "")

MESSAGE("===================== 8 Ball =====================")
IF(NOT QUESTION)
    MESSAGE(STATUS "Welcome to 8 ball! Please provide a question ")
    MESSAGE(STATUS "using the flag -DQUESTION=\"my question\"")
ELSE()
    RANDOM_RESPONSE()
ENDIF()
MESSAGE("==================================================")


ADD_CUSTOM_TARGET(${PROJECT_NAME} ALL)

No question specified:

$ cmake -H. -Bbuild
-- The C compiler identification is GNU 8.3.0
-- The CXX compiler identification is GNU 8.3.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
===================== 8 Ball =====================
-- Welcome to 8 ball! Please provide a question 
-- using the flag -DQUESTION="my question"
==================================================
-- Configuring done
-- Generating done

With question then provided as an option:

cmake -H. -Bbuild -DQUESTION="Am I going to be famous?"
===================== 8 Ball =====================
-- Question: Am I going to be famous?
-- Response: Reply hazy try again.
==================================================
-- Configuring done
-- Generating done

COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. 8BALL.
       AUTHOR. Bill Gunshannon 
       INSTALLATION.  
       DATE-WRITTEN. 12 March 2024 
      ************************************************************
      ** Program Abstract:
      **   Just ask the Magic 8 Ball and all will be revealed.
      ************************************************************
       
       ENVIRONMENT DIVISION.
       
       DATA DIVISION.
       
       WORKING-STORAGE SECTION.

       01  ANSWER-TABLE.
               10  ANSWER01   PIC X(40) 
	   VALUE "As I see it, yes                        ".
               10  ANSWER02   PIC X(40) 
	   VALUE "Ask again later                         ".
               10  ANSWER03   PIC X(40) 
	   VALUE "Better not tell you now                 ".
               10  ANSWER04   PIC X(40) 
	   VALUE "Cannot predict now                      ".
               10  ANSWER05   PIC X(40) 
	   VALUE "Concentrate and ask again               ".
               10  ANSWER06   PIC X(40) 
	   VALUE "Don't bet on it                         ".
               10  ANSWER07   PIC X(40) 
	   VALUE "It is certain                           ".
               10  ANSWER08   PIC X(40) 
	   VALUE "It is decidedly so                      ".
               10  ANSWER09   PIC X(40) 
	   VALUE "Most likely                             ".
               10  ANSWER10   PIC X(40) 
	   VALUE "My reply is no                          ".
               10  ANSWER11   PIC X(40) 
	   VALUE "My sources say maybe                    ".
               10  ANSWER12   PIC X(40) 
	   VALUE "My sources say no                       ".
               10  ANSWER13   PIC X(40) 
	   VALUE "Outlook good                            ".
               10  ANSWER14   PIC X(40) 
	   VALUE "Outlook not so good                     ".
               10  ANSWER15   PIC X(40) 
	   VALUE "Reply hazy, try again                   ".
               10  ANSWER16   PIC X(40) 
	   VALUE "Signs point to yes                      ".
               10  ANSWER17   PIC X(40) 
	   VALUE "Very doubtful                           ".
               10  ANSWER18   PIC X(40) 
	   VALUE "Without a doubt                         ".
               10  ANSWER19   PIC X(40) 
	   VALUE "Yes                                     ".
               10  ANSWER20   PIC X(40) 
	   VALUE "Yes, definitely                         ".
               10  ANSWER21   PIC X(40) 
	   VALUE "Yes, probably not                       ".
               10  ANSWER22   PIC X(40) 
	   VALUE "You may rely on it                      ".
               10  ANSWER23   PIC X(40) 
	   VALUE "Your question has already been answered ".
       01  PRINT-ANSWER  REDEFINES ANSWER-TABLE OCCURS 23 TIMES.
               10 THE-BALL-SPEAKS     PIC X(40). 

       01  RND         PIC 99999.
       01  QUESTION    PIC X(72).
       01  GREETING    PIC X(30)
           VALUE  "Ask and all will be revealed!!".
       
       
       PROCEDURE DIVISION.
       
       Main-Program.
           DISPLAY GREETING.
           ACCEPT QUESTION.
           MOVE FUNCTION CURRENT-DATE(1:16) TO RND.
            PERFORM 8-BALL.

           STOP RUN.

       8-BALL.
             COMPUTE RND =  
                 FUNCTION RANDOM(RND) * 11111.
             DISPLAY PRINT-ANSWER(FUNCTION MOD(RND, 23)).
       
       
       END-PROGRAM.

Commodore BASIC

10 dim f$(19):for i=0 to 19: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):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."

Craft Basic

title "Magic 8 Ball"

resize 0, 0, 340, 150
center

bgcolor 0, 0, 255
cls graphics

formid 1
formtext "Think of a question and select the magic button."
staticform 10, 10, 310, 20
bgcolor 0, 0, 0
fgcolor 255, 0, 255
colorform

formid 2
formtext "Magic Button"
buttonform 115, 50, 100, 20
bgcolor 255, 0, 0
fgcolor 0, 0, 255
colorform

do


	if forms = 2 then

		gosub magicbutton

	endif

	button k, 27

	wait

loop k = 0

end

sub magicbutton

	let r = int(rnd * 20) + 1

	if r = 1 then

		alert "It is certain."

	endif

	if r = 2 then

		alert "It is decidedly so."

	endif

	if r = 3 then

		alert "Without a doubt."

	endif

	if r = 4 then

		alert "Yes – definitely."

	endif

	if r = 5 then

		alert "You may rely on it."

	endif

	if r = 6 then

		alert "As I see it", comma, " yes."

	endif

	if r = 7 then

		alert "Most likely."

	endif

	if r = 8 then

		alert "Outlook good."

	endif

	if r = 9 then

		alert "Yes."

	endif

	if r = 10 then

		alert "Signs point to yes."

	endif

	if r = 11 then

		alert "Reply hazy", comma, " try again."

	endif

	if r = 12 then

		alert "Ask again later."

	endif

	if r = 13 then

		alert "Better not tell you now."

	endif

	if r = 14 then

		alert "Cannot predict now."

	endif

	if r = 15 then

		alert "Concentrate and ask again."

	endif

	if r = 16 then

		alert "Don't count on it."

	endif

	if r = 17 then

		alert "My reply is no."

	endif

	if r = 18 then

		alert "My sources say no."

	endif

	if r = 19 then

		alert "Outlook not so good."

	endif

	if r = 20 then

		alert "Very doubtful."

	endif

return

D

import std.random, std.stdio, std.string;

const string[] 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"];

void main()
{
    string question = "";
    auto rnd = Random(unpredictableSeed);
    int index = -1;

    writeln("Welcome to 8 ball! Please enter your question to ");
    write("find the answers you seek.");
    write("Type 'quit' to exit.", "\n\n"); 

    while(true)
    {
        write("Question: ");
        question = stdin.readln();
        if(strip(question) == "quit")
        {
            break;
        }
        write("Response: ");
        index = uniform(0, 20, rnd);
        write(responses[index], "\n\n");
    }
}

Output:

Welcome to 8 ball! Please enter your question to find the answers you seek.
Type 'quit' to exit.

Question: Am I rich?
Response: Without a doubt

Delphi

Library: windows
Translation of: C#
program Magic_8_ball;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  windows;

// https://stackoverflow.com/questions/29794559/delphi-console-xe7-clearscreen
procedure ClearScreen;
var
  stdout: THandle;
  csbi: TConsoleScreenBufferInfo;
  ConsoleSize: DWORD;
  NumWritten: DWORD;
  Origin: TCoord;
begin
  stdout := GetStdHandle(STD_OUTPUT_HANDLE);
  Win32Check(stdout <> INVALID_HANDLE_VALUE);
  Win32Check(GetConsoleScreenBufferInfo(stdout, csbi));
  ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y;
  Origin.X := 0;
  Origin.Y := 0;
  Win32Check(FillConsoleOutputCharacter(stdout, ' ', ConsoleSize, Origin, NumWritten));
  Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize,
    Origin, NumWritten));
  Win32Check(SetConsoleCursorPosition(stdout, Origin));
end;

const
  answers: array[0..19] of 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.');

begin
  Randomize;
  while True do
  begin
    writeln('Magic 8 Ball! Ask question and hit ENTER key for the answer!');
    readln;
    ClearScreen;
    writeln(answers[Random(length(answers))], #10#10#10);
    writeln('(Hit ENTER key to ask again)');
    readln;
    ClearScreen;
  end;
end.
Output:
Magic 8 Ball! Ask question and hit ENTER key for the answer!
Reply hazy, try again.



(Hit ENTER key to ask again)

EasyLang

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 "q to quit."
repeat
   print "What would you like to know? "
   q$ = input
   until q$ = "q"
   print answers$[randint len answers$[]]
.

Factor

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

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

FOCAL

Works with: FOCAL version for 6502 processors, string handling may be different in PDP-8/11-type flavors.

Template:Based on the BASIC versions

1.09 S FRAN(-1);C randomize
1.10 S FISL(80,A$);C set length to 80 char.
1.20 T !"Magic 8-Ball (Q to quit)"!!
1.30 T "What would you like to know?"!
1.40 S FSTI(80,A$(0),13);C input from console to A$, CR delimited
1.42 S Z=A$(0);I (Z-81) , 50.1;C Capital Q, if first char = then branch
1.44 S Z=A$(0);I (Z-113) , 50.1;C lowercase q, if first char = then branch

1.50 T !
1.60 S R=FINT(FRAN(0)*20+1);C get a random integer 1-20
1.70 D R*2;C 'do' calculated response subroutine
1.80 T !!"What else would you like to know?"!;G 1.4;C loop up to A$ input

2.10 T "It is certain.";R;C print a response and return from subroutine
4.10 T "It is decidedly so.";R;C etc.....
6.10 T "Without a doubt.";R
8.10 T "Yes - definitely.";R
10.10 T "You may rely on it.";R
12.10 T "As I see it, yes.";R
14.10 T "Most likely.";R
16.10 T "Outlook good.";R
18.10 T "Yes.";R
20.10 T "Signs point to yes.";R
22.10 T "Reply hazy, try again.";R
24.10 T "Ask again later.";R
26.10 T "Better not tell you now.";R
28.10 T "Cannot predict now.";R
30.10 T "Concentrate and ask again.";R
32.10 T "Don't count on it.";R
34.10 T "My reply is no.";R
36.10 T "My sources say no.";R
38.10 T "Outlook not so good.";R
40.10 T "Very doubtful.";R
50.10 T !"Thanks for consulting Magic 8-Ball for your life choices."!
50.20 Q

Forth

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

? :

Fortran

PROGRAM EIGHT_BALL
    CHARACTER(LEN=100) :: RESPONSE
    CHARACTER(LEN=100) :: QUESTION
    CHARACTER(LEN=100), DIMENSION(20) :: RESPONSES
    REAL :: R

    CALL RANDOM_SEED()

    RESPONSES(1) = "It is certain" 
    RESPONSES(2) = "It is decidedly so"
    RESPONSES(3) = "Without a doubt"
    RESPONSES(4) = "Yes, definitely"
    RESPONSES(5) = "You may rely on it"
    RESPONSES(6) = "As I see it, yes"
    RESPONSES(7) = "Most likely"
    RESPONSES(8) = "Outlook good"
    RESPONSES(9) = "Signs point to yes"
    RESPONSES(10) = "Yes"
    RESPONSES(11) = "Reply hazy, try again"
    RESPONSES(12) = "Ask again later"
    RESPONSES(13) = "Better not tell you now"
    RESPONSES(14) = "Cannot predict now"
    RESPONSES(15) = "Concentrate and ask again"
    RESPONSES(16) = "Don't bet on it"
    RESPONSES(17) = "My reply is no"
    RESPONSES(18) = "My sources say no"
    RESPONSES(19) = "Outlook not so good"
    RESPONSES(20) = "Very doubtful"

    WRITE(*,*) "Welcome to 8 Ball! Ask a question to find the answers"
    WRITE(*,*) "you seek, type either 'quit' or 'q' to exit", NEW_LINE('A')

    DO WHILE(.TRUE.)
        PRINT*, "Ask your question: "
        READ(*,*) QUESTION
        IF(QUESTION == "q" .OR. QUESTION == "quit") THEN
            CALL EXIT(0)
        ENDIF
        CALL RANDOM_NUMBER(R)
        PRINT*, "Response: ", TRIM(RESPONSES(FLOOR(R*20))), NEW_LINE('A')
    ENDDO
END PROGRAM EIGHT_BALL

Output:

 Welcome to 8 Ball! Ask a question to find the answers
 you seek, type either 'quit' or 'q' to exit

 Ask your question: 
Is the future bright?
 Response: Signs point to yes

Go

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

? : 

GW-BASIC

0 DATA "It is certain.", "It is decidedly so."
20 DATA "Without a doubt.", "Yes - definitely."
30 DATA "You may rely on it.", "As I see it, yes."
40 DATA "Most likely.", "Outlook good."
50 DATA "Yes.", "Signs point to yes."
60 DATA "Reply hazy, try again.", "Ask again later."
70 DATA "Better not tell you now.", "Cannot predict now."
80 DATA "Concentrate and ask again.", "Don't count on it."
90 DATA "My reply is no.", "My sources say no."
100 DATA "Outlook not so good.", "Very doubtful."
110 DIM M8BALL$(20)
120 FOR I=0 TO 19
130 READ M8BALL$(I)
140 NEXT I
150 RANDOMIZE TIMER
160 INPUT "What would you like to know? ", Q$
170 PRINT M8BALL$(INT(RND*20))
180 END

Haskell

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

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 ({~ ?@:#) 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

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

//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

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

K

Works with: ngn/k
ask:{` 0:*1?"/"\"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"}

Examples:

ask "Will this work?"
Signs point to yes
ask "Was this worth doing?"
Without a doubt
ask "Can I have a cookie?"
Yes, definitely

Kotlin

// 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

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

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

Lua

math.randomseed(os.time())
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."
}
while true do
  io.write("Q:  ")
  question = io.read()
  print("A:  "..answers[math.random(#answers)])
end
Output:
Q:  Are you truly a magic 8-ball?
A:  Very doubtful.
Q:  Are you a simulation of one?
A:  Most likely.

M2000 Interpreter

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

Mathematica / Wolfram Language

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."};
q = Input["Please enter your question"];
SeedRandom[Hash[q]];
Print[RandomChoice[answers]]
Output:
[Are you awesome?]Yes - definitely.

Maxima

set_random_state(make_random_state(true))$

block(
    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","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"],
    read("Ask a question"),
    print(responses[random(20)])
);
Output:
"Ask a question"" ""Are you aware of yourself?";
"My sources say no"

min

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

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

Nim

import random, strutils

const 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"]

proc exit() =
  echo "Bye."
  quit QuitSuccess

randomize()

try:
  while true:
    echo "Type your question or an empty line to quit."
    stdout.write "? "
    let question = stdin.readLine()
    if question.strip().len == 0: exit()
    echo Answers[rand(19)], ".\n"
except EOFError:
  exit()
Output:

Example of session (no cheating).

Type your question or an empty line to quit.
? Is Nim a good language?
As I see it, yes.

Type your question or an empty line to quit.
? 
Bye.

ooRexx

/* 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:

Pascal

Free Pascal

nearly copy of Delphi

program Magic_8_ball;
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
uses
  SysUtils,crt;
const
  answers: array[0..19] of 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.');
begin
  Randomize;
  repeat
    writeln('Magic 8 Ball! Ask question and hit ENTER key for the answer!');
    readln;
    ClrScr;
    writeln(answers[Random(length(answers))],#13#10);
    writeln('Hit ESCape to leave');
    repeat until keypressed;
    ClrScr;
  until readkey=#27;
end.
Output:
Magic 8 Ball! Ask question and hit ENTER key for the answer!
Will I find my mobile again :-(

Very doubtful.

Hit ESCape to leave 

Perl

@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

Library: Phix/pGUI
Library: Phix/online

You can run this online here.

with javascript_semantics
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"}

include pGUI.e
Ihandle dlg, vbox, question, answer
 
sequence answered = {}
bool clearkey = false

function key_cb(Ihandle /*dlg*/, atom c)
    if c=K_ESC then return IUP_CLOSE end if -- (standard practice for me)
    if c=K_F5 then return IUP_DEFAULT end if -- (let browser reload work)
    if c=K_CR then
        string q = IupGetAttribute(question,"VALUE"), reply
        if length(q) then
            if find(q,answered) then
                reply = "Your question has already been answered"
            else
                answered = append(answered,q)
                reply = answers[rand(length(answers))]
            end if
            IupSetStrAttribute(answer,"TITLE",reply)
            clearkey = true
        end if
    elsif clearkey then
        IupSetAttribute(question,"VALUE","")
        clearkey = false
    end if
    return IUP_CONTINUE
end function

IupOpen()
question = IupText("EXPAND=HORIZONTAL")
answer = IupLabel("","EXPAND=HORIZONTAL")
vbox = IupVbox({question,answer},`MARGIN=40x40`)
dlg = IupDialog(vbox,`TITLE="Magic 8-ball",SIZE=250x100`)
IupSetCallback(dlg,"KEY_CB",Icallback("key_cb"))
IupShow(dlg)
if platform()!=JS then
    IupMainLoop()
    IupHide(dlg)
end if

PHP

CLI

<?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

PureBasic

Define.s Magic8="● It is certain."+#LF$+
                "● It is decidedly so."+#LF$+
                "● Without a doubt."+#LF$+
                "● Yes – definitely."+#LF$+
                "● You may rely on it."+#LF$+
                "● As I see it, yes."+#LF$+
                "● Most likely."+#LF$+
                "● Outlook good."+#LF$+
                "● Yes."+#LF$+
                "● Signs point To yes."+#LF$+	
                "● Reply hazy, try again."+#LF$+
                "● Ask again later."+#LF$+
                "● Better Not tell you now."+#LF$+
                "● Cannot predict now."+#LF$+
                "● Concentrate And ask again."+#LF$+	
                "● Don't count on it."+#LF$+
                "● My reply is no."+#LF$+
                "● My sources say no."+#LF$+
                "● Outlook Not so good."+#LF$+
                "● Very doubtful."+#LF$
                
                OpenConsole()
                
                Repeat
                  Print("MAGIC8: What would you like To know? "): q$=Input()
                  If Len(q$)=0 : End : EndIf
                  PrintN(StringField(Magic8,Random(CountString(Magic8,#LF$),1),#LF$))
                ForEver
Output:
MAGIC8: What would you like To know? Do you want me to take over the world?
● Don't count on it.
MAGIC8: What would you like To know? Should I invest all my money in the stagecoach company?
● Yes.
MAGIC8: What would you like To know? Should I order a pepperoni pizza?
● My reply is no.
MAGIC8: What would you like To know? 

Python

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
        
    if question in q_and_a:
        print('Your question has already been answered')
    else:
        answer = random.choice(s)
        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:

Quackery

[ 20 random 
  [ table
    $ "Concentrate and ask again."       $ "Yes."
    $ "Better not tell you now." $ "Most likely."
    $ "Reply hazy, try again."  $ "Outlook good."
    $ "Outlook not so good."   $ "It is certain."
    $ "Cannot predict now."    $ "Very doubtful."
    $ "Signs point to yes."   $ "My reply is no."
    $ "It is decidedly so."  $ "Ask again later."
    $ "You may rely on it."  $ "Without a doubt."
    $ "Don't count on it."  $ "Yes - definitely."
    $ "My sources say no."  $ "As I see it, yes." ]
    do echo$ cr ]                                   is 8-ball ( --> )

Testing in Quackery shell:

/O> 8-ball
... 
Reply hazy, try again.

Stack empty.

/O> 10 times 8-ball
... 
As I see it, yes.
It is decidedly so.
Ask again later.
Outlook good.
Without a doubt.
My sources say no.
Signs point to yes.
Don't count on it.
Very doubtful.
Very doubtful.

Stack empty.

R

eight_ball <- function()
{
    responses <- c("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")

    question <- ""

    cat("Welcome to 8 ball!\n\n", "Please ask yes/no questions to get answers.",
        " Type 'quit' to exit the program\n\n")

    while(TRUE)
    {
        question <- readline(prompt="Enter Question: ")
        if(question == 'quit')
        {
            break
        }
        randint <- runif(1, 1, 20)
        cat("Response: ", responses[randint], "\n")
    }
}

if(!interactive())
{
    eight_ball()
}

Output:

Welcome to 8 ball!

 Please ask yes/no questions to get answers.  Type 'quit' to exit the program

Enter Question: Is the future bright?
Response:  Ask again later 
Enter Question: Is the future positive?
Response:  Cannot predict now

Racket

(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

(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

version 1

/* 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

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)), ,"┼")).
possible output   when invoking the REXX program:
Reply hazy, try again.

Ring

# 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

RPL

Translation of: Quackery
≪ 
  { "Concentrate and ask again."        "Yes."
    "Better not tell you now."  "Most likely."
    "Reply hazy, try again."   "Outlook good."
    "Outlook not so good."    "It is certain."
    "Cannot predict now."     "Very doubtful."
    "Signs point to yes."    "My reply is no."
    "It is decidedly so."   "Ask again later."
    "You may rely on it."   "Without a doubt."
    "Don't count on it."   "Yes - definitely."
    "My sources say no."   "As I see it, yes." }
   RAND 20 * CEIL GET
≫ 'MAG8B' STO

Ruby

#!/usr/bin/ruby

class EightBall
  def initialize
    print "Welcome to 8 ball! Ask your question below. "
    puts "Type 'quit' to exit the program.\n\n"
    @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"]
  end

  def ask_question
    print "Question: "
    question = gets

    if question.chomp.eql? "quit"
      exit(0)
    end

    puts "Response: #{@responses.sample} \n\n"
  end

  def run
    loop do
      ask_question
    end
  end
end

eight_ball = EightBall.new
eight_ball.run

Output:

Welcome to 8 ball! Ask your question below. Type 'quit' to exit the program.

Question: Am I rich?
Response: It is decidedly so

Rust

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

Sather

class MAIN is
   const answers: ARRAY{STR} :=
               |
               "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."
               |;
   main is
      RND::seed := #TIMES.wall_time;
      loop
         #OUT+"Your question: "; #OUT.flush;
         question ::= #IN.get_str;
         #OUT+answers[RND::int(0, answers.size-1)] + "\n";
      end;
   end;
end;

Scala

import scala.util.Random

object Magic8Ball extends App {
  val shake: () => String = {
    val answers = 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."
    )
    val r = new Random
    () => answers(r.nextInt(answers.length))
  }

  println("Ask the Magic 8-Ball your questions. ('q' or 'quit' to quit)\n")

  while (true) {
    io.StdIn.readLine("Question: ").toLowerCase match {
      case "q" | "quit" =>
        println("Goodbye.")
        sys.exit()
      case _ =>
        println(s"Response: ${shake()}\n")
    }
  }
}

Tcl

namespace path {::tcl::mathop ::tcl::mathfunc}

set answers {
	"As I see it, yes"
	"Ask again later"
	"Better not tell you now"
	"Cannot predict now"
	"Concentrate and ask again"
	"Don't bet on it"
	"It is certain"
	"It is decidedly so"
	"Most likely"
	"My reply is no"
	"My sources say maybe"
	"My sources say no"
	"Outlook good"
	"Outlook not so good"
	"Reply hazy, try again"
	"Signs point to yes"
	"Very doubtful"
	"Without a doubt"
	"Yes"
	"Yes, definitely"
	"Yes, probably not"
	"You may rely on it"
	"Your question has already been answered"
}

puts -nonewline "Question: "; flush stdout
while {[gets stdin line] > 0} {
	set answer [lindex $answers [int [* [rand] [llength $answers]]]]
	puts "⑧ says “$answer”"
	puts -nonewline "Question: "; flush stdout
}
Output:
$ tclsh magic8.tcl
Question: Will it rain today?
⑧ says “Yes, probably not”
Question: Am I dead?
⑧ says “Yes, definitely”
Question:

Tiny BASIC

Works with: TinyBasic
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."

Transd

The description of Magic ball never says that the answer must be random. Hey, how can we give the user just random answers?

#lang transd

MainModule : {
    ans: ["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."],
	_start: (lambda locals: sense 0 quest ""
        (while true
            (lout "Please, ask your question:")
            (getline quest)
            (if (not (size quest)) break)
            (if (neq (back quest) "?") (lout "\nEh?") continue)
            (= sense 0)
            (tql quest reduce: ["col1"] using: (λ c Char() (+= sense c)))
            (lout (get ans (mod sense 20)))
        )
    )
}

uBasic/4tH

Works with: R4
Push "It is certain", "It is decidedly so", "Without a doubt"
Push "Yes, definitely", "You may rely on it"
Push "As I see it, yes", "Most likely", "Outlook good"
Push "Signs point to yes", "Yes", "Reply hazy, try again"
Push "Ask again later", "Better not tell you now"
Push "Cannot predict now", "Concentrate and ask again"
Push "Don't bet on it", "My reply is no", "My sources say no"
Push "Outlook not so good", "Very doubtful"
                                       ' read the replies
For x = 0 to Used() - 1 : @(x) = Pop(): Next
Print "Please enter your question or a blank line to quit.\n"
                                       ' now show the prompt
Do
  r = Ask("? : ")                      ' ask a question
Until Len(r)=0                         ' check for empty line
  Print Show(@(Rnd(x))) : Print        ' show the reply
Loop

UNIX Shell

Works with: Bourne Again Shell
#!/bin/bash
  
declare -ra 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")

printf "Welcome to 8 ball! Enter your questions using the prompt below to
find the answers you seek. Type 'quit' to exit.\n\n"

until
  read -p 'Enter Question: '
  [[ "$REPLY" == quit ]]
do printf "Response: %s\n\n" "${RESPONSES[RANDOM % ${#RESPONSES[@]}]}"
done
Output:
Welcome to 8 ball! Enter your questions using the prompt below to
find the answers you seek. Type 'quit' to exit.

Enter Question: Is the future bright?
Response: Yes definitely

Wren

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

? : 

XBS

Random Choice

set 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.","Yes.","Sign points 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){
	window->prompt("Ask 8-Ball a question");
	log(Responses[rnd(0,?Responses-1)]);
}

Non-Random Choice

set 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.","Yes.","Sign points 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."];

func Compile(String){
	set n = 0;
	foreach(k,v as String){
		n+=string.char(v);
	}
	send n;
}

while(true){
	let Response = window->prompt("Ask 8-Ball a question");
	let N = Compile(Response);
	log(Responses[N%(?Responses)]);
}

XPL0

Translation of Kotlin and C.

int     Answers, Answer, Question;
[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"];
Text(0, "Please enter your question or a blank line to quit.
");
while true do
        [CrLf(0);  Text(0, "? : ");
        Question:= ChIn(0);
        if Question = \CR\$0D then return;
        OpenI(0);       \discard any remaining chars in keyboard buffer
        Answer:= Answers(Ran(20));
        Text(0, Answer);  CrLf(0);
        ]
]
Output:
Please enter your question or a blank line to quit.

? : Will Trump win?
Don't bet on it

? : Have you read the news lately?
Reply hazy, try again

? : Is this program working?
Without a doubt

? : 

zkl

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
? :