This commit is contained in:
2026-03-27 10:43:10 -04:00
Unverified
parent 2495f41df9
commit c8781fddaa
15 changed files with 1650 additions and 1630 deletions

View File

@@ -0,0 +1,4 @@
node_modules
.next
out
connect4-moderator-server

4
connect4-ui/.prettierrc Normal file
View File

@@ -0,0 +1,4 @@
{
"useTabs": false,
"tabWidth": 2
}

View File

@@ -8,5 +8,8 @@
body {
background-color: var(--background);
color: var(--foreground);
font-family: system-ui, -apple-system, sans-serif;
font-family:
system-ui,
-apple-system,
sans-serif;
}

View File

@@ -4,23 +4,23 @@ import Nav from "@/components/Nav";
import { ConnectionProvider } from "@/lib/connection";
export const metadata: Metadata = {
title: "Connect4 Moderator",
description: "Watch matches, track tournaments, and play Connect4",
title: "Connect4 Moderator",
description: "Watch matches, track tournaments, and play Connect4",
};
export default function RootLayout({
children,
children,
}: {
children: React.ReactNode;
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className="min-h-screen bg-gray-950 text-gray-100">
<ConnectionProvider>
<Nav />
<main className="max-w-7xl mx-auto px-4 py-6">{children}</main>
</ConnectionProvider>
</body>
</html>
);
return (
<html lang="en">
<body className="min-h-screen bg-gray-950 text-gray-100">
<ConnectionProvider>
<Nav />
<main className="max-w-7xl mx-auto px-4 py-6">{children}</main>
</ConnectionProvider>
</body>
</html>
);
}

View File

@@ -6,80 +6,80 @@ import { DEFAULT_WS_URL } from "@/lib/protocol";
import { useConnection } from "@/lib/connection";
export default function Home() {
const router = useRouter();
const {
connect,
role,
status,
wsUrl: connectedWsUrl,
shouldRedirectToConnect,
clearRedirectFlag,
} = useConnection();
const router = useRouter();
const {
connect,
role,
status,
wsUrl: connectedWsUrl,
shouldRedirectToConnect,
clearRedirectFlag,
} = useConnection();
const [wsUrl, setWsUrl] = useState(DEFAULT_WS_URL);
const [wsUrl, setWsUrl] = useState(DEFAULT_WS_URL);
useEffect(() => {
if (shouldRedirectToConnect) {
clearRedirectFlag();
}
}, [shouldRedirectToConnect, clearRedirectFlag]);
useEffect(() => {
if (shouldRedirectToConnect) {
clearRedirectFlag();
}
}, [shouldRedirectToConnect, clearRedirectFlag]);
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
connect({ role: "observer", wsUrl });
router.push("/spectate");
};
connect({ role: "observer", wsUrl });
router.push("/spectate");
};
return (
<div className="max-w-3xl mx-auto py-10">
<div className="bg-gray-900 border border-gray-700 rounded-2xl p-6 md:p-8 flex flex-col gap-6">
<div>
<h1 className="text-3xl font-bold text-white">
Connect to Moderator Server
</h1>
<p className="text-sm text-gray-400 mt-2">
Connect as an observer to watch live matches and tournaments.
</p>
</div>
return (
<div className="max-w-3xl mx-auto py-10">
<div className="bg-gray-900 border border-gray-700 rounded-2xl p-6 md:p-8 flex flex-col gap-6">
<div>
<h1 className="text-3xl font-bold text-white">
Connect to Moderator Server
</h1>
<p className="text-sm text-gray-400 mt-2">
Connect as an observer to watch live matches and tournaments.
</p>
</div>
{shouldRedirectToConnect && (
<div className="rounded-lg border border-red-700 bg-red-950/40 px-4 py-3 text-sm text-red-200">
Connection lost. Please reconnect to continue.
</div>
)}
{shouldRedirectToConnect && (
<div className="rounded-lg border border-red-700 bg-red-950/40 px-4 py-3 text-sm text-red-200">
Connection lost. Please reconnect to continue.
</div>
)}
{status === "connected" && role && (
<div className="rounded-lg border border-green-700 bg-green-950/30 px-4 py-3 text-sm text-green-200">
Connected to {connectedWsUrl} as observer.
</div>
)}
{status === "connected" && role && (
<div className="rounded-lg border border-green-700 bg-green-950/30 px-4 py-3 text-sm text-green-200">
Connected to {connectedWsUrl} as observer.
</div>
)}
<form className="flex flex-col gap-4" onSubmit={onSubmit}>
<div>
<label className="text-xs text-gray-400 uppercase tracking-wider mb-1 block">
Server URL
</label>
<input
className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
value={wsUrl}
onChange={(e) => setWsUrl(e.target.value)}
placeholder="wss://..."
/>
</div>
<form className="flex flex-col gap-4" onSubmit={onSubmit}>
<div>
<label className="text-xs text-gray-400 uppercase tracking-wider mb-1 block">
Server URL
</label>
<input
className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
value={wsUrl}
onChange={(e) => setWsUrl(e.target.value)}
placeholder="wss://..."
/>
</div>
<div className="flex flex-wrap gap-2 pt-2">
<button
type="submit"
className="px-5 py-2 bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium rounded-lg transition-colors"
>
{status === "connecting" || status === "reconnecting"
? "Connecting..."
: "Connect to Server"}
</button>
</div>
</form>
</div>
</div>
);
<div className="flex flex-wrap gap-2 pt-2">
<button
type="submit"
className="px-5 py-2 bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium rounded-lg transition-colors"
>
{status === "connecting" || status === "reconnecting"
? "Connecting..."
: "Connect to Server"}
</button>
</div>
</form>
</div>
</div>
);
}

View File

