SOURCE

console 命令行工具 X clear

                    
>
console
function init(n) {
    n = +n;
    let res = parseInt(Math.random() * n)
    let left = 1;
    let right = n;
    let count = 0;
    function reset() {
        res = parseInt(Math.random() * n);
        left = 1;
        right = n;
        count = 0;
    }
    function test(num) {
        count++
        num = +num;
        let text = '';
        if (num === res) {

            text = `共猜测${count}次,猜中答案:${res}。`
            reset()
            text += `答题区间已重置:${left}_${right}`
            return text;
        }

        if (num < res && num > left) {
            left = num
        }
        if (num > res && num < right) {
            right = num
        }
        // 就是答案在 这两个数中间时 不用再继续直接也算结束
        if (right - left === 2) {
            text = `共猜测${count}次,${left}_${right},答案:${res}。`
            reset()
            text += `答题区间已重置:${left}_${right}`
            return text;
        }
        // 第一次只能确定左右其中一个,所以没法判断是否在合理区间内,因为区间还未确定。
        if ((num > right || num < left) && count > 1) {
            text = `共猜测${count}次,${num}不在答题区间内:${left}_${right}`
            return text;
        }

        text = `共猜测${count}次,答题区间:${left}_${right}`
        return text
    }
    return test
}
(function () {
    // 默认随机区间1 - initRandom
    const initRandom = 100;
    // 初始回答默认值 可以省略;
    const initAnswer = 100;
    let fn = init(initRandom);
    提醒.innerText = `1 _ ${initRandom}`;
    区间.setAttribute('value', initRandom);
    区间.addEventListener('change', () => {
        fn = init(区间.value)
        提醒.innerText = `1 _ ${initRandom}`;
    })
    回答.setAttribute('value', initAnswer);
    回答.addEventListener('change', ()=>{
        提醒.innerText = fn(回答.value)
    })
})()

随机区间 <input type="number" id="区间" ><br>
猜测数字 <input type="number" id="回答" > 回车验证
<div >
    答题区间
    <strong id="提醒"></strong>
</div>
<br>