@@ -4,6 +4,14 @@ import { Box } from "./Box.tsx";
4
4
import { playNote } from "../util/playNote.ts" ;
5
5
import { config } from "../constants.ts" ;
6
6
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
+
7
15
type GameState = "pre-game" | "game-over" | "player-turn" | "cpu-turn" ;
8
16
9
17
// TODO: Move this to a new file later
@@ -41,11 +49,28 @@ export function App() {
41
49
color = { box . color }
42
50
onClick = { ( ) => {
43
51
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
+ } ) ;
45
69
} }
46
70
/>
47
71
) ) }
48
72
</ div >
73
+ < pre > Game State: { gameState } </ pre >
49
74
< pre > Player Moves: { JSON . stringify ( playerMoves , null , 2 ) } </ pre >
50
75
< pre > Correct Moves: { JSON . stringify ( correctMoves , null , 2 ) } </ pre >
51
76
</ >
0 commit comments