Question

Looking to implement a game here, and I'm having trouble figuring out the best way to do it.

(This will be Tic-Tac-Toe expanded greatly).

Theoretically, if I have a multidimensional array in JS:

ie: var array = [ ["","",""], ["","",""], ["","",""] ]

And an HTML table for example:

<table id="board">
  <tr>
   <td>""</td><td>""</td><td>""</td>
  </tr>
  <tr>
   <td>""</td><td>""</td><td>""</td>
  </tr>
  <tr>
   <td>""</td><td>""</td><td>""</td>
  </tr>
</table>

How would I apply a click handler to the table to reference the indexed values in the array I have built?

For example,

array[1][1] should be equal to the 2nd child tr of the table, and the 2nd child td of the selected (or the technical middle square once I apply some CSS).

So, I need my click event to select your spot on the table to convert our array to...

array = [ ["","",""], ["","X",""], ["","",""] ]

I know it should be pretty simple. I already have the computer action working for selecting locations randomly, but I need the user input part and I'm brain farting.

(I'm OK to use jQuery for this functionality if its easier) Any help is appreciated!

Était-ce utile?

La solution

You can do tableElement.rows[1].cells[1] to get the xell at coordinates 1,1 from the top-left. You can then do anything you'd normally want to do with that.

You can also bind the event to the table, and then do [event.target.cellIndex, event.target.parentNode.rowIndex] to get the coordinates x,y within that event listener.

Autres conseils

Try this

$("tr:eq(x)  td:eq(y)").text();

Put your row and col for x and y

Using jQuery, you can do something like:

var rows = $('#board tr');

You can access that like an array: $(rows[2]) for the third row, etc.

To get the columns in a row, you can use jQuery's child queries:

var cols = $('td', rows[2]);

Note: if jQuery is in no conflict mode, you'll need to use jQuery instead of $or wrap it all in a jQuery closure.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top