File: othello.c

package info (click to toggle)
vgagamespack 1.4-5
  • links: PTS
  • area: main
  • in suites: sarge, woody
  • size: 292 kB
  • ctags: 424
  • sloc: ansic: 3,826; makefile: 85
file content (1265 lines) | stat: -rw-r--r-- 39,839 bytes parent folder | download | duplicates (2)
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
/*
 * Othello playing program.
 * 
 * Written in 1993 by Bennett Todd, with some help by John White, who
 * designed the finite state automaton for edge strategy.
 *
 * Hacked by Evan Harris in 1994-1998, to enable a more general user
 * interface.
 */

/*

    Plays othello using alpha-beta search.

    Switches:
    -f  gofirst (default=no)
    -bn allocate n boards: default=64, grows as branching factor*depth
    -dn look ahead n moves: default is variable, must be greater than 0
    -rn reverse the initial board in various ways:

        -r1 reverse initial board setup; 'o' still goes first
        -r2 reverse initial board setup; 'x' goes first
        -r3  normal initial board setup; 'x' goes first

*/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <getopt.h>

#include "othello.h"

#define DEBUG_LEVEL 1

/*
    About the following defines:
    BEST and WORST are upper and lower bounds, respectively, on the
        worth of a board.
    MAXSONS is the maximum number of possible moves from any given board,
        used to size the sons array in a board node.
    EMPTY, MINE, and HIS are values for the possible states of a square
        on an othello board. In the original code, they were used as an
        enumerated type, after the fashion of PASCAL. However, during
        the process of optimizing the program, It was observed that
        in the code
            <expression>!=EMPTY
        !=EMPTY doesn't change the logical value of the expression, and
            <expression>==EMPTY is equivalent to !<expression>
        Thus the contents of board cells are sometimes used as boolean
        variables.
        What's worse, many nested if expressions and switch statements
        were removed by using values of board cells as subscripts into
        arrays, a process which altogether exceeded any reasonable bounds
        in the finite state machine found in the function worth.
*/

#define TRUE 1
#define FALSE 0
#define WORST -1000
#define BEST   1000
#define MAXSONS 30
#define EMPTY '\0'
#define MINE  '\1'
#define HIS   '\2'

typedef struct boardtype
{
    struct boardtype *sons[MAXSONS];    /* pointers to descendants  */
    int val;                            /* worth of board position  */
    char *array[8];                     /* the board itself         */
}
BOARD;

BOARD *freeboards; /* pointer to head of linked list of free boards */

int maxdepth[60]=   /* maxdepth[movenumber] is the depth that alphabeta */
    {               /* will search on the movenumber'th move            */
        1, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
        3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
        3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
        3, 3, 3, 3, 3, 3, 4, 7, 6, 5, 4, 3, 2, 1, 1
    },
    maxboards=64,   /* default number of boards to allocate     */
    reversed=FALSE, /* switch to reverse initial board position */
    movenumber=0,   /* counter for what move we are on          */
    time_out[3]=    /* timeout points, to hurry up if we are in */
    {               /* danger of overshooting 30 seconds        */
        2000,2500,2800
    },
    start_dive=52,  /* the movenumber on which to switch worths */
    gofirst=FALSE,  /* by default, the opponent goes first      */
    max,            /* who is playing at any given instant      */
    (*worth)(),     /* pointer to the current worth function    */
    i_tran[64]=     /* i subscript generator                    */
    {
        0, 0, 0, 0, 0, 0, 0, 0,
        1, 1, 1, 1, 1, 1, 1, 1,
        2, 2, 2, 2, 2, 2, 2, 2,
        3, 3, 3, 3, 3, 3, 3, 3,
        4, 4, 4, 4, 4, 4, 4, 4,
        5, 5, 5, 5, 5, 5, 5, 5,
        6, 6, 6, 6, 6, 6, 6, 6,
        7, 7, 7, 7, 7, 7, 7, 7
    },
    j_tran[64]=     /* j subscript generator                    */
    {
        0, 1, 2, 3, 4, 5, 6, 7,
        0, 1, 2, 3, 4, 5, 6, 7,
        0, 1, 2, 3, 4, 5, 6, 7,
        0, 1, 2, 3, 4, 5, 6, 7,
        0, 1, 2, 3, 4, 5, 6, 7,
        0, 1, 2, 3, 4, 5, 6, 7,
        0, 1, 2, 3, 4, 5, 6, 7,
        0, 1, 2, 3, 4, 5, 6, 7
    };

long lasttime;          /* time tick holder, for stopwatch  */

