/
QuoridorModel.java
1287 lines (1101 loc) · 32.5 KB
/
QuoridorModel.java
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
package passaj;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
* QuoridorModel encapsulates all the logic relating to a game of Quoridor.
*/
public class QuoridorModel
{
private static final int WALL_VALUE = 7;
private Point[] myLocations;
private int[][] myBoard;
private int[] myWallCounts;
private int[] myPathLengths;
private int myTurn;
private int myBoardSize;
private int myPlayers;
private int myWallNumber;
private String myBoardType;
private List<int[]> moves;
private boolean[][] wallsInPath;
public QuoridorModel()
{
this.myBoardSize = 9;
this.myPlayers = 2;
this.myBoardType = "default";
initialize();
}
/**
* Initialize a model with parameters.
*
* Params
* playerCount = number of players in the game: 2 or 4
* size = size of the board (default 9)
*/
public QuoridorModel(int playerCount, int size, String type)
{
this.myBoardSize = size;
this.myPlayers = playerCount;
this.myBoardType = type;
initialize();
}
/**
* Dupicates an instance of a quoridor model.
*/
public QuoridorModel(QuoridorModel m) {
this.myBoardSize = m.myBoardSize;
this.myPlayers = m.myPlayers;
this.myBoardType = m.myBoardType;
initialize();
// Override default values with values from the old model
for (int i = 0; i < this.myPlayers; i++) {
this.myWallCounts[i] = m.myWallCounts[i];
this.myPathLengths[i] = m.myPathLengths[i];
this.myLocations[i] = new Point(m.myLocations[i]);
for (int j = 0; j < this.wallsInPath.length; j++)
this.wallsInPath[i][j] = m.wallsInPath[i][j];
}
this.myBoard = deepCopy(m.myBoard);
this.myTurn = m.myTurn;
}
/**
* This yields 10 for board size 9, as it should, as well as
* reasonable numbers for the other sizes.
*/
private int numberOfWalls(int boardSize, int players)
{
return (boardSize - 1) * (boardSize - 1) * 5 / 16 / players;
}
/**
* Set all internal variables to their initial values.
*/
public void initialize()
{
this.myTurn = 0;
// Initialize the board
int half = this.myBoardSize - 1;
this.myBoard = new int[2 * half + 1][2 * half + 1];
// Start keeping track of walls in my path.
this.wallsInPath = new boolean[this.myPlayers][half * half * 2];
// Put pieces in appropriate starting locations
this.myLocations = new Point[this.myPlayers];
this.placePieces();
// Put the pieces on the board
for (int i = 0; i < this.myPlayers; i++)
this.myBoard[this.myLocations[i].x][this.myLocations[i].y] = i + 1;
// Start list of moves
this.moves = new ArrayList<int[]>();
// Set correct number of walls per player
this.myWallNumber = numberOfWalls(this.myBoardSize, this.myPlayers);
// Set the wall counts and path lengths to initial values
this.myWallCounts = new int[this.myPlayers];
this.myPathLengths = new int[this.myPlayers];
for (int i = 0; i < this.myPlayers; i++) {
this.myWallCounts[i] = this.myWallNumber;
this.myPathLengths[i] = pathLength(i);
}
}
/**
* Make sure all pieces end up on appropriate starting squares.
*/
private void placePieces()
{
final int half = this.myBoardSize - 1;
final int quarter = half / 2;
final int eighth = half / 4;
final int threeQuarters = half * 3 / 2;
final int sevenEighths = half * 7 / 4;
// Every board has one player in the same location.
this.myLocations[0] = new Point(half, 0);
// Except with three players, every board has an opponent across
if (this.myPlayers != 3)
this.myLocations[1] = new Point(half, 2 * half);
else
this.myLocations[1] = new Point(sevenEighths, threeQuarters);
// Add third and fourth players for normal boards
if (this.myPlayers == 4 && this.myBoardType != "hexagonal")
{
this.myLocations[2] = new Point(2 * half, half);
this.myLocations[3] = new Point(0, half);
}
// Players 3-6 always go in the same place
if (this.myBoardType == "hexagonal" && this.myPlayers > 2)
{
// Third player
this.myLocations[2] = new Point(eighth, threeQuarters);
// Fourth player
if (this.myPlayers > 3)
this.myLocations[3] = new Point(sevenEighths, quarter);
// Fifth and Sixth players
if (this.myPlayers == 6)
{
this.myLocations[4] = new Point(sevenEighths, threeQuarters);
this.myLocations[5] = new Point(eighth, quarter);
}
}
// If we have an even number of squares, we have to shift one out of
// each pair of pieces to make the board rotation-symmetric.
//
// TODO adjust pieces on even hex boards.
if (isEven(this.myBoardSize))
{
this.myLocations[0].x -= 1;
this.myLocations[1].x += 1;
if (this.myBoardType != "hexagonal" && this.myPlayers == 4)
{
this.myLocations[2].y -= 1;
this.myLocations[3].y += 1;
}
}
}
/**
* Public move function.
*/
public boolean move(final Point destination)
{
return movePiece(destination);
}
public boolean move(final Point placement, final int o)
{
return placeWall(placement, o);
}
/**
* ai_move uses minimax to decide on a move and take it.
*
* Params:
* millis = the length of time to search moves in milliseconds
*/
int[] ai_move(long millis)
{
int i = 1;
int[] move = null;
int[] testMove;
long t0 = System.currentTimeMillis();
// iterative deepening
while (i < 15)
{
QuoridorModel testModel = new QuoridorModel(this);
testMove = testModel.negascout(i, -1000, 1000, millis, t0, move);
i += 1;
if (System.currentTimeMillis() - t0 < millis && i < 100)
move = testMove;
else
break;
}
// Print the level that we got to
System.out.println(i);
printrow(move);
if (move[2] != 0)
{
System.out.println("Placing wall");
if (!placeWall(new Point(move[0], move[1]), move[2]))
System.out.println("Illegal move:" + move[0] + " " + move[1] + " " + move[2]);
}
else
{
System.out.println("Moving piece");
if (!movePiece(new Point(move[0], move[1])))
System.out.println("Illegal move:" + move[0] + " " + move[1]);
}
return move;
}
/**
* Undo last moves.
*
* Params:
* n = the number of moves to undo
*/
void undo(int n)
{
for (int i = 0; i < n; i++)
{
int[] move = moves.remove(moves.size() - 1);
int x = move[0];
int y = move[1];
int o = move[2];
// update turn
this.myTurn -= 1;
int turn = this.myTurn % this.myPlayers;
// undo wall
if (o != 0)
{
wallVal(new Point(x, y), o, 0);
this.myWallCounts[turn] += 1;
}
// undo move
else
{
this.myBoard[x][y] = turn + 1;
this.myBoard[this.myLocations[turn].x][this.myLocations[turn].y] = 0;
this.myLocations[turn].x = x;
this.myLocations[turn].y = y;
}
this.myPathLengths = new int[this.myPlayers];
for (int j = 0; j < this.myPlayers; j++)
this.myPathLengths[j] = this.pathLength(j);
}
}
/**
* Checks for move legality, and if legal, moves the player.
*
* Params:
* destiantion = the desired location to move the piece to
*
* Returns: whether or not the move occurred
*/
boolean movePiece(final Point destination)
{
final int turn = this.myTurn % this.myPlayers;
final Point origin = new Point(this.myLocations[turn]);
if (this.myBoardType == "hexagonal"
&& isLegalHexMove(origin, destination)
|| this.myBoardType != "hexagonal"
&& isLegalMove(origin, destination))
{
// make the move
this.myLocations[turn].x = destination.x;
this.myLocations[turn].y = destination.y;
this.myBoard[origin.x][origin.y] = 0;
this.myBoard[destination.x][destination.y] = turn + 1;
// update shortest path length
this.myPathLengths[turn] = pathLength(turn);
// update turn
this.myTurn++;
// add old location to undo list
this.moves.add(new int[] {origin.x, origin.y, 0});
return true;
}
return false;
}
/**
* Check if this piece movement is legal.
*
* Params:
* origin = current location of piece
* destination = desired new location of piece
*
* Returns:
* Whether or not the move is legal
*/
boolean isLegalMove(final Point origin, final Point destination)
{
// Check for out-of-bounds
if (!isOnBoard(destination))
return false;
// Check if another player is where we're going
if (this.myBoard[destination.x][destination.y] != 0)
return false;
// jump dist
final int Xdist = Math.abs(destination.x - origin.x);
final int Ydist = Math.abs(destination.y - origin.y);
// In between start and finish
final int avgX = (destination.x + origin.x) / 2;
final int avgY = (destination.y + origin.y) / 2;
// One past the destination
final int onePastX = destination.x + avgX - origin.x;
final int onePastY = destination.y + avgY - origin.y;
// normal move: one space away and no wall between
if ((Xdist == 2 && Ydist == 0 || Xdist == 0 && Ydist == 2)
&& this.myBoard[avgX][avgY] != WALL_VALUE)
return true;
// jump in a straight line
final Point jump = new Point(avgX, avgY);
if ((Xdist == 4 && Ydist == 0 || Xdist == 0 && Ydist == 4)
&& legalJump(origin, jump, destination))
return true;
// jump diagonally
final Point jump1 = new Point(origin.x, destination.y);
final Point jump2 = new Point(destination.x, origin.y);
final Point jump1wall = new Point(origin.x, onePastY);
final Point jump2wall = new Point(onePastX, origin.y);
if (Xdist == 2 && Ydist == 2
&& (legalJump(origin, jump1, destination, jump1wall)
|| legalJump(origin, jump2, destination, jump2wall)))
return true;
// Failed to find a valid way to make that move
return false;
}
/**
* Check if this piece movement is legal on a hex board.
*
* Params:
* origin = previous location
* destination = attempted location
*
* Returns whether or not this move is legal, true or false
*/
boolean isLegalHexMove(final Point origin, final Point destination)
{
// Can't jump off the board!
if (!isOnBoard(destination))
return false;
// There's a piece where we're trying to go!
if (this.myBoard[destination.x][destination.y] != 0)
return false;
// How far did we travel in each direction?
final int Xdist = Math.abs(destination.x - origin.x);
final int Ydist = Math.abs(destination.y - origin.y);
// The middle ground
final int avgX = (destination.x + origin.x) / 2;
final int avgY = (destination.y + origin.y) / 2;
// Which direction are we moving in?
int Xdir = 0;
int Ydir = 0;
if (Xdist != 0)
Xdir = (destination.x - origin.x) / Xdist;
if (Ydist != 0)
Ydir = (destination.y - origin.y) / Ydist;
// Normal move
if ((Xdist == 2 && Ydist == 0 || Xdist == 1 && Ydist == 2)
&& !wallBetween(origin, destination))
return true;
// Jump in a straight line
Point jump = new Point(avgX, avgY);
if ((Xdist == 4 && Ydist == 0 || Xdist == 2 && Ydist == 4)
&& legalJump(origin, jump, destination))
return true;
// Jump two spaces vertically by jumping over a piece
Point leftJump = new Point(origin.x - 1, avgY);
Point leftWall = new Point(origin.x - 2, (destination.y + avgY) / 2);
Point rightJump = new Point(origin.x + 1, avgY);
Point rightWall = new Point(origin.x + 2, (destination.y + avgY) / 2);
if (Xdist == 0 && Ydist == 4
&& (legalJump(origin, leftJump, destination, leftWall)
|| legalJump(origin, rightJump, destination, rightWall)))
return true;
// Jump in a 120 degree angle to a horizontal location.
jump = new Point(origin.x + 2 * Xdir, origin.y);
Point wall = new Point(origin.x + 3 * Xdir, origin.y - Ydir);
if (Xdist == 3 && Ydist == 2
&& legalJump(origin, jump, destination, wall))
return true;
// Jump in a 60 degree angle to a horizontal location.
leftJump = new Point(avgX, origin.y + 2);
Point leftWall1 = new Point(origin.x, origin.y + 3);
Point leftWall2 = new Point(destination.x, origin.y + 3);
rightJump = new Point(avgX, origin.y - 2);
Point rightWall1 = new Point(origin.x, origin.y - 3);
Point rightWall2 = new Point(destination.x, destination.y - 3);
if (Xdist == 2 && Ydist == 0
&& (legalJump(origin, leftJump, destination, leftWall1, leftWall2)
|| legalJump(origin, rightJump, destination, rightWall1, rightWall2)))
return true;
// Jump in a 60 degree angle to a vertical location.
leftJump = new Point(origin.x + 2 * Xdir, origin.y);
leftWall1 = new Point(origin.x + 2 * Xdir, origin.y - Ydir);
leftWall2 = new Point(origin.x + 3 * Xdir, avgY);
rightJump = new Point(origin.x - Xdir, destination.y);
rightWall1 = new Point(origin.x - Xdir, destination.y + Ydir);
rightWall2 = new Point(origin.x - 2 * Xdir, avgY);
if (Xdist == 1 && Ydist == 2
&& (legalJump(origin, leftJump, destination, leftWall1, leftWall2)
|| legalJump(origin, rightJump, destination, rightWall1, rightWall2)))
return true;
// We've failed to find a valid way to make this move
return false;
}
/**
* Tests a jump to see if it is legal.
*
* Params:
* origin = Where we're jumping from
* jump = Where we're jumping over
* destination = Where we're jumping to
* walls = Array of walls that have to exist for the jump to be legal
*/
boolean legalJump(
final Point origin,
final Point jump,
final Point destination,
final Point... walls)
{
// Jumping over a piece
if (!isOnBoard(jump) || this.myBoard[jump.x][jump.y] == 0)
return false;
// Gotta be a wall or the edge of the board behind them
for (Point wall : walls)
if (isOnBoard(wall) && this.myBoard[wall.x][wall.y] != WALL_VALUE)
return false;
// Can't be a wall between any space on the jump route
if (wallBetween(origin, jump) || wallBetween(jump, destination))
return false;
return true;
}
/**
* Tests whether or not there is a wall between two adjacent hexes.
*/
boolean wallBetween(final Point origin, final Point destination)
{
// Assure we're only one space away
assert Math.abs(destination.x - origin.x) == 2
&& Math.abs(destination.y - origin.y) == 0
|| this.myBoardType == "hexagonal"
&& Math.abs(destination.x - origin.x) == 1
&& Math.abs(destination.y - origin.y) == 2
|| this.myBoardType != "hexagonal"
&& Math.abs(destination.x - origin.x) == 0
&& Math.abs(destination.y - origin.y) == 2;
final int avgX = (origin.x + destination.x) / 2;
final int avgY = (origin.y + destination.y) / 2;
// Horizontal move
if (origin.y == destination.y)
return this.myBoard[avgX][origin.y] == WALL_VALUE;
// Normal board, vertical move
else if (this.myBoardType != "hexagonal")
return this.myBoard[origin.x][avgY] == WALL_VALUE;
// Hexagonal board, vertical move
else
return this.myBoard[origin.x][avgY] == WALL_VALUE
|| this.myBoard[destination.x][avgY] == WALL_VALUE;
}
/**
* Checks for wall legality, and if legal, places the wall.
*
* Params:
* placement = the desired wall placement location
* o = the orientation (1 for vertical, 2 for horizontal)
*/
boolean placeWall(Point placement, int o)
{
if (!isLegalWall(placement, o))
return false;
// Add the wall for checking both player's paths
wallVal(placement, o, WALL_VALUE);
int[] testLengths = new int[this.myPlayers];
// check if this wall blocks any path
for (int i = 0; i < this.myPlayers; i++)
{
if (wallsInPath[i][linearize(placement.x, placement.y, o)])
{
testLengths[i] = pathLength(i);
if (testLengths[i] == 0)
{
// remove wall
wallVal(placement, o, 0);
return false;
}
}
}
// All players have a path, so update shortest paths
for (int i = 0; i < this.myPlayers; i++)
{
if (testLengths[i] != 0)
this.myPathLengths[i] = testLengths[i];
}
// Reduce the walls remaining
this.myWallCounts[this.myTurn % this.myPlayers]--;
// update turn
this.myTurn++;
// add wall to the list of moves (for undo)
this.moves.add(new int[] {placement.x, placement.y, o});
return true;
}
/**
* This function helps keep track of walls that would interrupt
* the shortest path, so we can recalculate when necessary.
*/
void addWalls(final int player, final Point origin, final Point destination)
{
int avgX = (origin.x + destination.x) / 2;
int avgY = (origin.y + destination.y) / 2;
// horizontal move
if (origin.y == destination.y)
{
if (isOnBoard(origin.y - 1))
wallsInPath[player][linearize(avgX, origin.y - 1, 1)] = true;
if (isOnBoard(origin.y + 1))
wallsInPath[player][linearize(avgX, origin.y + 1, 1)] = true;
}
// vertical hex move
else if (this.myBoardType == "hexagonal")
{
wallsInPath[player][linearize(origin.x, avgY, 1)] = true;
wallsInPath[player][linearize(destination.x, avgY, 1)] = true;
}
// vertical move on normal board
else
{
if (isOnBoard(origin.x - 1))
wallsInPath[player][linearize(origin.x - 1, avgY, 2)] = true;
if (isOnBoard(origin.x + 1))
wallsInPath[player][linearize(origin.x + 1, avgY, 2)] = true;
}
}
/**
* Calculate linear location in array from x and y.
*/
int linearize(int x, int y, int o)
{
return x - 1 + (this.myBoardSize - 1) * (y - 1) + o - 1;
}
/**
* Asserts a wall is legal.
*
* Params:
* placement = desired location of new wall
* orientation = orientation of new wall (vertical, 1, or horizontal, 2)
*/
boolean isLegalWall(final Point placement, final int orientation)
{
// Make sure wall isn't in move land
assert this.myBoardType == "hexagonal"
|| !isEven(placement.x) && !isEven(placement.y) : "Invalid wall";
assert this.myBoardType != "hexagonal"
|| !isEven(placement.y) : "Invalid wall";
// Make sure orientation is valid
assert orientation == 1 || orientation == 2;
// check for out-of-bounds
if (!isOnBoard(placement))
return false;
// Make sure the player has walls left
if (this.myWallCounts[this.myTurn % this.myPlayers] == 0)
return false;
// Hex board walls cannot be immediately next to any other walls
if (this.myBoardType == "hexagonal")
{
// +1 when x + y is odd, -1 when x + y is even
final int yAdd = 2 * ((placement.x + placement.y) % 2) - 1;
if (this.myBoard[placement.x][placement.y] != 0
|| this.myBoard[placement.x][placement.y + yAdd] != 0
|| this.myBoard[placement.x - 1][placement.y] != 0
|| this.myBoard[placement.x + 1][placement.y] != 0)
return false;
}
// Default board actually fills three locations
else
{
final int xAdd = orientation - 1;
final int yAdd = orientation % 2;
if (this.myBoard[placement.x][placement.y] != 0
|| this.myBoard[placement.x + xAdd][placement.y + yAdd] != 0
|| this.myBoard[placement.x - xAdd][placement.y - yAdd] != 0)
return false;
}
return true;
}
/**
* The wall defined by placement and o will be set to 'val'.
*/
void wallVal(final Point placement, final int orientation, final int val)
{
// Walls on hex board take up 2 locations.
if (this.myBoardType == "hexagonal")
{
final int yAdd = 2 * ((placement.x + placement.y) % 2) - 1;
this.myBoard[placement.x][placement.y] = val;
this.myBoard[placement.x][placement.y + yAdd] = val;
}
// Walls on the default board takes up 3 locations.
else
{
final int xAdd = orientation - 1;
final int yAdd = orientation % 2;
this.myBoard[placement.x][placement.y] = val;
this.myBoard[placement.x + xAdd][placement.y + yAdd] = val;
this.myBoard[placement.x - xAdd][placement.y - yAdd] = val;
}
}
/**
* Tests whether a single dimension is within the limits of the board.
*
* This should only be called for the default board, because figuring
* out if a dimension is on the hexagonal board requires both dimensions.
*/
boolean isOnBoard(final int d)
{
return 0 <= d && d < this.myBoardSize * 2 - 1;
}
/**
* Tests whether a (x, y) location is within the limits of the board.
*
* This can be called for either default or hexagonal boards.
*/
boolean isOnBoard(final Point test)
{
final int half = this.myBoardSize - 1;
if (this.myBoardType != "hexagonal")
return isOnBoard(test.x) && isOnBoard(test.y);
else
return test.y >= 0
&& test.y <= 2 * half
&& -2 * test.x + test.y <= half
&& 2 * test.x - test.y <= 3 * half
&& 2 * test.x + test.y >= half
&& 2 * test.x + test.y <= 5 * half;
}
/**
* Evaluate function for Negascout.
*
* Boards look better if your path is shorter than your opponent,
* and if you have more walls than your opponent.
*
* Negative numbers are good for player 1, positive are good for 2.
*/
int evaluate()
{
int won = 0;
if (heuristic(0, this.myLocations[0]) == 0)
won = -100;
if (heuristic(1, this.myLocations[1]) == 0)
won = 100;
return (
won
- this.myWallCounts[0]
+ this.myWallCounts[1]
+ 2 * this.myPathLengths[0]
- 2 * this.myPathLengths[1]
);
}
/**
* Negascout algorithm, a variation of the minimax algorithm, which
* recursively examines possible moves for both players and evaluates
* them, looking for the best one.
*
* Params:
* qb = The board to search for a move on
* depth = how many moves deep to search
* a, b = alpha and beta for pruning unecessary sub-trees
* seconds, t0 = time limit and time of beginning the search
* best = best move so far for scouting
*
* Returns:
* best move that could be found in form [x, y, o, score]
*/
int[] negascout(int depth, int alpha, int beta, long millis, long t0, int[] best)
{
if (depth <= 0 || this.isGameOver()
|| System.currentTimeMillis() - t0 > millis)
{
int score = this.evaluate();
if (this.myTurn % 2 == 0)
score = -score;
return new int[] {0, 0, 0, score};
}
// initialize values
int[] opponentMove = new int[] {0, 0, 0};
int scoutVal = beta;
int bestX = 0;
int bestY = 0;
int bestO = 0;
int score = 0;
final Point origin = this.myLocations[this.myTurn % 2];
final int oldPathLength = this.myPathLengths[this.myTurn % 2];
final int opponentX = this.myLocations[(this.myTurn + 1) % 2].x;
final int opponentY = this.myLocations[(this.myTurn + 1) % 2].y;
boolean first = true;
QuoridorModel testBoard = new QuoridorModel(this);
// We'll only do this for the root node, where we
// have a best move recorded
if (best != null)
{
if (best[2] == 0)
testBoard.movePiece(new Point(best[0], best[1]));
else
testBoard.placeWall(new Point(best[0], best[1]), best[2]);
opponentMove = testBoard.negascout(
depth - 1,
-scoutVal,
-alpha,
millis,
t0,
null
);
alpha = -opponentMove[3];
bestX = best[0];
bestY = best[1];
bestO = best[2];
first = false;
}
// move piece
for (Point move : legalMoves(origin))
{
// If we haven't checked it already
if (best == null || best[2] != 0 || best[0] != move.x || best[1] != move.y)
{
testBoard = new QuoridorModel(this);
testBoard.movePiece(move);
/* Don't consider moves that lengthen our path.
* This is always bad, and sometimes the computer will make a
* dumb move to avoid getting blocked by a wall.
*/
if (testBoard.myPathLengths[this.myTurn % 2] > oldPathLength)
continue;
opponentMove = testBoard.negascout(
depth - 1,
-scoutVal,
-alpha,
millis,
t0,
null
);
if (alpha < -opponentMove[3] && -opponentMove[3] < beta && !first)
{
opponentMove = testBoard.negascout(
depth - 1,
-beta,
-alpha,
millis,
t0,
null
);
}
if (-opponentMove[3] > alpha)
{
alpha = -opponentMove[3];
bestX = move.x;
bestY = move.y;
bestO = 0;
}
if (alpha >= beta
|| System.currentTimeMillis() - t0 > millis)
return new int[] {bestX, bestY, bestO, alpha};
scoutVal = alpha + 1;
if (first)
first = false;
}
}
// walls
for (int x = 1; x < this.myBoardSize; x += 2)
{
for (int y = 1; y < this.myBoardSize; y += 2)
{
for (int o = 1; o < 3; o++)
{
// limit to walls in the opponents path,
// or walls in their own path, but opposite orientation to block
if (
// Walls in my opponent's path
this.wallsInPath[(this.myTurn + 1) % 2][linearize(x, y, o)]
// walls that block the wall the opponent would place if I move
|| opponentMove != null
&& (
// opponent plays vertical wall, blocking walls have same x
opponentMove[2] == 1 && opponentMove[0] == x
// check same place, opposite orientation
&& (opponentMove[1] == y && o == 2
// check blocking either end
|| Math.abs(opponentMove[1] - y) == 2 && o == 1)
// opponent plays horizontal wall, blocking walls have same y
|| (opponentMove[2] == 2 && opponentMove[1] == y
// same place opposite orientation
&& (opponentMove[0] == x && o == 1
// blocking either end
|| Math.abs(opponentMove[0] - x) == 2 && o == 2))
)
// check walls around me, in case I can block off my path
// (least essential, but I think I'll keep it)
|| Math.abs(x - origin.x) == 1 && Math.abs(y - origin.y) == 1
// check walls around my opponent
|| Math.abs(x - opponentX) == 1
&& Math.abs(y - opponentY) == 1
// check all walls in the first case
// for obvious moves that we might otherwise miss
|| best != null
)
{
// some testing done twice, but faster to test than allocate
if (this.isLegalWall(new Point(x, y), o))
{
testBoard = new QuoridorModel(this);
if (testBoard.placeWall(new Point(x, y), o))
{
score = -testBoard.negascout(
depth - 1,
-scoutVal,
-alpha,
millis,
t0,
null
)[3];
if (alpha < score && score < beta && !first)
{
score = -testBoard.negascout(
depth - 1,
-beta,
-alpha,
millis,
t0,
null
)[3];
}
if (score > alpha)
{
alpha = score;
bestX = x;
bestY = y;
bestO = o;
}
if (alpha >= beta
|| System.currentTimeMillis() - t0 > millis)
return new int[] {bestX, bestY, bestO, alpha};
scoutVal = alpha + 1;
}
}
}
}
}
}
return new int[] {bestX, bestY, bestO, alpha};
}
/**
* Finds the length of the shortest path for a player.
*
* Also keeps track of walls that would block the path.
*
* Returns: length of the shortest path, ignoring the other player.
* If there is no available path, returns 0.
*/
int pathLength(int player)
{
// Remove other players from the board so that they don't
// interfere with finding the shortest path.
removePlayers(player);
// get current location
Point location = new Point(this.myLocations[player]);
// distance from current location