我正在構建一個井字棋遊戲,我希望一旦一名玩家獲勝,棋盤就可以重置。如何重置html頁面?
截至目前,當有人連續三人時,按照我使用的.remove
函數消失,但game.newgame
沒有被調用,我不知道爲什麼。
這裏是代碼片段:
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]]
嘗試用'game.newGame()替換'game.newGame;';' – Cerbrus