mcts_private_impl.h 32.1 KB
Newer Older
1
2
/* tarot implements the rules of the tarot game
 * Copyright (C) 2018, 2019  Vivien Kraus
Vivien Kraus's avatar
Vivien Kraus committed
3
 *
4
5
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation, version 3 of the License.
Vivien Kraus's avatar
Vivien Kraus committed
7
8
9
10
11
12
13
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
14
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
Vivien Kraus's avatar
Vivien Kraus committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 */

#include <config.h>
#include <tarot/mcts_private.h>
#include <tarot/simulation.h>
#include <tarot/counter_private.h>
#include <tarot/game_private.h>
#include <tarot/game_event_private.h>
#include <float.h>
#include <string.h>
#include <pool.h>

/* #define DEBUG_MCTS */

#ifdef DEBUG_MCTS
#define DEBUG fprintf
#else /* not DEBUG_MCS */
#define DEBUG(...)
#endif /* not DEBUG_MCTS */

Vivien Kraus's avatar
Vivien Kraus committed
35
36
37
38
39
#define TUNE_ITERATIONS 100
#define TUNE_PARAMETER 0.000828
#define TUNE_SIMULATION_RANDOM 0.000000
#define TUNE_SIMULATION_AGREED 0.781867

Vivien Kraus's avatar
Vivien Kraus committed
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
/* Add a few starting positions, or all of them if they are enumerable. */
static TarotMctsError mcts_setup_root (TarotMcts * mcts);

static inline size_t
mcts_construct (size_t max_mem, char *mem, size_t *alignment,
                size_t pool_size)
{
  size_t required = sizeof (TarotMcts) + pool_size;
  *alignment = alignof (TarotMcts);
  if (max_mem >= required)
    {
      TarotMcts *mcts = (TarotMcts *) mem;
      mcts->root = NULL;
      mcts->pool_tail = mem + sizeof (TarotMcts);
      mcts->pool_remaining = pool_size;
      mcts->pool_head = mem + sizeof (TarotMcts);
      mcts->tune_parameter = TUNE_PARAMETER;
      mcts->tune_simulation_random = TUNE_SIMULATION_RANDOM;
      mcts->tune_simulation_agreed = TUNE_SIMULATION_AGREED;
      game_initialize (&(mcts->base), 4, 0);
      return max_mem;
    }
  return required;
}

static inline void
mcts_copy (TarotMcts * dest, const TarotMcts * source)
{
  (void) dest;
  (void) source;
  fprintf (stderr, "%s:%d: Not implemented yet\n", __FILE__, __LINE__);
  assert (0);
}

static inline TarotMctsError
mcts_set_base (TarotMcts * mcts, const TarotGame * base)
{
  size_t freed = mcts->pool_head - mcts->pool_tail;
  assert (mcts->pool_head >= mcts->pool_tail);
  mcts->root = NULL;
  mcts->pool_remaining += freed;
  mcts->pool_head -= freed;
  assert (mcts->pool_head == mcts->pool_tail);
  game_copy (&(mcts->base), base);
  return mcts_setup_root (mcts);
}

static TarotMctsNode *mcts_select (TarotMcts * mcts, size_t n_simulations);

static int mcts_load (const TarotMcts * mcts, const TarotMctsNode * leaf,
                      TarotGame * game);

static int mcts_impute (TarotGame * game, struct yarrow256_ctx *rng);

static int mcts_next_move (const TarotGame * game, TarotGameEvent * event,
                           struct yarrow256_ctx *rng);

static int mcts_expand (TarotMcts * mcts, TarotMctsNode ** node,
                        const TarotGameEvent * event,
                        TarotPlayer next_player);

static void mcts_simulate (double simulation_random,
                           double simulation_agreed,
                           struct yarrow256_ctx *rng, TarotGame * game,
                           size_t n_players, int *score);

static void mcts_backpropagate (TarotMctsNode * node, TarotPlayer taker,
                                size_t n_players, const int *score);

