Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f341251812 | |||
| 5fb3ad4205 | |||
| 33d917c8f2 | |||
| d129458039 | |||
| 8284815337 | |||
| 5b30ac8d83 | |||
| 34e8984daa | |||
| cb3f5fb5cf |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "tictactoe-vite",
|
||||
"version": "v0.1.0",
|
||||
"version": "v0.2.0",
|
||||
"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>
|
||||
|
||||
68
src/tictactoe/Leaderboard.tsx
Normal file
68
src/tictactoe/Leaderboard.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import React from "react";
|
||||
import { useRef, useEffect, useState } from "react";
|
||||
import {
|
||||
ApiLeaderboardRecordList,
|
||||
// @ts-ignore
|
||||
} from "@heroiclabs/nakama-js/dist/api.gen"
|
||||
import { useNakama } from "./providers/NakamaProvider";
|
||||
|
||||
export default function Leaderboard({
|
||||
intervalMs = 10000,
|
||||
}: {
|
||||
intervalMs?: number;
|
||||
}) {
|
||||
const {
|
||||
getLeaderboardTop
|
||||
} = useNakama()
|
||||
const [records, setRecords] = useState<ApiLeaderboardRecordList>([]);
|
||||
const timerRef = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const data = await getLeaderboardTop();
|
||||
if (mounted) setRecords(data);
|
||||
} catch (err) {
|
||||
console.error("Leaderboard fetch failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
// First load immediately
|
||||
load();
|
||||
|
||||
// Start interval polling
|
||||
timerRef.current = window.setInterval(load, intervalMs);
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
};
|
||||
}, [getLeaderboardTop, intervalMs]);
|
||||
|
||||
// @ts-ignore
|
||||
return (
|
||||
<div className="leaderboard">
|
||||
<h2 className="leaderboard-title">🏆 Leaderboard – Wins</h2>
|
||||
|
||||
{records?.records?.length === 0 && (
|
||||
<div className="leaderboard-empty">No entries yet.</div>
|
||||
)}
|
||||
|
||||
{records?.records?.map((
|
||||
r: {
|
||||
owner_id: number,
|
||||
username: string,
|
||||
score: number
|
||||
},
|
||||
i: number
|
||||
) => (
|
||||
<div className="leaderboard-row" key={r.owner_id + i}>
|
||||
<div className="leaderboard-rank">{i + 1}</div>
|
||||
<div className="leaderboard-name">{r.username || r.owner_id}</div>
|
||||
<div className="leaderboard-score">{r.score}</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,13 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNakama } from "./providers/NakamaProvider";
|
||||
import Board from "./Board";
|
||||
import Leaderboard from "./Leaderboard";
|
||||
// import { Match } from "@heroiclabs/nakama-js";
|
||||
// import MatchList from "./MatchList";
|
||||
|
||||
export default function TicTacToe() {
|
||||
const [username, setUsername] = useState("");
|
||||
const [selectedMode, setSelectedMode] = useState("classic");
|
||||
const [board, setBoard] = useState<string[][]>([
|
||||
["", "", ""],
|
||||
["", "", ""],
|
||||
@@ -11,13 +15,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 +33,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 +77,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 +101,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 +110,7 @@ export default function TicTacToe() {
|
||||
<div>
|
||||
<h1>Tic Tac Toe Multiplayer</h1>
|
||||
|
||||
{!matchId && (
|
||||
{!session && (
|
||||
<>
|
||||
<input
|
||||
placeholder="username"
|
||||
@@ -81,7 +118,33 @@ 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} />*/}
|
||||
<Leaderboard/>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -90,6 +153,8 @@ export default function TicTacToe() {
|
||||
board={board}
|
||||
turn={turn}
|
||||
winner={winner}
|
||||
players={players}
|
||||
myUserId={session?.user_id ?? null}
|
||||
onCellClick={handleCellClick}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -3,10 +3,16 @@ import {
|
||||
Session,
|
||||
Socket,
|
||||
MatchmakerTicket,
|
||||
Match,
|
||||
MatchData,
|
||||
MatchmakerMatched,
|
||||
} from "@heroiclabs/nakama-js";
|
||||
|
||||
import {
|
||||
ApiMatch,
|
||||
ApiLeaderboardRecordList,
|
||||
// @ts-ignore
|
||||
} from "@heroiclabs/nakama-js/dist/api.gen"
|
||||
|
||||
import React, { createContext, useContext, useState } from "react";
|
||||
|
||||
function getOrCreateDeviceId(): string {
|
||||
@@ -32,6 +38,8 @@ export interface NakamaContextType {
|
||||
sendMatchData(matchId: string, op: number, data: object): void;
|
||||
|
||||
onMatchData(cb: (msg: any) => void): void;
|
||||
getLeaderboardTop(): Promise<ApiLeaderboardRecordList>;
|
||||
listOpenMatches(): Promise<ApiMatch[]>;
|
||||
}
|
||||
|
||||
export const NakamaContext = createContext<NakamaContextType>(null!);
|
||||
@@ -44,6 +52,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 +69,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 +106,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 +117,8 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
{ mode } // stringProperties
|
||||
);
|
||||
|
||||
lastModeRef.current = mode;
|
||||
|
||||
return ticket.ticket;
|
||||
}
|
||||
|
||||
@@ -128,6 +156,29 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
};
|
||||
}
|
||||
|
||||
async function getLeaderboardTop(): Promise<ApiLeaderboardRecordList> {
|
||||
if (!session) return [];
|
||||
|
||||
return await client.listLeaderboardRecords(
|
||||
session,
|
||||
"tictactoe",
|
||||
[],
|
||||
10 // top 10
|
||||
);
|
||||
}
|
||||
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 +191,8 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
joinMatch,
|
||||
sendMatchData,
|
||||
onMatchData,
|
||||
getLeaderboardTop,
|
||||
listOpenMatches,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
background: #f4f4f4;
|
||||
background: #eaeef3;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding-top: 50px;
|
||||
margin: 0;
|
||||
color: #222;
|
||||
}
|
||||
|
||||
.game-container {
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.board {
|
||||
@@ -22,32 +24,111 @@ body {
|
||||
|
||||
.square {
|
||||
background: white;
|
||||
border: 2px solid #333;
|
||||
font-size: 2rem;
|
||||
border-radius: 10px;
|
||||
border: 2px solid #444;
|
||||
font-size: 2.2rem;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
height: 100px;
|
||||
width: 100px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: 0.15s ease;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.15);
|
||||
}
|
||||
|
||||
.square:hover {
|
||||
background: #eee;
|
||||
background: #f1f1f1;
|
||||
transform: scale(1.04);
|
||||
}
|
||||
|
||||
.status {
|
||||
font-size: 1.4rem;
|
||||
margin-bottom: 10px;
|
||||
font-size: 1.6rem;
|
||||
margin-bottom: 15px;
|
||||
font-weight: bold;
|
||||
color: #222;
|
||||
}
|
||||
|
||||
.reset-btn {
|
||||
padding: 10px 20px;
|
||||
background: #333;
|
||||
padding: 12px 26px;
|
||||
background: #3558d8;
|
||||
color: white;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
border-radius: 8px;
|
||||
transition: 0.2s ease;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.25);
|
||||
}
|
||||
|
||||
.reset-btn:hover {
|
||||
background: #555;
|
||||
background: #2449c7;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.leaderboard {
|
||||
width: 300px;
|
||||
margin: 25px auto;
|
||||
padding: 15px 20px;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
font-family: sans-serif;
|
||||
}
|
||||
|
||||
/* Leaderboard title */
|
||||
.leaderboard-title {
|
||||
margin: 0 0 15px 0;
|
||||
font-size: 1.4rem;
|
||||
font-weight: 700;
|
||||
text-align: center;
|
||||
color: #222;
|
||||
}
|
||||
|
||||
/* Each row */
|
||||
.leaderboard-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 10px 8px;
|
||||
background: #f7f9fc;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 8px;
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,0.08);
|
||||
}
|
||||
|
||||
/* Empty state */
|
||||
.leaderboard-empty {
|
||||
padding: 12px 0;
|
||||
text-align: center;
|
||||
color: #777;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
/* Rank number */
|
||||
.leaderboard-rank {
|
||||
width: 28px;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 700;
|
||||
color: #3558d8;
|
||||
}
|
||||
|
||||
/* Username */
|
||||
.leaderboard-name {
|
||||
flex: 1;
|
||||
margin-left: 10px;
|
||||
font-weight: 500;
|
||||
color: #333;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Score value */
|
||||
.leaderboard-score {
|
||||
width: 40px;
|
||||
text-align: right;
|
||||
font-weight: 700;
|
||||
color: #111;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user