python中tictactoe的Minimax代码

2024-04-25 11:48:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试编写一个井字游戏,但我面临一个问题。例如,如果我在一个角上画一个十字,机器人应该在中间标记“O”,但这不会发生。取而代之的是,它在十字架的旁边做了标记。机器人没有在矩阵上选择正确的值。任何帮助都将不胜感激。 机器人永远是第一个玩家,而人类永远是第一个玩家。 代码如下:

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()

Tags: inboardgameformovereturnifvalue
1条回答
网友
1楼 · 发布于 2024-04-25 11:48:14

托比亚斯,这是一个好的开始,但是你的算法搜索的是最少的一步来赢得胜利,对吧?当玩家(X)做出错误的选择时,移动次数最少。在

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

O|X|X
O| |X 
 | | 

我建议你根据获胜方法的多少来衡量位置。在

^{pr2}$

然后根据最大重量计算出一个最终获胜的移动。在

相关问题 更多 >