-
Notifications
You must be signed in to change notification settings - Fork 2
/
Algorithm.cpp
executable file
·550 lines (500 loc) · 11 KB
/
Algorithm.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
#include "Algorithm.h"
#include "GameState.h"
#include "Player.h"
#include <time.h>
#include <assert.h>
#include "Timer.h"
namespace hearts {
static void my_nothing_error(const char *fmt, ...) {}
//#define LOG if (1) printf
//#define LOG /*if (VERBOSE)*/ printf
#define LOG my_nothing_error
//const bool logNodes = true;
Algorithm::Algorithm()
{
useDEPTHLIMIT = false;
useNODELIMIT = false;
useTIMELIMIT = false;
useTHREADS = false;
useAFTERSTATES = false;
SEARCHNODELIMIT = uINF;
SEARCHTIMELIMIT = kMaxTimeLimit;
SEARCHDEPTHLIMIT = uINF;
BFLIMIT = uINF;
USEHASH = false;
VERIFYHASH = false;
VERBOSE = false;
SAVE = false;
PRUNING = true;
randomize = false;
ht = 0;
searchDepth = 0;
prevBest = 0;
returnValueList = 0;
totalNodesExpanded = 0;
rand.srand(time((time_t*)0));
}
Algorithm::Algorithm(const Algorithm& a)
{
// printf("Called algorithm copy constructor\n");
who = 0; prevBest = 0;
returnValueList = 0;
iterDepth = a.iterDepth;
USEHASH = a.USEHASH;
VERIFYHASH = a.VERIFYHASH;
if (USEHASH)
ht = new HashTable(49979693);//452930477);//1257787);//131071
else
ht = 0;
searchDepth = a.searchDepth;
totalMoves = a.totalMoves; // the depth when we start our search
nodesExpanded = a.nodesExpanded;
totalNodesExpanded = a.totalNodesExpanded;
useDEPTHLIMIT = a.useDEPTHLIMIT;
useNODELIMIT = a.useNODELIMIT;
useTIMELIMIT = a.useTIMELIMIT;
useTHREADS = a.useTHREADS;
useAFTERSTATES = a.useAFTERSTATES;
SEARCHDEPTHLIMIT = a.SEARCHDEPTHLIMIT;
startDepth = a.startDepth;
SEARCHTIMELIMIT = a.SEARCHTIMELIMIT;
SEARCHNODELIMIT = a.SEARCHNODELIMIT;
BFLIMIT = a.BFLIMIT;
VERBOSE = a.VERBOSE;
PRUNING = a.PRUNING;
t1 = a.t1;
t2 = a.t2;
}
Algorithm::~Algorithm()
{
delete ht;
delete prevBest;
while (returnValueList)
{
returnValue *tmp = returnValueList;
returnValueList = returnValueList->next;
tmp->next = 0;
delete tmp;
}
}
returnValue *Algorithm::Play(GameState *g, Player *p)
{
int val;
returnValue *currMove=0, *oldMove=0;
who = p;
std::vector<int> iterationNodes;
int cp=-1;
for (unsigned int x = 0; x < g->getNumPlayers(); x++) {
if (g->getPlayer(x) == p)
cp = x;
}
//assert(cp != -1);
// if I'm not part of the game, I can play on behalf of that player?
if (cp == -1)
cp = g->getNextPlayerNum();
val = setupNextIteration(g, p);
LOG("Starting at depth %d, %d\n", iterDepth, val);
printf("depth %2d: ", iterDepth);
while (!searchExpired(g))
{
Timer t;
t.StartTimer();
currMove = DispatchSearch(0, cp, g);
t.EndTimer();
printf("%6.1f seconds elapsed %10lu nodes expanded\t", t.GetElapsedTime(), getNodesExpanded());
if (currMove)
{
LOG("Done\n");
//printf("%1.2f}\t ", currMove->getValue(g->getPlayerNum(who)));
currMove->Print(1);
if (searchExpired(g))
{
delete currMove;
break;
}
if (oldMove != 0)
{
delete oldMove;
}
oldMove = currMove;
currMove = 0;
}
val = setupNextIteration(g, p);
printf("depth %2d: ", val);
fflush(stdout);
if ((unsigned int)iterDepth > p->getMaxDepth())
{
LOG("Stopping because of max depth\n");
break;
}
// lets stop if we expect our next iteration
// to put us over the top
if (useNODELIMIT && getNodesExpanded()*4 > SEARCHNODELIMIT)
{
printf("Special: Stopping because nodes is rapidly approaching search limit\n");
break;
}
iterationNodes.push_back(getNodesExpanded());
int lastArrayIndex = iterationNodes.size()-1;
if ((iterationNodes.size() > 2) &&
((iterationNodes[lastArrayIndex] - iterationNodes[lastArrayIndex-1]) ==
(iterationNodes[lastArrayIndex-1] - iterationNodes[lastArrayIndex-2])))
{
printf("Special: Stopping because not making any progress\n");
break;
}
}
if ((oldMove == 0) || (oldMove->m == 0))
{
Move *m = getMoves(g, g->getPlayer(cp));
delete m->next;
m->next = 0;
delete oldMove;
oldMove = new returnValue(m);
}
LOG("%ld nodes expanded\n", getNodesExpanded());
return oldMove;
}
returnValue *Algorithm::Analyze(GameState *g, Player *p)
{
who = p;
returnValue *currMove=0, *oldMove=0;
int val;
int cp=0, np = g->getNumPlayers();
for (int x = 0; x < np; x++) {
if (g->getPlayer(x) == p)
cp = x;
}
val = setupNextIteration(g, p);
if (searchExpired(g))
LOG("Hey, search already expired!\n");
LOG("Starting at depth %d, %d\n", iterDepth, val);
while (!searchExpired(g))
{
LOG("Searching %s depth %d, %d\n", getName(), iterDepth, val);
currMove = analyzeHelper(0, cp, g);
//currMove = analyzeHelper(0, np, cp, op, g, 0, 0);
if (currMove)
{
//currMove->Print(1);
if (searchExpired(g))
{
if (oldMove == 0)
LOG("Search Expired, and we have no other moves!\n");
delete currMove;
break;
}
if (oldMove != 0)
{
delete oldMove;
}
oldMove = currMove;
currMove = 0;
}
if ((unsigned int)iterDepth > p->getMaxDepth())
break;
if (getNodesExpanded()*3 > SEARCHNODELIMIT)
break;
val = setupNextIteration(g, p);
}
if ((oldMove == 0) || (oldMove->m == 0))
{
Move *m = getMoves(g, g->getPlayer(cp));
delete m->next;
m->next = 0;
delete oldMove;
oldMove = new returnValue(m);
}
return oldMove;
}
returnValue *Algorithm::analyzeHelper(unsigned int depth, unsigned int cp, GameState *g)
{
returnValue *tmp, *answer=0;
Move *m, *t;
t = m = getMoves(g, g->getPlayer(cp));
while (t) {
m = t;
ApplyMove(g, m);
tmp = DispatchSearch(depth+1, g->getNextPlayerNum(), g);
UndoMove(g, m);
if (tmp)
{
t = t->next; m->next = tmp->m; tmp->m = m;
tmp->next = answer;
answer = tmp;
tmp = 0;
}
else {
t = t->next;
m->next = 0;
delete m;
}
}
return answer;
}
void Algorithm::ApplyMove(GameState *g, Move *m)
{
nodesExpanded++;
totalNodesExpanded++;
searchDepth++;
g->ApplyMove(m);
}
void Algorithm::UndoMove(GameState *g, Move *m)
{
searchDepth--;
g->UndoMove(m);
}
void Algorithm::setUseHashTable(bool use)
{
USEHASH = use;
if ((ht == 0) && (use))
ht = new HashTable(49979693);//HashTable(1257787);//10037//131071
}
void Algorithm::setVerifyHashTable(bool verify)
{
VERIFYHASH = verify;
}
bool Algorithm::searchExpired(GameState *g)
{
if (g->Done())
{
LOG("Stopped because game's over\n");
return true;
}
if ((useAFTERSTATES && (g->getPreviousPlayer() == who)) || (!useAFTERSTATES))
{
if ((useDEPTHLIMIT) && (getCurrentSearchDepth() > SEARCHDEPTHLIMIT))
{
LOG("Stopped with current search depth %d\n", getCurrentSearchDepth());
return true;
}
}
if ((iterDepth != -1) && (getCurrentSearchDepth() >= (unsigned int)iterDepth))
{
LOG("Stopped with current search depth %d iter = %d\n", getCurrentSearchDepth(),iterDepth);
return true;
}
if ((useDEPTHLIMIT) && ((unsigned)iterDepth > SEARCHDEPTHLIMIT))
{
LOG("Stopped because iterDepth (%d) is bigger than limit (%d)\n", iterDepth, SEARCHDEPTHLIMIT);
return true;
}
if (timeExpired())
{
LOG("Time's up...we quit.\n");
return true;
}
if ((useNODELIMIT) && (nodesExpanded >= SEARCHNODELIMIT))
{
LOG("Stopped with %ld nodes expanded\n", nodesExpanded);
return true;
}
return false;
}
Move *Algorithm::getRandomMove(GameState *g)
{
return g->getRandomMove();
}
Move *Algorithm::getMoves(GameState *g, Player *p)
{
Move holder;
Move *t, *m = g->getMoves();
unsigned int count = 0;
if (m->next != 0)
{
while (m)
{
assert(m->player == g->getPlayerNum(p));
Move *tmp = m->next;
m->next = 0;
if (randomize)
m->dist = rand.rand_long();
else
m->dist = p->rankMove(m, g);
holder.insert(m);
count++;
m = tmp;
}
m = holder.next;
holder.next = 0;
}
t = m;
if (count <= BFLIMIT)
return m;
for (unsigned int x = 0; t && (x < BFLIMIT-1) && (t->next); x++, t = t->next)
{
//LOG("Keeping d=%d\n", t->dist);
}
while (t->next)
{
Move *tmp = t->next;
t->next = tmp->next;
tmp->next = 0;
//LOG("Dropping d=%d\n", tmp->dist);
g->freeMove(tmp);
//delete tmp;
/*
delete t->next;
t->next = 0;*/
}
// LOG("Length is %d\n", m->length());
return m;
}
int Algorithm::setupNextIteration(GameState *g, Player *p)
{
if ((iterDepth != -1) && (!useTHREADS))
{
if (1)
{
logNodes();
}
}
searchDepth = 0;
iterDepth = p->getNextDepth(iterDepth);
clearHashTable(g);
return iterDepth;
}
void Algorithm::logNodes()
{
FILE *t = fopen("nodes.out", "a+");
if (t)
{
fprintf(t, "%s\t%d\t%ld\n", getName(), iterDepth, nodesExpanded);
fclose(t);
}
}
int Algorithm::getIterationSearchLimit()
{
return iterDepth;
}
void Algorithm::setSearchDepthLimit(int val)
{
useDEPTHLIMIT = true;
SEARCHDEPTHLIMIT = val;
}
void Algorithm::setSearchTimeLimit(double val)
{
useTIMELIMIT = true;
SEARCHTIMELIMIT = val;
}
void Algorithm::setSearchNodeLimit(unsigned long val)
{
useNODELIMIT = true;
SEARCHNODELIMIT = val;
}
void Algorithm::setBranchingFactorLimit(unsigned long val)
{
BFLIMIT = val;
}
void Algorithm::clearHashTable(GameState *g)
{
if (ht)
{
//ht->PrintStats();
ht->iterReset();
while (!ht->iterDone())
{
HashState *hs = (HashState*)ht->iterNext();
if ((hs->ret) && (hs->ret->m))
{
delete hs->ret->m;
//g->freeMove(hs->ret->m);
hs->ret->m = 0;
}
}
ht->Clear();
}
}
const HashState *Algorithm::checkHashTable(HashState *s)
{
const HashState *st;
if (s == 0)
return 0;
if (ht == 0)
return 0;
if ((st = (HashState*)ht->IsIn(s)) != 0)
return st;//st->ret->clone();
return 0;
}
void Algorithm::addHashTable(HashState *s, returnValue *r)
{
//HashState *st=0;
if ((s == 0) || (ht == 0))
{
// dangerous because these points still exist in calling function...
delete s;
s = 0;
delete r;
r = 0;
return;
}
/*
st = ht->IsIn(s); // eliminate this check to speed things up
if (st)
{
printf("Trying to add something already in there!!!\n");
exit(0);
}
*/
if (s->ret != 0)
{
printf("Trying to add a return value where I shouldn't...\n");
exit(0);
}
s->ret = r;
ht->Add(s);
}
HashState *Algorithm::getHashState(GameState *g, HashState *mem)
{
if (getCurrentSearchDepth() > (unsigned int)iterDepth-2*g->getNumPlayers())
return 0;
if (getCurrentSearchDepth() < 2*g->getNumPlayers())
return 0;
if (ht && ht->getNumElts() > 2000000)
return 0;
return g->getHashState(mem);
}
void Algorithm::resetCounters(GameState *g)
{
nodesExpanded = 0;
//totalMoves = g->getDepth();
searchDepth = 0;
iterDepth = -1;
delete prevBest;
prevBest = 0;
clearHashTable(g);
// this should probably be before we clear the hash table, but not right now.
t1 = ((double)clock()/CLOCKS_PER_SEC);
}
bool Algorithm::timeExpired()
{
return (useTIMELIMIT)&&(timeElapsed() > SEARCHTIMELIMIT);
}
void Algorithm::setReturnValueType(returnValue *v)
{
delete returnValueList;
returnValueList = v;
v->next = 0;
}
returnValue *Algorithm::getNewReturnValue(GameState *g)
{
if (returnValueList->next == 0)
return returnValueList->clone(g);
returnValue *t = returnValueList;
returnValueList = returnValueList->next;
t->next = 0;
t->m = 0;
return t;
}
void Algorithm::freeReturnValue(returnValue *v)
{
if (v)
{
returnValue *trav;
for (trav = v; trav->next; trav = trav->next)
{ }
trav->next = returnValueList;
returnValueList = v;
}
}
} // namespace hearts