Guess the number: Difference between revisions

 
(48 intermediate revisions by 26 users not shown)
Line 22:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">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!’)</langsyntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program guessNumber.s */
Line 137:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">REPORT guess_the_number.
 
DATA prng TYPE REF TO cl_abap_random_int.
Line 165:
 
cl_demo_output=>display( |Well Done| ).
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Guess_the_number.png Screenshot from Atari 8-bit computer]
<pre>
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!
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
procedure Guess_Number is
Line 189 ⟶ 220:
end loop;
Ada.Text_IO.Put_Line ("Well guessed!");
end Guess_Number;</lang>
 
-------------------------------------------------------------------------------------------------------
-- 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;</syntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">file f;
integer n;
text s;
Line 212 ⟶ 314:
}
 
o_text("You have won!\n");</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 219 ⟶ 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].}}
{{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''.}}
<langsyntaxhighlight lang="algol68">main:
(
INT n;
Line 237 ⟶ 339:
break:
puts("You have won! ")
)</langsyntaxhighlight>
Sample output:
<pre>
Line 254 ⟶ 356:
=={{header|AppleScript}}==
 
<langsyntaxhighlight AppleScriptlang="applescript">on run
-- define the number to be guessed
set numberToGuess to (random number from 1 to 10)
Line 278 ⟶ 380:
end if
end repeat
end run</langsyntaxhighlight>
 
 
Or, constraining mutation, and abstracting a little to an '''until(predicate, function, value)''' pattern
<langsyntaxhighlight AppleScriptlang="applescript">-- GUESS THE NUMBER ----------------------------------------------------------
 
on run
Line 357 ⟶ 459:
end tell
return v
end |until|</langsyntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">n: random 1 10
 
while [notEqual? to :integer input "Guess the number: " n] [
<lang arturo>n: random 1 10
print "Guess the number: Wrong!"
]
 
print "Well guessed!"</syntaxhighlight>
loop [toNumber|strip|input ~] != n {
print "Wrong! Guess again: "
}
print "Well guessed!"</lang>
 
{{out}}
 
<pre>Guess the number: 2
Wrong!
5
Wrong! Guess againthe number: 4
Wrong!
2
Wrong! Guess againthe number: 6
Wrong!
7
Guess the number: 7
Wrong!
Guess the number: 3
Well guessed!</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="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.
 
Line 394 ⟶ 498:
Msgbox Try again.
}
</syntaxhighlight>
</lang>
 
=={{header|AutoIt}}==
<langsyntaxhighlight lang="autoit">
$irnd = Random(1, 10, 1)
$iinput = -1
Line 404 ⟶ 508:
WEnd
MsgBox(0, "Success", "Well guessed!")
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GUESS_THE_NUMBER.AWK
BEGIN {
Line 427 ⟶ 531:
exit(0)
}
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 N% = RND(1) * 10 + 1
20 PRINT "A NUMBER FROM 1 ";
30 PRINT "TO 10 HAS BEEN ";
Line 440 ⟶ 544:
70 Q = G% = N%
80 NEXT
90 PRINT "WELL GUESSED!"</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
Line 446 ⟶ 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.
 
<langsyntaxhighlight lang="commodorebasicv2">10 n% = int(rnd(1)*10)+1
20 print chr$(147);chr$(14)
30 print "I have chosen a number from 1 to 10."
Line 454 ⟶ 558:
70 q = g% = n%
80 next
90 print "WELL GUESSED!"</langsyntaxhighlight>
 
{{out}}
Line 469 ⟶ 573:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Guess.bas"
110 RANDOMIZE
120 LET N=RND(10)+1
Line 475 ⟶ 579:
140 INPUT PROMPT "Guess a number that's between 1-10: ":G
150 LOOP UNTIL N=G
160 PRINT "Well guessed!"</langsyntaxhighlight>
 
==={{header|QBasic}}, Gives Hints===
<langsyntaxhighlight lang="qbasic">supervisor:
GOSUB initialize
GOSUB guessing
Line 514 ⟶ 618:
STOP
END IF
WEND</langsyntaxhighlight>
 
==={{header|QBasic}}, More Polished Version===
A more polished version of this program in QBasic/QB/VB-DOS
<langsyntaxhighlight lang="qbasic">
' 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
Line 568 ⟶ 672:
 
END FUNCTION
</syntaxhighlight>
</lang>
 
==={{header|QB64}}===
The following is a modification of the above polished version in QBasic with explanations of differences.
<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.
 
'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</syntaxhighlight>
 
===QB64 Alternative Version, Gives Hints===
Single-line "Guess the Number" program QBasic QB64 from Russia
<syntaxhighlight lang="qbasic">
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>
The multi-line equivalent of the above.
<syntaxhighlight lang="qbasic">'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</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.
<langsyntaxhighlight 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</langsyntaxhighlight>
 
==={{header|QB64}}===
 
Single-line "Guess the Number" program QBasic QB64 from Russia
<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
</lang>
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256">n = int(rand * 10) + 1
print "I am thinking of a number from 1 to 10"
do
Line 594 ⟶ 795:
endif
until g = n
print "Yea! You guessed my number."</langsyntaxhighlight>
 
=={{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.).<langsyntaxhighlight lang="dos">@echo off
set /a answer=%random%%%(10-1+1)+1
set /p guess=Pick a number between 1 and 10:
Line 603 ⟶ 804:
if %guess%==%answer% (echo Well guessed!
pause) else (set /p guess=Nope, guess again:
goto loop)</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> choose% = RND(10)
REPEAT
INPUT "Guess a number between 1 and 10: " guess%
Line 615 ⟶ 816:
PRINT "Sorry, try again"
ENDIF
UNTIL FALSE</langsyntaxhighlight>
 
=={{header|Befunge}}==
Line 621 ⟶ 822:
{{works with|Fungus|0.28}}
{{works with|CCBI|2.1}}
<langsyntaxhighlight Befungelang="befunge">v RNG anthouse
> v ,,,,,,<
v?v ,
Line 638 ⟶ 839:
+>,,,,,,,,,,,,,,,,^
>>>>>>>>>v^"guessthenumber!"+19<
RNG unit > 22p ^</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="bracmat">( ( GuessTheNumber
= mynumber
. clk$:?mynumber
Line 653 ⟶ 854:
)
& GuessTheNumber$
);</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">number = random 10
 
p "Guess a number between 1 and 10."
Line 664 ⟶ 865:
{ p "Well guessed!"; true }
{ p "Guess again!" }
}</langsyntaxhighlight>
 
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <time.h>
Line 697 ⟶ 898:
puts("That's not my number. Try another guess:");
}
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<syntaxhighlight lang="csharp">using System;
 
==={{header|C sharp}}===
<lang csharp>using System;
 
class GuessTheNumberGame
Line 708 ⟶ 907:
static void Main()
{
boolint numberCorrectrandomNumber = falsenew Random().Next(1, 11);
Random randomNumberGenerator = new Random();
int randomNumber = randomNumberGenerator.Next(1, 10+1);
Console.WriteLine("I'm thinking of a number between 1 and 10. Can you guess it?");
dowhile(true)
{
Console.Write("Guess: ");
int userGuess =if (int.Parse(Console.ReadLine()); == randomNumber)
break;
 
if Console.WriteLine(userGuess"That's not it. ==Guess randomNumberagain.");
{}
Console.WriteLine("Congrats!! You guessed right!");
numberCorrect = true;
Console.WriteLine("Congrats!! You guessed right!");
}
else
Console.WriteLine("That's not it. Guess again.");
} while (!numberCorrect);
}
};</langsyntaxhighlight>
 
==={{header|C_sharp}}===
 
===Expanded Range, Auto-Interactive===
Single-line "Guess the Number" program C# from Russia
<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
<lang C_sharp>
{ static void Main(string[] args)
using System; using System.Text;namespace GURU { class Program { static void Main(string[] args) { Random rand = new Random(); int Russia = 0; int n = 0; int num = 0; dav: if(Russia == 0) {Russia = 2222; num = rand.Next(100)+1; goto dav; }else if (Russia != 0) {Console.Write("? "); n = Convert.ToInt32(Console.ReadLine());} if (n < num) { Console.WriteLine("MORE"); goto dav;}else if (n > num) { Console.WriteLine("less"); goto dav;}else if (n == num) {Console.Write("da"); Console.ReadKey(); }else goto dav;}}}// DANILIN Russia 9-9-2019 guessnum.cs
{ Random rand = new Random();int t=0;
</lang>
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++}}==
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cstdlib>
#include <ctime>
Line 761 ⟶ 986:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(def target (inc (rand-int 10))
 
Line 775 ⟶ 1,000:
(println "Try again")
(recur (inc n))))))
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Guess-The-Number.
 
Line 802 ⟶ 1,027:
GOBACK
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="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!"</langsyntaxhighlight>
 
{{works_with|node.js}}
 
<langsyntaxhighlight lang="coffeescript">
# This shows how to do simple REPL-like I/O in node.js.
readline = require "readline"
Line 833 ⟶ 1,058:
guess()
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="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))
Line 845 ⟶ 1,070:
(force-output)
finally (format t "Well guessed! You took ~a ~:*~[~;try~:;tries~].~%" num-guesses)))
</syntaxhighlight>
</lang>
Output:
<pre>CL-USER> (guess-the-number 10)
Line 860 ⟶ 1,085:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="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!"</langsyntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
void main() {
immutable num = uniform(1, 10).text;
Line 874 ⟶ 1,099:
 
writeln("Yep, you guessed my ", num);
}</langsyntaxhighlight>
{{out}}
<pre>What's next guess (1 - 9)? 1
Line 883 ⟶ 1,108:
=={{header|Dart}}==
{{Trans|Kotlin}}
<langsyntaxhighlight lang="dart">import 'dart:math';
import 'dart:io';
 
Line 891 ⟶ 1,116:
do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
print("\nWell guessed!");
}</langsyntaxhighlight>
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="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!"</langsyntaxhighlight>
{{out}}
<pre>$ @guess_the_number
Line 910 ⟶ 1,135:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program GuessTheNumber;
 
{$APPTYPE CONSOLE}
Line 929 ⟶ 1,154:
Writeln('Congratulations' ) ;
end.
</syntaxhighlight>
</lang>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local :number random-range 1 11
 
