JS应用猜数游戏

(function(){
let rs = require("readline-sync");
let guessNumber = new Set();
function getNumber() {//随机生成四个不重复的小于10的整数,且第一个数大于0.
    guessNumber.clear();
    while (guessNumber.size < 4) {
        let randomNumber = parseInt(Math.random() * 10);
        guessNumber.add(randomNumber);
        if (guessNumber.size == 1 && randomNumber == 0) {
            guessNumber.clear();
        }

    }

}

function getGuessInputNumber() {
    while (true){
        console.log("请输入你猜测的数:(是一个首位不为0的不重复4位数)");
        let inputNum = rs.question();
        let exchangeNum = Number(inputNum);
        if (exchangeNum) {
            if (exchangeNum >= 1000 && exchangeNum <= 9999) {
                let t = exchangeNum;
               
                let geWei = (t % 10);t=parseInt(t/10);
                let shiWei = (t % 10);t=parseInt(t/10);
                let baiWei = (t % 10);t=parseInt(t/10);
                let qiuanWei = (t % 10);t=parseInt(t/10);
                let judge = new Set([qiuanWei,baiWei,shiWei,geWei]);
                if (judge.size == 4) {
                    return [...judge];
                } else {
                    console.log("输入的4位数字出现重复位!");
                }
            } else {
                console.log("请输入一个4位数字!");
            }
        } else {
            console.log("请输入一个数字!");
        }

    }
}

function judgeNumber(inputNum){//参数是一个数字,包含4位数的各个部分
    let SystemNum = [...guessNumber];
    let a=0,b=0;
    for (let i = 0; i < inputNum.length; i++) {
        let index = SystemNum.indexOf(inputNum[i]);//-1,0,1,2,3
        if(index == i){
            a++
        }else if(index == -1){

        }else{
            b++;
        }
    }
    console.log(`${a}A${b}B`);
    if(a==4){
        return true;
    }

}


function run(){//主体逻辑,一般命名为run或者main
    getNumber();
    for (let i = 0; i < 10; i++) {
        if(judgeNumber(getGuessInputNumber())){
            console.log("恭喜你,猜成功了,你一共使用了"+(i+1)+"次猜测机会!");
            break;
        }
        console.log("请继续")
    }
}


run();
})()
posted @ 2019-04-19 20:34  代码狂魔2019  阅读(1069)  评论(0编辑  收藏  举报