RSS

Tag Archives: mastermind

Full code for the mastermind game

Here’s the whole thing as I’ve written it – my first full program ever!

Mastermind code in Javascript

Took me about a week to set up properly

Finally succeeded July 2, 2012

Plays all basics of the game – doesn’t show a running list to help player, but shows all moves at finish.

//gets the number of digits used

var code = function(){

var enteredCode = 0;

var codeVeritas = false;

while (codeVeritas === false){

enteredCode = prompt(“How many digits shall the code be? (1-6)”);

//verify input

if (enteredCode > 0 && enteredCode <= 6){

console.log(“We will be using “+ enteredCode+ ” digits in our code”);

codeVeritas = true;

return enteredCode;

} else{

alert(“number is out of range.”);

}

}

};

//gets numerals to be used in code

var numbers = function(){

var enteredNumber = 0;

var numbersVeritas = false;

while (numbersVeritas === false){

enteredNumber = prompt(“code will consist of numerals 1 – : (1-9)”);

if (enteredNumber>0 && enteredNumber <=9){

console.log(“We will be using numerals from 1 to “+ enteredNumber+ ” for our code”);

numbersVeritas = true;

return enteredNumber;

} else{

alert(“number is out of range.”);

numbersVeritas = false;

}

}

};

//sets up an array of numbers that will be the secret code

// code is the number of digits, number is the integers used for each digit

setSecretCode = function(code,numbers){

var secretCode = “0”;

var secret = [];

for (i=0; i < code; i++){

secret[i] = Math.floor(Math.random()*numbers+1);

}

return secret; // returns result to be used going forward

};

//accepts guess from user and parses it into an array of ‘code’ length

acceptGuess = function(code,numbers){

var guess = 0;

var guessDigit = [];

guess = prompt(“Make a guess at the secret code (“+code+”digits/1-“+numbers+”)”);

var codeNum = code * 1; // to transform code into a ‘number’

if (guess.length === codeNum){

for (i=0;i<code; i++){

guessDigit[i] =guess.substring(i,i+1);

}

return guessDigit;

} else {

console.log(“invalid guess”);

}

};

var compareGuess = function(code,secrets,guesses){

var green = 1-1; //right color, right position

var yellow = 1-1; //right color, wrong position

var white = 1-1; //wrong color

var guessedAlready=[];

var secretedAlready = [];

code = code*1; //converts code to a number type

//part 0: set ‘Already’ arrays to false

for (i=0; i<code; i++){

guessedAlready[i] = false;

secretedAlready [i]= false;

};

//part 1: check for perfect matches, alter guesses and secrets

//array positions to eliminate recount – count greens

for (i=0; i<code; i++){

guesses[i] = guesses[i] *1;

//console.log(“I’m in the first loop”);

//console.log(“guess”+i+”=”+guesses[i]+” of type “+typeof guesses[i]);

//console.log(“secret”+i+”=”+secrets[i]+” of type “+typeof secrets[i]);

if (guesses[i] === secrets[i] &&

guessedAlready[i] === false && secretedAlready[i] === false){

//console.log(“I’m in green”);

green++;

guessedAlready[i] = true;

secretedAlready[i] = true;

}

}

//part2: check for imperfect matches, alter guesses and secrets

//array positions to eliminate recount – count yellows

for(i=0; i<code; i++){

for (j=0; j<code; j++){

if (guesses[i] === secrets[j] &&

guessedAlready[i] === false && secretedAlready[j] === false){

yellow++;

guessedAlready[i] = true;

secretedAlready[j] = true;

}

}

}

//part 3: set white to number of unmatched items

//provide feedback to player

white = code – (green+yellow);

alert(green+” green    ” + yellow+” yellow”+ white+” white”);

console.log(green+” green ” + yellow+” yellow”+ white+” white”);

if (green === code){

exitShowResultLoop = true;

}

};

//main function

var guessArray = [];

var exitShowResultLoop = false;

var enteredCode = code(); // brings the variable  enteredCode out of the function

var enteredNumber = numbers(); // brings the variable enteredNumber out of the function

var secret = setSecretCode(enteredCode,enteredNumber);

//printout of array for debugging

console.log(“secret code is: “+ secret);

//play the game using a while loop to loop until correct guess is made

while (exitShowResultLoop === false){

guessArray = acceptGuess(enteredCode, enteredNumber);

console.log(“guess is: “+guessArray);

compareGuess(enteredCode, secret, guessArray);

}

console.log(“You’ve done it!!! Congratulations!!”);

 

Tags: , , , , , ,

function: compareGuess – the hardest one yet

First – I’m playing with some themes, so sorry about the fact that the site doesn’t look the same. I’m actually having a hell of a time getting things set up in a way that I am happy with and feel like I have sufficient control over.

Second -the new function: compareGuess. This one was a bear! I was wrestling with it forever before I finally got it to work correctly. Well, I hope it works correctly – I’ll post the whole program in the next post so that you can copy and paste it into a Javascript editor / compiler /whatever it’s called.

Why this one was hard is that, in the game, there are two ways you can ‘score’: if you get the right number in the right position, that’s the best(I’m calling that green). You can also get the right number in the wrong position (I’m calling that yellow). The problem is that these are mutually exclusive, with green trumping yellow in a manner of speaking. This is further complicated by the fact that once a number matches, you don’t want to use that same number to match again. This requires an example to illustrate…

secret code is: 112

guess is 123

The first position is a perfect match (green). But then the first position of the guess needs to be ignored when analyzing the rest of the code. If you just nest one loop inside another, you can easily get output of :

1 green

2 yellow

This is because position#1 of the guess matches position#1 of the code= green

