python井字棋ai_实现AI下井字棋的alpha-beta剪枝算法(python实现)
时间: 2024-01-27 13:04:33 浏览: 180
python实现采用Alpha-Beta剪枝搜索实现黑白棋AI-源码
5星 · 资源好评率100%
好的,下面是实现AI下井字棋的alpha-beta剪枝算法的Python代码:
```python
import math
MAX = math.inf
MIN = -math.inf
def minimax(board, depth, alpha, beta, is_maximizing):
result = check_winner(board)
if result != None:
return result
if is_maximizing:
best_score = MIN
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
score = minimax(board, depth+1, alpha, beta, False)
board[i][j] = ' '
best_score = max(score, best_score)
alpha = max(alpha, best_score)
if beta <= alpha:
break
return best_score
else:
best_score = MAX
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
score = minimax(board, depth+1, alpha, beta, True)
board[i][j] = ' '
best_score = min(score, best_score)
beta = min(beta, best_score)
if beta <= alpha:
break
return best_score
def find_best_move(board):
best_score = MIN
best_move = None
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
score = minimax(board, 0, MIN, MAX, False)
board[i][j] = ' '
if score > best_score:
best_score = score
best_move = (i, j)
return best_move
def check_winner(board):
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] != ' ':
return 1 if board[i][0] == 'X' else -1
if board[0][i] == board[1][i] == board[2][i] != ' ':
return 1 if board[0][i] == 'X' else -1
if board[0][0] == board[1][1] == board[2][2] != ' ':
return 1 if board[0][0] == 'X' else -1
if board[0][2] == board[1][1] == board[2][0] != ' ':
return 1 if board[0][2] == 'X' else -1
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
return None
return 0
board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
while True:
print(board[0])
print(board[1])
print(board[2])
winner = check_winner(board)
if winner != None:
if winner == 0:
print("Tie!")
else:
print("You win!" if winner == 1 else "AI wins!")
break
row = int(input("Enter row (0, 1, or 2): "))
col = int(input("Enter column (0, 1, or 2): "))
if board[row][col] != ' ':
print("Invalid move!")
continue
board[row][col] = 'O'
winner = check_winner(board)
if winner != None:
if winner == 0:
print("Tie!")
else:
print("You win!" if winner == 1 else "AI wins!")
break
row, col = find_best_move(board)
board[row][col] = 'X'
```
这个代码实现了一个简单的人机对战井字棋游戏,其中AI使用了alpha-beta剪枝算法来下棋。当玩家输入坐标时,程序会将玩家的棋子放在对应的位置,并检查是否有获胜者。如果没有获胜者,AI会使用minimax算法和alpha-beta剪枝来找到最好的下棋位置,并将棋子放在那里。程序会不断循环,直到游戏结束。
阅读全文