-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChessBoard.m
1579 lines (1310 loc) · 59.4 KB
/
ChessBoard.m
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
classdef ChessBoard < handle
properties
pcounts
% Piece counts; for optimisation purposes.
ccounts
% Capture counts; to save speed captures will have their enigmas
% cleared (if you are doing capture recovery).
Checks
% [whitestatus, blackstatus]
% Testing checkiness / checkmateness is computationally expensive
% (~3ms) so automagically updates checkmate status after moves
% internally rather than depending on [CHESS PROGRAM] to do so.
Board
% This is an 8x8 matrix that can either have 0 (empty) or ChessPieces.
% It is something called a cell array, which looks something like
% this: {0, 0, ChessPiece, 0, ChessPiece}.
% You can access an item in a cell array like regular arrays, just
% use {} instead of (). So something like "board{3,5}" to get 5th
% piece on 3rd row.
% If you try to use "board(3,5)" to get an item it will give you a
% cell array of just that item instead ({ChessPiece} or {0}), which you can't really do anything with.
end
methods
function obj = ChessBoard(preset)
if nargin == 0
preset = BoardPreset.Standard;
end
% Below, the board is organized like so:
% _________________
% |_|_|_|_|_|_|_|_| 1
% |_|_|_|_|_|_|_|_| 2
% |_|_|_|_|_|_|_|_| 3
% |_|_|_|_|_|_|_|_| 4
% |_|_|_|_|_|_|_|_| 5
% |_|_|_|_|_|_|_|_| 6
% |_|_|_|_|_|_|_|_| 7
% |_|_|_|_|_|_|_|_| 8
% 1 2 3 4 5 6 7 8
%
% ...where the black pieces are in rows 1-2 and white in rows
% 7-8.
%
% This is also why it's a cell array; with regular array you
% can't use both ChessPiece and numbers — so [0, ChessPiece, 0]
% won't work.
%
% You can access this matrix directly using something like
% "board = cb.Board"
% Pass in '-' to forcibly not set board.
obj.bset(preset);
% Update check status (there is a chance initial layout
% may already create check); initialise first to avoid
% indexing issue in checkcheck().
obj.Checks = [0,0];
obj.checkcheck();
% Update pcount and ccount.
% P N B R Q K p n b r q k
pcount = [ 0, 0, 0, 0, 0, 0; 0, 0, 0, 0, 0, 0 ];
ccount = [ 0, 0, 0, 0, 0, 0; 0, 0, 0, 0, 0, 0 ];
bsize = size(obj.Board);
for r = 1:bsize(1)
for c = 1:bsize(2)
piece = obj.get([r,c]);
if ~iseabs(piece)
pcount(piece.Player, abs(piece.rank())) = pcount(piece.Player, abs(piece.rank())) + 1;
end
end
end
end
% "Copy"
% Makes a copy of this object (just board and checks).
function board = cpy(obj)
board = ChessBoard(obj.Board);
end
% "Set board up"
% Due to ChessPiece extending handle, there is no easy way to
% create new boards without using .cpy() which clutters things
% visually. Thus this method simply takes a cell array of the
% template pieces and makes copies accordingly.
%
% preset may be a preset handle (BoardPreset.*) or the raw preset
% itself ({...})
function bset(obj, preset)
% Get applied preset
if ~isa(preset, "BoardPreset")
aps = preset;
else
aps = BoardPreset.apply(preset);
end
% Get dims
psize = size(aps);
% Create board
obj.Board = cell(psize);
for i = 1:psize(1)
for j = 1:psize(2)
piece = aps{i,j};
if iseabs(piece)
obj.Board(i,j) = { 0 };
else
obj.Board(i,j) = { piece.fcpy() };
end
end
end
end
%
% "Forsyth-Edwards Notation"
% Note this is FEN for only the starting position. Since ChessBoard
% does not store any data about the game itself (current player, #
% of turns, etc.) it is impossible to get a FEN beyond
% initialisation.
%
% This is mainly handy for PGN and weird formats such as Chess960.
%
function rep = fen(obj)
bsize = size(obj.Board);
rbuffer = Buffer(32);
% Loop through all pieces
for i = 1:bsize(1)
for j = 1:bsize(2)
piece = obj.get([i,j]);
rpool = rbuffer.pool();
% Increment empty space in buffer, otherwise get FEN
% mapping.
if iseabs(piece)
if ~isempty(rpool) && isnumeric(rpool{end})
rbuffer.Pool{length(rpool)} = rpool{end} + 1;
else
rbuffer.a(1);
end
else
rbuffer.a(fenMapper(piece));
end
end
% Omit if at last row.
if i < bsize(1)
rbuffer.a('/');
end
end
% Flush and convert piece cellarr to str.
rep = cell2str(rbuffer.flush());
% Add other flags...
% Current turn? (default to White)
rep = rep + ' w';
% Castling availability?
kq = obj.kquery();
kpure = [obj.get(kq(1)).FlagPure, obj.get(kq(2)).FlagPure];
rep = rep + ' ';
if any(kpure)
if kpure(1)
rep = rep + 'KQ';
end
if kpure(2)
rep = rep + 'kq';
end
else
rep = rep + '-';
end
% En passant square? (we haven't started so defualt to -)
rep = rep + ' -';
% Halfmove clock?
rep = rep + ' 0';
% Fullmove number?
rep = rep + ' 1';
end
% "Position of piece"
% Gets the positions of the given piece.
% There might be more than 1 of that piece (such as white rook) so
% it will usually be an array.
%
% cb.getpos(WhiteRook)
%
function pos = getpos(obj, piece)
pos = obj.pquery(piece.Type, piece.Player);
end
%
% "Query pieces"
% This function gives you a cell array with all the pieces
% currently on the board (handy if you need to loop through all the
% pieces).
%
% This includes their position as well.
%
% cb.query()
% = {{ChessPiece, [3,4]}, {ChessPiece, [2,4]}, {ChessPiece, [1,3]}...}
%
function pieces = query(obj)
indices = find(cellfun(@(p) ~iseabs(p), obj.Board));
pieces = arrayfun(@(ind) {obj.get(unflat(ind, 8)), unflat(ind, 8)}, indices, 'UniformOutput', false);
% lame readable approach :c
% pieces = cell(length(indices));
% for i = 1:length(indices)
% pieces(i) = {obj.Board(indices(i), indices(i))};
% end
end
% "Antiquery"
%
% Gets all empty spaces.
%
function pieces = aquery(obj)
indices = find(cellfun(@(p) iseabs(p), obj.Board));
pieces = arrayfun(@(ind) {obj.get(unflat(ind, 8)), unflat(ind, 8)}, indices, 'UniformOutput', false);
end
% "Enigma query"
%
% Gets all enigma pieces for that player.
function pieces = equery(obj, player)
indices = find(cellfun(@(p) ~iseabs(p) && p.Player == player && ~isempty(p.Enigmas), obj.Board));
pieces = arrayfun(@(ind) {obj.get(unflat(ind, 8)), unflat(ind, 8)}, indices, 'UniformOutput', false);
end
% "Piece query"
%
% Gets pieces of player {[piece, pos]...}
% You can either pass in 1 parameter (ChessPiece)
% or 2 parameters (type, player)
%
function pieces = pquery(obj, varargin)
if nargin == 3
jp = ChessPiece(varargin{1}, varargin{2});
else
jp = varargin{1};
end
pbuffer = Buffer(16);
for i = 1:8
for j = 1:8
cp = obj.get([i,j]);
if (~iseabs(cp) && cp == jp)
pbuffer.a({cp, [i,j]});
end
end
end
pieces = pbuffer.flush();
end
% "King query"
% Queries both kings, only position. 0 if non-existent; [white, black]
function kings = kquery(obj)
whitepq = obj.pquery(PieceType.King, 1);
blackpq = obj.pquery(PieceType.King, 2);
if isempty(whitepq)
kings{1} = 0;
else
wk = whitepq{1};
kings{1} = wk{2};
end
if isempty(blackpq)
kings{2} = 0;
else
bk = blackpq{1};
kings{2} = bk{2};
end
end
% "Query's valid pieces"
% Gets indices of query array that have any valid moves.
% ...this doesn't mean they will be good moves.
function inds = qvp(obj, query)
% Extract position vector
qpos = exti(query, 2);
% Get indices
% inds = find(~isempty(obj.vmoves(qpos)));
ibuffer = Buffer(length(qpos));
for i = 1:length(qpos)
if ~isempty(obj.vmoves(qpos{i}))
ibuffer.a(i);
end
end
inds = cell2mat(ibuffer.flush());
end
% "Is relative piece @ position that player type?"
% This is simply ispabs() but only requires a position instead.
function result = isprel(obj, pos, player)
result = ispabs(obj.get(pos), player);
end
% "Correspondence"
% Creates the abstract correspondence (sprite index array) for the concrete
% representation (board cell array) based on OSU Components
% conventions.
%
% Tip: chain this with mow() on Layer 2 for easy updating.
%
% The example below uses the pieceExistsMapper function (you can
% pass functions instead of vars by putting @), which is
% what it says on the tin — if it exists, then abstract it as 1,
% otherwise 0. Thus the correspondence reflects that.
%
% cb.correspond(@pieceExistsMapper)
% = [1, 1, 1, 1, 1, 1, 1, 1;
% 1, 1, 1, 1, 1, 1, 1, 1;
% 0, 0, 0, 0, 0, 0, 0, 0;
% 0, 0, 0, 0, 0, 0, 0, 0;
% 0, 0, 0, 0, 0, 0, 0, 0;
% 0, 0, 0, 0, 0, 0, 0, 0;
% 1, 1, 1, 1, 1, 1, 1, 1;
% 1, 1, 1, 1, 1, 1, 1, 1]
%
%
% The example below uses the intended mapper @repMapper, which
% converts each ChessPiece (or 0) to its intended sprite index.
% This also means any sprite indices are hard-coded, so any changes
% to the spritesheet should be manually reflected in the mapper.
%
% This means you can directly slot this onto the Layer 2 matrix via
% the "matrix overwrite" function or mow()!
%
% corr = cb.correspond(@repMapper)
% = [15, 16, 14, 13, 12, 14, 16, 15;
% 11, 11, 11, 11, 11, 11, 11, 11;
% 100, 100, 100, 100, 100, 100, 100, 100;
% 100, 100, 100, 100, 100, 100, 100, 100;
% 100, 100, 100, 100, 100, 100, 100, 100;
% 100, 100, 100, 100, 100, 100, 100, 100;
% 1, 1, 1, 1, 1, 1, 1, 1;
% 5, 6, 4, 2, 3, 4, 6, 5]
%
% layer2 = mow(layer2, corr, [3,1])
%
function abscorr = correspond(obj, mapper)
abscorr = cellfun(mapper, obj.Board);
end
% "Stringify"
% Gets a string representation with proper line
% breaks.
function rep = stringify(obj)
bsize = size(obj.Board);
rep = strings(bsize(1), 1);
for i = 1:bsize(1)
for j = 1:bsize(2)
rep(i) = rep(i) + ' ' + unicodeMapper(obj.get([i,j])) + ' ';
end
end
end
%
% "Is unobstructed"
% This function, given a start (oldPos) and end position (newPos)
% tells you if there are any pieces between them ("obstructing" the
% path).
%
% REQUIRED: oldPos and newPos are on the board and path is
% unit-straight.
%
% cb.isuno([1,1], [5,5])
% = 0 <-- the diagonal path is clear
%
function result = isuno(obj, oldPos, newPos)
if ~isunst(newPos - oldPos)
error("isuno can only be called on a unit-straight offset!");
end
oldPos = unflat(oldPos, 8);
newPos = unflat(newPos, 8);
indices = indmat(oldPos, newPos);
% Remove piece itself
indices = indices(2:length(indices));
result = all(cellfun(@(p) obj.iserel(p), indices));
end
%
% "Get piece from position"
% This function extracts the item at the board position.
% You can pass it either an flat index or index pair.
%
% cb.get(13) <-- 8 + 5, so row 2 item 5
% = ChessPiece
%
% cb.get([2,5]) <-- same as above
% = ChessPiece
function item = get(obj, pos)
pos = unflat(unwrap(pos, 1), 8);
item = obj.Board{pos(1), pos(2)};
end
%
% "Is empty relative"
% This function tells you if the board position is empty or not.
%
% Similar to iseabs(piece), which tells you if the extracted
% "piece" is 0 or actually a piece.
%
% cb.iserel([1,1])
% = 1 <-- the space is empty
%
function result = iserel(obj, pos)
piece = obj.get(unflat(pos, 8));
result = (isa(piece, "double"));
end
%
% "Is opponent"
% This function tells you if the piece at the board position is an
% opponent or not.
%
% The player parameter is the current player, so either 1 or 2.
%
% cb.isoppo([3,3], 1)
% = 1 <-- given we are white, the piece at [3,3] is an opponent (black)
%
function result = isoppo(obj, pos, player)
piece = obj.get(unflat(pos, 8));
result = (~iseabs(piece) && piece.Player ~= player);
end
% "Indices until obstacle"
% This function gives you an array of spaces from your starting
% position until it either reaches edge of the board or a piece in
% the way. It doesn't take into account what kind of piece it is,
% just that it can move in that direction (same output whether pawn or
% bishop, for example).
%
% The dir parameter is in the form Direction.[something], so
% Direction.Left, Direction.Right, etc. This is which way you are
% checking. Open the "Direction.m" file to see all options. The
% directions are all relative (it takes into account which way each
% player is facing) so down doesn't necessarily mean always going
% down rows of the matrix.
%
% The oppoAware parameter stands for "is aware of opponents", and
% instead of stopping before any piece will include that occupied
% space if it has an opponent piece (useful for capturing pieces).
% Set it to 0 to disable, 1 for enable and current player is white,
% 2 for enable and current player is black.
%
% ~~Note what is returned are flat indices, so instead of [row,
% column] it is the # of spaces from the top-left corner. You can
% still index an array with it. array(10) is the same as
% array([1,2])!~~
%
% 2D indices are returned now!
%
% cb.iuntil([2,2], Direction.LeftUp, 0)
% = [18, 25, 33] <-- the pawn at [2,2] can go diagonally
% left and up for these 3 spaces until
% reaching the board edge or an
% obstacle
%
% cb.iuntil([4,4], Direction.Down, 2)
% = [8, 16, 24, 32] <-- the black rook at [4,4] can go
% downwards for these four spaces
% until reaching board edge or
% obstacle (obstacle is a white
% bishop so it is included in
% possible moves)
%
function indices = iuntil(obj, pos, dir, oppoAware)
indices = obj.iuntilmax(pos, dir, 8, oppoAware);
end
% "Indices until obstacle or max spaces"
% This function is the same as iuntil() but you can give it a max #
% of spaces it can move too — for the king you would use max = 1.
%
% cb.iuntil([1,5], Direction.Up, 0)
% = [13, 21, 29] <-- the black king has three
% open spaces in front of it
%
% cb.iuntilmax([1,5], Direction.Up, 1, 0)
% = [13] <-- the black king can only move
% 1 space, so limit to max of
% 1.
%
function indices = iuntilmax(obj, pos, dir, max, oppoAware)
% Unflat pos
pos = unflat(pos, 8);
% Get offset from direction, and relative fix based on player
offset = dir.Offset;
if (obj.get(pos).Player == 1)
offset = -offset;
end
% Last valid position until obstruction/off-board
lastValidPos = pos;
% # of spaces checked.
numSpaces = 0;
% Run condition.
isFinding = 1;
% Keep searching in direction until BEFORE invalid index hit or
% checked spaces = max.
while (isFinding)
% Look-ahead at next hit.
nextPos = lastValidPos + offset;
isFinding = valabs(nextPos) && obj.iserel(nextPos) && numSpaces + 1 <= max;
% Apply (confirmed) offset; if oppo aware and is opposing player then add and
% stop.
if (isFinding || (numSpaces + 1 <= max && valabs(nextPos) && oppoAware && obj.isoppo(nextPos, oppoAware)))
lastValidPos = nextPos;
numSpaces = numSpaces + 1;
end
end
% Add all indices
indices = indmat(pos, lastValidPos);
% Remove current position (1st item).
indices = indices(2:length(indices));
end
% "Get consuming moves for player"
% Gets all consuming moves for particular player.
% Stored as pair of coords (old and new) since this targets all
% rather than just 1 piece.
function movepairs = cpmoves(obj, player)
types = [ PieceType.Pawn, PieceType.Knight, PieceType.King, PieceType.Bishop, PieceType.Queen, PieceType.Rook ];
mpbuffer = Buffer(20);
% For every piece type...
for type = types
% Get all positions for pieces of that type...
typepos = exti(obj.pquery(type, player), 2);
% For every position get every cmoves...
for tpcell = typepos
tp = unwrap(tpcell, 1);
cmoves = obj.cmoves(tp);
% For every cmoves, add to movepairs.
if ~isempty(cmoves)
for ccell = cmoves
c = ccell{1};
mpbuffer.a({tp, c});
end
end
end
end
movepairs = mpbuffer.flush();
end
% "Get checking moves"
% This includes enigma moves!!
function moves = chmoves(obj, pos)
% Get position's player
player = obj.get(pos).Player;
% Get position's opponent
oplayer = circ(player + 1, 1, 2);
% Get all valid moves for piece
moves = [ obj.vmoves(pos), obj.evmoves(pos) ];
% Keep only the moves that put other opponent in check
for i = length(moves):-1:1
% Get move
move = moves{i};
% Check if that move puts opponent in check
if obj.isresmove(pos, move, oplayer)
moves(i) = [];
end
end
end
% "Get checking moves for player"
% Gets all moves that check the other player for particular player.
% See instructions for cpmoves.
function movepairs = chpmoves(obj, player)
types = [ PieceType.Pawn, PieceType.Knight, PieceType.King, PieceType.Bishop, PieceType.Queen, PieceType.Rook ];
mpbuffer = Buffer(50);
% For every piece type...
for type = types
% Get all positions for pieces of that type...
typepos = exti(obj.pquery(type, player), 2);
% For every position get every chmoves...
for tpcell = typepos
tp = tpcell{1};
cmoves = obj.chmoves(tp);
% For every cmoves, add to movepairs.
if ~isempty(cmoves)
for ccell = cmoves
c = ccell{1};
mpbuffer.a({tp, c});
end
end
end
end
movepairs = mpbuffer.flush();
end
% "Get consuming moves for piece"
% Gets indices of vmoves that are moves that consume a piece.
% Handy for check checking or ChessBot move priority.
function moves = cmoves(obj, pos)
mbuffer = Buffer(5);
piece = obj.get(pos);
% Check if not empty.
if ~iseabs(piece)
player = piece.Player;
allmoves = [ obj.vmoves(pos, -1), obj.evmoves(pos) ];
for i = 1:length(allmoves)
move = unwrap(allmoves{i});
if obj.isoppo(move, player)
mbuffer.a(move);
end
end
end
moves = mbuffer.flush();
end
% "Get valid moves for player"
% Gets all valid moves for a player in a cell array in {{oldpos,
% newpos}...} format. Uniquely accepts prio parameter due to use in
% checkmate.
function movepairs = vpmoves(obj, player, prio)
if nargin < 3
prio = 1;
end
types = [ PieceType.Pawn, PieceType.Knight, PieceType.Bishop, PieceType.Rook, PieceType.Queen, PieceType.King ];
mpbuffer = Buffer(50);
% For every piece type...
for type = types
% Get all positions for pieces of that type...
typepos = exti(obj.pquery(type, player), 2);
% For every position get every vmoves...
for tpcell = typepos
tp = tpcell{1};
vmoves = obj.vmoves(tp, prio);
% For every cmoves, add to movepairs.
if ~isempty(vmoves)
for vcell = vmoves
v = vcell{1};
mpbuffer.a({tp, v});
end
end
end
end
movepairs = mpbuffer.flush();
end
% "Filter resolving moves for piece"
% Get subset of moves from a given set of moves from a static position (such as vmoves)
% that are resolving (or don't put the player in check).
function submoves = frmoves(obj, pos, moves)
% Get the player!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
player = obj.get(pos).Player;
% Loop through all the moves.
submoves = moves;
for i = length(submoves):-1:1
% Remove if not resolving (puts in check).
if ~obj.isresmove(pos, submoves{i}, player)
submoves(i) = [];
end
end
end
% "Filter resolving moves for player"
% Get subset of moves from a given set of (use player moves
% functions such as vpmoves or cpmoves)
% that are resolving (see frmoves for details)
function submovepairs = frpmoves(obj, movepairs, player)
% Loop through all the movepairs.
submovepairs = movepairs;
for i = length(submovepairs):-1:1
% Get the start and end of movepair
submovepair = submovepairs{i};
submstart = submovepair{1};
submend = submovepair{2};
% Remove if not resolving (puts in check)
if ~obj.isresmove(submstart, submend, player)
submovepairs(i) = [];
end
end
end
% "Get resolving moves for piece"
% Integrates checkresmove to ensure the moves passed in resolve check.
% You should only pass either vmoves and/or emoves into this!
function submoves = rmoves(obj, pos)
% If empty, return.
if obj.iserel(pos)
submoves = [];
else
% Get all valid moves
submoves = obj.vmoves(pos, 1);
% Get player of piece @ position
player = obj.get(pos).Player;
% Remove any moves that won't resolve check
for i = length(submoves):-1:1
rm = unwrap(submoves{i});
if ~obj.isresmove(pos, rm, player)
submoves(i) = [];
end
end
end
end
% "Get resolving enigma moves for piece"
% Same as rmoves. Please don't confuse this with removing a piece.
function submoves = removes(obj, pos)
% If empty, return.
if obj.iserel(pos)
submoves = [];
else
% Get all valid moves
submoves = obj.evmoves(pos);
% Get player of piece @ position
player = obj.get(pos).Player;
% Remove any moves that won't resolve check
for i = length(submoves):-1:1
rm = submoves{i};
if ~obj.isresmove(pos, rm, player)
submoves(i) = [];
end
end
end
end
% "Get resolving moves for player"
% Does enigmas as well! :D
function movepairs = rpmoves(obj, player)
types = [ PieceType.Pawn, PieceType.Knight, PieceType.Bishop, PieceType.Rook, PieceType.Queen, PieceType.King ];
mpbuffer = Buffer(40);
% For every piece type...
for type = types
% Get all positions for pieces of that type...
typepos = exti(obj.pquery(type, player), 2);
% For every position get all rmoves
for tpcell = typepos
tp = unwrap(tpcell, 1);
rmoves = obj.rmoves(tp);
% For every rmoves, add to movepairs.
if ~isempty(rmoves)
for rcell = rmoves
mpbuffer.a({tp, unwrap(rcell, 1)});
end
end
end
end
% For all enigma pieces of player...
for epcell = exti(obj.equery(player), 2)
ep = unwrap(epcell, 1);
% Get all evmoves
evmoves = obj.evmoves(ep);
% For every evmoves, add to movepairs.
for ecell = evmoves
mpbuffer.a({ep, unwrap(ecell, 1)});
end
end
movepairs = mpbuffer.flush();
end
%
% "Get valid moves for piece"
% This function returns a cell array of all the valid moves for a
% piece at the given position.
%
% Note that "moves" represents absolute indices (rather than
% relative to the given position), so you can directly use these to
% change the sprites on the board where the user can move the
% piece.
%
% UPDATE: This also takes into account checking!!
%
% To iterate through a cell array, you can use foreach loop and extract
% each from cells like so:
%
% for cell in moves
% index = cell{1};
% ...
% end
%
% ...or, you can use a regular forloop and use the extract
% function.
%
% for i = 1:length(moves)
% index = moves{i};
% ...
% end
%
%
% cb.vmoves([7,6])
% = { } <-- there are no possible moves for this pawn
%
% cb.vmoves([1,8])
% = { [2,8], [2,9] } <-- the pawn can go diagonally to
% the left or forward 1.
%
% cb.vmoves([5,7])
% = { 13, 15, 16, 19, 54 } <-- the bishop is implemented
% using iuntil() and gives
% absolute indices. You can
% still loop through and use
% them!
%
% The NEW prio (performance) parameter determines which aspects to
% skip (this is primarily regarding speeding up the AI; imperative
% player moves should be left at prio 1).
%
% -1 -> Skips castling/en passant (same as 2), INCLUDES diagonal moves for
% pawns.
% 1 -> Calculates all (castling and en passant).
% 2 -> Skips castling and en passant. Default.
% 3 -> Skips pawns, castling, and en passant.
function moves = vmoves(obj, pos, prio)
isforcedp = false;
% Set prio if not passed.
if nargin < 3
prio = 2;
elseif prio == -1
isforcedp = true;
prio = 2;
end
% Get chess piece object
piece = obj.get(unflat(pos, 8));
% This is a buffer — this is more efficient than the original
% Queue which had to resize every time which was very costly.
% Increasing priority takes a larger initial cost to avoid
% resizing as much as possible; normally we risk a lil.
bfr = Buffer(clamp(10 * prio, 15, 30));
% If no piece present, skip all checks.
if ~iseabs(piece)
player = piece.Player; % 1 for white, 2 for black
% Check all potential moves based on piece type.
switch (piece.Type)
case PieceType.Pawn
if prio < 3
% Move forward 1 space (## target is empty)
move_fw1 = rel2abs(pos, [1,0], player);
if (valabs(move_fw1) && obj.iserel(move_fw1))
bfr.a(move_fw1);
end
% Move forward 2 spaces (## pure-flagged, target is empty and path unobstructed)
if piece.FlagPure
move_fw2 = rel2abs(pos, [2,0], player);
if (valabs(move_fw2) && obj.isuno(pos, move_fw2))
bfr.a(move_fw2);
end
end
% Diagornal 1 space (## target occupied by opponent)
% + en passant (## pawn on 1 row into opponent, prior
% turn opponent pawn 2-hopped to horizontal adjacent)
moves_diag = { [1,1], [1,-1] };
% Filter invalid moves (normally this would be
% implicitly done via valabs check, but we need to
% always check diagonals for en passant now.
moves_diag = moves_diag(cellfun(@(m) valrel(pos, m, player), moves_diag));
if isforcedp
bfr.aa(cellfun(@(m) rel2abs(pos, m, player), moves_diag, "UniformOutput", false));
else
for i = 1:length(moves_diag)
relmove = moves_diag{i};
if prio < 2
% Absolute conversion
absmove = rel2abs(pos, relmove, player);
% En passant row for your piece
enp_row = 3 + player;
% En passant's other piece.
enp_oppo = obj.get(rel2abs(pos, [0, relmove(2)], player));
% Verbose/one-liner for compactness. Checks if
% move itself is valid, then if either opponent
% or [EN PASSANT CONDITIONS] add.
% Note that ensuring enp_row guarantees
% enp_oppo is valid (skipping a valrel) but we
% do still need to check emptiness hence var
% separation.
% o/ hiya--! you actually don't need to check if
% there is a piece to capture or not... since a
% 2-hop requires empty space!
if valabs(absmove) && (obj.isoppo(absmove, player) || (prio == 1 && pos(1) == enp_row && ~iseabs(enp_oppo) && enp_oppo.Type == PieceType.Pawn && enp_oppo.FlagTemp))
bfr.a(absmove);
end
end
end
end
end
case PieceType.King
% All spaces in 1-space radius (## target
% unoccupied or is opponent)