while true:
Line 939 ⟶ 1,164:
return
else:
!print "Nope, try again."</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
<lang>n = random 10 + 1
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!"</lang>
</syntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 980 ⟶ 1,208:
 
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).
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
RANDOMIZER
Line 1,025 ⟶ 1,253:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,041 ⟶ 1,269:
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
public program()
{
int randomNumber := randomGenerator.evalnextInt(1,10);
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
bool numberCorrect := false;
Line 1,063 ⟶ 1,291:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,077 ⟶ 1,305:
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<langsyntaxhighlight lang="elixir">defmodule GuessingGame do
def play do
play(Enum.random(1..10))
Line 1,097 ⟶ 1,325:
end
GuessingGame.play</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(let ((number (1+ (random 10))))
<lang Lisp>
(while (not (= (read-number "Guess the number ") number))
(let ((num (1+ (random 10))))
(princmessage "GuessWrong, thetry noagain.") )
(message "Well guessed! %d" number))</syntaxhighlight>
(loop
(setq guess (read))
(if (eq guess num)
(progn(princ-list "Guess was right! " num) (return)) (print "Wrong, try again.") ) ) )</lang>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(guess_the_number).
-export([main/0]).
Line 1,127 ⟶ 1,352:
guess(N)
end.
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM GUESS_NUMBER
 
Line 1,160 ⟶ 1,385:
END WHILE
END PROGRAM
</syntaxhighlight>
</lang>
Note: Adapted from Qbasic version.
 
=={{header|Euphoria}}==
{{trans|ZX_Spectrum_Basic}}
<langsyntaxhighlight Euphorialang="euphoria">include get.e
 
integer n,g
Line 1,181 ⟶ 1,406:
end while
 
puts(1,"Well done! You guessed it.")</langsyntaxhighlight>
 
=={{header|Factor}}==
 
<langsyntaxhighlight lang="factor">
USING: io random math math.parser kernel formatting ;
IN: guess-the-number
Line 1,206 ⟶ 1,431:
gen-number play-game
"Yes, the number was %d!\n" printf ;
</syntaxhighlight>
</lang>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,231 ⟶ 1,456:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">
<lang Forth>
\ tested with GForth 0.7.0
: RND ( -- n) TIME&DATE 2DROP 2DROP DROP 10 MOD ; \ crude random number
Line 1,246 ⟶ 1,471:
CR ." Yes it was " .
CR ." Good guess!" ;
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran">program guess_the_number
implicit none
 
Line 1,284 ⟶ 1,509:
 
end program guess_the_number
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Randomize
Line 1,300 ⟶ 1,525:
End
End If
Loop</langsyntaxhighlight>
 
{{out}}
Line 1,317 ⟶ 1,542:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">// Guess a Number
target = random[1,10] // Min and max are both inclusive for the random function
guess = 0
Line 1,330 ⟶ 1,555:
guess == target ? println["$guess is correct. Well guessed!"] : println["$guess is not correct. Guess again!"]
}
</syntaxhighlight>
</lang>
{{out}}
Including an example with a non-integer entered.
Line 1,342 ⟶ 1,567:
7 is correct. Well guessed!
</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}}==
<langsyntaxhighlight lang="gambas">Public Sub Form_Open()
Dim byGuess, byGos As Byte
Dim byNo As Byte = Rand(1, 10)
Line 1,358 ⟶ 1,616:
Me.Close
 
End</langsyntaxhighlight>
 
=={{header|GML}}==
<langsyntaxhighlight GMLlang="gml">var n, g;
n = irandom_range(1,10);
show_message("I'm thinking of a number from 1 to 10");
Line 1,369 ⟶ 1,627:
g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1);
}
show_message("Well guessed!");</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,394 ⟶ 1,652:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">
def random = new Random()
def keyboard = new Scanner(System.in)
Line 1,408 ⟶ 1,666:
}
println "Hurray! You guessed correctly!"
</syntaxhighlight>
</lang>
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="qbasic">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!"</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">
import Control.Monad
import System.Random
Line 1,436 ⟶ 1,694:
putStrLn "Try to guess my secret number between 1 and 10."
ask `until_` answerIs ans
</syntaxhighlight>
</lang>
 
Simple version:
 
<langsyntaxhighlight lang="haskell">
import System.Random
 
Line 1,451 ⟶ 1,709:
then putStrLn "You got it!"
else putStrLn "Nope. Guess again." >> gameloop r
</syntaxhighlight>
</lang>
 
=={{header|HolyC}}==
 
<langsyntaxhighlight lang="holyc">U8 n, *g;
 
n = 1 + RandU16 % 10;
Line 1,471 ⟶ 1,729:
 
Print("That's not my number. Try another guess:\n");
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,477 ⟶ 1,735:
This solution works in both languages.
 
<langsyntaxhighlight lang="unicon">procedure main()
n := ?10
repeat {
Line 1,484 ⟶ 1,742:
}
write("Well guessed!")
end</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">require 'misc'
game=: verb define
n=: 1 + ?10
Line 1,496 ⟶ 1,754:
smoutput (guess=n){::'no.';'Well guessed!'
end.
)</langsyntaxhighlight>
 
Example session:
 
