Guess the number: Difference between revisions

From Rosetta Code
Content added Content deleted
 
(17 intermediate revisions by 10 users not shown)
Line 22: Line 22:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<lang 11l>V t = random:(1..10)
<syntaxhighlight lang="11l">V t = random:(1..10)
V g = Int(input(‘Guess a number that's between 1 and 10: ’))
V g = Int(input(‘Guess a number that's between 1 and 10: ’))
L t != g
L t != g
g = Int(input(‘Guess again! ’))
g = Int(input(‘Guess again! ’))
print(‘That's right!’)</lang>
print(‘That's right!’)</syntaxhighlight>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program guessNumber.s */
/* program guessNumber.s */
Line 137: Line 137:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>REPORT guess_the_number.
<syntaxhighlight lang="abap">REPORT guess_the_number.


DATA prng TYPE REF TO cl_abap_random_int.
DATA prng TYPE REF TO cl_abap_random_int.
Line 165: Line 165:


cl_demo_output=>display( |Well Done| ).
cl_demo_output=>display( |Well Done| ).
</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
BYTE x,n,min=[1],max=[10]
BYTE x,n,min=[1],max=[10]


Line 182: Line 182:
FI
FI
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number.png Screenshot from Atari 8-bit computer]
Line 200: Line 200:
=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Numerics.Discrete_Random;
<syntaxhighlight lang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
with Ada.Text_IO;
procedure Guess_Number is
procedure Guess_Number is
Line 291: Line 291:
New_Line;
New_Line;
end main;</lang>
end main;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>file f;
<syntaxhighlight lang="aime">file f;
integer n;
integer n;
text s;
text s;
Line 314: Line 314:
}
}


o_text("You have won!\n");</lang>
o_text("You have won!\n");</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 321: Line 321:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<lang algol68>main:
<syntaxhighlight lang="algol68">main:
(
(
INT n;
INT n;
Line 339: Line 339:
break:
break:
puts("You have won! ")
puts("You have won! ")
)</lang>
)</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 356: Line 356:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang AppleScript>on run
<syntaxhighlight lang="applescript">on run
-- define the number to be guessed
-- define the number to be guessed
set numberToGuess to (random number from 1 to 10)
set numberToGuess to (random number from 1 to 10)
Line 380: Line 380:
end if
end if
end repeat
end repeat
end run</lang>
end run</syntaxhighlight>




Or, constraining mutation, and abstracting a little to an '''until(predicate, function, value)''' pattern
Or, constraining mutation, and abstracting a little to an '''until(predicate, function, value)''' pattern
<lang AppleScript>-- GUESS THE NUMBER ----------------------------------------------------------
<syntaxhighlight lang="applescript">-- GUESS THE NUMBER ----------------------------------------------------------


on run
on run
Line 459: Line 459:
end tell
end tell
return v
return v
end |until|</lang>
end |until|</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>n: random 1 10
<syntaxhighlight lang="rebol">n: random 1 10


while [notEqual? to :integer input "Guess the number: " n] [
while [notEqual? to :integer input "Guess the number: " n] [
Line 468: Line 468:
]
]


print "Well guessed!"</lang>
print "Well guessed!"</syntaxhighlight>


{{out}}
{{out}}
Line 484: Line 484:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Random, rand, 1, 10 ; This stores a number between 1 and 10 in the var rand using the Mersenne Twister
<syntaxhighlight lang="autohotkey">Random, rand, 1, 10 ; This stores a number between 1 and 10 in the var rand using the Mersenne Twister
msgbox I am thinking of a number between 1 and 10.
msgbox I am thinking of a number between 1 and 10.


Line 498: Line 498:
Msgbox Try again.
Msgbox Try again.
}
}
</syntaxhighlight>
</lang>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang autoit>
<syntaxhighlight lang="autoit">
$irnd = Random(1, 10, 1)
$irnd = Random(1, 10, 1)
$iinput = -1
$iinput = -1
Line 508: Line 508:
WEnd
WEnd
MsgBox(0, "Success", "Well guessed!")
MsgBox(0, "Success", "Well guessed!")
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GUESS_THE_NUMBER.AWK
# syntax: GAWK -f GUESS_THE_NUMBER.AWK
BEGIN {
BEGIN {
Line 531: Line 531:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>10 N% = RND(1) * 10 + 1
<syntaxhighlight lang="applesoftbasic">10 N% = RND(1) * 10 + 1
20 PRINT "A NUMBER FROM 1 ";
20 PRINT "A NUMBER FROM 1 ";
30 PRINT "TO 10 HAS BEEN ";
30 PRINT "TO 10 HAS BEEN ";
Line 544: Line 544:
70 Q = G% = N%
70 Q = G% = N%
80 NEXT
80 NEXT
90 PRINT "WELL GUESSED!"</lang>
90 PRINT "WELL GUESSED!"</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
Line 550: Line 550:
For the most part, identical to the Applesoft BASIC example above, except that Commodore BASIC evaluates TRUE as a value of -1 instead of 1.
For the most part, identical to the Applesoft BASIC example above, except that Commodore BASIC evaluates TRUE as a value of -1 instead of 1.


<lang commodorebasicv2>10 n% = int(rnd(1)*10)+1
<syntaxhighlight lang="commodorebasicv2">10 n% = int(rnd(1)*10)+1
20 print chr$(147);chr$(14)
20 print chr$(147);chr$(14)
30 print "I have chosen a number from 1 to 10."
30 print "I have chosen a number from 1 to 10."
Line 558: Line 558:
70 q = g% = n%
70 q = g% = n%
80 next
80 next
90 print "WELL GUESSED!"</lang>
90 print "WELL GUESSED!"</syntaxhighlight>


{{out}}
{{out}}
Line 573: Line 573:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "Guess.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "Guess.bas"
110 RANDOMIZE
110 RANDOMIZE
120 LET N=RND(10)+1
120 LET N=RND(10)+1
Line 579: Line 579:
140 INPUT PROMPT "Guess a number that's between 1-10: ":G
140 INPUT PROMPT "Guess a number that's between 1-10: ":G
150 LOOP UNTIL N=G
150 LOOP UNTIL N=G
160 PRINT "Well guessed!"</lang>
160 PRINT "Well guessed!"</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}, Gives Hints===
<lang qbasic>supervisor:
<syntaxhighlight lang="qbasic">supervisor:
GOSUB initialize
GOSUB initialize
GOSUB guessing
GOSUB guessing
Line 618: Line 618:
STOP
STOP
END IF
END IF
WEND</lang>
WEND</syntaxhighlight>


==={{header|QBasic}}===
===QBasic, More Polished Version===
A more polished version of this program in QBasic/QB/VB-DOS
A more polished version of this program in QBasic/QB/VB-DOS
<lang qbasic>
<syntaxhighlight lang="qbasic">
' OPTION EXPLICIT ' Remove remark for VB-DOS/PDS 7.1
' OPTION EXPLICIT ' Remove remark for VB-DOS/PDS 7.1
'dIM
'dIM
Line 672: Line 672:


END FUNCTION
END FUNCTION
</syntaxhighlight>
</lang>


==={{header|QB64}}===
==={{header|QB64}}===
The following is a modification of the above polished version in QBasic with explanations of differences.
The following is a modification of the above polished version in QBasic with explanations of differences.
<lang QB64>Randomize Timer 'Moved to the head as it is an initialization statement,
<syntaxhighlight lang="qbasic">Randomize Timer 'Moved to the head as it is an initialization statement,
'although it could be placed anywhere prior to the Rnd() function being called.
'although it could be placed anywhere prior to the Rnd() function being called.


Line 719: Line 719:
Print
Print
Print "End of the program. Thanks for playing."
Print "End of the program. Thanks for playing."
End</lang>
End</syntaxhighlight>

==={{header|ZX Spectrum Basic}}===
ZX Spectrum Basic has no [[:Category:Conditional loops|conditional loop]] constructs, so we have to emulate them here using IF and GO TO.
<lang zxbasic>10 LET n=INT (RND*10)+1
20 INPUT "Guess a number that's between 1 and 10: ",g
30 IF g=n THEN PRINT "That's my number!": STOP
40 PRINT "Guess again!"
50 GO TO 20</lang>

==={{header|QB64}}===


===QB64 Alternative Version, Gives Hints===
Single-line "Guess the Number" program QBasic QB64 from Russia
Single-line "Guess the Number" program QBasic QB64 from Russia
<syntaxhighlight lang="qbasic">
<lang zxbasic>
1 IF Russia = 0 THEN Russia = 2222: RANDOMIZE TIMER: num = INT(RND * 100) + 1: GOTO 1 ELSE IF Russia <> 0 THEN INPUT n: IF n < num THEN PRINT "MORE": GOTO 1 ELSE IF n > num THEN PRINT "less": GOTO 1 ELSE IF n = num THEN PRINT "da": END ELSE GOTO 1 'DANILIN Russia 9-9-2019 guessnum.bas
1 IF Russia = 0 THEN Russia = 2222: RANDOMIZE TIMER: num = INT(RND * 100) + 1: GOTO 1 ELSE IF Russia <> 0 THEN INPUT n: IF n < num THEN PRINT "MORE": GOTO 1 ELSE IF n > num THEN PRINT "less": GOTO 1 ELSE IF n = num THEN PRINT "da": END ELSE GOTO 1 'DANILIN Russia 9-9-2019 guessnum.bas
</syntaxhighlight>
</lang>
The multi-line equivalent of the above.
The multi-line equivalent of the above.
<lang QB64>'Based on DANILIN Russia 9-9-2019 guessnum.bas
<syntaxhighlight lang="qbasic">'Based on DANILIN Russia 9-9-2019 guessnum.bas
1 If c% = 0 Then
1 If c% = 0 Then
c% = 1
c% = 1
Line 754: Line 745:
End
End
End If
End If
End If</lang>
End If</syntaxhighlight>

===QB64 Expanded Range, Auto-Interactive===
<b>Note:</b> This is off-task, as there is no user interaction.<br/><br/>
Program from Russia guesses 1 out of a billion
<syntaxhighlight lang="qbasic">
h1=0: h2=10^9:t=1:f=0: Randomize Timer 'daMilliard.bas
human = Int(Rnd*h2) 'human DANILIN
comp = Int(Rnd*h2) 'comp

While f < 1
Print t; "human ="; human; " comp ="; comp;

If comp < human Then
Print " MORE": a=comp: comp=Int((comp+h2)/2): h1=a

Else If human < comp Then
Print " less": a=comp: comp=Int((h1+comp)/2): h2=a

Else If human=comp Then
Print " win by "; t; " steps": f=1
End If: End If: End If: t = t + 1
Wend: End</syntaxhighlight>
{{out}}
<pre>1 40 11 MORE
2 40 55 less
3 40 33 MORE
4 40 44 less
5 40 38 MORE
6 40 41 less
7 40 39 MORE
8 40 40 win by 8 steps</pre>

==={{header|ZX Spectrum Basic}}===
ZX Spectrum Basic has no [[:Category:Conditional loops|conditional loop]] constructs, so we have to emulate them here using IF and GO TO.
<syntaxhighlight lang="zxbasic">10 LET n=INT (RND*10)+1
20 INPUT "Guess a number that's between 1 and 10: ",g
30 IF g=n THEN PRINT "That's my number!": STOP
40 PRINT "Guess again!"
50 GO TO 20</syntaxhighlight>


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang BASIC256>n = int(rand * 10) + 1
<syntaxhighlight lang="basic256">n = int(rand * 10) + 1
print "I am thinking of a number from 1 to 10"
print "I am thinking of a number from 1 to 10"
do
do
Line 765: Line 795:
endif
endif
until g = n
until g = n
print "Yea! You guessed my number."</lang>
print "Yea! You guessed my number."</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
At the line set /a answer=%random%%%(10-1+1)+1, if you want to change the minimum and maximum numbers, change all number ones (not counting the one that is in 10) to your desired chosen number and for the maximum, which is 10, do the same, but for maximum (eg. the minimum could be 123 and the maximum could be 321, etc.).<lang dos>@echo off
At the line set /a answer=%random%%%(10-1+1)+1, if you want to change the minimum and maximum numbers, change all number ones (not counting the one that is in 10) to your desired chosen number and for the maximum, which is 10, do the same, but for maximum (eg. the minimum could be 123 and the maximum could be 321, etc.).<syntaxhighlight lang="dos">@echo off
set /a answer=%random%%%(10-1+1)+1
set /a answer=%random%%%(10-1+1)+1
set /p guess=Pick a number between 1 and 10:
set /p guess=Pick a number between 1 and 10:
Line 774: Line 804:
if %guess%==%answer% (echo Well guessed!
if %guess%==%answer% (echo Well guessed!
pause) else (set /p guess=Nope, guess again:
pause) else (set /p guess=Nope, guess again:
goto loop)</lang>
goto loop)</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> choose% = RND(10)
<syntaxhighlight lang="bbcbasic"> choose% = RND(10)
REPEAT
REPEAT
INPUT "Guess a number between 1 and 10: " guess%
INPUT "Guess a number between 1 and 10: " guess%
Line 786: Line 816:
PRINT "Sorry, try again"
PRINT "Sorry, try again"
ENDIF
ENDIF
UNTIL FALSE</lang>
UNTIL FALSE</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
Line 792: Line 822:
{{works with|Fungus|0.28}}
{{works with|Fungus|0.28}}
{{works with|CCBI|2.1}}
{{works with|CCBI|2.1}}
<lang Befunge>v RNG anthouse
<syntaxhighlight lang="befunge">v RNG anthouse
> v ,,,,,,<
> v ,,,,,,<
v?v ,
v?v ,
Line 809: Line 839:
+>,,,,,,,,,,,,,,,,^
+>,,,,,,,,,,,,,,,,^
>>>>>>>>>v^"guessthenumber!"+19<
>>>>>>>>>v^"guessthenumber!"+19<
RNG unit > 22p ^</lang>
RNG unit > 22p ^</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
The value is generated by the <code>clk</code> function, which returns a (probably) non-integral rational number. The <code>den</code> function retrieves the denominators of this number. The rational number, multiplied by its denominator, becomes an natural number.
The value is generated by the <code>clk</code> function, which returns a (probably) non-integral rational number. The <code>den</code> function retrieves the denominators of this number. The rational number, multiplied by its denominator, becomes an natural number.
<lang bracmat>( ( GuessTheNumber
<syntaxhighlight lang="bracmat">( ( GuessTheNumber
= mynumber
= mynumber
. clk$:?mynumber
. clk$:?mynumber
Line 824: Line 854:
)
)
& GuessTheNumber$
& GuessTheNumber$
);</lang>
);</syntaxhighlight>


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>number = random 10
<syntaxhighlight lang="brat">number = random 10


p "Guess a number between 1 and 10."
p "Guess a number between 1 and 10."
Line 835: Line 865:
{ p "Well guessed!"; true }
{ p "Well guessed!"; true }
{ p "Guess again!" }
{ p "Guess again!" }
}</lang>
}</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==


<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <time.h>
#include <time.h>
Line 868: Line 898:
puts("That's not my number. Try another guess:");
puts("That's not my number. Try another guess:");
}
}
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


class GuessTheNumberGame
class GuessTheNumberGame
Line 889: Line 919:
Console.WriteLine("Congrats!! You guessed right!");
Console.WriteLine("Congrats!! You guessed right!");
}
}
};</lang>
};</syntaxhighlight>


===Expanded Range, Auto-Interactive===
<b>Note:</b> This is off-task, as there is no user interaction.<br/><br/>
Program from Russia guesses 1 out of a billion<br/>
https://rextester.com/DYVZM84267
<syntaxhighlight lang="csharp">using System; using System.Text; //daMilliard.cs
namespace DANILIN

{ class Program
{ static void Main(string[] args)
{ Random rand = new Random();int t=0;
int h2=100000000; int h1=0; int f=0;
int comp = rand.Next(h2);
int human = rand.Next(h2);

while (f<1)
{ Console.WriteLine();Console.Write(t);
Console.Write(" ");Console.Write(comp);
Console.Write(" ");Console.Write(human);

if(comp < human)
{ Console.Write(" MORE");
int a=comp; comp=(comp+h2)/2; h1=a; }

else if(comp > human)
{ Console.Write(" less");
int a=comp; comp=(h1+comp)/2; h2=a;}

else {Console.Write(" win by ");
Console.Write(t); Console.Write(" steps");f=1;}
t++; }}}}</syntaxhighlight>
{{out}}
<pre>1 40 11 MORE
2 40 55 less
3 40 33 MORE
4 40 44 less
5 40 38 MORE
6 40 41 less
7 40 39 MORE
8 40 40 win by 8 steps</pre>


=={{header|C++}}==
=={{header|C++}}==


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <cstdlib>
#include <cstdlib>
#include <ctime>
#include <ctime>
Line 915: Line 986:
}
}


</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(def target (inc (rand-int 10))
(def target (inc (rand-int 10))


Line 929: Line 1,000:
(println "Try again")
(println "Try again")
(recur (inc n))))))
(recur (inc n))))))
</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Guess-The-Number.
PROGRAM-ID. Guess-The-Number.


Line 956: Line 1,027:
GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>num = Math.ceil(Math.random() * 10)
<syntaxhighlight lang="coffeescript">num = Math.ceil(Math.random() * 10)
guess = prompt "Guess the number. (1-10)"
guess = prompt "Guess the number. (1-10)"
while parseInt(guess) isnt num
while parseInt(guess) isnt num
guess = prompt "YOU LOSE! Guess again. (1-10)"
guess = prompt "YOU LOSE! Guess again. (1-10)"
alert "Well guessed!"</lang>
alert "Well guessed!"</syntaxhighlight>


{{works_with|node.js}}
{{works_with|node.js}}


<lang coffeescript>
<syntaxhighlight lang="coffeescript">
# This shows how to do simple REPL-like I/O in node.js.
# This shows how to do simple REPL-like I/O in node.js.
readline = require "readline"
readline = require "readline"
Line 987: Line 1,058:
guess()
guess()
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun guess-the-number (max)
<syntaxhighlight lang="lisp">(defun guess-the-number (max)
(format t "Try to guess a number from 1 to ~a!~%Guess? " max)
(format t "Try to guess a number from 1 to ~a!~%Guess? " max)
(loop with num = (1+ (random max))
(loop with num = (1+ (random max))
Line 999: Line 1,070:
(force-output)
(force-output)
finally (format t "Well guessed! You took ~a ~:*~[~;try~:;tries~].~%" num-guesses)))
finally (format t "Well guessed! You took ~a ~:*~[~;try~:;tries~].~%" num-guesses)))
</syntaxhighlight>
</lang>
Output:
Output:
<pre>CL-USER> (guess-the-number 10)
<pre>CL-USER> (guess-the-number 10)
Line 1,014: Line 1,085:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>n = rand(1..10)
<syntaxhighlight lang="ruby">n = rand(1..10)
puts "Guess the number: 1..10"
puts "Guess the number: 1..10"
until gets.to_s.to_i == n; puts "Wrong! Guess again: " end
until gets.to_s.to_i == n; puts "Wrong! Guess again: " end
puts "Well guessed!"</lang>
puts "Well guessed!"</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
void main() {
void main() {
immutable num = uniform(1, 10).text;
immutable num = uniform(1, 10).text;
Line 1,028: Line 1,099:


writeln("Yep, you guessed my ", num);
writeln("Yep, you guessed my ", num);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>What's next guess (1 - 9)? 1
<pre>What's next guess (1 - 9)? 1
Line 1,037: Line 1,108:
=={{header|Dart}}==
=={{header|Dart}}==
{{Trans|Kotlin}}
{{Trans|Kotlin}}
<lang dart>import 'dart:math';
<syntaxhighlight lang="dart">import 'dart:math';
import 'dart:io';
import 'dart:io';


Line 1,045: Line 1,116:
do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
print("\nWell guessed!");
print("\nWell guessed!");
}</lang>
}</syntaxhighlight>


=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>$ time = f$time()
<syntaxhighlight lang="dcl">$ time = f$time()
$ number = f$extract( f$length( time ) - 1, 1, time ) + 1
$ number = f$extract( f$length( time ) - 1, 1, time ) + 1
$ loop:
$ loop:
$ inquire guess "enter a guess (integer 1-10) "
$ inquire guess "enter a guess (integer 1-10) "
$ if guess .nes. number then $ goto loop
$ if guess .nes. number then $ goto loop
$ write sys$output "Well guessed!"</lang>
$ write sys$output "Well guessed!"</syntaxhighlight>
{{out}}
{{out}}
<pre>$ @guess_the_number
<pre>$ @guess_the_number
Line 1,064: Line 1,135:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program GuessTheNumber;
<syntaxhighlight lang="delphi">program GuessTheNumber;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,083: Line 1,154:
Writeln('Congratulations' ) ;
Writeln('Congratulations' ) ;
end.
end.
</syntaxhighlight>
</lang>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>local :number random-range 1 11
<syntaxhighlight lang="dejavu">local :number random-range 1 11


while true:
while true:
Line 1,093: Line 1,164:
return
return
else:
else:
!print "Nope, try again."</lang>
!print "Nope, try again."</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<syntaxhighlight>
<lang>n = random 10 + 1
n = randint 10
write "Guess a number between 1 and 10: "
write "Guess a number between 1 and 10: "
repeat
repeat
Line 1,105: Line 1,177:
write "try again: "
write "try again: "
.
.
print " is correct. Well guessed!"</lang>
print " is correct. Well guessed!"
</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 1,135: Line 1,208:


end
end
</syntaxhighlight>
</lang>
The code above is simplified if we create a RANDOMIZER, which simplifies reuse (e.g. the code in RANDOMIZER does not have to be recreated for each need of a random number).
The code above is simplified if we create a RANDOMIZER, which simplifies reuse (e.g. the code in RANDOMIZER does not have to be recreated for each need of a random number).
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
RANDOMIZER
RANDOMIZER
Line 1,180: Line 1,253:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,196: Line 1,269:


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 6.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
{
{
int randomNumber := randomGenerator.eval(1,10);
int randomNumber := randomGenerator.nextInt(1,10);
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
bool numberCorrect := false;
bool numberCorrect := false;
Line 1,218: Line 1,291:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,232: Line 1,305:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
{{works with|Elixir|1.2}}
<lang elixir>defmodule GuessingGame do
<syntaxhighlight lang="elixir">defmodule GuessingGame do
def play do
def play do
play(Enum.random(1..10))
play(Enum.random(1..10))
Line 1,252: Line 1,325:
end
end
GuessingGame.play</lang>
GuessingGame.play</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(let ((number (1+ (random 10))))
<syntaxhighlight lang="lisp">(let ((number (1+ (random 10))))
(while (not (= (read-number "Guess the number ") number))
(while (not (= (read-number "Guess the number ") number))
(message "Wrong, try again."))
(message "Wrong, try again."))
(message "Well guessed! %d" number))</lang>
(message "Well guessed! %d" number))</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(guess_the_number).
-module(guess_the_number).
-export([main/0]).
-export([main/0]).
Line 1,279: Line 1,352:
guess(N)
guess(N)
end.
end.
</syntaxhighlight>
</lang>


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM GUESS_NUMBER
PROGRAM GUESS_NUMBER


Line 1,312: Line 1,385:
END WHILE
END WHILE
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
Note: Adapted from Qbasic version.
Note: Adapted from Qbasic version.


=={{header|Euphoria}}==
=={{header|Euphoria}}==
{{trans|ZX_Spectrum_Basic}}
{{trans|ZX_Spectrum_Basic}}
<lang Euphoria>include get.e
<syntaxhighlight lang="euphoria">include get.e


integer n,g
integer n,g
Line 1,333: Line 1,406:
end while
end while


puts(1,"Well done! You guessed it.")</lang>
puts(1,"Well done! You guessed it.")</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==


<lang factor>
<syntaxhighlight lang="factor">
USING: io random math math.parser kernel formatting ;
USING: io random math math.parser kernel formatting ;
IN: guess-the-number
IN: guess-the-number
Line 1,358: Line 1,431:
gen-number play-game
gen-number play-game
"Yes, the number was %d!\n" printf ;
"Yes, the number was %d!\n" printf ;
</syntaxhighlight>
</lang>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,383: Line 1,456:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
<syntaxhighlight lang="forth">
<lang Forth>
\ tested with GForth 0.7.0
\ tested with GForth 0.7.0
: RND ( -- n) TIME&DATE 2DROP 2DROP DROP 10 MOD ; \ crude random number
: RND ( -- n) TIME&DATE 2DROP 2DROP DROP 10 MOD ; \ crude random number
Line 1,398: Line 1,471:
CR ." Yes it was " .
CR ." Yes it was " .
CR ." Good guess!" ;
CR ." Good guess!" ;
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==


<lang fortran>program guess_the_number
<syntaxhighlight lang="fortran">program guess_the_number
implicit none
implicit none


Line 1,436: Line 1,509:


end program guess_the_number
end program guess_the_number
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Randomize
Randomize
Line 1,452: Line 1,525:
End
End
End If
End If
Loop</lang>
Loop</syntaxhighlight>


{{out}}
{{out}}
Line 1,469: Line 1,542:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>// Guess a Number
<syntaxhighlight lang="frink">// Guess a Number
target = random[1,10] // Min and max are both inclusive for the random function
target = random[1,10] // Min and max are both inclusive for the random function
guess = 0
guess = 0
Line 1,482: Line 1,555:
guess == target ? println["$guess is correct. Well guessed!"] : println["$guess is not correct. Guess again!"]
guess == target ? println["$guess is correct. Well guessed!"] : println["$guess is not correct. Guess again!"]
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
Including an example with a non-integer entered.
Including an example with a non-integer entered.
Line 1,494: Line 1,567:
7 is correct. Well guessed!
7 is correct. Well guessed!
</pre>
</pre>

=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn BuildWindow
window 1, @"Guess the number (1-10)", (0,0,480,270), NSWindowStyleMaskTitled
textfield 1,,, (220,124,40,21)
ControlSetAlignment( 1, NSTextAlignmentCenter )
WindowMakeFirstResponder( 1, 1 )
AppSetProperty( @"Number", @(rnd(10)) )
end fn

void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case 1
if ( fn ControlIntegerValue( 1 ) == fn NumberIntegerValue( fn AppProperty( @"Number" ) ) )
alert 1,, @"Well guessed!",, @"Exit"
end
else
textfield 1,, @""
alert 1,, @"Wrong number!",, @"Try again"
end if
end select
end select
end fn

fn BuildWindow

on dialog fn DoDialog

HandleEvents
</syntaxhighlight>


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Form_Open()
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim byGuess, byGos As Byte
Dim byGuess, byGos As Byte
Dim byNo As Byte = Rand(1, 10)
Dim byNo As Byte = Rand(1, 10)
Line 1,510: Line 1,616:
Me.Close
Me.Close


End</lang>
End</syntaxhighlight>


=={{header|GML}}==
=={{header|GML}}==
<lang GML>var n, g;
<syntaxhighlight lang="gml">var n, g;
n = irandom_range(1,10);
n = irandom_range(1,10);
show_message("I'm thinking of a number from 1 to 10");
show_message("I'm thinking of a number from 1 to 10");
Line 1,521: Line 1,627:
g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1);
g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1);
}
}
show_message("Well guessed!");</lang>
show_message("Well guessed!");</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,546: Line 1,652:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>
<syntaxhighlight lang="groovy">
def random = new Random()
def random = new Random()
def keyboard = new Scanner(System.in)
def keyboard = new Scanner(System.in)
Line 1,560: Line 1,666:
}
}
println "Hurray! You guessed correctly!"
println "Hurray! You guessed correctly!"
</syntaxhighlight>
</lang>


=={{header|GW-BASIC}}==
=={{header|GW-BASIC}}==
<lang qbasic>10 RANDOMIZE TIMER:N=INT(RND*10+1):G=0
<syntaxhighlight lang="qbasic">10 RANDOMIZE TIMER:N=INT(RND*10+1):G=0
20 PRINT "Guess the number between 1 and 10."
20 PRINT "Guess the number between 1 and 10."
30 WHILE N<>G
30 WHILE N<>G
40 INPUT "Your guess? ",G
40 INPUT "Your guess? ",G
50 WEND
50 WEND
60 PRINT "That's correct!"</lang>
60 PRINT "That's correct!"</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>
<syntaxhighlight lang="haskell">
import Control.Monad
import Control.Monad
import System.Random
import System.Random
Line 1,588: Line 1,694:
putStrLn "Try to guess my secret number between 1 and 10."
putStrLn "Try to guess my secret number between 1 and 10."
ask `until_` answerIs ans
ask `until_` answerIs ans
</syntaxhighlight>
</lang>


Simple version:
Simple version:


<lang haskell>
<syntaxhighlight lang="haskell">
import System.Random
import System.Random


Line 1,603: Line 1,709:
then putStrLn "You got it!"
then putStrLn "You got it!"
else putStrLn "Nope. Guess again." >> gameloop r
else putStrLn "Nope. Guess again." >> gameloop r
</syntaxhighlight>
</lang>


=={{header|HolyC}}==
=={{header|HolyC}}==


<lang holyc>U8 n, *g;
<syntaxhighlight lang="holyc">U8 n, *g;


n = 1 + RandU16 % 10;
n = 1 + RandU16 % 10;
Line 1,623: Line 1,729:


Print("That's not my number. Try another guess:\n");
Print("That's not my number. Try another guess:\n");
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 1,629: Line 1,735:
This solution works in both languages.
This solution works in both languages.


<lang unicon>procedure main()
<syntaxhighlight lang="unicon">procedure main()
n := ?10
n := ?10
repeat {
repeat {
Line 1,636: Line 1,742:
}
}
write("Well guessed!")
write("Well guessed!")
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>require 'misc'
<syntaxhighlight lang="j">require 'misc'
game=: verb define
game=: verb define
n=: 1 + ?10
n=: 1 + ?10
Line 1,648: Line 1,754:
smoutput (guess=n){::'no.';'Well guessed!'
smoutput (guess=n){::'no.';'Well guessed!'
end.
end.
)</lang>
)</syntaxhighlight>


Example session:
Example session:


<lang> game''
<syntaxhighlight lang="text"> game''
Guess my integer, which is bounded by 1 and 10
Guess my integer, which is bounded by 1 and 10
Guess: 1
Guess: 1
no.
no.
Guess: 2
Guess: 2
Well guessed!</lang>
Well guessed!</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|6+}}
{{works with|Java|6+}}
<lang java5>public class Guessing {
<syntaxhighlight lang="java5">public class Guessing {
public static void main(String[] args) throws NumberFormatException{
public static void main(String[] args) throws NumberFormatException{
int n = (int)(Math.random() * 10 + 1);
int n = (int)(Math.random() * 10 + 1);
Line 1,670: Line 1,776:
System.out.println("Well guessed!");
System.out.println("Well guessed!");
}
}
}</lang>
}</syntaxhighlight>
For pre-Java 6, use a <code>Scanner</code> or <code>BufferedReader</code> for input instead of <code>System.console()</code> (see [[Input loop#Java]]).
For pre-Java 6, use a <code>Scanner</code> or <code>BufferedReader</code> for input instead of <code>System.console()</code> (see [[Input loop#Java]]).


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>
<syntaxhighlight lang="javascript">
function guessNumber() {
function guessNumber() {
// Get a random integer from 1 to 10 inclusive
// Get a random integer from 1 to 10 inclusive
Line 1,686: Line 1,792:
}
}


guessNumber();</lang>
guessNumber();</syntaxhighlight>


Requires a host environment that supports <code>prompt</code> and <code>alert</code> such as a browser.
Requires a host environment that supports <code>prompt</code> and <code>alert</code> such as a browser.
Line 1,694: Line 1,800:


jq currently does not have a built-in random number generator, so a suitable PRNG for this task is defined below. Once `rand(n)` has been defined, the task can be accomplished as follows:
jq currently does not have a built-in random number generator, so a suitable PRNG for this task is defined below. Once `rand(n)` has been defined, the task can be accomplished as follows:
<syntaxhighlight lang="jq">
<lang jq>
{prompt: "Please enter your guess:", random: (1+rand(9)) }
{prompt: "Please enter your guess:", random: (1+rand(9)) }
| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt),
| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt),
"Well done!"</lang>
"Well done!"</syntaxhighlight>


'''Invocation'''
'''Invocation'''
Line 1,706: Line 1,812:


'''PRNG'''
'''PRNG'''
<lang jq># LCG::Microsoft generates 15-bit integers using the same formula
<syntaxhighlight lang="jq"># LCG::Microsoft generates 15-bit integers using the same formula
# as rand() from the Microsoft C Runtime.
# as rand() from the Microsoft C Runtime.
# Input: [ count, state, random ]
# Input: [ count, state, random ]
Line 1,720: Line 1,826:


# A random integer in [0 ... (n-1)]:
# A random integer in [0 ... (n-1)]:
def rand(n): n * (rand_Microsoft($seed|tonumber) / 32768) | trunc;</lang>
def rand(n): n * (rand_Microsoft($seed|tonumber) / 32768) | trunc;</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript entry.
From Javascript entry.
<lang javascript>function guessNumber() {
<syntaxhighlight lang="javascript">function guessNumber() {
// Get a random integer from 1 to 10 inclusive
// Get a random integer from 1 to 10 inclusive
var num = Math.ceil(Math.random() * 10);
var num = Math.ceil(Math.random() * 10);
Line 1,757: Line 1,863:
The number was 2 it took 3 tries
The number was 2 it took 3 tries
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 1,766: Line 1,872:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>function guess()
<syntaxhighlight lang="julia">function guess()
number = dec(rand(1:10))
number = dec(rand(1:10))
print("Guess my number! ")
print("Guess my number! ")
Line 1,775: Line 1,881:
end
end


guess()</lang>
guess()</syntaxhighlight>


{{out}}
{{out}}
Line 1,791: Line 1,897:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,798: Line 1,904:
do { print(" Your guess : ") } while (n != readLine())
do { print(" Your guess : ") } while (n != readLine())
println("\nWell guessed!")
println("\nWell guessed!")
}</lang>
}</syntaxhighlight>
Sample input/output:
Sample input/output:
{{out}}
{{out}}
Line 1,814: Line 1,920:


=={{header|langur}}==
=={{header|langur}}==
<lang langur>writeln "Guess a number from 1 to 10"
<syntaxhighlight lang="langur">writeln "Guess a number from 1 to 10"


val .n = toString random 10
val .n = string random 10
for {
for {
val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, ZLS
val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, ""
if .guess == ZLS {
if .guess == "" {
writeln "too much bad data"
writeln "too much bad data"
break
break
Line 1,828: Line 1,934:
}
}
writeln "not it"
writeln "not it"
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,846: Line 1,952:
===Command Line===
===Command Line===
The following example works when Lasso is called from a command line
The following example works when Lasso is called from a command line
<lang Lasso>local(
<syntaxhighlight lang="lasso">local(
number = integer_random(10, 1),
number = integer_random(10, 1),
status = false,
status = false,
Line 1,873: Line 1,979:
}
}


}</lang>
}</syntaxhighlight>


===Web form===
===Web form===
The following example is a web page form
The following example is a web page form
<lang Lasso><?LassoScript
<syntaxhighlight lang="lasso"><?LassoScript


local(
local(
Line 1,917: Line 2,023:
[/if]
[/if]
</body>
</body>
</html></lang>
</html></syntaxhighlight>


=={{header|LFE}}==
=={{header|LFE}}==


<lang lisp>
<syntaxhighlight lang="lisp">
(defmodule guessing-game
(defmodule guessing-game
(export (main 0)))
(export (main 0)))
Line 1,941: Line 2,047:
(: random uniform 10)
(: random uniform 10)
(get-player-guess)))
(get-player-guess)))
</syntaxhighlight>
</lang>


From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):
From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):
<lang lisp>
<syntaxhighlight lang="lisp">
> (slurp '"guessing-game.lfe")
> (slurp '"guessing-game.lfe")
#(ok guessing-game)
#(ok guessing-game)
Line 1,953: Line 2,059:
Well-guessed!!
Well-guessed!!
ok
ok
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>number = int(rnd(0) * 10) + 1
<syntaxhighlight lang="lb">number = int(rnd(0) * 10) + 1
input "Guess the number I'm thinking of between 1 and 10. "; guess
input "Guess the number I'm thinking of between 1 and 10. "; guess
while guess <> number
while guess <> number
input "Incorrect! Try again! "; guess
input "Incorrect! Try again! "; guess
wend
wend
print "Congratulations, well guessed! The number was "; number;"."</lang>
print "Congratulations, well guessed! The number was "; number;"."</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>command guessTheNumber
<syntaxhighlight lang="livecode">command guessTheNumber
local tNumber, tguess
local tNumber, tguess
put random(10) into tNumber
put random(10) into tNumber
Line 1,978: Line 2,084:
end if
end if
end repeat
end repeat
end guessTheNumber</lang>
end guessTheNumber</syntaxhighlight>


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==


<lang locobasic>10 RANDOMIZE TIME:num=INT(RND*10+1):guess=0
<syntaxhighlight lang="locobasic">10 RANDOMIZE TIME:num=INT(RND*10+1):guess=0
20 PRINT "Guess the number between 1 and 10."
20 PRINT "Guess the number between 1 and 10."
30 WHILE num<>guess
30 WHILE num<>guess
40 INPUT "Your guess? ", guess
40 INPUT "Your guess? ", guess
50 WEND
50 WEND
60 PRINT "That's correct!"</lang>
60 PRINT "That's correct!"</syntaxhighlight>


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
There is no native support for random numbers. This solution uses a simple linear congruential generator to simulate them, with the lamentable restriction that the user must first be prompted for a seed.
There is no native support for random numbers. This solution uses a simple linear congruential generator to simulate them, with the lamentable restriction that the user must first be prompted for a seed.
<lang LOLCODE>HAI 1.3
<syntaxhighlight lang="lolcode">HAI 1.3


VISIBLE "SEED ME, FEMUR! "!
VISIBLE "SEED ME, FEMUR! "!
Line 2,013: Line 2,119:
IM OUTTA YR guesser
IM OUTTA YR guesser


KTHXBYE</lang>
KTHXBYE</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>math.randomseed( os.time() )
<syntaxhighlight lang="lua">math.randomseed( os.time() )
n = math.random( 1, 10 )
n = math.random( 1, 10 )


Line 2,029: Line 2,135:
print "Guess again: "
print "Guess again: "
end
end
until x == n</lang>
until x == n</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
A copy from QBASIC, write blocks { } where needed, We use GOSUB and GOTO in a Module.
A copy from QBASIC, write blocks { } where needed, We use GOSUB and GOTO in a Module.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module QBASIC_Based {
Module QBASIC_Based {
supervisor:
supervisor:
Line 2,077: Line 2,183:
}
}
QBASIC_Based
QBASIC_Based
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==


<lang Maple>GuessNumber := proc()
<syntaxhighlight lang="maple">GuessNumber := proc()
local number;
local number;
randomize():
randomize():
Line 2,090: Line 2,196:
end do:
end do:
printf("Well guessed! The answer was %d.\n", number);
printf("Well guessed! The answer was %d.\n", number);
end proc:</lang>
end proc:</syntaxhighlight>
<lang Maple>GuessNumber();</lang>
<syntaxhighlight lang="maple">GuessNumber();</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>number = RandomInteger[{1, 10}];
<syntaxhighlight lang="mathematica">number = RandomInteger[{1, 10}];
While[guess =!= number, guess = Input["Guess my number"]];
While[guess =!= number, guess = Input["Guess my number"]];
Print["Well guessed!"]</lang>
Print["Well guessed!"]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang matlab>number = ceil(10*rand(1));
<syntaxhighlight lang="matlab">number = ceil(10*rand(1));
[guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));
[guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));


Line 2,105: Line 2,211:
[guess, status] = str2num(input('Guess again: ','s'));
[guess, status] = str2num(input('Guess again: ','s'));
end
end
disp('Well guessed!')</lang>
disp('Well guessed!')</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
rand = random 1 10
rand = random 1 10
clearListener()
clearListener()
Line 2,117: Line 2,223:
format "\nChoose another value\n"
format "\nChoose another value\n"
)
)
</syntaxhighlight>
</lang>


=={{header|Mercury}}==
=={{header|Mercury}}==
Mercury does have a 'time' module in its standard library, but it offers an abstract type instead of the seconds-since-the-epoch we want to seed the RNG with. So this is also an example of how easy it is to call out to C. (It's just as easy to call out to C#, Java, and Erlang.) Also, rather than parse the input, this solution prepares the random number to match the typed input. This isn't a weakness of Mercury, just the author's desire to cheat a bit.
Mercury does have a 'time' module in its standard library, but it offers an abstract type instead of the seconds-since-the-epoch we want to seed the RNG with. So this is also an example of how easy it is to call out to C. (It's just as easy to call out to C#, Java, and Erlang.) Also, rather than parse the input, this solution prepares the random number to match the typed input. This isn't a weakness of Mercury, just the author's desire to cheat a bit.


<lang Mercury>:- module guess.
<syntaxhighlight lang="mercury">:- module guess.
:- interface.
:- interface.
:- import_module io.
:- import_module io.
Line 2,154: Line 2,260:
:- pragma foreign_proc("C", time(Int::out, _IO0::di, _IO1::uo),
:- pragma foreign_proc("C", time(Int::out, _IO0::di, _IO1::uo),
[will_not_call_mercury, promise_pure],
[will_not_call_mercury, promise_pure],
"Int = time(NULL);").</lang>
"Int = time(NULL);").</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.6}}
{{works with|min|0.19.6}}
<lang min>randomize
<syntaxhighlight lang="min">randomize


9 random succ
9 random succ
Line 2,166: Line 2,272:
("Your guess" ask int over ==) 'pop ("Wrong." puts!) () linrec
("Your guess" ask int over ==) 'pop ("Wrong." puts!) () linrec


"Well guessed!" puts!</lang>
"Well guessed!" puts!</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>num = ceil(rnd*10)
<syntaxhighlight lang="miniscript">num = ceil(rnd*10)
while true
while true
x = val(input("Your guess?"))
x = val(input("Your guess?"))
Line 2,176: Line 2,282:
break
break
end if
end if
end while</lang>
end while</syntaxhighlight>


=={{header|MIPS Assembly}}==
=={{header|MIPS Assembly}}==
<lang mips>
<syntaxhighlight lang="mips">
# WRITTEN: August 26, 2016 (at midnight...)
# WRITTEN: August 26, 2016 (at midnight...)


Line 2,236: Line 2,342:
syscall
syscall
jr $ra
jr $ra
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Ursa}}
{{trans|Ursa}}
<lang Nanoquery>random = new(Nanoquery.Util.Random)
<syntaxhighlight lang="nanoquery">random = new(Nanoquery.Util.Random)
target = random.getInt(9) + 1
target = random.getInt(9) + 1
guess = 0
guess = 0
Line 2,249: Line 2,355:
end
end


println "That's right!"</lang>
println "That's right!"</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 2,271: Line 2,377:
WriteLine("Well guessed!");
WriteLine("Well guessed!");
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary
Line 2,297: Line 2,403:


return
return
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>; guess-number.lsp
<syntaxhighlight lang="newlisp">; guess-number.lsp
; oofoe 2012-01-19
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number
; http://rosettacode.org/wiki/Guess_the_number
Line 2,312: Line 2,418:
(println "Well guessed! Congratulations!")
(println "Well guessed! Congratulations!")


(exit)</lang>
(exit)</syntaxhighlight>


Sample output:
Sample output:
Line 2,325: Line 2,431:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils, random
<syntaxhighlight lang="nim">import strutils, random
randomize()
randomize()
Line 2,337: Line 2,443:
guess = parseInt(readLine(stdin))
guess = parseInt(readLine(stdin))
echo "Well guessed!"</lang>
echo "Well guessed!"</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 NUMBER=RND(10)+1
<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
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
30 IF GUESS<>NUMBER THEN PRINT "INCORRECT GUESS. TRY AGAIN.": GOTO 20
30 IF GUESS<>NUMBER THEN PRINT "INCORRECT GUESS. TRY AGAIN.": GOTO 20
40 PRINT "CORRECT NUMBER."</lang>
40 PRINT "CORRECT NUMBER."</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c Version 2
Works with oo2c Version 2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE GuessTheNumber;
MODULE GuessTheNumber;
IMPORT
IMPORT
Line 2,372: Line 2,478:
Do;
Do;
END GuessTheNumber.
END GuessTheNumber.
</syntaxhighlight>
</lang>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use IO;
use IO;


Line 2,405: Line 2,511:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==


<lang objc>
<syntaxhighlight lang="objc">
#import <Foundation/Foundation.h>
#import <Foundation/Foundation.h>


Line 2,449: Line 2,555:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>#!/usr/bin/env ocaml
<syntaxhighlight lang="ocaml">#!/usr/bin/env ocaml


let () =
let () =
Line 2,469: Line 2,575:
print_endline "The guess was wrong! Please try again!"
print_endline "The guess was wrong! Please try again!"
done;
done;
print_endline "Well guessed!"</lang>
print_endline "Well guessed!"</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>import: console
<syntaxhighlight lang="oforth">import: console


: guess
: guess
10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ]
10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ]
drop "Well guessed!" . ;</lang>
drop "Well guessed!" . ;</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<syntaxhighlight lang="ol">
<lang ol>
(import (otus random!))
(import (otus random!))


Line 2,489: Line 2,595:
(print "Well guessed!")
(print "Well guessed!")
(loop)))
(loop)))
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>guess()=my(r=random(10)+1);while(input()!=r,); "Well guessed!";</lang>
<syntaxhighlight lang="parigp">guess()=my(r=random(10)+1);while(input()!=r,); "Well guessed!";</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>Program GuessTheNumber(input, output);
<syntaxhighlight lang="pascal">Program GuessTheNumber(input, output);


var
var
Line 2,514: Line 2,620:
writeln ('You made an excellent guess. Thank you and have a nice day.');
writeln ('You made an excellent guess. Thank you and have a nice day.');
end.
end.
</syntaxhighlight>
</lang>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>my $number = 1 + int rand 10;
<syntaxhighlight lang="perl">my $number = 1 + int rand 10;
do { print "Guess a number between 1 and 10: " } until <> == $number;
do { print "Guess a number between 1 and 10: " } until <> == $number;
print "You got it!\n";</lang>
print "You got it!\n";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Guess_the_number.exw
-- demo\rosetta\Guess_the_number.exw
Line 2,561: Line 2,667:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">
<?php
<?php


Line 2,612: Line 2,718:
</body>
</body>
</html>
</html>
</syntaxhighlight>
</lang>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
N = random(1,10),
N = random(1,10),
do print("Guess a number: ")
do print("Guess a number: ")
while (read_int() != N),
while (read_int() != N),
println("Well guessed!").</lang>
println("Well guessed!").</syntaxhighlight>


{{trans|Prolog}}
{{trans|Prolog}}
<lang Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>
N = random(1, 10),
N = random(1, 10),
repeat,
repeat,
Line 2,628: Line 2,734:
N = read_int(),
N = read_int(),
println("Well guessed!"),
println("Well guessed!"),
!.</lang>
!.</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de guessTheNumber ()
<syntaxhighlight lang="picolisp">(de guessTheNumber ()
(let Number (rand 1 9)
(let Number (rand 1 9)
(loop
(loop
Line 2,637: Line 2,743:
(T (= Number (read))
(T (= Number (read))
(prinl "Well guessed!") )
(prinl "Well guessed!") )
(prinl "Sorry, this was wrong") ) ) )</lang>
(prinl "Sorry, this was wrong") ) ) )</syntaxhighlight>


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Play guess the number.
Play guess the number.
Line 2,654: Line 2,760:
If the number is the secret number, break.
If the number is the secret number, break.
Repeat.
Repeat.
Write "Well guessed!" to the console.</lang>
Write "Well guessed!" to the console.</syntaxhighlight>


=={{header|PlainTeX}}==
=={{header|PlainTeX}}==
This code should be compiled with etex features in console mode (for example "pdftex <name of the file>"):
This code should be compiled with etex features in console mode (for example "pdftex <name of the file>"):
<lang tex>\newlinechar`\^^J
<syntaxhighlight lang="tex">\newlinechar`\^^J
\edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}%
\edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}%
\message{^^JI'm thinking of a number between 1 and 10, try to guess it!}%
\message{^^JI'm thinking of a number between 1 and 10, try to guess it!}%
Line 2,672: Line 2,778:
\ifnotguessed
\ifnotguessed
\repeat
\repeat
\bye</lang>
\bye</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Provides a function that analyzes the provided number by its call. The second script block is important and needed inside the script so the function will be called.
Provides a function that analyzes the provided number by its call. The second script block is important and needed inside the script so the function will be called.
<lang PowerShell>Function GuessNumber($Guess)
<syntaxhighlight lang="powershell">Function GuessNumber($Guess)
{
{
$Number = Get-Random -min 1 -max 11
$Number = Get-Random -min 1 -max 11
Line 2,687: Line 2,793:
While ($Number -ne $Guess)
While ($Number -ne $Guess)
Write-Host "Well done! You successfully guessed the number $Guess."
Write-Host "Well done! You successfully guessed the number $Guess."
}</lang>
}</syntaxhighlight>
<lang powershell>$myNumber = Read-Host "What's the number?"
<syntaxhighlight lang="powershell">$myNumber = Read-Host "What's the number?"
GuessNumber $myNumber</lang>
GuessNumber $myNumber</syntaxhighlight>


=={{header|ProDOS}}==
=={{header|ProDOS}}==
Uses math module:
Uses math module:
<syntaxhighlight lang="prodos">:a
<lang ProDOS>:a
editvar /modify /value=-random-= <10
editvar /modify /value=-random-= <10
editvar /newvar /value=-random- /title=a
editvar /newvar /value=-random- /title=a
editvar /newvar /value=b /userinput=1 /title=Guess a number:
editvar /newvar /value=b /userinput=1 /title=Guess a number:
if -b- /hasvalue=-a- printline You guessed correctly! else printline Your guess was wrong & goto :a</lang>
if -b- /hasvalue=-a- printline You guessed correctly! else printline Your guess was wrong & goto :a</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
{{works with|SWI-Prolog|6}}


<lang prolog>main :-
<syntaxhighlight lang="prolog">main :-
random_between(1, 10, N),
random_between(1, 10, N),
repeat,
repeat,
Line 2,708: Line 2,814:
read(N),
read(N),
writeln('Well guessed!'),
writeln('Well guessed!'),
!.</lang>
!.</syntaxhighlight>


Example:
Example:


<lang prolog>?- main.
<syntaxhighlight lang="prolog">?- main.
Guess the number: 1.
Guess the number: 1.
Guess the number: 2.
Guess the number: 2.
Guess the number: 3.
Guess the number: 3.
Well guessed!
Well guessed!
true.</lang>
true.</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
Define TheNumber=Random(9)+1
Define TheNumber=Random(9)+1
Line 2,732: Line 2,838:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>import random
<syntaxhighlight lang="python">import random
t,g=random.randint(1,10),0
t,g=random.randint(1,10),0
g=int(input("Guess a number that's between 1 and 10: "))
g=int(input("Guess a number that's between 1 and 10: "))
while t!=g:g=int(input("Guess again! "))
while t!=g:g=int(input("Guess again! "))
print("That's right!")</lang>
print("That's right!")</syntaxhighlight>

===Expanded Range, Auto-Interactive===
<b>Note:</b> This is off-task, as there is no user interaction.<br/><br/>
Program from Russia guesses 1 out of a billion<br/>
https://rextester.com/GWJFOO4393
<syntaxhighlight lang="python">
import random #milliard.py
h1 = 0; h2 = 10**16; t = 0; f=0
c = random.randrange(0,h2) #comp
h = random.randrange(0,h2) #human DANILIN

while f<1:
print(t,c,h)

if h<c:
print('MORE')
a=h
h=int((h+h2)/2)
h1=a

elif h>c:
print('less')
a=h
h=int((h1+h)/2)
h2=a

else:
print('win by', t, 'steps')
f=1
t=t+1</syntaxhighlight>
{{out}}
<pre>1 40 11 MORE
2 40 55 less
3 40 33 MORE
4 40 44 less
5 40 38 MORE
6 40 41 less
7 40 39 MORE
8 40 40 win by 8 steps</pre>


=={{header|QB64}}==
=={{header|QB64}}==
''CBTJD'': 2020/04/13
''CBTJD'': 2020/04/13
<lang qbasic>START:
<syntaxhighlight lang="qbasic">START:
CLS
CLS
RANDOMIZE TIMER
RANDOMIZE TIMER
Line 2,753: Line 2,898:
LOOP UNTIL n = num
LOOP UNTIL n = num
INPUT "Well guessed! Go again"; a$
INPUT "Well guessed! Go again"; a$
IF LEFT$(LCASE$(a$), 1) = "y" THEN GOTO START</lang>
IF LEFT$(LCASE$(a$), 1) = "y" THEN GOTO START</syntaxhighlight>

=={{header|QB64}}==
<syntaxhighlight lang="qb64">
'Task
'Plus features: 1) AI gives suggestions about your guess
' 2) AI controls wrong input by user (numbers outer 1 and 10).
' 3) player can choose to replay the game

Randomize Timer
Dim As Integer Done, Guess, Number

Done = 1
Guess = 0
While Done
Cls
Number = Rnd * 10 + 1
Do While Number <> Guess
Cls
Locate 2, 1
Input "What number have I thought? (1-10)", Guess
If Guess > 0 And Guess < 11 Then
If Guess = Number Then
Locate 4, 1: Print "Well done, you win!"; Space$(20)
Exit Do
ElseIf Guess > Number Then
Locate 4, 1: Print "Too high, try lower"; Space$(20)
ElseIf Guess < Number Then
Locate 4, 1: Print "Too low, try higher"; Space$(20)
End If
Else
Print "Wrong input data! Try again"; Space$(20)
End If
_Delay 1
If Done = 11 Then Exit Do Else Done = Done + 1
Loop
If Done = 11 Then
Locate 4, 1: Print "Ah ah ah, I win and you loose!"; Space$(20)
Else
Locate 4, 1: Print " Sigh, you win!"; Space$(20)
End If
Locate 6, 1: Input "Another play? 1 = yes, others values = no ", Done
If Done <> 1 Then Done = 0
Wend
End
</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
<lang quackery>randomise
<syntaxhighlight lang="quackery">randomise
10 random 1+ number$
10 random 1+ number$
say 'I chose a number between 1 and 10.' cr
say 'I chose a number between 1 and 10.' cr
Line 2,763: Line 2,953:
done
done
again ]
again ]
drop say 'Well guessed!'</lang>
drop say 'Well guessed!'</syntaxhighlight>
A sample output of exceptionally bad guessing:
A sample output of exceptionally bad guessing:
{{out}}
{{out}}
Line 2,782: Line 2,972:


=={{header|R}}==
=={{header|R}}==
<lang R>f <- function() {
<syntaxhighlight lang="r">f <- function() {
print("Guess a number between 1 and 10 until you get it right.")
print("Guess a number between 1 and 10 until you get it right.")
n <- sample(10, 1)
n <- sample(10, 1)
Line 2,789: Line 2,979:
}
}
print("You got it!")
print("You got it!")
}</lang>
}</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define (guess-number)
(define (guess-number)
(define number (add1 (random 10)))
(define number (add1 (random 10)))
Line 2,799: Line 2,989:
(if (equal? guess number)
(if (equal? guess number)
(display "Well guessed!\n")
(display "Well guessed!\n")
(loop))))</lang>
(loop))))</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>my $number = (1..10).pick;
<syntaxhighlight lang="raku" line>my $number = (1..10).pick;
repeat {} until prompt("Guess a number: ") == $number;
repeat {} until prompt("Guess a number: ") == $number;
say "Guessed right!";</lang>
say "Guessed right!";</syntaxhighlight>


=={{header|RapidQ}}==
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
RANDOMIZE
RANDOMIZE
number = rnd(10) + 1
number = rnd(10) + 1
Line 2,819: Line 3,009:
print "You guessed right, well done !"
print "You guessed right, well done !"
input "Press enter to quit";a$
input "Press enter to quit";a$
</syntaxhighlight>
</lang>


=={{header|Rascal}}==
=={{header|Rascal}}==
<lang Rascal>import vis::Render;
<syntaxhighlight lang="rascal">import vis::Render;
import vis::Figure;
import vis::Figure;
import util::Math;
import util::Math;
Line 2,836: Line 3,026:
button("Start over", void(){random = arbInt(10);}) ]));
button("Start over", void(){random = arbInt(10);}) ]));
render(figure);
render(figure);
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 2,843: Line 3,033:


=={{header|Red}}==
=={{header|Red}}==
<lang red>
<syntaxhighlight lang="red">
Red []
Red []
#include %environment/console/CLI/input.red
#include %environment/console/CLI/input.red
Line 2,853: Line 3,043:
]
]
print "Well guessed!"
print "Well guessed!"
</syntaxhighlight>
</lang>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>: checkGuess ( gn-gf || f )
<syntaxhighlight lang="retro">: checkGuess ( gn-gf || f )
over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;
over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;


