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

جواب «Step 4: How Many Are On?» چالش 4 از جلسه‌ی 30

سؤال

قدم آخر: خانه باید همیشه بگوید چند اتاق روشن است.
drawAll را کامل کن تا بعد از کشیدنِ اتاق‌ها، در #msg بنویسد On: 2 of 4:
- عددِ اول تعداد اتاق‌های روشن است؛ با rooms.filter پیدایش کن.
- عددِ دوم تعداد همه‌ی اتاق‌هاست؛ از rooms.length بگیر.

چون همه‌ی دکمه‌ها drawAll() را صدا می‌زنند، این خط با هر دکمه خودش تازه می‌شود.

راهنما

آخرِ drawAll، بعد از حلقه: let lit = rooms.filter((room) => room.on); و document.getElementById("msg").textContent = On: ${lit.length} of ${rooms.length};

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.house { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; max-width: 340px; margin: 12px auto; }
.room { width: 150px; padding: 18px 0; border-radius: 12px; background: #334155; color: white; }
.room.on { background: #fde047; color: black; }
</style>

<div class="house">
  <div id="kitchen" class="room">Kitchen</div>
  <div id="bedroom" class="room">Bedroom</div>
  <div id="living" class="room">Living room</div>
  <div id="bath" class="room">Bath</div>
</div>
<button id="b-kitchen" onclick="toggle('kitchen')">Kitchen</button>
<button id="b-bedroom" onclick="toggle('bedroom')">Bedroom</button>
<button id="b-living" onclick="toggle('living')">Living room</button>
<button id="b-bath" onclick="toggle('bath')">Bath</button>
<br>
<button id="off" onclick="allOff()">All off</button>
<button id="flip" onclick="flipAll()">Flip all</button>
<p id="msg"></p>

<script>
const rooms = [
  { id: "kitchen", name: "Kitchen", on: true },
  { id: "bedroom", name: "Bedroom", on: false },
  { id: "living", name: "Living room", on: true },
  { id: "bath", name: "Bath", on: false }
];

function draw(room) {
  let box = document.getElementById(room.id);
  if (room.on) {
    box.classList.add("on");
  } else {
    box.classList.remove("on");
  }
}

function drawAll() {
  for (const room of rooms) {
    draw(room);
  }
  let lit = rooms.filter((room) => room.on);
  document.getElementById("msg").textContent = `On: ${lit.length} of ${rooms.length}`;
}

drawAll();

function flipAll() {
  for (const room of rooms) {
    room.on = !room.on;
  }
  drawAll();
}

function toggle(id) {
  let room = rooms.find((r) => r.id === id);
  room.on = !room.on;
  drawAll();
}

function allOff() {
  for (const room of rooms) {
    room.on = false;
  }
  drawAll();
}
</script>

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