<syntaxhighlight lang="text"> game''
Guess my integer, which is bounded by 1 and 10
Guess: 1
no.
Guess: 2
Well guessed!</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|6+}}
<langsyntaxhighlight lang="java5">public class Guessing {
public static void main(String[] args) throws NumberFormatException{
int n = (int)(Math.random() * 10 + 1);
Line 1,518 ⟶ 1,776:
System.out.println("Well guessed!");
}
}</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="javascript">
function guessNumber() {
// Get a random integer from 1 to 10 inclusive
Line 1,534 ⟶ 1,792:
}
 
guessNumber();</langsyntaxhighlight>
 
Requires a host environment that supports <code>prompt</code> and <code>alert</code> such as a browser.
Line 1,542 ⟶ 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:
<syntaxhighlight lang="jq">
<lang jq>
{prompt: "Please enter your guess:", random: (1+rand(9)) }
| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt),
"Well done!"</langsyntaxhighlight>
 
'''Invocation'''
Line 1,554 ⟶ 1,812:
 
'''PRNG'''
<langsyntaxhighlight lang="jq"># LCG::Microsoft generates 15-bit integers using the same formula
# as rand() from the Microsoft C Runtime.
# Input: [ count, state, random ]
Line 1,568 ⟶ 1,826:
 
# A random integer in [0 ... (n-1)]:
def rand(n): n * (rand_Microsoft($seed|tonumber) / 32768) | trunc;</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript entry.
<langsyntaxhighlight lang="javascript">function guessNumber() {
// Get a random integer from 1 to 10 inclusive
var num = Math.ceil(Math.random() * 10);
Line 1,605 ⟶ 1,863:
The number was 2 it took 3 tries
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,614 ⟶ 1,872:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function guess()
number = dec(rand(1:10))
print("Guess my number! ")
Line 1,623 ⟶ 1,881:
end
 
guess()</langsyntaxhighlight>
 
{{out}}
Line 1,639 ⟶ 1,897:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
fun main(args: Array<String>) {
Line 1,646 ⟶ 1,904:
do { print(" Your guess : ") } while (n != readLine())
println("\nWell guessed!")
}</langsyntaxhighlight>
Sample input/output:
{{out}}
Line 1,662 ⟶ 1,920:
 
=={{header|langur}}==
<langsyntaxhighlight lang="langur">writeln "Guess a number from 1 to 10"
 
val .n = toStringstring random 10
for {
val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, ZLS""
if .guess == ZLS"" {
writeln "too much bad data"
break
Line 1,676 ⟶ 1,934:
}
writeln "not it"
}</langsyntaxhighlight>
 
{{out}}
Line 1,694 ⟶ 1,952:
===Command Line===
The following example works when Lasso is called from a command line
<langsyntaxhighlight Lassolang="lasso">local(
number = integer_random(10, 1),
status = false,
Line 1,721 ⟶ 1,979:
}
 
}</langsyntaxhighlight>
 
===Web form===
The following example is a web page form
<langsyntaxhighlight Lassolang="lasso"><?LassoScript
 
local(
Line 1,765 ⟶ 2,023:
[/if]
</body>
</html></langsyntaxhighlight>
 
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">
(defmodule guessing-game
(export (main 0)))
Line 1,789 ⟶ 2,047:
(: random uniform 10)
(get-player-guess)))
</syntaxhighlight>
</lang>
 
From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):
<langsyntaxhighlight lang="lisp">
> (slurp '"guessing-game.lfe")
#(ok guessing-game)
Line 1,801 ⟶ 2,059:
Well-guessed!!
ok
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">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;"."</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">command guessTheNumber
local tNumber, tguess
put random(10) into tNumber
Line 1,826 ⟶ 2,084:
end if
end repeat
end guessTheNumber</langsyntaxhighlight>
 
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">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!"</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
VISIBLE "SEED ME, FEMUR! "!
Line 1,861 ⟶ 2,119:
IM OUTTA YR guesser
 
KTHXBYE</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">math.randomseed( os.time() )
n = math.random( 1, 10 )
 
Line 1,877 ⟶ 2,135:
print "Guess again: "
end
until x == n</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
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 {
supervisor:
Line 1,925 ⟶ 2,183:
}
QBASIC_Based
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
 
<langsyntaxhighlight Maplelang="maple">GuessNumber := proc()
local number;
randomize():
Line 1,938 ⟶ 2,196:
end do:
printf("Well guessed! The answer was %d.\n", number);
end proc:</langsyntaxhighlight>
<syntaxhighlight lang Maple="maple">GuessNumber();</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">number = RandomInteger[{1, 10}];
While[guess =!= number, guess = Input["Guess my number"]];
Print["Well guessed!"]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight lang="matlab">number = ceil(10*rand(1));
[guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));
 
Line 1,953 ⟶ 2,211:
[guess, status] = str2num(input('Guess again: ','s'));
end
disp('Well guessed!')</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
rand = random 1 10
clearListener()
Line 1,965 ⟶ 2,223:
format "\nChoose another value\n"
)
</syntaxhighlight>
</lang>
 
=={{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.
 
<langsyntaxhighlight Mercurylang="mercury">:- module guess.
:- interface.
:- import_module io.
Line 2,002 ⟶ 2,260:
:- pragma foreign_proc("C", time(Int::out, _IO0::di, _IO1::uo),
[will_not_call_mercury, promise_pure],
"Int = time(NULL);").</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.6}}
<syntaxhighlight lang="min">randomize
 