static TarotMctsError
one_iteration (TarotMcts * mcts, size_t n_simulations,
               struct yarrow256_ctx *rng)
{
  TarotMctsNode *node;
  TarotGame game;
  int score[5];
  TarotGameEvent next;
  unsigned int next_buffer[78];
  TarotPlayer taker;
  next.data = next_buffer;
  game_initialize (&game, 4, 0);
  /* SELECT */
  node = mcts_select (mcts, n_simulations);
  DEBUG (stderr, "%s:%d: Select node %p\n", __FILE__, __LINE__, node);
  /* IMPUTE */
  if (mcts_load (mcts, node, &game) != 0)
    {
      DEBUG (stderr, "%s:%d: Could not load til then.\n", __FILE__, __LINE__);
      assert (0);
    }
  if (mcts_impute (&game, rng) != 0)
    {
      DEBUG (stderr, "%s:%d: Could not impute.\n", __FILE__, __LINE__);
      return TAROT_MCTS_OK;
    }
  /* EXPAND */
  if (game_step (&game) != TAROT_END)
    {
      TarotPlayer next_player = game_n_players (&game);
      int has_next = (game_get_next (&game, &next_player) == TAROT_GAME_OK);
      has_next = (game_get_next (&game, &next_player) == TAROT_GAME_OK);
      if (!has_next)
        {
          assert (game_step (&game) == TAROT_DOG);
          next_player = game_n_players (&game);
        }
      if (mcts_next_move (&game, &next, rng) != 0)
        {
          /* deal failed (petit sec) */
          DEBUG (stderr, "%s:%d: Could not select the next move\n",
                 __FILE__, __LINE__);
          return TAROT_MCTS_OK;
        }
      if (game_add_event (&game, &next) != 0)
        {
          DEBUG (stderr, "%s:%d: Could not add the next move\n", __FILE__,
                 __LINE__);
          assert (0);
        }
      DEBUG (stderr, "%s:%d: Expanding node %p\n", __FILE__, __LINE__, node);
      assert (node != NULL);
      if (mcts_expand (mcts, &node, &next, next_player) != 0)
        {
          /* No memory for child */
          DEBUG (stderr, "%s:%d: Could not expand\n", __FILE__, __LINE__);
          return TAROT_MCTS_NOMEM;
        }
      DEBUG (stderr, "%s:%d: Expanded to node %p\n", __FILE__, __LINE__,
             node);
    }
  /* SIMULATE */
  assert (game_n_players (&game) <= 5);
  mcts_simulate (mcts->tune_simulation_random, mcts->tune_simulation_agreed,
                 rng, &game, game_n_players (&game), score);
  DEBUG (stderr, "%s:%d: Backpropagate scores\n", __FILE__, __LINE__);
  /* BACKPROPAGATE */
  game_get_taker (&game, &taker);
  mcts_backpropagate (node, taker, game_n_players (&game), score);
  return TAROT_MCTS_OK;
}

static inline void
mcts_seed (TarotMcts * mcts, size_t seed_size, const void *seed)
{
  yarrow256_init (&(mcts->generator), 0, NULL);
  yarrow256_seed (&(mcts->generator), seed_size, seed);
}

static inline TarotMctsError
mcts_run (TarotMcts * mcts, size_t n_iterations)
{
  TarotMctsError ret = TAROT_MCTS_OK;
  size_t i;
  DEBUG (stderr, "Starting running the MCTS...\n");
  for (i = 0; i < n_iterations; i++)
    {
      TarotMctsError next;
      DEBUG (stderr, "MCTS %lu/%lu...\n", i, n_iterations);
      next = one_iteration (mcts, i, &(mcts->generator));
      if (next != TAROT_MCTS_OK && ret == TAROT_MCTS_OK)
        {
          ret = next;
        }
    }
  return ret;
}

static inline void
mcts_set_parameter (TarotMcts * mcts, double value)
{
  mcts->tune_parameter = value;
}

static inline double
mcts_get_parameter (const TarotMcts * mcts)
{
  return mcts->tune_parameter;
}

static inline void
mcts_set_simulation_random (TarotMcts * mcts, double value)
{
  mcts->tune_simulation_random = value;
}

static inline double
mcts_get_simulation_random (const TarotMcts * mcts)
{
  return mcts->tune_simulation_random;
}

static inline void
mcts_set_simulation_agreed (TarotMcts * mcts, double value)
{
  mcts->tune_simulation_agreed = value;
}

static inline double
mcts_get_simulation_agreed (const TarotMcts * mcts)
{
  return mcts->tune_simulation_agreed;
}

static inline size_t
mcts_default_iterations ()
{
  return TUNE_ITERATIONS;
}

static inline const TarotGameEvent *
mcts_get_best (const TarotMcts * mcts)
{
  const TarotMctsNode *root = mcts->root;
  const TarotMctsNode *best_event;
  double best_score;
  const TarotGameEvent *event;
  size_t n_simulations;
  int sum_scores;
  best_event = root;
  event = mcts_get (root, &n_simulations, &sum_scores);
  if (event == NULL)
    {
      return NULL;
    }
  best_score = sum_scores / (n_simulations + 0.0);
  for (root = mcts_next_sibling ((TarotMctsNode *) root);
       root != NULL; root = mcts_next_sibling ((TarotMctsNode *) root))
    {
      double score;
      event = mcts_get (root, &n_simulations, &sum_scores);
      score = sum_scores / (n_simulations + 0.0);
      if (score > best_score)
        {
          best_event = root;
        }
    }
  return mcts_get (best_event, &n_simulations, &sum_scores);
}

static double
compute_score (double tune_parameter, const TarotMctsNode * node,
               double n_simulations)
{
  if (node->n_simulations == 0)
    {
      /* This is an unexplored root! */
      return DBL_MAX;
    }
  else
    {
      double win_ratio = node->sum_scores / ((double) node->n_simulations);
      double exploration_ratio = 1 - (node->n_simulations / n_simulations);
      return win_ratio + tune_parameter * exploration_ratio;
    }
}

static void
search_best_select (double tune_parameter, const TarotMctsNode * node,
                    TarotMctsNode ** best, double n_simulations,
                    double *best_value)
{
  const TarotMctsNode *left = node->left;
  const TarotMctsNode *right = node->right;
  int left_ok = (left != NULL);
  int right_ok = (right != NULL);
  size_t this_n_simulations = n_simulations;
  double value;
  int sum_scores;
  const TarotGameEvent *event =
    mcts_get (node, &this_n_simulations, &sum_scores);
  if (event_type (event) != TAROT_DOG_EVENT)
    {
      value = compute_score (tune_parameter, node, n_simulations);
      if (value > *best_value)
        {
          *best_value = value;
          *best = (TarotMctsNode *) node;
        }
    }
  if (left_ok)
    {
      search_best_select (tune_parameter, left, best, this_n_simulations,
                          best_value);
    }
  if (right_ok)
    {
      search_best_select (tune_parameter, right, best, this_n_simulations,
                          best_value);
    }
}

static inline TarotMctsNode *
mcts_select (TarotMcts * mcts, size_t n_simulations)
{
  if (n_simulations != 0)
    {
      TarotMctsNode *best = mcts->root;
      double value_best = -DBL_MAX;
      search_best_select (mcts->tune_parameter, best, &best, n_simulations,
                          &value_best);
      return best;
    }
  return mcts->root;
}

static inline void
restrict_deal_all_event (const TarotGame * game, TarotGameEvent * event,
                         TarotPlayer who)
{
  size_t n_cards;
  TarotCard cards[78];
  if (game_get_deal_of (game, who, &n_cards, 0, 78, cards) != TAROT_GAME_OK)
    {
      assert (0);
    }
  event_set_deal (event, who, n_cards, cards);
}

static inline void
restrict_discard_event (const TarotGame * game, TarotGameEvent * event,
                        TarotPlayer who)
{
  size_t n_cards;
  TarotCard cards[78];
  TarotPlayer taker;
  int has_taker = (game_get_taker (game, &taker) == TAROT_GAME_OK);
  assert (has_taker);
  if (who == taker)
    {
      if (game_get_full_discard (game, &n_cards, 0, 78, cards) !=
          TAROT_GAME_OK)
        {
          assert (0);
        }
    }
  else
    {
      if (game_get_public_discard (game, &n_cards, 0, 78, cards) !=
          TAROT_GAME_OK)
        {
          assert (0);
        }
    }
  event_set_discard (event, n_cards, cards);
}

static int
mcts_load (const TarotMcts * mcts, const TarotMctsNode * leaf,
           TarotGame * game)
{
  DEBUG (stderr, "%s:%d: Load %p\n", __FILE__, __LINE__, leaf);
  if (leaf != NULL)
    {
      const TarotMctsNode *parent = mcts_parent ((TarotMctsNode *) leaf);
      size_t n_simulations;
      int sum_scores;
      const TarotGameEvent *event =
        mcts_get (leaf, &n_simulations, &sum_scores);
      DEBUG (stderr, "%s:%d: %p is the parent of %p\n", __FILE__, __LINE__,
             parent, leaf);
      if (mcts_load (mcts, parent, game) != 0)
        {
          return 1;
        }
      if (event == NULL)
        {
          DEBUG (stderr, "%s:%d: loading the root, no iterations yet\n",
                 __FILE__, __LINE__);
          return 0;
        }
      if (game_add_event (game, event) != TAROT_GAME_OK)
        {
          if (event_type (event) == TAROT_DISCARD_EVENT)
            {
              /* We have to try with only the trumps, since we're not
                 imputed yet */
              size_t n_full_discard;
              size_t n_trump_free;
              TarotCard full_discard[6];
              TarotCard trump_free[6];
              size_t max_full_discard =
                sizeof (full_discard) / sizeof (full_discard[0]);
              size_t max_trump_free =
                sizeof (trump_free) / sizeof (trump_free[0]);
              unsigned int event_restricted_data[78];
              TarotGameEvent event_restricted = {
                .data = event_restricted_data
              };
              size_t i;
              int is_discard =
                (event_get_discard
                 (event, &n_full_discard, 0, max_full_discard,
                  full_discard) == TAROT_EVENT_OK);
              assert (is_discard);
              n_trump_free = 0;
              for (i = 0; i < n_full_discard; i++)
                {
                  TarotCard c = full_discard[i];
                  if (c > 56 && c < 76)
                    {
                      trump_free[n_trump_free++] = c;
                    }
                }
              assert (n_trump_free <= max_trump_free);
              event_set_discard (&event_restricted, n_trump_free, trump_free);
              if (game_add_event (game, &event_restricted) != TAROT_GAME_OK)
                {
                  DEBUG (stderr,
                         "%s:%d: could not add an event of type %d for node %p.\n",
                         __FILE__, __LINE__,
                         event_type (&event_restricted), leaf);
                  return 1;
                }
            }
          else
            {
              DEBUG (stderr,
                     "%s:%d: could not add an event of type %d for node %p.\n",
                     __FILE__, __LINE__, event_type (event), leaf);
              return 1;
            }
        }
      else
        {
          DEBUG (stderr, "%s:%d: added an event of type %d for node %p\n",
                 __FILE__, __LINE__, event_type (event), leaf);
        }
    }
  else
    {
      TarotGameIterator iterator;
      const TarotGameEvent *event;
      game_iterator_setup (&iterator, &(mcts->base));
      while ((event = game_iterator_next_value (&iterator)) != NULL)
        {
          TarotPlayer next;
          unsigned int added_data[78];
          TarotGameEvent added = {.n = 0,.data = added_data };
          int has_next =
            (game_get_next (&(mcts->base), &next) == TAROT_GAME_OK);
          switch (event_type (event))
            {
            case TAROT_DEAL_ALL_EVENT:
              assert (has_next);
              restrict_deal_all_event (&(mcts->base), &added, next);
              break;
            case TAROT_DISCARD_EVENT:
              assert (has_next);
              restrict_discard_event (&(mcts->base), &added, next);
              break;
            default:
              event_copy (&added, event);
              break;
            }
          if (game_add_event (game, &added) != TAROT_GAME_OK)
            {
              assert (0);
            }
          DEBUG (stderr, "%s:%d: added an event of type %d\n",
                 __FILE__, __LINE__, event_type (event));
        }
    }
  return 0;
}

static int
mcts_impute (TarotGame * game, struct yarrow256_ctx *rng)
{
  char imputation_seed[16];
  size_t sz = sizeof (imputation_seed);
  int ret = 0;
  TarotCounter counter;
  counter_initialize (&counter);
  yarrow256_random (rng, sz, (void *) imputation_seed);
  counter_load_from_game (&counter, game);
  ret =
Vivien Kraus's avatar
Vivien Kraus committed
516
    (counter_and_game_impute
517
     (&counter, game, sz, (void *) imputation_seed) != TAROT_IMPUTATION_OK);
Vivien Kraus's avatar
Vivien Kraus committed
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
  return ret;
}

static void
select_next_move_deal (size_t n_players, TarotGameEvent * event,
                       struct yarrow256_ctx *rng)
{
  char deal_seed[16];
  size_t sz = sizeof (deal_seed);
  yarrow256_random (rng, sz, (void *) deal_seed);
  event_set_deal_all_random (event, n_players, sz, (void *) deal_seed);
}

static void
select_next_move_bid (TarotGameEvent * event, TarotBid mini,
                      struct yarrow256_ctx *rng)
{
  unsigned char random_byte;
  double random_value;
  yarrow256_random (rng, 1, &random_byte);
  random_value = random_byte / 256.0;
  if (random_value <= 0.75)
    {
      event_set_bid (event, TAROT_PASS);
    }
  else
    {
      /* Outbid */
      event_set_bid (event, mini);
    }
}

static void
select_next_move_decl (TarotGameEvent * event, int allowed,
                       struct yarrow256_ctx *rng)
{
  char random_byte;
  int has_decl;
  yarrow256_random (rng, 1, (void *) &random_byte);
  has_decl = allowed && (random_byte % 2 == 0);
  event_set_decl (event, has_decl);
}

static void
select_next_move_call (TarotGameEvent * event, TarotNumber mini_face,
                       struct yarrow256_ctx *rng)
{
  TarotNumber face;
  static TarotSuit suits[4] =
    { TAROT_HEARTS, TAROT_CLUBS, TAROT_DIAMONDS, TAROT_SPADES };
  TarotSuit suit;
  TarotCard call;
  unsigned int random_value;
  if (mini_face == TAROT_KING)
    {
      face = TAROT_KING;
    }
  else
    {
      yarrow256_random (rng, sizeof (random_value), (void *) &random_value);
      face = mini_face + random_value % (TAROT_KING - mini_face + 1);
    }
  yarrow256_random (rng, sizeof (random_value), (void *) &random_value);
  suit = suits[random_value % 4];
  if (tarot_of (face, suit, &call) != 0)
    {
      assert (0);
    }
  event_set_call (event, call);
}

static void
select_next_move_dog (TarotGameEvent * event, const TarotGame * imputed)
{
  size_t n_dog;
  TarotCard dog[6];
594
  const size_t max_dog = sizeof (dog) / sizeof (dog[0]);
Vivien Kraus's avatar
Vivien Kraus committed
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
  if (!game_can_autoreveal (imputed, &n_dog, 0, max_dog, dog))
    {
      assert (0);
    }
  assert (n_dog <= 6);
  event_set_dog (event, n_dog, dog);
}

static void
shuffle (size_t n, TarotCard * set, struct yarrow256_ctx *rng)
{
  size_t random_value;
  size_t i;
  for (i = 1; i < n; i++)
    {
      size_t j;
      TarotCard hold;
      yarrow256_random (rng, sizeof (random_value), (void *) &random_value);
      j = random_value % (i + 1);
      hold = set[i];
      set[i] = set[j];
      set[j] = hold;
    }
}

static void
sample (size_t n_samplable, TarotCard * set, size_t n,
        struct yarrow256_ctx *rng, size_t *n_selected, int *selected)
{
  size_t i;
  shuffle (n_samplable, set, rng);
  for (i = 0; i < n_samplable; i++)
    {
      if (*n_selected < n)
        {
          TarotCard c = set[i];
          if (selected[c] == 0)
            {
              selected[c] = 1;
              *n_selected += 1;
            }
        }
    }
}

static void
select_next_move_discard (TarotGameEvent * event, size_t n, size_t n_prio,
                          TarotCard * prio, size_t n_additional,
                          TarotCard * additional, struct yarrow256_ctx *rng)
{
  int selected[78];
  size_t n_selected, i;
  TarotCard discard[6];
  for (i = 0; i < 78; i++)
    {
      selected[i] = 0;
    }
  n_selected = 0;
  sample (n_prio, prio, n, rng, &n_selected, selected);
  if (n_selected < n)
    {
      sample (n_additional, additional, n - n_selected, rng, &n_selected,
              selected);
    }
  assert (n_selected == n);
  n_selected = 0;
  for (i = 0; i < 78; i++)
    {
      if (selected[i])
        {
          assert (n_selected < sizeof (discard) / sizeof (discard[0]));
          discard[n_selected++] = i;
        }
    }
  assert (n_selected == n);
  event_set_discard (event, n, discard);
}

static void
select_next_move_card (TarotGameEvent * event,
                       size_t n_playable, TarotCard * playable,
                       struct yarrow256_ctx *rng)
{
  size_t i;
  size_t random_value;
  yarrow256_random (rng, sizeof (random_value), (void *) &random_value);
  i = random_value % n_playable;
  event_set_card (event, playable[i]);
}

