Skip to content

Instantly share code, notes, and snippets.

@oksmelnik
Last active June 9, 2019 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oksmelnik/0d3c899ba0d4be511009bf779f58e424 to your computer and use it in GitHub Desktop.
Save oksmelnik/0d3c899ba0d4be511009bf779f58e424 to your computer and use it in GitHub Desktop.
Terminal based TicTacToe game built with Node.js
const playingField = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
printInstruction()
nextMove('X')
function printInstruction() {
process.stdout.write('Cell\'s numbers:\n')
printRow(1, 2, 3)
printLine()
printRow(4, 5, 6)
printLine()
printRow(7, 8, 9)
}
function nextMove(player) {
const nextPlayer = player === 'X' ? 'Y' : 'X'
process.stdout.write(`You're playing for ${player}. Make a move by choosing a number from 1 to 9\n`)
process.stdin.once('data', function(data) {
if (isValidInput(data)) {
let arrayIndex = data - 1
playingField[arrayIndex] = player
if (isEndofGame(arrayIndex)) {
process.stdout.write('YOU WON!')
} else {
printCurrentField()
nextMove(nextPlayer)
}
} else {
nextMove(player)
}
})
}
function printRow(x, y, z) {
process.stdout.write(` ${x} | ${y} | ${z} \n`)
}
function printLine() {
process.stdout.write(`- - -|- - -|- - -\n`)
}
function printCurrentField() {
printRow(...playingField.slice(0, 3))
printLine()
printRow(...playingField.slice(3, 6))
printLine()
printRow(...playingField.slice(6, 9))
}
function isValidInput(input) {
if (0 < input && input < 10 ) {
if (playingField[input - 1] !== ' ') {
process.stdout.write('The cell is filled already. Try again \n')
return false
} else {
return true
}
} else {
process.stdout.write('This is not a valid number. Try again \n')
return false
}
}
function isEndofGame(index) {
let winningCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
for (var index = 0; index < winningCombinations.length; index++) {
if (allEqual(...winningCombinations[index])) {
return true
}
}
}
function allEqual(x, y, z) {
if (playingField[x] !== ' ' &&
playingField[x] === playingField[y] &&
playingField[y] === playingField[z]) {
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment