forked from btouellette/concarneau
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gamestate.js
1574 lines (1558 loc) · 63.4 KB
/
gamestate.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
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
/* jslint smarttabs:true */
// load the things we need
var mongoose = require('mongoose');
var moniker = require('moniker');
var Q = require('q');
var Tile = require('../models/tile');
var User = require('../models/user');
// Tile features are defined in terms of the cardinal directions they use
// Roads and cities potentially connect cardinal directions (N S E W)
// Fields potentially connect secondary-intercardinal directions (NNW NNE ENE ESE SSE SSW WSW WNW)
// NW NNW N NNE NE
// WNW ENE
// W * E
// WSW ESE
// SW SSW S SSE SE
// define the schema for our game model
var gamestateSchema = mongoose.Schema({
name: String,
expansions: [String],
finished: { type: Boolean, default: false },
messages: [{ username: String, message: { type: String, trim: true } }], // if there is no username this is a message generated by the game
players: [{
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
points: Number,
remainingMeeples: Number,
hasLargeMeeple: Boolean,
hasPigMeeple: Boolean,
hasBuilderMeeple: Boolean,
active: Boolean,
color: String,
acknowledgedGameEnd: Boolean,
goods: {
fabric: Number,
wine: Number,
wheat: Number
},
towers: Number,
capturedMeeples: [{
meepleType: String,
playerIndex: Number
}]
}],
unusedTiles: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Tile' }],
activeTile: {
tile: { type: mongoose.Schema.Types.ObjectId, ref: 'Tile' },
validPlacements: [{
x: Number,
y: Number,
rotations: [{
rotation: Number,
meeples: [{
meepleType: String, // 'normal', 'large', 'pig', 'builder', etc for different types of meeples
locationType: String, // 'road', 'city', 'farm', or 'cloister'
index: Number // which element of tiles[].roads/cities/farms (external schema)
}]
}]
}],
discardedTiles: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Tile' }]
},
placedTiles: [{
tile: { type: mongoose.Schema.Types.ObjectId, ref: 'Tile' },
rotation: Number, // number of times tile is rotated clockwise
meeples: [{
playerIndex: Number, // references players
placement: {
locationType: String, // 'road', 'city', 'farm', or 'cloister'
index: Number // which element of tiles[].roads/cities/farms (external schema)
},
meepleType: String, // 'normal', 'large', 'pig', 'builder', etc for different types of meeples
scored: Boolean // whether the meeple has already had score assigned for it (only used at game end, otherwise the meeple is removed when it is scored)
}],
tower: {
height: Number, // number of tower floors placed on this tower
completed: Boolean,
meepleType: String, // 'normal' or 'large', only followers can be used to complete a tower
playerIndex: Number // which player completed this tower
},
northTileIndex: Number, // references placedTiles
southTileIndex: Number,
westTileIndex: Number,
eastTileIndex: Number,
x: Number,
y: Number,
playerIndex: Number // which player placed this tile
}],
lastModified: { type: Date, default: new Date() }
});
function getMeepleFlagFromType(meepleType) {
return 'has' + meepleType.charAt(0).toUpperCase() + meepleType.slice(1) + 'Meeple';
}
gamestateSchema.methods.userIsInGame = function(user) {
var gamestate = this;
var userID = user;
if(typeof user !== 'string') {
userID = user._id.toHexString();
}
var inGame = false;
for(var i = 0; i < gamestate.players.length; i++) {
var id = gamestate.players[i].user._id || gamestate.players[i].user;
inGame = inGame || id.equals(userID);
}
return inGame;
};
gamestateSchema.methods.userIsActive = function(user) {
var gamestate = this;
var userID = user;
if(typeof user !== 'string') {
userID = user._id.toHexString();
}
var active = false;
for(var i = 0; i < gamestate.players.length; i++) {
var id = gamestate.players[i].user._id || gamestate.players[i].user;
active = active || (id.equals(userID) && gamestate.players[i].active);
}
return active;
};
function completeGame(gamestate) {
// score and remove all currently placed meeples
for(var i = 0; i < gamestate.placedTiles.length; i++) {
var tile = gamestate.placedTiles[i];
for(var k = 0; k < tile.meeples.length; k++) {
if(!tile.meeples[k].scored &&
(tile.meeples[k].meepleType === 'normal' || tile.meeples[k].meepleType === 'large')) {
// console.log('finalizing meeple=>');
// console.log(JSON.stringify(tile.meeples[k]));
checkAndFinalizeFeature(tile, tile.meeples[k].placement.index, tile.meeples[k].placement.locationType, true, gamestate);
}
}
}
if(gamestate.expansions.indexOf('traders-and-builders') !== -1) {
// add 10 points for the users with the most of each trade good
var maxGoods = {
fabric: 0,
wine: 0,
wheat: 0
};
// find the max number picked up for each token type
for(var j = 0; j < gamestate.players.length; j++) {
maxGoods.fabric = Math.max(gamestate.players[j].goods.fabric, maxGoods.fabric);
maxGoods.wine = Math.max(gamestate.players[j].goods.wine, maxGoods.wine);
maxGoods.wheat = Math.max(gamestate.players[j].goods.wheat, maxGoods.wheat);
}
// construct messages about scoring for the chat log
var fabricMessage = '';
var wineMessage = '';
var wheatMessage = '';
for(var l = 0; l < gamestate.players.length; l++) {
if(gamestate.players[l].goods.fabric === maxGoods.fabric) {
gamestate.players[l].points += 10;
if(fabricMessage !== '') {
fabricMessage += ' and ';
}
fabricMessage += gamestate.players[l].user.username + ' (' + gamestate.players[l].points + ')';
}
if(gamestate.players[l].goods.wine === maxGoods.wine) {
gamestate.players[l].points += 10;
if(wineMessage !== '') {
wineMessage += ' and ';
}
wineMessage += gamestate.players[l].user.username + ' (' + gamestate.players[l].points + ')';
}
if(gamestate.players[l].goods.wheat === maxGoods.wheat) {
gamestate.players[l].points += 10;
if(wheatMessage !== '') {
wheatMessage += ' and ';
}
wheatMessage += gamestate.players[l].user.username + ' (' + gamestate.players[l].points + ')';
}
}
fabricMessage += ' scored 10 points for having the most fabric tokens';
wineMessage += ' scored 10 points for having the most wine tokens';
wheatMessage += ' scored 10 points for having the most wheat tokens';
gamestate.messages.push({ username: null, message: fabricMessage });
gamestate.messages.push({ username: null, message: wineMessage });
gamestate.messages.push({ username: null, message: wheatMessage });
}
gamestate.finished = true;
}
gamestateSchema.methods.drawTile = function(callback, autocomplete) {
this.populate('unusedTiles placedTiles.tile players.user', function(err, gamestate) {
// if we're out of tiles score/complete game
if(gamestate.unusedTiles.length === 0 || autocomplete) {
completeGame(gamestate);
}
// move one random tile from unused to active
var potentialPlacements = [], discardedTiles = [];
var currentTile, rotatedTile, activeTile;
var rotatedPlacements;
var rotatedTiles = gamestate.placedTiles.map(function getRotatedTileEdges(gamestateTile) {
return gamestateTile.rotation === 0 ?
{
northEdge: gamestateTile.tile.northEdge,
eastEdge: gamestateTile.tile.eastEdge,
southEdge: gamestateTile.tile.southEdge,
westEdge: gamestateTile.tile.westEdge
}
: gamestateTile.rotation === 1 ?
{
northEdge: gamestateTile.tile.westEdge,
eastEdge: gamestateTile.tile.northEdge,
southEdge: gamestateTile.tile.eastEdge,
westEdge: gamestateTile.tile.southEdge
}
: gamestateTile.rotation === 2 ?
{
northEdge: gamestateTile.tile.southEdge,
eastEdge: gamestateTile.tile.westEdge,
southEdge: gamestateTile.tile.northEdge,
westEdge: gamestateTile.tile.eastEdge
}
:
{
northEdge: gamestateTile.tile.eastEdge,
eastEdge: gamestateTile.tile.southEdge,
southEdge: gamestateTile.tile.westEdge,
westEdge: gamestateTile.tile.northEdge
};
});
while(potentialPlacements.length === 0 && gamestate.unusedTiles.length > 0 && !autocomplete) {
// splice a random unused tile into the active tile
activeTile = gamestate.unusedTiles.splice(Math.floor(Math.random()*gamestate.unusedTiles.length), 1)[0];
// make sure mongoose sees the field as changed to save later
gamestate.markModified('unusedTiles');
// find out all the places we can place it
for(var i = 0; i < gamestate.placedTiles.length; i++) {
currentTile = gamestate.placedTiles[i];
rotatedTile = rotatedTiles[i];
if(currentTile.northTileIndex === undefined) {
if(rotatedTile.northEdge === activeTile.northEdge) {
potentialPlacements.push({
x: currentTile.x,
y: currentTile.y - 1,
rotation: 2,
sourceIndex: i,
directionToSource: 'S',
directionFromSource: 'N'
});
}
if(rotatedTile.northEdge === activeTile.eastEdge) {
potentialPlacements.push({
x: currentTile.x,
y: currentTile.y - 1,
rotation: 1,
sourceIndex: i,
directionToSource: 'S',
directionFromSource: 'N'
});
}
if(rotatedTile.northEdge === activeTile.southEdge) {
potentialPlacements.push({
x: currentTile.x,
y: currentTile.y - 1,
rotation: 0,
sourceIndex: i,
directionToSource: 'S',
directionFromSource: 'N'
});
}
if(rotatedTile.northEdge === activeTile.westEdge) {
potentialPlacements.push({
x: currentTile.x,
y: currentTile.y - 1,
rotation: 3,
sourceIndex: i,
directionToSource: 'S',
directionFromSource: 'N'
});
}
}
if(currentTile.eastTileIndex === undefined) {
if(rotatedTile.eastEdge === activeTile.northEdge) {
potentialPlacements.push({
x: currentTile.x + 1,
y: currentTile.y,
rotation: 3,
sourceIndex: i,
directionToSource: 'W',
directionFromSource: 'E'
});
}
if(rotatedTile.eastEdge === activeTile.eastEdge) {
potentialPlacements.push({
x: currentTile.x + 1,
y: currentTile.y,
rotation: 2,
sourceIndex: i,
directionToSource: 'W',
directionFromSource: 'E'
});
}
if(rotatedTile.eastEdge === activeTile.southEdge) {
potentialPlacements.push({
x: currentTile.x + 1,
y: currentTile.y,
rotation: 1,
sourceIndex: i,
directionToSource: 'W',
directionFromSource: 'E'
});
}
if(rotatedTile.eastEdge === activeTile.westEdge) {
potentialPlacements.push({
x: currentTile.x + 1,
y: currentTile.y,
rotation: 0,
sourceIndex: i,
directionToSource: 'W',
directionFromSource: 'E'
});
}
}
if(currentTile.southTileIndex === undefined) {
if(rotatedTile.southEdge === activeTile.northEdge) {
potentialPlacements.push({
x: currentTile.x,
y: currentTile.y + 1,
rotation: 0,
sourceIndex: i,
directionToSource: 'N',
directionFromSource: 'S'
});
}
if(rotatedTile.southEdge === activeTile.eastEdge) {
potentialPlacements.push({
x: currentTile.x,
y: currentTile.y + 1,
rotation: 3,
sourceIndex: i,
directionToSource: 'N',
directionFromSource: 'S'
});
}
if(rotatedTile.southEdge === activeTile.southEdge) {
potentialPlacements.push({
x: currentTile.x,
y: currentTile.y + 1,
rotation: 2,
sourceIndex: i,
directionToSource: 'N',
directionFromSource: 'S'
});
}
if(rotatedTile.southEdge === activeTile.westEdge) {
potentialPlacements.push({
x: currentTile.x,
y: currentTile.y + 1,
rotation: 1,
sourceIndex: i,
directionToSource: 'N',
directionFromSource: 'S'
});
}
}
if(currentTile.westTileIndex === undefined) {
if(rotatedTile.westEdge === activeTile.northEdge) {
potentialPlacements.push({
x: currentTile.x - 1,
y: currentTile.y,
rotation: 1,
sourceIndex: i,
directionToSource: 'E',
directionFromSource: 'W'
});
}
if(rotatedTile.westEdge === activeTile.eastEdge) {
potentialPlacements.push({
x: currentTile.x - 1,
y: currentTile.y,
rotation: 0,
sourceIndex: i,
directionToSource: 'E',
directionFromSource: 'W'
});
}
if(rotatedTile.westEdge === activeTile.southEdge) {
potentialPlacements.push({
x: currentTile.x - 1,
y: currentTile.y,
rotation: 3,
sourceIndex: i,
directionToSource: 'E',
directionFromSource: 'W'
});
}
if(rotatedTile.westEdge === activeTile.westEdge) {
potentialPlacements.push({
x: currentTile.x - 1,
y: currentTile.y,
rotation: 2,
sourceIndex: i,
directionToSource: 'E',
directionFromSource: 'W'
});
}
}
}
rotatedPlacements = potentialPlacements.map(function(currentPlacement) {
return currentPlacement.rotation === 0 ?
{
northEdge: activeTile.northEdge,
eastEdge: activeTile.eastEdge,
southEdge: activeTile.southEdge,
westEdge: activeTile.westEdge
}
: currentPlacement.rotation === 1 ?
{
northEdge: activeTile.westEdge,
eastEdge: activeTile.northEdge,
southEdge: activeTile.eastEdge,
westEdge: activeTile.southEdge
}
: currentPlacement.rotation === 2 ?
{
northEdge: activeTile.southEdge,
eastEdge: activeTile.westEdge,
southEdge: activeTile.northEdge,
westEdge: activeTile.eastEdge
}
:
{
northEdge: activeTile.eastEdge,
eastEdge: activeTile.southEdge,
southEdge: activeTile.westEdge,
westEdge: activeTile.northEdge
};
});
var invalidPlacementIndices = [];
// remove placements which conflict with already placed tiles
for(var k = 0; k < gamestate.placedTiles.length; k++) {
currentTile = gamestate.placedTiles[k];
rotatedTile = rotatedTiles[k];
for(var j = 0; j < potentialPlacements.length; j++) {
var placement = potentialPlacements[j];
var rotatedPlacement = rotatedPlacements[j];
if((currentTile.x === placement.x && currentTile.y - 1 === placement.y && rotatedTile.northEdge !== rotatedPlacement.southEdge) ||
(currentTile.x === placement.x && currentTile.y + 1 === placement.y && rotatedTile.southEdge !== rotatedPlacement.northEdge) ||
(currentTile.y === placement.y && currentTile.x - 1 === placement.x && rotatedTile.westEdge !== rotatedPlacement.eastEdge) ||
(currentTile.y === placement.y && currentTile.x + 1 === placement.x && rotatedTile.eastEdge !== rotatedPlacement.westEdge)) {
invalidPlacementIndices.push(j);
}
}
}
potentialPlacements = potentialPlacements.filter(function(placement, index) {
return invalidPlacementIndices.indexOf(index) === -1;
});
rotatedPlacements = rotatedPlacements.filter(function(placement, index) {
return invalidPlacementIndices.indexOf(index) === -1;
});
if(potentialPlacements.length === 0) {
// console.log('=======discarded tile=====');
discardedTiles.push(activeTile);
}
}
// calculate valid meeple placements for each valid tile placement
for(var index = 0; index < potentialPlacements.length; index++) {
var currentPlacement = potentialPlacements[index];
var adjacentTile = gamestate.placedTiles[currentPlacement.sourceIndex];
// console.log('calculating meeple placements: ' + currentPlacement.x + ',' + currentPlacement.y);
currentPlacement.meeples = [];
// meeple placement is valid if for all directions in a (rotated) feature
// direction isn't pointed to the adjacent tile OR adjacent tile feature isn't owned
var directions = ['N','E','S','W'];
// check each city for valid meeple placements
var valid, adjacentIndex, featureInfo, meepleIndex, placedTile;
for(var index2 = 0; index2 < activeTile.cities.length; index2++) {
// assume we can place unless we find that there are other meeples on this feature
valid = true;
featureInfo = null;
// check the adjacent tile (in the direction the current tiles city is pointing) for conflicting meeples
var rotatedCityDirections = activeTile.cities[index2].directions.map(function(direction) {
return directions[(directions.indexOf(direction) + currentPlacement.rotation) % 4];
});
// if we find another city in that direction only remain valid if there are no other meeples on it
if(rotatedCityDirections.indexOf(currentPlacement.directionToSource) !== -1) {
adjacentIndex = getFeatureIndex(adjacentTile, 'city', currentPlacement.directionFromSource);
featureInfo = getFeatureInfo(adjacentTile, adjacentIndex, 'city', gamestate);
valid = featureInfo.tilesWithMeeples.length === 0;
// if there was a city with meeples already on it and it is this (the active) player's add a valid placement for the builder
for(var i1 = 0; i1 < featureInfo.tilesWithMeeples.length; i1++) {
meepleIndex = featureInfo.tilesWithMeeples[i1].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[i1].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'builder',
locationType: 'city',
index: index2
});
break;
}
}
}
if(valid) {
// add to placement
currentPlacement.meeples.push({
meepleType: 'normal',
locationType: 'city',
index: index2
});
}
}
// check each road for valid meeple placements
for(var index3 = 0; index3 < activeTile.roads.length; index3++) {
// assume we can place unless we find that there are other meeples on this feature
valid = true;
featureInfo = null;
// check the adjacent tile (in the direction the current tiles road is pointing) for conflicting meeples
var rotatedRoadDirections = activeTile.roads[index3].directions.map(function(direction) {
return directions[(directions.indexOf(direction) + currentPlacement.rotation) % 4];
});
// if we find another road in that direction only remain valid if there are no other meeples on it
if(rotatedRoadDirections.indexOf(currentPlacement.directionToSource) !== -1) {
adjacentIndex = getFeatureIndex(adjacentTile, 'road', currentPlacement.directionFromSource);
featureInfo = getFeatureInfo(adjacentTile, adjacentIndex, 'road', gamestate);
valid = featureInfo.tilesWithMeeples.length === 0;
// if there was a road with meeples already on it and it is this (the active) player's add a valid placement for the builder
for(var i2 = 0; i2 < featureInfo.tilesWithMeeples.length; i2++) {
meepleIndex = featureInfo.tilesWithMeeples[i2].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[i2].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'builder',
locationType: 'road',
index: index3
});
break;
}
}
}
if(valid) {
// add to placement
currentPlacement.meeples.push({
meepleType: 'normal',
locationType: 'road',
index: index3
});
}
}
// check each farm for valid meeple placements
var farmDirections = ['NNE','ENE','ESE','SSE','SSW','WSW','WNW','NNW'];
for(var index4 = 0; index4 < activeTile.farms.length; index4++) {
// console.log('checking farm: ' + index4 + ' ' + JSON.stringify(activeTile.farms[index4]));
valid = true;
var rotatedFarmDirections = activeTile.farms[index4].directions.map(function(direction) {
return farmDirections[(farmDirections.indexOf(direction) + currentPlacement.rotation * 2) % 8];
});
if(currentPlacement.directionToSource === 'N') {
// console.log('looking ' + currentPlacement.directionToSource);
if(rotatedFarmDirections.indexOf('NNW') !== -1) {
featureInfo = getFeatureInfo(adjacentTile, getFeatureIndex(adjacentTile, 'farm', 'SSW'), 'farm', gamestate);
for(var iSSW = 0; iSSW < featureInfo.tilesWithMeeples.length; iSSW++) {
meepleIndex = featureInfo.tilesWithMeeples[iSSW].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[iSSW].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'pig',
locationType: 'farm',
index: index4
});
break;
}
}
valid = valid && featureInfo.tilesWithMeeples.length === 0;
// console.log('NNW ' + valid);
}
if(rotatedFarmDirections.indexOf('NNE') !== -1) {
featureInfo = getFeatureInfo(adjacentTile, getFeatureIndex(adjacentTile, 'farm', 'SSE'), 'farm', gamestate);
for(var iSSE = 0; iSSE < featureInfo.tilesWithMeeples.length; iSSE++) {
meepleIndex = featureInfo.tilesWithMeeples[iSSE].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[iSSE].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'pig',
locationType: 'farm',
index: index4
});
break;
}
}
valid = valid && featureInfo.tilesWithMeeples.length === 0;
// console.log('NNE ' + valid);
}
} else if(currentPlacement.directionToSource === 'E') {
// console.log('looking ' + currentPlacement.directionToSource);
if(rotatedFarmDirections.indexOf('ENE') !== -1) {
featureInfo = getFeatureInfo(adjacentTile, getFeatureIndex(adjacentTile, 'farm', 'WNW'), 'farm', gamestate);
for(var iWNW = 0; iWNW < featureInfo.tilesWithMeeples.length; iWNW++) {
meepleIndex = featureInfo.tilesWithMeeples[iWNW].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[iWNW].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'pig',
locationType: 'farm',
index: index4
});
break;
}
}
valid = valid && featureInfo.tilesWithMeeples.length === 0;
// console.log('ENE ' + valid);
}
if(rotatedFarmDirections.indexOf('ESE') !== -1) {
featureInfo = getFeatureInfo(adjacentTile, getFeatureIndex(adjacentTile, 'farm', 'WSW'), 'farm', gamestate);
for(var iWSW = 0; iWSW < featureInfo.tilesWithMeeples.length; iWSW++) {
meepleIndex = featureInfo.tilesWithMeeples[iWSW].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[iWSW].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'pig',
locationType: 'farm',
index: index4
});
break;
}
}
valid = valid && featureInfo.tilesWithMeeples.length === 0;
// console.log('ESE ' + valid);
}
} else if(currentPlacement.directionToSource === 'S') {
// console.log('looking ' + currentPlacement.directionToSource);
if(rotatedFarmDirections.indexOf('SSW') !== -1) {
featureInfo = getFeatureInfo(adjacentTile, getFeatureIndex(adjacentTile, 'farm', 'NNW'), 'farm', gamestate);
for(var iNNW = 0; iNNW < featureInfo.tilesWithMeeples.length; iNNW++) {
meepleIndex = featureInfo.tilesWithMeeples[iNNW].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[iNNW].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'pig',
locationType: 'farm',
index: index4
});
break;
}
}
valid = valid && featureInfo.tilesWithMeeples.length === 0;
// console.log('SSW ' + valid);
}
if(rotatedFarmDirections.indexOf('SSE') !== -1) {
featureInfo = getFeatureInfo(adjacentTile, getFeatureIndex(adjacentTile, 'farm', 'NNE'), 'farm', gamestate);
for(var iNNE = 0; iNNE < featureInfo.tilesWithMeeples.length; iNNE++) {
meepleIndex = featureInfo.tilesWithMeeples[iNNE].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[iNNE].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'pig',
locationType: 'farm',
index: index4
});
break;
}
}
valid = valid && featureInfo.tilesWithMeeples.length === 0;
// console.log('SSE ' + valid);
}
} else if(currentPlacement.directionToSource === 'W') {
// console.log('looking ' + currentPlacement.directionToSource);
if(rotatedFarmDirections.indexOf('WNW') !== -1) {
featureInfo = getFeatureInfo(adjacentTile, getFeatureIndex(adjacentTile, 'farm', 'ENE'), 'farm', gamestate);
for(var iENE = 0; iENE < featureInfo.tilesWithMeeples.length; iENE++) {
meepleIndex = featureInfo.tilesWithMeeples[iENE].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[iENE].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'pig',
locationType: 'farm',
index: index4
});
break;
}
}
valid = valid && featureInfo.tilesWithMeeples.length === 0;
// console.log('WNW ' + valid);
}
if(rotatedFarmDirections.indexOf('WSW') !== -1) {
featureInfo = getFeatureInfo(adjacentTile, getFeatureIndex(adjacentTile, 'farm', 'ESE'), 'farm', gamestate);
for(var iESE = 0; iESE < featureInfo.tilesWithMeeples.length; iESE++) {
meepleIndex = featureInfo.tilesWithMeeples[iESE].meepleIndex;
placedTile = featureInfo.tilesWithMeeples[iESE].placedTile;
if(gamestate.players[placedTile.meeples[meepleIndex].playerIndex].active) {
currentPlacement.meeples.push({
meepleType: 'pig',
locationType: 'farm',
index: index4
});
break;
}
}
valid = valid && featureInfo.tilesWithMeeples.length === 0;
// console.log('WSW ' + valid);
}
}
if(valid) {
// add to placement
currentPlacement.meeples.push({
meepleType: 'normal',
locationType: 'farm',
index: index4
});
}
}
// if there is a cloister on the active tile it will always be valid for any rotation
if(activeTile.cloister) {
currentPlacement.meeples.push({
meepleType: 'normal',
locationType: 'cloister',
index: 0
});
}
}
gamestate.activeTile.tile = activeTile;
gamestate.activeTile.discarded = discardedTiles;
// console.log('ungrouped placements =>' + JSON.stringify(potentialPlacements));
// console.log('==========================');
// remove duplicates while storing an array of potential rotations and meeple placements for each position
// duplicates are created because the potential placement generation only looks at one adjacent tile each time
// meeples for valid placements must be valid for ALL potential placements with same x/y/rotation
// otherwise at some point there was a conflict for that meeple placement found
var groupedPlacements = {};
potentialPlacements.forEach(function(item) {
var key = item.x + ',' + item.y;
if(groupedPlacements[key]) {
var matched = false;
for(var i = 0; i < groupedPlacements[key].rotations.length; i++) {
var currentRotation = groupedPlacements[key].rotations[i];
// if this rotation has already been placed
if(currentRotation.rotation === item.rotation) {
matched = true;
// since non-normal meeples don't have disqualifying conditions (only qualifying ones aka an existing active meeple) allow all unless they would be duplicates
for(var j = 0; j < item.meeples.length; j++) {
var newMeeple = item.meeples[j];
if(newMeeple.meepleType !== 'normal') {
var duplicated = false;
for(var k = 0; k < currentRotation.meeples.length; k++) {
var existingMeeple = currentRotation.meeples[k];
if(existingMeeple.meepleType === newMeeple.meepleType &&
existingMeeple.locationType === newMeeple.locationType &&
existingMeeple.index === newMeeple.index) {
duplicated = true;
break;
}
}
if(!duplicated) {
currentRotation.meeples.push(newMeeple);
}
}
}
// only keep normal meeple placements that are valid in both tile placements
currentRotation.meeples = currentRotation.meeples.filter(function(meeple, index) {
if(meeple.meepleType === 'normal') {
for(var i = 0; i < item.meeples.length; i++) {
if(item.meeples[i].meepleType === meeple.meepleType &&
item.meeples[i].locationType === meeple.locationType &&
item.meeples[i].index === meeple.index) {
return true;
}
}
return false;
} else {
return true;
}
});
break;
}
}
// if it hasn't been placed add it
if(!matched) {
groupedPlacements[key].rotations.push({
rotation: item.rotation,
meeples: item.meeples
});
}
} else {
groupedPlacements[key] = {
x: item.x,
y: item.y,
rotations: [{
rotation: item.rotation,
meeples: item.meeples
}]
};
}
});
// place each grouped item into the valid placements for the active tile
gamestate.activeTile.validPlacements = [];
for (var key in groupedPlacements) {
gamestate.activeTile.validPlacements.push(groupedPlacements[key]);
}
gamestate.lastModified = new Date();
gamestate.markModified('lastModified');
if(autocomplete) {
callback(null, gamestate);
return;
}
gamestate.save(callback);
});
};
gamestateSchema.methods.initializeNewGame = function(initialUser, friends, expansions, callback) {
var newGame = this;
// create a random name to identify the game
newGame.name = moniker.choose();
// record the expansions enabled for this game
newGame.expansions = expansions;
// add the initial players
var allPlayers = friends.concat([initialUser._id]);
newGame.players = allPlayers.map(function(userID) { return { user: userID }; });
// add the game to the users' active games
var userGamesUpdated = User.update({ _id: { $in: allPlayers }},
{ $push: { activeGames: newGame._id }},
{ multi: true }).exec();
// grab the starting tile and make it the only placed tile
var startTilePlaced = Tile.findOne({ startingTile: true, expansion: 'base-game' }).exec(function(err, startTile) {
newGame.placedTiles.unshift({
tile: startTile._id,
rotation: 0,
x: 0,
y: 0
});
});
// grab the rest of the tiles and put them in the unplaced list
var unusedTilesLoaded = Tile.find({ expansion: { $in: expansions }}).exec(function(err, allTiles) {
// load a copy of each unused tile based on their counts, skip one copy of the starting tile
for(var i = 0; i < allTiles.length; i++) {
var countToAdd = allTiles[i].startingTile ? allTiles[i].count - 1 : allTiles[i].count;
for(var j = 0; j < countToAdd; j++) {
newGame.unusedTiles.push(allTiles[i]._id);
}
}
});
Q.all([userGamesUpdated, startTilePlaced, unusedTilesLoaded]).then(function() {
var colors = ['blue', 'green', 'purple', 'red', 'yellow'];
// only use gray color if there is a 6th player
if(newGame.players.length > 5) {
colors.push('gray');
}
// choose a random player to start
var startingPlayer = Math.floor(Math.random()*newGame.players.length);
// set default attributes for each player
for(var i = 0; i < newGame.players.length; i++) {
newGame.players[i].active = (i === startingPlayer);
newGame.players[i].points = 0;
newGame.players[i].remainingMeeples = 7;
// choose a random remaining color for this player
newGame.players[i].color = colors.splice(Math.floor(Math.random()*colors.length), 1)[0];
if(expansions.indexOf('inns-and-cathedrals') !== -1) {
newGame.players[i].hasLargeMeeple = true;
}
if(expansions.indexOf('traders-and-builders') !== -1) {
newGame.players[i].hasPigMeeple = true;
newGame.players[i].hasBuilderMeeple = true;
newGame.players[i].goods = {
fabric: 0,
wine: 0,
wheat: 0
};
}
if(expansions.indexOf('the-tower') !== -1) {
newGame.players[i].towers = newGame.players.length === 1 ? 30 : // if playing solo let them have all the tower pieces
newGame.players.length === 2 ? 10 :
newGame.players.length === 3 ? 9 :
newGame.players.length === 4 ? 7 :
newGame.players.length === 5 ? 6 :
5;
}
}
// start the game by drawing the first tile
newGame.drawTile(callback);
});
};
//TODO: remove all autocomplete
gamestateSchema.methods.placeTile = function(move, callback, autocomplete) {
/* move: {
* placement: { // x and y of where the tile is to be placed
* x: Number,
* y: Number,
* },
* rotation: Number, // number of clockwise 90° rotations
* meeple: {
* meepleType: String, // 'normal', 'large', 'pig', etc
* locationType: String,
* index: Number
* },
* tower: {
* meepleType: String, // 'normal' or 'large', only set if tower is being completed instead of added to
* tileIndex: Number, // index of tile tower or completing meeple is being placed on
* capture: {
* tileIndex: Number, // index in placedTiles of tile whose meeple is being captured
* meepleIndex: Number, // index in placedTiles.meeples of meeple being captured
* exchangeType: String
* }
* }
* }
*/
this.populate('activeTile.tile players.user', function(err, gamestate) {
var validPlacement = false;
// get the active player
var activePlayer, activePlayerIndex;
for(var i1 = 0; i1 < gamestate.players.length; i1++) {
if(gamestate.players[i1].active) {
activePlayer = gamestate.players[i1];
activePlayerIndex = i1;
break;
}
}
// if move is using older move format still (due to cached page) convert it to the new format
if(move && move.meeple && !move.meeple.meepleType) {
move.meeple.meepleType = move.meeple.large ? 'large' : 'normal';
}
// validate tile and meeple placement
for(var i2 = 0; i2 < gamestate.activeTile.validPlacements.length; i2++) {
var placement = gamestate.activeTile.validPlacements[i2];
if(placement.x === move.placement.x &&
placement.y === move.placement.y) {
for(var i3 = 0; i3 < placement.rotations.length; i3++) {
if(placement.rotations[i3].rotation === move.rotation) {
// the placement is valid if this x/y/rotation was previously added to the active tiles valid placements
// and either there wasn't a meeple placed
// or there was a meeple placed and the user has at least 1 normal meeple or the has(MeepleType)Meeple flag is true for their player
if(!move.meeple) {
validPlacement = true;
} else if((move.meeple.meepleType === 'normal' && activePlayer.remainingMeeples > 0) ||
(move.meeple.meepleType !== 'normal' && activePlayer[getMeepleFlagFromType(move.meeple.meepleType)])) {
var meepleType = move.meeple.meepleType === 'large' ? 'normal' : move.meeple.meepleType;
for(var i4 = 0; i4 < placement.rotations[i3].meeples.length; i4++) {
if(placement.rotations[i3].meeples[i4].meepleType === meepleType &&
placement.rotations[i3].meeples[i4].locationType === move.meeple.locationType &&
placement.rotations[i3].meeples[i4].index === move.meeple.index) {
validPlacement = true;
break;
}
}
}
break;
}
}
break;
}
}
if(validPlacement) {
// add tile creating proper north/south/east/west links to the existing placed tiles
var newTile = {
_id: mongoose.Types.ObjectId(),
tile: gamestate.activeTile.tile,
rotation: move.rotation,
x: move.placement.x,
y: move.placement.y,
playerIndex: activePlayerIndex
};
// validate that the player has the proper type of meeple for placement
if(move.meeple) {
if(move.meeple.meepleType === 'normal' && activePlayer.remainingMeeples > 0) {
activePlayer.remainingMeeples -= 1;
newTile.meeples = [{
playerIndex: activePlayerIndex,
placement: {
locationType: move.meeple.locationType,
index: move.meeple.index
},
meepleType: move.meeple.meepleType
}];
} else if(move.meeple.meepleType !== 'normal') {
var meepleFlagName = getMeepleFlagFromType(move.meeple.meepleType);
if(activePlayer[meepleFlagName] === true) {
activePlayer[meepleFlagName] = false;
newTile.meeples = [{
playerIndex: activePlayerIndex,
placement: {
locationType: move.meeple.locationType,
index: move.meeple.index
},
meepleType: move.meeple.meepleType
}];
}
}
}
// set up the base tower with no tokens if this tile has a tower
// since mongoose creates the entire schema structure check a primitive for undefined rather than "tile.tower"
if(newTile.tile.tower.offset.x) {
newTile.tower = {
height: 0,
completed: false
};
}
// create links between the new tile and existing placed tiles
for(var i5 = 0; i5 < gamestate.placedTiles.length; i5++) {
var placedTile = gamestate.placedTiles[i5];
if(placedTile.x === newTile.x) {
if(placedTile.y === newTile.y - 1) {
newTile.northTileIndex = i5;
placedTile.southTileIndex = gamestate.placedTiles.length;
} else if(placedTile.y === newTile.y + 1) {
newTile.southTileIndex = i5;