import express from 'express' import { WebSocketExpress } from 'websocket-express' import Game from './game.js' import Entity from './entity.js' import Terrain from './terrain.js' const app = new WebSocketExpress() const port = 1280 const game = new Game() app.use('/', express.static('public')) app.use('/three/', express.static('node_modules/three')) app.use(express.urlencoded({ extended: true })) app.ws('/ws', async (req, res) => { const websocket = await res.accept() const subscription = () => websocket.send(JSON.stringify(game.state())) game.eventEmitter.on('tick', subscription) websocket.on('close', () => { game.eventEmitter.removeListener('tick', subscription) }) websocket.on('message', (rawData) => { const message = JSON.parse(rawData) const entity = message.id != null ? game.entities.find((e) => e.id == message.id) : null console.log(message) if (message.action == 'teleport') { entity.teleport(message.x, message.y) } if (message.action == 'move') { entity.moveAction(message.x, message.y) } }) }) app.listen(port, () => { console.log(`Server started! Visit http://localhost:${port}`) const entity1 = new Entity() entity1.id = '1' entity1.teleport(350, 500) entity1.radius = 50 game.spawn_entity(entity1) const entity2 = new Entity() entity2.id = '2' entity2.teleport(800, 100) entity2.radius = 35 game.spawn_entity(entity2) const vertices = [ { x: 400, y: 400 }, { x: 600, y: 400 }, { x: 600, y: 600 }, { x: 400, y: 600 }, ] const terrain1 = new Terrain(vertices) terrain1.id = 'a' game.add_terrain(terrain1) game.start() })