جواب «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.
(کارتهای اشتباه فعلا باز میمانند؛ قدم بعد آنها را میبندد.)
راهنما
جفت بودن: 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 };. در Tile: const done = game.done.includes(index); و className={done ? "tile done" : "tile"}.
یک جواب درست
<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>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن