React hooks for connecting guests to a host via WebRTC.
Peer Party uses WebRTC and a common set of game rules to host and share a multiplayer game with freinds, all without the use of a server. Guest can emit valid game moves to the host and the host will broadcast what moves have been made by whom.
npm install --save @compendium/peer-party
import React from 'react'
import { usePartyGuest, usePartyHost } from '@compendium/peer-party'
const MyGamesRules = {
makeGuestMove: ({ state }) => ({ ...state, title: "Guests are better" })
makeHostMove: ({ state }) => ({ ...state, title: "Host is best" })
}
const GuestComponent = ({ roomId }) => {
const { state, moves } = usePartyGuest({ roomId, game: MyGamesRules });
return (
<div>
<h1>{state.title}</h1>
<button onClick={() => moves.makeGuestMove()}>
Click Me
</button>
</div>
);
}
const HostComponent = ({ roomId }) => {
const { state, moves } = usePartyHost({ roomId, game: MyGameRules });
return (
<div>
<h1>{state.title}</h1>
<button onClick={() => moves.makeHostMove()}>
Click Me
</button>
</div>
);
}
All guests using the list of events generate their own local state by applying the deterministic move functions to a state. This prevents the host having to send large amounts of data to guests over the network, whilst maintaining a reactive experience and allowing guests to preempt the game state after making their move locally.
Randomness is handled using seeded random number generators.
Secret states are handled on the host, which sends a patch (diffs) to each guest, which they apply to their local state.
UNLICENSED © James O'Toole
A React hook that, provided the game rules and a shared room identifier, returns the host's state representation and an object with moves to call on the host's user action.
A higher order function to provide random
, a random number generator, to a move defintion.
withRandom(({ random, state }) => {
const isHeads = random() > 0.5;
return ({ ...state, isHeads })
})
A game move definition, which will require randomness
A random move definition
A higher order function to provide contextId
and revealASecret
, enabling the move
to return a different state for different peers.
withSecret(({ contextId, hostId, revealSecret, state }) => {
const isHostContext = hostId === contextId
if (isHostContext) {
return ({ ...state, deck: state.deck.slice(1) })
} else {
const topCardOfDeck = revealSecret(hostId, s => s.deck[0])
return ({ ...state, revealedCard: topCardOfDeck })
}
})
A move defition that needs to be secretive
A move defintion with context awareness and access to secret state
Generated using TypeDoc
A React hook that, provided the game rules and a shared room identifier, returns the guest's state representation and an object with moves to call on the guest's user action.