html写一个猜拳小游戏
以下是一个简单的猜拳小游戏的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">元素中。
原文地址: https://www.cveoy.top/t/topic/jgkp 著作权归作者所有。请勿转载和采集!