tome-web/client/game/useServerSocket.ts

288 lines
7.6 KiB
TypeScript
Raw Normal View History

2021-09-24 06:51:17 -04:00
import React from 'react'
import useWebSocket from 'react-use-websocket'
import assertNever from '~/common/assertNever.ts'
import { AsyncHandle, GameCommand, GameAction } from './types.ts'
2021-09-29 16:00:39 -04:00
const WS_URL = Deno.env.get("WS_URL")
2021-09-24 06:51:17 -04:00
const MY_ID = (function(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
})
})()
function shouldReconnect() {
console.log('Reconnecting...')
return true
}
// session commands
// query, join, leave, play (game command), poll
interface SessionCommandAPI {
query: () => void
join: () => void
leave: () => void
play: () => void
poll: () => void
2021-09-30 21:28:15 -04:00
ready: () => void
2021-09-24 06:51:17 -04:00
}
interface SocketMessage {
command: keyof SessionCommandAPI
// required unless command === 'query'
match_id?: string
player_id?: string
// only present if command === 'play'
game_command?: GameCommand
}
type GameSocketSessionState =
| { status: 'not-connected' }
| { status: 'connecting' }
| { status: 'finding-game' }
| { status: 'joining-game'; playerId: string; matchId: string }
2021-09-30 21:28:15 -04:00
| { status: 'pre-game'; playerId: string; matchId: string }
2021-09-24 06:51:17 -04:00
| { status: 'in-game'; playerId: string; matchId: string }
type Action =
| { type: 'open' }
| { type: 'close' }
| { type: 'find-game'; playerId: string; matchId: string }
| { type: 'join-game' }
2021-09-30 21:28:15 -04:00
| { type: 'ready-game' }
2021-09-24 06:51:17 -04:00
function reducer(state: GameSocketSessionState, action: Action): GameSocketSessionState {
switch (action.type) {
case 'open': {
if (state.status !== 'connecting') return state
return { status: 'finding-game' }
}
case 'find-game': {
if (state.status !== 'finding-game') return state
return { status: 'joining-game', matchId: action.matchId, playerId: action.playerId }
}
case 'join-game': {
if (state.status !== 'joining-game') return state
2021-09-30 21:28:15 -04:00
return { ...state, status: 'pre-game' }
}
case 'ready-game': {
if (state.status !== 'pre-game') return state
2021-09-24 06:51:17 -04:00
return { ...state, status: 'in-game' }
}
case 'close': {
return { status: 'not-connected' }
}
default: return assertNever(action)
}
}
const initialState: GameSocketSessionState = {status: 'connecting'}
2021-09-30 21:28:15 -04:00
type ServerResult =
// session command result
| 'found'
| 'joined p1'
| 'joined p2'
| 'left'
| 'played'
| 'game ready'
| 'generic error'
// poll command result
| 'Scourge joined'
| 'Scourge turn'
| 'Scourge wins'
| 'Scourge player is ready'
| 'Scourge player has left'
| 'Sentinal joined'
| 'Sentinal turn'
| 'Sentinal wins'
| 'Sentinal player is ready'
| 'Sentinal player has left'
| 'update'
interface ServerResponse {
player_id: string
match_id: string
result: ServerResult
game_result: any
}
2021-09-24 06:51:17 -04:00
interface SocketHandle {
sendGameCommand: (command: GameCommand) => void
2021-09-30 21:28:15 -04:00
sendPoll: () => void
2021-09-24 06:51:17 -04:00
}
export default function useServerSocket(
onUpdate: (action: GameAction) => void
): AsyncHandle<SocketHandle> {
const [state, dispatch] = React.useReducer(reducer, initialState)
2021-09-29 16:00:39 -04:00
/* prep socket */
2021-09-24 06:51:17 -04:00
const onMessage = React.useCallback((message: WebSocketEventMap['message']) => {
2021-09-30 21:28:15 -04:00
const data = JSON.parse(message.data) as ServerResponse
2021-09-24 06:51:17 -04:00
switch (data.result) {
case 'found': {
dispatch({
type: 'find-game',
matchId: data.match_id,
playerId: data.player_id,
})
return
}
case 'joined p1': {
onUpdate({ type: 'set-player-team', team: 1 })
dispatch ({ type: 'join-game' })
2021-09-24 06:51:17 -04:00
return
}
case 'joined p2': {
onUpdate({ type: 'set-player-team', team: 2 })
dispatch ({ type: 'join-game' })
2021-09-24 06:51:17 -04:00
return
}
2021-09-30 21:28:15 -04:00
case 'game ready': {
dispatch({ type: 'ready-game' })
return
}
case 'played': {
switch (data.game_result.result_type) {
case 'a': {
const result = data.game_result.action_result
if (result) onUpdate({
type: 'receive-cards',
cards: result.cards,
})
return
}
case 's': {
const result = data.game_result.state_result
if (result) onUpdate({
type: 'update-state',
state: {
board: result.board,
player: result.player,
2021-09-30 22:07:34 -04:00
deckSize: result.deck_size,
enemyLife: result.enemy_life,
enemyDeckSize: result.enemy_deck_size,
enemyHandSize: result.enemy_hand_size,
currentTurn: result.current_turn,
canDraw: result.can_draw,
hasDrawn: result.has_drawn,
gameStatus: result.game_status,
},
})
return
}
default: return
}
}
2021-09-30 21:28:15 -04:00
case 'update': {
2021-09-30 21:32:13 -04:00
// console.log(message)
2021-09-30 21:28:15 -04:00
return;
}
default: return;
2021-09-24 06:51:17 -04:00
}
}, [onUpdate])
const onOpen = React.useCallback(() => {
console.log('socket opened')
dispatch({type: 'open'})
}, [])
const onError = React.useCallback((event: WebSocketEventMap['error']) => {
console.error(event)
}, [])
const onClose = React.useCallback((_event: WebSocketEventMap['close']) => {
console.log('socket closed')
dispatch({type: 'close'})
}, [])
const {sendJsonMessage} = useWebSocket(
2021-09-29 16:00:39 -04:00
WS_URL,
2021-09-24 06:51:17 -04:00
{onMessage, onOpen, onError, onClose, shouldReconnect},
)
// convenient type-safe wrapper
const sendJson = React.useCallback((message: SocketMessage) => {
sendJsonMessage(message)
}, [sendJsonMessage])
const sendGameCommand = React.useCallback((gameCommand: GameCommand) => {
2021-09-24 06:51:17 -04:00
if (state.status !== 'in-game') return
sendJson({
2021-09-30 21:28:15 -04:00
player_id: state.playerId,
2021-09-24 06:51:17 -04:00
match_id: state.matchId,
command: 'play',
game_command: gameCommand,
2021-09-24 06:51:17 -04:00
})
}, [state, sendJson])
2021-09-30 21:28:15 -04:00
const sendPoll = React.useCallback(() => {
if (state.status !== 'in-game') return
sendJson({
player_id: state.playerId,
match_id: state.matchId,
command: 'poll',
})
}, [sendJson, state])
2021-09-29 16:00:39 -04:00
/* effects to push the coordinator along */
2021-09-24 06:51:17 -04:00
React.useEffect(() => {
if (state.status !== 'finding-game') return
sendJson({command: 'query', player_id: MY_ID})
}, [sendJson, state.status])
React.useEffect(() => {
if (state.status !== 'joining-game') return
sendJson({command: 'join', player_id: state.playerId, match_id: state.matchId})
}, [sendJson, state])
2021-09-30 21:28:15 -04:00
React.useEffect(() => {
if (state.status !== 'pre-game') return
2021-10-01 19:54:43 -04:00
const intervalId = setInterval(() => {
sendJson({command: 'ready', player_id: state.playerId, match_id: state.matchId})
}, 200)
return () => {
clearInterval(intervalId)
}
2021-09-30 21:28:15 -04:00
}, [sendJson, state])
React.useEffect(() => {
if (state.status !== 'in-game') return
const leaveGame = () => {
sendJson({command: 'leave', player_id: state.playerId, match_id: state.matchId})
}
addEventListener('beforeunload', leaveGame)
return () => {
removeEventListener('beforeunload', leaveGame)
}
}, [sendJson, state])
2021-09-29 16:00:39 -04:00
/* return game command handler in wrapper */
2021-09-24 06:51:17 -04:00
const handle = React.useMemo<AsyncHandle<SocketHandle>>(() => {
switch (state.status) {
case 'in-game': {
2021-09-30 21:28:15 -04:00
return {status: 'connected', handle: {sendGameCommand, sendPoll}}
2021-09-24 06:51:17 -04:00
}
case 'finding-game':
2021-09-30 21:28:15 -04:00
case 'joining-game':
case 'pre-game': {
2021-09-24 06:51:17 -04:00
return {status: 'connecting'}
}
case 'connecting':
case 'not-connected': {
return state
}
default: return assertNever(state)
}
}, [sendGameCommand])
return handle
}