forked from elektricM/collaborative-pixel-art
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
69 lines (59 loc) · 2.16 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// server.js
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const fs = require('fs');
const initialPixelColor = '#FFFFFF'; // Default color: White
const canvasWidth = 200;
const canvasHeight = 200;
let pixels = new Array(canvasWidth * canvasHeight).fill(initialPixelColor);
let totalPixelsPlaced = 0; // Counter for total pixels placed by everyone
// Function to save the canvas data to a JSON file
function saveCanvasToJSON() {
const data = JSON.stringify(pixels);
fs.writeFileSync('canvas_data.json', data, 'utf8', (err) => {
if (err) {
console.error('Error saving canvas data:', err);
}
});
}
// 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');
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();
}
} catch (err) {
console.error('Error loading canvas data:', err);
}
}
app.use(express.static(__dirname + '/public'));
io.on('connection', (socket) => {
// Send the initial pixel data to the connected client
socket.emit('initPixels', pixels);
// Send the total pixels count to the connected client
socket.emit('totalPixelsCount', totalPixelsPlaced);
socket.on('placePixel', (index, color) => {
// Update the pixel color in the array
pixels[index] = color;
// Broadcast the updated pixel color to all clients
io.emit('updatePixel', index, color);
// Increment the total pixels counter when a pixel is placed
totalPixelsPlaced++;
// Broadcast the updated total count to all clients
io.emit('totalPixelsCount', totalPixelsPlaced);
// Save the updated canvas data to the JSON file
saveCanvasToJSON();
});
});
http.listen(3000, () => {
console.log('Server started on http://localhost:3000');
// Load the canvas data from the JSON file when the server starts
loadCanvasFromJSON();
});