Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const readline = require("readline-sync")
- let debugLog = (text, val) => console.log(text + ":" + val)
- let getUserInput = (entry) => readline.question(entry + " ")
- let gameText = {
- startText: "Hi, can you guess the word",
- errorText: "Sorry, try again",
- lifeText: "Here your lifes:",
- winText: "Good You've won",
- loseText: "Sorry you've lost",
- inputText: "please choose character:"
- }
- class GameConfig {
- static getWordList() {
- return ["wordFirst", "wordSecond", "wordThird"]
- }
- static getLifes() {
- return 10
- }
- }
- class RandomWordGenerator {
- static makeRandomWord(wordList) {
- let len = wordList.length;
- let rndNum = Math.floor(Math.random() * len)
- return wordList[rndNum]
- }
- }
- class Game {
- constructor() {
- this.lifes = GameConfig.getLifes()
- this.secretWordObj = new SecretWord()
- }
- init() {
- console.log(gameText.startText)
- this.gameLoop()
- }
- gameLoop() {
- while(this.isPlaying()) {
- let secretWord = this.secretWordObj.getSecretWord()
- console.log(gameText.lifeText + this.lifes)
- console.log(secretWord)
- let userInput = getUserInput(gameText.inputText)
- let guessResult = this.secretWordObj.guessChar(userInput)
- console.clear()
- if(guessResult) {
- this.secretWordObj.insertChar(guessResult)
- } else {
- this.lifes--
- console.log(gameText.errorText)
- }
- }
- }
- isPlaying() {
- if(this.checkWinCondition()) {
- console.log(gameText.winText)
- return false
- }
- if(this.checkLoseCondition()) {
- console.log(gameText.loseText)
- return false
- }
- return true
- }
- checkWinCondition() {
- let length = this.secretWordObj.getSecretWord().length
- let guessedChars = this.secretWordObj.getGuessedChars()
- if(length == guessedChars) {
- return true
- }
- return false
- }
- checkLoseCondition() {
- if(!this.lifes) {
- return true
- }
- return false
- }
- }
- class SecretWord {
- constructor() {
- this.word = []
- this.secretWord = []
- this.guessedChars = 0
- let randomWord = RandomWordGenerator.makeRandomWord(GameConfig.getWordList())
- this._setWord(randomWord)
- this._setSecretWord()
- }
- _setWord(word) {
- this.word = word.split("")
- }
- _setSecretWord() {
- for(let char in this.word) {
- this.secretWord.push("*")
- }
- }
- getSecretWord() {
- return this.secretWord.join("")
- }
- getGuessedChars() {
- return this.guessedChars
- }
- guessChar(char) {
- for(let item in this.word) {
- if(this.word[item] == char) {
- let guessedChar = {
- char: this.word[item],
- index: item
- }
- delete this.word[item]
- return guessedChar
- }
- }
- return false
- }
- insertChar(charObj) {
- this.secretWord[charObj.index] = charObj.char
- this.guessedChars++
- }
- }
- new Game().init()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement