From 621bc77e2af4b841972b17a809979daf0afbc967 Mon Sep 17 00:00:00 2001 From: uhuru3 Date: Sun, 28 Oct 2018 18:14:10 -0700 Subject: [PATCH] TicTacToe completed --- 03week/ticTacToe.js | 94 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/03week/ticTacToe.js b/03week/ticTacToe.js index 1abf5b900..9f62668f9 100644 --- a/03week/ticTacToe.js +++ b/03week/ticTacToe.js @@ -25,22 +25,116 @@ function printBoard() { function horizontalWin() { // Your code here + if (board[0][0] != " " && board[0][0] == board[0][1] && board[0][2]==board[0][0]){ + return true; + } + if (board[1][0] != " " && board[1][0] == board[1][1] && board[1][2]==board[1][0]){ + return true; + } + if (board[2][0] != " " && board[2][0] == board[2][1] && board[2][2]==board[2][0]){ + return true; + } + } function verticalWin() { // Your code here + if (board[0][0] != " " && board[0][0] == board[1][0] && board[2][0]==board[0][0]){ + + return true; + } + if (board[0][1] != " " && board[0][1] == board[1][1] && board[2][1]==board[0][1]){ + + return true; + } + if (board[0][2] != " " && board[0][2] == board[1][2] && board[2][2]==board[0][2]){ + + return true; + } } function diagonalWin() { // Your code here + if (board[0][0] != " " && board[0][0] == board[1][1] && board[2][2]==board[0][0]){ + return true; + } + if (board[0][2] != " " && board[0][2] == board[1][1] && board[2][0]==board[0][2]){ + return true; + } } function checkForWin() { // Your code here + return horizontalWin() || verticalWin() || diagonalWin(); +} + +const resetGame=()=>{ + board.forEach(element => { + element.fill(" "); + }); + playerTurn = 'X'; } +const isValid =(row, column)=>{ + if(row == '0' || row == '1' || row == '2'){ + if(column == '0' || column == '1' || column == '2'){ + return true; + } + } +}; + +const isEmpty =(row, column)=>{ + if(board[row][column] == ' '){ + return true; + } +}; + +const draw =()=>{ + for(let i = 0; i < board.length; i++){ + if (board[i].includes(' ')){ + return false; + } + } + return true; +}; + function ticTacToe(row, column) { // Your code here + // user selelects position on the board to place their mark + // make sure it is a valid pick, isValid() T/F + // make sure the place is empty, isEmpty() T/F + // put the mark + // check win, checkForWin() + // swich user, swithUser() + // check for draw, checkForDraw() + if (isValid(row, column)){ + if (isEmpty(row, column)){ + board[row][column] = playerTurn; + if (checkForWin()){ + console.log(playerTurn + ' Wins!'); + resetGame(); + }else{ + if (draw()){ + console.log('Draw! No One Wins, Restart Game'); + resetGame(); + }else{ + switchPlayer() + } + } + }else{ + console.log('Pick An Empty Space') + } + }else{ + console.log('Enter Valid Entry!') + } +} + +const switchPlayer =()=>{ + if(playerTurn == 'X'){ + playerTurn = 'O'; + }else{ + playerTurn = 'X'; + } } function getPrompt() {