forked from btouellette/concarneau
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.ejs
1924 lines (1856 loc) · 72.3 KB
/
game.ejs
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html>
<head>
<script type="text/javascript">
// if Facebook redirect hash is present remove it: https://stackoverflow.com/questions/7131909/facebook-callback-appends-to-return-url
if (window.location.hash && window.location.hash == '#_=_') {
if (window.history && history.pushState) {
window.history.pushState("", document.title, window.location.pathname);
} else {
window.location.hash = '';
}
}
</script>
<title>Concarneau</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<link rel="apple-touch-icon" href="/content/images/tiles/base-game/RCr.png">
<link rel="apple-touch-startup-image" href="/content/images/ui/bg.jpg">
<link rel="shortcut icon" href="/content/images/ui/favicon.ico" type="image/x-icon">
<link rel="icon" href="/content/images/ui/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="/content/css/bootstrap.3.0.2.min.css" type='text/css'>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0/jquery.qtip.min.css" type='text/css'>
<link rel="stylesheet" href="/content/css/game.css" type='text/css'>
</head>
<body>
<input type="checkbox" id="menu-checkbox" checked />
<input type="checkbox" id="collapsible-menu-checkbox-outer" <%- user.collapsible_menu ? 'checked="true"' : '' %> />
<div id="wrapper">
<label id="menu-open" for="menu-checkbox" onclick="openMenu()">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</label>
<label id="menu-close" for="menu-checkbox" class="hidden">
<svg class="fa-times"><use xlink:href="#fa-times"></use></svg>
</label>
<label id="menu-overlay" for="menu-checkbox"></label>
<div id="menus">
<div id="game-menu">
<span class="menu-header">GAMES <svg class="fa-edit" onclick="enableGamesEdit(evt || event)"><use xlink:href="#fa-edit"></use></svg><svg class="fa-plus-square-o"><use xlink:href="#fa-plus-square-o"></use></svg></span>
<div id="list-games">
<div id="active-games">
<div class="menu-sub-header">Your move:</div>
</div>
<div id="inactive-games">
<div class="menu-sub-header">Waiting on move:</div>
</div>
<div id="finished-games">
<div class="menu-sub-header">Finished:</div>
</div>
</div>
<!--<div>
<input type="checkbox" id="test-complete" />
</div>-->
</div>
<div id="friends-menu">
<span class="menu-header">FRIENDS <svg class="fa-edit hidden" onclick="enableFriendsEdit(event)"><use xlink:href="#fa-edit"></use></svg></span>
<div id="username-info">You: <svg class="fa-user"><use xlink:href="#fa-user"></use></svg><%- user.username %></div>
<form id="add-friend-form">
<div class="input-group">
<input type="text" class="form-control" id="add-friend-input" placeholder="Username" autocomplete="off">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Add</button>
</span>
</div>
</form>
<div id="username-alert" class="alert">Placeholder text</div>
<div id="friends-list"></div>
</div>
<div id="settings-menu">
<span class="menu-header">SETTINGS</span>
<a href="/profile">Profile</a>
<div class="checkbox">
<label>
<input type="checkbox"
onclick="socket.emit('email notification', this.checked)"
<%- user.email_notifications ? 'checked="true"' : '' %>
<%- !(user.facebook.email || user.google.email || user.local.email) ? 'disabled' : '' %>> E-mail notifications
</label>
<%- !(user.facebook.email || user.google.email || user.local.email) ? '(requires non-Twitter login linked in Profile)' : '' %>
</div>
<div class="checkbox">
<label>
<input type="checkbox"
onclick="socket.emit('twitter notification', this.checked)"
<%- user.twitter_notifications ? 'checked="true"' : '' %>
<%- !user.twitter.username ? 'disabled' : '' %>> Twitter notifications
</label>
<%- !user.twitter.username ? '(requires Twitter login linked in Profile)' : '' %>
</div>
<div class="checkbox">
<label>
<input id="sound-notifications-checkbox"
type="checkbox"
onclick="socket.emit('sound notification', this.checked); if(this.checked) { var bell = new Audio('/content/sounds/church-bell.mp3'); bell.volume = 0; bell.play(); }"
<%- user.sound_notifications ? 'checked="true"' : '' %>> Sound notifications
</label>
</div>
<div class="checkbox">
<label>
<input id="collapsible-menu-checkbox"
type="checkbox"
onclick="socket.emit('collapsible menu', this.checked); if(this.checked) { $('#collapsible-menu-checkbox-outer').prop('checked', true); } else { $('#collapsible-menu-checkbox-outer').prop('checked', false); }"
<%- user.collapsible_menu ? 'checked="true"' : '' %>> Always collapse menu
</label>
</div>
<div class="dropdown">
<label for="preferred-color-select">Preferred color:</label>
<select id="preferred-color-select" class="form-control"
onchange="socket.emit('preferred color', this.value)">
<option value="none" <%- !user.preferred_color || user.preferred_color === 'none' ? 'selected' : '' %>>No preference</option>
<option value="green" <%- user.preferred_color === 'green' ? 'selected' : '' %>>Green</option>
<option value="gray" <%- user.preferred_color === 'gray' ? 'selected' : '' %>>Gray</option>
<option value="blue" <%- user.preferred_color === 'blue' ? 'selected' : '' %>>Blue</option>
<option value="red" <%- user.preferred_color === 'red' ? 'selected' : '' %>>Red</option>
<option value="yellow" <%- user.preferred_color === 'yellow' ? 'selected' : '' %>>Yellow</option>
<option value="purple" <%- user.preferred_color === 'purple' ? 'selected' : '' %>>Purple</option>
</select>
</div>
<a href="/logout">Logout</a>
</div>
</div>
<div id="menu-selection">
<div id="game-menu-selection" class="iconmelon" onclick="menuClick('#game-menu', this)">
<svg viewBox="0 0 32 32">
<use xlink:href="#svgicon-templates"></use>
</svg>
</div>
<div id="friends-menu-selection" class="iconmelon" onclick="menuClick('#friends-menu', this)">
<svg viewBox="0 0 32 32">
<use xlink:href="#svgicon-environment"></use>
</svg>
</div>
<div id="settings-menu-selection" class="iconmelon" onclick="menuClick('#settings-menu', this)">
<svg viewBox="0 0 32 32">
<use xlink:href="#svgicon-settings"></use>
</svg>
</div>
</div>
<div id="author-info">
<div>
Created by <span id="author-name">Brian Ouellette</span>
<a href="http:https://github.com/btouellette/concarneau"><img height="25" width="25" src="/content/images/ui/github_logo.png" /></a>
</div>
<div>
<span>Buy me a beer?</span>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="item_name" value="Concarneau">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-DonationsBF:paypal-icon.png:NonHostedGuest">
<input type="image" height="25" width="25" src="/content/images/ui/paypal_logo.png" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
</form>
<img id="btc-donate" height="25" width="25" src="/content/images/ui/bitcoin_logo.png" />
</div>
<div>
<span>Buy the game?</span>
<a href="http:https://amzn.to/1pd6fg3"><img id="amazon-link" height="25" width="25" src="/content/images/ui/amazon_logo.png" /></a>
</div>
</div>
<div id="svg-wrapper">
<svg id="game-svg" width="100%" height="100%">
<defs>
<pattern id="thin-stripes-pattern" width="5" height="5" patternUnits="userSpaceOnUse">
<rect width="5" height="5" fill="#f5f5f5"></rect>
<path d="M0 5L5 0ZM6 4L4 6ZM-1 1L1 -1Z" stroke="#e0e0e0"></path>
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#thin-stripes-pattern)" id="game-background"></rect>
</svg>
</div>
<div id="chat-wrapper" class="panel panel-primary hidden">
<div id="chat-header" class="panel-heading">
<div id="chat-header-label"><svg class="fa-comments" fill="white"><use xlink:href="#fa-comments"></use></svg><span> Chat</span></div>
<div id="chat-toggle" class="btn-group">
<a class="btn btn-default btn-xs" onclick="$('#chat-body,#chat-footer').toggle()">
<svg class="fa-chevron-down"><use xlink:href="#fa-chevron-down"></use></svg>
</a>
</div>
</div>
<div id="chat-body">
<ul id="chat-message-list">
</ul>
</div>
<div id="chat-footer">
<form id="chat-message-form">
<div class="input-group">
<input id="chat-message-input" type="text" class="form-control input-sm" maxlength="200" placeholder="Type your message here...">
<span class="input-group-btn">
<button class="btn btn-sm btn-info" type="submit">Send</button>
</span>
</div>
</form>
</div>
</div>
</div>
<script src="/content/js/standalone.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0/jquery.qtip.min.js"></script>
<script>
//TODO: show socket status on page
//TODO: show player online status
//TODO: show player avatars (gravatars?)
//TODO: Modernizr and noscript redirects
//TODO: move these variables out of the global namespace (add onclick to elements via JS)
//TODO: zoom and pan when active tile moves if out of zoom/pan range
//TODO: default zoom level should be dependendent on number of placed tiles
//TODO: see if there is a way to prevent the image rerender across the board when the active tile is scaled
//TODO: add keyboard shortcuts ENTER = place tile, arrows = pan
//TODO: concede button
//TODO: list points on the board
//TODO: activatable overlay showing count of tiles that could fit in a space
//TODO: add welcome popup explaining buttons and linking to rules if 0 games and 0 friends, allow to view again from settings
//TODO: scoreboard/game record
//TODO: You win! or You lost! alert when game is finished (with rematch button)
//TODO: if there is a choice about which meeple to exchange from tower captures prompt the user to choose and populate meeple.tower.capture.exchangeType
//TODO: keep win/loss stats
//TODO: add a message to the game chat when a tile is discarded
var userGames = <%- JSON.stringify(user.activeGames) %>;
// sort user's games most to least recent
userGames.sort(function(a,b) { return (a.lastModified < b.lastModified) ? 1 : ((b.lastModified < a.lastModified) ? -1 : 0); });
var userFriends = <%- JSON.stringify(user.friends) %>;
var userID = '<%- user._id %>';
// Disabling HTTPS/polling transport initially as this is causing H12 errors on Heroku, allow polling on reconnect if initial connection fails
var socket = io.connect('<%- process.env.SOCKET_URL %>', {
transports: ['websocket']
});
socket.on('reconnect_attempt', () => {
socket.io.opts.transports = ['polling', 'websocket'];
});
var currentGameID, selectedMove, svgHeight, svgWidth;
var meeplePlacementMode = 'normal';
var reverseScale = 1;
var reverseTranslation = [0,0];
var transitionDuration = 750;
var tileSize = 100;
function menuClick(menuToOpen, button) {
$('#menus > div').hide();
$(menuToOpen).show();
$('#menu-selection > div').css('fill','#272727');
$(button).css('fill','#808080');
}
function openMenu() {
$("#menu-close").removeClass('hidden');
}
function enableFriendsEdit(e) {
$('#friends-list .fa-user').attr('class','fa-user hidden');
$('#friends-list .fa-trash-o').attr('class','fa-trash-o').css('cursor', 'pointer').on('click', function () {
socket.emit('remove friend', this.parentNode.id.substr(7));
$(this.parentNode).remove();
if($('.friend-listing').length === 0) {
$('#friends-menu .fa-edit').attr('class','fa-edit hidden');
}
});
$(window).on('click.friend-edit', function() {
disableFriendsEdit();
});
e.stopPropagation();
}
function disableFriendsEdit() {
$('#friends-list .fa-trash-o').attr('class','fa-trash-o hidden');
$('#friends-list .fa-user').attr('class','fa-user');
$(window).off('click.friend-edit');
}
function enableGamesEdit(e) {
$('#game-menu .tile-count').hide();
// remove hidden element from trash icons
$('#game-menu .fa-trash-o').attr('class','fa-trash-o').on('click', function () {
var gameID = this.parentNode.parentNode.id.substr(5);
socket.emit('remove game', gameID);
$(this.parentNode.parentNode).remove();
// if we deleted the game we are viewing remove relevant svg elements
if(gameID === currentGameID) {
resetActiveTile(false);
$('#placed-tile-images,#placed-tile-pieces,#turn-markers,#valid-placements,#meeple-placements').empty();
$('#active-tile-image').remove();
$('.score-group').remove();
$('#score-bg').attr('opacity', 0);
}
// if there are no more games hide the edit/delete button
if($('.menu-game-listing').length === 0) {
$('#game-menu .fa-edit').attr('class','fa-edit hidden');
}
});
$(window).on('click.games-edit', function() {
disableGamesEdit();
});
e.stopPropagation();
}
function disableGamesEdit() {
$('#game-menu .fa-trash-o').attr('class','fa-trash-o hidden').off('click');
$('#game-menu .tile-count').show();
$(window).off('click.games-edit');
}
(function ($) {
// debouncedresize: special jQuery event that happens once after a window resize
// https://github.com/louisremi/jquery-smartresize
// Copyright 2012 @louis_remi
// Licensed under the MIT license.
var $event = $.event,
$special,
resizeTimeout;
$special = $event.special.debouncedresize = {
setup: function () { $(this).on("resize", $special.handler); },
teardown: function () { $(this).off("resize", $special.handler); },
handler: function (event, execAsap) {
// Save the context
var context = this,
args = arguments,
dispatch = function () {
// set correct event type
event.type = "debouncedresize";
$event.dispatch.apply(context, args);
};
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
execAsap ? dispatch() : resizeTimeout = setTimeout(dispatch, $special.threshold);
},
threshold: 150
};
})(jQuery);
function resetActiveTile(withTransition) {
// hide any placed meeples and their outlines
$('#meeple-placements').attr('visibility', 'hidden');
$('#meeple-placements image').attr('visibility', 'hidden');
// hide the tower placements
$('.tower-outline,.placed-tower').attr('visibility', 'hidden');
// change back to default meeple placement mode
changeMeepleMode();
// show the meeples in the score area as they are no longer placed
$('#score-area image').removeAttr('visibility');
// remove data stored regarding the active tile position
$('#active-tile').removeData('rotationIndex').removeData('placementIndex');
// remove any selected move
selectedMove = null;
if(withTransition) {
var startingScale = reverseScale;
var startingTranslationX = reverseTranslation[0];
var startingTranslationY = reverseTranslation[1];
d3.selectAll('#confirm-button,#send-move-button').transition().duration(transitionDuration).attr('opacity', 0);
d3.selectAll('#confirm-button,#send-move-button').transition().delay(transitionDuration).attr('visibility', 'hidden');
d3.selectAll('#confirm-button > *').transition().delay(transitionDuration).attr('visibility', null);
d3.select('#active-tile').transition().duration(transitionDuration).attr({
transform: 'scale(' + reverseScale + ') translate(' + (reverseTranslation[0] + (svgWidth - tileSize - 5)) + ',' + (reverseTranslation[1] + 5) + ')'
}).select('#active-tile-rotation').attr({
transform: 'rotate(0)'
}).each('end', function() {
// check to see if zoom or pan has happened since this transition began and redraw if so
if(reverseScale !== startingScale ||
reverseTranslation[0] !== startingTranslationX ||
reverseTranslation[1] !== startingTranslationY) {
resetActiveTile(true);
}
});
d3.select('#active-tile-rotation-indicator').transition().duration(transitionDuration).attr({
opacity: 0,
visibility: null
});
} else {
d3.selectAll('#confirm-button,#send-move-button').transition().duration(0).attr({
opacity: 0,
visibility: 'hidden'
});
d3.selectAll('#confirm-button > *').attr('visibility', null);
d3.select('#active-tile').attr({
transform: 'scale(' + reverseScale + ') translate(' + (reverseTranslation[0] + (svgWidth - tileSize - 5)) + ',' + (reverseTranslation[1] + 5) + ')'
}).select('#active-tile-rotation').attr({
transform: 'rotate(0)'
});
d3.select('#active-tile-rotation-indicator').attr({
opacity: 0,
visibility: null
});
}
}
function changeMeepleMode(newMode) {
if(newMode === undefined) {
// activate the meeple placement mode for the first (minimum x value) existing meeple if there is one
var firstFoundMeepleClass = $('.score-group:first image[class$="-meeple"]').sort(function(a, b) {
return parseFloat(a.attributes.x.value) > parseFloat(b.attributes.x.value);
}).first().attr('class');
if(!firstFoundMeepleClass) {
return;
}
newMode = firstFoundMeepleClass.slice(0,-7);
}
// update all meeple placements (outlines and actual meeples) with the appropriate size and image
var size = newMode !== 'normal' ? tileSize * 3 / 8 : tileSize / 4;
d3.selectAll('#meeple-placements image').attr({
width: size,
height: size,
x: -size / 2,
y: -size / 2,
'xlink:href': function(d) {
var suffix = newMode === 'normal' || newMode === 'large' ? (d.locationType === 'farm' ? 'lying' : 'standing') : newMode;
return this.attributes.href.value.replace(/_[^\.]*/, '_' + suffix);
}
});
// do nothing else if the mode doesn't actually change
if(newMode === meeplePlacementMode) {
return;
}
// show clickable cursor on deactivating mode, show default cursor on activating mode
var firstScoreGroup = d3.select('.score-group');
firstScoreGroup.selectAll('.' + meeplePlacementMode + '-meeple').attr({ cursor: 'pointer' });
firstScoreGroup.selectAll('.' + newMode + '-meeple').attr({ cursor: null });
if(selectedMove && selectedMove.meeple) {
// unhide (pick up) all meeples to start with
firstScoreGroup.selectAll('image').attr('visibility', null);
// the only way for the placement to still be valid is if we are changing between large and normal placements
if((newMode === 'normal' && meeplePlacementMode === 'large') ||
(newMode === 'large' && meeplePlacementMode === 'normal')) {
selectedMove.meeple.meepleType = newMode;
// hide the newly placed meeple (reselect is necessary to still get just the first element and avoid rebinding data: https://github.com/mbostock/d3/wiki/Selections#select)
d3.select(firstScoreGroup.selectAll('.' + newMode + '-meeple')[0][0]).attr('visibility', 'hidden');
} else {
// this placement is no longer valid
// remove the move and hide any placed meeples
delete selectedMove.meeple;
d3.selectAll('#meeple-placements .placed-meeple').attr('visibility', 'hidden');
}
}
meeplePlacementMode = newMode;
updateMeeplePlacements(false);
}
function updateMeeplePlacements(withTransition) {
// if the active tile isn't laid down on a valid placement don't update the meeple placement information as it will be done when the tile is placed
if(!selectedMove) {
return;
}
// show outlines for any valid meeple placements and rotate them appropriately
var validMeeplePlacements = selectedMove.placement.rotations[selectedMove.rotationIndex].meeples;
var container = d3.select('#meeple-placements');
container.selectAll('image.meeple-outline').transition().duration(withTransition ? transitionDuration : 0).attr({
visibility: function(d) {
for(var i = 0; i < validMeeplePlacements.length; i++) {
if(validMeeplePlacements[i].meepleType === (meeplePlacementMode === 'large' ? 'normal' : meeplePlacementMode) &&
validMeeplePlacements[i].locationType === d.locationType &&
validMeeplePlacements[i].index === d.index) {
// remove hidden visibility attribute
return null;
}
}
return 'hidden';
},
transform: function() {
return 'rotate(' + -selectedMove.rotation * 90 + ')';
}
});
// remove meeple placement from the move and hide placed meeple if old placement is no longer valid
container.selectAll('image.placed-meeple').transition().duration(withTransition ? transitionDuration : 0).attr({
visibility: function(d) {
// keep null visibility attribute if we find this placement in the valid placements
for(var i = 0; i < validMeeplePlacements.length; i++) {
if(validMeeplePlacements[i].meepleType === (meeplePlacementMode === 'large' ? 'normal' : meeplePlacementMode) &&
validMeeplePlacements[i].locationType === d.locationType &&
validMeeplePlacements[i].index === d.index) {
// remove hidden visibility attribute
return $(this).attr('visibility');
}
}
// otherwise show any hidden meeples in the score area delete the selected move
if(selectedMove &&
selectedMove.meeple &&
selectedMove.meeple.locationType === d.locationType &&
selectedMove.meeple.index === d.index) {
$('#score-area image').removeAttr('visibility');
delete selectedMove.meeple;
}
// and hide this placed meeple
return 'hidden';
},
transform: function() {
return 'rotate(' + -selectedMove.rotation * 90 + ')';
}
});
// rotate the tower outline on the active tile
d3.selectAll('#active-tile image.tower-outline,#active-tile image.placed-tower').transition().duration(withTransition ? transitionDuration : 0).attr({
transform: function(d) {
return 'translate(' + (d.offset.x - 1/2) * tileSize + ',' + (d.offset.y - 1/2) * tileSize + ') rotate(' + -selectedMove.rotation * 90 + ')';
}
});
}
$(document).ready(function() {
// maybe avoid getting some spam with this
$('#author-name').replaceWith('<a href="mailto:' + 'btouellette+concarneau' + '@' + 'gmail.com' + '">Brian Ouellette</a>');
$('#btc-donate').qtip({
prerender: true,
content: {
text: '<img src="/content/images/ui/bitcoin_qr.png" class="btc-qr"></img>13C6vXxhQuSrGs628imU8ug2xvachM6pJ2'
},
style: {
classes: 'qtip-bootstrap'
},
position: {
my: 'bottom center',
at: 'top center',
viewport: $(window),
adjust: {
method: 'shift'
}
},
show: {
event: 'mouseenter click',
delay: 200
},
hide: {
event: 'unfocus mouseleave',
delay: 500
},
events: {
render: function(event, api) {
$(this).attr('id', 'btc-popup');
// detect when it was clicked and store it
api.elements.target.click(function(e) {
api.wasClicked = !api.wasClicked;
});
},
hide: function(event, api) {
// if we're hiding and it was previously clicked stop, if it gets hidden unset the clicked status
if((api.wasClicked && (event.originalEvent.type === 'mouseleave' || event.originalEvent.type === 'mouseout')) ||
$('#btc-popup').is(":hover")) {
try{ event.preventDefault(); } catch(e) {}
} else {
api.wasClicked = false;
}
}
}
});
$('#game-menu .fa-plus-square-o').qtip({
content: {
text: '<div id="new-game-popup">' +
'<div>Click friends to add to game:</div>' +
'<div id="solo-notifier"><svg class="fa-exclamation-triangle"><use xlink:href="#fa-exclamation-triangle"></use></svg> Currently playing solo</div>' +
'</div>' +
'<button type="button" id="new-game-cancel" class="btn btn-default btn-sm">Cancel</button>' +
'<button id="new-game-send" type="button" class="btn btn-default btn-sm">Start</button>' +
<% if (/*['gatskee','crmack','novamute','mom','werxes','greatgatskee','blakestock','evan'].indexOf(user.username) !== -1*/ true) { %>
'<div id="expansion-header">Expansions:</div>' +
'<div><label class="expansion-label">' +
'<input type="checkbox" id="inns-and-cathedrals-checkbox" class="expansion-checkbox"> <a target="_blank" href="http:https://zmangames.com/rulebooks/Carcassonne_Exp1.pdf">Inns and Cathedrals</a>' +
'</label></div>' +
'<div><label class="expansion-label">' +
'<input type="checkbox" id="traders-and-builders-checkbox" class="expansion-checkbox"> <a target="_blank" href="http:https://zmangames.com/rulebooks/Carcassonne_Exp2.pdf">Traders and Builders</a>' +
'</label></div>' +
//'<div><label class="expansion-label">' +
// '<input type="checkbox" id="the-tower-checkbox" class="expansion-checkbox"> <a target="_blank" href="http:https://zmangames.com/rulebooks/Carcassonne_Exp4.pdf">The Tower</a>' +
//'</label></div>' +
<% } %>
''
},
style: {
classes: 'qtip-bootstrap',
tip: {
corner: false
}
},
position: {
my: 'left center',
at: 'center right',
viewport: $(window),
adjust: {
method: 'shift',
x: 249
}
},
show: {
event: 'click'
},
hide: {
event: 'click'
},
events: {
show: function() {
$('#new-game-popup .friend-listing').remove();
$('#friends-menu .fa-edit').hide();
$('#friends-menu-selection').click();
// hide user symbols
$('#friends-list .fa-user').attr('class','fa-user hidden');
// unhide add symbols
$('#friends-list .fa-plus-square-o').attr('class','fa-plus-square-o');
$('#friends-list .friend-listing').on('click', function() {
if($('#new-game-popup .friend-listing').length < 5) {
$('#solo-notifier').hide();
var element = $(this);
element.clone().attr('id', 'add-' + element.attr('id')).css('cursor', 'default').addClass('add-friend-listing').appendTo('#new-game-popup');
$('#add-' + element.attr('id') + ' svg').remove();
}
});
},
hide: function() {
$('#friends-menu .fa-edit').show();
$('#game-menu-selection').click();
$('#friends-list .fa-plus-square-o').attr('class','fa-plus-square-o hidden');
$('#friends-list .fa-user').attr('class','fa-user');
$('#friends-list .friend-listing').off('click');
$('#solo-notifier').delay(250).show(0);
},
render: function(e, api) {
$('#new-game-cancel', this).click(function(event) {
api.hide(event);
event.preventDefault();
});
$('#new-game-send', this).click(function(event) {
var friends = [];
$('.add-friend-listing').each(function() {
friends.push(this.id.substr(11));
});
var expansions = ['base-game'];
$('.expansion-checkbox:checked').each(function() {
expansions.push(this.id.slice(0,-9));
});
socket.emit('new game', friends, expansions);
api.hide(event);
event.preventDefault();
});
}
}
});
$('#add-friend-form').on('submit', function(e) {
e.preventDefault();
socket.emit('add friend', $('#add-friend-input').val());
});
$('#chat-message-form').on('submit', function(e) {
e.preventDefault();
var input = $('#chat-message-input');
socket.emit('sending message', input.val(), currentGameID);
input.val('');
});
// Listen for Enter keypresses and trigger move submission
jQuery.fn.d3Click = function () {
this.each(function (i, e) {
var evt = new MouseEvent("click");
e.dispatchEvent(evt);
});
};
$(document).keypress(function (event) {
// Ignore enter keypress if it is to send a chat message
if(event.target.id !== 'chat-message-input' && (event.which == 13 || event.keyCode == 13)) {
var sendVisible = $('#send-move-button').css('visibility') !== 'hidden';
var confirmVisible = $('#confirm-button').css('visibility') !== 'hidden';
if(sendVisible) {
$('#send-move-button').d3Click();
} else if(confirmVisible) {
$('#confirm-button').d3Click();
}
}
});
// Play a silent sound so that we can play background audio later if needed
if($('#sound-notifications-checkbox').is(':checked')) {
var bell = new Audio('/content/sounds/church-bell.mp3');
bell.volume = 0;
bell.play();
}
// Load in SVG icons
var c = new XMLHttpRequest();
c.open('GET', '/content/images/ui/icons.svg', false);
c.setRequestHeader('Content-Type', 'text/xml');
c.send();
document.body.insertBefore(c.responseXML.firstChild, document.body.firstChild);
var lastGamestate;
var zoom = d3.behavior.zoom().scaleExtent([0.25, 1]).on('zoom', function() {
//d3.event.sourceEvent.preventDefault();
reverseScale = 1/d3.event.scale;
reverseTranslation = d3.event.translate.map(function(item) { return -1 * item; });
gameArea.attr('transform', 'translate(' + d3.event.translate + ') scale(' + d3.event.scale + ')');
if(!selectedMove) {
resetActiveTile(false);
}
});
var svg = d3.select('#game-svg').call(zoom).on("dblclick.zoom", null);
var gameArea = svg.append('g').attr({ id: 'game-area' });
var placedTileImages = gameArea.append('g').attr({ id: 'placed-tile-images' });
var placedTilePieces = gameArea.append('g').attr({ id: 'placed-tile-pieces' });
var turnMarkerArea = gameArea.append('g').attr({ id: 'turn-markers' });
var placements = gameArea.append('g').attr({ id: 'valid-placements' });
var activeTileContainer = gameArea.append('g').attr({ id: 'active-tile' });
var activeTileImageContainer = activeTileContainer.append('g').attr({ id: 'active-tile-translation', transform: 'translate(' + tileSize / 2 + ',' + tileSize / 2 + ')' })
.append('g').attr({ id: 'active-tile-rotation' });
activeTileImageContainer.append('use').attr({
id: 'active-tile-rotation-indicator',
'xlink:href': '#svgicon-repeat-payment',
x: -16,
y: -16,
transform: 'scale(' + tileSize / 32 + ')',
fill: 'white',
stroke: 'black',
opacity: 0,
'pointer-events': 'none'
});
var meeplePlacements = activeTileImageContainer.append('g').attr({
id: 'meeple-placements',
visibility: 'hidden'
});
var uiArea = svg.append('g').attr({ id: 'ui-area' });
var scoreArea = uiArea.append('g').attr({ id: 'score-area' });
scoreArea.append('rect').attr({
id: 'score-bg',
rx: 15,
ry: 15,
x: -15,
y: -15,
fill: 'white',
stroke: 'black',
'stroke-width': 2,
opacity: 0.75
});
var sendMoveButton = uiArea.append('g').attr({
id: 'send-move-button',
cursor: 'pointer',
visibility: 'hidden'
}).on('click', function() {
if(selectedMove) {
socket.emit('sending move', currentGameID, selectedMove, $('#test-complete').is(':checked'));
// while waiting for the next gamestate hide any tile placements and the send move button
d3.selectAll('#send-move-button,.tile-placements').transition().duration(transitionDuration+1500).attr('opacity', 0);
}
});
sendMoveButton.append('circle').attr({
cy: 5 + tileSize / 2,
cx: $('#svg-wrapper').width() - 5 - tileSize / 2,
r: 30,
fill: 'green',
stroke: 'black',
'stroke-width': 5
});
sendMoveButton.append('use').attr({
'xlink:href': '#svgicon-transfer',
x: $('#svg-wrapper').width() - 5 - tileSize / 2 - 16,
y: 5 + tileSize / 2 - 16
});
var confirmButton = uiArea.append('g').attr({
id: 'confirm-button',
cursor: 'pointer',
visibility: 'hidden'
}).on('click', function() {
d3.selectAll('#confirm-button,#active-tile-rotation-indicator').attr('visibility', 'hidden');
d3.select('#send-move-button').attr({
visibility: null,
opacity: 1
});
d3.select('#meeple-placements').attr('visibility', null);
d3.selectAll('.tower-outline').attr('visibility', null);
});
confirmButton.append('circle').attr({
cy: 5 + tileSize / 2,
cx: $('#svg-wrapper').width() - 5 - tileSize / 2,
r: 30,
fill: 'green',
stroke: 'black',
'stroke-width': 5
});
confirmButton.append('use').attr({
'xlink:href': '#svgicon-selecting-from-list',
x: $('#svg-wrapper').width() - 5 - tileSize / 2 - 16,
y: 5 + tileSize / 2 - 16
});
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval >= 1) {
return interval + "y";
}
interval = Math.floor(seconds / 86400);
if (interval >= 1) {
return interval + "d";
}
interval = Math.floor(seconds / 3600);
if (interval >= 1) {
return interval + "h";
}
interval = Math.floor(seconds / 60);
if (interval >= 1) {
return interval + "m";
}
return Math.floor(seconds) + "s";
}
function addNewGameListing(game, menuGroup) {
var gameID = game._id;
var element = '<div class="menu-game-listing" id="game-' + gameID + '">';
// add remaining tiles text
element += '<span class="right-side">'
element += '<div><span class="tile-count">[' + (game.unusedTiles.length + (game.finished ? 0 : 1)) + ']</span></div>';
if (game.players.length > 1) {
element += '<div><span class="time-since">' + timeSince(new Date(game.lastModified)) + '</span></div>';
}
element += '<svg class="fa-trash-o hidden"><use xlink:href="#fa-trash-o"></use></svg>'
element += '</span>';
// add sub divs for each user in the game
element += game.players.map(function(item) {
return '<div class="game-player-listing">' + (item.active ? '<' + item.user.username+ '>' : item.user.username) + '</div>';
}).join('');
element += '</div>';
// when the game listing is clicked load that game
$(element).click(function() {
socket.emit('load game', gameID);
$('#chat-wrapper').removeClass('hidden');
$('#menu-checkbox').attr('checked', false);
currentGameID = gameID;
}).appendTo(menuGroup);
// show the game delete/edit button in case it was hidden
$('#game-menu .fa-edit').attr('class','fa-edit');
}
// draw the menus
var $gameListings = $('#game-menu');
var $activeGames = $('#active-games');
var $inactiveGames = $('#inactive-games');
var $finishedGames = $('#finished-games');
// add the active games and separate waiting and finished games
for(var i = 0; i < userGames.length; i++) {
if(userGames[i].finished) {
if($gameListings.has('#game-' + userGames[i]._id).length) {
$('#game-' + userGames[i]._id).appendTo($finishedGames);
} else {
addNewGameListing(userGames[i], $finishedGames);
}
} else {
var active = false;
for(var k = 0; k < userGames[i].players.length; k++) {
if(userGames[i].players[k].user._id === userID &&
userGames[i].players[k].active) {
active = true;
if($gameListings.has('#game-' + userGames[i]._id).length) {
$('#game-' + userGames[i]._id).appendTo($activeGames);
} else {
addNewGameListing(userGames[i], $activeGames);
}
break;
}
}
if(!active) {
if($gameListings.has('#game-' + userGames[i]._id).length) {
$('#game-' + userGames[i]._id).appendTo($inactiveGames);
} else {
addNewGameListing(userGames[i], $inactiveGames);
}
}
}
}
// set up the friends menu
var friends = userFriends.sort(function(a, b) {
var username_a = a.username.toLowerCase();
var username_b = b.username.toLowerCase();
if(username_a > username_b) {
return 1;
}
if(username_a < username_b) {
return -1;
}
return 0;
});
var $friendsList = $('#friends-menu');
// show the friends edit button if there are friends to potentially delete
if(friends.length > 0) {
$friendsList.find('.fa-edit').attr('class','fa-edit');
}
for(var j = 0; j < friends.length; j++) {
if($friendsList.has('#friend-' + friends[j]._id).length === 0) {
// insert the new friend in alphabetical order by display name
var element = '<div class="friend-listing" id="friend-' + friends[j]._id + '"><svg class="fa-trash-o hidden"><use xlink:href="#fa-trash-o"></use></svg><svg class="fa-plus-square-o hidden"><use xlink:href="#fa-plus-square-o"></use></svg><svg class="fa-user"><use xlink:href="#fa-user"></use></svg> ' + friends[j].username + '</div>';
if(j === 0) {
$(element).appendTo("#friends-list");
} else {
$(element).insertAfter('#friend-' + friends[j-1]._id);
}
}
}
// reset the active tile if the user clicks the background and isn't doing a zoom/pan
d3.select('#game-background').on('click', function() {
if (d3.event.defaultPrevented === false) {
resetActiveTile(true);
}
});
// update the SVG on resize
$(window).on("debouncedresize", function () { if(lastGamestate) { draw(lastGamestate); }});
// listen for new gamestate data from the server
socket.on('sending gamestate', function(gamestate, loadingGame) {
// update the tile count in the menu
$('#game-' + gamestate._id + ' .tile-count').text('[' + (gamestate.unusedTiles.length + (gamestate.finished ? 0 : 1)) + ']');
// put the game listing in the correct place in the menu
var $activeGames = $('#active-games');
var $inactiveGames = $('#inactive-games');
var $finishedGames = $('#finished-games');
var $newGame = $('#game-' + gamestate._id);
// mark the active players name with <username> in the game list
var activePlayerIndex = 0;
while(!gamestate.players[activePlayerIndex].active && activePlayerIndex < gamestate.players.length) {
activePlayerIndex++;
}
$newGame.children('.game-player-listing').text(function(i, text) {
var username = text.replace('<','').replace('>','');
return (i === activePlayerIndex ? '<' + username + '>' : username)
});
// put the game listing in the correct category in the menu
if(gamestate.finished) {
if($finishedGames.has($newGame).length === 0) {
$newGame.appendTo($finishedGames);
}
} else {
var active = false;
for(var k = 0; k < gamestate.players.length; k++) {
if(gamestate.players[k].user._id === userID &&
gamestate.players[k].active) {
active = true;
if($activeGames.has($newGame).length === 0) {
$newGame.appendTo($activeGames);
}
break;
}
}
if(!active) {
if($inactiveGames.has($newGame).length === 0) {
$newGame.appendTo($inactiveGames);
}
}
}
// update the page title to inform the user there is something new if it is their turn
if(gamestate.players[activePlayerIndex].user._id === userID && !loadingGame) {
document.title = '(!) Concarneau';
$('body').on('mousemove', function() {
document.title = 'Concarneau';
$('body').off('mousemove');
});
// if the sound notifications are enabled play one
if($('#sound-notifications-checkbox').is(':checked')) {
new Audio('/content/sounds/church-bell.mp3').play();
}
}
// if this is the first time loading this game clear the chat list and redraw all messages
if(loadingGame) {
// draw chat messages into chat box grouped by username
$('#chat-header-label span').text(' Chat');
var $chatBody = $('#chat-body');
var $messageList = $('#chat-message-list').detach();
$messageList.empty();
var index = 0;
while(index < gamestate.messages.length) {
var username = gamestate.messages[index].username;
var messageGroup = [];
while(messageGroup.length === 0 ||
(index < gamestate.messages.length && gamestate.messages[index].username === username)) {
messageGroup.push(gamestate.messages[index].message);
index++
}
// if there is no username this is a system generated message so don't draw a username and apply the system message class
var $li = username === null ? $('<li>') : $('<li>').append($('<div class="chat-user-name">').text(username + ':'));
for(var j = 0; j < messageGroup.length; j++) {
$li.append($(username === null ? '<div class="chat-system-message">' : '<div class="chat-message">').text(messageGroup[j]));
}
$messageList.append($li);
}
$chatBody.append($messageList);
// scroll chat messages to bottom
$chatBody.scrollTop($chatBody[0].scrollHeight);
$('#chat-footer input').val('');
$('#chat-wrapper').removeClass('hidden');