Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 33d917c8f2 | |||
| d129458039 | |||
| 8284815337 | |||
| 5b30ac8d83 | |||
| 34e8984daa | |||
| cb3f5fb5cf |
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "tictactoe-vite",
|
"name": "tictactoe-vite",
|
||||||
"version": "v0.1.0",
|
"version": "v0.1.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -4,16 +4,52 @@ interface BoardProps {
|
|||||||
board: string[][];
|
board: string[][];
|
||||||
turn: number;
|
turn: number;
|
||||||
winner: string | null;
|
winner: string | null;
|
||||||
|
players: string[];
|
||||||
|
myUserId: string | null;
|
||||||
onCellClick: (row: number, col: number) => void;
|
onCellClick: (row: number, col: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Board({ board, turn, winner, onCellClick }: BoardProps) {
|
export default function Board({
|
||||||
|
board,
|
||||||
|
turn,
|
||||||
|
winner,
|
||||||
|
players,
|
||||||
|
myUserId,
|
||||||
|
onCellClick,
|
||||||
|
}: BoardProps) {
|
||||||
|
const myIndex = players.indexOf(myUserId ?? "");
|
||||||
|
const gameReady = players.length === 2;
|
||||||
|
|
||||||
|
const mySymbol =
|
||||||
|
myIndex === 0 ? "X" : myIndex === 1 ? "O" : null;
|
||||||
|
|
||||||
|
const opponentSymbol =
|
||||||
|
mySymbol === "X" ? "O" : mySymbol === "O" ? "X" : null;
|
||||||
|
|
||||||
|
const isMyTurn = gameReady && myIndex !== -1 && turn === myIndex;
|
||||||
|
|
||||||
|
// -------------------------------
|
||||||
|
// 🟦 HEADER STATUS FIXED
|
||||||
|
// -------------------------------
|
||||||
|
let status;
|
||||||
|
if (!gameReady) {
|
||||||
|
status = "Waiting for opponent...";
|
||||||
|
} else if (winner) {
|
||||||
|
status = `Winner: ${winner}`;
|
||||||
|
} else if (myIndex === -1) {
|
||||||
|
status = "Spectating";
|
||||||
|
} else {
|
||||||
|
status = isMyTurn ? "Your turn" : "Opponent's turn";
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{winner ? (
|
<h2 style={{ marginBottom: 8 }}>{status}</h2>
|
||||||
<h2>Winner: {winner}</h2>
|
|
||||||
) : (
|
{gameReady && mySymbol && (
|
||||||
<h2>Turn: Player {turn === 0 ? "X" : "O"}</h2>
|
<div style={{ marginBottom: 8, fontSize: 14, color: "#666" }}>
|
||||||
|
You: <strong>{mySymbol}</strong> — Opponent: <strong>{opponentSymbol}</strong>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
@@ -21,26 +57,35 @@ export default function Board({ board, turn, winner, onCellClick }: BoardProps)
|
|||||||
display: "grid",
|
display: "grid",
|
||||||
gridTemplateColumns: "repeat(3, 80px)",
|
gridTemplateColumns: "repeat(3, 80px)",
|
||||||
gap: "10px",
|
gap: "10px",
|
||||||
marginTop: "20px",
|
marginTop: "6px",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{board.map((row, rIdx) =>
|
{board.map((row, rIdx) =>
|
||||||
row.map((cell, cIdx) => (
|
row.map((cell, cIdx) => {
|
||||||
<button
|
const disabled =
|
||||||
key={`${rIdx}-${cIdx}`}
|
!!cell ||
|
||||||
style={{
|
!!winner ||
|
||||||
width: "80px",
|
!gameReady ||
|
||||||
height: "80px",
|
myIndex === -1 ||
|
||||||
fontSize: "2rem",
|
!isMyTurn;
|
||||||
cursor: cell || winner ? "not-allowed" : "pointer",
|
|
||||||
}}
|
return (
|
||||||
onClick={() => {
|
<button
|
||||||
if (!cell && !winner) onCellClick(rIdx, cIdx);
|
key={`${rIdx}-${cIdx}`}
|
||||||
}}
|
style={{
|
||||||
>
|
width: "80px",
|
||||||
{cell}
|
height: "80px",
|
||||||
</button>
|
fontSize: "2rem",
|
||||||
))
|
cursor: disabled ? "not-allowed" : "pointer",
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
if (!disabled) onCellClick(rIdx, cIdx);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{cell}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
55
src/tictactoe/MatchList.tsx
Normal file
55
src/tictactoe/MatchList.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { Match } from "@heroiclabs/nakama-js";
|
||||||
|
|
||||||
|
interface MatchListProps {
|
||||||
|
matches: Match[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function MatchList({ matches }: MatchListProps) {
|
||||||
|
if (!matches.length) return <p>No open matches</p>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ marginTop: "20px" }}>
|
||||||
|
<h3>Open Matches</h3>
|
||||||
|
|
||||||
|
<table
|
||||||
|
style={{
|
||||||
|
width: "100%",
|
||||||
|
borderCollapse: "collapse",
|
||||||
|
marginTop: "10px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th style={th}>Sr No.</th>
|
||||||
|
<th style={th}>Match ID</th>
|
||||||
|
<th style={th}>Label</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
|
||||||
|
<tbody>
|
||||||
|
{matches
|
||||||
|
.filter(m => m.size ?? 0 > 0)
|
||||||
|
.map((m, index) => (
|
||||||
|
<tr key={m.match_id}>
|
||||||
|
<td style={td}>{index + 1}</td>
|
||||||
|
<td style={td}>{m.match_id}</td>
|
||||||
|
<td style={td}>{m.label ?? "-"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const th: React.CSSProperties = {
|
||||||
|
textAlign: "left",
|
||||||
|
padding: "8px",
|
||||||
|
background: "#f2f2f2",
|
||||||
|
borderBottom: "1px solid #ccc",
|
||||||
|
};
|
||||||
|
|
||||||
|
const td: React.CSSProperties = {
|
||||||
|
padding: "8px",
|
||||||
|
borderBottom: "1px solid #eee",
|
||||||
|
};
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useNakama } from "./providers/NakamaProvider";
|
import { useNakama } from "./providers/NakamaProvider";
|
||||||
|
import { Match } from "@heroiclabs/nakama-js";
|
||||||
import Board from "./Board";
|
import Board from "./Board";
|
||||||
|
// import MatchList from "./MatchList";
|
||||||
|
|
||||||
export default function TicTacToe() {
|
export default function TicTacToe() {
|
||||||
const [username, setUsername] = useState("");
|
const [username, setUsername] = useState("");
|
||||||
|
const [selectedMode, setSelectedMode] = useState("classic");
|
||||||
const [board, setBoard] = useState<string[][]>([
|
const [board, setBoard] = useState<string[][]>([
|
||||||
["", "", ""],
|
["", "", ""],
|
||||||
["", "", ""],
|
["", "", ""],
|
||||||
@@ -11,13 +14,17 @@ export default function TicTacToe() {
|
|||||||
]);
|
]);
|
||||||
const [turn, setTurn] = useState<number>(0);
|
const [turn, setTurn] = useState<number>(0);
|
||||||
const [winner, setWinner] = useState<string | null>(null);
|
const [winner, setWinner] = useState<string | null>(null);
|
||||||
|
// const [openMatches, setOpenMatches] = useState<Match[]>([]);
|
||||||
|
const [players, setPlayers] = useState<string[]>([]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
loginOrRegister,
|
loginOrRegister,
|
||||||
joinMatchmaker,
|
joinMatchmaker,
|
||||||
onMatchData,
|
onMatchData,
|
||||||
sendMatchData,
|
sendMatchData,
|
||||||
|
listOpenMatches,
|
||||||
matchId,
|
matchId,
|
||||||
|
session,
|
||||||
} = useNakama();
|
} = useNakama();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -25,13 +32,38 @@ export default function TicTacToe() {
|
|||||||
console.log("[Match Data]", msg);
|
console.log("[Match Data]", msg);
|
||||||
|
|
||||||
if (msg.opCode === 2) {
|
if (msg.opCode === 2) {
|
||||||
setBoard(msg.data.board);
|
const state = msg.data;
|
||||||
setTurn(msg.data.turn);
|
console.log("Match state:", state);
|
||||||
setWinner(msg.data.winner || null);
|
|
||||||
|
setBoard(state.board);
|
||||||
|
setTurn(state.turn);
|
||||||
|
setWinner(state.winner || null);
|
||||||
|
|
||||||
|
// new:
|
||||||
|
setPlayers(state.players || []);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, [onMatchData]);
|
}, [onMatchData]);
|
||||||
|
|
||||||
|
// useEffect(() => {
|
||||||
|
// let active = true;
|
||||||
|
//
|
||||||
|
// async function refreshLoop() {
|
||||||
|
// while (active) {
|
||||||
|
// const matches = await listOpenMatches();
|
||||||
|
// setOpenMatches(matches);
|
||||||
|
//
|
||||||
|
// await new Promise(res => setTimeout(res, 500)); // 0.5s refresh
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// refreshLoop();
|
||||||
|
//
|
||||||
|
// return () => {
|
||||||
|
// active = false;
|
||||||
|
// };
|
||||||
|
// }, [listOpenMatches]);
|
||||||
|
|
||||||
// ------------------------------------------
|
// ------------------------------------------
|
||||||
// CONNECT
|
// CONNECT
|
||||||
// ------------------------------------------
|
// ------------------------------------------
|
||||||
@@ -44,10 +76,14 @@ export default function TicTacToe() {
|
|||||||
|
|
||||||
if (msg.opCode === 2) {
|
if (msg.opCode === 2) {
|
||||||
const state = msg.data;
|
const state = msg.data;
|
||||||
|
console.log("Match state:", state);
|
||||||
|
|
||||||
setBoard(state.board);
|
setBoard(state.board);
|
||||||
setTurn(state.turn);
|
setTurn(state.turn);
|
||||||
setWinner(state.winner || null);
|
setWinner(state.winner || null);
|
||||||
|
|
||||||
|
// new:
|
||||||
|
setPlayers(state.players || []);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -64,8 +100,8 @@ export default function TicTacToe() {
|
|||||||
// ------------------------------------------
|
// ------------------------------------------
|
||||||
// MATCHMAKING
|
// MATCHMAKING
|
||||||
// ------------------------------------------
|
// ------------------------------------------
|
||||||
async function startQueue() {
|
async function startQueue(selectedMode: string) {
|
||||||
const ticket = await joinMatchmaker("classic");
|
const ticket = await joinMatchmaker(selectedMode);
|
||||||
console.log("Queued:", ticket);
|
console.log("Queued:", ticket);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,7 +109,7 @@ export default function TicTacToe() {
|
|||||||
<div>
|
<div>
|
||||||
<h1>Tic Tac Toe Multiplayer</h1>
|
<h1>Tic Tac Toe Multiplayer</h1>
|
||||||
|
|
||||||
{!matchId && (
|
{!session && (
|
||||||
<>
|
<>
|
||||||
<input
|
<input
|
||||||
placeholder="username"
|
placeholder="username"
|
||||||
@@ -81,7 +117,32 @@ export default function TicTacToe() {
|
|||||||
onChange={(e) => setUsername(e.target.value)}
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
/>
|
/>
|
||||||
<button onClick={connect}>Connect</button>
|
<button onClick={connect}>Connect</button>
|
||||||
<button onClick={startQueue}>Join Matchmaking</button>
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{session && !matchId && (
|
||||||
|
<>
|
||||||
|
<h2>Hello, {session.username}</h2>
|
||||||
|
|
||||||
|
{/* Game mode selection */}
|
||||||
|
<label style={{ display: "block", marginTop: "10px" }}>
|
||||||
|
Select Game Mode:
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<select
|
||||||
|
value={selectedMode}
|
||||||
|
onChange={(e) => setSelectedMode(e.target.value)}
|
||||||
|
style={{ padding: "6px", marginBottom: "10px" }}
|
||||||
|
>
|
||||||
|
<option value="classic">Classic</option>
|
||||||
|
<option value="blitz">Blitz</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
{/* Join matchmaking */}
|
||||||
|
<button onClick={() => startQueue(selectedMode)}>Join Matchmaking</button>
|
||||||
|
|
||||||
|
{/*/!* List open matches *!/*/}
|
||||||
|
{/*<MatchList matches={openMatches} />*/}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -90,6 +151,8 @@ export default function TicTacToe() {
|
|||||||
board={board}
|
board={board}
|
||||||
turn={turn}
|
turn={turn}
|
||||||
winner={winner}
|
winner={winner}
|
||||||
|
players={players}
|
||||||
|
myUserId={session?.user_id ?? null}
|
||||||
onCellClick={handleCellClick}
|
onCellClick={handleCellClick}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ import {
|
|||||||
Session,
|
Session,
|
||||||
Socket,
|
Socket,
|
||||||
MatchmakerTicket,
|
MatchmakerTicket,
|
||||||
Match,
|
|
||||||
MatchData,
|
MatchData,
|
||||||
MatchmakerMatched,
|
MatchmakerMatched,
|
||||||
} from "@heroiclabs/nakama-js";
|
} from "@heroiclabs/nakama-js";
|
||||||
|
// @ts-ignore
|
||||||
|
import { ApiMatch } from "@heroiclabs/nakama-js/dist/api.gen"
|
||||||
|
|
||||||
import React, { createContext, useContext, useState } from "react";
|
import React, { createContext, useContext, useState } from "react";
|
||||||
|
|
||||||
function getOrCreateDeviceId(): string {
|
function getOrCreateDeviceId(): string {
|
||||||
@@ -32,6 +34,7 @@ export interface NakamaContextType {
|
|||||||
sendMatchData(matchId: string, op: number, data: object): void;
|
sendMatchData(matchId: string, op: number, data: object): void;
|
||||||
|
|
||||||
onMatchData(cb: (msg: any) => void): void;
|
onMatchData(cb: (msg: any) => void): void;
|
||||||
|
listOpenMatches(): Promise<ApiMatch[]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const NakamaContext = createContext<NakamaContextType>(null!);
|
export const NakamaContext = createContext<NakamaContextType>(null!);
|
||||||
@@ -44,6 +47,8 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
|||||||
const [session, setSession] = useState<Session | null>(null);
|
const [session, setSession] = useState<Session | null>(null);
|
||||||
const [socket, setSocket] = useState<Socket | null>(null);
|
const [socket, setSocket] = useState<Socket | null>(null);
|
||||||
const [matchId, setMatchId] = useState<string | null>(null);
|
const [matchId, setMatchId] = useState<string | null>(null);
|
||||||
|
const lastModeRef = React.useRef<string | null>(null);
|
||||||
|
const socketRef = React.useRef<Socket | null>(null);
|
||||||
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
// LOGIN
|
// LOGIN
|
||||||
@@ -59,17 +64,32 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
|||||||
const s = client.createSocket(undefined, undefined); // no SSL on localhost
|
const s = client.createSocket(undefined, undefined); // no SSL on localhost
|
||||||
await s.connect(newSession, true);
|
await s.connect(newSession, true);
|
||||||
setSocket(s);
|
setSocket(s);
|
||||||
|
socketRef.current = s;
|
||||||
|
|
||||||
console.log("[Nakama] WebSocket connected");
|
console.log("[Nakama] WebSocket connected");
|
||||||
|
|
||||||
// MATCHMAKER MATCHED CALLBACK
|
// MATCHMAKER MATCHED CALLBACK
|
||||||
s.onmatchmakermatched = async (matched: MatchmakerMatched) => {
|
s.onmatchmakermatched = async (matched: MatchmakerMatched) => {
|
||||||
|
// 1) If match_id is empty → server rejected the group.
|
||||||
|
if (!matched.match_id) {
|
||||||
|
console.warn("[Nakama] Match rejected by server. Auto-requeueing...");
|
||||||
|
|
||||||
|
if (lastModeRef.current) {
|
||||||
|
try {
|
||||||
|
await joinMatchmaker(lastModeRef.current);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[Nakama] Requeue failed:", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Valid match: continue as usual.
|
||||||
console.log("[Nakama] MATCHED:", matched);
|
console.log("[Nakama] MATCHED:", matched);
|
||||||
|
|
||||||
setMatchId(matched.match_id);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await s.joinMatch(matched.match_id);
|
await s.joinMatch(matched.match_id);
|
||||||
|
setMatchId(matched.match_id);
|
||||||
console.log("[Nakama] Auto-joined match:", matched.match_id);
|
console.log("[Nakama] Auto-joined match:", matched.match_id);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[Nakama] Failed to join match:", err);
|
console.error("[Nakama] Failed to join match:", err);
|
||||||
@@ -81,6 +101,7 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
|||||||
// MATCHMAKING
|
// MATCHMAKING
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
async function joinMatchmaker(mode: string) {
|
async function joinMatchmaker(mode: string) {
|
||||||
|
const socket = socketRef.current;
|
||||||
if (!socket) throw new Error("socket missing");
|
if (!socket) throw new Error("socket missing");
|
||||||
|
|
||||||
console.log(`[Nakama] Matchmaking... with +mode:"${mode}"`);
|
console.log(`[Nakama] Matchmaking... with +mode:"${mode}"`);
|
||||||
@@ -91,6 +112,8 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
|||||||
{ mode } // stringProperties
|
{ mode } // stringProperties
|
||||||
);
|
);
|
||||||
|
|
||||||
|
lastModeRef.current = mode;
|
||||||
|
|
||||||
return ticket.ticket;
|
return ticket.ticket;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,6 +151,19 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function listOpenMatches(): Promise<ApiMatch[]> {
|
||||||
|
if (!session) {
|
||||||
|
console.warn("[Nakama] listOpenMatches called before login");
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await client.listMatches(session, 10);
|
||||||
|
|
||||||
|
console.log("[Nakama] Open matches:", result.matches);
|
||||||
|
|
||||||
|
return result.matches ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<NakamaContext.Provider
|
<NakamaContext.Provider
|
||||||
value={{
|
value={{
|
||||||
@@ -140,6 +176,7 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
|||||||
joinMatch,
|
joinMatch,
|
||||||
sendMatchData,
|
sendMatchData,
|
||||||
onMatchData,
|
onMatchData,
|
||||||
|
listOpenMatches,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
Reference in New Issue
Block a user