static inline int
mcts_next_move (const TarotGame * game, TarotGameEvent * event,
                struct yarrow256_ctx *rng)
{
  TarotBid mini_bid;
  int decl_allowed;
  TarotPlayer next;
  TarotNumber mini_face;
  TarotCard prio[78];
694
  const size_t max_prio = sizeof (prio) / sizeof (prio[0]);
Vivien Kraus's avatar
Vivien Kraus committed
695
696
  size_t n_prio;
  TarotCard additional[78];
697
  const size_t max_additional = sizeof (additional) / sizeof (additional[0]);
Vivien Kraus's avatar
Vivien Kraus committed
698
699
  size_t n_additional;
  TarotCard playable[78];
700
  const size_t max_playable = sizeof (playable) / sizeof (playable[0]);
Vivien Kraus's avatar
Vivien Kraus committed
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
  size_t n_playable;
  size_t n_cards;
  int ret = 0;
  switch (game_step (game))
    {
    case TAROT_SETUP:
      /* Since we have at least one event in the past, and we cannot
         have two consecutive setup events, then this is not
         possible */
      assert (0);
      break;
    case TAROT_DEAL:
      select_next_move_deal (game_n_players (game), event, rng);
      if (!game_check_event (game, event))
        {
          /* Petit sec */
          ret = 1;
        }
      break;
    case TAROT_BIDS:
      if (game_get_hint_bid (game, &next, &mini_bid) != TAROT_GAME_OK)
        {
          assert (0);
        }
      select_next_move_bid (event, mini_bid, rng);
      break;
    case TAROT_DECLS:
      if (game_get_hint_decl (game, &next, &decl_allowed) != TAROT_GAME_OK)
        {
          assert (0);
        }
      select_next_move_decl (event, decl_allowed, rng);
      break;
    case TAROT_CALL:
      if (game_get_hint_call (game, &next, &mini_face) != TAROT_GAME_OK)
        {
          assert (0);
        }
      select_next_move_call (event, mini_face, rng);
      break;
    case TAROT_DOG:
      select_next_move_dog (event, game);
      break;
    case TAROT_DISCARD:
      if (game_get_hint_discard
          (game, &next, &n_cards, &n_prio, 0, max_prio, prio, &n_additional,
           0, max_additional, additional) != TAROT_GAME_OK)
        {
          assert (0);
        }
751
      assert (n_cards == 3 || n_cards == 6);
Vivien Kraus's avatar
Vivien Kraus committed
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
      select_next_move_discard (event, n_cards, n_prio, prio, n_additional,
                                additional, rng);
      break;
    case TAROT_TRICKS:
      if (game_get_hint_card (game, &next, &n_playable, 0, max_playable,
                              playable) != TAROT_GAME_OK)
        {
          assert (0);
        }
      select_next_move_card (event, n_playable, playable, rng);
      break;
    case TAROT_END:
      /* We don't select a move if we're at end */
      assert (0);
      break;
    }
  return ret;
}

static TarotMctsNode *
mcts_tree_alloc (TarotMcts * mcts, const TarotGameEvent * event,
                 TarotPlayer next_player)
{
  TarotMctsNode *ret = talloc (&(mcts->pool_remaining), &(mcts->pool_head),
                               sizeof (TarotMctsNode),
                               alignof (TarotMctsNode));
  assert (ret != NULL);
  ret->up = NULL;
  ret->left = NULL;
  ret->right = NULL;
  ret->sum_scores = 0;
  ret->n_simulations = 0;
  ret->myself = next_player;
  ret->event.data =
    talloc (&(mcts->pool_remaining), &(mcts->pool_head),
            event->n * sizeof (unsigned int), alignof (unsigned int));
  if (ret->event.data == NULL)
    {
      return NULL;
    }
  event_copy (&(ret->event), event);
  return ret;
}

static TarotMctsNode *
mcts_tree_insert_left (TarotMcts * mcts, TarotMctsNode * parent,
                       const TarotGameEvent * event, TarotPlayer next_player)
{
  TarotMctsNode *ret = mcts_tree_alloc (mcts, event, next_player);
  ret->up = parent;
  assert (parent->left == NULL);
  parent->left = ret;
  ret->left = NULL;
  ret->right = NULL;
  return ret;
}

static TarotMctsNode *
mcts_tree_insert_right (TarotMcts * mcts, TarotMctsNode * parent,
                        const TarotGameEvent * event, TarotPlayer next_player)
{
  TarotMctsNode *ret = mcts_tree_alloc (mcts, event, next_player);
  ret->up = parent;
  assert (parent->right == NULL);
  parent->right = ret;
  ret->left = NULL;
  ret->right = NULL;
  return ret;
}

static TarotMctsNode *
mcts_tree_add_child (TarotMcts * mcts, TarotMctsNode * parent,
                     const TarotGameEvent * event, TarotPlayer next_player)
{
  if (parent->left == NULL)
    {
      return mcts_tree_insert_left (mcts, parent, event, next_player);
    }
  parent = parent->left;
  while (parent->right != NULL)
    {
      parent = parent->right;
    }
  return mcts_tree_insert_right (mcts, parent, event, next_player);
}

