今天周六,没事干,李华说哎呀好无聊,玩一下猜数字游戏吧!
废话少说上代码!
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<title>猜数字游戏</title>
<style>
body {
font-family: 'STKaiti', 'KaiTi', cursive;
text-align: center;
background-color: #f7f4e7;
color: #705544;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
border: 20px solid #d2ab8d;
box-shadow: 0 0 20px #705544;
}
h1 {
margin-bottom: 20px;
font-size: 3em;
text-transform: uppercase;
color: #705544;
}
p {
font-size: 1.5em;
margin: 20px 0;
color: #705544;
}
input {
padding: 10px;
margin: 10px;
font-size: 18px;
border: 2px solid #705544;
border-radius: 5px;
width: 200px;
background-color: #f7f4e7;
color: #705544;
box-shadow: 0 0 10px #705544;
}
button {
padding: 12px 24px;
margin-top: 10px;
cursor: pointer;
font-size: 1.2em;
background-color: #d2ab8d;
color: #705544;
border: 1px solid #705544;
border-radius: 5px;
transition: background-color 0.3s ease;
box-shadow: 0 0 10px #705544;
}
button:hover {
background-color: #c09162;
}
#result {
margin-top: 20px;
font-size: 24px;
font-weight: bold;
color: #705544;
}
#attempts {
margin-top: 10px;
font-size: 18px;
color: #705544;
}
</style>
</head>
<body>
<h1>猜数字游戏</h1>
<p>猜一个1到100之间的数字</p>
<input type="number" id="guessInput" min="1" max="100">
<br>
<button onclick="checkGuess()">提交猜测</button>
<div id="result"></div>
<div id="attempts"></div>
<script>
const randomNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
function checkGuess() {
const guessInput = document.getElementById('guessInput');
const resultDisplay = document.getElementById('result');
const attemptsDisplay = document.getElementById('attempts');
const userGuess = parseInt(guessInput.value);
attempts++;
if (userGuess === randomNumber) {
if (attempts <= 3) {
resultDisplay.textContent = `恭喜!你在 ${attempts} 次尝试中猜对了数字!你太聪明了!`;
} else if (attempts <= 10) {
resultDisplay.textContent = `恭喜!你在 ${attempts} 次尝试中猜对了数字!你简直无敌!`;
} else if (attempts <= 20) {
resultDisplay.textContent = `恭喜!你在 ${attempts} 次尝试中猜对了数字!你太厉害了!`;
} else {
resultDisplay.textContent = `你猜对了,但已经尝试了 ${attempts} 次,别玩了!`;
}
resultDisplay.style.color = '#705544';
attemptsDisplay.textContent = ''; // Clear previous attempts
guessInput.disabled = true; // Disable input after correct guess
} else if (userGuess > randomNumber) {
resultDisplay.textContent = '太高了!再试一次。';
resultDisplay.style.color = '#705544';
attemptsDisplay.textContent = `已尝试次数: ${attempts}`;
} else if (userGuess < randomNumber) {
resultDisplay.textContent = '太低了!再试一次。';
resultDisplay.style.color = '#705544';
attemptsDisplay.textContent = `已尝试次数: ${attempts}`;
}
}
</script>
</body>
</html>