-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtiles2048.cpp
1914 lines (1660 loc) · 50.8 KB
/
tiles2048.cpp
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
#include "glfontstash.h"
#include "tinythread.h"
#include "mintomic/mintomic.h"
#define CRAZY_VERBOSE_CACHE_DEBUGGER 0
#define USE_CACHE_VERIFICATION_MAP 0
#define PRINT_BOARD_STATE 0
#define PRINT_CACHE_STATS 0
#include <GLFW/glfw3.h>
#if USE_CACHE_VERIFICATION_MAP
#include <map>
#endif
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <cassert>
#include <stdint.h>
template <typename T>
static T min(T a, T b) { return (a < b ? a : b); }
template <typename T>
static T max(T a, T b) { return (a > b ? a : b); }
template <typename T>
static T clamp(T x, T a, T b) { return (x < a ? a : (x > b ? b : x)); }
template <typename T>
static T signum(T a) { return T(T(0) < a) - T(a < T(0)); }
enum BoardConfig {
TILES_X = 4,
TILES_Y = 4,
NUM_TILES = TILES_X * TILES_Y,
MAX_POWER = 15
};
// note: if you change this you must change DIR_DX and DIR_DY
enum MoveDir {
MOVE_LEFT,
MOVE_RIGHT,
MOVE_UP,
MOVE_DOWN
};
// note: depends on order of values in enum MoveDir
static const int DIR_DX[4] = { -1, 1, 0, 0 };
static const int DIR_DY[4] = { 0, 0, -1, 1 };
struct RNG {
uint32_t x, y, z, w;
void reset(uint32_t seed = 0u) {
x = seed ? seed : 123456789u;
y = x^(x<<13); y ^= (y >> 17); y ^= (y << 5);
z = y^(y<<13); z ^= (z >> 17); z ^= (z << 5);
w = z^(z<<13); w ^= (w >> 17); w ^= (w << 5);
}
uint32_t next32() {
uint32_t t = x^(x<<15); t = (w^(w>>21)) ^ (t^(t>>4));
x = y; y = z; z = w; w = t;
return t;
}
uint64_t next64() {
const uint64_t a = next32();
const uint64_t b = next32();
return (a << 32) | b;
}
int next_n(int n) {
// see: http://www.azillionmonkeys.com/qed/random.html
assert(n > 0);
const uint32_t range = UINT32_MAX - (UINT32_MAX % n);
uint32_t value;
do { value = next32(); } while (value >= range);
value = (value / ((range - 1) / (uint32_t)n + 1));
assert(value < (uint32_t)n);
return value;
}
};
typedef uint8_t BoardState[NUM_TILES];
#define PRINT_ANIM 0
struct AnimCurve {
enum { MAX_KEYS = 8 };
float ky[MAX_KEYS];
float kt[MAX_KEYS];
int nkeys;
void reset() {
nkeys = 0;
}
void push(float t, float y) {
assert(nkeys < MAX_KEYS);
assert(t >= 0.0f);
assert(nkeys == 0 || t > kt[nkeys-1]);
ky[nkeys] = y;
kt[nkeys] = t;
++nkeys;
}
float eval(float at) const {
if (nkeys == 0) { return 0.0f; }
if (nkeys == 1) { return ky[0]; }
at = max(at, 0.0f);
for (int i = 1; i < nkeys; ++i) {
if (at < kt[i]) {
float alpha = (at - kt[i-1]) / (kt[i] - kt[i-1]);
return (1.0f - alpha)*ky[i-1] + alpha*ky[i];
}
}
return ky[nkeys - 1];
}
float period() const {
return (nkeys == 0 ? 0.0f : kt[nkeys-1]);
}
};
static void tile_idx_to_xy(int where, float *x, float *y) {
assert(where >= 0 && where < NUM_TILES);
assert(x);
assert(y);
*x = 128.0f * (where % TILES_X);
*y = 128.0f * (where / TILES_X);
}
struct TileAnim {
int value;
AnimCurve x;
AnimCurve y;
AnimCurve scale;
void reset() {
value = 15;
x.reset();
y.reset();
scale.reset();
}
float period() const {
return max(max(x.period(), y.period()), scale.period());
}
};
struct ScoreAnim {
int score;
AnimCurve x;
AnimCurve y;
AnimCurve alpha;
void reset() {
score = 0;
x.reset();
y.reset();
alpha.reset();
}
float period() const {
return max(max(x.period(), y.period()), alpha.period());
}
};
struct Board;
struct AnimState {
TileAnim tiles[NUM_TILES*2];
ScoreAnim scores[NUM_TILES];
float period;
int ntiles;
int nscores;
bool moved;
bool tiles_changed() const {
return moved;
}
void reset() {
period = 0.0f;
ntiles = 0;
nscores = 0;
moved = false;
}
void add_slide(int from, int to, int value) {
assert(ntiles < NUM_TILES*2);
assert(to >= 0 && to < NUM_TILES);
assert(from >= 0 && from < NUM_TILES);
float x0, y0, x1, y1;
tile_idx_to_xy(from, &x0, &y0);
tile_idx_to_xy(to, &x1, &y1);
TileAnim &tile = tiles[ntiles++];
tile.reset();
tile.value = value;
tile.x.push(0, x0);
tile.x.push(100, x1);
tile.y.push(0, y0);
tile.y.push(100, y1);
tile.scale.push(0, 1.0f);
period = max(period, tile.period());
}
void add_slide_and_vanish(int from, int to, int value) {
add_slide(from, to, value);
tiles[ntiles-1].scale.push( 80, 1.0f);
tiles[ntiles-1].scale.push(200, 0.2f);
period = max(period, tiles[ntiles-1].period());
}
void add_pop_tile(int where, int value) {
assert(ntiles < NUM_TILES*2);
assert(where >= 0 && where < NUM_TILES);
float x, y;
tile_idx_to_xy(where, &x, &y);
TileAnim &tile = tiles[ntiles++];
tile.reset();
tile.value = value;
tile.x.push(0, x);
tile.y.push(0, y);
tile.scale.push(0, 0.0f);
tile.scale.push(89.9999f, 0.0f);
tile.scale.push(90, 0.2f);
tile.scale.push(120, 1.25f);
tile.scale.push(200, 1.0f);
period = max(period, tile.period());
}
void add_place_tile(int where, int value) {
assert(ntiles < NUM_TILES*2);
assert(where >= 0 && where < NUM_TILES);
float x, y;
tile_idx_to_xy(where, &x, &y);
TileAnim &tile = tiles[ntiles++];
tile.reset();
tile.value = value;
tile.x.push(0.0f, x);
tile.y.push(0.0f, y);
tile.scale.push(0, 0.0f);
tile.scale.push(89.9999f, 0.0f);
tile.scale.push(90, 0.2f);
tile.scale.push(200, 1.0f);
period = max(period, tile.period());
}
void add_score_slide(int where, int value) {
assert(nscores < NUM_TILES);
float x, y;
tile_idx_to_xy(where, &x, &y);
ScoreAnim &score = scores[nscores++];
score.reset();
score.score = 1 << value;
score.x.push(0, x);
score.y.push(0, y);
score.y.push(100, y);
score.y.push(500, y-96.0f);
score.alpha.push(0, 0.0f);
score.alpha.push(90, 0.0f);
score.alpha.push(100, 0.4f);
score.alpha.push(500, 1.0f);
period = max(period, score.period());
}
void merge(int from0, int from1, int to, int old_value) {
add_slide_and_vanish(from0, to, old_value);
add_slide_and_vanish(from1, to, old_value);
add_pop_tile(to, old_value + 1);
add_score_slide(to, old_value + 1);
moved = true;
}
void slide(int from, int to, int value) {
add_slide(from, to, value);
if (from != to) { moved = true; }
}
void blank(int /*where*/) {}
void new_tile(int where, int value) {
add_place_tile(where, value);
moved = true;
}
};
struct Board {
BoardState state;
void reset() {
memset(&state, 0, sizeof(state));
}
int count_free(uint8_t *free = 0) const {
int nfree = 0;
for (int i = 0; i < NUM_TILES; ++i) {
if (free && (state[i] == 0)) { free[nfree] = i; }
nfree += (state[i] == 0);
}
assert(nfree >= 0 && nfree <= NUM_TILES);
return nfree;
}
bool has_direct_matches() const {
/* check rows */
for (int i = 0; i < TILES_Y; ++i) {
const uint8_t *at = (state + i*TILES_X);
for (int j = 1; j < TILES_X; ++j) {
if (at[0] && (at[0] == at[1])) { return true; }
++at;
}
}
/* check columns */
for (int j = 0; j < TILES_X; ++j) {
const uint8_t *at = (state + j);
for (int i = 1; i < TILES_Y; ++i) {
if (at[0] && (at[0] == at[TILES_X])) { return true; }
at += TILES_X;
}
}
return false;
}
bool finished() const {
return (count_free() == 0 && !has_direct_matches());
}
void place(int count, AnimState *anim, RNG &rng) {
assert(count > 0);
uint8_t free[NUM_TILES];
int nfree = count_free(free);
while (count && nfree) {
int value = (rng.next_n(10) < 9 ? 1 : 2);
int which = rng.next_n(nfree);
assert(which >= 0 && which < nfree);
state[free[which]] = value;
if (anim) { anim->new_tile(free[which], value); }
// could do this by swapping the last value into free[which],
// but that changes the order of slots which means that
// place(1); place(1); would behave differently to place(2);
for (int i = which + 1; i < nfree; ++i) {
assert(i < NUM_TILES);
free[i-1] = free[i];
}
--nfree;
--count;
}
}
bool tilt(int dx, int dy, AnimState *anim = 0, int *score = 0) {
assert((dx && !dy) || (dy && !dx));
int begin = ((dx | dy) > 0 ? NUM_TILES - 1 : 0);
int step_major = -(dx*TILES_X + dy);
int step_minor = -(dy*TILES_X + dx);
int n = (dx ? TILES_Y : TILES_X);
int m = (dx ? TILES_X : TILES_Y);
bool moved = false;
for (int i = 0; i < n; ++i) {
int stop = begin + m*step_minor;
int from = begin, to = begin;
int last_value = 0;
int last_from = from;
while (from != stop) {
if (state[from]) {
if (last_value) {
if (last_value == state[from]) {
if (anim) { anim->merge(last_from, from, to, last_value); }
if (score) { *score += (1 << (last_value + 1)); }
moved = true;
state[to] = last_value + 1;
last_value = 0;
} else {
if (anim) { anim->slide(last_from, to, last_value); }
if (last_from != to) { moved = true; }
int tmp = state[from];
state[to] = last_value;
last_value = tmp;
last_from = from;
}
to += step_minor;
} else {
last_value = state[from];
last_from = from;
}
}
from += step_minor;
}
if (last_value) {
if (anim) { anim->slide(last_from, to, last_value); }
if (last_from != to) { moved = true; }
state[to] = last_value;
to += step_minor;
}
while (to != stop) {
if (anim) { anim->blank(to); }
state[to] = 0;
to += step_minor;
}
begin += step_major;
}
return moved;
}
bool move(int dir, AnimState *anim, RNG &rng, int *score) {
assert(dir >= 0 && dir < 4);
if (anim) { anim->reset(); }
bool moved = tilt(DIR_DX[dir], DIR_DY[dir], anim, score);
if (moved) { place(1, anim, rng); }
return moved;
}
};
struct BoardHistory {
struct HistoryState {
Board board;
RNG rng;
int score;
void reset() {
board.reset();
rng.reset();
score = 0;
}
void reset(const RNG &initial_rng) {
board.reset();
rng = initial_rng;
score = 0;
}
void reset(const Board &initial_board, const RNG &initial_rng) {
board = initial_board;
rng = initial_rng;
score = 0;
}
void reset(uint32_t seed) {
board.reset();
rng.reset(seed);
score = 0;
}
void place(int n, AnimState *anim) {
board.place(n, anim, rng);
}
bool move(int dir, AnimState *anim) {
return board.move(dir, anim, rng, &score);
}
};
enum { MAX_UNDO = 4096 };
HistoryState history[MAX_UNDO];
int current;
int undo_avail;
int redo_avail;
void clear_history() {
// retain RNG state
RNG rng = get_rng();
history[0].reset(rng);
current = 0;
undo_avail = 0;
redo_avail = 0;
}
void reset(uint32_t seed = 0u) {
history[0].reset(seed);
current = 0;
undo_avail = 0;
redo_avail = 0;
}
void reset(const Board &board, const RNG &initial_state) {
history[0].reset(board, initial_state);
current = 0;
undo_avail = 0;
redo_avail = 0;
}
void new_game(AnimState &anim) {
clear_history();
history[0].place(2, &anim);
}
const Board &get() const { return history[current].board; }
const RNG &get_rng() const { return history[current].rng; }
int get_score() const { return history[current].score; }
Board &undo() {
if (undo_avail) {
--undo_avail;
++redo_avail;
current = (current + MAX_UNDO - 1) % MAX_UNDO;
}
return history[current].board;
}
Board &redo() {
if (redo_avail) {
--redo_avail;
++undo_avail;
current = (current + 1) % MAX_UNDO;
}
return history[current].board;
}
void move(int dir, AnimState &anim) {
HistoryState next = history[current];
bool moved = next.move(dir, &anim);
if (moved) {
current = (current + 1) % MAX_UNDO;
history[current] = next;
if (undo_avail < MAX_UNDO) { ++undo_avail; }
redo_avail = 0;
}
}
};
static uint64_t pack_board_state(const Board &board) {
uint64_t k = 0u;
assert(NUM_TILES == 16);
for (int i = 0; i < NUM_TILES; ++i) {
assert(board.state[i] < 16);
k = (k << 4) | board.state[i];
}
return k;
}
#if 0 // unused
static void unpack_board_state(Board &board, const uint64_t state) {
assert(NUM_TILES == 16);
uint64_t k = state;
for (int i = 0; i < 16; ++i) {
board.state[15 - i] = (k & 0x0F);
k >>= 4;
}
}
#endif
static uint64_t mix64(uint64_t key) {
// from: https://gist.github.com/badboy/6267743
key = (~key) + (key << 21); // key = (key << 21) - key - 1;
key = key ^ (key >> 24);
key = key * 265;
key = key ^ (key >> 14);
key = key * 21;
key = key ^ (key >> 28);
key = key + (key << 31);
return key;
}
#if CRAZY_VERBOSE_CACHE_DEBUGGER
template <typename T>
void print_blob(const T &v) {
uint8_t buf[sizeof(T)];
memcpy(buf, &v, sizeof(T));
for (int i = 0; i < sizeof(T); ++i) { printf("%02x", buf[i]); }
}
#endif
template <typename T>
class BoardCache {
enum {
ENTRY_COUNT = (1 << 15),
BUCKET_SIZE = 8,
BUCKET_COUNT = ENTRY_COUNT / BUCKET_SIZE,
BUCKET_INDEX_MASK = (BUCKET_COUNT - 1)
};
struct Bucket {
uint64_t keys[BUCKET_SIZE];
T values[BUCKET_SIZE];
};
const T *bucket_get(const Bucket &bucket, const uint64_t k) const {
for (int i = 0; i < BUCKET_SIZE; ++i) {
if (bucket.keys[i] == k) { return &bucket.values[i]; }
}
return 0;
}
#if USE_CACHE_VERIFICATION_MAP
typedef std::map<uint64_t, T> MapT;
typedef typename MapT::iterator MapIterT;
typedef typename MapT::value_type MapValueT;
#endif
public:
BoardCache(): m_buckets(0) {
m_buckets = static_cast<Bucket*>(calloc(BUCKET_COUNT, sizeof(Bucket)));
}
~BoardCache() {
free(m_buckets);
}
void reset() {
memset(m_buckets, 0, BUCKET_COUNT * sizeof(Bucket));
}
void *where(const Board &board) { return where(pack_board_state(board)); }
const void *where(const Board &board) const { return where(pack_board_state(board)); }
void *where(const uint64_t k) {
const uint64_t h = mix64(k);
return static_cast<void*>(&m_buckets[h & BUCKET_INDEX_MASK]);
}
const void *where(const uint64_t k) const {
const uint64_t h = mix64(k);
return static_cast<const void*>(&m_buckets[h & BUCKET_INDEX_MASK]);
}
const T *get(const uint64_t k, const void *where) const {
assert(k);
assert(where);
const Bucket &bucket = *static_cast<const Bucket*>(where);
for (int i = 0; i < BUCKET_SIZE; ++i) {
if (bucket.keys[i] == k) {
#if CRAZY_VERBOSE_CACHE_DEBUGGER
printf("%016lx: get (found) ", k);
print_blob(bucket.values[i]);
printf(" : ");
print_blob(m_verifier.find(k)->second);
printf("\n");
#endif
#if USE_CACHE_VERIFICATION_MAP
assert(m_verifier.count(k));
assert(memcmp(&m_verifier.find(k)->second, &bucket.values[i], sizeof(T)) == 0);
#endif
return &bucket.values[i];
}
}
#if CRAZY_VERBOSE_CACHE_DEBUGGER
printf("%016lx: get (not found)\n", k);
#endif
//assert(m_verifier.count(k) == 0); // not actually necessarily true
return 0;
}
void put(const uint64_t k, void *where, const T &value) {
assert(k);
assert(where);
Bucket &bucket = *static_cast<Bucket*>(where);
for (int i = 0; i < BUCKET_SIZE; ++i) {
if (bucket.keys[i] == k) {
#if CRAZY_VERBOSE_CACHE_DEBUGGER
printf("%016lx: replace ", k);
print_blob(bucket.values[i]);
printf(" : ");
print_blob(m_verifier.find(k)->second);
printf("\n");
#endif
#if USE_CACHE_VERIFICATION_MAP
assert(m_verifier.count(k));
assert(memcmp(&m_verifier.find(k)->second, &bucket.values[i], sizeof(T)) == 0);
m_verifier[k] = value;
#endif
bucket.values[i] = value;
return;
}
}
#if CRAZY_VERBOSE_CACHE_DEBUGGER
printf("%016lx: put (new)\n", k);
#endif
//assert(m_verifier.count(k) == 0); // not actually necessarily true
for (int i = BUCKET_SIZE-1; i > 0; --i) {
bucket.keys[i] = bucket.keys[i-1];
bucket.values[i] = bucket.values[i-1];
}
bucket.keys[0] = k;
bucket.values[0] = value;
#if USE_CACHE_VERIFICATION_MAP
m_verifier[k] = value;
#endif
}
const T *get(const Board &board) const {
const uint64_t k = pack_board_state(board);
return get(k, where(k));
}
void put(const Board &board, const T &value) {
const uint64_t k = pack_board_state(board);
put(k, where(k), value);
}
private:
Bucket *m_buckets;
#if USE_CACHE_VERIFICATION_MAP
MapT m_verifier;
#endif
};
typedef int (*Evaluator)(const Board &board);
class Searcher {
public:
Searcher(): evalfn(0), num_moves(0), best_first_move(-1) {
m_cancelled._nonatomic = 0;
}
void cancel() {
mint_store_32_relaxed(&m_cancelled, 1);
}
int search(Evaluator evalfn, const Board &board, const RNG &rng, int lookahead) {
assert(evalfn);
this->evalfn = evalfn;
this->num_moves = 0;
this->best_first_move = -1;
this->m_cancelled._nonatomic = 0;
int move;
int score = do_search(board, rng, lookahead, &move);
if (this->m_cancelled._nonatomic) { return INT_MIN; }
this->best_first_move = move;
return score;
}
int get_num_moves() const { return num_moves; }
int get_best_first_move() const { return best_first_move; }
protected:
int eval_board(const Board &board) { return evalfn(board); }
void tally_move() { ++num_moves; }
bool cancelled() { return (mint_load_32_relaxed(&m_cancelled) != 0); }
private:
Evaluator evalfn;
int num_moves;
int best_first_move;
mint_atomic32_t m_cancelled;
virtual int do_search(const Board &board, const RNG &rng, int lookahead, int *move) = 0;
};
class SearcherCheat : public Searcher {
private:
int do_search_real(const Board &board, const RNG &rng, int lookahead, int *move) {
if (move) { *move = -1; }
if (lookahead == 0) {
if (cancelled()) { return INT_MIN; }
return eval_board(board);
}
Board next_state;
RNG next_rng;
int best_score = INT_MIN;
for (int i = 0; i < 4; ++i) {
next_state = board;
next_rng = rng;
if (!next_state.move(i, 0, next_rng, 0)) { continue; } // ignore null moves
tally_move();
int score = do_search_real(next_state, next_rng, lookahead - 1, 0);
if (cancelled()) { return INT_MIN; }
if (score > best_score) {
best_score = score;
if (move) { *move = i; }
}
}
return best_score;
}
virtual int do_search(const Board &board, const RNG &rng, int lookahead, int *move) {
assert(lookahead >= 0);
return do_search_real(board, rng, lookahead, move);
}
};
class SearcherNaiveMinimax : public Searcher {
private:
int do_search_real(const Board &board, int lookahead, int *move) {
if (move) { *move = -1; }
if (lookahead == 0) {
if (cancelled()) { return INT_MIN; }
return eval_board(board);
}
int best_score;
Board next_state;
if (lookahead & 1) {
// minimise
best_score = INT_MAX;
for (int i = 0; i < NUM_TILES; ++i) {
if (board.state[i]) { continue; } // can only place tiles in empty cells
for (int value = 1; value < 3; ++value) {
next_state = board;
next_state.state[i] = value;
int score = do_search_real(next_state, lookahead - 1, 0);
if (cancelled()) { return INT_MIN; }
if (score < best_score) {
best_score = score;
}
}
}
} else {
// maximise
best_score = INT_MIN;
for (int i = 0; i < 4; ++i) {
next_state = board;
if (!next_state.tilt(DIR_DX[i], DIR_DY[i])) { continue; } // ignore null moves
tally_move();
int score = do_search_real(next_state, lookahead - 1, 0);
if (cancelled()) { return INT_MIN; }
if (score > best_score) {
best_score = score;
if (move) { *move = i; }
}
}
}
return best_score;
}
virtual int do_search(const Board &board, const RNG& /*rng*/, int lookahead, int *move) {
assert(lookahead >= 0);
return do_search_real(board, lookahead*2, move);
}
};
class SearcherAlphaBeta : public Searcher {
private:
int num_pruned;
int do_search_mini(const Board &board, int alpha, int beta, int lookahead) {
Board next_state;
for (int i = 0; i < NUM_TILES; ++i) {
if (board.state[i]) { continue; } // can only place tiles in empty cells
for (int value = 1; value < 3; ++value) {
next_state = board;
next_state.state[i] = value;
beta = min(beta, do_search_maxi(next_state, alpha, beta, lookahead - 1, 0));
if (cancelled()) { return INT_MAX; }
if (alpha >= beta) { ++num_pruned; return beta; }
}
}
return beta;
}
int do_search_maxi(const Board &board, int alpha, int beta, int lookahead, int *move) {
if (move) { *move = -1; }
if (lookahead == 0) {
if (cancelled()) { return INT_MIN; }
return eval_board(board);
}
// final score must be *at least* alpha and *at most* beta
// alpha <= score <= beta
Board next_state;
for (int i = 0; i < 4; ++i) {
next_state = board;
if (!next_state.tilt(DIR_DX[i], DIR_DY[i])) { continue; } // ignore null moves
tally_move();
int score = do_search_mini(next_state, alpha, beta, lookahead - 1);
if (cancelled()) { return INT_MIN; }
if (score > alpha) {
alpha = score;
if (move) { *move = i; }
}
if (alpha >= beta) { ++num_pruned; return alpha; }
}
return alpha;
}
virtual int do_search(const Board &board, const RNG& /*rng*/, int lookahead, int *move) {
assert(lookahead >= 0);
num_pruned = 0;
int score = do_search_maxi(board, INT_MIN, INT_MAX, lookahead*2, move);
#if PRINT_CACHE_STATS
printf("(alpha-beta) alpha-beta pruned %d\n", num_pruned);
#endif
return score;
}
};
class SearcherCachingMinimax : public Searcher {
private:
struct Info { static const Info NIL; int lookahead; int score; };
BoardCache<Info> cache;
enum { STAT_DEPTH = 20 };
int num_cached[STAT_DEPTH];
void tally_cache_hit(int lookahead) {
++num_cached[min(lookahead, STAT_DEPTH - 1)];
}
int do_search_real(const Board &board, int lookahead, int *move) {
if (move) { *move = -1; }
const uint64_t board_k = pack_board_state(board);
void *cache_loc = cache.where(board_k);
const Info *cached = cache.get(board_k, cache_loc);
if (cached && cached->lookahead == lookahead) {
tally_cache_hit(lookahead);
return cached->score;
}
int best_score;
if (lookahead == 0) {
if (cancelled()) { return INT_MIN; }
best_score = eval_board(board);
} else {
Board next_state;
if (lookahead & 1) {
// minimise
best_score = INT_MAX;
for (int i = 0; i < NUM_TILES; ++i) {
if (board.state[i]) { continue; } // can only place tiles in empty cells
for (int value = 1; value < 3; ++value) {
next_state = board;
next_state.state[i] = value;
int score = do_search_real(next_state, lookahead - 1, 0);
if (cancelled()) { return INT_MAX; }
if (score < best_score) {
best_score = score;
}
}
}
} else {
// maximise
best_score = INT_MIN;
for (int i = 0; i < 4; ++i) {
next_state = board;
if (!next_state.tilt(DIR_DX[i], DIR_DY[i])) { continue; } // ignore null moves
tally_move();
int score = do_search_real(next_state, lookahead - 1, 0);
if (cancelled()) { return INT_MIN; }
if (score > best_score) {
best_score = score;
if (move) { *move = i; }
}
}
}
}
const Info new_cached = { lookahead, best_score };
cache.put(board_k, cache_loc, new_cached);
return best_score;
}
virtual int do_search(const Board &board, const RNG& /*rng*/, int lookahead, int *move) {
assert(lookahead >= 0);
memset(num_cached, 0, sizeof(num_cached));
cache.reset();
int score = do_search_real(board, lookahead*2, move);
#if PRINT_CACHE_STATS
printf("(caching-minimax) cache hits:");
for (int i = 0; i < min(lookahead*2, STAT_DEPTH); ++i) { printf(" %d", num_cached[i]); }
printf("\n");
#endif
return score;
}
};
const SearcherCachingMinimax::Info SearcherCachingMinimax::Info::NIL = { -1, INT_MIN };
class SearcherCachingAlphaBeta : public Searcher {
private:
enum { SCORE_UNKNOWN, SCORE_EXACT, SCORE_LOWER_BOUND, SCORE_UPPER_BOUND };
struct Info { static const Info NIL; int16_t lookahead; int16_t type; int score; };
BoardCache<Info> cache;
enum { STAT_DEPTH = 20 };
int num_cached[STAT_DEPTH];
int num_pruned;
void tally_cache_hit(int lookahead) {
++num_cached[min(lookahead, STAT_DEPTH - 1)];
}
bool check_cached(const Info * const cached, int alpha, int beta, int lookahead, int &output) {
bool cache_valid = false;
if (cached && cached->lookahead == lookahead) {
switch (cached->type) {
case SCORE_EXACT: cache_valid = true; break;
case SCORE_UPPER_BOUND: cache_valid = (cached->score <= alpha); break;
case SCORE_LOWER_BOUND: cache_valid = (cached->score >= beta); break;
}
}
if (cache_valid) {
tally_cache_hit(lookahead);
output = cached->score;
}
return cache_valid;
}