JavaScript Rock-paper-scissors


I wrote the rock paper program and saw it. I will post it as a memorandum.

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Rock-paper-scissors</title>
</head>
<body>
    <div id="message1" >
        <h3>CPU: what?</h3>
    </div>
    <div id="message2" >
        <h3>Result: Please select from the select box and press decision button.</h3>
    </div>
    <form>
        <select id="janken">
            <option>Rock</option>
            <option>scissors</option>
            <option>paper</option>
        </select>
        <input type="button" value="battle" onclick="myGame()">
    </form>
    <script>
    function myGame() {
        var myte = document.getElementById("janken").selectedIndex;
        var cpunum = Math.floor(Math.random()*3);
        var cpuhand;
        var judge;

        if(cpunum == 0) {
            cpuhand = "Rock";
        } else if(cpunum == 1) {
            cpuhand = "scissors";
        } else if(cpunum == 2) {
            cpuhand = "paper";
        }

        if(myte == 0 && cpunum == 1) {
            judge = "you win";
        } else if(myte == 1 && cpunum == 2) {
            judge = "you win";
        } else if(myte == 2 && cpunum == 0) {
            judge = "you win";
        } else if(myte == cpunum) {
            judge = "draw";
        } else {
            judge = "you lose";
        }

        document.getElementById("message1").innerHTML = "<h3>CPUの手: " + cpuhand + "</h3>";
        document.getElementById("message2").innerHTML = "<h3>結果: " + judge + "</h3>";
    }
    </script>
</body>
</html>

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?