Currently, I am working on a JavaScript version of the well-known board game "Mastermind".
I have been facing some fundamental issues, mainly with JavaScript arrays and how to reference their values or elements. Despite spending quite a bit of time trying to solve these problems on my own, I have decided to seek help.
Key Points:
The game pegs and the game board are created using an HTML table. Each row consists of 4 pegs and a td element containing the results image, implemented in the following manner:
<td> <a href="javascript:void(0)" onClick="changePegColor('0','0'); return false" onFocus="this.blur()"> <img src="img/void.png" width=22 height=22 name="peg_0_0"> </a> </td>
My attempts at declaring default arrays have not been successful so far, as shown in the examples below:
var pegsAI = ['pegAI_0', 'pegAI_1', 'pegAI_2', 'pegAI_3']; var pegsAI = new Array('pegAI_0', 'pegAI_1', 'pegAI_2', 'pegAI_3');
The process for setting AI's pegs, which the player needs to guess, is functioning correctly without any array-related issues:
pegsAI[position] = Math.floor((Math.random() * possibleColorsNumber));
However, here are the specific issues I am encountering:
Upon clicking the Submit button, there is a check to ensure that every peg in a row has a color assigned. The current implementation is not yielding the desired result and does not throw errors in Chrome Developer Tools:
... for (var position = 0; position <= 3; position++) { if (document["peg_" + currentRow + "_" + position].src === "img/void.png") { alert('Finish color picking!'); return false; } } ...
Following this check, there is a function intended to convert the players' pegs into numbers, which should then be saved in an array. However, this conversion process seems to be faulty as the array ends up with 'undefined' values:
function convertToNumbers() { for (var position = 0; position <= 3; position++) { if (document["peg_" + currentRow + "_" + position].src === possibleColors[index]) { pegsPlayer[position] = index; } } }
///added for explanation
A snippet from my score calculation function:
var goodPegPlayer = [false, false, false, false];
var goodPegAI = [false, false, false, false];
function calcSkore() {
convertToNumbers();
alert("array values" + pegsPlayer[0] + "_" + pegsPlayer[1] + "_" + pegsPlayer[2] + "_" + pegsPlayer[3]);
// more code follows here
// Please note the usage of alert() after convertToNumbers()
}
To summarize, the challenges I'm facing primarily revolve around array manipulation and referencing within the context of my Mastermind game project.