python中tic-tac-toe的Minimax代码

时间:2017-11-16 17:49:32

标签: python minimax

我一直在尝试编写一个井字游戏,但我遇到了一个问题。例如,如果我在其中一个角上放置十字架,机器人应该在中心标记“O”,但这不会发生。相反,它标志着它在十字架附近。机器人没有在矩阵上选择正确的值。任何帮助,将不胜感激。 PS:第一个玩家总是人类,而第二个玩家是机器人。 这是代码:

import re
current_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
current_game = list(" | | \n_|_|_\n | | \n_|_|_\n | | \n | | \n")

def draw1():
    for i in range(9):
        if(i<3 and i>=0):
            current_game[2*i]=current_board[i]
        elif(i<6 and i>=3):
            current_game[2*(i-3)+12]=current_board[i]
        elif(i<9 and i>=6):
            current_game[2*(i-6)+24]=current_board[i]
    print "".join(current_game)

def win(board, depth):
    board="".join(board)
    regex1 = [r"XXX......", r"...XXX...", r"......XXX", r"X..X..X..", r".X..X..X.", r"..X..X..X", r"X...X...X", r"..X.X.X.."]
    for i in regex1:
        if bool(re.search(i, board)):
            return -10+depth
    regex2 = [r"OOO......", r"...OOO...", r"......OOO", r"O..O..O..", r".O..O..O.", r"..O..O..O", r"O...O...O", r"..O.O.O.."]
    for i in regex2:
        if bool(re.search(i, board)):
            return 10-depth

def draw(board):
    for i in board:
        if i==" ":
            return False
    return True

def assigning_values_to_a_move(board, isOplaying, depth):
    scorelist=[]
    if win(board, depth)==10-depth:
        return 10-depth
    elif win(board, depth)==-10+depth:
        return -10+depth
    elif draw(board):
        return 0
    else:
        if(isOplaying):
            for i in range(len(board)):
                if board[i]==" ":
                    board[i]="O"
                    scorelist.append(assigning_values_to_a_move(board, not isOplaying, depth+1))
                    board[i]=" "
            return max(scorelist)
        else:
            for i in range(len(board)):
                if board[i]==" ":
                    board[i]="X"
                    scorelist.append(assigning_values_to_a_move(board, isOplaying, depth+1))
                    board[i]=" "
            return min(scorelist)

def choosing_the_move(board, depth):
    current_value=-1000
    best_value=-1000
    best_index=-1
    for i in range(9):
        if board[i]==" ":
            board[i]="O"
            current_value=assigning_values_to_a_move(board, False, depth)
            if(current_value>best_value):
                best_value=current_value
                best_index=i
            board[i]=" "
    return best_index

for i in range(9):
    if i%2==0:
        y=int(raw_input())
        current_board[y]="X"
        draw1()
    else:
        current_board[choosing_the_move(current_board,i+1)]="O"
        draw1()

1 个答案:

答案 0 :(得分:0)

Tobias,这是一个好的开始,但你的算法正在寻找获胜的最少动作,对吗?当玩家(X)做出糟糕的选择时,会发生最少的动作。

例如,如果电路板看起来像这样。

O|X|X
O| |X 
 | | 

我建议你根据获胜方式的数量来衡量这些位置。

weights = [3,2,3,
           2,4,2,
           3,2,3]

然后计算一个基于最大权重获胜的举动。