-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
469 lines (426 loc) · 15.1 KB
/
main.c
File metadata and controls
469 lines (426 loc) · 15.1 KB
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
/*
* Program entry and CLI modes
* ---------------------------
* - Interactive game loop (human vs AI)
* - Self-play mode via --selfplay|-s [games] [--quiet|-q] [--tt-size|-t SIZE] [--seed|-S SEED]
* * Default games: 1000 when omitted
* * --quiet/-q suppresses all self-play output (errors always printed)
* * --tt-size/-t overrides transposition table size
* * --seed/-S sets PRNG seed for Zobrist keys (deterministic by default)
*/
/* Platform-specific high-resolution timer */
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#define _POSIX_C_SOURCE 199309L
#include <time.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <errno.h>
#include "TicTacToe/tic_tac_toe.h"
#include "Negamax/negamax.h"
#include "Negamax/transposition.h"
/* Portable high-resolution timer */
#ifdef _MSC_VER
typedef LARGE_INTEGER HiResTimer;
static int timer_get(HiResTimer *t)
{
return QueryPerformanceCounter(t) ? 0 : -1;
}
static double timer_diff_seconds(const HiResTimer *start, const HiResTimer *end)
{
LARGE_INTEGER freq;
if (!QueryPerformanceFrequency(&freq))
return -1.0;
return (double)(end->QuadPart - start->QuadPart) / (double)freq.QuadPart;
}
#else
typedef struct timespec HiResTimer;
static int timer_get(HiResTimer *t)
{
return clock_gettime(CLOCK_MONOTONIC, t);
}
static double timer_diff_seconds(const HiResTimer *start, const HiResTimer *end)
{
double sec = (double)(end->tv_sec - start->tv_sec);
double nsec = (double)(end->tv_nsec - start->tv_nsec);
return sec + (nsec / 1e9);
}
#endif
/*
* Maximum transposition table size (entry count).
* This caps the allocation when BOARD_SIZE is large.
* At 16 bytes per entry: 250M entries = 4 GB (SI). The allocator rounds up
* to the next power of 2 (268,435,456 entries = 4 GiB actual).
*/
#define MAX_TRANSPOSITION_TABLE_SIZE 250000000
/*
* Interactive human vs AI loop. Prompts the user to choose a symbol, then
* alternates between human input and AI selection until the game ends.
*/
static void playGame(void)
{
while (1)
{
restartGame();
choosePlayerSymbol();
if (player_turn != ai_symbol)
printBoard();
while (1)
{
int row, col;
if (player_turn == human_symbol)
{
if (getMove(&row, &col) == -1)
{
printf("\nEOF received. Exiting game.\n");
return; /* Clean exit on EOF */
}
makeMove(row, col);
GameResult result = checkWinner(row, col);
if (result != GAME_CONTINUE)
{
printGameResult(result);
break;
}
}
else
{
int ai_row, ai_col;
getAiMove(board_state, ai_symbol, &ai_row, &ai_col);
/* Defensive: getAiMove returns (-1, -1) for terminal positions */
if (ai_row == -1 || ai_col == -1)
{
fprintf(stderr, "Error: AI returned invalid move (terminal position)\n");
break; /* Exit game loop */
}
makeMove(ai_row, ai_col);
printf("AI plays (%d, %d)\n", ai_col + 1, ai_row + 1);
GameResult result = checkWinner(ai_row, ai_col);
if (result != GAME_CONTINUE)
{
printGameResult(result);
break;
}
else
{
printBoard();
}
}
}
if (!askRestart())
return;
}
}
/*
* Self-play mode: runs gameCount AI vs AI games starting from an empty
* board, alternating turns. Prints timing and throughput unless quiet.
*
* Returns EXIT_SUCCESS if all games are ties (correct perfect play).
* Returns EXIT_FAILURE immediately if any game is won, printing a diagnostic
* to stderr; a win indicates a bug in the engine.
*
* Parameters:
* - gameCount: number of games to run
* - quiet: when non-zero, suppress all self-play output (errors always print)
*/
static int selfPlay(int gameCount, int quiet)
{
HiResTimer startTime = {0};
int timing_available = 0;
if (!quiet)
{
if (timer_get(&startTime) != 0)
{
fprintf(stderr, "Warning: timer initialization failed, timing stats unavailable\n");
timing_available = 0;
}
else
{
timing_available = 1;
}
}
for (int g = 0; g < gameCount; ++g)
{
restartGame();
while (1)
{
int currentRow = -1;
int currentCol = -1;
char currentPlayer = player_turn;
getAiMove(board_state, currentPlayer, ¤tRow, ¤tCol);
/* Defensive: getAiMove returns (-1, -1) for terminal positions */
if (currentRow == -1 || currentCol == -1)
{
fprintf(stderr, "Error: AI returned invalid move in self-play (game %d)\n", g + 1);
return EXIT_FAILURE;
}
makeMove(currentRow, currentCol);
GameResult result = checkWinner(currentRow, currentCol);
if (result != GAME_CONTINUE)
{
if (result != GAME_TIE)
{
fprintf(stderr, "Error: perfect play broken - %s won game %d\n",
(result == X_WIN) ? "X" : "O", g + 1);
return EXIT_FAILURE;
}
break;
}
}
}
if (!quiet)
{
double elapsed = 0.0;
double throughput = 0.0;
/* Try to get timing data if clock was available at start */
if (timing_available)
{
HiResTimer endTime;
if (timer_get(&endTime) != 0)
{
fprintf(stderr, "Warning: timer read failed, timing stats unavailable\n");
timing_available = 0;
}
else
{
/* Calculate elapsed time in seconds */
elapsed = timer_diff_seconds(&startTime, &endTime);
if (elapsed < 0)
{
fprintf(stderr, "Warning: negative elapsed time, timing stats unavailable\n");
timing_available = 0;
}
else
{
throughput = elapsed > 0 ? (gameCount / elapsed) : 0.0;
}
}
}
if (timing_available)
{
if (throughput >= 1000000.0)
printf("%d games in %.3f s (%.2f M games/s)\n", gameCount, elapsed, throughput / 1000000.0);
else if (throughput >= 1000.0)
printf("%d games in %.3f s (%.2f K games/s)\n", gameCount, elapsed, throughput / 1000.0);
else
printf("%d games in %.3f s (%.1f games/s)\n", gameCount, elapsed, throughput);
}
else
{
printf("%d games (timing unavailable)\n", gameCount);
}
}
return EXIT_SUCCESS;
}
/*
* CLI:
* - Default (no args): interactive human vs AI game
* - --selfplay|-s [games] [--quiet|-q] [--tt-size|-t SIZE] [--seed|-S SEED]: run AI vs AI for N games (default 1000)
*/
int main(int argc, char **argv)
{
/* Scan for --help first so it always wins over other flags */
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
{
printf("Usage: ttt [OPTIONS]\n\n");
printf("Play Tic-Tac-Toe against a perfect negamax AI or run self-play simulations.\n");
printf("Compiled for %dx%d board.\n\n", BOARD_SIZE, BOARD_SIZE);
printf("OPTIONS:\n");
printf(" Interactive Mode (default):\n");
printf(" Start an interactive game against the AI.\n\n");
printf(" Self-Play Mode:\n");
printf(" --selfplay, -s [GAMES] Run self-play simulations (default: 1000 games)\n");
printf(" --quiet, -q Suppress output (requires --selfplay)\n\n");
printf(" Configuration:\n");
printf(" --tt-size SIZE, -t SIZE Transposition table size in entries\n");
printf(" (0 disables TT, default: auto-sized, max: %d)\n", MAX_TRANSPOSITION_TABLE_SIZE);
printf(" --seed SEED, -S SEED PRNG seed for Zobrist keys (default: fixed internal seed)\n\n");
printf(" Help:\n");
printf(" --help, -h Show this help message and exit\n\n");
printf("EXAMPLES:\n");
printf(" ttt # Interactive game\n");
printf(" ttt --selfplay 5000 # Run 5000 self-play games\n");
printf(" ttt --selfplay 10000 -q # Run 10000 games, quiet output\n");
printf(" ttt -S 42 -s 1000 # Custom Zobrist hash seed\n");
printf(" ttt --tt-size 0 -s 1000 # Benchmark without transposition table\n");
printf("\nBuilt by Pavol Ulicny - github.com/PavolUlicny\n");
return EXIT_SUCCESS;
}
}
/* Single-pass argument parsing */
int opt_selfplay = 0;
int opt_selfplay_games = 1000;
int opt_quiet = 0;
int opt_seed_set = 0;
uint64_t opt_seed = 0;
int opt_tt_size_set = 0;
size_t opt_tt_size = 0;
for (int i = 1; i < argc; i++)
{
const char *arg = argv[i];
if (strcmp(arg, "--") == 0)
{
if (i + 1 < argc)
{
fprintf(stderr, "Error: Unexpected argument '%s'\n", argv[i + 1]);
fprintf(stderr, "Use --help to see available options.\n");
return EXIT_FAILURE;
}
break;
}
if (strcmp(arg, "--selfplay") == 0 || strcmp(arg, "-s") == 0)
{
opt_selfplay = 1;
/* Optional positional argument: game count */
if (i + 1 < argc)
{
char *endptr;
errno = 0;
long val = strtol(argv[i + 1], &endptr, 10);
if (endptr != argv[i + 1] && *endptr == '\0')
{
/* Valid integer — consume as game count */
if (errno == ERANGE || val < 1 || val > INT_MAX)
{
fprintf(stderr, "Error: Game count must be a positive integer.\n");
return EXIT_FAILURE;
}
opt_selfplay_games = (int)val;
i++;
}
else if (argv[i + 1][0] != '-')
{
/* Non-flag, non-integer: error */
fprintf(stderr, "Error: Invalid --selfplay value '%s' (must be a positive integer)\n",
argv[i + 1]);
return EXIT_FAILURE;
}
/* Starts with '-': another flag, leave for next iteration */
}
}
else if (strcmp(arg, "--quiet") == 0 || strcmp(arg, "-q") == 0)
{
opt_quiet = 1;
}
else if (strcmp(arg, "--seed") == 0 || strcmp(arg, "-S") == 0)
{
if (i + 1 >= argc)
{
fprintf(stderr, "Error: --seed/-S requires a value\n");
return EXIT_FAILURE;
}
i++;
const char *seed_str = argv[i];
if (seed_str[0] == '\0')
{
fprintf(stderr, "Error: --seed/-S value cannot be empty\n");
return EXIT_FAILURE;
}
if (seed_str[0] == '-')
{
fprintf(stderr, "Error: Invalid --seed/-S value '%s' (must be 0 to %llu)\n",
seed_str, (unsigned long long)ULLONG_MAX);
return EXIT_FAILURE;
}
char *endptr;
errno = 0;
unsigned long long val = strtoull(seed_str, &endptr, 10);
if (endptr == seed_str || *endptr != '\0')
{
fprintf(stderr, "Error: Invalid --seed/-S value '%s' (not a valid number)\n", seed_str);
return EXIT_FAILURE;
}
if (errno == ERANGE)
{
fprintf(stderr, "Error: --seed/-S value '%s' out of range (max: %llu)\n",
seed_str, (unsigned long long)ULLONG_MAX);
return EXIT_FAILURE;
}
opt_seed = (uint64_t)val;
opt_seed_set = 1;
}
else if (strcmp(arg, "--tt-size") == 0 || strcmp(arg, "-t") == 0)
{
if (i + 1 >= argc ||
(argv[i + 1][0] == '-' && !isdigit((unsigned char)argv[i + 1][1])))
{
fprintf(stderr, "Error: --tt-size requires a value\n");
return EXIT_FAILURE;
}
i++;
char *endptr;
errno = 0;
long val = strtol(argv[i], &endptr, 10);
if (endptr == argv[i] || *endptr != '\0' ||
errno == ERANGE || val < 0 || val > MAX_TRANSPOSITION_TABLE_SIZE)
{
fprintf(stderr, "Error: Invalid --tt-size value '%s' (must be 0 to %d)\n",
argv[i], MAX_TRANSPOSITION_TABLE_SIZE);
return EXIT_FAILURE;
}
opt_tt_size = (size_t)val;
opt_tt_size_set = 1;
}
else if (arg[0] == '-')
{
fprintf(stderr, "Error: Unknown option '%s'\n", arg);
fprintf(stderr, "Use --help to see available options.\n");
return EXIT_FAILURE;
}
else
{
fprintf(stderr, "Error: Unexpected argument '%s'\n", arg);
fprintf(stderr, "Use --help to see available options.\n");
return EXIT_FAILURE;
}
}
if (opt_quiet && !opt_selfplay)
{
fprintf(stderr, "Error: --quiet requires --selfplay\n");
fprintf(stderr, "Use --help to see available options.\n");
return EXIT_FAILURE;
}
/* Initialize subsystems in required order */
init_win_masks();
if (opt_seed_set)
zobrist_set_seed(opt_seed);
zobrist_init();
/*
* Transposition table sizing.
* BOARD_SIZE 3 and 4 use hardcoded values tuned by benchmarking.
* BOARD_SIZE ≥ 5 uses the formula: size = 1,500,000 × (BOARD_SIZE / 4)^9.4,
* capped at MAX_TRANSPOSITION_TABLE_SIZE.
*/
size_t tt_size;
#if BOARD_SIZE == 3
tt_size = 100000;
#elif BOARD_SIZE == 4
tt_size = 1500000;
#else
{
double growth_factor = pow((double)BOARD_SIZE / 4.0, 9.4);
tt_size = (size_t)(1500000.0 * growth_factor);
if (tt_size > MAX_TRANSPOSITION_TABLE_SIZE)
tt_size = MAX_TRANSPOSITION_TABLE_SIZE;
}
#endif
if (opt_tt_size_set)
tt_size = opt_tt_size;
transposition_table_init(tt_size);
int ret_code = 0;
if (opt_selfplay)
ret_code = selfPlay(opt_selfplay_games, opt_quiet);
else
playGame();
transposition_table_free();
return ret_code;
}