-
Notifications
You must be signed in to change notification settings - Fork 1
/
searchPlayer.xc
546 lines (512 loc) · 18.1 KB
/
searchPlayer.xc
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
#include <state.xh>
#include <driver.xh>
#include <players.xh>
#include <prolog_utils.xh>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <assert.h>
#include <time.h>
#include <pthread.h>
#ifdef DEBUG
#define TIMEOUT 5
#else
#define TIMEOUT 15
#endif
#define PLAYOUT_DEPTH 10
//#define PRINT_UNEXPANDED
void printGameTree(GameTree tree, unsigned depth) {
#ifndef PRINT_UNEXPANDED
if (tree.status.tag != NodeStatus_Unexpanded)
#endif
printf("%s", (str(" ") * depth).text);
char *parentAction = match (tree.parent)
(!NULL@&{.status=ExpandedBurn(_)} -> "burn *";
!NULL@_ -> (char *)showAction(tree.action, PLAYER_ID_NONE, PLAYER_ID_NONE).text;
_ -> "";);
match (tree) {
{.status=Expanded(children, trials, wins), .parent=parent} -> {
printf("%d", trials);
match (parent) {
!NULL@&{{parentPlayer}} -> {
printf(" %f", wins[parentPlayer] / trials);
}
}
if (depth > 0) {
printf(" : %s", parentAction);
}
printf(" %s\n", show(tree.turn).text);
for (unsigned i = 0; i < children.size; i++) {
printGameTree(children[i], depth + 1);
}
}
{.status=ExpandedBurn(&child)} -> {
printf("?");
if (depth > 0) {
printf(" : %s", parentAction);
}
printf("\n");
printGameTree(child, depth + 1);
}
{.status=Unexpanded()} -> {
#ifdef PRINT_UNEXPANDED
printf("0 : %s\n", parentAction);
#endif
}
{.status=Leaf(winner), .state=St(?&numPlayers, ?&partners, _, _), .parent=parent} -> {
match (parent) {
!NULL@&{{parentPlayer}} -> {
printf("leaf %d", winner == parentPlayer || (partners && winner == partner(numPlayers, parentPlayer)));
}
}
if (depth > 0) {
printf(" : %s", parentAction);
}
printf("\n");
}
}
}
vector<float> heuristicScore(State s) {
match (s) {
St(?&numPlayers, ?&partners, _, _) -> {
vector<float> scores = new vector<float>(numPlayers, 0);
if (isWon(s)) {
PlayerId winner = getWinner(s);
scores[winner] = 1;
if (partners) {
scores[partner(numPlayers, winner)] = 1;
}
} else {
unsigned totalScore = 0;
for (PlayerId p1 = 0; p1 < numPlayers; p1++) {
unsigned score = getPlayerHeuristicValue(s, p1);
totalScore += score;
scores[p1] += score;
if (partners) {
scores[partner(numPlayers, p1)] += score;
}
}
if (totalScore > 0) {
for (PlayerId p1 = 0; p1 < numPlayers; p1++) {
scores[p1] /= totalScore;
}
}
}
return scores;
}
}
}
vector<float> playout(State s, PlayerId p, unsigned depth) {
if (depth == 0 || isWon(s)) {
return heuristicScore(s);
} else {
Card c = rand() % CARD_MAX;
Hand h = {0};
h[c] = 1;
vector<Action> actions = getActions(s, p, h);
Action a = actions[rand() % actions.size];
vector<float> result[1];
bool success = query S1 is s, MS is (getActionMoves(a)), moves(S1, MS, S2) {
*result = playout(value(S2), (p + 1) % numPlayers(s), depth - 1);
};
assert(success);
return *result;
}
}
vector<float> playoutHand(State s, PlayerId p, Hand hands[], unsigned depth) {
if (depth == 0 || isWon(s)) {
return heuristicScore(s);
} else {
vector<Action> actions = getActions(s, p, hands[p]);
if (actions.size) {
Action a = actions[rand() % actions.size];
Card c = getActionCard(a);
hands[p][c]--;
vector<float> result[1];
bool success = query S1 is s, MS is (getActionMoves(a)), moves(S1, MS, S2) {
*result = playoutHand(value(S2), (p + 1) % numPlayers(s), hands, depth - 1);
};
assert(success);
return *result;
} else {
return playout(s, p, depth);
}
}
}
vector<float> rulePlayout(State s, PlayerId p, unsigned depth) {
if (depth == 0 || isWon(s)) {
return heuristicScore(s);
} else {
Card c = rand() % CARD_MAX;
Hand h = {0};
h[c] = 1;
vector<Action> actions = getActions(s, p, h);
Action a = actions[makeRulePlayer().getAction(s, h, NULL, NULL, NULL, (TurnInfo){p}, actions)];
vector<float> result[1];
bool success = query S1 is s, MS is (getActionMoves(a)), moves(S1, MS, S2) {
*result = rulePlayout(value(S2), (p + 1) % numPlayers(s), depth - 1);
};
assert(success);
return *result;
}
}
vector<float> rulePlayoutHand(State s, PlayerId p, Hand hands[], unsigned depth) {
if (depth == 0 || isWon(s)) {
return heuristicScore(s);
} else {
vector<Action> actions = getActions(s, p, hands[p]);
if (actions.size) {
Action a = actions[makeRulePlayer().getAction(s, hands[p], hands, NULL, NULL, (TurnInfo){p}, actions)];
Card c = getActionCard(a);
hands[p][c]--;
vector<float> result[1];
bool success = query S1 is s, MS is (getActionMoves(a)), moves(S1, MS, S2) {
*result = rulePlayoutHand(value(S2), (p + 1) % numPlayers(s), hands, depth - 1);
};
assert(success);
return *result;
} else {
return rulePlayout(s, p, depth);
}
}
}
void backpropagate(GameTree *t, vector<float> scores) {
match (t) {
!NULL@&{.status=status, .state=St(?&numPlayers, _, _, _), .parent=parent} -> {
match (status) {
Expanded(_, trials, wins) -> {
t->status.contents.Expanded.trials++;
for (PlayerId p = 0; p < numPlayers; p++) {
wins[p] += scores[p];
}
}
}
backpropagate(parent, scores);
}
}
}
GameTree expandedChild(GameTree t) {
return match (t.status)
(ExpandedBurn(&t1) -> expandedChild(t1);
_ -> t;);
}
float weight(GameTree *t) {
return match (expandedChild(*t).status, t->parent)
(Unexpanded(), _ -> INFINITY;
Expanded(_, trials, wins), &{.status=Expanded(_, parentTrials, _), .turn={p}} ->
(float)wins[p] / trials + sqrtf(2 * logf((float)parentTrials) / trials);
Leaf(winner), &{.turn={p}} ->
p == winner || (partners(t->state) && winner == partner(numPlayers(t->state), p)););
}
void expand(PlayoutFn playoutHand, unsigned depth, GameTree *t,
Hand possibleDeck, Hand deck, Hand possibleHands[], Hand hands[]) {
match (t) {
&{{p}, .state=St(?&numPlayers, _, _, _)} -> {
// Re-deal from deck if the hand is empty
if (getDeckSize(hands[p]) == 0) {
if (getDeckSize(deck) < numPlayers * MIN_HAND) {
initializeDeck(possibleDeck);
initializeDeck(deck);
}
for (PlayerId p = 0; p < numPlayers; p++) {
memcpy(possibleHands[p], possibleDeck, sizeof(Hand));
}
deal(MIN_HAND, MAX_HAND, deck, numPlayers, hands);
}
for (Card c = Joker; c < CARD_MAX; c++) {
assert(deck[c] <= possibleDeck[c]);
for (PlayerId p = 0; p < numPlayers; p++) {
assert(hands[p][c] <= possibleHands[p][c]);
}
}
}
}
match (t) {
&{turn@{p}, _, s@St(?&numPlayers, ?&partners, _, _), _, Unexpanded()} -> {
TurnInfo newTurn = nextTurn(turn, numPlayers, getDeckSize(hands[(p + 1) % numPlayers]) == 0, getDeckSize(deck) < numPlayers * MIN_HAND);
if (isWon(s)) {
t->status = Leaf(getWinner(s));
backpropagate(t, heuristicScore(s));
} else if (!actionPossible(s, p, possibleHands[p], partners? possibleHands[partner(numPlayers, p)] : NULL)) {
// All moves for the player will be burns, collapse children to a single node
GameTree *child = GC_malloc(sizeof(GameTree));
*child = (GameTree){newTurn, Burn(CARD_MAX), s, t, Unexpanded()};
t->status = ExpandedBurn(child);
// Play an arbitrary card and expand the child
for (Card c = 0; c < CARD_MAX; c++) {
if (hands[p][c]) {
hands[p][c]--;
break;
}
}
expand(playoutHand, depth, child, possibleDeck, deck, possibleHands, hands);
} else {
// Compute valid actions
vector<Action> actions = getActions(s, p, possibleHands[p]);
assert(actions.size > 0);
// Include actions for burning cards with no valid move
Hand included = {0};
for (unsigned i = 0; i < actions.size; i++) {
included[getActionCard(actions[i])] = 1;
}
for (Card c = 0; c < CARD_MAX; c++) {
if (possibleHands[p][c] && !included[c]) {
actions.append(Burn(c));
}
}
// Construct the children
vector<GameTree> children = new vector<GameTree>(actions.size);
for (unsigned i = 0; i < actions.size; i++) {
Action a = actions[i];
State newState = applyAction(a, s, NULL, NULL);
children[i] = (GameTree){newTurn, a, newState, t, Unexpanded()};
}
// Expand the node
vector<float> wins = new vector<float>(numPlayers, 0);
t->status = Expanded(children, 0, wins);
vector<float> scores = playoutHand(s, p, hands, depth);
backpropagate(t, scores);
}
}
&{{p}, .state=s, .status=ExpandedBurn(child)} -> {
// Play an arbitrary card and expand the child
for (Card c = 0; c < CARD_MAX; c++) {
if (hands[p][c]) {
hands[p][c]--;
break;
}
}
expand(playoutHand, depth, child, possibleDeck, deck, possibleHands, hands);
}
&{{p}, .state=s, .status=Expanded(children, trials, wins)} -> {
assert(children.size > 0);
#ifdef DEBUG
for (Card c = Joker; c < CARD_MAX; c++) {
if (hands[p][c] && getCardMoves(s, p, c).size > 0) {
bool inChildren = false;
for (unsigned i = 0; i < children.size; i++) {
inChildren |= getActionCard(children[i].action) == c;
}
assert(inChildren);
}
}
#endif
float maxWeight = -INFINITY;
GameTree *maxChild = NULL;
// Compute max weight child that corresponds to playing a card
for (unsigned i = 0; i < children.size; i++) {
GameTree *child = &children[i];
match (child->action) {
Play(c, _) @when (hands[p][c]) -> {
float w = weight(child);
if (w >= maxWeight) {
maxWeight = w;
maxChild = child;
}
}
}
}
if (maxChild == NULL) {
// If no valid children correspond to plays, then pick the max-weight burn child
for (unsigned i = 0; i < children.size; i++) {
GameTree *child = &children[i];
match (child->action) {
Burn(c) @when (hands[p][c]) -> {
float w = weight(child);
if (w >= maxWeight) {
maxWeight = w;
maxChild = child;
}
}
}
}
}
assert(maxChild != NULL);
Card c = getActionCard(maxChild->action);
assert(possibleHands[p][c]);
assert(hands[p][c]);
possibleHands[p][c]--;
hands[p][c]--;
expand(playoutHand, depth, maxChild, possibleDeck, deck, possibleHands, hands);
}
&{.state=s, .status=Leaf(_)} -> {
backpropagate(t, heuristicScore(s));
}
}
}
Player makeSearchPlayer(unsigned numPlayers, unsigned timeout, PlayoutFn playoutHand, unsigned depth) {
Hand *possibleHands = GC_malloc(sizeof(Hand[numPlayers]));
return (Player){"search", lambda (State s, const Hand h, const Hand hands[], const Hand discard, const unsigned handSizes[],
TurnInfo turn, vector<Action> actions) -> unsigned {
PlayerId p = turn.player;
#ifdef DEBUG
printf("%s\n", show(h).text);
#endif
// If there is only one possible action, choose it immediately
if (actions.size <= 1) {
return 0;
}
struct timespec start, finish;
clock_gettime(CLOCK_MONOTONIC, &start);
match (s) {
St(?&stateNumPlayers, ?&partners, board, _) -> {
assert(numPlayers == stateNumPlayers);
// If no moves will be possible with this hand, choose a random action immediately
if (!actionPossible(s, p, h, hands && partners? hands[partner(numPlayers, p)] : NULL)) {
return rand() % actions.size;
}
// Construct the deck of remaining cards that may be held by another player
Hand remaining;
initializeDeck(remaining);
for (Card c = 0; c < CARD_MAX; c++) {
remaining[c] -= discard[c];
if (hands) {
for (PlayerId p1 = 0; p1 < numPlayers; p1++) {
remaining[c] -= hands[p1][c];
}
} else {
remaining[c] -= h[c];
}
}
// Update the possible hands held by each player
if (turn.turnNum == 0) {
// This is the first turn in a hand, reset the possible hands
for (PlayerId p1 = 0; p1 < numPlayers; p1++) {
initializeDeck(possibleHands[p1]);
}
}
if (hands) {
// The possible hands are known exactly
memcpy(possibleHands, hands, sizeof(Hand[numPlayers]));
} else {
// Update the possible hands based on the remaining cards
for (Card c = 0; c < CARD_MAX; c++) {
for (PlayerId p1 = 0; p1 < numPlayers; p1++) {
if (p != p1 && possibleHands[p1][c] > remaining[c]) {
possibleHands[p1][c] = remaining[c];
}
}
}
memcpy(possibleHands[p], h, sizeof(Hand));
}
// Construct the initial children
TurnInfo newTurn =
nextTurn(turn, numPlayers, handSizes[(p + 1) % numPlayers] == 0,
DECK_SIZE - getDeckSize(discard) < numPlayers * MIN_HAND);
GameTree t;
vector<GameTree> children = new vector<GameTree>(actions.size);
for (unsigned i = 0; i < actions.size; i++) {
Action a = actions[i];
State newState = applyAction(a, s, NULL, NULL);
children[i] = (GameTree){
newTurn, a, newState, &t, Unexpanded()
};
}
t = (GameTree){turn, {0}, s, NULL, Expanded(children, 0, new vector<float>(numPlayers, 0))};
// Perform playouts
unsigned numPlayouts = 0;
do {
Hand trialPossibleDeck, trialDeck, trialPossibleHands[numPlayers], trialHands[numPlayers];
memcpy(trialPossibleDeck, remaining, sizeof(Hand));
bool validHands;
do {
initializeDeck(trialDeck);
for (Card c = 0; c < CARD_MAX; c++) {
trialDeck[c] -= discard[c];
}
validHands = true;
for (PlayerId p1 = 0; p1 < numPlayers; p1++) {
Hand possibleHand;
memcpy(possibleHand, possibleHands[p1], sizeof(Hand));
unsigned handSize = handSizes[p1];
unsigned dealt = deal(handSize, handSize, possibleHand, 1, trialHands + p1);
assert(dealt == handSize);
for (Card c = 0; c < CARD_MAX; c++) {
if (trialDeck[c] < trialHands[p1][c]) {
validHands = false;
break;
}
trialDeck[c] -= trialHands[p1][c];
}
if (!validHands) {
break;
}
memcpy(trialPossibleHands[p1], possibleHands[p1], sizeof(Hand));
}
} while (!validHands);
expand(playoutHand, depth, &t, trialPossibleDeck, trialDeck, trialPossibleHands, trialHands);
numPlayouts++;
clock_gettime(CLOCK_MONOTONIC, &finish);
pthread_testcancel(); // This is a long-running task, allow cancellation at this point
} while (finish.tv_sec - start.tv_sec < timeout);
#ifdef DEBUG
printf("Finished %d playouts\n", numPlayouts);
#endif
// Find the child with the highest ration of wins for p / trials
match (t) {
{.status=Expanded(children, trials, wins)} -> {
#ifdef DEBUG
printf("Win confidence: %f\n", (float)wins[p] / trials);
printGameTree(t, 0);
#endif
float maxScore = -INFINITY;
unsigned maxAction;
for (unsigned i = 0; i < actions.size; i++) {
float w = match (expandedChild(children[i]).status)
(Expanded(_, trials, wins) -> (float)wins[p] / trials;
Leaf(winner) -> winner == p || (partners && winner == partner(numPlayers, p));
Unexpanded() -> -INFINITY;);
if (w > maxScore) {
maxScore = w;
maxAction = i;
}
}
return maxAction;
}
_ -> { assert(false); }
}
}
_ -> { assert(false); }
}
}, lambda (State s, TurnInfo turn, Action action) -> void {
PlayerId p = turn.player;
if (turn.turnNum == 0) {
// This is the first turn in a hand, reset the possible hands
for (PlayerId p1 = 0; p1 < numPlayers; p1++) {
initializeDeck(possibleHands[p1]);
}
}
match (action) {
Burn(_) -> {
// Remove all cards from the player's hand that could have enabled a move
for (Card c = 0; c < CARD_MAX; c++) {
if (possibleHands[p][c] && getCardMoves(s, p, c).size > 0) {
possibleHands[p][c] = 0;
}
}
}
}
#ifdef DEBUG
printf("\nPossible hands\n");
for (PlayerId p = 0; p < numPlayers; p++) {
printf("Player %d: %s\n", p, show(possibleHands[p]).text);
}
#endif
}
};
}
Player makeHeuristicSearchPlayer(unsigned numPlayers) {
Player result = makeSearchPlayer(numPlayers, TIMEOUT, playoutHand, PLAYOUT_DEPTH);
result.name = "search";
return result;
}
Player makeDeepSearchPlayer(unsigned numPlayers) {
Player result = makeSearchPlayer(numPlayers, TIMEOUT, playoutHand, 15);
result.name = "deep_search";
return result;
}
Player makeRuleSearchPlayer(unsigned numPlayers) {
Player result = makeSearchPlayer(numPlayers, TIMEOUT, rulePlayoutHand, PLAYOUT_DEPTH);
result.name = "rule_search";
return result;
}