-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCheckerBoard.c
6014 lines (5138 loc) · 170 KB
/
CheckerBoard.c
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
// checkerboard.c
//
// version 1.0 was written by Martin Fierz on
// 15th february 2000
// (c) 2000-2011 by Martin Fierz - all rights reserved.
// contributions by Ed Gilbert are gratefully acknowledged
//
// checkerboard is a graphical front-end for checkers engines. it checks
// user moves for correctness. you can save and load games. you can change
// the board and piece colors. you can change the window size.
//
// interfacing to checkers engines:
// if you want your checkers engine to use checkerboard as a front-end,
// you must compile your engine as a dll, and provide the following 2
// functions:
// int WINAPI getmove(Board8x8 board, int color, double maxtime, char str[1024], int *playnow, int info, int moreinfo, CBmove *move);
// int WINAPI enginecommand(const char *command, char reply[1024]);
// TODO: bug report: if you hit takeback while CB is animating a move, you get an undefined state
/******************************************************************************/
// CB uses multithreading, up to 4 threads:
// -> main thread for the window
// -> checkers engine runs in 'Thread'
// -> animation runs in 'AniThread'
// -> game analysis & engine match are driven by 'AutoThread'
#define STRICT
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#include <windows.h>
#include <windowsx.h>
#include <wininet.h>
#include <commctrl.h>
#include <mmsystem.h>
#include <stdio.h>
#include <shellapi.h>
#include <shlwapi.h>
#include <commdlg.h>
#include <time.h>
#include <io.h>
#include <intrin.h>
#include <vector>
#include <algorithm>
#include "standardheader.h"
#include "cb_interface.h"
#include "CBstructs.h"
#include "CBconsts.h"
#include "PDNparser.h"
#include "dialogs.h"
#include "pdnfind.h"
#include "checkerboard.h"
#include "bmp.h"
#include "coordinates.h"
#include "bitboard.h"
#include "utility.h"
#include "fen.h"
#include "resource.h"
#include "saveashtml.h"
#include "graphics.h"
#include "registry.h"
#include "app_instance.h"
#ifdef _WIN64
#pragma message("_WIN64 is defined.")
#endif
//---------------------------------------------------------------------
// globals - should be identified in code by g_varname but aren't all...
PDNgame cbgame; /* The current game. */
// all checkerboard options are collected in CBoptions; like this, they can be saved
// as one struct in the registry, instead of using lots of commands.
CBoptions cboptions;
int g_app_instance; /* 0, 1, 2, ... */
char g_app_instance_suffix[10]; /* "", "[1]", "[2]", ... */
DWORD g_SearchThreadId, g_AniThreadId, AutoThreadId;
HANDLE hSearchThread, hAniThread, hAutoThread;
int enginethreadpriority = THREAD_PRIORITY_NORMAL; /* default priority setting*/
int usersetpriority = THREAD_PRIORITY_NORMAL; /* default priority setting*/
HICON hIcon; /* CB icon for the window */
TBBUTTON tbButtons[NUMBUTTONS]; /* for the toolbar */
/* these globals are used to synchronize threads */
int abortcalculation; // used to tell the SearchThreadFunc that the calculation has been aborted
static BOOL enginebusy; /* true while engine thread is busy */
static BOOL animationbusy; /* true while animation thread is busy */
static BOOL enginestarting; // true when a play command is issued to the engine but engine has not started yet
BOOL gameover; /* true when autoplay or engine match game is finished */
BOOL startmatch = TRUE; /* startmatch is only true before engine match was started */
BOOL newposition = TRUE; /* is true when position has changed. used in analysis mode to
restart search and then reset */
BOOL startengine; /* is true if engine is expected to start */
int game_result; /* CB_DRAW, CB_WIN, CB_LOSS, or CB_UNKNOWN. */
time_ctrl_t time_ctrl; /* Clock control. */
int toolbarheight = 30;
int clockheight; /* 0 or CLOCKHEIGHT when clock is visible. */
int statusbarheight = 20;
int menuheight = 16;
int titlebarheight = 12;
int offset = 40;
int upperoffset = 20;
char szWinName[] = "CheckerBoard"; /* name of window class */
Board8x8 cbboard8; /* the board being displayed in the GUI*/
int cbcolor = CB_BLACK; /* the side to move next in the GUI */
bool setup_mode;
static int addcomment;
int testset_number;
int playnow; /* playnow is passed to the checkers engines, it is set to nonzero if the user chooses 'play' */
bool reset_move_history; /* send option to engine to reset its list of game moves. */
int gameindex; /* game to load/replace from/in a database */
/* dll globals */
/* CB uses function pointers to access the dll.
enginename, engineabout, engineoptions, enginehelp, getmove point to the currently used functions
...1 and ...2 are the pointers to dll1 and dll2 as read from engines.ini. */
/* library instances for primary, secondary and analysis engines */
HINSTANCE hinstLib, hinstLib1, hinstLib2;
/* function pointers for the engine functions */
CB_GETMOVE getmove, getmove1, getmove2;
CB_ENGINECOMMAND enginecommand1, enginecommand2;
// multi-version support
CB_ISLEGAL islegal, islegal1, islegal2;
CB_GETSTRING enginename1, enginename2;
CB_GETGAMETYPE CBgametype; // built in gametype and islegal functions
// instance and window handles
HINSTANCE g_hInst; //instance of checkerboard
HWND hwnd; // main window
HWND hStatusWnd; // status window
static HWND tbwnd; // toolbar window
std::vector<gamepreview> game_previews; // preview info displayed in game select dialog.
// statusbar_txt holds the output string shown in the status bar - it is updated by WM_TIMER messages
char statusbar_txt[1024];
char playername[MAXNAME]; // name of the player we are searching games of
char eventname[MAXNAME]; // event we're searching for
char datename[MAXNAME]; // date we're searching for
char commentname[MAXNAME]; // comment we're searching for
int searchwithposition; // search with position?
HMENU hmenu; // menu handle
double xmetric, ymetric; // gives the size of the board8: one square is xmetric*ymetric
Squarelist clicks; // user clicks on the board
char reply[ENGINECOMMAND_REPLY_SIZE]; // holds reply of engine to command requests
char CBdirectory[MAX_PATH]; // holds the directory from where CB is started:
char CBdocuments[MAX_PATH]; // CheckerBoard directory under My Documents
char pdn_filename[MAX_PATH]; // current PDN database
char userbookname[MAX_PATH]; // current userbook
CBmove cbmove;
char savegame_filename[MAX_PATH];
emstats_t emstats; // engine match stats and state
std::vector<BALLOT_INFO> user_ballots;
bool two_player_mode; // true if in 2-player mode
int book_state; // engine book state (0/1/2/3)
int currentengine = 1; // 1=primary, 2=secondary
int maxmovecount = 300; // engine match limit; use 200 if early_game_adjudication is enabled.
bool has_getmovelist; // true if current engine has enginecommand "get movelist"
// keep a small user book
userbookentry userbook[MAXUSERBOOK];
int userbooknum;
int userbookcur;
static CHOOSECOLOR ccs;
// reindex tells whether we have to reindex a database when searching.
// reindex is set to 1 if a game is saved, a game is replaced, or the
// database changed. and initialized to 1.
int reindex = 1;
int re_search_ok;
char piecesetname[MAXPIECESET][256];
int maxpieceset;
CRITICAL_SECTION ani_criticalsection, engine_criticalsection;
int handletooltiprequest(LPTOOLTIPTEXT TTtext);
void reset_game(PDNgame &game);
void forward_to_game_end(void);
// checkerboard goes finite-state: it can be in one of the modes above.
// normal: after the user enters a move, checkerboard starts to calculate
// with engine.
// autoplay: checkerboard plays engine-engine
// enginematch: checkerboard plays engine-engine2
// analyzegame: checkerboard moves through a game and comments on every move
// entergame: checkerboard does nothing while the user enters a game
// observegame: checkerboard calculates while the user enters a game
enum state {
NORMAL,
AUTOPLAY,
ENGINEMATCH,
ENGINEGAME,
ANALYZEGAME,
OBSERVEGAME,
ENTERGAME,
BOOKVIEW,
BOOKADD,
RUNTESTSET,
ANALYZEPDN
} CBstate = NORMAL;
void start_animation_thread(void)
{
static HANDLE animation_lock_handle;
static HANDLE animation_thread_handle;
/* Use a mutex to prevent multiple threads from simultaneously starting the thread. */
if (!animation_lock_handle)
animation_lock_handle = CreateMutex(NULL, FALSE, NULL);
WaitForSingleObject(animation_lock_handle, INFINITE);
if (animation_thread_handle != NULL)
CloseHandle(animation_thread_handle);
setanimationbusy(TRUE);
animation_thread_handle = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)AnimationThreadFunc,
hwnd,
0,
&g_AniThreadId);
ReleaseMutex(animation_lock_handle);
}
int WINAPI WinMain(HINSTANCE hThisInst, HINSTANCE hPrevInst, LPSTR lpszArgs, int nWinMode)
{
// the main function which runs all the time, processing messages and sending them on
// to windowfunc() which is the heart of CB
MSG msg;
WNDCLASS wcl;
HACCEL hAccel;
INITCOMMONCONTROLSEX iccex;
RECT rect;
// Define a window class.
wcl.lpszMenuName = NULL;
wcl.hInstance = hThisInst; // handle to this instance
wcl.lpszClassName = szWinName; // window class name
wcl.lpfnWndProc = WindowFunc; // window function
wcl.style = 0; // default style
wcl.hIcon = LoadIcon(hThisInst, "icon1"); // load CB icon
wcl.hCursor = LoadCursor(NULL, IDC_ARROW); // cursor style
wcl.cbClsExtra = 0; // no extra
wcl.cbWndExtra = 0; // information needed
wcl.hbrBackground = (HBRUSH) GetSysColorBrush(GetSysColor(COLOR_MENU));
// register the window class
if (!RegisterClass(&wcl))
return 0;
// create the window
hwnd = CreateWindow(szWinName, // name of window class
"CheckerBoard:", // title
WS_OVERLAPPEDWINDOW ^ WS_MAXIMIZEBOX, // window style - normal
CW_USEDEFAULT, // x coordinate - let windows decide
CW_USEDEFAULT, // y coordinate - let windows decide
480, // width
560, // height
HWND_DESKTOP, // no parent window
NULL, // no menu
hThisInst, // handle of this instance of the program
NULL // no additional arguments
);
// load settings from the registry
createcheckerboard(hwnd);
// display the window
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
// set database filename in case of shell-doubleclick on a *.pdn file
sprintf(savegame_filename, lpszArgs);
// initialize common controls - toolbar and status bar need this
iccex.dwSize = sizeof(INITCOMMONCONTROLSEX);
iccex.dwICC = ICC_COOL_CLASSES | ICC_BAR_CLASSES;
InitCommonControlsEx(&iccex);
// save the instance in a global variable - the dialog boxes in dialogs.c need this
g_hInst = hThisInst;
// load the keyboard accelerator table
hAccel = LoadAccelerators(hThisInst, "MENUENGLISH");
// Initialize the Toolbar
tbwnd = CreateAToolBar(hwnd);
// get toolbar height
GetWindowRect(tbwnd, &rect);
toolbarheight = rect.bottom - rect.top;
clockheight = cboptions.use_incremental_time ? CLOCKHEIGHT : 0;
// initialize status bar
InitStatus(hwnd);
// get status bar height
GetWindowRect(hStatusWnd, &rect);
statusbarheight = rect.bottom - rect.top;
// get menu and title bar height:
menuheight = GetSystemMetrics(SM_CYMENU);
titlebarheight = GetSystemMetrics(SM_CXSIZE);
// get offsets before the board is printed for the first time
offset = toolbarheight + statusbarheight + clockheight - 1;
upperoffset = toolbarheight + clockheight - 1;
setoffsets(offset, upperoffset);
// start a timer @ 10Hz: every time this timer goes off, handletimer() is called
// this updates the status bar and the toolbar
SetTimer(hwnd, 1, 100, NULL);
// create the message loop
while (GetMessage(&msg, NULL, 0, 0)) {
if (!TranslateAccelerator(hwnd, hAccel, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
bool fixed_time_needed_msg()
{
if (cboptions.use_incremental_time) {
MessageBox(hwnd, "Change to a fixed time/move.", "Error", MB_OK);
return(true);
}
return(false);
}
void reset_game_clocks()
{
if (cboptions.use_incremental_time) {
time_ctrl.clock_paused = true;
time_ctrl.black_time_remaining = cboptions.initial_time + cboptions.time_increment;
time_ctrl.white_time_remaining = cboptions.initial_time + cboptions.time_increment;
time_ctrl.starttime = clock();
}
else {
time_ctrl.black_time_remaining = 0;
time_ctrl.white_time_remaining = 0;
}
}
void start_clock()
{
time_ctrl.clock_paused = false;
time_ctrl.starttime = clock();
}
void stop_clock()
{
if (cboptions.use_incremental_time && time_ctrl.clock_paused == false)
time_ctrl.clock_paused = true;
}
/*
* Get the instantaneous values of time left of black and white clocks.
* Add the value spent on thinking for the current move to
* the clock value that was last updated at the start of its turn.
*/
void get_game_clocks(double *black_clock, double *white_clock)
{
double newtime;
if (time_ctrl.clock_paused)
newtime = 0;
else
newtime = (clock() - time_ctrl.starttime) / (double)CLOCKS_PER_SEC;
if (cbcolor == CB_BLACK) {
*black_clock = time_ctrl.black_time_remaining - newtime;
*white_clock = time_ctrl.white_time_remaining;
}
else {
*black_clock = time_ctrl.black_time_remaining;
*white_clock = time_ctrl.white_time_remaining - newtime;
}
}
/*
* Decide if the move described by moveindex is a first player or second player move.
* If the game has a normal start position, even moves are first player, odd moves are second player.
* If the game has a FEN setup, see if the start color is the same as the gametype's start color.
* If the same, then even moves are first player, odd moves are second player.
* If not the same, then odd moves are first player, even moves are second player.
*/
bool is_second_player(PDNgame &game, int moveindex)
{
int startcolor;
if (game.FEN[0] == 0) {
if (moveindex & 1)
return(true);
else
return(false);
}
startcolor = get_startcolor(game.gametype);
if (game.FEN[0] == 'B' && startcolor == CB_BLACK || game.FEN[0] == 'W' && startcolor == CB_WHITE) {
if (moveindex & 1)
return(true);
else
return(false);
}
else {
if (moveindex & 1)
return(false);
else
return(true);
}
}
int moveindex2movenum(PDNgame &game, int moveindex)
{
if (game.FEN[0] == 0)
return(1 + moveindex / 2);
int startcolor = get_startcolor(game.gametype);
if (game.FEN[0] == 'B' && startcolor == CB_BLACK || game.FEN[0] == 'W' && startcolor == CB_WHITE)
return(1 + moveindex / 2);
else
return(1 + (moveindex + 1) / 2);
}
/* Transition to or from setup mode. */
void set_setup_mode(bool state)
{
if (state) {
// entering setup mode
PostMessage(hwnd, WM_COMMAND, ABORTENGINE, 0);
CheckMenuItem(hmenu, SETUPMODE, MF_CHECKED);
sprintf(statusbar_txt, "Setup mode...");
}
else {
// leaving setup mode;
CheckMenuItem(hmenu, SETUPMODE, MF_UNCHECKED);
reset_move_history = true;
clicks.clear();
sprintf(statusbar_txt, "Setup done");
// get FEN string
reset_game(cbgame);
board8toFEN(cbboard8, cbgame.FEN, cbcolor, cbgame.gametype);
}
setup_mode = state;
}
LRESULT CALLBACK WindowFunc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
// this is the main function of checkerboard. it receives messages from winmain(), and
// then acts appropriately
FILE *fp;
LPRECT lprec;
int x, y;
char str2[256], Lstr[256];
char str1024[1024];
char *gamestring;
static enum state laststate;
static int oldengine;
RECT windowrect;
RECT WinDim;
static int cxClient, cyClient;
MENUBARINFO mbi;
HINSTANCE hinst;
switch (message) {
case WM_CREATE:
InitializeCriticalSection(&ani_criticalsection);
InitializeCriticalSection(&engine_criticalsection);
PostMessage(hwnd, WM_COMMAND, LOADENGINES, 0);
break;
case WM_ACTIVATE:
InvalidateRect(hwnd, NULL, true);
break;
case WM_NOTIFY:
// respond to tooltip request //
// lParam contains (LPTOOLTIPTEXT) - send it on to handletooltiprequest function
handletooltiprequest((LPTOOLTIPTEXT) lParam);
break;
case WM_DROPFILES:
DragQueryFile((HDROP) wParam, 0, pdn_filename, sizeof(pdn_filename));
DragFinish((HDROP) wParam);
PostMessage(hwnd, WM_COMMAND, GAMELOAD, 0);
break;
case WM_TIMER:
// timer goes off, telling us to update status bar, toolbar
// icons. handletimer does this, only if it's necessary.
handletimer();
break;
case WM_RBUTTONDOWN:
x = (int)(LOWORD(lParam) / xmetric);
y = (int)(8 - (HIWORD(lParam) - toolbarheight - clockheight) / ymetric);
handle_rbuttondown(x, y);
break;
case WM_LBUTTONDOWN:
x = (int)(LOWORD(lParam) / xmetric);
y = (int)(8 - (HIWORD(lParam) - toolbarheight - clockheight) / ymetric);
handle_lbuttondown(x, y);
break;
case WM_PAINT: // repaint window
updategraphics(hwnd);
break;
case WM_SIZING: // keep window quadratic
lprec = (LPRECT) lParam;
mbi.cbSize = sizeof(MENUBARINFO);
GetMenuBarInfo(hwnd, OBJID_MENU, 0, &mbi);
menuheight = mbi.rcBar.bottom - mbi.rcBar.top;
offset = toolbarheight + statusbarheight + clockheight - 1;
upperoffset = toolbarheight + clockheight - 1;
setoffsets(offset, upperoffset);
cxClient = lprec->right - lprec->left;
cxClient -= cxClient % 8;
cxClient += 2 * (GetSystemMetrics(SM_CXSIZEFRAME) - 4);
cyClient = cxClient;
lprec->right = lprec->left + cxClient;
lprec->bottom = lprec->top + cyClient + offset + menuheight + titlebarheight + 2; //+ cboptions.addoffset;
break;
case WM_SIZE:
// window size has changed
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
// check menu height
mbi.cbSize = sizeof(MENUBARINFO);
GetMenuBarInfo(hwnd, OBJID_MENU, 0, &mbi);
menuheight = mbi.rcBar.bottom - mbi.rcBar.top;
offset = toolbarheight + statusbarheight + clockheight - 1;
upperoffset = toolbarheight + clockheight - 1;
setoffsets(offset, upperoffset);
// get window size, set xmetric and ymetric which CB needs to know where user clicks
GetClientRect(hwnd, &WinDim);
xmetric = WinDim.right / 8.0;
ymetric = (WinDim.bottom - offset) / 8.0;
// get error:
GetWindowRect(hwnd, &WinDim);
// make window quadratic
if ((xmetric - ymetric) * 8 != 0) {
MoveWindow(hwnd,
WinDim.left,
WinDim.top,
WinDim.right - WinDim.left,
WinDim.bottom - WinDim.top + (int)((xmetric - ymetric) * 8),
1);
}
// update stretched stones etc
resizegraphics(hwnd);
updateboardgraphics(hwnd);
SendMessage(hStatusWnd, WM_SIZE, wParam, lParam);
SendMessage(tbwnd, WM_SIZE, wParam, lParam);
break;
case WM_COMMAND:
// the following case structure handles user command (and also internal commands
// that CB may generate itself
switch (LOWORD(wParam)) {
case LOADENGINES:
hSearchThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) initengines, (HWND) 0, 0, &g_SearchThreadId);
break;
case GAMENEW:
PostMessage(hwnd, WM_COMMAND, ABORTENGINE, 0);
newgame();
break;
case GAMEANALYZE:
if (CBstate == BOOKVIEW || CBstate == BOOKADD)
break;
if (fixed_time_needed_msg())
break;
changeCBstate(ANALYZEGAME);
startmatch = TRUE;
// the rest is taken care of in the AutoThreadFunc section
break;
case GAMEANALYZEPDN:
if (CBstate == BOOKVIEW || CBstate == BOOKADD)
break;
if (fixed_time_needed_msg())
break;
changeCBstate(ANALYZEPDN);
startmatch = TRUE;
// the rest is taken care of in the AutoThreadFunc section
break;
case GAME3MOVE:
PostMessage(hwnd, WM_COMMAND, ABORTENGINE, 0);
if (cboptions.op_crossboard || cboptions.op_barred || cboptions.op_mailplay) {
int opening_index = getopening(&cboptions);
PostMessage(hwnd, WM_COMMAND, START3MOVE, opening_index);
}
else
MessageBox(hwnd, "nothing selected in the 3-move deck!", "Error", MB_OK);
break;
case START3MOVE:
start3move(LOWORD(lParam));
break;
case GAMEREPLACE:
// replace a game in the pdn database
// assumption: you have loaded a game, so now "pdn_filename" holds the db filename
// and gameindex is the index of the game in the file
handlegamereplace(gameindex, pdn_filename);
break;
case GAMESAVE:
// show save game dialog. if OK, call 'dosave' to do the work
SetCurrentDirectory(cboptions.userdirectory);
if (DialogBox(g_hInst, "IDD_SAVEGAME", hwnd, (DLGPROC) DialogFuncSavegame)) {
if (getfilename(savegame_filename, OF_SAVEGAME)) {
SendMessage(hwnd, WM_COMMAND, DOSAVE, 0);
}
}
SetCurrentDirectory(CBdirectory);
break;
case GAMESAVEASHTML:
// show save game dialog. if OK is selected, call 'savehtml' to do the work
if (DialogBox(g_hInst, "IDD_SAVEGAME", hwnd, (DLGPROC) DialogFuncSavegame)) {
if (getfilename(savegame_filename, OF_SAVEASHTML)) {
saveashtml(savegame_filename, &cbgame);
sprintf(statusbar_txt, "game saved as HTML!");
}
}
break;
case DOSAVE:
// saves the game stored in cbgame
fp = fopen(savegame_filename, "at+");
// file with savegame_filename opened - we append to that file
// filename was set by save game
if (fp != NULL) {
std::string gamepdn;
PDNgametoPDNstring(cbgame, gamepdn, "\n");
fprintf(fp, "\n%s", gamepdn.c_str());
fclose(fp);
}
// set reindex flag
reindex = 1;
break;
case GAMEDATABASE:
// set working database
sprintf(pdn_filename, "%s", cboptions.userdirectory);
getfilename(pdn_filename, OF_LOADGAME);
// set reindex flag
reindex = 1;
break;
case SELECTUSERBOOK:
// set user book.
sprintf(userbookname, "%s", CBdocuments);
if (getfilename(userbookname, OF_USERBOOK)) {
// load user book
fp = fopen(userbookname, "rb");
if (fp != NULL) {
userbooknum = (int)fread(userbook, sizeof(userbookentry), MAXUSERBOOK, fp);
fclose(fp);
}
sprintf(statusbar_txt, "found %d positions in user book", userbooknum);
}
break;
case GAMELOAD:
// call selectgame with GAMELOAD to let the user select from all games
cblog("pdn load game\n");
selectgame(GAMELOAD);
break;
case GAMEINFO:
// display a box with information on the game
if (get_startcolor(cbgame.gametype) == CB_BLACK)
sprintf(str1024,
"Event: %s\nBlack: %s\nWhite: %s\nResult: %s",
cbgame.event,
cbgame.black,
cbgame.white,
cbgame.resultstring);
else
sprintf(str1024,
"Event: %s\nWhite: %s\nBlack: %s\nResult: %s",
cbgame.event,
cbgame.white,
cbgame.black,
cbgame.resultstring);
MessageBox(hwnd, str1024, "Game information", MB_OK);
sprintf(statusbar_txt, "");
break;
case SEARCHMASK:
// call selectgame with SEARCHMASK to let the user
// select from games of a certain player/event/date
cblog("pdn search with player, event, or date.\n");
selectgame(SEARCHMASK);
break;
case RE_SEARCH:
cblog("pdn research\n");
selectgame(RE_SEARCH);
break;
case GAMEFIND:
// find a game with the current position in the current database
// index the database
cblog("find current pos\n");
selectgame(GAMEFIND);
break;
case GAMEFINDCR:
// find games with current position color-reversed
selectgame(GAMEFINDCR);
cblog("find colors reversed pos\n");
break;
case GAMEFINDTHEME:
// find a game with the current position in the current database
// index the database
selectgame(GAMEFINDTHEME);
cblog("find theme\n");
break;
case LOADNEXT:
sprintf(statusbar_txt, "load next game");
cblog("load next game\n");
loadnextgame();
break;
case LOADPREVIOUS:
sprintf(statusbar_txt, "load previous game");
cblog("load previous game\n");
loadpreviousgame();
break;
case GAMEEXIT:
PostMessage(hwnd, WM_DESTROY, 0, 0);
break;
case DIAGRAM:
diagramtoclipboard(hwnd);
break;
case SAMPLEDIAGRAM:
samplediagramtoclipboard(hwnd);
break;
case GAME_FENTOCLIPBOARD:
if (setup_mode) {
MessageBox(hwnd,
"Cannot copy position in setup mode.\nLeave the setup mode first if you\nwant to copy this position.",
"Error",
MB_OK);
}
else
FENtoclipboard(hwnd, cbboard8, cbcolor, cbgame.gametype);
break;
case GAME_FENFROMCLIPBOARD:
// first, get the stuff that is in the clipboard
gamestring = textfromclipboard(hwnd, statusbar_txt);
// now if we have something, do something with it
if (gamestring != NULL) {
PostMessage(hwnd, WM_COMMAND, ABORTENGINE, 0);
if (FENtoboard8(cbboard8, gamestring, &cbcolor, cbgame.gametype)) {
updateboardgraphics(hwnd);
reset_move_history = true;
newposition = TRUE;
sprintf(statusbar_txt, "position copied");
PostMessage(hwnd, WM_COMMAND, GAMEINFO, 0);
sprintf(cbgame.FEN, gamestring);
}
else
sprintf(statusbar_txt, "no valid FEN position in clipboard!");
free(gamestring);
}
break;
case GAMECOPY:
if (setup_mode) {
MessageBox(hwnd,
"Cannot copy game in setup mode.\nLeave the setup mode first if you\nwant to copy this game.",
"Error",
MB_OK);
}
else
PDNtoclipboard(hwnd, cbgame);
break;
case GAMEPASTE:
// copy game or fen string from the clipboard...
gamestring = textfromclipboard(hwnd, statusbar_txt);
// now that the game is in gamestring doload() on it
if (gamestring != NULL) {
std::string errormsg;
PostMessage(hwnd, WM_COMMAND, ABORTENGINE, 0);
/* Detect fen or game, load it in either case. */
if (is_fen(gamestring)) {
if (!FENtoboard8(cbboard8, gamestring, &cbcolor, cbgame.gametype)) {
if (doload(&cbgame, gamestring, &cbcolor, cbboard8, errormsg))
MessageBox(hwnd, errormsg.c_str(), "Error", MB_OK);
sprintf(statusbar_txt, "game copied");
}
else {
reset_game(cbgame);
board8toFEN(cbboard8, cbgame.FEN, cbcolor, cbgame.gametype);
sprintf(statusbar_txt, "position copied");
}
}
else {
if (doload(&cbgame, gamestring, &cbcolor, cbboard8, errormsg))
MessageBox(hwnd, errormsg.c_str(), "Error", MB_OK);
else
sprintf(statusbar_txt, "position copied");
}
free(gamestring);
// game is fully loaded, clean up
updateboardgraphics(hwnd);
reset_move_history = true;
newposition = TRUE;
PostMessage(hwnd, WM_COMMAND, GAMEINFO, 0);
}
else
sprintf(statusbar_txt, "clipboard open failed");
break;
case MOVESPLAY:
// force the engine to either play now, or to start calculating
// this is the only place where the engine is started
if (setup_mode)
set_setup_mode(false);
if (!getenginebusy() && !getanimationbusy()) {
// TODO think about synchronization issues here!
setenginebusy(TRUE);
setenginestarting(FALSE);
CloseHandle(hSearchThread);
hSearchThread = CreateThread(NULL, 100000, (LPTHREAD_START_ROUTINE)SearchThreadFunc, (LPVOID) 0, 0, &g_SearchThreadId);
}
else
SendMessage(hwnd, WM_COMMAND, INTERRUPTENGINE, 0);
clicks.clear();
break;
case INTERRUPTENGINE:
// tell engine to stop thinking and play a move
if (getenginebusy())
playnow = 1;
break;
case ABORTENGINE:
// tell engine to stop thinking and not play a move
if (getenginebusy()) {
abortcalculation = 1;
playnow = 1;
}
break;
case MOVESBACK:
// take back a move
abortengine();
if (CBstate == BOOKVIEW && userbooknum != 0) {
if (userbookcur > 0)
userbookcur--;
userbookcur %= userbooknum;
sprintf(statusbar_txt,
"position %d of %d: %i-%i",
userbookcur + 1,
userbooknum,
coortonumber(userbook[userbookcur].move.from, cbgame.gametype),
coortonumber(userbook[userbookcur].move.to, cbgame.gametype));
// set up position
if (userbookcur < userbooknum) {
// only if there are any positions
bitboardtoboard8(&(userbook[userbookcur].position), cbboard8);
updateboardgraphics(hwnd);
}
break;
}
if (cbgame.movesindex == 0 && (CBstate == ANALYZEGAME || CBstate == ANALYZEPDN))
gameover = TRUE;
if (cbgame.movesindex > 0) {
--cbgame.movesindex;
gamebody_entry *tbmove = &cbgame.moves[cbgame.movesindex];
undomove(tbmove->move, cbboard8);
updateboardgraphics(hwnd);
// shouldnt this color thing be handled in undomove?
cbcolor = CB_CHANGECOLOR(cbcolor);
sprintf(statusbar_txt, "takeback: ");
// and print move number and move into the status bar
// get move number:
if (is_second_player(cbgame, cbgame.movesindex))
sprintf(Lstr, "%i... %s", moveindex2movenum(cbgame, cbgame.movesindex), tbmove->PDN);
else
sprintf(Lstr, "%i. %s", moveindex2movenum(cbgame, cbgame.movesindex), tbmove->PDN);
strcat(statusbar_txt, Lstr);
if (strcmp(tbmove->comment, "") != 0) {
sprintf(Lstr, " %s", tbmove->comment);
strcat(statusbar_txt, Lstr);
}
if (CBstate == OBSERVEGAME)
PostMessage(hwnd, WM_COMMAND, INTERRUPTENGINE, 0);
else
abortengine();
}
else
sprintf(statusbar_txt, "Takeback not possible: you are at the start of the game!");
newposition = TRUE;
reset_move_history = true;
break;
case MOVESFORWARD:
// go forward one move
// stop the engine if it is still running
abortengine();
// if in user book mode, move to the next position in user book
if (CBstate == BOOKVIEW && userbooknum != 0) {
if (userbookcur < userbooknum - 1)
userbookcur++;
userbookcur %= userbooknum;
sprintf(statusbar_txt,
"position %d of %d: %i-%i",
userbookcur + 1,
userbooknum,
coortonumber(userbook[userbookcur].move.from, cbgame.gametype),
coortonumber(userbook[userbookcur].move.to, cbgame.gametype));
// set up position
if (userbookcur < userbooknum) {
// only if there are any positions
bitboardtoboard8(&(userbook[userbookcur].position), cbboard8);
updateboardgraphics(hwnd);
}
break;
}
// normal case - move forward one move
if (cbgame.movesindex < (int)cbgame.moves.size()) {
gamebody_entry *pmove = &cbgame.moves[cbgame.movesindex];
domove(pmove->move, cbboard8);
updateboardgraphics(hwnd);
cbcolor = CB_CHANGECOLOR(cbcolor);