-
Notifications
You must be signed in to change notification settings - Fork 0
/
pictionary.js
397 lines (333 loc) · 12.1 KB
/
pictionary.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
var _u = require('underscore'),
Backbone = require('backbone'),
PlayersCollection = require('./player.js'),
wordBase = require('./wordbase/wordbase.js'),
TURN_DURATION = 120000,
TURN_BREAK_DURATION = 5000,
GameStatusEnum = {
NOT_STARTED : 0,
IN_PROGRESS : 1,
FINISHED : 2
},
GameModel = Backbone.Model.extend({
initialize: function () {
var time = (new Date()).getTime(); // arbitrary id so that isNew
// is false on client side when
// saving.
this.set({
'id': 'lobby:game',
'players': new PlayersCollection(),
'gameStatus': new Backbone.Model({ 'turnDuration': TURN_DURATION,
'warmupDuration': TURN_BREAK_DURATION,
'id': 'lobby:gameStatus' })
});
}
}),
Pictionary = {
initialize: function () {
_u.bindAll(this);
_u.extend(this, Backbone.Events);
this.model = new GameModel();
return this;
},
// For each incoming path, store in userPaths keyed by socket.id
// Once mouseup event comes in, move path from userPaths to allPaths
// (only one path in userPaths[socketid] at a time)
// On clearBoard event, remove userPaths and allPaths
// Holds arrays of PaperJS Points, keyed by socket.id
// Used primarily for freeDraw
userPaths: {},
// Array of arrays of PaperJS Points
// (Array of Paths)
allPaths: [],
wordBase: wordBase,
turn_duration: TURN_DURATION,
turn_break_duration: TURN_BREAK_DURATION,
userColors: {},
// Override
// TODO: Need to distinguish between system messages and
// user-generated messages
setChat: function (chat) {
this.chatController = chat;
this.chatController.bind('newMessage', this.doCheckGuesses);
return this;
},
doCheckGuesses: function (o) {
var messageModel = o.message,
currArtistId = this.model.get('players').getCurrentArtist();
if (!currArtistId) { return; }
// filter out any "guesses" from the artist
if (messageModel.sender !== currArtistId) {
correctGuess = this.wordBase.checkGuesses(messageModel);
if (correctGuess) {
// handle on chat side
o.callback(correctGuess, o.socket);
this.io.emit('notifyCorrectGuess');
this.sendNextWord();
}
}
},
sendNextWord: function () {
var nextWord = this.wordBase.getUnusedWord(),
playersModel = this.model.get('players'),
currArtistId = playersModel.getCurrentArtist();
// Send currArtist the next word.
this.io.socket(currArtistId).emit('wordToDraw', nextWord);
},
// Start the actual turn for the artist.
startNextTurn: function () {
var model = this.model;
gameStatusModel = model.get('gameStatus'),
currArtist = model.get('players').getCurrentArtist(),
date = new Date(),
turnStart = date.getTime() + date.getTimezoneOffset(),
newStatus = { 'currArtist': currArtist,
'turnStart': turnStart };
gameStatusModel.set(newStatus);
this.io.emit('gameStatusUpdate', newStatus);
this.sendNextWord();
//this.turnInterval = setInterval(this.doTurnInterval, 1000);
this.turnTimeout = setTimeout(this.startNextWarmUpAndTurn, this.turn_duration);
},
// Starts the next turn, buffered by 5 seconds to
// allow the players to prepare.
startNextWarmUpAndTurn: function () {
var players = this.model.get('players'),
nextArtist;
if (players.hasNextArtist()) {
nextArtist = players.getNextArtist();
this.io.emit('nextUp', { 'currArtist': nextArtist }); // send the warm-up message
setTimeout(this.startNextTurn, this.turn_break_duration);
}
else {
// No more artists, signal end of round.
this.handleGameFinish();
}
},
handleGameStart: function (o, socket) {
this.model.get('players').decideArtistOrder();
// Clear cached paths
this.userPaths = {};
this.allPaths = [];
socket.broadcast.emit('gameStatusUpdate', { 'gameStatus': GameStatusEnum.IN_PROGRESS });
this.startNextWarmUpAndTurn();
},
handleGameFinish: function (o) {
var gameStatusModel = this.model.get('gameStatus'),
newStatus = { 'gameStatus': GameStatusEnum.FINISHED,
'currArtist': -1,
'turnStart': 0 };
gameStatusModel.set(newStatus);
if (this.turnTimeout) {
clearTimeout(this.turnTimeout);
}
this.io.emit('gameStatusUpdate', newStatus);
this.clearCachedPaths();
},
// Start or finish game.
handleGameStatus: function (model, socket) {
var gameStatusModel = this.model.get('gameStatus');
if (typeof model.gameStatus !== 'undefined' &&
model.gameStatus !== gameStatusModel.get('gameStatus')) {
gameStatusModel.set({ 'gameStatus': model.gameStatus });
if (model.gameStatus === GameStatusEnum.IN_PROGRESS) {
this.handleGameStart(model, socket);
}
else if (model.gameStatus === GameStatusEnum.FINISHED) {
this.handleGameFinish(model);
}
}
if (typeof model.freeDrawEnabled !== undefined &&
gameStatusModel.get('freeDrawEnabled') !== model.freeDrawEnabled) {
// Free draw value has been changed. Update everyone.
gameStatusModel.set({ 'freeDrawEnabled': model.freeDrawEnabled });
socket.broadcast.emit( 'toggleFreeDraw', { freeDrawEnabled: model.freeDrawEnabled });
}
},
handleDisconnect: function (socket) {
var id = socket.id,
players = this.model.get('players'),
player = players.get(id),
wasLeader = player.get('isLeader'),
currArtist = this.model.get('players').getCurrentArtist(),
newLeader;
// Remove player from players array
players.remove(player);
if (!players.length) {
// No one is left in the room. =(
if (this.turnTimeout) {
clearTimeout(this.turnTimeout);
}
this.handleGameFinish();
return;
}
// If player was leader, reassign leader
if (wasLeader && players.length) {
newLeader = players.at(0);
newLeader.set({ 'isLeader': true });
}
socket.broadcast.emit('playerDisconnect', { 'id': id, 'newLeaderId': newLeader ? newLeader.id : 0 });
// If player was currArtist, begin new turn
if (currArtist === id && this.model.get('gameStatus').get('gameStatus') === GameStatusEnum.IN_PROGRESS) {
// Prevent race condition by clearing original timeout.
if (this.turnTimeout) {
clearTimeout(this.turnTimeout);
}
this.startNextWarmUpAndTurn();
}
},
// Create the data to pass to a newly connected player
createInitPlayerInfo: function (id) {
var players = this.model.get('players'),
name = 'Player ' + id,
isLeader = !players.length; // first player defaults to leader
return { 'id': id,
'name': name,
'isLeader': isLeader };
},
getUserColor: function (socketid) {
if (this.userColors[socketid]) {
return this.userColors[socketid];
}
return '#000';
},
clearCachedPaths: function () {
this.userPaths = {};
this.allPaths = [];
},
create: function (data, socket) {
switch (data.modelName) {
case 'messageModel':
socket.emit(['read', data.modelName].join(':'),
{ 'model': this.model,
'initPaths': this.allPaths,
'userId': socket.id });
break;
default:
console.log('[WARNING] Did not recognize model name: ' + data.modelName);
}
},
read: function (data, socket) {
switch (data.modelName) {
case 'gameModel':
socket.emit(['read', data.modelName].join(':'),
{ 'model': this.model,
'initPaths': this.allPaths,
'userId': socket.id });
break;
default:
console.log('[WARNING] Did not recognize model name: ' + data.modelName);
}
},
update: function (data, socket) {
var sendingPlayer = this.model.get('players').get(socket.id),
player,
modelInfo = data.modelName,
modelName = modelInfo[0];
if (data.modelName === 'players') {
player = this.model.get('players').get(data.model.id);
player.set(data.model);
socket.broadcast.emit('playerUpdate', data.model);
}
else if (data.modelName === 'gameStatus') {
// Only allow leader to make changes to game status.
if (sendingPlayer.get('isLeader')) {
this.handleGameStatus(data.model, socket);
}
}
},
// Listen to Socket.io
listen: function(io) {
this.io = io.of('/game');
this.io.on('connection', (function (socket) {
var initInfo = this.createInitPlayerInfo(socket.id),
players = this.model.get('players');
players.add(initInfo);
this.chatController.broadcastNewPlayer(initInfo);
socket.broadcast.emit('newPlayer', initInfo); // Sends to everyone except for new user
// LISTENERS
socket.on('endTurn', function () {
console.log('endTurn');
});
socket.on('setName', function (name) {
socket.get('id', function (err, id) {
var player;
if (err) { console.log('[ERROR] ' + err); }
else {
player = players.get(id);
player.set({ 'name': name });
socket.json.broadcast.emit('playerUpdate', {
id: id,
name: name
});
}
});
});
socket.on('disconnect', (function () {
this.handleDisconnect(socket);
}).bind(this));
socket.on('newPoints', (function (data) {
var path, userColor = this.getUserColor(socket.id);
socket.broadcast.emit('newPoints', { 'senderId': socket.id,
'points': data,
'color': userColor });
if (!this.userPaths[socket.id]) {
this.userPaths[socket.id] = { 'color': userColor,
'points': [] };
}
path = this.userPaths[socket.id].points;
this.userPaths[socket.id].points = path.concat(data);
}).bind(this));
// Client has completed drawing a path.
socket.on('completedPath', (function (o) {
var pathObj, path;
socket.broadcast.emit('completedPath', { 'senderId': socket.id,
'points': o });
pathObj = this.userPaths[socket.id];
path = pathObj ? pathObj.points : null;
if (path && path.length) {
if (o && o.length) {
pathObj.points = path.concat(o);
}
this.allPaths.push(pathObj);
}
else if (o && o.length) {
this.allPaths.push({ 'senderId': socket.id,
'color': this.getUserColor(socket.id),
'points': o });
}
this.userPaths[socket.id] = null;
}).bind(this));
socket.on('toggleFreeDraw', (function (data) {
var gameStatusModel;
// only leader is allowed to toggle free draw.
if (socket.id === players.getLeader().get('id')) {
socket.broadcast.emit('toggleFreeDraw', data);
}
gameStatusModel = this.model.get('gameStatus');
if (gameStatusModel.get('gameStatus') !== GameStatusEnum.IN_PROGRESS) {
gameStatusModel.set(data);
}
}).bind(this));
socket.on('clearBoard', (function () {
socket.broadcast.emit('clearBoard');
this.clearCachedPaths();
}).bind(this));
socket.on('changeColor', (function (brushColor) {
this.userColors[socket.id] = brushColor;
}).bind(this));
socket.on('debug', (function () {
console.log(this.allPaths);
//console.log(this.userPaths);
}).bind(this));
// ======================
// Backbone.sync handler
// ======================
socket.on('sync', (function (data) {
this[data.method](data, socket);
}).bind(this));
}).bind(this));
return this;
}
};
module.exports = Pictionary.initialize();