Guess the number/With feedback: Difference between revisions
→{{header|Tiny Craft Basic}}
Basicgames (talk | contribs) |
|||
(71 intermediate revisions by 33 users not shown) | |||
Line 15:
* [[Guess the number/With Feedback (Player)]]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V (target_min, target_max) = (1, 100)
print("Guess my target number that is between #. and #. (inclusive).\n".format(target_min, target_max))
V target = random:(target_min..target_max)
V (answer, i) = (target_min - 1, 0)
L answer != target
i++
V txt = input(‘Your guess(#.): ’.format(i))
X.try
answer = Int(txt)
X.catch ValueError
print(‘ I don't understand your input of '#.' ?’.format(txt))
L.continue
I answer < target_min | answer > target_max
print(‘ Out of range!’)
L.continue
I answer == target
print(‘ Ye-Haw!!’)
L.break
I answer < target {print(‘ Too low.’)}
I answer > target {print(‘ Too high.’)}
print("\nThanks for playing.")</syntaxhighlight>
{{out}}
<pre>
Guess my target number that is between 1 and 100 (inclusive).
Your guess(1): kk
I don't understand your input of 'kk' ?
Your guess(2): 0
Out of range!
Your guess(3): 100
Too high.
Your guess(4): 101
Out of range!
Your guess(5): 50
Too high.
Your guess(6): 25
Too high.
Your guess(7): 13
Too low.
Your guess(8): 16
Too low.
Your guess(9): 18
Too low.
Your guess(10): 20
Too low.
Your guess(11): 23
Too low.
Your guess(12): 24
Ye-Haw!!
Thanks for playing.
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE x,n,min=[1],max=[100]
PrintF("Try to guess a number %B-%B: ",min,max)
x=Rand(max-min+1)+min
DO
n=InputB()
IF n<min OR n>max THEN
Print("The input is incorrect. Try again: ")
ELSEIF n<x THEN
Print("My number is higher. Try again: ")
ELSEIF n>x THEN
Print("My number is lower. Try again: ")
ELSE
PrintE("Well guessed!")
EXIT
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number_with_feedback.png Screenshot from Atari 8-bit computer]
<pre>
Try to guess a number 1-100: 50
My number is lower. Try again: 25
My number is lower. Try again: 12
My number is higher. Try again: 19
My number is lower. Try again: 15
My number is lower. Try again: 14
Well guessed!
</pre>
=={{header|Ada}}==
<
with Ada.Text_IO;
procedure Guess_Number_Feedback is
function Get_Int (Prompt : in String) return Integer is
begin
loop
Ada.Text_IO.Put (Prompt);
declare
Response : constant String := Ada.Text_IO.Get_Line;
begin
if Response /= "" then
return Integer'Value (Response);
end if;
exception
when others =>
Ada.Text_IO.Put_Line ("Invalid response, not an integer!");
end;
end loop;
end Get_Int;
procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is
subtype Number is Integer range Lower_Limit .. Upper_Limit;
package Number_RNG is new Ada.Numerics.Discrete_Random (Number);
Generator : Number_RNG.Generator;
My_Number : Number;
Your_Guess :
begin
Number_RNG.Reset (Generator);
Line 33 ⟶ 139:
Ada.Text_IO.Put_Line ("Guess my number!");
loop
exit when Your_Guess = My_Number;
if Your_Guess > My_Number then
Line 44 ⟶ 149:
Ada.Text_IO.Put_Line ("Well guessed!");
end Guess_Number;
Lower_Limit : Integer;
Upper_Limit : Integer;
begin
loop
exit when Lower_Limit < Upper_Limit;
Ada.Text_IO.Put_Line ("Lower limit must be lower!");
end loop;
Guess_Number (Lower_Limit, Upper_Limit);
end Guess_Number_Feedback;</
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
main:(
Line 107 ⟶ 209:
OD;
print( ( "That's correct!", newline ) )
)</
{{out}}
<pre>
Line 133 ⟶ 235:
=={{header|AppleScript}}==
<
property minLimit : 1
property maxLimit : 100
Line 171 ⟶ 273:
end try
end repeat
end run</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">n: random 1 10
while ø [
try? [
num: to :integer input "Guess the number: " n
case [num]
when? [=n][print "\tWell Guessed! :)", exit]
when? [>n][print "\tHigher than the target..."]
when? [<n][print "\tLess than the target..."]
else []
]
else -> print "\tInvalid input!"
]</syntaxhighlight>
{{out}}
<pre>Guess the number: 3
Less than the target...
Guess the number: 9
Higher than the target...
Guess the number: something
Invalid input!
Guess the number: 5
Less than the target...
Guess the number: 7
Well Guessed! :)</pre>
=={{header|AutoHotkey}}==
<
MaxNum = 99999999999
Line 205 ⟶ 335:
}
TotalTime := Round((A_TickCount - TotalTime) / 1000,1)
MsgBox, 64, Correct, The number %RandNum% was guessed in %Tries% tries, which took %TotalTime% seconds.</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f GUESS_THE_NUMBER_WITH_FEEDBACK.AWK
BEGIN {
Line 237 ⟶ 367:
exit(0)
}
</syntaxhighlight>
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<
110 U% = 10
120 N% = RND(1) * (U% - L% + 1) + L%
Line 255 ⟶ 384:
210 Q = G% = N%
220 NEXT
230 PRINT "THE GUESS WAS EQUAL TO THE TARGET."</
==={{header|BASIC256}}===
{{works with|BASIC256 }}
<
chosen = int(rand*(Max-Min+1)) + Min
print "Guess a whole number between "+Min+" and "+Max
Line 273 ⟶ 401:
if guess = chosen then print "Well guessed!"
end if
until guess = chosen</syntaxhighlight>
Output:(example)
<pre>Guess a whole number between 5 and 15
Enter your number 10
Sorry, your number was too high
Line 283 ⟶ 409:
Sorry, your number was too low
Enter your number 8
Well guessed!</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">100 cls
110 nmax = 20
120 chosen = int(rnd(1)*nmax)+1
130 print "Guess a whole number between 1 a ";nmax;chr$(10)
140 do
150 input "Enter your number: ",guess
160 if guess < n or guess > nmax then
170 print "That was an invalid number"
180 exit do
190 else
200 if guess < chosen then print "Sorry, your number was too low"
210 if guess > chosen then print "Sorry, your number was too high"
220 if guess = chosen then print "Well guessed!"
230 endif
240 loop until guess = chosen
250 end</syntaxhighlight>
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
Randomize
Dim guess As Integer, max As Integer = 20
Dim n As Integer = Int(Rnd * max) + 1
Print "Guess which number I've chosen in the range 1 to "; max; Chr(10)
Do
Print " Your guess : "
Input guess
If guess > n And guess <= 20 Then
Print "Your guess is higher than the chosen number, try again"
Else If guess = n Then
Print "Correct, well guessed!"
Break
Else If guess < n And guess >= 1 Then
Print "Your guess is lower than the chosen number, try again"
Else
Print "Your guess is inappropriate, try again"
End If
Loop
End</syntaxhighlight>
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
<syntaxhighlight lang="qbasic">100 CLS
110 RANDOMIZE 1
120 L = 20
130 X = INT(RND(1)*L)+1
140 PRINT "Guess a whole number between 1 a ";L;CHR$(10)
150 'do
160 INPUT "Enter your number: ", N
170 IF N < N OR N > L THEN PRINT "That was an invalid number" : GOTO 230
180 'else
190 IF N < X THEN PRINT "Sorry, your number was too low"
200 IF N > X THEN PRINT "Sorry, your number was too high"
210 IF N = X THEN PRINT "Well guessed!"
220 IF N <> X THEN GOTO 150
230 END</syntaxhighlight>
==={{header|IS-BASIC}}===
<
110 RANDOMIZE
120 LET UP=10:LET LO=1 ! Limits
Line 303 ⟶ 492:
240 PRINT "Well guessed! Numner of tips:";COUNT
250 END SELECT
260 LOOP UNTIL NR=GU</
==={{header|Minimal BASIC}}===
{{trans|Tiny Craft Basic}}
<syntaxhighlight lang="qbasic">100 RANDOMIZE
110 LET T = 0
120 LET N = 20
130 LET R = INT(RND*N)+1
140 PRINT "GUESS A WHOLE NUMBER BETWEEN 1 AND";N
150 LET T = T+1
160 PRINT "ENTER YOUR NUMBER ";
170 INPUT G
180 IF G <> R THEN 210
190 PRINT "YOU GUESSED IT IN";T;"TRIES."
200 GOTO 310
210 IF G > R THEN 240
220 IF G < 1 THEN 240
230 PRINT "SORRY, YOUR NUMBER WAS TOO LOW"
240 IF G < R THEN 270
250 IF G > 100 THEN 270
260 PRINT "SORRY, YOUR NUMBER WAS TOO HIGH"
270 IF G >= 1 THEN 300
280 IF G <= 100 THEN 300
290 PRINT "THAT WAS AN INVALID NUMBER"
300 IF G <> R THEN 140
310 END</syntaxhighlight>
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">100 CLS
120 L = 20
130 X = INT(RND(1)*L)+1
140 PRINT "Guess a whole number between 1 a ";L;CHR$(10)
150 'do
160 INPUT "Enter your number: "; N
170 IF N < N OR N > L THEN PRINT "That was an invalid number" : GOTO 230
180 'else
190 IF N < X THEN PRINT "Sorry, your number was too low"
200 IF N > X THEN PRINT "Sorry, your number was too high"
210 IF N = X THEN PRINT "Well guessed!"
220 IF N <> X THEN GOTO 150
230 END</syntaxhighlight>
==={{header|QB64}}===
Note that <code>INPUT</code> only allows the user to type things that can fit in the variable it's storing to. Since we're storing to a byte, we don't have to worry about the user typing any non-numbers.
<syntaxhighlight lang="qbasic">DIM secretNumber AS _BYTE ' the secret number
DIM guess AS _BYTE ' the player's guess
RANDOMIZE TIMER ' set a seed based on system time
secretNumber%% = INT(RND * 10) + 1 ' a random value between 1 and 10
PRINT "The computer has chosen a secret number between 1 and 10."
DO
PRINT "What is your guess";
INPUT guess%%
SELECT CASE guess%%
CASE IS < 1, IS > 10
PRINT "Please enter a number between 1 and 10!"
_CONTINUE
CASE IS < secretNumber%%
PRINT "Your guess is LOWER than the target."
CASE IS > secretNumber%%
PRINT "Your guess is HIGHER than the target."
END SELECT
LOOP UNTIL guess%% = secretNumber%%
PRINT "You won!"; secretNumber%%; "was the secret number!"</syntaxhighlight>
{{out}}
<pre>The computer has chosen a secret number between 1 and 10.
What is your guess? -1
Please enter a number between 1 and 10!
What is your guess? 11
Please enter a number between 1 and 10!
What is your guess? 1
Your guess is LOWER than the target.
What is your guess? 10
Your guess is HIGHER than the target.
What is your guess? 5
Your guess is HIGHER than the target.
What is your guess? 3
Your guess is HIGHER than the target.
What is your guess? 2
You won! 2 was the secret number!</pre>
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">CLS
RANDOMIZE TIMER ' set a seed based on system time
nmax = 20
chosen = INT(RND * nmax) + 1
PRINT "Guess a whole number between 1 a"; nmax; CHR$(10)
DO
INPUT "Enter your number"; guess
IF guess < n OR guess > nmax THEN
PRINT "That was an invalid number"
EXIT DO
ELSE
IF guess < chosen THEN PRINT "Sorry, your number was too low"
IF guess > chosen THEN PRINT "Sorry, your number was too high"
IF guess = chosen THEN PRINT "Well guessed!"
END IF
LOOP UNTIL guess = chosen
END</syntaxhighlight>
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="vb">nmin = 5
nmax = 15
chosen = int( rnd( 1) * (nmax-nmin+1)) +nmin
print "Guess a whole number between "; nmin; " and "; nmax
[loop]
input "Enter your number "; guess
if guess < nmin or guess > nmax then
print "That was an invalid number"
end
else
if guess < chosen then print "Sorry, your number was too low"
if guess > chosen then print "Sorry, your number was too high"
if guess = chosen then print "Well guessed!": end
end if
if guess <> chosen then [loop]</syntaxhighlight>
==={{header|True BASIC}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">RANDOMIZE
LET nmax = 20
LET chosen = int(rnd*nmax)+1
PRINT "Guess a whole number between 1 a"; nmax; chr$(10)
DO
INPUT prompt "Enter your number ": guess
IF guess < n or guess > nmax then
PRINT "That was an invalid number"
EXIT DO
ELSE
IF guess < chosen then PRINT "Sorry, your number was too low"
IF guess > chosen then PRINT "Sorry, your number was too high"
IF guess = chosen then PRINT "Well guessed!"
END IF
LOOP until guess = chosen
END</syntaxhighlight>
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">nmin = 5
nmax = 15
chosen = int(ran(nmax-nmin+1)) + nmin
print "Guess a whole number between ", nmin, " and ", nmax
repeat
input "Enter your number " guess
if guess < nmin or guess > nmax then
print "That was an invalid number"
end
else
if guess < chosen print "Sorry, your number was too low"
if guess > chosen print "Sorry, your number was too high"
if guess = chosen print "Well guessed!"
fi
until guess = chosen</syntaxhighlight>
=={{header|Batch File}}==
<
:A
Line 322 ⟶ 668:
echo You won! The number was %number%
pause>nul
goto A</
=={{header|BBC BASIC}}==
<
Max% = 10
chosen% = RND(Max%-Min%+1) + Min% - 1
Line 343 ⟶ 689:
ENDCASE
UNTIL FALSE
END</
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
static $( randstate = ? $)
let rand(min,max) = valof
$( let x = ?
let range = max-min
let mask = 1
while mask < range do mask := (mask << 1) | 1
$( randstate := random(randstate)
x := (randstate >> 6) & mask
$) repeatuntil 0 <= x < range
resultis x + min
$)
let readguess(min,max) = valof
$( let x = ?
writes("Guess? ")
x := readn()
if min <= x < max then resultis x
writes("Invalid input.*N")
$) repeat
let play(min,max,secret) be
$( let tries, guess = 0, ?
$( guess := readguess(min,max)
if guess < secret then writes("Too low!*N")
if guess > secret then writes("Too high!*N")
tries := tries + 1
$) repeatuntil guess = secret
writef("Correct! You guessed it in %N tries.*N", tries)
$)
let start() be
$( let min, max = ?, ?
writes("Guess the number*N*N")
writes("Random seed? ") ; randstate := readn()
$( writes("Lower bound? ") ; min := readn()
writes("Upper bound? ") ; max := readn() + 1
test max-1 > min break or writes("Invalid bounds.*N")
$) repeat
wrch('*N')
play(min, max, rand(min, max))
$)</syntaxhighlight>
{{out}}
<pre>Guess the number
Random seed? 12345
Lower bound? 1
Upper bound? 100
Guess? 0
Invalid input.
Guess? 101
Invalid input.
Guess? 50
Too low!
Guess? 75
Too high!
Guess? 62
Too high!
Guess? 56
Too high!
Guess? 53
Too high!
Guess? 52
Correct! You guessed it in 6 tries.</pre>
=={{header|Befunge}}==
The number range is hardcoded at the start of the program (<tt>1:"d"</tt> being 1 to 100), but can easily be changed.
<
<*2\_$\1+%+48*">",,#v>#+:&#>#5-:!_0`00p0"hgih"00g>_0"wol"00g!>_48vv1?
\1-:^v"d correctly!"<^,,\,+55,". >"$_,#!>#:<"Your guess was too"*<>+>
:#,_@>"ess" >"eug uoY"></
{{out}}
Line 366 ⟶ 779:
=={{header|Brat}}==
<
p "Guess a number between 1 and 10."
Line 382 ⟶ 795:
}
}
}</
=={{header|C}}==
<
#include <stdio.h>
#include <time.h>
Line 399 ⟶ 812:
printf( "Guess the number between %d and %d: ", lower_limit, upper_limit );
fflush(stdout); // Flush the output buffer
while( scanf( "%d", &guess ) == 1 ){
Line 409 ⟶ 823:
return 0;
}</
Demonstration:
Line 426 ⟶ 840:
Try again: 59
You guessed correctly!</pre>
=={{header|C sharp}}==
<
class Program
Line 514 ⟶ 881:
}
}
</syntaxhighlight>
Output:
<pre>The number is between 1 and 10. Make a guess: 1
Line 531 ⟶ 898:
Press any key to exit.
</pre>
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::srand(std::time(0));
int lower, upper, guess;
std::cout << "Enter lower limit: ";
std::cin >> lower;
std::cout << "Enter upper limit: ";
std::cin >> upper;
int random_number = lower + std::rand() % ((upper + 1) - lower);
do
{
std::cout << "Guess what number I have: ";
std::cin >> guess;
if (guess > random_number)
std::cout << "Your guess is too high\n";
else if (guess < random_number)
std::cout << "Your guess is too low\n";
else
std::cout << "You got it!\n";
} while (guess != random_number);
return 0;
}</syntaxhighlight>
Output:
<pre>Enter lower limit: 1
Enter upper limit: 100
Guess what number I have: 50
Your guess is too high
Guess what number I have: 40
Your guess is too high
Guess what number I have: 25
Your guess is too high
Guess what number I have: 10
Your guess is too high
Guess what number I have: 2
Your guess is too low
Guess what number I have: 4
Your guess is too high
Guess what number I have: 3
You got it!</pre>
=={{header|Caché ObjectScript}}==
<
}
}
{{out}}<pre>SAMPLES>do ^GUESSNUM^
Guess the integer between 1 and 100: 50
Line 581 ⟶ 994:
Your guess was correct!
You guessed the number in 7 attempts.
=={{header|Ceylon}}==
Line 588 ⟶ 1,000:
In you module.ceylon file put import ceylon.random "1.3.1";
<
DefaultRandom
}
Line 624 ⟶ 1,036:
}
}
}</
=={{header|Clojure}}==
<
(let [start 1
end 100
Line 642 ⟶ 1,054:
:else true)
(println "Correct")
(recur (inc i)))))))</
=={{header|CLU}}==
<syntaxhighlight lang="clu">read_number = proc (prompt: string) returns (int)
po: stream := stream$primary_output()
pi: stream := stream$primary_input()
while true do
stream$puts(po, prompt)
return(int$parse(stream$getl(pi)))
except when bad_format:
stream$putl(po, "Invalid number.")
end
end
end read_number
read_limits = proc () returns (int,int)
po: stream := stream$primary_output()
while true do
min: int := read_number("Lower limit? ")
max: int := read_number("Upper limit? ")
if min >= 0 cand min < max then return(min,max) end
stream$putl(po, "Invalid limits, try again.")
end
end read_limits
read_guess = proc (min, max: int) returns (int)
po: stream := stream$primary_output()
while true do
guess: int := read_number("Guess? ")
if min <= guess cand max >= guess then return(guess) end
stream$putl(po, "Guess must be between "
|| int$unparse(min) || " and " || int$unparse(max) || ".")
end
end read_guess
play_game = proc (min, max, secret: int)
po: stream := stream$primary_output()
guesses: int := 0
while true do
guesses := guesses + 1
guess: int := read_guess(min, max)
if guess = secret then break
elseif guess < secret then stream$putl(po, "Too low!")
elseif guess > secret then stream$putl(po, "Too high!")
end
end
stream$putl(po, "Correct! You got it in " || int$unparse(guesses) || " tries.")
end play_game
start_up = proc ()
po: stream := stream$primary_output()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
stream$putl(po, "Guess the number\n----- --- ------\n")
min, max: int := read_limits()
secret: int := min + random$next(max - min + 1)
play_game(min, max, secret)
end start_up</syntaxhighlight>
{{out}}
<pre>Guess the number
----- --- ------
Lower limit? 1
Upper limit? 100
Guess? 50
Too high!
Guess? 25
Too high!
Guess? 12
Too low!
Guess? 18
Too low!
Guess? 22
Too high!
Guess? 20
Too low!
Guess? 21
Correct! You got it in 7 tries.</pre>
=={{header|COBOL}}==
<
PROGRAM-ID. Guess-With-Feedback.
Line 674 ⟶ 1,164:
GOBACK
.</
=={{header|Common Lisp}}==
<
(let ((num-guesses 0)
(num (+ (random (1+ (- max min))) min))
Line 693 ⟶ 1,183:
(= guess num)))
(format t "You got the number correct on the ~:r guess!~%" num-guesses)))
</syntaxhighlight>
Output:
<pre>CL-USER> (guess-the-number-feedback 1 1024)
Line 715 ⟶ 1,205:
You got the number correct on the eighth guess!
</pre>
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">let n = int(rnd * 100) + 1
do
let t = t + 1
input "guess the number between 1 and 100", g
if g < n then
alert "guess higher"
endif
if g > n then
alert "guess lower"
endif
loop g <> n
alert "you guessed the number in ", t, " tries"</syntaxhighlight>
=={{header|Crystal}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">number = rand(1..10)
puts "Guess the number between 1 and 10"
loop do
begin
user_number = gets.to_s.to_i
if user_number == number
puts "You guessed it."
break
elsif user_number > number
puts "Too high."
else
puts "Too low."
end
rescue ArgumentError
puts "Please enter an integer."
end
end</syntaxhighlight>
=={{header|D}}==
{{trans|Python}}
<
std.range;
Line 748 ⟶ 1,285:
writeln(answer < target ? " Too low." : " Too high.");
}
}</
Sample game:
<pre>Guess my target number that is between 1 and 100 (inclusive).
Line 770 ⟶ 1,307:
Your guess #9: 83
Well Guessed.</pre>
=={{header|DCL}}==
<
$ count = 0
$ loop:
Line 785 ⟶ 1,323:
$ if guess .gt. rnd then $ write sys$output "too large"
$ if guess .ne. rnd then $ goto loop
$ write sys$output "it only took you ", count, " guesses"</
{{out}}
<pre>$ @guess
Line 807 ⟶ 1,345:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 892 ⟶ 1,430:
end.
</syntaxhighlight>
=={{header|EasyLang}}==
<syntaxhighlight>
print "Guess a number between 1 and 100!"
n = randint 100
repeat
g = number input
if error = 1
print "You must enter a number!"
print " is too high"
print " is too low"
until g = n
.
print
</syntaxhighlight>
=={{header|EchoLisp}}==
<
;;(read <default-value> <prompt>) prompts the user with a default value using the browser dialog box.
;; we play sounds to make this look like an arcade game
Line 929 ⟶ 1,470:
(play-sound 'ok )
" 🔮 Well played!! 🍒 🍇 🍓")
</syntaxhighlight>
=={{header|Ela}}==
<
guess () = do
Line 968 ⟶ 1,509:
ask ()
guess () ::: IO</
=={{header|Elena}}==
ELENA
<
public program()
{
int randomNumber := randomGenerator.
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
bool numberCorrect := false;
Line 996 ⟶ 1,538:
}
}
}</
{{out}}
<pre>
Line 1,010 ⟶ 1,552:
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<
def play(lower, upper) do
play(lower, upper, Enum.random(lower .. upper))
Line 1,029 ⟶ 1,571:
end
GuessingGame.play(1, 100)</
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(let* ((min 1)
(number (+ (random (1+ (- max min))) min))
guess done)
(message "Guess the number between %d and %d" min max)
(while (
(
(cond
((< guess number)
((> guess
(
((
(message "Well guessed!")))))</syntaxhighlight>
=={{header|Erlang}}==
<
-module(guess_number).
-export([main/0]).
Line 1,075 ⟶ 1,618:
guess(N)
end.
</syntaxhighlight>
{{out}}
<pre>1> c(guess_number).
Line 1,095 ⟶ 1,638:
=={{header|Euphoria}}==
<
constant lower_limit = 0, upper_limit = 100
Line 1,113 ⟶ 1,656:
puts(1,"You guessed to low.\nTry again: ")
end if
end while</
=={{header|F_Sharp|F#}}==
<
open System
Line 1,147 ⟶ 1,690:
0
</syntaxhighlight>
=={{header|Factor}}==
<
formatting
fry
Line 1,175 ⟶ 1,718:
[ unparse "Number in range %s, your guess?\n" printf flush ]
[ random '[ _ game-step ] loop ]
bi ;</
=={{header|Fantom}}==
<
class Main
{
Line 1,216 ⟶ 1,759:
}
}
</syntaxhighlight>
Sample game:
Line 1,242 ⟶ 1,785:
Well guessed!
</pre>
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.01 S T=0
01.02 A "LOWER LIMIT",L
01.03 A "UPPER LIMIT",H
01.04 I (H-L)1.05,1.05,1.06
01.05 T "INVALID RANGE",!;G 1.02
01.06 S S=FITR(L+FRAN()*(H-L+1))
01.10 A "GUESS",G
01.11 I (H-G)1.13,1.12,1.12
01.12 I (G-L)1.13,1.14,1.14
01.13 T "OUT OF RANGE",!;G 1.1
01.14 S T=T+1
01.15 I (G-S)1.16,1.17,1.18
01.16 T "TOO LOW!",!;G 1.1
01.17 T "CORRECT! GUESSES",%4,T,!;Q
01.18 T "TOO HIGH!",!;G 1.1</syntaxhighlight>
{{out}}
<pre>LOWER LIMIT:1
UPPER LIMIT:100
GUESS:0
OUT OF RANGE
GUESS:101
OUT OF RANGE
GUESS:50
TOO LOW!
GUESS:75
TOO LOW!
GUESS:87
TOO LOW!
GUESS:94
TOO HIGH!
GUESS:90
CORRECT! GUESSES= 5</pre>
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 1,271 ⟶ 1,850:
end if
end do
end program</
Output
<pre>I have chosen a number bewteen 1 and 100 and you have to try to guess it.
Line 1,289 ⟶ 1,868:
=={{header|FreeBASIC}}==
<
Randomize
Line 1,310 ⟶ 1,889:
End If
Loop
End</
Sample input/output
Line 1,324 ⟶ 1,903:
Correct, well guessed!
</pre>
=={{header|Frink}}==
<syntaxhighlight lang="frink">// Guess a Number with feedback.
target = random[1,100] // Min and max are both inclusive for the random function
guess = 0
println["Welcome to guess a number! I've picked a number between 1 and 100. Try to guess it!"]
while guess != target
{
guessStr = input["What is your guess?"]
guess = parseInt[guessStr]
if guess == undef
{
println["$guessStr is not a valid guess. Please enter a number from 1 to 100."]
next
}
if guess < target
println["My number is higher than $guess."]
if guess > target
println["My number is lower than $guess."]
if guess == target
println["$guess is correct! Well guessed!"]
}
</syntaxhighlight>
{{out}}
Including an example with a non-integer entered.
<pre>Welcome to guess a number! I've picked a number between 1 and 100. Try to guess it!
My number is lower than 50.
My number is higher than 25.
ABC is not a valid guess. Please enter a number from 1 to 100.
My number is lower than 37.
My number is higher than 31.
34 is correct! Well guessed!
</pre>
=={{header|FTCBASIC}}==
<syntaxhighlight lang="basic">rem Hilo number guessing game
rem compile with FTCBASIC to 704 bytes com program file
use time.inc
use random.inc
define try = 0, tries = 0, game = 0
gosub systemtime
let randseed = loworder
let randlimit = 100
do
gosub intro
gosub play
gosub continue
loop try = 0
end
sub intro
bell
cls
print "Hilo game"
crlf
return
sub play
gosub generaterand
+1 rand
0 tries
let game = 1
print "Guess the number between 1 and 100"
crlf
do
+1 tries
input try
crlf
if try = rand then
let game = 0
print "You guessed the number!"
print "Tries: " \
print tries
endif
if game = 1 then
if try > rand then
print "Try lower..."
endif
if try < rand then
print "Try higher..."
endif
endif
crlf
loop game = 1
return
sub continue
print "Enter 0 to play again or 1 to EXIT to DOS"
input try
return</syntaxhighlight>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
Short n // We'll just do 1..10 to get the idea
void local fn BuildInterface
Short i
window 1, @"Guess the number", ( 0, 0, 340, 120 )
for i = 1 to 10
button i,,, fn StringWithFormat(@"%d", i), ( 26 * i, 60, 40, 22 )
ButtonSetBordered( i, No )
next
button 11,,, @"Quit", ( 38, 10, 95, 32 )
button 12,,, @"Again", ( 200, 10, 95, 32 )
textlabel 13, @"Guess the number:", ( 112, 85, 200, 22 )
textlabel 14,, ( 158, 30, 100, 22 ) // Hints here
filemenu 1 : menu 1, -1, No // Build but disable File menu
editmenu 2 : menu 2, -1, No // Build but disable Edit menu
end fn
void local fn newGame
CFRange r = fn RangeMake( 1, 10 )
ControlRangeSetEnabled( r, Yes ) // Enable number buttobns
button 11, No // Disable Quit button
button 12, No // Disable Again button
n = rnd( 10 ) // Choose a random number
textlabel 14, @"🔴" // Not found yet
end fn
void local fn DoDialog( evt as Long, tag as Long )
CFRange r = fn RangeMake( 1, 10 )
select evt
case _btnClick
button tag, No
select tag
case 11 : end // Quit
case 12 : fn newGame // Again
case n : textlabel 14, @"🟢" // Found
ControlRangeSetEnabled( r, No )
button 11, Yes
button 12, Yes
case < n : textlabel 14, @"➡️"
case > n : textlabel 14, @"⬅️"
end select
case _windowWillClose : end
end select
end fn
fn buildInterface
fn newGame
on dialog fn DoDialog
handleevents
</syntaxhighlight>
=={{header|Genie}}==
<
/*
Number guessing with feedback, in Genie
Line 1,376 ⟶ 2,133:
init
var game = new NumberGuessing(1, 100)
game.start()</
{{out}}
Line 1,414 ⟶ 2,171:
=={{header|Go}}==
<
import (
Line 1,442 ⟶ 2,199:
}
}
}</
=={{header|Groovy}}==
Based on the Java implementation
<
def rand = new Random() // java.util.Random
def range = 1..100 // Range (inclusive)
Line 1,467 ⟶ 2,224:
}
}
</syntaxhighlight>
Example:
<syntaxhighlight lang="text">
The number is in 1..100
Guess the number: ghfvkghj
Line 1,485 ⟶ 2,242:
Guess the number: 92
Your guess is spot on!
</syntaxhighlight>
=={{header|Haskell}}==
<
import Control.Monad
import System.Random
Line 1,512 ⟶ 2,269:
putStrLn "Try to guess my secret number between 1 and 100."
ask `until_` answerIs ans
</syntaxhighlight>
=={{header|HolyC}}==
<
U8 min = 1, max = 100;
Line 1,534 ⟶ 2,291:
if (Str2I64(g) > n)
Print("Your guess was too high.\nTry again: ");
}</
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">
procedure main()
smallest := 5
Line 1,559 ⟶ 2,316:
}
end
</syntaxhighlight>
Output:
Line 1,577 ⟶ 2,334:
=={{header|J}}==
<
game=: verb define
assert. y -: 1 >. <.{.y
Line 1,587 ⟶ 2,344:
smoutput (*x-n){::'You win.';'Too high.';'Too low.'
end.
)</
Note: in computational contexts, J programmers typically avoid loops. However, in contexts which involve progressive input and output and where event handlers are too powerful (too complicated), loops are probably best practice.
Line 1,593 ⟶ 2,350:
Example use:
<syntaxhighlight lang="text"> game 100
Guess my integer, which is bounded by 1 and 100
Guess: 64
Line 1,604 ⟶ 2,361:
Too low.
Guess: 44
You win.</
=={{header|Java}}==
<
import java.util.Scanner;
public class Main
Line 1,634 ⟶ 2,391:
} while (guessedNumber != randomNumber);
}
}</
Demonstration:
<pre>The number is between 1 and 100.
Line 1,651 ⟶ 2,408:
=={{header|JavaScript}}==
<
<form id="guessNumber">
<input type="text" name="guess">
Line 1,657 ⟶ 2,414:
</form>
<p id="output"></p>
<script type="text/javascript"></
<
function verify() {
Line 1,678 ⟶ 2,435:
}
document.getElementById('guessNumber').onsubmit = verify;</
<syntaxhighlight lang
=== Spidermonkey Version ===
<
function main() {
Line 1,726 ⟶ 2,483:
main();
</syntaxhighlight>
Example session:
Line 1,742 ⟶ 2,499:
Your guess: 57
You got it in 6 tries.
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
In the following, a time-based PRNG is used as that is sufficient for
the task. For a different PRNG, see e.g. [[Guess_the_number#jq]]
<syntaxhighlight lang=jq>
# $min and $max can be specified on the command line but for illustrative purposes:
def minmax: [0, 20];
# low-entropy PRNG in range($a;$b) i.e. $a <= prng < $b
# (no checking)
def prng($a;$b): $a + ((now * 1000000 | trunc) % ($b - $a) );
def play:
# extract a number if possible
def str2num:
try tonumber catch null;
minmax as [$min, $max]
| prng($min; $max) as $number
| "The computer has chosen a whole number between \($min) and \($max) inclusive.",
"Please guess the number or type q to quit:",
(label $out
| foreach inputs as $guess (null;
if $guess == "q" then null, break $out
else ($guess|str2num) as $g
| if $g == null or $g < 0 then "Please enter a non-negative integer or q to quit"
elif $g < $min or $g > $max then "That is out of range. Try again"
elif $g > $number then "Too high"
elif $g < $number then "Too low"
else true, break $out
end
end)
| if type == "string" then .
elif . == true then "Spot on!", "Let's start again.\n", play
else empty
end );
play
</syntaxhighlight>
'''Transcript:'''
<pre>
$ jq -nRr -f guess-the-number-with-feedback.jq
The computer has chosen a whole number between 0 and 20 inclusive.
Please guess the number or type q to quit:
10
Too low
16
Too high
14
Too high
12
Too high
11
Spot on!
Let's start again.
The computer has chosen a whole number between 0 and 20 inclusive.
Please guess the number or type q to quit:
19
Too high
q
Please enter a non-negative integer or q to quit
q
$</pre>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
number = rand(1:n)
print("I choose a number between 1 and $n\nYour guess? ")
Line 1,760 ⟶ 2,584:
end
guesswithfeedback(10)</
{{out}}
Line 1,772 ⟶ 2,596:
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.random.Random
fun main(
val n = 1 + rand.nextInt(20)
println("Guess which number I've chosen in the range 1 to 20\n")
while (true) {
print(" Your guess : ")
val guess = readLine()
when (guess) {
n -> { println("Correct, well guessed!") ; return }
Line 1,789 ⟶ 2,611:
}
}
}</
Sample inout/output
{{out}}
Line 1,806 ⟶ 2,628:
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def game
Line 1,828 ⟶ 2,650:
{game {pow 2 32}} // 2**32 = 4294967296
</syntaxhighlight>
Sample inout/output
Line 1,869 ⟶ 2,691:
=={{header|Lasso}}==
<
local(
Line 1,901 ⟶ 2,723:
#status = true
}
}</
With range value 8 and 73. Correct number 13
Line 1,917 ⟶ 2,739:
=={{header|LFE}}==
<
(defmodule guessing-game
(export (main 0)))
Line 1,939 ⟶ 2,761:
(: random uniform 10)
(get-player-guess)))
</syntaxhighlight>
From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):
<
> (slurp '"guessing-game.lfe")
#(ok guessing-game)
Line 1,958 ⟶ 2,780:
ok
>
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
[start]
target = int( rnd( 1) * 100) +1
Line 1,979 ⟶ 2,800:
if c >target then print " Your guess was too high."
wend
</syntaxhighlight>
=={{header|LiveCode}}==
<
local tNumber, tguess, tmin, tmax
if lowN is empty or lowN < 1 then
Line 2,012 ⟶ 2,831:
end if
end repeat
end guessTheNumber</
Test
<
guessTheNumber --defaults to 1-10
guessTheNumber 9,12
end testGuessNumber</
=={{header|Locomotive Basic}}==
<
20 PRINT "Please specify lower and upper limits":guess=0
30 INPUT " (must be positive integers) :", first, last
Line 2,034 ⟶ 2,852:
110 INPUT "That's correct! Another game (y/n)? ", yn$
120 IF yn$="y" THEN 20
</syntaxhighlight>
Output:
Line 2,042 ⟶ 2,860:
=={{header|Logo}}==
{{trans|UNIX Shell}}
<
local "number
make "number random :max
Line 2,067 ⟶ 2,885:
]
end
</syntaxhighlight>
Sample run:<pre>? guess
Line 2,084 ⟶ 2,902:
=={{header|Lua}}==
<
me_win=false
my_number=math.random(1,10)
Line 2,106 ⟶ 2,924:
end
end
</syntaxhighlight>
<pre>
Line 2,121 ⟶ 2,939:
That was correct.
</pre>
=={{header|M2000 Interpreter}}==
{{trans|BASIC256}}
<syntaxhighlight lang="m2000 interpreter">
Module GuessNumber {
Read Min, Max
Line 2,153 ⟶ 2,970:
}
GuessNumber 5, 15
</syntaxhighlight>
{{out}}
Line 2,159 ⟶ 2,976:
=={{header|Maple}}==
<
local number, input;
randomize():
Line 2,175 ⟶ 2,992:
end if;
end do:
end proc:</
<syntaxhighlight lang
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Module[{number = RandomInteger[{min, max}], guess},
While[guess =!= number,
Line 2,188 ⟶ 3,005:
ToString@max <> "."]]];
CreateDialog[{"Well guessed!", DefaultButton[]}]];
guessnumber[1, 10]</
=={{header|MATLAB}} / {{header|Octave}}==
{{untested|Octave}}
Tested in MATLAB. Untested in Octave.
<
if nargin < 1 || ~isnumeric(low) || length(low) > 1 || isnan(low)
Line 2,218 ⟶ 3,035:
gs = '';
end
end</
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
Range = [1,100]
randomNumber = (random Range.x Range.y) as integer
Line 2,236 ⟶ 3,054:
)
)
</syntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
Enter a number between 1 and 100: 5
Too low!
Line 2,253 ⟶ 3,071:
Well guessed!
OK
</syntaxhighlight>
=={{header|Mirah}}==
<
s = System.console.readLine()
Integer.parseInt(s)
Line 2,281 ⟶ 3,099:
puts "Please enter an integer."
end
end</
=={{header|Modula-2}}==
<
IMPORT InOut, Random, NumConv, Strings;
Line 2,323 ⟶ 3,141:
InOut.WriteString ("Thank you for playing; have a nice day!");
InOut.WriteLn
END guessf.</
<pre>I have chosen a number below 1000; please try to guess it.
Enter your guess : 500
Line 2,336 ⟶ 3,154:
Your guess is spot on!
Thank you for playing; have a nice day!</pre>
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">import Nanoquery.Util
random = new(Random)
inclusive_range = {1, 100}
print format("Guess my target number that is between %d and %d (inclusive).\n",\
inclusive_range[0], inclusive_range[1])
target = random.getInt(inclusive_range[1]) + inclusive_range[0]
answer = 0
i = 0
while answer != target
i += 1
print format("Your guess(%d): ", i)
txt = input()
valid = true
try
answer = int(txt)
catch
println format(" I don't understand you input of '%s' ?", txt)
value = false
end
if valid
if (answer < inclusive_range[0]) or (answer > inclusive_range[1])
println " Out of range!"
else if answer = target
println " Ye-Haw!!"
else if answer < target
println " Too low."
else if answer > target
println " Too high."
end
end
end
println "\nThanks for playing."</syntaxhighlight>
=={{header|Nemerle}}==
<
using System.Console;
Line 2,364 ⟶ 3,221:
} while (guess != secret)
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 2,429 ⟶ 3,286:
return
</syntaxhighlight>
=={{header|NewLISP}}==
<
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number/With_feedback
Line 2,459 ⟶ 3,316:
(println "\nWell guessed! Congratulations!")
(exit)</
Sample output:
Line 2,477 ⟶ 3,334:
=={{header|Nim}}==
<syntaxhighlight lang
randomize()
Line 2,484 ⟶ 3,341:
echo "Guess my target number that is between ", iRange.a, " and ", iRange.b, " (inclusive)."
let target =
var answer, i = 0
while answer != target:
inc i
let txt = stdin.readLine()
try: answer = parseInt(txt)
except ValueError:
echo " I don't understand your input of '", txt, "'"
continue
if answer
elif answer < target: echo " Too low."
elif answer > target: echo " Too high."
else: echo " Ye-Haw!!"
echo "Thanks for playing."</
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 NUMBER=RND(10)+1
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
30 IF GUESS>NUMBER THEN PRINT "MY NUMBER IS LOWER THAN THAT.": GOTO 20
40 IF GUESS<NUMBER THEN PRINT "MY NUMBER IS HIGHER THAN THAT.": GOTO 20
50 PRINT "THAT'S THE CORRECT NUMBER."</syntaxhighlight>
=={{header|Objeck}}==
<
bundle Default {
Line 2,556 ⟶ 3,400:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
try read_int()
with _ ->
Line 2,594 ⟶ 3,438:
loop ()
in
loop ()</
Playing the game:
Line 2,627 ⟶ 3,471:
=={{header|Octave}}==
<
% Guess a number (with feedback)
% http://rosettacode.org/wiki/Guess_the_number/With_feedback
Line 2,653 ⟶ 3,497:
end
end
disp('Well guessed!')</
=={{header|Oforth}}==
<
: guessNumber(a, b)
Line 2,667 ⟶ 3,511:
g n == ifTrue: [ "You found it !" .cr return ]
g n < ifTrue: [ "Less" ] else: [ "Greater" ] . "than the target" .cr
again ;</
=={{header|Ol}}==
<syntaxhighlight lang="ol">
(import (otus random!))
Line 2,697 ⟶ 3,541:
((= guess number)
(print "Well guessed!")))))
</syntaxhighlight>
=={{header|ooRexx}}==
Line 2,724 ⟶ 3,551:
entering ? shows the number we are looking for
This program should, of course, also work with all other Rexxes
<syntaxhighlight lang="oorexx">
/*REXX program that plays the guessing (the number) game. */
low=1 /*lower range for the guessing game.*/
Line 2,781 ⟶ 3,608:
ser: say; say '*** error ! ***'; say arg(1); say; return
</syntaxhighlight>
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">guess_the_number(N=10)={
a=random(N);
print("guess the number between 0 and "N);
for(x=1,N,
if(x>1,
if(b>a,
print("guess again lower")
,
print("guess again higher")
);
b=input();
if(b==a,break())
);
print("You guessed it correctly")
};</syntaxhighlight>
=={{header|Pascal}}==
See [[Guess_the_number#Delphi | Delphi]]
=={{header|Perl}}==
<
my $prompt = shift;
while (1) {
Line 2,804 ⟶ 3,649:
while ($_ = $tgt <=> prompt "Your guess");
print "Correct! You guessed it after $tries tries.\n";</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Guess_the_number3.exw
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.1"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (VALUECHANGED_CB fix)</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">lower_limit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">upper_limit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">secret</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand_range</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lower_limit</span><span style="color: #0000FF;">,</span><span style="color: #000000;">upper_limit</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Enter your guess, a number between %d and %d"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">prompt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">lower_limit</span><span style="color: #0000FF;">,</span><span style="color: #000000;">upper_limit</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">label</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">input</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">state</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*input*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">guess</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;"><</span><span style="color: #000000;">secret</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"Too low"</span><span style="color: #0000FF;">:</span>
<span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">=</span><span style="color: #000000;">secret</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"You got it!"</span><span style="color: #0000FF;">:</span>
<span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">></span><span style="color: #000000;">secret</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"Too high"</span><span style="color: #0000FF;">:</span>
<span style="color: #008000;">"uh?"</span><span style="color: #0000FF;">)))</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">state</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">label</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prompt</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">input</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"VALUE=0, EXPAND=HORIZONTAL, MASK="</span><span style="color: #0000FF;">&</span><span style="color: #004600;">IUP_MASK_INT</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">state</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttributes</span><span style="color: #0000FF;">({</span><span style="color: #000000;">label</span><span style="color: #0000FF;">,</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #000000;">state</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"PADDING=0x15"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">label</span><span style="color: #0000FF;">,</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #000000;">state</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"MARGIN=15x15"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">`TITLE="Guess the number"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
=={{header|PHP}}==
<
<?php
Line 2,904 ⟶ 3,744:
</body>
</html>
</syntaxhighlight>
=={{header|PicoLisp}}==
{{trans|PureBasic}}
<
(use (Low High Guess)
(until
Line 2,926 ⟶ 3,766:
"Your guess is too "
(if (> Number Guess) "low" "high")
"." ) ) ) ) )</
Output:
<pre>: (guessTheNumber)
Line 2,938 ⟶ 3,778:
You got it!</pre>
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">The low number is 1.
The high number is 100.
To run:
Start up.
Play the guessing game.
Wait for the escape key.
Shut down.
To play the guessing game:
Pick a secret number between the low number and the high number.
Write "I chose a secret number between " then the low number then " and " then the high number then "." then the return byte on the console.
Loop.
Ask the user for a number.
If the number is the secret number, break.
If the number is less than the secret number, write " Too low." on the console.
If the number is greater than the secret number, write " Too high." on the console.
Repeat.
Write " Well guessed!" on the console.
To ask the user for a number:
Write "Your guess? " to the console without advancing.
Read a string from the console.
If the string is not any integer, write " Guess must be an integer." on the console; repeat.
Convert the string to the number.
If the number is less than the low number, write " Guess can't be lower than " then the low number then "." on the console; repeat.
If the number is greater than the high number, write " Guess can't be higher than " then the high number then "." on the console; repeat.</syntaxhighlight>
{{out}}
<pre>
I chose a secret number between 1 and 100.
Your guess? apple
Guess must be an integer.
Your guess? 3.14159
Guess must be an integer.
Your guess? -50
Guess can't be lower than 1.
Your guess? 150
Guess can't be higher than 100.
Your guess? 50
Too high.
Your guess? 25
Too low.
Your guess? 37
Too low.
Your guess? 43
Too low.
Your guess? 46
Too low.
Your guess? 48
Well guessed!
</pre>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function Get-Guess
{
Line 2,986 ⟶ 3,880:
Write-Host ("The number was {0} and it took {1} guesses to find it." -f $answer.Number, $answer.Guesses.Count)
</syntaxhighlight>
{{Out}}
<pre>
Line 3,006 ⟶ 3,900:
The number was 73 and it took 6 guesses to find it.
</pre>
=={{header|Prolog}}==
Line 3,033 ⟶ 3,905:
{{works with|SWI-Prolog|6}}
<
play_guess_number.
Line 3,069 ⟶ 3,941:
; Guess > N -> writeln('Your guess is too high.')
; Guess =:= N -> writeln("Correct!")
).</
Input in the standard Prolog top level is terminated with a `.`: E.g.,
<
Guess an integer between 1 and 10.
Guess the number: a.
Invalid input.
Guess the number: 3.
Your guess is too low.</
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">OpenConsole()
Repeat
; Ask for limits, with sanity check
Print("Enter low limit : "): low =Val(Input())
Print("Enter high limit: "): High =Val(Input())
Until High>low
TheNumber=Random(High-low)+low
Debug TheNumber
Repeat
Print("Guess what number I have: "): Guess=Val(Input())
If Guess=TheNumber
PrintN("You got it!"): Break
ElseIf Guess < TheNumber
PrintN("Your guess is to low.")
Else
PrintN("Your guess is to high.")
EndIf
ForEver</syntaxhighlight>
=={{header|Python}}==
<
inclusive_range = (1, 100)
Line 3,107 ⟶ 4,001:
if answer > target: print(" Too high.")
print("\nThanks for playing.")</
'''Sample Game'''
Line 3,141 ⟶ 4,035:
I don't understand your input of 'Howdy' ?
Your guess(4): </pre>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ say "Guess the number (1-100 inclusive.)"
cr cr
100 random 1+
[ $ "Your guess... " input
trim reverse trim reverse
$->n
not iff
[ drop
say "That is not a number." cr ]
again
2dup != while
over < iff
[ say "Too small." cr ]
again
say "Too large." cr
again ]
say "Well done! "
echo say " is correct. " cr
drop ] is guess-the-number ( --> )</syntaxhighlight>
{{out}}
In the Quackery shell.
<pre>/O> guess-the-number
...
Guess the number (1-100 inclusive.)
Your guess... eleventy thruppence
That is not a number.
Your guess... 50
Too small.
Your guess... 75
Too small.
Your guess... 83
Too large.
Your guess... 79
Too large.
Your guess... 77
Too large.
Your guess... 76
Well done! 76 is correct.
Stack empty.
/O></pre>
=={{header|R}}==
The previous solution lacked the required checks for if the input was appropriate, was bugged if low==high (R's sample function works differently if the input is of length 1), and behaved very strangely if low or high weren't whole numbers.
This solution works on the assumption that the number to be found is an integer and also assumes that the upper and lower bounds are distinct integers used inclusively. For example, this means that low=4 and high=5 should be a solvable case, but low=high=4 will throw an error. See [[Talk:Guess the number/With feedback|Talk page]] entry dated 1st June 2020.
<syntaxhighlight lang="rsplus">guessANumber <- function(low, high)
{
boundryErrorCheck(low, high)
goal <-
guess <- getValidInput(paste0("I have a whole number between ", low, " and ", high, ". What's your guess? "))
while(guess != goal)
if(guess < low || guess > high){guess <- getValidInput("Out of range! Try again "); next}
if(guess > goal){guess <- getValidInput("Too high! Try again "); next}
if(guess < goal){guess <- getValidInput("Too low! Try again "); next}
}
"Winner!"
}
boundryErrorCheck <- function(low, high)
{
if(!is.numeric(low) || as.integer(low) != low) stop("Lower bound must be an integer. Try again.")
if(!is.numeric(high) || as.integer(high) != high) stop("Upper bound must be an integer. Try again.")
if(high < low) stop("Upper bound must be strictly greater than lower bound. Try again.")
if(low == high) stop("This game is impossible to lose. Try again.")
invisible()
}
#R's system for checking if numbers are integers is lacking (e.g. is.integer(1) returns FALSE)
#so we need this next function.
#A better way to check for integer inputs can be found in is.interger's docs, but this is easier to read.
#Note that readline outputs the user's input as a string, hence the need for type.convert.
getValidInput <- function(requestText)
{
guess <- type.convert(readline(requestText))
while(!is.numeric(guess) || as.integer(guess) != guess){guess <- type.convert(readline("That wasn't an integer! Try again "))}
as.integer(guess)
}</syntaxhighlight>
=={{header|Racket}}==
<
(define (guess-number min max)
Line 3,178 ⟶ 4,143:
(guess-number 1 100)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my $maxnum = prompt("Hello, please give me an upper boundary: ");
until 0 < $maxnum < Inf {
say "Oops! The upper boundary should be > 0 and not Inf";
$maxnum = prompt("Please give me a valid upper boundary: ");
}
my $count = 0;
my $number = (1..$maxnum).pick;
say "I'm thinking of a number from 1 to $maxnum, try to guess it!";
repeat until my $guessed-right {
given prompt("Your guess: ") {
when /^[e|q]/ { say 'Goodbye.'; exit; }
when not 1 <= $_ <= $maxnum {
say "You really should give me a number from 1 to $maxnum."
}
$count++;
when $number { $guessed-right = True }
when $number < $_ { say "Sorry, my number is smaller." }
when $number > $_ { say "Sorry, my number is bigger." }
}
}
say "Great you guessed right after $count attempts!";</syntaxhighlight>
<pre>Hello, please give me an upper boundary: 10
I'm thinking of a number from 1 to 10, try to guess it!
Your guess: 5
Sorry, my number is bigger.
Your guess: 7
Sorry, my number is smaller.
Your guess: 6
Great you guessed right after 3 attempts!</pre>
=={{header|Retro}}==
<
over > [ "high" ] [ "low" ] if ;
Line 3,196 ⟶ 4,197:
think [ getToken toNumber checkGuess ] while
"You got it!\n" puts ;
</syntaxhighlight>
=={{header|REXX}}==
To make the program more engaging, randomized words for the hint are used.
<
low=
high=
try=
r= random(
lows= 'too_low too_small too_little below under underneath too_puny'
highs= 'too_high too_big too_much above over over_the_top too_huge'
erm= '***error***'
@gtn= "guess the number, it's between"
prompt= centre(@gtn low 'and' high '(inclusive) ───or─── Quit:', 79, "─")
/* [↓] BY 0 ─── used to LEAVE a loop*/
do ask=0 by 0; say; say prompt; say; pull g; g= space(g); say
do validate=0 by 0 /*DO index required; LEAVE instruction.*/
select
when g=='' then iterate ask
when abbrev('QUIT', g, 1) then exit /*what a whoos.*/
when words(g) \==
when \datatype(g, 'N') then say erm g "isn't numeric"
when \datatype(g, 'W') then say erm g "isn't a whole number"
Line 3,226 ⟶ 4,227:
end /*validate*/
try= try + 1
if g=r then leave
if g>r then what= word(highs, random(1, words(highs) ) )
else what= word( lows, random(1, words( lows) ) )
say 'your guess of' g "is" translate(what
end /*ask*/
/*stick a fork in it, we're all done. */
if try==1 then say 'Gadzooks!!! You guessed the number right away!'
else say 'Congratulations!, you guessed the number in ' try " tries."</syntaxhighlight>
=={{header|Ring}}==
<
while true
see "Hey There,
Line 3,268 ⟶ 4,268:
d = random(e)
if d >= s return d ok
end</
=={{header|Ruby}}==
{{trans|Mirah}}
<
puts "Guess the number between 1 and 10"
Line 3,290 ⟶ 4,290:
puts "Please enter an integer."
end
end</
=={{header|Rust}}==
{{libheader|rand}}
<syntaxhighlight lang
use
use std::io;
const LOWEST: u32 = 1;
const HIGHEST: u32 = 100;
fn main() {
let
println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST);
loop {
println!("Please input your guess.");
let mut guess = String::new();
.expect("Failed to read line");
Err(_) => continue,
};
println!("You guessed: {}",
match
Ordering::Less
Ordering::Greater => println!("Too
Ordering::Equal =>
}
}
}
}</
<pre>I have chosen my number between
Please input your guess.
5
You guessed: 5
Too small!
Please input your guess.
50
You guessed: 50
Too small!
Please input your guess.
80
You guessed: 80
Too big!
Please input your guess.
67
You guessed: 67
Too big!
Please input your guess.
57
You guessed: 57
Too small!
Please input your guess.
63
You guessed: 63
Too small!
Please input your guess.
65
You guessed: 65
Too small!
Please input your guess.
66
You guessed: 66
You win!</pre>
=={{header|Scala}}==
<
import java.util.Scanner
Line 3,362 ⟶ 4,383:
else if (guessedNumber < randomNumber) println("Your guess is too low!")
else println("You got it!")
} while (guessedNumber != randomNumber)</
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
{{works with|Guile}}
<
(define minimum -5)
(define number (+ (random (- (+ maximum 1) minimum)) minimum))
Line 3,383 ⟶ 4,405:
(if (< guess number)
(display "Too low!\n> ")))))
(display "Correct!\n")</
=={{header|Seed7}}==
<
const integer: lower_limit is 0;
Line 3,412 ⟶ 4,434:
writeln("You gave up!");
end if;
end func;</
=={{header|Sidef}}==
{{trans|Ruby}}
<
say "Guess the number between 1 and 10";
Line 3,425 ⟶ 4,447:
default { say "Too high" }
}
}</
=={{header|Small Basic}}==
<
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
Line 3,439 ⟶ 4,461:
EndIf
EndWhile
TextWindow.WriteLine("You win!")</
=={{header|Smalltalk}}==
{{works with|Pharo|7.0.3}}
To load:
Save the example. In a Pharo image, go to "Tools" -> "File Browser" -> Select the file... -> Filein.
To play: run "GuessingGame playFrom: 1 to: 100" on a Workspace (Tools -> Workspace)
<syntaxhighlight lang="smalltalk">
'From Pharo7.0.3 of 12 April 2019 [Build information: Pharo-7.0.3+build.158.sha.0903ade8a6c96633f07e0a7f1baa9a5d48cfdf55 (64 Bit)] on 30 October 2019 at 4:24:17.115807 pm'!
Object subclass: #GuessingGame
instanceVariableNames: 'min max uiManager tries'
classVariableNames: ''
poolDictionaries: ''
category: 'GuessingGame'!
!GuessingGame methodsFor: 'initialization' stamp: 'EduardoPadoan 10/26/2019 23:51'!
initialize
uiManager := UIManager default.
tries := 0! !
!GuessingGame methodsFor: 'services' stamp: 'EduardoPadoan 10/26/2019 23:40'!
alert: aString
uiManager alert: aString! !
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
max
^ max! !
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
min
^ min! !
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
min: anObject
min := anObject! !
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
max: anObject
max := anObject! !
!GuessingGame methodsFor: 'playing-main' stamp: 'EduardoPadoan 10/27/2019 00:18'!
play
| toGuess |
toGuess := self selectNumber.
[ :break |
| choice |
[
choice := self getGuessOrExitWith: break.
choice
ifNil: [ self alert: 'Invalid Input' ]
ifNotNil: [
self incrementTries.
choice = toGuess
ifTrue: [ self congratulateForGuess: choice andExitWith: break ]
ifFalse: [ choice > toGuess ifTrue: [ self alert: 'Too high' ]
ifFalse: [ self alert: 'Too low' ] ]
]
] repeat.
] valueWithExit.! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:39'!
makeRequest: aString
^ uiManager request: aString! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:48'!
getGuessOrExitWith: anExitBlock
^ [(self makeRequest: 'Guess number a between , min,' and ', max, '.') asInteger]
on: MessageNotUnderstood "nil"
do: [
self sayGoodbye.
anExitBlock value ].! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:51'!
incrementTries
tries := tries + 1! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:05'!
sayGoodbye
self alert: 'Gave up? Sad.'.! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:15'!
congratulateForGuess: anInteger andExitWith: anExitBlock
self alert: 'Correct!! The value was indeed ', anInteger asString, '. Took you only ', tries asString, ' tries.'.
^ anExitBlock value! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:35'!
selectNumber
^ (min to: max) atRandom ! !
"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!
GuessingGame class
slots: { }!
!GuessingGame class methodsFor: 'creating' stamp: 'EduardoPadoan 10/27/2019 00:15'!
playFrom: aMinNumber to: aMaxNumber
self new
min: aMinNumber;
max: aMaxNumber;
play! !
</syntaxhighlight>
=={{header|Sparkling}}==
<
let lowerBound = toint(getline());
Line 3,468 ⟶ 4,598:
break;
}
}</
=={{header|Swift}}==
<
var found = false
Line 3,492 ⟶ 4,623:
println("Good try but the number is less than that!")
}
}</
=={{header|Tcl}}==
<
set to 10
set target [expr {int(rand()*($to-$from+1) + $from)}]
Line 3,514 ⟶ 4,645:
break
}
}</
Sample output:
<pre>
Line 3,533 ⟶ 4,664:
Well done! You guessed it.
</pre>
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
Line 3,555 ⟶ 4,687:
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP
</syntaxhighlight>
Output:
<pre>
Line 3,582 ⟶ 4,714:
{{works with|Public Domain Korn SHell}}
{{works with|Z SHell}}
<
[[ -n $BASH_VERSION ]] && shopt -s extglob
[[ -n $ZSH_VERSION ]] && set -o KSH_GLOB
Line 3,607 ⟶ 4,739:
fi
done
}</
Sample run:
Line 3,626 ⟶ 4,758:
=={{header|Ursa}}==
{{trans|Python}}
<
set low 0
set high 100
Line 3,655 ⟶ 4,787:
end while
out endl "Thanks for playing." endl console</
=={{header|Vala}}==
<
void main(){
const int from = 1;
Line 3,690 ⟶ 4,822:
}//while
} // main
</syntaxhighlight>
Shorter but no error checking
<
int guess, x = Random.int_range(1, 10);
stdout.printf("Make a guess (1-10): ");
Line 3,701 ⟶ 4,833:
stdout.printf("Got it!\n");
return 0;
}</
=={{header|VBA Excel}}==
The Application.InputBox display a message when input is inappropriate.
<
Dim Nbc&, Nbp&, m&, n&, c&
Line 3,722 ⟶ 4,854:
Loop
MsgBox "Well guessed!" & vbCrLf & "You find : " & Nbc & " in " & c & " guesses!"
End Sub</
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Dim max,min,secretnum,numtries,usernum
max=100
Line 3,752 ⟶ 4,884:
End If
Loop
</syntaxhighlight>
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import rand.seed
import rand
import os
const (
lower = 1
upper = 100
)
fn main() {
rand.seed(seed.time_seed_array(2))
n := rand.intn(upper-lower+1) or {0} + lower
for {
guess := os.input("Guess integer number from $lower to $upper: ").int()
if guess < n {
println("Too low. Try again: ")
} else if guess > n {
println("Too high. Try again: ")
} else {
println("Well guessed!")
return
}
}
}</syntaxhighlight>
=={{header|VTL-2}}==
<syntaxhighlight lang="vtl2">10 ?="Minimum? ";
20 L=?
30 ?="Maximum? ";
40 H=?
50 #=L<H*80
60 ?="Minimum must be lower than maximum."
70 #=10
80 S='/(H-L+1)*0+L+%
90 T=0
100 ?="Guess? ";
110 G=?
120 #=G>L*(H>G)*150
130 ?="Guess must be in between minimum and maximum."
140 #=100
150 T=T+1
160 #=G=S*220
170 #=G<S*200
180 ?="Too high."
190 #=100
200 ?="Too low."
210 #=100
220 ?="Correct!"
230 ?="Tries: ";
240 ?=T</syntaxhighlight>
{{out}}
<pre>Minimum? 10
Maximum? 90
Guess? 91
Guess must be in between minimum and maximum.
Guess? 9
Guess must be in between minimum and maximum.
Guess? 50
Too low.
Guess? 70
Too high.
Guess? 60
Too high.
Guess? 55
Correct!
Tries: 4</pre>
=={{header|Wren}}==
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout
import "random" for Random
var rand = Random.new()
var n = rand.int(1, 21) // computer number from 1..20 inclusive, say
System.print("The computer has chosen a number between 1 and 20 inclusive.")
while (true) {
System.write(" Your guess 1-20 : ")
Stdout.flush()
var g = Num.fromString(Stdin.readLine())
if (!g || g.type != Num || !g.isInteger || g < 1 || g > 20) {
System.print(" Inappropriate")
} else if (g > n) {
System.print(" Too high")
} else if (g < n) {
System.print(" Too low")
} else {
System.print(" Spot on!")
break
}
}</syntaxhighlight>
{{out}}
Sample session:
<pre>
The computer has chosen a number between 1 and 20 inclusive.
Your guess 1-20 : 21
Inappropriate
Your guess 1-20 : 1.5
Inappropriate
Your guess 1-20 : abc
Inappropriate
Your guess 1-20 : 10
Too low
Your guess 1-20 : 15
Too high
Your guess 1-20 : 13
Too high
Your guess 1-20 : 12
Too high
Your guess 1-20 : 11
Spot on!
</pre>
=={{header|XLISP}}==
<
; minimum and maximum, to be supplied by the user
(defun prompt ()
Line 3,780 ⟶ 5,026:
(display ". Try to guess it!")
(newline)
(prompt))</
{{out}}
<pre>[1] (guessing-game 19 36)
Line 3,802 ⟶ 5,048:
=={{header|XPL0}}==
<
int Lo, Hi, C, Guess, Number;
Line 3,825 ⟶ 5,071:
CrLf(0);
until Guess = Number;
]</
Example output:
Line 3,843 ⟶ 5,089:
=={{header|zkl}}==
<
while(1){
n:=ask("Num between 1 & 10: ");
Line 3,849 ⟶ 5,095:
if(n==r){ println("Well guessed!"); break; }
println((n<r) and "small" or "big");
}</
{{out}}
<pre>
Line 3,863 ⟶ 5,109:
Well guessed!
</pre>
=={{header|Zoomscript}}==
For typing:
<syntaxhighlight lang="zoomscript">var randnum
var guess
randnum & random 1 10
guess = 0
while ne randnum guess
print "I'm thinking of a number between 1 and 10. What is it? "
guess & get
if lt guess randnum
print "Too low. Try again!"
println
endif
if gt guess randnum
print "Too high. Try again!"
println
endif
endwhile
print "Correct number. You win!"</syntaxhighlight>
For importing:
¶0¶var randnum¶0¶var guess¶0¶randnum & random 1 10¶0¶guess = 0¶0¶while ne randnum guess¶0¶print "I'm thinking of a number between 1 and 10. What is it? "¶0¶guess & get¶0¶if lt guess randnum¶0¶print "Too low. Try again!"¶0¶println¶0¶endif¶0¶if gt guess randnum¶0¶print "Too high. Try again!"¶0¶println¶0¶endif¶0¶endwhile¶0¶print "Correct number. You win!"
=={{header|ZX Spectrum Basic}}==
<
1 LET n=INT (RND*10)+1
2 INPUT "Guess a number that is between 1 and 10: ",g: IF g=n THEN PRINT "That's my number!": STOP
3 IF g<n THEN PRINT "That guess is too low!": GO TO 2
4 IF g>n THEN PRINT "That guess is too high!": GO TO 2</
|