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

Step 2: Pairs چالش 2 از جلسه‌ی 35، متوسط

حالا قانون جفت‌ها. reducer را برای سفارش "flip" این‌طور کامل کن (i همان action.index است):
- اگر دو کارت باز است، یا کارت i خودش باز یا جفت‌شده است: همان game را برگردان (کلیک بی‌اثر).
- اگر هیچ کارتی باز نیست: open بشود [i].
- اگر یک کارت باز است (first): moves یکی زیاد شود. اگر میوه‌ی دو کارت یکی بود، هر دو شماره به done اضافه شوند و open خالی شود. اگر نبود، open بشود [first, i].

در Tile کارت جفت‌شده هم میوه‌اش را نشان بدهد و کلاسش tile done باشد. در App بالای صفحه‌ی بازی یک p با id برابر moves بگذار که بنویسد Moves: 0.
(کارت‌های اشتباه فعلا باز می‌مانند؛ قدم بعد آن‌ها را می‌بندد.)

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#board { display: grid; grid-template-columns: repeat(3, 72px); gap: 8px; justify-content: center; }
.tile { width: 72px; height: 72px; margin: 0; font-size: 28px; border: 2px solid #334155; border-radius: 12px; background: #e2e8f0; }
.done { background: #bbf7d0; }
</style>

<div id="root" dir="ltr"></div>

<script type="text/jsx">
import { useReducer, useEffect } from "react";
import { createRoot } from "react-dom/client";

const CARDS = ["🍎", "🍌", "🍎", "🍇", "🍌", "🍇"];
const START = { open: [], done: [], moves: 0 };

function reducer(game, action) {
  if (action.type === "flip") {
    return { ...game, open: [...game.open, action.index] };
  }
  return game;
}

function useGame() {
  const [game, dispatch] = useReducer(reducer, START);

  function flip(index) {
    dispatch({ type: "flip", index: index });
  }

  return { game, flip };
}

function Tile({ index, game, flip }) {
  const up = game.open.includes(index);
  return (
    <button id={"t" + index} className="tile" onClick={() => flip(index)}>
      {up ? CARDS[index] : "?"}
    </button>
  );
}

function App() {
  const { game, flip } = useGame();
  return (
    <div>
      <h1>Memory Game</h1>
      <div id="board">
        {CARDS.map((card, i) => (
          <Tile key={i} index={i} game={game} flip={flip} />
        ))}
      </div>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<App />);
</script>

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 35: پروژه: بازی حافظه · چالش بعدی: Step 3: Close the Wrong Ones

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js