static inline int
mcts_expand (TarotMcts * mcts, TarotMctsNode ** node,
             const TarotGameEvent * event, TarotPlayer next_player)
{
  TarotMctsNode *new_node = NULL;
  /* The first node data should go to the root, then we can expand */
  if (mcts->root != NULL)
    {
      if (*node != NULL)
        {
          assert (event_type (event) <= TAROT_CARD_EVENT);
          new_node = mcts_tree_add_child (mcts, *node, event, next_player);
        }
      else
        {
          const TarotMctsNode *right = NULL;
          /* New child directly from root */
          for (*node = mcts->root, right = (*node)->right;
               right != NULL;
               *node = (TarotMctsNode *) right, right = (*node)->right)
            ;
          new_node = mcts_tree_insert_right (mcts, *node, event, next_player);
        }
    }
  else
    {
      new_node = mcts_tree_alloc (mcts, event, next_player);
    }
  if (new_node == NULL)
    {
      return 1;
    }
  if (mcts->root == NULL)
    {
      mcts->root = new_node;
      assert (mcts->root->up == NULL);
      assert (mcts->root->left == NULL);
      assert (mcts->root->right == NULL);
    }
  DEBUG (stderr, "%s:%d: node %p set with event of type %d\n",
         __FILE__, __LINE__, *node, event_type (event));
  assert (new_node->left == NULL);
  assert (new_node->right == NULL);
  *node = new_node;
  return 0;
}

static inline void
mcts_simulate (double simulation_random,
               double simulation_agreed,
               struct yarrow256_ctx *rng, TarotGame * game,
               size_t n_players, int *score)
{
  size_t n;
  double simulation_total = simulation_random + simulation_agreed;
  size_t generated;
  yarrow256_random (rng, sizeof (generated), (void *) &generated);
  double generated_max = ((double) ((size_t) (-1))) + 1.0;
  double generated_norm = generated / generated_max;
  TarotSimulationError err;
  (void) err;
  if (generated_norm < simulation_random / simulation_total)
    {
      err = tarot_simulate_random (rng, game);
    }
  else
    {
      err = tarot_simulate_agreed (rng, game);
    }
  assert (err == TAROT_SIMULATION_OK);
  if (game_get_scores (game, &n, 0, n_players, score) != TAROT_GAME_OK)
    {
      assert (0);
    }
  assert (n == n_players);
}

static inline void
mcts_backpropagate (TarotMctsNode * node, TarotPlayer taker, size_t n_players,
                    const int *score)
{
  TarotMctsNode *parent = mcts_parent (node);
  TarotPlayer myself = node->myself;
  if (myself >= n_players)
    {
      myself = taker;
    }
  assert (myself < n_players);
  DEBUG (stderr, "%s:%d: backpropagate score %d to node %p (%d / %lu)\n",
         __FILE__, __LINE__, score[myself], node, node->sum_scores,
         node->n_simulations);
  node->sum_scores += score[myself];
  node->n_simulations += 1;
  if (parent != NULL)
    {
      mcts_backpropagate (parent, taker, n_players, score);
    }
}

static inline TarotMctsNode *
mcts_root (TarotMcts * mcts)
{
  return mcts->root;
}

static inline const TarotGameEvent *
mcts_get (const TarotMctsNode * node, size_t *n_simulations, int *sum_scores)
{
  *n_simulations = node->n_simulations;
  *sum_scores = node->sum_scores;
  return &(node->event);
}

static inline TarotMctsNode *
mcts_parent (TarotMctsNode * node)
{
  /* First parent from which we're left */
  if (node == NULL || node->up == NULL)
    {
      return NULL;
    }
  if (node->up->left == node)
    {
      return node->up;
    }
  return mcts_parent (node->up);
}

static inline TarotMctsNode *
mcts_first_child (TarotMctsNode * node)
{
  if (node == NULL)
    {
      return NULL;
    }
  return node->left;
}

static inline TarotMctsNode *
mcts_previous_sibling (TarotMctsNode * node)
{
  if (node == NULL || node->up == NULL)
    {
      return NULL;
    }
  if (node->up->right == node)
    {
      return node->up;
    }
  return NULL;
}

static inline TarotMctsNode *
mcts_next_sibling (TarotMctsNode * node)
{
  if (node == NULL)
    {
      return NULL;
    }
  return node->right;
}

static inline int
mcts_setup_bids (TarotMcts * mcts)
{
  TarotPlayer who;
  TarotBid mini;
  TarotGameEvent event;
  TarotBid bid;
  TarotMctsNode *node = NULL;
  if (game_get_hint_bid (&(mcts->base), &who, &mini) != TAROT_GAME_OK)
    {
      assert (0);
    }
  event_set_bid (&event, TAROT_PASS);
  if (mcts_expand (mcts, &node, &event, who) != 0)
    {
      return 1;
    }
  for (bid = mini; bid <= TAROT_DOUBLE_KEEP; bid++)
    {
      event_set_bid (&event, bid);
      node = NULL;
      if (mcts_expand (mcts, &node, &event, who) != 0)
        {
          return 1;
        }
    }
  return 0;
}

