puzzle/game/Communication.js

42 lines
909 B
JavaScript
Raw Normal View History

2020-11-09 01:54:05 +01:00
import WsClient from './WsClient.js'
2020-11-12 19:19:02 +01:00
const EV_SERVER_STATE_CHANGED = 1
const EV_SERVER_INIT = 4
const EV_CLIENT_MOUSE = 2
const EV_CLIENT_INIT = 3
2020-11-09 01:54:05 +01:00
let conn
let changesCallback = () => {}
function onChanges(callback) {
changesCallback = callback
}
function connect(gameId, playerId) {
conn = new WsClient(WS_ADDRESS, playerId + '|' + gameId)
return new Promise(r => {
conn.connect()
2020-11-12 19:19:02 +01:00
conn.send(JSON.stringify([EV_CLIENT_INIT]))
2020-11-09 01:54:05 +01:00
conn.onSocket('message', async ({ data }) => {
2020-11-12 19:19:02 +01:00
const [type, typeData] = JSON.parse(data)
if (type === EV_SERVER_INIT) {
const game = typeData
r(game)
} else if (type === EV_SERVER_STATE_CHANGED) {
const changes = typeData
changesCallback(changes)
2020-11-09 01:54:05 +01:00
}
})
})
}
2020-11-12 19:19:02 +01:00
function addMouse(mouse) {
conn.send(JSON.stringify([EV_CLIENT_MOUSE, mouse]))
2020-11-09 01:54:05 +01:00
}
export default {
connect,
onChanges,
2020-11-12 19:19:02 +01:00
addMouse,
2020-11-09 01:54:05 +01:00
}