Line 2,867: Line 3,057:
think [ getToken toNumber checkGuess ] while
think [ getToken toNumber checkGuess ] while
"You got it!\n" puts ;
"You got it!\n" puts ;
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<small>(Note: most REXXes won't accept that first statement, the shebang/sha-bang/hashbang/pound-bang/hash-exclam/hash-pling.)</small>
<small>(Note: most REXXes won't accept that first statement, the shebang/sha-bang/hashbang/pound-bang/hash-exclam/hash-pling.)</small>
<lang rexx>#!/usr/bin/rexx
<syntaxhighlight lang="rexx">#!/usr/bin/rexx
/*REXX program to play: Guess the number */
/*REXX program to play: Guess the number */


Line 2,888: Line 3,078:


say "Well done! You guessed it!"
say "Well done! You guessed it!"
</syntaxhighlight>
</lang>


===version 2===
===version 2===
<lang rexx>/*REXX program interactively plays "guess my number" with a human, the range is 1──►10. */
<syntaxhighlight lang="rexx">/*REXX program interactively plays "guess my number" with a human, the range is 1──►10. */
?= random(1, 10) /*generate a low random integer. */
?= random(1, 10) /*generate a low random integer. */
say 'Try to guess my number between 1 ──► 10 (inclusive).' /*the directive to be used.*/
say 'Try to guess my number between 1 ──► 10 (inclusive).' /*the directive to be used.*/
Line 2,899: Line 3,089:
pull g /*obtain a guess from user.*/
pull g /*obtain a guess from user.*/
end /*j*/
end /*j*/
say 'Well guessed!' /*stick a fork in it, we're all done. */</lang>
say 'Well guessed!' /*stick a fork in it, we're all done. */</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==


<lang ring>
<syntaxhighlight lang="ring">


### Bert Mariani
### Bert Mariani
Line 2,929: Line 3,119:
end
end


</syntaxhighlight>
</lang>


=={{header|RPL}}==
=={{header|RPL}}==


<syntaxhighlight lang="userrpl">
<lang UserRPL>
DIR
DIR
INITIALIZE
INITIALIZE
Line 2,964: Line 3,154:
END
END
>>
>>
END</lang>
END</syntaxhighlight>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>
<syntaxhighlight lang="ruby">
n = rand(1..10)
n = rand(1..10)
puts 'Guess the number: '
puts 'Guess the number: '
puts 'Wrong! Guess again: ' until gets.to_i == n
puts 'Wrong! Guess again: ' until gets.to_i == n
puts 'Well guessed!'
puts 'Well guessed!'
</syntaxhighlight>
</lang>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang Runbasic>while 1
<syntaxhighlight lang="runbasic">while 1
choose = int(RND(0) * 9) + 1
choose = int(RND(0) * 9) + 1
while guess <> choose
while guess <> choose
Line 2,985: Line 3,175:
end if
end if
wend
wend
wend</lang>
wend</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
{{libheader|rand}}
{{libheader|rand}}
<lang rust>extern crate rand;
<syntaxhighlight lang="rust">extern crate rand;


fn main() {
fn main() {
Line 3,013: Line 3,203:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==


<lang scala>
<syntaxhighlight lang="scala">
val n = (math.random * 10 + 1).toInt
val n = (math.random * 10 + 1).toInt
print("Guess the number: ")
print("Guess the number: ")
while(readInt != n) print("Wrong! Guess again: ")
while(readInt != n) print("Wrong! Guess again: ")
println("Well guessed!")
println("Well guessed!")
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
{{works with|Chicken Scheme}}
{{works with|Guile}}
{{works with|Guile}}
<lang scheme>(define (guess)
<syntaxhighlight lang="scheme">(define (guess)
(define number (random 11))
(define number (random 11))
(display "Pick a number from 1 through 10.\n> ")
(display "Pick a number from 1 through 10.\n> ")
(do ((guess (read) (read)))
(do ((guess (read) (read)))
((= guess number) (display "Well guessed!\n"))
((= guess number) (display "Well guessed!\n"))
(display "Guess again.\n")))</lang>
(display "Guess again.\n")))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>scheme> (guess)
<pre>scheme> (guess)
Line 3,048: Line 3,238:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 3,065: Line 3,255:
end while;
end while;
writeln("You have won!");
writeln("You have won!");
end func;</lang>
end func;</syntaxhighlight>


=={{header|Self}}==
=={{header|Self}}==
Line 3,073: Line 3,263:
Well factored:
Well factored:


<lang self>(|
<syntaxhighlight lang="self">(|
parent* = traits clonable.
parent* = traits clonable.
copy = (resend.copy secretNumber: random integerBetween: 1 And: 10).
copy = (resend.copy secretNumber: random integerBetween: 1 And: 10).
Line 3,085: Line 3,275:
hasGuessed = ( [ask = secretNumber] onReturn: [|:r| r ifTrue: [reportSuccess] False: [reportFailure]] ).
hasGuessed = ( [ask = secretNumber] onReturn: [|:r| r ifTrue: [reportSuccess] False: [reportFailure]] ).
run = (sayIntroduction. [hasGuessed] whileFalse)
run = (sayIntroduction. [hasGuessed] whileFalse)
|) copy run</lang>
|) copy run</syntaxhighlight>


Simple method:
Simple method:


<lang self>| n |
<syntaxhighlight lang="self">| n |
userQuery report: 'Try to guess my secret number between 1 and 10.'.
userQuery report: 'Try to guess my secret number between 1 and 10.'.
n: random integerBetween: 1 And: 10.
n: random integerBetween: 1 And: 10.
[(userQuery askString: 'Guess the Number.') asInteger = n] whileFalse: [
[(userQuery askString: 'Guess the Number.') asInteger = n] whileFalse: [
userQuery report: 'Nope. Guess again.'].
userQuery report: 'Nope. Guess again.'].
userQuery report: 'You got it!'</lang>
userQuery report: 'You got it!'</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var n = irand(1, 10)
<syntaxhighlight lang="ruby">var n = irand(1, 10)
var msg = 'Guess the number: '
var msg = 'Guess the number: '
while (n != read(msg, Number)) {
while (n != read(msg, Number)) {
msg = 'Wrong! Guess again: '
msg = 'Wrong! Guess again: '
}
}
say 'Well guessed!'</lang>
say 'Well guessed!'</syntaxhighlight>


=={{header|Small Basic}}==
=={{header|Small Basic}}==
<lang Small Basic>number=Math.GetRandomNumber(10)
<syntaxhighlight lang="small basic">number=Math.GetRandomNumber(10)
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
While guess<>number
Line 3,111: Line 3,301:
TextWindow.WriteLine("Guess again! ")
TextWindow.WriteLine("Guess again! ")
EndWhile
EndWhile
TextWindow.WriteLine("You win!")</lang>
TextWindow.WriteLine("You win!")</syntaxhighlight>


=={{header|SNUSP}}==
=={{header|SNUSP}}==
Line 3,149: Line 3,339:


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Cocoa
<syntaxhighlight lang="swift">import Cocoa


var found = false
var found = false
Line 3,165: Line 3,355:
println("Well guessed!")
println("Well guessed!")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set target [expr {int(rand()*10 + 1)}]
<syntaxhighlight lang="tcl">set target [expr {int(rand()*10 + 1)}]
puts "I have thought of a number."
puts "I have thought of a number."
puts "Try to guess it!"
puts "Try to guess it!"
Line 3,180: Line 3,370:
puts "Your guess was wrong. Try again!"
puts "Your guess was wrong. Try again!"
}
}
puts "Well done! You guessed it."</lang>
puts "Well done! You guessed it."</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 3,196: Line 3,386:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
PRINT "Find the luckynumber (7 tries)!"
Line 3,215: Line 3,405:
ENDLOOP
ENDLOOP
ENDCOMPILE
ENDCOMPILE
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,231: Line 3,421:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
# Guess the number
# Guess the number
# This simplified program does not check the input is valid
# This simplified program does not check the input is valid
Line 3,244: Line 3,434:
echo 'Sorry, the guess was wrong! Try again!'
echo 'Sorry, the guess was wrong! Try again!'
done
done
echo 'Well done! You guessed it.'</lang>
echo 'Well done! You guessed it.'</syntaxhighlight>


An older version used <code>while [ "$guess" -ne "$number" ]</code>. With [[pdksh]], input like '+' or '4x' would force the test to fail, end that while loop, and act like a correct guess. With <code>until [ "$guess" -eq "$number" ]</code>, input like '+' or '4x' now continues this until loop, and acts like a wrong guess. With Heirloom's Bourne Shell, '+' acts like '0' (always a wrong guess), and '4x' acts like '4' (perhaps correct).
An older version used <code>while [ "$guess" -ne "$number" ]</code>. With [[pdksh]], input like '+' or '4x' would force the test to fail, end that while loop, and act like a correct guess. With <code>until [ "$guess" -eq "$number" ]</code>, input like '+' or '4x' now continues this until loop, and acts like a wrong guess. With Heirloom's Bourne Shell, '+' acts like '0' (always a wrong guess), and '4x' acts like '4' (perhaps correct).
Line 3,250: Line 3,440:
==={{header|C Shell}}===
==={{header|C Shell}}===
{{libheader|jot}}
{{libheader|jot}}
<lang csh>#!/bin/csh -f
<syntaxhighlight lang="csh">#!/bin/csh -f
# Guess the number
# Guess the number


Line 3,263: Line 3,453:
@ guess = "$<"
@ guess = "$<"
end
end
echo 'Well done! You guessed it.'</lang>
echo 'Well done! You guessed it.'</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
{{trans|Python}}
{{trans|Python}}
<lang ursa># Simple number guessing game
<syntaxhighlight lang="ursa"># Simple number guessing game


decl ursa.util.random random
decl ursa.util.random random
Line 3,278: Line 3,468:
end while
end while


out "That's right!" endl console</lang>
out "That's right!" endl console</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>int main() {
<syntaxhighlight lang="vala">int main() {
int x = Random.int_range(1, 10);
int x = Random.int_range(1, 10);
stdout.printf("Make a guess (1-10): ");
stdout.printf("Make a guess (1-10): ");
Line 3,288: Line 3,478:
stdout.printf("Got it!\n");
stdout.printf("Got it!\n");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang VB>Sub GuessTheNumber()
<syntaxhighlight lang="vb">Sub GuessTheNumber()
Dim NbComputer As Integer, NbPlayer As Integer
Dim NbComputer As Integer, NbPlayer As Integer
Randomize Timer
Randomize Timer
Line 3,299: Line 3,489:
Loop While NbComputer <> NbPlayer
Loop While NbComputer <> NbPlayer
MsgBox "Well guessed!"
MsgBox "Well guessed!"
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang VBScript>randomize
<syntaxhighlight lang="vbscript">randomize
MyNum=Int(rnd*10)+1
MyNum=Int(rnd*10)+1
Do
Do
Line 3,322: Line 3,512:
wscript.quit
wscript.quit
end if
end if
loop</lang>
loop</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>Module Guess_the_Number
<syntaxhighlight lang="vbnet">Module Guess_the_Number
Sub Main()
Sub Main()
Dim random As New Random()
Dim random As New Random()
Line 3,348: Line 3,538:
Loop Until gameOver
Loop Until gameOver
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>
{{Out}}
{{Out}}
<pre>I am thinking of a number from 1 to 10. Can you guess it?
<pre>I am thinking of a number from 1 to 10. Can you guess it?
Line 3,362: Line 3,552:
Well guessed!</pre>
Well guessed!</pre>


=={{header|Vlang}}==
=={{header|V (Vlang)}}==
<lang go>import rand
<syntaxhighlight lang="go">import rand
import rand.seed
import rand.seed
import os
import os
Line 3,381: Line 3,571:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Please guess a number from 1-10 and press <Enter>: 1
<pre>Please guess a number from 1-10 and press <Enter>: 1
Line 3,397: Line 3,587:
=={{header|WebAssembly}}==
=={{header|WebAssembly}}==
Uses [https://github.com/WebAssembly/WASI WASI] for I/O and random number generation. May be run directly with [https://github.com/bytecodealliance/wasmtime wasmtime].
Uses [https://github.com/WebAssembly/WASI WASI] for I/O and random number generation. May be run directly with [https://github.com/bytecodealliance/wasmtime wasmtime].
<lang WebAssembly>(module
<syntaxhighlight lang="webassembly">(module
(import "wasi_unstable" "fd_read"
(import "wasi_unstable" "fd_read"
(func $fd_read (param i32 i32 i32 i32) (result i32)))
(func $fd_read (param i32 i32 i32 i32) (result i32)))
Line 3,524: Line 3,714:
end
end
)
)
)</lang>
)</syntaxhighlight>


=={{header|Wee Basic}}==
=={{header|Wee Basic}}==
Due to how the code works, any key has to be entered to generate the random number.
Due to how the code works, any key has to be entered to generate the random number.
<lang Wee Basic>let mnnumber=1
<syntaxhighlight lang="wee basic">let mnnumber=1
let mxnumber=10
let mxnumber=10
let number=mnnumber
let number=mnnumber
Line 3,551: Line 3,741:
endif
endif
wend
wend
end</lang>
end</syntaxhighlight>


=={{header|Wortel}}==
=={{header|Wortel}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
num 10Wc
num 10Wc
guess 0
guess 0
Line 3,563: Line 3,753:
!alert "Congratulations!\nThe number was {num}."
!alert "Congratulations!\nThe number was {num}."
]
]
}</lang>
}</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for Stdin, Stdout
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout
import "random" for Random
import "random" for Random


Line 3,579: Line 3,769:
break
break
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,592: Line 3,782:
=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
{{works with|NASM|Linux}}
{{works with|NASM|Linux}}
<lang asm>
<syntaxhighlight lang="asm">


segment .data
segment .data
Line 3,696: Line 3,886:


; "Guess my number" program by Randomboi (8/8/2021)
; "Guess my number" program by Randomboi (8/8/2021)
</syntaxhighlight>
</lang>


=={{header|XBS}}==
=={{header|XBS}}==
<lang xbs>const Range:{Min:number,Max:number} = {
<syntaxhighlight lang="xbs">const Range:{Min:number,Max:number} = {
Min:number=1,
Min:number=1,
Max:number=10,
Max:number=10,
Line 3,711: Line 3,901:
stop;
stop;
}
}
}</lang>
}</syntaxhighlight>


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang lisp>(defun guessing-game ()
<syntaxhighlight lang="lisp">(defun guessing-game ()
(defun prompt ()
(defun prompt ()
(display "What is your guess? ")
(display "What is your guess? ")
Line 3,727: Line 3,917:
(display "I have thought of a number between 1 and 10. Try to guess it!")
(display "I have thought of a number between 1 and 10. Try to guess it!")
(newline)
(newline)
(prompt))</lang>
(prompt))</syntaxhighlight>
{{out}}
{{out}}
<pre>[1] (guessing-game)
<pre>[1] (guessing-game)
Line 3,747: Line 3,937:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>code Ran=1, IntIn=10, Text=12;
<syntaxhighlight lang="xpl0">code Ran=1, IntIn=10, Text=12;
int N, G;
int N, G;
[N:= Ran(10)+1;
[N:= Ran(10)+1;
Line 3,757: Line 3,947:
];
];
Text(0, "Well guessed!^M^J");
Text(0, "Well guessed!^M^J");
]</lang>
]</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Strings are used to avoid dealing with error handling
Strings are used to avoid dealing with error handling
<lang zkl>r:=((0).random(10)+1).toString();
<syntaxhighlight lang="zkl">r:=((0).random(10)+1).toString();
while(1){
while(1){
n:=ask("Num between 1 & 10: ");
n:=ask("Num between 1 & 10: ");
if(n==r){ println("Well guessed!"); break; }
if(n==r){ println("Well guessed!"); break; }
println("Nope")
println("Nope")
}</lang>
}</syntaxhighlight>


=={{header|Zoomscript}}==
=={{header|Zoomscript}}==
For typing:
For typing:
<lang Zoomscript>var randnum
<syntaxhighlight lang="zoomscript">var randnum
var guess
var guess
randnum & random 1 10
randnum & random 1 10
Line 3,782: Line 3,972:
endif
endif
endwhile
endwhile
print "Correct number. You win!"</lang>
print "Correct number. You win!"</syntaxhighlight>


For importing:
For importing:

Latest revision as of 16:01, 20 March 2024

Task
Guess the number
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Write a program where the program chooses a number between   1   and   10.

A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct.

When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits.

A   conditional loop   may be used to repeat the guessing until the user is correct.


Related tasks



11l

