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 () {
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>