Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. const playingField = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
  2.  
  3. printInstruction()
  4. nextMove('X')
  5.  
  6. function printInstruction() {
  7. process.stdout.write('Cell\'s numbers:\n')
  8. printRow(1, 2, 3)
  9. printLine()
  10. printRow(4, 5, 6)
  11. printLine()
  12. printRow(7, 8, 9)
  13. }
  14.  
  15. function nextMove(player) {
  16.  
  17. const nextPlayer = player === 'X' ? 'Y' : 'X'
  18.  
  19. process.stdout.write(`You're playing for ${player}. Make a move by choosing a number from 1 to 9\n`)
  20.  
  21. process.stdin.once('data', function(data) {
  22.  
  23. if (isValidInput(data)) {
  24.  
  25. let arrayIndex = data - 1
  26. playingField[arrayIndex] = player
  27.  
  28. if (isEndofGame(arrayIndex)) {
  29. process.stdout.write('YOU WON!')
  30. } else {
  31. printCurrentField()
  32. nextMove(nextPlayer)
  33. }
  34. } else {
  35. nextMove(player)
  36. }
  37. })
  38. }
  39.  
  40. function printRow(x, y, z) {
  41. process.stdout.write(` ${x} | ${y} | ${z} \n`)
  42. }
  43.  
  44. function printLine() {
  45. process.stdout.write(`- - -|- - -|- - -\n`)
  46. }
  47.  
  48. function printCurrentField() {
  49. printRow(...playingField.slice(0, 3))
  50. printLine()
  51. printRow(...playingField.slice(3, 6))
  52. printLine()
  53. printRow(...playingField.slice(6, 9))
  54. }
  55.  
  56. function isValidInput(input) {
  57. if (0 < input && input < 10 ) {
  58. if (playingField[input - 1] !== ' ') {
  59. process.stdout.write('The cell is filled already. Try again \n')
  60. return false
  61. } else {
  62. return true
  63. }
  64. } else {
  65. process.stdout.write('This is not a valid number. Try again \n')
  66. return false
  67. }
  68. }
  69.  
  70. function isEndofGame(index) {
  71.  
  72. let winningCombinations = [
  73. [0, 1, 2],
  74. [3, 4, 5],
  75. [6, 7, 8],
  76. [0, 3, 6],
  77. [1, 4, 7],
  78. [2, 5, 8],
  79. [0, 4, 8],
  80. [2, 4, 6]
  81. ]
  82.  
  83. for (var index = 0; index < winningCombinations.length; index++) {
  84. if (allEqual(...winningCombinations[index])) {
  85. return true
  86. }
  87. }
  88. }
  89.  
  90. function allEqual(x, y, z) {
  91. if (playingField[x] !== ' ' &&
  92. playingField[x] === playingField[y] &&
  93. playingField[y] === playingField[z]) {
  94. return true
  95. }
  96. return false
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement