Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(input){
- const dashboard = [
- [false, false, false],
- [false, false, false],
- [false, false, false]
- ];
- let currentPlayer = 'X';
- for (const line of input) {
- let [row, col] = line.split(' ').map(Number);
- if (dashboard[row][col] === false){
- dashboard[row][col] = currentPlayer;
- // check for winner
- if (checkWinner(dashboard, row, col)){
- console.log(`Player ${dashboard[row][col]} wins!`);
- break;
- }else{
- if(isFinished(dashboard)){
- console.log(`The game ended! Nobody wins :(`);
- break;
- }
- }
- //if winner => BREAk!
- currentPlayer = currentPlayer === 'X'? 'O':'X';
- }else{
- console.log('This place is already taken. Please choose another!');
- }
- }
- return dashboard.map(x=>x.join('\t')).join('\n');
- ////////
- ////////
- ////////
- function checkWinner(mtrx, r, c){
- if(
- mtrx[r][0] === mtrx[r][1] && mtrx[r][0] === mtrx[r][2] ||
- mtrx[0][c] === mtrx[1][c] && mtrx[0][c] === mtrx[2][c] ||
- mtrx[0][0] === mtrx[1][1] && mtrx[0][0] === mtrx[2][2] && mtrx[0][0] !== false ||
- mtrx[0][2] === mtrx[1][1] && mtrx[0][2] === mtrx[2][0] && mtrx[0][2] !== false
- ){
- return true;
- }
- return false;
- }
- function isFinished(mtrx){
- for(let row = 0; row < mtrx.length; row++){
- for(let col = 0; col < mtrx[row].length; col++){
- if(mtrx[row][col] === false){
- return false;
- }
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment