Guest User

Untitled

a guest
Jan 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.39 KB | None | 0 0
  1. // API to read input from the command line in Node.js
  2. const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  3.  
  4. /**
  5. * Defines relations between options
  6. * [Key] wins against [value]
  7. * Example:
  8. * [schere] wins against [papier]
  9. */
  10. const rules = {
  11. schere: 'papier',
  12. stein: 'schere',
  13. papier: 'stein'
  14. }
  15.  
  16. // main function that initializes the game and handles user input
  17. function play() {
  18. /**
  19. * Ask the user which option they choose.
  20. * [answer] is the users input.
  21. */
  22. rl.question('\n✂️ Schere, 💎 Stein oder 🧻 Papier?\n\n', answer => {
  23. /**
  24. * Option chosen by the computer. But what is going on here?
  25. * `Object.keys ` returns all keys of the `rules` object
  26. * => ['schere', 'stein', 'papier']
  27. */
  28. const allOptions = Object.keys(rules)
  29.  
  30. /**
  31. * `Math.random() * 2` generates a random number between 0 and 2
  32. * => e.g. 1,235654
  33. * `Math.round` will round that number since an integer is needed to pick an option
  34. * => 1
  35. */
  36. const randomIndex = Math.round(Math.random() * 2)
  37.  
  38. /**
  39. * Pick the option based on the random index
  40. * => allOptions[1] === 'stein'
  41. */
  42. const computerChoice = allOptions[randomIndex]
  43.  
  44. /**
  45. * Capitalize the first letter of our option to use in the programs output.
  46. * Not needed but it is correct german.
  47. * `stein` => `Stein`
  48. */
  49. const capitalizedOption = capitalizeFirstLetter(computerChoice[0])
  50.  
  51. /**
  52. * Normalize the user input
  53. * `answer.toLowerCase()` normalizes the user input.
  54. * That means the user can capitalize how they want.
  55. * `'ScHEre'.toLowerCase()` => `schere`
  56. */
  57. const normalizedAnswer = answer.toLowerCase()
  58.  
  59. /**
  60. * Check if the users answer is a valid option.
  61. * `['schere', 'stein', 'papier'].includes('günther') === false`
  62. * The `!` negates the statement.
  63. * `!['schere', 'stein', 'papier'].includes('günther') === true`
  64. * In the case that the answer is not one of the options,
  65. * tell the user and start the game again.
  66. */
  67. if (!allOptions.includes(normalizedAnswer)) {
  68. return playAgain(`\n"${answer}" ist keine valide Option!\n`)
  69. }
  70.  
  71. /**
  72. * Check if the user and the computer chose the same option.
  73. * If that is the case, print a draw message and ask to play again.
  74. */
  75. if (normalizedAnswer === computerChoice) {
  76. return playAgain(`\nUnentschieden!\n`)
  77. }
  78.  
  79. /**
  80. * Decide who whon based on the rules object.
  81. * => `rules['stein'] === schere`
  82. * => `schere === schere`
  83. * => `true`
  84. * Computer wins
  85. *
  86. * => `rules['stein'] === stein`
  87. * => `schere === stein`
  88. * => `false`
  89. * User wins
  90. *
  91. * This works because we checked the possibility of both choices being the same earlier.
  92. * Rock, Paper, Scissors only has 3 options(draw, win, loose) and we checked one already.
  93. * And this only works because 1 option can only win against 1 other, not 2.
  94. * If rock would win against paper and scissors, this logic breaks
  95. * (and the game wouldn't be fair any more).
  96. */
  97. const computerWon = rules[computerChoice] === normalizedAnswer
  98.  
  99. /**
  100. * Initialize a variable for the game end message.
  101. */
  102. let gameEndMessage = ''
  103.  
  104. /**
  105. * Decide to print a win or loose message based on the game outcome.
  106. * `\n` Creates a new line in the terminal. It's like pressing enter.
  107. */
  108. if (computerWon) {
  109. gameEndMessage = `\nDu hast gegen ${capitalizedOption} verloren.\n`
  110. } else {
  111. gameEndMessage = `\n🎉 Du hast gegen ${capitalizedOption} gewonnen! 🎉\n`
  112. }
  113.  
  114. /**
  115. * Print the game end message and ask the user if they want to play again
  116. */
  117. playAgain(gameEndMessage)
  118. })
  119. }
  120.  
  121. /**
  122. * This function prints the given message, and asks the user if they want to play again.
  123. * If the user answers `ja` the game starts again.
  124. * Any other input stops the game and exits the program.
  125. */
  126. function playAgain(message) {
  127. console.log(message)
  128. rl.question('Noch einmal spielen? (Ja | Nein)\n\n', answer =>
  129. answer.toLowerCase() === 'ja' ? play() : rl.close()
  130. )
  131. }
  132.  
  133. /**
  134. * Start the game the first time
  135. */
  136. play()
  137.  
  138. /**
  139. * Small helper function that capitalizes the first letter of a string.
  140. * `capitalizeFirstLetter('dr. Strange')`
  141. * => `Dr. Strange`
  142. */
  143. function capitalizeFirstLetter (string) {
  144. return computerChoice[0].toUpperCase() + computerChoice.slice(1)
  145. }
Add Comment
Please, Sign In to add comment