prompt实现猜数字游戏

小作业
1494 0

时间:2018.12.07

类型:javascript

关键代码:

<!--需要用到Jquery-->
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

<!--content用来实现HTMLEncode方法-->
<div id="content"></div>
<!--process用来显示游戏过程-->
<p class="process"></p>
<button id="btn">猜数字</button>

<script type="text/javascript">

//HTML转义 防止脚本注入
function HTMLEncode(html) {
    var temp = document.createElement("content");
    (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
    var output = temp.innerHTML;
    temp = null;
    return output;
}
    
//定义输出内容    
var arr = ["<font color='#6C890B'><b>小</b></font>","<font color='#7F1874'><b>大</b></font>","输入错误!","<font color='red'><b>你猜对啦!</b></font>","你放弃了这次猜数字。"];

//i表示输出结果,j表示猜测次数
var i,j = 0;

//生成随机数
var answer = Math.round(Math.random()*100);

if (!navigator.onLine){
    alert("请联网后运行,谢谢!");
    window.opener = null;
    window.close();
}

$(function() {

    $("#btn").click(function prt() {
        var result = prompt("一个两位整数","666");
        if (result) {
            if (isNaN(result)) {
                alert("请输入数字");
                i = 2;
            }else{
                if(result - parseInt(result) != 0){
                    result < answer ? i = 0 : i = 1;
                    alert("这应该是个整数哦!而且,它太" + arr[i] + "了!");
                }else if (result == 666) {
                    i = 1;
                    alert("当然不会是666啦!换一个吧。");
                }else if(result > 99){
                    i = 1;
                    alert("有没有搞错,两位数啦!");
                }else if (result > answer) {
                    alert("这个数太大了!");
                    i = 1;
                }else if (result < answer) {
                    i = 0;
                    alert("这个数太小了!");
                }else if(result == answer){
                    i = 3;
                    alert("恭喜你,猜对了!!!!");
                }
            }
            j += 1;
            $(".process").append("第" + j + "次:" + HTMLEncode(result) + "——" + arr[i] + "<br>");
            if (i != 3) {
                setTimeout(function() {
                    prt();
                },500);
            }
        }else{
            j += 1;
            i = 4;
            $(".process").append("第" + j + "次:" + HTMLEncode(result) + "——" + arr[i] + "<br>");
        }
    });
});
</script>
最后更新 2020-04-18
评论 ( 0 )
OωO
隐私评论