Home  >  Article  >  Web Front-end  >  Solve the JavaScript number guessing game in one move

Solve the JavaScript number guessing game in one move

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-04-21 09:37:403646browse

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.

Solve the JavaScript number guessing game in one move

JavaScript Number Guessing Game

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(&#39;答案:&#39;+num);
    var i=0;
    do {
        var n=prompt(&#39;欢迎来到猜数字游戏\n系统已自动生成一个1~10的整数,请输入你猜的数字:&#39;);
        if (n>num) {
            alert(&#39;你猜大了,继续猜&#39;);
        }else if (n<num) {
            alert(&#39;你猜小了,继续猜&#39;);
         }
         i++;
        var cishu=10-i;
         alert(&#39;已使用&#39;+i+&#39;次机会,还剩&#39;+cishu+&#39;次机会&#39;);
        }while (n !=num && i <10) {
            if(n==num){
                alert(&#39;恭喜你!猜对了!&#39;)
            }else if (i==10){
                alert(&#39;你的十次机会已达上限,游戏失败,欢迎下次再来~&#39;);
            }  
        }    </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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete