JavaScript实现猜数字游戏
主要思想:设置一个随机数,然后从输入框获取用户输入的数字,然后进行比较,如果获取的数字猜低了给个提示,获取的数字高了,给一个提示,猜对了给一个提示,最后再一个猜题次数,必须小于等于10,否则游戏结束。
<!DOCTYPE html> <html lang="zh"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>猜数字游戏</title> </head> <body><label for="guessNum">请猜一个数字:</label><input type="text" id="guessNum" class="guessNum" /><input type="submit" name="" id="" value="确定" class="guessSubmit"/><p class="guesses"></p><p class="lastResult"></p><p class="lowOrHi"></p> </body> <script type="text/javascript">//开始编写 JavaScript 代码let randomNumber = Math.floor(Math.random()* 100) + 1;const guesses = document.querySelector('.guesses');const lastResult = document.querySelector('.lastResult')const lowOrHi = document.querySelector('.lowOrHi')const guessSubmit = document.querySelector('.guessSubmit')const guessNum = document.querySelector('.guessNum')let guessCount = 1;let resetButton;function checkGuess(){let userGuess = Number(guessNum.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 ++;guessNum.value = '';//获取较焦点guessNum.focus();}guessSubmit.addEventListener('click',checkGuess);function setGameOver(){guessNum.disabled = true;guessSubmit.disabled = true;resetButton = document.createElement('button');resetButton.textContent = '开始新游戏!';document.body.appendChild(resetButton);resetButton.addEventListener('click',resetGame);}function resetGame(){guessCount = 1;const resetParas = document.querySelectorAll('.resultParas p');for(let i = 0; i < resetParas.length;i ++){resetParas[i].textContent = '';}resetButton.parentNode.removeChild(resetButton);guessNum.disabled = false;guessSubmit.disabled = false;guessNum.value = '';guessNum.focus();lastResult.style.backgroundColor = 'burlywood';randomNumber = Math.floor(Math.random() * 100) + 1;} </script> </html>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091