@@ -6,14 +6,19 @@ import {
66 useReducer ,
77} from "react" ;
88import { isNil , throttle } from "lodash" ;
9- import { mergeAnimationDuration , tileCountPerDimension } from "@/constants" ;
9+ import {
10+ gameWinTileValue ,
11+ mergeAnimationDuration ,
12+ tileCountPerDimension ,
13+ } from "@/constants" ;
1014import { Tile } from "@/models/tile" ;
1115import gameReducer , { initialState } from "@/reducers/game-reducer" ;
1216
1317type MoveDirection = "move_up" | "move_down" | "move_left" | "move_right" ;
1418
1519export const GameContext = createContext ( {
1620 score : 0 ,
21+ status : "ongoing" ,
1722 moveTiles : ( _ : MoveDirection ) => { } ,
1823 getTiles : ( ) => [ ] as Tile [ ] ,
1924 startGame : ( ) => { } ,
@@ -61,15 +66,27 @@ export default function GameProvider({ children }: PropsWithChildren) {
6166 ) ;
6267
6368 const startGame = ( ) => {
69+ dispatch ( { type : "reset_game" } ) ;
6470 dispatch ( { type : "create_tile" , tile : { position : [ 0 , 1 ] , value : 2 } } ) ;
6571 dispatch ( { type : "create_tile" , tile : { position : [ 0 , 2 ] , value : 2 } } ) ;
6672 } ;
6773
74+ const checkGameState = ( ) => {
75+ const isWon =
76+ Object . values ( gameState . tiles ) . filter ( ( t ) => t . value === gameWinTileValue )
77+ . length > 0 ;
78+
79+ if ( isWon ) {
80+ dispatch ( { type : "update_status" , status : "won" } ) ;
81+ }
82+ } ;
83+
6884 useEffect ( ( ) => {
6985 if ( gameState . hasChanged ) {
7086 setTimeout ( ( ) => {
7187 dispatch ( { type : "clean_up" } ) ;
7288 appendRandomTile ( ) ;
89+ checkGameState ( ) ;
7390 } , mergeAnimationDuration ) ;
7491 }
7592 } , [ gameState . hasChanged ] ) ;
@@ -78,6 +95,7 @@ export default function GameProvider({ children }: PropsWithChildren) {
7895 < GameContext . Provider
7996 value = { {
8097 score : gameState . score ,
98+ status : gameState . status ,
8199 getTiles,
82100 moveTiles,
83101 startGame,
0 commit comments