Guest User

Untitled

a guest
Sep 28th, 2019
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let arr = [
  3.         [false, false, false],
  4.         [false, false, false],
  5.         [false, false, false]
  6.     ];
  7.     let player = 'X';
  8.  
  9.     for (let line of input) {
  10.         [currRow, currCol] = line
  11.             .split(" ")
  12.             .map(Number);
  13.  
  14.         let theresFalse = false;
  15.  
  16.         for(let row = 0; row < arr.length; row++){
  17.             if(arr[row].includes(false)){
  18.                 theresFalse = true;
  19.             }
  20.         }
  21.  
  22.         if (!theresFalse) {
  23.             console.log("The game ended! Nobody wins :(");
  24.             printMatrix();
  25.             return;
  26.         }
  27.  
  28.         if (arr[currRow][currCol] !== false) {
  29.             console.log("This place is already taken. Please choose another!");
  30.             continue;
  31.         }
  32.  
  33.         arr[currRow][currCol] = player;
  34.  
  35.         //check horizontal and vertical
  36.         for (let i = 0; i < 3; i++) {
  37.             if (arr[i][0] === player &&
  38.                 arr[i][1] === player &&
  39.                 arr[i][2] === player) {
  40.                 console.log(`Player ${player} wins!`)
  41.                 printMatrix();
  42.                 return;
  43.             }
  44.  
  45.             else if (arr[0][i] === player &&
  46.                 arr[1][i] === player &&
  47.                 arr[2][i] === player) {
  48.                 console.log(`Player ${player} wins!`)
  49.                 printMatrix();
  50.                 return;
  51.             }
  52.         }
  53.  
  54.         //check left to right
  55.         if (arr[0][0] === player &&
  56.             arr[1][1] === player &&
  57.             arr[2][2] === player) {
  58.             console.log(`Player ${player} wins!`)
  59.             printMatrix();
  60.             return;
  61.         }
  62.  
  63.         //check right to left
  64.  
  65.         else if (arr[0][2] === player &&
  66.             arr[1][1] === player &&
  67.             arr[2][0] === player) {
  68.             console.log(`Player ${player} wins!`)
  69.             printMatrix();
  70.             return;
  71.         }
  72.  
  73.         player = player === "X" ? "O" : "X";
  74.     }
  75.  
  76.     function printMatrix(){
  77.         for(let row = 0; row < arr.length; row++){
  78.             console.log(arr[row].join("\t"));
  79.         }
  80.     }
  81.  
  82. }
Add Comment
Please, Sign In to add comment