but position #1 of the guess also matches position#2 of the code = yellow? -It’s not supposed to be, but how to fix?!?

then, position#2 of guess matches position#3 of the code = yellow (this one’s correctly attributed)

that gives us a total of three match signals when only two are a match!!

 

My solution (after a long time of playing around) was to add ‘guessedAlready’ and ‘secretedAlready’ Boolean Arrays within the function (It’s really important to keep these arrays private / privileged otherwise, you can run into problems when values get carried over from one guess to the next).

guessedAlready[0] refers to the first position of the guess, i.e. guess[0].

Then I set the arrays to false to start, added statements redefining them as true anytime a match was made and finally added qualifiers to my ‘if’ statements that check to see if each number was guessed already (or part of the secret code already) and therefore should be ignored.

This solution still ran into problems though until I separated my loops and looked for only exact matches (green) first, then went back and looked for inexact matches (yellow). Otherwise, if I found an inexact match in the secret code and then hid it, I couldn’t ‘see’ it for the exact match comparison later. Ughhh. example:

secret code: 112

guess : 212

if guess[0] matches code[2] as above, then we get a yellow peg for an inexact match and then we hide code[2] and don’t see that it should actually be an exact match with guess[2].

So, the function has two major parts. Part#1 loops and looks for greens. Part#2 loops and looks for yellows. Then I added a short Part#3 that sets the # of whites (no match) to white = code -(green+yellow), where code is the number of digits in the code.

I hope that makes sense. I tested this several times last night and it looked good. I will test it more later, but please feel free to make comments if you see a problem. Or ever better: if you can code and are still reading this for some reason, let me know if there is an easier way to solve this problem.

Here’s the code:

 

var compareGuess = function(code,secrets,guesses){

var green = 1-1; //right color, right position

var yellow = 1-1; //right color, wrong position

var white = 1-1; //wrong color

var guessedAlready=[];

var secretedAlready = [];

code = code*1; //converts code to a number type

//part 0: set ‘Already’ arrays to false

for (i=0; i<code; i++){

guessedAlready[i] = false;

secretedAlready [i]= false;

};

//part 1: check for perfect matches, alter guesses and secrets

//array positions to eliminate recount – count greens

for (i=0; i<code; i++){

guesses[i] = guesses[i] *1;

//console.log(“I’m in the first loop”);

//console.log(“guess”+i+”=”+guesses[i]+” of type “+typeof guesses[i]);

//console.log(“secret”+i+”=”+secrets[i]+” of type “+typeof secrets[i]);

if (guesses[i] === secrets[i] &&

guessedAlready[i] === false && secretedAlready[i] === false){

//console.log(“I’m in green”);

green++;

guessedAlready[i] = true;

secretedAlready[i] = true;

}

}

//part2: check for imperfect matches, alter guesses and secrets

//array positions to eliminate recount – count yellows

for(i=0; i<code; i++){

for (j=0; j<code; j++){

if (guesses[i] === secrets[j] &&

guessedAlready[i] === false && secretedAlready[j] === false){

yellow++;

guessedAlready[i] = true;

secretedAlready[j] = true;

}

}

}

//part 3: set white to number of unmatched items

//provide feedback to player

white = code – (green+yellow);

alert(green+” green    ” + yellow+” yellow”+ white+” white”);

console.log(green+” green ” + yellow+” yellow”+ white+” white”);

if (green === code){

exitShowResultLoop = true;

}

 

};

 

 

 

 

Tags: , , , , , , , ,

function: AcceptGuess

The next function I had to work out was how to accept the player’s guess in a way that would set up an array in a way that each digit of the player’s guess is an entry in the array. This would give me an array containing the secretCode generated by the computer and an array containing the guess generated by the user. All I’d have to do then, in cycle through the arrays to make comparisons (If only it was so easy).

So, this function proved to be quite simple:

 

 

//accepts guess from user and parses it into an array of ‘code’ length

acceptGuess = function(code,numbers){

    console.log(“***acceptGuess function reached***”);

    var guess = prompt(“Make a guess at the secret code (“+code+”digits/1-“+numbers+”)”);

    //need to add something to ensure guess is within parameters

        console.log(“guesslength is “+guess.length);

        console.log(“code is “+code);

        var codeNum = code * 1;

        console.log(typeof guess.length);

        console.log(typeof codeNum);

        if (guess.length === codeNum){

        console.log(“got inside the loop”);

            for (i=0;i>code; i++){

                console.log(“guess[i] = “+guess[i]);

                guessDigit[i] =guess.substring(i,i+1);

                console.log(guessDigit[i]);

            }

            return guessDigit;

        } else {

             console.log(“invalid guess”);

        }

};

The only problem I had with this was that the parameter ‘code’ comes through as a string. Note the two lines of code:

console.log(typeof guess.length);

console.log(typeof codeNum);

I’ve realized that the best way to debug is to have console.log lines everywhere that write out what is going on step by step. ‘typeof’ has been a very valuable code that I use whenever it looks like math isn’t working – so far it has uncovered the problem nearly 100% of the time.

Javascript will convert it to a ‘number’ if you do any mathematical function with the variable. An easy way to do this without messing anything up is to multiply by 1. To be even more careful, I created a new variable, ‘codeNum’, to hold this value as a number. The following line did that:

var codeNum = code * 1;

 

Last piece in my next post: comparing the values of the guess with the secret code. I just finished this 5 minutes ago after running myself ragged for several days (it was the reason I was dilly dallying about this posting)

 

 
Leave a comment

Posted by on July 3, 2012 in Uncategorized

 

Tags: , , , , , , ,