I just went through a very easy online example creating a Rock-Paper-Scissors game, but it seemed like it was not a great use of computing power.
It seemed like I was writing out results for every possible outcome instead of declaring properties or attributes for variables that will dictate the results depending on the situation.
Could an index or something be used to set up the variables?
var rock = ["rock", "paper", "scissors"];
var paper = ["paper", "scissors", "rock"];
var scissors = ["scissors", "rock", "paper"];
index 0 1 2
Player 1 could select a variable, then player 2 could select a string in the index, and the position of the selection in the index would determine the winner (0 = tie, 1 = p1Loss, 2 = p1Win). Is this possible?
I think the code in the example below would start to get messy and bloated if you were to expand on the choices/options. i.e. Instead of 3 options you have 9, any one of which will beat 4 options and loose to the other 4.
I guess I'm just wondering if there is a better way to do this that would scale better with larger numbers.
I've included the code from the example below:
var user1Choice = prompt("Do you choose rock, paper or scissors?");
var user2Choice = prompt("Do you choose rock, paper or scissors?");
var compare = function(choice1, choice2) {
if (choice1 === choice2) {
return "its a tie";
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins";
}
}
else if (choice1 === "scissors") {
if (choice2 === "paper") {
return "scissors wins";
}
else {
return "paper wins";
}
}
}
compare(user1Choice, user2Choice)
rock
to represent a rock, whereas it really is an array containing "rock", "paper", and "scissors" and so is unintuitive. If you really hate conditionals, wrap your three subarrays into another array and then the result would be determined byresults[player1][player2]
\$\endgroup\$