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

Step 3: Close the Wrong Ones چالش 3 از جلسه‌ی 35، سخت

دو کارت اشتباه باید یک ثانیه دیده شوند و بعد خودشان بسته شوند.
1. در reducer سفارش "hide" را اضافه کن که open را خالی می‌کند.
2. در هوک useGame یک useEffect بنویس: اگر دو کارت باز بود (game.open.length === 2)، با setTimeout بعد از 1000 میلی‌ثانیه سفارش "hide" را بفرستد. تابع تمیزکاری تایمر را با clearTimeout پاک کند. فهرست وابستگی: [game.open].

<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") {
    const i = action.index;
    if (game.open.length === 2 || game.open.includes(i) || game.done.includes(i)) {
      return game;
    }
    if (game.open.length === 0) {
      return { ...game, open: [i] };
    }
    const first = game.open[0];
    if (CARDS[first] === CARDS[i]) {
      return { open: [], done: [...game.done, first, i], moves: game.moves + 1 };
    }
    return { ...game, open: [first, i], moves: game.moves + 1 };
  }
  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 done = game.done.includes(index);
  const up = done || game.open.includes(index);
  return (
    <button id={"t" + index} className={done ? "tile done" : "tile"} onClick={() => flip(index)}>
      {up ? CARDS[index] : "?"}
    </button>
  );
}

function App() {
  const { game, flip } = useGame();
  return (
    <div>
      <h1>Memory Game</h1>
      <p id="moves">Moves: {game.moves}</p>
      <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 4: Win and Play Again

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