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(200, 500) entity1.radius = 50 game.spawn_entity(entity1) const entity2 = new Entity() entity2.id = '2' entity2.teleport(110, 110) entity2.radius = 50 game.spawn_entity(entity2) const horseshoe = new Terrain([ { x: 400, y: 200 }, { x: 600, y: 200 }, { x: 700, y: 300 }, { x: 650, y: 600 }, { x: 400, y: 600 }, { x: 400, y: 450 }, { x: 600, y: 500 }, { x: 600, y: 300 }, { x: 400, y: 300 }, ]) horseshoe.id = 'horseshoe' game.add_terrain(horseshoe) const stopsign = new Terrain([ { x: 800, y: 800 }, { x: 900, y: 900 }, { x: 900, y: 1000 }, { x: 800, y: 1100 }, { x: 800, y: 1100 }, { x: 700, y: 1100 }, { x: 600, y: 1000 }, { x: 600, y: 900 }, { x: 700, y: 800 }, ]) stopsign.id = 'stopsign' game.add_terrain(stopsign) const box = new Terrain([ { x: 1200, y: 700 }, { x: 1200, y: 800 }, { x: 1300, y: 800 }, { x: 1300, y: 700 }, ]) box.id = 'box' game.add_terrain(box) const diamond = new Terrain([ { x: 1000, y: 300 }, { x: 1100, y: 400 }, { x: 1000, y: 500 }, { x: 900, y: 400 }, ]) diamond.id = 'diamond' game.add_terrain(diamond) const pole = new Terrain([ { x: 400, y: 1000 }, { x: 410, y: 1000 }, { x: 410, y: 1010 }, { x: 400, y: 1010 }, ]) pole.id = 'pole' game.add_terrain(pole) game.start() })