forked from gabrielecirulli/2048
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
115 lines (95 loc) · 2.51 KB
/
app.js
File metadata and controls
115 lines (95 loc) · 2.51 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
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
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server)
, game = require('./private/game');
// serve public folder
app.use(express.static(__dirname + '/public'));
// listen on port
var port = 3000;
server.listen(port);
// setup game
var nextUserId = 0;
var moveCount = 0;
var voted = false;
var idsVoted = []; // keep track of which users have voted
var votes = [0, 0, 0, 0]
// start with a new state on server-side
game.restart();
// pick the most selected direction
setInterval(function() {
direction = democracy(votes);
if (direction === -1) {
return;
} else {
moveCount++;
game.move(direction)
var data = {
gameState: game.getState(),
direction: direction,
userId: "crowd",
numUsers: Object.keys(io.sockets.manager.connected).length,
};
io.sockets.emit('move', data);
if (data.gameState.over || data.gameState.won) {
game.restart();
}
}
// reset direction votes
userMoves = {};
idsVoted = [];
votes = [0, 0, 0, 0];
voted = false;
}, 1000);
// when a new client connects
io.sockets.on('connection', function(socket) {
socket.userId = ++nextUserId;
var numUsers = Object.keys(io.sockets.manager.connected).length;
console.log("game state: " + game.getState());
var data = {
gameState: game.getState(),
userId: socket.userId,
numUsers: numUsers,
};
socket.emit('connected', data);
socket.broadcast.emit('join', data);
socket.on('sendMove', function (data) {
console.log(data);
if (!voted) {
voted = true;
votes[data.direction]++;
// send move with old game state
var state = game.getState();
var data = {
gameState: state,
direction: direction,
userId: socket.userId,
numUsers: Object.keys(io.sockets.manager.connected).length,
};
io.sockets.emit('move', data);
}
});
socket.on('disconnect', function() {
var numUsers = Object.keys(io.sockets.manager.connected).length;
var data = {
gameState: game.getState(),
numUsers: numUsers,
};
// update userCount on client side
io.sockets.emit('join', data);
});
});
// calculate which direction had the most votes
function democracy(votes) {
var direction = 0;
for (var i=0; i < votes.length; i++) {
if (votes[i] > votes[direction]) {
direction = i;
}
}
if (votes[direction] == 0) {
return -1;
}
return direction;
}