summaryrefslogtreecommitdiff
path: root/plugins/!NotAdopted/Chess4Net/ChessRulesEngine.pas
blob: 466f7b9190114347959f24c64709137e88e7c0c8 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
////////////////////////////////////////////////////////////////////////////////
// All code below is exclusively owned by author of Chess4Net - Pavel Perminov
// (packpaul@mail.ru, packpaul1@gmail.com).
// Any changes, modifications, borrowing and adaptation are a subject for
// explicit permition from the owner.

unit ChessRulesEngine;

interface

uses
  Classes;

type
  TFigureName = (K, Q, R, B, N, P);
  TFigure = (WK, WQ, WR, WB, WN, WP, ES,
              BK, BQ, BR, BB, BN, BP); // ES - Empty Square
  TFigureColor = (fcWhite, fcBlack);

  TCastlingCapability = set of (
    WhiteKingSide, WhiteQueenSide, BlackKingSide, BlackQueenSide);

  PChessPosition = ^TChessPosition;
  TChessPosition = object // Chess position
    board: array[1..8, 1..8] of TFigure;
    color: TFigureColor; // Who moves
    castling: TCastlingCapability;
    en_passant: 0..8; // possibility of e.p 0 - no e.p.
  private
    procedure FUpdateKingSideCastling(AColor: TFigureColor);
    procedure FUpdateQueenSideCastling(AColor: TFigureColor);
  public
    function SetPiece(i, j: integer; APiece: TFigure): boolean;
  end;

  PMoveAbs = ^TMoveAbs;
  TMoveAbs = record
    i0, j0, i, j: byte;
    prom_fig: TFigureName;
  end;

  IChessRulesEngineable = interface
    function AskPromotionFigure(FigureColor: TFigureColor): TFigureName;
  end;

  TEvaluation = (evInGame, evMate, evStaleMate);

  TMoveNotationFormat = (mnfCh4N, mnfCh4NEx); // TODO: mnfPGN

  TChessRulesEngine = class
  private
    m_ChessRulesEngineable: IChessRulesEngineable;
    m_Position: TChessPosition;
    m_iMovesOffset: integer;
    m_i0, m_j0: integer;  // Previous position of piece
    m_fig: TFigure;    // Piece that moves
    m_lastMove: TMoveAbs; // Last move done
    m_strLastMoveStr: string; // last move in algebraic notation
    m_MoveNotationFormat: TMoveNotationFormat;
    m_bFENFormat: boolean;
    m_lstPosition: TList;

    function FGetPosition: PChessPosition;
    function FAskPromotionFigure(FigureColor: TFigureColor): TFigureName;
    procedure FAddPosMoveToList; // Add position and its move to the list
    function FMove2Str(const pos: TChessPosition): string;

    function FCheckMove(const chp: TChessPosition; var chp_res: TChessPosition;
      i0, j0, i, j: integer; var prom_fig: TFigureName): boolean;

    function FGetLastMove: PMoveAbs;
    procedure FDeleteLastPositionFromPositionList;

    function FDoMove(i, j: integer; prom_fig: TFigureName = K): boolean;

    class function FFieldUnderAttack(const pos: TChessPosition; i0,j0: integer): boolean;
    class function FCheckCheck(const pos: TChessPosition): boolean;
    function FCanMove(pos: TChessPosition): boolean;

    procedure FSetMovesOffset(iValue: integer);

    property i0: integer read m_i0 write m_i0;
    property j0: integer read m_j0 write m_j0;
    property fig: TFigure read m_fig write m_fig;

  public
    constructor Create(ChessRulesEngineable: IChessRulesEngineable = nil);
    destructor Destroy; override;

    function DoMove(move_str: string): boolean; overload;
    function DoMove(i0, j0, i, j: integer; prom_fig: TFigureName = K): boolean; overload;
    function TakeBack: boolean;
    function SetPosition(strValue: string): boolean;
    function GetPosition: string;
    function GetColorStarts: TFigureColor;
    procedure InitNewGame;
    procedure InitNewPPRandomGame;
    procedure ResetMoveList; // Clears positions list
    function NMovesDone: integer; // amount of moves done
    function NPlysDone: integer; // amount of plys done
    function GetFENMoveNumber: integer;
    function GetEvaluation: TEvaluation;

    property Position: PChessPosition read FGetPosition;
    property lastMove: PMoveAbs read FGetLastMove;
    property lastMoveStr: string read m_strLastMoveStr;
    property MovesOffset: integer read m_iMovesOffset write FSetMovesOffset;
    property PositionsList: TList read m_lstPosition;
    property MoveNotationFormat: TMoveNotationFormat
      read m_MoveNotationFormat write m_MoveNotationFormat;
    property FENFormat: boolean read m_bFENFormat write m_bFENFormat;
  end;

  PPosMove = ^TPosMove;
  TPosMove = record
    pos: TChessPosition;
    move: TMoveAbs;
  end;

const
  INITIAL_CHESS_POSITION = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -';
  EMPTY_CHESS_POSITION = '8/8/8/8/8/8/8/8 w - -';
  INITIAL_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
  EMPTY_FEN = '8/8/8/8/8/8/8/8 w - - 0 1';

implementation

{$J+}

uses
  SysUtils, StrUtils;

type
  TDeltaMove = array [TFigureName] of
    record
      longRange: boolean;
      dx,dy: array[1..8] of Integer;
    end;

const
  DELTA_MOVE: TDeltaMove = ((longRange: FALSE; // Êîðîëü
                            dx: (1,0,-1,0, 1,-1,-1,1); dy: (0,1,0,-1, 1,1,-1,-1)),
                            (longRange: TRUE; // Ôåðçü
                            dx: (1,0,-1,0, 1,-1,-1,1); dy: (0,1,0,-1, 1,1,-1,-1)),
                            (longRange: TRUE; // Ëàäüÿ
                            dx: (1,0,-1,0, 0,0,0,0); dy: (0,1,0,-1, 0,0,0,0)),
                            (longRange: TRUE; // Ñëîí
                            dx: (1,-1,-1,1, 0,0,0,0); dy: (1,1,-1,-1, 0,0,0,0)),
                            (longRange: FALSE; // Êîíü
                            dx: (2,1,-1,-2, 2,1,-1,-2); dy: (1,2,2,1, -1,-2,-2,-1)),
                            (longRange: FALSE; // Ïåøêà
                            dx: (0,0,-1,1, 0,0,0,0); dy: (2,1,1,1, 0,0,0,0)));

////////////////////////////////////////////////////////////////////////////////
// TChessRulesEngine

constructor TChessRulesEngine.Create(ChessRulesEngineable: IChessRulesEngineable = nil);
begin
  inherited Create;

  m_ChessRulesEngineable := ChessRulesEngineable;
  m_lstPosition := TList.Create;

  InitNewGame;
end;


destructor TChessRulesEngine.Destroy;
begin
  ResetMoveList;
  m_lstPosition.Free;
  
  inherited;
end;


function TChessRulesEngine.FGetPosition: PChessPosition;
begin
  Result := @m_Position;
end;


function TChessRulesEngine.FAskPromotionFigure(FigureColor: TFigureColor): TFigureName;
begin
  if (Assigned(m_ChessRulesEngineable)) then
    Result := m_ChessRulesEngineable.AskPromotionFigure(FigureColor)
  else
    Result := Q;
end;


class function TChessRulesEngine.FCheckCheck(const pos: TChessPosition): boolean;
label
  l;
const
  _i0: integer = 1; // äëÿ óâåëè÷åíèÿ ñêîðîñòè îáðàáîòêè
  _j0: integer = 1;
var
  i, j: integer;
begin
  with pos do
  begin
    if ((color = fcWhite) and (board[_i0, _j0] = WK)) or
       ((color = fcBlack) and (board[_i0, _j0] = BK)) then goto l;
    // ïîèñê êîðîëÿ íà äîñêå
    for i:= 1 to 8 do
    begin
      for j:= 1 to 8 do
      begin
        if ((color = fcWhite) and (board[i,j] = WK)) or
           ((color = fcBlack) and (board[i,j] = BK)) then
        begin
          _i0 := i;
          _j0 := j;
          goto l;
        end;
      end; // for j
    end; // for i
l:
    Result := FFieldUnderAttack(pos, _i0, _j0);
  end;
end;


class function TChessRulesEngine.FFieldUnderAttack(const pos: TChessPosition; i0, j0: integer): boolean;
var
  f: TFigureName;
  ef: TFigure;
  l: byte;
  ti,tj: Integer;
  locLongRange: boolean;
begin
  for f:= R to N do
    for l:= 1 to 8 do
      with DELTA_MOVE[f], pos do
        begin
          if (dx[l] = 0) and (dy[l] = 0) then break; // Âñå õîäû ïðîñìîòðåíû
          ti:= i0; tj:= j0;
          locLongRange:= FALSE;
          repeat
            ti:= ti + dx[l]; tj:= tj + dy[l];
            if not(ti in [1..8]) or not(tj in [1..8]) then break;
            ef:= board[ti,tj];
            if ((color = fcWhite) and (ef < ES)) or ((color = fcBlack) and (ef > ES))
              then break;
            case ef of
              WK,BK:
                if locLongRange or (f = N) then break;
              WQ,BQ:
                if f = N then break;
              WR,BR:
                if f <> R then break;
              WB,BB:
                if f <> B then break;
              WN,BN:
                if f <> N then break;
              WP,BP:
                if locLongRange or (f <> B) or
                   ((color = fcWhite) and not(tj > j0)) or
                   ((color = fcBlack) and not(tj < j0))
                          then break;
              ES:
                begin
                  locLongRange:= TRUE;
                  continue;
                end;
            end;
            Result:= TRUE;
            exit;
          until (not longRange);
        end;

  Result := FALSE;
end;


function TChessRulesEngine.FCheckMove(const chp: TChessPosition; var chp_res: TChessPosition;
  i0, j0, i, j: integer; var prom_fig: TFigureName): boolean;
label
  here;
var
  ti,tj: integer;
  l: byte;
  f: TFigureName;
  _fig: TFigure;
  pos: TChessPosition;
begin
  Result := FALSE;
  
  if (not ((i0 in [1..8]) and (j0 in [1..8]) and
           (i in [1..8]) and (j in [1..8]))) then
    exit;

  _fig := chp.board[i0, j0];
  if (((chp.color = fcWhite) and (_fig > ES)) or
      ((chp.color = fcBlack) and (_fig < ES))) then
    exit;

  f := TFigureName(ord(_fig) - ord(chp.color) * ord(BK));

  for l := 1 to 8 do
    with DELTA_MOVE[f], chp do
      begin
        if (dx[l] = 0) and (dy[l] = 0) then
          break; // All moves have been viewed

        ti := i0;
        tj := j0;

        case f of
          P:
          begin
            if ((l = 1) and
                (not (((color = fcWhite) and (j0 = 2) and (board[i0,3] = ES)) or
                      ((color = fcBlack) and (j0 = 7) and (board[i0,6] = ES))))) then
              continue; // Pawn is not on 2/7 row - long move is impossible

            case color of
              fcWhite:
              begin
                inc(ti, dx[l]);
                inc(tj, dy[l]);
              end;

              fcBlack:
              begin
                dec(ti, dx[l]);
                dec(tj, dy[l]);
              end;
            end;
              
            if (not (ti in [1..8]) or not(tj in [1..8])) then
              continue;
            if ((l <= 2) and (board[ti,tj] <> ES)) then
              continue; // There's a piece before the pawn -> exit

            if ((l >= 3) and (not (((color = fcWhite) and ((board[ti,tj] > ES) or
                                   ((j0 = 5) and (en_passant = ti)))) or
                                  ((color = fcBlack) and ((board[ti,tj] < ES) or
                                   ((j0 = 4) and (en_passant = ti))))))) then
              continue;

            if ((ti = i) and (tj = j)) then
              goto here;
          end;
          
        else
          begin
            repeat
              inc(ti, dx[l]);
              inc(tj, dy[l]);

              if ((not (ti in [1..8])) or (not (tj in [1..8])) or
                  ((color = fcWhite) and ((board[ti,tj] < ES) or
                   ((board[ti,tj] > ES) and ((ti <> i) or (tj <> j))))) or
                  ((color = fcBlack) and ((board[ti,tj] > ES) or
                   ((board[ti,tj] < ES) and ((ti <> i) or (tj <> j)))))) then
                break;

              if ((ti = i) and (tj = j)) then
                goto here;

            until (not longRange);
          end;

        end; { case }
      end;

      if (f = K) then // Checking against castling
      begin
        with chp do
        begin
          if (i-i0 = 2) and (j = j0) and
             (((color = fcWhite) and (WhiteKingSide in castling)) or
              ((color = fcBlack) and (BlackKingSide in castling))) then
          begin
            if ((board[6,j0] <> ES) or (board[7,j0] <> ES) or // 0-0
                FFieldUnderAttack(chp,5,j0) or
                FFieldUnderAttack(chp,6,j0)) then exit;
          end
          else if ((i-i0 = -2) and (j = j0) and
             (((color = fcWhite) and (WhiteQueenSide in castling)) or
              ((color = fcBlack) and (BlackQueenSide in castling)))) then
          begin
            if ((board[4,j0] <> ES) or (board[3,j0] <> ES) or // 0-0-0
                (board[2,j0] <> ES) or
                FFieldUnderAttack(chp,5,j0) or
                FFieldUnderAttack(chp,4,j0)) then
              exit;
          end
          else
            exit;

          goto here;
        end;
      end;

      exit; // The piece was moved not according to rules

here:
  // Making move on pos
  pos := chp;
  
  with pos do
  begin
    case f of
      P:
      begin
        if (((color = fcWhite) and (j0 = 5)) or
            ((color = fcBlack) and (j0 = 4))) and (i = en_passant) then
          board[i,j0]:= ES; // remove enemy pawn with e.p.
      end;

      K:
      begin
        if i-i0 = 2 then
          begin
            board[6,j0]:= board[8,j0]; // 0-0
            board[8,j0]:= ES;
          end
        else
        if i0-i = 2 then
          begin
            board[4,j0]:= board[1,j0]; // 0-0-0
            board[1,j0]:= ES;
          end;
        case color of
          fcWhite:
            castling:= castling - [WhiteKingSide, WhiteQueenSide];
          fcBlack:
            castling:= castling - [BlackKingSide, BlackQueenSide];
        end;
      end;

      R:
        begin
          if ((i0 = 8) and (j0 = 1)) or ((i = 8) and (j = 1)) then
            castling := castling - [WhiteKingSide]
          else if ((i0 = 1) and (j0 = 1)) or ((i = 1) and (j = 1)) then
            castling := castling - [WhiteQueenSide]
          else if ((i0 = 8) and (j0 = 8)) or ((i = 8) and (j = 8)) then
            castling := castling - [BlackKingSide]
          else if ((i0 = 1) and (j0 = 8)) or ((i = 1) and (j = 8)) then
            castling := castling - [BlackQueenSide];
        end;
    end;

    if ((f = P) and (abs(j-j0) = 2) and
        (((i > 1) and (((color = fcWhite) and (board[i-1,j] = BP)) or
                       ((color = fcBlack) and (board[i-1,j] = WP)))) or
         ((i < 8) and (((color = fcWhite) and (board[i+1,j] = BP)) or
                       ((color = fcBlack) and (board[i+1,j] = WP)))))) then
      en_passant := i0 // e.p. on
    else
      en_passant := 0; // e.p. off

    // make the move

    board[i0, j0]:= ES;
    board[i, j] := _fig;
    
    if (FCheckCheck(pos)) then
      exit; // move is impossible because of check
      
    if (f = P) and ((j = 1) or (j = 8)) then
    begin
      case prom_fig of
        Q..N: ;
      else
        prom_fig := FAskPromotionFigure(pos.color);
      end; // case
      board[i, j] := TFigure(ord(color) * ord(BK) + ord(prom_fig));
    end;

    if (color = fcWhite) then
      color := fcBlack
    else
      color := fcWhite;
  end; // with

  chp_res := pos;
  
  Result:= TRUE;
