Harry B. Harry B. - 1 month ago 6
Javascript Question

How do I Reset page in html?

I'm building a tic-tac-toe game and I want the board to reset once one player has won.

As of now, when someone gets three in a row, the board disappears as per the

.remove
function I am using, but
game.newgame
is not being called and I'm not sure why.

Here is the code snippet:

var gameboard = {

initialize: function() {
for(var x = 0; x < 3; x++) {
for(var y = 0; y < 3; y++) {
var unit = $("<div class='unit'></div>");
unit.appendTo('#gameboard');
}
}
console.log(100);
gameboard.addId();
},

addId: function() {
var id = 1
$('.unit').each(function() {
$(this).attr('id', id);
id++;
});
}
};

var game = {

newGame: gameboard.initialize(),

currentPlayerTurn: players.firstPlayer.token,

displayToken: function() {
$('.unit').click(function() {
if(game.currentPlayerTurn === 'X' && !$(this).hasClass('selected')) {
$(this).addClass('selected').removeClass('unit').text("X");
game.currentPlayerTurn = players.secondPlayer.token;
} else if(game.currentPlayerTurn === 'O' && !$(this).hasClass('selected')) {
$(this).addClass('selected').removeClass('unit').text("O");
game.currentPlayerTurn = players.firstPlayer.token;
}
game.win($(this));
//console.log($(this));
})
},

win: function(div) {

game.winCombos.forEach(function(element) {
element.forEach(function(unitIndex){
if(unitIndex.toString() === div.attr('id').toString()) {
var elementIndex = game.winCombos.indexOf(element);
var unitIndex = element.indexOf(unitIndex);
game.winCombos[elementIndex][unitIndex] = game.currentPlayerTurn;
}

var counter = 0

for (var i = 0; i < element.length; i++) {
if (element[i] === game.currentPlayerTurn) {
counter ++;
}

if(counter === 3) {
game.gameOver(true);

}


}

})
})
},

gameOver: function(bool) {
if (bool === undefined) {
bool = false;
}
$('.unit').remove();
$('.selected').remove();
game.newGame;
},

winCombos: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]

Answer

That newGame function should just be a reference to gameboard.initialize. There's no point in storing the extra reference.

Remove this line:

newGame: gameboard.initialize(),

And replace:

game.newGame;

with

gameboard.initialize();