Step 7
Here are the solutions. Don't use a solution here until you've finished implementing all the missing pieces and debugged your implementation.
-
Implement
switchPlayer
Solution
// switches the player value from 0 to 1 and vice versa function switchPlayer() { player = player === 0 ? 1 : 0; }
-
Implement
checkRow
Solution
// returns true if all cells in the given row // are marked with the same marker, otherwise returns false function checkRow(row) { for (let col = 0; col < numCols; col++) { let index = toLinearIndex(row, col); if (board[index] !== markers[player]) return false; } return true; }
-
Implement
checkColumns
Solution
// returns true if all cells in a column // are marked with the same marker, otherwise returns false function checkColumns() { for (let col = 0; col < numCols; col++) { if (checkColumn(col)) return true; } return false; }
-
Implement
checkColumn
Solution
// returns true if all cells in the given column // are marked with the same marker, otherwise returns false function checkColumn(col) { for (let row = 0; row < numRows; row++) { let index = toLinearIndex(row, col); if (board[index] !== markers[player]) return false; } return true; }
-
Implement
checkMajorDiagonal
Solution
// returns true if all cells in the major diagonal // are marked with the same marker, otherwise returns false function checkMajorDiagonal() { for (let row = 0; row < numRows; row++) { let index = toLinearIndex(row, row); if (board[index] !== markers[player]) return false; } return true; }
-
Implement
checkMinorDiagonal
Solution
// returns true if all cells in the minor diagonal // are marked with the same marker, otherwise returns false function checkMinorDiagonal() { for (let row = 0; row < numRows; row++) { let index = toLinearIndex(row, numCols - row - 1); if (board[index] !== markers[player]) return false; } return true; }
-
Complete the implementation of
game
Solution
// the main event listener and the controller for the game function game(event) { if (gameIsOver) return window.alert( "This game has ended. Refresh the page for a new game!" ); let cell = event.target; let index = cell.id; if (board[index]) return window.alert("This cell has already been marked!"); // update the board board[index] = markers[player]; cell.classList.add(markers[player]); numEmptyCells--; updateGameStatus(); switchPlayer(); }
The app must be working now! Enjoy playing the Tic-Tac-Toe game 🎉
You can download the complete implementation from https://github.com/cs280fall20/tic-tac-toe.git.