/*
    The array moves, declared below, is an array of pointers to arrays
    of pointers to arrays of subscripts, ranging from 0 to 63.
    A board is declared in the structure declaration above to be represented
    by an array of 8 pointers to arrays of chars (8 per array). In my
    initialization of the board structures, I explicitly allocate the row
    arrays consecutively; therefore, board->array[0] can be taken as a
    pointer to an array 64 long of chars, containing the cells of the board.
    board->array[0][moves[i][j][k]] is the k-th step in th j-th direction
    from the i-th cell in board. Moves is 64 long; moves[i] is variable
    length (one for each direction in which a move is possible) delimited
    with NULLs, and move[i][j] is variable length, delimited by i. In
    other words, to walk as far as possible in the j-th direction from
    cell i, you could use
        for(k=0;i!=moves[i][j][k];k++)
    though I didn't, since I use pointers to walk through the array.

*/

char **moves[64];


void initmoves(), initfree(), sort();
void move(), reclaim(), score(), putboard();
int getmove(), allsons(), alphabeta(), worth_1(), worth_2();


static struct option long_options[] = {
    { "computer-starts", 0, NULL, 'c' },
    { "search-depth", 1, NULL, 'd' },
    { "reverse-colours", 0, NULL, 'r' },
    { "reverse-colors", 0, NULL, 'r' },
    { "help", 0, NULL, 'H' }
};


int
main(argc,argv)
int argc;
char **argv;
{
    int temp, end = 0, endmove = 0, reversecolors = 0, oldmove;

    BOARD *root,            /* the root of the current tree, changed by     */
          *firstboard();    /* both move() and getmove()                    */

    int c, depth, err = 0;
    int option_index;
    
    while ((c = getopt_long(argc, argv, "cd:rH",
			    long_options, &option_index)) != -1) {
	switch (c) {
	  case 'c':
	    gofirst = TRUE;
	    break;
	  case 'd':
	    depth = atoi(optarg);
	    if (depth >= 1 && depth <= 9) {
		maxdepth[0] = depth;
		start_dive = 60 - depth;
		for(temp = 0; temp < 59; temp++)
		    maxdepth[temp+1] = maxdepth[temp];
	    } else {
		err++;
	    }
	    break;
	  case 'r':
	    reversecolors = TRUE;
	    break;
	  case 'H':
	  case '?':
	    err++;
	    break;
	}
    }
    if (err) {
	fprintf(stderr, "Usage: %s [-c] [-d N] [-r] [-H]\n", argv[0]);
	fprintf(stderr, "  -c     --computer-starts   computer plays first\n");
	fprintf(stderr, "  -d N   --search-depth=N    set search depth to N (1-9),\n");
        fprintf(stderr, "                             default: 3 (higher in endgame)\n");
	fprintf(stderr, "  -r     --reverse-colours   reverse chip colours\n");
	fprintf(stderr, "  -H     --help              print this help message\n");
	exit(EXIT_FAILURE);
    }
    
    /* call various initialization routines         */
    worth=worth_1;  /* the main heuristic function  */

    initmoves();    /* initialize the array moves   */

    initfree();         /* set up free boards list  */

    InitDisplay(reversecolors);
    
    while (!end) {
	root=firstboard();	/* set up to play the game  */

	lasttime=clock();	/* and mark time            */

	if(gofirst)
	    move(&root);
	else
	    putboard(root);

	oldmove=(-1);		/* dummy out endgame flag, it's only starting now! */

	/* main game loop */
	while(movenumber<60 && movenumber!=oldmove) /* game lasts 60 moves, */
	{			/* unless no one can move   */
	    if(movenumber>start_dive) /* change to h*, the "true" h function */
	    {
		time_out[0]=time_out[1];
		worth=worth_2;	/* only computable by looking to the end*/
	    }
	    oldmove=movenumber;	/* set to recognize if no one can move  */
	    endmove = getmove(&root);	/* get a move from the user */
	    if (endmove < 0) {
		movenumber = 60;
	    } else {
		move(&root);	/* make a move              */
	    }
	}
	if (endmove >= 0) {
	    score(root);	/* report the result */
	}

	while (endmove >= 0)
	    endmove = GetMove();
	switch (endmove) {
	  case NEWGAME:
	    NewGame();
	    worth=worth_1;  /* the main heuristic function  */
	    time_out[0]=2000;
	    movenumber = 0;
	    break;
	  case QUIT:
	    end = 1;
	    break;
	  default:
	    break;
	}
    }

    EndDisplay();

    return 0;
}

/*
    move makes a move on the (called-by-reference) board. It first
    expands all possible moves with a call to allsons, with max set to
    true (moves is trying to maximize the evaluation function), then uses
    alphabeta to evaluate each possibility, picking the best.
    Move is different from alphabeta mostly in that
        a)  it always and only plays as max
        b)  it must keep track of the actual boards, and not just
            their values (alphabeta always reclaims as soon as possible)
        c)  it is in charge of initializing everything for the search
        d)  rather than returning a backed up value, it simply outputs the
            move (and some other junk) and resets the root to point to the
            new move.
*/

