Reputation: 13
So I am trying to develop a Tic Tac Toe game for practice with javascript but I've hit a roadblock. I have an if statement that should be returning true but it isn't. Here is a sample.
var game = true;
var x = 'X';
var o = 'O';
var blank = '';
var turn = x;
var board = [blank, blank, blank,
blank, blank, blank,
blank, blank, blank];
function write() {
$('td').click(function() {
//Making sure that the block that was clicked can only be clicked once
var id = $(event.target).attr('id');
var digit = parseInt(id.slice(-1));
//check to see of the block has been clicked on
if (board[digit] = blank) {
board[digit] = turn;
$(board[digit]).html(turn.toUpperCase());
if (turn = x) {
turn = o;
} else if (turn = o) {
turn = x;
}
} else {
alert("That box has already been clicked on!")
}
});
}
Upvotes: 1
Views: 58
Reputation: 106
You have two issues at first glance.
First, event
is undefined. Define it as a function parameter in your .click
call.
$('td').click(function(event) { /* rest of the code */ }
Second, as Pointy commented, =
is for assignment, ==
and ===
are meant for comparisons.
Thus
if (board[digit] = blank) { /**/ }
needs to be
if (board[digit] === blank) { /**/ }
Regarding the difference between ==
and ===
you can get more information here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Short version, prefer ===
unless you're absolutely sure you know what you're doing and want to explicitly use ==
.
Upvotes: 1