Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d962d9c5eb | |||
| 94bdec8cb4 | |||
| f7929b10ef | |||
| f341251812 | |||
| 5fb3ad4205 |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "tictactoe-vite",
|
||||
"version": "v0.1.1",
|
||||
"version": "v0.2.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
82
src/tictactoe/Player.tsx
Normal file
82
src/tictactoe/Player.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import Leaderboard from "./Leaderboard";
|
||||
import { useNakama } from "./providers/NakamaProvider";
|
||||
|
||||
export default function Player({
|
||||
onMatchDataCallback,
|
||||
}: {
|
||||
onMatchDataCallback: (msg: any) => void;
|
||||
}) {
|
||||
const {
|
||||
session,
|
||||
matchId,
|
||||
loginOrRegister,
|
||||
logout,
|
||||
onMatchData,
|
||||
joinMatchmaker,
|
||||
} = useNakama();
|
||||
|
||||
const [username, setUsername] = useState(
|
||||
localStorage.getItem("username") ?? ""
|
||||
);
|
||||
const [selectedMode, setSelectedMode] = useState("classic");
|
||||
|
||||
// ------------------------------------------
|
||||
// CONNECT
|
||||
// ------------------------------------------
|
||||
async function handleConnect() {
|
||||
await loginOrRegister(username);
|
||||
|
||||
// Match data listener
|
||||
onMatchData(onMatchDataCallback);
|
||||
}
|
||||
|
||||
// ------------------------------------------
|
||||
// MATCHMAKING
|
||||
// ------------------------------------------
|
||||
async function startQueue(selectedMode: string) {
|
||||
const ticket = await joinMatchmaker(selectedMode);
|
||||
console.log("Queued:", ticket);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
handleConnect();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: "20px" }}>
|
||||
{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>
|
||||
<button onClick={() => logout()}>Logout</button>
|
||||
|
||||
{/*/!* List open matches *!/*/}
|
||||
{/*<MatchList matches={openMatches} />*/}
|
||||
<Leaderboard/>
|
||||
</>
|
||||
)}
|
||||
{session && matchId && (
|
||||
<>
|
||||
<h2>Go {session.username}!</h2>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNakama } from "./providers/NakamaProvider";
|
||||
import { Match } from "@heroiclabs/nakama-js";
|
||||
import Board from "./Board";
|
||||
import Player from "./Player";
|
||||
// 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[][]>([
|
||||
["", "", ""],
|
||||
["", "", ""],
|
||||
@@ -17,32 +16,32 @@ export default function TicTacToe() {
|
||||
// const [openMatches, setOpenMatches] = useState<Match[]>([]);
|
||||
const [players, setPlayers] = useState<string[]>([]);
|
||||
|
||||
function onMatchDataCallback(msg: { opCode: number; data: any }) {
|
||||
console.log("[Match Data]", msg);
|
||||
|
||||
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 || []);
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
loginOrRegister,
|
||||
joinMatchmaker,
|
||||
onMatchData,
|
||||
sendMatchData,
|
||||
listOpenMatches,
|
||||
// listOpenMatches,
|
||||
matchId,
|
||||
session,
|
||||
} = useNakama();
|
||||
|
||||
useEffect(() => {
|
||||
onMatchData((msg) => {
|
||||
console.log("[Match Data]", msg);
|
||||
|
||||
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 || []);
|
||||
}
|
||||
});
|
||||
onMatchData(onMatchDataCallback);
|
||||
}, [onMatchData]);
|
||||
|
||||
// useEffect(() => {
|
||||
@@ -64,30 +63,6 @@ export default function TicTacToe() {
|
||||
// };
|
||||
// }, [listOpenMatches]);
|
||||
|
||||
// ------------------------------------------
|
||||
// CONNECT
|
||||
// ------------------------------------------
|
||||
async function connect() {
|
||||
await loginOrRegister(username);
|
||||
|
||||
// Match data listener
|
||||
onMatchData((msg) => {
|
||||
console.log("[Match Data]", msg);
|
||||
|
||||
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 || []);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------
|
||||
// SEND A MOVE
|
||||
// ------------------------------------------
|
||||
@@ -97,54 +72,13 @@ export default function TicTacToe() {
|
||||
sendMatchData(matchId, 1, { row, col }); // OpMove=1
|
||||
}
|
||||
|
||||
// ------------------------------------------
|
||||
// MATCHMAKING
|
||||
// ------------------------------------------
|
||||
async function startQueue(selectedMode: string) {
|
||||
const ticket = await joinMatchmaker(selectedMode);
|
||||
console.log("Queued:", ticket);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>Tic Tac Toe Multiplayer</h1>
|
||||
|
||||
{!session && (
|
||||
<>
|
||||
<input
|
||||
placeholder="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
/>
|
||||
<button onClick={connect}>Connect</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} />*/}
|
||||
</>
|
||||
)}
|
||||
<Player
|
||||
onMatchDataCallback={onMatchDataCallback}
|
||||
/>
|
||||
|
||||
{matchId && (
|
||||
<Board
|
||||
|
||||
@@ -6,8 +6,12 @@ import {
|
||||
MatchData,
|
||||
MatchmakerMatched,
|
||||
} from "@heroiclabs/nakama-js";
|
||||
|
||||
import {
|
||||
ApiMatch,
|
||||
ApiLeaderboardRecordList,
|
||||
// @ts-ignore
|
||||
import { ApiMatch } from "@heroiclabs/nakama-js/dist/api.gen"
|
||||
} from "@heroiclabs/nakama-js/dist/api.gen"
|
||||
|
||||
import React, { createContext, useContext, useState } from "react";
|
||||
|
||||
@@ -28,12 +32,14 @@ export interface NakamaContextType {
|
||||
matchId: string | null;
|
||||
|
||||
loginOrRegister(username: string): Promise<void>;
|
||||
logout(): Promise<void>;
|
||||
joinMatchmaker(mode: string): Promise<string>;
|
||||
joinMatch(matchId: string): Promise<void>;
|
||||
|
||||
sendMatchData(matchId: string, op: number, data: object): void;
|
||||
|
||||
onMatchData(cb: (msg: any) => void): void;
|
||||
getLeaderboardTop(): Promise<ApiLeaderboardRecordList>;
|
||||
listOpenMatches(): Promise<ApiMatch[]>;
|
||||
}
|
||||
|
||||
@@ -50,17 +56,63 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
const lastModeRef = React.useRef<string | null>(null);
|
||||
const socketRef = React.useRef<Socket | null>(null);
|
||||
|
||||
async function autoLogin() {
|
||||
const deviceId = getOrCreateDeviceId();
|
||||
|
||||
try {
|
||||
return await client.authenticateDevice(
|
||||
deviceId,
|
||||
false
|
||||
);
|
||||
} catch (e) {
|
||||
// fallback: treat as new user
|
||||
localStorage.removeItem("registered");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function registerWithUsername(username: string) {
|
||||
const deviceId = getOrCreateDeviceId();
|
||||
|
||||
// create + set username
|
||||
const session = await client.authenticateDevice(
|
||||
deviceId,
|
||||
true,
|
||||
username
|
||||
);
|
||||
|
||||
// mark an account as registered
|
||||
localStorage.setItem("registered", "yes");
|
||||
localStorage.setItem("username", username);
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
async function getSession(username?: string) {
|
||||
const isRegistered = localStorage.getItem("registered") === "yes";
|
||||
if (!username && !isRegistered) {
|
||||
throw new Error("No username provided and not registered");
|
||||
}
|
||||
|
||||
let newSession;
|
||||
if (!isRegistered) {
|
||||
newSession = await registerWithUsername(username ?? "");
|
||||
} else {
|
||||
newSession = await autoLogin();
|
||||
}
|
||||
|
||||
return newSession;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// LOGIN
|
||||
// ----------------------------------------------------
|
||||
async function loginOrRegister(username: string) {
|
||||
const deviceId = getOrCreateDeviceId();
|
||||
|
||||
async function loginOrRegister(username?: string) {
|
||||
// authenticate user
|
||||
const newSession = await client.authenticateDevice(deviceId, true, username);
|
||||
const newSession = await getSession(username);
|
||||
setSession(newSession);
|
||||
|
||||
// create socket (new Nakama 3.x signature)
|
||||
// create a socket (new Nakama 3.x signature)
|
||||
const s = client.createSocket(undefined, undefined); // no SSL on localhost
|
||||
await s.connect(newSession, true);
|
||||
setSocket(s);
|
||||
@@ -97,6 +149,25 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
};
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
// 1) Disconnect socket if present
|
||||
if (socketRef.current) {
|
||||
socketRef.current.disconnect(true);
|
||||
console.log("[Nakama] WebSocket disconnected");
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("[Nakama] Error while disconnecting socket:", err);
|
||||
}
|
||||
|
||||
// 2) Clear state
|
||||
setSocket(null);
|
||||
socketRef.current = null;
|
||||
setSession(null);
|
||||
|
||||
console.log("[Nakama] Clean logout completed");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// MATCHMAKING
|
||||
// ----------------------------------------------------
|
||||
@@ -151,6 +222,16 @@ 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");
|
||||
@@ -172,10 +253,12 @@ export function NakamaProvider({ children }: { children: React.ReactNode }) {
|
||||
socket,
|
||||
matchId,
|
||||
loginOrRegister,
|
||||
logout,
|
||||
joinMatchmaker,
|
||||
joinMatch,
|
||||
sendMatchData,
|
||||
onMatchData,
|
||||
getLeaderboardTop,
|
||||
listOpenMatches,
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -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