working version with the cookie fixed

This commit is contained in:
ElektricM 2023-07-21 23:31:11 +02:00
commit 8e5b67b5e8
2 changed files with 10 additions and 10 deletions

View file

@ -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

View file

@ -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();