I finally made my game work... The only problem is when I reset the page clicking on my reset button it would yes clear the board but It won't allow me to play any longer..How can I solve this problem?
HTML
<h1>Tic Tac Toe</h1>
<div id="message"> </div>
<button id="reset" > Reset</button>
<div class="console">
<div id="firstRow">
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<div id="box3" class="box"></div>
</div>
<div class="secondRow">
<div id="box4" class="box"></div>
<div id="box5" class="box"> </div>
<div id="box6" class="box"> </div>
</div>
<div class="thirdRow">
<div id="box7" class="box"></div>
<div id="box8" class="box"> </div>
<div id="box9" class="box"> </div>
</div>
</div>
JAVASCRIPT
var turn = "X";
var winner = null; // to change player's turnn at the begin
var nextMove = function(box) {
if(winner !== null){
setMessage(winner +" already won the game");
clearBox();
}
else if(box.innerHTML === ""){
box.innerHTML = turn;
switchTurn();
}
else {
setMessage("Choose another box.");
}
}
var startGame = function() {
for (var i =1; i <= 9; i++) { //clears all my boxes
clearBox(i);
}
setMessage(turn + " gets to start.");
}
var setMessage = function(msg) {
document.getElementById("message").innerHTML = msg;
}
function switchTurn() {
if(checkWinner(turn)) {
setMessage("Congratulations, " + turn + " wins!");
winner = turn; // whoever wins is gonna start the game
}
else if(turn === "X") {
turn = "O";
setMessage("It's " + turn + " turn.");
}
else {
turn = "X";
setMessage("Its " + turn + " turn.");
}
}
function checkWinner(move) {
var result = false;
if( checkRow(1, 2, 3, move) ||
checkRow(4, 5, 6, move) ||
checkRow(7, 8, 9, move) ||
checkRow(1, 4, 7, move) ||
checkRow(2, 5, 8, move) ||
checkRow(3, 6, 9, move) ||
checkRow(1, 5, 9, move) ||
checkRow(3, 5, 7, move)) {
result = true;
}
return result;
}
function checkRow(a, b, c, move) {
var result = false;
if(getBox(a) === move && getBox(b) === move && getBox(c) === move) {
result = true;
}
return result;
}
function getBox(number) {
return document.getElementById("box" + number).innerHTML;
}
function clearBox(number) {
return document.getElementById("box" + number).innerHTML = "";
}
var btnReset = document.getElementById('reset');
btnReset.addEventListener('click', function() {
startGame();
});
var consoleDiv = document.getElementsByClassName("console")[0];
consoleDiv.addEventListener("click", function(event) {
// event.target === the box to go in
nextMove(event.target);
var hasWon = checkWinner();
});
startGame();
Remove clearBox();
from your nextMove function and add winner = null;
to your btnReset.addEventListener('click', function() {
function.
Once the player won, winner was never set back to null therefore there was always a winner and since you check winner !== null
, below that you would call the clearBox()
which would then call the function without the required parameter and it would break your program.