写一个石头剪刀布的html小游戏
<!DOCTYPE html>
<html>
<head>
<title>石头剪刀布</title>
<style>
body{
background-color: #f2f2f2;
text-align: center;
}
h1{
font-size: 48px;
color: #333;
margin-top: 50px;
}
p{
font-size: 24px;
color: #666;
margin-top: 20px;
}
#buttons{
margin-top: 50px;
}
button{
font-size: 24px;
padding: 10px 20px;
margin-right: 20px;
background-color: #ddd;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover{
background-color: #ccc;
}
#result{
font-size: 36px;
color: #333;
margin-top: 50px;
}
</style>
</head>
<body>
<h1>石头剪刀布</h1>
<p>请选择你的手势:</p>
<div id="buttons">
<button id="rock">石头</button>
<button id="scissors">剪刀</button>
<button id="paper">布</button>
</div>
<div id="result"></div>
<script>
var buttons = document.querySelectorAll("button");
var result = document.getElementById("result");
var playerScore = 0;
var computerScore = 0;
<pre><code> function computerPlay(){
var hands = ["石头", "剪刀", "布"];
var randomIndex = Math.floor(Math.random() * 3);
return hands[randomIndex];
}
function playRound(playerSelection, computerSelection){
if(playerSelection == "石头"){
if(computerSelection == "石头"){
return "平局!";
}else if(computerSelection == "剪刀"){
playerScore++;
return "你赢了!";
}else{
computerScore++;
return "电脑赢了!";
}
}else if(playerSelection == "剪刀"){
if(computerSelection == "石头"){
computerScore++;
return "电脑赢了!";
}else if(computerSelection == "剪刀"){
return "平局!";
}else{
playerScore++;
return "你赢了!";
}
}else{
if(computerSelection == "石头"){
playerScore++;
return "你赢了!";
}else if(computerSelection == "剪刀"){
computerScore++;
return "电脑赢了!";
}else{
return "平局!";
}
}
}
function game(){
playerScore = 0;
computerScore = 0;
result.innerHTML = "";
buttons.forEach(button =>{
button.addEventListener("click", function(){
var playerSelection = button.textContent;
var computerSelection = computerPlay();
var roundResult = playRound(playerSelection, computerSelection);
result.innerHTML += roundResult + "<br>";
result.innerHTML += "你:" + playerScore + " 分,电脑:" + computerScore + " 分<br><br>";
if(playerScore == 5 || computerScore == 5){
if(playerScore > computerScore){
result.innerHTML += "你赢了!";
}else{
result.innerHTML += "电脑赢了!";
}
buttons.forEach(button =>{
button.disabled = true;
});
}
});
});
}
game();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/bgKx 著作权归作者所有。请勿转载和采集!