@@ -4,11 +4,11 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Board from "@/components/Board";
import {
BoardState,
ParsedMessage,
cmd,
createEmptyBoard,
placeToken,
BoardState,
ParsedMessage,
cmd,
createEmptyBoard,
placeToken,
} from "@/lib/protocol";
import { useConnection } from "@/lib/connection";
@@ -17,465 +17,465 @@ type GamePhase = "idle" | "connected" | "ready" | "playing" | "game-over";
type GameResult = "win" | "loss" | "draw" | "terminated";
export default function PlayPage() {
const router = useRouter();
const {
role,
username,
status,
send,
subscribe,
disconnect,
reconnectAttempts,
shouldRedirectToConnect,
clearRedirectFlag,
} = useConnection();
const router = useRouter();
const {
role,
username,
status,
send,
subscribe,
disconnect,
reconnectAttempts,
shouldRedirectToConnect,
clearRedirectFlag,
} = useConnection();
const [gamePhase, setGamePhase] = useState<GamePhase>("idle");
const [myColor, setMyColor] = useState<1 | 2 | null>(null);
const [isMyTurn, setIsMyTurn] = useState(false);
const [board, setBoard] = useState<BoardState>(createEmptyBoard());
const [lastMove, setLastMove] = useState<{
column: number;
row: number;
} | null>(null);
const [gameResult, setGameResult] = useState<GameResult | null>(null);
const [moveCount, setMoveCount] = useState(0);
const [statusMessages, setStatusMessages] = useState<string[]>([]);
const [tournamentMode, setTournamentMode] = useState(false);
const [gamePhase, setGamePhase] = useState<GamePhase>("idle");
const [myColor, setMyColor] = useState<1 | 2 | null>(null);
const [isMyTurn, setIsMyTurn] = useState(false);
const [board, setBoard] = useState<BoardState>(createEmptyBoard());
const [lastMove, setLastMove] = useState<{
column: number;
row: number;
} | null>(null);
const [gameResult, setGameResult] = useState<GameResult | null>(null);
const [moveCount, setMoveCount] = useState(0);
const [statusMessages, setStatusMessages] = useState<string[]>([]);
const [tournamentMode, setTournamentMode] = useState(false);
const myColorRef = useRef<1 | 2 | null>(null);
const isMyTurnRef = useRef(false);
const myColorRef = useRef<1 | 2 | null>(null);
const isMyTurnRef = useRef(false);
const addStatus = useCallback(
(msg: string) =>
setStatusMessages((prev) => [
`[${new Date().toLocaleTimeString()}] ${msg}`,
...prev.slice(0, 29),
]),
[],
);
const addStatus = useCallback(
(msg: string) =>
setStatusMessages((prev) => [
`[${new Date().toLocaleTimeString()}] ${msg}`,
...prev.slice(0, 29),
]),
[],
);
const resetGame = useCallback(() => {
setBoard(createEmptyBoard());
setLastMove(null);
setMoveCount(0);
setMyColor(null);
myColorRef.current = null;
setIsMyTurn(false);
isMyTurnRef.current = false;
setGameResult(null);
}, []);
const resetGame = useCallback(() => {
setBoard(createEmptyBoard());
setLastMove(null);
setMoveCount(0);
setMyColor(null);
myColorRef.current = null;
setIsMyTurn(false);
isMyTurnRef.current = false;
setGameResult(null);
}, []);
useEffect(() => {
if (status === "disconnected" && shouldRedirectToConnect) {
clearRedirectFlag();
router.replace("/");
}
useEffect(() => {
if (status === "disconnected" && shouldRedirectToConnect) {
clearRedirectFlag();
router.replace("/");
}
if (status === "idle") {
router.replace("/");
}
if (status === "idle") {
router.replace("/");
}
if (role !== "player" && status !== "idle") {
router.replace("/spectate");
return;
}
if (role !== "player" && status !== "idle") {
router.replace("/spectate");
return;
}
if (status === "connected" && gamePhase === "idle") {
setGamePhase("connected");
}
}, [
role,
status,
router,
gamePhase,
shouldRedirectToConnect,
clearRedirectFlag,
]);
if (status === "connected" && gamePhase === "idle") {
setGamePhase("connected");
}
}, [
role,
status,
router,
gamePhase,
shouldRedirectToConnect,
clearRedirectFlag,
]);
useEffect(() => {
const unsubscribe = subscribe((msg: ParsedMessage) => {
switch (msg.type) {
case "CONNECT_ACK":
case "RECONNECT_ACK":
setGamePhase((prev) => (prev === "idle" ? "connected" : prev));
addStatus("Connected to server");
break;
useEffect(() => {
const unsubscribe = subscribe((msg: ParsedMessage) => {
switch (msg.type) {
case "CONNECT_ACK":
case "RECONNECT_ACK":
setGamePhase((prev) => (prev === "idle" ? "connected" : prev));
addStatus("Connected to server");
break;
case "ERROR":
addStatus(`${msg.message}`);
break;
case "ERROR":
addStatus(`${msg.message}`);
break;
case "READY_ACK":
setGamePhase("ready");
addStatus("⏳ Waiting for an opponent...");
break;
case "READY_ACK":
setGamePhase("ready");
addStatus("⏳ Waiting for an opponent...");
break;
case "GAME_START": {
resetGame();
const color: 1 | 2 = msg.goesFirst ? 1 : 2;
setMyColor(color);
myColorRef.current = color;
setGamePhase("playing");
const firstTurn = msg.goesFirst;
setIsMyTurn(firstTurn);
isMyTurnRef.current = firstTurn;
addStatus(
msg.goesFirst
? "🔴 You are Red - you go first"
: "🟡 You are Yellow - wait for opponent's move",
);
break;
}
case "GAME_START": {
resetGame();
const color: 1 | 2 = msg.goesFirst ? 1 : 2;
setMyColor(color);
myColorRef.current = color;
setGamePhase("playing");
const firstTurn = msg.goesFirst;
setIsMyTurn(firstTurn);
isMyTurnRef.current = firstTurn;
addStatus(
msg.goesFirst
? "🔴 You are Red - you go first"
: "🟡 You are Yellow - wait for opponent's move",
);
break;
}
case "OPPONENT_MOVE": {
const opponentColor: 1 | 2 = myColorRef.current === 1 ? 2 : 1;
setBoard((prev) => {
const { board: next, row } = placeToken(
prev,
opponentColor,
msg.column,
);
setLastMove({ column: msg.column, row });
return next;
});
setMoveCount((n) => n + 1);
setIsMyTurn(true);
isMyTurnRef.current = true;
addStatus(`Opponent played column ${msg.column}`);
break;
}
case "OPPONENT_MOVE": {
const opponentColor: 1 | 2 = myColorRef.current === 1 ? 2 : 1;
setBoard((prev) => {
const { board: next, row } = placeToken(
prev,
opponentColor,
msg.column,
);
setLastMove({ column: msg.column, row });
return next;
});
setMoveCount((n) => n + 1);
setIsMyTurn(true);
isMyTurnRef.current = true;
addStatus(`Opponent played column ${msg.column}`);
break;
}
case "GAME_WINS":
setGameResult("win");
setGamePhase("game-over");
setIsMyTurn(false);
isMyTurnRef.current = false;
addStatus("🏆 You won!");
break;
case "GAME_WINS":
setGameResult("win");
setGamePhase("game-over");
setIsMyTurn(false);
isMyTurnRef.current = false;
addStatus("🏆 You won!");
break;
case "GAME_LOSS":
setGameResult("loss");
setGamePhase("game-over");
setIsMyTurn(false);
isMyTurnRef.current = false;
addStatus("💔 You lost");
break;
case "GAME_LOSS":
setGameResult("loss");
setGamePhase("game-over");
setIsMyTurn(false);
isMyTurnRef.current = false;
addStatus("💔 You lost");
break;
case "GAME_DRAW":
setGameResult("draw");
setGamePhase("game-over");
setIsMyTurn(false);
isMyTurnRef.current = false;
addStatus("🤝 Draw");
break;
case "GAME_DRAW":
setGameResult("draw");
setGamePhase("game-over");
setIsMyTurn(false);
isMyTurnRef.current = false;
addStatus("🤝 Draw");
break;
case "GAME_TERMINATED":
setGameResult("terminated");
setGamePhase("game-over");
setIsMyTurn(false);
isMyTurnRef.current = false;
addStatus("⛔ Match terminated");
break;
case "GAME_TERMINATED":
setGameResult("terminated");
setGamePhase("game-over");
setIsMyTurn(false);
isMyTurnRef.current = false;
addStatus("⛔ Match terminated");
break;
case "TOURNAMENT_START":
setTournamentMode(true);
addStatus(`🏆 Tournament started: ${msg.tournamentType}`);
break;
case "TOURNAMENT_START":
setTournamentMode(true);
addStatus(`🏆 Tournament started: ${msg.tournamentType}`);
break;
case "TOURNAMENT_END":
setGamePhase("connected");
resetGame();
send(cmd.ready());
setGamePhase("ready");
addStatus("⏳ Ready for next round...");
break;
case "TOURNAMENT_END":
setGamePhase("connected");
resetGame();
send(cmd.ready());
setGamePhase("ready");
addStatus("⏳ Ready for next round...");
break;
case "TOURNAMENT_CANCEL":
setTournamentMode(false);
setGamePhase("connected");
resetGame();
addStatus("Tournament cancelled");
break;
case "TOURNAMENT_CANCEL":
setTournamentMode(false);
setGamePhase("connected");
resetGame();
addStatus("Tournament cancelled");
break;
default:
break;
}
});
default:
break;
}
});
return unsubscribe;
}, [addStatus, resetGame, send, subscribe]);
return unsubscribe;
}, [addStatus, resetGame, send, subscribe]);
const handleColumnClick = useCallback(
(col: number) => {
if (!isMyTurnRef.current || gamePhase !== "playing") return;
const color = myColorRef.current;
if (!color) return;
const handleColumnClick = useCallback(
(col: number) => {
if (!isMyTurnRef.current || gamePhase !== "playing") return;
const color = myColorRef.current;
if (!color) return;
setBoard((prev) => {
const { board: next, row } = placeToken(prev, color, col);
if (row === -1) return prev;
setLastMove({ column: col, row });
return next;
});
setBoard((prev) => {
const { board: next, row } = placeToken(prev, color, col);
if (row === -1) return prev;
setLastMove({ column: col, row });
return next;
});
setIsMyTurn(false);
isMyTurnRef.current = false;
setMoveCount((n) => n + 1);
send(cmd.play(col));
addStatus(`You played column ${col}`);
},
[addStatus, gamePhase, send],
);
setIsMyTurn(false);
isMyTurnRef.current = false;
setMoveCount((n) => n + 1);
send(cmd.play(col));
addStatus(`You played column ${col}`);
},
[addStatus, gamePhase, send],
);
const sendReady = useCallback(() => {
send(cmd.ready());
setGamePhase("ready");
addStatus("⏳ Waiting for an opponent...");
}, [addStatus, send]);
const sendReady = useCallback(() => {
send(cmd.ready());
setGamePhase("ready");
addStatus("⏳ Waiting for an opponent...");
}, [addStatus, send]);
const myColorLabel =
myColor === 1 ? "🔴 Red" : myColor === 2 ? "🟡 Yellow" : null;
const opponentColor: 1 | 2 | null =
myColor === 1 ? 2 : myColor === 2 ? 1 : null;
const redPlayerName = myColor === 1 ? username : "Opponent";
const yellowPlayerName = myColor === 2 ? username : "Opponent";
const myColorLabel =
myColor === 1 ? "🔴 Red" : myColor === 2 ? "🟡 Yellow" : null;
const opponentColor: 1 | 2 | null =
myColor === 1 ? 2 : myColor === 2 ? 1 : null;
const redPlayerName = myColor === 1 ? username : "Opponent";
const yellowPlayerName = myColor === 2 ? username : "Opponent";
return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-white">🎮 Play Connect4</h1>
<p className="text-gray-400 text-sm mt-1">
Connected as <span className="text-green-300">{username}</span>
</p>
</div>
<PhaseIndicator phase={gamePhase} isMyTurn={isMyTurn} />
</div>
return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-white">🎮 Play Connect4</h1>
<p className="text-gray-400 text-sm mt-1">
Connected as <span className="text-green-300">{username}</span>
</p>
</div>
<PhaseIndicator phase={gamePhase} isMyTurn={isMyTurn} />
</div>
{status === "reconnecting" && (
<div className="rounded-lg border border-yellow-700 bg-yellow-950/30 px-4 py-3 text-sm text-yellow-200">
Connection lost during a live match. Reconnect attempt #
{reconnectAttempts}...
</div>
)}
{status === "reconnecting" && (
<div className="rounded-lg border border-yellow-700 bg-yellow-950/30 px-4 py-3 text-sm text-yellow-200">
Connection lost during a live match. Reconnect attempt #
{reconnectAttempts}...
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="flex flex-col gap-4">
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-col gap-3">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
Session
</h2>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="flex flex-col gap-4">
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-col gap-3">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
Session
</h2>
<div className="text-xs text-gray-400">
Status: <span className="text-gray-200">{status}</span>
</div>
<div className="text-xs text-gray-400">
User: <span className="text-gray-200">{username}</span>
</div>
<div className="text-xs text-gray-400">
Status: <span className="text-gray-200">{status}</span>
</div>
<div className="text-xs text-gray-400">
User: <span className="text-gray-200">{username}</span>
</div>
<button
onClick={disconnect}
className="w-full py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm font-medium rounded-lg transition-colors"
>
Disconnect
</button>
</div>
<button
onClick={disconnect}
className="w-full py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm font-medium rounded-lg transition-colors"
>
Disconnect
</button>
</div>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-col gap-3">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
Match
</h2>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-col gap-3">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
Match
</h2>
{tournamentMode && (
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-purple-950/50 border border-purple-700 text-purple-300 text-sm">
<span>🏆</span>
<span>Tournament mode active</span>
</div>
)}
{tournamentMode && (
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-purple-950/50 border border-purple-700 text-purple-300 text-sm">
<span>🏆</span>
<span>Tournament mode active</span>
</div>
)}
{gamePhase === "connected" && (
<button
onClick={sendReady}
className="w-full py-2.5 bg-green-700 hover:bg-green-600 text-white text-sm font-semibold rounded-lg transition-colors"
>
Ready to Play
</button>
)}
{gamePhase === "connected" && (
<button
onClick={sendReady}
className="w-full py-2.5 bg-green-700 hover:bg-green-600 text-white text-sm font-semibold rounded-lg transition-colors"
>
Ready to Play
</button>
)}
{gamePhase === "ready" && (
<div className="text-center py-3 text-yellow-300 text-sm animate-pulse">
Waiting for opponent...
</div>
)}
{gamePhase === "ready" && (
<div className="text-center py-3 text-yellow-300 text-sm animate-pulse">
Waiting for opponent...
</div>
)}
{(gamePhase === "playing" || gamePhase === "game-over") &&
myColor && (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-gray-800">
<div
className={`w-4 h-4 rounded-full ${myColor === 1 ? "bg-red-500" : "bg-yellow-400"}`}
/>
<span className="text-white font-medium text-sm">
You are {myColorLabel}
</span>
</div>
{(gamePhase === "playing" || gamePhase === "game-over") &&
myColor && (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-gray-800">
<div
className={`w-4 h-4 rounded-full ${myColor === 1 ? "bg-red-500" : "bg-yellow-400"}`}
/>
<span className="text-white font-medium text-sm">
You are {myColorLabel}
</span>
</div>
{gamePhase === "playing" && (
<div
className={`flex items-center justify-center gap-2 px-3 py-2 rounded-lg font-semibold text-sm ${
isMyTurn
? "bg-green-900/50 border border-green-600 text-green-300 animate-pulse"
: "bg-gray-800 text-gray-400"
}`}
>
{isMyTurn
? "⬆ Your turn - click a column"
: "⏳ Waiting for opponent..."}
</div>
)}
{gamePhase === "playing" && (
<div
className={`flex items-center justify-center gap-2 px-3 py-2 rounded-lg font-semibold text-sm ${
isMyTurn
? "bg-green-900/50 border border-green-600 text-green-300 animate-pulse"
: "bg-gray-800 text-gray-400"
}`}
>
{isMyTurn
? "⬆ Your turn - click a column"
: "⏳ Waiting for opponent..."}
</div>
)}
<div className="text-xs text-gray-500 text-center">
{moveCount} move{moveCount !== 1 ? "s" : ""} played
</div>
</div>
)}
<div className="text-xs text-gray-500 text-center">
{moveCount} move{moveCount !== 1 ? "s" : ""} played
</div>
</div>
)}
{gamePhase === "game-over" && gameResult && !tournamentMode && (
<button
onClick={sendReady}
className="w-full py-2 bg-green-700 hover:bg-green-600 text-white text-sm font-semibold rounded-lg transition-colors"
>
Play Again
</button>
)}
</div>
{gamePhase === "game-over" && gameResult && !tournamentMode && (
<button
onClick={sendReady}
className="w-full py-2 bg-green-700 hover:bg-green-600 text-white text-sm font-semibold rounded-lg transition-colors"
>
Play Again
</button>
)}
</div>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-2">
Status Log
</h2>
<div className="flex flex-col gap-0.5 max-h-52 overflow-y-auto">
{statusMessages.length === 0 ? (
<p className="text-gray-600 text-xs">No events yet</p>
) : (
statusMessages.map((m, i) => (
<p key={i} className="text-xs text-gray-400 font-mono">
{m}
</p>
))
)}
</div>
</div>
</div>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-2">
Status Log
</h2>
<div className="flex flex-col gap-0.5 max-h-52 overflow-y-auto">
{statusMessages.length === 0 ? (
<p className="text-gray-600 text-xs">No events yet</p>
) : (
statusMessages.map((m, i) => (
<p key={i} className="text-xs text-gray-400 font-mono">
{m}
</p>
))
)}
</div>
</div>
</div>
<div className="lg:col-span-2 bg-gray-900 border border-gray-700 rounded-xl p-6 flex flex-col items-center justify-center gap-4 min-h-96">
{gamePhase === "idle" ? (
<div className="text-gray-500 text-center py-10">
Connect from the connection page to start.
</div>
) : gamePhase === "connected" ? (
<div className="flex flex-col items-center gap-4 text-center py-8">
<div className="text-5xl"></div>
<p className="text-blue-300 text-lg font-medium">
Ready up to start
</p>
<p className="text-gray-500 text-sm max-w-sm">
Click the{" "}
<span className="text-green-300 font-semibold">
Ready to Play
</span>{" "}
button in the Match panel to enter the queue.
</p>
</div>
) : gamePhase === "ready" ? (
<div className="flex flex-col items-center gap-4 text-center py-8">
<div className="text-5xl animate-bounce"></div>
<p className="text-yellow-300 text-lg font-medium">
Waiting for an opponent...
</p>
</div>
) : (
<>
{gameResult && (
<div
className={`w-full max-w-md rounded-xl p-4 text-center font-bold text-xl border ${
gameResult === "win"
? "bg-green-900/50 border-green-500 text-green-300"
: gameResult === "loss"
? "bg-red-900/50 border-red-500 text-red-300"
: gameResult === "draw"
? "bg-blue-900/50 border-blue-500 text-blue-300"
: "bg-gray-800 border-gray-600 text-gray-300"
}`}
>
{gameResult === "win"
? "🏆 You Won!"
: gameResult === "loss"
? "💔 You Lost"
: gameResult === "draw"
? "🤝 Draw"
: "⛔ Match Terminated"}
</div>
)}
<div className="lg:col-span-2 bg-gray-900 border border-gray-700 rounded-xl p-6 flex flex-col items-center justify-center gap-4 min-h-96">
{gamePhase === "idle" ? (
<div className="text-gray-500 text-center py-10">
Connect from the connection page to start.
</div>
) : gamePhase === "connected" ? (
<div className="flex flex-col items-center gap-4 text-center py-8">
<div className="text-5xl"></div>
<p className="text-blue-300 text-lg font-medium">
Ready up to start
</p>
<p className="text-gray-500 text-sm max-w-sm">
Click the{" "}
<span className="text-green-300 font-semibold">
Ready to Play
</span>{" "}
button in the Match panel to enter the queue.
</p>
</div>
) : gamePhase === "ready" ? (
<div className="flex flex-col items-center gap-4 text-center py-8">
<div className="text-5xl animate-bounce"></div>
<p className="text-yellow-300 text-lg font-medium">
Waiting for an opponent...
</p>
</div>
) : (
<>
{gameResult && (
<div
className={`w-full max-w-md rounded-xl p-4 text-center font-bold text-xl border ${
gameResult === "win"
? "bg-green-900/50 border-green-500 text-green-300"
: gameResult === "loss"
? "bg-red-900/50 border-red-500 text-red-300"
: gameResult === "draw"
? "bg-blue-900/50 border-blue-500 text-blue-300"
: "bg-gray-800 border-gray-600 text-gray-300"
}`}
>
{gameResult === "win"
? "🏆 You Won!"
: gameResult === "loss"
? "💔 You Lost"
: gameResult === "draw"
? "🤝 Draw"
: "⛔ Match Terminated"}
</div>
)}
<Board
board={board}
lastMove={lastMove}
player1={redPlayerName}
player2={yellowPlayerName}
currentTurnColor={
gamePhase === "playing" && myColor
? isMyTurn
? myColor
: opponentColor
: null
}
onColumnClick={
gamePhase === "playing" && isMyTurn
? handleColumnClick
: undefined
}
disabled={gamePhase !== "playing" || !isMyTurn}
/>
</>
)}
</div>
</div>
</div>
);
<Board
board={board}
lastMove={lastMove}
player1={redPlayerName}
player2={yellowPlayerName}
currentTurnColor={
gamePhase === "playing" && myColor
? isMyTurn
? myColor
: opponentColor
: null
}
onColumnClick={
gamePhase === "playing" && isMyTurn
? handleColumnClick
: undefined
}
disabled={gamePhase !== "playing" || !isMyTurn}
/>
</>
)}
</div>
</div>
</div>
);
}
function PhaseIndicator({
phase,
isMyTurn,
phase,
isMyTurn,
}: {
phase: GamePhase;
isMyTurn: boolean;
phase: GamePhase;
isMyTurn: boolean;
}) {
if (phase === "playing" && isMyTurn) {
return (
<span className="px-3 py-1.5 rounded-full text-sm font-medium bg-green-900/60 text-green-300 animate-pulse">
Your Turn!
</span>
);
}
if (phase === "playing" && isMyTurn) {
return (
<span className="px-3 py-1.5 rounded-full text-sm font-medium bg-green-900/60 text-green-300 animate-pulse">
Your Turn!
</span>
);
}
const config: Record<GamePhase, { label: string; cls: string }> = {
idle: { label: "Not ready", cls: "bg-gray-700 text-gray-400" },
connected: { label: "Connected", cls: "bg-blue-900/60 text-blue-300" },
ready: {
label: "Waiting...",
cls: "bg-yellow-900/60 text-yellow-300 animate-pulse",
},
playing: { label: "In Game", cls: "bg-green-900/60 text-green-400" },
"game-over": { label: "Game Over", cls: "bg-gray-700 text-gray-400" },
};
const config: Record<GamePhase, { label: string; cls: string }> = {
idle: { label: "Not ready", cls: "bg-gray-700 text-gray-400" },
connected: { label: "Connected", cls: "bg-blue-900/60 text-blue-300" },
ready: {
label: "Waiting...",
cls: "bg-yellow-900/60 text-yellow-300 animate-pulse",
},
playing: { label: "In Game", cls: "bg-green-900/60 text-green-400" },
"game-over": { label: "Game Over", cls: "bg-gray-700 text-gray-400" },
};
const { label, cls } = config[phase];
return (
<span className={`px-3 py-1.5 rounded-full text-sm font-medium ${cls}`}>
{label}
</span>
);
const { label, cls } = config[phase];
return (
<span className={`px-3 py-1.5 rounded-full text-sm font-medium ${cls}`}>
{label}
</span>
);
}

