以下是一个简单的猜拳小游戏的 HTML 代码,供您学习和参考:

<!DOCTYPE html>
<html>
<head>
    <title>猜拳小游戏</title>
    <style>
        h1 {
            text-align: center;
        }
        .choices {
            display: flex;
            justify-content: center;
            margin-top: 50px;
        }
        .choice {
            margin: 0 10px;
            cursor: pointer;
        }
        img {
            width: 100px;
            height: 100px;
        }
        #result {
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>猜拳小游戏</h1>
    
    <div class='choices'>
        <div class='choice' onclick='playGame('rock')'>
            <img src='rock.png' alt='Rock'>
            <p>石头</p>
        </div>
        <div class='choice' onclick='playGame('paper')'>
            <img src='paper.png' alt='Paper'>
            <p>布</p>
        </div>
        <div class='choice' onclick='playGame('scissors')'>
            <img src='scissors.png' alt='Scissors'>
            <p>剪刀</p>
        </div>
    </div>
    
    <div id='result'></div>
    
    <script>
        function playGame(userChoice) {
            var choices = ['rock', 'paper', 'scissors'];
            var computerChoice = choices[Math.floor(Math.random() * choices.length)];
            
            var result = '';
            
            if (userChoice === computerChoice) {
                result = '平局!';
            } else if ((userChoice === 'rock' && computerChoice === 'scissors') ||
                       (userChoice === 'paper' && computerChoice === 'rock') ||
                       (userChoice === 'scissors' && computerChoice === 'paper')) {
                result = '你赢了!';
            } else {
                result = '电脑赢了!';
            }
            
            document.getElementById('result').innerHTML = result;
        }
    </script>
</body>
</html>

在这个代码中,我们使用 <div> 元素创建了三个选项(石头、剪刀、布),每个选项都包裹在一个 <div> 标签中,并添加了 onclick 事件。当用户点击选项时,会调用 playGame 函数进行游戏的逻辑判断。

playGame 函数首先生成一个随机的电脑选择,然后根据用户选择和电脑选择的不同情况,判断游戏结果,并将结果显示在页面上的 <div id='result'> 元素中。

HTML 猜拳小游戏代码示例 - 简单易懂

原文地址: https://www.cveoy.top/t/topic/cIzb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录