我是一个年轻的程序员,正在学习python并努力实现AI(使用minimax)来玩TicTacToe。我开始在线观看教程,但是该教程使用的是JavaScript,因此无法解决我的问题。我也查看了这个问题(Python minimax for tictactoe),但是它没有任何答案,实现与我的有很大不同。
这是我的代码:
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
playerSymbol = ""
playerPosition = []
aiSymbol = ""
aiPosition = []
global score
possiblePositions = [0, 1, 2, 3, 4, 5, 6, 7, 8]
winner = None
scoreBoard = {
playerSymbol: 1,
aiSymbol: -1,
"tie": 0
}
turn = 0
def drawBoard():
print(board[0] + " | " + board[1] + " | " + board[2])
print("___" + "___" + "___")
print(board[3] + " | " + board[4] + " | " + board[5])
print("___" + "___" + "___")
print(board[6] + " | " + board[7] + " | " + board[8])
def choice():
global playerSymbol
global aiSymbol
answer = input("What do you want to play as? (type x or o) ")
if answer.upper() == "X":
playerSymbol = "X"
aiSymbol = "O"
else:
playerSymbol = "O"
aiSymbol = "X"
def won():
global winner
winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 4, 8}, {2, 4, 6}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}]
for position in winningPositions:
if position.issubset(playerPosition):
winner = playerSymbol
print("Player Wins :)")
return True
elif position.issubset(aiPosition):
winner = aiSymbol
print("AI wins :(")
return True
if len(possiblePositions) == 0:
winner = "tie"
print("Guess it's a draw")
return True
return False
def findOptimalField(field):
global score
sampleScore = -1000
for i in range(9):
if field[i] == " ":
field[i] = aiSymbol
score = minimax(field, 0, False)
field[i] = " "
if score > sampleScore:
sampleScore = score
optimalMove = i
return optimalMove
def minimax(field, depth, isMaximizing):
global scoreBoard
global score
global winner
if winner is not None:
return scoreBoard[winner]
if isMaximizing:
bestScore = -1000
for i in range(9):
if field[i] == " ":
field[i] = aiSymbol
score = minimax(field, depth + 1, False)
field[i] = " "
bestScore = max(score, bestScore)
return bestScore
else:
otherBestScore = 1000
for i in range(9):
if field[i] == " ":
field[i] = playerSymbol
score = minimax(field, depth + 1, True)
field[i] = " "
otherBestScore = min(score, otherBestScore)
return otherBestScore
def play(field):
global turn
global score
choice()
optimalMove = 0
while not won():
if turn % 2 == 0:
pos = int(input("Where would you like to play? (0-8) "))
possiblePositions.remove(pos)
playerPosition.append(pos)
field[pos] = playerSymbol
turn += 1
drawBoard()
else:
aiTurn = findOptimalField(field)
possiblePositions.remove(aiTurn)
aiPosition.append(aiTurn)
field[aiTurn] = aiSymbol
turn += 1
print("\n")
print("\n")
drawBoard()
else:
print("Thanks for playing :)")
play(board)
我一直遇到问题:UnboundLocalError:赋值之前引用的局部变量'optimalMove',我认为这是由于分数从不大于> sampleScore。除非另有声明,否则这可能是Python逻辑将每个变量解释为局部变量的结果。我来自Java背景,并不习惯:(
但是,我愿意提出建议和方法来改进我的代码并修复此错误。预先感谢并保持健康,克里斯蒂
更改此部分,即使它不在optimalMove
内部,您的实现也会返回if statement
。
if score > sampleScore:
sampleScore = score
optimalMove = i
return optimalMove