Translation of: Python
V t = random:(1..10)
V g = Int(input(‘Guess a number that's between 1 and 10: ’))
L t != g
   g = Int(input(‘Guess again! ’))
print(‘That's right!’)

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program guessNumber.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE,          100


/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessNum: .asciz "I'm thinking of a number between 1 and 10. \n Try to guess it:\n"

szMessError:            .asciz "That's not my number. Try another guess:\n"
szMessSucces:           .asciz "Correct.\n"

szCarriageReturn:       .asciz "\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss 
sBuffer:              .skip BUFFERSIZE
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main 
main: 
    mov x0,1
    mov x1,10
    bl extRandom                                // generate random number
    mov x5,x0
    
    ldr x0,qAdrszMessNum
    bl affichageMess
loop:
    mov x0,#STDIN                               // Linux input console
    ldr x1,qAdrsBuffer                          // buffer address 
    mov x2,#BUFFERSIZE                          // buffer size 
    mov x8,#READ                                // request to read datas
    svc 0                                       // call system
    ldr x1,qAdrsBuffer                          // buffer address 
    mov x2,#0                                   // end of string
    sub x0,x0,#1                                // replace character 0xA
    strb w2,[x1,x0]                             // store byte at the end of input string (x0 contains number of characters)
    ldr x0,qAdrsBuffer
    bl conversionAtoD                           // call routine conversion ascii to décimal
    cmp x0,x5
    beq 1f
    ldr x0,qAdrszMessError                      // not Ok
    bl affichageMess
    b loop
1:
    ldr x0,qAdrszMessSucces                     // ok
    bl affichageMess

100:                                            // standard end of the program
    mov x0, #0                                  // return code
    mov x8, #EXIT                               // request to exit program
    svc 0                                       // perform system call
qAdrszMessNum:            .quad szMessNum
qAdrszMessError:          .quad szMessError
qAdrszMessSucces:         .quad szMessSucces

qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsBuffer:              .quad sBuffer
/******************************************************************/
/*     random number                                          */ 
/******************************************************************/
/*  x0 contains inferior value */
/*  x1 contains maxi value */
/*  x0 return random number */
extRandom:
    stp x1,lr,[sp,-16]!        // save  registers
    stp x2,x8,[sp,-16]!        // save  registers
    stp x19,x20,[sp,-16]!      // save  registers
    sub sp,sp,16               // reserve 16 octets on stack
    mov x19,x0
    add x20,x1,1
    mov x0,sp                  // store result on stack
    mov x1,8                   // length 8 bytes
    mov x2,0
    mov x8,278                 //  call system Linux 64 bits Urandom
    svc 0
    mov x0,sp                  // load résult on stack
    ldr x0,[x0]
    sub x2,x20,x19             // calculation of the range of values 
    udiv x1,x0,x2              // calculation range modulo
    msub x0,x1,x2,x0
    add  x0,x0,x19             // and add inferior value
100:
    add sp,sp,16               // alignement stack 
    ldp x19,x20,[sp],16        // restaur  2 registers
    ldp x2,x8,[sp],16          // restaur  2 registers
    ldp x1,lr,[sp],16          // restaur  2 registers
    ret                        // retour adresse lr x30
 
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

ABAP

REPORT guess_the_number.

DATA prng TYPE REF TO cl_abap_random_int.

cl_abap_random_int=>create(
  EXPORTING
    seed = cl_abap_random=>seed( )
    min  = 1
    max  = 10
  RECEIVING
    prng = prng ).

DATA(number) = prng->get_next( ).

DATA(field) = VALUE i( ).

cl_demo_input=>add_field( EXPORTING text = |Choice one number between 1 and 10| CHANGING field = field ).
cl_demo_input=>request( ).

WHILE number <> field.
  cl_demo_input=>add_field( EXPORTING text = |You miss, try again| CHANGING field = field ).
  cl_demo_input=>request( ).
ENDWHILE.

cl_demo_output=>display( |Well Done| ).

Action!

PROC Main()
  BYTE x,n,min=[1],max=[10]

  PrintF("Try to guess a number %B-%B: ",min,max)
  x=Rand(max-min+1)+min
  DO
    n=InputB()
    IF n=x THEN
      PrintE("Well guessed!")
      EXIT
    ELSE
      Print("Incorrect. Try again: ")
    FI
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

Try to guess a number 1-10: 7
Incorrect. Try again: 4
Incorrect. Try again: 5
Incorrect. Try again: 2
Incorrect. Try again: 6
Incorrect. Try again: 1
Incorrect. Try again: 8
Incorrect. Try again: 3
Incorrect. Try again: 9
Well guessed!

Ada

with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
procedure Guess_Number is
   subtype Number is Integer range 1 .. 10;
   package Number_IO is new Ada.Text_IO.Integer_IO (Number);
   package Number_RNG is new Ada.Numerics.Discrete_Random (Number);
   Generator  : Number_RNG.Generator;
   My_Number  : Number;
   Your_Guess : Number;
begin
   Number_RNG.Reset (Generator);
   My_Number := Number_RNG.Random (Generator);
   Ada.Text_IO.Put_Line ("Guess my number!");
   loop
      Ada.Text_IO.Put ("Your guess: ");
      Number_IO.Get (Your_Guess);
      exit when Your_Guess = My_Number;
      Ada.Text_IO.Put_Line ("Wrong, try again!");
   end loop;
   Ada.Text_IO.Put_Line ("Well guessed!");
end Guess_Number;

-------------------------------------------------------------------------------------------------------
-- Another version ------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Numerics.Discrete_Random;

-- procedure main - begins program execution
procedure main is
guess : Integer := 0;
counter : Integer := 0;
theNumber : Integer := 0;

-- function generate number - creates and returns a random number between the
-- ranges of 1 to 100
function generateNumber return Integer is
   type randNum is new Integer range 1 .. 100;
   package Rand_Int is new Ada.Numerics.Discrete_Random(randNum);
   use Rand_Int;
   gen : Generator;
   numb : randNum;

begin
   Reset(gen);
   
   numb := Random(gen);
   
   return Integer(numb);
end generateNumber;

-- procedure intro - prints text welcoming the player to the game
procedure intro is
begin
   Put_Line("Welcome to Guess the Number");
   Put_Line("===========================");
   New_Line;
   
   Put_Line("Try to guess the number. It is in the range of 1 to 100.");
   Put_Line("Can you guess it in the least amount of tries possible?");
   New_Line;
end intro;

begin
   New_Line;
   
   intro;
   theNumber := generateNumber;
   
   -- main game loop
   while guess /= theNumber loop
      Put("Enter a guess: ");
      guess := integer'value(Get_Line);
      
      counter := counter + 1;
      
      if guess > theNumber then
         Put_Line("Too high!");
      elsif guess < theNumber then
         Put_Line("Too low!");
      end if;
   end loop;
   
   New_Line;
   
   Put_Line("CONGRATULATIONS! You guessed it!");
   Put_Line("It took you a total of " & integer'image(counter) & " attempts.");
   
   New_Line;
end main;

Aime

file f;
integer n;
text s;

f.stdin;

n = irand(1, 10);
o_text("I'm thinking of a number between 1 and 10.\n");
o_text("Try to guess it!\n");
while (1) {
    f_look(f, "0123456789");
    f_near(f, "0123456789", s);
    if (atoi(s) != n) {
	o_text("That's not my number.\n");
	o_text("Try another guess!\n");
    } else {
	break;
    }
}

o_text("You have won!\n");

ALGOL 68

Translation of: C
Works with: ALGOL 68 version Revision 1 - no extensions to language used.
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny.
main:
(
    INT n;
    INT g;
    n := ENTIER (random*10+1);
    PROC puts = (STRING string)VOID: putf(standout, ($gl$,string));
    puts("I'm thinking of a number between 1 and 10.");
    puts("Try to guess it! ");
    DO
        readf(($g$, g));
        IF g = n THEN break
        ELSE
          puts("That's not my number. ");
          puts("Try another guess!")
        FI
    OD;
    break: 
    puts("You have won! ")
)

Sample output:

I'm thinking of a number between 1 and 10.
Try to guess it! 
1
That's not my number. 
Try another guess!
2
That's not my number. 
Try another guess!
3
You have won! 

AppleScript

on run
    -- define the number to be guessed
    set numberToGuess to (random number from 1 to 10)
    -- prepare a variable to store the user's answer
    set guessedNumber to missing value
    -- start a loop (will be exited by using "exit repeat" after a correct guess)
    repeat
        try
            -- ask the user for his/her guess
            set usersChoice to (text returned of (display dialog "Guess the number between 1 and 10 inclusive" default answer "" buttons {"Check"} default button "Check"))
            -- try to convert the given answer to an integer
            set guessedNumber to usersChoice as integer
        on error
            -- something gone wrong, overwrite user's answer with a non-matching value
            set guessedNumber to missing value
        end try
        -- decide if the user's answer was the right one
        if guessedNumber is equal to numberToGuess then
            -- the user guessed the correct number and gets informed
            display dialog "Well guessed! The number was " & numberToGuess buttons {"OK"} default button "OK"
            -- exit the loop (quits this application)
            exit repeat
        end if
    end repeat
end run


Or, constraining mutation, and abstracting a little to an until(predicate, function, value) pattern

-- GUESS THE NUMBER ----------------------------------------------------------

on run
    -- isMatch :: Int -> Bool
    script isMatch
        on |λ|(x)
            tell x to its guess = its secret
        end |λ|
    end script
    
    -- challenge :: () -> {secret: Int, guess: Int}
    script challenge
        on response()
            set v to (text returned of (display dialog ¬
                "Guess the number in range 1-10" default answer ¬
                "" buttons {"Esc", "Check"} default button ¬
                "Check" cancel button "Esc"))
            
            if isInteger(v) then
                v as integer
            else
                -1
            end if
        end response
        
        on |λ|(rec)
            {secret:(random number from 1 to 10), guess:response() ¬
                of challenge, attempts:(attempts of rec) + 1}
        end |λ|
    end script
    
    
    -- MAIN LOOP -------------------------------------------------------------
    set rec to |until|(isMatch, challenge, {secret:-1, guess:0, attempts:0})
    
    display dialog (((guess of rec) as string) & ":    Well guessed ! " & ¬
        linefeed & linefeed & "Attempts: " & (attempts of rec))
end run


-- GENERIC FUNCTIONS ---------------------------------------------------------

-- isInteger :: a -> Bool
on isInteger(e)
    try
        set n to e as integer
    on error
        return false
    end try
    true
end isInteger

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
    set mp to mReturn(p)
    set v to x
    
    tell mReturn(f)
        repeat until mp's |λ|(v)
            set v to |λ|(v)
        end repeat
    end tell
    return v
end |until|

Arturo

n: random 1 10

while [notEqual? to :integer input "Guess the number: " n] [
	print "Wrong!"
] 

print "Well guessed!"
Output:
Guess the number: 2
Wrong!
Guess the number: 4
Wrong!
Guess the number: 6
Wrong!
Guess the number: 7
Wrong!
Guess the number: 3
Well guessed!

AutoHotkey

Random, rand, 1, 10  ; This stores a number between 1 and 10 in the var rand using the Mersenne Twister
msgbox I am thinking of a number between 1 and 10.

loop
{
	InputBox, guess, Guess the number, Type in a number from 1 to 10
		If (guess = rand)
		{
			msgbox Well Guessed!
			Break ; exits loop
		}
		Else
			Msgbox Try again.
}

AutoIt

$irnd = Random(1, 10, 1)
$iinput = -1
While $input <> $irnd
	$iinput = InputBox("Choose a number", "Please chosse a Number between 1 and 10")
WEnd
MsgBox(0, "Success", "Well guessed!")

AWK

# syntax: GAWK -f GUESS_THE_NUMBER.AWK
BEGIN {
    srand()
    n = int(rand() * 10) + 1
    print("I am thinking of a number between 1 and 10. Try to guess it.")
    while (1) {
      getline ans
      if (ans !~ /^[0-9]+$/) {
        print("Your input was not a number. Try again.")
        continue
      }
      if (n == ans) {
        print("Well done you.")
        break
      }
      print("Incorrect. Try again.")
    }
    exit(0)
}

BASIC

Applesoft BASIC

10 N% = RND(1) * 10 + 1
20 PRINT "A NUMBER FROM 1 ";
30 PRINT "TO 10 HAS BEEN ";
40 PRINT "RANDOMLY CHOSEN."
50 FOR Q = 0 TO 1 STEP 0
60     INPUT "ENTER A GUESS. "; G%
70     Q = G% = N%
80 NEXT
90 PRINT "WELL GUESSED!"

Commodore BASIC

For the most part, identical to the Applesoft BASIC example above, except that Commodore BASIC evaluates TRUE as a value of -1 instead of 1.

10 n% = int(rnd(1)*10)+1
20 print chr$(147);chr$(14)
30 print "I have chosen a number from 1 to 10."
40 print
50 for q = 0 TO -1 step 0
60     input "What is your guess";g%
70     q = g% = n%
80 next
90 print "WELL GUESSED!"
Output:
I have chosen a number from 1 to 10.

What is your guess? 5
What is your guess? 3
What is your guess? 7
WELL GUESSED!

ready.

IS-BASIC

100 PROGRAM "Guess.bas"
110 RANDOMIZE
120 LET N=RND(10)+1
130 DO
140   INPUT PROMPT "Guess a number that's between 1-10: ":G
150 LOOP UNTIL N=G
160 PRINT "Well guessed!"

QBasic, Gives Hints

supervisor:
GOSUB initialize
GOSUB guessing
GOTO continue

initialize:
RANDOMIZE TIMER
n = 0: r = INT(RND * 100 + 1): g = 0: c$ = ""
RETURN

guessing:
WHILE g <> r
    INPUT "Pick a number between 1 and 100"; g
    IF g = r THEN
        PRINT "You got it!"
        n = n + 1
        PRINT "It took "; n; "tries to pick the right number."
    ELSEIF g < r THEN
        PRINT "Try a larger number."
        n = n + 1
    ELSE
        PRINT "Try a smaller number."
        n = n + 1
    END IF
WEND
RETURN

continue:
WHILE c$ <> "YES" AND c$ <> "NO"
    INPUT "Do you want to continue? (YES/NO)"; c$
    c$ = UCASE$(c$)
    IF c$ = "YES" THEN
        GOTO supervisor
    ELSEIF c$ = "NO" THEN
        STOP
    END IF
WEND

QBasic, More Polished Version

A more polished version of this program in QBasic/QB/VB-DOS

' OPTION EXPLICIT ' Remove remark for VB-DOS/PDS 7.1
'dIM
' Var
DIM n AS INTEGER, g AS INTEGER, t AS INTEGER, a AS STRING
CONST c = 10

' Functions
DECLARE FUNCTION getNumber () AS INTEGER

' Program to guess a number between 1 and 10
DO
  CLS
  PRINT "Program to guess a number between 1 and 10"
  n = getNumber()
  t = 0
  DO
    t = t + 1
    DO
      PRINT "Type a number (between 1 and " + FORMAT$(c) + "): ";
      INPUT "", g
      IF g < 1 OR g > c THEN BEEP
    LOOP UNTIL g > 0 AND g < (c + 1)

    ' Compares the number
    SELECT CASE g
      CASE IS > n: PRINT "Try a lower number..."
      CASE IS < n: PRINT "Try a higher number..."
      CASE ELSE: PRINT "You got it! Attempts: " + FORMAT$(t)
    END SELECT
  LOOP UNTIL n = g
  PRINT
  PRINT "Do you want to try again? (Y/n)"
  DO
   a = UCASE$(INKEY$)
   IF a <> "" AND a <> "Y" AND a <> "N" THEN BEEP
  LOOP UNTIL a = "Y" OR a = "N"
LOOP UNTIL a = "N"
PRINT
PRINT "End of the program. Thanks for playing."
END

FUNCTION getNumber () AS INTEGER
  ' Generates a random number
  ' between 1 and the c Constant

  RANDOMIZE TIMER
  getNumber = INT(RND * c) + 1

END FUNCTION

QB64

The following is a modification of the above polished version in QBasic with explanations of differences.

Randomize Timer        'Moved to the head as it is an initialization statement, 
                       'although it could be placed anywhere prior to the Rnd() function being called.

'Dimensioning the function is not required, nor used, by the QB64 compiler.

'Var
Dim As Integer n, g, t 'Multiple variables of the same type may be defined as a list
Dim As String a        'Variables of different types require their own statements
Const c = 10

' Program to guess a number between 1 and 10
Do
    Cls
    Print "Program to guess a number between 1 and 10"
    n = Int(Rnd * c) + 1  'Removed the function call since this was the only statement left in it
    t = 0
    Do
        t = t + 1
        Do
            Print "Type a number (between 1 and " + LTrim$(Str$(c)) + "): "; 'FORMAT$ is not a function in QB64
                                                                             'The Str$() function converts the number to its text
                                                                             'value equivalent, while LTrim$() removes a leading 
                                                                             'space character placed in front of positive values.
            Input "", g
            If g < 1 Or g > c Then Beep
        Loop Until g > 0 And g < (c + 1)

        ' Compares the number
        Select Case g
            Case Is > n: Print "Try a lower number..."
            Case Is < n: Print "Try a higher number..."
            Case Else: Print "You got it! Attempts: " + LTrim$(Str$(t)) 'Use of LTrim$() and Str$() for the same reasons as above.
        End Select
    Loop Until n = g
    Print
    Print "Do you want to try again? (Y/n)"
    Do
        a = UCase$(InKey$)
        If a <> "" And a <> "Y" And a <> "N" Then Beep
    Loop Until a = "Y" Or a = "N"
Loop Until a = "N"
Print
Print "End of the program. Thanks for playing."
End

QB64 Alternative Version, Gives Hints

Single-line "Guess the Number" program QBasic QB64 from Russia

1 IF Russia = 0 THEN Russia = 2222: RANDOMIZE TIMER: num = INT(RND * 100) + 1: GOTO 1 ELSE IF Russia <> 0 THEN INPUT n: IF n < num THEN PRINT "MORE": GOTO 1 ELSE IF n > num THEN PRINT "less": GOTO 1 ELSE IF n = num THEN PRINT "da": END ELSE GOTO 1 'DANILIN Russia 9-9-2019 guessnum.bas

The multi-line equivalent of the above.

'Based on DANILIN Russia 9-9-2019 guessnum.bas
1 If c% = 0 Then
    c% = 1
    Randomize Timer
    n% = Int(Rnd * 100) + 1
    GoTo 1
Else
    Input g%
    If g% < n% Then
        Print "MORE"
        GoTo 1
    ElseIf g% > n% Then
        Print "less"
        GoTo 1
    Else
        Print "da"
        End
    End If
End If

QB64 Expanded Range, Auto-Interactive

Note: This is off-task, as there is no user interaction.

Program from Russia guesses 1 out of a billion

h1=0: h2=10^9:t=1:f=0: Randomize Timer 'daMilliard.bas
human = Int(Rnd*h2) 'human DANILIN
comp = Int(Rnd*h2) 'comp

While f < 1
Print t; "human ="; human; "     comp ="; comp;

If comp < human Then
Print " MORE": a=comp: comp=Int((comp+h2)/2): h1=a

  Else If human < comp Then
  Print " less": a=comp: comp=Int((h1+comp)/2): h2=a

    Else If human=comp Then
    Print " win by "; t; " steps": f=1
End If: End If: End If: t = t + 1
Wend: End
Output:
1    40    11    MORE
2    40    55    less
3    40    33    MORE
4    40    44    less
5    40    38    MORE
6    40    41    less
7    40    39    MORE
8    40    40    win by 8 steps

ZX Spectrum Basic

ZX Spectrum Basic has no conditional loop constructs, so we have to emulate them here using IF and GO TO.

10 LET n=INT (RND*10)+1
20 INPUT "Guess a number that's between 1 and 10: ",g
30 IF g=n THEN PRINT "That's my number!": STOP
40 PRINT "Guess again!"
50 GO TO 20

BASIC256

n = int(rand * 10) + 1
print "I am thinking of a number from 1 to 10"
do
   input "Guess it > ",g
   if g <> n then
      print "No luck,  Try again."
   endif
until g = n
print "Yea! You guessed my number."

Batch File

At the line set /a answer=%random%%%(10-1+1)+1, if you want to change the minimum and maximum numbers, change all number ones (not counting the one that is in 10) to your desired chosen number and for the maximum, which is 10, do the same, but for maximum (eg. the minimum could be 123 and the maximum could be 321, etc.).

@echo off
set /a answer=%random%%%(10-1+1)+1
set /p guess=Pick a number between 1 and 10: 
:loop
if %guess%==%answer% (echo Well guessed!
pause) else (set /p guess=Nope, guess again: 
goto loop)

BBC BASIC

      choose% = RND(10)
      REPEAT
        INPUT "Guess a number between 1 and 10: " guess%
        IF guess% = choose% THEN
          PRINT "Well guessed!"
          END
        ELSE
          PRINT "Sorry, try again"
        ENDIF
      UNTIL FALSE

Befunge

Works with: Fungus version 0.28
Works with: CCBI version 2.1
v     RNG anthouse
>          v  ,,,,,,<
          v?v       ,
         vvvvv      ,
        v?????v     ,
       vvvvvvvvv    ,
      >?????????v   ,
      >vvvvvvvvvv<  ,
      >??????????<  ,
      >vvvvvvvvvv<  ,
      >??????????<  ,
      >vvvvvvvvvv<  ^"Well guessed!"<
      >??????????<        >"oN",,91v  actual game unit
       1234567899         ^_91+"!"  ^
                1          ^-g22<&<>+,v
                +>,,,,,,,,,,,,,,,,^
       >>>>>>>>>v^"guessthenumber!"+19<
       RNG unit > 22p                 ^

Bracmat

The value is generated by the clk function, which returns a (probably) non-integral rational number. The den function retrieves the denominators of this number. The rational number, multiplied by its denominator, becomes an natural number.

( ( GuessTheNumber
  =   mynumber
    .   clk$:?mynumber
      & mod$(!mynumber*den$!mynumber.10)+1:?mynumber
      &   whl
        ' ( put'"Guess my number:"
          & get':~!mynumber:?K
          )
      & out'"Well guessed!"
  )
& GuessTheNumber$
);

Brat

number = random 10

p "Guess a number between 1 and 10."

until {
  true? ask("Guess: ").to_i == number
    { p "Well guessed!"; true }
    { p "Guess again!" }
}

C

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main(void)
{
    int n;
    int g;
    char c;

    srand(time(NULL));
    n = 1 + (rand() % 10);

    puts("I'm thinking of a number between 1 and 10.");
    puts("Try to guess it:");

    while (1) {
        if (scanf("%d", &g) != 1) {
		/* ignore one char, in case user gave a non-number */
		scanf("%c", &c);
		continue;
	}

        if (g == n) {
	    puts("Correct!");
	    return 0;
	}
        puts("That's not my number. Try another guess:");
    }
}

C#

using System;

class GuessTheNumberGame
{
    static void Main()
    {
        int randomNumber = new Random().Next(1, 11);
        
        Console.WriteLine("I'm thinking of a number between 1 and 10. Can you guess it?");
        while(true)
        {
            Console.Write("Guess: ");
            if (int.Parse(Console.ReadLine()) == randomNumber)
                break;
            Console.WriteLine("That's not it. Guess again.");
        }
        Console.WriteLine("Congrats!! You guessed right!");
    }
};


Expanded Range, Auto-Interactive

Note: This is off-task, as there is no user interaction.

Program from Russia guesses 1 out of a billion
https://rextester.com/DYVZM84267

using System; using System.Text; //daMilliard.cs 
namespace DANILIN

{ class Program
    { static void Main(string[] args)
    { Random rand = new Random();int t=0;
int h2=100000000; int h1=0; int f=0; 
int comp = rand.Next(h2); 
int human = rand.Next(h2); 

while (f<1)
{ Console.WriteLine();Console.Write(t);
Console.Write(" ");Console.Write(comp); 
Console.Write(" ");Console.Write(human);

if(comp < human)
{ Console.Write(" MORE");
int a=comp; comp=(comp+h2)/2; h1=a; }

else if(comp > human)
{ Console.Write(" less");
int a=comp; comp=(h1+comp)/2; h2=a;}

else {Console.Write(" win by ");
Console.Write(t); Console.Write(" steps");f=1;}
t++; }}}}
Output:
1    40    11    MORE
2    40    55    less
3    40    33    MORE
4    40    44    less
5    40    38    MORE
6    40    41    less
7    40    39    MORE
8    40    40    win by 8 steps

C++

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    srand(time(0));
    int n = 1 + (rand() % 10);
    int g;
    std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! ";
    while(true)
    {
        std::cin >> g;
        if (g == n)
            break;
        else
            std::cout << "That's not my number.\nTry another guess! ";
    }
    std::cout << "You've guessed my number!";
    return 0;
}

Clojure

(def target (inc (rand-int 10))

(loop [n 0]
   (println "Guess a number between 1 and 10 until you get it right:")
   (let [guess (read)]
	(if (= guess target)
	    (printf "Correct on the %d guess.\n" n)
	    (do
	     (println "Try again")
	     (recur (inc n))))))

COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. Guess-The-Number.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  Random-Num PIC 99.
       01  Guess      PIC 99.

       PROCEDURE DIVISION.
           COMPUTE Random-Num = 1 + (FUNCTION RANDOM * 10)
           DISPLAY "Guess a number between 1 and 10:"

           PERFORM FOREVER
               ACCEPT Guess

               IF Guess = Random-Num
                   DISPLAY "Well guessed!"
                   EXIT PERFORM
               ELSE
                   DISPLAY "That isn't it. Try again."
               END-IF
           END-PERFORM
           
           GOBACK
           .

CoffeeScript

num = Math.ceil(Math.random() * 10)
guess = prompt "Guess the number. (1-10)"
while parseInt(guess) isnt num
  guess = prompt "YOU LOSE! Guess again. (1-10)"
alert "Well guessed!"
Works with: node.js
# This shows how to do simple REPL-like I/O in node.js.
readline = require "readline"

do ->
  number = Math.ceil(10 * Math.random())
  interface = readline.createInterface process.stdin, process.stdout

  guess = ->
    interface.question "Guess the number between 1 and 10: ", (answer) ->
      if parseInt(answer) == number
        # These lines allow the program to terminate.
        console.log "GOT IT!"
        interface.close()
        process.stdin.destroy()
      else
        console.log "Sorry, guess again"
        guess()
      
  guess()

Common Lisp

(defun guess-the-number (max)
  (format t "Try to guess a number from 1 to ~a!~%Guess? " max)
  (loop with num = (1+ (random max))
        for guess = (read)
        as num-guesses from 1
        until (and (numberp guess) (= guess num))
        do (format t "Your guess was wrong.  Try again.~%Guess? ")
           (force-output)
        finally (format t "Well guessed! You took ~a ~:*~[~;try~:;tries~].~%" num-guesses)))

Output:

CL-USER> (guess-the-number 10)
Try to guess a number from 1 to 10!
Guess? a
Your guess was wrong.  Try again.
Guess? 1
Your guess was wrong.  Try again.
Guess? 2
Your guess was wrong.  Try again.
Guess? 3
Well guessed! You took 4 tries!

Crystal

Translation of: Ruby
n = rand(1..10)
puts "Guess the number: 1..10"
until gets.to_s.to_i == n; puts "Wrong! Guess again: " end
puts "Well guessed!"

D

void main() {
    immutable num = uniform(1, 10).text;

    do write("What's next guess (1 - 9)? ");
    while (readln.strip != num);

    writeln("Yep, you guessed my ", num);
}
Output:
What's next guess (1 - 9)? 1
What's next guess (1 - 9)? 2
What's next guess (1 - 9)? 3
Yep, you guessed my 3!

Dart

Translation of: Kotlin
import 'dart:math';
import 'dart:io';

main() {
  final n = (1 + new Random().nextInt(10)).toString();
  print("Guess which number I've chosen in the range 1 to 10");
  do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
  print("\nWell guessed!");
}

DCL

$ time = f$time()
$ number = f$extract( f$length( time ) - 1, 1, time ) + 1
$ loop:
$  inquire guess "enter a guess (integer 1-10) "
$  if guess .nes. number then $ goto loop
$ write sys$output "Well guessed!"
Output:
$ @guess_the_number
enter a guess (integer 1-10) : 5
enter a guess (integer 1-10) : 1
enter a guess (integer 1-10) : 2
enter a guess (integer 1-10) : 3
enter a guess (integer 1-10) : 4
Well guessed!

Delphi

program GuessTheNumber;

{$APPTYPE CONSOLE}

uses SysUtils;

var
  theDigit : String ;
  theAnswer : String ;

begin
  Randomize ;
  theDigit := IntToStr(Random(9)+1) ;
  while ( theAnswer <> theDigit ) do Begin
    Writeln('Please enter a digit between 1 and 10' ) ;
    Readln(theAnswer);
  End ;
  Writeln('Congratulations' ) ;
end.

Déjà Vu

local :number random-range 1 11

while true:
	if = number to-num !prompt "Guess my number: ":
		!print "Congratulations, you've guessed it!"
		return
	else:
		!print "Nope, try again."

EasyLang

n = randint 10
write "Guess a number between 1 and 10: "
repeat
  g = number input
  write g
  until g = n
  print " is wrong"
  write "try again: "
.
print " is correct. Well guessed!"

Eiffel

class
	APPLICATION

create
	make

feature {NONE} -- Initialization

	make
		local
			number_to_guess: INTEGER
		do
			number_to_guess := (create {RANDOMIZER}).random_integer_in_range (1 |..| 10)
			from
				print ("Please guess the number!%N")
				io.read_integer
			until
				io.last_integer = number_to_guess
			loop
				print ("Please, guess again!%N")
				io.read_integer
			end
			print ("Well guessed!%N")
		end

end

The code above is simplified if we create a RANDOMIZER, which simplifies reuse (e.g. the code in RANDOMIZER does not have to be recreated for each need of a random number).

class
	RANDOMIZER

inherit
	ANY
		redefine
			default_create
		end

feature {NONE} -- Initialization

	default_create
			-- <Precursor>
		local
			time: TIME
		do
			sequence.do_nothing
		end

feature -- Access

	random_integer_in_range (a_range: INTEGER_INTERVAL): INTEGER
		do
			Result := (sequence.double_i_th (1) * a_range.upper).truncated_to_integer + a_range.lower
		end

feature {NONE} -- Implementation

	sequence: RANDOM
		local
			seed: INTEGER_32
			time: TIME
		once
			create time.make_now
			seed := time.hour *
					(60 + time.minute) *
					(60 + time.second) *
					(1000 + time.milli_second)
			create Result.set_seed (seed)
		end

end
Output:
Please guess the number!
10

Please, guess again!
9

Please, guess again!
8

Correct!

Elena

ELENA 6.x :

import extensions;
 
public program()
{
    int randomNumber := randomGenerator.nextInt(1,10);
    console.printLine("I'm thinking of a number between 1 and 10.  Can you guess it?");
    bool numberCorrect := false;
    until(numberCorrect)
    {
        console.print("Guess: ");
        int userGuess := console.readLine().toInt();
        if (randomNumber == userGuess)
        {
            numberCorrect := true;
            console.printLine("Congrats!!  You guessed right!")
        }
        else
        {
            console.printLine("That's not it.  Guess again.")
        }
    }
}
Output:
I'm thinking of a number between 1 and 10.  Can you guess it?
Guess: 2
That's not it.  Guess again.
Guess: 5
That's not it.  Guess again.
Guess: 6
Congrats!!  You guessed right!

Elixir

Works with: Elixir version 1.2
defmodule GuessingGame do
  def play do
    play(Enum.random(1..10))
  end
  
  defp play(number) do
    guess = Integer.parse(IO.gets "Guess a number (1-10): ")
    case guess do
      {^number, _} ->
        IO.puts "Well guessed!"
      {n, _} when n in 1..10 ->
        IO.puts "That's not it."
        play(number)
      _ ->
        IO.puts "Guess not in valid range."
        play(number)
    end
  end
end
 
GuessingGame.play

Emacs Lisp

(let ((number (1+ (random 10))))
  (while (not (= (read-number "Guess the number ") number))
    (message "Wrong, try again."))
  (message "Well guessed! %d" number))

Erlang

% Implemented by Arjun Sunel
-module(guess_the_number).
-export([main/0]).

main() ->
	io:format("Guess my number between 1 and 10 until you get it right:\n"),
	N = random:uniform(10),
	guess(N).

guess(N) ->
	{ok, [K]} = io:fread("Guess number :  ","~d"),
	
	if 
		K=:=N ->
			io:format("Well guessed!!\n");
		true -> 
			guess(N)	
	end.

ERRE

PROGRAM GUESS_NUMBER

!
! for rosettacode.org
!

BEGIN

  RANDOMIZE(TIMER)
  N=0
  R=INT(RND(1)*100+1)  ! RND function gives a random number from 0 to 1
  G=0
  C$=""

  WHILE G<>R DO
    INPUT("Pick a number between 1 and 100";G)
    IF G=R THEN
        PRINT("You got it!")
        N+=1
        PRINT("It took";N;"tries to pick the right Number.")
    ELSIF G<R THEN
        PRINT("Try a larger number.")
        N+=1
    ELSE
        PRINT("Try a smaller number.")
        N+=1
    END IF
  END WHILE
END PROGRAM

Note: Adapted from Qbasic version.

Euphoria

Translation of: ZX_Spectrum_Basic
include get.e

integer n,g
n = rand(10)

puts(1,"I have thought of a number from 1 to 10.\n")
puts(1,"Try to guess it!\n")

while 1 do
    g = prompt_number("Enter your guess: ",{1,10})
    if n = g then
        exit
    end if
    puts(1,"Your guess was wrong. Try again!\n")
end while

puts(1,"Well done! You guessed it.")

Factor

USING: io random math math.parser kernel formatting ;
IN: guess-the-number

<PRIVATE

: gen-number ( -- n )
  10 random 1 + ;

: make-guess ( n -- n ? )
  dup readln string>number = ;

: play-game ( n -- n )
  [ make-guess ]
  [ "Guess a number between 1 and 10:" print flush ] do until ;

PRIVATE>

: guess-the-number ( -- )
  gen-number play-game
  "Yes, the number was %d!\n" printf ;

Fantom

class Main
{
  public static Void main ()
  {
    Str target := (1..10).random.toStr
    Str guess := ""
    while (guess != target)
    {
      echo ("Enter a guess: ")
      guess = Env.cur.in.readLine
      if (guess.trim == target) // 'trim' to remove any spaces/newline
      {
        echo ("Well guessed!")
        break
      }
      else
        echo ("Failed - try again")
    }
  }
}

Forth

\ tested with GForth  0.7.0
: RND    ( -- n) TIME&DATE 2DROP 2DROP DROP 10 MOD ;         \ crude random number
: ASK    ( -- ) CR ." Guess a number between 1 and 10? " ;
: GUESS  ( -- n)  PAD DUP 4 ACCEPT EVALUATE ;
: REPLY  ( n n' -- n)  2DUP <> IF CR ." No, it's not " DUP . THEN ;

: GAME ( -- )
          RND
          BEGIN   ASK GUESS REPLY  OVER =  UNTIL
          CR ." Yes it was " .
          CR ." Good guess!"  ;

Fortran

program guess_the_number
 implicit none

 integer                          :: guess
 real                             :: r
 integer                          :: i, clock, count, n
 integer,dimension(:),allocatable :: seed

 real,parameter :: rmax = 10	

!initialize random number generator:
 call random_seed(size=n)
 allocate(seed(n))
 call system_clock(count)
 seed = count
 call random_seed(put=seed)
 deallocate(seed)

!pick a random number between 1 and rmax:
 call random_number(r)          !r between 0.0 and 1.0
 i = int((rmax-1.0)*r + 1.0)    !i between 1 and rmax

!get user guess:
 write(*,'(A)') 'I''m thinking of a number between 1 and 10.'
 do   !loop until guess is correct
	write(*,'(A)',advance='NO') 'Enter Guess: '
	read(*,'(I5)') guess
	if (guess==i) exit
	write(*,*) 'Sorry, try again.'
 end do

 write(*,*) 'You''ve guessed my number!'

end program guess_the_number

FreeBASIC

' FB 1.05.0 Win64

Randomize
Dim n As Integer = Int(Rnd * 10) + 1
Dim guess As Integer
Print "Guess which number I've chosen in the range 1 to 10"
Print
Do
  Input " Your guess : "; guess
  If n = guess Then
    Print "Well guessed!"
    End
  End If
Loop
Output:

Sample input/output :

Guess which number I've chosen in the range 1 to 10

 Your guess : ? 3
 Your guess : ? 6
 Your guess : ? 7
 Your guess : ? 9
 Your guess : ? 2
 Your guess : ? 4
Well guessed!

Frink

// Guess a Number
target = random[1,10] // 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 10. 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 10."]
   else
      guess == target ? println["$guess is correct. Well guessed!"] : println["$guess is not correct. Guess again!"]
}
Output:

Including an example with a non-integer entered.

Welcome to guess a number! I've picked a number between 1 and 10. Try to guess it!
2 is not correct. Guess again!
4 is not correct. Guess again!
ABC is not a valid guess. Please enter a number from 1 to 10.
6 is not correct. Guess again!
5 is not correct. Guess again!
7 is correct. Well guessed!

FutureBasic

void local fn BuildWindow
  window 1, @"Guess the number (1-10)", (0,0,480,270), NSWindowStyleMaskTitled
  textfield 1,,, (220,124,40,21)
  ControlSetAlignment( 1, NSTextAlignmentCenter )
  WindowMakeFirstResponder( 1, 1 )
  AppSetProperty( @"Number", @(rnd(10)) )
end fn

void local fn DoDialog( ev as long, tag as long )
  select ( ev )
    case _btnClick
      select ( tag )
        case 1
          if ( fn ControlIntegerValue( 1 ) == fn NumberIntegerValue( fn AppProperty( @"Number" ) ) )
            alert 1,, @"Well guessed!",, @"Exit"
            end
          else
            textfield 1,, @""
            alert 1,, @"Wrong number!",, @"Try again"
          end if
      end select
  end select
end fn

fn BuildWindow

on dialog fn DoDialog

HandleEvents

Gambas

Public Sub Form_Open()
Dim byGuess, byGos As Byte
Dim byNo As Byte = Rand(1, 10)
Dim sHead As String = "Guess the number"

Repeat
  Inc byGos
  byGuess = InputBox("Guess the number between 1 and 10", sHead)
  sHead = "Sorry, have another go"
Until byGuess = byNo

Message.Info("Well guessed! You took " & Str(byGos) & " gos to guess the number was " & Str(byNo), "OK")
Me.Close

End

GML

var n, g;
n = irandom_range(1,10);
show_message("I'm thinking of a number from 1 to 10");
g = get_integer("Please enter guess", 1);
while(g != n)
    {
    g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1);
    }
show_message("Well guessed!");

Go

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    fmt.Print("Guess number from 1 to 10: ")
    rand.Seed(time.Now().Unix())
    n := rand.Intn(10) + 1
    for guess := n; ; fmt.Print("No. Try again: ") {
        switch _, err := fmt.Scan(&guess); {
        case err != nil:
            fmt.Println("\n", err, "\nSo, bye.")
            return
        case guess == n:
            fmt.Println("Well guessed!")
            return
        }
    }
}

Groovy

def random = new Random()
def keyboard = new Scanner(System.in)
def number = random.nextInt(10) + 1
println "Guess the number which is between 1 and 10: "
def guess = keyboard.nextInt()
while (number != guess) {
    println "Guess again: "
    guess = keyboard.nextInt()
}
println "Hurray! You guessed correctly!"

GW-BASIC

10 RANDOMIZE TIMER:N=INT(RND*10+1):G=0
20 PRINT "Guess the number between 1 and 10."
30 WHILE N<>G
40 INPUT "Your guess? ",G
50 WEND
60 PRINT "That's correct!"

Haskell

import Control.Monad
import System.Random

-- Repeat the action until the predicate is true.
until_ act pred = act >>= pred >>= flip unless (until_ act pred)

answerIs ans guess 
    | ans == guess = putStrLn "You got it!" >> return True
    | otherwise = putStrLn "Nope. Guess again." >> return False

ask = liftM read getLine

main = do
  ans <- randomRIO (1,10) :: IO Int
  putStrLn "Try to guess my secret number between 1 and 10."
  ask `until_` answerIs ans

Simple version:

import System.Random

main = randomRIO (1,10) >>= gameloop

gameloop :: Int -> IO ()
gameloop r = do	
	i <- fmap read getLine
	if i == r 
	  then putStrLn "You got it!"
	  else putStrLn "Nope. Guess again." >> gameloop r

HolyC

U8 n, *g;

n = 1 + RandU16 % 10;

Print("I'm thinking of a number between 1 and 10.\n");
Print("Try to guess it:\n");

while(1) {
  g = GetStr;

  if (Str2I64(g) == n) {
    Print("Correct!\n");
    break;
  }

  Print("That's not my number. Try another guess:\n");
}

Icon and Unicon

This solution works in both languages.

procedure main()
    n := ?10
    repeat {
        writes("Pick a number from 1 through 10: ")
        if n = numeric(read()) then break
        }
    write("Well guessed!")
end

J

require 'misc'
game=: verb define
  n=: 1 + ?10
  smoutput 'Guess my integer, which is bounded by 1 and 10'
  whilst. -. guess -: n do.
    guess=. {. 0 ". prompt 'Guess: '
    if. 0 -: guess do. 'Giving up.' return. end. 
    smoutput (guess=n){::'no.';'Well guessed!'
  end.
)

Example session:

   game''
Guess my integer, which is bounded by 1 and 10
Guess: 1
no.
Guess: 2
Well guessed!

Java

Works with: Java version 6+
public class Guessing {
    public static void main(String[] args) throws NumberFormatException{
        int n = (int)(Math.random() * 10 + 1);
        System.out.print("Guess the number between 1 and 10: ");
        while(Integer.parseInt(System.console().readLine()) != n){
            System.out.print("Wrong! Guess again: ");
        }
        System.out.println("Well guessed!");
    }
}

For pre-Java 6, use a Scanner or BufferedReader for input instead of System.console() (see Input loop#Java).

JavaScript

function guessNumber() {
  // Get a random integer from 1 to 10 inclusive
  var num = Math.ceil(Math.random() * 10);
  var guess;

  while (guess != num) {
    guess = prompt('Guess the number between 1 and 10 inclusive');
  }
  alert('Congratulations!\nThe number was ' + num);
}

guessNumber();

Requires a host environment that supports prompt and alert such as a browser.

jq

Works with: jq version 1.5

jq currently does not have a built-in random number generator, so a suitable PRNG for this task is defined below. Once `rand(n)` has been defined, the task can be accomplished as follows:

{prompt: "Please enter your guess:", random: (1+rand(9)) }
| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt),
  "Well done!"

Invocation

With the program as given here in a file named program.jq, a seed must be specified on the command line as illustrated on the following line:

   $ jq -nr -f program.jq --arg seed 17

PRNG

# LCG::Microsoft generates 15-bit integers using the same formula
# as rand() from the Microsoft C Runtime.
# Input: [ count, state, random ]
def next_rand_Microsoft:
  .[0] as $count
  | ((214013 * .[1]) + 2531011) % 2147483648 # mod 2^31
  | [$count+1 , ., (. / 65536 | floor) ];

def rand_Microsoft(seed):
  [0,seed]
  | next_rand_Microsoft  # the seed is not so random
  | next_rand_Microsoft | .[2]; 

# A random integer in [0 ... (n-1)]:
def rand(n): n * (rand_Microsoft($seed|tonumber) / 32768) | trunc;

Jsish

From Javascript entry.

function guessNumber() {
    // Get a random integer from 1 to 10 inclusive
    var num = Math.ceil(Math.random() * 10);
    var guess;
    var tries = 0;
 
    while (guess != num) {
        tries += 1;
        printf('%s', 'Guess the number between 1 and 10 inclusive: ');
        guess = console.input();
    }
    printf('Congratulations!\nThe number was %d   it took %d tries\n', num, tries);
}

if (Interp.conf('unitTest')) {
    // Set a predictable outcome
    Math.srand(0);
    guessNumber();
}

/*
=!INPUTSTART!=
5
9
2
=!INPUTEND!=
*/

/*
=!EXPECTSTART!=
Guess the number between 1 and 10 inclusive: Guess the number between 1 and 10 inclusive: Guess the number between 1 and 10 inclusive: Congratulations!
The number was 2   it took 3 tries
=!EXPECTEND!=
*/
Output:
prompt$ jsish -u guessNumber.jsi
[PASS] guessNumber.jsi

Julia

Works with: Julia version 0.6
function guess()
    number = dec(rand(1:10))
    print("Guess my number! ")
    while readline() != number
        print("Nope, try again... ")
    end
    println("Well guessed!")
end

guess()
Output:
Guess my number! 1
Nope, try again... 2
Nope, try again... 3
Nope, try again... 4
Nope, try again... 5
Nope, try again... 6
Nope, try again... 7
Nope, try again... 8
Nope, try again... 9
Nope, try again... 10
Well guessed!

Kotlin

// version 1.0.5-2

fun main(args: Array<String>) {
	val n = (1 + java.util.Random().nextInt(10)).toString()
	println("Guess which number I've chosen in the range 1 to 10\n")
	do { print(" Your guess : ") } while (n != readLine())
	println("\nWell guessed!")
}

Sample input/output:

Output:
Guess which number I've chosen in the range 1 to 10

 Your guess : 5
 Your guess : 8

Well guessed!

LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

langur

writeln "Guess a number from 1 to 10"

val .n = string random 10
for {
    val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, ""
    if .guess == "" {
        writeln "too much bad data"
        break
    }
    if .guess == .n {
        writeln "That's it."
        break
    }
    writeln "not it"
}
Output:
Guess a number from 1 to 10
>> 0.1
bad data
>> 001.0
not it
>> 789
bad data
>> 2
not it
>> 3
That's it.

Lasso

Command Line

The following example works when Lasso is called from a command line

local(
	number	= integer_random(10, 1),
	status	= false,
	guess
)

// prompt for a number
stdout('Guess a number between 1 and 10: ')

while(not #status) => {
	#guess = null

	// the following bits wait until the terminal gives you back a line of input
	while(not #guess or #guess -> size == 0) => {
		#guess = file_stdin -> readSomeBytes(1024, 1000)
	}
	#guess = integer(#guess)

	if(not (range(#guess, 1, 10) == #guess)) => {
		stdout('Input not of correct type or range. Guess a number between 1 and 10: ')
	else(#guess == #number)
		stdout('Well guessed!')
		#status = true
	else
		stdout('You guessed wrong number. Guess a number between 1 and 10: ')
	}

}

Web form

The following example is a web page form

<?LassoScript

local(
	number	= integer(web_request -> param('number') or integer_random(10, 1)),
	status	= false,
	guess	= web_request -> param('guess'),
	_guess	= integer(#guess),
	message	= 'Guess a number between 1 and 10'
)



if(#guess) => {
	if(not (range(#_guess, 1, 10) == #_guess)) => {
		#Message = 'Input not of correct type or range. Guess a number between 1 and 10'
	else(#_guess == #number)
		#Message = 'Well guessed!'
		#status = true
	else
		#Message = 'You guessed wrong number. Guess a number between 1 and 10'
	}
}


?><!DOCTYPE html>
<html lang="en">
	<head>
		<title>Guess the number - Rosetta Code</title>
	</head>
	<body>
		<h3>[#message]</h3>
[if(not #status)]
		<form method="post">
			<label for="guess">Guess:</label><br/ >
			<input type="number" name="guess" />
			<input name="number" type="hidden" value="[#number]" />
			<input name="submit" type="submit" />
		</form>
[/if]
	</body>
</html>

LFE

(defmodule guessing-game
  (export (main 0)))

(defun get-player-guess ()
  (let (((tuple 'ok (list guessed)) (: io fread '"Guess number: " '"~d")))
    guessed))

(defun check-guess (answer guessed)
    (cond
      ((== answer guessed)
        (: io format '"Well-guessed!!~n"))
      ((/= answer guessed)
        (check-guess answer (get-player-guess)))))

(defun main ()
  (: io format '"Guess the number I have chosen, between 1 and 10.~n")
  (check-guess
    (: random uniform 10)
    (get-player-guess)))

From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):

> (slurp '"guessing-game.lfe")
#(ok guessing-game)
> (main)
Guess the number I have chosen, between 1 and 10.
Guess number: 10
Guess number: 5
Well-guessed!!
ok

Liberty BASIC

number = int(rnd(0) * 10) + 1
input "Guess the number I'm thinking of between 1 and 10. "; guess
while guess <> number
    input "Incorrect! Try again! "; guess
wend
print "Congratulations, well guessed! The number was "; number;"."

LiveCode

command guessTheNumber
    local tNumber, tguess
    put random(10) into tNumber
    repeat until tguess is tNumber
        ask question "Please enter a number between 1 and 10" titled "Guess the number"
        if it is not empty then
            put it into tguess
            if tguess is tNumber then 
                answer "Well guessed!"
            end if
        else
            exit repeat
        end if
    end repeat
end guessTheNumber

Locomotive Basic

10 RANDOMIZE TIME:num=INT(RND*10+1):guess=0
20 PRINT "Guess the number between 1 and 10."
30 WHILE num<>guess
40 INPUT "Your guess? ", guess
50 WEND
60 PRINT "That's correct!"

LOLCODE

There is no native support for random numbers. This solution uses a simple linear congruential generator to simulate them, with the lamentable restriction that the user must first be prompted for a seed.

HAI 1.3

VISIBLE "SEED ME, FEMUR! "!
I HAS A seed, GIMMEH seed

HOW IZ I randomizin
    seed R MOD OF SUM OF 1 AN PRODUKT OF 69069 AN seed AN 10
IF U SAY SO

I IZ randomizin MKAY
I HAS A answer ITZ SUM OF seed AN 1
I HAS A guess

IM IN YR guesser
    VISIBLE "WUTS MY NUMBR? "!
    GIMMEH guess, guess IS NOW A NUMBR

    BOTH SAEM guess AN answer, O RLY?
        YA RLY, VISIBLE "U WIN!", GTFO
    OIC
IM OUTTA YR guesser

KTHXBYE

Lua

math.randomseed( os.time() )
n = math.random( 1, 10 )

print( "I'm thinking of a number between 1 and 10. Try to guess it: " )

repeat
    x = tonumber( io.read() )

    if x == n then
	print "Well guessed!"
    else
	print "Guess again: "
    end
until x == n

M2000 Interpreter

A copy from QBASIC, write blocks { } where needed, We use GOSUB and GOTO in a Module.

Module QBASIC_Based {
      supervisor:
      GOSUB initialize
      GOSUB guessing
      GOTO continue
       
      initialize:
      \\ Not need to RANDOMIZE TIMER
      \\ we can use Random(1, 100) to get a number from 1 to 100
      n = 0: r = INT(RND * 100 + 1): g = 0: c$ = ""
      RETURN
       
      guessing:
      WHILE g <> r {
                INPUT "Pick a number between 1 and 100:"; g
                IF g = r THEN {
                    PRINT "You got it!"
                    n ++
                    PRINT "It took "; n; " tries to pick the right number."
                } ELSE.IF g < r THEN {
                    PRINT "Try a larger number."
                    n ++
                } ELSE {
                    PRINT "Try a smaller number."
                    n++
                }
      }
      RETURN
       
      continue:
      WHILE c$ <> "YES" AND c$ <> "NO" {
          INPUT "Do you want to continue? (YES/NO)"; c$
          c$ = UCASE$(c$)
          IF c$ = "YES" THEN {
              GOTO supervisor
          } ELSE.IF c$ = "NO" THEN {
              Goto End
          }
      }
      End:     
}
QBASIC_Based

Maple

GuessNumber := proc()
    local number;
    randomize():
    printf("Guess a number between 1 and 10 until you get it right:\n:");
    number := rand(1..10)();
    while parse(readline()) <> number do
        printf("Try again!\n:");
    end do:
    printf("Well guessed! The answer was %d.\n", number);
end proc:
GuessNumber();

Mathematica / Wolfram Language

number = RandomInteger[{1, 10}];
While[guess =!= number, guess = Input["Guess my number"]];
Print["Well guessed!"]

MATLAB

number = ceil(10*rand(1));
[guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));

while (~status || guess ~= number)
    [guess, status] = str2num(input('Guess again: ','s'));
end
disp('Well guessed!')

MAXScript

rand = random 1 10
clearListener()
while true do
(
	userval = getKBValue prompt:"Enter an integer between 1 and 10: "
	if userval == rand do (format "\nWell guessed!\n"; exit)
	format "\nChoose another value\n"
)

Mercury

Mercury does have a 'time' module in its standard library, but it offers an abstract type instead of the seconds-since-the-epoch we want to seed the RNG with. So this is also an example of how easy it is to call out to C. (It's just as easy to call out to C#, Java, and Erlang.) Also, rather than parse the input, this solution prepares the random number to match the typed input. This isn't a weakness of Mercury, just the author's desire to cheat a bit.

:- module guess.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module random, string.

main(!IO) :-
        time(Time, !IO),
        random.init(Time, Rand),
        random.random(1, 10, N, Rand, _),
        main(from_int(N) ++ "\n", !IO).

:- pred main(string::in, io::di, io::uo) is det.
main(N, !IO) :-
        io.write_string("Guess the number: ", !IO),
        io.read_line_as_string(Res, !IO),
        (
                Res = ok(S),
                ( if S = N then io.write_string("Well guessed!\n", !IO)
                  else main(N, !IO) )
        ;
                Res = error(E)
        ;
                Res = eof
        ).

:- pred time(int::out, io::di, io::uo) is det.

:- pragma foreign_decl("C", "#include <time.h>").
:- pragma foreign_proc("C", time(Int::out, _IO0::di, _IO1::uo),
                       [will_not_call_mercury, promise_pure],
                       "Int = time(NULL);").

min

Works with: min version 0.19.6
randomize

9 random succ

"Guess my number between 1 and 10." puts!

("Your guess" ask int over ==) 'pop ("Wrong." puts!) () linrec

"Well guessed!" puts!

MiniScript

num = ceil(rnd*10)
while true
    x = val(input("Your guess?"))
    if x == num then
        print "Well guessed!"
        break
    end if
end while

MIPS Assembly

# WRITTEN: August 26, 2016 (at midnight...)

# This targets MARS implementation and may not work on other implementations
# Specifically, using MARS' random syscall
.data
	take_a_guess: .asciiz "Make a guess:"
	good_job: .asciiz "Well guessed!"

.text
	#retrieve system time as a seed
	li $v0,30
	syscall
	
	#use the high order time stored in $a1 as the seed arg
	move $a1,$a0

	#set the seed
	li $v0,40
	syscall
	
	#generate number 0-9 (random int syscall generates a number where):
	# 0 <= $v0 <= $a1
	li $a1,10
	li $v0,42
	syscall
	
	#increment the randomly generated number and store in $v1
	add $v1,$a0,1
	
loop:	jal print_take_a_guess
	jal read_int
	
	#go back to beginning of loop if user hasn't guessed right,
	#    else, just "fall through" to exit_procedure
	bne $v0,$v1,loop
	
exit_procedure:
	#set syscall to print_string, then set good_job string as arg
	li $v0,4
	la $a0,good_job
	syscall
	
	#exit program
	li $v0,10
	syscall
	
print_take_a_guess:
	li $v0,4
	la $a0,take_a_guess
	syscall
	jr $ra
	
read_int:
	li $v0,5
	syscall
	jr $ra

Nanoquery

Translation of: Ursa
random = new(Nanoquery.Util.Random)
target = random.getInt(9) + 1
guess = 0

println "Guess a number between 1 and 10."
while not target = guess
	guess = int(input())
end

println "That's right!"

Nemerle

using System;
using System.Console;

module Guess
{
    Main() : void
    {
        def rand = Random();
        def x = rand.Next(1, 11);  // returns 1 <= x < 11
        mutable guess = 0;
    
        do
        {
            WriteLine("Guess a nnumber between 1 and 10:");
            guess = Int32.Parse(ReadLine());
        } while (guess != x);
    
        WriteLine("Well guessed!");   
    }
}

NetRexx

/* NetRexx */

options replace format comments java crossref savelog symbols nobinary

guessThis = (Math.random * 10 + 1) % 1
guess = -1
prompt = [ -
  'Try guessing a number between 1 and 10', -
  'Wrong; try again...' -
  ]
promptIdx = int 0

loop label g_ until guess = guessThis
  say prompt[promptIdx]
  promptIdx = 1
  parse ask guess .
  if guess = guessThis then do
    say 'Well guessed!' guess 'is the correct number.'
    leave g_
    end
  end g_

return

NewLISP

; guess-number.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number

(seed (time-of-day)) ; Initialize random number generator from clock.
(setq number (+ 1 (rand 10)))

(println "I'm thinking of a number between 1 and 10. Can you guess it?")
(print   "Type in your guess and hit [enter]: ")
(while (!= number (int (read-line))) (print "Nope! Try again: "))
(println "Well guessed! Congratulations!")

(exit)

Sample output:

I'm thinking of a number between 1 and 10. Can you guess it?
Type in your guess and hit [enter]: 5
Nope! Try again: 3
Nope! Try again: 10
Nope! Try again: 1
Nope! Try again: 4
Well guessed! Congratulations!

Nim

import strutils, random
 
randomize()
var chosen = rand(1..10)
echo "I have thought of a number. Try to guess it!"
 
var guess = parseInt(readLine(stdin))

while guess != chosen:
  echo "Your guess was wrong. Try again!"
  guess = parseInt(readLine(stdin))
 
echo "Well guessed!"

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 "INCORRECT GUESS. TRY AGAIN.": GOTO 20
40 PRINT "CORRECT NUMBER."

Oberon-2

Works with oo2c Version 2

MODULE GuessTheNumber;
IMPORT 
  RandomNumbers,
  In,
  Out;

  PROCEDURE Do;
  VAR
    n,guess: LONGINT;
  BEGIN
    n := RandomNumbers.RND(10);
    Out.String("Guess a number between 1 and 10: ");Out.Flush();
    LOOP
      In.LongInt(guess);  
      IF  guess = n THEN 
        Out.String("You guessed!!"); Out.Ln; EXIT
      END;
      Out.String(" Sorry, try again: ");Out.Flush()
    END
  END Do;

BEGIN
  Do;
END GuessTheNumber.

Objeck

use IO;

bundle Default {
  class GuessNumber {
    function : Main(args : String[]) ~ Nil {
      done := false;
      "Guess the number which is between 1 and 10 or 'q' to quite: "->PrintLine();
      rand_num := (Float->Random() * 10.0)->As(Int) + 1;
      while(done = false) {
        guess := Console->ReadString();
        number := guess->ToInt();
        if(number <> 0) {
          if(number <> rand_num) {
            "Guess again: "->PrintLine();
          }
          else {
            "Hurray! You guessed correctly!"->PrintLine();
            done := true;
          };
        }
        else {
          if(guess->StartsWith("q") | guess->StartsWith("Q")) {
            done := true;
          };
        };
      };
    }
  }
}

Objective-C

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSLog(@"I'm thinking of a number between 1 - 10. Can you guess what it is?\n");
        
        int rndNumber = arc4random_uniform(10) + 1;
        
        // Debug (Show rndNumber in console)
        //NSLog(@"Random number is %i", rndNumber);
        
        int userInput;
        
        do {
           
            NSLog(@"Input the number below\n");
            scanf("%i", &userInput);
          
            if (userInput > 10) {
              
                NSLog(@"Please enter a number less than 10\n");
            }
            
            if (userInput > 10 || userInput != rndNumber) {
                
                NSLog(@"Your guess %i is incorrect, please try again", userInput);
                
            } else {
                
                NSLog(@"Your guess %i is correct!", userInput);
            }
        
        } while (userInput > 10 || userInput != rndNumber);
    }
    return 0;
}

OCaml

#!/usr/bin/env ocaml

let () =
  Random.self_init();
  let n =
    if Random.bool () then
      let n = 2 + Random.int 8 in
      print_endline "Please guess a number between 1 and 10 excluded";
      (n)
    else
      let n = 1 + Random.int 10 in
      print_endline "Please guess a number between 1 and 10 included";
      (n)
  in
  while read_int () <> n do
    print_endline "The guess was wrong! Please try again!"
  done;
  print_endline "Well guessed!"

Oforth

import: console

: guess
   10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ]
   drop "Well guessed!" . ;

Ol

(import (otus random!))

(define number (+ 1 (rand! 10)))
(let loop ()
   (display "Pick a number from 1 through 10: ")
   (if (eq? (read) number)
      (print "Well guessed!")
      (loop)))

PARI/GP

guess()=my(r=random(10)+1);while(input()!=r,); "Well guessed!";

Pascal

Program GuessTheNumber(input, output);

var
  number, guess: integer;

begin
  randomize;
  number := random(10) + 1;
  writeln ('I''m thinking of a number between 1 and 10, which you should guess.');
  write   ('Enter your guess: ');
  readln  (guess);
  while guess <> number do
  begin
    writeln ('Sorry, but your guess is wrong. Please try again.');
    write   ('Enter your new guess: ');
    readln  (guess);
  end;
  writeln ('You made an excellent guess. Thank you and have a nice day.');
end.

Perl

my $number = 1 + int rand 10;
do { print "Guess a number between 1 and 10: " } until <> == $number;
print "You got it!\n";

Phix

--
-- demo\rosetta\Guess_the_number.exw
--
with javascript_semantics
include pGUI.e

integer secret = rand(10)

function valuechanged_cb(Ihandle guess)
    integer n = IupGetInt(guess,"VALUE")
    if n=secret then
        Ihandle lbl = IupGetBrother(guess,true)
        IupSetAttribute(lbl,"TITLE","Your guess was correct")
        IupRefresh(lbl)
        IupSetInt(guess,"ACTIVE",false)
    end if
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()
    Ihandle lbl = IupLabel("Your guess","RASTERSIZE=58x21"),
            guess = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"),
                            "RASTERSIZE=21x21"),
            dlg = IupDialog(IupVbox({IupFill(),
                            IupHbox({IupFill(),lbl,guess,IupFill()},
                                    "GAP=10"),
                            IupFill()}),
                            `MINSIZE=300x100,TITLE="Guess the number"`)
    IupShow(dlg)
    IupSetAttribute(lbl,"RASTERSIZE","x21")
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure
 
main()

PHP

<?php

session_start();

if(isset($_SESSION['number']))
{
   $number = $_SESSION['number'];
}
else
{
   $_SESSION['number'] = rand(1,10);
}


if(isset($_POST["guess"])){
	if($_POST["guess"]){
	    $guess  = htmlspecialchars($_POST['guess']);
	 
		echo $guess . "<br />";
	    if ($guess != $number)
		{ 
	        echo "Your guess is not correct";
	    }
		elseif($guess == $number)
		{
	        echo "You got the correct number!";
	    }
	} 
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Guess A Number</title>
	</head>

	<body>
		<form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number">
		    <label for="guess">Guess number:</label><br/ >
		    <input type="text" name="guess" />
		    <input name="number" type="hidden" value="<?= $number ?>" />
		    <input name="submit" type="submit" />
		</form>
	</body>
</html>

Picat

go =>
  N = random(1,10),
  do print("Guess a number: ")
  while (read_int() != N),
  println("Well guessed!").
Translation of: Prolog
go2 =>
  N = random(1, 10),
  repeat,
  print('Guess the number: '),
  N = read_int(),
  println("Well guessed!"),
  !.

PicoLisp

(de guessTheNumber ()
   (let Number (rand 1 9)
      (loop
         (prin "Guess the number: ")
         (T (= Number (read))
            (prinl "Well guessed!") )
         (prinl "Sorry, this was wrong") ) ) )

Plain English

To run:
Start up.
Play guess the number.
Wait for the escape key.
Shut down.

To play guess the number:
Pick a secret number between 1 and 10.
Write "I picked a secret number between 1 and 10." to the console.
Loop.
Write "What is your guess? " to the console without advancing.
Read a number from the console.
If the number is the secret number, break.
Repeat.
Write "Well guessed!" to the console.

Plain TeX

This code should be compiled with etex features in console mode (for example "pdftex <name of the file>"):

\newlinechar`\^^J
\edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}%
\message{^^JI'm thinking of a number between 1 and 10, try to guess it!}%
\newif\ifnotguessed
\notguessedtrue
\loop
	\message{^^J^^JYour try: }\read -1 to \useranswer
	\ifnum\useranswer=\tagetnumber\relax
		\message{You win!^^J}\notguessedfalse
	\else
		\message{No, it's another number, try again...}%
	\fi
	\ifnotguessed
\repeat
\bye

PowerShell

Provides a function that analyzes the provided number by its call. The second script block is important and needed inside the script so the function will be called.

Function GuessNumber($Guess)
{
    $Number = Get-Random -min 1 -max 11
    Write-Host "What number between 1 and 10 am I thinking of?"
        Do
        {
        Write-Warning "Try again!"
        $Guess = Read-Host "What's the number?"
        }
        While ($Number -ne $Guess)
    Write-Host "Well done! You successfully guessed the number $Guess."
}
$myNumber = Read-Host "What's the number?"
GuessNumber $myNumber

ProDOS

Uses math module:

:a
editvar /modify /value=-random-= <10
editvar /newvar /value=-random- /title=a
editvar /newvar /value=b /userinput=1 /title=Guess a number:
if -b- /hasvalue=-a- printline You guessed correctly! else printline Your guess was wrong & goto :a

Prolog

Works with: SWI-Prolog version 6
main :-
    random_between(1, 10, N),
    repeat,
    prompt1('Guess the number: '),
    read(N),
    writeln('Well guessed!'),
    !.

Example:

?- main.
Guess the number: 1.
Guess the number: 2.
Guess the number: 3.
Well guessed!
true.

PureBasic

If OpenConsole()
  Define TheNumber=Random(9)+1
  
  PrintN("I've picked a number from 1 to 10." + #CRLF$)
  Repeat
    Print("Guess the number: ")
  Until TheNumber=Val(Input()) 
  
  PrintN("Well guessed!")
  
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf

Python

import random
t,g=random.randint(1,10),0
g=int(input("Guess a number that's between 1 and 10: "))
while t!=g:g=int(input("Guess again! "))
print("That's right!")

Expanded Range, Auto-Interactive

Note: This is off-task, as there is no user interaction.

Program from Russia guesses 1 out of a billion
https://rextester.com/GWJFOO4393

import random #milliard.py
h1 = 0; h2 = 10**16; t = 0; f=0
c = random.randrange(0,h2) #comp
h = random.randrange(0,h2) #human DANILIN

while f<1:
    print(t,c,h)

    if h<c:
        print('MORE')
        a=h
        h=int((h+h2)/2)
        h1=a

    elif h>c:
        print('less')
        a=h
        h=int((h1+h)/2)
        h2=a

    else:
        print('win by', t, 'steps')
        f=1
    t=t+1
Output:
1    40    11    MORE
2    40    55    less
3    40    33    MORE
4    40    44    less
5    40    38    MORE
6    40    41    less
7    40    39    MORE
8    40    40    win by 8 steps

QB64

CBTJD: 2020/04/13

START:
CLS
RANDOMIZE TIMER
num = INT(RND * 10) + 1
DO
    INPUT "Enter a number between 1 and 10: ", n
    IF n = num THEN EXIT DO
    PRINT "Nope."
LOOP UNTIL n = num
INPUT "Well guessed! Go again"; a$
IF LEFT$(LCASE$(a$), 1) = "y" THEN GOTO START

QB64

'Task
'Plus features:  1) AI gives suggestions about your guess
' 2) AI controls wrong input by user (numbers outer  1   and   10).
' 3) player can choose to replay the game

Randomize Timer
Dim As Integer Done, Guess, Number

Done = 1
Guess = 0
While Done
    Cls
    Number = Rnd * 10 + 1
    Do While Number <> Guess
        Cls
        Locate 2, 1
        Input "What number have I thought? (1-10)", Guess
        If Guess > 0 And Guess < 11 Then
            If Guess = Number Then
                Locate 4, 1: Print "Well done, you win!"; Space$(20)
                Exit Do
            ElseIf Guess > Number Then
                Locate 4, 1: Print "Too high, try lower"; Space$(20)
            ElseIf Guess < Number Then
                Locate 4, 1: Print "Too low, try higher"; Space$(20)
            End If
        Else
            Print "Wrong input data! Try again"; Space$(20)
        End If
        _Delay 1
        If Done = 11 Then Exit Do Else Done = Done + 1
    Loop
    If Done = 11 Then
        Locate 4, 1: Print "Ah ah ah, I win and you loose!"; Space$(20)
    Else
        Locate 4, 1: Print " Sigh, you win!"; Space$(20)
    End If
    Locate 6, 1: Input "Another play? 1 = yes, others values = no ", Done
    If Done <> 1 Then Done = 0
Wend
End

Quackery

randomise
10 random 1+ number$
say 'I chose a number between 1 and 10.' cr
[ $ 'Your guess? ' input
  over = if
    done
  again ]
drop say 'Well guessed!'

A sample output of exceptionally bad guessing:

Output:
I chose a number between 1 and 10.
Your guess? 5
Your guess? 4
Your guess? 1
Your guess? 10
Your guess? 3
Your guess? 2
Your guess? 6
Your guess? 7
Your guess? 8
Your guess? 9
Well guessed!

R

f <- function() {
    print("Guess a number between 1 and 10 until you get it right.")
    n <- sample(10, 1)
    while (as.numeric(readline()) != n) {
        print("Try again.")
    }
    print("You got it!")
}

Racket

#lang racket
(define (guess-number)
  (define number (add1 (random 10)))
  (let loop ()
    (define guess (read))
    (if (equal? guess number)
        (display "Well guessed!\n")
        (loop))))

Raku

(formerly Perl 6)

my $number = (1..10).pick;
repeat {} until prompt("Guess a number: ") == $number;
say "Guessed right!";

RapidQ

RANDOMIZE
number = rnd(10) + 1
Print "I selected a number between 1 and 10, try to find it:" + chr$(10)

while Guess <> Number 
    input "Your guess: "; Guess
wend

print "You guessed right, well done !"
input "Press enter to quit";a$

Rascal

import vis::Render;
import vis::Figure;
import util::Math;

public void Guess(){
	random = arbInt(10);
	entered = "";
	guess = false;
	figure = box(vcat([
			text("Try to guess the number from 0 to 9."),
			textfield("Put your guess here", void(str s){guess = (toInt(s)==random); entered = s; }, fillColor("white")),
			text(str(){return guess ? "Correct answer!" : "This is false, the number is not <entered>.";}),
			button("Start over", void(){random = arbInt(10);}) ]));	 	
	render(figure);
}

Output:

Red

Red []
#include %environment/console/CLI/input.red
random/seed now
print "I have thought of a number between 1 and 10. Try to guess it."
number: random 10
while [(to integer! input) <> number][
    print "Your guess was wrong. Try again."
]
print "Well guessed!"

Retro

: checkGuess ( gn-gf || f )
  over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;

: think ( -n )
  random abs 10 mod 1+ ;

: guess ( - )
  "I'm thinking of a number between 1 and 10.\n" puts
  "Try to guess it!\n" puts
  think [ getToken toNumber checkGuess ] while
  "You got it!\n" puts ;

REXX

version 1

(Note: most REXXes won't accept that first statement, the shebang/sha-bang/hashbang/pound-bang/hash-exclam/hash-pling.)

#!/usr/bin/rexx
/*REXX program to play:    Guess the number  */

number = random(1,10)
say "I have thought of a number. Try to guess it!"

guess=0    /* We don't want a valid guess, before we start */

do while guess \= number
  pull guess
  if guess \= number then
    say "Sorry, the guess was wrong. Try again!"
  /* endif - There is no endif in rexx. */
end

say "Well done! You guessed it!"

version 2

/*REXX program interactively plays "guess my number" with a human, the range is 1──►10. */
?= random(1, 10)                                 /*generate a low random integer.       */
say 'Try to guess my number between 1 ──► 10  (inclusive).'  /*the directive to be used.*/

                     do j=1  until  g=?                      /*keep prompting 'til done.*/
                     if j\==1  then say 'Try again.'         /*issue secondary prompt.  */
                     pull g                                  /*obtain a guess from user.*/
                     end   /*j*/
say 'Well guessed!'                              /*stick a fork in it,  we're all done. */

Ring

### Bert Mariani
### 2018-03-01
### Guess_My_Number

myNumber = random(10)
answer   = 0

See "Guess my number between 1 and 10"+ nl

while answer != myNumber
  See "Your guess: "
  Give answer

  if answer = myNumber
    See "Well done! You guessed it! "+ myNumber +nl
  else
    See "Try again"+ nl
  ok

  if answer = 0
    See "Give up. My number is: "+ myNumber +nl
  ok
end

RPL

DIR
  INITIALIZE
  << { C G R } PURGE RAND 10 * 1 + IP 'R' STO GUESSING
  >>
  GUESSING
  << "Pick a number between 1 and 10." "" INPUT OBJ-> 'G' STO
     IF
       G R ==
     THEN
       CLLCD "You got it!" 1 DISP 7 FREEZE 0 WAIT CLLCD CONTINUE
     ELSE
       IF
         G R <
       THEN
         CLLCD "Try a larger number." 1 DISP 7 FREEZE 0 WAIT GUESSING
       ELSE
         CLLCD "Try a smaller number." 1 DISP 7 FREEZE 0 WAIT GUESSING
       END
     END
  >>
  CONTINUE
  << "Do you want to continue? (0/1)" "" INPUT OBJ-> 'C' STO
     IF
       C 1 ==
     THEN
       INITIALIZE
     ELSE
       CLEAR
     END
  >>
END

Ruby

n = rand(1..10)
puts 'Guess the number: '
puts 'Wrong! Guess again: ' until gets.to_i == n
puts 'Well guessed!'

Run BASIC

while 1
choose = int(RND(0) * 9) + 1
while guess <> choose
   print "Guess a number between 1 and 10: ";: input guess
   if guess = choose THEN
      print "You guessed!"
     else
      print "Sorry, try again"
   end if
wend
wend

Rust

Library: rand
extern crate rand;

fn main() {
    println!("Type in an integer between 1 and 10 and press enter.");

    let n = rand::random::<u32>() % 10 + 1;
    loop {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let option: Result<u32,_> = line.trim().parse();
        match option {
            Ok(guess) => {
                if guess < 1 || guess > 10 {
                    println!("Guess is out of bounds; try again.");
                } else if guess == n {
                    println!("Well guessed!");
                    break;
                } else {
                    println!("Wrong! Try again.");
                }
            },
            Err(_) => println!("Invalid input; try again.")
        }
    }
}

Scala

val n = (math.random * 10 + 1).toInt
print("Guess the number: ")
while(readInt != n) print("Wrong! Guess again: ")
println("Well guessed!")

Scheme

Works with: Chicken Scheme
Works with: Guile
(define (guess) 
  (define number (random 11))
  (display "Pick a number from 1 through 10.\n> ")
  (do ((guess (read) (read)))
        ((= guess number) (display "Well guessed!\n"))
      (display "Guess again.\n")))
Output:
scheme> (guess)
Pick a number from 1 through 10.
1
Guess again.
2
Guess again.
3
Guess again.
4
Guess again.
5
Well guessed!

Seed7

$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: number is 0;
    var integer: guess is 0;
  begin
    number := rand(1, 10);
    writeln("I'm thinking of a number between 1 and 10.");
    writeln("Try to guess it!");
    readln(guess);
    while guess <> number do
      writeln("That's not my number.");
      writeln("Try another guess!");
      readln(guess);
    end while;
    writeln("You have won!");
  end func;

Self

Gives dialog boxes in GUI, uses stdout/in otherwise.

Well factored:

(| 
parent* = traits clonable.
copy = (resend.copy secretNumber: random integerBetween: 1 And: 10).
secretNumber.

ask             = ((userQuery askString: 'Guess the Number: ') asInteger).
reportSuccess   = (userQuery report: 'You got it!').
reportFailure   = (userQuery report: 'Nope. Guess again.').
sayIntroduction = (userQuery report: 'Try to guess my secret number between 1 and 10.').

hasGuessed = ( [ask = secretNumber] onReturn: [|:r| r ifTrue: [reportSuccess] False: [reportFailure]] ).
run  = (sayIntroduction. [hasGuessed] whileFalse)
|) copy run

Simple method:

| n | 
userQuery report: 'Try to guess my secret number between 1 and 10.'.
n: random integerBetween: 1 And: 10.
[(userQuery askString: 'Guess the Number.') asInteger = n] whileFalse: [
    userQuery report: 'Nope. Guess again.'].
userQuery report: 'You got it!'

Sidef

var n = irand(1, 10)
var msg = 'Guess the number: '
while (n != read(msg, Number)) {
    msg = 'Wrong! Guess again: '
}
say 'Well guessed!'

Small Basic

number=Math.GetRandomNumber(10)
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
    guess=TextWindow.ReadNumber()
    TextWindow.WriteLine("Guess again! ")
EndWhile
TextWindow.WriteLine("You win!")

SNUSP

Works with: SNUSP Bloated

(random numbers are between 0 and 9; %assigns a random value between 0 and current cell value) Unoptimised.

                        /++.#
                        \>.--.++<..+ +\
                        />+++++++.>-.+/
       / \              />++++++>++\
       < +              ?
       < >              \ -<<++++++/   
$++++\ - +              !
/++++/   >              \++++++++++\ 
\+ %!/!\?/>>>,>>>>>>+++\/ !/?\<?\>>/
      /++++++++++++++++/   > -  \\
      \+++++++++\  /    /  - <
      /+++++++++/          \ /
      \+++++++++++\ /++++++++++>>/
       /<<<<<</?\!/ !
              < -   /-<<+++++++\
              < >   ?
              < >   \>+++++++>+/
              < >   >
              < >   .
              < >   \-----.>++\
              - >    /.+++.+++/
              \ /    \!/?\<!/?\    \
       \           /   \-/  \-/
     \          <</?\!>/?\!</?\!<<</
                  \-/  >    \-/
                       + -
                       < >
                       < +
                       \ /

Swift

import Cocoa

var found = false
let randomNum = Int(arc4random_uniform(10) + 1)

println("Guess a number between 1 and 10\n")
while (!found) {
    var fh = NSFileHandle.fileHandleWithStandardInput()
    
    println("Enter a number: ")
    let data = fh.availableData
    var str = NSString(data: data, encoding: NSUTF8StringEncoding)
    if (str?.integerValue == randomNum) {
        found = true
        println("Well guessed!")
    }
}

Tcl

set target [expr {int(rand()*10 + 1)}]
puts "I have thought of a number."
puts "Try to guess it!"
while 1 {
    puts -nonewline "Enter your guess: "
    flush stdout
    gets stdin guess
    if {$guess == $target} {
	break
    }
    puts "Your guess was wrong. Try again!"
}
puts "Well done! You guessed it."

Sample output:

I have thought of a number.
Try to guess it!
Enter your guess: 1
Your guess was wrong. Try again!
Enter your guess: 2
Your guess was wrong. Try again!
Enter your guess: 3
Your guess was wrong. Try again!
Enter your guess: 8
Well done! You guessed it.

TUSCRIPT

$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
luckynumber=RANDOM_NUMBERS (1,10,1)
COMPILE
LOOP round=1,7
message=CONCAT ("[",round,"] Please insert a number")
ASK $message: n=""
 IF (n!='digits') THEN
   PRINT "wrong insert: ",n," Please insert a digit"
 ELSEIF (n>10.or.n<1) THEN
   PRINT "wrong insert: ",n," Please insert a number between 1-10"
 ELSEIF (n==#luckynumber) THEN
   PRINT "BINGO"
   EXIT
ENDIF
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP
ENDCOMPILE

Output:

Find the luckynumber (7 tries)!
[1] Please insert a number >a
wrong insert: a Please insert a digit
[2] Please insert a number >10
[3] Please insert a number >1
[4] Please insert a number >2
[5] Please insert a number >9
[6] Please insert a number >8
BINGO 

UNIX Shell

Works with: Bourne Shell
#!/bin/sh
# Guess the number
# This simplified program does not check the input is valid

# Use awk(1) to get a random number. If awk(1) not found, exit now.
number=`awk 'BEGIN{print int(rand()*10+1)}'` || exit

echo 'I have thought of a number. Try to guess it!'
echo 'Enter an integer from 1 to 10.'
until read guess; [ "$guess" -eq "$number" ]
do
  echo 'Sorry, the guess was wrong! Try again!'
done
echo 'Well done! You guessed it.'

An older version used while [ "$guess" -ne "$number" ]. With pdksh, input like '+' or '4x' would force the test to fail, end that while loop, and act like a correct guess. With until [ "$guess" -eq "$number" ], input like '+' or '4x' now continues this until loop, and acts like a wrong guess. With Heirloom's Bourne Shell, '+' acts like '0' (always a wrong guess), and '4x' acts like '4' (perhaps correct).

C Shell

Library: jot
#!/bin/csh -f
# Guess the number

# jot(1) a random number. If jot(1) not found, exit now.
@ number = `jot -r 1 1 10` || exit

echo 'I have thought of a number. Try to guess it!'
echo 'Enter an integer from 1 to 10.'
@ guess = "$<"
while ( $guess != $number )
	echo 'Sorry, the guess was wrong! Try again!'
	@ guess = "$<"
end
echo 'Well done! You guessed it.'

Ursa

Translation of: Python
# Simple number guessing game

decl ursa.util.random random
decl int target guess

set target (int (+ 1 (random.getint 9)))
out "Guess a number between 1 and 10." endl console
while (not (= target guess))
        set guess (in int console)
end while

out "That's right!" endl console

Vala

int main() {
	int x = Random.int_range(1, 10);
	stdout.printf("Make a guess (1-10): ");
	while(int.parse(stdin.read_line()) != x) 
                stdout.printf("Wrong! Try again: ");
	stdout.printf("Got it!\n");
	return 0;
}

VBA

Sub GuessTheNumber()
Dim NbComputer As Integer, NbPlayer As Integer
    Randomize Timer
    NbComputer = Int((Rnd * 10) + 1)
    Do
        NbPlayer = Application.InputBox("Choose a number between 1 and 10 : ", "Enter your guess", Type:=1)
    Loop While NbComputer <> NbPlayer
    MsgBox "Well guessed!"
End Sub

VBScript

randomize
MyNum=Int(rnd*10)+1
Do
	x=x+1
	YourGuess=InputBox("Enter A number from 1 to 10")
	If not Isnumeric(YourGuess) then
		msgbox YourGuess &" is not numeric. Try again."
	ElseIf CInt(YourGuess)>10 or CInt(YourGuess)<1 then
		msgbox YourGuess &" is not between 1 and 10. Try Again."
	ElseIf CInt(YourGuess)=CInt(MyNum) then
		MsgBox "Well Guessed!"
		wscript.quit
	ElseIf Cint(YourGuess)<>CInt(Mynum) then
		MsgBox "Nope. Try again."
	end If

	if x > 20 then
		msgbox "I take pity on you"
		wscript.quit
	end if
loop

Visual Basic .NET

Module Guess_the_Number
    Sub Main()
        Dim random As New Random()
        Dim secretNum As Integer = random.Next(10) + 1
        Dim gameOver As Boolean = False
        Console.WriteLine("I am thinking of a number from 1 to 10. Can you guess it?")
        Do
            Dim guessNum As Integer
            Console.Write("Enter your guess: ")

            If Not Integer.TryParse(Console.ReadLine(), guessNum) Then
                Console.WriteLine("You should enter a number from 1 to 10. Try again!")
                Continue Do
            End If

            If guessNum = secretNum Then
                Console.WriteLine("Well guessed!")
                gameOver = True
            Else
                Console.WriteLine("Incorrect. Try again!")
            End If
        Loop Until gameOver
    End Sub
End Module
Output:
I am thinking of a number from 1 to 10. Can you guess it?
Enter your guess: abc
You should enter a number from 1 to 10. Try again!
Enter your guess: 1
Incorrect. Try again!
Enter your guess: 2
Incorrect. Try again!
Enter your guess: 3
Incorrect. Try again!
Enter your guess: 4
Well guessed!

V (Vlang)

import rand
import rand.seed
import os

fn main() {
    seed_array := seed.time_seed_array(2)
    rand.seed(seed_array)
    num := rand.intn(10) + 1  // Random number 1-10
    for {
        print('Please guess a number from 1-10 and press <Enter>: ')
        guess := os.get_line()
        if guess.int() == num {
            println("Well guessed! '$guess' is correct.")
            return
        } else {
            println("'$guess' is Incorrect. Try again.")
        }
    }
}
Output:
Please guess a number from 1-10 and press <Enter>: 1
'1' is Incorrect. Try again.
Please guess a number from 1-10 and press <Enter>: 2
'2' is Incorrect. Try again.
Please guess a number from 1-10 and press <Enter>: 9
'9' is Incorrect. Try again.
Please guess a number from 1-10 and press <Enter>: 10
'10' is Incorrect. Try again.
Please guess a number from 1-10 and press <Enter>: 3
Well guessed! '3' is correct.

WebAssembly

Uses WASI for I/O and random number generation. May be run directly with wasmtime.

(module
  (import "wasi_unstable" "fd_read" 
    (func $fd_read (param i32 i32 i32 i32) (result i32)))
  (import "wasi_unstable" "fd_write" 
    (func $fd_write (param i32 i32 i32 i32) (result i32)))
  (import "wasi_unstable" "random_get" 
    (func $random_get (param i32 i32) (result i32)))

  (memory 1) (export "memory" (memory 0))
  ;; memory usage:
  ;; 0-7: temp IO Vector used with WASI functions
  ;; 8-24: temp buffer used for reading numbers
  ;; 100-: string data

  ;; string constants
  (data (i32.const 100) "Guess a number between 1 and 10.\n")
  (data (i32.const 200) "Well guessed!\n")  

  ;; function to print a null-terminated string at the given address
  ;; (assumes use of an IOVector at address 0)
  (func $print_cstr (param $strAddr i32)
	(local $charPos i32)
	
	;; store the data address into our IO vector (address 0)
	i32.const 0  local.get $strAddr  i32.store
	
	;; find the null terminator at the end of the string
	local.get $strAddr  local.set $charPos
	block $loop_break 
	  loop $LOOP
		;; get the character at charPos
		local.get $charPos  i32.load
		;; if it is equal to zero, break out of the loop
		i32.eqz if br $loop_break end
		;; otherwise, increment and loop
		local.get $charPos  i32.const 1  i32.add  local.set $charPos
		br $LOOP
	  end
	end
	
	;; from that, compute the length of the string for our IOVector
	i32.const 4  ;; (address of string length in the IOVector)
	local.get $charPos  local.get $strAddr  i32.sub
	i32.store
	
	;; now call $fd_write to actually write to stdout
	i32.const 1  ;; 1 for stdout
	i32.const 0  i32.const 1   ;; 1 IOVector at address 0
	i32.const 0  ;; where to stuff the number of bytes written
	call $fd_write
	drop  ;; (drop the result value)
  )
  
  ;; function to read a number
  ;; (assumes use of an IOVector at address 0, 
  ;; and 16-character buffer at address 8)
  (func $input_i32 (result i32)
	(local $ptr i32)
	(local $n i32)
	(local $result i32)
	
	;; prepare our IOVector to point to the buffer
	i32.const 0  i32.const 8  i32.store    ;; (address of buffer)
	i32.const 4  i32.const 16  i32.store   ;; (size of buffer)
	
	i32.const 0  ;; 0 for stdin
	i32.const 0  i32.const 1  ;; 1 IOVector at address 0
	i32.const 4  ;; where to stuff the number of bytes read
	call $fd_read  drop

	;; Convert that to a number!
	;; loop over characters in the string until we hit something < '0'.
	i32.const 8  local.set $ptr
	block $LOOP_BREAK
	  loop $LOOP
		;; get value of current digit
		;; (we assume all positive integers for this task)
		local.get $ptr  i32.load8_u
		i32.const 48  i32.sub     ;; (subtract 48, ASCII value of '0')
		local.tee $n
		
		;; bail out if < 0
		i32.const 0  i32.lt_s  br_if $LOOP_BREAK
		
		;; multiply current number by 10, and add new number
		local.get $result  i32.const 10  i32.mul
		local.get $n  i32.add
		local.set $result
		
		;; increment and loop
		local.get $ptr  i32.const 1  i32.add  local.set $ptr
		br $LOOP
	  end
	end
	
	local.get $result
  )
  
  ;; function to get a random i32
  ;; (assumes use of temporary space at address 0)
  (func $random_i32 (result i32)
	i32.const 0  i32.const 4  call $random_get  drop
	i32.const 0  i32.load
  )

  (func $main (export "_start")
	(local $trueNumber i32)
	
	;; get a random integer, then take that (unsigned) mod 10
	call $random_i32  i32.const 10  i32.rem_u
	local.set $trueNumber
	
	loop $LOOP
	    ;; print prompt
	    i32.const 100  call $print_cstr
	
	    ;; input a guess
	    call $input_i32
		
	    ;; if correct, print message and we're done
	    local.get $trueNumber i32.eq  if
		i32.const 200  call $print_cstr
		return
	    end
	    br $LOOP
	end
  )
)

Wee Basic

Due to how the code works, any key has to be entered to generate the random number.

let mnnumber=1
let mxnumber=10
let number=mnnumber
let keycode=0
let guessed=0
print 1 "Press any key so the computer can generate a random number for you to guess."
while keycode=0
let number=number=1
let keycode=key()
if number=mxnumber+1
let number=mnnumber
endif
wend
print 1 "Guess the number. It is between "+mnnumber+"and "+mxnumber
while guessed=0
input guess
if guess=number
print 1 "Well done! You guessed the correct number."
let guessed=1
else
print 1 "You guessed the incorrect number. Please try again."
endif
wend
end

Wortel

Translation of: JavaScript
@let {
  num 10Wc
  guess 0
  [
    @while != guess num
      :guess !prompt "Guess the number between 1 and 10 inclusive"
    !alert "Congratulations!\nThe number was {num}."
  ]
}

Wren

import "io" for Stdin, Stdout
import "random" for Random

var rand = Random.new()
var n = rand.int(1, 11) // computer number from 1..10 inclusive
while (true) {
    System.write("Your guess 1-10 : ")
    Stdout.flush()
    var guess = Num.fromString(Stdin.readLine())
    if (n == guess) {
        System.print("Well guessed!")
        break
    }
}
Output:

Sample session:

Your guess 1-10 : 9
Your guess 1-10 : 4
Your guess 1-10 : 6
Well guessed!

X86 Assembly

Works with: NASM version Linux
 segment .data

      random  dd  0   ; Where the random number will be stored
      guess   dd  0   ; Where the user input will be stored
 
     instructions    db  10, "Welcome user! The game is simple: Guess a random number (1-10)!", 10, 10
     len1 equ $ - instructions   ; 1 \n before and 2 \n after instructions for better appearance

     wrong           db  "Not the number :(", 10
     len2 equ $ - wrong

     correct         db  "You guessed right, congratulations :D", 10
     len3 equ $ - correct

 segment .bss

 segment .text
     global  main

 main:
     push    rbp
     mov     rbp, rsp
     ; ********** CODE STARTS HERE **********

     ;;;;; Random number generator ;;;;;

     mov     eax, 13
     mov     ebx, random
     int     80h
     mov     eax, [ebx]
     mov     ebx, 10
     xor     edx, edx
     div     ebx
     inc     edx
     mov     [random], edx

     ;;;;; Print the instructions ;;;;;

     mov     eax, 4
     mov     ebx, 1
     mov     ecx, instructions
     mov     edx, len1
     int     80h

 userInput:

     ;;;;; Ask user for input ;;;;;

     mov     eax, 3
     xor     ebx, ebx
     mov     ecx, instructions
     mov     edx, 1
     int     80h
     mov     al, [ecx]
     cmp     al, 48
     jl      valCheck
     cmp     al, 57
     jg      valCheck

     ;;;;; If number ;;;;;

     sub     al, 48
     xchg    eax, [guess]
     mov     ebx, 10
     mul     ebx
     add     [guess], eax
     jmp     userInput

 valCheck:

     ;;;;; Else check number ;;;;;

     mov     eax, 4
     inc     ebx
     mov     ecx, [guess]
     cmp     ecx, [random]
     je      correctResult

     ;;;;; If not equal, "not the number :(" ;;;;;

     mov     ecx, wrong
     mov     edx, len2
     mov     DWORD [guess], 0
     int     80h
     jmp     userInput

 correctResult:

     ;;;;; If equal, "congratulations :D" ;;;;;

     mov     ecx, correct
     mov     edx, len3
     int     80h

     ;;;;; EXIT ;;;;;

     mov     rax, 0
     mov     rsp, rbp
     pop     rbp
     ret

; "Guess my number" program by Randomboi (8/8/2021)

XBS

const Range:{Min:number,Max:number} = {
	Min:number=1,
	Max:number=10,
};

while(true){
	set RandomNumber:number = math.random(Range.Min,Range.Max);
	set Response:string = window->prompt("Enter a number from "+tostring(Range.Min)+" to "+tostring(Range.Max));
	if (toint(Response)==RandomNumber){
		log("Well guessed!");
		stop;
	}
}

XLISP

(defun guessing-game ()
    (defun prompt ()
        (display "What is your guess? ")
        (define guess (read))
        (if (= guess n)
            (display "Well guessed!")
            (begin
                (display "No...")
                (newline)
                (prompt))))
    (define n (+ (random 10) 1))
    (display "I have thought of a number between 1 and 10. Try to guess it!")
    (newline)
    (prompt))
Output:
[1] (guessing-game)
I have thought of a number between 1 and 10. Try to guess it!
What is your guess? 2
No...
What is your guess? 8
No...
What is your guess? 1
No...
What is your guess? 3
No...
What is your guess? 6
No...
What is your guess? 7
No...
What is your guess? 10
Well guessed!

XPL0

code Ran=1, IntIn=10, Text=12;
int N, G;
[N:= Ran(10)+1;
Text(0, "I'm thinking of a number between 1 and 10.^M^J");
loop    [Text(0, "Can you guess it? ");
        G:= IntIn(0);
        if G=N then quit;
        Text(0, "Nope, that's not it.^M^J");
        ];
Text(0, "Well guessed!^M^J");
]

zkl

Strings are used to avoid dealing with error handling

r:=((0).random(10)+1).toString();
while(1){
   n:=ask("Num between 1 & 10: ");
   if(n==r){ println("Well guessed!"); break; } 
   println("Nope")
}

Zoomscript

For typing:

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 ne guess randnum
print "Incorrect. Try again!"
println
endif
endwhile
print "Correct number. You win!"

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 ne guess randnum¶0¶print "Incorrect. Try again!"¶0¶println¶0¶endif¶0¶endwhile¶0¶print "Correct number. You win!"