111sree 111sree - 4 months ago 5
jQuery Question

how to compute tic-tac-toe board and find out match_status in javascript

i have created a javascript for tic-tak-toe.the input is given to the html using $('td').text("X")and$('td').text("O") for 2player,also i declared an array of winning combination.Now my problem is how to validate(function match_status() the board and determine the winner/loser or the match is drawn

$(document).ready(function(){
var count=0;
$('td').on('click',function(event)
{
if(count%2!=0)
{
$(this).text("X");
$("p").toggle('fast', function(){
$("h2").text('player one');
});
}
else
{
$(this).text("O");
$("p").toggle('fast', function(){
$("h2").text('player two');
});
}
count++;
checkboard(this.id);
});
//td ids
var wins = [["#0","#1","#2"], ["#3","#4","#5"], ["#6","#7","#8"], ["#0","#4","#8"], ["#2","#4","#6"], ["#0","#3","#6"], ["#1","#4","#7"], ["#2","#5","#8"]];
function checkboard()
{


for (var i=0; i<wins.length; i++)
{
var w = wins[i];
var checkXwin = $(w[0].val()) == "X" && w[1].val() == "X" && w[2].val() == "X";
var checkOwin = w[0].val() == "O" && w[1].val() == "O" && w[2].val() == "O";
if (checkXwin)
{
alert("X Wins!");
}
}

Answer

Try the following in the checkBoard function.

Change $(w[0].val()) to $(w[0]).text(). The $(w[0]) will pick the element by id, and .text() will pick the text without any formatting - so X or O in your case. Do that for each check. And I do mean each check. w[1].val() == "X" is incorrect. w[1] is a string, not an object.

The difference is that $(w[0].val()) is not an element, but $(w[0]) is, and then you can get the text from this element.