Skip to content

Commit 265da6a

Browse files
committed
feat: adding gamestatus state transitions
1 parent 4e7dc3d commit 265da6a

File tree

1 file changed

+32
-5
lines changed
  • workspaces/simon-game/src/app/components

1 file changed

+32
-5
lines changed

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

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import { Box } from "./Box.tsx";
44
import { playNote } from "../util/playNote.ts";
55
import { config } from "../constants.ts";
66

7-
function isSequenceCorrect(check: number[], correct: number[]): boolean {
7+
function isSequenceCorrect(
8+
check: readonly number[],
9+
correct: readonly number[],
10+
): boolean {
811
return check.every((element, i) => element === correct[i]);
912
}
1013

@@ -13,11 +16,10 @@ type GameState = "pre-game" | "game-over" | "player-turn" | "cpu-turn";
1316
export function App() {
1417
const [playerMoves, setPlayerMoves] = useState<readonly number[]>([]);
1518
const [gameState, setGameState] = useState<GameState>("pre-game");
16-
const [_correctMoves, _setCorrectMoves] = useState<readonly number[]>([
19+
const [correctMoves, _setCorrectMoves] = useState<readonly number[]>([
1720
0, 1, 2, 3,
1821
]);
19-
console.log(isSequenceCorrect);
20-
console.log(_correctMoves, _setCorrectMoves);
22+
console.log(_setCorrectMoves);
2123

2224
if (gameState === "pre-game") {
2325
return (
@@ -43,11 +45,36 @@ export function App() {
4345
color={box.color}
4446
onClick={() => {
4547
playNote(box.frequency);
46-
setPlayerMoves((prev) => [...prev, index]);
48+
setPlayerMoves((prev) => {
49+
const newPlayerMoves = [...prev, index];
50+
const isCorrectSequence = isSequenceCorrect(
51+
newPlayerMoves,
52+
correctMoves,
53+
);
54+
if (!isCorrectSequence) {
55+
setGameState("game-over");
56+
return [];
57+
}
58+
if (
59+
isCorrectSequence &&
60+
newPlayerMoves.length === correctMoves.length
61+
) {
62+
setGameState("cpu-turn");
63+
return [];
64+
}
65+
if (
66+
isCorrectSequence &&
67+
newPlayerMoves.length < correctMoves.length
68+
) {
69+
setGameState("player-turn");
70+
}
71+
return newPlayerMoves;
72+
});
4773
}}
4874
/>
4975
))}
5076
</div>
77+
<pre>{gameState}</pre>
5178
<pre>{JSON.stringify(playerMoves, null, 2)}</pre>
5279
</>
5380
);

0 commit comments

Comments
 (0)