Guess the number: Difference between revisions
→{{header|langur}}
Langurmonkey (talk | contribs) |
|||
(48 intermediate revisions by 26 users not shown) | |||
Line 22:
=={{header|11l}}==
{{trans|Python}}
<
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!’)</
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight 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>
=={{header|ABAP}}==
<
DATA prng TYPE REF TO cl_abap_random_int.
Line 165:
cl_demo_output=>display( |Well Done| ).
</syntaxhighlight>
=={{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}}==
<
with Ada.Text_IO;
procedure Guess_Number is
Line 189 ⟶ 220:
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;</syntaxhighlight>
=={{header|Aime}}==
<
integer n;
text s;
Line 212 ⟶ 314:
}
o_text("You have won!\n");</
=={{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''.}}
<
(
INT n;
Line 237 ⟶ 339:
break:
puts("You have won! ")
)</
Sample output:
<pre>
Line 254 ⟶ 356:
=={{header|AppleScript}}==
<
-- define the number to be guessed
set numberToGuess to (random number from 1 to 10)
Line 278 ⟶ 380:
end if
end repeat
end run</
Or, constraining mutation, and abstracting a little to an '''until(predicate, function, value)''' pattern
<
on run
Line 357 ⟶ 459:
end tell
return v
end |until|</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">n: random 1 10
while [notEqual? to :integer input "Guess the number: " n] [
print "
]
print "Well guessed!"</syntaxhighlight>
{{out}}
<pre>Guess the number: 2
Wrong!
Wrong!
Wrong!
Guess the number: 7
Wrong!
Guess the number: 3
Well guessed!</pre>
=={{header|AutoHotkey}}==
<
msgbox I am thinking of a number between 1 and 10.
Line 394 ⟶ 498:
Msgbox Try again.
}
</syntaxhighlight>
=={{header|AutoIt}}==
<
$irnd = Random(1, 10, 1)
$iinput = -1
Line 404 ⟶ 508:
WEnd
MsgBox(0, "Success", "Well guessed!")
</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f GUESS_THE_NUMBER.AWK
BEGIN {
Line 427 ⟶ 531:
exit(0)
}
</syntaxhighlight>
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<
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!"</
==={{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.
<
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!"</
{{out}}
Line 469 ⟶ 573:
==={{header|IS-BASIC}}===
<
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!"</
==={{header|QBasic}}, Gives Hints===
<
GOSUB initialize
GOSUB guessing
Line 514 ⟶ 618:
STOP
END IF
WEND</
===
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
Line 568 ⟶ 672:
END FUNCTION
</syntaxhighlight>
==={{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.
<
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</
=={{header|BASIC256}}==
<
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."</
=={{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.).<
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)</
=={{header|BBC BASIC}}==
<
REPEAT
INPUT "Guess a number between 1 and 10: " guess%
Line 615 ⟶ 816:
PRINT "Sorry, try again"
ENDIF
UNTIL FALSE</
=={{header|Befunge}}==
Line 621 ⟶ 822:
{{works with|Fungus|0.28}}
{{works with|CCBI|2.1}}
<
> v ,,,,,,<
v?v ,
Line 638 ⟶ 839:
+>,,,,,,,,,,,,,,,,^
>>>>>>>>>v^"guessthenumber!"+19<
RNG unit > 22p ^</
=={{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.
<
= mynumber
. clk$:?mynumber
Line 653 ⟶ 854:
)
& GuessTheNumber$
);</
=={{header|Brat}}==
<
p "Guess a number between 1 and 10."
Line 664 ⟶ 865:
{ p "Well guessed!"; true }
{ p "Guess again!" }
}</
=={{header|C}}==
<
#include <stdio.h>
#include <time.h>
Line 697 ⟶ 898:
puts("That's not my number. Try another guess:");
}
}</
=={{header|C sharp}}==
<syntaxhighlight lang="csharp">using System;
class GuessTheNumberGame
Line 708 ⟶ 907:
static void Main()
{
Console.WriteLine("I'm thinking of a number between 1 and 10.
{
Console.Write("Guess: ");
break;
Console.WriteLine("Congrats!! You guessed right!");
}
};</
===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++}}==
<
#include <cstdlib>
#include <ctime>
Line 761 ⟶ 986:
}
</syntaxhighlight>
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(def target (inc (rand-int 10))
Line 775 ⟶ 1,000:
(println "Try again")
(recur (inc n))))))
</syntaxhighlight>
=={{header|COBOL}}==
<
PROGRAM-ID. Guess-The-Number.
Line 802 ⟶ 1,027:
GOBACK
.</
=={{header|CoffeeScript}}==
<
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"
Line 833 ⟶ 1,058:
guess()
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(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>
Output:
<pre>CL-USER> (guess-the-number 10)
Line 860 ⟶ 1,085:
=={{header|Crystal}}==
{{trans|Ruby}}
<
puts "Guess the number: 1..10"
until gets.to_s.to_i == n; puts "Wrong! Guess again: " end
puts "Well guessed!"</
=={{header|D}}==
<syntaxhighlight lang="d">
void main() {
immutable num = uniform(1, 10).text;
Line 874 ⟶ 1,099:
writeln("Yep, you guessed my ", num);
}</
{{out}}
<pre>What's next guess (1 - 9)? 1
Line 883 ⟶ 1,108:
=={{header|Dart}}==
{{Trans|Kotlin}}
<
import 'dart:io';
Line 891 ⟶ 1,116:
do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
print("\nWell guessed!");
}</
=={{header|DCL}}==
<
$ 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!"</
{{out}}
<pre>$ @guess_the_number
Line 910 ⟶ 1,135:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 929 ⟶ 1,154:
Writeln('Congratulations' ) ;
end.
</syntaxhighlight>
=={{header|Déjà Vu}}==
<
while true:
Line 939 ⟶ 1,164:
return
else:
!print "Nope, try again."</
=={{header|EasyLang}}==
<syntaxhighlight>
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!"
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 980 ⟶ 1,208:
end
</syntaxhighlight>
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">
class
RANDOMIZER
Line 1,025 ⟶ 1,253:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,041 ⟶ 1,269:
=={{header|Elena}}==
ELENA
<
public program()
{
int randomNumber := randomGenerator.
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
bool numberCorrect := false;
Line 1,063 ⟶ 1,291:
}
}
}</
{{out}}
<pre>
Line 1,077 ⟶ 1,305:
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<
def play do
play(Enum.random(1..10))
Line 1,097 ⟶ 1,325:
end
GuessingGame.play</
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(let ((number (1+ (random 10))))
(while (not (= (read-number "Guess the number ") number))
(
(message "Well guessed! %d" number))</syntaxhighlight>
=={{header|Erlang}}==
<
-module(guess_the_number).
-export([main/0]).
Line 1,127 ⟶ 1,352:
guess(N)
end.
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM GUESS_NUMBER
Line 1,160 ⟶ 1,385:
END WHILE
END PROGRAM
</syntaxhighlight>
Note: Adapted from Qbasic version.
=={{header|Euphoria}}==
{{trans|ZX_Spectrum_Basic}}
<
integer n,g
Line 1,181 ⟶ 1,406:
end while
puts(1,"Well done! You guessed it.")</
=={{header|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>
=={{header|Fantom}}==
<
class Main
{
Line 1,231 ⟶ 1,456:
}
}
</syntaxhighlight>
=={{header|Forth}}==
<syntaxhighlight 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>
=={{header|Fortran}}==
<
implicit none
Line 1,284 ⟶ 1,509:
end program guess_the_number
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Randomize
Line 1,300 ⟶ 1,525:
End
End If
Loop</
{{out}}
Line 1,317 ⟶ 1,542:
=={{header|Frink}}==
<
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>
{{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}}==
<
Dim byGuess, byGos As Byte
Dim byNo As Byte = Rand(1, 10)
Line 1,358 ⟶ 1,616:
Me.Close
End</
=={{header|GML}}==
<
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!");</
=={{header|Go}}==
<
import (
Line 1,394 ⟶ 1,652:
}
}
}</
=={{header|Groovy}}==
<
def random = new Random()
def keyboard = new Scanner(System.in)
Line 1,408 ⟶ 1,666:
}
println "Hurray! You guessed correctly!"
</syntaxhighlight>
=={{header|GW-BASIC}}==
<
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!"</
=={{header|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>
Simple version:
<
import System.Random
Line 1,451 ⟶ 1,709:
then putStrLn "You got it!"
else putStrLn "Nope. Guess again." >> gameloop r
</syntaxhighlight>
=={{header|HolyC}}==
<
n = 1 + RandU16 % 10;
Line 1,471 ⟶ 1,729:
Print("That's not my number. Try another guess:\n");
}</
=={{header|Icon}} and {{header|Unicon}}==
Line 1,477 ⟶ 1,735:
This solution works in both languages.
<
n := ?10
repeat {
Line 1,484 ⟶ 1,742:
}
write("Well guessed!")
end</
=={{header|J}}==
<
game=: verb define
n=: 1 + ?10
Line 1,496 ⟶ 1,754:
smoutput (guess=n){::'no.';'Well guessed!'
end.
)</
Example session:
<syntaxhighlight lang="text"> game''
Guess my integer, which is bounded by 1 and 10
Guess: 1
no.
Guess: 2
Well guessed!</
=={{header|Java}}==
{{works with|Java|6+}}
<
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!");
}
}</
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}}==
<
function guessNumber() {
// Get a random integer from 1 to 10 inclusive
Line 1,534 ⟶ 1,792:
}
guessNumber();</
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">
{prompt: "Please enter your guess:", random: (1+rand(9)) }
| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt),
"Well done!"</
'''Invocation'''
Line 1,554 ⟶ 1,812:
'''PRNG'''
<
# 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;</
=={{header|Jsish}}==
From Javascript entry.
<
// 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!=
*/</
{{out}}
Line 1,614 ⟶ 1,872:
{{works with|Julia|0.6}}
<
number = dec(rand(1:10))
print("Guess my number! ")
Line 1,623 ⟶ 1,881:
end
guess()</
{{out}}
Line 1,639 ⟶ 1,897:
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,646 ⟶ 1,904:
do { print(" Your guess : ") } while (n != readLine())
println("\nWell guessed!")
}</
Sample input/output:
{{out}}
Line 1,662 ⟶ 1,920:
=={{header|langur}}==
<
val .n =
for {
val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7,
if .guess ==
writeln "too much bad data"
break
Line 1,676 ⟶ 1,934:
}
writeln "not it"
}</
{{out}}
Line 1,694 ⟶ 1,952:
===Command Line===
The following example works when Lasso is called from a command line
<
number = integer_random(10, 1),
status = false,
Line 1,721 ⟶ 1,979:
}
}</
===Web form===
The following example is a web page form
<
local(
Line 1,765 ⟶ 2,023:
[/if]
</body>
</html></
=={{header|LFE}}==
<
(defmodule guessing-game
(export (main 0)))
Line 1,789 ⟶ 2,047:
(: random uniform 10)
(get-player-guess)))
</syntaxhighlight>
From the LFE REPL (assuming the above code was saved in the file "guessing-game.lfe"):
<
> (slurp '"guessing-game.lfe")
#(ok guessing-game)
Line 1,801 ⟶ 2,059:
Well-guessed!!
ok
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<
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;"."</
=={{header|LiveCode}}==
<
local tNumber, tguess
put random(10) into tNumber
Line 1,826 ⟶ 2,084:
end if
end repeat
end guessTheNumber</
=={{header|Locomotive Basic}}==
<
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!"</
=={{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.
<
VISIBLE "SEED ME, FEMUR! "!
Line 1,861 ⟶ 2,119:
IM OUTTA YR guesser
KTHXBYE</
=={{header|Lua}}==
<
n = math.random( 1, 10 )
Line 1,877 ⟶ 2,135:
print "Guess again: "
end
until x == n</
=={{header|M2000 Interpreter}}==
A copy from QBASIC, write blocks { } where needed, We use GOSUB and GOTO in a Module.
<syntaxhighlight lang="m2000 interpreter">
Module QBASIC_Based {
supervisor:
Line 1,925 ⟶ 2,183:
}
QBASIC_Based
</syntaxhighlight>
=={{header|Maple}}==
<
local number;
randomize():
Line 1,938 ⟶ 2,196:
end do:
printf("Well guessed! The answer was %d.\n", number);
end proc:</
<syntaxhighlight lang
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
While[guess =!= number, guess = Input["Guess my number"]];
Print["Well guessed!"]</
=={{header|MATLAB}}==
<
[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!')</
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
rand = random 1 10
clearListener()
Line 1,965 ⟶ 2,223:
format "\nChoose another value\n"
)
</syntaxhighlight>
=={{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.
<
:- 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);").</
=={{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}}==
<
while true
x = val(input("Your guess?"))
Line 2,012 ⟶ 2,282:
break
end if
end while</
=={{header|MIPS Assembly}}==
<
# WRITTEN: August 26, 2016 (at midnight...)
Line 2,072 ⟶ 2,342:
syscall
jr $ra
</syntaxhighlight>
=={{header|Nanoquery}}==
{{trans|Ursa}}
<
target = random.getInt(9) + 1
guess = 0
Line 2,085 ⟶ 2,355:
end
println "That's right!"</
=={{header|Nemerle}}==
<
using System.Console;
Line 2,107 ⟶ 2,377:
WriteLine("Well guessed!");
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,133 ⟶ 2,403:
return
</syntaxhighlight>
=={{header|NewLISP}}==
<
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number
Line 2,148 ⟶ 2,418:
(println "Well guessed! Congratulations!")
(exit)</
Sample output:
Line 2,161 ⟶ 2,431:
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strutils, random
randomize()
var chosen =
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>
=={{header|NS-HUBASIC}}==
<
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."</
=={{header|Oberon-2}}==
Works with oo2c Version 2
<
MODULE GuessTheNumber;
IMPORT
Line 2,210 ⟶ 2,478:
Do;
END GuessTheNumber.
</syntaxhighlight>
=={{header|Objeck}}==
<
use IO;
Line 2,243 ⟶ 2,511:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<
#import <Foundation/Foundation.h>
Line 2,287 ⟶ 2,555:
return 0;
}
</syntaxhighlight>
=={{header|OCaml}}==
<
let () =
Line 2,307 ⟶ 2,575:
print_endline "The guess was wrong! Please try again!"
done;
print_endline "Well guessed!"</
=={{header|Oforth}}==
<
: guess
10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ]
drop "Well guessed!" . ;</
=={{header|Ol}}==
<syntaxhighlight lang="ol">
(import (otus random!))
Line 2,327 ⟶ 2,595:
(print "Well guessed!")
(loop)))
</syntaxhighlight>
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
<
var
Line 2,352 ⟶ 2,620:
writeln ('You made an excellent guess. Thank you and have a nice day.');
end.
</syntaxhighlight>
=={{header|Perl}}==
<
do { print "Guess a number between 1 and 10: " } until <> == $number;
print "You got it!\n";</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Guess_the_number.exw
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #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}}==
<
<?php
Line 2,417 ⟶ 2,718:
</body>
</html>
</syntaxhighlight>
=={{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}}==
<
(let Number (rand 1 9)
(loop
Line 2,426 ⟶ 2,743:
(T (= Number (read))
(prinl "Well guessed!") )
(prinl "Sorry, this was wrong") ) ) )</
=={{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>"):
<
\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</
=={{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.
<
{
$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."
}</
<
GuessNumber $myNumber</
=={{header|ProDOS}}==
Uses math module:
<syntaxhighlight 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</
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
<
random_between(1, 10, N),
repeat,
Line 2,480 ⟶ 2,814:
read(N),
writeln('Well guessed!'),
!.</
Example:
<
Guess the number: 1.
Guess the number: 2.
Guess the number: 3.
Well guessed!
true.</
=={{header|PureBasic}}==
<
Define TheNumber=Random(9)+1
Line 2,504 ⟶ 2,838:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
=={{header|Python}}==
<
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===
<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
<
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</
=={{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}}==
<
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!")
}</
=={{header|Racket}}==
<
(define (guess-number)
(define number (add1 (random 10)))
Line 2,545 ⟶ 2,989:
(if (equal? guess number)
(display "Well guessed!\n")
(loop))))</
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
repeat {} until prompt("Guess a number: ") == $number;
say "Guessed right!";</
=={{header|RapidQ}}==
<syntaxhighlight 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>
=={{header|Rascal}}==
<
import vis::Figure;
import util::Math;
Line 2,582 ⟶ 3,026:
button("Start over", void(){random = arbInt(10);}) ]));
render(figure);
}</
Output:
Line 2,589 ⟶ 3,033:
=={{header|Red}}==
<
Red []
#include %environment/console/CLI/input.red
Line 2,599 ⟶ 3,043:
]
print "Well guessed!"
</syntaxhighlight>
=={{header|Retro}}==
<
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>
=={{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>
<
/*REXX program to play: Guess the number */
Line 2,634 ⟶ 3,078:
say "Well done! You guessed it!"
</syntaxhighlight>
===version 2===
<
?= random(1, 10)
say 'Try to guess my number between 1 ──► 10 (inclusive).'
say 'Well guessed!' /*stick a fork in it, we're all done. */</
=={{header|Ring}}==
<
### Bert Mariani
Line 2,675 ⟶ 3,119:
end
</syntaxhighlight>
=={{header|RPL}}==
<syntaxhighlight lang="userrpl">
DIR
INITIALIZE
Line 2,710 ⟶ 3,154:
END
>>
END</
=={{header|Ruby}}==
<
n = rand(1..10)
puts 'Guess the number: '
puts 'Wrong! Guess again: ' until gets.to_i == n
puts 'Well guessed!'
</syntaxhighlight>
=={{header|Run BASIC}}==
<
choose = int(RND(0) * 9) + 1
while guess <> choose
Line 2,731 ⟶ 3,175:
end if
wend
wend</
=={{header|Rust}}==
{{libheader|rand}}
<
fn main() {
Line 2,759 ⟶ 3,203:
}
}
}</
=={{header|Scala}}==
<
val n = (math.random * 10 + 1).toInt
print("Guess the number: ")
while(readInt != n) print("Wrong! Guess again: ")
println("Well guessed!")
</syntaxhighlight>
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
{{works with|Guile}}
<
(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")))</
{{Out}}
<pre>scheme> (guess)
Line 2,794 ⟶ 3,238:
=={{header|Seed7}}==
<
const proc: main is func
Line 2,811 ⟶ 3,255:
end while;
writeln("You have won!");
end func;</
=={{header|Self}}==
Line 2,819 ⟶ 3,263:
Well factored:
<
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</
Simple method:
<
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!'</
=={{header|Sidef}}==
<
while (n != read(msg, Number)
}
say 'Well guessed!'</
=={{header|Small Basic}}==
<
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!")</
=={{header|SNUSP}}==
Line 2,895 ⟶ 3,339:
=={{header|Swift}}==
<
var found = false
Line 2,911 ⟶ 3,355:
println("Well guessed!")
}
}</
=={{header|Tcl}}==
<
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."</
Sample output:
<pre>
Line 2,942 ⟶ 3,386:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
Line 2,961 ⟶ 3,405:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
Output:
<pre>
Line 2,977 ⟶ 3,421:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<
# 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.'</
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}}
<
# Guess the number
Line 3,009 ⟶ 3,453:
@ guess = "$<"
end
echo 'Well done! You guessed it.'</
=={{header|Ursa}}==
{{trans|Python}}
<
decl ursa.util.random random
Line 3,024 ⟶ 3,468:
end while
out "That's right!" endl console</
=={{header|Vala}}==
<
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;
}</
=={{header|VBA}}==
<
Dim NbComputer As Integer, NbPlayer As Integer
Randomize Timer
Line 3,045 ⟶ 3,489:
Loop While NbComputer <> NbPlayer
MsgBox "Well guessed!"
End Sub</
=={{header|VBScript}}==
<
MyNum=Int(rnd*10)+1
Do
Line 3,068 ⟶ 3,512:
wscript.quit
end if
loop</
=={{header|Visual Basic .NET}}==
<
Sub Main()
Dim random As New Random()
Line 3,094 ⟶ 3,538:
Loop Until gameOver
End Sub
End Module</
{{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)}}==
<
import
import os
fn main() {
rand.seed(seed_array)
num
for {
print('Please guess a number from 1-10 and press <Enter>: ')
if guess.int() == num {
println("Well guessed!
} else {
println("'$guess' is Incorrect. Try
}
}
}</syntaxhighlight>
{{out}}
<pre>Please guess a number from 1-10 and press <Enter>: 1
'1' is Incorrect. Try again.
'2' is Incorrect. Try again.
'9' is Incorrect. Try again.
'10' is Incorrect. Try again.
Please guess a number from 1-10 and press <Enter>: 3
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.
<
let mxnumber=10
let number=mnnumber
Line 3,168 ⟶ 3,741:
endif
wend
end</
=={{header|Wortel}}==
{{trans|JavaScript}}
<
num 10Wc
guess 0
Line 3,180 ⟶ 3,753:
!alert "Congratulations!\nThe number was {num}."
]
}</
=={{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
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 $
segment .bss
segment .text
global
main:
push
mov
; ********** CODE STARTS HERE **********
;;;;; Random number
mov
mov
int
mov eax, [ebx]
mov ebx, 10
xor
div
inc
mov
;;;;; Print the
mov
mov
mov
mov
int
userInput:
;;;;; Ask user
mov
xor ebx, ebx
mov ecx, instructions
mov
int
mov
cmp
jl
cmp
jg
;;;;; If number
sub
xchg
mov ebx, 10
add
jmp
valCheck:
;;;;; Else check
mov
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}}==
<
(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))</
{{out}}
<pre>[1] (guessing-game)
Line 3,296 ⟶ 3,937:
=={{header|XPL0}}==
<
int N, G;
[N:= Ran(10)+1;
Line 3,306 ⟶ 3,947:
];
Text(0, "Well guessed!^M^J");
]</
=={{header|zkl}}==
Strings are used to avoid dealing with error handling
<
while(1){
n:=ask("Num between 1 & 10: ");
if(n==r){ println("Well guessed!"); break; }
println("Nope")
}</
=={{header|Zoomscript}}==
For typing:
<
var guess
randnum & random 1 10
Line 3,331 ⟶ 3,972:
endif
endwhile
print "Correct number. You win!"</
For importing:
|