This article will give you a detailed introduction to how to play the JavaScript number guessing game. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Randomly select a number from 1 to 10 (the number can be viewed on the console) and there are only ten chances
Code:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>wangwang</title></head><body><script type="text/javascript"> function getRandom(min,max) { return Math.floor(Math.random()*(max-min+1))+min; } // 猜数字 var num=getRandom(1,10); // 在控制台查看答案 console.log('答案:'+num); var i=0; do { var n=prompt('欢迎来到猜数字游戏\n系统已自动生成一个1~10的整数,请输入你猜的数字:'); if (n>num) { alert('你猜大了,继续猜'); }else if (n<num) { alert('你猜小了,继续猜'); } i++; var cishu=10-i; alert('已使用'+i+'次机会,还剩'+cishu+'次机会'); }while (n !=num && i <10) { if(n==num){ alert('恭喜你!猜对了!') }else if (i==10){ alert('你的十次机会已达上限,游戏失败,欢迎下次再来~'); } } </script></body></html>
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of Solve the JavaScript number guessing game in one move. For more information, please follow other related articles on the PHP Chinese website!