puzzle/game/Communication.js

56 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-11-09 01:54:05 +01:00
import WsClient from './WsClient.js'
2020-11-17 21:46:56 +01:00
import Protocol from './../common/Protocol.js'
2020-11-09 01:54:05 +01:00
2020-11-17 21:46:56 +01:00
/** @type WsClient */
2020-11-09 01:54:05 +01:00
let conn
let changesCallback = () => {}
2020-11-17 21:46:56 +01:00
function onServerChange(callback) {
2020-11-09 01:54:05 +01:00
changesCallback = callback
}
2020-11-17 21:46:56 +01:00
function send(message) {
conn.send(JSON.stringify(message))
}
let clientSeq
let events
2020-11-17 22:34:15 +01:00
function connect(gameId, clientId) {
2020-11-17 21:46:56 +01:00
clientSeq = 0
events = {}
2020-11-17 22:34:15 +01:00
conn = new WsClient(WS_ADDRESS, clientId + '|' + gameId)
2020-11-09 01:54:05 +01:00
return new Promise(r => {
conn.connect()
2020-11-17 21:46:56 +01:00
send([Protocol.EV_CLIENT_INIT])
2020-11-09 01:54:05 +01:00
conn.onSocket('message', async ({ data }) => {
2020-11-17 21:46:56 +01:00
const msg = JSON.parse(data)
const msgType = msg[0]
if (msgType === Protocol.EV_SERVER_INIT) {
const game = msg[1]
2020-11-12 19:19:02 +01:00
r(game)
2020-11-17 21:46:56 +01:00
} else if (msgType === Protocol.EV_SERVER_EVENT) {
2020-11-17 22:34:15 +01:00
const msgClientId = msg[1]
const msgClientSeq = msg[2]
if (msgClientId === clientId && events[msgClientSeq]) {
delete events[msgClientSeq]
}
2020-11-17 21:46:56 +01:00
changesCallback(msg)
2020-11-09 01:54:05 +01:00
}
})
})
}
2020-11-17 21:46:56 +01:00
function sendClientEvent(mouse) {
// when sending event, increase number of sent events
// and add the event locally
clientSeq++;
events[clientSeq] = mouse
send([Protocol.EV_CLIENT_EVENT, clientSeq, events[clientSeq]])
2020-11-09 01:54:05 +01:00
}
export default {
connect,
2020-11-17 21:46:56 +01:00
onServerChange,
sendClientEvent,
2020-11-09 01:54:05 +01:00
}