Skip to content

Instantly share code, notes, and snippets.

@dariye
Created November 6, 2018 17:48
Show Gist options
  • Save dariye/83a0edd76621acf24bee1501d8208969 to your computer and use it in GitHub Desktop.
Save dariye/83a0edd76621acf24bee1501d8208969 to your computer and use it in GitHub Desktop.
WorrisomeSaddlebrownRuby created by pauldariye - https://repl.it/@pauldariye/WorrisomeSaddlebrownRuby
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table id="board">
<tr>
<th>X</th>
<th>X</th>
<th>X</th>
<th>X</th>
</tr>
<tr>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
</tr>
</table>
<label for="guess">Enter your guess</label><br>
<input name="guess" id="guess" type="text">
<script src="index.js"></script>
</body>
</html>
/*
* Mastermind rules
* 1. 6 possible colors (R, O ,Y, G, B, P)
* 2. Player chooses a code (ordered list of 4 colors with possible dups)
* 3. Player 2 has 10 guesses
* 4. After each guess, player 1 gives a score; black for correct color and position; white for correct color but incorrect position
*/
function generateRandomCode() {
const colors = `ROYGBP`.split('')
let code = []
for (let i = 0; i < 4; i ++) {
code.push(colors[Math.floor(Math.random() * (6))])
}
return code.join('');
}
function playGame() {
const code = generateRandomCode();
let guessesLeft = 10;
let status = [];
while (guessesLeft > 0) {
// TODO: Validate user input
const guess = prompt(`Make a guess! You have ${guessesLeft} guesses left. Guesses so far:\n ${ status.join('\n')}`);
result = checkGuess(code, guess);
if (result[0] == 4) {
console.log(`You win! You had ${guessesLeft} guesses left!`);
return;
}
status.push([guess, result]);
guessesLeft--;
}
}
// [# black pegs, # white pegs]
function checkGuess(code, guess) {
if (code == guess) {
return [4, 0];
}
let blackPegs = 0;
let whitePegs = 0;
let matches = [0, 0, 0, 0];
for (let i = 0; i < 4; i++) {
if (code[i] === guess[i]) {
matches[i] = 1;
}
}
// matches [1, 0 , 0, 0]
for (let i = 0; i < 4; i++) {
if (matches[i] === 1) {
continue
}
for (let j = 0; j < 4; j++) {
if (matches[j] !== 0) {
continue
}
if (code[i] === guess[j]) {
matches[j] = 2
break
}
}
}
matches.forEach(match => {
if (match === 1) blackPegs++;
if (match === 2) whitePegs++;
});
return [blackPegs, whitePegs];
}
function test() {
console.log(checkGuess('YGYG', 'GGYY')); // [2, 2]
console.log(checkGuess('YGGG', 'GGYY')); // [1, 2]
console.log(checkGuess('GYGP', 'GGYY')); // [1, 2]
console.log(checkGuess('PPGB', 'PYGB')); // [3, 0]
console.log(checkGuess('PPGB', 'PYBG')); // [1, 2]
}
function main() {
// test();
playGame();
}
document.getElementById('guess')
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment