Mastermind: Difference between revisions

m
(Added Wren)
 
(13 intermediate revisions by 8 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}}
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
Line 219 ⟶ 493:
end;
end MasterMind;
</syntaxhighlight>
</lang>
{{out}}
<pre>How many colors? 9
Line 272 ⟶ 546:
{{works with|GNU APL}}
 
<langsyntaxhighlight APLlang="apl">#!/usr/local/bin/apl -s -f --
 
⍝ Define the alphabet
Line 402 ⟶ 676:
 
Mastermind
)OFF</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">w := h := 32, maxRows := 10, numPegs := 8
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
;-----------------------------------------------------------------------</langsyntaxhighlight>
 
=={{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++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <algorithm>
#include <ctime>
Line 723 ⟶ 1,114:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 752 ⟶ 1,143:
=={{header|EasyLang}}==
 
[https://easylang.onlinedev/apps/mastermind.html Run it]
 
<syntaxhighlight>
<lang>col[] = [ 802 990 171 229 950 808 ]
col[] = [ 802 990 171 229 950 808 ]
len code[] 4
len guess[] 4
#
subr init_vars
row = 70
.
funcproc draw_rate r black white . .
for j rangerange0 2
for c rangerange0 2
move_pen move c * 3.5 + 71.5 r * 11.5 + 109.4 +- j * 3.5
if black > 0
set_color color 000
draw_circle circle 1.4
black -= 1
elif white > 0
set_color color 999
draw_circle circle 1.4
white -= 1
else
set_color color 310
draw_circle circle 0.7
.
.
.
.
.
funcproc show_code . .
set_color color 531
move_pen move 22 092
draw_rect rect 46 8
for i rangeto 4
move_pen move i * 8 + 2820 397
set_color color col[code[i]]
draw_circle circle 2
.
.
funcproc draw_guess . .
for c rangeto 4
move_pen move c * 12 + 208 row * 11.5 + 127.5
set_color color col[guess[c]]
draw_circle circle 3.8
.
.
funcproc next_row . .
set_color color 420
set_linewidth linewidth 11
move_pen move 17 row * 11.5 + 127.5
draw_line line 60 row * 11.5 + 127.5
call draw_guess
move_pen move 73.5 row * 11.5 + 127.5
set_color color 310
draw_circle circle 5.0
set_color color 753
move_pen move 71.5 row * 11.5 + 8.5
set_textsize textsize 7
draw_text text "✓"
.
funcproc rate . .
move_pen move 73.5 row * 11.5 + 127.5
set_color color 531
draw_circle circle 5.2
c[] = code[]
g[] = guess[]
for i rangeto 4
if c[i] = g[i]
black += 1
c[i] = -1
g[i] = -2
.
.
for i range 4
for j range 4
if c[i] = g[j]
white += 1
c[i] = -1
g[j] = -2
.
.
for i to 4
.
for j to 4
call draw_rate row black white
if c[i] = g[j]
set_color 531
white += 1
set_linewidth 12
c[i] = -1
move_pen 17 row * 11.5 + 12
g[j] = -2
draw_line 60 row * 11.5 + 12
.
call draw_guess
row -= 1 .
if black = 4.
draw_rate row =black -1white
color 531
.
if rowlinewidth = -112
move 17 row * 11.5 + 7.5
call show_code
line 60 row * 11.5 + 7.5
set_timer 1
draw_guess
else
row call+= next_row1
if black = 4
.
row = 8
.
if row = 8
show_code
timer 2
else
next_row
.
.
on timer
row = -2
.
funcproc new . .
call init_vars
for i rangeto 4
code[i] = randomrandint 6
.
set_color color 531
move_pen move 10 10
draw_rect rect 70 80
set_linewidth linewidth 10
move_pen 5move 5 95
draw_line line 5 955
draw_line line 85 955
draw_line line 85 595
draw_line 5line 5 95
set_color color 310
set_linewidth linewidth 7
move_pen move 28 396.5
draw_line line 58 396.5
move_pen move 30 195
set_color color 864
set_textsize textsize 4.5
draw_text text "Mastermind"
set_color color 310
set_linewidth linewidth 0.5
move_pen 10move 10 90
draw_line line 10 964
move_pen move 67 1090
draw_line line 67 964
move_pen move 80 1090
draw_line line 80 964
for r rangerange0 8
for c rangerange0 4
move_pen move c * 12 + 20 r * 11.5 + 127.5
draw_circle circle 2
.
call draw_rate r 0 0
.
guess[01] = 01
guess[12] = 01
guess[23] = 12
guess[34] = 12
call next_row
.
funcproc do_move . .
c = (mouse_x - 15) div 12
guess[c + 1] = (guess[c] + 1)] mod 6 + 1
call draw_guess
.
on mouse_down
if row = -2
call new
elif mouse_y > row * 11.5 + 70.5 and mouse_y < row * 11.5 + 1710.5 and row < 8
if mouse_x > 15 and mouse_x < 61
call do_move
elif mouse_x > 67 and mouse_x < 80
call rate
.
.
.
new
call new</lang>
</syntaxhighlight>
 
=={{header|Go}}==
 
<langsyntaxhighlight Golang="go">package main
 
import (
Line 1,103 ⟶ 1,496:
none := m.holes - black - white
return blacks[:black] + whites[:white] + nones[:none], black == m.holes
}</langsyntaxhighlight>
{{out|note=using Knuth's five-guess algorithm}}
<pre>
Line 1,123 ⟶ 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,128 ⟶ 1,745:
You can try it [http://paulo-jorente.de/webgames/repos/mastermind/ here].
 
<langsyntaxhighlight lang="javascript">
class Mastermind {
constructor() {
Line 1,361 ⟶ 1,978:
mm.check()
});
</syntaxhighlight>
</lang>
 
To test you'll need a HTML file
Line 1,497 ⟶ 2,114:
=={{header|Julia}}==
GUI version, uses the Gtk toolkit.
<langsyntaxhighlight lang="julia">using Gtk, Colors, Cairo, Graphics
 
struct Guess
Line 1,706 ⟶ 2,323:
 
mastermindapp()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|C++}}
<langsyntaxhighlight lang="scala">// version 1.2.51
 
import java.util.Random
Line 1,827 ⟶ 2,444:
val m = Mastermind(4, 8, 12, false)
m.play()
}</langsyntaxhighlight>
 
Sample input/output (showing last 2 guesses only):
Line 1,867 ⟶ 2,484:
=={{header|Lua}}==
Based on C++
<langsyntaxhighlight lang="lua">
math.randomseed( os.time() )
local black, white, none, code = "X", "O", "-"
Line 1,946 ⟶ 2,563:
if arg[4] ~= nil and arg[4] == "true" or arg[4] == "false" then rept = ( arg[4] == "true" ) end
play()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,973 ⟶ 2,590:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight Nimlang="nim">import random, sequtils, strformat, strutils
 
proc encode(correct, guess: string): string =
Line 2,023 ⟶ 2,640:
 
randomize()
playGame()</langsyntaxhighlight>
 
{{out}}
Line 2,051 ⟶ 2,668:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use List::Util qw(any);
 
print 'Enter pool size, puzzle size, attempts allowed: ';
Line 2,102 ⟶ 2,719:
 
sub lose { print 'Too bad, you ran out of guesses. The solution was: ' . join(' ',@puzzle) . "\n"; exit }
</syntaxhighlight>
</lang>
Sample output, omitting redundant instructions.
{{out}}
Line 2,124 ⟶ 2,741:
=={{header|Phix}}==
OTT GUI solution, fully configurable with solver.
<langsyntaxhighlight Phixlang="phix">-- demo/rosetta/mastermind.exw
constant SET_LIMIT = 1_000_000 -- above this, it uses random sampling.
 
Line 2,692 ⟶ 3,309:
IupClose()
end procedure
main()</langsyntaxhighlight>
 
=={{header|Prolog}}==
 
<langsyntaxhighlight Prologlang="prolog">mastermind :- mastermind(7, 4, 8, no_duplicates).
 
mastermind(Colours, Length, Guesses, Duplicates) :-
Line 2,796 ⟶ 3,413:
N > 0,
N1 is N - 1,
truncate_list(T, N1, R).</langsyntaxhighlight>
{{out}}
<pre>
Line 2,847 ⟶ 3,464:
{{works with|cpython|3.7.3}}
Tested in Python 3.7.3. Includes input verification.
<langsyntaxhighlight lang="python">
import random
 
Line 2,908 ⟶ 3,525:
play_game()
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,937 ⟶ 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" perl6line>sub MAIN (
Int :$colors where 1 < * < 21 = 6, Int :$length where 3 < * < 11 = 4,
Int :$guesses where 7 < * < 21 = 10, Bool :$repeat = False
Line 2,995 ⟶ 3,612:
 
sub lose { say 'Too bad, you ran out of guesses. The solution was: ', $puzzle; exit }
}</langsyntaxhighlight>
{{out|Sample output}}
<pre>Valid letter, but wrong position: ○ - Correct letter and position: ●
Line 3,012 ⟶ 3,629:
=={{header|REXX}}==
More checks could have been added &nbsp; (for illegal inputs and illegal options).
<langsyntaxhighlight lang="rexx">/*REXX pgm scores mastermind game with a human or CBLFs (Carbon Based Life Forms). */
parse arg let wid mxG oRep seed _ /*obtain optional arguments from the CL*/
arg . . . rep . /*get uppercase 4th argument " " " */
Line 3,089 ⟶ 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</langsyntaxhighlight>
'''output'''
<pre>
Line 3,146 ⟶ 3,763:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Mastermind
 
Line 3,240 ⟶ 3,857:
next
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,256 ⟶ 3,873:
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand;
 
use rand::prelude::*;
Line 3,418 ⟶ 4,035:
res.sort_by(|a, b| b.cmp(a));
res.into_iter().collect()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,471 ⟶ 4,088:
 
=={{header|SQL}}==
<langsyntaxhighlight lang="sql">
-- Create Table
-- Distinct combination
Line 3,542 ⟶ 4,159:
check_white(guesses.*, mastermind.*)
FROM guesses, mastermind
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
Line 3,548 ⟶ 4,165:
{{libheader|Wren-ioutil}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./ioutil" for Input
import "./str" for Str
 
var Rand = Random.new()
Line 3,653 ⟶ 4,270:
 
var m = Mastermind.new(4, 8, 12, false)
m.play()</langsyntaxhighlight>
 
{{out}}
Line 3,714 ⟶ 4,331:
=={{header|zkl}}==
{{trans|C++}}
<langsyntaxhighlight lang="zkl">class MasterMind{
fcn init(code_len,guess_count){
var codeLen =code_len.max(4).min(10);
Line 3,760 ⟶ 4,377:
return(black==codeLen,"X"*black + "O"*white)
}
}(4,12).play();</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits