-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.js
More file actions
87 lines (80 loc) · 2.35 KB
/
app.js
File metadata and controls
87 lines (80 loc) · 2.35 KB
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
var express=require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongojs = require('mongojs'),
db = mongojs("InSecurity", ['defender', 'attacker']);
console.log("test");
app.use(express.static(__dirname+"/static"));
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(req, res) {
res.redirect('/index.html');
});
app.post('/api/attacker', function(req, res) {
db.collection('attacker').find(req.params, function(err, docs) {
if(docs.length==0) {
req.params.frequency = 1;
db.collection('attacker').save(req.params);
}
else {
db.collection('attacker').update(req.params, {$inc : {"frequency" : 1}});
}
});
res.send(200);
});
app.post('/api/defender', function(req, res) {
db.collection('defender').find(req.body, function(err, docs) {
if(docs.length==0) {
req.body.frequency = 1;
db.collection('defender').save(req.body);
}
else {
db.collection('defender').update(req.body, {$inc : {"frequency" : 1}});
}
});
res.send(200);
});
var attackers = {};
var defenders = {};
io.sockets.on('connection', function(socket) {
console.log("Someone connected");
socket.on('chooseDefender', function(id, room) {
console.log("Someone choose a defender");
if(attackers[room] && attackers[room].length!=0) {
var attacker = attackers[room].pop();
socket.emit("foundPartner", attacker.id);
}
else {
if(!defenders[room]) defenders[room] = [];
defenders[room].push({"id" : id, "connection" : socket});
}
});
socket.on('chooseAttacker', function(id, room) {
console.log("Someone choose an attacker");
//if there are already defenders, send both players the other players id
if(defenders[room] && defenders[room].length!=0) {
var defender = defenders[room].pop();
defender.connection.emit("foundPartner", id);
}
//otherwise add them to a waiting list
else {
if(!attackers[room]) attackers[room]=[];
attackers[room].push({"id" : id, "connection" : socket});
}
});
socket.on('disconnect', function() {
//remove any people who disconnect before finding a partner
for(var i=0; i<defenders.length; i++) {
if(defenders[i].connection===socket) {
defenders.splice(i,1);
}
}
for(var i=0; i<attackers.length; i++) {
if(attackers[i].connection===socket) {
attackers.splice(i,1);
}
}
});
});
server.listen(3002);