1// One socket is one player. The server owns the world; we send intents and are 2// handed back the state to draw. 3import type { Body, Loose, Ore, Ship, Shot, System } from './sim'; 4 5export type State = { 6 you: number; 7 held: number; 8 bodies: Body[]; 9 systems: System[]; 10 loose: Loose[]; 11 ore: Ore[]; 12 shots: Shot[]; 13 players: Ship[]; 14}; 15 16// Dev: vite on :5173, game server on :8090. Prod: Caddy proxies /ws on the same 17// origin, so the page's own scheme/host is the right socket. 18const url = import.meta.env.DEV 19 ? `ws://${location.hostname}:8090/ws` 20 : `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`; 21 22export function connect(onState: (s: State) => void): { send: (msg: unknown) => void } { 23 let ws: WebSocket | null = null; 24 const open = () => { 25 ws = new WebSocket(url); 26 ws.onmessage = (e) => { 27 const m = JSON.parse(e.data); 28 if (m.t === 'state') onState(m); 29 }; 30 ws.onclose = () => setTimeout(open, 500); 31 }; 32 open(); 33 return { 34 send: (msg) => { 35 if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg)); 36 }, 37 }; 38}