Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 33d917c8f2 | |||
| d129458039 | |||
| 8284815337 | |||
| 5b30ac8d83 | |||
| 34e8984daa | |||
| cb3f5fb5cf |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "tictactoe-vite",
|
||||
"version": "v0.1.0",
|
||||
"version": "v0.1.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -4,16 +4,52 @@ interface BoardProps {
|
||||
board: string[][];
|
||||
turn: number;
|
||||
winner: string | null;
|
||||
players: string[];
|
||||
myUserId: string | null;
|
||||
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 (
|
||||
<div>
|
||||
{winner ? (
|
||||
<h2>Winner: {winner}</h2>
|
||||
) : (
|
||||
<h2>Turn: Player {turn === 0 ? "X" : "O"}</h2>
|
||||
<h2 style={{ marginBottom: 8 }}>{status}</h2>
|
||||
|
||||
{gameReady && mySymbol && (
|
||||
<div style={{ marginBottom: 8, fontSize: 14, color: "#666" }}>
|
||||
You: <strong>{mySymbol}</strong> — Opponent: <strong>{opponentSymbol}</strong>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
@@ -21,26 +57,35 @@ export default function Board({ board, turn, winner, onCellClick }: BoardProps)
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(3, 80px)",
|
||||
gap: "10px",
|
||||
marginTop: "20px",
|
||||
marginTop: "6px",
|
||||
}}
|
||||
>
|
||||
{board.map((row, rIdx) =>
|
||||
row.map((cell, cIdx) => (
|
||||
<button
|
||||
key={`${rIdx}-${cIdx}`}
|
||||
style={{
|
||||
width: "80px",
|
||||
height: "80px",
|
||||
fontSize: "2rem",
|
||||
cursor: cell || winner ? "not-allowed" : "pointer",
|
||||
}}
|
||||
onClick={() => {
|
||||
if (!cell && !winner) onCellClick(rIdx, cIdx);
|
||||
}}
|
||||
>
|
||||
{cell}
|
||||
</button>
|
||||
))
|
||||
row.map((cell, cIdx) => {
|
||||
const disabled =
|
||||
!!cell ||
|
||||
!!winner ||
|
||||
!gameReady ||
|
||||
myIndex === -1 ||
|
||||
!isMyTurn;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={`${rIdx}-${cIdx}`}
|
||||
style={{
|
||||
width: "80px",
|
||||
height: "80px",
|
||||
fontSize: "2rem",
|
||||
cursor: disabled ? "not-allowed" : "pointer",
|
||||
}}
|
||||
onClick={() => {
|
||||
if (!disabled) onCellClick(rIdx, cIdx);
|
||||
}}
|
||||
>
|
||||
{cell}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</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 { useNakama } from "./providers/NakamaProvider";
|
||||
import { Match } from "@heroiclabs/nakama-js";
|
||||
import Board from "./Board";
|
||||
// import MatchList from "./MatchList";
|
||||
|
||||
export default function TicTacToe() {
|
||||
const [username, setUsername] = useState("");
|
||||
const [selectedMode, setSelectedMode] = useState("classic");
|
||||
const [board, setBoard] = useState<string[][]>([
|
||||
["", "", ""],
|
||||
["", "", ""],
|
||||
@@ -11,13 +14,17 @@ export default function TicTacToe() {
|
||||
]);
|
||||
const [turn, setTurn] = useState<number>(0);
|
||||
const [winner, setWinner] = useState<string | null>(null);
|
||||
// const [openMatches, setOpenMatches] = useState<Match[]>([]);
|
||||
const [players, setPlayers] = useState<string[]>([]);
|
||||
|
||||
const {
|
||||
loginOrRegister,
|
||||
joinMatchmaker,
|
||||
onMatchData,
|
||||
sendMatchData,
|
||||
listOpenMatches,
|
||||
matchId,
|
||||
session,
|
||||
} = useNakama();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -25,13 +32,38 @@ export default function TicTacToe() {
|
||||
console.log("[Match Data]", msg);
|
||||
|
||||
if (msg.opCode === 2) {
|
||||
setBoard(msg.data.board);
|
||||
setTurn(msg.data.turn);
|
||||
setWinner(msg.data.winner || null);
|
||||
const state = msg.data;
|
||||
console.log("Match state:", state);
|
||||
|
||||
setBoard(state.board);
|
||||
setTurn(state.turn);
|
||||
setWinner(state.winner || null);
|
||||
|
||||
// new:
|
||||
setPlayers(state.players || []);
|
||||
}
|
||||
});
|
||||
}, [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
|
||||
// ------------------------------------------
|
||||
@@ -44,10 +76,14 @@ export default function TicTacToe() {
|
||||
|
||||
if (msg.opCode === 2) {
|
||||
const state = msg.data;
|
||||
console.log("Match state:", state);
|
||||
|
||||
setBoard(state.board);
|
||||
setTurn(state.turn);
|
||||
setWinner(state.winner || null);
|
||||
|
||||
// new:
|
||||
setPlayers(state.players || []);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -64,8 +100,8 @@ export default function TicTacToe() {
|
||||
// ------------------------------------------
|
||||
// MATCHMAKING
|
||||
// ------------------------------------------
|
||||
async function startQueue() {
|
||||
const ticket = await joinMatchmaker("classic");
|
||||
async function startQueue(selectedMode: string) {
|
||||
const ticket = await joinMatchmaker(selectedMode);
|
||||
console.log("Queued:", ticket);
|
||||
}
|
||||
|
||||
@@ -73,7 +109,7 @@ export default function TicTacToe() {
|
||||
<div>
|
||||
<h1>Tic Tac Toe Multiplayer</h1>
|
||||
|
||||
{!matchId && (
|
||||
{!session && (
|
||||
<>
|
||||
<input
|
||||
placeholder="username"
|
||||
@@ -81,7 +117,32 @@ export default function TicTacToe() {
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
/>
|
||||
<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}
|
||||
turn={turn}
|
||||
winner={winner}
|
||||
players={players}
|
||||
myUserId={session?.user_id ?? null}
|
||||
onCellClick={handleCellClick}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -3,10 +3,12 @@ import {
|
||||
Session,
|
||||
Socket,
|
||||
MatchmakerTicket,
|
||||
Match,
|
||||
MatchData,
|
||||
MatchmakerMatched,
|
||||
} from "@heroiclabs/nakama-js";
|
||||
// @ts-ignore
|
||||
import { ApiMatch } from "@heroiclabs/nakama-js/dist/api.gen"
|
||||
|
||||
import React, { createContext, useContext, useState } from "react";
|
||||
|
||||
function getOrCreateDeviceId(): string {
|
||||
@@ -32,6 +34,7 @@ export interface NakamaContextType {
|
||||
sendMatchData(matchId: string, op: number, data: object): void;
|
||||
|
||||
onMatchData(cb: (msg: any) => void): void;
|
||||
listOpenMatches(): Promise<ApiMatch[]>;
|
||||
}
|
||||
|
||||
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 [socket, setSocket] = useState<Socket | null>(null);
|
||||
const [matchId, setMatchId] = useState<string | null>(null);
|
||||
const lastModeRef = React.useRef<string | null>(null);
|
||||
const socketRef = React.useRef<Socket | null>(null);
|
||||
|
||||
// ----------------------------------------------------
|
||||
// LOGIN
|
||||
@@ -59,17 +64,32 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
const s = client.createSocket(undefined, undefined); // no SSL on localhost
|
||||
await s.connect(newSession, true);
|
||||
setSocket(s);
|
||||
socketRef.current = s;
|
||||
|
||||
console.log("[Nakama] WebSocket connected");
|
||||
|
||||
// MATCHMAKER MATCHED CALLBACK
|
||||
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);
|
||||
|
||||
setMatchId(matched.match_id);
|
||||
|
||||
try {
|
||||
await s.joinMatch(matched.match_id);
|
||||
setMatchId(matched.match_id);
|
||||
console.log("[Nakama] Auto-joined match:", matched.match_id);
|
||||
} catch (err) {
|
||||
console.error("[Nakama] Failed to join match:", err);
|
||||
@@ -81,6 +101,7 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
// MATCHMAKING
|
||||
// ----------------------------------------------------
|
||||
async function joinMatchmaker(mode: string) {
|
||||
const socket = socketRef.current;
|
||||
if (!socket) throw new Error("socket missing");
|
||||
|
||||
console.log(`[Nakama] Matchmaking... with +mode:"${mode}"`);
|
||||
@@ -91,6 +112,8 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
{ mode } // stringProperties
|
||||
);
|
||||
|
||||
lastModeRef.current = mode;
|
||||
|
||||
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 (
|
||||
<NakamaContext.Provider
|
||||
value={{
|
||||
@@ -140,6 +176,7 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
joinMatch,
|
||||
sendMatchData,
|
||||
onMatchData,
|
||||
listOpenMatches,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
Reference in New Issue
Block a user