void
move(board)
BOARD **board;
{
    BOARD *tempboard;

    int i,
        n,
        rush=0,         /* used to panic stop short of 30 seconds           */
        temp,
        alpha=WORST,    /* the root is max, and therefore has an alpha value*/
        best=WORST-1,   /* must be worst than the worst possible value, so  */
                        /* that a move will be picked even if they are all  */
                        /* the worst.                                       */
        bestboard;      /* subscript of the best board seen so far          */

    char *t1,           /* a couple of temporary pointers used to           */
         *t2;           /* figure out exactly where I moved.                */

    max=TRUE;   /* let us get this straight, once and for all... */

    /* read the following as "if( <number of sons found> == 0)" */
    if(!(n=allsons(*board)))    /* "==0" is equivalent to "!"   */
    {
	/* computer cannot move - warning ? */

        return;
    }

    ThinkingOn();

    /* for every son */
    for(i=0;i<n;i++)
    {

        max=FALSE;  /* think as my opponent would think */

        /* if this is better than the best we have seen so far */
        if(best<(temp=alphabeta((*board)->sons[i],maxdepth[movenumber],
                                alpha,BEST)))
        {
            best=alpha=temp;
            bestboard=i;
        }

	Poll();

        /* make sure we do not under any circumstances exceed 30 seconds */
        if((clock()-lasttime) * 100 / CLOCKS_PER_SECOND > time_out[rush])
        {
            if(rush==2)
                goto outta_here;

            rush++;
            maxdepth[movenumber]--;
        }
    }

outta_here:
    t1=(*board)->array[0]-1;                    /* set up pointers  */
    t2=(*board)->sons[bestboard]->array[0]-1;   /* for comparison   */
loop:
    while(*++t1==(*++t2));  /* find different squares           */
    if(*t1) /* then this square was flipped, not actually moved */
        goto loop;  /* so keep trying                           */

    /* temp gets the 0-63 subscript of the move */
    temp=t1-(*board)->array[0];

    ThinkingOff();

    ShowTime(((double)(clock()-lasttime))/CLOCKS_PER_SECOND);
    
    putboard((*board)->sons[bestboard]);

    /* now reclaim unneeded boards, reset the root, and count this move */
    for(i=0;i<n;i++)
        if(i!=bestboard)
            reclaim((*board)->sons[i]);
    tempboard=(*board)->sons[bestboard];
    reclaim(*board);
    *board=tempboard;
    movenumber++;
}

/*
    alphabeta takes four parameters: the board to evaluate,
    the depth to search, and the current alpha and beta values.
    It returns the worth of the board, obtained by backing up
    the values seen at the bottom of the search.
    It plays maximizing or minimizing, based on the global
    boolean variable max.
*/
    
int alphabeta(current,depth,alpha,beta)
BOARD *current;
int depth,
    alpha,
    beta;
{
    int i,
        n,
        temp,
        best,
        curmax;     /* contains the current value of the global "max",  */
                    /* negated (to minimize the number of negations)    */

    BOARD *curson;  /* contains the son being examined currently        */

    /* if no sons can be found */
    if(!(n=allsons(current)))
    {
        max=!max;                       /* then try as the other guy    */
        if(!(n=allsons(current)))       /* and if he can't move         */
            return(worth_2(current));   /* return the final value       */
    }

    best=max?WORST:BEST;    /* start off assuming the worst     */
    depth--;                /* keep track of depth              */
    curmax=!max;            /* and max through recursive calls  */

    /* for every son */
    for(i=0;i<n;i++)
    {
        max=curmax;
        curson=current->sons[i];

	Poll();

        /*
            This statement does it all. Recurse, propogating correct alpha
            and beta values (only one of which can change at any given node)
            unless of course the recursion has terminated, in which case we
            use the value of the node, as evaluated by worth when allsons
            created the node. Put the value thus obtained into temp, and
            compare it with the best value seen so far. The sense of
            comparison is reversed if curmax is true (bitwise xor is all
            right if both booleans are "pure"--0 or 1).
        */
        if(curmax^best<(temp=depth?
                                (curmax?
                                    alphabeta(curson,depth,alpha,best)
                                    :alphabeta(curson,depth,best,beta))
                                :curson->val))
        {
            /* check for an alphabeta "prune" of the tree */
            if(curmax?(temp<=alpha):(temp>=beta))
            {
                while(i<n)                      /* clean up         */
                    reclaim(current->sons[i++]);
                return(temp);                   /* and pack it in   */
            }
            else
                best=temp;  /* remember the best value seen so far  */
        }
        reclaim(curson);
    }
    return(best);
}

/*
    Simple-minded free space management. Keep a bunch of boards on a linked
    list. When one is needed, take it off the top. When no longer needed,
    insert it at the top. Optionally, check for out-of-boards (The converse,
    attempting to check for freeing of space not taken from the freeboard
    list, seemed to be too difficult. Perhaps I could have kept around high-
    water and low-water mark pointers to the space of legal board pointers.),
    and accumulate statistics.
*/

BOARD *newboard()
{
    BOARD *temp;

#if DEBUG_LEVEL > 0
    if(!freeboards)
        initfree();
#endif

    temp=freeboards;
    freeboards=freeboards->sons[0];
    temp->sons[0]=NULL;
    return(temp);
}

