-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
132 lines (102 loc) · 2.94 KB
/
app.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
var handler = function(req, res) {
if (req.url.indexOf('.jpg') > -1 || req.url.indexOf('.png') > -1){
fs.readFile(__dirname + req.url, function (err, data){
if (err) console.log("Error loading IMG file: " + err);
res.writeHead(200, { 'Content-Type' : 'image/jpg' });
res.end(data, 'binary');
});
}
if (req.url.indexOf('.css') > -1){
fs.readFile(__dirname + req.url, function (err, data){
if (err) console.log("Error loading CSS file: " + err);
res.writeHead(200, { 'Content-Type': 'text/css' });
res.end(data);
});
}
if (req.url.indexOf('.js') > -1){
fs.readFile(__dirname + req.url, function (err, data){
if (err) console.log("Error loading JS file: " + err);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(data);
});
}
if (req.url == "/" || req.url.indexOf('.html') > -1){
fs.readFile('./page.html', function (err, data) {
console.log(data);
if(err) throw err;
res.writeHead(200);
res.end(data);
});
}
};
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var Moniker = require('moniker');
var port = 3250;
app.listen(port);
/* ==================================================================== */
io.sockets.on('connection', function(socket){
var user;
socket.on('userEnters', function(data){
user = addUser(data.username);
socket.emit("userAccepted", user);
updateUsers();
});
socket.on("click", function(){
user.clicks += 4;
if (user.clicks >= winCount){
io.sockets.emit("win", { "user" : user });
}
updateUsers();
});
socket.on('disconnect', function() {
removeUser(user);
});
socket.on('startRace', function() {
if (!raceStarted){
io.sockets.emit("raceStarted");
raceStarted = true;
}
});
socket.on('restartRace', function(){
raceStarted = false;
io.sockets.emit("raceRestarted");
cleanUsers();
updateUsers();
});
});
var raceStarted = false;
var winCount = 200;
var users = [];
var globalId = 0;
var cleanUsers = function(){
for (var i = 0; i < users.length; i++){
users[i].clicks = 0;
}
};
var addUser = function(username){
var user = {
id: globalId,
name : username || Moniker.choose(),
clicks: 0
};
globalId += 1;
users.push(user);
return user;
};
var removeUser = function(user){
for (var i = 0; i < users.length; i++){
if (user.name === users[i].name){
users.splice(i, 1);
if (users.length === 0){
raceStarted = false;
}
io.sockets.emit("removeUser", user);
return;
}
}
};
var updateUsers = function(){
io.sockets.emit("updateUsers", { users : users });
};