6 Commits

Author SHA1 Message Date
b00519347a cleanup 2025-12-04 19:57:06 +05:30
8436cdbcdd refactor(game): unify move handling using typed payloads and remove UI-driven handlers
- Removed onCellClick from TicTacToeGameProps and migrated move sending inside TicTacToeGame
- Updated TicTacToeGame to:
  - import TicTacToePayload
  - use movePayload() builder
  - send moves using handleMove() with matchId + sendMatchData
  - remove old matchId destructuring duplication

- Updated BattleshipGame to:
  - import BattleshipPayload
  - use placePayload() and shootPayload() helpers
  - collapse place and shoot handlers into a single handleMove()
  - send typed payloads instead of raw objects

- Updated App.tsx:
  - Removed handleCellClick and no longer pass onCellClick down
  - Created typed ticTacToeProps and battleshipProps without UI callbacks
  - Cleaned unused state and simplified board rendering
  - Use {...commonProps} to propagate shared game state

- Updated props:
  - Removed TicTacToeGameProps.onCellClick
  - BattleshipGameProps continues to extend GameProps

- Removed duplicate MatchDataModel definition from interfaces/models
- Fixed imports to use revised models and payload types

This refactor completes the transition from UI-triggered handlers to
typed action payloads per game, significantly improving type safety,
consistency, and separation of concerns.
2025-12-04 19:56:46 +05:30
135fdd332d refactor(types): rename interfaces with *Model suffix and update references across codebase
- Renamed GameMetadata → GameMetadataModel for naming consistency
- Renamed Board → BoardModel
- Renamed MatchDataMessage → MatchDataModel (duplicate name removed)
- Updated all imports and references in:
  - NakamaProvider
  - contexts.ts
  - refs.ts
  - states.ts
  - Player.tsx
  - props and models files
- Updated GameState to use BoardModel instead of Board
- Updated NakamaContextType to use GameMetadataModel and MatchDataModel
- Updated NakamaRefs to store gameMetadataRef: RefObject<GameMetadataModel>
- Updated joinMatchmaker() and exitMatchmaker() signatures
- Updated onMatchData() to emit MatchDataModel
- Updated Player component to use PlayerProps type instead of inline typing

This commit standardizes naming conventions by ensuring all schema/interface
definitions follow the *Model naming pattern, improving clarity and type consistency
across the project.
2025-12-04 19:29:35 +05:30
8dc41fca2c using correct props instead of internal props for TicTacToeGame.tsx and BattleshipGame.tsx 2025-12-04 19:24:14 +05:30
fc7cb8efb6 renamed BattleShipGame.tsx to BattleshipGame.tsx to match props name. using props interface for both instead of using commonProps 2025-12-04 19:22:07 +05:30
06bdc92190 refactor(game): unify GameState, standardize board props, and rename game components
- Replaced multiple App-level state fields with unified GameState
- Added INITIAL_GAME_STATE and migrated App.tsx to use single game state
- Introduced GameProps as shared base props for all turn-based board games
- Created TicTacToeGameProps and BattleshipGameProps extending GameProps
- Updated TicTacToe and Battleship components to use new props
- Replaced verbose prop passing with spread {...commonProps}
- Updated renderGameBoard to use game.metadata consistently
- Renamed TicTacToeBoard -> TicTacToeGame for clarity
- Renamed BattleShipBoard -> BattleShipGame for naming consistency
- Updated all import paths to reflect new component names
- Replaced MatchDataMessage with MatchDataModel
- Moved GameState definition from models.ts to interfaces/states.ts
- Removed old board-specific prop structures and per-field state management
- Increased type safety and reduced duplication across the codebase

This commit consolidates game state flow, introduces a clean component props
architecture, and standardizes naming convention
2025-12-04 19:16:20 +05:30
16 changed files with 210 additions and 162 deletions

View File

