I’m making a tic-tac-toe game.
How would I change the following code so that the winner could be declared before complete is true, (every square filled) and the winner is the first to achieve 3 matching values, not the last to achieve it?
function check_squares () {
var values = new Array();
var complete = true;
$('.square').each(function () {
values.push( $(this).html() );
//if ($(this).html() == '') complete = false;
});
if (complete == true) {
var winner = false;
if ( values[0] == values[1] && values[1] == values[2] ) winner = values[0];
if ( values[3] == values[4] && values[4] == values[5] ) winner = values[3];
if ( values[6] == values[7] && values[7] == values[8] ) winner = values[6];
if ( values[0] == values[3] && values[3] == values[6] ) winner = values[0];
if ( values[1] == values[4] && values[4] == values[7] ) winner = values[1];
if ( values[2] == values[5] && values[5] == values[8] ) winner = values[2];
if ( values[0] == values[4] && values[4] == values[8] ) winner = values[0];
if ( values[2] == values[4] && values[4] == values[6] ) winner = values[2];
if (winner) {
$('#output').html('Winner: ' + winner);
} else {
$('#output').html('No Winner');
}
} else {
if (player_x == true) {
$('#output').html('x turn to move');
} else {
$('#output').html('o turn to move');
}
}
}
Your function is almost correct. Mainly, you just need to call it each time that a player changes a cell’s value.
I have tweaked your function a little bit to allow it to be called multiple times. I have added comments to the sections that I changed to make them easier to find.
I have created a simple JSFiddle to see a working example.