void
reclaim(board)
BOARD *board;
{
    board->sons[0]=freeboards;
    freeboards=board;
}

/*
    Shell sort taken from K&R, sorts the n boards in the array into ascending
    or descending order based on the global boolean max, sorting on the
    values contained in the value member of each board structure. This sort
    focuses the alphabeta search significantly, increasing the pruning enough
    to cut depth 4 search time by approximately 65 percent.
*/

void
sort(boards,n)
BOARD **boards;
int n;
{
    int i,
        j,
        gap,
        jpg; /* temporary storage hold j+gap */

    BOARD *tempboard;

    for(gap=n/2;gap>0;gap/=2)
        for(i=gap;i<n;i++)
            for(j=i-gap;j>=0 &&
                    (max?(boards[j]->val<boards[jpg=j+gap]->val):
                    (boards[j]->val>boards[jpg=j+gap]->val));j-=gap)
            {
                tempboard=boards[j];
                boards[j]=boards[jpg];
                boards[jpg]=tempboard;
            }
}

/*
    Initialize a linked list of free boards. Each board has an array of
    8 pointers to rows of 8 bytes each. Allocate space for the rows, and
    initialize the pointer arrays to point to the rows. The rows in a board
    are explicitly allocated contiguously, so it is possible (and turns out
    to enhance efficiency at the expense of comprehensability) to treat
    a board as a single array of 64 bytes, pointed to by the pointer to
    the first row. Optionally, produce statistics on allocation of memory.
*/

void
initfree()
{
    int i,j;

    char *boardspace;

    freeboards=((BOARD *) calloc(maxboards,sizeof(BOARD)));
    if(!freeboards)
    {
        fprintf(stderr, "Error: board structure allocation failed.\n");
        exit(1);
    }
    boardspace=calloc(maxboards,sizeof(char [64]));
    if(!boardspace)
    {
        fprintf(stderr, "Error: board freespace allocation failed.\n");
        exit(1);
    }

    /* thread linked list and arrange the row pointer arrays */
    for(i=0;i<maxboards;i++)
    {
	if (i>0)
	{
	    freeboards[i-1].sons[0]=freeboards+i;
	}
        for(j=0;j<8;j++)
	{
	    freeboards[i].array[j]=boardspace+64*i+8*j;
	}
    }
    freeboards[maxboards-1].sons[0]=NULL;

    /* We might be called again, if he needs more boards */
    maxboards=10;
}

/*
    The array moves contains information about the shape of a board, in
    a fashion which simplifies the checking of loop conditions in the
    code which is examining a board for a move, and flipping the resulting
    pieces. Specifically, moves (which is a byte array because it needs
    no large numbers) is used as follows:
        moves[i][j][k] refers to the subscript of the
            k-th square, in the
            j-th direction, from the
            i-th square on the board.
    Moves is 64 long; moves[i] is variable length delimited by NULL; and
    moves[i][j] is variable length delimited by the value of i.
*/

void
initmoves()
{
    int i,
        j,
        k,
        l,
        m,
        n;

    char **pointers,
         *bytes;

    /* 484 and 2016 are computed by rote */
    pointers=((char **) calloc(484,sizeof(char **)));
    if(pointers==NULL)
    {
        fprintf(stderr, "Error in initmoves: cannot allocate pointers.\n");
        exit(1);
    }
    bytes=calloc(2016,sizeof(char));
    if(bytes==NULL)
    {
        fprintf(stderr, "Error in initmoves: cannot allocate bytes.\n");
        exit(1);
    }

    /* for each square on the board */
    for(i=0;i<8;i++) for(j=0;j<8;j++)
    {

        /* set the corresponding entry of moves to some free pointers */
        moves[i*8+j]=pointers;

        /* for each direction */
        for(k=(-1);k<2;k++) for(l=(-1);l<2;l++)
            if(k || l)  /* if neither k or l we aren't going anywhere */
            {
                *pointers=bytes; /* point to some free bytes */
                /* let m and n walk to the edge of the board */
                for(m=i+k,n=j+l;m>=0 && m<8 && n>=0 && n<8;m+=k,n+=l)
                    (*bytes++)=m*8+n;
                if(m!=i+k || n!=j+l)
                /* then we managed to walk somewhere */
                {
                    (*bytes++)=i*8+j;   /* terminate bytes list             */
                    pointers++;         /* get pointer for next direction   */
                }
            }
        (*pointers++)=NULL; /* terminate pointers list */
    }
}

/*
    allsons finds all sons for the board which is its parameter, sets the
    array of pointers to sons to point to new boards containing the resulting
    boards, sets the val member of each son board structure to the value as
    evaluated by worth, and sorts the sons in order, to focus the alphabeta
    search. It returns the number of sons it found.
*/

