From 8e5b67b5e8c531686f6a7081e4fa2f0e235ea9b4 Mon Sep 17 00:00:00 2001 From: ElektricM Date: Fri, 21 Jul 2023 23:31:11 +0200 Subject: [PATCH] working version with the cookie fixed --- public/script.js | 9 +++++---- server.js | 11 +++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/public/script.js b/public/script.js index 8f043d2..0dd1b17 100644 --- a/public/script.js +++ b/public/script.js @@ -67,7 +67,7 @@ function updatePixel(index, color) { } // Function to update the pixel count display -function updatePixelCount(totalPixelsPlaced) { +function updatePixelCount() { const pixelCountElement = document.getElementById('pixel-count'); pixelCountElement.textContent = `Total Pixels: ${totalPixelsPlaced}, Your Pixels: ${yourPixelsPlaced}`; } @@ -94,7 +94,7 @@ canvasDiv.addEventListener('click', (event) => { // Increment yourPixelsPlaced when you place a pixel yourPixelsPlaced++; - updatePixelCount(totalPixelsPlaced); + updatePixelCount(); // Save yourPixelsPlaced value to the cookie setCookie('yourPixelsPlaced', yourPixelsPlaced, 365); // Cookie expires in 365 days } @@ -107,8 +107,9 @@ socket.on('updatePixel', (index, color) => { // Receive the total pixels count from the server socket.on('totalPixelsCount', (count) => { - updatePixelCount(count); + totalPixelsPlaced = count; + updatePixelCount(); }); createCanvas(); -updatePixelCount(0); // Call to initialize the pixel count display with 0 +updatePixelCount(); // Call to initialize the pixel count display diff --git a/server.js b/server.js index a09dc66..7b446c9 100644 --- a/server.js +++ b/server.js @@ -11,9 +11,9 @@ const canvasHeight = 50; let pixels = new Array(canvasWidth * canvasHeight).fill(initialPixelColor); let totalPixelsPlaced = 0; // Counter for total pixels placed by everyone -// Function to save the canvas data and the total number of pixels placed to a JSON file +// Function to save the canvas data to a JSON file function saveCanvasToJSON() { - const data = JSON.stringify({ pixels, totalPixelsPlaced }); + const data = JSON.stringify(pixels); fs.writeFileSync('canvas_data.json', data, 'utf8', (err) => { if (err) { console.error('Error saving canvas data:', err); @@ -21,14 +21,13 @@ function saveCanvasToJSON() { }); } -// Function to load the canvas data and the total number of pixels placed from the JSON file +// Function to load the canvas data from the JSON file function loadCanvasFromJSON() { try { if (fs.existsSync('canvas_data.json')) { const data = fs.readFileSync('canvas_data.json', 'utf8'); - const jsonData = JSON.parse(data); - pixels = jsonData.pixels; - totalPixelsPlaced = jsonData.totalPixelsPlaced; + pixels = JSON.parse(data); + totalPixelsPlaced = pixels.filter(color => color !== initialPixelColor).length; } else { // If the file does not exist, create a new one with default pixel data saveCanvasToJSON();