9 random succ
 
"Guess my number between 1 and 10." puts!
 
("Your guess" ask int over ==) 'pop ("Wrong." puts!) () linrec
 
"Well guessed!" puts!</syntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">num = ceil(rnd*10)
while true
x = val(input("Your guess?"))
Line 2,012 ⟶ 2,282:
break
end if
end while</langsyntaxhighlight>
 
=={{header|MIPS Assembly}}==
<langsyntaxhighlight lang="mips">
# WRITTEN: August 26, 2016 (at midnight...)
 
Line 2,072 ⟶ 2,342:
syscall
jr $ra
</syntaxhighlight>
</lang>
 
=={{header|Nanoquery}}==
{{trans|Ursa}}
<langsyntaxhighlight Nanoquerylang="nanoquery">random = new(Nanoquery.Util.Random)
target = random.getInt(9) + 1
guess = 0
Line 2,085 ⟶ 2,355:
end
 
println "That's right!"</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 2,107 ⟶ 2,377:
WriteLine("Well guessed!");
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 2,133 ⟶ 2,403:
 
return
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">; guess-number.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number
Line 2,148 ⟶ 2,418:
(println "Well guessed! Congratulations!")
 
(exit)</langsyntaxhighlight>
 
Sample output:
Line 2,161 ⟶ 2,431:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strutils, random
<lang nim>
import strutils, math
 
randomize()
var chosen = 1 + randomrand(1..10)
echo "I have thought of a number. Try to guess it!"
 
var guess = parseInt(readLine(stdin))
 
Line 2,173 ⟶ 2,442:
echo "Your guess was wrong. Try again!"
guess = parseInt(readLine(stdin))
 
echo "Well guessed!"</syntaxhighlight>
</lang>
 
=={{header|NS-HUBASIC}}==
<langsyntaxhighlight NSlang="ns-HUBASIChubasic">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."</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
Works with oo2c Version 2
<langsyntaxhighlight lang="oberon2">
MODULE GuessTheNumber;
IMPORT
Line 2,210 ⟶ 2,478:
Do;
END GuessTheNumber.
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use IO;
 
Line 2,243 ⟶ 2,511:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
 
<langsyntaxhighlight lang="objc">
#import <Foundation/Foundation.h>
 
Line 2,287 ⟶ 2,555:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#!/usr/bin/env ocaml
 
let () =
Line 2,307 ⟶ 2,575:
print_endline "The guess was wrong! Please try again!"
done;
print_endline "Well guessed!"</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">import: console
 
: guess
10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ]
drop "Well guessed!" . ;</langsyntaxhighlight>
 
=={{header|Ol}}==
<syntaxhighlight lang="ol">
<lang ol>
(import (otus random!))
 
Line 2,327 ⟶ 2,595:
(print "Well guessed!")
(loop)))
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">guess()=my(r=random(10)+1);while(input()!=r,); "Well guessed!";</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program GuessTheNumber(input, output);
 
var
Line 2,352 ⟶ 2,620:
writeln ('You made an excellent guess. Thank you and have a nice day.');
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my $number = 1 + int rand 10;
do { print "Guess a number between 1 and 10: " } until <> == $number;
print "You got it!\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>integer secret = rand(10)
<span style="color: #000080;font-style:italic;">--
puts(1,"Guess the number between 1 and 10: ")
-- demo\rosetta\Guess_the_number.exw
while 1 do
--</span>
if prompt_number("",{1,10})=secret then exit end if
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
puts(1,"Your guess was wrong.\nTry again: ")
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
end while
puts(1,"You got it!\n")</lang>
<span style="color: #004080;">integer</span> <span style="color: #000000;">secret</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">guess</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">secret</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">lbl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetBrother</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lbl</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Your guess was correct"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRefresh</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lbl</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">lbl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Your guess"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"RASTERSIZE=58x21"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">guess</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">"RASTERSIZE=21x21"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">(),</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">lbl</span><span style="color: #0000FF;">,</span><span style="color: #000000;">guess</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">()},</span>
<span style="color: #008000;">"GAP=10"</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">()}),</span>
<span style="color: #008000;">`MINSIZE=300x100,TITLE="Guess the number"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lbl</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"x21"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
<?php
 
Line 2,417 ⟶ 2,718:
</body>
</html>
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
N = random(1,10),
do print("Guess a number: ")
while (read_int() != N),
println("Well guessed!").</syntaxhighlight>
 
{{trans|Prolog}}
<syntaxhighlight lang="picat">go2 =>
N = random(1, 10),
repeat,
print('Guess the number: '),
N = read_int(),
println("Well guessed!"),
!.</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de guessTheNumber ()
(let Number (rand 1 9)
(loop
Line 2,426 ⟶ 2,743:
(T (= Number (read))
(prinl "Well guessed!") )
(prinl "Sorry, this was wrong") ) ) )</langsyntaxhighlight>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">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.</syntaxhighlight>
 
=={{header|PlainTeX}}==
This code should be compiled with etex features in console mode (for example "pdftex <name of the file>"):
<langsyntaxhighlight lang="tex">\newlinechar`\^^J
\edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}%
\message{^^JI'm thinking of a number between 1 and 10, try to guess it!}%
Line 2,444 ⟶ 2,778:
\ifnotguessed
\repeat
\bye</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight PowerShelllang="powershell">Function GuessNumber($Guess)
{
$Number = Get-Random -min 1 -max 11
Line 2,459 ⟶ 2,793:
While ($Number -ne $Guess)
Write-Host "Well done! You successfully guessed the number $Guess."
}</langsyntaxhighlight>
<langsyntaxhighlight lang="powershell">$myNumber = Read-Host "What's the number?"
GuessNumber $myNumber</langsyntaxhighlight>
 
=={{header|ProDOS}}==
Uses math module:
<syntaxhighlight lang="prodos">:a
<lang ProDOS>: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</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
 
<langsyntaxhighlight lang="prolog">main :-
random_between(1, 10, N),
repeat,
Line 2,480 ⟶ 2,814:
read(N),
writeln('Well guessed!'),
!.</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="prolog">?- main.
Guess the number: 1.
Guess the number: 2.
Guess the number: 3.
Well guessed!
true.</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define TheNumber=Random(9)+1
Line 2,504 ⟶ 2,838:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="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!")</langsyntaxhighlight>
 
