import { players } from './state' ; import { World } from './world' ; import { SocketServer } from './server' ; export namespace Router { export let world ; export let server ; let messageMap = { "player_interaction" : reciveInteraction , "init_game_state" : initPlayer , "ping" : sendPong , } ; export function routeMessage ( msg , client , playerId ) { if ( messageMap [ msg . type ] !== undefined ) { messageMap [ msg . type ] ( msg . msg , playerId , client , msg . origin , msg . id ) ; } } function sendPong ( data , playerId , client , origin , requestId ) { client . send ( JSON . stringify ( { ts : data , origin , id : requestId } ) ) ; } function reciveInteraction ( data , playerId ) { world . applyMovment ( playerId , data ) ; } function initPlayer ( data , playerId , client , origin , requestId ) { playerId = createID ( ) ; world . createPlayer ( playerId , data . name ) ; client . send ( JSON . stringify ( { players , playerId , origin , id : requestId } ) ) ; server . setPlayerId ( client , playerId ) ; } export function updateWorld ( ) { let msg = { type : "update" , players : players } ; server . broadCast ( JSON . stringify ( msg ) ) ; } export function removePlayer ( key ) { let msg = { type : "remove_player" , key : key } ; server . broadCast ( JSON . stringify ( msg ) ) ; } function createID ( ) { return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' . replace ( /[xy]/g , function ( c ) { var r = Math . random ( ) * 16 | 0 , v = c == 'x' ? r : ( r & 0x3 | 0x8 ) ; return v . toString ( 16 ) ; } ) ; } }