بتل کد Battle Codeدارد باز می‌شود…

جواب «Guess the Number» چالش 5 از جلسه‌ی 38

سؤال

یک بازی حدس عدد بساز.
- با زدن New game یک عدد صحیح تصادفی از 1 تا 10 در متغیر secret بگذار و در msg بنویس Guess!.
- با زدن Try عدد کادر guess را با Number() بخوان:
- اگر با secret برابر بود بنویس Correct!
- اگر از secret کوچک‌تر بود بنویس Higher
- اگر بزرگ‌تر بود بنویس Lower

راهنما

در newGame: secret = Math.floor(Math.random() * 10) + 1; در tryIt: let n = Number(box.value); و بعد if (n === secret) { ... } else if (n < secret) { ... } else { ... }

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
</style>

<button id="new" onclick="newGame()">New game</button>
<br>
<input id="guess">
<button id="try" onclick="tryIt()">Try</button>
<p id="msg"></p>

<script>
let secret = 0;
let box = document.getElementById("guess");
let line = document.getElementById("msg");

function newGame() {
  secret = Math.floor(Math.random() * 10) + 1;
  line.textContent = "Guess!";
}

function tryIt() {
  let n = Number(box.value);
  if (n === secret) {
    line.textContent = "Correct!";
  } else if (n < secret) {
    line.textContent = "Higher";
  } else {
    line.textContent = "Lower";
  }
}
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن