-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·110 lines (94 loc) · 2.29 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
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser')
var data = require('./gamedata.json');
var fs = require('fs');
var gameStarted = false;
var startTime;
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
});
var io = require('socket.io')(server);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser());
app.get('/newgame', function(req, res){
gameStarted = true;
stateTime = new Date();
res.send('Be cool');
});
app.get('/gameon', function(req, res){
res.send(isGameOn());
});
app.get('/cleargame', function(req, res) {
clearData();
res.send("cleared");
});
app.get('/gamename', function (req, res) {
res.send(data.name);
});
function clearData() {
data.name = "";
data.started = "";
data.players = [];
updateGameDataToFile();
}
app.post('/addplayer', function(req, res) {
console.log(req.body);
console.log(data.players);
checkFirstPlayer(req.body.name);
addPlayer(req.body.id, req.body.name);
res.status(200).jsonp(data.started);
});
app.get('/players', function (req, res) {
res.send(data.players);
});
function checkFirstPlayer(playerName) {
if(data.players.length == 0) {
setupGame(playerName);
}
}
function setupGame(playerName) {
data.name = playerName + "'s game";
startTime = new Date();
startTime.setMinutes(startTime.getMinutes() +1);
data.started = startTime;
updateGameDataToFile();
}
function addPlayer(id, name) {
var player = {};
player.id = id;
player.name = name;
data.players.push(player);
console.log(data.players);
updateGameDataToFile();
}
function updateGameDataToFile() {
fs.writeFile('./gamedata.json',
JSON.stringify(data, null, 4),
function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to file");
}
});
}
function isGameOn() {
if(startTime && startTime != "") {
var timeOut = 1000 * 60 * 10;
var now = new Date();
if(Math.abs(now - startTime) < timeOut) {
return true;
}
}
return false;
}
io.on('connection', function (socket) {
console.log('emitting');
socket.on('shot', function (data) {
console.log('emitting 2');
console.log(data);
socket.broadcast.emit('shot', data);
});
});