Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Create my function using an ARROW FUNCTION
- // It is not necessary to write "= (userInput) =>"
- // because I have only 1 parameter
- const getUserChoice = userInput => {
- // Lowercase option: User can type "rock" or "Rock" or sth else
- const initialInput = userInput;
- userInput = userInput.toLowerCase();
- // Check if we have a valid string typed in
- if(userInput === "rock" || userInput === "paper" || userInput === "scissors" || userInput === "bomb"){
- return userInput;
- }
- else{
- console.log("Invalid option. You typed in '" + initialInput + "'");
- }
- };
- // Classic way for function declaring
- function getComputerChoice(){
- let choice = Math.floor(Math.random() * 3);
- switch(choice){
- case 0:
- return "rock";
- break;
- case 1:
- return "paper";
- break;
- case 2:
- return "scissors";
- break;
- default:
- console.log("Invalid option.");
- break;
- }
- }
- // Function, that determines the winner
- function determineWinner(userChoice, computerChoice){
- // Firstly, I will check if someone has found
- // the secret cheat code = "bomb"
- if(userChoice === "bomb"){
- console.log("User wins! He found the secret key-word to win!");
- }
- // If the game is a tie (3 tie-combinations out of the possible 9 ways)
- if(userChoice === computerChoice){
- console.log("It's a tie! Both sides chose: '" + userChoice + "'");
- }
- // 6 different combinations of NOT THE SAME CHOICE by user and computer
- else{
- // 1st combination of not a tie-game
- if(userChoice === "rock" && computerChoice === "scissors"){
- console.log("User wins")
- }
- // 2nd combination
- else if(userChoice === "rock" && computerChoice === "paper"){
- console.log("Computer wins");
- }
- // 3rd combination
- else if(userChoice === "scissors" && computerChoice === "paper"){
- console.log("User wins");
- }
- // 4th combination
- else if(userChoice === "scissors" && computerChoice === "rock"){
- console.log("Computer wins");
- }
- // 5th combination
- else if(userChoice === "paper" && computerChoice === "rock"){
- console.log("User wins");
- }
- // 6th combination
- else if(userChoice === "paper" && computerChoice === "scissors"){
- console.log("Computer wins");
- }
- } // End of else-case
- }
- function playGame(){
- const userChoice = getUserChoice("rock");
- const computerChoice = getComputerChoice();
- console.log(" User chooses : " + userChoice);
- console.log("Computer chooses: " + computerChoice);
- console.log();
- determineWinner(userChoice, computerChoice);
- }
- // Main part of the game
- playGame();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement