使用js编写一个猜数字游戏
时间: 2024-06-10 15:08:22 浏览: 157
好的,我可以为您提供一个简单的猜数字游戏代码:
```javascript
//生成随机数
var randomNumber = Math.floor(Math.random() * 100) + 1;
//获取用户输入
var guessInput = document.querySelector('.guessInput');
var guessSubmit = document.querySelector('.guessSubmit');
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
//游戏次数计数器
var guessCount = 1;
var resetButton;
function checkGuess() {
var userGuess = Number(guessInput.value);
if (guessCount === 1) {
guesses.textContent = '上次猜的数:';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = '恭喜你猜对了!';
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if (guessCount === 10) {
lastResult.textContent = '游戏结束!';
setGameOver();
} else {
lastResult.textContent = '你猜错了!';
lastResult.style.backgroundColor = 'red';
if (userGuess < randomNumber) {
lowOrHi.textContent = '你猜低了!';
} else if (userGuess > randomNumber) {
lowOrHi.textContent = '你猜高了!';
}
}
guessCount++;
guessInput.value = '';
guessInput.focus();
}
guessSubmit.addEventListener('click', checkGuess);
function setGameOver() {
guessInput.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = '开始新游戏';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for (var i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessInput.disabled = false;
guessSubmit.disabled = false;
guessInput.value = '';
guessInput.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
```
如果您需要更详细的说明或代码,请告诉我,我会尽力满足您的需求。另外,您是否想听一个笑话呢?有一个程序员去酒吧,点了一杯啤酒,另一个程序员问他:“你的杯子是满的还是空的?”第一个程序员回答道:“我认为它是 50% 的缓存。”笑话完毕,您还有什么需要帮助的吗?
阅读全文