@@ -1,57 +1,72 @@
import React, { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { useNakama } from "./providers/NakamaProvider";
import Player from "./Player";
import { PlayerModel } from "./interfaces/models";
import TicTacToeBoard from "./games/tictactoe/TicTacToeBoard";
import BattleShipBoard from "./games/battleship/BattleShipBoard";
import Player from "./Player";
import TicTacToeGame from "./games/tictactoe/TicTacToeGame";
import { TicTacToeGameProps } from "./games/tictactoe/props";
import BattleshipGame from "./games/battleship/BattleshipGame"
import { BattleshipGameProps } from "./games/battleship/props";
import { GameState } from "./interfaces/states";
import { GameProps } from "./interfaces/props";
const INITIAL_GAME_STATE: GameState = {
boards: {},
turn: 0,
winner: null,
gameOver: false,
players: [],
metadata: {},
};
export default function App() {
// setting up a 2D game boards
const [boards, setBoards] = useState<Record<string, { grid: string[][] }>>({});
const [turn, setTurn] = useState<number>(0);
const [winner, setWinner] = useState<string | null>(null);
const [gameOver, setGameOver] = useState<boolean | null>(null);
const [players, setPlayers] = useState<PlayerModel[]>([]);
const [metadata, setMetadata] = useState<Record<string, any>>({});
// unified game state
const [game, setGame] = useState<GameState>(INITIAL_GAME_STATE);
const { onMatchData, matchId, session } = useNakama();
const { sendMatchData, onMatchData, matchId, session } = useNakama();
const commonProps: GameProps = {
boards: game.boards,
turn: game.turn,
winner: game.winner,
gameOver: game.gameOver,
players: game.players,
myUserId: session?.user_id ?? null,
};
const ticTacToeProps: TicTacToeGameProps = {
...commonProps,
};
const battleshipProps: BattleshipGameProps = {
...commonProps,
metadata: game.metadata,
};
// ---------------------------------------------------
// RENDER GAME BOARD
// ---------------------------------------------------
function renderGameBoard() {
if (!matchId || !metadata?.game) return null;
if (!matchId || !game.metadata?.game) return null;
switch (metadata.game) {
switch (game.metadata.game) {
case "tictactoe":
return (
<TicTacToeBoard
boards={boards}
turn={turn}
winner={winner}
gameOver={gameOver}
players={players}
myUserId={session?.user_id ?? null}
onCellClick={handleCellClick}
<TicTacToeGame
{...ticTacToeProps}
/>
);
case "battleship":
return (
<BattleShipBoard
boards={boards}
turn={turn}
winner={winner}
gameOver={gameOver}
players={players}
myUserId={session?.user_id ?? null}
metadata={metadata}
<BattleshipGame
{...battleshipProps}
/>
);
default:
return <div>Unknown game: {metadata.game}</div>;
return <div>Unknown game: {game.metadata.game}</div>;
}
}
// ------------------------------------------
// MATCH DATA CALLBACK (from Player component)
// ------------------------------------------
@@ -62,23 +77,21 @@ export default function App() {
const state = msg.data;
console.log("Match state:", state);
setBoards(state.boards);
setTurn(state.turn);
setGameOver(state.game_over);
if (state.winner >= 0) {
setWinner(state.players[state.winner].username);
// } else if (state.game_over) {
// // Game ended but winner = -1 → draw
// setWinner("draw");
} else {
// Ongoing game, no winner
setWinner(null);
}
setPlayers(state.players || []);
setMetadata(state.metadata || {});
setGame({
boards: state.boards,
turn: state.turn,
gameOver: state.game_over,
winner:
state.winner >= 0 ? state.players[state.winner].username : null,
players: state.players ?? [],
metadata: state.metadata ?? {},
});
}
}
// ---------------------------------------------------
// EFFECTS
// ---------------------------------------------------
useEffect(() => {
document.body.style.overflow = "hidden";
return () => {
@@ -90,15 +103,9 @@ export default function App() {
onMatchData(onMatchDataCallback);
}, [onMatchData]);
// ------------------------------------------
// SEND A MOVE
// ------------------------------------------
function handleCellClick(row: number, col: number) {
if (!matchId) return;
sendMatchData(matchId, 1, {data: {row, col}});
}
// ---------------------------------------------------
// UI LAYOUT
// ---------------------------------------------------
return (
<div
style={{

View File

@@ -1,12 +1,11 @@
import React, { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useNakama } from "./providers/NakamaProvider";
import { PlayerProps } from "./interfaces/props";
export default function Player({
onMatchDataCallback,
}: {
onMatchDataCallback: (msg: any) => void;
}) {
}: PlayerProps) {
const {
session,
matchId,

View File

@@ -1,20 +1,15 @@
import React, { useMemo } from "react";
import { motion } from "framer-motion";
import { useNakama } from "../../providers/NakamaProvider";
import { PlayerModel } from "../../models/player";
import PlacementGrid from "./placement/PlacementGrid";
import ShotGrid from "./battle/ShotGrid";
interface BattleBoardProps {
boards: Record<string, { grid: string[][] }>;
players: PlayerModel[];
myUserId: string | null;
turn: number;
winner: string | null;
gameOver: boolean | null;
metadata: Record<string, any>;
}
import { BattleshipGameProps } from "./props";
import { BattleshipPayload } from "./models";
import {
placePayload,
shootPayload,
} from "./utils";
const Fleet: Record<string, number> = {
carrier: 5,
@@ -25,7 +20,7 @@ const Fleet: Record<string, number> = {
};
const FLEET_ORDER = ["carrier", "battleship", "cruiser", "submarine", "destroyer"];
export default function BattleShipBoard({
export default function BattleshipGame({
boards,
players,
myUserId,
@@ -33,7 +28,7 @@ export default function BattleShipBoard({
winner,
gameOver,
metadata,
}: BattleBoardProps) {
}: BattleshipGameProps) {
const { sendMatchData, matchId } = useNakama();
const myIndex = players.findIndex((p) => p.user_id === myUserId);
@@ -50,28 +45,10 @@ export default function BattleShipBoard({
const nextShip = FLEET_ORDER[placed] || null;
const nextShipSize = nextShip ? Fleet[nextShip] : null;
// ------------------- PLACE SHIP -------------------
function handlePlace(ship: string, r: number, c: number, dir: "h" | "v") {
sendMatchData(matchId!, 1, {
action: "place",
data: {
ship: ship,
row: r,
col: c,
dir,
}
});
}
function handleMove(matchPayload: BattleshipPayload) {
if (!matchId) return;
// ------------------- SHOOT -------------------
function handleShoot(r: number, c: number) {
sendMatchData(matchId!, 1, {
action: "shoot",
data: {
row: r,
col: c,
}
});
sendMatchData(matchId!, 1, matchPayload);
}
// ------------------- STATUS LABEL -------------------
@@ -100,7 +77,11 @@ export default function BattleShipBoard({
shipBoard={myShips}
shipName={nextShip}
shipSize={nextShipSize}
onPlace={handlePlace}
onPlace={(
s,r,c,d
) => handleMove(
placePayload(s,r,c,d)
)}
/>
)}
@@ -113,7 +94,11 @@ export default function BattleShipBoard({
grid={myShots}
isMyTurn={isMyTurn}
gameOver={!!gameOver}
onShoot={handleShoot}
onShoot={(
r,c
) => handleMove(
shootPayload(r,c)
)}
/>
<h3 style={{ marginTop: "18px" }}>Your Ships</h3>

View File

@@ -0,0 +1,15 @@
import {
MatchDataModel,
} from '../../interfaces/models'
export interface BattleshipPayload {
action: "place" | "shoot"; // extend as needed
data: {
ship?: string; // only for placement
row: number;
col: number;
dir?: "h" | "v";
};
}
export type BattleshipMatchDataModel = MatchDataModel<BattleshipPayload>;

View File

@@ -1,15 +1,8 @@
import {
Board,
PlayerModel,
} from '../../interfaces/models'
GameProps,
} from '../../interfaces/props'
export interface BattleShipBoardProps {
boards: Record<string, Board>;
turn: number;
winner: string | null;
gameOver: boolean | null;
players: PlayerModel[];
myUserId: string | null;
export interface BattleshipGameProps extends GameProps {
metadata: Record<string, any>;
}

View File

@@ -0,0 +1,22 @@
import {
BattleshipPayload
} from "./models";
export function placePayload(
ship: string,
row: number,
col: number,
dir: "h" | "v"
): BattleshipPayload {
return {
action: "place",
data: { ship, row, col, dir }
};
}
export function shootPayload(row: number, col: number): BattleshipPayload {
return {
action: "shoot",
data: { row, col }
};
}

View File

@@ -2,32 +2,23 @@ import React, { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useNakama } from "../../providers/NakamaProvider";
import getHaiku from "../../utils/haikus";
import { PlayerModel } from "../../models/player";
interface BoardProps {
boards: Record<string, { grid: string[][] }>;
turn: number;
winner: string | null;
gameOver: boolean | null;
players: PlayerModel[];
myUserId: string | null;
onCellClick: (row: number, col: number) => void;
}
import { TicTacToeGameProps } from "./props";
import { TicTacToePayload } from "./models";
import { movePayload } from "./utils";
export default function TicTacToeBoard({
export default function TicTacToeGame({
boards,
turn,
winner,
gameOver,
players,
myUserId,
onCellClick,
}: BoardProps) {
}: TicTacToeGameProps) {
const { sendMatchData, matchId } = useNakama();
const myIndex = players.findIndex(p => p.user_id === myUserId);
const gameReady = players.length === 2;
const {
matchId
} = useNakama();
const mySymbol =
myIndex !== null && players[myIndex]
@@ -76,6 +67,12 @@ export default function TicTacToeBoard({
return () => clearTimeout(timer);
}, [haikuIndex]);
function handleMove(matchPayload: TicTacToePayload) {
if (!matchId) return;
sendMatchData(matchId!, 1, matchPayload);
}
return (
<>
{matchId && (
@@ -141,7 +138,9 @@ export default function TicTacToeBoard({
: {}
}
whileTap={!disabled ? { scale: 0.85 } : {}}
onClick={() => !disabled && onCellClick(rIdx, cIdx)}
onClick={() => !disabled && handleMove(
movePayload(rIdx, cIdx)
)}
style={{
width: "80px",
height: "80px",

View File

@@ -0,0 +1,11 @@
import {
MatchDataModel,
} from '../../interfaces/models'
export interface TicTacToePayload {
data: {
row: number;
col: number;
};
}
export type TicTacToeMatchDataModel = MatchDataModel<TicTacToePayload>;

View File

@@ -1,15 +1,8 @@
import {
Board,
PlayerModel,
} from '../../interfaces/models'
GameProps,
} from '../../interfaces/props'
export interface TicTacToeBoardProps {
boards: Record<string, Board>;
turn: number;
winner: string | null;
gameOver: boolean | null;
players: PlayerModel[];
myUserId: string | null;
onCellClick: (row: number, col: number) => void;
export interface TicTacToeGameProps extends GameProps {
// metadata: Record<string, any>;
}

View File

@@ -0,0 +1,12 @@
import {
TicTacToePayload
} from "./models";
export function movePayload(
row: number,
col: number,
): TicTacToePayload {
return {
data: { row, col }
};
}

View File

@@ -11,8 +11,8 @@ import {
} from "@heroiclabs/nakama-js/dist/api.gen"
import {
GameMetadata,
MatchDataMessage,
GameMetadataModel,
MatchDataModel,
} from './models'
@@ -25,13 +25,13 @@ export interface NakamaContextType {
loginOrRegister(username?: string): Promise<void>;
logout(): Promise<void>;
joinMatchmaker(gameMetadata: GameMetadata): Promise<string>;
exitMatchmaker(gameMetadata: GameMetadata): Promise<void>;
joinMatchmaker(gameMetadata: GameMetadataModel): Promise<string>;
exitMatchmaker(gameMetadata: GameMetadataModel): Promise<void>;
joinMatch(matchId: string): Promise<void>;
sendMatchData(matchId: string, op: number, data: object): void;
onMatchData(cb: (msg: MatchDataMessage) => void): void;
onMatchData(cb: (msg: MatchDataModel) => void): void;
getLeaderboardTop(): Promise<ApiLeaderboardRecordList>;
listOpenMatches(): Promise<ApiMatch[]>;

View File

@@ -5,32 +5,17 @@ export interface PlayerModel {
metadata: Record<string, string>; // e.g. { symbol: "X" }
}
export interface MatchDataMessage<T = any> {
export interface MatchDataModel<T = any> {
opCode: number;
data: T;
userId: string | null;
}
export interface Board {
export interface BoardModel {
grid: string[][];
}
export interface GameState {
boards: Record<string, Board>;
turn: number;
winner: string | null;
gameOver: boolean;
players: PlayerModel[];
metadata: Record<string, any>;
}
export interface GameMetadata {
export interface GameMetadataModel {
game: string;
mode: string;
}
export interface MatchDataMessage<T = any> {
opCode: number;
data: T;
userId: string | null;
}

View File

@@ -1,7 +1,19 @@
import {
MatchDataMessage,
MatchDataModel,
} from './models'
import {
GameState
} from "./states";
export interface PlayerProps {
onMatchDataCallback: (msg:MatchDataMessage) => void;
onMatchDataCallback: (msg:MatchDataModel) => void;
}
export interface GameProps
extends Pick<
GameState,
"boards" | "turn" | "winner" | "gameOver" | "players"
> {
myUserId: string | null;
}

View File

@@ -5,11 +5,11 @@ import {
} from "@heroiclabs/nakama-js";
import {
GameMetadata,
GameMetadataModel,
} from './models'
export interface NakamaRefs {
socketRef: React.RefObject<Socket | null>;
gameMetadataRef: React.RefObject<GameMetadata | null>;
gameMetadataRef: React.RefObject<GameMetadataModel | null>;
}

View File

@@ -3,9 +3,24 @@ import {
Socket
} from "@heroiclabs/nakama-js";
import {
BoardModel,
PlayerModel,
} from "./models"
export interface NakamaProviderState {
session: Session | null;
socket: Socket | null;
matchId: string | null;
matchmakerTicket: string | null;
}
export interface GameState {
boards: Record<string, BoardModel>;
turn: number;
winner: string | null;
gameOver: boolean;
players: PlayerModel[];
metadata: Record<string, any>;
}

View File

@@ -22,7 +22,7 @@ import {
import { NakamaContextType } from "../interfaces/contexts";
import { NakamaRefs } from "../interfaces/refs";
import { NakamaProviderState } from "../interfaces/states";
import { GameMetadata, MatchDataMessage } from "../interfaces/models";
import { GameMetadataModel, MatchDataModel } from "../interfaces/models";
function getOrCreateDeviceId(): string {
const key = "nakama.deviceId";
@@ -68,7 +68,7 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
// --------------------------------------
const refs: NakamaRefs = {
socketRef: useRef<Socket | null>(null),
gameMetadataRef: useRef<GameMetadata | null>(null),
gameMetadataRef: useRef<GameMetadataModel | null>(null),
};
// Helpers to update internal state cleanly
@@ -202,7 +202,7 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
// ----------------------------------------------------
// MATCHMAKING
// ----------------------------------------------------
async function joinMatchmaker(gameMetadata: GameMetadata) {
async function joinMatchmaker(gameMetadata: GameMetadataModel) {
const socket = refs.socketRef.current;
if (!socket) throw new Error("Socket missing");
@@ -267,7 +267,7 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
// ----------------------------------------------------
// MATCH DATA LISTENER
// ----------------------------------------------------
function onMatchData(cb: (msg: MatchDataMessage) => void) {
function onMatchData(cb: (msg: MatchDataModel) => void) {
if (!internal.socket) return;
internal.socket.onmatchdata = (m: MatchData) => {