-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
680 lines (656 loc) · 19.3 KB
/
main.rs
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
use std::env;
use std::io::{stdin,stdout,Write};
use std::fs::File;
use std::io::Read;
use std::vec::Vec;
use std::collections::HashMap;
use std::thread;
use serde_json;
extern crate lazy_static;
use colored::Colorize;
// store a board node in the tree
#[derive(Clone, Debug)]
pub struct Board {
pub brd: [[i8; 9]; 9],
pub scope: u8,
pub player: i8,
pub movenum: u8,
pub parent: Option<usize>,
pub children: Vec<usize>,
pub prediction: Option<f32>,
}
// DB: store boards
// CURINDEX: store current board
pub static mut DB: Vec<Board> = Vec::new();
pub static mut CURINDEX: usize = 0;
lazy_static::lazy_static! {
pub static ref PROBS: HashMap<String, (f32, f32)> = {
// initialize probability hashmap
let args: Vec<String> = env::args().collect();
let mut json = String::new();
let mut f = File::open(&args[1]).expect("Unable to open file");
f.read_to_string(&mut json).expect("Unable to read string");
let p: HashMap<String, (f32, f32)> = serde_json::from_str(&json).expect("JSON not readable");
p
};
}
impl Board {
// check if a board in the tree is not reachable given the game state
fn obselete(&self, db: &Vec<Board>, curindex: usize) -> bool {
let ogboard = &db[curindex];
let mut thisboard = self;
while thisboard.movenum > ogboard.movenum {
thisboard = &db[thisboard.parent.unwrap()];
}
return thisboard.brd != ogboard.brd;
}
}
// update the prediction rating of this board to be max/min of children
// depending on who's turn it is
pub fn updatepred(db: &mut Vec<Board>, curindex: usize) -> usize {
let cpboard = db[curindex].clone();
if cpboard.children.len() > 0 {
if cpboard.player == 1 {
// get max rating from children
let mut maxrate: Option<f32> = None;
let mut maxindex: usize = 0;
for i in 0..cpboard.children.len() {
if maxrate == None || db[cpboard.children[i]].prediction > maxrate {
maxrate = db[cpboard.children[i]].prediction;
maxindex = i as usize;
}
}
db[curindex].prediction = maxrate;
return maxindex;
}
else {
// get min rating from children
let mut minrate: Option<f32> = None;
let mut minindex: usize = 0;
let onwon = small_winner(get_slice(cpboard.brd, cpboard.scope)) != 0;
let mut all_loop = true;
for i in 0..cpboard.children.len() {
let child = &db[cpboard.children[i]];
let nextwon = small_winner(get_slice(child.brd, child.scope)) != 0;
if !(onwon && loopstuck(&db, curindex, i) && (!nextwon)) {
all_loop = false;
break;
}
}
for i in 0..cpboard.children.len() {
let child = &db[cpboard.children[i]];
let nextwon = small_winner(get_slice(child.brd, child.scope)) != 0;
if (all_loop || !(onwon && loopstuck(&db, curindex, i) && (!nextwon))) && (minrate == None || child.prediction > minrate) {
minrate = db[cpboard.children[i]].prediction;
minindex = i as usize;
}
}
db[curindex].prediction = minrate;
return minindex;
}
}
return 0;
}
// write a board to a file for storing and later debug (or potentially game recovery!)
fn write_board(board: [[i8; 9]; 9], outfile: &mut File) {
outfile.write(b"\n[").expect("failed to write file");
for row in 0..9 {
outfile.write(b"[").expect("failed to write file");
for col in 0..9 {
outfile.write(
match board[row][col] {
-2 => b"-2",
-1 => b"-1",
0 => b"0",
1 => b"1",
2 => b"2",
_ => b".",
}
).expect("failed to write file");
outfile.write(b", ").expect("failed to write file");
}
outfile.write(b"],\n").expect("failed to write file");
}
outfile.write(b"]").expect("failed to write file");
}
fn main() {
println!("Welcome to AI Big Tac Toe!");
let args: Vec<String> = env::args().collect();
let mut starter = Board {
brd: [[0; 9]; 9],
scope: 1,
player: 1,
movenum: 0,
children: Vec::new(),
parent: None,
prediction: None,
};
if args.len() > 2 {
starter.brd = [[1, -1, 1, 2, -1, 1, -1, 2, -2, ],
[0, 0, -2, 1, 1, 1, -1, 2, 2, ],
[-1, -1, -1, 2, 2, 2, -1, -2, 2, ],
[0, -1, -1, 0, -1, 1, 1, -2, -1, ],
[1, 0, -1, 0, 0, 0, 1, 0, -1, ],
[-1, 0, 0, 0, 0, -1, 1, -2, 1, ],
[1, -1, 1, 1, -2, 1, -1, -1, -1, ],
[0, -1, 2, 0, 0, 1, 1, 0, -2, ],
[1, -1, -1, -1, 2, 1, 2, -2, 2, ],
];
starter.scope = 1;
starter.player = 1;
}
play(starter);
}
// play the game 1 player
pub fn play(starter: Board) {
let mut game_history = File::create("game_history.txt").expect("failed to open file");
// thread that builds the decision tree
unsafe {DB.push(starter);}
buildtree();
// thread that takes user input and gets best computer move
while winner(unsafe {DB[CURINDEX].brd}) == 0 {
let board = unsafe{&DB[CURINDEX].clone()};
// println!("This board has {} children", board.children.len());
write_board(board.brd, &mut game_history);
if board.player == 1 {
// println!("Board rating: {}", rate_board(board));
print_board(&board);
println!("Board rating: human: {}, comp: {}. Computer can see {} moves ahead.", rate_board(board.brd).0, rate_board(board.brd).1, unsafe{DB.last().unwrap().movenum - DB[CURINDEX].movenum});
let mut go_scope = board.scope;
if is_full(get_slice(board.brd, board.scope)) {
print!("Your board is full. Please enter a number, 0-8 (inclusive) for which board you want to play on: ");
let up = input();
go_scope = up.parse::<u8>().unwrap();
}
print!("You are on board number {}. Please enter a number, 0-8 (inclusive) for where you want to place your X: ", go_scope);
let up = input();
let truep = up.parse::<u8>().unwrap();
let board = unsafe{&DB[CURINDEX].clone()};
if truep < 9 && get(board.brd, go_scope, truep) == 0 {
unsafe{CURINDEX = domove(board, go_scope, truep);}
}
}
else {
unsafe{CURINDEX = domove(board, board.scope, getcpmove(&mut DB, CURINDEX, Some(DB.last().unwrap().movenum - 1)));}
}
}
print_board(unsafe{&DB[CURINDEX]});
if winner(unsafe{DB[CURINDEX].brd}) == 1 {
print!("You ");
}
else {
print!("The computer ");
}
println!("won. Thank you for playing!");
}
// build the board tree
pub fn buildtree() {
thread::spawn(|| {
fn tryall(database: &mut Vec<Board>, index: usize) {
if winner(database[index].brd) == 0 {
let myslice = get_slice(database[index].brd, database[index].scope);
if is_full(myslice) {
for row in 0..9 {
for col in 0..9 {
if database[index].brd[row][col] == 0 {
let p: u8 = ((row % 3) * 3 + col % 3) as u8;
let mut newbrd = Board {
brd: database[index].brd.clone(),
scope: p,
player: database[index].player * -1,
movenum: database[index].movenum + 1,
children: Vec::new(),
parent: Some(index),
prediction: None,
};
place(&mut newbrd.brd, database[index].player, ((row / 3) * 3 + (col / 3)) as u8, p);
newbrd.prediction = Some(rate_board(newbrd.brd).0 * (1.0 - rate_board(newbrd.brd).1));
let dblength = database.len() as usize;
database[index].children.push(dblength);
database.push(newbrd);
}
}
}
}
else {
for row in 0..3 {
for col in 0..3 {
if myslice[row][col] == 0 {
let p: u8 = (row * 3 + col) as u8;
let mut newbrd = Board {
brd: database[index].brd.clone(),
scope: p,
player: database[index].player * -1,
movenum: database[index].movenum + 1,
children: Vec::new(),
parent: Some(index),
prediction: None,
};
place(&mut newbrd.brd, database[index].player, database[index].scope, p);
newbrd.prediction = Some(rate_board(newbrd.brd).0 * (1.0 - rate_board(newbrd.brd).1));
let dblength = database.len() as usize;
database[index].children.push(dblength);
database.push(newbrd.clone());
}
}
}
}
}
}
let mut curin = 0;
while unsafe {DB.len()} > curin {
let thisboard = unsafe{DB[curin].clone()};
if !thisboard.obselete(unsafe{&DB}, unsafe{CURINDEX}) && thisboard.children.len() == 0 {
tryall(unsafe {&mut DB}, curin);
}
curin += 1;
// println!("{}", curin);
}
});
}
// get user input in String type
fn input() -> String {
let mut s = String::new();
let _=stdout().flush();
stdin().read_line(&mut s).expect("Did not enter a correct string");
if let Some('\n')=s.chars().next_back() {
s.pop();
}
if let Some('\r')=s.chars().next_back() {
s.pop();
}
return s;
}
// place an X or O on a board
fn place(board: &mut [[i8; 9]; 9], player: i8, scope: u8, p: u8) {
let p_round: u8 = p / 3;
let mut scope_round: u8 = scope / 3;
scope_round *= 3;
let r: u8 = scope_round + p_round;
let c: u8 = 3 * (scope % 3) + (p % 3);
let slice = get_slice(*board, scope);
let ru: usize = r as usize;
let cu: usize = c as usize;
if small_winner(slice) == 0 {
board[ru][cu] = player;
}
else {
board[ru][cu] = player * 2;
}
}
// get an entry given the scope and the local index
fn get(board: [[i8; 9]; 9], scope: u8, p: u8) -> i8 {
let p_round: u8 = p / 3;
let mut scope_round: u8 = scope / 3;
scope_round *= 3;
let r: u8 = scope_round + p_round;
let c: u8 = 3 * (scope % 3) + (p % 3);
return board[r as usize][c as usize];
}
// get a 3x3 sub-board of the 9x9 full board ("slice")
pub fn get_slice(board: [[i8; 9]; 9], scope: u8) -> [[i8; 3]; 3] {
let mut slice = [[0; 3]; 3];
for row in 0..3 {
for col in 0..3 {
slice[row][col] = get(board, scope, (3*row + col) as u8);
}
}
return slice;
}
// print a board so the player can see or for debug
pub fn print_board(board: &Board) {
// calculate the last move
let mut last_move = (9, 9);
if board.parent.is_some() {
let pscope = unsafe{DB[board.parent.unwrap()].scope};
last_move = ((pscope / 3) * 3 + (board.scope / 3), (pscope % 3) * 3 + (board.scope % 3));
}
// see if you can go anywhere this turn
let go_anywhere = is_full(get_slice(board.brd, board.scope));
println!();
for row in 0..9 {
// horizontal dividers
if row % 3 == 0 && row != 0 {
println!("{}", "-".repeat(23));
}
for col in 0..9 {
// vertical dividers
if col % 3 == 0 && col != 0 {
print!(" |")
}
// get scope winner
let scope: u8 = ((row / 3) as u8) * 3 + (col / 3) as u8;
let b_winner = small_winner(get_slice(board.brd, scope));
let value = board.brd[row][col];
// smart print for color
let smart_print = |s: String| {
if (go_anywhere || scope == board.scope) && board.brd[row][col] == 0 {
print!("{}", s.green());
}
else if row == last_move.0 as usize && col == last_move.1 as usize {
print!("{}", s.red());
}
else {
print!("{}", s);
}
};
if b_winner == 0 {
if value == 1 || value == 2 {
smart_print(" X".to_string());
}
else if value == -1 || value == -2 {
smart_print(" O".to_string());
}
else {
smart_print (" _".to_string());
}
}
else {
if row > 0 && col > 0 && (row - 1) % 3 == 0 && (col - 1) % 3 == 0 {
// print filled board with central winner
if board.brd[row][col] == 0 {
smart_print(" _".to_string());
}
else {
// print the winner in the center
if b_winner == 1 {
smart_print(" X".to_string());
}
else {
smart_print(" O".to_string());
}
}
}
else {
if board.brd[(((row / 3) as u8) * 3 + 1) as usize][(((col / 3) as u8) * 3 + 1) as usize] == 0 {
if value == 0 {
smart_print(" _".to_string());
}
else {
// board conquered and middle not occupied
// print the winner so it's not ambiguous
if b_winner == 1 {
smart_print(" X".to_string());
}
else {
smart_print(" O".to_string());
}
}
}
else {
// board conquered and middle occupied
if value == 0 {
smart_print(" _".to_string());
}
else {
smart_print(" *".to_string());
}
}
}
}
}
println!();
}
println!();
}
// check if there is a full board winner
fn winner(board: [[i8; 9]; 9]) -> i8 {
let mut winners: [[i8; 3]; 3] = [[0; 3]; 3];
for b_row in 0..3 {
for b_col in 0..3 {
let slice = get_slice(board, (b_row*3 + b_col) as u8);
winners[b_row][b_col] = small_winner(slice);
}
}
return small_winner(winners);
}
// check if there is a 3x3 board winner
pub fn small_winner(board: [[i8; 3]; 3]) -> i8 {
// check rows
for row in 0..3 {
let mut counts = [0; 2];
for col in 0..3 {
if board[row][col] == 1 {
counts[0] += 1;
}
else if board[row][col] == -1 {
counts[1] += 1;
}
}
// row is useless if blocked
if counts[0] == 3 {
return 1;
}
else if counts[1] == 3 {
return -1;
}
}
// check cols
for col in 0..3 {
let mut counts = [0; 2];
for row in 0..3 {
if board[row][col] == 1 {
counts[0] += 1;
}
else if board[row][col] == -1 {
counts[1] += 1;
}
}
// col is useless if blocked
if counts[0] == 3 {
return 1;
}
else if counts[1] == 3 {
return -1;
}
}
// check diagonals
{
let mut counts = [0; 2];
for i in 0..3 {
if board[i][i] == 1 {
counts[0] += 1;
}
else if board[i][i] == -1 {
counts[1] += 1;
}
}
if counts[0] == 3 {
return 1;
}
else if counts[1] == 3 {
return -1;
}
}
{
let mut counts = [0; 2];
for i in 0..3 {
if board[i][2-i] == 1 {
counts[0] += 1;
}
else if board[i][2-i] == -1 {
counts[1] += 1;
}
}
if counts[0] == 3 {
return 1;
}
else if counts[1] == 3 {
return -1;
}
}
return 0;
}
// convert a board to a str representation for easy json storing
pub fn board_to_str(board: & [[i8; 3]; 3]) -> String {
// add 1 to avoid negatives
return format!("{}{}{}{}{}{}{}{}{}",
board[0][0]+1, board[0][1]+1, board[0][2]+1,
board[1][0]+1, board[1][1]+1, board[1][2]+1,
board[2][0]+1, board[2][1]+1, board[2][2]+1)
}
// rate a board by "pseudo-probability"
pub fn rate_board(board: [[i8; 9]; 9]) -> (f32, f32) {
let mut overall_prob: (f32, f32) = (0.0, 0.0);
let mut scope_probs: [[(f32, f32); 3]; 3] = [[(0.0, 0.0); 3]; 3];
for scope in 0..9 {
let brd_str = board_to_str(&get_slice(board, scope));
let swinner = small_winner(get_slice(board, scope));
if swinner == -1 {
scope_probs[scope as usize / 3 as usize][scope as usize % 3 as usize] = (0.0, 1.0);
}
else if swinner == 1 {
scope_probs[scope as usize / 3 as usize][scope as usize % 3 as usize] = (1.0, 0.0);
}
else {
scope_probs[scope as usize / 3 as usize][scope as usize % 3 as usize] = *PROBS.get(&brd_str).unwrap();
}
}
// rate big board
// rows
for row in 0..3 {
let mut row_prob: (f32, f32) = (1.0, 1.0);
for col in 0..3 {
row_prob = (row_prob.0 * scope_probs[row][col].0, row_prob.1 * scope_probs[row][col].1);
}
// add to overall prob
overall_prob = (overall_prob.0 + (1.0 - overall_prob.0) * row_prob.0, overall_prob.1 + (1.0 - overall_prob.1) * row_prob.1);
}
// cols
for col in 0..3 {
let mut col_prob: (f32, f32) = (1.0, 1.0);
for row in 0..3 {
col_prob = (col_prob.0 * scope_probs[row][col].0, col_prob.1 * scope_probs[row][col].1);
}
// add to overall prob
overall_prob = (overall_prob.0 + (1.0 - overall_prob.0) * col_prob.0, overall_prob.1 + (1.0 - overall_prob.1) * col_prob.1);
}
// diagonal 1
{
let mut diag_prob: (f32, f32) = (1.0, 1.0);
for diag in 0..3 {
diag_prob = (diag_prob.0 * scope_probs[diag][diag].0, diag_prob.1 * scope_probs[diag][diag].1);
}
// add to overall prob
overall_prob = (overall_prob.0 + (1.0 - overall_prob.0) * diag_prob.0, overall_prob.1 + (1.0 - overall_prob.1) * diag_prob.1);
}
// diagonal 2
{
let mut diag_prob: (f32, f32) = (1.0, 1.0);
for diag in 0..3 {
diag_prob = (diag_prob.0 * scope_probs[2 - diag][diag].0, diag_prob.1 * scope_probs[2 - diag][diag].1);
}
// add to overall prob
overall_prob = (overall_prob.0 + (1.0 - overall_prob.0) * diag_prob.0, overall_prob.1 + (1.0 - overall_prob.1) * diag_prob.1);
}
return overall_prob;
}
// check if the board is full
fn is_full(board: [[i8; 3]; 3]) -> bool {
for row in 0..3 {
for col in 0..3 {
if board[row][col] == 0 {
return false;
}
}
}
return true;
}
// try all of the possibilities for this move
fn domove(board: &Board, go_scope: u8, pindex: u8) -> usize {
if board.player == 1 {
if is_full(get_slice(board.brd, board.scope)) {
let mut veccount: usize = 0;
let my_row = (go_scope / 3) as usize * 3 + (pindex / 3) as usize;
let my_col = (go_scope % 3) as usize * 3 + (pindex % 3) as usize;
let large_p = my_row * 9 + my_col;
for row in 0..9 {
for col in 0..9 {
if row * 9 + col < large_p {
let this_scope = (row / 3) * 3 + (col / 3);
let this_p = (row % 3) * 3 + (col % 3);
if get(board.brd, this_scope as u8, this_p as u8) == 0 {
veccount += 1;
}
}
}
}
return board.children[veccount];
}
else {
let mut veccount: usize = 0;
for row in 0..3 {
for col in 0..3 {
if row * 3 + col < pindex {
if get(board.brd, board.scope, (row * 3 + col) as u8) == 0 {
veccount += 1;
}
}
}
}
return board.children[veccount];
}
}
else {
return board.children[pindex as usize];
}
}
// get the computer's optimal move at this instant
pub fn getcpmove(db: &mut Vec<Board>, curindex: usize, maxdepth: Option<u8>) -> u8 {
for child in 0..db[curindex].children.len() {
let newindex = db[curindex].children[child];
calcmove(&mut *db, newindex, maxdepth);
}
let haswon = small_winner(get_slice(db[curindex].brd, db[curindex].scope)) != 0;
let mut minindex: u8 = 0;
let mut minrating: Option<f32> = None;
let mut all_loop = true;
for childnum in 0..db[curindex].children.len() {
let child = &db[db[curindex].children[childnum]];
let isloop = haswon && (loopstuck(&db, curindex, childnum));
let nextwon = small_winner(get_slice(child.brd, child.scope)) != 0;
if !(isloop && !nextwon) {
all_loop = false;
}
}
for childnum in 0..db[curindex].children.len() {
let child = &db[db[curindex].children[childnum]];
let childrating = child.prediction.unwrap();
// print!(", {}", childrating);
let isloop = haswon && (loopstuck(&db, curindex, childnum));
let nextwon = small_winner(get_slice(child.brd, child.scope)) != 0;
if (all_loop || !(isloop && !nextwon)) && (minrating == None || childrating < minrating.unwrap()) {
minrating = Some(childrating);
minindex = childnum as u8;
}
}
println!("Computer is moving towards a board with rating {}", minrating.unwrap());
return minindex;
}
// calculate the optimal move (recursive)
fn calcmove(db: &mut Vec<Board>, curindex: usize, maxdepth: Option<u8>) {
if maxdepth.is_some() && db[curindex].movenum == maxdepth.unwrap() {
return;
}
else {
for child in 0..db[curindex].children.len() {
let newindex = db[curindex].children[child];
calcmove(&mut *db, newindex, maxdepth);
}
if !db[curindex].children.len() > 0 {
updatepred(&mut *db, curindex);
}
}
}
// determine if the computer is stuck in a loop
// where it is always sent to the same board
fn loopstuck(db: &Vec<Board>, curindex: usize, child: usize) -> bool {
let stuckboard = db[curindex].scope;
let grandchildren = &db[db[curindex].children[child]].children;
for grandchild in 0..grandchildren.len() {
if db[grandchildren[grandchild]].scope == stuckboard {
return true;
}
}
return false;
}