-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
89 lines (73 loc) · 1.96 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
let SNAKES = [];
let FoodX = [];
let FoodY = [];
let ran = [];
class Snake {
constructor(id, name, snake, lambi, col) {
this.id = id;
this.name = name;
this.snake = snake;
this.lambi = lambi;
this.col = col;
}
}
const express = require('express');
const app = express();
const port = process.env.PORT || 1412;
const server = app.listen(port);
console.log(`Starting server at http://localhost:${port}`);
app.use(express.static('public'));
const socket = require('socket.io');
const io = socket(server);
setInterval(heartbeat, 30);
function heartbeat() {
io.sockets.emit('heartbeat', SNAKES);
}
io.sockets.on('connection',
function (socket) {
console.log('Connected: ' + socket.id);
socket.on('start',
function (data) {
// console.log(socket.id+" "+data.name+" "+data.mySnake+" "+data.lambi+" "+data.col);
var snake = new Snake(socket.id, data.name, data.mySnake, data.lambi, data.col);
SNAKES.push(snake);
var FOOD = {
FoodX: FoodX,
FoodY: FoodY,
ran: ran
}
io.sockets.emit('newFood', FOOD);
});
socket.on('update',
function (data) {
for (var i = 0; i < SNAKES.length; i++) {
if (socket.id == SNAKES[i].id) {
var snake = new Snake(socket.id, data.name, data.mySnake, data.lambi, data.col);
SNAKES[i] = snake;
break;
}
}
});
socket.on('foodLocation',
function (data) {
FoodX = data.x;
FoodY = data.y;
ran = data.ran;
var FOOD = {
FoodX: FoodX,
FoodY: FoodY,
ran: ran
}
io.sockets.emit('newFood', FOOD);
});
socket.on('disconnect',
function () {
console.log('Disconnected: ' + socket.id);
for (var i = 0; i < SNAKES.length; i++) {
if (socket.id == SNAKES[i].id) {
SNAKES.splice(i, 1);
break;
}
}
});
});