end;


function TChessRulesEngine.FCanMove(pos: TChessPosition): boolean;
var
  i,j: integer;
  ti,tj: integer;
  l: byte;
  f: TFigureName;
  prom_fig: TFigureName;
begin
  with pos do
    for i:= 1 to 8 do
      for j:= 1 to 8 do
        begin
          if ((color = fcWhite) and (board[i,j] >= ES)) or
             ((color = fcBlack) and (board[i,j] <= ES)) then continue;

          f:= TFigureName(ord(board[i,j]) - ord(color) * ord(BK));
          for l:= 1 to 8 do
            with DELTA_MOVE[f] do
              begin
                if (dx[l] = 0) and (dy[l] = 0) then break; // Âñå õîäû ïðîñìîòðåíû
                ti:= i; tj:= j;
                repeat
                  case color of
                    fcWhite:
                      begin
                        ti:= ti + dx[l]; tj:= tj + dy[l];
                      end;
                    fcBlack:
                      begin
                        ti:= ti - dx[l]; tj:= tj - dy[l];
                      end;
                  end;
                  if not ((ti in [1..8]) and (tj in [1..8])) then break;
                  prom_fig := Q;
                  if FCheckMove(pos, pos, i, j, ti, tj, prom_fig) then
                  begin
                    Result:= TRUE;
                    exit;
                  end;
                until not longRange;
              end;
        end;

  Result := FALSE;
end;


function TChessRulesEngine.DoMove(move_str: string): boolean;
label
  l1;
var
  l: byte;
  f, prom_f: TFigureName;
  i, j: integer;
  ti, tj: integer;
  saved_i, saved_j: integer;
begin
  Result := FALSE;

  l := length(move_str);
  if ((l <= 1)) then // at least two characters
    exit;

  if ((move_str[l] in ['+', '#'])) then
    move_str := LeftStr(move_str, l - 1);

  // Ïðîâåðêà íà ðîêèðîâêó
  if (move_str = '0-0') then
  begin
    if (Position.color = fcWhite) then
      move_str:= 'Ke1g1'
    else
      move_str:= 'Ke8g8'
  end
  else if (move_str = '0-0-0') then
  begin
    if (Position.color = fcWhite) then
      move_str:= 'Ke1c1'
    else
      move_str:= 'Ke8c8';
  end;

  l := length(move_str);

  i0 := 0;
  j0 := 0;
  i := 0;
  j := 0;

  prom_f := K;
  case move_str[l] of
    'Q': prom_f := Q;
    'R': prom_f := R;
    'B': prom_f := B;
    'N': prom_f := N;
  else
    inc(l);
  end;

  dec(l);

  if move_str[l] in ['1'..'8'] then
  begin
    j := StrToInt(move_str[l]);
    dec(l);
  end;
  if move_str[l] in ['a'..'h'] then
  begin
    i := ord(move_str[l]) - ord('a') + 1;
    dec(l);
  end;
  if (l > 0) and (move_str[l] in ['1'..'8']) then
  begin
    j0 := StrToInt(move_str[l]);
    dec(l);
  end;
  if (l > 0) and (move_str[l] in ['a'..'h']) then
  begin
    i0 := ord(move_str[l]) - ord('a') + 1;
    dec(l);
  end;

  if (l = 0) then
    f := P
  else
  begin
    case move_str[l] of
      'K': f:= K;
      'Q': f:= Q;
      'R': f:= R;
      'B': f:= B;
      'N': f:= N;
    end;
  end;

  with m_Position do
  begin
    fig := TFigure(ord(f) + ord(Position.color) * ord(BK));

    case f of
      K..N: // Õîä Êð - Ê
      begin
        if ((i0 > 0) and (j0 > 0)) then
        begin
          Result := FDoMove(i, j, prom_f);
          exit;
        end;

        for l := 1 to 8 do
        begin
          with DELTA_MOVE[f] do
          begin
            if (dx[l] = 0) and (dy[l] = 0) then break; // Âñå õîäû ïðîñìîòðåíû
            ti:= i;
            tj:= j;
            repeat
              ti:= ti + dx[l];
              tj:= tj + dy[l];
              if not ((ti in [1..8]) and (tj in [1..8])) or
                 ((board[ti,tj] <> ES) and (board[ti,tj] <> fig)) then
                break;

              if ((i0 = 0) or (i0 = ti)) and ((j0 = 0) or (j0 = tj)) and
                 (board[ti, tj] = fig) then
                begin // Õîäÿùàÿ ôèãóðà íàéäåíà
                  saved_i := i0;
                  saved_j := j0;

                  i0 := ti;
                  j0 := tj;
                  Result := FDoMove(i, j, prom_f);
                  if (Result) then
                    exit;

                  i0 := saved_i;
                  j0 := saved_j;
                end;
            until (f = K) or (f = N); // Åñëè Êð èëè Ê, òî âûõîä
          end; // with
        end; // for
      end; // K..N

      P:    // Õîä ïåøêîé
      begin
        if (i0 <> 0) and (i0 <> i) then // âçÿòèå ïåøêîé
        begin
          for l := 2 to 7 do
          begin
            if (board[i0, l] = fig) and ((j0 = 0) or (j0 = l)) then
            begin
              if color = fcWhite then
              begin
                if ((board[i, l + 1] > ES) or
                    ((l = 5) and (en_passant = i))) and
                   ((j = 0) or (j = l+1)) and (abs(i - i0) = 1) then
                begin
                  j0 := l;
                  j := l + 1;
                  Result := FDoMove(i, j, prom_f);
                  if (Result) then
                    exit;
                end;
              end
              else // color = fcBlack
              if ((board[i,l - 1] < ES) or
                  ((l = 4) and (en_passant = i))) and
                 ((j = 0) or (j = l-1)) and (abs(i - i0) = 1) then
              begin
                j0 := l;
                j := l - 1;
                Result := FDoMove(i, j, prom_f);
                if (Result) then
                  exit;
              end;
            end; // if
          end; // for
        end
        else  // Õîä ïðÿìî
        begin
          i0 := i;
          if color = fcWhite then
          begin
            if board[i, j - 1] = fig then
              j0 := j - 1
            else if (j = 4) and (board[i, 3] = ES) and
                    (board[i,2] = fig) then
              j0 := 2;
          end
          else // color = fcBlack
          begin
            if (board[i, j + 1] = fig) then
              j0 := j + 1
            else if (j = 5) and (board[i,6] = ES) and (board[i, 7] = fig) then
              j0 := 7;
          end;

          Result := FDoMove(i, j, prom_f);
        end; // if
      end; // P:

    end;  // case
  end;
