import React, { useMemo } from "react"; import { motion } from "framer-motion"; import { useNakama } from "../../providers/NakamaProvider"; import PlacementGrid from "./placement/PlacementGrid"; import ShotGrid from "./battle/ShotGrid"; import { BattleshipGameProps } from "./props"; import { BattleshipPayload } from "./models"; import { placePayload, shootPayload, } from "./utils"; const Fleet: Record = { carrier: 5, battleship: 4, cruiser: 3, submarine: 3, destroyer: 2, }; const FLEET_ORDER = ["carrier", "battleship", "cruiser", "submarine", "destroyer"]; export default function BattleshipGame({ boards, players, myUserId, turn, winner, gameOver, metadata, }: BattleshipGameProps) { const { sendMatchData, matchId } = useNakama(); const myIndex = players.findIndex((p) => p.user_id === myUserId); const oppIndex = myIndex === 0 ? 1 : 0; const phase = metadata["phase"] ?? "lobby"; const isMyTurn = phase === "battle" && turn === myIndex; const myShips = boards[`p${myIndex}_ships`]?.grid ?? [[]]; const myShots = boards[`p${myIndex}_shots`] ?.grid ?? [[]]; const placed = metadata[`p${myIndex}_placed`] ?? 0; const nextShip = FLEET_ORDER[placed] || null; const nextShipSize = nextShip ? Fleet[nextShip] : null; function handleMove(matchPayload: BattleshipPayload) { if (!matchId) return; sendMatchData(matchId!, 1, matchPayload); } // ------------------- STATUS LABEL ------------------- const status = useMemo(() => { if (phase === "lobby") return `In Lobby`; if (winner !== null) return `Winner: Player ${winner}`; if (gameOver) return "Game over — draw"; if (phase === "placement") return `Place your ${nextShip ?? ""}`; if (myIndex === -1) return "Spectating"; if (!isMyTurn) return "Opponent’s turn"; return "Your turn"; }, [winner, gameOver, phase, isMyTurn, myIndex, nextShip]); return (

{status}

{/* ---------------- PHASE 1: PLACEMENT ---------------- */} {phase === "placement" && nextShip && ( handleMove( placePayload(s,r,c,d) )} /> )} {/* ---------------- PHASE 2: BATTLE ---------------- */} {phase === "battle" && ( <>

Your Shots

handleMove( shootPayload(r,c) )} />

Your Ships

{}} /> )} {/* ---------------- WINNER UI ---------------- */} {winner !== null && ( 🎉 Player {winner} Wins! 🎉 )}
); }