Skip to content

Commit d97371c

Browse files
authored
Adding player moves and correct moves verifier (#501)
Added a verifier for player moves and correct moves
1 parent 195415b commit d97371c

File tree

1 file changed

+26
-1
lines changed
  • workspaces/simon-game/src/app/components

1 file changed

+26
-1
lines changed

workspaces/simon-game/src/app/components/App.tsx

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@ import { Box } from "./Box.tsx";
44
import { playNote } from "../util/playNote.ts";
55
import { config } from "../constants.ts";
66

7+
// TODO: Make this a reusable utility
8+
function isPrefixCorrect(
9+
prefix: readonly number[],
10+
correct: readonly number[],
11+
): boolean {
12+
return prefix.every((element, i) => element === correct[i]);
13+
}
14+
715
type GameState = "pre-game" | "game-over" | "player-turn" | "cpu-turn";
816

917
// TODO: Move this to a new file later
@@ -41,11 +49,28 @@ export function App() {
4149
color={box.color}
4250
onClick={() => {
4351
playNote(box.frequency);
44-
setPlayerMoves((prev) => [...prev, index]);
52+
setPlayerMoves(() => {
53+
const newPlayerMoves = [...playerMoves, index];
54+
const isSequenceCorrect = isPrefixCorrect(
55+
newPlayerMoves,
56+
correctMoves,
57+
);
58+
if (!isSequenceCorrect) {
59+
setGameState("game-over");
60+
return newPlayerMoves;
61+
}
62+
if (newPlayerMoves.length === correctMoves.length) {
63+
setGameState("cpu-turn");
64+
return [];
65+
}
66+
setGameState("player-turn");
67+
return newPlayerMoves;
68+
});
4569
}}
4670
/>
4771
))}
4872
</div>
73+
<pre>Game State: {gameState}</pre>
4974
<pre>Player Moves: {JSON.stringify(playerMoves, null, 2)}</pre>
5075
<pre>Correct Moves: {JSON.stringify(correctMoves, null, 2)}</pre>
5176
</>

0 commit comments

Comments
 (0)