-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathall_AI_iterations.py
2252 lines (1920 loc) · 94.9 KB
/
all_AI_iterations.py
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
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
751
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
import statistics
import copy
import time
import numpy as np
import pandas as pd
import os
import math
def save_game_result_to_csv(file_name, model, score, duration, board, other_data: dict = None):
"""
Save game results to a CSV file.
Args:
file_name (str): The name of the CSV file.
model (str): The model used for the game.
score (int): The score achieved in the game.
duration (float): The duration of the game in seconds.
board (list): 2d array of the board when the game ended
other_data (dict): dictionary of other data to be added
"""
# Create the 'saved games' folder if it doesn't exist
folder_path = os.path.join(os.getcwd(), 'saved games')
if not os.path.exists(folder_path):
os.makedirs(folder_path)
# Check if the CSV file exists
file_path = os.path.join(folder_path, f"{file_name}.csv")
if os.path.exists(file_path):
print(f"FILE PATH EXISTS: {file_path}")
# Load the existing CSV file
df = pd.read_csv(file_path)
else:
# Create a new DataFrame
df = pd.DataFrame(columns=['Model', 'Score', 'Duration', 'Board'])
# Flatten the board into a 1D list
flattened_board = np.array(board).flatten().tolist()
# if other_data is not None:
# # Add other_data columns to the DataFrame
# for key, value in other_data.items():
# df[key] = value
# Create a new row with the provided data
new_row = pd.Series({'Model': model, 'Score': score, 'Duration': duration, 'Board': flattened_board, **other_data}) # added other data thing
# if other_data is not None:
# # Add other_data columns to the new row
# for key, value in other_data.items():
# new_row[key] = value
if other_data is not None:
if not set(other_data.keys()).issubset(df.columns):
df[list(other_data.keys())] = None
df.loc[len(df)] = new_row
# Save the DataFrame to the CSV file
df.to_csv(f"{file_path}", index=False)
class RandomMoves:
def __init__(self, game):
self.game = game
def run(self):
while not self.game.game_over_check():
self.game.move(np.random.randint(0, 4), illegal_warn=False)
else:
print("done")
save_game_result_to_csv("MC5", "random", self.game.score, 0, self.game.board.board)
class Down2:
def __init__(self, game, print_moves=False):
self.print_moves = print_moves
self.game = game
self.game.setup_board()
def run(self):
# if down is legal, do until illegal
# if left is legal, do until illegal, then start from top
# if right is legal, do until illegal, then start from top
# if up is legal, do until illegal, then start from top
i = 0
j = 1
while True:
# print(f"------------------i = {i}...j = {j}------------------")
if self.print_moves:
self.game.display_updated_board()
if j % 2 != 0:
if not self.game.down(): # does down until illegal
# print(f"i = {i}, j = {j}, down illegal")
j *= 2 # set j to 2, so we skip down
# if j % 7 == 0:
# print(f"GAME OVER, i = {i}, j = {j}")
# break
elif j % 3 != 0:
if not self.game.left():
# print(f"i = {i}, j = {j}, left illegal")
j *= 3
continue
else:
j = 1
elif j % 5 != 0:
if not self.game.right():
# print(f"i = {i}, j = {j}, right illegal")
j *= 5
continue
else:
j = 1
elif j % 7 != 0:
if not self.game.up():
# print(f"i = {i}, j = {j}, up illegal")
j *= 7
print(f"GAME OVER, i = {i}, j = {j}")
break
#continue
else:
j = 1
i += 1
def reset(self):
self.__init__(self.game) # wait I need a new game object
class DownBot:
def __init__(self, game, print_moves=False):
self.print_moves = print_moves
self.game = game
self.game.setup_board()
def run(self):
while True:
print("----------------------------------------")
if self.print_moves:
self.game.display_updated_board()
print("----------------------------------------")
#print(self.game.down())
if not self.game.down():
if not self.game.left():
if not self.game.right():
if not self.game.up():
print(f"GAME OVER. {self.game.num_moves} moves, {self.game.score}, highest = {self.game.highest_tile}")
break
def reset(self):
self.__init__(self.game)
class ManyRuns:
def __init__(self, bot_type, num_simulations, print_moves=False):
#self.print_moves = print_moves
self.num_simulations = num_simulations
self.bot = bot_type(print_moves=print_moves)
def run(self):
num_moves = []
scores = []
highest_tiles = []
for i in range(self.num_simulations):
self.bot.run()
num_moves.append(self.bot.game.num_moves)
scores.append(self.bot.game.score)
highest_tiles.append(self.bot.game.highest_tile)
self.bot.reset()
print(f"num moves: {num_moves}")
print(f"scores: {scores}")
print(f"highest tiles: {highest_tiles}")
self.analysis(num_moves, scores, highest_tiles)
def analysis(self, moves, scores, tiles):
score_mean = statistics.mean(scores)
score_SD = statistics.stdev(scores, score_mean)
print(f"SCORES: mean = {score_mean}, SD = {score_SD}")
print(f"tile: mean = {statistics.mean(tiles)}, SD = {statistics.stdev(tiles, statistics.mean(tiles))}")
#plt.plot(scores)
'''x = np.arange(0, 5000)
plt.plot(x, norm.pdf(x, score_mean, score_SD))
plt.show()'''
class MC2:
"""DOESNT WORK BC NO DEEPCOPY"""
def __init__(self, game, sims_per_turn: int = 100, verbose: bool = True) -> None:
self.main_game = game
self.sims_per_turn = sims_per_turn
self.verbose = verbose
@staticmethod
def one_game(game):
"""
Where all the magic happens: plays random moves until the game is over
args:
game (Game): game object to manipulate
"""
while not game.game_over_check():
current_direction = np.random.randint(0, 4)
game.move(current_direction, print_board=False, illegal_warn=False)
else:
return game.score
def n_games(self):
move_dict = {0: "right", 1: "left", 2: "up", 3: "down"}
scores = []
for direction in range(4):
game_copy = copy.deepcopy(self.main_game)
if not game_copy.move(direction, print_board=False, illegal_warn=False):
# print(f"illegal to move {move_dict[direction]}") # illegal warn but specifies direction
scores.append(game_copy.score)
else:
# print("ok")
direction_scores_to_avg = []
for sim in range(self.sims_per_turn):
# print(f"sim num {sim}")
current_score = self.one_game(game_copy)
direction_scores_to_avg.append(current_score)
scores.append(np.average(np.array(direction_scores_to_avg)))
# print(f"done direction {direction}")
best_direction = scores.index(max(scores))
if self.verbose:
print(f"{np.array(scores).round()}\t"
f"going {move_dict[best_direction]}\t"
f"score: {self.main_game.score}\t"
f"proj score: {round(max(scores))}")
# time.sleep(0.01)
self.main_game.move(best_direction)
# print("ok")
def run(self):
while not self.main_game.game_over_check():
self.n_games()
self.main_game.display_updated_board()
else:
if self.verbose:
print(f"GAME OVER: SCORE = {self.main_game.score}")
class MC3:
"""
same as MC2 but tracks projected scores. only selects moves which increase projected score
Uses max score instead of average as projected score.
seems to somehow be worse despite being much slower
DOESNT WORK BECAUSE NO DEEPCOPY
"""
def __init__(self, game, sims_per_turn: int = 100, verbose: bool = True) -> None:
self.main_game = game
self.sims_per_turn = sims_per_turn
self.verbose = verbose
self.projected_scores = [0]
@staticmethod
def one_game(game):
"""
Where all the magic happens: plays random moves until the game is over
args:
game (Game): game object to manipulate
"""
while not game.game_over_check():
current_direction = np.random.randint(0, 4)
game.move(current_direction, print_board=False, illegal_warn=False)
else:
return game.score
def n_games(self):
move_dict = {0: "right", 1: "left", 2: "up", 3: "down"}
scores = []
num_beat_attempts = 0
while num_beat_attempts < 100:
for direction in range(4):
game_copy = copy.deepcopy(self.main_game)
if not game_copy.move(direction, print_board=False, illegal_warn=False):
# if it's illegal to move in the current direction, just add the current score to decision list
scores.append(game_copy.score)
else:
direction_scores_to_avg = []
for sim in range(self.sims_per_turn):
current_score = self.one_game(game_copy)
direction_scores_to_avg.append(current_score)
scores.append(np.average(np.array(direction_scores_to_avg)))
projected_score_current = max(scores)
print(f"current projected score: {scores}, {projected_score_current}")
if projected_score_current > self.projected_scores[-1]:
break
num_beat_attempts += 1
if num_beat_attempts < 100: # reset and try to beat score only if we're not on last attempt
scores = []
best_direction = scores.index(max(scores))
if self.verbose:
print(f"{np.array(scores).round()}\t"
f"going {move_dict[best_direction]}\t"
f"score: {self.main_game.score}\t"
f"proj score: {round(max(scores))}")
self.projected_scores.append(max(scores))
self.main_game.move(best_direction)
def run(self):
while not self.main_game.game_over_check():
self.n_games()
self.main_game.display_updated_board()
else:
if self.verbose:
print(f"GAME OVER: SCORE = {self.main_game.score}")
class MC4:
"""
same as the stackoverflow guy
THIS IS ACTUALLY A GOOD MODEL! PROBABLY BETTER THAN up to and including MC9
FIRST WORKING DESIGN BC USES DEEPCOPY ON INNER OBJECT
same as MC2 but
current_score = self.one_game(copy.deepcopy(game_copy)) instead of current_score = self.one_game(game_copy)
one in MC2 resulted in direction_scores_to_avg being all the same number. this version doesn't
"""
def __init__(self, game, sims_per_turn: int = 100, verbose: bool = True) -> None:
self.main_game = game
self.sims_per_turn = sims_per_turn
self.verbose = verbose
@staticmethod
def one_game(game):
"""
Where all the magic happens: plays random moves until the game is over
args:
game (Game): game object to manipulate
"""
while not game.game_over_check():
current_direction = np.random.randint(0, 4)
game.move(current_direction, print_board=False, illegal_warn=False)
else:
return game.score
def n_games(self):
move_dict = {0: "right", 1: "left", 2: "up", 3: "down"}
scores = []
for direction in range(4):
game_copy = copy.deepcopy(self.main_game)
if not game_copy.move(direction, print_board=False, illegal_warn=False):
# print(f"illegal to move {move_dict[direction]}") # illegal warn but specifies direction
scores.append(game_copy.score)
else:
direction_scores_to_avg = []
for sim in range(self.sims_per_turn):
# print(f"sim num {sim}")
current_score = self.one_game(copy.deepcopy(game_copy))
direction_scores_to_avg.append(current_score)
# print("------------------------direction_scores_to_avg------------------------")
# print(direction_scores_to_avg)
scores.append(np.average(np.array(direction_scores_to_avg)))
# print(f"done direction {direction}")
best_direction = scores.index(max(scores))
scores = np.array(scores)
if self.verbose:
print(f"{scores.round()}\t"
f"going {move_dict[best_direction]}\t"
f"score: {self.main_game.score}\t"
f"proj score: {round(max(scores))}")
# time.sleep(0.01)
# if np.all(scores == scores[0]):
# save_game_result_to_csv("MC4", "MC4_ENCOUNTER ERROR", self.main_game.score, 0, self.main_game.board.board)
# this just always ends up being the end, so no big deal AT ALL!!
self.main_game.move(best_direction)
# print("ok")
def run(self):
start_time = time.time()
while not self.main_game.game_over_check():
self.n_games()
if self.main_game.use_gui:
self.main_game.display_updated_board()
total_time = time.time() - start_time
print(f"GAME OVER: SCORE = {self.main_game.score}")
save_game_result_to_csv("MC4", f"MC4_sims_{self.sims_per_turn}", self.main_game.score, total_time, self.main_game.board.board)
class MC5:
"""
same as MC4 but picks move by highest average of top 50 moves, not highest of all 100
keeps the high tile in the corner a bit more especially near the beginning but still hardly does
next attempt could be to try switching to the MC4 strategy in critical positions where its close to losing to account for unlucky events
could also try something where it attempts each possible next tile spawn 5 times or something, then do this eliminate bad attempts thing where it eliminates bad attempts given a certain next move
that way we guarantee the
could even maximize expected value := P(direction maximized) > P(all other directions maximize)
or maximize sum top_5_score for direction P(getting it) (assumes we check each tile) this idea not fleshed out
"""
def __init__(self, game, sims_per_turn: int = 100, verbose: bool = True) -> None:
self.main_game = game
self.sims_per_turn = sims_per_turn
self.verbose = verbose
@staticmethod
def one_game(game):
"""
Where all the magic happens: plays random moves until the game is over
args:
game (Game): game object to manipulate
"""
while not game.game_over_check():
current_direction = np.random.randint(0, 4)
game.move(current_direction, print_board=False, illegal_warn=False)
else:
return game.score
def n_games(self):
move_dict = {0: "right", 1: "left", 2: "up", 3: "down"}
scores = []
for direction in range(4):
game_copy = copy.deepcopy(self.main_game)
if not game_copy.move(direction, print_board=False, illegal_warn=False):
# print(f"illegal to move {move_dict[direction]}") # illegal warn but specifies direction
scores.append(game_copy.score)
else:
direction_scores_to_avg = []
for sim in range(self.sims_per_turn):
# print(f"sim num {sim}")
current_score = self.one_game(copy.deepcopy(game_copy))
direction_scores_to_avg.append(current_score)
direction_scores_to_avg_upper_quantile = np.sort(np.array(direction_scores_to_avg))[::-1][:50]
scores.append(np.average(direction_scores_to_avg_upper_quantile))
# print(f"done direction {direction}")
best_direction = scores.index(max(scores))
if self.verbose:
print(f"{np.array(scores).round()}\t"
f"going {move_dict[best_direction]}\t"
f"score: {self.main_game.score}\t"
f"proj score: {round(max(scores))}")
# time.sleep(0.01)
self.main_game.move(best_direction)
# print("ok")
def run(self):
start_time = time.time()
while not self.main_game.game_over_check():
self.n_games()
self.main_game.display_updated_board()
total_time = time.time() - start_time
print(f"GAME OVER: SCORE = {self.main_game.score}")
save_game_result_to_csv("MC5", "MC5", self.main_game.score, total_time, self.main_game.board.board)
class MC6:
"""
EVALUATES ALL POSSIBLE NEXT MOVES
"""
def __init__(self, game, game_obj, sims_per_turn: int = 100, verbose: bool = True) -> None:
self.main_game = game
self.game_obj = game_obj
self.sims_per_turn = sims_per_turn
self.verbose = verbose
def one_game(self, game):
"""
Where all the magic happens: plays random moves until the game is over
args:
game (Game): game object to manipulate
"""
i = 1 # get rid of i
while not game.game_over_check():
# print(f"DETECTED GAME OVER after {i} in one_game")
# time.sleep(0.01)
current_direction = np.random.randint(0, 4)
game.move(current_direction, print_board=False, illegal_warn=False)
i += 1
if type(game.score) != int: # trying to make sure there's no NAN by replacing non int values which somehow seem to arise with current score
return self.main_game.score
return game.score
def n_games(self):
depth_dict_4 = {
15: 1,
14: 1,
13: 1,
12: 1,
11: 1,
10: 1,
9: 1,
8: 2,
7: 2, # 126 for 2
6: 2, # 108 for 2
5: 3, # 135 for 2
4: 4, # 144 for 2
3: 5, # 135 for 2
2: 8, # 144 for 2
1: 15 # 135 for 2
}
move_dict = {0: "right", 1: "left", 2: "up", 3: "down"}
scores = []
for direction in range(4):
game_copy = copy.deepcopy(self.main_game)
if not game_copy.move(direction, print_board=False, illegal_warn=False, add_tile=False):
# print(f"illegal to move {move_dict[direction]}") # illegal warn but specifies direction
scores.append(game_copy.score)
else:
# THIS IS WHERE WE MAKE THE NODES START
# take board we're currently working on, get list of all possible tiles that could spawn
# print(f"There are {len(game_copy.board.get_empty_tiles())} empty squares")
tmp = copy.deepcopy(game_copy.board)
boards2, boards4 = self.get_possible_boards(tmp) # will deepcopying the boardhlp?
# print("BOARDS4 START")
# print(boards4)
# print("BOARDS4 END")
num_open_tiles = len(boards2) # try increasing num open tiles to get rid of NAN?
direction_scores_to_avg = []
for board in boards4: # for each board, do necessary depth
for depth in range(depth_dict_4[num_open_tiles]):
# make new game obj with same score as current game
current_game_obj = self.game_obj(board=board, use_gui=False)
current_game_obj.score = game_copy.score
# print("MADE OBJ IN LOOP OF BOARDS4")
# current_game_obj.display_updated_board() # temp line!
# time.sleep(1)
current_score = self.one_game(copy.deepcopy(current_game_obj))
direction_scores_to_avg.append(current_score)
# print("DONE LOOP OF BOARDS4")
if num_open_tiles == 0: # I THINK THIS IS WHATS CAUSING IT
print("WARNING!! THIS IS CAUSING NAN PROBS")
print(f"num_open_tiles = {num_open_tiles}")
print("CANT HAVE 0 open tiles bc the dict cant understand that and it makes 0 sense")
print(f"SHOWING BOARD2 and 4 list. len board 2, 4 = {len(boards2), boards4}") # boards2 and 4 have len0 is the problem!!
for board in boards2:
board.print()
print("---the above was from boards2---")
for board in boards4:
board.print()
print("---the above was from boards2---")
time.sleep(10)
if len(boards4) == 0 or len(boards2) == 0 or depth_dict_4[num_open_tiles] == 0:
print("WARNING!! THIS IS CAUSING NAN PROBS")
print("NUM OPEN TILES:")
print(f"len boards4, 2, depth dict: {len(boards4)}, {len(boards2)}, {depth_dict_4[num_open_tiles]}")
time.sleep(10)
for board in boards2: # this can be condensed, only diff is *9 in second for statement
for depth in range(depth_dict_4[num_open_tiles] * 9): # * 9 bc 90% chance of 2 spawning
# make new game obj
current_game_obj = self.game_obj(board=board, use_gui=False)
current_game_obj.score = game_copy.score
current_score = self.one_game(copy.deepcopy(current_game_obj))
direction_scores_to_avg.append(current_score)
# NOW ADD THE TILE ONCE ALL EVALUATING IS DONE??
game_copy.add_new_tile()
if self.verbose:
np.set_printoptions(linewidth=np.inf)
print(np.array(direction_scores_to_avg)) # getting nans from direction_scores_to_avg!!!!
scores.append(np.average(np.array(direction_scores_to_avg))) # DOES ALL, NOT JUST BETTER HALF, BUT THE WHOLE POINT OF THIS STRAT IS IT ENABLES BETTER USAGE OF UPPER HALF BC THE BAD SCORES WERE ELIMINATING AREN'T DUE TO LUCK BC WE ENSURE ALL POSSIBLE SPAWNS ARE CONSIDERED
if len(direction_scores_to_avg) == 0:
print("len(direction_scores_to_avg) = 0!!")
print(f"len boards4, 2, depth dict: {len(boards4)}, {len(boards2)}, {depth_dict_4[num_open_tiles]}")
print(f"CURRENTLY ON DIRECTION {direction}, {move_dict[direction]}")
time.sleep(10)
if self.verbose:
print(np.array(scores).round())
best_direction = scores.index(max(scores)) # THIS SHOULD BE UPDATED TO EXPECTED VALUE CALCULATION. DONE IN MC7
if self.verbose:
print(f"{np.array(scores).round()}\t"
f"going {move_dict[best_direction]}\t"
f"score: {self.main_game.score}\t"
f"proj score: {round(np.nanmax(scores))}, " # BAND AID SOLN to ignore NANs but idk what causes them
f"#EVALs: {len(boards4)}")
self.main_game.move(best_direction)
if self.verbose:
self.main_game.board.print()
@staticmethod
def get_possible_boards(board) -> tuple[list, list]:
"""
takes current board, returns list of all possible board "responses"
:param board: board of time (Board) (custom object),
:return: ([boards with 2s], [boards with 4s])
"""
# print("IN GET POSSIBLE BOARDS with baord =")
# board.print(2)
# print("DONE START OF IN GET POSSIBLE BOARDS with baord =")
boards2, boards4 = [], []
# print("------------------------new enter into get possible boards----------------------------")
# print("BOARD IN THE FN = ")
# board.print()
for new_tile_value in (2, 4):
# print(f"board.get_empty_tiles() = {board.get_empty_tiles()}")
for y, x in board.get_empty_tiles():
new_board = copy.deepcopy(board) # THIS IS WHERE THE ERROR IS FROM
new_board.add_tile(tile_value=new_tile_value, x_coord=x, y_coord=y)
# print("MAGIC")
# new_board.print(2)
# time.sleep(1)
if new_tile_value == 2:
boards2.append(new_board)
else:
boards4.append(new_board)
# print("DONE POSSIBLE BOARDS")
return boards2, boards4 # MB the nan are caused by boards that cant get evaluated for some reason...?
def run(self):
start_time = time.time()
while not self.main_game.game_over_check():
self.n_games()
if self.main_game.use_gui:
self.main_game.display_updated_board()
total_time = time.time() - start_time
print(f"GAME OVER: SCORE = {self.main_game.score}")
save_game_result_to_csv("MC6", "MC6", self.main_game.score, total_time, self.main_game.board.board)
class MC7:
"""
EVALUATES ALL POSSIBLE NEXT MOVES. USES EXPECTED VALUE EVALUATION, WHICH TURNS OUT TO GIVE SAME ANSWER AS MC6 EVALUATION
WHEN ALL POSSIBLE MOVES ARE CONSIDERED
"""
def __init__(self, game, game_obj, sims_per_turn: int = 100, verbose: bool = True) -> None:
self.main_game = game
self.game_obj = game_obj
self.sims_per_turn = sims_per_turn
self.verbose = verbose
@staticmethod
def one_game(game):
"""
Where all the magic happens: plays random moves until the game is over
args:
game (Game): game object to manipulate
"""
while not game.game_over_check():
current_direction = np.random.randint(0, 4)
game.move(current_direction, print_board=False, illegal_warn=False)
else:
return game.score
def n_games(self):
depth_dict_4 = {
15: 1,
14: 1,
13: 1,
12: 1,
11: 1,
10: 1,
9: 1,
8: 2,
7: 2, # 126 for 2
6: 2, # 108 for 2
5: 3, # 135 for 2
4: 4, # 144 for 2
3: 5, # 135 for 2
2: 8, # 144 for 2
1: 15 # 135 for 2
}
move_dict = {0: "right", 1: "left", 2: "up", 3: "down"}
scores = []
mc6_scores = []
for direction in range(4):
game_copy = copy.deepcopy(self.main_game)
if not game_copy.move(direction, print_board=False, illegal_warn=False, add_tile=False):
# print(f"illegal to move {move_dict[direction]}") # illegal warn but specifies direction
scores.append(game_copy.score)
else:
# THIS IS WHERE WE MAKE THE NODES START
# take board we're currently working on, get list of all possible tiles that could spawn
boards2, boards4 = self.get_possible_boards(game_copy.board)
# print("GOT BOARDS")
# print("BOARDS4 START")
# print(boards4)
# print("BOARDS4 END")
num_empty_tiles = len(boards2)
direction_scores_to_avg2, direction_scores_to_avg4 = [], []
for board in boards4: # for each board, do necessary depth
for depth in range(depth_dict_4[num_empty_tiles]):
# make new game obj
current_game_obj = self.game_obj(board=board, use_gui=False)
current_game_obj.score = game_copy.score
# print("MADE OBJ IN LOOP OF BOARDS4")
# current_game_obj.display_updated_board() # temp line!
# time.sleep(1)
current_score = self.one_game(copy.deepcopy(current_game_obj))
direction_scores_to_avg4.append(current_score)
# print("DONE LOOP OF BOARDS4")
for board in boards2: # this can be condensed, only diff is *9 in second for statement
for depth in range(depth_dict_4[num_empty_tiles] * 9): # * 9 bc 90% chance of 2 spawning
# make new game obj
current_game_obj = self.game_obj(board=board, use_gui=False)
current_game_obj.score = game_copy.score
current_score = self.one_game(copy.deepcopy(current_game_obj))
direction_scores_to_avg2.append(current_score)
scores.append(self.expected_value(direction_scores_to_avg4, direction_scores_to_avg2, num_empty_tiles))
mc6_scores.append(np.average(np.array(direction_scores_to_avg4 + direction_scores_to_avg2)))
# finish evaluation, then add piece
game_copy.add_new_tile()
if self.verbose:
print(f"MC6 SCORES: {np.array(mc6_scores).round()}")
print(f"MC7 SCORES: {np.array(scores).round()}")
best_direction = scores.index(max(scores)) # THIS SHOULD BE UPDATED
if self.verbose:
print(f"{np.array(scores).round()}\t"
f"going {move_dict[best_direction]}\t"
f"score: {self.main_game.score}\t"
f"proj score: {round(np.nanmax(scores))}"
f"4,2 #EVALs: {len(boards4), len(boards2)}")
self.main_game.move(best_direction)
if self.verbose:
self.main_game.board.print()
@staticmethod
def expected_value(scores4, scores2, num_empty):
"""DOES CALCULATION IN BLUE CIRCLE ON WHITEBOARD PIC JUN ^
THIS COULD BE VECTORIZED FOR MORE SPEED
SEEMS TO GIVE ALMOST THE EXACT SAME SCORE AS MC6 BUT SOMETIEMS ONE IS WAY LOWER
"""
scores2, scores4 = np.array(scores2), np.array(scores4)
output2 = 1 / num_empty
# output2 += np.sum(scores4 * 0.1) / len(scores4)
# output2 += np.sum(scores2 * 0.9) / len(scores2)
output2 += np.mean(scores4) * 0.1 # DOES SAME THING AS ORIGINAL BUT FASTER
output2 += np.mean(scores2) * 0.9
# output = 1 / num_empty
# for i in scores4:
# output += i * 0.1 / len(scores4) # divide by len to scale properly. wait but mb multiplying by 0.1 does the scaling bc len(scores4) = 0.1 len(scores2)
# for i in scores2:
# output += np.average(scores2) * 0.9
# output += i * 0.9 / len(scores2)
# print(f"OUTPUT = {output}")
# print(f"OUTPUT1=OUTPUT2: {round(output) == round(output2)}")
# print(f"OUTPUT1 and 2: {output, output2}")
return output2
@staticmethod
def get_possible_boards(board) -> tuple[list, list]:
"""
takes current board, returns list of all possible board "responses"
:param board: board of time (Board) (custom object),
:return: ([boards with 2s], [boards with 4s])
"""
# print("IN GET POSSIBLE BOARDS with baord =")
# board.print(2)
# print("DONE START OF IN GET POSSIBLE BOARDS with baord =")
boards2, boards4 = [], []
for new_tile_value in (2, 4):
for y, x in board.get_empty_tiles():
new_board = copy.deepcopy(board) # THIS IS WHERE THE ERROR IS FROM
new_board.add_tile(tile_value=2, x_coord=x, y_coord=y)
# print("MAGIC")
# new_board.print(2)
# time.sleep(1)
if new_tile_value == 2:
boards2.append(new_board)
else:
boards4.append(new_board)
return boards2, boards4
def run(self):
start_time = time.time()
while not self.main_game.game_over_check():
self.n_games()
if self.verbose:
self.main_game.display_updated_board()
total_time = time.time() - start_time
print(f"GAME OVER: SCORE = {self.main_game.score}")
save_game_result_to_csv("MC7", "MC7", self.main_game.score, total_time, self.main_game.board.board)
class MC8:
"""
MC7 but evaluates top half of moves
Gets very fast when the board starts filling up
still not fantastic
try max instead of avg bc all nodes are covered
wait I think this eliminates whole nodes bc its not seperate lists
"""
def __init__(self, game, game_obj, sims_per_turn: int = 100, verbose: bool = True) -> None:
self.main_game = game
self.game_obj = game_obj
self.sims_per_turn = sims_per_turn
self.verbose = verbose
@staticmethod
def one_game(game):
"""
Where all the magic happens: plays random moves until the game is over
args:
game (Game): game object to manipulate
"""
while not game.game_over_check():
current_direction = np.random.randint(0, 4)
game.move(current_direction, print_board=False, illegal_warn=False)
else:
return game.score
def n_games(self):
depth_dict_4 = {
15: 1, # 135 for 2; total: 138
14: 1, # 126 for 2; total: 141
13: 1, # 117 for 2; total: 130
12: 1, # 108 for 2; total: 123
11: 1, # 99 for 2; total: 114
10: 1, # 90 for 2; total: 103
9: 1, # 81 for 2; total: 92
8: 2, # 144 for 2; total: 154
7: 2, # 126 for 2; total: 135
6: 2, # 108 for 2; total: 116
5: 3, # 135 for 2; total: 143
4: 4, # 144 for 2; total: 152
3: 5, # 135 for 2; total: 143
2: 8, # 144 for 2; total: 154
1: 15 # 135 for 2; total: 151
}
move_dict = {0: "right", 1: "left", 2: "up", 3: "down"}
scores = []
mc6_scores = []
for direction in range(4):
game_copy = copy.deepcopy(self.main_game)
if not game_copy.move(direction, print_board=False, illegal_warn=False, add_tile=False):
# print(f"illegal to move {move_dict[direction]}") # illegal warn but specifies direction
scores.append(game_copy.score)
else:
# THIS IS WHERE WE MAKE THE NODES START
# take board we're currently working on, get list of all possible tiles that could spawn
boards2, boards4 = self.get_possible_boards(game_copy.board)
# print("GOT BOARDS")
# print("BOARDS4 START")
# print(boards4)
# print("BOARDS4 END")
num_empty_tiles = len(boards2)
direction_scores_to_avg2, direction_scores_to_avg4 = [], []
for board in boards4: # for each board, do necessary depth
for depth in range(depth_dict_4[num_empty_tiles]):
# make new game obj
current_game_obj = self.game_obj(board=board, use_gui=False)
current_game_obj.score = game_copy.score
# print("MADE OBJ IN LOOP OF BOARDS4")
# current_game_obj.display_updated_board() # temp line!
# time.sleep(1)
current_score = self.one_game(copy.deepcopy(current_game_obj))
direction_scores_to_avg4.append(current_score)
# print("DONE LOOP OF BOARDS4")
for board in boards2: # this can be condensed, only diff is *9 in second for statement
for depth in range(depth_dict_4[num_empty_tiles] * 9): # * 9 bc 90% chance of 2 spawning
# make new game obj
current_game_obj = self.game_obj(board=board, use_gui=False)
current_game_obj.score = game_copy.score
current_score = self.one_game(copy.deepcopy(current_game_obj))
direction_scores_to_avg2.append(current_score)
scores.append(self.expected_value(direction_scores_to_avg4, direction_scores_to_avg2, num_empty_tiles))
mc6_scores.append(np.average(np.array(direction_scores_to_avg4 + direction_scores_to_avg2)))
# finish evaluation, then add piece
game_copy.add_new_tile()
if self.verbose:
print(f"MC6 SCORES: {np.array(mc6_scores).round()}")
print(f"MC8 SCORES: {np.array(scores).round()}")
best_direction = scores.index(max(scores)) # THIS SHOULD BE UPDATED
if self.verbose:
print(f"{np.array(scores).round()}\t"
f"going {move_dict[best_direction]}\t"
f"score: {self.main_game.score}\t"
f"proj score: {round(np.nanmax(scores))}\n")
self.main_game.move(best_direction)
if self.verbose:
self.main_game.board.print()
@staticmethod
def expected_value(scores4, scores2, num_empty):
"""
Calculate the expected value based on scores4 and scores2 arrays.
WHITEBOARD CALCULATION
Args:
scores4 (list or ndarray): Scores monte carlo tree got for 4 spawning next.
scores2 (list or ndarray): Scores monte carlo tree got for 2 spawning next.
num_empty (int): Number of empty cells in the game board.
Returns:
float: The expected value.
"""
scores2, scores4 = np.array(scores2), np.array(scores4)
# scores2, scores4 = np.sort(scores2)[::-1], np.sort(scores4)[::-1]
# output2 = 1 / num_empty
#
# output2 += np.mean(scores4[:math.ceil(len(scores4)/2)]) * 0.1 # DOES SAME THING AS ORIGINAL BUT FASTER
# output2 += np.mean(scores2[:math.ceil(len(scores2)/2)]) * 0.9
#
# OUTPUT 2 and 3 are equivalent but output 3 is faster
# Compute the mean of the top half of scores4 and scores2
len_scores_4 = len(scores4)
len_scores_2 = len_scores_4 * 9
top_scores4_mean = np.mean(scores4[np.argsort(-scores4)[:math.ceil(len_scores_4 / 2)]])
top_scores2_mean = np.mean(scores2[np.argsort(-scores2)[:math.ceil(len_scores_2 / 2)]])
output3 = 1 / num_empty
output3 += top_scores4_mean * 0.1
output3 += top_scores2_mean * 0.9
# print(f"OUTPUT3 {output3}")
# print(f"OUTPUT2 {output2}")
# print(f"OUTPUT3=2 {output2.round(2) == output3.round(2)}")
# print(f"Len scores4, len scores2, empty {len(scores2), len(scores4), num_empty}"
# f"16-len = num_empty {16 - len(scores4) == num_empty}")
return output3
@staticmethod
def get_possible_boards(board) -> tuple[list, list]:
"""
takes current board, returns list of all possible board "responses"
:param board: board of time (Board) (custom object),
:return: ([boards with 2s], [boards with 4s])
"""
# print("IN GET POSSIBLE BOARDS with baord =")
# board.print(2)
# print("DONE START OF IN GET POSSIBLE BOARDS with baord =")
boards2, boards4 = [], []
for new_tile_value in (2, 4):
for y, x in board.get_empty_tiles():
new_board = copy.deepcopy(board) # THIS IS WHERE THE ERROR IS FROM
new_board.add_tile(tile_value=2, x_coord=x, y_coord=y)
# print("MAGIC")
# new_board.print(2)
# time.sleep(1)
if new_tile_value == 2:
boards2.append(new_board)
else:
boards4.append(new_board)
return boards2, boards4
def run(self):
start_time = time.time()
while not self.main_game.game_over_check():
self.n_games()
if self.main_game.use_gui:
self.main_game.display_updated_board()
total_time = time.time() - start_time
print(f"GAME OVER: SCORE = {self.main_game.score}")
save_game_result_to_csv("MC8", "MC8", self.main_game.score, total_time, self.main_game.board.board)