Em đang sử dụng thuật toán Minimax cho trò chơi Caro. Nhưng không hiểu sao chạy không được ạ (Lỗi biến) Mong mọi người nhận xét và giúp đỡ ạ
import random
import sys
tab = range(1,10)
board = [i for i in range(0, 9)]
winners=((0,1,2),(3,4,5),(6,7,8),(1,4,7),(2,5,8),(0,3,6),(0,4,8),(2,4,6))
brd = [i for i in range(1,10)]
player, computer = '',''
# Corners, Center and Other, respectively
def print_board():
x=1
for i in board:
end = ' | '
if x%3 == 0:
end = ' \n'
if i != 1: end+='------------\n';
char=' '
if i in ('X','O'): char=i;
x+=1
print(char,end=end)
def can_move(brd, player, move):
if move in tab and brd[move-1] == move-1:
return True
return False
def can_win(brd, player):
win=True
for tup in winners:
win=True
for ix in tup:
if brd[ix] != player:
win=False
break
if win == True:
break
if win == True:
break
return win
def make_move(brd, player,move):
if can_move(brd, player, move):
brd[move-1]=player
win=can_win(brd, player)
return (True, win)
return(False,False)
#AI algorithm (Minimax)
def GetBestMove(brd, player):
if can_win(brd, computer):
return 1
elif can_win(brd, player):
return -1
elif not space_exist():
return 0
moves = []
empty_cells = []
for i in range(1, 10):
if brd[i-1] == i-1:
empty_cells.append(i)
for empty_cell in empty_cells:
get = {}
get['index'] = empty_cell
newBrd = brd.copy()
make_move(newBrd, player, empty_cell)
if player == 'X':
result = GetBestMove(newBrd, 'O')
get['score'] = result
else:
result = GetBestMove(newBrd, 'X')
get['score'] = result
moves.append(get)
best_move = None
if player == 'X':
best = -3
for get in moves:
if get['score'] > best:
best = get['score']
best_move = get['index']
else:
best = 99
for get in moves:
if get['score'] < best:
best = get['score']
best_move = get['index']
return(best_move)
def space_exist():
return board.count('X')+board.count("O") != 9
player = 'O'
computer = 'X'
print('Player is X and Computer is O')
result='Draw'
while space_exist():
print_board()
print('Make your move ! [1-9]: ',end='')
move=int(input())
moved, won = make_move(board, player, move)
if not moved:
print('Error! Try Again. ')
continue
if won:
result='Congratulations! You won'
break
elif make_move(board, computer, GetBestMove(board, computer))[1]:
result='You lose.'
break
print_board()
print(result)
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?