===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}}==
''CBTJD'': 2020/04/13
<langsyntaxhighlight lang="qbasic">START:
CLS
RANDOMIZE TIMER
Line 2,525 ⟶ 2,898:
LOOP UNTIL n = num
INPUT "Well guessed! Go again"; a$
IF LEFT$(LCASE$(a$), 1) = "y" THEN GOTO START</langsyntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="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!'</syntaxhighlight>
A sample output of exceptionally bad guessing:
{{out}}
<pre>
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!
</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">f <- function() {
print("Guess a number between 1 and 10 until you get it right.")
n <- sample(10, 1)
Line 2,535 ⟶ 2,979:
}
print("You got it!")
}</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (guess-number)
(define number (add1 (random 10)))
Line 2,545 ⟶ 2,989:
(if (equal? guess number)
(display "Well guessed!\n")
(loop))))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>my $number = (1..10).pick;
repeat {} until prompt("Guess a number: ") == $number;
say "Guessed right!";</langsyntaxhighlight>
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
RANDOMIZE
number = rnd(10) + 1
Line 2,565 ⟶ 3,009:
print "You guessed right, well done !"
input "Press enter to quit";a$
</syntaxhighlight>
</lang>
 
=={{header|Rascal}}==
<langsyntaxhighlight Rascallang="rascal">import vis::Render;
import vis::Figure;
import util::Math;
Line 2,582 ⟶ 3,026:
button("Start over", void(){random = arbInt(10);}) ]));
render(figure);
}</langsyntaxhighlight>
 
Output:
Line 2,589 ⟶ 3,033:
 
=={{header|Red}}==
<langsyntaxhighlight lang="red">
Red []
#include %environment/console/CLI/input.red
Line 2,599 ⟶ 3,043:
]
print "Well guessed!"
</syntaxhighlight>
</lang>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">: checkGuess ( gn-gf || f )
over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;
 