int allsons(pos)
BOARD *pos;
{
    int cur=0, /* son next to allocate */
        i;

    char mine,          /* mine, from the point of the current player   */
         hisn,          /* likewise                                     */
         whose,         /* temporary variable--keep from recomputing    */
         *board,        /* pointer into the board array                 */
         ***move_ptr,   /* pointer into the moves array                 */
         **dir_ptr,     /* pointer into moves[i] arrays of directions   */
         *sub_ptr;      /* pointer into moves[i][j] arrays of subscrtips*/

    BOARD *resultof(),  /* create a board resulting from making a move  */
          *curson;      /* point to current son                         */

    mine=max?MINE:HIS;
    hisn=max?HIS:MINE;
    board=pos->array[0];

    /* for(i=0;i<64;i++) with move_ptr=moves[i] */
    for(i=0,move_ptr=moves;i<64;i++,move_ptr++)
    {
        /* if(board[i]==EMPTY) */
        if(!board[i])
            /* for(j=0;moves[i][j]!=NULL;j++) with sub_ptr=moves[i][j] */
            for(dir_ptr=(*move_ptr);sub_ptr=(*dir_ptr++);)
                /* if he owns the cell in the j-th direction */
                if(board[*sub_ptr++]==hisn)
                {
                    /* scan until edge of board or end of list */
                    /*
                        NOTE: moves[i][j] is delimited by i, so the edge of
                        the board looks like a cell containing the same thing
                        as board[i], which must be empty if I got into this
                        code; therefore, hitting edge of board looks just
                        like seeing a space at the end of the string of
                        opponents pieces, which means I cannot capture them.
                    */
                    while((whose=board[*sub_ptr++])==hisn);
                    if(whose==mine) /* then we have a possible capture */
                    {
                        curson=pos->sons[cur++]=resultof(pos,i);
                        curson->val=(*worth)(curson);
                        goto endit; /* don't look in other directions */
                    }
                }
endit:  ;
    }

#if DEBUG_LEVEL > 0
    if(cur>MAXSONS)
    {
        fprintf(stderr,"allsons: I needed %d sons for",cur+1);
        putboard(pos);
        fprintf(stderr,"allsons: but I only am alotted %d.\n",MAXSONS);
        printf("Sorry, boss.\n");
        exit(0);
    }
#endif

    sort(pos->sons,cur);
    pos->sons[cur]=0;
    return(cur);
}

/*
    Resultof makes a copy of the board (using _move(), a fast block
    move routine that comes with Mark DeSmet's Cware C compiler, if
    the code is being generated for an IBM-PC) and flips all squares
    thet need to be flipped based on making a move at position x
    (where x ranges for 0 to 63), takes the square at x, and returns
    a pointer to the resulting board. It calls newboard(), the free
    board server.
*/

BOARD *resultof(father,x)
BOARD *father;
int x;
{
    int mine,   /* mine, from the point of view of the current player   */
        hisn;   /* likewise                                             */

    char *board,    /* pointer into the board array                     */
		 *tmpptr,	/* pointers for copying the board in portble C		*/
		 *tmplim,
         **dir, /* pointer for moves[x][j], a direction                 */
         *sub;  /* pointer to a subscript, moves[i][j][k]               */

    BOARD *newboard(),
          *temp;

    mine=max?MINE:HIS;
    hisn=max?HIS:MINE;
    temp=newboard();

    /* Copy the board. Use a block move on the PC   */
    board=temp->array[0];
    tmpptr=father->array[0];
    tmplim=board+64;
    while(board<tmplim)
        (*board++)=(*tmpptr++);

    board=temp->array[0];

    /* for(j=0;moves[x][j]!=NULL;j++) */
    for(dir=moves[x];*dir;dir++)
        /* if the cell in the j-th direction is his  */
        if(board[**dir]==hisn)
        {
            sub=(*dir);

            /* scan as long as the pieces are his   */
            /* (Please see discussion in allsons    */
            while(board[*++sub]==hisn);

            /* if the search was terminated by a piece of mine */
            if(board[*sub]==mine)
            {
                /* do the same scan, flipping pieces as you go */
                sub=(*dir);
                while(board[*sub]==hisn)
                    board[*(sub++)]=mine;
            }
        }

    /* put a piece where we actually moved */
    board[x]=mine;
    return(temp);
}

/*
    firstboard() returns a pointer to a board set up in the initial position.
    It is the only routine that actually zeros out a board array, and sets
    things up in it. The remainder of the boards are made by copying and
    then changing, by resultof(). The initial position is reversed if we
    are going first (because what is stored is not x's and o's, but MINE
    and HIS) and can be reversed again by a reverse switch.
*/

BOARD *firstboard()
{
    BOARD *temp,
          *newboard();

    int i,
        j;

    temp=newboard();

    /* zero out the array */
    for(i=0;i<8;i++)
        for(j=0;j<8;j++)
            temp->array[i][j]=EMPTY;
    /* put the start position into the cells */
    /* either gofirst or reversed can switch the initialization */
    temp->array[3][3]=temp->array[4][4]=(!(gofirst^reversed))?MINE:HIS;
    temp->array[3][4]=temp->array[4][3]=(!(gofirst^reversed))?HIS:MINE;

    return(temp);
}

