Mastermind: Difference between revisions
m
→{{header|EasyLang}}
m (will -> may) |
|||
(17 intermediate revisions by 9 users not shown) | |||
Line 54:
* [[Guess the number/With Feedback]]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F encode(correct, guess)
[String] output_arr
L(i) 0 .< correct.len
output_arr [+]= I guess[i] == correct[i] {‘X’} E I guess[i] C correct {‘O’} E ‘-’
R output_arr
F safe_int_input(prompt, min_val, max_val)
L
V user_input_str = input(prompt)
X.try
V user_input = Int(user_input_str)
I user_input C min_val .. max_val
R user_input
X.catch ValueError
L.continue
F play_game()
print(‘Welcome to Mastermind.’)
print(‘You will need to guess a random code.’)
print(‘For each guess, you will receive a hint.’)
print(‘In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.’)
print()
V number_of_letters = safe_int_input(‘Select a number of possible letters for the code (2-20): ’, 2, 20)
V code_length = safe_int_input(‘Select a length for the code (4-10): ’, 4, 10)
V letters = ‘ABCDEFGHIJKLMNOPQRST’[0 .< number_of_letters]
V code = ‘’
L 0 .< code_length
code ‘’= random:choice(letters)
[String] guesses
L
print()
V guess = input(‘Enter a guess of length #. (#.): ’.format(code_length, letters)).uppercase()
I guess.len != code_length | any(guess.map(char -> char !C @letters))
L.continue
E I guess == code
print("\nYour guess "guess‘ was correct!’)
L.break
E
guesses.append(‘#.: #. => #.’.format(guesses.len + 1, Array(guess).join(‘ ’), encode(code, guess).join(‘ ’)))
L(i_guess) guesses
print(‘------------------------------------’)
print(i_guess)
print(‘------------------------------------’)
play_game()</syntaxhighlight>
{{out}}
<pre>
Welcome to Mastermind.
You will need to guess a random code.
For each guess, you will receive a hint.
In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.
Select a number of possible letters for the code (2-20): 4
Select a length for the code (4-10): 4
Enter a guess of length 4 (ABCD): abcd
------------------------------------
1: A B C D => X X O O
------------------------------------
Enter a guess of length 4 (ABCD): abcc
------------------------------------
1: A B C D => X X O O
------------------------------------
2: A B C C => X X O X
------------------------------------
Enter a guess of length 4 (ABCD): abdc
Your guess ABDC was correct!
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE MINCOLORS="2"
DEFINE MAXCOLORS="20"
DEFINE MINLENGTH="4"
DEFINE MAXLENGTH="10"
DEFINE MINGUESS="7"
DEFINE MAXGUESS="20"
TYPE Score=[BYTE spot,corr,err]
TYPE Settings=[BYTE colors,length,guesses,repeat]
PROC GetSettings(Settings POINTER s)
CHAR ARRAY tmp(10)
DO
PrintF("Enter number of colors (%B-%B):",MINCOLORS,MAXCOLORS)
s.colors=InputB()
UNTIL s.colors>=MINCOLORS AND s.colors<=MAXCOLORS
OD
DO
PrintF("Enter length of code (%B-%B):",MINLENGTH,MAXLENGTH)
s.length=InputB()
UNTIL s.length>=MINLENGTH AND s.length<=MAXLENGTH
OD
DO
PrintF("Enter max number of guesses (%B-%B):",MINGUESS,MAXGUESS)
s.guesses=InputB()
UNTIL s.guesses>=MINGUESS AND s.guesses<=MAXGUESS
OD
IF s.colors<s.length THEN
s.repeat=1
ELSE
DO
Print("Allow repeated colors (Y/N):")
InputS(tmp)
IF tmp(0)=1 THEN
IF tmp(1)='y OR tmp(1)='Y THEN
s.repeat=1 EXIT
ELSEIF tmp(1)='n OR tmp(1)='N THEN
s.repeat=0 EXIT
FI
FI
OD
FI
RETURN
PROC Generate(CHAR ARRAY code Settings POINTER s)
CHAR ARRAY col(MAXCOLORS)
BYTE i,j,d,tmp,count
FOR i=0 TO MAXCOLORS-1
DO
col(i)=i+'A
OD
code(0)=s.length
count=s.colors
FOR i=1 TO s.length
DO
d=Rand(count)
code(i)=col(d)
IF s.repeat=0 THEN
count==-1
col(d)=col(count)
FI
OD
RETURN
BYTE FUNC GetCount(CHAR ARRAY s CHAR c)
BYTE i,count
count=0
FOR i=1 TO s(0)
DO
IF s(i)=c THEN
count==+1
FI
OD
RETURN (count)
PROC CheckScore(CHAR ARRAY code,guess
Settings POINTER s Score POINTER res)
BYTE i,j,codeCount,guessCount
res.spot=0
res.corr=0
IF guess(0)#s.length THEN
res.err=1
RETURN
FI
res.err=0
FOR i=0 TO s.colors-1
DO
codeCount=GetCount(code,i+'A)
guessCount=GetCount(guess,i+'A)
IF codeCount<guessCount THEN
res.corr==+codeCount
ELSE
res.corr==+guessCount
FI
OD
FOR i=1 TO s.length
DO
IF guess(i)=code(i) THEN
res.spot==+1
res.corr==-1
FI
OD
RETURN
PROC ToUpper(CHAR ARRAY s)
BYTE i,c
IF s(0)=0 THEN RETURN FI
FOR i=1 TO s(0)
DO
c=s(i)
IF c>='a AND c<='z THEN
s(i)=c-'a+'A
FI
OD
RETURN
PROC PrintScore(Score POINTER res Settings POINTER s)
INT i
FOR i=1 TO res.spot
DO Put('X) OD
FOR i=1 TO res.corr
DO Put('O) OD
FOR i=1 TO s.length-res.spot-res.corr
DO Put('-) OD
RETURN
PROC Main()
CHAR ARRAY code(MAXLENGTH+1),guess(255)
Score res
Settings s
BYTE tries
PrintE("Mastermind") PutE()
GetSettings(s) PutE()
Generate(code,s)
tries=s.guesses
PrintF("Enter your guess (%B tries):%E",tries)
DO
InputS(guess) ToUpper(guess)
CheckScore(code,guess,s,res)
Put(28) ;cursor up
PrintF("%S -> ",guess)
IF res.err THEN
Print("Wrong input")
ELSE
PrintScore(res,s)
IF res.spot=s.length THEN
PutE() PutE()
PrintE("You won!")
EXIT
FI
tries==-1
IF tries=0 THEN
PutE() PutE()
PrintE("You lost!")
EXIT
FI
FI
PrintF(", try again (%B tries):%E",tries)
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Mastermind.png Screenshot from Atari 8-bit computer]
<pre>
Mastermind
Enter number of colors (2-20):6
Enter length of code (4-10):5
Enter max number of guesses (7-20):20
Allow repeated colors (Y/N):Y
Enter your guess (20 tries):
AAAA -> Wrong input, try again (20 tries):
AAAAA -> -----, try again (19 tries):
BBBBB -> -----, try again (18 tries):
CCCCC -> -----, try again (17 tries):
DDDDD -> XX---, try again (16 tries):
EEEEE -> X----, try again (15 tries):
DDEFF -> XXXXX
You won!
</pre>
=={{header|Ada}}==
{{works with|Ada|Ada|2012}}
<
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
Line 219 ⟶ 493:
end;
end MasterMind;
</syntaxhighlight>
{{out}}
<pre>How many colors? 9
Line 272 ⟶ 546:
{{works with|GNU APL}}
<
⍝ Define the alphabet
Line 402 ⟶ 676:
Mastermind
)OFF</
=={{header|AutoHotkey}}==
<
ww := floor(w/2-2), hh := floor(h/2-2)
grid := [], dx := w*4.5
Line 572 ⟶ 846:
GuiControl,, Radio%A_Index%, % pegs[A_Index]
return
;-----------------------------------------------------------------------</
=={{header|BASIC}}==
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">'--- Declaration of global variables ---
Dim As String colors(1 To 4) => {"A", "B", "C", "D"}
Dim Shared As Integer nr, ub', numlet=4, lencod=4
Dim Shared As String*4 master, pz
ub = Ubound(colors)
nr = 0
'--- SUBroutines and FUNCtions ---
Sub Encabezado
Dim As String dup
Color 11: Print "Welcome to Mastermind"
Print "=====================" + Chr(13) + Chr(10) : Color 15
Print "You will need to guess a random code."
Print "For each guess, you will receive a hint:"
Print "X - denotes a correct letter,"
Print "O - denotes a letter in the original"
Print " string but a different position."
Print "You have 12 attempts."
Print "Duplicates are not allowed." + Chr(10)
Print "Good luck!" + Chr(10) + Chr(10) : Color 7
End Sub
Sub showresult(test() As String, place1 As Byte, place2 As Byte, place3 As Byte)
Dim As Integer r, n1, n2, n3
Print Using "##: "; nr;
For r = 1 To Ubound(test)
Print test(r);
Next R
Print " : ";
For n1 = 1 To place1
Print "X"; " ";
Next N1
For n2 = 1 To place2
Print "O"; " ";
Next N2
For n3 = 1 To place3
Print "-"; " ";
Next N3
Print : Print
End Sub
Sub Inicio
Dim As Integer mind(ub), rands(ub)
Dim As Integer n, aleat
Dim As Boolean repeat = false
For n = 1 To ub
While true
aleat = (Rnd * (ub-1)) + 1
If rands(aleat) <> 1 Then
mind(n) = aleat
rands(aleat) = 1
Exit While
End If
Wend
Next n
For n = 1 To ub
Mid(master,n,1) = Chr(64 + mind(n))
pz &= Chr(64 + mind(n))
Next n
End Sub
'--- Main Program ---
Randomize Timer
Cls
Dim As Integer guesses = 12
Encabezado
Inicio
Color 15: Print pz : Color 7
Do
Dim As Integer n, p, d, x, posic
Dim As Integer places(1 To 2), place1, place2, place3
Dim As String*4 testbegin
Dim As String test(ub), mastertemp, tmp
Dim As Boolean flag = True
For p = 1 To Ubound(places)
places(p) = 0
Next p
nr += 1
Input "Your guess (ABCD)? " , testbegin
For d = 1 To Ubound(test)
test(d) = Mid(testbegin,d,1)
Next d
For n = 1 To Ubound(test)
If Ucase(test(n)) <> Mid(master,n,1) Then flag = False
Next n
If flag = True Then
Color 10: Print !"\nWell done! You guess correctly." : Sleep : Exit Do
Else
For x = 1 To Len(master)
If Ucase(test(x)) = Mid(master,x,1) Then places(1) += 1
Next x
mastertemp = master
For p = 1 To Ubound(test)
posic = Instr(mastertemp, Ucase(test(p)))
If posic > 0 Then
tmp = mastertemp
mastertemp = Left(tmp,posic-1) + Mid(tmp, posic+1, Len(tmp)-1)
places(2) += 1
End If
Next p
End If
place1 = places(1)
place2 = places(2) - place1
place3 = Len(master) - (place1 + place2)
showresult(test(), place1, place2, place3)
Loop Until nr = guesses
Color 14: Print "The correct combination was: "; pz
Color 7: Print !"\nEnd of game"
Sleep</syntaxhighlight>
=={{header|C++}}==
<
#include <algorithm>
#include <ctime>
Line 723 ⟶ 1,114:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 752 ⟶ 1,143:
=={{header|EasyLang}}==
[https://easylang.
<syntaxhighlight>
col[] = [
len code[] 4
len guess[] 4
#
subr init_vars
row =
.
for j
for c
move c * 3.5 +
if black > 0
color 000
circle 1.4
black -= 1
elif white > 0
color 999
circle 1.4
white -= 1
else
color 310
circle 0.7
.
.
.
color 531
move
rect 46 8
for i
move i * 8 +
color col[code[i]]
circle 2
.
.
for c
move c * 12 +
color col[guess[c]]
circle 3.8
.
.
color 420
linewidth 11
move
line
move
color 310
circle 5.0
color 753
move 71.5 row * 11.5 + 5
textsize 7
text "✓"
.
move
color 531
circle 5.2
c[] = code[]
g[] = guess[]
for i
if c[i] = g[i]
black += 1
c[i] = -1
g[i] = -2
.
for i to 4
for j to 4
if c[i] = g[j]
white += 1
.
draw_rate row
color 531
move 17 row * 11.5 + 7.5
line 60 row * 11.5 + 7.5
draw_guess
row
if black = 4
row = 8
.
if row = 8
show_code
timer 2
else
next_row
.
.
on timer
row = -2
.
for i
code[i] =
.
color 531
move
rect 70 80
linewidth 10
move
line
line
line
line
color 310
linewidth 7
move
line
move
color 864
textsize 4
text "Mastermind"
color 310
linewidth 0.5
move
line
move
line
move
line
for r
for c
move c * 12 +
circle 2
.
.
guess[3] = 2
guess[4] = 2
next_row
.
c =
guess[c + 1] =
.
on mouse_down
if row = -2
elif mouse_y > row * 11.5 +
if mouse_x >
elif mouse_x >
.
.
.
new
</syntaxhighlight>
=={{header|Go}}==
<
import (
Line 1,102 ⟶ 1,496:
none := m.holes - black - white
return blacks[:black] + whites[:white] + nones[:none], black == m.holes
}</
{{out|note=using Knuth's five-guess algorithm}}
<pre>
Line 1,122 ⟶ 1,516:
You found the code in 5 guesses.
</pre>
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public final class MastermindTask {
public static void main(String[] aArgs) {
Mastermind mastermind = new Mastermind(4, 8, 12, false);
mastermind.play();
}
private static final class Mastermind {
public Mastermind(int aCodeLength, int aLetterCount, int aGuessCount, boolean aRepeatLetters) {
if ( aCodeLength < 4 ) {
aCodeLength = 4;
} else if ( aCodeLength > 10 ) {
aCodeLength = 10;
}
if ( aLetterCount < 2 ) {
aLetterCount = 2;
} else if ( aLetterCount > 20 ) {
aLetterCount = 20;
}
if ( aGuessCount < 7 ) {
aGuessCount = 7;
} else if ( aGuessCount > 20 ) {
aGuessCount = 20;
}
if ( ! aRepeatLetters && aLetterCount < aCodeLength ) {
aLetterCount = aCodeLength;
}
codeLength = aCodeLength;
letterCount = aLetterCount;
guessCount = aGuessCount;
repeatLetters = aRepeatLetters;
String validLetters = "ABCDEFGHIJKLMNOPQRST";
letters = "";
for ( int i = 0; i < letterCount; i++ ) {
letters += validLetters.charAt(i);
}
}
public void play() {
boolean playerWin = false;
goal = createGoal();
while ( guessCount > 0 && ! playerWin ) {
showBoard();
if ( checkUserInput(obtainUserGuess()) ) {
playerWin = true;
reader.close();
}
guessCount--;
}
if ( playerWin ) {
System.out.println(newLine + newLine + "--------------------------------" + newLine +
"Very well done! " + newLine + "You found the code: " + goal +
newLine + "--------------------------------" + newLine + newLine);
} else {
System.out.println(newLine + newLine + "--------------------------------" + newLine +
"I'm sorry, you couldn't make it! " + newLine + "The code was: " + goal +
newLine + "--------------------------------" + newLine + newLine);
}
}
private void showBoard() {
for ( int i = 0; i < guesses.size(); i++ ) {
System.out.print(newLine + "--------------------------------" + newLine);
System.out.print(( i + 1 ) + ": ");
for ( char ch : guesses.get(i) ) {
System.out.print(ch + " ");
}
System.out.print(" : ");
for ( char ch : results.get(i) ) {
System.out.print(ch + " ");
}
final int errorCount = codeLength - results.get(i).size();
for ( int j = 0; j < errorCount; j++ ) {
System.out.print("- ");
}
}
System.out.print(newLine + newLine);
}
private String obtainUserGuess() {
String result = "";
do {
System.out.print("Enter your guess (" + letters + "): ");
result = reader.nextLine().toUpperCase();
if ( result.length() != codeLength ) {
System.out.println("Please try again, your guess should have " + codeLength + " letters");
}
} while ( result.length() != codeLength );
return result;
}
private boolean checkUserInput(String aUserInput) {
List<Character> userInputCharacters = new ArrayList<Character>();
for ( char ch : aUserInput.toCharArray() ) {
userInputCharacters.add(ch);
}
guesses.add(userInputCharacters);
int xCount = 0;
int oCount = 0;
List<Boolean> fullMatches = new ArrayList<Boolean>(Collections.nCopies(codeLength, false));
List<Boolean> partialMatches = new ArrayList<Boolean>(Collections.nCopies(codeLength, false));
for ( int i = 0; i < codeLength; i++ ) {
if ( aUserInput.charAt(i) == goal.charAt(i) ) {
fullMatches.set(i, true);
partialMatches.set(i, true);
xCount++;
}
}
for ( int i = 0; i < codeLength; i++ ) {
if ( fullMatches.get(i) ) {
continue;
}
for ( int j = 0; j < codeLength; j++ ) {
if ( i == j || partialMatches.get(j) ) {
continue;
}
if ( aUserInput.charAt(i) == goal.charAt(j) ) {
partialMatches.set(j, true);
oCount++;
break;
}
}
}
List<Character> nextResult = new ArrayList<Character>();
for ( int i = 0; i < xCount; i++ ) {
nextResult.add('X');
}
for ( int i = 0; i < oCount; i++ ) {
nextResult.add('O');
}
results.add(nextResult);
return xCount == codeLength;
}
private String createGoal() {
String result = "";
String lettersCopy = letters;
for ( int i = 0; i < codeLength; i++ ) {
final int index = random.nextInt(lettersCopy.length());
result += lettersCopy.charAt(index);
if ( ! repeatLetters ) {
lettersCopy = lettersCopy.substring(0, index) + lettersCopy.substring(index + 1);
}
}
return result;
}
private int codeLength, letterCount, guessCount;
private String letters, goal;
private boolean repeatLetters;
private Scanner reader = new Scanner(System.in);
private List<List<Character>> guesses = new ArrayList<List<Character>>();
private List<List<Character>> results = new ArrayList<List<Character>>();
private final ThreadLocalRandom random = ThreadLocalRandom.current();
private final String newLine = System.lineSeparator();
}
}
</syntaxhighlight>
{{ out }}
<pre>
Enter your guess (ABCDEFGH): abcd
--------------------------------
1: A B C D : X O O -
Enter your guess (ABCDEFGH): bcde
--------------------------------
1: A B C D : X O O -
--------------------------------
2: B C D E : O O O -
Enter your guess (ABCDEFGH): fbcd
--------------------------------
1: A B C D : X O O -
--------------------------------
2: B C D E : O O O -
--------------------------------
3: F B C D : X O O O
Enter your guess (ABCDEFGH): fbdc
--------------------------------
1: A B C D : X O O -
--------------------------------
2: B C D E : O O O -
--------------------------------
3: F B C D : X O O O
--------------------------------
4: F B D C : X X O O
Enter your guess (ABCDEFGH):
// continues ...
</pre>
Line 1,127 ⟶ 1,745:
You can try it [http://paulo-jorente.de/webgames/repos/mastermind/ here].
<
class Mastermind {
constructor() {
Line 1,360 ⟶ 1,978:
mm.check()
});
</syntaxhighlight>
To test you'll need a HTML file
Line 1,496 ⟶ 2,114:
=={{header|Julia}}==
GUI version, uses the Gtk toolkit.
<
struct Guess
Line 1,705 ⟶ 2,323:
mastermindapp()
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|C++}}
<
import java.util.Random
Line 1,826 ⟶ 2,444:
val m = Mastermind(4, 8, 12, false)
m.play()
}</
Sample input/output (showing last 2 guesses only):
Line 1,866 ⟶ 2,484:
=={{header|Lua}}==
Based on C++
<
math.randomseed( os.time() )
local black, white, none, code = "X", "O", "-"
Line 1,945 ⟶ 2,563:
if arg[4] ~= nil and arg[4] == "true" or arg[4] == "false" then rept = ( arg[4] == "true" ) end
play()
</syntaxhighlight>
{{out}}
<pre>
Line 1,969 ⟶ 2,587:
Play again( Y/N )?
</pre>
=={{header|Nim}}==
{{trans|Python}}
<syntaxhighlight lang="nim">import random, sequtils, strformat, strutils
proc encode(correct, guess: string): string =
result.setlen(correct.len)
for i in 0..correct.high:
result[i] = if correct[i] == guess[i]: 'X' else: (if guess[i] in correct: 'O' else: '-')
result.join(" ")
proc safeIntInput(prompt: string; minVal, maxVal: Positive): int =
while true:
stdout.write prompt
let userInput = stdin.readLine()
result = try: parseInt(userInput)
except ValueError: continue
if result in minVal..maxVal:
return
proc playGame() =
echo "You will need to guess a random code."
echo "For each guess, you will receive a hint."
echo "In this hint, X denotes a correct letter, " &
"and O a letter in the original string but in a different position."
echo ""
let numLetters = safeIntInput("Select a number of possible letters for the code (2-20): ", 2, 20)
let codeLength = safeIntInput("Select a length for the code (4-10): ", 4, 10)
let letters = "ABCDEFGHIJKLMNOPQRST"[0..<numLetters]
let code = newSeqWith(codeLength, letters.sample()).join()
var guesses: seq[string]
while true:
echo ""
stdout.write &"Enter a guess of length {codeLength} ({letters}): "
let guess = stdin.readLine().toUpperAscii().strip()
if guess.len != codeLength or guess.anyIt(it notin letters):
continue
elif guess == code:
echo &"\nYour guess {guess} was correct!"
break
else:
guesses.add &"{guesses.len + 1}: {guess.join(\" \")} => {encode(code, guess)}"
for guess in guesses:
echo "------------------------------------"
echo guess
echo "------------------------------------"
randomize()
playGame()</syntaxhighlight>
{{out}}
<pre>You will need to guess a random code.
For each guess, you will receive a hint.
In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.
Select a number of possible letters for the code (2-20): 4
Select a length for the code (4-10): 4
Enter a guess of length 4 (ABCD): ABCD
------------------------------------
1: A B C D => - O - X
------------------------------------
Enter a guess of length 4 (ABCD): BDBD
------------------------------------
1: A B C D => - O - X
------------------------------------
2: B D B D => X X O X
------------------------------------
Enter a guess of length 4 (ABCD): BDDD
Your guess BDDD was correct!</pre>
=={{header|Perl}}==
{{trans|Raku}}
<
print 'Enter pool size, puzzle size, attempts allowed: ';
Line 2,023 ⟶ 2,719:
sub lose { print 'Too bad, you ran out of guesses. The solution was: ' . join(' ',@puzzle) . "\n"; exit }
</syntaxhighlight>
Sample output, omitting redundant instructions.
{{out}}
Line 2,045 ⟶ 2,741:
=={{header|Phix}}==
OTT GUI solution, fully configurable with solver.
<
constant SET_LIMIT = 1_000_000 -- above this, it uses random sampling.
Line 2,613 ⟶ 3,309:
IupClose()
end procedure
main()</
=={{header|Prolog}}==
<
mastermind(Colours, Length, Guesses, Duplicates) :-
Line 2,717 ⟶ 3,413:
N > 0,
N1 is N - 1,
truncate_list(T, N1, R).</
{{out}}
<pre>
Line 2,768 ⟶ 3,464:
{{works with|cpython|3.7.3}}
Tested in Python 3.7.3. Includes input verification.
<
import random
Line 2,829 ⟶ 3,525:
play_game()
</syntaxhighlight>
{{out}}
<pre>
Line 2,858 ⟶ 3,554:
{{works with|Rakudo|2017.01}}
By default, plays classic Mastermind using letters in place of colors. ( 4 chosen from 6, no repeats, 10 guess limit. ) Pass in parameters to modify the game. Enter a string of --length (default 4) letters with or without spaces. Guesses accept lower or upper case.
<syntaxhighlight lang="raku"
Int :$colors where 1 < * < 21 = 6, Int :$length where 3 < * < 11 = 4,
Int :$guesses where 7 < * < 21 = 10, Bool :$repeat = False
Line 2,916 ⟶ 3,612:
sub lose { say 'Too bad, you ran out of guesses. The solution was: ', $puzzle; exit }
}</
{{out|Sample output}}
<pre>Valid letter, but wrong position: ○ - Correct letter and position: ●
Line 2,933 ⟶ 3,629:
=={{header|REXX}}==
More checks could have been added (for illegal inputs and illegal options).
<
parse arg let wid mxG oRep seed _ /*obtain optional arguments from the CL*/
arg . . . rep . /*get uppercase 4th argument " " " */
Line 3,010 ⟶ 3,706:
if val > mx then call ser ? "has a value greater than " mx /*◄■■■■■■ optional vetting.*/
if ?=='REP' & \datatype(val,W) then call ser "Value for REPEATS isn't valid: " oRep /*◄■■■■■■ optional vetting.*/
return 1</
'''output'''
<pre>
Line 3,067 ⟶ 3,763:
=={{header|Ring}}==
<
# Project : Mastermind
Line 3,161 ⟶ 3,857:
next
see nl
</syntaxhighlight>
Output:
<pre>
Line 3,177 ⟶ 3,873:
=={{header|Rust}}==
{{libheader|rand}}
<
use rand::prelude::*;
Line 3,339 ⟶ 4,035:
res.sort_by(|a, b| b.cmp(a));
res.into_iter().collect()
}</
{{out}}
<pre>
Line 3,392 ⟶ 4,088:
=={{header|SQL}}==
<
-- Create Table
-- Distinct combination
Line 3,463 ⟶ 4,159:
check_white(guesses.*, mastermind.*)
FROM guesses, mastermind
</syntaxhighlight>
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-ioutil}}
{{libheader|Wren-str}}
<syntaxhighlight lang="wren">import "random" for Random
import "./ioutil" for Input
import "./str" for Str
var Rand = Random.new()
class Mastermind {
construct new(codeLen, colorsCnt, guessCnt, repeatClr) {
var color = "ABCDEFGHIJKLMNOPQRST"
_codeLen = codeLen.clamp(4, 10)
var cl = colorsCnt
if (!repeatClr && cl < _codeLen) cl = _codeLen
_colorsCnt = cl.clamp(2, 20)
_guessCnt = guessCnt.clamp(7, 20)
_repeatClr = repeatClr
_colors = color.take(_colorsCnt).join()
_combo = ""
_guesses = []
_results = []
}
play() {
var win = false
_combo = getCombo_()
while (_guessCnt != 0) {
showBoard_()
if (checkInput_(getInput_())) {
win = true
break
}
_guessCnt = _guessCnt - 1
}
System.print("\n\n--------------------------------")
if (win) {
System.print("Very well done!\nYou found the code: %(_combo)")
} else {
System.print("I am sorry, you couldn't make it!\nThe code was: %(_combo)")
}
System.print("--------------------------------\n")
}
showBoard_() {
for (x in 0..._guesses.count) {
System.print("\n--------------------------------")
System.write("%(x + 1): ")
for (y in _guesses[x]) System.write("%(y) ")
System.write(" : ")
for (y in _results[x]) System.write("%(y) ")
var z = _codeLen - _results[x].count
if (z > 0) System.write("- " * z)
}
System.print("\n")
}
getInput_() {
while (true) {
var a = Str.upper(Input.text("Enter your guess (%(_colors)): ", 1)).take(_codeLen)
if (a.all { |c| _colors.contains(c) } ) return a.join()
}
}
checkInput_(a) {
_guesses.add(a.toList)
var black = 0
var white = 0
var gmatch = List.filled(_codeLen, false)
var cmatch = List.filled(_codeLen, false)
for (i in 0..._codeLen) {
if (a[i] == _combo[i]) {
gmatch[i] = true
cmatch[i] = true
black = black + 1
}
}
for (i in 0..._codeLen) {
if (gmatch[i]) continue
for (j in 0..._codeLen) {
if (i == j || cmatch[j]) continue
if (a[i] == _combo[j]) {
cmatch[j] = true
white = white + 1
break
}
}
}
var r = []
r.addAll(("X" * black).toList)
r.addAll(("O" * white).toList)
_results.add(r)
return black == _codeLen
}
getCombo_() {
var c = ""
var clr = _colors
for (s in 0..._codeLen) {
var z = Rand.int(clr.count)
c = c + clr[z]
if (!_repeatClr) Str.delete(clr, z)
}
return c
}
}
var m = Mastermind.new(4, 8, 12, false)
m.play()</syntaxhighlight>
{{out}}
Sample game:
<pre>
Enter your guess (ABCDEFGH): abcd
--------------------------------
1: A B C D : X - - -
Enter your guess (ABCDEFGH): efgh
--------------------------------
1: A B C D : X - - -
--------------------------------
2: E F G H : O O - -
Enter your guess (ABCDEFGH): aefa
--------------------------------
1: A B C D : X - - -
--------------------------------
2: E F G H : O O - -
--------------------------------
3: A E F A : X X - -
Enter your guess (ABCDEFGH): aagh
--------------------------------
1: A B C D : X - - -
--------------------------------
2: E F G H : O O - -
--------------------------------
3: A E F A : X X - -
--------------------------------
4: A A G H : X O O O
Enter your guess (ABCDEFGH): agah
--------------------------------
1: A B C D : X - - -
--------------------------------
2: E F G H : O O - -
--------------------------------
3: A E F A : X X - -
--------------------------------
4: A A G H : X O O O
--------------------------------
5: A G A H : X X O O
Enter your guess (ABCDEFGH): agha
--------------------------------
Very well done!
You found the code: AGHA
--------------------------------
</pre>
=={{header|zkl}}==
{{trans|C++}}
<
fcn init(code_len,guess_count){
var codeLen =code_len.max(4).min(10);
Line 3,513 ⟶ 4,377:
return(black==codeLen,"X"*black + "O"*white)
}
}(4,12).play();</
{{out}}
<pre>
|