From d227202cb913aad5304fa1799b3b9da4641b45fc Mon Sep 17 00:00:00 2001 From: leca Date: Tue, 1 Aug 2023 11:53:03 +0300 Subject: [PATCH] board can now be loaded --- README.md | 2 +- index.js | 33 +++++++++++++++++++++++++-------- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 33b908f..6c3acfc 100644 --- a/README.md +++ b/README.md @@ -19,5 +19,5 @@ That's it! 1. Server settings are located in `./settings.json`, you need to change serverAddress in order to deploy -2. When catches SIGUSR1, server will save a board with name read from settings file. SIGINT (CTRL + C) does the same but exit server when board is saved +2. When catches SIGUSR1, server will save a board with name read from settings file. SIGINT (CTRL + C) does the same but exit server when board is saved **KILL WITH SIGTERM WILL NOT SAVE THE BOARD!** diff --git a/index.js b/index.js index 98395ed..6dbeb04 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ const http = express(); const path = require('path'); const pug = require('pug'); const Jimp = require('jimp'); +const fs = require('fs'); http.use(express.static(path.join(__dirname, 'html'))); http.set('view engine', 'pug'); @@ -19,7 +20,30 @@ const boardHeight = config.boardHeight; var toQuit = false; var board = new Array(boardWidth * boardHeight * 4); -board.fill(255); + +if (!fs.existsSync(saveFile)) { + console.log("No save file found, creating blank board."); + board.fill(255); +} else { + console.log("Save file found, loading") + let image = Jimp.read(`./${saveFile}`, (err, image) => { + for (let x = 0; x < boardWidth; x ++) { + for (let y = 0; y < boardHeight; y ++) { + pixelNumber = evaulatePixelNumber(x * 4, y * 4); + let pixel = Jimp.intToRGBA(image.getPixelColor(x, y)) + board[pixelNumber + 0] = pixel.r + board[pixelNumber + 1] = pixel.g + board[pixelNumber + 2] = pixel.b + board[pixelNumber + 3] = 255; + } + } + console.log("Loaded") + }); + +} + + + const server = new WebSocket.Server({ port: appPort @@ -88,13 +112,6 @@ http.listen(httpPort, "0.0.0.0", () => { console.log(`Starting pixelbattle http server on port ${httpPort}`); }) -const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => { - const hex = x.toString(16) - return hex.length === 1 ? '0' + hex : hex -}).join('') - -function d2h(d) { return (+d).toString(16).toUpperCase(); } - const save = (err, image) => { if (err) throw err; console.log()