-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockus.js
More file actions
1437 lines (1215 loc) · 39.1 KB
/
blockus.js
File metadata and controls
1437 lines (1215 loc) · 39.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
var DEBUG = false;
function Point(x_, y_) {
this.x = x_;
this.y = y_;
/**
* Takes this point and rotates it by the given angle about the optional
* given origin, default being (0,0), and returns the new point
* @param angle in radians
* @param originX default 0
* @param originY default 0
* @returns new Point
*/
this.rotate = function(angle, originX, originY) {
if (typeof originX == 'undefined') { originX = 0; }
if (typeof originY == 'undefined') { originY = 0; }
var newX = Math.cos(angle) * (this.x - originX) - Math.sin(angle) * (this.y - originY) + originX;
var newY = Math.sin(angle) * (this.x - originX) + Math.cos(angle) * (this.y - originY) + originY;
return new Point(newX, newY);
};
this.equals = function(other) {
return this.x == other.x && this.y == other.y;
};
}
/**
* A real piece that is drawn on the board
* Can be positioned, rotated, and flipped
*/
function Piece(gl, shaderProgram, color, vertices, indices, pointsOfCenters) {
var _gl = gl;
var _shaderProgram = shaderProgram;
var _color = color;
var _loc = new Point(0,0);
var self = this;
var _flipped = false;
var _rotation = 0;
var _vertexBuffer;
var _vertexColorBuffer;
var _indexBuffer;
var _pointsOfCenters = [];
var _init = function(vertices, indices) {
if (typeof pointsOfCenters != 'undefined') {
for (var i = 0; i < pointsOfCenters.length; i += 2) {
_pointsOfCenters = _pointsOfCenters.concat(
new Point(pointsOfCenters[i], pointsOfCenters[i + 1])
);
}
}
// Vertex Buffer
_vertexBuffer = _gl.createBuffer();
_gl.bindBuffer(_gl.ARRAY_BUFFER, _vertexBuffer);
_gl.bufferData(_gl.ARRAY_BUFFER, new Float32Array(vertices), _gl.STATIC_DRAW);
_vertexBuffer.itemSize = 3;
_vertexBuffer.numItems = vertices.length;
// Vertex Color buffer
_vertexColorBuffer = _gl.createBuffer();
_gl.bindBuffer(_gl.ARRAY_BUFFER, _vertexColorBuffer);
var colors = [];
var numVertices = vertices.length / _vertexBuffer.itemSize;
for (var i = 0; i < numVertices; ++i) {
colors = colors.concat(color);
}
_gl.bufferData(_gl.ARRAY_BUFFER, new Float32Array(colors), _gl.STATIC_DRAW);
_vertexColorBuffer.itemSize = 4;
_vertexColorBuffer.numItems = colors.length;
// Index buffer
_indexBuffer = _gl.createBuffer();
_gl.bindBuffer(_gl.ELEMENT_ARRAY_BUFFER, _indexBuffer);
_gl.bufferData(_gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), _gl.STATIC_DRAW);
_indexBuffer.itemSize = 1;
_indexBuffer.numItems = indices.length;
_gl.bindBuffer(_gl.ARRAY_BUFFER, null);
_gl.bindBuffer(_gl.ELEMENT_ARRAY_BUFFER, null);
};
/**
* @returns how many squares this piece has
*/
this.getNumSquares = function() {
return _pointsOfCenters.length;
};
/**
* @returns the collection of squares this piece has
*/
this.getPointsOfCenters = function() {
return _pointsOfCenters;
}
this.getColor = function() {
return _color;
};
this.flip = function() {
_flipped = !_flipped;
_flipPointsOfCenters();
};
/**
* Keeps rotation angle between 0 and 2Pi
*/
this.rotateLeft = function() {
_rotate(Math.PI / 2);
};
/**
* Keeps rotation angle between 0 and 2Pi
*/
this.rotateRight = function() {
_rotate(- Math.PI / 2);
};
var _rotate = function(angle) {
var coefficient = (_flipped ? -1 : 1);
_rotation += coefficient * angle;
if (_rotation == 2 * Math.PI) {
_rotation = 0;
}
else if (_rotation == - Math.PI / 2) {
_rotation = 3 * Math.PI / 2;
}
_rotatePointsOfCenters(angle);
}
/**
* @private
* Flips the points of centers along the y axis by inverting the x coordinates
*/
var _flipPointsOfCenters = function() {
for (var i = 0; i < _pointsOfCenters.length; ++i) {
_pointsOfCenters[i].x *= -1;
}
};
/**
* @private
*/
var _rotatePointsOfCenters = function(angle) {
for (var i = 0; i < _pointsOfCenters.length; ++i) {
var newPoint = _pointsOfCenters[i].rotate(angle);
_pointsOfCenters[i].x = Math.round(newPoint.x);
_pointsOfCenters[i].y = Math.round(newPoint.y);
}
};
/**
* Removes any flips or rotations
*/
this.reset = function() {
// First undo any flips
if (_flipped) {
this.flip();
}
// And then undo any rotations
_rotatePointsOfCenters(-_rotation); // Rotate back to zero
_rotation = 0;
};
/**
* Moves the top left corner of the piece to the given location
* @param loc Point object
*/
this.setLocation = function(loc) {
_loc = loc;
};
/**
* Returns the top left corner of the piece
*/
this.getLocation = function() {
return _loc;
};
/**
* Sets the location of this piece at the mouse position,
* but depending on the rotation adjusts it to the next whole location
*/
this.placeAt = function(mousePos) {
var newX = 0;
var newY = 0;
if (!_flipped) {
if (_rotation == 0) {
newX = Math.floor(mousePos.x);
newY = Math.floor(mousePos.y);
}
else if (_rotation == 3 * Math.PI / 2) {
newX = Math.floor(mousePos.x);
newY = Math.ceil(mousePos.y);
}
else if (_rotation == Math.PI) {
newX = Math.ceil(mousePos.x);
newY = Math.ceil(mousePos.y);
}
else if (_rotation == Math.PI / 2) {
newX = Math.ceil(mousePos.x);
newY = Math.floor(mousePos.y);
}
}
else {
if (_rotation == 0) {
newX = Math.ceil(mousePos.x);
newY = Math.floor(mousePos.y);
}
else if (_rotation == 3 * Math.PI / 2) {
newX = Math.ceil(mousePos.x);
newY = Math.ceil(mousePos.y);
}
else if (_rotation == Math.PI) {
newX = Math.floor(mousePos.x);
newY = Math.ceil(mousePos.y);
}
else if (_rotation == Math.PI / 2) {
newX = Math.floor(mousePos.x);
newY = Math.floor(mousePos.y);
}
}
this.setLocation(new Point(newX, newY));
}
/**
* Draws this piece at its location
*/
this.draw = function() {
_drawAtLocation(_loc);
};
/**
* Draws this piece at the given mouse location
* @param position [x,y] location of the mouse, in world coordinates
*/
this.drawAtMouse = function(position) {
// Offset the piece so that the bottom left square of the piece is centered
// on the location of the mouse
var coefficient = (_flipped ? -1 : 1);
var offsetX = -0.5 * coefficient;
if (_rotation >= Math.PI / 2 && _rotation <= Math.PI) {
offsetX = 0.5 * coefficient;
}
var offsetY = -0.5;
if (_rotation >= Math.PI && _rotation <= 3 * Math.PI / 2) {
offsetY = 0.5;
}
_drawAtLocation(new Point(position.x + offsetX, position.y + offsetY));
};
/**
* @private
* Draws this piece at the given location
* @param position [x,y] location to draw the piece in world coordinates
*/
var _drawAtLocation = function(position) {
_gl.bindBuffer(_gl.ARRAY_BUFFER, _vertexBuffer);
_gl.vertexAttribPointer(_shaderProgram.vertexPositionAttribute, _vertexBuffer.itemSize, _gl.FLOAT, false, 0, 0);
_gl.bindBuffer(_gl.ARRAY_BUFFER, _vertexColorBuffer);
_gl.vertexAttribPointer(_shaderProgram.vertexColorAttribute, _vertexColorBuffer.itemSize, _gl.FLOAT, false, 0, 0);
_gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer);
mvPushMatrix();
// Transformations have to be in the opposite order desired
// 3) Move the piece to the given location
mat4.translate(mvMatrix, mvMatrix, [position.x, position.y, 0.0]);
// 2) Flips the piece in the Y axis
if (_flipped) {
mat4.rotate(mvMatrix, mvMatrix, Math.PI, [0, 1, 0]);
}
// 1) Rotates the piece
mat4.rotate(mvMatrix, mvMatrix, _rotation, [0, 0, 1]);
setMatrixUniforms();
_gl.drawElements(gl.TRIANGLES, _indexBuffer.numItems, gl.UNSIGNED_SHORT, 0);
mvPopMatrix();
_gl.bindBuffer(_gl.ARRAY_BUFFER, null);
_gl.bindBuffer(_gl.ELEMENT_ARRAY_BUFFER, null);
};
_init(vertices, indices, pointsOfCenters);
}
/**
* Represents an individual player
* @param name the Player's dispayable name
* @param pieces a list of the pieces at this player's disposal
* @param availableMoves a ready made container that is set up to store available moves
* @param moveValidator a function that allows a player to check if a hypothetical move is valid
*/
function Player(name, pieces, availableMoves, moveValidator) {
var _name = name;
var _availablePieces = pieces;
var NONE = -1;
var _currentPiece = NONE;
var _numAvailableMoves = 1; // Convenience variable to keep track of how many available moves remain
var _availableMoves = availableMoves; // 2D Array of pieces, where the indices are the board locations
var _score = 0;
var _stillPlaying = true;
var _moveValidator = moveValidator; // function which checks if hypothetical moves are valid
var _latestNumSquaresPlaced = 0;
// DEBUG
var _possibleMove;
this.getPossibleMove = function() {
return _possibleMove;
};
//
this.getNumAvailablePieces = function() {
return _availablePieces.length;
};
this.hasPieceSelected = function() {
return _currentPiece != NONE;
};
this.getName = function() {
return _name;
};
this.getScore = function() {
return _score;
};
this.isStillPlaying = function() {
return _stillPlaying;
};
this.getCurrentPiece = function() {
return _availablePieces[_currentPiece];
};
/**
* If pased a valid piece #, resets the current one and sets to it
* If not, makes nothing selected
*/
this.setCurrentPiece = function(piece) {
if (_currentPiece != NONE) {
_availablePieces[_currentPiece].reset();
}
if (piece < _availablePieces.length) {
_currentPiece = piece;
}
else {
_currentPiece = NONE;
}
};
/**
* Removes the current piece from the available pieces
* and returns it. Also updates the score
*/
this.placeCurrentPiece = function() {
var piece = _availablePieces.splice(_currentPiece, 1)[0];
_currentPiece = NONE;
// Add piece's number of squares to the score
_latestNumSquaresPlaced = piece.getNumSquares();
_score += _latestNumSquaresPlaced;
return piece;
};
/**
* Based off of various scenarios, determines if this player can no longer make any moves
*/
this.determineIfStillPlaying = function() {
// Simplest scenario where the player is finished: if there are no more pieces to place,
// or there is no place even the 1 square piece can fit
if (_availablePieces.length != 0 && _numAvailableMoves != 0) {
// If the above scenario isn't true, then check if any of the remaining pieces can fit
// somewhere, if not then the player is done
// NOTE: The following efficiency tricks assume that the available pieces array is sorted smallest to largest
// If they still have their 1 piece, then no matter what if there are available moves then it can fit
if (_availablePieces[0].getNumSquares() == 1) {
return;
}
// TODO: Maybe do something simple for 2 piece?
// Otherwise, go through all the pieces with the hope that one of the smallest pieces fit somewhere
// Worst case is their last piece only fits in the last spot checked, so have to check all combinations (unlikely)
for (var pieceI = 0; pieceI < _availablePieces.length; ++pieceI) {
var piece = _availablePieces[pieceI];
var numSquares = piece.getNumSquares();
var boardSize = _availableMoves.length;
var xOffset = 0;
var yOffset = 0;
var NUM_ROTATIONS = 4;
var NUM_FLIPS = 1;
var rotation = Math.PI / 2;
// Loop through each available move (ie: a square that must be touched by any newly placed piece)
for (var y = 0; y < boardSize; ++y) {
for (var x = 0; x < boardSize; ++x) {
if (_availableMoves[x][y] != null) {
// Attempt all possible ways this piece can touch this spot. For each square of the piece,
// attempt to have it touch the spot by trying all 4 rotations * 2 flip orientations
// So for each available move the maximum number of checks is = numSquares * 4 * 2
for (var squareI = 0; squareI < numSquares; ++squareI) {
for (var i = 0; i < NUM_FLIPS; ++i) {
for (var j = 0; j < NUM_ROTATIONS; ++j) {
var squares = piece.getPointsOfCenters(); // Get the updated square locations
var square = squares[squareI]; // Get the current square to place at (x,y)
var firstSquare = squares[0];
// Move validator expects the location of the first square, so
// find out where it should go by taking the difference between the two
xOffset = square.x - firstSquare.x;
yOffset = square.y - firstSquare.y;
if (_moveValidator(piece, x - xOffset, y - yOffset) == true) {
// Can place this piece here in this orientation, player not finished
// DEBUG!
_possibleMove = {};
_possibleMove.x = x;
_possibleMove.y = y;
_possibleMove.squareI = squareI;
_possibleMove.pointsOfCenters = new Array(squares.length);
for (var z = 0; z < squares.length; ++z) {
_possibleMove.pointsOfCenters[z] = new Point(squares[z].x, squares[z].y);
}
piece.reset(); // Undo any changes
return;
}
piece.rotateLeft(rotation);
}
piece.flip();
}
}
}
}
}
piece.reset(); // Undo any changes
}
}
// If got to this point, then the player is done
_stillPlaying = false;
// If they used all their pieces and their last move was the 1 piece, double their score
if (_availablePieces.length == 0 && _latestNumSquaresPlaced == 1) {
_score *= 2;
}
alert(_name + " has no more available moves");
};
this.rotateLeft = function() {
if (_currentPiece != NONE) {
_availablePieces[_currentPiece].rotateLeft();
}
};
this.rotateRight = function() {
if (_currentPiece != NONE) {
_availablePieces[_currentPiece].rotateRight();
}
};
this.flip = function() {
if (_currentPiece != NONE) {
_availablePieces[_currentPiece].flip();
}
};
/**
* Arranges all the available pieces to the locations
* given
*/
this.arrangeAvailablePieces = function(locations) {
for (var i = 0; i < _availablePieces.length; ++i) {
_availablePieces[i].setLocation(locations[i]);
}
};
/**
* Adds the given moves to the list of available moves if they don't already exist
*/
this.addNewAvailableMoves = function(moves) {
for (var i = 0; i < moves.length; ++i) {
var loc = moves[i].getLocation();
if (_availableMoves[loc.x][loc.y] == null) {
_availableMoves[loc.x][loc.y] = moves[i];
++_numAvailableMoves;
}
}
};
/**
* Removes the available move stored at the given location
* If their number of available moves is now 0, they are no longer playing
*/
this.removeAvailableMove = function(pos) {
if (_availableMoves[pos.x][pos.y] != null) {
_availableMoves[pos.x][pos.y] = null;
--_numAvailableMoves;
}
};
/**
* Draws the current piece at the location of the mouse
*/
this.draw = function(mousePosition) {
if (_currentPiece != NONE) {
_availablePieces[_currentPiece].drawAtMouse(mousePosition);
}
};
/**
* Draws all the available pieces on the right of the screen
*/
this.drawAvailablePieces = function() {
for (var i = 0; i < _availablePieces.length; ++i) {
if (i == _currentPiece) continue;
_availablePieces[i].draw();
}
};
/**
* Draws all the available moves this player has
*/
this.drawAvailableMoves = function() {
for (var i = 0; i < _availableMoves.length; ++i) {
for (var j = 0; j < _availableMoves[i].length; ++j) {
if (_availableMoves[i][j] != null) {
_availableMoves[i][j].draw();
}
}
}
};
}
/**
* Represents the game board
*/
function Board(size) {
var _gridSize = size;
var _board = new Array(_gridSize);
var self = this;
var EMPTY = '#';
var BLUE = 'B';
var YELLOW = 'Y';
var RED = 'R';
var GREEN = 'G';
var _colorMap = {}; // RGB color -> color code
var _startedMap = {}; // Color code -> First move or not
var _firstPieceMap = {}; // Color code -> Location of first piece
var _init = function() {
_colorMap[[0.0, 0.0, 1.0, 1.0]] = BLUE;
_colorMap[[1.0, 1.0, 0.0, 1.0]] = YELLOW;
_colorMap[[1.0, 0.0, 0.0, 1.0]] = RED;
_colorMap[[0.0, 1.0, 0.0, 1.0]] = GREEN;
_startedMap[BLUE] = _startedMap[RED] = _startedMap[GREEN] = _startedMap[YELLOW] = false;
_firstPieceMap[BLUE] = new Point(0, _gridSize - 1); // Top left corner
_firstPieceMap[YELLOW] = new Point(_gridSize - 1, _gridSize - 1); // Top right corner
_firstPieceMap[RED] = new Point(_gridSize - 1, 0); // Bottom right corner
_firstPieceMap[GREEN] = new Point(0, 0); // Bottom right corner
for (var i = 0; i < _gridSize; ++i) {
_board[i] = new Array(_gridSize);
for (var j = 0; j < _gridSize; ++j) {
_board[i][j] = EMPTY;
}
}
};
/**
* @private
*/
var _getColorCode = function(piece) {
return _colorMap[piece.getColor()];
};
/**
* @returns true if the given coordinates are out of bounds, else false
*/
this.isOutOfBounds = function(x, y) {
return x < 0 || y < 0 || x >= _gridSize || y >= _gridSize;
};
/**
* @returns true if this is a valid move for this piece, false otherwise
*/
this.canPlacePiece = function(piece, x, y) {
var color = _getColorCode(piece);
var pointsOfCenters = piece.getPointsOfCenters();
if (_startedMap[color]) {
return _validateMove(color, pointsOfCenters, x, y);
}
else {
return _checkFirstMove(color, pointsOfCenters, x, y);
}
};
/**
* @private
* If this isn't the players first move, returns if a given move is valid
*/
var _validateMove = function(color, pointsOfCenters, x, y) {
var touchedCorner = false; // Must turn true to be a valid move
// Go through each square of the piece
for (var z = 0; z < pointsOfCenters.length; ++z) {
var square = pointsOfCenters[z];
var location = new Point(x + square.x, y + square.y);
if (self.isOutOfBounds(location.x, location.y)) {
return false;
}
// Check in all 8 surrounding directions for each square
for (var j = 1; j > -2; --j) {
for (var i = -1; i < 2; ++i) {
var newX = location.x + i;
var newY = location.y + j;
// Check if outside the board, if so continue since no issue
if (self.isOutOfBounds(newX, newY)) continue;
// If checking self, make sure its empty
if (i == 0 && j == 0) {
if (_board[newX][newY] != EMPTY) {
return false;
}
}
// If 'x' direction, check to see if same color exists, needs to happen at least once to be a valid move
else if (Math.abs(i) == Math.abs(j)) {
if (touchedCorner) {
continue; // Don't bother checking
}
touchedCorner = (_board[newX][newY] == color); // else
}
// If '+' direction, check to see if same same color exists, if so, that's an invalid move
else if (_board[newX][newY] == color) {
return false;
}
}
}
}
return touchedCorner;
};
/**
* Every piece has a corner that their first move has to touch
* Check if any of the squares of this piece touch the first location
* as long as the piece didn't go out of bounds
*/
var _checkFirstMove = function(color, pointsOfCenters, x, y) {
var firstPieceLocation = _firstPieceMap[color];
var success = false;
for (var z = 0; z < pointsOfCenters.length; ++z) {
var square = pointsOfCenters[z];
var location = new Point(x + square.x, y + square.y);
if (self.isOutOfBounds(location.x, location.y)) {
return false;
}
if (location.equals(firstPieceLocation)) {
success = true;
}
}
// If made it to the end without going out of bounds
if (success) {
_startedMap[color] = true;
}
return success; // None of the squares touched the first location
};
/**
* Puts a piece on the game board
*/
this.placePiece = function(piece, x, y) {
var color = _getColorCode(piece);
var pointsOfCenters = piece.getPointsOfCenters();
for (var i = 0; i < pointsOfCenters.length; ++i) {
var piece = pointsOfCenters[i];
_board[x + piece.x][y + piece.y] = color;
}
if (DEBUG) {
this.printBoard();
}
};
/**
* After a piece is placed, determine all the new available pieces that
* are now possible
*/
this.discoverNewAvailableMoves = function(piece, x, y) {
var newMoves = [];
var checkedSpots = []; // Avoid redundant checks
var color = _getColorCode(piece);
var pointsOfCenters = piece.getPointsOfCenters();
for (var z = 0; z < pointsOfCenters.length; ++z) {
// For each square of a piece, check in X direction for empty space
var square = pointsOfCenters[z];
var location = new Point(x + square.x, y + square.y);
for (var j = 1; j > -2; --j) {
for (var i = -1; i < 2; ++i) {
// If 'x' direction, check to see if the spot is empty
if (Math.abs(i) == Math.abs(j)) {
var newX = location.x + i;
var newY = location.y + j;
var newLoc = new Point(newX, newY);
// Check if outside the board, if so not a new move
if (self.isOutOfBounds(newX, newY)) continue;
if (_board[newX][newY] == EMPTY) {
// If it's empty, see if we've checked this spot before
if (checkedSpots.indexOf(newLoc) > -1) {
continue;
}
var newMoveWorks = true;
// If not, then check this spot's + directions to see if it's adjacent to this piece's color
for (var l = 1; l > -2; --l) {
for (var k = -1; k < 2; ++k) {
if (k != l && Math.abs(k) != Math.abs(l)) {
var checkX = newX + k;
var checkY = newY + l;
// Check if outside the board, if so continue since no issue
if (self.isOutOfBounds(checkX, checkY)) continue;
if (_board[checkX][checkY] == color) {
newMoveWorks = false;
break;
}
}
}
if (!newMoveWorks) {
break;
}
}
// If made it this far, this is a new move
if (newMoveWorks) {
newMoves = newMoves.concat(newLoc);
}
// Make sure we don't check this spot again
checkedSpots = checkedSpots.concat(newLoc);
}
}
}
}
}
return newMoves;
}
/**
* @debug
*/
this.printBoard = function() {
for (var i = _gridSize - 1; i >= 0; --i) {
var output = "";
for (var j = 0; j < _gridSize; ++j) {
output += _board[j][i] + " ";
}
console.log(output);
}
};
_init();
}
/**
* Class mostly responsible for the drawing of the game and handling user interaction
*/
function Blockus(gl, shaderProgram, gridSize, pieces) {
var _gl = gl;
var _shaderProgram = shaderProgram;
var _NUM_PLAYERS = 4;
var _players = [];
var _currentPlayer = 0;
var _firstRound = true; // Not all players have placed their first piece
var _gameBoard;
var _placedPieces = [];
var self = this;
// Grid variables
var _gridSize = 20; // 20 X 20 board
var _halfGridSize = _gridSize * 0.5; // 10 cells
var _gridVertices;
var _gridVertexColors;
var _gridIndexBuffer;
// Scroll buttons
var _scrollVertices;
var _scrollVertexColors;
var _scrollTriangleIndices;
var _scrollSquareIndices;
var _scrollAmount = 0;
var _rightPiecesMarginX = 6;
var _rightPiecesMarginY = 4;
var _mousePosition = []; // Empty object
var _lightPlayerColors;
var _gameOver = false;
/**
* @private
* Initializes the game
*/
var _init = function(pieces) {
_gameBoard = new Board(_gridSize);
_lightPlayerColors = [
[0.0, 0.0, 1.0, 0.3],
[1.0, 1.0, 0.0, 0.5],
[1.0, 0.0, 0.0, 0.3],
[0.0, 1.0, 0.0, 0.3]
];
_initPlayers(pieces);
_initBuffers();
_mousePosition.x = 0;
_mousePosition.y = 0;
};
/**
* @private
* Convenience function to create a displayable piece
* that takes up one square
* Used for displaying hints as to where to place a piece
*
* @param color [r,g,b] of the piece to display
* @param pos either Point or array [x,y] position to display the top left corner of the piece
* @returns the created piece
*/
var _createSquarePiece = function(color, pos) {
var p = new Piece(_gl, _shaderProgram, color,
[
0, 0, 0,
1, 0, 0,
0, 1, 0,
1, 1, 0
],
[
0, 3, 1,
0, 2, 3
]
);
if (pos instanceof Point) {
p.setLocation(pos);
}
else {
p.setLocation(new Point(pos[0], pos[1]));
}
return p;
};
/**
* @private
* Makes the next player who is still playing have their turn
*/
var _nextPlayer = function () {
var numAttempts = 0;
do {
_currentPlayer = (_currentPlayer + 1) % 4;
if (++numAttempts > _NUM_PLAYERS) {
// Game is over
var maxScore = 0;
var winner;
for (var i = 0; i < _NUM_PLAYERS; ++i) {
var currentScore = _players[i].getScore();
if (currentScore > maxScore) {
maxScore = currentScore;
winner = _players[i].getName();
}
}
alert("Game is over! Winner is: " + winner);
_gameOver = true;
return;
}
}
while (_players[_currentPlayer].isStillPlaying() == false);
// See if this player actually has any moves left
_players[_currentPlayer].determineIfStillPlaying();
if (_players[_currentPlayer].isStillPlaying() == false) {
_nextPlayer(); // Try again
}
};
/**
* @private
* Creates and initializes all the players
* First it sets up the available moves for each player on startup
*/
var _initPlayers = function(pieces) {
// Set up each player's first available moves
var firstMoves = new Array(_NUM_PLAYERS);
var positions = [
[0, _gridSize - 1],
[_gridSize - 1, _gridSize - 1],
[_gridSize - 1, 0],
[0, 0]
];
for (var i = 0; i < _NUM_PLAYERS; ++i) {
firstMoves[i] = _createSquarePiece(_lightPlayerColors[i], positions[i]);
}
var names = ["Blue", "Yellow", "Red", "Green"];
// Create each player, passing the necessary data
for (var i = 0; i < _NUM_PLAYERS; ++i) {
// Give each player a ready made 2D array
var availableMoves = new Array(_gridSize);
for (var j = 0; j < _gridSize; ++j) {
availableMoves[j] = new Array(_gridSize);
}
// Give each player their first move
availableMoves[positions[i][0]][positions[i][1]] = firstMoves[i];
_players = _players.concat(new Player(names[i], pieces[i], availableMoves, _gameBoard.canPlacePiece));
_arrangeAvailablePieces(i);
}
};
/**
* @private
* Sets up the buffers for drawing
*/
var _initBuffers = function() {
_initGridBuffers();
_initScrollBuffers();
};
/**
* @private
* Sets the buffers for the grid
*/
var _initGridBuffers = function() {
// Vertex buffer
_gridVertices = _gl.createBuffer();
_gl.bindBuffer(_gl.ARRAY_BUFFER, _gridVertices);
var vertices = [];
var numHorizontal = _gridSize;
var numVertical = _gridSize + 1; // Also want at the edge of the board
// Horizontal Lines
for (var i = 0; i < numHorizontal; ++i) {
vertices = vertices.concat([0.0, i, 0.0]);
vertices = vertices.concat([_gridSize, i, 0.0]);
}
// Vertical lines
for (var i = 0; i < numVertical; ++i) {