end;


function TChessRulesEngine.FDoMove(i, j: integer; prom_fig: TFigureName = K): boolean;
var
  newPosition: TChessPosition;
begin
  Result := FCheckMove(m_Position, newPosition, i0, j0, i, j, prom_fig);
  if (Result) then
  begin
    // Store the move done
    lastMove.i0 := i0;
    lastMove.j0 := j0;
    lastMove.i := i;
    lastMove.j := j;
    lastMove.prom_fig := prom_fig;

    FAddPosMoveToList;

    m_strLastMoveStr := FMove2Str(newPosition);
    
    m_Position := newPosition;
  end;
end;


function TChessRulesEngine.DoMove(i0, j0, i, j: integer; prom_fig: TFigureName = K): boolean;
begin
  self.i0 := i0;
  self.j0 := j0;
  Result := FDoMove(i, j, prom_fig);
end;


function TChessRulesEngine.FGetLastMove: PMoveAbs;
begin
  Result := @m_lastMove;
end;


procedure TChessRulesEngine.FAddPosMoveToList;
var
  pm: PPosMove;
begin
  new(pm);
  pm.pos := m_Position;
  pm.move := lastMove^;
  PositionsList.Add(pm);
end;


function TChessRulesEngine.FMove2Str(const pos: TChessPosition): string;

  procedure NExtendWithCheckOrMate(var strMove: string);
  begin
    if (strMove = '') then
      exit;

    if (FCheckCheck(pos)) then
    begin
      if (FCanMove(pos)) then
        strMove := strMove + '+'
      else
        strMove := strMove + '#';      
    end;
  end;

var
  f: TFigureName;
  l: byte;
  ti, tj: integer;
  ambig, hor, ver: boolean;
  _fig: TFigure;
  DummyPosition: TChessPosition;
begin // .FMove2Str
  if (lastMove.i0 = 0) then // No move
  begin
    Result:= '';
    exit;
  end;

  _fig := Position.board[lastMove.i0, lastMove.j0];
  f := TFigureName(ord(_fig) + (ord(pos.color) - 1) * ord(BK));

  // Pawn moves
  if (f = P) then
  begin
    with pos do
    begin
      if ((lastMove.i - lastMove.i0) = 0) then // move
        Result := chr(ord('a') + lastMove.i - 1) + IntToStr(lastMove.j)
      else // capturing
      begin
        Result := chr(ord('a') + lastMove.i0 - 1) + chr(ord('a') + lastMove.i - 1);

        for l := 2 to 7 do // Checking against ambiguity of capturing
        begin
          if (board[lastMove.i0, l] = WP) then
            tj := l + 1
          else if (board[lastMove.i0, l] = BP) then
            tj := l - 1
          else
            continue;

          if ((((tj > l)  and ((Position.board[lastMove.i, tj] > ES) or
               ((Position.en_passant = lastMove.i) and (l = 5)))) and (color = fcBlack)) or
              (((tj < l)  and ((Position.board[lastMove.i, tj] < ES) or
               ((Position.en_passant = lastMove.i) and (l = 4)))) and (color = fcWhite))) then
          begin
            if ((MoveNotationFormat <> mnfCh4NEx) or
                FCheckMove(m_Position, DummyPosition, lastMove.i0, l, lastMove.i, tj,
                           lastMove.prom_fig)) then
            begin
              Result := Result + IntToStr(lastMove.j);
            end;
          end;
          
        end;
      end;

      if (lastMove.j = 8) or (lastMove.j = 1) then // The pawn has been promoted
      begin
        case board[lastMove.i,lastMove.j] of
          WQ,BQ: Result := Result + 'Q';
          WR,BR: Result := Result + 'R';
          WB,BB: Result := Result + 'B';
          WN,BN: Result := Result + 'N';
        end;
      end;

      if (m_MoveNotationFormat = mnfCh4NEx) then
        NExtendWithCheckOrMate(Result);

      exit;
      
    end; // with
  end; // if

  // <Piece>
  case f of
    K: Result:= 'K';
    Q: Result:= 'Q';
    R: Result:= 'R';
    B: Result:= 'B';
    N: Result:= 'N';
  end;

  // [<Line>][<Row>]
  ambig:= FALSE;
  hor:= FALSE;
  ver:= FALSE;

  for l := 1 to 8 do
  begin
    with pos, DELTA_MOVE[f] do
    begin
      if (dx[l] = 0) and (dy[l] = 0) then
        break; // All moves have been viewed

      ti := lastMove.i;
      tj := lastMove.j;

      repeat
        inc(ti, dx[l]);
        inc(tj, dy[l]);

        if ((not (ti in [1..8])) or (not (tj in [1..8]))) then
          break;

        if (board[ti,tj] = ES) then
          continue;

        if (board[ti, tj] <> _fig) then
          break;

        if ((m_MoveNotationFormat <> mnfCh4NEx) or
            FCheckMove(m_Position, DummyPosition, ti, tj, lastMove.i, lastMove.j,
                       lastMove.prom_fig)) then
        begin
          ambig := TRUE;
          ver := (ver or (ti = lastMove.i0));
          hor := (hor or (tj = lastMove.j0));

          break;
        end;

      until (f = K) or (f = N); // If K or N -> exit
      
    end;
  end; // for l

  if (ambig) then
  begin
    if ((not ver) or hor) then
      Result := Result + chr(ord('a') + lastMove.i0 - 1);
    if (ver) then
      Result := Result + IntToStr(lastMove.j0);
  end;

  // <Destination field>
  Result := Result + chr(ord('a') + lastMove.i - 1) + IntToStr(lastMove.j);

  // <Short castling> | <Long castling>
  if (f = K) then
  begin
    if ((lastMove.i - lastMove.i0) = 2) then
      Result := '0-0'
    else if (lastMove.i0 - lastMove.i = 2) then
      Result := '0-0-0';
  end;

  if (m_MoveNotationFormat = mnfCh4NEx) then
    NExtendWithCheckOrMate(Result);
end;


function TChessRulesEngine.TakeBack: boolean;
begin
  Result := (PositionsList.Count > 0);
  if (Result) then
  begin
    FDeleteLastPositionFromPositionList;
    lastMove.i0 := 0;
  end;
end;


procedure TChessRulesEngine.FDeleteLastPositionFromPositionList;
var
  i: integer;
begin
  i := PositionsList.Count - 1;
  if (i >= 0) then
  begin
    m_Position := PPosMove(PositionsList[i]).pos;
    Dispose(PositionsList[i]);
    PositionsList.Delete(i);
  end;
end;


function TChessRulesEngine.SetPosition(strValue: string): boolean;

  function NNextToken(var str: string): string;
  var
    iPos: integer;
  begin
    str := TrimLeft(str);
    if (str = '') then
      Result := ''
    else
    begin
      iPos := Pos(' ', str);
      if (iPos > 0) then
      begin
        Result := LeftStr(str, Pred(iPos));
        str := Copy(str, iPos, MaxInt);
      end
      else
      begin
        Result := str;
        str := '';
      end;
    end;
  end;

var
  pos: TChessPosition;

  function NSetPlacingOfPieces: boolean;
  var
    strPos: string;
    iPos: integer;
    j, i, k: integer;
  begin
    Result := FALSE;

    strPos := NNextToken(strValue);

    iPos := 1;

    for j := 8 downto 1 do
    begin
      i := 1;
      repeat
        if (iPos > Length(strPos)) then
          exit;

        case strPos[iPos] of
          'K': pos.board[i,j]:= WK;
          'Q': pos.board[i,j]:= WQ;
          'R': pos.board[i,j]:= WR;
          'B': pos.board[i,j]:= WB;
          'N': pos.board[i,j]:= WN;
          'P': pos.board[i,j]:= WP;

          'k': pos.board[i,j]:= BK;
          'q': pos.board[i,j]:= BQ;
          'r': pos.board[i,j]:= BR;
          'b': pos.board[i,j]:= BB;
          'n': pos.board[i,j]:= BN;
          'p': pos.board[i,j]:= BP;

          '1'..'8': // Insert empty fields
            begin
              k := StrToInt(strPos[iPos]);
              repeat
                pos.board[i,j]:= ES;
                dec(k); inc(i);
              until k = 0;
              dec(i);
            end;

          ' ': break; // Position is read -> exit from loop

          else
            exit; // Error in strPos
        end;

        inc(i);
        inc(iPos);

      until ((i > 8) or (strPos[iPos] = '/')); // Repeat until '/' or if not on the row

      inc(iPos);
      
    end; // for j

    Result := TRUE;
  end;

var
  i: integer;
  iMovesOffset: integer;
  strToken: string;
begin // .SetPosition
  Result := NSetPlacingOfPieces;
  if (not Result) then
    exit;

  // Defaults
  pos.color := fcWhite;
  pos.castling := [];
  pos.en_passant := 0;
  iMovesOffset := 0;

  try
    strToken := NNextToken(strValue);
    if (strToken = '') then
      exit;

    case strToken[1] of
      'w':
        pos.color := fcWhite;
      'b':
        pos.color := fcBlack;
      else
        exit;
    end;

    strToken := NNextToken(strValue);
    if (strToken = '') then
      exit;

    for i := 1 to Length(strToken) do
    begin
      with pos do
      begin
        case strToken[i] of
          'K':
            Include(castling, WhiteKingSide);
          'Q':
            Include(castling, WhiteQueenSide);
          'k':
            Include(castling, BlackKingSide);
          'q':
            Include(castling, BlackQueenSide);
          '-':
            castling := [];
        else
          exit;
        end;
      end;

    end; // for

    strToken := NNextToken(strValue);
    if (strToken = '') then
      exit;

    with pos do
    begin
      case strToken[1] of
        'a'..'h':
          en_passant := ord(strToken[1]) - ord('a') + 1;
      end;
    end;

    strToken := NNextToken(strValue);
    if (strToken = '') then
      exit;

    // Skip 50-moves counter

    strToken := NNextToken(strValue);
    if (strToken = '') then
      exit;

    iMovesOffset := StrToIntDef(strToken, 1) - 1;
    if (iMovesOffset < 0) then
      iMovesOffset := 0;

  finally
    ResetMoveList;
    m_Position := pos;
    m_iMovesOffset := iMovesOffset;
  end;

end;


procedure TChessRulesEngine.InitNewGame;
var
  bRes: boolean;
begin
  bRes := SetPosition(INITIAL_CHESS_POSITION);
  Assert(bRes);
end;


procedure TChessRulesEngine.ResetMoveList;
var
  i: integer;
begin
  for i := 0 to PositionsList.Count - 1 do
    Dispose(PositionsList[i]);
  PositionsList.Clear;

  lastMove.i0 := 0;
end;


function TChessRulesEngine.GetPosition: string;

  function NGetPlacingOfPieces: string;
  var
    i, j: Integer;
    k: byte;
    chFig: char;
  begin
    Result := '';

    // Placing of pieces
    for j := 8 downto 1 do
    begin
      k := 0;

      for i := 1 to 8 do
      begin
        case Position.board[i, j] of
          WK: chFig := 'K';
          WQ: chFig := 'Q';
          WR: chFig := 'R';
          WB: chFig := 'B';
          WN: chFig := 'N';
          WP: chFig := 'P';
          BK: chFig := 'k';
          BQ: chFig := 'q';
          BR: chFig := 'r';
          BB: chFig := 'b';
          BN: chFig := 'n';
          BP: chFig := 'p';
          ES:
          begin
            inc(k);
            continue;
          end;
        end;

        if (k > 0) then
        begin
          Result := Result + IntToStr(k);
          k := 0;
        end;

        Result := Result + chFig;
      end; // for i

      if (k > 0) then
        Result := Result + IntToStr(k);
      if (j = 1) then
        Result := Result + ' '
      else
        Result := Result + '/'; // i <= 7
    end; // for j

  end;

begin // .GetPosition
  Result := NGetPlacingOfPieces;

  if (Position.color = fcWhite) then
    Result := Result + 'w '
  else
    Result := Result + 'b '; // color = fcBlack

  // Castling
  if (Position.castling = []) then
    Result := Result + '-'
  else
  begin
    if (WhiteKingSide in Position.castling) then
      Result := Result + 'K';
    if (WhiteQueenSide in Position.castling) then
      Result := Result + 'Q';
    if (BlackKingSide in Position.castling) then
      Result := Result + 'k';
    if (BlackQueenSide in Position.castling) then
      Result := Result + 'q';
  end;

  // en-passant
  if (Position.en_passant = 0) then
    Result := Result + ' -'
  else
  begin
    Result := Result + ' ' + Chr(Ord('a') - 1 + Position.en_passant);
  end;

  if (not FENFormat) then
    exit;

  if (Position.en_passant <> 0) then
  begin
    if (Position.color = fcWhite) then
      Result := Result + '6'
    else
      Result := Result + '3'; // Black
  end;

  Result := Result + ' 0'; // TODO: 50-moves rule

  Result := Result + ' ' + IntToStr(GetFENMoveNumber);
end;


function TChessRulesEngine.GetFENMoveNumber: integer;
begin
  Result := NMovesDone;
  if ((m_Position.color = fcWhite) or (Result = 0)) then
    inc(Result);
end;


procedure TChessRulesEngine.FSetMovesOffset(iValue: integer);
begin
  Assert(iValue >= 0);
  m_iMovesOffset := iValue;
end;


procedure TChessRulesEngine.InitNewPPRandomGame;
const
  FIG: array[0..5] of TFigureName = (B, B, Q, R, N, N);
  SQR: array[0..5] of byte = (2, 3, 4, 6, 7, 0);
var
  rnd_sqr: array[0..5] of byte;
  i,j: integer;
  f: boolean;
begin
  InitNewGame;

  if (Random(2) = 0) then
    SQR[5] := 1 // ñ êàêîé ñòîðîíû îñòàâëÿåì ëàäüþ
  else
    SQR[5] := 8;

  for i := 0 to 5 do
  begin
    repeat
      rnd_sqr[i] := SQR[Random(6)];
      f := FALSE;
      for j := 0 to i-1 do f := f or (rnd_sqr[i] = rnd_sqr[j]);
    until not (f or ((i = 1) and (((rnd_sqr[0] xor rnd_sqr[1]) and 1) = 0)));
    m_Position.board[rnd_sqr[i], 1] := TFigure(ord(FIG[i]));
    m_Position.board[rnd_sqr[i], 8] := TFigure(ord(BK) + ord(FIG[i]));
  end;
end;


function TChessRulesEngine.NMovesDone: integer;
var
  iMovesCount: integer;
begin
  if ((PositionsList.Count = 0) and (m_iMovesOffset = 0)) then
    iMovesCount := 0
  else
  begin
    if (GetColorStarts = fcWhite) then
      iMovesCount := ((PositionsList.Count + 1) div 2)
    else // GetColorStarts = fcBlack
      iMovesCount := ((PositionsList.Count + 2) div 2);
  end;

  Result := m_iMovesOffset + iMovesCount;
end;


function TChessRulesEngine.GetColorStarts: TFigureColor;
begin
  if (Odd(PositionsList.Count) and (m_Position.color = fcBlack)) or
      (not Odd(PositionsList.Count) and (m_Position.color = fcWhite)) then
    Result := fcWhite
  else
    Result := fcBlack;
end;


function TChessRulesEngine.NPlysDone: integer; // amount of plys done
begin
  Result := (2 * m_iMovesOffset) + PositionsList.Count;
end;


function TChessRulesEngine.GetEvaluation: TEvaluation;
begin
  Result := evInGame;
  if (not FCanMove(m_Position)) then
  begin
    if (FCheckCheck(m_Position)) then
      Result := evMate
    else
      Result := evStaleMate;
  end;
  // TODO: Evaluate position for possible technical draw
end;


function TChessPosition.SetPiece(i, j: integer; APiece: TFigure): boolean;
var
  SavedPiece: TFigure;
begin
  Result := ((i in [1..8]) and (j in [1..8]));
  if (not Result) then
    exit;

  SavedPiece := board[i, j];
  board[i, j] := APiece;

  if (SavedPiece = APiece) then
    exit;

  if ((i = 5) and (j = 1)) then
  begin
    FUpdateKingSideCastling(fcWhite);
    FUpdateQueenSideCastling(fcWhite);
  end
  else if ((i = 8) and (j = 1)) then
    FUpdateKingSideCastling(fcWhite)
  else if ((i = 1) and (j = 1)) then
    FUpdateQueenSideCastling(fcWhite)
  else if ((i = 5) and (j = 8)) then
  begin
    FUpdateKingSideCastling(fcBlack);
    FUpdateQueenSideCastling(fcBlack);
  end
  else if ((i = 8) and (j = 8)) then
    FUpdateKingSideCastling(fcBlack)
  else if ((i = 1) and (j = 8)) then
    FUpdateQueenSideCastling(fcBlack);
end;


procedure TChessPosition.FUpdateKingSideCastling(AColor: TFigureColor);
var
  j: integer;
  King, Rook: TFigure;
begin
  if (AColor = fcWhite) then
  begin
    j := 1;
    King := WK;
    Rook := WR;
  end
  else // fcBlack
  begin
    j := 8;
    King := BK;
    Rook := BR;
  end;

  if ((board[5, j] = King) and (board[8, j] = Rook)) then
  begin
    if (AColor = fcWhite) then
      Include(castling, WhiteKingSide)
    else
      Include(castling, BlackKingSide);
  end
  else
  begin
    if (AColor = fcWhite) then
      Exclude(castling, WhiteKingSide)
    else
      Exclude(castling, BlackKingSide);
  end;

end;


procedure TChessPosition.FUpdateQueenSideCastling(AColor: TFigureColor);
var
  j: integer;
  King, Rook: TFigure;
begin
  if (AColor = fcWhite) then
  begin
    j := 1;
    King := WK;
    Rook := WR;
  end
  else // fcBlack
  begin
    j := 8;
    King := BK;
    Rook := BR;
  end;

  if ((board[5, j] = King) and (board[1, j] = Rook)) then
  begin
    if (AColor = fcWhite) then
      Include(castling, WhiteQueenSide)
    else
      Include(castling, BlackQueenSide);
  end
  else
  begin
    if (AColor = fcWhite) then
      Exclude(castling, WhiteQueenSide)
    else
      Exclude(castling, BlackQueenSide);
  end;

end;

initialization

begin
  Randomize; // It's for PP Random
end;

finalization

end.