Line 2,613 ⟶ 3,057:
think [ getToken toNumber checkGuess ] while
"You got it!\n" puts ;
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
===version 1===
<small>(Note: most REXXes won't accept that first statement, the shebang/sha-bang/hashbang/pound-bang/hash-exclam/hash-pling.)</small>
<langsyntaxhighlight lang="rexx">#!/usr/bin/rexx
/*REXX program to play: Guess the number */
 
Line 2,634 ⟶ 3,078:
 
say "Well done! You guessed it!"
</syntaxhighlight>
</lang>
 
===version 2===
<langsyntaxhighlight 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. */
say 'Try to guess my number between 1 ──► 10 (inclusive).' /*the directive to be used.*/
 
do j=1 until g=? /*keep atprompting it'til ···done.*/
if j\==1 then say 'Try again.' /*issue secondary prompt. /*2nd-ary prompt*/
pull g /*obtain a guess from user.*/
end /*j*/
say 'Well guessed!' /*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
=={{header|Ring}}==
 
<langsyntaxhighlight lang="ring">
 
### Bert Mariani
Line 2,675 ⟶ 3,119:
end
 
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
 
<syntaxhighlight lang="userrpl">
<lang UserRPL>
DIR
INITIALIZE
Line 2,710 ⟶ 3,154:
END
>>
END</langsyntaxhighlight>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">
n = rand(1..10)
puts 'Guess the number: '
puts 'Wrong! Guess again: ' until gets.to_i == n
puts 'Well guessed!'
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">while 1
choose = int(RND(0) * 9) + 1
while guess <> choose
Line 2,731 ⟶ 3,175:
end if
wend
wend</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand;
 
fn main() {
Line 2,759 ⟶ 3,203:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
 
<langsyntaxhighlight lang="scala">
val n = (math.random * 10 + 1).toInt
print("Guess the number: ")
while(readInt != n) print("Wrong! Guess again: ")
println("Well guessed!")
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
{{works with|Guile}}
<langsyntaxhighlight lang="scheme">(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")))</langsyntaxhighlight>
{{Out}}
<pre>scheme> (guess)
Line 2,794 ⟶ 3,238:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,811 ⟶ 3,255:
end while;
writeln("You have won!");
end func;</langsyntaxhighlight>
 
=={{header|Self}}==
Line 2,819 ⟶ 3,263:
Well factored:
 
<langsyntaxhighlight lang="self">(|
parent* = traits clonable.
copy = (resend.copy secretNumber: random integerBetween: 1 And: 10).
Line 2,831 ⟶ 3,275:
hasGuessed = ( [ask = secretNumber] onReturn: [|:r| r ifTrue: [reportSuccess] False: [reportFailure]] ).
run = (sayIntroduction. [hasGuessed] whileFalse)
|) copy run</langsyntaxhighlight>
 
Simple method:
 
<langsyntaxhighlight lang="self">| 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!'</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var n = pickirand(1.., 10)
printvar msg = 'Guess the number: '
while (n != read(msg, Number).int) {
printmsg = 'Wrong! Guess again: '
}
say 'Well guessed!'</langsyntaxhighlight>
 
=={{header|Small Basic}}==
<langsyntaxhighlight Smalllang="small Basicbasic">number=Math.GetRandomNumber(10)
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
Line 2,857 ⟶ 3,301:
TextWindow.WriteLine("Guess again! ")
EndWhile
TextWindow.WriteLine("You win!")</langsyntaxhighlight>
 
=={{header|SNUSP}}==
Line 2,895 ⟶ 3,339:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Cocoa
 
var found = false
Line 2,911 ⟶ 3,355:
println("Well guessed!")
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set target [expr {int(rand()*10 + 1)}]
puts "I have thought of a number."
puts "Try to guess it!"
Line 2,926 ⟶ 3,370:
puts "Your guess was wrong. Try again!"
}
puts "Well done! You guessed it."</langsyntaxhighlight>
Sample output:
<pre>
Line 2,942 ⟶ 3,386:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
Line 2,961 ⟶ 3,405:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,977 ⟶ 3,421:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">#!/bin/sh
# Guess the number
# This simplified program does not check the input is valid
Line 2,990 ⟶ 3,434:
echo 'Sorry, the guess was wrong! Try again!'
done
echo 'Well done! You guessed it.'</langsyntaxhighlight>
 
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 2,996 ⟶ 3,440:
==={{header|C Shell}}===
{{libheader|jot}}
<langsyntaxhighlight lang="csh">#!/bin/csh -f
# Guess the number
 
Line 3,009 ⟶ 3,453:
@ guess = "$<"
end
echo 'Well done! You guessed it.'</langsyntaxhighlight>
 
=={{header|Ursa}}==
{{trans|Python}}
<langsyntaxhighlight lang="ursa"># Simple number guessing game
 
decl ursa.util.random random
Line 3,024 ⟶ 3,468:
end while
 
out "That's right!" endl console</langsyntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">int main() {
int x = Random.int_range(1, 10);
stdout.printf("Make a guess (1-10): ");
Line 3,034 ⟶ 3,478:
stdout.printf("Got it!\n");
return 0;
}</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight VBlang="vb">Sub GuessTheNumber()
Dim NbComputer As Integer, NbPlayer As Integer
Randomize Timer
Line 3,045 ⟶ 3,489:
Loop While NbComputer <> NbPlayer
MsgBox "Well guessed!"
End Sub</langsyntaxhighlight>
 
=={{header|VBScript}}==
<langsyntaxhighlight VBScriptlang="vbscript">randomize
MyNum=Int(rnd*10)+1
Do
Line 3,068 ⟶ 3,512:
wscript.quit
end if
loop</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Module Guess_the_Number
Sub Main()
Dim random As New Random()
Line 3,094 ⟶ 3,538:
Loop Until gameOver
End Sub
End Module</langsyntaxhighlight>
{{Out}}
<pre>I am thinking of a number from 1 to 10. Can you guess it?
Line 3,108 ⟶ 3,552:
Well guessed!</pre>
 
=={{header|V (Vlang)}}==
<langsyntaxhighlight vlanglang="go">import rand
import timerand.seed
import os
 
fn main() {
tseed_array := timeseed.nowtime_seed_array(2)
rand.seed(seed_array)
s := t.calc_unix()
num := rand.seedintn(s10) + 1 // Random number 1-10
for {
num := rand.next(10) // Random number
print('Please guess a number from 1-10 and press <Enter>: ')
// Game loop
forguess {:= os.get_line()
if guess.int() == num {
println('Please guess a number from 1-10 and press <Enter>')
println("Well guessed! '$guess' :=is oscorrect.get_line(")
if guess.int() == num {return
} else {
println('Well guessed!')
println("'$guess' is Incorrect. Try returnagain.")
}
else {
print('Incorrect! ')
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
<pre>Please guess a number from 1-10 and press <Enter>: 1
'1' is Incorrect. Try again.
2
Incorrect! Please guess a number from 1-10 and press <Enter>: 2
'2' is Incorrect. Try again.
1
Incorrect! Please guess a number from 1-10 and press <Enter>: 9
'9' is Incorrect. Try again.
9
Incorrect! Please guess a number from 1-10 and press <Enter>: 10
'10' is Incorrect. Try again.
8
Please guess a number from 1-10 and press <Enter>: 3
Well guessed!
Well guessed! '3' is correct.
</pre>
 
=={{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].
<syntaxhighlight lang="webassembly">(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
)
)</syntaxhighlight>
 
=={{header|Wee Basic}}==
Due to how the code works, any key has to be entered to generate the random number.
<langsyntaxhighlight Weelang="wee Basicbasic">let mnnumber=1
let mxnumber=10
let number=mnnumber
Line 3,168 ⟶ 3,741:
endif
wend
end</langsyntaxhighlight>
 
=={{header|Wortel}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="wortel">@let {
num 10Wc
guess 0
Line 3,180 ⟶ 3,753:
!alert "Congratulations!\nThe number was {num}."
]
}</langsyntaxhighlight>
 
=={{header|Wren}}==
<syntaxhighlight lang="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
}
}</syntaxhighlight>
 
{{out}}
Sample session:
<pre>
Your guess 1-10 : 9
Your guess 1-10 : 4
Your guess 1-10 : 6
Well guessed!
</pre>
 
=={{header|X86 Assembly}}==
{{works with|NASM|Linux}}
<syntaxhighlight lang ="asm">global _start
 
section segment .data
 
random dd 0 ; Where the random number will be stored
rand dd 0
guess dd 0 ; Where the user input will be stored
msg1 db "Guess my number (1-10)", 10
instructions db 10, "Welcome user! The game is simple: Guess a random number (1-10)!", 10, 10
len1 equ $ - msg1
len1 equ $ - instructions ; 1 \n before and 2 \n after instructions for better appearance
msg2 db "Wrong, try again!", 10
len2 equ $ - msg2
msg3 db "Well guessed!", 10
len3 equ $ - msg3
 
wrong db "Not the number :(", 10
section .text
len2 equ $ - wrong
 
correct db "You guessed right, congratulations :D", 10
_start:
len3 equ $ ;- random number using timecorrect
 
mov eax, 13
segment .bss
mov ebx, rand
 
int 80h
segment .text
mov eax, [ebx]
global mov ebx, 10main
 
xor edx, edx
main:
div ebx
push inc edxrbp
mov mov [rand]rbp, edxrsp
; ********** CODE STARTS HERE **********
 
; print msg1
;;;;; Random number movgenerator eax, 4;;;;;
 
mov ebx, 1
mov mov ecxeax, msg113
mov mov edxebx, len1random
int int 80h
mov eax, [ebx]
mov ebx, 10
input:
xor ; get inputedx, edx
div mov eax, 3ebx
inc xor ebx, ebxedx
mov mov ecx[random], msg1edx
 
mov edx, 1
;;;;; Print the intinstructions 80h;;;;;
 
mov al, [ecx]
mov cmp al eax, 484
mov jl check ebx, 1
mov cmp al ecx, 57instructions
mov jg check edx, len1
int ; if number80h
 
sub al, 48
userInput:
xchg eax, [guess]
 
mov ebx, 10
;;;;; Ask user mulfor ebxinput ;;;;;
 
add [guess], eax
mov jmp input eax, 3
xor ebx, ebx
mov ecx, instructions
check:
mov ; else checkedx, number1
int mov eax, 480h
mov inc ebx al, [ecx]
cmp mov ecx al, [guess]48
jl cmp ecx, [rand] valCheck
cmp je done al, 57
jg ; if not equalvalCheck
 
mov ecx, msg2
;;;;; If number mov edx, len2;;;;;
 
mov dword [guess], 0
sub int 80h al, 48
xchg jmp inputeax, [guess]
mov ebx, 10
done: mul ebx
add ; well guessed[guess], eax
jmp mov ecx, msg3userInput
 
mov edx, len3
valCheck:
int 80h
 
; exit
;;;;; Else check movnumber eax, 1;;;;;
 
xor ebx, ebx
mov int 80h</lang> 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)
</syntaxhighlight>
 
=={{header|XBS}}==
<syntaxhighlight lang="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;
}
}</syntaxhighlight>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(defun guessing-game ()
(defun prompt ()
(display "What is your guess? ")
Line 3,276 ⟶ 3,917:
(display "I have thought of a number between 1 and 10. Try to guess it!")
(newline)
(prompt))</langsyntaxhighlight>
{{out}}
<pre>[1] (guessing-game)
Line 3,296 ⟶ 3,937:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Ran=1, IntIn=10, Text=12;
int N, G;
[N:= Ran(10)+1;
Line 3,306 ⟶ 3,947:
];
Text(0, "Well guessed!^M^J");
]</langsyntaxhighlight>
 
=={{header|zkl}}==
Strings are used to avoid dealing with error handling
<langsyntaxhighlight lang="zkl">r:=((0).random(10)+1).toString();
while(1){
n:=ask("Num between 1 & 10: ");
if(n==r){ println("Well guessed!"); break; }
println("Nope")
}</langsyntaxhighlight>
 
=={{header|Zoomscript}}==
For typing:
<langsyntaxhighlight Zoomscriptlang="zoomscript">var randnum
var guess
randnum & random 1 10
Line 3,331 ⟶ 3,972:
endif
endwhile
print "Correct number. You win!"</langsyntaxhighlight>
 
For importing:
885

edits