# ===== CodeLab: game-js-guess ===== # 以下代码片段按文章出现顺序拼接, 共 6 段 # ----- 片段 1 (html) -----

猜数字

我随机想了一个 1~100 的整数,你能猜中吗?

等待你的第一次猜测……

已猜次数:0

# ----- 片段 2 (css) ----- body { font-family: "PingFang SC", "Microsoft YaHei", sans-serif; background: #f0f4f8; min-height: 100vh; display: flex; justify-content: center; align-items: center; } .game { background: #fff; padding: 2.5rem; border-radius: 16px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08); text-align: center; width: 320px; } input, button { font-size: 1rem; padding: 0.5rem 0.8rem; border-radius: 8px; border: 1px solid #ccc; margin: 0.3rem; } button { background: #4f6ef7; color: #fff; border: none; cursor: pointer; } button:hover { background: #3d5ae0; } #feedback { font-size: 1.1rem; font-weight: bold; min-height: 1.5em; } # ----- 片段 3 (javascript) ----- let secret = Math.floor(Math.random() * 100) + 1; let attempts = 0; const input = document.getElementById('guess'); const feedback = document.getElementById('feedback'); const count = document.getElementById('count'); function check() { const value = Number(input.value); if (!Number.isInteger(value) || value < 1 || value > 100) { feedback.textContent = '请输入 1~100 之间的整数!'; return; } attempts = attempts + 1; count.textContent = '已猜次数:' + attempts; if (value === secret) { feedback.textContent = '🎉 恭喜!你用了 ' + attempts + ' 次猜中!'; input.disabled = true; } else if (value < secret) { feedback.textContent = '太小了,再大一点!'; } else { feedback.textContent = '太大了,再小一点!'; } input.value = ''; input.focus(); } # ----- 片段 4 (javascript) ----- // 错误示范:直接用字符串比较 console.log('10' < '9'); // true!因为按字典序,'1' 排在 '9' 前面 // 正确做法:先转成数字再比 console.log(Number('10') < Number('9')); // false,10 当然比 9 大 # ----- 片段 5 (javascript) ----- function restart() { secret = Math.floor(Math.random() * 100) + 1; attempts = 0; input.disabled = false; input.value = ''; feedback.textContent = '新的一局,开始猜吧!'; count.textContent = '已猜次数:0'; input.focus(); } document.getElementById('submit').addEventListener('click', check); input.addEventListener('keydown', (e) => { if (e.key === 'Enter') check(); }); document.getElementById('restart').addEventListener('click', restart); # ----- 片段 6 (html) ----- 猜数字