dabidabidesh

ticTacToe

Sep 24th, 2020
323
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ticTacToe = arr => {
  2.   'use-strict'
  3.  
  4.   let dashBoard = [[false, false, false],
  5.   [false, false, false],
  6.   [false, false, false],]
  7.  
  8.   const isWinning = char => {
  9.     let leftDiagonal = dashBoard[0][0] + dashBoard[1][1] + dashBoard[2][2]
  10.     let rightDiagonal = dashBoard[0][2] + dashBoard[1][1] + dashBoard[2][0]
  11.     if (char.repeat(3) === leftDiagonal || char.repeat(3) === rightDiagonal)
  12.       return true
  13.     for (let i = 0; i < 3; i++) {
  14.       let horizontal = dashBoard[i].reduce((a, c) => a + c, '')
  15.       let vertical = dashBoard
  16.         .map((x) => x[i])
  17.         .reduce((a, c) => a + c, '')
  18.       if (char.repeat(3) === horizontal || char.repeat(3) === vertical)
  19.         return true
  20.     }
  21.     return false
  22.   }
  23.  
  24.   let flag = true
  25.   let count = 0
  26.  
  27.   for (const el of arr) {
  28.     let [row, col] = el.split(' ')
  29.  
  30.     if (dashBoard[row][col] === 'X' || dashBoard[row][col] === 'O')
  31.       console.log('This place is already taken. Please choose another!')
  32.     else {
  33.       if (flag) {
  34.         flag = false
  35.         dashBoard[row][col] = 'X'
  36.         if (isWinning('X')) {
  37.           console.log(`Player X wins!`)
  38.           break
  39.         }
  40.       }
  41.       else {
  42.         flag = true
  43.         dashBoard[row][col] = 'O'
  44.         if (isWinning('O')) {
  45.           console.log(`Player O wins!`)
  46.           break
  47.         }
  48.       }
  49.       count++
  50.       if (count === 9) {
  51.         console.log('The game ended! Nobody wins :(')
  52.         break
  53.       }
  54.     }
  55.   }
  56.   console.log(dashBoard.map(row => row.join('\t')).join('\n'))
  57. }
RAW Paste Data