View File

@@ -4,487 +4,487 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Board from "@/components/Board";
import {
BoardState,
GameEntry,
ParsedMessage,
PlayerEntry,
ScoreEntry,
cmd,
createEmptyBoard,
placeToken,
replayMoves,
BoardState,
GameEntry,
ParsedMessage,
PlayerEntry,
ScoreEntry,
cmd,
createEmptyBoard,
placeToken,
replayMoves,
} from "@/lib/protocol";
import { useConnection } from "@/lib/connection";
interface LiveGame {
id: number;
player1: string;
player2: string;
board: BoardState;
lastMove: { column: number; row: number } | null;
currentTurnColor: 1 | 2;
result:
| { kind: "win"; winner: string }
| { kind: "draw" }
| { kind: "terminated" }
| null;
id: number;
player1: string;
player2: string;
board: BoardState;
lastMove: { column: number; row: number } | null;
currentTurnColor: 1 | 2;
result:
| { kind: "win"; winner: string }
| { kind: "draw" }
| { kind: "terminated" }
| null;
}
export default function SpectatePage() {
const router = useRouter();
const {
role,
status,
send,
subscribe,
disconnect,
shouldRedirectToConnect,
clearRedirectFlag,
} = useConnection();
const router = useRouter();
const {
role,
status,
send,
subscribe,
disconnect,
shouldRedirectToConnect,
clearRedirectFlag,
} = useConnection();
const [tournamentActive, setTournamentActive] = useState(false);
const [tournamentType, setTournamentType] = useState<string | null>(null);
const [scores, setScores] = useState<ScoreEntry[]>([]);
const [players, setPlayers] = useState<PlayerEntry[]>([]);
const [gameList, setGameList] = useState<GameEntry[]>([]);
const [liveGames, setLiveGames] = useState<Map<number, LiveGame>>(new Map());
const [selectedGame, setSelectedGame] = useState<number | null>(null);
const [log, setLog] = useState<string[]>([]);
const [tournamentActive, setTournamentActive] = useState(false);
const [tournamentType, setTournamentType] = useState<string | null>(null);
const [scores, setScores] = useState<ScoreEntry[]>([]);
const [players, setPlayers] = useState<PlayerEntry[]>([]);
const [gameList, setGameList] = useState<GameEntry[]>([]);
const [liveGames, setLiveGames] = useState<Map<number, LiveGame>>(new Map());
const [selectedGame, setSelectedGame] = useState<number | null>(null);
const [log, setLog] = useState<string[]>([]);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const liveGamesRef = useRef<Map<number, LiveGame>>(new Map());
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const liveGamesRef = useRef<Map<number, LiveGame>>(new Map());
const addLog = useCallback(
(msg: string) =>
setLog((prev) => [
`[${new Date().toLocaleTimeString()}] ${msg}`,
...prev.slice(0, 79),
]),
[],
);
const addLog = useCallback(
(msg: string) =>
setLog((prev) => [
`[${new Date().toLocaleTimeString()}] ${msg}`,
...prev.slice(0, 79),
]),
[],
);
const updateGame = useCallback((id: number, patch: Partial<LiveGame>) => {
setLiveGames((prev) => {
const next = new Map(prev);
const existing = next.get(id) ?? {
id,
player1: "",
player2: "",
board: createEmptyBoard(),
lastMove: null,
currentTurnColor: 1 as const,
result: null,
};
next.set(id, { ...existing, ...patch });
liveGamesRef.current = next;
return next;
});
}, []);
const updateGame = useCallback((id: number, patch: Partial<LiveGame>) => {
setLiveGames((prev) => {
const next = new Map(prev);
const existing = next.get(id) ?? {
id,
player1: "",
player2: "",
board: createEmptyBoard(),
lastMove: null,
currentTurnColor: 1 as const,
result: null,
};
next.set(id, { ...existing, ...patch });
liveGamesRef.current = next;
return next;
});
}, []);
useEffect(() => {
if (status === "disconnected" && shouldRedirectToConnect) {
clearRedirectFlag();
router.replace("/");
}
if (status === "idle") {
router.replace("/");
}
useEffect(() => {
if (status === "disconnected" && shouldRedirectToConnect) {
clearRedirectFlag();
router.replace("/");
}
if (role !== "observer" && status !== "idle") {
router.replace("/play");
return;
}
}, [role, status, shouldRedirectToConnect, clearRedirectFlag, router]);
if (status === "idle") {
router.replace("/");
}
useEffect(() => {
const unsubscribe = subscribe((msg: ParsedMessage) => {
switch (msg.type) {
case "TOURNAMENT_START":
setTournamentActive(true);
setTournamentType(msg.tournamentType);
setScores([]);
addLog(`🏆 Tournament started: ${msg.tournamentType}`);
send(cmd.gameList());
send(cmd.playerList());
break;
if (role !== "observer" && status !== "idle") {
router.replace("/play");
return;
}
}, [role, status, shouldRedirectToConnect, clearRedirectFlag, router]);
case "TOURNAMENT_CANCEL":
setTournamentActive(false);
setTournamentType(null);
addLog("❌ Tournament cancelled");
break;
useEffect(() => {
const unsubscribe = subscribe((msg: ParsedMessage) => {
switch (msg.type) {
case "TOURNAMENT_START":
setTournamentActive(true);
setTournamentType(msg.tournamentType);
setScores([]);
addLog(`🏆 Tournament started: ${msg.tournamentType}`);
send(cmd.gameList());
send(cmd.playerList());
break;
case "TOURNAMENT_SCORES":
setScores(msg.scores);
break;
case "TOURNAMENT_CANCEL":
setTournamentActive(false);
setTournamentType(null);
addLog("❌ Tournament cancelled");
break;
case "TOURNAMENT_END":
addLog("Round ended");
send(cmd.gameList());
send(cmd.playerList());
break;
case "TOURNAMENT_SCORES":
setScores(msg.scores);
break;
case "GAME_LIST":
setGameList(msg.games);
for (const g of msg.games) {
if (!liveGamesRef.current.has(g.id)) {
send(cmd.gameWatch(g.id));
}
}
break;
case "TOURNAMENT_END":
addLog("Round ended");
send(cmd.gameList());
send(cmd.playerList());
break;
case "GAME_WATCH_ACK": {
const { board, lastMove } = replayMoves(msg.moves, msg.player1);
const moveCount = msg.moves.length;
updateGame(msg.matchId, {
player1: msg.player1,
player2: msg.player2,
board,
lastMove,
currentTurnColor: (moveCount % 2 === 0 ? 1 : 2) as 1 | 2,
result: null,
});
break;
}
case "GAME_LIST":
setGameList(msg.games);
for (const g of msg.games) {
if (!liveGamesRef.current.has(g.id)) {
send(cmd.gameWatch(g.id));
}
}
break;
case "GAME_MOVE": {
if (typeof msg.matchId !== "number") {
addLog("Protocol error: GAME_MOVE missing matchId");
break;
}
case "GAME_WATCH_ACK": {
const { board, lastMove } = replayMoves(msg.moves, msg.player1);
const moveCount = msg.moves.length;
updateGame(msg.matchId, {
player1: msg.player1,
player2: msg.player2,
board,
lastMove,
currentTurnColor: (moveCount % 2 === 0 ? 1 : 2) as 1 | 2,
result: null,
});
break;
}
const game = liveGamesRef.current.get(msg.matchId);
if (!game) break;
const color: 1 | 2 = msg.username === game.player1 ? 1 : 2;
const { board: next, row } = placeToken(
game.board,
color,
msg.column,
);
updateGame(msg.matchId, {
board: next,
lastMove: { column: msg.column, row },
currentTurnColor: (color === 1 ? 2 : 1) as 1 | 2,
});
break;
}
case "GAME_MOVE": {
if (typeof msg.matchId !== "number") {
addLog("Protocol error: GAME_MOVE missing matchId");
break;
}
case "GAME_WIN": {
if (typeof msg.matchId !== "number") {
addLog("Protocol error: GAME_WIN missing matchId");
break;
}
const game = liveGamesRef.current.get(msg.matchId);
if (!game) break;
const color: 1 | 2 = msg.username === game.player1 ? 1 : 2;
const { board: next, row } = placeToken(
game.board,
color,
msg.column,
);
updateGame(msg.matchId, {
board: next,
lastMove: { column: msg.column, row },
currentTurnColor: (color === 1 ? 2 : 1) as 1 | 2,
});
break;
}
updateGame(msg.matchId, {
result: { kind: "win", winner: msg.winner },
});
setTimeout(() => {
send(cmd.gameList());
send(cmd.playerList());
}, 750);
break;
}
case "GAME_WIN": {
if (typeof msg.matchId !== "number") {
addLog("Protocol error: GAME_WIN missing matchId");
break;
}
case "GAME_DRAW":
if (typeof msg.matchId !== "number") {
addLog("Protocol error: GAME_DRAW missing matchId");
break;
}
updateGame(msg.matchId, { result: { kind: "draw" } });
break;
updateGame(msg.matchId, {
result: { kind: "win", winner: msg.winner },
});
setTimeout(() => {
send(cmd.gameList());
send(cmd.playerList());
}, 750);
break;
}
case "GAME_TERMINATED":
if (typeof msg.matchId !== "number") {
addLog("Protocol error: GAME_TERMINATED missing matchId");
break;
}
updateGame(msg.matchId, { result: { kind: "terminated" } });
send(cmd.gameList());
break;
case "GAME_DRAW":
if (typeof msg.matchId !== "number") {
addLog("Protocol error: GAME_DRAW missing matchId");
break;
}
updateGame(msg.matchId, { result: { kind: "draw" } });
break;
case "PLAYER_LIST":
setPlayers(msg.players);
break;
case "GAME_TERMINATED":
if (typeof msg.matchId !== "number") {
addLog("Protocol error: GAME_TERMINATED missing matchId");
break;
}
updateGame(msg.matchId, { result: { kind: "terminated" } });
send(cmd.gameList());
break;
case "GET_DATA":
if (
msg.key === "TOURNAMENT_STATUS" &&
msg.value &&
msg.value !== "false"
) {
setTournamentActive(true);
setTournamentType(msg.value);
}
break;
case "PLAYER_LIST":
setPlayers(msg.players);
break;
case "ERROR":
addLog(`Error: ${msg.message}`);
break;
case "GET_DATA":
if (
msg.key === "TOURNAMENT_STATUS" &&
msg.value &&
msg.value !== "false"
) {
setTournamentActive(true);
setTournamentType(msg.value);
}
break;
default:
break;
}
});
case "ERROR":
addLog(`Error: ${msg.message}`);
break;
return unsubscribe;
}, [addLog, selectedGame, send, subscribe, updateGame]);
default:
break;
}
});
useEffect(() => {
if (status !== "connected" || role !== "observer") {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
return;
}
return unsubscribe;
}, [addLog, selectedGame, send, subscribe, updateGame]);
send(cmd.getData("TOURNAMENT_STATUS"));
send(cmd.gameList());
send(cmd.playerList());
useEffect(() => {
if (status !== "connected" || role !== "observer") {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
return;
}
pollRef.current = setInterval(() => {
send(cmd.gameList());
send(cmd.playerList());
}, 5000);
send(cmd.getData("TOURNAMENT_STATUS"));
send(cmd.gameList());
send(cmd.playerList());
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, [role, send, status]);
pollRef.current = setInterval(() => {
send(cmd.gameList());
send(cmd.playerList());
}, 5000);
const selectedGameData =
selectedGame !== null ? liveGames.get(selectedGame) : null;
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, [role, send, status]);
return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-white">
👁 Observer Dashboard
</h1>
<p className="text-gray-400 text-sm mt-1">
Unified spectate and tournament view
</p>
</div>
<button
onClick={disconnect}
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm font-medium rounded-lg transition-colors"
>
Disconnect
</button>
</div>
const selectedGameData =
selectedGame !== null ? liveGames.get(selectedGame) : null;
{status !== "connected" && (
<div className="rounded-lg border border-yellow-700 bg-yellow-950/30 px-4 py-3 text-sm text-yellow-200">
Waiting for observer connection...
</div>
)}
return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-white">
👁 Observer Dashboard
</h1>
<p className="text-gray-400 text-sm mt-1">
Unified spectate and tournament view
</p>
</div>
<button
onClick={disconnect}
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm font-medium rounded-lg transition-colors"
>
Disconnect
</button>
</div>
{status === "connected" && (
<div
className={`rounded-xl p-4 border flex items-center gap-4 ${
tournamentActive
? "bg-purple-950/40 border-purple-600"
: "bg-gray-900 border-gray-700"
}`}
>
<div className="text-3xl">{tournamentActive ? "🏆" : "⏳"}</div>
<div>
<div className="font-semibold text-white">
{tournamentActive
? `Tournament Active - ${tournamentType ?? "Unknown Type"}`
: "No Active Tournament"}
</div>
<div className="text-sm text-gray-400">
{gameList.length} match{gameList.length !== 1 ? "es" : ""} running
· {players.filter((p) => p.inMatch).length}/{players.length}{" "}
players in game
</div>
</div>
</div>
)}
{status !== "connected" && (
<div className="rounded-lg border border-yellow-700 bg-yellow-950/30 px-4 py-3 text-sm text-yellow-200">
Waiting for observer connection...
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="flex flex-col gap-4">
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-3">
Leaderboard
</h2>
{scores.length === 0 ? (
<p className="text-gray-500 text-sm text-center py-4">
No scores yet
</p>
) : (
<div className="flex flex-col gap-1.5">
{scores.map((s, i) => (
<div
key={s.player}
className="flex items-center gap-3 px-3 py-2 rounded-lg bg-gray-800"
>
<span className="text-sm font-bold w-6 text-gray-300">
{i + 1}.
</span>
<span className="text-white flex-1 font-medium text-sm">
{s.player}
</span>
<span className="text-blue-400 font-bold">{s.score}</span>
</div>
))}
</div>
)}
</div>
{status === "connected" && (
<div
className={`rounded-xl p-4 border flex items-center gap-4 ${
tournamentActive
? "bg-purple-950/40 border-purple-600"
: "bg-gray-900 border-gray-700"
}`}
>
<div className="text-3xl">{tournamentActive ? "🏆" : "⏳"}</div>
<div>
<div className="font-semibold text-white">
{tournamentActive
? `Tournament Active - ${tournamentType ?? "Unknown Type"}`
: "No Active Tournament"}
</div>
<div className="text-sm text-gray-400">
{gameList.length} match{gameList.length !== 1 ? "es" : ""} running
· {players.filter((p) => p.inMatch).length}/{players.length}{" "}
players in game
</div>
</div>
</div>
)}
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-3 flex items-center justify-between">
<span>Players</span>
<span className="text-xs text-gray-500 font-normal">
{players.length} connected
</span>
</h2>
{players.length === 0 ? (
<p className="text-gray-500 text-sm text-center py-4">
No players connected
</p>
) : (
<div className="flex flex-col gap-1.5">
{players.map((p) => (
<div
key={p.username}
className="flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-800"
>
<span className="text-white text-sm flex-1 font-medium">
{p.username}
</span>
{p.inMatch ? (
<span className="text-xs px-2 py-0.5 rounded-full bg-blue-900/60 text-blue-300 border border-blue-700">
In game
</span>
) : p.ready ? (
<span className="text-xs px-2 py-0.5 rounded-full bg-green-900/60 text-green-300 border border-green-700">
Ready
</span>
) : (
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-700 text-gray-500">
Idle
</span>
)}
</div>
))}
</div>
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="flex flex-col gap-4">
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-3">
Leaderboard
</h2>
{scores.length === 0 ? (
<p className="text-gray-500 text-sm text-center py-4">
No scores yet
</p>
) : (
<div className="flex flex-col gap-1.5">
{scores.map((s, i) => (
<div
key={s.player}
className="flex items-center gap-3 px-3 py-2 rounded-lg bg-gray-800"
>
<span className="text-sm font-bold w-6 text-gray-300">
{i + 1}.
</span>
<span className="text-white flex-1 font-medium text-sm">
{s.player}
</span>
<span className="text-blue-400 font-bold">{s.score}</span>
</div>
))}
</div>
)}
</div>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-2">
Event Log
</h2>
<div className="flex flex-col gap-0.5 max-h-40 overflow-y-auto">
{log.slice(0, 20).map((entry, i) => (
<p key={i} className="text-xs text-gray-400 font-mono">
{entry}
</p>
))}
{log.length === 0 && (
<p className="text-gray-600 text-xs">No events yet</p>
)}
</div>
</div>
</div>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-3 flex items-center justify-between">
<span>Players</span>
<span className="text-xs text-gray-500 font-normal">
{players.length} connected
</span>
</h2>
{players.length === 0 ? (
<p className="text-gray-500 text-sm text-center py-4">
No players connected
</p>
) : (
<div className="flex flex-col gap-1.5">
{players.map((p) => (
<div
key={p.username}
className="flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-800"
>
<span className="text-white text-sm flex-1 font-medium">
{p.username}
</span>
{p.inMatch ? (
<span className="text-xs px-2 py-0.5 rounded-full bg-blue-900/60 text-blue-300 border border-blue-700">
In game
</span>
) : p.ready ? (
<span className="text-xs px-2 py-0.5 rounded-full bg-green-900/60 text-green-300 border border-green-700">
Ready
</span>
) : (
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-700 text-gray-500">
Idle
</span>
)}
</div>
))}
</div>
)}
</div>
<div className="lg:col-span-2 flex flex-col gap-4">
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-3">
Active Matches
</h2>
{gameList.length === 0 ? (
<p className="text-gray-500 text-sm text-center py-3">
No active matches
</p>
) : (
<div className="flex flex-wrap gap-2">
{gameList.map((g) => {
const live = liveGames.get(g.id);
return (
<button
key={g.id}
onClick={() =>
setSelectedGame(selectedGame === g.id ? null : g.id)
}
className={`px-3 py-2 rounded-lg border text-sm transition-colors ${
selectedGame === g.id
? "border-blue-500 bg-blue-950/50 text-blue-200"
: "border-gray-700 bg-gray-800 hover:border-gray-500 text-gray-300"
}`}
>
<span className="text-gray-500 text-xs font-mono mr-1">
#{g.id}
</span>
<span className="text-red-400">{g.player1}</span>
<span className="text-gray-500 mx-1">vs</span>
<span className="text-yellow-400">{g.player2}</span>
{live?.result && (
<span className="ml-1 text-xs">
{live.result.kind === "win"
? ` 🏆 ${live.result.winner}`
: live.result.kind === "draw"
? " 🤝"
: " ⛔"}
</span>
)}
</button>
);
})}
</div>
)}
</div>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-2">
Event Log
</h2>
<div className="flex flex-col gap-0.5 max-h-40 overflow-y-auto">
{log.slice(0, 20).map((entry, i) => (
<p key={i} className="text-xs text-gray-400 font-mono">
{entry}
</p>
))}
{log.length === 0 && (
<p className="text-gray-600 text-xs">No events yet</p>
)}
</div>
</div>
</div>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-6 flex flex-col items-center gap-4 min-h-64">
{!selectedGameData ? (
<div className="flex flex-col items-center justify-center gap-3 py-12 text-center">
<span className="text-4xl text-gray-700">🎯</span>
<p className="text-gray-500 text-sm">
{gameList.length > 0
? "Click a match above to see the board"
: "Active matches will appear here"}
</p>
</div>
) : (
<>
{selectedGameData.result && (
<div
className={`w-full rounded-lg p-3 text-center font-semibold ${
selectedGameData.result.kind === "win"
? "bg-green-900/50 border border-green-600 text-green-300"
: selectedGameData.result.kind === "draw"
? "bg-blue-900/50 border border-blue-600 text-blue-300"
: "bg-red-900/50 border border-red-600 text-red-300"
}`}
>
{selectedGameData.result.kind === "win"
? `🏆 ${selectedGameData.result.winner} wins!`
: selectedGameData.result.kind === "draw"
? "🤝 Draw!"
: "⛔ Match Terminated"}
</div>
)}
<Board
board={selectedGameData.board}
lastMove={selectedGameData.lastMove}
player1={selectedGameData.player1}
player2={selectedGameData.player2}
currentTurnColor={
selectedGameData.result
? null
: selectedGameData.currentTurnColor
}
disabled
/>
</>
)}
</div>
</div>
</div>
</div>
);
<div className="lg:col-span-2 flex flex-col gap-4">
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-3">
Active Matches
</h2>
{gameList.length === 0 ? (
<p className="text-gray-500 text-sm text-center py-3">
No active matches
</p>
) : (
<div className="flex flex-wrap gap-2">
{gameList.map((g) => {
const live = liveGames.get(g.id);
return (
<button
key={g.id}
onClick={() =>
setSelectedGame(selectedGame === g.id ? null : g.id)
}
className={`px-3 py-2 rounded-lg border text-sm transition-colors ${
selectedGame === g.id
? "border-blue-500 bg-blue-950/50 text-blue-200"
: "border-gray-700 bg-gray-800 hover:border-gray-500 text-gray-300"
}`}
>
<span className="text-gray-500 text-xs font-mono mr-1">
#{g.id}
</span>
<span className="text-red-400">{g.player1}</span>
<span className="text-gray-500 mx-1">vs</span>
<span className="text-yellow-400">{g.player2}</span>
{live?.result && (
<span className="ml-1 text-xs">
{live.result.kind === "win"
? ` 🏆 ${live.result.winner}`
: live.result.kind === "draw"
? " 🤝"
: " ⛔"}
</span>
)}
</button>
);
})}
</div>
)}
</div>
<div className="bg-gray-900 border border-gray-700 rounded-xl p-6 flex flex-col items-center gap-4 min-h-64">
{!selectedGameData ? (
<div className="flex flex-col items-center justify-center gap-3 py-12 text-center">
<span className="text-4xl text-gray-700">🎯</span>
<p className="text-gray-500 text-sm">
{gameList.length > 0
? "Click a match above to see the board"
: "Active matches will appear here"}
</p>
</div>
) : (
<>
{selectedGameData.result && (
<div
className={`w-full rounded-lg p-3 text-center font-semibold ${
selectedGameData.result.kind === "win"
? "bg-green-900/50 border border-green-600 text-green-300"
: selectedGameData.result.kind === "draw"
? "bg-blue-900/50 border border-blue-600 text-blue-300"
: "bg-red-900/50 border border-red-600 text-red-300"
}`}
>
{selectedGameData.result.kind === "win"
? `🏆 ${selectedGameData.result.winner} wins!`
: selectedGameData.result.kind === "draw"
? "🤝 Draw!"
: "⛔ Match Terminated"}
</div>
)}
<Board
board={selectedGameData.board}
lastMove={selectedGameData.lastMove}
player1={selectedGameData.player1}
player2={selectedGameData.player2}
currentTurnColor={
selectedGameData.result
? null
: selectedGameData.currentTurnColor
}
disabled
/>
</>
)}
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,5 +1,5 @@
import { redirect } from "next/navigation";
export default function TournamentRedirectPage() {
redirect("/spectate");
redirect("/spectate");
}

View File

@@ -54,7 +54,9 @@ export default function Board({
<div className="w-3.5 h-3.5 rounded-full bg-yellow-400 shrink-0" />
<span className="font-medium">{player2}</span>
{currentTurnColor === 2 && (
<span className="text-xs text-yellow-400 animate-pulse"> Turn</span>
<span className="text-xs text-yellow-400 animate-pulse">
Turn
</span>
)}
</div>
</div>
@@ -80,7 +82,9 @@ export default function Board({
{/* Drop arrow indicator */}
<div
className={`h-2 flex items-center justify-center transition-opacity ${
hoveredCol === col && canInteract ? "opacity-100" : "opacity-0"
hoveredCol === col && canInteract
? "opacity-100"
: "opacity-0"
}`}
>
<div className="w-0 h-0 border-l-4 border-r-4 border-t-4 border-l-transparent border-r-transparent border-t-white/70" />
@@ -98,21 +102,19 @@ export default function Board({
className={`w-12 h-12 rounded-full border-2 transition-all duration-150 ${
cell === 1
? `bg-red-500 shadow-lg shadow-red-950/60 ${
isLast
? "border-white scale-110"
: "border-red-700"
isLast ? "border-white scale-110" : "border-red-700"
}`
: cell === 2
? `bg-yellow-400 shadow-lg shadow-yellow-950/60 ${
isLast
? "border-white scale-110"
: "border-yellow-600"
}`
: `bg-slate-950 border-slate-800 ${
hoveredCol === col && canInteract
? "border-blue-400/50"
: ""
}`
? `bg-yellow-400 shadow-lg shadow-yellow-950/60 ${
isLast
? "border-white scale-110"
: "border-yellow-600"
}`
: `bg-slate-950 border-slate-800 ${
hoveredCol === col && canInteract
? "border-blue-400/50"
: ""
}`
}`}
/>
);

View File

@@ -7,115 +7,115 @@ import { useConnection } from "@/lib/connection";
import { cmd, DEFAULT_WS_URL } from "@/lib/protocol";
export default function Nav() {
const pathname = usePathname();
const router = useRouter();
const { status, role, username, send, becomePlayer } = useConnection();
const [showPlayerModal, setShowPlayerModal] = useState(false);
const [nextUsername, setNextUsername] = useState(username);
const pathname = usePathname();
const router = useRouter();
const { status, role, username, send, becomePlayer } = useConnection();
const [showPlayerModal, setShowPlayerModal] = useState(false);
const [nextUsername, setNextUsername] = useState(username);
const statusLabel =
status === "connected"
? `Connected ${role === "player" ? `as ${username}` : "as observer"}`
: status === "reconnecting"
? "Reconnecting..."
: status === "connecting"
? "Connecting..."
: "Not connected";
const isConnectionPage = pathname === "/";
const statusLabel =
status === "connected"
? `Connected ${role === "player" ? `as ${username}` : "as observer"}`
: status === "reconnecting"
? "Reconnecting..."
: status === "connecting"
? "Connecting..."
: "Not connected";
const isConnectionPage = pathname === "/";
const disableRoleSwitch =
status === "connecting" || status === "reconnecting";
const disableRoleSwitch =
status === "connecting" || status === "reconnecting";
const handleBecomeObserver = () => {
const handleBecomeObserver = () => {
send(cmd.disconnect());
router.push("/spectate");
};
router.push("/spectate");
};
const handleBecomePlayer = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const trimmed = nextUsername.trim();
if (!trimmed) return;
const handleBecomePlayer = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const trimmed = nextUsername.trim();
if (!trimmed) return;
becomePlayer(trimmed);
setShowPlayerModal(false);
router.push("/play");
};
setShowPlayerModal(false);
router.push("/play");
};
return (
<>
<nav className="bg-gray-900 border-b border-gray-800 px-4 py-3">
<div className="max-w-7xl mx-auto flex items-center gap-4 flex-wrap">
<Link
href="/"
className="text-lg font-bold text-white flex items-center gap-2"
>
<span className="text-2xl">🔴</span>
<span>Connect4</span>
<span className="text-gray-400 text-sm font-normal">Moderator</span>
</Link>
return (
<>
<nav className="bg-gray-900 border-b border-gray-800 px-4 py-3">
<div className="max-w-7xl mx-auto flex items-center gap-4 flex-wrap">
<Link
href="/"
className="text-lg font-bold text-white flex items-center gap-2"
>
<span className="text-2xl">🔴</span>
<span>Connect4</span>
<span className="text-gray-400 text-sm font-normal">Moderator</span>
</Link>
<div className="ml-auto flex items-center gap-2">
{!isConnectionPage && (
<button
onClick={
role === "player"
? handleBecomeObserver
: () => {
setNextUsername(username);
setShowPlayerModal(true);
}
}
disabled={disableRoleSwitch}
className="px-4 py-2 rounded-lg text-sm font-semibold transition-colors bg-blue-600 hover:bg-blue-500 disabled:bg-gray-700 disabled:text-gray-500 text-white"
>
{role === "player" ? "Become Observer" : "Become Player"}
</button>
)}
<div className="ml-auto flex items-center gap-2">
{!isConnectionPage && (
<button
onClick={
role === "player"
? handleBecomeObserver
: () => {
setNextUsername(username);
setShowPlayerModal(true);
}
}
disabled={disableRoleSwitch}
className="px-4 py-2 rounded-lg text-sm font-semibold transition-colors bg-blue-600 hover:bg-blue-500 disabled:bg-gray-700 disabled:text-gray-500 text-white"
>
{role === "player" ? "Become Observer" : "Become Player"}
</button>
)}
<div className="text-xs text-gray-400 bg-gray-800 px-3 py-1 rounded-full">
{statusLabel}
</div>
</div>
</div>
</nav>
<div className="text-xs text-gray-400 bg-gray-800 px-3 py-1 rounded-full">
{statusLabel}
</div>
</div>
</div>
</nav>
{showPlayerModal && (
<div className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center px-4">
<form
onSubmit={handleBecomePlayer}
className="w-full max-w-sm bg-gray-900 border border-gray-700 rounded-xl p-5 flex flex-col gap-3"
>
<h2 className="text-lg font-semibold text-white">Become Player</h2>
<p className="text-sm text-gray-400">
Enter a username to connect as a player.
</p>
{showPlayerModal && (
<div className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center px-4">
<form
onSubmit={handleBecomePlayer}
className="w-full max-w-sm bg-gray-900 border border-gray-700 rounded-xl p-5 flex flex-col gap-3"
>
<h2 className="text-lg font-semibold text-white">Become Player</h2>
<p className="text-sm text-gray-400">
Enter a username to connect as a player.
</p>
<input
autoFocus
value={nextUsername}
onChange={(event) => setNextUsername(event.target.value)}
className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
placeholder="Username"
/>
<input
autoFocus
value={nextUsername}
onChange={(event) => setNextUsername(event.target.value)}
className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
placeholder="Username"
/>
<div className="flex justify-end gap-2 pt-1">
<button
type="button"
onClick={() => setShowPlayerModal(false)}
className="px-3 py-2 rounded-lg text-sm font-medium bg-gray-700 hover:bg-gray-600 text-white"
>
Cancel
</button>
<button
type="submit"
className="px-3 py-2 rounded-lg text-sm font-semibold bg-blue-600 hover:bg-blue-500 text-white"
>
Continue
</button>
</div>
</form>
</div>
)}
</>
);
<div className="flex justify-end gap-2 pt-1">
<button
type="button"
onClick={() => setShowPlayerModal(false)}
className="px-3 py-2 rounded-lg text-sm font-medium bg-gray-700 hover:bg-gray-600 text-white"
>
Cancel
</button>
<button
type="submit"
className="px-3 py-2 rounded-lg text-sm font-semibold bg-blue-600 hover:bg-blue-500 text-white"
>
Continue
</button>
</div>
</form>
</div>
)}
</>
);
}

View File

@@ -1,390 +1,390 @@
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
DEFAULT_WS_URL,
ParsedMessage,
RECONNECT_INTERVAL_MS,
RECONNECT_TIMEOUT_MS,
cmd,
parseMessage,
DEFAULT_WS_URL,
ParsedMessage,
RECONNECT_INTERVAL_MS,
RECONNECT_TIMEOUT_MS,
cmd,
parseMessage,
} from "@/lib/protocol";
export type ConnectionRole = "observer" | "player";
export type ConnectionStatus =
| "idle"
| "connecting"
| "connected"
| "reconnecting"
| "disconnected";
| "idle"
| "connecting"
| "connected"
| "reconnecting"
| "disconnected";
type MessageListener = (message: ParsedMessage, raw: string) => void;
interface ConnectOptions {
role: ConnectionRole;
wsUrl: string;
username?: string;
role: ConnectionRole;
wsUrl: string;
username?: string;
}
interface ConnectionContextValue {
role: ConnectionRole | null;
wsUrl: string;
username: string;
status: ConnectionStatus;
isInMatch: boolean;
reconnectAttempts: number;
shouldRedirectToConnect: boolean;
becomePlayer: (username: string) => void;
connect: (options: ConnectOptions) => void;
disconnect: () => void;
send: (message: string) => boolean;
subscribe: (listener: MessageListener) => () => void;
clearRedirectFlag: () => void;
role: ConnectionRole | null;
wsUrl: string;
username: string;
status: ConnectionStatus;
isInMatch: boolean;
reconnectAttempts: number;
shouldRedirectToConnect: boolean;
becomePlayer: (username: string) => void;
connect: (options: ConnectOptions) => void;
disconnect: () => void;
send: (message: string) => boolean;
subscribe: (listener: MessageListener) => () => void;
clearRedirectFlag: () => void;
}
const ConnectionContext = createContext<ConnectionContextValue | null>(null);
interface SessionState {
role: ConnectionRole;
wsUrl: string;
username: string;
role: ConnectionRole;
wsUrl: string;
username: string;
}
export function ConnectionProvider({
children,
children,
}: {
children: React.ReactNode;
children: React.ReactNode;
}) {
const [role, setRole] = useState<ConnectionRole | null>(null);
const [wsUrl, setWsUrl] = useState(DEFAULT_WS_URL);
const [username, setUsername] = useState("");
const [status, setStatus] = useState<ConnectionStatus>("idle");
const [isInMatch, setIsInMatch] = useState(false);
const [reconnectAttempts, setReconnectAttempts] = useState(0);
const [shouldRedirectToConnect, setShouldRedirectToConnect] = useState(false);
const [role, setRole] = useState<ConnectionRole | null>(null);
const [wsUrl, setWsUrl] = useState(DEFAULT_WS_URL);
const [username, setUsername] = useState("");
const [status, setStatus] = useState<ConnectionStatus>("idle");
const [isInMatch, setIsInMatch] = useState(false);
const [reconnectAttempts, setReconnectAttempts] = useState(0);
const [shouldRedirectToConnect, setShouldRedirectToConnect] = useState(false);
const wsRef = useRef<WebSocket | null>(null);
const listenersRef = useRef<Set<MessageListener>>(new Set());
const manualCloseRef = useRef(false);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const reconnectDeadlineRef = useRef<number | null>(null);
const reconnectActiveRef = useRef(false);
const isInMatchRef = useRef(false);
const sessionRef = useRef<SessionState | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const listenersRef = useRef<Set<MessageListener>>(new Set());
const manualCloseRef = useRef(false);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const reconnectDeadlineRef = useRef<number | null>(null);
const reconnectActiveRef = useRef(false);
const isInMatchRef = useRef(false);
const sessionRef = useRef<SessionState | null>(null);
const clearReconnectTimer = useCallback(() => {
if (reconnectTimerRef.current) {
clearTimeout(reconnectTimerRef.current);
reconnectTimerRef.current = null;
}
}, []);
const clearReconnectTimer = useCallback(() => {
if (reconnectTimerRef.current) {
clearTimeout(reconnectTimerRef.current);
reconnectTimerRef.current = null;
}
}, []);
const clearReconnectState = useCallback(() => {
reconnectActiveRef.current = false;
reconnectDeadlineRef.current = null;
clearReconnectTimer();
setReconnectAttempts(0);
}, [clearReconnectTimer]);
const clearReconnectState = useCallback(() => {
reconnectActiveRef.current = false;
reconnectDeadlineRef.current = null;
clearReconnectTimer();
setReconnectAttempts(0);
}, [clearReconnectTimer]);
const emitMessage = useCallback((message: ParsedMessage, raw: string) => {
listenersRef.current.forEach((listener) => listener(message, raw));
}, []);
const emitMessage = useCallback((message: ParsedMessage, raw: string) => {
listenersRef.current.forEach((listener) => listener(message, raw));
}, []);
const safeCloseSocket = useCallback(() => {
const current = wsRef.current;
if (!current) return;
current.onopen = null;
current.onmessage = null;
current.onclose = null;
current.onerror = null;
try {
current.close();
} catch {
// no-op
}
wsRef.current = null;
}, []);
const safeCloseSocket = useCallback(() => {
const current = wsRef.current;
if (!current) return;
current.onopen = null;
current.onmessage = null;
current.onclose = null;
current.onerror = null;
try {
current.close();
} catch {
// no-op
}
wsRef.current = null;
}, []);
const handleDisconnect = useCallback(() => {
const currentRole = sessionRef.current?.role;
const handleDisconnect = useCallback(() => {
const currentRole = sessionRef.current?.role;
if (currentRole === "observer") {
clearReconnectState();
setStatus("disconnected");
setShouldRedirectToConnect(true);
return;
}
if (currentRole === "observer") {
clearReconnectState();
setStatus("disconnected");
setShouldRedirectToConnect(true);
return;
}
if (currentRole === "player" && isInMatchRef.current) {
if (reconnectActiveRef.current) {
setStatus("reconnecting");
return;
}
reconnectActiveRef.current = true;
reconnectDeadlineRef.current = Date.now() + RECONNECT_TIMEOUT_MS;
setStatus("reconnecting");
setReconnectAttempts(0);
return;
}
if (currentRole === "player" && isInMatchRef.current) {
if (reconnectActiveRef.current) {
setStatus("reconnecting");
return;
}
reconnectActiveRef.current = true;
reconnectDeadlineRef.current = Date.now() + RECONNECT_TIMEOUT_MS;
setStatus("reconnecting");
setReconnectAttempts(0);
return;
}
clearReconnectState();
setStatus("disconnected");
setShouldRedirectToConnect(true);
}, [clearReconnectState]);
clearReconnectState();
setStatus("disconnected");
setShouldRedirectToConnect(true);
}, [clearReconnectState]);
const attachSocket = useCallback(
(socket: WebSocket, reconnecting: boolean) => {
socket.onopen = () => {
const session = sessionRef.current;
if (!session) return;
const attachSocket = useCallback(
(socket: WebSocket, reconnecting: boolean) => {
socket.onopen = () => {
const session = sessionRef.current;
if (!session) return;
if (session.role === "observer") {
socket.send(cmd.observe());
return;
}
if (session.role === "observer") {
socket.send(cmd.observe());
return;
}
if (reconnecting) {
socket.send(cmd.reconnect(session.username));
} else {
socket.send(cmd.connect(session.username));
}
};
if (reconnecting) {
socket.send(cmd.reconnect(session.username));
} else {
socket.send(cmd.connect(session.username));
}
};
socket.onmessage = (event) => {
const raw = event.data as string;
console.log(raw);
const parsed = parseMessage(raw);
socket.onmessage = (event) => {
const raw = event.data as string;
console.log(raw);
const parsed = parseMessage(raw);
if (parsed.type === "OBSERVE_ACK") {
setRole("observer");
setShouldRedirectToConnect(false);
setStatus("connected");
}
if (parsed.type === "OBSERVE_ACK") {
setRole("observer");
setShouldRedirectToConnect(false);
setStatus("connected");
}
if (parsed.type === "CONNECT_ACK") {
setRole("player");
}
if (parsed.type === "CONNECT_ACK") {
setRole("player");
}
if (parsed.type === "RECONNECT_ACK") {
clearReconnectState();
setShouldRedirectToConnect(false);
setStatus("connected");
}
if (parsed.type === "RECONNECT_ACK") {
clearReconnectState();
setShouldRedirectToConnect(false);
setStatus("connected");
}
if (parsed.type === "DISCONNECT_ACK") {
setRole("observer");
setUsername("");
isInMatchRef.current = false;
setIsInMatch(false);
}
if (parsed.type === "DISCONNECT_ACK") {
setRole("observer");
setUsername("");
isInMatchRef.current = false;
setIsInMatch(false);
}
if (parsed.type === "GAME_START") {
isInMatchRef.current = true;
setIsInMatch(true);
}
if (parsed.type === "GAME_START") {
isInMatchRef.current = true;
setIsInMatch(true);
}
if (
parsed.type === "GAME_WINS" ||
parsed.type === "GAME_LOSS" ||
parsed.type === "GAME_DRAW" ||
parsed.type === "GAME_TERMINATED"
) {
isInMatchRef.current = false;
setIsInMatch(false);
}
if (
parsed.type === "GAME_WINS" ||
parsed.type === "GAME_LOSS" ||
parsed.type === "GAME_DRAW" ||
parsed.type === "GAME_TERMINATED"
) {
isInMatchRef.current = false;
setIsInMatch(false);
}
if (
parsed.type === "ERROR" &&
reconnecting &&
parsed.message.startsWith("ERROR:INVALID:RECONNECT")
) {
safeCloseSocket();
}
if (
parsed.type === "ERROR" &&
reconnecting &&
parsed.message.startsWith("ERROR:INVALID:RECONNECT")
) {
safeCloseSocket();
}
emitMessage(parsed, raw);
};
emitMessage(parsed, raw);
};
socket.onclose = () => {
wsRef.current = null;
if (manualCloseRef.current) {
manualCloseRef.current = false;
return;
}
handleDisconnect();
};
socket.onclose = () => {
wsRef.current = null;
if (manualCloseRef.current) {
manualCloseRef.current = false;
return;
}
handleDisconnect();
};
socket.onerror = () => {
// Allow close event to drive state transitions.
};
},
[clearReconnectState, emitMessage, handleDisconnect, safeCloseSocket],
);
socket.onerror = () => {
// Allow close event to drive state transitions.
};
},
[clearReconnectState, emitMessage, handleDisconnect, safeCloseSocket],
);
const openSocket = useCallback(
(reconnecting: boolean) => {
const session = sessionRef.current;
if (!session) return;
const openSocket = useCallback(
(reconnecting: boolean) => {
const session = sessionRef.current;
if (!session) return;
safeCloseSocket();
manualCloseRef.current = false;
const socket = new WebSocket(session.wsUrl);
wsRef.current = socket;
attachSocket(socket, reconnecting);
},
[attachSocket, safeCloseSocket],
);
safeCloseSocket();
manualCloseRef.current = false;
const socket = new WebSocket(session.wsUrl);
wsRef.current = socket;
attachSocket(socket, reconnecting);
},
[attachSocket, safeCloseSocket],
);
useEffect(() => {
if (!reconnectActiveRef.current) return;
useEffect(() => {
if (!reconnectActiveRef.current) return;
const runReconnectAttempt = () => {
if (!reconnectActiveRef.current) return;
const runReconnectAttempt = () => {
if (!reconnectActiveRef.current) return;
const deadline = reconnectDeadlineRef.current;
if (!deadline || Date.now() >= deadline) {
reconnectActiveRef.current = false;
reconnectDeadlineRef.current = null;
setStatus("disconnected");
setShouldRedirectToConnect(true);
return;
}
const deadline = reconnectDeadlineRef.current;
if (!deadline || Date.now() >= deadline) {
reconnectActiveRef.current = false;
reconnectDeadlineRef.current = null;
setStatus("disconnected");
setShouldRedirectToConnect(true);
return;
}
setReconnectAttempts((prev) => prev + 1);
openSocket(true);
setReconnectAttempts((prev) => prev + 1);
openSocket(true);
clearReconnectTimer();
reconnectTimerRef.current = setTimeout(
runReconnectAttempt,
RECONNECT_INTERVAL_MS,
);
};
clearReconnectTimer();
reconnectTimerRef.current = setTimeout(
runReconnectAttempt,
RECONNECT_INTERVAL_MS,
);
};
runReconnectAttempt();
runReconnectAttempt();
return () => clearReconnectTimer();
}, [clearReconnectTimer, openSocket, status]);
return () => clearReconnectTimer();
}, [clearReconnectTimer, openSocket, status]);
const connect = useCallback(
({ role, wsUrl, username }: ConnectOptions) => {
const resolvedUsername = (username ?? "").trim();
sessionRef.current = { role, wsUrl, username: resolvedUsername };
const connect = useCallback(
({ role, wsUrl, username }: ConnectOptions) => {
const resolvedUsername = (username ?? "").trim();
sessionRef.current = { role, wsUrl, username: resolvedUsername };
setRole(role);
setWsUrl(wsUrl);
setUsername(resolvedUsername);
setShouldRedirectToConnect(false);
clearReconnectState();
isInMatchRef.current = false;
setIsInMatch(false);
setStatus("connecting");
setRole(role);
setWsUrl(wsUrl);
setUsername(resolvedUsername);
setShouldRedirectToConnect(false);
clearReconnectState();
isInMatchRef.current = false;
setIsInMatch(false);
setStatus("connecting");
openSocket(false);
},
[clearReconnectState, openSocket],
);
openSocket(false);
},
[clearReconnectState, openSocket],
);
const becomePlayer = useCallback(
(username: string) => {
const resolvedUsername = (username ?? "").trim();
setRole("player");
setUsername(resolvedUsername);
isInMatchRef.current = false;
setIsInMatch(false);
send(cmd.connect(resolvedUsername));
},
[clearReconnectState, openSocket],
);
const becomePlayer = useCallback(
(username: string) => {
const resolvedUsername = (username ?? "").trim();
setRole("player");
setUsername(resolvedUsername);
isInMatchRef.current = false;
setIsInMatch(false);
send(cmd.connect(resolvedUsername));
},
[clearReconnectState, openSocket],
);
const disconnect = useCallback(() => {
clearReconnectState();
manualCloseRef.current = true;
safeCloseSocket();
const disconnect = useCallback(() => {
clearReconnectState();
manualCloseRef.current = true;
safeCloseSocket();
sessionRef.current = null;
setRole(null);
setStatus("idle");
setUsername("");
setIsInMatch(false);
isInMatchRef.current = false;
setShouldRedirectToConnect(false);
}, [clearReconnectState, safeCloseSocket]);
sessionRef.current = null;
setRole(null);
setStatus("idle");
setUsername("");
setIsInMatch(false);
isInMatchRef.current = false;
setShouldRedirectToConnect(false);
}, [clearReconnectState, safeCloseSocket]);
const send = useCallback((message: string) => {
if (wsRef.current?.readyState !== WebSocket.OPEN) return false;
wsRef.current.send(message);
return true;
}, []);
const send = useCallback((message: string) => {
if (wsRef.current?.readyState !== WebSocket.OPEN) return false;
wsRef.current.send(message);
return true;
}, []);
const subscribe = useCallback((listener: MessageListener) => {
listenersRef.current.add(listener);
return () => {
listenersRef.current.delete(listener);
};
}, []);
const subscribe = useCallback((listener: MessageListener) => {
listenersRef.current.add(listener);
return () => {
listenersRef.current.delete(listener);
};
}, []);
const clearRedirectFlag = useCallback(() => {
setShouldRedirectToConnect(false);
}, []);
const clearRedirectFlag = useCallback(() => {
setShouldRedirectToConnect(false);
}, []);
useEffect(() => {
return () => {
clearReconnectState();
manualCloseRef.current = true;
safeCloseSocket();
};
}, [clearReconnectState, safeCloseSocket]);
useEffect(() => {
return () => {
clearReconnectState();
manualCloseRef.current = true;
safeCloseSocket();
};
}, [clearReconnectState, safeCloseSocket]);
const value = useMemo<ConnectionContextValue>(
() => ({
role,
wsUrl,
username,
status,
isInMatch,
reconnectAttempts,
shouldRedirectToConnect,
becomePlayer,
connect,
disconnect,
send,
subscribe,
clearRedirectFlag,
}),
[
role,
wsUrl,
username,
status,
isInMatch,
reconnectAttempts,
shouldRedirectToConnect,
connect,
disconnect,
send,
subscribe,
clearRedirectFlag,
],
);
const value = useMemo<ConnectionContextValue>(
() => ({
role,
wsUrl,
username,
status,
isInMatch,
reconnectAttempts,
shouldRedirectToConnect,
becomePlayer,
connect,
disconnect,
send,
subscribe,
clearRedirectFlag,
}),
[
role,
wsUrl,
username,
status,
isInMatch,
reconnectAttempts,
shouldRedirectToConnect,
connect,
disconnect,
send,
subscribe,
clearRedirectFlag,
],
);
return (
<ConnectionContext.Provider value={value}>
{children}
</ConnectionContext.Provider>
);
return (
<ConnectionContext.Provider value={value}>
{children}
</ConnectionContext.Provider>
);
}
export function useConnection() {
const context = useContext(ConnectionContext);
if (!context) {
throw new Error("useConnection must be used within a ConnectionProvider");
}
return context;
const context = useContext(ConnectionContext);
if (!context) {
throw new Error("useConnection must be used within a ConnectionProvider");
}
return context;
}

View File

@@ -1,262 +1,262 @@
// ─── Types ───────────────────────────────────────────────────────────────────
export interface GameEntry {
id: number;
player1: string;
player2: string;
id: number;
player1: string;
player2: string;
}
export interface PlayerEntry {
username: string;
ready: boolean;
inMatch: boolean;
username: string;
ready: boolean;
inMatch: boolean;
}
export interface ScoreEntry {
player: string;
score: number;
player: string;
score: number;
}
export interface MoveEntry {
username: string;
column: number;
username: string;
column: number;
}
export const DEFAULT_WS_URL =
process.env.NODE_ENV === "development"
? "ws://localhost:8080"
: "wss://connect4.abunchofknowitalls.com";
process.env.NODE_ENV === "development"
? "ws://localhost:8080"
: "wss://connect4.abunchofknowitalls.com";
export const RECONNECT_INTERVAL_MS = 5000;
export const RECONNECT_TIMEOUT_MS = 60000;
// ─── Parsed message union ────────────────────────────────────────────────────
export type ParsedMessage =
| { type: "CONNECT_ACK" }
| { type: "RECONNECT_ACK" }
| { type: "DISCONNECT_ACK" }
| { type: "OBSERVE_ACK"; enabled: boolean }
| { type: "READY_ACK" }
| { type: "GAME_START"; goesFirst: boolean }
| { type: "GAME_WINS" }
| { type: "GAME_LOSS" }
| { type: "GAME_DRAW"; matchId?: number }
| { type: "GAME_TERMINATED"; matchId?: number }
| { type: "OPPONENT_MOVE"; column: number }
| { type: "GAME_LIST"; games: GameEntry[] }
| {
type: "GAME_WATCH_ACK";
matchId: number;
player1: string;
player2: string;
moves: MoveEntry[];
}
| { type: "GAME_MOVE"; matchId?: number; username: string; column: number }
| { type: "GAME_WIN"; matchId?: number; winner: string }
| { type: "PLAYER_LIST"; players: PlayerEntry[] }
| { type: "TOURNAMENT_START"; tournamentType: string }
| { type: "TOURNAMENT_CANCEL" }
| { type: "TOURNAMENT_SCORES"; scores: ScoreEntry[] }
| { type: "TOURNAMENT_END" }
| { type: "ADMIN_AUTH_ACK" }
| { type: "GET_DATA"; key: string; value: string }
| { type: "SET_DATA_ACK"; key: string }
| { type: "ERROR"; message: string }
| { type: "UNKNOWN"; raw: string };
| { type: "CONNECT_ACK" }
| { type: "RECONNECT_ACK" }
| { type: "DISCONNECT_ACK" }
| { type: "OBSERVE_ACK"; enabled: boolean }
| { type: "READY_ACK" }
| { type: "GAME_START"; goesFirst: boolean }
| { type: "GAME_WINS" }
| { type: "GAME_LOSS" }
| { type: "GAME_DRAW"; matchId?: number }
| { type: "GAME_TERMINATED"; matchId?: number }
| { type: "OPPONENT_MOVE"; column: number }
| { type: "GAME_LIST"; games: GameEntry[] }
| {
type: "GAME_WATCH_ACK";
matchId: number;
player1: string;
player2: string;
moves: MoveEntry[];
}
| { type: "GAME_MOVE"; matchId?: number; username: string; column: number }
| { type: "GAME_WIN"; matchId?: number; winner: string }
| { type: "PLAYER_LIST"; players: PlayerEntry[] }
| { type: "TOURNAMENT_START"; tournamentType: string }
| { type: "TOURNAMENT_CANCEL" }
| { type: "TOURNAMENT_SCORES"; scores: ScoreEntry[] }
| { type: "TOURNAMENT_END" }
| { type: "ADMIN_AUTH_ACK" }
| { type: "GET_DATA"; key: string; value: string }
| { type: "SET_DATA_ACK"; key: string }
| { type: "ERROR"; message: string }
| { type: "UNKNOWN"; raw: string };
// ─── Parser ──────────────────────────────────────────────────────────────────
export function parseMessage(raw: string): ParsedMessage {
const parts = raw.split(":");
const parts = raw.split(":");
switch (parts[0]) {
case "CONNECT":
if (parts[1] === "ACK") return { type: "CONNECT_ACK" };
break;
case "RECONNECT":
if (parts[1] === "ACK") return { type: "RECONNECT_ACK" };
break;
case "DISCONNECT":
if (parts[1] === "ACK") return { type: "DISCONNECT_ACK" };
break;
case "OBSERVE":
if (parts[1] === "ACK") {
return { type: "OBSERVE_ACK", enabled: parts[2] === "1" };
}
break;
case "READY":
if (parts[1] === "ACK") return { type: "READY_ACK" };
break;
switch (parts[0]) {
case "CONNECT":
if (parts[1] === "ACK") return { type: "CONNECT_ACK" };
break;
case "RECONNECT":
if (parts[1] === "ACK") return { type: "RECONNECT_ACK" };
break;
case "DISCONNECT":
if (parts[1] === "ACK") return { type: "DISCONNECT_ACK" };
break;
case "OBSERVE":
if (parts[1] === "ACK") {
return { type: "OBSERVE_ACK", enabled: parts[2] === "1" };
}
break;
case "READY":
if (parts[1] === "ACK") return { type: "READY_ACK" };
break;
case "GAME": {
const scopedMatchId = parseInt(parts[1], 10);
if (!Number.isNaN(scopedMatchId)) {
switch (parts[2]) {
case "MOVE":
return {
type: "GAME_MOVE",
matchId: scopedMatchId,
username: parts[3],
column: parseInt(parts[4], 10),
};
case "WIN":
return {
type: "GAME_WIN",
matchId: scopedMatchId,
winner: parts[3],
};
case "DRAW":
return { type: "GAME_DRAW", matchId: scopedMatchId };
case "TERMINATED":
return { type: "GAME_TERMINATED", matchId: scopedMatchId };
}
}
case "GAME": {
const scopedMatchId = parseInt(parts[1], 10);
if (!Number.isNaN(scopedMatchId)) {
switch (parts[2]) {
case "MOVE":
return {
type: "GAME_MOVE",
matchId: scopedMatchId,
username: parts[3],
column: parseInt(parts[4], 10),
};
case "WIN":
return {
type: "GAME_WIN",
matchId: scopedMatchId,
winner: parts[3],
};
case "DRAW":
return { type: "GAME_DRAW", matchId: scopedMatchId };
case "TERMINATED":
return { type: "GAME_TERMINATED", matchId: scopedMatchId };
}
}
switch (parts[1]) {
case "START":
return { type: "GAME_START", goesFirst: parts[2] === "1" };
case "WINS":
return { type: "GAME_WINS" };
case "LOSS":
return { type: "GAME_LOSS" };
case "DRAW":
return { type: "GAME_DRAW" };
case "TERMINATED":
return { type: "GAME_TERMINATED" };
switch (parts[1]) {
case "START":
return { type: "GAME_START", goesFirst: parts[2] === "1" };
case "WINS":
return { type: "GAME_WINS" };
case "LOSS":
return { type: "GAME_LOSS" };
case "DRAW":
return { type: "GAME_DRAW" };
case "TERMINATED":
return { type: "GAME_TERMINATED" };
case "LIST": {
const data = parts[2] ?? "";
if (!data) return { type: "GAME_LIST", games: [] };
const games: GameEntry[] = data.split("|").map((g) => {
const [id, player1, player2] = g.split(",");
return { id: parseInt(id), player1, player2 };
});
return { type: "GAME_LIST", games };
}
case "LIST": {
const data = parts[2] ?? "";
if (!data) return { type: "GAME_LIST", games: [] };
const games: GameEntry[] = data.split("|").map((g) => {
const [id, player1, player2] = g.split(",");
return { id: parseInt(id), player1, player2 };
});
return { type: "GAME_LIST", games };
}
case "WATCH": {
if (parts[2] === "ACK") {
// GAME:WATCH:ACK:<id>,<p1>,<p2>|<username>,<col>|...
const data = parts.slice(3).join(":");
const segments = data.split("|");
const [idStr, player1, player2] = segments[0].split(",");
const moves: MoveEntry[] = segments
.slice(1)
.filter(Boolean)
.map((m) => {
const lastComma = m.lastIndexOf(",");
return {
username: m.substring(0, lastComma),
column: parseInt(m.substring(lastComma + 1)),
};
});
return {
type: "GAME_WATCH_ACK",
matchId: parseInt(idStr),
player1,
player2,
moves,
};
}
break;
}
}
break;
}
case "WATCH": {
if (parts[2] === "ACK") {
// GAME:WATCH:ACK:<id>,<p1>,<p2>|<username>,<col>|...
const data = parts.slice(3).join(":");
const segments = data.split("|");
const [idStr, player1, player2] = segments[0].split(",");
const moves: MoveEntry[] = segments
.slice(1)
.filter(Boolean)
.map((m) => {
const lastComma = m.lastIndexOf(",");
return {
username: m.substring(0, lastComma),
column: parseInt(m.substring(lastComma + 1)),
};
});
return {
type: "GAME_WATCH_ACK",
matchId: parseInt(idStr),
player1,
player2,
moves,
};
}
break;
}
}
break;
}
case "OPPONENT":
return {
type: "OPPONENT_MOVE",
column: parseInt(parts[parts.length - 1], 10),
};
case "OPPONENT":
return {
type: "OPPONENT_MOVE",
column: parseInt(parts[parts.length - 1], 10),
};
case "PLAYER": {
if (parts[1] === "LIST") {
const data = parts[2] ?? "";
if (!data) return { type: "PLAYER_LIST", players: [] };
const players: PlayerEntry[] = data.split("|").map((p) => {
const [username, ready, inMatch] = p.split(",");
return {
username,
ready: ready === "true",
inMatch: inMatch === "true",
};
});
return { type: "PLAYER_LIST", players };
}
break;
}
case "PLAYER": {
if (parts[1] === "LIST") {
const data = parts[2] ?? "";
if (!data) return { type: "PLAYER_LIST", players: [] };
const players: PlayerEntry[] = data.split("|").map((p) => {
const [username, ready, inMatch] = p.split(",");
return {
username,
ready: ready === "true",
inMatch: inMatch === "true",
};
});
return { type: "PLAYER_LIST", players };
}
break;
}
case "TOURNAMENT": {
switch (parts[1]) {
case "START":
return { type: "TOURNAMENT_START", tournamentType: parts[2] };
case "CANCEL":
return { type: "TOURNAMENT_CANCEL" };
case "SCORES": {
const data = parts[2] ?? "";
if (!data) return { type: "TOURNAMENT_SCORES", scores: [] };
const scores: ScoreEntry[] = data.split("|").map((s) => {
const lastComma = s.lastIndexOf(",");
return {
player: s.substring(0, lastComma),
score: parseInt(s.substring(lastComma + 1)),
};
});
return { type: "TOURNAMENT_SCORES", scores };
}
case "END":
return { type: "TOURNAMENT_END" };
}
break;
}
case "TOURNAMENT": {
switch (parts[1]) {
case "START":
return { type: "TOURNAMENT_START", tournamentType: parts[2] };
case "CANCEL":
return { type: "TOURNAMENT_CANCEL" };
case "SCORES": {
const data = parts[2] ?? "";
if (!data) return { type: "TOURNAMENT_SCORES", scores: [] };
const scores: ScoreEntry[] = data.split("|").map((s) => {
const lastComma = s.lastIndexOf(",");
return {
player: s.substring(0, lastComma),
score: parseInt(s.substring(lastComma + 1)),
};
});
return { type: "TOURNAMENT_SCORES", scores };
}
case "END":
return { type: "TOURNAMENT_END" };
}
break;
}
case "ADMIN":
if (parts[1] === "AUTH" && parts[2] === "ACK")
return { type: "ADMIN_AUTH_ACK" };
break;
case "ADMIN":
if (parts[1] === "AUTH" && parts[2] === "ACK")
return { type: "ADMIN_AUTH_ACK" };
break;
case "GET":
return { type: "GET_DATA", key: parts[1], value: parts[2] ?? "" };
case "GET":
return { type: "GET_DATA", key: parts[1], value: parts[2] ?? "" };
case "SET":
if (parts[2] === "ACK") return { type: "SET_DATA_ACK", key: parts[1] };
break;
case "SET":
if (parts[2] === "ACK") return { type: "SET_DATA_ACK", key: parts[1] };
break;
case "ERROR":
return { type: "ERROR", message: raw };
}
case "ERROR":
return { type: "ERROR", message: raw };
}
return { type: "UNKNOWN", raw };
return { type: "UNKNOWN", raw };
}
// ─── Command builders ────────────────────────────────────────────────────────
export const cmd = {
connect: (username: string) => `CONNECT:${username}`,
reconnect: (username: string) => `RECONNECT:${username}`,
disconnect: () => "DISCONNECT",
observe: () => "OBSERVE",
ready: () => "READY",
play: (column: number) => `PLAY:${column}`,
playerList: () => "PLAYER:LIST",
gameList: () => "GAME:LIST",
gameWatch: (matchId: number) => `GAME:WATCH:${matchId}`,
gameTerminate: (matchId: number) => `GAME:TERMINATE:${matchId}`,
gameAward: (matchId: number, winner: string) =>
`GAME:AWARD:${matchId}:${winner}`,
adminAuth: (password: string) => `ADMIN:AUTH:${password}`,
adminKick: (username: string) => `ADMIN:KICK:${username}`,
tournamentStart: (type = "RoundRobin") => `TOURNAMENT:START:${type}`,
tournamentCancel: () => "TOURNAMENT:CANCEL",
getData: (
key: "TOURNAMENT_STATUS" | "MOVE_WAIT" | "DEMO_MODE" | "MAX_TIMEOUT",
) => `GET:${key}`,
setData: (key: string, value: string) => `SET:${key}:${value}`,
reservationAdd: (p1: string, p2: string) => `RESERVATION:ADD:${p1},${p2}`,
reservationDelete: (p1: string, p2: string) =>
`RESERVATION:DELETE:${p1},${p2}`,
reservationGet: () => "RESERVATION:GET",
connect: (username: string) => `CONNECT:${username}`,
reconnect: (username: string) => `RECONNECT:${username}`,
disconnect: () => "DISCONNECT",
observe: () => "OBSERVE",
ready: () => "READY",
play: (column: number) => `PLAY:${column}`,
playerList: () => "PLAYER:LIST",
gameList: () => "GAME:LIST",
gameWatch: (matchId: number) => `GAME:WATCH:${matchId}`,
gameTerminate: (matchId: number) => `GAME:TERMINATE:${matchId}`,
gameAward: (matchId: number, winner: string) =>
`GAME:AWARD:${matchId}:${winner}`,
adminAuth: (password: string) => `ADMIN:AUTH:${password}`,
adminKick: (username: string) => `ADMIN:KICK:${username}`,
tournamentStart: (type = "RoundRobin") => `TOURNAMENT:START:${type}`,
tournamentCancel: () => "TOURNAMENT:CANCEL",
getData: (
key: "TOURNAMENT_STATUS" | "MOVE_WAIT" | "DEMO_MODE" | "MAX_TIMEOUT",
) => `GET:${key}`,
setData: (key: string, value: string) => `SET:${key}:${value}`,
reservationAdd: (p1: string, p2: string) => `RESERVATION:ADD:${p1},${p2}`,
reservationDelete: (p1: string, p2: string) =>
`RESERVATION:DELETE:${p1},${p2}`,
reservationGet: () => "RESERVATION:GET",
};
// ─── Board helpers ────────────────────────────────────────────────────────────
@@ -266,39 +266,39 @@ export type CellColor = 0 | 1 | 2;
export type BoardState = CellColor[][]; // board[col][row], 7 cols × 6 rows
export function createEmptyBoard(): BoardState {
return Array.from({ length: 7 }, () => Array(6).fill(0)) as BoardState;
return Array.from({ length: 7 }, () => Array(6).fill(0)) as BoardState;
}
/** Place a token and return the new board plus the row it landed in (-1 if column full). */
export function placeToken(
board: BoardState,
color: 1 | 2,
column: number,
board: BoardState,
color: 1 | 2,
column: number,
): { board: BoardState; row: number } {
const newBoard = board.map((col) => [...col]) as BoardState;
let placedRow = -1;
for (let row = 0; row < 6; row++) {
if (newBoard[column][row] === 0) {
newBoard[column][row] = color;
placedRow = row;
break;
}
}
return { board: newBoard, row: placedRow };
const newBoard = board.map((col) => [...col]) as BoardState;
let placedRow = -1;
for (let row = 0; row < 6; row++) {
if (newBoard[column][row] === 0) {
newBoard[column][row] = color;
placedRow = row;
break;
}
}
return { board: newBoard, row: placedRow };
}
/** Replay a move list onto an empty board. */
export function replayMoves(
moves: MoveEntry[],
player1: string,
moves: MoveEntry[],
player1: string,
): { board: BoardState; lastMove: { column: number; row: number } | null } {
let board = createEmptyBoard();
let lastMove: { column: number; row: number } | null = null;
for (const move of moves) {
const color: 1 | 2 = move.username === player1 ? 1 : 2;
const result = placeToken(board, color, move.column);
board = result.board;
lastMove = { column: move.column, row: result.row };
}
return { board, lastMove };
let board = createEmptyBoard();
let lastMove: { column: number; row: number } | null = null;
for (const move of moves) {
const color: 1 | 2 = move.username === player1 ? 1 : 2;
const result = placeToken(board, color, move.column);
board = result.board;
lastMove = { column: move.column, row: result.row };
}
return { board, lastMove };
}

View File

@@ -20,6 +20,7 @@
"eslint": "^9",
"eslint-config-next": "15.2.4",
"postcss": "^8",
"prettier": "^3.8.1",
"tailwindcss": "^4",
"typescript": "^5"
}
@@ -4962,6 +4963,22 @@
"node": ">= 0.8.0"
}
},
"node_modules/prettier": {
"version": "3.8.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz",
"integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",

View File

@@ -6,7 +6,9 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "next lint",
"format": "prettier --write .",
"format:check": "prettier --check ."
},
"dependencies": {
"next": "15.2.4",
@@ -14,14 +16,15 @@
"react-dom": "^19.0.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.2.4",
"typescript": "^5",
"postcss": "^8",
"prettier": "^3.8.1",
"tailwindcss": "^4",
"@tailwindcss/postcss": "^4",
"postcss": "^8"
"typescript": "^5"
}
}

View File

@@ -1,10 +1,6 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
@@ -22,19 +18,10 @@
}
],
"paths": {
"@/*": [
"./*"
]
"@/*": ["./*"]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}