Checkers โ React integration guide
Exact files to create, what to put in each one, and how they connect together.
1
Install the SDK
npm install @beta-gamer/react2
Create a session on your backend
โ ๏ธ Never call the Beta Gamer API directly from your frontend. Your API key must stay server-side only. Use any backend below โ a single serverless function is enough.
๐ server/routes/game.js
app.post('/api/game/start', async (req, res) => {
const { userId, userName, game, matchType } = req.body;
const resp = await fetch('https://api.beta-gamer.com/v1/sessions', {
method: 'POST',
headers: { 'Authorization': 'Bearer bg_live_xxxx', 'Content-Type': 'application/json' },
body: JSON.stringify({
game, matchType, players: [{ id: userId, displayName: userName }],
}),
});
const { sessionToken, sessionId } = await resp.json();
res.json({ sessionToken, sessionId });
});3
Create a lobby page
๐ src/pages/checkers/lobby.tsx
import { useState } from 'react';
import { useRouter } from 'next/navigation';
export default function CheckersLobby() {
const router = useRouter();
const [loading, setLoading] = useState(false);
const startGame = async (matchType: 'matchmaking' | 'bot') => {
setLoading(true);
const res = await fetch('/api/game/checkers/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ matchType }),
});
const { sessionToken, sessionId } = await res.json();
router.push(`/checkers/game/${sessionId}?token=${sessionToken}`);
};
return (
<div>
<h1>Play Checkers</h1>
<button onClick={() => startGame('matchmaking')} disabled={loading}>Find opponent</button>
<button onClick={() => startGame('bot')} disabled={loading}>vs Bot</button>
</div>
);
}4
Create the game page
๐ src/pages/checkers/game/[sessionId].tsx
import { useEffect, useState } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import { BetaGamerProvider } from '@beta-gamer/react';
import { CheckersRoom } from '@/components/checkers/CheckersRoom';
export default function CheckersGamePage() {
const { sessionId } = useParams<{ sessionId: string }>();
const token = useSearchParams().get('token');
const [status, setStatus] = useState<'checking' | 'ok' | 'ended'>('checking');
useEffect(() => {
if (!token) { setStatus('ended'); return; }
fetch(`/api/v1/sessions/validate?token=${token}`)
.then(r => r.json())
.then(d => setStatus(d.status === 'ended' ? 'ended' : 'ok'))
.catch(() => setStatus('ok'));
}, [token]);
if (status === 'checking') return <p>Loadingโฆ</p>;
if (status === 'ended') return <div><p>Session ended.</p><a href="/checkers/lobby">Play again</a></div>;
return (
<BetaGamerProvider token={token!} serverUrl="https://api.beta-gamer.com">
<CheckersRoom sessionId={sessionId} onLeave={() => window.location.href = '/checkers/lobby'} />
</BetaGamerProvider>
);
}5
Create the CheckersRoom component
๐ src/components/checkers/CheckersRoom.tsx
'use client';
import { useEffect, useRef, useState } from 'react';
import { useSocket, useSession } from '@beta-gamer/react';
interface Props { sessionId: string; onLeave: () => void; }
export function CheckersRoom({ sessionId, onLeave }: Props) {
const socket = useSocket();
const session = useSession();
const myPlayerId = session.players[0]?.id ?? '';
const roomIdRef = useRef('');
const [board, setBoard] = useState<any[]>(Array(64).fill(null));
const [myColor, setMyColor] = useState<'red' | 'black'>('red');
const [currentTurn, setCurrentTurn] = useState(0);
const [players, setPlayers] = useState<any[]>([]);
const [validMoves, setValidMoves] = useState<number[]>([]);
const [selectedSquare, setSelectedSquare] = useState<number | null>(null);
const [gameResult, setGameResult] = useState<{ winner: string | null; reason: string } | null>(null);
useEffect(() => {
if (!socket) return;
const join = () => socket.emit('matchmaking:join', {
username: session.players[0]?.displayName,
playerId: myPlayerId,
sessionId,
});
if (socket.connected) join(); else socket.once('connect', join);
socket.on('game:started', (d: any) => {
roomIdRef.current = d.roomId;
setMyColor(d.color);
setBoard(d.board);
setPlayers(d.players);
setCurrentTurn(d.currentTurn);
});
socket.on('game:valid_moves', ({ moves }: { from: number; moves: number[] }) => {
setValidMoves(moves);
});
socket.on('game:move:made', (d: any) => {
setBoard(d.board);
setCurrentTurn(d.currentTurn);
setValidMoves([]);
setSelectedSquare(null);
});
socket.on('game:over', (d: any) => {
setGameResult({ winner: d.winner ?? null, reason: d.reason });
});
return () => {
socket.off('connect', join);
socket.off('game:started');
socket.off('game:valid_moves');
socket.off('game:move:made');
socket.off('game:over');
};
}, [socket]);
const isMyTurn = players[currentTurn]?.id === myPlayerId;
const selectPiece = (square: number) => {
if (!isMyTurn || gameResult) return;
setSelectedSquare(square);
socket?.emit('game:get_moves', { roomId: roomIdRef.current, from: square });
};
const movePiece = (to: number) => {
if (selectedSquare === null) return;
socket?.emit('game:move', {
roomId: roomIdRef.current,
playerId: myPlayerId,
move: { from: selectedSquare, to },
});
};
return (
<div>
{/* Render 8x8 board using board[], validMoves, selectedSquare */}
{/* Call selectPiece(squareIndex) on piece click */}
{/* Call movePiece(squareIndex) on valid destination click */}
<p>{isMyTurn ? 'Your turn' : "Opponent's turn"}</p>
{gameResult && <p>Game over: {gameResult.reason}</p>}
<button onClick={() => socket?.emit('game:resign', { roomId: roomIdRef.current, playerId: myPlayerId })}>Resign</button>
<button onClick={onLeave}>Leave</button>
</div>
);
}Full event payload reference โ Checkers socket events
Beta Gamer GaaS API โ questions? support@beta-gamer.com