/*
    Getmove gets a move from the user. 
*/

int
getmove(board)
BOARD **board;
{
    int i,
        j,
        k,
        n;
    int move;

    BOARD *resultof(),
          *temp;

    max=FALSE;

    /* if(<the number of sons found>==0) */
    if(!(n=allsons(*board)))
    {
	/* player cannot move - warning ? */

        lasttime=clock();
        return 0;
    }

    movenumber++;
#ifdef EVAN0
    if(n==1)
    {
        printf("You have only one move. Press return to continue: ");

        while(getchar()!='\n');

        lasttime=clock();
        temp=(*board)->sons[0];

        reclaim(*board);
        (*board)=temp;
        return;
    }
#endif

    /* get and validity check move */
retry:
    move = GetMove();
    if (move == NEWGAME || move == QUIT) {
	return move;
    }
    lasttime = clock();

    i = move % 8;
    j = move / 8;

    /* if(<position is out of range> || board[i][j]!=EMPTY) */
    if(i<0 || i>7 || j<0 || j>7 || (*board)->array[i][j])
    {
        goto retry;
    }
    /* scan the sons list, looking for a son with this cell occupied    */
    for(k=0;!((*board)->sons[k]->array[i][j]);)
        /* if we have reached the end of the list without finding one   */
        if(++k==n)
        {
            goto retry;
        }

    /* clean up stray sons */
    for(i=0;i<n;i++)
        if(i!=k)
            reclaim((*board)->sons[i]);
    temp=(*board)->sons[k];

    reclaim(*board);
    *board=temp;

    putboard(*board);

    return 0;
}

/*
    Score simply adds up the number of cells owned by each player,
    reports the results, and leaves.
*/

void
score(board)
BOARD *board;
{
    char i,
         sums[3]={0,0,0},
         *ptr;

    ptr=board->array[0];
    for(i=0;i<64;i++)
        sums[(int)*ptr++]++;
    if (sums[MINE] == sums[HIS]) {
	ShowDraw(sums[MINE]);
    } else if (sums[MINE] > sums[HIS]) {
	ShowWin(MINE, sums[MINE], sums[HIS]);
    } else {
	ShowWin(HIS, sums[HIS], sums[MINE]);
    }
}

/*
    Putboard can be used for one or two boards. For one board, make the
    second parameter NULL. It calls a function fast_puts to put the string
    out. This is to allow quick board drawing on a PC.
    Optionally, error checking code can be compiled in, to check for the
    (common) C bug of wandering of into randomn memory locations.
    Throughout the function, realize the "if(new)" is functionally identical
    to "if(new!=NULL)".
*/

void
putboard(new)
BOARD *new;
{
    int i, j;

    PutBoardStart();

    /* for every row */
    for(i=0;i<8;i++)
    {
        /* for every column */
        for(j=0;j<8;j++)
        {
	    PutSquare(j, i, new->array[i][j]);
        }
    }

    PutBoardEnd();
}

/*
    Worth_1 is the worth function containing all the subtle strategic
    heuristic information in the game. It is used until we can start
    looking all the way to the end of the game, at which point the
    optimum heuristic function, h* becomes available. That is called
    worth_2, and is much simpler.
*/

int
worth_1(board)
BOARD *board;
{
    int valsum[3]; /* buckets in which to accumulate the sums       */

    char *ptr,  /* temporary pointers for walking through the array */
         *t;

    static char
        val1[3]={30,0,0},   /* value of (1,1) if (0,0)=0,1,2 */
        val2[3]={ 4,0,0},   /* value of (1,2) if (0,2)=0,1,2 */
        val3[3]={ 5,0,0};   /* value of (1,3) if (0,3)=0,1,2 */

#define ev0 50  /* value of pos 00 (corner)     */
#define ev1 4   /* value of pos 01              */
#define ev2 16  /* value of pos 02              */
#define ev3 12  /* value of pos 03              */
#define sv  20  /* value of a split on the edge */

/*
     50,  4, 16, 12, 12, 16,  4, 50,
      4,-30, -4, -5, -5, -4,-30,  4,
     16, -4,  1,  0,  0,  1, -4, 16,        This is what the board cell
     12, -5,  0,  0,  0,  0, -5, 12,        worth function looks like,
     12, -5,  0,  0,  0,  0, -5, 12,        discounting all dynamic
     16, -4,  1,  0,  0,  1, -4, 16,        dependancies.
      4,-30, -4, -5, -5, -4,-30,  4,
     50,  4, 16, 12, 12, 16,  4, 50
*/

/*
    f[] is a finite state automaton used for edge strategy
    It recognizes two related phenomena, which we call "splits";
    positions where two pieces owned by one player on an edge are

        a) separated by exactly 1 blank, or
        b) separated by 1 or more of the opponent's

    Invented by John White, it is structured as follows:

    f[105] can be viewed as 5 tiers of 7 states, each of which requires
    3 cells for the three possible input values.
    Starting at one corner, you scan along an edge.
    Keep always in mind that the values of board cells are

                        0       EMPTY
                        1       MINE
                        2       HIS

    The states are numbered as follows:

      state         decription                      board
      ----- ----------------------------------      ------

        0   currently scanning through blanks       ... 0
        1   just seen a square of mine              ... 1
        2   just seen a square if his               ... 2
        3   a blank following a square of mine      ... 10
        4   a blank following a square of his       ... 20
        5   one of his following one of mine        ... 12
        6   one of mine following one of his        ... 21

    The following table identifies the transitions between states.
    The numbers down the left, labelling the rows, are the input
    cell values. The numbers across the top are state numbers.
    The contents of a cell in this matrix is the number of the
    state the will be result from the input at the left from the
    state above.

            0       1       2       3       4       5       6
        ---------------------------------------------------------
    0   |   0   |   3   |   4   |   0   |   0   |   4   |   3   |
        ---------------------------------------------------------
    1   |   1   |   1   |   6   |   1 - |   1   |   6 - |   6   |
        ---------------------------------------------------------
    2   |   2   |   5   |   2   |   2   |   2 + |   5   |   5 + |
        ---------------------------------------------------------

    The cells containing postfix "+" or "-" symbols represent
    situations in which we have found one of the key patterns,
    at which point we go to the state indicated in the immediately
    higher or lower tier, respectively. The final value is
    simply the number of the tier we are on at the end, multiplied
    by sv, the split value. Note that each state takes three array elements,
    so the actual contents of the array are three times the state
    numbers shown above, repeated 5 times, offset by the tier start
    subscripts, with special offsets applied to the cells which
    jump tiers. The array v[] is used for the last lookup, since
    we are uninterested in the exact state, but just the tier, and
    since the tier number must be multiplied by sv, we put the resulting
    products in v[]. Finally, the tiers are organized as follows:

              offset    meaning             value
              ------ ----------------       -----
        
                 0       neutral               0
                21        good                sv
                42        bad                -sv
                63      very good            2*sv
                84      very bad            -2*sv

    With this organization, if the state of the machine at time t0 is
    S0 and the input is I0, the state at time t1 is f[S0+I0], and therefore
    the state at time t2 is f[f[S0+I0]+I1] and so forth.
    So, without further ado:
*/

    static char f[105]=
                {
/*----------------------------------------------------------------------------
|state    0         1          2         3         4          5          6   |
|input 0  1  2   0  1  2   0   1  2   0  1  2   0  1  2   0   1  2   0   1  2|
----------------------------------------------------------------------------*/
       0, 3, 6,  9, 3,15, 12, 18, 6,  0,45, 6,  0, 3,27, 12, 60,15,  9, 18,36,
      21,24,27, 30,24,36, 33, 39,27, 21, 3,27, 21,24,69, 33, 18,36, 30, 39,78,
      42,45,48, 51,45,57, 54, 60,48, 42,87,48, 42,45, 6, 54,102,57, 51, 60,15,
      63,66,69, 72,66,78, 75, 81,69, 63,24,69, 63,66,69, 75, 39,78, 72, 81,78,
      84,87,90, 93,87,99, 96,102,90, 84,87,90, 84,87,48, 96,102,99, 93,102,57
                };

/* v is the final pass of f, and is board value instead of next state */

    static int v[105]=
               {
        0,0,0,0,0,0,0,0,0,0,-sv,0,0,0,sv,0,-sv,0,0,0,sv,
        sv,sv,sv,sv,sv,sv,sv,sv,sv,sv,0,sv,sv,sv,2*sv,sv,0,sv,sv,sv,2*sv,
        -sv,-sv,-sv,-sv,-sv,-sv,-sv,-sv,-sv,-sv,-2*sv,-sv,-sv,-sv,0,-sv,
                -2*sv,-sv,-sv,-sv,0,
        2*sv,2*sv,2*sv,2*sv,2*sv,2*sv,2*sv,2*sv,2*sv,2*sv,sv,2*sv,2*sv,
                2*sv,2*sv,2*sv,sv,2*sv,2*sv,2*sv,2*sv,
        -2*sv,-2*sv,-2*sv,-2*sv,-2*sv,-2*sv,-2*sv,-2*sv,-2*sv,-2*sv,-2*sv,
                -2*sv,-2*sv,-2*sv,-sv,-2*sv,-2*sv,-2*sv,-2*sv,-2*sv,-sv
               };

#if DEBUG_LEVEL > 1
    worth_called++;
#endif

    *valsum=valsum[2]=0;    /* clean out buckets    */
    ptr=t=board->array[0];  /* set up pointers      */

    /* and let the finite state automoton roll--one edge in each term */
    valsum[1]=
      v[f[f[f[f[f[f[f[  *t ]+t[ 1]]+t[ 2]]+t[ 3]]+t[ 4]]+t[ 5]]+t[ 6]]+t[ 7]]
     +v[f[f[f[f[f[f[f[  *t ]+t[ 8]]+t[16]]+t[24]]+t[32]]+t[40]]+t[48]]+t[56]]
     +v[f[f[f[f[f[f[f[t[ 7]]+t[15]]+t[23]]+t[31]]+t[39]]+t[47]]+t[55]]+t[63]]
     +v[f[f[f[f[f[f[f[t[56]]+t[57]]+t[58]]+t[59]]+t[60]]+t[61]]+t[62]]+t[63]];

    /*
        if the worth array shown in the comment above actually existed, the
        next 60 or so lines might have been written

            for(i=0;i<64;i++)
                valsum[board[i]]+=worth[i];

        but it doesn't, except in the defined constants ev0 through ev3.
        Besides, it's quicker to execute 60 statements than to go through
        a loop 60 times (no loop control and branching) and this function
        is at the bottom of the recursion, and needs to be fast.
    */

    valsum[(int)*ptr++]+=ev0;
    valsum[(int)*ptr++]+=ev1;
    valsum[(int)*ptr++]+=ev2;
    valsum[(int)*ptr++]+=ev3;
    valsum[(int)*ptr++]+=ev3;
    valsum[(int)*ptr++]+=ev2;
    valsum[(int)*ptr++]+=ev1;
    valsum[(int)*ptr++]+=ev0;

    valsum[(int)*ptr++]+=ev1;
    valsum[(int)*ptr++]-=val1[(int)*t];
    valsum[(int)*ptr++]-=val2[(int)t[2]];
    valsum[(int)*ptr++]-=val3[(int)t[3]];
    valsum[(int)*ptr++]-=val3[(int)t[4]];
    valsum[(int)*ptr++]-=val2[(int)t[5]];
    valsum[(int)*ptr++]-=val1[(int)t[7]];
    valsum[(int)*ptr++]+=ev1;

    valsum[(int)*ptr++]+=ev2;
    valsum[(int)*ptr++]-=val2[(int)t[16]];
    valsum[(int)*ptr]++;
    ptr+=3;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]-=val2[(int)t[23]];
    valsum[(int)*ptr++]+=ev2;

    valsum[(int)*ptr++]+=ev3;
    valsum[(int)*ptr]-=val3[(int)t[24]];
    ptr+=5;
    valsum[(int)*ptr++]-=val3[(int)t[31]];
    valsum[(int)*ptr++]+=ev3;

    valsum[(int)*ptr++]+=ev3;
    valsum[(int)*ptr]-=val3[(int)t[32]];
    ptr+=5;
    valsum[(int)*ptr++]-=val3[(int)t[39]];
    valsum[(int)*ptr++]+=ev3;

    valsum[(int)*ptr++]+=ev2;
    valsum[(int)*ptr++]-=val2[(int)t[40]];
    valsum[(int)*ptr]++;
    ptr+=3;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]-=val2[(int)t[47]];
    valsum[(int)*ptr++]+=ev2;

    valsum[(int)*ptr++]+=ev1;
    valsum[(int)*ptr++]-=val1[(int)t[56]];
    valsum[(int)*ptr++]-=val2[(int)t[58]];
    valsum[(int)*ptr++]-=val3[(int)t[59]];
    valsum[(int)*ptr++]-=val3[(int)t[60]];
    valsum[(int)*ptr++]-=val2[(int)t[61]];
    valsum[(int)*ptr++]-=val1[(int)t[63]];
    valsum[(int)*ptr++]+=ev1;

    valsum[(int)*ptr++]+=ev0;
    valsum[(int)*ptr++]+=ev1;
    valsum[(int)*ptr++]+=ev2;
    valsum[(int)*ptr++]+=ev3;
    valsum[(int)*ptr++]+=ev3;
    valsum[(int)*ptr++]+=ev2;
    valsum[(int)*ptr++]+=ev1;
    valsum[(int)*ptr]+=ev0;

    return(valsum[1]-valsum[2]);
}

/*
    If worth_2 is being called, we are looking all the way to the end of
    the game, and we can use the final board as an evaluator: the worth
    of the board is the number of squares more I have than he. This number
    is shifted left 2 to attempt to make the range of values returned
    approximately comparable to worth_1, so that worth_2 can be used
    by alphabeta when we find an early game ending.
*/

int
worth_2(board)
BOARD *board;
{

    int valsum[3]={0,0,0};

    char *ptr;

    ptr=board->array[0];
    /*
        The following 64 lines could have been replaced with
            for(i=0;i<64;i++)
                valsum[board[i]]++;

        but it would have been slower.
    */
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr++]++;
    valsum[(int)*ptr]++;

    /* return((<number I have> - <number he has>) * 2); */
    return((valsum[1]-valsum[2])<<2);
}