everything
This commit is contained in:
@@ -1,23 +1,26 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import Nav from "@/components/Nav";
|
import Nav from "@/components/Nav";
|
||||||
|
import { ConnectionProvider } from "@/lib/connection";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Connect4 Moderator",
|
title: "Connect4 Moderator",
|
||||||
description: "Watch matches, track tournaments, and play Connect4",
|
description: "Watch matches, track tournaments, and play Connect4",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<body className="min-h-screen bg-gray-950 text-gray-100">
|
<body className="min-h-screen bg-gray-950 text-gray-100">
|
||||||
<Nav />
|
<ConnectionProvider>
|
||||||
<main className="max-w-7xl mx-auto px-4 py-6">{children}</main>
|
<Nav />
|
||||||
</body>
|
<main className="max-w-7xl mx-auto px-4 py-6">{children}</main>
|
||||||
</html>
|
</ConnectionProvider>
|
||||||
);
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,84 +1,85 @@
|
|||||||
import Link from "next/link";
|
"use client";
|
||||||
|
|
||||||
const cards = [
|
import { FormEvent, useEffect, useState } from "react";
|
||||||
{
|
import { useRouter } from "next/navigation";
|
||||||
href: "/spectate",
|
import { DEFAULT_WS_URL } from "@/lib/protocol";
|
||||||
icon: "👁",
|
import { useConnection } from "@/lib/connection";
|
||||||
title: "Spectate Matches",
|
|
||||||
desc: "Watch live Connect4 games in real time. See every move as it happens on an interactive board.",
|
|
||||||
color: "border-blue-600 hover:border-blue-400",
|
|
||||||
badge: "Observer",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/tournament",
|
|
||||||
icon: "🏆",
|
|
||||||
title: "Tournament View",
|
|
||||||
desc: "Track tournament standings, scores, and active rounds. Stay updated with live leaderboards.",
|
|
||||||
color: "border-purple-600 hover:border-purple-400",
|
|
||||||
badge: "Live Stats",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/play",
|
|
||||||
icon: "🎮",
|
|
||||||
title: "Play as Human",
|
|
||||||
desc: "Join the server as a player. Connect with a username, ready up, and play Connect4 live.",
|
|
||||||
color: "border-green-600 hover:border-green-400",
|
|
||||||
badge: "Interactive",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
return (
|
const router = useRouter();
|
||||||
<div className="flex flex-col items-center gap-10 py-12">
|
const {
|
||||||
<div className="text-center">
|
connect,
|
||||||
<h1 className="text-4xl font-bold text-white mb-3">
|
role,
|
||||||
Connect4 Moderator
|
status,
|
||||||
</h1>
|
wsUrl: connectedWsUrl,
|
||||||
<p className="text-gray-400 text-lg max-w-xl">
|
shouldRedirectToConnect,
|
||||||
Student AI tournament platform — watch games, track standings, or play
|
clearRedirectFlag,
|
||||||
yourself.
|
} = useConnection();
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 w-full max-w-4xl">
|
const [wsUrl, setWsUrl] = useState(DEFAULT_WS_URL);
|
||||||
{cards.map(({ href, icon, title, desc, color, badge }) => (
|
|
||||||
<Link
|
|
||||||
key={href}
|
|
||||||
href={href}
|
|
||||||
className={`bg-gray-900 border-2 ${color} rounded-xl p-6 flex flex-col gap-3 transition-all hover:bg-gray-800 hover:shadow-xl group`}
|
|
||||||
>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-4xl">{icon}</span>
|
|
||||||
<span className="text-xs font-mono bg-gray-800 text-gray-400 px-2 py-1 rounded-full group-hover:bg-gray-700">
|
|
||||||
{badge}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-xl font-semibold text-white">{title}</h2>
|
|
||||||
<p className="text-gray-400 text-sm leading-relaxed">{desc}</p>
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-gray-900 border border-gray-700 rounded-xl p-6 max-w-2xl w-full">
|
useEffect(() => {
|
||||||
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">
|
if (shouldRedirectToConnect) {
|
||||||
WebSocket Protocol Reference
|
clearRedirectFlag();
|
||||||
</h3>
|
}
|
||||||
<div className="grid grid-cols-2 gap-2 text-xs font-mono">
|
}, [shouldRedirectToConnect, clearRedirectFlag]);
|
||||||
{[
|
|
||||||
["CONNECT:<name>", "Register as player"],
|
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||||
["READY", "Signal ready to play"],
|
event.preventDefault();
|
||||||
["PLAY:<col>", "Drop piece in column 0–6"],
|
|
||||||
["GAME:LIST", "List active matches"],
|
connect({ role: "observer", wsUrl });
|
||||||
["GAME:WATCH:<id>", "Watch a specific match"],
|
router.push("/spectate");
|
||||||
["PLAYER:LIST", "List connected players"],
|
};
|
||||||
].map(([cmd, desc]) => (
|
|
||||||
<div key={cmd} className="flex gap-2">
|
return (
|
||||||
<span className="text-blue-400">{cmd}</span>
|
<div className="max-w-3xl mx-auto py-10">
|
||||||
<span className="text-gray-500">→ {desc}</span>
|
<div className="bg-gray-900 border border-gray-700 rounded-2xl p-6 md:p-8 flex flex-col gap-6">
|
||||||
</div>
|
<div>
|
||||||
))}
|
<h1 className="text-3xl font-bold text-white">
|
||||||
</div>
|
Connect to Moderator Server
|
||||||
</div>
|
</h1>
|
||||||
</div>
|
<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>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,555 +1,477 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
import Board from "@/components/Board";
|
import Board from "@/components/Board";
|
||||||
import {
|
import {
|
||||||
BoardState,
|
BoardState,
|
||||||
ParsedMessage,
|
ParsedMessage,
|
||||||
cmd,
|
cmd,
|
||||||
createEmptyBoard,
|
createEmptyBoard,
|
||||||
parseMessage,
|
placeToken,
|
||||||
placeToken,
|
|
||||||
} from "@/lib/protocol";
|
} from "@/lib/protocol";
|
||||||
|
import { useConnection } from "@/lib/connection";
|
||||||
|
|
||||||
type ConnStatus = "idle" | "connecting" | "connected" | "disconnected";
|
type GamePhase = "idle" | "connected" | "ready" | "playing" | "game-over";
|
||||||
type GamePhase =
|
|
||||||
| "idle" // not connected or connected but no game
|
|
||||||
| "connected" // connected, awaiting ready
|
|
||||||
| "ready" // sent READY, waiting for match
|
|
||||||
| "playing" // in a match
|
|
||||||
| "game-over"; // match finished
|
|
||||||
|
|
||||||
type GameResult = "win" | "loss" | "draw" | "terminated";
|
type GameResult = "win" | "loss" | "draw" | "terminated";
|
||||||
|
|
||||||
const DEFAULT_URL = "wss://connect4.abunchofknowitalls.com";
|
|
||||||
|
|
||||||
export default function PlayPage() {
|
export default function PlayPage() {
|
||||||
const [wsUrl, setWsUrl] = useState(DEFAULT_URL);
|
const router = useRouter();
|
||||||
const [username, setUsername] = useState("");
|
const {
|
||||||
const [connStatus, setConnStatus] = useState<ConnStatus>("idle");
|
role,
|
||||||
const [gamePhase, setGamePhase] = useState<GamePhase>("idle");
|
username,
|
||||||
|
status,
|
||||||
|
send,
|
||||||
|
subscribe,
|
||||||
|
disconnect,
|
||||||
|
reconnectAttempts,
|
||||||
|
shouldRedirectToConnect,
|
||||||
|
clearRedirectFlag,
|
||||||
|
} = useConnection();
|
||||||
|
|
||||||
const [myColor, setMyColor] = useState<1 | 2 | null>(null); // 1=red, 2=yellow
|
const [gamePhase, setGamePhase] = useState<GamePhase>("idle");
|
||||||
const [isMyTurn, setIsMyTurn] = useState(false);
|
const [myColor, setMyColor] = useState<1 | 2 | null>(null);
|
||||||
const [board, setBoard] = useState<BoardState>(createEmptyBoard());
|
const [isMyTurn, setIsMyTurn] = useState(false);
|
||||||
const [lastMove, setLastMove] = useState<{ column: number; row: number } | null>(null);
|
const [board, setBoard] = useState<BoardState>(createEmptyBoard());
|
||||||
const [gameResult, setGameResult] = useState<GameResult | null>(null);
|
const [lastMove, setLastMove] = useState<{
|
||||||
const [moveCount, setMoveCount] = useState(0);
|
column: number;
|
||||||
const [statusMessages, setStatusMessages] = useState<string[]>([]);
|
row: number;
|
||||||
const [tournamentMode, setTournamentMode] = useState(false);
|
} | null>(null);
|
||||||
const [waitingForNextRound, setWaitingForNextRound] = useState(false);
|
const [gameResult, setGameResult] = useState<GameResult | null>(null);
|
||||||
|
const [moveCount, setMoveCount] = useState(0);
|
||||||
|
const [statusMessages, setStatusMessages] = useState<string[]>([]);
|
||||||
|
const [tournamentMode, setTournamentMode] = useState(false);
|
||||||
|
|
||||||
const wsRef = useRef<WebSocket | null>(null);
|
const myColorRef = useRef<1 | 2 | null>(null);
|
||||||
const myColorRef = useRef<1 | 2 | null>(null);
|
const isMyTurnRef = useRef(false);
|
||||||
const isMyTurnRef = useRef(false);
|
|
||||||
|
|
||||||
const addStatus = (msg: string) =>
|
const addStatus = useCallback(
|
||||||
setStatusMessages((prev) => [
|
(msg: string) =>
|
||||||
`[${new Date().toLocaleTimeString()}] ${msg}`,
|
setStatusMessages((prev) => [
|
||||||
...prev.slice(0, 29),
|
`[${new Date().toLocaleTimeString()}] ${msg}`,
|
||||||
]);
|
...prev.slice(0, 29),
|
||||||
|
]),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
const send = useCallback((msg: string) => {
|
const resetGame = useCallback(() => {
|
||||||
if (wsRef.current?.readyState === WebSocket.OPEN) wsRef.current.send(msg);
|
setBoard(createEmptyBoard());
|
||||||
}, []);
|
setLastMove(null);
|
||||||
|
setMoveCount(0);
|
||||||
|
setMyColor(null);
|
||||||
|
myColorRef.current = null;
|
||||||
|
setIsMyTurn(false);
|
||||||
|
isMyTurnRef.current = false;
|
||||||
|
setGameResult(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const resetGame = useCallback(() => {
|
useEffect(() => {
|
||||||
setBoard(createEmptyBoard());
|
if (status === "disconnected" && shouldRedirectToConnect) {
|
||||||
setLastMove(null);
|
clearRedirectFlag();
|
||||||
setMoveCount(0);
|
router.replace("/");
|
||||||
setMyColor(null);
|
}
|
||||||
myColorRef.current = null;
|
|
||||||
setIsMyTurn(false);
|
|
||||||
isMyTurnRef.current = false;
|
|
||||||
setGameResult(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleColumnClick = useCallback(
|
if (role !== "player" && status !== "idle") {
|
||||||
(col: number) => {
|
router.replace("/spectate");
|
||||||
if (!isMyTurnRef.current || gamePhase !== "playing") return;
|
return;
|
||||||
// Optimistically place the piece; server validates and replies
|
}
|
||||||
const color = myColorRef.current!;
|
|
||||||
setBoard((prev) => {
|
|
||||||
const { board: next, row } = placeToken(prev, color, col);
|
|
||||||
if (row === -1) return prev; // column full, ignore
|
|
||||||
setLastMove({ column: col, row });
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
setIsMyTurn(false);
|
|
||||||
isMyTurnRef.current = false;
|
|
||||||
setMoveCount((n) => n + 1);
|
|
||||||
send(cmd.play(col));
|
|
||||||
addStatus(`You played column ${col}`);
|
|
||||||
},
|
|
||||||
[gamePhase, send]
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleMessage = useCallback(
|
if (status === "connected" && gamePhase === "idle") {
|
||||||
(raw: string) => {
|
setGamePhase("connected");
|
||||||
const msg: ParsedMessage = parseMessage(raw);
|
}
|
||||||
switch (msg.type) {
|
|
||||||
case "CONNECT_ACK":
|
|
||||||
setConnStatus("connected");
|
|
||||||
setGamePhase("connected");
|
|
||||||
addStatus(`✅ Connected as "${username}"`);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "ERROR":
|
|
||||||
addStatus(`⚠ ${msg.message}`);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "READY_ACK":
|
}, [
|
||||||
setGamePhase("ready");
|
role,
|
||||||
addStatus("⏳ Waiting for an opponent…");
|
status,
|
||||||
break;
|
router,
|
||||||
|
gamePhase,
|
||||||
|
shouldRedirectToConnect,
|
||||||
|
clearRedirectFlag,
|
||||||
|
]);
|
||||||
|
|
||||||
case "GAME_START": {
|
useEffect(() => {
|
||||||
resetGame();
|
const unsubscribe = subscribe((msg: ParsedMessage) => {
|
||||||
const color: 1 | 2 = msg.goesFirst ? 1 : 2;
|
switch (msg.type) {
|
||||||
setMyColor(color);
|
case "CONNECT_ACK":
|
||||||
myColorRef.current = color;
|
case "RECONNECT_ACK":
|
||||||
setGamePhase("playing");
|
setGamePhase((prev) => (prev === "idle" ? "connected" : prev));
|
||||||
setWaitingForNextRound(false);
|
addStatus("Connected to server");
|
||||||
const firstTurn = msg.goesFirst;
|
break;
|
||||||
setIsMyTurn(firstTurn);
|
|
||||||
isMyTurnRef.current = firstTurn;
|
|
||||||
addStatus(
|
|
||||||
msg.goesFirst
|
|
||||||
? "🔴 You are Red — you go FIRST!"
|
|
||||||
: "🟡 You are Yellow — wait for opponent's first move"
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "OPPONENT_MOVE": {
|
case "ERROR":
|
||||||
const opponentColor: 1 | 2 = myColorRef.current === 1 ? 2 : 1;
|
addStatus(`⚠ ${msg.message}`);
|
||||||
setBoard((prev) => {
|
break;
|
||||||
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} — your turn!`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "GAME_WINS":
|
case "READY_ACK":
|
||||||
setGameResult("win");
|
setGamePhase("ready");
|
||||||
setGamePhase("game-over");
|
addStatus("⏳ Waiting for an opponent...");
|
||||||
setIsMyTurn(false);
|
break;
|
||||||
isMyTurnRef.current = false;
|
|
||||||
addStatus("🏆 You won!");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "GAME_LOSS":
|
case "GAME_START": {
|
||||||
setGameResult("loss");
|
resetGame();
|
||||||
setGamePhase("game-over");
|
const color: 1 | 2 = msg.goesFirst ? 1 : 2;
|
||||||
setIsMyTurn(false);
|
setMyColor(color);
|
||||||
isMyTurnRef.current = false;
|
myColorRef.current = color;
|
||||||
addStatus("💔 You lost");
|
setGamePhase("playing");
|
||||||
break;
|
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_DRAW":
|
case "OPPONENT_MOVE": {
|
||||||
setGameResult("draw");
|
const opponentColor: 1 | 2 = myColorRef.current === 1 ? 2 : 1;
|
||||||
setGamePhase("game-over");
|
setBoard((prev) => {
|
||||||
setIsMyTurn(false);
|
const { board: next, row } = placeToken(
|
||||||
isMyTurnRef.current = false;
|
prev,
|
||||||
addStatus("🤝 Draw!");
|
opponentColor,
|
||||||
break;
|
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_TERMINATED":
|
case "GAME_WINS":
|
||||||
setGameResult("terminated");
|
setGameResult("win");
|
||||||
setGamePhase("game-over");
|
setGamePhase("game-over");
|
||||||
setIsMyTurn(false);
|
setIsMyTurn(false);
|
||||||
isMyTurnRef.current = false;
|
isMyTurnRef.current = false;
|
||||||
addStatus("⛔ Match terminated");
|
addStatus("🏆 You won!");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "TOURNAMENT_START":
|
case "GAME_LOSS":
|
||||||
setTournamentMode(true);
|
setGameResult("loss");
|
||||||
addStatus(`🏆 Tournament started: ${msg.tournamentType}`);
|
setGamePhase("game-over");
|
||||||
break;
|
setIsMyTurn(false);
|
||||||
|
isMyTurnRef.current = false;
|
||||||
|
addStatus("💔 You lost");
|
||||||
|
break;
|
||||||
|
|
||||||
case "TOURNAMENT_END":
|
case "GAME_DRAW":
|
||||||
addStatus("Round over — sending Ready for next round…");
|
setGameResult("draw");
|
||||||
setWaitingForNextRound(false);
|
setGamePhase("game-over");
|
||||||
setGamePhase("connected");
|
setIsMyTurn(false);
|
||||||
resetGame();
|
isMyTurnRef.current = false;
|
||||||
// Auto-ready for next round (mirror the gameloop.py behavior)
|
addStatus("🤝 Draw");
|
||||||
setTimeout(() => send(cmd.ready()), 500);
|
break;
|
||||||
setGamePhase("ready");
|
|
||||||
addStatus("⏳ Ready for next round…");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "TOURNAMENT_CANCEL":
|
case "GAME_TERMINATED":
|
||||||
setTournamentMode(false);
|
setGameResult("terminated");
|
||||||
setWaitingForNextRound(false);
|
setGamePhase("game-over");
|
||||||
setGamePhase("connected");
|
setIsMyTurn(false);
|
||||||
resetGame();
|
isMyTurnRef.current = false;
|
||||||
addStatus("Tournament cancelled");
|
addStatus("⛔ Match terminated");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
case "TOURNAMENT_START":
|
||||||
break;
|
setTournamentMode(true);
|
||||||
}
|
addStatus(`🏆 Tournament started: ${msg.tournamentType}`);
|
||||||
},
|
break;
|
||||||
[username, resetGame, send]
|
|
||||||
);
|
|
||||||
|
|
||||||
const connect = useCallback(() => {
|
case "TOURNAMENT_END":
|
||||||
if (!username.trim()) {
|
setGamePhase("connected");
|
||||||
addStatus("⚠ Please enter a username first");
|
resetGame();
|
||||||
return;
|
send(cmd.ready());
|
||||||
}
|
setGamePhase("ready");
|
||||||
if (wsRef.current) wsRef.current.close();
|
addStatus("⏳ Ready for next round...");
|
||||||
|
break;
|
||||||
|
|
||||||
setConnStatus("connecting");
|
case "TOURNAMENT_CANCEL":
|
||||||
setGamePhase("idle");
|
setTournamentMode(false);
|
||||||
resetGame();
|
setGamePhase("connected");
|
||||||
setStatusMessages([]);
|
resetGame();
|
||||||
setTournamentMode(false);
|
addStatus("Tournament cancelled");
|
||||||
setWaitingForNextRound(false);
|
break;
|
||||||
|
|
||||||
const ws = new WebSocket(wsUrl);
|
default:
|
||||||
wsRef.current = ws;
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
ws.onopen = () => ws.send(cmd.connect(username.trim()));
|
return unsubscribe;
|
||||||
ws.onmessage = (e) => handleMessage(e.data as string);
|
}, [addStatus, resetGame, send, subscribe]);
|
||||||
ws.onclose = () => {
|
|
||||||
setConnStatus("disconnected");
|
|
||||||
setGamePhase("idle");
|
|
||||||
addStatus("Disconnected from server");
|
|
||||||
};
|
|
||||||
ws.onerror = () => addStatus("WebSocket error");
|
|
||||||
}, [username, wsUrl, handleMessage, resetGame]);
|
|
||||||
|
|
||||||
const disconnect = useCallback(() => {
|
const handleColumnClick = useCallback(
|
||||||
send(cmd.disconnect());
|
(col: number) => {
|
||||||
setTimeout(() => wsRef.current?.close(), 200);
|
if (!isMyTurnRef.current || gamePhase !== "playing") return;
|
||||||
}, [send]);
|
const color = myColorRef.current;
|
||||||
|
if (!color) return;
|
||||||
|
|
||||||
const sendReady = useCallback(() => {
|
setBoard((prev) => {
|
||||||
send(cmd.ready());
|
const { board: next, row } = placeToken(prev, color, col);
|
||||||
setGamePhase("ready");
|
if (row === -1) return prev;
|
||||||
addStatus("⏳ Waiting for an opponent…");
|
setLastMove({ column: col, row });
|
||||||
}, [send]);
|
return next;
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => () => wsRef.current?.close(), []);
|
setIsMyTurn(false);
|
||||||
|
isMyTurnRef.current = false;
|
||||||
|
setMoveCount((n) => n + 1);
|
||||||
|
send(cmd.play(col));
|
||||||
|
addStatus(`You played column ${col}`);
|
||||||
|
},
|
||||||
|
[addStatus, gamePhase, send],
|
||||||
|
);
|
||||||
|
|
||||||
// Derived display values
|
const sendReady = useCallback(() => {
|
||||||
const myColorLabel = myColor === 1 ? "🔴 Red" : myColor === 2 ? "🟡 Yellow" : null;
|
send(cmd.ready());
|
||||||
const opponentColor: 1 | 2 | null = myColor === 1 ? 2 : myColor === 2 ? 1 : null;
|
setGamePhase("ready");
|
||||||
|
addStatus("⏳ Waiting for an opponent...");
|
||||||
|
}, [addStatus, send]);
|
||||||
|
|
||||||
return (
|
const myColorLabel =
|
||||||
<div className="flex flex-col gap-6">
|
myColor === 1 ? "🔴 Red" : myColor === 2 ? "🟡 Yellow" : null;
|
||||||
{/* Header */}
|
const opponentColor: 1 | 2 | null =
|
||||||
<div className="flex items-center justify-between">
|
myColor === 1 ? 2 : myColor === 2 ? 1 : null;
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-white">🎮 Play Connect4</h1>
|
|
||||||
<p className="text-gray-400 text-sm mt-1">
|
|
||||||
Connect as a player and compete in matches
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<PhaseIndicator phase={gamePhase} isMyTurn={isMyTurn} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
return (
|
||||||
{/* Left: controls + status */}
|
<div className="flex flex-col gap-6">
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex items-center justify-between">
|
||||||
{/* Connection card */}
|
<div>
|
||||||
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-col gap-3">
|
<h1 className="text-2xl font-bold text-white">🎮 Play Connect4</h1>
|
||||||
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
|
<p className="text-gray-400 text-sm mt-1">
|
||||||
Connection
|
Connected as <span className="text-green-300">{username}</span>
|
||||||
</h2>
|
</p>
|
||||||
|
</div>
|
||||||
|
<PhaseIndicator phase={gamePhase} isMyTurn={isMyTurn} />
|
||||||
|
</div>
|
||||||
|
|
||||||
<div>
|
{status === "reconnecting" && (
|
||||||
<label className="text-xs text-gray-400 mb-1 block">Server URL</label>
|
<div className="rounded-lg border border-yellow-700 bg-yellow-950/30 px-4 py-3 text-sm text-yellow-200">
|
||||||
<input
|
Connection lost during a live match. Reconnect attempt #
|
||||||
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"
|
{reconnectAttempts}...
|
||||||
value={wsUrl}
|
</div>
|
||||||
onChange={(e) => setWsUrl(e.target.value)}
|
)}
|
||||||
placeholder="wss://..."
|
|
||||||
disabled={connStatus === "connected" || connStatus === "connecting"}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||||
<label className="text-xs text-gray-400 mb-1 block">Username</label>
|
<div className="flex flex-col gap-4">
|
||||||
<input
|
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-col gap-3">
|
||||||
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"
|
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
|
||||||
value={username}
|
Session
|
||||||
onChange={(e) => setUsername(e.target.value)}
|
</h2>
|
||||||
placeholder="Enter your username"
|
|
||||||
disabled={connStatus === "connected" || connStatus === "connecting"}
|
|
||||||
onKeyDown={(e) => e.key === "Enter" && connStatus === "idle" && connect()}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{connStatus !== "connected" ? (
|
<div className="text-xs text-gray-400">
|
||||||
<button
|
Status: <span className="text-gray-200">{status}</span>
|
||||||
onClick={connect}
|
</div>
|
||||||
disabled={connStatus === "connecting" || !username.trim()}
|
<div className="text-xs text-gray-400">
|
||||||
className="w-full py-2 bg-blue-600 hover:bg-blue-500 disabled:bg-gray-700 disabled:text-gray-500 text-white text-sm font-medium rounded-lg transition-colors"
|
User: <span className="text-gray-200">{username}</span>
|
||||||
>
|
</div>
|
||||||
{connStatus === "connecting" ? "Connecting…" : "Connect"}
|
|
||||||
</button>
|
|
||||||
) : (
|
|
||||||
<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>
|
|
||||||
|
|
||||||
{/* Game controls */}
|
<button
|
||||||
{connStatus === "connected" && (
|
onClick={disconnect}
|
||||||
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-col gap-3">
|
className="w-full py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm font-medium rounded-lg transition-colors"
|
||||||
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
|
>
|
||||||
Match
|
Disconnect
|
||||||
</h2>
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{tournamentMode && (
|
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-col gap-3">
|
||||||
<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">
|
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
|
||||||
<span>🏆</span>
|
Match
|
||||||
<span>Tournament mode active</span>
|
</h2>
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{gamePhase === "connected" && !tournamentMode && (
|
{tournamentMode && (
|
||||||
<button
|
<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">
|
||||||
onClick={sendReady}
|
<span>🏆</span>
|
||||||
className="w-full py-2.5 bg-green-700 hover:bg-green-600 text-white text-sm font-semibold rounded-lg transition-colors"
|
<span>Tournament mode active</span>
|
||||||
>
|
</div>
|
||||||
✋ Ready to Play
|
)}
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{gamePhase === "ready" && (
|
{gamePhase === "connected" && (
|
||||||
<div className="text-center py-3 text-yellow-300 text-sm animate-pulse">
|
<button
|
||||||
⏳ Waiting for opponent…
|
onClick={sendReady}
|
||||||
</div>
|
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 === "playing" || gamePhase === "game-over") && myColor && (
|
{gamePhase === "ready" && (
|
||||||
<div className="flex flex-col gap-2">
|
<div className="text-center py-3 text-yellow-300 text-sm animate-pulse">
|
||||||
<div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-gray-800">
|
⏳ Waiting for opponent...
|
||||||
<div
|
</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>
|
|
||||||
{myColor === 1 && (
|
|
||||||
<span className="text-xs text-gray-500">(1st)</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{gamePhase === "playing" && (
|
{(gamePhase === "playing" || gamePhase === "game-over") &&
|
||||||
<div
|
myColor && (
|
||||||
className={`flex items-center justify-center gap-2 px-3 py-2 rounded-lg font-semibold text-sm ${
|
<div className="flex flex-col gap-2">
|
||||||
isMyTurn
|
<div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-gray-800">
|
||||||
? "bg-green-900/50 border border-green-600 text-green-300 animate-pulse"
|
<div
|
||||||
: "bg-gray-800 text-gray-400"
|
className={`w-4 h-4 rounded-full ${myColor === 1 ? "bg-red-500" : "bg-yellow-400"}`}
|
||||||
}`}
|
/>
|
||||||
>
|
<span className="text-white font-medium text-sm">
|
||||||
{isMyTurn ? "⬆ Your turn — click a column!" : "⏳ Waiting for opponent…"}
|
You are {myColorLabel}
|
||||||
</div>
|
</span>
|
||||||
)}
|
</div>
|
||||||
|
|
||||||
<div className="text-xs text-gray-500 text-center">
|
{gamePhase === "playing" && (
|
||||||
{moveCount} move{moveCount !== 1 ? "s" : ""} played
|
<div
|
||||||
</div>
|
className={`flex items-center justify-center gap-2 px-3 py-2 rounded-lg font-semibold text-sm ${
|
||||||
</div>
|
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 === "game-over" && gameResult && (
|
<div className="text-xs text-gray-500 text-center">
|
||||||
<div className="flex flex-col gap-2">
|
{moveCount} move{moveCount !== 1 ? "s" : ""} played
|
||||||
<div
|
</div>
|
||||||
className={`text-center py-3 rounded-lg font-bold text-base border ${
|
</div>
|
||||||
gameResult === "win"
|
)}
|
||||||
? "bg-green-900/50 border-green-600 text-green-300"
|
|
||||||
: gameResult === "loss"
|
|
||||||
? "bg-red-900/50 border-red-600 text-red-300"
|
|
||||||
: gameResult === "draw"
|
|
||||||
? "bg-blue-900/50 border-blue-600 text-blue-300"
|
|
||||||
: "bg-gray-800 border-gray-600 text-gray-300"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{gameResult === "win"
|
|
||||||
? "🏆 You Won!"
|
|
||||||
: gameResult === "loss"
|
|
||||||
? "💔 You Lost"
|
|
||||||
: gameResult === "draw"
|
|
||||||
? "🤝 Draw"
|
|
||||||
: "⛔ Terminated"}
|
|
||||||
</div>
|
|
||||||
{!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>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Status log */}
|
{gamePhase === "game-over" && gameResult && !tournamentMode && (
|
||||||
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
|
<button
|
||||||
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-2">
|
onClick={sendReady}
|
||||||
Status Log
|
className="w-full py-2 bg-green-700 hover:bg-green-600 text-white text-sm font-semibold rounded-lg transition-colors"
|
||||||
</h2>
|
>
|
||||||
<div className="flex flex-col gap-0.5 max-h-52 overflow-y-auto">
|
Play Again
|
||||||
{statusMessages.length === 0 ? (
|
</button>
|
||||||
<p className="text-gray-600 text-xs">Connect to start</p>
|
)}
|
||||||
) : (
|
</div>
|
||||||
statusMessages.map((m, i) => (
|
|
||||||
<p key={i} className="text-xs text-gray-400 font-mono">
|
|
||||||
{m}
|
|
||||||
</p>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* How to play */}
|
<div className="bg-gray-900 border border-gray-700 rounded-xl p-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-2">
|
||||||
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-2">
|
Status Log
|
||||||
How to Play
|
</h2>
|
||||||
</h2>
|
<div className="flex flex-col gap-0.5 max-h-52 overflow-y-auto">
|
||||||
<ol className="flex flex-col gap-1.5 text-xs text-gray-400">
|
{statusMessages.length === 0 ? (
|
||||||
<li className="flex gap-2">
|
<p className="text-gray-600 text-xs">No events yet</p>
|
||||||
<span className="text-blue-400 font-bold shrink-0">1.</span>
|
) : (
|
||||||
Enter the server URL and your username, then click <strong className="text-gray-300">Connect</strong>
|
statusMessages.map((m, i) => (
|
||||||
</li>
|
<p key={i} className="text-xs text-gray-400 font-mono">
|
||||||
<li className="flex gap-2">
|
{m}
|
||||||
<span className="text-blue-400 font-bold shrink-0">2.</span>
|
</p>
|
||||||
Click <strong className="text-gray-300">Ready to Play</strong> to queue for a match
|
))
|
||||||
</li>
|
)}
|
||||||
<li className="flex gap-2">
|
</div>
|
||||||
<span className="text-blue-400 font-bold shrink-0">3.</span>
|
</div>
|
||||||
When the game starts, click a column number to drop your piece
|
</div>
|
||||||
</li>
|
|
||||||
<li className="flex gap-2">
|
|
||||||
<span className="text-blue-400 font-bold shrink-0">4.</span>
|
|
||||||
Connect 4 in a row (horizontal, vertical, or diagonal) to win!
|
|
||||||
</li>
|
|
||||||
</ol>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right: board */}
|
<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">
|
||||||
<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" ? (
|
||||||
{connStatus !== "connected" || gamePhase === "idle" ? (
|
<div className="text-gray-500 text-center py-10">
|
||||||
<div className="flex flex-col items-center gap-4 text-center py-8">
|
Connect from the connection page to start.
|
||||||
<span className="text-6xl">🎮</span>
|
</div>
|
||||||
<p className="text-gray-400 text-lg font-medium">Ready to play?</p>
|
) : gamePhase === "connected" ? (
|
||||||
<p className="text-gray-600 text-sm max-w-xs">
|
<div className="flex flex-col items-center gap-4 text-center py-8">
|
||||||
Enter your username and connect to the server to start a match
|
<div className="text-5xl">✋</div>
|
||||||
</p>
|
<p className="text-blue-300 text-lg font-medium">
|
||||||
</div>
|
Ready up to start
|
||||||
) : gamePhase === "ready" ? (
|
</p>
|
||||||
<div className="flex flex-col items-center gap-4 text-center py-8">
|
<p className="text-gray-500 text-sm max-w-sm">
|
||||||
<div className="text-5xl animate-bounce">⏳</div>
|
Click the{" "}
|
||||||
<p className="text-yellow-300 text-lg font-medium">
|
<span className="text-green-300 font-semibold">
|
||||||
Waiting for an opponent…
|
Ready to Play
|
||||||
</p>
|
</span>{" "}
|
||||||
<p className="text-gray-500 text-sm">
|
button in the Match panel to enter the queue.
|
||||||
The game will start automatically when a match is found
|
</p>
|
||||||
</p>
|
</div>
|
||||||
</div>
|
) : gamePhase === "ready" ? (
|
||||||
) : (
|
<div className="flex flex-col items-center gap-4 text-center py-8">
|
||||||
<>
|
<div className="text-5xl animate-bounce">⏳</div>
|
||||||
{gameResult && (
|
<p className="text-yellow-300 text-lg font-medium">
|
||||||
<div
|
Waiting for an opponent...
|
||||||
className={`w-full max-w-md rounded-xl p-4 text-center font-bold text-xl border ${
|
</p>
|
||||||
gameResult === "win"
|
</div>
|
||||||
? "bg-green-900/50 border-green-500 text-green-300"
|
) : (
|
||||||
: gameResult === "loss"
|
<>
|
||||||
? "bg-red-900/50 border-red-500 text-red-300"
|
{gameResult && (
|
||||||
: gameResult === "draw"
|
<div
|
||||||
? "bg-blue-900/50 border-blue-500 text-blue-300"
|
className={`w-full max-w-md rounded-xl p-4 text-center font-bold text-xl border ${
|
||||||
: "bg-gray-800 border-gray-600 text-gray-300"
|
gameResult === "win"
|
||||||
}`}
|
? "bg-green-900/50 border-green-500 text-green-300"
|
||||||
>
|
: gameResult === "loss"
|
||||||
{gameResult === "win"
|
? "bg-red-900/50 border-red-500 text-red-300"
|
||||||
? "🏆 You Won!"
|
: gameResult === "draw"
|
||||||
: gameResult === "loss"
|
? "bg-blue-900/50 border-blue-500 text-blue-300"
|
||||||
? "💔 You Lost"
|
: "bg-gray-800 border-gray-600 text-gray-300"
|
||||||
: gameResult === "draw"
|
}`}
|
||||||
? "🤝 Draw!"
|
>
|
||||||
: "⛔ Match Terminated"}
|
{gameResult === "win"
|
||||||
</div>
|
? "🏆 You Won!"
|
||||||
)}
|
: gameResult === "loss"
|
||||||
|
? "💔 You Lost"
|
||||||
|
: gameResult === "draw"
|
||||||
|
? "🤝 Draw"
|
||||||
|
: "⛔ Match Terminated"}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<Board
|
<Board
|
||||||
board={board}
|
board={board}
|
||||||
lastMove={lastMove}
|
lastMove={lastMove}
|
||||||
player1={username}
|
player1={username}
|
||||||
player2="Opponent"
|
player2="Opponent"
|
||||||
currentTurnColor={
|
currentTurnColor={
|
||||||
gamePhase === "playing" && myColor
|
gamePhase === "playing" && myColor
|
||||||
? isMyTurn
|
? isMyTurn
|
||||||
? myColor
|
? myColor
|
||||||
: opponentColor
|
: opponentColor
|
||||||
: null
|
: null
|
||||||
}
|
}
|
||||||
onColumnClick={
|
onColumnClick={
|
||||||
gamePhase === "playing" && isMyTurn ? handleColumnClick : undefined
|
gamePhase === "playing" && isMyTurn
|
||||||
}
|
? handleColumnClick
|
||||||
disabled={gamePhase !== "playing" || !isMyTurn}
|
: undefined
|
||||||
/>
|
}
|
||||||
|
disabled={gamePhase !== "playing" || !isMyTurn}
|
||||||
{gamePhase === "playing" && (
|
/>
|
||||||
<p className="text-sm text-gray-400">
|
</>
|
||||||
{isMyTurn ? (
|
)}
|
||||||
<span className="text-green-400 font-semibold animate-pulse">
|
</div>
|
||||||
⬆ Click a column to drop your piece
|
</div>
|
||||||
</span>
|
</div>
|
||||||
) : (
|
);
|
||||||
<span className="text-gray-500">Waiting for opponent…</span>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function PhaseIndicator({
|
function PhaseIndicator({
|
||||||
phase,
|
phase,
|
||||||
isMyTurn,
|
isMyTurn,
|
||||||
}: {
|
}: {
|
||||||
phase: GamePhase;
|
phase: GamePhase;
|
||||||
isMyTurn: boolean;
|
isMyTurn: boolean;
|
||||||
}) {
|
}) {
|
||||||
if (phase === "playing" && isMyTurn) {
|
if (phase === "playing" && isMyTurn) {
|
||||||
return (
|
return (
|
||||||
<span className="px-3 py-1.5 rounded-full text-sm font-medium bg-green-900/60 text-green-300 animate-pulse">
|
<span className="px-3 py-1.5 rounded-full text-sm font-medium bg-green-900/60 text-green-300 animate-pulse">
|
||||||
Your Turn!
|
Your Turn!
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const config: Record<GamePhase, { label: string; cls: string }> = {
|
|
||||||
idle: { label: "Not connected", cls: "bg-gray-700 text-gray-400" },
|
const config: Record<GamePhase, { label: string; cls: string }> = {
|
||||||
connected: { label: "Connected", cls: "bg-blue-900/60 text-blue-300" },
|
idle: { label: "Not ready", cls: "bg-gray-700 text-gray-400" },
|
||||||
ready: { label: "Waiting…", cls: "bg-yellow-900/60 text-yellow-300 animate-pulse" },
|
connected: { label: "Connected", cls: "bg-blue-900/60 text-blue-300" },
|
||||||
playing: { label: "In Game", cls: "bg-green-900/60 text-green-400" },
|
ready: {
|
||||||
"game-over": { label: "Game Over", cls: "bg-gray-700 text-gray-400" },
|
label: "Waiting...",
|
||||||
};
|
cls: "bg-yellow-900/60 text-yellow-300 animate-pulse",
|
||||||
const { label, cls } = config[phase];
|
},
|
||||||
return (
|
playing: { label: "In Game", cls: "bg-green-900/60 text-green-400" },
|
||||||
<span className={`px-3 py-1.5 rounded-full text-sm font-medium ${cls}`}>{label}</span>
|
"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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,366 +1,485 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
import Board from "@/components/Board";
|
import Board from "@/components/Board";
|
||||||
import {
|
import {
|
||||||
BoardState,
|
BoardState,
|
||||||
GameEntry,
|
GameEntry,
|
||||||
ParsedMessage,
|
ParsedMessage,
|
||||||
cmd,
|
PlayerEntry,
|
||||||
createEmptyBoard,
|
ScoreEntry,
|
||||||
parseMessage,
|
cmd,
|
||||||
placeToken,
|
createEmptyBoard,
|
||||||
replayMoves,
|
placeToken,
|
||||||
|
replayMoves,
|
||||||
} from "@/lib/protocol";
|
} from "@/lib/protocol";
|
||||||
|
import { useConnection } from "@/lib/connection";
|
||||||
|
|
||||||
type ConnStatus = "idle" | "connecting" | "connected" | "disconnected";
|
interface LiveGame {
|
||||||
|
id: number;
|
||||||
interface WatchState {
|
player1: string;
|
||||||
matchId: number;
|
player2: string;
|
||||||
player1: string; // Red
|
board: BoardState;
|
||||||
player2: string; // Yellow
|
lastMove: { column: number; row: number } | null;
|
||||||
|
currentTurnColor: 1 | 2;
|
||||||
|
result:
|
||||||
|
| { kind: "win"; winner: string }
|
||||||
|
| { kind: "draw" }
|
||||||
|
| { kind: "terminated" }
|
||||||
|
| null;
|
||||||
}
|
}
|
||||||
|
|
||||||
type GameResult =
|
|
||||||
| { kind: "win"; winner: string }
|
|
||||||
| { kind: "draw" }
|
|
||||||
| { kind: "terminated" };
|
|
||||||
|
|
||||||
const DEFAULT_URL = "wss://connect4.abunchofknowitalls.com";
|
|
||||||
|
|
||||||
export default function SpectatePage() {
|
export default function SpectatePage() {
|
||||||
const [wsUrl, setWsUrl] = useState(DEFAULT_URL);
|
const router = useRouter();
|
||||||
const [status, setStatus] = useState<ConnStatus>("idle");
|
const {
|
||||||
const [log, setLog] = useState<string[]>([]);
|
role,
|
||||||
|
status,
|
||||||
|
send,
|
||||||
|
subscribe,
|
||||||
|
disconnect,
|
||||||
|
shouldRedirectToConnect,
|
||||||
|
clearRedirectFlag,
|
||||||
|
} = useConnection();
|
||||||
|
|
||||||
const [gameList, setGameList] = useState<GameEntry[]>([]);
|
const [tournamentActive, setTournamentActive] = useState(false);
|
||||||
const [watching, setWatching] = useState<WatchState | null>(null);
|
const [tournamentType, setTournamentType] = useState<string | null>(null);
|
||||||
const [board, setBoard] = useState<BoardState>(createEmptyBoard());
|
const [scores, setScores] = useState<ScoreEntry[]>([]);
|
||||||
const [lastMove, setLastMove] = useState<{ column: number; row: number } | null>(null);
|
const [players, setPlayers] = useState<PlayerEntry[]>([]);
|
||||||
const [currentTurnColor, setCurrentTurnColor] = useState<1 | 2>(1);
|
const [gameList, setGameList] = useState<GameEntry[]>([]);
|
||||||
const [moveCount, setMoveCount] = useState(0);
|
const [liveGames, setLiveGames] = useState<Map<number, LiveGame>>(new Map());
|
||||||
const [gameResult, setGameResult] = useState<GameResult | null>(null);
|
const [selectedGame, setSelectedGame] = useState<number | null>(null);
|
||||||
|
const [log, setLog] = useState<string[]>([]);
|
||||||
|
|
||||||
const wsRef = useRef<WebSocket | null>(null);
|
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
const liveGamesRef = useRef<Map<number, LiveGame>>(new Map());
|
||||||
const watchingRef = useRef<WatchState | null>(null);
|
|
||||||
|
|
||||||
const addLog = (msg: string) =>
|
const addLog = useCallback(
|
||||||
setLog((prev) => [`[${new Date().toLocaleTimeString()}] ${msg}`, ...prev.slice(0, 49)]);
|
(msg: string) =>
|
||||||
|
setLog((prev) => [
|
||||||
|
`[${new Date().toLocaleTimeString()}] ${msg}`,
|
||||||
|
...prev.slice(0, 79),
|
||||||
|
]),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
const send = useCallback((msg: string) => {
|
const updateGame = useCallback((id: number, patch: Partial<LiveGame>) => {
|
||||||
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
setLiveGames((prev) => {
|
||||||
wsRef.current.send(msg);
|
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 handleMessage = useCallback(
|
useEffect(() => {
|
||||||
(raw: string) => {
|
if (status === "disconnected" && shouldRedirectToConnect) {
|
||||||
const msg: ParsedMessage = parseMessage(raw);
|
clearRedirectFlag();
|
||||||
switch (msg.type) {
|
router.replace("/");
|
||||||
case "GAME_LIST":
|
} else if (status === "idle") {
|
||||||
setGameList(msg.games);
|
router.replace("/");
|
||||||
break;
|
|
||||||
|
|
||||||
case "GAME_WATCH_ACK": {
|
|
||||||
const { board: replayed, lastMove: lm } = replayMoves(msg.moves, msg.player1);
|
|
||||||
const watchState: WatchState = {
|
|
||||||
matchId: msg.matchId,
|
|
||||||
player1: msg.player1,
|
|
||||||
player2: msg.player2,
|
|
||||||
};
|
|
||||||
setWatching(watchState);
|
|
||||||
watchingRef.current = watchState;
|
|
||||||
setBoard(replayed);
|
|
||||||
setLastMove(lm);
|
|
||||||
setMoveCount(msg.moves.length);
|
|
||||||
setCurrentTurnColor(msg.moves.length % 2 === 0 ? 1 : 2);
|
|
||||||
setGameResult(null);
|
|
||||||
addLog(`Watching match ${msg.matchId}: ${msg.player1} (🔴) vs ${msg.player2} (🟡)`);
|
|
||||||
if (msg.moves.length > 0)
|
|
||||||
addLog(`Replayed ${msg.moves.length} existing move(s)`);
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case "GAME_MOVE": {
|
if (role !== "observer" && status !== "idle") {
|
||||||
const w = watchingRef.current;
|
router.replace("/play");
|
||||||
if (!w) break;
|
return;
|
||||||
const color: 1 | 2 = msg.username === w.player1 ? 1 : 2;
|
}
|
||||||
setBoard((prev) => {
|
}, [role, status, shouldRedirectToConnect, clearRedirectFlag, router]);
|
||||||
const { board: next, row } = placeToken(prev, color, msg.column);
|
|
||||||
setLastMove({ column: msg.column, row });
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
setMoveCount((n) => n + 1);
|
|
||||||
setCurrentTurnColor((c) => (c === 1 ? 2 : 1));
|
|
||||||
addLog(`${msg.username} played column ${msg.column}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "GAME_WIN":
|
useEffect(() => {
|
||||||
setGameResult({ kind: "win", winner: msg.winner });
|
const unsubscribe = subscribe((msg: ParsedMessage) => {
|
||||||
setCurrentTurnColor(1); // reset
|
switch (msg.type) {
|
||||||
addLog(`🏆 ${msg.winner} wins!`);
|
case "TOURNAMENT_START":
|
||||||
break;
|
setTournamentActive(true);
|
||||||
|
setTournamentType(msg.tournamentType);
|
||||||
|
setScores([]);
|
||||||
|
addLog(`🏆 Tournament started: ${msg.tournamentType}`);
|
||||||
|
send(cmd.gameList());
|
||||||
|
send(cmd.playerList());
|
||||||
|
break;
|
||||||
|
|
||||||
case "GAME_DRAW":
|
case "TOURNAMENT_CANCEL":
|
||||||
setGameResult({ kind: "draw" });
|
setTournamentActive(false);
|
||||||
addLog("🤝 Draw!");
|
setTournamentType(null);
|
||||||
break;
|
addLog("❌ Tournament cancelled");
|
||||||
|
break;
|
||||||
|
|
||||||
case "GAME_TERMINATED":
|
case "TOURNAMENT_SCORES":
|
||||||
setGameResult({ kind: "terminated" });
|
setScores(msg.scores);
|
||||||
addLog("⛔ Match terminated");
|
break;
|
||||||
break;
|
|
||||||
|
|
||||||
case "ERROR":
|
case "TOURNAMENT_END":
|
||||||
addLog(`Error: ${msg.message}`);
|
addLog("Round ended");
|
||||||
break;
|
send(cmd.gameList());
|
||||||
|
send(cmd.playerList());
|
||||||
|
break;
|
||||||
|
|
||||||
default:
|
case "GAME_LIST":
|
||||||
break;
|
setGameList(msg.games);
|
||||||
}
|
for (const g of msg.games) {
|
||||||
},
|
if (!liveGamesRef.current.has(g.id)) {
|
||||||
[]
|
send(cmd.gameWatch(g.id));
|
||||||
);
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
const connect = useCallback(() => {
|
case "GAME_WATCH_ACK": {
|
||||||
if (wsRef.current) wsRef.current.close();
|
const { board, lastMove } = replayMoves(msg.moves, msg.player1);
|
||||||
setStatus("connecting");
|
const moveCount = msg.moves.length;
|
||||||
setLog([]);
|
updateGame(msg.matchId, {
|
||||||
setGameList([]);
|
player1: msg.player1,
|
||||||
setWatching(null);
|
player2: msg.player2,
|
||||||
watchingRef.current = null;
|
board,
|
||||||
setBoard(createEmptyBoard());
|
lastMove,
|
||||||
setLastMove(null);
|
currentTurnColor: (moveCount % 2 === 0 ? 1 : 2) as 1 | 2,
|
||||||
setGameResult(null);
|
result: null,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
const ws = new WebSocket(wsUrl);
|
case "GAME_MOVE": {
|
||||||
wsRef.current = ws;
|
const gamesSnapshot = liveGamesRef.current;
|
||||||
|
for (const [id, game] of gamesSnapshot) {
|
||||||
|
if (
|
||||||
|
game.player1 === msg.username ||
|
||||||
|
game.player2 === msg.username
|
||||||
|
) {
|
||||||
|
const color: 1 | 2 = msg.username === game.player1 ? 1 : 2;
|
||||||
|
const { board: next, row } = placeToken(
|
||||||
|
game.board,
|
||||||
|
color,
|
||||||
|
msg.column,
|
||||||
|
);
|
||||||
|
updateGame(id, {
|
||||||
|
board: next,
|
||||||
|
lastMove: { column: msg.column, row },
|
||||||
|
currentTurnColor: (color === 1 ? 2 : 1) as 1 | 2,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
ws.onopen = () => {
|
case "GAME_WIN": {
|
||||||
setStatus("connected");
|
const gamesSnapshot = liveGamesRef.current;
|
||||||
addLog("Connected as observer");
|
for (const [id, game] of gamesSnapshot) {
|
||||||
ws.send(cmd.gameList());
|
if (game.player1 === msg.winner || game.player2 === msg.winner) {
|
||||||
};
|
updateGame(id, { result: { kind: "win", winner: msg.winner } });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setTimeout(() => {
|
||||||
|
send(cmd.gameList());
|
||||||
|
send(cmd.playerList());
|
||||||
|
}, 750);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
ws.onmessage = (e) => handleMessage(e.data as string);
|
case "GAME_DRAW":
|
||||||
|
if (selectedGame !== null) {
|
||||||
|
updateGame(selectedGame, { result: { kind: "draw" } });
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
ws.onclose = () => {
|
case "GAME_TERMINATED":
|
||||||
setStatus("disconnected");
|
if (selectedGame !== null) {
|
||||||
addLog("Disconnected");
|
updateGame(selectedGame, { result: { kind: "terminated" } });
|
||||||
if (pollRef.current) clearInterval(pollRef.current);
|
}
|
||||||
};
|
send(cmd.gameList());
|
||||||
|
break;
|
||||||
|
|
||||||
ws.onerror = () => addLog("WebSocket error");
|
case "PLAYER_LIST":
|
||||||
|
setPlayers(msg.players);
|
||||||
|
break;
|
||||||
|
|
||||||
// Poll game list every 4s
|
case "GET_DATA":
|
||||||
pollRef.current = setInterval(() => {
|
if (
|
||||||
if (ws.readyState === WebSocket.OPEN) ws.send(cmd.gameList());
|
msg.key === "TOURNAMENT_STATUS" &&
|
||||||
}, 4000);
|
msg.value &&
|
||||||
}, [wsUrl, handleMessage]);
|
msg.value !== "false"
|
||||||
|
) {
|
||||||
|
setTournamentActive(true);
|
||||||
|
setTournamentType(msg.value);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
const disconnect = useCallback(() => {
|
case "ERROR":
|
||||||
if (pollRef.current) clearInterval(pollRef.current);
|
addLog(`Error: ${msg.message}`);
|
||||||
wsRef.current?.close();
|
break;
|
||||||
}, []);
|
|
||||||
|
|
||||||
const watchGame = useCallback(
|
default:
|
||||||
(id: number) => {
|
break;
|
||||||
setBoard(createEmptyBoard());
|
}
|
||||||
setLastMove(null);
|
});
|
||||||
setGameResult(null);
|
|
||||||
setMoveCount(0);
|
|
||||||
setCurrentTurnColor(1);
|
|
||||||
send(cmd.gameWatch(id));
|
|
||||||
},
|
|
||||||
[send]
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => () => {
|
return unsubscribe;
|
||||||
if (pollRef.current) clearInterval(pollRef.current);
|
}, [addLog, selectedGame, send, subscribe, updateGame]);
|
||||||
wsRef.current?.close();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
useEffect(() => {
|
||||||
<div className="flex flex-col gap-6">
|
if (status !== "connected" || role !== "observer") {
|
||||||
<div className="flex items-center justify-between">
|
if (pollRef.current) {
|
||||||
<div>
|
clearInterval(pollRef.current);
|
||||||
<h1 className="text-2xl font-bold text-white">👁 Spectate Matches</h1>
|
pollRef.current = null;
|
||||||
<p className="text-gray-400 text-sm mt-1">
|
}
|
||||||
Watch live Connect4 games in real time
|
return;
|
||||||
</p>
|
}
|
||||||
</div>
|
|
||||||
<StatusBadge status={status} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Connection bar */}
|
send(cmd.getData("TOURNAMENT_STATUS"));
|
||||||
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-wrap gap-3 items-end">
|
send(cmd.gameList());
|
||||||
<div className="flex-1 min-w-48">
|
send(cmd.playerList());
|
||||||
<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://..."
|
|
||||||
disabled={status === "connected" || status === "connecting"}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{status !== "connected" ? (
|
|
||||||
<button
|
|
||||||
onClick={connect}
|
|
||||||
disabled={status === "connecting"}
|
|
||||||
className="px-5 py-2 bg-blue-600 hover:bg-blue-500 disabled:bg-gray-700 disabled:text-gray-500 text-white text-sm font-medium rounded-lg transition-colors"
|
|
||||||
>
|
|
||||||
{status === "connecting" ? "Connecting…" : "Connect"}
|
|
||||||
</button>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
onClick={disconnect}
|
|
||||||
className="px-5 py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm font-medium rounded-lg transition-colors"
|
|
||||||
>
|
|
||||||
Disconnect
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
pollRef.current = setInterval(() => {
|
||||||
{/* Left: game list + log */}
|
send(cmd.gameList());
|
||||||
<div className="flex flex-col gap-4">
|
send(cmd.playerList());
|
||||||
{/* Game list */}
|
}, 5000);
|
||||||
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
|
|
||||||
<div className="flex items-center justify-between mb-3">
|
|
||||||
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider">
|
|
||||||
Live Matches
|
|
||||||
</h2>
|
|
||||||
<span className="text-xs text-gray-500">
|
|
||||||
{gameList.length} game{gameList.length !== 1 ? "s" : ""}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
{status !== "connected" ? (
|
|
||||||
<p className="text-gray-600 text-sm text-center py-4">
|
|
||||||
Connect to see matches
|
|
||||||
</p>
|
|
||||||
) : gameList.length === 0 ? (
|
|
||||||
<p className="text-gray-500 text-sm text-center py-4">
|
|
||||||
No active matches
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
{gameList.map((g) => (
|
|
||||||
<button
|
|
||||||
key={g.id}
|
|
||||||
onClick={() => watchGame(g.id)}
|
|
||||||
className={`w-full text-left px-3 py-2.5 rounded-lg border transition-colors text-sm ${
|
|
||||||
watching?.matchId === g.id
|
|
||||||
? "border-blue-500 bg-blue-950/50 text-blue-300"
|
|
||||||
: "border-gray-700 bg-gray-800 hover:border-gray-600 hover:bg-gray-750 text-gray-300"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<div className="font-mono text-xs text-gray-500 mb-0.5">
|
|
||||||
#{g.id}
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-red-400">{g.player1}</span>
|
|
||||||
<span className="text-gray-600 text-xs">vs</span>
|
|
||||||
<span className="text-yellow-400">{g.player2}</span>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Event log */}
|
return () => {
|
||||||
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
|
if (pollRef.current) clearInterval(pollRef.current);
|
||||||
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider mb-3">
|
};
|
||||||
Event Log
|
}, [role, send, status]);
|
||||||
</h2>
|
|
||||||
<div className="flex flex-col gap-1 max-h-48 overflow-y-auto">
|
|
||||||
{log.length === 0 ? (
|
|
||||||
<p className="text-gray-600 text-xs">No events yet</p>
|
|
||||||
) : (
|
|
||||||
log.map((entry, i) => (
|
|
||||||
<p key={i} className="text-xs text-gray-400 font-mono">
|
|
||||||
{entry}
|
|
||||||
</p>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right: board */}
|
const selectedGameData =
|
||||||
<div className="lg:col-span-2 bg-gray-900 border border-gray-700 rounded-xl p-6 flex flex-col items-center gap-4">
|
selectedGame !== null ? liveGames.get(selectedGame) : null;
|
||||||
{!watching ? (
|
|
||||||
<div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
|
|
||||||
<span className="text-5xl">👁</span>
|
|
||||||
<p className="text-gray-400">
|
|
||||||
{status === "connected"
|
|
||||||
? "Select a match from the list to start watching"
|
|
||||||
: "Connect to the server to see live matches"}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
{/* Game result banner */}
|
|
||||||
{gameResult && (
|
|
||||||
<div
|
|
||||||
className={`w-full rounded-lg p-3 text-center font-semibold text-lg ${
|
|
||||||
gameResult.kind === "win"
|
|
||||||
? "bg-green-900/50 border border-green-600 text-green-300"
|
|
||||||
: gameResult.kind === "draw"
|
|
||||||
? "bg-blue-900/50 border border-blue-600 text-blue-300"
|
|
||||||
: "bg-red-900/50 border border-red-600 text-red-300"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{gameResult.kind === "win"
|
|
||||||
? `🏆 ${gameResult.winner} wins!`
|
|
||||||
: gameResult.kind === "draw"
|
|
||||||
? "🤝 Draw!"
|
|
||||||
: "⛔ Match Terminated"}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Board
|
return (
|
||||||
board={board}
|
<div className="flex flex-col gap-6">
|
||||||
lastMove={lastMove}
|
<div className="flex items-center justify-between">
|
||||||
player1={watching.player1}
|
<div>
|
||||||
player2={watching.player2}
|
<h1 className="text-2xl font-bold text-white">
|
||||||
currentTurnColor={gameResult ? null : currentTurnColor}
|
👁 Observer Dashboard
|
||||||
disabled
|
</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>
|
||||||
|
|
||||||
<div className="text-xs text-gray-500 font-mono">
|
{status !== "connected" && (
|
||||||
Match #{watching.matchId} · {moveCount} move
|
<div className="rounded-lg border border-yellow-700 bg-yellow-950/30 px-4 py-3 text-sm text-yellow-200">
|
||||||
{moveCount !== 1 ? "s" : ""}
|
Waiting for observer connection...
|
||||||
</div>
|
</div>
|
||||||
</>
|
)}
|
||||||
)}
|
|
||||||
</div>
|
{status === "connected" && (
|
||||||
</div>
|
<div
|
||||||
</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"
|
||||||
function StatusBadge({ status }: { status: ConnStatus }) {
|
}`}
|
||||||
const colors: Record<ConnStatus, string> = {
|
>
|
||||||
idle: "bg-gray-700 text-gray-400",
|
<div className="text-3xl">{tournamentActive ? "🏆" : "⏳"}</div>
|
||||||
connecting: "bg-yellow-900/60 text-yellow-300 animate-pulse",
|
<div>
|
||||||
connected: "bg-green-900/60 text-green-300",
|
<div className="font-semibold text-white">
|
||||||
disconnected: "bg-red-900/60 text-red-300",
|
{tournamentActive
|
||||||
};
|
? `Tournament Active - ${tournamentType ?? "Unknown Type"}`
|
||||||
const labels: Record<ConnStatus, string> = {
|
: "No Active Tournament"}
|
||||||
idle: "Not connected",
|
</div>
|
||||||
connecting: "Connecting…",
|
<div className="text-sm text-gray-400">
|
||||||
connected: "Connected",
|
{gameList.length} match{gameList.length !== 1 ? "es" : ""} running
|
||||||
disconnected: "Disconnected",
|
· {players.filter((p) => p.inMatch).length}/{players.length}{" "}
|
||||||
};
|
players in game
|
||||||
return (
|
</div>
|
||||||
<span className={`px-3 py-1.5 rounded-full text-sm font-medium ${colors[status]}`}>
|
</div>
|
||||||
{labels[status]}
|
</div>
|
||||||
</span>
|
)}
|
||||||
);
|
|
||||||
|
<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-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="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="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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,546 +1,5 @@
|
|||||||
"use client";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
export default function TournamentRedirectPage() {
|
||||||
import Board from "@/components/Board";
|
redirect("/spectate");
|
||||||
import {
|
|
||||||
BoardState,
|
|
||||||
GameEntry,
|
|
||||||
ParsedMessage,
|
|
||||||
PlayerEntry,
|
|
||||||
ScoreEntry,
|
|
||||||
cmd,
|
|
||||||
createEmptyBoard,
|
|
||||||
parseMessage,
|
|
||||||
placeToken,
|
|
||||||
replayMoves,
|
|
||||||
} from "@/lib/protocol";
|
|
||||||
|
|
||||||
type ConnStatus = "idle" | "connecting" | "connected" | "disconnected";
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DEFAULT_URL = "wss://connect4.abunchofknowitalls.com";
|
|
||||||
|
|
||||||
export default function TournamentPage() {
|
|
||||||
const [wsUrl, setWsUrl] = useState(DEFAULT_URL);
|
|
||||||
const [status, setStatus] = useState<ConnStatus>("idle");
|
|
||||||
|
|
||||||
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 wsRef = useRef<WebSocket | null>(null);
|
|
||||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
|
||||||
// keep a ref to liveGames for use inside the message handler closure
|
|
||||||
const liveGamesRef = useRef<Map<number, LiveGame>>(new Map());
|
|
||||||
|
|
||||||
const addLog = (msg: string) =>
|
|
||||||
setLog((prev) => [`[${new Date().toLocaleTimeString()}] ${msg}`, ...prev.slice(0, 79)]);
|
|
||||||
|
|
||||||
const send = useCallback((msg: string) => {
|
|
||||||
if (wsRef.current?.readyState === WebSocket.OPEN) wsRef.current.send(msg);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
/** Merge a partial update into a live game, creating it if new. */
|
|
||||||
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 handleMessage = useCallback(
|
|
||||||
(raw: string) => {
|
|
||||||
const msg: ParsedMessage = parseMessage(raw);
|
|
||||||
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_CANCEL":
|
|
||||||
setTournamentActive(false);
|
|
||||||
setTournamentType(null);
|
|
||||||
addLog("❌ Tournament cancelled");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "TOURNAMENT_SCORES":
|
|
||||||
setScores(msg.scores);
|
|
||||||
addLog(
|
|
||||||
`📊 Scores updated: ${msg.scores
|
|
||||||
.map((s) => `${s.player} ${s.score}`)
|
|
||||||
.join(", ")}`
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "TOURNAMENT_END":
|
|
||||||
addLog("Round ended");
|
|
||||||
send(cmd.gameList());
|
|
||||||
send(cmd.playerList());
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "GAME_LIST": {
|
|
||||||
setGameList(msg.games);
|
|
||||||
// Watch any new games we don't have yet
|
|
||||||
for (const g of msg.games) {
|
|
||||||
if (!liveGamesRef.current.has(g.id)) {
|
|
||||||
send(cmd.gameWatch(g.id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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,
|
|
||||||
});
|
|
||||||
addLog(`Watching match ${msg.matchId}: ${msg.player1} vs ${msg.player2}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "GAME_MOVE": {
|
|
||||||
// find the game this player is in
|
|
||||||
const gamesSnapshot = liveGamesRef.current;
|
|
||||||
for (const [id, game] of gamesSnapshot) {
|
|
||||||
if (game.player1 === msg.username || game.player2 === msg.username) {
|
|
||||||
const color: 1 | 2 = msg.username === game.player1 ? 1 : 2;
|
|
||||||
const { board: next, row } = placeToken(game.board, color, msg.column);
|
|
||||||
updateGame(id, {
|
|
||||||
board: next,
|
|
||||||
lastMove: { column: msg.column, row },
|
|
||||||
currentTurnColor: (color === 1 ? 2 : 1) as 1 | 2,
|
|
||||||
});
|
|
||||||
addLog(`[#${id}] ${msg.username} played column ${msg.column}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "GAME_WIN": {
|
|
||||||
const gamesSnapshot = liveGamesRef.current;
|
|
||||||
for (const [id, game] of gamesSnapshot) {
|
|
||||||
if (game.player1 === msg.winner || game.player2 === msg.winner) {
|
|
||||||
updateGame(id, { result: { kind: "win", winner: msg.winner } });
|
|
||||||
addLog(`🏆 [#${id}] ${msg.winner} wins!`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// refresh lists after match ends
|
|
||||||
setTimeout(() => {
|
|
||||||
send(cmd.gameList());
|
|
||||||
send(cmd.playerList());
|
|
||||||
}, 1000);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "GAME_DRAW": {
|
|
||||||
// mark the selected game as draw (we can't easily identify which)
|
|
||||||
if (selectedGame !== null) {
|
|
||||||
updateGame(selectedGame, { result: { kind: "draw" } });
|
|
||||||
}
|
|
||||||
addLog("🤝 Draw");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "GAME_TERMINATED": {
|
|
||||||
if (selectedGame !== null) {
|
|
||||||
updateGame(selectedGame, { result: { kind: "terminated" } });
|
|
||||||
}
|
|
||||||
addLog("⛔ Match terminated");
|
|
||||||
send(cmd.gameList());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "PLAYER_LIST":
|
|
||||||
setPlayers(msg.players);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "GET_DATA":
|
|
||||||
if (msg.key === "TOURNAMENT_STATUS") {
|
|
||||||
if (msg.value && msg.value !== "false") {
|
|
||||||
setTournamentActive(true);
|
|
||||||
setTournamentType(msg.value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "ERROR":
|
|
||||||
addLog(`Error: ${msg.message}`);
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[send, updateGame, selectedGame]
|
|
||||||
);
|
|
||||||
|
|
||||||
const connect = useCallback(() => {
|
|
||||||
if (wsRef.current) wsRef.current.close();
|
|
||||||
setStatus("connecting");
|
|
||||||
setLog([]);
|
|
||||||
setLiveGames(new Map());
|
|
||||||
liveGamesRef.current = new Map();
|
|
||||||
setSelectedGame(null);
|
|
||||||
setScores([]);
|
|
||||||
setPlayers([]);
|
|
||||||
setGameList([]);
|
|
||||||
setTournamentActive(false);
|
|
||||||
setTournamentType(null);
|
|
||||||
|
|
||||||
const ws = new WebSocket(wsUrl);
|
|
||||||
wsRef.current = ws;
|
|
||||||
|
|
||||||
ws.onopen = () => {
|
|
||||||
setStatus("connected");
|
|
||||||
addLog("Connected as observer");
|
|
||||||
ws.send(cmd.getData("TOURNAMENT_STATUS"));
|
|
||||||
ws.send(cmd.gameList());
|
|
||||||
ws.send(cmd.playerList());
|
|
||||||
};
|
|
||||||
|
|
||||||
ws.onmessage = (e) => handleMessage(e.data as string);
|
|
||||||
ws.onclose = () => {
|
|
||||||
setStatus("disconnected");
|
|
||||||
addLog("Disconnected");
|
|
||||||
if (pollRef.current) clearInterval(pollRef.current);
|
|
||||||
};
|
|
||||||
ws.onerror = () => addLog("WebSocket error");
|
|
||||||
|
|
||||||
pollRef.current = setInterval(() => {
|
|
||||||
if (ws.readyState === WebSocket.OPEN) {
|
|
||||||
ws.send(cmd.gameList());
|
|
||||||
ws.send(cmd.playerList());
|
|
||||||
}
|
|
||||||
}, 5000);
|
|
||||||
}, [wsUrl, handleMessage]);
|
|
||||||
|
|
||||||
const disconnect = useCallback(() => {
|
|
||||||
if (pollRef.current) clearInterval(pollRef.current);
|
|
||||||
wsRef.current?.close();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => () => {
|
|
||||||
if (pollRef.current) clearInterval(pollRef.current);
|
|
||||||
wsRef.current?.close();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const selectedGameData = selectedGame !== null ? liveGames.get(selectedGame) : null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col gap-6">
|
|
||||||
{/* Header */}
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-white">🏆 Tournament View</h1>
|
|
||||||
<p className="text-gray-400 text-sm mt-1">
|
|
||||||
Live standings, active matches, and player status
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<StatusBadge status={status} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Connection bar */}
|
|
||||||
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex flex-wrap gap-3 items-end">
|
|
||||||
<div className="flex-1 min-w-48">
|
|
||||||
<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)}
|
|
||||||
disabled={status === "connected" || status === "connecting"}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{status !== "connected" ? (
|
|
||||||
<button
|
|
||||||
onClick={connect}
|
|
||||||
disabled={status === "connecting"}
|
|
||||||
className="px-5 py-2 bg-blue-600 hover:bg-blue-500 disabled:bg-gray-700 disabled:text-gray-500 text-white text-sm font-medium rounded-lg transition-colors"
|
|
||||||
>
|
|
||||||
{status === "connecting" ? "Connecting…" : "Connect"}
|
|
||||||
</button>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
onClick={disconnect}
|
|
||||||
className="px-5 py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm font-medium rounded-lg transition-colors"
|
|
||||||
>
|
|
||||||
Disconnect
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Tournament banner */}
|
|
||||||
{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">
|
|
||||||
{tournamentActive
|
|
||||||
? `${gameList.length} match${gameList.length !== 1 ? "es" : ""} running · ${players.filter((p) => p.inMatch).length}/${players.length} players in game`
|
|
||||||
: "Waiting for admin to start a tournament"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
|
||||||
{/* Left column */}
|
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
{/* Leaderboard */}
|
|
||||||
<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">
|
|
||||||
{status === "connected" ? "No scores yet" : "Connect to see scores"}
|
|
||||||
</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 ${
|
|
||||||
i === 0
|
|
||||||
? "text-yellow-400"
|
|
||||||
: i === 1
|
|
||||||
? "text-gray-300"
|
|
||||||
: i === 2
|
|
||||||
? "text-amber-700"
|
|
||||||
: "text-gray-600"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{i === 0 ? "🥇" : i === 1 ? "🥈" : i === 2 ? "🥉" : `${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>
|
|
||||||
|
|
||||||
{/* Player list */}
|
|
||||||
<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">
|
|
||||||
{status === "connected" ? "No players connected" : "Connect to see players"}
|
|
||||||
</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>
|
|
||||||
|
|
||||||
{/* Event log */}
|
|
||||||
<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>
|
|
||||||
|
|
||||||
{/* Right: active matches + board */}
|
|
||||||
<div className="lg:col-span-2 flex flex-col gap-4">
|
|
||||||
{/* Active matches */}
|
|
||||||
<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">
|
|
||||||
{status === "connected" ? "No active matches" : "Connect to see 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>
|
|
||||||
|
|
||||||
{/* Selected game board */}
|
|
||||||
<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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function StatusBadge({ status }: { status: ConnStatus }) {
|
|
||||||
const colors: Record<ConnStatus, string> = {
|
|
||||||
idle: "bg-gray-700 text-gray-400",
|
|
||||||
connecting: "bg-yellow-900/60 text-yellow-300 animate-pulse",
|
|
||||||
connected: "bg-green-900/60 text-green-300",
|
|
||||||
disconnected: "bg-red-900/60 text-red-300",
|
|
||||||
};
|
|
||||||
const labels: Record<ConnStatus, string> = {
|
|
||||||
idle: "Not connected",
|
|
||||||
connecting: "Connecting…",
|
|
||||||
connected: "Connected",
|
|
||||||
disconnected: "Disconnected",
|
|
||||||
};
|
|
||||||
return (
|
|
||||||
<span className={`px-3 py-1.5 rounded-full text-sm font-medium ${colors[status]}`}>
|
|
||||||
{labels[status]}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,39 +1,121 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { FormEvent, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
|
import { useConnection } from "@/lib/connection";
|
||||||
const links = [
|
import { cmd, DEFAULT_WS_URL } from "@/lib/protocol";
|
||||||
{ href: "/spectate", label: "👁 Spectate", desc: "Watch live matches" },
|
|
||||||
{ href: "/tournament", label: "🏆 Tournament", desc: "Tournament standings" },
|
|
||||||
{ href: "/play", label: "🎮 Play", desc: "Join as a player" },
|
|
||||||
];
|
|
||||||
|
|
||||||
export default function Nav() {
|
export default function Nav() {
|
||||||
const path = usePathname();
|
const pathname = usePathname();
|
||||||
return (
|
const router = useRouter();
|
||||||
<nav className="bg-gray-900 border-b border-gray-800 px-4 py-3">
|
const { status, role, username, send, becomePlayer } = useConnection();
|
||||||
<div className="max-w-7xl mx-auto flex items-center gap-6">
|
const [showPlayerModal, setShowPlayerModal] = useState(false);
|
||||||
<Link href="/" className="text-lg font-bold text-white flex items-center gap-2">
|
const [nextUsername, setNextUsername] = useState(username);
|
||||||
<span className="text-2xl">🔴</span>
|
|
||||||
<span>Connect4</span>
|
const statusLabel =
|
||||||
<span className="text-gray-400 text-sm font-normal">Moderator</span>
|
status === "connected"
|
||||||
</Link>
|
? `Connected ${role === "player" ? `as ${username}` : "as observer"}`
|
||||||
<div className="flex gap-1 ml-4">
|
: status === "reconnecting"
|
||||||
{links.map(({ href, label }) => (
|
? "Reconnecting..."
|
||||||
<Link
|
: status === "connecting"
|
||||||
key={href}
|
? "Connecting..."
|
||||||
href={href}
|
: "Not connected";
|
||||||
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
|
const isConnectionPage = pathname === "/";
|
||||||
path === href
|
|
||||||
? "bg-blue-600 text-white"
|
const disableRoleSwitch =
|
||||||
: "text-gray-300 hover:bg-gray-800 hover:text-white"
|
status === "connecting" || status === "reconnecting";
|
||||||
}`}
|
|
||||||
>
|
const handleBecomeObserver = () => {
|
||||||
{label}
|
send(cmd.disconnect());
|
||||||
</Link>
|
router.push("/spectate");
|
||||||
))}
|
};
|
||||||
</div>
|
|
||||||
</div>
|
const handleBecomePlayer = (event: FormEvent<HTMLFormElement>) => {
|
||||||
</nav>
|
event.preventDefault();
|
||||||
);
|
const trimmed = nextUsername.trim();
|
||||||
|
if (!trimmed) return;
|
||||||
|
|
||||||
|
becomePlayer(trimmed);
|
||||||
|
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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
{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"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
384
connect4-ui/lib/connection.tsx
Normal file
384
connect4-ui/lib/connection.tsx
Normal file
@@ -0,0 +1,384 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from "react";
|
||||||
|
import {
|
||||||
|
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";
|
||||||
|
|
||||||
|
type MessageListener = (message: ParsedMessage, raw: string) => void;
|
||||||
|
|
||||||
|
interface ConnectOptions {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ConnectionContext = createContext<ConnectionContextValue | null>(null);
|
||||||
|
|
||||||
|
interface SessionState {
|
||||||
|
role: ConnectionRole;
|
||||||
|
wsUrl: string;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ConnectionProvider({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
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 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 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 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;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
clearReconnectState();
|
||||||
|
setStatus("disconnected");
|
||||||
|
setShouldRedirectToConnect(true);
|
||||||
|
}, [clearReconnectState]);
|
||||||
|
|
||||||
|
const attachSocket = useCallback(
|
||||||
|
(socket: WebSocket, reconnecting: boolean) => {
|
||||||
|
socket.onopen = () => {
|
||||||
|
const session = sessionRef.current;
|
||||||
|
if (!session) return;
|
||||||
|
|
||||||
|
if (session.role === "observer") {
|
||||||
|
setStatus("connected");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reconnecting) {
|
||||||
|
socket.send(cmd.reconnect(session.username));
|
||||||
|
} else {
|
||||||
|
socket.send(cmd.connect(session.username));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.onmessage = (event) => {
|
||||||
|
const raw = event.data as string;
|
||||||
|
const parsed = parseMessage(raw);
|
||||||
|
|
||||||
|
if (parsed.type === "CONNECT_ACK") {
|
||||||
|
setRole("player");
|
||||||
|
}
|
||||||
|
|
||||||
|
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 === "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 === "ERROR" &&
|
||||||
|
reconnecting &&
|
||||||
|
parsed.message.startsWith("ERROR:INVALID:RECONNECT")
|
||||||
|
) {
|
||||||
|
safeCloseSocket();
|
||||||
|
}
|
||||||
|
|
||||||
|
emitMessage(parsed, raw);
|
||||||
|
};
|
||||||
|
|
||||||
|
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],
|
||||||
|
);
|
||||||
|
|
||||||
|
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],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
setReconnectAttempts((prev) => prev + 1);
|
||||||
|
openSocket(true);
|
||||||
|
|
||||||
|
clearReconnectTimer();
|
||||||
|
reconnectTimerRef.current = setTimeout(
|
||||||
|
runReconnectAttempt,
|
||||||
|
RECONNECT_INTERVAL_MS,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
runReconnectAttempt();
|
||||||
|
|
||||||
|
return () => clearReconnectTimer();
|
||||||
|
}, [clearReconnectTimer, openSocket, status]);
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
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 disconnect = useCallback(() => {
|
||||||
|
clearReconnectState();
|
||||||
|
manualCloseRef.current = true;
|
||||||
|
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 subscribe = useCallback((listener: MessageListener) => {
|
||||||
|
listenersRef.current.add(listener);
|
||||||
|
return () => {
|
||||||
|
listenersRef.current.delete(listener);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const clearRedirectFlag = useCallback(() => {
|
||||||
|
setShouldRedirectToConnect(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
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,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -1,218 +1,239 @@
|
|||||||
// ─── Types ───────────────────────────────────────────────────────────────────
|
// ─── Types ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface GameEntry {
|
export interface GameEntry {
|
||||||
id: number;
|
id: number;
|
||||||
player1: string;
|
player1: string;
|
||||||
player2: string;
|
player2: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PlayerEntry {
|
export interface PlayerEntry {
|
||||||
username: string;
|
username: string;
|
||||||
ready: boolean;
|
ready: boolean;
|
||||||
inMatch: boolean;
|
inMatch: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ScoreEntry {
|
export interface ScoreEntry {
|
||||||
player: string;
|
player: string;
|
||||||
score: number;
|
score: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MoveEntry {
|
export interface MoveEntry {
|
||||||
username: string;
|
username: string;
|
||||||
column: number;
|
column: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_WS_URL = 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 ────────────────────────────────────────────────────
|
// ─── Parsed message union ────────────────────────────────────────────────────
|
||||||
|
|
||||||
export type ParsedMessage =
|
export type ParsedMessage =
|
||||||
| { type: "CONNECT_ACK" }
|
| { type: "CONNECT_ACK" }
|
||||||
| { type: "RECONNECT_ACK" }
|
| { type: "RECONNECT_ACK" }
|
||||||
| { type: "DISCONNECT_ACK" }
|
| { type: "DISCONNECT_ACK" }
|
||||||
| { type: "READY_ACK" }
|
| { type: "READY_ACK" }
|
||||||
| { type: "GAME_START"; goesFirst: boolean }
|
| { type: "GAME_START"; goesFirst: boolean }
|
||||||
| { type: "GAME_WINS" }
|
| { type: "GAME_WINS" }
|
||||||
| { type: "GAME_LOSS" }
|
| { type: "GAME_LOSS" }
|
||||||
| { type: "GAME_DRAW" }
|
| { type: "GAME_DRAW" }
|
||||||
| { type: "GAME_TERMINATED" }
|
| { type: "GAME_TERMINATED" }
|
||||||
| { type: "OPPONENT_MOVE"; column: number }
|
| { type: "OPPONENT_MOVE"; column: number }
|
||||||
| { type: "GAME_LIST"; games: GameEntry[] }
|
| { type: "GAME_LIST"; games: GameEntry[] }
|
||||||
| {
|
| {
|
||||||
type: "GAME_WATCH_ACK";
|
type: "GAME_WATCH_ACK";
|
||||||
matchId: number;
|
matchId: number;
|
||||||
player1: string;
|
player1: string;
|
||||||
player2: string;
|
player2: string;
|
||||||
moves: MoveEntry[];
|
moves: MoveEntry[];
|
||||||
}
|
}
|
||||||
| { type: "GAME_MOVE"; username: string; column: number }
|
| { type: "GAME_MOVE"; username: string; column: number }
|
||||||
| { type: "GAME_WIN"; winner: string }
|
| { type: "GAME_WIN"; winner: string }
|
||||||
| { type: "PLAYER_LIST"; players: PlayerEntry[] }
|
| { type: "PLAYER_LIST"; players: PlayerEntry[] }
|
||||||
| { type: "TOURNAMENT_START"; tournamentType: string }
|
| { type: "TOURNAMENT_START"; tournamentType: string }
|
||||||
| { type: "TOURNAMENT_CANCEL" }
|
| { type: "TOURNAMENT_CANCEL" }
|
||||||
| { type: "TOURNAMENT_SCORES"; scores: ScoreEntry[] }
|
| { type: "TOURNAMENT_SCORES"; scores: ScoreEntry[] }
|
||||||
| { type: "TOURNAMENT_END" }
|
| { type: "TOURNAMENT_END" }
|
||||||
| { type: "ADMIN_AUTH_ACK" }
|
| { type: "ADMIN_AUTH_ACK" }
|
||||||
| { type: "GET_DATA"; key: string; value: string }
|
| { type: "GET_DATA"; key: string; value: string }
|
||||||
| { type: "SET_DATA_ACK"; key: string }
|
| { type: "SET_DATA_ACK"; key: string }
|
||||||
| { type: "ERROR"; message: string }
|
| { type: "ERROR"; message: string }
|
||||||
| { type: "UNKNOWN"; raw: string };
|
| { type: "UNKNOWN"; raw: string };
|
||||||
|
|
||||||
// ─── Parser ──────────────────────────────────────────────────────────────────
|
// ─── Parser ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function parseMessage(raw: string): ParsedMessage {
|
export function parseMessage(raw: string): ParsedMessage {
|
||||||
const parts = raw.split(":");
|
const parts = raw.split(":");
|
||||||
|
|
||||||
switch (parts[0]) {
|
switch (parts[0]) {
|
||||||
case "CONNECT":
|
case "CONNECT":
|
||||||
if (parts[1] === "ACK") return { type: "CONNECT_ACK" };
|
if (parts[1] === "ACK") return { type: "CONNECT_ACK" };
|
||||||
break;
|
break;
|
||||||
case "RECONNECT":
|
case "RECONNECT":
|
||||||
if (parts[1] === "ACK") return { type: "RECONNECT_ACK" };
|
if (parts[1] === "ACK") return { type: "RECONNECT_ACK" };
|
||||||
break;
|
break;
|
||||||
case "DISCONNECT":
|
case "DISCONNECT":
|
||||||
if (parts[1] === "ACK") return { type: "DISCONNECT_ACK" };
|
if (parts[1] === "ACK") return { type: "DISCONNECT_ACK" };
|
||||||
break;
|
break;
|
||||||
case "READY":
|
case "READY":
|
||||||
if (parts[1] === "ACK") return { type: "READY_ACK" };
|
if (parts[1] === "ACK") return { type: "READY_ACK" };
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "GAME": {
|
case "GAME": {
|
||||||
switch (parts[1]) {
|
switch (parts[1]) {
|
||||||
case "START":
|
case "START":
|
||||||
return { type: "GAME_START", goesFirst: parts[2] === "1" };
|
return { type: "GAME_START", goesFirst: parts[2] === "1" };
|
||||||
case "WINS":
|
case "WINS":
|
||||||
return { type: "GAME_WINS" };
|
return { type: "GAME_WINS" };
|
||||||
case "LOSS":
|
case "LOSS":
|
||||||
return { type: "GAME_LOSS" };
|
return { type: "GAME_LOSS" };
|
||||||
case "DRAW":
|
case "DRAW":
|
||||||
return { type: "GAME_DRAW" };
|
return { type: "GAME_DRAW" };
|
||||||
case "TERMINATED":
|
case "TERMINATED":
|
||||||
return { type: "GAME_TERMINATED" };
|
return { type: "GAME_TERMINATED" };
|
||||||
|
|
||||||
case "LIST": {
|
case "LIST": {
|
||||||
const data = parts[2] ?? "";
|
const data = parts[2] ?? "";
|
||||||
if (!data) return { type: "GAME_LIST", games: [] };
|
if (!data) return { type: "GAME_LIST", games: [] };
|
||||||
const games: GameEntry[] = data.split("|").map((g) => {
|
const games: GameEntry[] = data.split("|").map((g) => {
|
||||||
const [id, player1, player2] = g.split(",");
|
const [id, player1, player2] = g.split(",");
|
||||||
return { id: parseInt(id), player1, player2 };
|
return { id: parseInt(id), player1, player2 };
|
||||||
});
|
});
|
||||||
return { type: "GAME_LIST", games };
|
return { type: "GAME_LIST", games };
|
||||||
}
|
}
|
||||||
|
|
||||||
case "WATCH": {
|
case "WATCH": {
|
||||||
if (parts[2] === "ACK") {
|
if (parts[2] === "ACK") {
|
||||||
// GAME:WATCH:ACK:<id>,<p1>,<p2>|<username>,<col>|...
|
// GAME:WATCH:ACK:<id>,<p1>,<p2>|<username>,<col>|...
|
||||||
const data = parts.slice(3).join(":");
|
const data = parts.slice(3).join(":");
|
||||||
const segments = data.split("|");
|
const segments = data.split("|");
|
||||||
const [idStr, player1, player2] = segments[0].split(",");
|
const [idStr, player1, player2] = segments[0].split(",");
|
||||||
const moves: MoveEntry[] = segments.slice(1).filter(Boolean).map((m) => {
|
const moves: MoveEntry[] = segments
|
||||||
const lastComma = m.lastIndexOf(",");
|
.slice(1)
|
||||||
return {
|
.filter(Boolean)
|
||||||
username: m.substring(0, lastComma),
|
.map((m) => {
|
||||||
column: parseInt(m.substring(lastComma + 1)),
|
const lastComma = m.lastIndexOf(",");
|
||||||
};
|
return {
|
||||||
});
|
username: m.substring(0, lastComma),
|
||||||
return {
|
column: parseInt(m.substring(lastComma + 1)),
|
||||||
type: "GAME_WATCH_ACK",
|
};
|
||||||
matchId: parseInt(idStr),
|
});
|
||||||
player1,
|
return {
|
||||||
player2,
|
type: "GAME_WATCH_ACK",
|
||||||
moves,
|
matchId: parseInt(idStr),
|
||||||
};
|
player1,
|
||||||
}
|
player2,
|
||||||
break;
|
moves,
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
case "MOVE":
|
case "MOVE":
|
||||||
// GAME:MOVE:<username>:<column>
|
// GAME:MOVE:<username>:<column>
|
||||||
return { type: "GAME_MOVE", username: parts[2], column: parseInt(parts[3]) };
|
return {
|
||||||
|
type: "GAME_MOVE",
|
||||||
|
username: parts[2],
|
||||||
|
column: parseInt(parts[3]),
|
||||||
|
};
|
||||||
|
|
||||||
case "WIN":
|
case "WIN":
|
||||||
return { type: "GAME_WIN", winner: parts[2] };
|
return { type: "GAME_WIN", winner: parts[2] };
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case "OPPONENT":
|
case "OPPONENT":
|
||||||
return { type: "OPPONENT_MOVE", column: parseInt(parts[1]) };
|
return { type: "OPPONENT_MOVE", column: parseInt(parts[1]) };
|
||||||
|
|
||||||
case "PLAYER": {
|
case "PLAYER": {
|
||||||
if (parts[1] === "LIST") {
|
if (parts[1] === "LIST") {
|
||||||
const data = parts[2] ?? "";
|
const data = parts[2] ?? "";
|
||||||
if (!data) return { type: "PLAYER_LIST", players: [] };
|
if (!data) return { type: "PLAYER_LIST", players: [] };
|
||||||
const players: PlayerEntry[] = data.split("|").map((p) => {
|
const players: PlayerEntry[] = data.split("|").map((p) => {
|
||||||
const [username, ready, inMatch] = p.split(",");
|
const [username, ready, inMatch] = p.split(",");
|
||||||
return { username, ready: ready === "true", inMatch: inMatch === "true" };
|
return {
|
||||||
});
|
username,
|
||||||
return { type: "PLAYER_LIST", players };
|
ready: ready === "true",
|
||||||
}
|
inMatch: inMatch === "true",
|
||||||
break;
|
};
|
||||||
}
|
});
|
||||||
|
return { type: "PLAYER_LIST", players };
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
case "TOURNAMENT": {
|
case "TOURNAMENT": {
|
||||||
switch (parts[1]) {
|
switch (parts[1]) {
|
||||||
case "START":
|
case "START":
|
||||||
return { type: "TOURNAMENT_START", tournamentType: parts[2] };
|
return { type: "TOURNAMENT_START", tournamentType: parts[2] };
|
||||||
case "CANCEL":
|
case "CANCEL":
|
||||||
return { type: "TOURNAMENT_CANCEL" };
|
return { type: "TOURNAMENT_CANCEL" };
|
||||||
case "SCORES": {
|
case "SCORES": {
|
||||||
const data = parts[2] ?? "";
|
const data = parts[2] ?? "";
|
||||||
if (!data) return { type: "TOURNAMENT_SCORES", scores: [] };
|
if (!data) return { type: "TOURNAMENT_SCORES", scores: [] };
|
||||||
const scores: ScoreEntry[] = data.split("|").map((s) => {
|
const scores: ScoreEntry[] = data.split("|").map((s) => {
|
||||||
const lastComma = s.lastIndexOf(",");
|
const lastComma = s.lastIndexOf(",");
|
||||||
return {
|
return {
|
||||||
player: s.substring(0, lastComma),
|
player: s.substring(0, lastComma),
|
||||||
score: parseInt(s.substring(lastComma + 1)),
|
score: parseInt(s.substring(lastComma + 1)),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
return { type: "TOURNAMENT_SCORES", scores };
|
return { type: "TOURNAMENT_SCORES", scores };
|
||||||
}
|
}
|
||||||
case "END":
|
case "END":
|
||||||
return { type: "TOURNAMENT_END" };
|
return { type: "TOURNAMENT_END" };
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case "ADMIN":
|
case "ADMIN":
|
||||||
if (parts[1] === "AUTH" && parts[2] === "ACK") return { type: "ADMIN_AUTH_ACK" };
|
if (parts[1] === "AUTH" && parts[2] === "ACK")
|
||||||
break;
|
return { type: "ADMIN_AUTH_ACK" };
|
||||||
|
break;
|
||||||
|
|
||||||
case "GET":
|
case "GET":
|
||||||
return { type: "GET_DATA", key: parts[1], value: parts[2] ?? "" };
|
return { type: "GET_DATA", key: parts[1], value: parts[2] ?? "" };
|
||||||
|
|
||||||
case "SET":
|
case "SET":
|
||||||
if (parts[2] === "ACK") return { type: "SET_DATA_ACK", key: parts[1] };
|
if (parts[2] === "ACK") return { type: "SET_DATA_ACK", key: parts[1] };
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "ERROR":
|
case "ERROR":
|
||||||
return { type: "ERROR", message: raw };
|
return { type: "ERROR", message: raw };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { type: "UNKNOWN", raw };
|
return { type: "UNKNOWN", raw };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Command builders ────────────────────────────────────────────────────────
|
// ─── Command builders ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const cmd = {
|
export const cmd = {
|
||||||
connect: (username: string) => `CONNECT:${username}`,
|
connect: (username: string) => `CONNECT:${username}`,
|
||||||
reconnect: (username: string) => `RECONNECT:${username}`,
|
reconnect: (username: string) => `RECONNECT:${username}`,
|
||||||
disconnect: () => "DISCONNECT",
|
disconnect: () => "DISCONNECT",
|
||||||
ready: () => "READY",
|
ready: () => "READY",
|
||||||
play: (column: number) => `PLAY:${column}`,
|
play: (column: number) => `PLAY:${column}`,
|
||||||
playerList: () => "PLAYER:LIST",
|
playerList: () => "PLAYER:LIST",
|
||||||
gameList: () => "GAME:LIST",
|
gameList: () => "GAME:LIST",
|
||||||
gameWatch: (matchId: number) => `GAME:WATCH:${matchId}`,
|
gameWatch: (matchId: number) => `GAME:WATCH:${matchId}`,
|
||||||
gameTerminate: (matchId: number) => `GAME:TERMINATE:${matchId}`,
|
gameTerminate: (matchId: number) => `GAME:TERMINATE:${matchId}`,
|
||||||
gameAward: (matchId: number, winner: string) => `GAME:AWARD:${matchId}:${winner}`,
|
gameAward: (matchId: number, winner: string) =>
|
||||||
adminAuth: (password: string) => `ADMIN:AUTH:${password}`,
|
`GAME:AWARD:${matchId}:${winner}`,
|
||||||
adminKick: (username: string) => `ADMIN:KICK:${username}`,
|
adminAuth: (password: string) => `ADMIN:AUTH:${password}`,
|
||||||
tournamentStart: (type = "RoundRobin") => `TOURNAMENT:START:${type}`,
|
adminKick: (username: string) => `ADMIN:KICK:${username}`,
|
||||||
tournamentCancel: () => "TOURNAMENT:CANCEL",
|
tournamentStart: (type = "RoundRobin") => `TOURNAMENT:START:${type}`,
|
||||||
getData: (key: "TOURNAMENT_STATUS" | "MOVE_WAIT" | "DEMO_MODE" | "MAX_TIMEOUT") =>
|
tournamentCancel: () => "TOURNAMENT:CANCEL",
|
||||||
`GET:${key}`,
|
getData: (
|
||||||
setData: (key: string, value: string) => `SET:${key}:${value}`,
|
key: "TOURNAMENT_STATUS" | "MOVE_WAIT" | "DEMO_MODE" | "MAX_TIMEOUT",
|
||||||
reservationAdd: (p1: string, p2: string) => `RESERVATION:ADD:${p1},${p2}`,
|
) => `GET:${key}`,
|
||||||
reservationDelete: (p1: string, p2: string) => `RESERVATION:DELETE:${p1},${p2}`,
|
setData: (key: string, value: string) => `SET:${key}:${value}`,
|
||||||
reservationGet: () => "RESERVATION:GET",
|
reservationAdd: (p1: string, p2: string) => `RESERVATION:ADD:${p1},${p2}`,
|
||||||
|
reservationDelete: (p1: string, p2: string) =>
|
||||||
|
`RESERVATION:DELETE:${p1},${p2}`,
|
||||||
|
reservationGet: () => "RESERVATION:GET",
|
||||||
};
|
};
|
||||||
|
|
||||||
// ─── Board helpers ────────────────────────────────────────────────────────────
|
// ─── Board helpers ────────────────────────────────────────────────────────────
|
||||||
@@ -222,39 +243,39 @@ export type CellColor = 0 | 1 | 2;
|
|||||||
export type BoardState = CellColor[][]; // board[col][row], 7 cols × 6 rows
|
export type BoardState = CellColor[][]; // board[col][row], 7 cols × 6 rows
|
||||||
|
|
||||||
export function createEmptyBoard(): BoardState {
|
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). */
|
/** Place a token and return the new board plus the row it landed in (-1 if column full). */
|
||||||
export function placeToken(
|
export function placeToken(
|
||||||
board: BoardState,
|
board: BoardState,
|
||||||
color: 1 | 2,
|
color: 1 | 2,
|
||||||
column: number
|
column: number,
|
||||||
): { board: BoardState; row: number } {
|
): { board: BoardState; row: number } {
|
||||||
const newBoard = board.map((col) => [...col]) as BoardState;
|
const newBoard = board.map((col) => [...col]) as BoardState;
|
||||||
let placedRow = -1;
|
let placedRow = -1;
|
||||||
for (let row = 0; row < 6; row++) {
|
for (let row = 0; row < 6; row++) {
|
||||||
if (newBoard[column][row] === 0) {
|
if (newBoard[column][row] === 0) {
|
||||||
newBoard[column][row] = color;
|
newBoard[column][row] = color;
|
||||||
placedRow = row;
|
placedRow = row;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { board: newBoard, row: placedRow };
|
return { board: newBoard, row: placedRow };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Replay a move list onto an empty board. */
|
/** Replay a move list onto an empty board. */
|
||||||
export function replayMoves(
|
export function replayMoves(
|
||||||
moves: MoveEntry[],
|
moves: MoveEntry[],
|
||||||
player1: string
|
player1: string,
|
||||||
): { board: BoardState; lastMove: { column: number; row: number } | null } {
|
): { board: BoardState; lastMove: { column: number; row: number } | null } {
|
||||||
let board = createEmptyBoard();
|
let board = createEmptyBoard();
|
||||||
let lastMove: { column: number; row: number } | null = null;
|
let lastMove: { column: number; row: number } | null = null;
|
||||||
for (const move of moves) {
|
for (const move of moves) {
|
||||||
const color: 1 | 2 = move.username === player1 ? 1 : 2;
|
const color: 1 | 2 = move.username === player1 ? 1 : 2;
|
||||||
const result = placeToken(board, color, move.column);
|
const result = placeToken(board, color, move.column);
|
||||||
board = result.board;
|
board = result.board;
|
||||||
lastMove = { column: move.column, row: result.row };
|
lastMove = { column: move.column, row: result.row };
|
||||||
}
|
}
|
||||||
return { board, lastMove };
|
return { board, lastMove };
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user