@lobstar/preact
Version:
A collection of Preact hooks to use Lobstar library for network and lobby management for multiplayer web games
64 lines (63 loc) • 2.2 kB
JavaScript
import { useMemo } from "preact/hooks";
import { SESSION_STATES } from "@lobstar/core";
import { useGameSession } from "./useGameSession";
import { useSessionState } from "./useSessionState";
import { usePlayers } from "./usePlayers";
import { useGameEvents } from "./useGameEvents";
/**
* Main hook that provides a complete interface to the game session
*/
export function useGameLobby(lobbyOptions = {}) {
const { options, onMessage, onError, onKicked } = lobbyOptions;
const { session, host, join, leave, setReady, startGame, endGame, kickPlayer, sendMessage, sendMessageToHost, broadcastMessage, } = useGameSession(options);
const state = useSessionState(session);
const { areAllPlayersReady, host: hostPlayer, isHost, playersList, self, } = usePlayers(session);
useGameEvents(session, onMessage, onError, onKicked);
// Computed values
const isConnected = useMemo(() => {
return (state !== SESSION_STATES.DISCONNECTED &&
state !== SESSION_STATES.CONNECTING &&
state !== SESSION_STATES.ERROR);
}, [state]);
const isPlaying = useMemo(() => {
return state === SESSION_STATES.PLAYING;
}, [state]);
const isInLobby = useMemo(() => {
return state === SESSION_STATES.LOBBY;
}, [state]);
const isGameOver = useMemo(() => {
return state === SESSION_STATES.GAME_OVER;
}, [state]);
const maxPlayers = useMemo(() => {
// Provides a fallback if session is null during initial render
return session?.getMaxPlayers() || options?.maxPlayers || 0;
}, [session, options?.maxPlayers]);
return {
// Session methods
host,
join,
leave,
setReady,
startGame,
endGame,
kickPlayer,
sendMessage,
sendMessageToHost,
broadcastMessage,
// Session state
state,
isConnected,
isPlaying,
isInLobby,
isGameOver,
// Players info
areAllPlayersReady,
playersList,
self,
hostPlayer,
isHost,
maxPlayers,
// Raw lobstar game session access (for advanced use cases)
session,
};
}