Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. function solution(arr = []) {
  2. const board = [
  3. ['false', 'false', 'false'],
  4. ['false', 'false', 'false'],
  5. ['false', 'false', 'false']
  6. ];
  7. function solve(array) {
  8. let toContinue = '';
  9. for (let i = 0; i < array.length; i += 2) {
  10. if (toContinue === 'X' || toContinue === '') {
  11. const playerXmoves = array[i].split(' ');
  12. let rowX = Number(playerXmoves[0]);
  13. let colX = Number(playerXmoves[1]);
  14.  
  15. if (board[rowX][colX] === 'false') {
  16. board[rowX][colX] = 'X';
  17. } else {
  18. console.log('This place is already taken. Please choose another!');
  19. array.splice(i, 1, array[i + 2]);
  20. i--;
  21. toContinue = 'X';
  22. continue;
  23. }
  24. }
  25.  
  26. if (i + 1 === array.length || i === 8) {
  27. break;
  28. }
  29.  
  30. if ((board[0][0] === 'X' && board[0][1] === 'X' && board[0][2] === 'X') ||
  31. (board[0][0] === 'X' && board[1][0] === 'X' && board[2][0] === 'X') ||
  32. (board[0][0] === 'X' && board[1][1] === 'X' && board[2][2] === 'X')) {
  33. return console.log('Player X wins!');
  34. }
  35.  
  36. if(toContinue==='O'||toContinue===''){
  37. const playerOMoves = array[i + 1].split(' ');
  38. let rowO = Number(playerOMoves[0]);
  39. let colO = Number(playerOMoves[1]);
  40.  
  41. if (board[rowO][colO] === 'false') {
  42. board[rowO][colO] = 'O';
  43. } else {
  44. console.log('This place is already taken. Please choose another!');
  45. array.splice(i+1, 1, array[i + 3]);
  46. i--;
  47. toContinue = 'O';
  48. console.log(array);
  49. continue;
  50. }
  51. }
  52.  
  53. if ((board[0][0] === 'O' && board[0][1] === 'O' && board[0][2] === 'O') ||
  54. (board[0][0] === 'O' && board[1][0] === 'O' && board[2][0] === 'O') ||
  55. (board[0][0] === 'O' && board[1][1] === 'O' && board[2][2] === 'O')) {
  56. return console.log('Player O wins!');
  57. }
  58. toContinue='X';
  59. }
  60. console.log(board);
  61. console.log('The game ended! Nobody wins :(');
  62.  
  63. }
  64. solve(arr);
  65.  
  66. for (let i = 0; i < board.length; i++) {
  67. console.log(board[i].join('\t'));
  68. }
  69. }
  70. solution(['0 0',
  71. '0 0',
  72. '1 1',
  73. '0 1',
  74. '1 2',
  75. '0 2',
  76. '2 2'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement