-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathchessbrd.pas
3893 lines (3375 loc) · 112 KB
/
chessbrd.pas
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
//--------------------------------------------------------------------------
// ChessBoard Component for Delphi2-5
// Version 3.03 - Feb 5, 2000
// Author: Daniel Terhell, Resplendence Sp
// Copyright (c) 1997-2000 Resplendence Sp
//
// Contains translated source from Tom's Simple Chess Program
//
// Contains graphics from Andrew Gate
//--------------------------------------------------------------------------
unit ChessBrd;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, ExtCtrls, ImgList;
{$RESOURCE Chessbrd.res}
const
// Resource Identifiers
SetAndrew40Str='SETANDREW40';
versionStr='3.02';
NoPiece =-1;
Black =0;
White =1;
// From Tom:
MOVE_STACK=4096;
HIST_STACK=64;
LIGHT =0;
DARK =1;
PAWN =0;
KNIGHT=1;
BISHOP=2;
ROOK =3;
QUEEN =4;
KING =5;
EMPTY =6;
// This is the basic description of a move. promote is what
// piece to promote the pawn to, if the move is a pawn
// promotion. bits is a bitfield that describes the move,
// with the following bits:
//
// 1 capture
// 2 castle
// 4 en passant capture
// 8 pushing a pawn 2 squares
// 16 pawn move
// 32 promote
//
type
EChessException = class(Exception);
Square=(None, A8,B8,C8,D8,E8,F8,G8,H8,
A7,B7,C7,D7,E7,F7,G7,H7,
A6,B6,C6,D6,E6,F6,G6,H6,
A5,B5,C5,D5,E5,F5,G5,H5,
A4,B4,C4,D4,E4,F4,G4,H4,
A3,B3,C3,D3,E3,F3,G3,H3,
A2,B2,C2,D2,E2,F2,G2,H2,
A1,B1,C1,D1,E1,F1,G1,H1);
DisplayCoords=(West, North, East, South);
CanStillCastle=(WhiteKingSide, WhiteQueenSide, BlackKingSide, BlackQueenSide);
CastleSet=set of CanStillCastle;
CoordSet= set of DisplayCoords;
MoveInfo = record
position: String;
Castling: CastleSet;
OldSquare,NewSquare, EnPassant: Square;
end;
pieces=(BP,BN,BB,BR,BK,BQ,WP,WN,WB,WR,WQ,WK);
pGenRec = ^gen_rec;
pSquare = ^Square;
pCastleSet= ^CastleSet;
pBoolean = ^Boolean;
pThreadPriority= ^TThreadPriority;
TMoveEvent =procedure(Sender:TObject; oldSq, newSq: Square) of object;
TCaptureEvent =procedure(Sender:TObject; oldSq, newSq: Square; CapturedPiece: Char) of object;
TOneSquareEvent=procedure(Sender:TObject; square: Square) of object;
TPromotionEvent=procedure(Sender:TObject; oldSq, newSq: Square;var NewPiece: Char) of object;
TMoveFunc =function(oldsq, newsq: Square): Boolean of Object;
TThinkEvent =procedure(Sender: TObject; var oldsq,newsq: Square) of object;
// From Tom:
move_bytes = record
src,dst,promote,bits: Byte;
end;
moverec = record
b: move_bytes;
end;
// an element of the move stack. it's just a move with a
// score, so it can be sorted by the search functions. */
gen_rec = record
m: moverec;
score: Integer;
end;
// an element of the history stack, with the information
// necessary to take a move back. */
hist_rec = record
m: moverec;
capture,castle,ep,fifty: Integer;
end;
// The thinking thread contains mainly code from Tom's Simple Chess Program:
TChessThread = class(TThread)
private
// pcsq stands for piece/square table. It's indexed by the piece's color,
// type, and square. The value of pcsq[LIGHT,KNIGHT,e5] might be 310
// one of the outer squares. //
// instead of just 300 because a knight on e5 is better than one on
pcsq: Array [0..1,0..5,0..63] of Integer;
flip: Array [0..63] of Integer;
pawn_pcsq: Array [0..63] of Integer;
kingside_pawn_pcsq: Array [0..63] of Integer;
queenside_pawn_pcsq: Array [0..63] of Integer;
minor_pcsq: Array [0..63] of Integer;
king_pcsq: Array [0..63] of Integer;
endgame_king_pcsq: Array[0..63] of Integer;
color: Array [0..63] of Integer; // LIGHT, DARK, or EMPTY
piece: Array [0..63] of Integer; // PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING, or EMPTY
side: Integer; // the side to move
xside: Integer; // the side not to move
castle: Integer; // a bitfield with the castle permissions. if 1 is set,
// white can still castle kingside. 2 is white queenside.
// 4 is black kingside. 8 is black queenside.
ep: Integer ; // the en passant square. if white moves e2e4, the en passant
// square is set to e3, because that's where a pawn would move
// in an en passant capture
fifty: Integer; // the number of moves since a capture or pawn move, used
// to handle the fifty-move-draw rule
ply: Integer; // the half-move that we're on
// this is the move stack. gen_dat is basically a list of move lists,
// all stored back to back. gen_begin[x] is where the first move of the
// ply x move list is (in gen_dat). gen_end is right after the last move.
gen_dat: Array [0..MOVE_STACK-1] of gen_rec;
gen_begin: Array [0..63] of Integer;
gen_end: Array [0..63] of Integer;
history: Array [0..63,0..63] of Integer;
// we need an array of hist_rec's so we can take back the
// moves we make
hist_dat: Array [0..63] of hist_rec;
nodes: Integer; // the number of nodes we've searched
// a triangular PV array
pv: Array[0..63,0..63]of moverec;
pv_length: Array [0..63] of Integer;
follow_pv: Boolean;
// Now we have the mailbox array, so called because it looks like a
// mailbox, at least according to Bob Hyatt. This is useful when we
// need to figure out what pieces can go where. Let's say we have a
// rook on square a4 (32) and we want to know if it can move one
// square to the left. We subtract 1, and we get 31 (h5). The rook
// obviously can't move to h5, but we don't know that without doing
// a lot of annoying work. Sooooo, what we do is figure out a4's
// mailbox number, which is 61. Then we subtract 1 from 61 (60) and
// see what mailbox[60] is. In this case, it's -1, so it's out of
// bounds and we can forget it. You can see how mailbox[] is used
// in attack() in board.c.
mailbox: Array [0..119] of Integer;
mailbox64:Array [0..63] of Integer;
// slide, offsets, and offset are basically the vectors that
// pieces can move in. If slide for the piece is FALSE, it can
// only move one square in any one direction. offsets is the
// number of directions it can move in, and offset is an array
// of the actual directions.
slide: Array[0..5] of Boolean;
offsets: Array [0..5] of Integer;
offset: Array[0..5,0..7] of Integer;
// This is the castle_mask array. We can use it to determine
// the castling permissions after a move. What we do is
// logical-AND the castle bits with the castle_mask bits for
// both of the move's squares. Let's say castle is 1, meaning
// that white can still castle kingside. Now we play a move
// where the rook on h1 gets captured. We AND castle with
// castle_mask[63], so we have 1&14, and castle becomes 0 and
// white can't castle kingside anymore.
castle_mask: Array [0..63] of Integer;
// values of the pieces
value: Array [0..5] of Integer;
// the piece letters, for print_board()
piece_char: Array [0..5] of Char;
// the initial board state
init_color: Array [0..63] of Integer;
init_piece: Array [0..63] of Integer;
//---------------------------------------------------------------------
Thinking: Boolean;
WhiteToMove: pBoolean;
ComputerPlaysWhite: pBoolean;
ComputerPlaysBlack: pBoolean;
StopThinkingNow: Boolean;
Position: pChar;
EnPassant: pSquare;
Castling: pCastleSet;
SearchDepth: PInt;
ThinkingPriority: pThreadPriority;
function eval: Integer;
function attack(sq,s: Integer): Boolean;
function ColorOfPiece (sq: Square): Integer;
function in_check(s: Integer): Boolean;
function makemove (m: move_bytes): Boolean;
function quiesce(alpha,beta: Integer): Integer;
function search(alpha,beta,depth: Integer): Integer;
procedure ThinkAboutAMove;
procedure ThinkingFinished;
procedure gen;
procedure gen_caps;
procedure gen_promote(src,dst,bits: Integer);
procedure gen_push(src,dst,bits: Integer);
procedure InitValues;
procedure init_eval;
procedure IntCopy (dest,source: pInt; count: Integer);
procedure PerformMove;
procedure sort(src: Integer);
procedure sort_pv;
procedure takeback;
protected
procedure Execute; override;
public
MoveFunc: TMoveFunc;
EndFunc: TNotifyEvent;
constructor Create;
end;
TChessBrd = class(TGraphicControl)
private
// Class members starting with a _
// represent internal storage variables of properties
timer: TTimer;
stopThinking: Boolean;
temp: MoveInfo;
OldCursor: TCursor;
Now: TChessThread;
GameEnded: Boolean;
FirstTime: Boolean;
MoveList: Array[0..256,0..2]of MoveInfo;
buf: Array[0..MAX_PATH] of Char;
PromoteTo: Char;
PieceIndex: Array[0..2,0..6] of Integer;
Boardx,Boardy, PieceSize, _SizeOfSquare, _CurrentMove: Integer;
ResizeState, _resizable: Boolean;
_ResizeMinSize,_ResizeMaxSize: Integer;
_ComputerPlaysWhite,_ComputerPlaysBlack: Boolean;
_SearchDepth: Integer;
_ThinkingPriority: TThreadPriority;
_legalMove,_check,_mate,_staleMate,_castle,_failed :TMoveEvent;
_paint,_draw,_noMatingMaterial,_threefoldPosition: TNotifyEvent;
_calculate: TThinkEvent;
_capture: TCaptureEvent;
_illegalMove: TOneSquareEvent;
_promotion: TPromotionEvent;
_enPassant: Square;
_position: Array[0..65] of Char;
list: TImageList;
_squareLight, _squareDark, _borderBitmap, _custompieceset, Default: TBitmap;
_lineStyle: TPen;
_coordFont: TFont;
_castlingAllowed: CastleSet;
_displayCoords: CoordSet;
_customEngine: Boolean;
SquareClick1, SquareClick2: Square;
_SizeOfBorder,_animationDelay: Integer;
_whiteOnTop,_whiteToMove,_boardlines, _animateMoves: Boolean;
_squareColorLight, _squareColorDark, _bordercolor: TColor;
_version: String;
procedure TimerCallback (Sender: TObject);
function CheckLegalBishopMove (oldsq, newsq: Square):Boolean;
function CheckLegalKingMove (oldsq, newsq: Square):Boolean;
function CheckLegalKnightMove (oldsq, newsq: Square):Boolean;
function CheckLegalPawnMove (oldsq, newsq: Square):Boolean;
function CheckLegalRookMove (oldsq, newsq: Square):Boolean;
function CheckLegalQueenMove (oldsq, newsq: Square):Boolean;
function BitmapExists (bmp: TBitmap) :Boolean;
function BitmapIsValidPieceSet(bmp: TBitmap) :Boolean;
function CheckForThreefoldPosition: Boolean;
function PieceToInt (piece: Char): Integer;
procedure DoPromotion (sq: Square);
procedure ThinkingComplete(Sender:TObject);
procedure DrawBorder;
procedure DrawBoard;
procedure DrawBoardLines;
procedure DrawPieces;
procedure DrawPiece (sq: Square; piece: Char);
procedure InitializeBitmap;
procedure OrganizeBitmaps;
procedure AnimateHorizontally (x1,x2,y,delay: Integer);
procedure AnimateVertically (y1,y2,x,delay: Integer);
procedure AnimateDiagonally (x1,y1,x2,y2,delay: Integer);
procedure SetNewGame;
//--Boring Write Methods--------------------------------------
function Get_Position: String;
function Get_Thinking: Boolean;
procedure Set_BoardLines (show: Boolean);
procedure Set_BorderBitmap (bmp: TBitmap);
procedure Set_BorderColor (c: TColor);
procedure Set_ComputerPlaysBlack (plays: Boolean);
procedure Set_ComputerPlaysWhite (plays: Boolean);
procedure Set_CoordFont (f: TFont);
procedure Set_CurrentMove (moveno: Integer);
procedure Set_CustomPieceSet (bmp: TBitmap);
procedure Set_CustomEngine (use: Boolean);
procedure Set_DarkSquare(bmp: TBitmap);
procedure Set_DisplayCoords (cset: CoordSet);
procedure Set_EnPassant(sq: Square);
procedure Set_LightSquare(bmp: TBitmap);
procedure Set_LineStyle (pen: TPen);
procedure Set_Position (pos: String);
procedure Set_ResizeMaxSize (size: Integer);
procedure Set_ResizeMinSize (size: Integer);
procedure Set_SearchDepth (depth: Integer);
procedure Set_SizeOfBorder (border: Integer);
procedure Set_SizeOfSquare (size: Integer);
procedure Set_SquareColorDark (c: TColor);
procedure Set_SquareColorLight (c: TColor);
procedure Set_Thinking (thinking: Boolean);
procedure Set_ThinkingPriority (priority: TThreadPriority);
procedure Set_Version (str: String);
procedure Set_WhiteOnTop (wabove: Boolean);
procedure Set_WhiteToMove (wmove: Boolean);
protected
procedure Click; override;
procedure DragCanceled;override;
procedure DragDrop(Source: TObject;X,Y: Integer);override;
procedure DragOver(Source: TObject;X,Y: Integer; State: TDragState;var Accept: Boolean );override;
procedure EndDrag(drop:Boolean);
procedure MouseDown(Button:TMouseButton; Shift:TShiftState;X,Y: Integer); override;
procedure MouseMove(Shift:TShiftState; X,Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X,Y: Integer);override;
procedure Paint; override;
procedure Promotion (Sender: TObject;oldSq,newSq: Square; var NewPiece: Char);
procedure WndProc(var Message: TMessage); override;
public
FirstMove, LastMove: Integer;
FirstTurn, LastTurn: Boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function BlackInCheckAfter(oldsq, newsq: Square): Boolean;
function ColorOfPiece (piece: Char): Integer;
function ColorOfPieceOnSquare (sq: Square): Integer;
function ColorOfSquare (sq: Square): Integer;
function GetMove (moveno: Integer; whiteMoves: Boolean): MoveInfo;
function GotoMove (moveno: Integer; whiteMoves:Boolean): Boolean;
function LegalMoveAvailable: Boolean;
function MouseToSquare (x, y: Integer): Square;
function Move (oldsq, newsq: Square): Boolean;
function MoveBackward: Boolean;
function MoveForward: Boolean;
function MoveIsLegal (oldsq, newsq: Square):Boolean;
function PerformMove (oldsq, newsq: Square): Boolean;
function SetUpPosition (pos: MoveInfo; moveno: Integer; whiteMoves:Boolean): Boolean;
function StringToSquare (str: String): Square;
function WhiteInCheckAfter(oldsq, newsq: Square):Boolean;
function WindowToSquare (x, y: Integer): Square;
function XPos (sq: Square): Integer;
function YPos (sq: Square): Integer;
procedure Animate (oldsq,newsq: Square; delay: Integer);
procedure CancelThinking;
procedure ClearSquare(sq: Square);
procedure DrawChessPiece (canvas: TCanvas; x,y: Integer; piece: Char);
procedure GetMoveList(var list: TStringList);
procedure NewGame;
procedure SquareToCoords (sq: Square; var x,y: Integer);
procedure Think;
procedure UpdateChessBoard (oldpos: String);
published
property AnimateMoves:Boolean read _animateMoves write _animateMoves;
property AnimationDelay:Integer read _animationDelay write _animationDelay;
property BoardLines:Boolean read _boardLines write Set_BoardLines;
property BorderBitmap:TBitmap read _borderBitmap write Set_BorderBitmap;
property BorderColor:TColor read _borderColor write Set_BorderColor;
property CastlingAllowed:CastleSet read _castlingAllowed write _castlingAllowed;
property ComputerPlaysBlack:Boolean read _ComputerPlaysBlack write Set_ComputerPlaysBlack;
property ComputerPlaysWhite:Boolean read _ComputerPlaysWhite write Set_ComputerPlaysWhite;
property Thinking: Boolean read Get_Thinking write Set_Thinking;
property CoordFont:TFont read _CoordFont write Set_CoordFont;
property CurrentMove:Integer read _CurrentMove write Set_CurrentMove;
property CustomPieceSet: TBitmap read _customPieceset write Set_CustomPieceSet;
property DisplayCoords:CoordSet read _displayCoords write Set_DisplayCoords;
property CustomEngine: Boolean read _customEngine write Set_CustomEngine;
property EnPassant:Square read _EnPassant write Set_EnPassant;
property LineStyle:TPen read _lineStyle write Set_LineStyle;
property Position:String read Get_position write Set_Position;
property Resizable:Boolean read _resizable write _resizable;
property ResizeMinSize:Integer read _ResizeMinSize write Set_ResizeMinSize;
property ResizeMaxSize:Integer read _ResizeMaxSize write Set_ResizeMaxSize;
property SearchDepth: Integer read _SearchDepth write set_SearchDepth;
property SizeOfBorder:Integer read _SizeOfBorder write Set_SizeOfBorder;
property SizeOfSquare:Integer read _SizeOfSquare write Set_SizeOfSquare;
property SquareColorDark:TColor read _squareColorDark write Set_SquareColorDark;
property SquareColorLight:TColor read _squareColorLight write Set_SquareColorLight;
property SquareDark:TBitmap read _SquareDark write Set_DarkSquare;
property SquareLight:TBitmap read _SquareLight write Set_LightSquare;
property WhiteOnTop:Boolean read _whiteOnTop write Set_WhiteOnTop;
property WhiteToMove:Boolean read _whiteToMove write Set_WhiteToMove;
property ThinkingPriority: TThreadPriority read _ThinkingPriority write set_ThinkingPriority;
property Version: String read _version write Set_Version;
property DragCursor;
property DragMode;
property Enabled;
property Visible;
property OnCapture: TCaptureEvent read _capture write _capture;
property OnCastle: TMoveEvent read _castle write _castle;
property OnCheck: TMoveEvent read _check write _check;
property OnDraw: TNotifyEvent read _draw write _draw;
property OnIllegalMove: TOneSquareEvent read _illegalmove write _illegalmove;
property OnLegalMove: TMoveEvent read _legalmove write _legalmove;
property OnMate: TMoveEvent read _mate write _mate;
property OnNoMatingMaterial: TNotifyEvent read _noMatingMaterial write _noMatingMaterial;
property OnPaint: TNotifyEvent read _paint write _paint;
property OnPromotion: TPromotionEvent read _promotion write _promotion;
property OnStaleMate: TMoveEvent read _stalemate write _stalemate;
property OnCalculateMove: TThinkEvent read _calculate write _calculate;
property OnCalculationFailed: TMoveEvent read _failed write _failed;
property OnThreefoldPosition: TNotifyEvent read _threefoldposition write _threefoldposition;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
ChessBrdError = class(Exception);
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Chess', [TChessBrd]);
end;
constructor TChessBrd.Create(AOwner: TComponent);
var
p,q: pInt;
begin
inherited Create(AOwner);
list:=TImageList.CreateSize(40,40);
Default:=TBitmap.Create;
_lineStyle :=TPen.Create;
_coordfont :=TFont.Create;
_customPieceSet:=TBitmap.Create;
_SquareLight :=TBitmap.Create;
_SquareDark :=TBitmap.Create;
_borderBitmap :=TBitmap.Create;
Timer:=TTimer.Create(Self);
_ResizeMinSize:=100;
_ResizeMaxSize:=1000;
_animateMoves:=TRUE;
_animationDelay:=0;
FirstMove:=1;
LastMove:=1;
LastTurn:=TRUE;
PromoteTo:='q';
InitializeBitmap;
OrganizeBitmaps;
_coordfont.Color:=clWhite;
_coordfont.Name:='Arial';
_coordfont.Size:=7;
_coordfont.Pitch:=fpDefault;
_SizeOfSquare:=40;
_SizeOfBorder:=24;
_bordercolor:=clBlack;
_squareColorDark:=clGray;
_squareColorLight:=clSilver;
Boardx:=_SizeOfBorder;
Boardy:=_SizeOfBorder;
_ComputerPlaysWhite:=FALSE;
_ComputerPlaysBlack:=FALSE;
_SearchDepth:=1;
_ThinkingPriority:=tpNormal;
p:=@Width;
p^:=8*_SizeOfSquare+2*_SizeOfBorder;
q:=@Height;
q^:=Width;
SetNewGame;
if ((csDesigning in ComponentState)=FALSE) then
begin
Now:=TChessThread.Create;
Now.Castling:=@_CastlingAllowed;
Now.EnPassant:=@_EnPassant;
Now.MoveFunc:=PerformMove;
Now.EndFunc:=ThinkingComplete;
Now.Position:=@_position;
Now.ComputerPlaysWhite:=@_ComputerPlaysWhite;
Now.ComputerPlaysBlack:=@_ComputerPlaysBlack;
Now.SearchDepth:=@_SearchDepth;
Now.ThinkingPriority:=@_ThinkingPriority;
Now.WhiteToMove:=@_WhiteToMove;
end;
end;
destructor TChessBrd.destroy;
begin
if(_customEngine=FALSE)and(Now<>nil) then
begin
Now.Suspend;
Now.Free;
end;
inherited destroy;
list.Destroy;
_lineStyle.Destroy;
_coordfont.Destroy;
_SquareLight.Destroy;
_SquareDark.Destroy;
_borderBitmap.Destroy;
_customPieceSet.Destroy;
Default.Destroy;
end;
procedure TChessBrd.TimerCallback(Sender: TObject);
var
msg: TMessage;
begin
WndProc(msg);
end;
procedure TChessBrd.MouseDown(Button: TMouseButton; Shift: TShiftState;X,Y: Integer);
var
sq: Square;
const
space: Char=' ';
begin
inherited MouseDown(Button,Shift,X,Y);
sq:=WindowToSquare(X,Y);
if (sq>=A8)AND(sq<=H1)AND
(_position[Integer(sq)]<>' ') then
begin
SquareClick1:=sq;
BeginDrag(FALSE);
end;
end;
procedure TChessBrd.ThinkingComplete(Sender: TObject);
begin
Now.Thinking:=FALSE;
Now.Suspend;
if (Now.StopThinkingNow=FALSE) then Think;
end;
procedure TChessBrd.WndProc (var Message: TMessage);
begin
inherited WndProc (Message);
if (stopThinking=FALSE)and(_customEngine)and(((_ComputerPlaysBlack)and(_WhiteToMove=FALSE))or
((_ComputerPlaysWhite)and(_WhiteToMove=TRUE)))and(csDesigning in ComponentState=FALSE)and
(csLoading in ComponentState=FALSE) then
Think;
end;
procedure TChessBrd.Paint;
var
size: Integer;
begin
if ((csLoading in ComponentState)=TRUE) then Exit;
if ((csDesigning in ComponentState)=FALSE)and(@_paint<>nil)
then _paint(Self);
if (FirstTime=FALSE) then
begin
OrganizeBitmaps;
end;
size:=(Width+Height) shr 1;
_SizeOfSquare:=(size-2*_SizeOfBorder) shr 3;
Width:=8*_SizeOfSquare+2*_SizeOfBorder;
Height:=Width;
DrawBorder;
DrawBoard;
DrawPieces;
if (FirstTime=FALSE) then
begin
FirstTime:=TRUE;
Think;
timer.Interval:=500;
timer.OnTimer:=TimerCallBack;
end;
end;
// Displays an move animation
// It's up to the to user ensure there is a piece on oldSq
procedure TChessBrd.Animate (oldSq,newSq: Square; delay: Integer);
var
x1,y1,x2,y2: Integer;
begin
if (list.Dragging=FALSE)then
begin
list.SetDragImage(PieceToInt(_position[Integer(oldSq)]), 0,0);
SquareToCoords(oldSq,x1,y1);
SquareToCoords(newSq,x2,y2);
x1:=x1+Left;
y1:=y1+Top;
x2:=x2+Left;
y2:=y2+Top;
list.DragLock (Parent.Handle,x1,y1);
list.ShowDragImage;
list.BeginDrag (Parent.Handle,0,0);
// Knights don't go diagonally
if (_position[Integer(oldSq)]<>'n')and(_position[Integer(oldSq)]<>'N') then
AnimateDiagonally(x1,y1,x2,y2,delay)
else
begin
AnimateHorizontally(x1,x2,y1,delay);
AnimateVertically(y1,y2,x2,delay);
end;
end;
list.HideDragImage;
list.EndDrag;
list.DragUnlock;
end;
procedure TChessBrd.AnimateHorizontally(x1,x2,y,delay: Integer);
var
x,v: Integer;
begin
if (x2>x1) then
for x:=x1 to x2 do
begin
v:=GetTickCount;
list.DragMove(x,y);
list.ShowDragImage;
if (delay>0) then
repeat
until ((GetTickCount-v)>delay);
end
else
for x:=x1 downto x2 do
begin
v:=GetTickCount;
list.DragMove(x,y);
list.ShowDragImage;
if (delay>0) then
repeat
until ((GetTickCount-v)>delay);
end;
end;
procedure TChessBrd.AnimateVertically(y1,y2,x,delay: Integer);
var
y,v: Integer;
begin
if (y2>y1) then
for y:=y1 to y2 do
begin
v:=GetTickCount;
list.DragMove(x,y);
list.ShowDragImage;
if (delay>0) then
repeat
until ((GetTickCount-v)>delay);
end
else
for y:=y1 downto y2 do
begin
v:=GetTickCount;
list.DragMove(x,y);
list.ShowDragImage;
if (delay>0) then
repeat
until ((GetTickCount-v)>delay);
end;
end;
procedure TChessBrd.AnimateDiagonally(x1,y1,x2,y2,delay: Integer);
var
y,v: Integer;
x,step: Real;
begin
if (x1-x2=0)and(y2-y1=0) then Exit;
if(abs(y2-y1)>abs(x2-x1)) then
begin
if (y2>y1) then
begin
step:=(x2-x1)/(y2-y1);
x:=x1;
for y:=y1 to y2 do
begin
v:=GetTickCount;
list.DragMove(Trunc(x),y);
list.ShowDragImage;
if (delay>0) then
repeat
until ((GetTickCount-v)>delay);
x:=x+step;
end;
end
else
begin
step:=(x2-x1)/(y1-y2);
x:=x1;
for y:=y1 downto y2 do
begin
v:=GetTickCount;
list.DragMove(Trunc(x),y);
list.ShowDragImage;
if (delay>0) then
repeat
until ((GetTickCount-v)>delay);
x:=x+step;
end;
end
end
else
begin
if (x2>x1) then
begin
step:=(y2-y1)/(x2-x1);
x:=y1;
for y:=x1 to x2 do
begin
v:=GetTickCount;
list.DragMove(y,Trunc(x));
list.ShowDragImage;
if (delay>0) then
repeat
until ((GetTickCount-v)>delay);
x:=x+step;
end;
end
else
begin
step:=(y2-y1)/(x1-x2);
x:=y1;
for y:=x1 downto x2 do
begin
v:=GetTickCount;
list.DragMove(y,Trunc(x));
list.ShowDragImage;
if (delay>0) then
repeat
until ((GetTickCount-v)>delay);
x:=x+step;
end;
end
end;
end;
procedure TChessBrd.DragOver(Source:TObject;
X,Y: Integer; State: TDragState; var Accept: Boolean );
var
sq: Square;
mid: Integer;
begin
inherited DragOver(Source, X, Y, State, Accept);
sq:=WindowToSquare(X,Y);
mid:=_SizeOfSquare shr 1;
if (list.Dragging=FALSE)then
begin
ClearSquare(SquareClick1);
DrawBoardLines;
list.SetDragImage(PieceToInt(_position[Integer(SquareClick1)]), 0,0);
list.DragLock (Parent.Handle,X+Left-mid,Y+Top-mid);
list.BeginDrag (Parent.Handle,0,0);
end;
list.DragMove(X+Left-mid,Y+Top-mid);
if (Source=Self)then
begin
if (Thinking=FALSE)then
begin
if MoveIsLegal(SquareClick1,sq)or(SquareClick1=sq) then
begin
Accept:=TRUE;
end;
end;
end;
end;
procedure TChessBrd.DragDrop(Source:TObject ;X,Y: Integer);
begin
inherited DragDrop(Source,X,Y);
if (list.Dragging)then
begin
list.HideDragImage;
list.EndDrag;
list.DragUnlock;
end;
SquareClick2:=WindowToSquare(X,Y);
if (SquareClick1<>SquareClick2)then
Move (SquareClick1,SquareClick2)
else DrawPiece (SquareClick1,_position[Integer(SquareClick1)]);
end;
procedure TChessBrd.DragCanceled;
begin
list.HideDragImage;
list.EndDrag;
list.DragUnlock;
DrawPiece (SquareClick1,_position[Integer(SquareClick1)]);
if (@_illegalmove<>nil) then _illegalmove(Self, SquareClick1);
end;
procedure TChessBrd.MouseMove(Shift: TShiftState;X,Y: Integer);
var
w: Integer;
begin
inherited MouseMove(Shift,X,Y);
if (Cursor<>crSizeNWSE)and(Cursor<>crSizeWE) and (Cursor<>crSizeNS)then
OldCursor:=Cursor;
if (_resizable)and(X>=(Width-10))and(X<=Width)and(Y>=(Height-10))
and (Y<=Height) then
begin
Cursor:=crSizeNWSE;
if (ssLeft in Shift)then
ResizeState:=TRUE;
end
else if (_resizable) and(ResizeState=FALSE)then
Cursor:=OldCursor;
if (_resizable)and(ResizeState) then
begin
if (X>Y) then w:=X
else w:=Y;
if (w<_ResizeMinSize) then w:=_ResizeMinSize;
if (w>_ResizeMaxSize) then w:=_ResizeMaxSize;
if (w<>Width) then
begin
Width:=w;
end;
end;
end;
procedure TChessBrd.MouseUp(Button:TMouseButton;Shift:TShiftState;
X,Y: Integer);
begin
inherited MouseUp(Button,Shift,X,Y);
if (ResizeState) then ResizeState:=FALSE;
end;
procedure TChessBrd.Click;
begin
inherited Click();
end;
procedure TChessBrd.EndDrag(drop: Boolean);
begin
inherited EndDrag(drop);
end;
procedure TChessBrd.Promotion (Sender:TObject; oldSq,newSq: Square;
var NewPiece: Char);
var
i: String;
r: Integer;
begin
i:='NBRQnbrq';
for r:=1 to 8 do
begin
if (NewPiece=i[r])then
Break;
if (r=8) then NewPiece:='q';
end;
PromoteTo:=NewPiece;
end;
procedure TChessBrd.DoPromotion (sq: Square);
begin
if YPos(sq)=8 then
begin
_position[Integer(sq)]:=UpCase(PromoteTo);
end
else if (YPos(sq)=1) then
begin
_position[Integer(sq)]:=Char(Integer(UpCase(PromoteTo))+32);
end;
ClearSquare(sq);
DrawPiece(sq,_position[Integer(sq)]);
DrawBoardLines;
end;
//-----------------------------------------------------------------------
// Boring Write Methods
//-----------------------------------------------------------------------
function TChessBrd.Get_Position: String;
begin
Result:=StrPas(@_position[1]);
end;
procedure TChessBrd.Set_ComputerPlaysBlack(plays: Boolean);
begin
CancelThinking;
_ComputerPlaysBlack:=plays;
Think;
end;
procedure TChessBrd.Set_ComputerPlaysWhite(plays: Boolean);
begin
CancelThinking;
_ComputerPlaysWhite:=plays;