Rock, Paper, Scissors in JavaScript

前端 未结 13 1716
野的像风
野的像风 2020-12-03 00:13

I\'m working on making my first game (Rock Paper Sissors) and I ran into an issue where when the userChoice is scissors and the com

13条回答
  •  误落风尘
    2020-12-03 00:52

    Something to study:

    var choices = ["rock", "paper", "scissors"];
    var map = {};
    
    choices.forEach(function(choice, i) {
        map[choice] = {};
        map[choice][choice] = "Was a tie"
        map[choice][choices[(i+1)%3]] = choices[(i+1)%3] + " wins"
        map[choice][choices[(i+2)%3]] = choice + " wins"
    })
    
    function compare(choice1, choice2) {
        return (map[choice1] || {})[choice2] || "Invalid choice";
    }
    

    Here's an alternate that will work for expanded sets. The assumption is that there's an odd number of possibilities, and from any given point, of the total number of opposition, reading forward from our given point (and wrapping around when we reach the end) the first half will win over the given point, and the second half will lose.

    Or another way to describe it would be that the half of the remaining opponents that precede our given point will lose, and the half that follow will win.

    Therefore the proper order in the choices Array is crucial.

    var choices = ["rock", "spock", "paper", "lizard", "scissors"];
    var map = {};
    
    choices.forEach(function(choice, i) {
        map[choice] = {};
        for (var j = 0, half = (choices.length-1)/2; j < choices.length; j++) {
            var opposition = (i+j)%choices.length
            if (!j)
                map[choice][choice] = "Was a tie"
            else if (j <= half)
                map[choice][choices[opposition]] = choices[opposition] + " wins"
            else
                map[choice][choices[opposition]] = choice + " wins"
        }
    })
    
    function compare(choice1, choice2) {
        return (map[choice1] || {})[choice2] || "Invalid choice";
    }
    

提交回复
热议问题