Another machine-coding favorite: a memory game. Twelve cards lie face down in a fixed order, the words in CARDS. The player turns two cards per move: if their words match, the pair stays face up; if not, both turn back after one second. Three states keep track: turned (the cards turned in this move), matched (the pairs found so far), both holding indexes into CARDS, and moves.
A change that should happen later goes in a timer. setTimeout takes a function and a delay in milliseconds, and runs the function once that time has passed. A Copy button, for example, can say "Copied" and go back by itself:
function copy() {
setLabel("Copied");
setTimeout(() => setLabel("Copy"), 2000);
}
While two different cards wait for their timer, a click on a third card must do nothing. A found pair goes into matched, so turned is empty for the next move. The check runs the page's clock itself (500 ms pass) and must print (shortened):
> open the page text: Moves: 0, button: Card 1 … button: Card 12 > click "Card 1" - button: Card 1 + button: Mug > click "Card 2" - text: Moves: 0 + text: Moves: 1 - button: Card 2 + button: Lamp > click "Card 3" screen: no change > 500 ms pass screen: no change > 500 ms pass - button: Mug + button: Card 1 - button: Lamp + button: Card 2 > click "Card 1" - button: Card 1 + button: Mug > click "Card 5" - text: Moves: 1 + text: Moves: 2 - button: Card 5 + button: Mug > click "Mug" screen: no change … the player finds the other pairs … > click "Card 12" - text: Moves: 8 + text: You won in 9 moves - button: Card 12 + button: Stapler
Your task: in src/App.jsx, finish turn: stop after the first card of a move, turn two different cards back after 1000 ms, ignore clicks while two cards are up, keep a found pair in matched and count the moves. Then show Moves: n, or You won in n moves once every card is matched.
Assignment
Follow the Coding Tutorial to compare the two turned cards, turn a wrong pair back with a timer, keep a right pair face up, count the moves and show the win.
Hint
A move ends when its second card turns: that's where moves goes up and where you compare CARDS[first] with CARDS[second]. Each early return in turn stops the lines below it from running.
Free plan: 30 tutor messages. PRO is unlimited.
