两次数学随机再现价值

肯定会遇到一些问题,大多数人会发现这很琐碎,但仍然会感谢您的帮助。这是我们最喜欢的Rock Papaer剪刀游戏:

的HTML:

    <div class="container">
    <h1>Rock, Paper, Scissors</h1>

    <div class="player">
        <div class="userchoice Rock"></div>
        <p>Player 1</p>
    </div>

    <div class="player">
        <div class="computerchoice Rock"></div>
        <p>Computer</p>
    </div>

    <div class="result"></div>

    <button class="startBtn">Play</button>
    </div>
    <script src="app.js"></script>

js

    var user = document.querySelector(".userchoice");
    var computer = document.querySelector(".computerchoice");
    var startBtn = document.querySelector(".startBtn");
    var result = document.querySelector(".result");

    var winStates = ["Rock", "Paper", "Scissors"];

    startBtn.addEventListener("click", playGame);


    function playGame(){
        startBtn.disabled = true;
        user.classList.add("count-in");
        computer.classList.add("count-in"); 

    }

    document.addEventListener("animationend", function(){
        user.classList.remove("count-in");
        computer.classList.remove("count-in");
        startBtn.disabled = false;
        var randomU = winStates[Math.floor(Math.random() *3)];
        var randomC = winStates[Math.floor(Math.random() *3)];
        computer.className = "computerchoice " + randomC;
        user.className = "userchoice " + randomU;
    })

问题出在执行Math.random时,好像它被触发了两次并从winStates数组中获取了两个值。自然地,它应该选择一个值并将其与已经定义的css类连接

评论