@@ -4,7 +4,10 @@ import { Box } from "./Box.tsx";
4
4
import { playNote } from "../util/playNote.ts" ;
5
5
import { config } from "../constants.ts" ;
6
6
7
- function isSequenceCorrect ( check : number [ ] , correct : number [ ] ) : boolean {
7
+ function isSequenceCorrect (
8
+ check : readonly number [ ] ,
9
+ correct : readonly number [ ] ,
10
+ ) : boolean {
8
11
return check . every ( ( element , i ) => element === correct [ i ] ) ;
9
12
}
10
13
@@ -13,11 +16,10 @@ type GameState = "pre-game" | "game-over" | "player-turn" | "cpu-turn";
13
16
export function App ( ) {
14
17
const [ playerMoves , setPlayerMoves ] = useState < readonly number [ ] > ( [ ] ) ;
15
18
const [ gameState , setGameState ] = useState < GameState > ( "pre-game" ) ;
16
- const [ _correctMoves , _setCorrectMoves ] = useState < readonly number [ ] > ( [
19
+ const [ correctMoves , _setCorrectMoves ] = useState < readonly number [ ] > ( [
17
20
0 , 1 , 2 , 3 ,
18
21
] ) ;
19
- console . log ( isSequenceCorrect ) ;
20
- console . log ( _correctMoves , _setCorrectMoves ) ;
22
+ console . log ( _setCorrectMoves ) ;
21
23
22
24
if ( gameState === "pre-game" ) {
23
25
return (
@@ -43,11 +45,36 @@ export function App() {
43
45
color = { box . color }
44
46
onClick = { ( ) => {
45
47
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
+ } ) ;
47
73
} }
48
74
/>
49
75
) ) }
50
76
</ div >
77
+ < pre > { gameState } </ pre >
51
78
< pre > { JSON . stringify ( playerMoves , null , 2 ) } </ pre >
52
79
</ >
53
80
) ;
0 commit comments