-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.client.js
568 lines (489 loc) · 21.3 KB
/
game.client.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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/* Copyright (c) 2012 Sven "FuzzYspo0N" Bergström,
2013 Robert XD Hawkins
written by : http://underscorediscovery.com
written for : http://buildnewgames.com/real-time-multiplayer/
modified for collective behavior experiments on Amazon Mechanical Turk
MIT Licensed.
*/
/*
THE FOLLOWING FUNCTIONS MAY NEED TO BE CHANGED
*/
// A window global for our game root variable.
var game = {};
// A window global for our id, which we can use to look ourselves up
var my_id = null;
var my_role = null;
// Keeps track of whether player is paying attention...
var visible;
var incorrect;
var dragging;
var waiting;
client_ondisconnect = function(data) {
// Redirect to exit survey
console.log("server booted")
var URL = 'http://web.stanford.edu/~rxdh/psych254/replication_project/forms/end.html?id=' + my_id;
window.location.replace(URL);
};
/*
Note: If you add some new variable to your game that must be shared
across server and client, add it both here and the server_send_update
function in game.core.js to make sure it syncs
Explanation: This function is at the center of the problem of
networking -- everybody has different INSTANCES of the game. The
server has its own, and both players have theirs too. This can get
confusing because the server will update a variable, and the variable
of the same name won't change in the clients (because they have a
different instance of it). To make sure everybody's on the same page,
the server regularly sends news about its variables to the clients so
that they can update their variables to reflect changes.
*/
client_onserverupdate_received = function(data){
// Update client versions of variables with data received from
// server_send_update function in game.core.js
if(data.players) {
_.map(_.zip(data.players, game.players),
function(z){
z[1].id = z[0].id;
})
}
var dataNames = _.map(data.objects,
function(e){ return e.name})
var localNames = _.map(game.objects,
function(e){return e.name})
// If your objects are out-of-date (i.e. if there's a new round), update them
if (game.objects.length == 0 || !_.isEqual(dataNames, localNames)) {
game.objects = _.map(data.objects, function(obj) {
var imgObj = new Image()
imgObj.src = obj.url
// Set it up to load properly
imgObj.onload = function(){
game.ctx.drawImage(imgObj, parseInt(obj.trueX), parseInt(obj.trueY), obj.width, obj.height)
// if(my_role == "director")
drawScreen(game, game.get_player(my_id))
}
return _.extend(_.omit(obj, ['trueX', 'trueY']),
{img: imgObj, trueX : obj.trueX, trueY : obj.trueY})
})
}
// Update local object positions
_.map(game.objects, function(obj) {
data_obj = _.find(data.objects, function(o) {return o.name == obj.name})
obj.trueX = data_obj.trueX;
obj.trueY = data_obj.trueY;
})
if(data.players.length > 1)
game.get_player(my_id).message = ""
game.currentDestination = data.curr_dest;
game.scriptedInstruction = data.scriptedInstruction;
game.instructions = data.instructions
game.instructionNum = data.instructionNum;
game.game_started = data.gs;
game.players_threshold = data.pt;
game.player_count = data.pc;
// Draw all this new stuff
drawScreen(game, game.get_player(my_id))
};
// This is where clients parse socket.io messages from the server. If
// you want to add another event (labeled 'x', say), just add another
// case here, then call
// this.instance.player_host.send("s.x. <data>")
// The corresponding function where the server parses messages from
// clients, look for "server_onMessage" in game.server.js.
client_onMessage = function(data) {
var commands = data.split('.');
var command = commands[0];
var subcommand = commands[1] || null;
var commanddata = commands[2] || null;
switch(command) {
case 's': //server message
switch(subcommand) {
case 'end' :
// Redirect to exit survey
console.log("received end message...")
var URL = 'http://web.stanford.edu/~rxdh/psych254/replication_project/forms/end.html?id=' + my_id;
window.location.replace(URL); break;
case 'alert' : // Not in database, so you can't play...
alert('You did not enter an ID');
window.location.replace('http://nodejs.org'); break;
case 'join' : //join a game requested
var num_players = commanddata;
client_onjoingame(num_players, commands[3]); break;
case 'add_player' : // New player joined... Need to add them to our list.
console.log("adding player" + commanddata)
if(hidden === 'hidden') {
flashTitle("GO!")
}
game.players.push({id: commanddata, player: new game_player(game)}); break;
case 'begin_game' :
client_newgame(); break;
case 'waiting' :
var type = commanddata;
game.get_player(my_id).message = type ? type + " move!\n\n" : ""
if(type == 'incorrect')
incorrect = true
if(my_role == "director") {
game.get_player(my_id).message += 'Waiting for matcher to re-position mouse...';
game.get_player(my_id).need_check = false
} else {
game.get_player(my_id).message += 'Please click on the circle in the center and\n wait for the director to give you instructions.';
waiting = true
game.get_player(my_id).need_click = true
game.get_player(my_id).need_check = false
}
drawScreen(game, game.get_player(my_id))
break;
case 'waitCheck':
if (my_role == "director") {
game.get_player(my_id).message = 'Please tell if the matcher make the right move or not';
game.get_player(my_id).need_check = true
} else {
game.get_player(my_id).message = 'Please wait for the director to judge your move.';
waiting = true
game.get_player(my_id).need_click = false
game.get_player(my_id).need_check = true
}
drawScreen(game, game.get_player(my_id))
break;
}
}
};
// When loading the page, we store references to our
// drawing canvases, and initiate a game instance.
window.onload = function(){
//Create our game client instance.
game = new game_core();
//Connect to the socket.io server!
client_connect_to_server(game);
//Fetch the viewport
game.viewport = document.getElementById('viewport');
//Adjust its size
game.viewport.width = game.world.width;
game.viewport.height = game.world.height;
//Fetch the rendering contexts
game.ctx = game.viewport.getContext('2d');
//Set the draw style for the font
game.ctx.font = '14px "Helvetica"';
document.getElementById('chatbox').focus();
};
// Associates callback functions corresponding to different socket messages
client_connect_to_server = function(game) {
//Store a local reference to our connection to the server
game.socket = io.connect();
// Tell server when client types something in the chatbox
$('#s').submit(function(){
var msg = 'chatMessage.' + Date.now() + '.' + $('#chatbox').val();
if($('#chatbox').val() != '') {
if(my_role == "director")
{
game.socket.send(msg);
}
$('#chatbox').val('');
// If you just sent a scripted instruction, get rid of it!
game.scriptedInstruction = "none";
}
return false;
});
// Tell server when client hit the right button
$('#r').submit(function () {
var msg = 'checkMessage.' + Date.now() + '.' + 'correct';
game.socket.send(msg);
return false;
});
// Tell server when client hit the right button
$('#w').submit(function () {
var msg = 'checkMessage.' + Date.now() + '.' + 'incorrect';
game.socket.send(msg);
return false;
});
// Update messages log when other players send chat
game.socket.on('chatMessage', function(data){
var otherRole = my_role === "director" ? "Matcher" : "Director"
var source = data.user === my_id ? "You" : otherRole
var col = source === "You" ? "#363636" : "#707070"
$('#messages').append($('<li style="padding: 5px 10px; background: ' + col + '">').text(source + ": " + data.msg));
$('#messages').stop().animate({
scrollTop: $("#messages")[0].scrollHeight
}, 800);
})
// Draw objects when someone else moves them
game.socket.on('objMove', function(data){
game.objects[data.i].trueX = data.x;
game.objects[data.i].trueY = data.y;
drawScreen(game, game.get_player(my_id))
})
//When we connect, we are not 'connected' until we have an id
//and are placed in a game by the server. The server sends us a message for that.
game.socket.on('connect', function(){}.bind(game));
//Sent when we are disconnected (network, server down, etc)
game.socket.on('disconnect', client_ondisconnect.bind(game));
//Sent each tick of the server simulation. This is our authoritive update
game.socket.on('onserverupdate', client_onserverupdate_received);
//Handle when we connect to the server, showing state and storing id's.
game.socket.on('onconnected', client_onconnected.bind(game));
//On message from the server, we parse the commands and send it to the handlers
game.socket.on('message', client_onMessage.bind(game));
game.socket.on('changeRole', client_onChangeRole.bind(game));
//game.socket.on('switch', client_onSwitch.bind(game));
};
client_onChangeRole = function (data) {
console.log(my_role)
if (my_role == "director") {
role = "matcher"
if (role === "matcher") {
$('#viewport').mousemove(function (event) {
var bRect = game.viewport.getBoundingClientRect();
mouseX = (event.clientX - bRect.left) * (game.viewport.width / bRect.width);
mouseY = (event.clientY - bRect.top) * (game.viewport.height / bRect.height);
game.socket.send('update_mouse.' + Date.now() + '.' + Math.floor(mouseX) + '.' + Math.floor(mouseY));
});
game.viewport.addEventListener("mousedown", mouseDownListener, false);
}
} else {
game.viewport.removeEventListener("mousedown", mouseDownListener, false)
window.removeEventListener("mousedown", mouseDownListener, false)
game.viewport.removeEventListener("mouseup", mouseUpListener, false)
window.removeEventListener("mouseup", mouseUpListener, false)
game.viewport.removeEventListener("mousemove", mouseMoveListener, false)
window.removeEventListener("mousemove", mouseMoveListener, false)
role = "director"
}
// Update w/ role (can only move stuff if agent)
$('#header').html("You are the " + role + ' now.');
if (role === "director") {
$('#instructs').html("Type instructions for the matcher to move the object in the direction of the arrow!")
} else {
$('#instructs').html("Click and drag objects to follow the director's instructions.")
}
// set role locally
my_role = role;
game.get_player(my_id).role = my_role
drawScreen(game, game.get_player(my_id))
}
client_onconnected = function(data) {
//The server responded that we are now in a game. Remember who we are
my_id = data.id;
game.players[0].id = my_id;
};
client_onjoingame = function(num_players, role) {
// Need client to know how many players there are, so they can set up the appropriate data structure
_.map(_.range(num_players - 1), function(i){
game.players.unshift({id: null, player: new game_player(game)})});
// Update w/ role (can only move stuff if agent)
$('#header').append("You are the " + role + ' now.');
if(role === "director") {
$('#instructs').append("Type instructions for the matcher to move the object in the direction of the arrow!")
} else {
$('#instructs').append("Click and drag objects to follow the director's instructions.")
}
// set role locally
my_role = role;
game.get_player(my_id).role = my_role;
if(num_players == 1)
game.get_player(my_id).message = 'Waiting for other player to connect...';
// set mouse-tracking event handler
if(role === "matcher") {
$('#viewport').mousemove(function(event){
var bRect = game.viewport.getBoundingClientRect();
mouseX = (event.clientX - bRect.left)*(game.viewport.width/bRect.width);
mouseY = (event.clientY - bRect.top)*(game.viewport.height/bRect.height);
game.socket.send('update_mouse.' + Date.now() + '.' + Math.floor(mouseX) + '.' + Math.floor(mouseY));
});
game.viewport.addEventListener("mousedown", mouseDownListener, false);
}
};
/*
MOUSE EVENT LISTENERS
*/
function mouseDownListener(evt) {
var i;
//We are going to pay attention to the layering order of the objects so that if a mouse down occurs over more than object,
//only the topmost one will be dragged.
var highestIndex = -1;
//getting mouse position correctly, being mindful of resizing that may have occured in the browser:
var bRect = game.viewport.getBoundingClientRect();
mouseX = (evt.clientX - bRect.left)*(game.viewport.width/bRect.width);
mouseY = (evt.clientY - bRect.top)*(game.viewport.height/bRect.height);
// if waiting flag is active, check if center was clicked
if(waiting) {
if((Math.pow(mouseX - game.viewport.width/2, 2) + Math.pow(mouseY - game.viewport.height/2, 2))
<= Math.pow(8, 2)) {
game.get_player(my_id).message = ""
if (incorrect) {
game.socket.send("ready.incorrect")
incorrect = false;
} else {
game.socket.send("ready")
}
waiting = false
}
} else {
//find which shape was clicked
for (i=0; i < game.objects.length; i++) {
if (hitTest(game.objects[i], mouseX, mouseY)) {
dragging = true;
if (i > highestIndex) {
//We will pay attention to the point on the object where the mouse is "holding" the object:
dragHoldX = mouseX - game.objects[i].trueX;
dragHoldY = mouseY - game.objects[i].trueY;
highestIndex = i;
dragIndex = i;
}
}
}
}
if (dragging) {
window.addEventListener("mousemove", mouseMoveListener, false);
}
game.viewport.removeEventListener("mousedown", mouseDownListener, false);
window.addEventListener("mouseup", mouseUpListener, false);
//code below prevents the mouse down from having an effect on the main browser window:
if (evt.preventDefault) {
evt.preventDefault();
} //standard
else if (evt.returnValue) {
evt.returnValue = false;
} //older IE
return false;
}
function mouseUpListener(evt) {
game.viewport.addEventListener("mousedown", mouseDownListener, false);
window.removeEventListener("mouseup", mouseUpListener, false);
if (dragging) {
// Set up the right variables
var bRect = game.viewport.getBoundingClientRect();
dropX = (evt.clientX - bRect.left)*(game.viewport.width/bRect.width);
dropY = (evt.clientY - bRect.top)*(game.viewport.height/bRect.height);
var obj = game.objects[dragIndex]
var cell = game.getCellFromPixel(dropX, dropY)
var currX = cell[0]
var currY = cell[1]
//check if the drop cell is empty
cell_empty = true
for (i = 0; i < game.objects.length; i++) {
if (i == dragIndex) {
continue
}
var tmp_item = game.objects[i]
if (currX == tmp_item.lastX && currY == tmp_item.lastY) {
//move the item back to the cell before draging
obj.gridX = obj.lastX
obj.gridY = obj.lastX
obj.trueX = game.getPixelFromCell(obj.lastX, obj.lastY).centerX - obj.width / 2
obj.trueY = game.getPixelFromCell(obj.lastX, obj.lastY).centerY - obj.height / 2
game.socket.send("objMove." + dragIndex + "." + Math.round(obj.trueX) + "." + Math.round(obj.trueY))
cell_empty = false
break
}
}
if (cell_empty) {
//check if move only one cell
move_distance = Math.abs(obj.lastX - cell[0]) + Math.abs(obj.lastY - cell[1])
if (move_distance >= 2) {
//move the item back to the cell before draging
obj.gridX = obj.lastX
obj.gridY = obj.lastX
obj.trueX = game.getPixelFromCell(obj.lastX, obj.lastY).centerX - obj.width / 2
obj.trueY = game.getPixelFromCell(obj.lastX, obj.lastY).centerY - obj.height / 2
game.socket.send("objMove." + dragIndex + "." + Math.round(obj.trueX) + "." + Math.round(obj.trueY))
}
else {
// center it
obj.gridX = cell[0]
obj.gridY = cell[1]
obj.lastX = cell[0]
obj.lastY = cell[1]
obj.trueX = game.getPixelFromCell(cell[0], cell[1]).centerX - obj.width / 2
obj.trueY = game.getPixelFromCell(cell[0], cell[1]).centerY - obj.height / 2
game.socket.send("objMove." + dragIndex + "." + Math.round(obj.trueX) + "." + Math.round(obj.trueY))
//send check message to server
game.socket.send("waitCheck." + dragIndex + "." + Math.round(obj.trueX) + "." + Math.round(obj.trueY))
}
}
// Tell server where you dropped it
drawScreen(game, game.get_player(my_id))
dragging = false;
window.removeEventListener("mousemove", mouseMoveListener, false);
}
}
function mouseMoveListener(evt) {
// prevent from dragging offscreen
var minX = 25;
var maxX = game.viewport.width - game.objects[dragIndex].width - 25;
var minY = 25;
var maxY = game.viewport.height - game.objects[dragIndex].height - 25;
//getting mouse position correctly
var bRect = game.viewport.getBoundingClientRect();
mouseX = (evt.clientX - bRect.left)*(game.viewport.width/bRect.width);
mouseY = (evt.clientY - bRect.top)*(game.viewport.height/bRect.height);
//clamp x and y positions to prevent object from dragging outside of canvas
var posX = mouseX - dragHoldX;
posX = (posX < minX) ? minX : ((posX > maxX) ? maxX : posX);
var posY = mouseY - dragHoldY;
posY = (posY < minY) ? minY : ((posY > maxY) ? maxY : posY);
// Update object locally
var obj = game.objects[dragIndex]
obj.trueX = Math.round(posX);
obj.trueY = Math.round(posY);
// Tell server about it
game.socket.send("objMove." + dragIndex + "." + Math.round(posX) + "." + Math.round(posY))
drawScreen(game, game.get_player(my_id));
}
function hitTest(shape,mx,my) {
var dx = mx - shape.trueX;
var dy = my - shape.trueY;
return (0 < dx) && (dx < shape.width) && (0 < dy) && (dy < shape.height)
}
// Automatically registers whether user has switched tabs...
(function() {
document.hidden = hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ('onfocusin' in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide = window.onfocus
= window.onblur = onchange;
})();
function onchange (evt) {
var v = 'visible', h = 'hidden',
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
};
evt = evt || window.event;
if (evt.type in evtMap) {
document.body.className = evtMap[evt.type];
} else {
document.body.className = evt.target.hidden ? "hidden" : "visible";
}
visible = document.body.className;
game.socket.send("h." + document.body.className);
};
(function () {
var original = document.title;
var timeout;
window.flashTitle = function (newMsg, howManyTimes) {
function step() {
document.title = (document.title == original) ? newMsg : original;
if (visible === "hidden") {
timeout = setTimeout(step, 500);
} else {
document.title = original;
}
};
cancelFlashTitle(timeout);
step();
};
window.cancelFlashTitle = function (timeout) {
clearTimeout(timeout);
document.title = original;
};
}());