GDG Logo

Game Dev with React Workshop

Game State Management (atom.js)

This file defines the global state management for the space shooter game using Jotai atoms. Each atom represents a specific piece of game state, from player position to game timer.

1. File Declaration and Import

import { atom } from 'jotai';

File setup: - Imports the atom function from Jotai - Jotai provides primitive atoms for building state management

2. Player Position State

export const playerPositionAtom = atom({ x: 375, y: 20 });

Player position management: - Tracks spaceship's position on the game board - x: 375 centers the spaceship horizontally (based on game width) - y: 20 positions the spaceship near the bottom of the screen

3. Game Score State

export const scoreAtom = atom(0);

Score tracking: - Initializes game score to 0 - Updated when player successfully hits obstacles - Used for displaying current score and final results

4. Game State Management

export const gameOverAtom = atom(false);

Game state control: - Tracks whether the game is active or over - false: game is running - true: game has ended (collision occurred)

5. Obstacles Management

export const obstaclesAtom = atom([]);

Obstacles tracking: - Stores array of all active obstacles - Each obstacle contains position and ID - Dynamically updated during gameplay - Empty array initially, populated as game progresses

6. Bullets Management

export const bulletsAtom = atom([]);

Bullets tracking: - Manages all active bullets on screen - Each bullet contains position and unique ID - Updated when player shoots or bullets hit obstacles - Empty array initially

7. Collision State

export const collisionStateAtom = atom(false);

Collision detection state: - Tracks active collisions - Prevents multiple collision detections - Reset when game restarts - false by default

8. Bullet Hits Tracking

export const bulletHitsAtom = atom([]);

Bullet hits management: - Records successful bullet hits - Used for score calculation - Helps manage obstacle removal - Empty array initially

9. Game Timer State

export const timerAtom = atom(0);

Game timer management: - Tracks game duration in seconds - Starts at 0 when game begins - Increments every second during gameplay - Used for displaying game duration