Advertisement
elena1234

Tic-Tac-Toe - work with matrix JavaScript

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