-
Notifications
You must be signed in to change notification settings - Fork 0
/
reversiAI.py
1278 lines (1162 loc) · 35.1 KB
/
reversiAI.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
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Othello Program
# John Fish
# Updated from May 29, 2015 - June 26, 2015
#
# Has both basic AI (random decision) as well as
# educated AI (minimax).
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Library import
from tkinter import *
from math import *
from time import *
from random import *
from copy import deepcopy
from collections import Counter
from statistics import mean
import operator
import argparse
import pandas as pd
#Variable setup
nodes = 0
depth = 4
moves = 0
pmctimes = []
abtimes = []
mctactimes = []
pmcscaledtimes = []
mctacscaledtimes = []
#Tkinter setup
root = Tk()
screen = Canvas(
root,
width=500,
height=600,
background="#222",
highlightthickness=0
)
screen.pack()
parser = argparse.ArgumentParser()
parser.add_argument(
"model1",
help="the AI model to use for player1: PMC, MC, AB"
)
parser.add_argument(
"model2",
help="the AI model to use for player2: PMC, MC, AB"
)
parser.add_argument(
"playouts",
help="number of playouts for monte carlo models to run and depth for alpha beta"
)
args = parser.parse_args()
playouts = int(args.playouts)
depth = int(args.playouts)
# depth is not the same as playouts and needs to be scaled down
if depth == 5:
depth = 2
elif depth == 10:
depth = 5
elif depth == 50:
depth = 6
elif depth == 100:
depth = 7
elif depth == 150:
depth = 7
elif depth == 175:
depth = 7
elif depth == 200:
depth = 7
if args.model1 == "PMC":
P0d = 1
elif args.model1 == "MC":
P0d = 4
elif args.model1 == "AB":
P0d = 6
else:
print("this is not a correct model, please enter one of the following:\n"
"\"PMC\" : pure monte carlo tree search\n"
"\"MC\" : monte carlo tree search with heuristics\n"
"\"AB\" : alpha beta\n")
difficulty = P0d
if args.model2 == "PMC":
P1d = 1
elif args.model2 == "MC":
P1d = 4
elif args.model2 == "AB":
P1d = 6
else:
print("this is not a correct model, please enter one of the following:\n"
"\"PMC\" : pure monte carlo tree search\n"
"\"MC\" : monte carlo tree search with heuristics\n"
"\"AB\" : alpha beta\n")
class Board:
def __init__(self):
#White goes first (0 is white and player,1 is black and computer)
self.player = 0
self.passed = False
self.won = False
#Initializing an empty board
self.array = []
for x in range(8):
self.array.append([])
for y in range(8):
self.array[x].append(None)
#Initializing center values
self.array[3][3]="w"
self.array[3][4]="b"
self.array[4][3]="b"
self.array[4][4]="w"
#Initializing old values
self.oldarray = self.array
#Updating the board to the screen
def update(self):
global playouts
screen.delete("highlight")
screen.delete("tile")
for x in range(8):
for y in range(8):
#Could replace the circles with images later, if I want
if self.oldarray[x][y]=="w":
screen.create_oval(
54+50*x,54+50*y,96+50*x,96+50*y,
tags="tile {0}-{1}".format(x,y),fill="#aaa",outline="#aaa"
)
screen.create_oval(
54+50*x,52+50*y,96+50*x,94+50*y,
tags="tile {0}-{1}".format(x,y),fill="#fff",outline="#fff"
)
elif self.oldarray[x][y]=="b":
screen.create_oval(
54+50*x,54+50*y,96+50*x,96+50*y,
tags="tile {0}-{1}".format(x,y),fill="#000",outline="#000"
)
screen.create_oval(
54+50*x,52+50*y,96+50*x,94+50*y,
tags="tile {0}-{1}".format(x,y),fill="#111",outline="#111"
)
#Animation of new tiles
screen.update()
for x in range(8):
for y in range(8):
#Could replace the circles with images later, if I want
if self.array[x][y]!=self.oldarray[x][y] and self.array[x][y]=="w":
screen.delete("{0}-{1}".format(x,y))
#42 is width of tile so 21 is half of that
#Shrinking
for i in range(21):
screen.create_oval(
54+i+50*x,54+i+50*y,96-i+50*x,96-i+50*y,
tags="tile animated",fill="#000",outline="#000"
)
screen.create_oval(
54+i+50*x,52+i+50*y,96-i+50*x,94-i+50*y,
tags="tile animated",fill="#111",outline="#111"
)
if i%3==0:
sleep(0.01)
screen.update()
screen.delete("animated")
#Growing
for i in reversed(range(21)):
screen.create_oval(
54+i+50*x,54+i+50*y,96-i+50*x,96-i+50*y,
tags="tile animated",fill="#aaa",outline="#aaa"
)
screen.create_oval(
54+i+50*x,52+i+50*y,96-i+50*x,94-i+50*y,
tags="tile animated",fill="#fff",outline="#fff"
)
if i%3==0:
sleep(0.01)
screen.update()
screen.delete("animated")
screen.create_oval(
54+50*x,54+50*y,96+50*x,96+50*y,
tags="tile",fill="#aaa",outline="#aaa"
)
screen.create_oval(
54+50*x,52+50*y,96+50*x,94+50*y,
tags="tile",fill="#fff",outline="#fff"
)
screen.update()
elif self.array[x][y]!=self.oldarray[x][y] and self.array[x][y]=="b":
screen.delete("{0}-{1}".format(x,y))
#42 is width of tile so 21 is half of that
#Shrinking
for i in range(21):
screen.create_oval(
54+i+50*x,54+i+50*y,96-i+50*x,96-i+50*y,
tags="tile animated",fill="#aaa",outline="#aaa"
)
screen.create_oval(
54+i+50*x,52+i+50*y,96-i+50*x,94-i+50*y,
tags="tile animated",fill="#fff",outline="#fff"
)
if i%3==0:
sleep(0.01)
screen.update()
screen.delete("animated")
#Growing
for i in reversed(range(21)):
screen.create_oval(
54+i+50*x,54+i+50*y,96-i+50*x,96-i+50*y,
tags="tile animated",fill="#000",outline="#000"
)
screen.create_oval(
54+i+50*x,52+i+50*y,96-i+50*x,94-i+50*y,
tags="tile animated",fill="#111",outline="#111"
)
if i%3==0:
sleep(0.01)
screen.update()
screen.delete("animated")
screen.create_oval(
54+50*x,54+50*y,96+50*x,96+50*y,
tags="tile",fill="#000",outline="#000"
)
screen.create_oval(
54+50*x,52+50*y,96+50*x,94+50*y,
tags="tile",fill="#111",outline="#111"
)
screen.update()
######## MODIFIED BY ME ##############################
if not self.won:
global difficulty
player = self.player
#Draw the scoreboard and update the screen
self.drawScoreBoard()
screen.update()
self.oldarray = self.array
#print(difficulty)
if difficulty == 1 or difficulty == 4:
start = time()
simpleMove = self.chooseMove(difficulty)
end = time()
if len(simpleMove) == 3 or len(simpleMove) == 2 :
self.array = simpleMove[0]
position = simpleMove[1]
if player == 1:
self.oldarray[position[0]][position[1]]="b"
#reset player incase it got changed by the playouts
self.player = 1
else:
self.oldarray[position[0]][position[1]]="w"
#reset player incase it got changed by the playouts
self.player = 0
if len(simpleMove) == 3:
if difficulty == 1:
pmctimes.append(end - start)
pmcscaledtimes.append(simpleMove[2])
if difficulty == 4:
mctactimes.append(end - start)
mctacscaledtimes.append(simpleMove[2])
else:
self.array = simpleMove[0]
#smartest AI with alpha beta min max pruneing and knowledge of tactics
else:
start = time()
alphaBetaResult = self.alphaBeta(
self.array,
depth,
-float("inf"),
float("inf"),
1
)
end = time()
abtimes.append(end-start)
self.array = alphaBetaResult[1]
if len(alphaBetaResult)==3:
position = alphaBetaResult[2]
if self.player == 1:
self.oldarray[position[0]][position[1]]="b"
else:
self.oldarray[position[0]][position[1]]="w"
if self.player == 1:
self.player = 0
difficulty = P0d
else:
self.player = 1
difficulty = P1d
nodes = 0
#Player must pass
self.passTest()
else:
screen.create_text(
250,550,anchor="c",
font=("Consolas",15), text="The game is done!"
)
#if len(pmctimes):
# print(
# "time per PMCTS play : {}".format(
# (mean(pmctimes))
# )
# )
#if len(mctactimes):
# print(
# "time per MC tactics play : {}".format(
# (mean(mctactimes))
# )
# )
#if len(abtimes):
# print(
# "time per alpha beta play : {}".format(
# (mean(abtimes))
# )
# )
#if len(pmcscaledtimes):
# print(
# "time per PMCTS playout : {}".format(
# (mean(pmcscaledtimes))
# )
# )
#if len(mctacscaledtimes):
# print(
# "time per MC tactics playout : {}".format(
# (mean(mctacscaledtimes))
# )
# )
if (P0d == 1 and P1d == 4) or (P0d == 4 and P1d == 1):
pmctimesavg = mean(pmctimes)
pmcscaledtimesavg = mean(pmcscaledtimes)
mctactimesavg = mean(mctactimes)
mctacscaledtimesavg = mean(mctacscaledtimes)
if P0d == 1:
if player_score > computer_score:
winner = "PMC"
else:
winner = "MC"
else:
if player_score > computer_score:
winner = "MC"
else:
winner = "PMC"
results = {
"PMCTS full play" : [pmctimesavg],
"PMCTS Playout" : [pmcscaledtimesavg],
"MCTS full play" : [mctactimesavg],
"MCTS Playout" : [mctacscaledtimesavg],
"AB full play" : ["NA"],
"MC vs PMC" : [winner],
"PMC vs AB" : ["NA"],
"MC vs AB" : ["NA"],
"Playouts" : [playouts],
"Language" : ["Python"]
}
resultsdf = pd.DataFrame(data=results)
resultsdf.to_csv('results.csv', mode='a', header=False)
elif P0d == 1 and P1d == 1:
pmctimesavg = mean(pmctimes)
pmcscaledtimesavg = mean(pmcscaledtimes)
results = {
"PMCTS full play" : [pmctimesavg],
"PMCTS Playout" : [pmcscaledtimesavg],
"MCTS full play" : ["NA"],
"MCTS Playout" : ["NA"],
"AB full play" : ["NA"],
"MC vs PMC" : ["NA"],
"PMC vs AB" : ["NA"],
"MC vs AB" : ["NA"],
"Playouts" : [playouts],
"Language" : ["Python"]
}
resultsdf = pd.DataFrame(data=results)
resultsdf.to_csv('results.csv', mode='a', header=False)
elif (P0d == 1 and P1d == 6) or (P0d == 6 and P1d == 1):
pmctimesavg = mean(pmctimes)
pmcscaledtimesavg = mean(pmcscaledtimes)
abtimesavg = mean(abtimes)
abscaledtimesavg = 0
if P0d == 1:
if player_score > computer_score:
winner = "PMC"
else:
winner = "AB"
else:
if player_score > computer_score:
winner = "AB"
else:
winner = "PMC"
results = {
"PMCTS full play" : [pmctimesavg],
"PMCTS Playout" : [pmcscaledtimesavg],
"MCTS full play" : ["NA"],
"MCTS Playout" : ["NA"],
"AB full play" : [abtimesavg],
"MC vs PMC" : ["NA"],
"PMC vs AB" : [winner],
"MC vs AB" : ["NA"],
"Playouts" : [playouts],
"Language" : ["Python"]
}
resultsdf = pd.DataFrame(data=results)
resultsdf.to_csv('results.csv', mode='a', header=False)
elif P0d == 4 and P1d == 4:
mctactimesavg = mean(mctactimes)
mctacscaledtimesavg = mean(mctacscaledtimes)
results = {
"PMCTS full play" : ["NA"],
"PMCTS Playout" : ["NA"],
"MCTS full play" : [mctactimesavg],
"MCTS Playout" : [mctacscaledtimesavg],
"AB full play" : ["NA"],
"MC vs PMC" : ["NA"],
"PMC vs AB" : ["NA"],
"MC vs AB" : ["NA"],
"Playouts" : [playouts],
"Language" : ["Python"]
}
resultsdf = pd.DataFrame(data=results)
resultsdf.to_csv('results.csv', mode='a', header=False)
elif (P0d == 4 and P1d == 6) or (P0d == 6 and P1d == 4):
mctactimesavg = mean(mctactimes)
mctacscaledtimesavg = mean(mctacscaledtimes)
abtimesavg = mean(abtimes)
abscaledtimesavg = 0
if P0d == 4:
if player_score > computer_score:
winner = "MC"
else:
winner = "AB"
else:
if player_score > computer_score:
winner = "AB"
else:
winner = "MC"
results = {
"PMCTS full play" : ["NA"],
"PMCTS Playout" : ["NA"],
"MCTS full play" : [mctactimesavg],
"MCTS Playout" : [mctacscaledtimesavg],
"AB full play" : [abtimesavg],
"MC vs PMC" : ["NA"],
"PMC vs AB" : ["NA"],
"MC vs AB" : [winner],
"Playouts" : [playouts],
"Language" : ["Python"]
}
resultsdf = pd.DataFrame(data=results)
resultsdf.to_csv('results.csv', mode='a', header=False)
elif (P0d == 6 and P1d == 6):
abtimesavg = mean(abtimes)
abscaledtimesavg = 0
results = {
"PMCTS full play" : ["NA"],
"PMCTS Playout" : ["NA"],
"MCTS full play" : ["NA"],
"MCTS Playout" : ["NA"],
"AB full play" : [abtimesavg],
"MC vs PMC" : ["NA"],
"PMC vs AB" : ["NA"],
"MC vs AB" : ["NA"],
"Playouts" : [playouts],
"Language" : ["Python"]
}
resultsdf = pd.DataFrame(data=results)
resultsdf.to_csv('results.csv', mode='a', header=False)
exit()
#root.destroy()
if not self.won:
root.after(0, self.update)
#### END OF MODIFIED BY ME ####################################
#METHOD: Draws scoreboard to screen
def drawScoreBoard(self):
global moves
global player_score
global computer_score
#Deleting prior score elements
screen.delete("score")
#Scoring based on number of tiles
player_score = 0
computer_score = 0
for x in range(8):
for y in range(8):
if self.array[x][y]=="w":
player_score+=1
elif self.array[x][y]=="b":
computer_score+=1
if self.player==0:
player_colour = "green"
computer_colour = "gray"
else:
player_colour = "gray"
computer_colour = "green"
screen.create_oval(5,540,25,560,fill=player_colour,outline=player_colour)
screen.create_oval(
380,540,400,560,
fill=computer_colour,
outline=computer_colour
)
#Pushing text to screen
screen.create_text(
30,550,anchor="w", tags="score",
font=("Consolas", 50),fill="white",text=player_score
)
screen.create_text(
400,550,anchor="w", tags="score",
font=("Consolas", 50),fill="black",text=computer_score
)
moves = player_score+computer_score
#METHOD: Test if player must pass: if they do, switch the player
def passTest(self):
mustPass = True
for x in range(8):
for y in range(8):
if valid(self.array,self.player,x,y):
mustPass=False
if mustPass:
self.player = 1-self.player
if self.passed==True:
self.won = True
else:
self.passed = True
self.update()
else:
self.passed = False
#choose random play
def getPlays(self, board):
#Generates all possible moves
choices = []
boards = []
for x in range(8):
for y in range(8):
if valid(board,self.player,x,y):
test = move(board,x,y)
boards.append(test)
choices.append([x,y])
return[choices, boards]
#################this code was written by me#################
#pure monte carlo tree search, level 1 and 2
def chooseMove(self, difficulty):
"""Choose Move determines what the next optimal move should be, based on the
maximizing the linear combination from the play statistics of random playouts
Parameters:
difficulty(int): difficulty 0 will do pure MCTS and difficulty 4 will use
tactics to choose the next play
Returns:
list : list with the new chosen board, the chosen tile to play and time
"""
global playouts
result_tracker = {}
current_board = self.array
current_player = self.player
loopTime = []
play_choices = self.getPlays(current_board)
empty = play_choices[0]
#remove empty lists
empty = [x for x in empty if x != []]
possible_boards = play_choices[1]
if len(empty) == 0:
self.passed = True
return [self.array]
elif len(empty) == 1:
return(possible_boards[0], empty[0])
#set up dict for the locations and their win statistics
for location in range(0, len(empty)):
result_tracker.setdefault(location, None)
for empty_location in result_tracker:
wins = 0
losses = 0
draws = 0
# set number of random playouts
for playout in range(playouts):
#incase the player gets changed in the playouts (eg. passing)
self.player = current_player
won = False
passed = self.passed
mustPass = True
current_board = possible_boards[empty_location]
self.player = 1-self.player
for x in range(8):
for y in range(8):
if valid(current_board,self.player,x,y):
mustPass=False
if mustPass:
if passed:
won = True
else:
passed = True
self.player = 1-self.player
# all subsequent plays random for both players until game over
''' time the while loop, majority of computation is here, the rest is
fairly negligible'''
start = time()
loopCounter = 0
while not won:
# choose randomly from empty locations
play_choices = self.getPlays(current_board)
play_choices = [x for x in play_choices if x != []]
if len(play_choices) == 0:
if passed:
won = True
else:
passed = True
self.player = 1-self.player
continue
temp_possible_boards = play_choices[1]
#pure MCTS
if difficulty == 1:
chosen = randint(0,((len(temp_possible_boards))-1))
#use gameplay tactics
else:
bestScore = -float("inf")
chosen = 0
for i in range(len(temp_possible_boards)):
score= finalHeuristic(temp_possible_boards[i],self.player)
if score>bestScore:
chosen=i
current_board = temp_possible_boards[chosen]
self.player = 1-self.player
mustPass = True
for x in range(8):
for y in range(8):
if valid(current_board,self.player,x,y):
mustPass=False
if mustPass:
if passed:
won = True
else:
passed = True
self.player = 1-self.player
loopCounter +=1
end = time()
# in order to account for some plays having more or less choices
if loopCounter:
loopTime.append((end-start)/(loopCounter))
else:
loopTime.append(0)
flat_board = [item for sublist in current_board for item in sublist]
tile_counts = {i:flat_board.count(i) for i in flat_board}
#number of black tiles
if 'b' in tile_counts:
black = tile_counts['b']
else:
black = 0
#number of white tiles
if 'w' in tile_counts:
white = tile_counts['w']
else:
white = 0
#increment the relevant stat
#allowe AI to play against eachother
if current_player == 1:
if black > white:
wins += 1
elif black == white:
draws += 1
elif black < white:
losses += 1
else:
if white > black:
wins += 1
elif black == white:
draws += 1
elif white < black:
losses += 1
#print(
# "square: {}, wins: {}, draws: {}, losses : {}".format(
# empty_location,wins, draws, losses
# )
#)
result_tracker[empty_location] = wins + draws*2 - losses*5
playtime = ((sum(loopTime)/len(loopTime)))
# choose the maximum of the linear combination
winning_move = max(result_tracker.items(), key=operator.itemgetter(1))[0]
#print(winning_move)
#print("run results are: {}".format(result_tracker))
#print("move choice: {}".format(winning_move))
# return location with max wins
return [
possible_boards[(winning_move)-1],
empty[(winning_move)-1],
playtime
]
####### END OF MY CODE #######################
#alphaBeta pruning on the minimax tree
def alphaBeta(self,node,depth,alpha,beta,maximizing):
"""Choose Move determines what the next optimal move should be, based alpha
beta pruning on a minimax tree
Parameters:
node(list): current play board
depth(int): number of playouts
alpha(int): previous alpha value
beta(int): previous beta value
maximizing(bool): if this playout will minimize or maximize
Returns:
list : list with the new chosen board and the chosen tile to play
"""
global nodes
nodes += 1
boards = []
choices = []
for x in range(8):
for y in range(8):
if valid(self.array,self.player,x,y):
test = move(node,x,y)
boards.append(test)
choices.append([x,y])
if depth==0 or len(choices)==0:
return ([finalHeuristic(node,maximizing),node])
if maximizing:
v = -float("inf")
bestBoard = []
bestChoice = []
for board in boards:
boardValue = self.alphaBeta(board,depth-1,alpha,beta,0)[0]
if boardValue>v:
v = boardValue
bestBoard = board
bestChoice = choices[boards.index(board)]
alpha = max(alpha,v)
if beta <= alpha:
break
return([v,bestBoard,bestChoice])
else:
v = float("inf")
bestBoard = []
bestChoice = []
for board in boards:
boardValue = self.alphaBeta(board,depth-1,alpha,beta,1)[0]
if boardValue<v:
v = boardValue
bestBoard = board
bestChoice = choices[boards.index(board)]
beta = min(beta,v)
if beta<=alpha:
break
return([v,bestBoard,bestChoice])
#FUNCTION: Returns a board after making a move according to rules
#Assumes the move is valid
def move(passedArray,x,y):
#Must copy the passedArray so we don't alter the original
array = deepcopy(passedArray)
#Set colour and set the moved location to be that colour
if board.player==0:
colour = "w"
else:
colour="b"
array[x][y]=colour
#Determining the neighbours to the square
neighbours = []
for i in range(max(0,x-1),min(x+2,8)):
for j in range(max(0,y-1),min(y+2,8)):
if array[i][j]!=None:
neighbours.append([i,j])
#Which tiles to convert
convert = []
#For all the generated neighbours, determine if they form a line
#If a line is formed, we will add it to the convert array
for neighbour in neighbours:
neighX = neighbour[0]
neighY = neighbour[1]
#Check if the neighbour is of a different colour - it must be to form a line
if array[neighX][neighY]!=colour:
#The path of each individual line
path = []
#Determining direction to move
deltaX = neighX-x
deltaY = neighY-y
tempX = neighX
tempY = neighY
#While we are in the bounds of the board
while 0<=tempX<=7 and 0<=tempY<=7:
path.append([tempX,tempY])
value = array[tempX][tempY]
#If we reach a blank tile, we're done and there's no line
if value==None:
break
#If we reach a tile of the player's colour, a line is formed
if value==colour:
#Append all of our path nodes to the convert array
for node in path:
convert.append(node)
break
#Move the tile
tempX+=deltaX
tempY+=deltaY
#Convert all the appropriate tiles
for node in convert:
array[node[0]][node[1]]=colour
return array
#Method for drawing the gridlines
def drawGridBackground(outline=False):
#If we want an outline on the board then draw one
if outline:
screen.create_rectangle(50,50,450,450,outline="#111")
#Drawing the intermediate lines
for i in range(7):
lineShift = 50+50*(i+1)
#Horizontal line
screen.create_line(50,lineShift,450,lineShift,fill="#111")
#Vertical line
screen.create_line(lineShift,50,lineShift,450,fill="#111")
screen.update()
#Simple heuristic. Compares number of each tile.
def simpleScore(array,player):
score = 0
#Set player and opponent colours
if player==1:
colour="b"
opponent="w"
else:
colour = "w"
opponent = "b"
#+1 if it's player colour, -1 if it's opponent colour
for x in range(8):
for y in range(8):
if array[x][y]==colour:
score+=1
elif array[x][y]==opponent:
score-=1
return score
#Less simple but still simple heuristic. Weights corners and edges as more
def slightlyLessSimpleScore(array,player):
score = 0
#Set player and opponent colours
if player==1:
colour="b"
opponent="w"
else:
colour = "w"
opponent = "b"
#Go through all the tiles
for x in range(8):
for y in range(8):
#Normal tiles worth 1
add = 1
#Edge tiles worth 3
if (
(x==0 and 1<y<6) or
(x==7 and 1<y<6) or
(y==0 and 1<x<6) or
(y==7 and 1<x<6)
):
add=3
#Corner tiles worth 5
elif (
(x==0 and y==0) or
(x==0 and y==7) or
(x==7 and y==0) or
(x==7 and y==7)
):
add = 5
#Add or subtract the value of the tile corresponding to the colour
if array[x][y]==colour:
score+=add
elif array[x][y]==opponent:
score-=add
return score
#Heuristic that weights corner tiles and edge tiles as positive
#adjacent to corners (if the corner is not yours) as negative
#Weights other tiles as one point
def decentHeuristic(array,player):
score = 0
cornerVal = 25
adjacentVal = 5
sideVal = 5
#Set player and opponent colours
if player==1:
colour="b"
opponent="w"
else:
colour = "w"
opponent = "b"
#Go through all the tiles
for x in range(8):
for y in range(8):
#Normal tiles worth 1
add = 1
#Adjacent to corners are worth -5
if (x==0 and y==1) or (x==1 and 0<=y<=1):
if array[0][0]==colour:
add = sideVal
else:
add = -adjacentVal
elif (x==0 and y==6) or (x==1 and 6<=y<=7):
if array[7][0]==colour:
add = sideVal
else:
add = -adjacentVal
elif (x==7 and y==1) or (x==6 and 0<=y<=1):
if array[0][7]==colour:
add = sideVal
else:
add = -adjacentVal
elif (x==7 and y==6) or (x==6 and 6<=y<=7):
if array[7][7]==colour:
add = sideVal
else:
add = -adjacentVal
#Edge tiles worth 5
elif (
(x==0 and 1<y<6) or
(x==7 and 1<y<6) or
(y==0 and 1<x<6) or
(y==7 and 1<x<6)
):
add=sideVal
#Corner tiles worth 25
elif (
(x==0 and y==0) or
(x==0 and y==7) or
(x==7 and y==0) or
(x==7 and y==7)
):
add = cornerVal
#Add or subtract the value of the tile corresponding to the colour
if array[x][y]==colour:
score+=add
elif array[x][y]==opponent:
score-=add
return score
### MY ALTERED CODE############################################################
def earlyGame(array,player):
"""Provide a score for a resulting board after a move, use game play tactics
so that early on you care more about power pieces which allow access to
corners
Parameters:
array(list): the current board
player(int): current player number