Minmax Alphabeta
Minmax Alphabeta
com='o'
player='x'
player_score={com:1,player:-1}
borad = [
['', '', ''],
['', '', ''],
['', '', ''],
]
def click_fun(x,y):
w = change(player, (x, y))
check_winer(w)
print('########################')
print(sc)
print('#######################')
def score_fun():
for i in range(3):
if borad[i][0]['text'] == borad[i][1]['text'] ==
borad[i][2]['text'] and borad[i][0]['text'] != '':
pl = borad[i][0]['text']
return player_score[pl]
for i in range(3):
if borad[0][i]['text'] == borad[1][i]['text'] ==
borad[2][i]['text'] and borad[2][i]['text'] != '':
pl = borad[0][i]['text']
return player_score[pl]
if borad[0][0]['text'] == borad[1][1]['text'] ==
borad[2][2]['text'] and borad[2][2]['text'] != '':
pl = borad[0][0]['text']
return player_score[pl]
if borad[2][0]['text'] == borad[1][1]['text'] ==
borad[0][2]['text'] and borad[0][2]['text'] != '':
pl = borad[0][2]['text']
return player_score[pl]
def check_winer(w):
if w is not None:
if w == 1:
label.config(text=("Computer won"))
result_style('red')
elif w == -1:
label.config(text=("YOU won"))
result_style("green")
else:
label.config(text=("Tie!"))
result_style("#ff7301")
def minMax_move(borad):
scores = []
pos = []
for x in range(3):
for y in range(3):
if borad[x][y]['text'] == '':
borad[x][y]['text'] = com
sc = minimaxi(borad, False)
scores.append(sc)
pos.append((x, y))
borad[x][y]['text'] = ''
if score != None:
return score
scores = []
for x in range(3):
for y in range(3):
if borad[x][y]['text'] == '':
if ismax:
borad[x][y]['text'] = com
else:
borad[x][y]['text'] = player
sc = minimaxi(borad,not ismax)
scores.append(sc)
borad[x][y]['text'] = ''
def alphabeta_move(borad):
scores = []
pos = []
alpha = -10
beta = 10
for x in range(3):
for y in range(3):
if borad[x][y]['text'] == '':
borad[x][y]['text'] = com
sc = alphabeta(borad, False, alpha, beta)
scores.append(sc)
pos.append((x, y))
borad[x][y]['text'] = ''
if score != None:
return score
if ismax:
best = -10
for x in range(3):
for y in range(3):
if borad[x][y]['text'] == '':
borad[x][y]['text'] = com
sc = alphabeta(borad, not ismax, alpha, beta)
borad[x][y]['text'] = ''
if sc > best:
best = sc
return best
else:
best = 10
for x in range(3):
for y in range(3):
if borad[x][y]['text'] == '':
borad[x][y]['text'] = player
sc = alphabeta(borad, not ismax, alpha, beta)
borad[x][y]['text'] = ''
if sc < best:
best = sc
return best
def result_style(col):
for x in range(3):
for y in range(3):
borad[x][y].config(bg=col)
def restart():
label.config(text=('player : ' + player +' com : ' + com))
for x in range(3):
for y in range(3):
borad[x][y].config(text="", bg="#F0F0F0")
window = Tk()
window.title("Tic-Tac-Toe Game")
btns_frame = Frame(window)
btns_frame.pack()
for row in range(3):
for col in range(3):
borad[row][col] = Button(btns_frame, text="",
font=('consolas', 50), width=4, height=1,
command=lambda row=row, col=col:
click_fun(row, col))
borad[row][col].grid(row=row, column=col)
window.mainloop()