Just learned "objects": rethinking "rock, paper, scissors"


#1

https://www.codecademy.com/en/courses/javascript-beginner-en-Bthev-mskY8/1/5?curriculum_id=506324b3a7dffd00020bf661

Actually working perfectly fine, wondering is this the better way to code the game?


var options = {
  rock: {canBeat: 'scissors', beatenBy: 'paper'},
  paper: {canBeat: 'rock', beatenBy: 'scissors'},
  scissors: {canBeat: 'paper', beatenBy: 'rock'},
};

function compare(choice1, choice2) {
  
  if (choice1 === choice2) {
    return "The result is a tie!";
  } else if (options[choice1].canBeat === choice2) {
  return choice1 + " " + "wins!";
  } else if (options[choice1].beatenBy === choice2) {
    return choice2 + " " + "wins!";
  } return "You're not going to win this way";
};

function gameRound() {

  var userChoice = prompt("Do you choose rock, paper or scissors?");

  var computerChoice = Math.random();

  if (computerChoice < 0.34) {
    computerChoice = "rock";
  } else if(computerChoice <= 0.67) {
    computerChoice = "paper";
  } else {
    computerChoice = "scissors";
  };

  var result = compare(userChoice, computerChoice);
  alert(result);
    
};
  
while (confirm("Do you want to play a game?")) {
   gameRound();
};


#2

what you for example could do for computerChoice is simply creating an array at the start of your code:

computerChoices = ["rock","paper","scissors"]

and then when the computer has to select a a option simply do:

computerChoice = computerChoices[Math.floor(Math.random()* (3 - 0)) + 0]

It is nice you took a moment to rethink this program now you have gained more knowlegde, that is very good :slight_smile:


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.