static int
mcts_setup_decls (TarotMcts * mcts)
{
  TarotPlayer who;
  int allowed;
  TarotGameEvent event;
  TarotMctsNode *node = NULL;
  if (game_get_hint_decl (&(mcts->base), &who, &allowed) != TAROT_GAME_OK)
    {
      assert (0);
    }
  event_set_decl (&event, 0);
  node = NULL;
  if (mcts_expand (mcts, &node, &event, who) != 0)
    {
      return 1;
    }
  event_set_decl (&event, 1);
  node = NULL;
  if (mcts_expand (mcts, &node, &event, who) != 0)
    {
      return 1;
    }
  return 0;
}

static int
mcts_setup_call (TarotMcts * mcts)
{
  TarotPlayer who;
  TarotNumber mini;
  TarotGameEvent event;
  TarotNumber face;
  TarotMctsNode *node = NULL;
  if (game_get_hint_call (&(mcts->base), &who, &mini) != TAROT_GAME_OK)
    {
      assert (0);
    }
  for (face = mini; face <= TAROT_KING; face++)
    {
      static TarotSuit suits[4] =
        { TAROT_HEARTS, TAROT_CLUBS, TAROT_DIAMONDS, TAROT_SPADES };
      size_t j;
      for (j = 0; j < 4; j++)
        {
          TarotCard c;
          if (tarot_of (face, suits[j], &c) != 0)
            {
              assert (0);
            }
          event_set_call (&event, c);
          node = NULL;
          if (mcts_expand (mcts, &node, &event, who) != 0)
            {
              return 1;
            }
        }
    }
  return 0;
}

static int
mcts_setup_discard (TarotMcts * mcts)
{
  TarotPlayer who;
  unsigned int event_data[78];
  TarotGameEvent event = {.data = event_data };
  size_t n_prio;
  TarotCard prio[78];
1098
  const size_t max_prio = sizeof (prio) / sizeof (prio[0]);
Vivien Kraus's avatar
Vivien Kraus committed
1099
1100
  size_t n_additional;
  TarotCard additional[78];
1101
  const size_t max_additional = sizeof (additional) / sizeof (additional[0]);
Vivien Kraus's avatar
Vivien Kraus committed
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
  struct yarrow256_ctx rng;
  static const char *seed = "default";
  size_t i, n;
  TarotMctsNode *node = NULL;
  yarrow256_init (&rng, 0, NULL);
  yarrow256_seed (&rng, strlen (seed), (const uint8_t *) seed);
  if (game_get_hint_discard
      (&(mcts->base), &who, &n, &n_prio, 0, max_prio, prio, &n_additional, 0,
       max_additional, additional) != TAROT_GAME_OK)
    {
      return 1;
    }
  assert (n_prio <= max_prio && n_additional <= max_additional);
  for (i = 0; i < 16; i++)
    {
      select_next_move_discard (&event, n, n_prio, prio, n_additional,
                                additional, &rng);
      node = NULL;
      if (mcts_expand (mcts, &node, &event, who) != 0)
        {
          return 1;
        }
    }
  return 0;
}

static TarotMctsError
mcts_setup_card (TarotMcts * mcts)
{
  TarotPlayer who;
  TarotGameEvent event;
  size_t n_playable;
  TarotCard playable[78];
1135
  const size_t max_playable = sizeof (playable) / sizeof (playable[0]);
Vivien Kraus's avatar
Vivien Kraus committed
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
  size_t i;
  TarotMctsNode *node = NULL;
  if (game_get_hint_card
      (&(mcts->base), &who, &n_playable, 0, max_playable,
       playable) != TAROT_GAME_OK)
    {
      return 1;
    }
  assert (n_playable <= max_playable);
  assert (n_playable != 0);
  for (i = 0; i < n_playable; i++)
    {
      event_set_card (&event, playable[i]);
      node = NULL;
      if (mcts_expand (mcts, &node, &event, who) != 0)
        {
          return 1;
        }
    }
  return 0;
}

static inline TarotMctsError
mcts_setup_root (TarotMcts * mcts)
{
  switch (game_step (&(mcts->base)))
    {
    case TAROT_BIDS:
      return mcts_setup_bids (mcts);
    case TAROT_DECLS:
      return mcts_setup_decls (mcts);
    case TAROT_CALL:
      return mcts_setup_call (mcts);
    case TAROT_DISCARD:
      return mcts_setup_discard (mcts);
    case TAROT_TRICKS:
      return mcts_setup_card (mcts);
    default:
      break;
    }
  return TAROT_MCTS_UNKNOWNNEXT;
}

#include <tarot/counter_private_impl.h>
#include <tarot/game_private_impl.h>
#include <tarot/game_event_private_impl.h>