From 3304212dceca0771563c0a7ae6c48c273d6b3979 Mon Sep 17 00:00:00 2001 From: hWeitian Date: Sat, 28 Aug 2021 16:01:18 +0800 Subject: [PATCH] secret word - base --- script.js | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/script.js b/script.js index bbe8a29..4ccfbfa 100644 --- a/script.js +++ b/script.js @@ -1,4 +1,65 @@ +var correctCount = 0; +var guessCorrectlyToWin = 2; + var main = function (input) { - var myOutputValue = 'hello world'; + // Generate the random secret word + var secretWord = computerChoice(); + + // Check if user has guessed correctly + var correctOrWrongGuess = didUserGuessedCorrectly(input, secretWord); + + // Check if user wins + var userWin = didUserWin(correctCount); + + var myOutputValue = `You guessed ${input}. The secret word is ${secretWord}.

${correctOrWrongGuess}.

${userWin}.`; + return myOutputValue; }; + +// Function to generate random secret word +var computerChoice = function () { + // Generate random number + var randomNum = Math.floor(Math.random() * 3); + + // Assign the random number generated to each secret word + if (randomNum == 0) { + var randomSecretWord = "banana"; + } + if (randomNum == 1) { + var randomSecretWord = "chisel"; + } + if (randomNum == 2) { + var randomSecretWord = "faucet"; + } + return randomSecretWord; +}; + +// Function to check if user's input is equals to the random secret word generated by the computer +var didUserGuessedCorrectly = function (userInput, secretWord) { + var results = `You are wrong`; + if (userInput == secretWord) { + correctCount = correctCount + 1; + var results = `You are correct`; + } + return results; +}; + +// Function to check the number of times that user has guessed correctly +var didUserWin = function (input) { + var winResults = `Try Again!`; + + // If the number of times user guessed correctly is equals to the number of times required to win, the program will output user wins + if (input == guessCorrectlyToWin) { + correctCount = 0; + winResults = `You have guessed 2 times correctly.

You Won! Submit an input to play again!`; + return winResults; + } + + // If the number of times user guessed correctly is lesser than the number of times required to win, the program will output the remaining number of times required + if (input < guessCorrectlyToWin) { + var correctCountRequired = guessCorrectlyToWin - input; + winResults = `You have guessed ${input} times correctly.

You need to guess ${correctCountRequired} more correct guess to win`; + } + + return winResults; +};