-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
124 lines (95 loc) · 3 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
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var serveStatic = require('serve-static')
// Game variables
var users = [];
var isGameCountingDown = false;
var isGameInProgress = false;
var startGameTimer;
var startGameCountDown = 5;
var gameCounterRatio = 100;
var pointsLostRatio = 50;
var initialScore = 5000;
app.use(serveStatic('build', {'index': ['default.html', 'default.htm']}))
server.listen(5555, function(){
console.log('Express server listening on port ' + 5555);
});
app.get('/', function (req, res) {
res.sendFile(__dirname + '/build/index.html');
});
io.on('connection', function (socket) {
if (isGameInProgress) return;
var user = {
score: initialScore,
socket: socket
};
users.push(user);
io.emit('dint:newUserAdded', {
startGameCountDown: startGameCountDown,
usersLength: users.length
});
socket.on('disconnect', function() {
var i = users.indexOf(user);
users.splice(i, 1);
io.emit('dint:userLeft', {usersLength: users.length});
});
if (isGameCountingDown) return;
isGameCountingDown = true;
startGameTimer = setInterval(function() {
startGameCountTimer();
}, 1000);
});
function startGameCountTimer() {
startGameCountDown --;
io.emit('dint:startGameCountDown', {
startGameCountDown: startGameCountDown
});
// If the timer reaches zero - start the game
if (startGameCountDown == 0) {
isGameInProgress = true;
clearInterval(startGameTimer);
io.emit('dint:gameStarted');
startGame();
}
}
function startGame() {
var randomUser;
var gameTimer;
var gameTimerCount = 0;
function pickNewUser() {
gameTimerCount = 0;
randomUser = users[Math.floor(Math.random()*users.length)];
gameTimer = setInterval(function() {
gameCounter();
}, gameCounterRatio);
randomUser.socket.once('dint:clicked', function() {
// When a user clicks dint - remove their points
clearInterval(gameTimer);
randomUser.score = randomUser.score - (gameTimerCount * pointsLostRatio);
randomUser.socket.emit('dint:scoreUpdated', {
score: randomUser.score
});
if (randomUser.score <= 0) {
randomUser.socket.emit('dint:youLost');
setTimeout(function() {
// Should check if users is last user
if (users.length === 1) {
users[0].socket.emit('dint:youWon');
} else {
pickNewUser();
}
}, 2000);
} else {
pickNewUser();
}
});
randomUser.socket.emit('dint:itsMe');
}
function gameCounter() {
gameTimerCount ++;
console.log('counting');
}
// kick it off
pickNewUser();
}