3

I am trying to develop a 2 player checkers game, for my college, but I am stuck at getting the index of the 2D array when I click on the piece.

I divided my HTML code in:

  • table - the game board
  • row - each row is the height of the array
  • cell - each cell is a piece and the width of the array

Then I setted a default array to start the game:

  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 the: - 0 - empty cell - 1 - Player 1 pieces - 2 - Player 2 pieces

To get the position I am using this code

function getPosition() {
  $('.row').on('click', function() {
    console.log( $('.row').index(this) );
  });
  $('.cell').on('click', function() {
    console.log( $('.cell').index(this) );
  });
}

Get the height array position which should be between 0 and 7 are ok, but the cell from the row should be between 0 and 7 too, but using this I am getting from 0 to 63, using this parameters I have no idea how to start the next comparisons of the game.

Here is the code from codepen http://codepen.io/michaelthompson/pen/jVdrav

2
  • change to console.log( $('.cell', this.parentElement).index(this) ); to get the index within the current row Commented Dec 18, 2016 at 23:04
  • 1
    or $('.cell').index(this) % 8 Commented Dec 18, 2016 at 23:05

1 Answer 1

4

In each instance you can simply use $(this).index() which will return the index within the element's siblings

But since clicking on a row always means clicking a cell you could combine them and do

$('.cell').on('click', function() {
   var $cell = $(this),  
       columnIndex = $cell.index(),
       rowIndex = $cell.parent().index();
});

What $('.cell').index(this) is doing is taking the whole collection of the class within the page and that's why you are getting 0-63

Sign up to request clarification or add additional context in comments.

1 Comment

Did this answer help you? If so, feel free to accept it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.