Advertisement
makispaiktis

1. Codecademy Intro - Rock Paper Scissors

Oct 17th, 2024 (edited)
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 1. Random Choice
  2. function getComputerChoice(){
  3.     random = Math.floor(3 * Math.random());
  4.     switch(random){
  5.         case 0:
  6.             return 'rock';
  7.         case 1:
  8.             return 'paper';
  9.         case 2:
  10.             return 'scissors';
  11.         default:
  12.             console.log('IMPOSSIBLE RANDOM NUMBER');
  13.             return -1000;
  14.     }
  15. }
  16.  
  17. // 2. User Choice
  18. const getUserChoice = userInput => {
  19.     userInput = userInput.toLowerCase();
  20.     flag = (userInput === 'rock') || (userInput === 'paper') || (userInput === 'scissors');
  21.     value = flag ? userInput : 'Error while choosing!';
  22.     return value
  23. }
  24.  
  25. // 3. Determine winner
  26. function determineWinner(userChoice, computerChoice){
  27.     if(userChoice === "bomb"){
  28.         return "User wins!"
  29.     }
  30.     if(userChoice === computerChoice){
  31.         return "Tie!"
  32.     }
  33.     winner = "";
  34.     if(userChoice === 'rock'){
  35.         winner = (computerChoice === 'paper') ? 'Computer wins!' : 'User wins!';
  36.     }
  37.     else if(userChoice === 'paper'){
  38.         winner = (computerChoice === 'rock') ? 'User wins!' : 'Computer wins!';
  39.     }
  40.     else{
  41.         winner = (computerChoice === 'rock') ? 'Computer wins!' : 'User wins!';
  42.     }
  43.     return winner;
  44. }
  45.  
  46. // MAIN FUNCTION
  47. user_list = ['rock', 'paper', 'scissors', 'bomb'];
  48. computer_list = ['rock', 'paper', 'scissors'];
  49. for (let i=0; i<user_list.length; i++){
  50.     userChoice = user_list[i];
  51.     for(let j=0; j<computer_list.length; j++){
  52.         computerChoice = computer_list[j];
  53.         winner = determineWinner(userChoice, computerChoice);
  54.         console.log(`User = ${userChoice}, computer = ${computerChoice} ----> ${winner}`);
  55.     }
  56.     console.log();
  57. }
  58.  
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement