Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solution(arr = []) {
- const board = [
- ['false', 'false', 'false'],
- ['false', 'false', 'false'],
- ['false', 'false', 'false']
- ];
- function solve(array) {
- let toContinue = '';
- for (let i = 0; i < array.length; i += 2) {
- if (toContinue === 'X' || toContinue === '') {
- const playerXmoves = array[i].split(' ');
- let rowX = Number(playerXmoves[0]);
- let colX = Number(playerXmoves[1]);
- if (board[rowX][colX] === 'false') {
- board[rowX][colX] = 'X';
- } else {
- console.log('This place is already taken. Please choose another!');
- array.splice(i, 1, array[i + 2]);
- i--;
- toContinue = 'X';
- continue;
- }
- }
- if (i + 1 === array.length || i === 8) {
- break;
- }
- if ((board[0][0] === 'X' && board[0][1] === 'X' && board[0][2] === 'X') ||
- (board[0][0] === 'X' && board[1][0] === 'X' && board[2][0] === 'X') ||
- (board[0][0] === 'X' && board[1][1] === 'X' && board[2][2] === 'X')) {
- return console.log('Player X wins!');
- }
- if(toContinue==='O'||toContinue===''){
- const playerOMoves = array[i + 1].split(' ');
- let rowO = Number(playerOMoves[0]);
- let colO = Number(playerOMoves[1]);
- if (board[rowO][colO] === 'false') {
- board[rowO][colO] = 'O';
- } else {
- console.log('This place is already taken. Please choose another!');
- array.splice(i+1, 1, array[i + 3]);
- i--;
- toContinue = 'O';
- console.log(array);
- continue;
- }
- }
- if ((board[0][0] === 'O' && board[0][1] === 'O' && board[0][2] === 'O') ||
- (board[0][0] === 'O' && board[1][0] === 'O' && board[2][0] === 'O') ||
- (board[0][0] === 'O' && board[1][1] === 'O' && board[2][2] === 'O')) {
- return console.log('Player O wins!');
- }
- toContinue='X';
- }
- console.log(board);
- console.log('The game ended! Nobody wins :(');
- }
- solve(arr);
- for (let i = 0; i < board.length; i++) {
- console.log(board[i].join('\t'));
- }
- }
- solution(['0 0',
- '0 0',
- '1 1',
- '0 1',
- '1 2',
- '0 2',
- '2 2'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement