Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement