Step 4: Win and Play Again چالش 4 از جلسهی 35، سخت
دو کار آخر:
1. وقتی همهی کارتها جفت شدند (game.done.length === CARDS.length)، زیر صفحهی بازی یک p با id برابر win نشان بده که بنویسد You win in 3 moves! (عدد از game.moves بیاید). قبل از بردن، این خط نباید روی صفحه باشد.
2. بازی دوباره: در reducer سفارش "reset" را اضافه کن که START را برمیگرداند. در useGame تابع reset را بنویس که این سفارش را میفرستد و آن را هم برگردان. در App یک دکمه با id برابر again و متن Play again بگذار که reset را صدا بزند.
<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 };
}
if (action.type === "hide") {
return { ...game, open: [] };
}
return game;
}
function useGame() {
const [game, dispatch] = useReducer(reducer, START);
useEffect(() => {
if (game.open.length !== 2) {
return;
}
const id = setTimeout(() => dispatch({ type: "hide" }), 1000);
return () => clearTimeout(id);
}, [game.open]);
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: پروژه: بازی حافظه
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js