pixelbattle/index.js

80 lines
2.3 KiB
JavaScript
Raw Normal View History

const WebSocket = require('ws');
const express = require('express')
const http = express()
const config = require("./settings.json");
const httpPort = config.httpPort
const appPort = config.appPort
var board = new Array(config.boardHeight * config.boardWidth * 4);
2023-07-31 20:46:04 +03:00
board.fill(255);
const server = new WebSocket.Server({
port: appPort
});
let clients = [];
const evaulatePixelNumber = (x, y) => {
let pixelNumber;
if (y > 0)
pixelNumber = (y) * config.boardWidth + x
if (y == 0)
pixelNumber = x
return pixelNumber
}
server.on('connection', function(client) {
clients.push(client);
// When you receive a message, send that message to every socket.
client.on('message', function(msg) {
2023-07-31 20:46:04 +03:00
let packet, content, code;
try {
packet = JSON.parse(msg.toString());
content = packet.content
code = packet.code
} catch (e) {console.log(e)}
2023-07-31 20:46:04 +03:00
console.log(packet)
let response = {};
switch(code) {
case 0:
response.code = 0;
response.content = board;
client.send(Buffer.from(JSON.stringify(response)));
break;
case 1:
response.code = 1;
response.content = content;
console.log(`response content ${response.content}`)
contentJson = JSON.parse(content);
2023-07-31 20:46:04 +03:00
let pixelNumber = evaulatePixelNumber(contentJson.x * 4, contentJson.y * 4);
if (contentJson.x < 0 || contentJson.y < 0) {
break;
}
2023-07-31 20:46:04 +03:00
board[pixelNumber + 0] = contentJson.r;
board[pixelNumber + 1] = contentJson.g;
board[pixelNumber + 2] = contentJson.b;
board[pixelNumber + 3] = 255;
clients.forEach(c => c.send(Buffer.from(JSON.stringify(response))));
break;
default:
console.log("Packet cannot be understood: ", packet);
client.send("{\"code\":-1}")
}
// clients.forEach(s => s.send(msg));
});
// When a socket closes, or disconnects, remove it from the array.
client.on('close', function() {
clients = clients.filter(s => s !== client);
});
});
http.get('/', (req, res) => {
res.sendFile('html/index.html', {root: __dirname })
})
http.listen(httpPort, () => {
console.log(`Starting pixelbattle http server on port ${httpPort}`)
})