Last active
December 8, 2017 03:42
-
-
Save northamerican/a17e3dc2cdc8ddc153cadaefeedf8394 to your computer and use it in GitHub Desktop.
console tic tac toe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tic tac toe | |
// paste into console, type play(x,y) to take turn | |
// ex: play(2,2) plays bottom right corner tile | |
const boardInit = () => [[null, null, null],[null, null, null],[null,null,null]] | |
const players = ['o', 'x'] | |
let board = boardInit() | |
let currentPlayerIndex = 0; | |
const currentPlayer = () => players[currentPlayerIndex] | |
const nextPlayer = () => currentPlayerIndex = +!currentPlayerIndex | |
const winningCombo = () => Array(3).fill(currentPlayer()).join('') | |
const play = (x,y) => { | |
console.log(`${currentPlayer()} plays ${x}, ${y}`) | |
if(board[y][x] !== null) { | |
console.log(`tile already played`) | |
console.log(`still ${currentPlayer()}'s turn`) | |
return | |
} | |
board[y][x] = currentPlayer() | |
checkWin() | |
nextPlayer() | |
console.table(board) | |
} | |
const checkWin = () => { | |
const checkVert = () => board.forEach(row => { | |
if(row.join('') === winningCombo()) win() | |
}) | |
const checkHoriz = () => { | |
for(let x = 0; x < 3; x++) { | |
let col = []; | |
for(let y = 0; y < 3; y++) { | |
col.push(board[y][x]) | |
} | |
if(col.join('') === winningCombo()) win() | |
} | |
} | |
const checkDiag = () => { | |
[ | |
[board[0][0], board[1][1], board[2][2]], | |
[board[0][2], board[1][1], board[2][0]] | |
].forEach(diag => { | |
if(diag.join('') === winningCombo()) win() | |
}) | |
} | |
checkVert(); | |
checkHoriz(); | |
checkDiag(); | |
} | |
const win = (piece) => { | |
console.table(board) | |
console.log(`${currentPlayer()} wins!`) | |
board = boardInit() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment