Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

game-state-context.tsx

366 lines12.4 KB

1import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react"
2import { GameState } from "../../shared/game-state"
3import { GAME_START_TIMESTAMP_KEY } from "../../shared/game-config"
4import { BoxBitmap } from "../lib/box-bitmap"
5import { playBoxSound, playPencilSound } from "../lib/game-sounds"
6import { useBoardRealtime } from "../hooks/useBoardRealtime"
7import { useTeam } from "./team-context"
8import { QUOTA_KEY, useQuota } from "./quota-context"
9import type { BoardTile } from "../../shared/tiles"
10import type { ReactNode } from "react"
11​
12// Local storage key for user's completed boxes (must match quota-context.tsx)
13const LOCAL_BOXES_KEY = `boxes:local-completed`
14const OUT_OF_MOVES_MESSAGE = `Out of moves! Recharging...`
15​
16export interface RecentEvent {
17 id: number
18 edgeId: number
19 teamId: number
20 timestamp: number
21 isLocal: boolean // true if placed by the current user
23​
24export interface GameStateContextValue {
25 gameState: GameState
26 boxBitmap: BoxBitmap
27 pendingEdge: number | null
28 placeEdge: (edgeId: number) => void
29 isConnected: boolean
30 isLoading: boolean
31 isReadyToRender: boolean
32 notifyCanvasRendered: () => void
33 error: string | null
34 version: number
35 recentEvents: Array<RecentEvent>
36 isGameComplete: boolean
37 winner: number | null // teamId (0-3) or null if tie
39​
40const GameStateContext = createContext<GameStateContextValue | null>(null)
41​
42export interface GameStateProviderProps {
43 children: ReactNode
45​
46// How long to keep recent events for animation (ms)
47const RECENT_EVENT_TTL = 1000
48​
49export function GameStateProvider({ children }: GameStateProviderProps) {
50 // Use a ref for the game state to avoid re-renders on every event
51 const gameStateRef = useRef<GameState>(new GameState())
52​
53 // Shared bitmap for rendering (1px per box, used by minimap and main canvas)
54 const boxBitmapRef = useRef<BoxBitmap>(new BoxBitmap())
55​
56 // Version counter to trigger re-renders when needed
57 const [version, setVersion] = useState(0)
58​
59 // UI state
60 const [pendingEdge, setPendingEdge] = useState<number | null>(null)
61 const [isConnected, setIsConnected] = useState(false)
62 const [isLoading, setIsLoading] = useState(true)
63 const [isReadyToRender, setIsReadyToRender] = useState(false)
64 const [error, setError] = useState<string | null>(null)
65​
66 // Track recent events for minimap pop animation
67 const [recentEvents, setRecentEvents] = useState<Array<RecentEvent>>([])
68 const eventIdRef = useRef(0)
69 // Track edge IDs placed by the local user (to identify local vs remote events)
70 const localEdgeIdsRef = useRef<Set<number>>(new Set())
71​
72 // Suppress move animations while installing the initial board snapshot.
73 const initialSyncCompleteRef = useRef(false)
74 const pendingFirstRenderRef = useRef(false)
75 const snapshotAppliedAtRef = useRef(0)
76​
77 // 60fps render throttling - only update version once per frame
78 const renderScheduledRef = useRef(false)
79 const pendingRecentEventsRef = useRef<Array<RecentEvent>>([])
80 const bitmapDirtyRef = useRef(false)
81​
82 // Get team and quota from contexts
83 const { teamId } = useTeam()
84 const { consume, syncFromServer, refund, remaining, notifyNoMoves } = useQuota()
85​
86 // Schedule a render for next animation frame (60fps throttle)
87 const scheduleRender = useCallback(() => {
88 if (renderScheduledRef.current) return
89​
90 renderScheduledRef.current = true
91 requestAnimationFrame(() => {
92 renderScheduledRef.current = false
93​
94 // Commit bitmap if dirty
95 if (bitmapDirtyRef.current) {
96 boxBitmapRef.current.commit()
97 bitmapDirtyRef.current = false
98 }
99​
100 // Add pending recent events
101 if (pendingRecentEventsRef.current.length > 0) {
102 const newEvents = pendingRecentEventsRef.current
103 pendingRecentEventsRef.current = []
104 const now = Date.now()
105 setRecentEvents((prev) => {
106 const cutoff = now - RECENT_EVENT_TTL
107 const filtered = prev.filter((e) => e.timestamp > cutoff)
108 return [...filtered, ...newEvents]
109 })
110 }
111​
112 // Trigger re-render
113 setVersion((v) => v + 1)
114 })
115 }, [])
116​
117 // Install tile owners directly; unordered snapshots must never infer box claims.
118 const handleTiles = useCallback(
119 (tiles: readonly BoardTile[], reset: boolean) => {
120 if (reset) {
121 setIsLoading(true)
122 gameStateRef.current = new GameState()
123 localEdgeIdsRef.current.clear()
124 pendingRecentEventsRef.current = []
125 setRecentEvents([])
126 }
127 const now = Date.now()
128 for (const tile of tiles) {
129 const { edgesChanged, boxesChanged } = gameStateRef.current.applyTile(tile)
130 if (!reset) {
131 for (const boxId of boxesChanged) {
132 const owner = gameStateRef.current.getBoxOwner(boxId)
133 boxBitmapRef.current.updateBox(boxId, owner - 1)
134 bitmapDirtyRef.current = true
135 }
136 for (const event of edgesChanged) {
137 const isLocal = localEdgeIdsRef.current.delete(event.edgeId)
138 pendingRecentEventsRef.current.push({
139 ...event,
140 id: eventIdRef.current++,
141 timestamp: now,
142 isLocal,
143 })
144 }
145 }
146 }
147 setPendingEdge((current) =>
148 current !== null && gameStateRef.current.isEdgeTaken(current) ? null : current,
149 )
150 if (reset) {
151 initialSyncCompleteRef.current = true
152 boxBitmapRef.current.rebuildFromState(gameStateRef.current)
153 bitmapDirtyRef.current = false
154 pendingFirstRenderRef.current = true
155 snapshotAppliedAtRef.current = performance.now()
156 setIsReadyToRender(true)
157 setVersion((value) => value + 1)
158 } else scheduleRender()
159 },
160 [scheduleRender],
161 )
162​
163 // Handle connection events
164 const handleConnected = useCallback(() => {
165 setIsConnected(true)
166 if (initialSyncCompleteRef.current && !pendingFirstRenderRef.current) {
167 setIsLoading(false)
168 }
169 setError(null)
170 }, [])
171​
172 const handleDisconnected = useCallback(() => {
173 setIsConnected(false)
174 }, [])
175​
176 const handleError = useCallback((err: Error) => {
177 setError(err.message)
178 }, [])
179​
180 // Clear the recharge prompt as soon as another move becomes available.
181 useEffect(() => {
182 if (remaining > 0 && error === OUT_OF_MOVES_MESSAGE) {
183 setError(null)
184 }
185 }, [remaining, error])
186​
187 const notifyCanvasRendered = useCallback(() => {
188 if (pendingFirstRenderRef.current) {
189 console.info("[Board Realtime] First canvas rendered", {
190 sinceStateAppliedMs: Math.round(performance.now() - snapshotAppliedAtRef.current),
191 })
192 pendingFirstRenderRef.current = false
193 setIsReadyToRender(false)
194 setIsLoading(false)
195 }
196 }, [])
197​
198 // Handle the game timestamp from the metadata subscription.
199 // If the timestamp changes (game reset), clear client-side cached data
200 const handleGameStartTimestamp = useCallback((timestamp: number) => {
201 try {
202 // Validate the incoming timestamp
203 if (!Number.isFinite(timestamp) || timestamp <= 0) {
204 console.warn(`[GameState] Invalid timestamp received:`, timestamp)
205 return
206 }
207​
208 const storedTimestamp = localStorage.getItem(GAME_START_TIMESTAMP_KEY)
209 const storedValue = storedTimestamp ? parseInt(storedTimestamp, 10) : null
210​
211 // Validate stored value - if invalid, treat as no stored value
212 const validStoredValue =
213 storedValue !== null && Number.isFinite(storedValue) && storedValue > 0 ? storedValue : null
214​
215 if (validStoredValue !== null && validStoredValue !== timestamp) {
216 // Game has been reset - clear stale client data
217 console.log(`[GameState] Game reset detected. Old: ${validStoredValue}, New: ${timestamp}`)
218 localStorage.removeItem(QUOTA_KEY)
219 localStorage.removeItem(LOCAL_BOXES_KEY)
220 // Force a page reload to reset all state
221 window.location.reload()
222 }
223​
224 // Store the current timestamp
225 localStorage.setItem(GAME_START_TIMESTAMP_KEY, String(timestamp))
226 } catch (err) {
227 console.error(`[GameState] Error handling game start timestamp:`, err)
228 // Clear potentially corrupted localStorage data
229 localStorage.removeItem(GAME_START_TIMESTAMP_KEY)
230 }
231 }, [])
232​
233 // Subscribe to authoritative tiles and game metadata.
234 const { awaitTxId, reconnect } = useBoardRealtime({
235 onTiles: handleTiles,
236 onError: handleError,
237 onConnected: handleConnected,
238 onDisconnected: handleDisconnected,
239 onGameStartTimestamp: handleGameStartTimestamp,
240 })
241​
242 // Place an edge on the board
243 const placeEdge = useCallback(
244 async (edgeId: number) => {
245 if (!isConnected || !initialSyncCompleteRef.current) return
246 // Clear any previous error on new attempt
247 setError(null)
248​
249 // Check if edge is already taken
250 if (gameStateRef.current.isEdgeTaken(edgeId)) {
251 return
252 }
253​
254 // Optimistically consume quota (will be synced from server response)
255 if (!consume()) {
256 setError(OUT_OF_MOVES_MESSAGE)
257 return
258 }
259​
260 // Set pending edge for optimistic UI
261 setPendingEdge(edgeId)
262 playPencilSound()
263​
264 // Track as local edge for pop animation filtering
265 localEdgeIdsRef.current.add(edgeId)
266​
267 try {
268 const response = await fetch(`/api/draw`, {
269 method: `POST`,
270 headers: { "Content-Type": `application/json` },
271 body: JSON.stringify({ edgeId }),
272 })
273 const result = await response.json()
274​
275 if (result.ok) {
276 if (typeof result.boxesClaimed === "number") playBoxSound(result.boxesClaimed)
277 // Success - Realtime will confirm the committed transaction.
278 // Sync quota from server (includes any refunds for completed boxes)
279 if (typeof result.quotaRemaining === `number`) {
280 syncFromServer(result.quotaRemaining, result.refillIn, result.boxesClaimed)
281 }
282 try {
283 await awaitTxId(result.txid)
284 } catch {
285 reconnect()
286 setError(`Move saved; waiting for synchronization`)
287 }
288 } else {
289 // Handle error codes
290 // Sync quota from server response if provided (even on errors)
291 if (typeof result.quotaRemaining === `number`) {
292 syncFromServer(result.quotaRemaining, result.refillIn)
293 }
294​
295 switch (result.code) {
296 case `EDGE_TAKEN`:
297 // Server already refunded - quota synced above
298 setError(null) // Not really an error, just already taken
299 break
300 case `QUOTA_EXHAUSTED`:
301 // Server says no quota - already synced above
302 notifyNoMoves()
303 setError(OUT_OF_MOVES_MESSAGE)
304 break
305 case `NO_IDENTITY`:
306 refund() // Fallback refund if no server quota info
307 setError(`No team assigned - please refresh`)
308 break
309 case `GAME_COMPLETE`:
310 refund()
311 setError(`Game is complete!`)
312 break
313 case `INVALID_EDGE`:
314 refund()
315 setError(`Invalid edge`)
316 break
317 case `DATABASE_ERROR`:
318 refund()
319 setError(`Database error - please try again`)
320 break
321 default:
322 refund()
323 setError(`Failed to place edge: ${result.code}`)
324 }
325​
326 // Clear pending edge on error
327 localEdgeIdsRef.current.delete(edgeId)
328 setPendingEdge(null)
329 }
330 } catch (err) {
331 // Network error - refund locally since we can't reach server
332 refund()
333 localEdgeIdsRef.current.delete(edgeId)
334 setPendingEdge(null)
335 setError(err instanceof Error ? err.message : `Failed to place edge`)
336 }
337 },
338 [consume, syncFromServer, refund, teamId, awaitTxId, reconnect, isConnected, notifyNoMoves],
339 )
340​
341 const value: GameStateContextValue = {
342 gameState: gameStateRef.current,
343 boxBitmap: boxBitmapRef.current,
344 pendingEdge,
345 placeEdge,
346 isConnected,
347 isLoading,
348 isReadyToRender,
349 notifyCanvasRendered,
350 error,
351 version,
352 recentEvents,
353 isGameComplete: gameStateRef.current.isComplete(),
354 winner: gameStateRef.current.getWinner(),
355 }
356​
357 return <GameStateContext.Provider value={value}>{children}</GameStateContext.Provider>
359​
360export function useGameStateContext(): GameStateContextValue {
361 const ctx = useContext(GameStateContext)
362 if (!ctx) {
363 throw new Error(`useGameStateContext must be used within GameStateProvider`)
364 }
365 return ctx