I am currently working on creating a 2 player checkers game for my college project. However, I have hit a roadblock in determining the index of the 2D array when I click on a game piece.
The HTML code structure I have divided into:
- table - representing the game board
- row - each row corresponds to the height of the array
- cell - each cell represents a game piece and the width of the array
To initialize the game, I have set a default array as follows:
var board = [
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[2, 0, 2, 0, 2, 0, 2, 0],
[0, 2, 0, 2, 0, 2, 0, 2],
[2, 0, 2, 0, 2, 0, 2, 0],
];
Where: - 0 represents an empty cell - 1 represents Player 1's pieces - 2 represents Player 2's pieces
For determining the position, I am using the following code:
function getPosition() {
$('.row').on('click', function() {
console.log( $('.row').index(this) );
});
$('.cell').on('click', function() {
console.log( $('.cell').index(this) );
});
}
While I am able to successfully obtain the row index between 0 and 7, for the cell within the row, I am getting indices ranging from 0 to 63. This is causing confusion for the subsequent comparisons and game logic implementation.
You can view the code on CodePen at the following link: http://codepen.io/michaelthompson/pen/jVdrav