源代码:
#kute_2024.06.31ai井字棋
import random
import os
# 棋盘状态
board = [['', '' ,''],
['', '' ,''],
['', '' ,'']]
# 打印棋盘
def print_board():
os.system('clear')
print(" 0 1 2")
for i in range(3):
print(f"{i} {board[i][0]} | {board[i][1]} | {board[i][2]}")
if i!= 2:
print(" ---------")
# 检查是否获胜
def check_win(player):
for i in range(3):
# 检查行
if board[i][0] == board[i][1] == board[i][2] == player:
return True
# 检查列
if board[0][i] == board[1][i] == board[2][i] == player:
return True
# 检查对角线
if board[0][0] == board[1][1] == board[2][2] == player:
return True
if board[0][2] == board[1][1] == board[2][0] == player:
return True
return False
# 评估当前棋盘状态(用于 AI 决策)
def evaluate_board():
if check_win('X'):
return 1
elif check_win('O'):
return -1
else:
return 0
# AI 决策
def ai_move():
best_score = float('-inf')
best_move = None
for i in range(3):
for j in range(3):
if board[i][j] =='':
board[i][j] = 'O'
score = minimax(board, 0, False)
board[i][j] =''
if score > best_score:
best_score = score
best_move = (i, j)
board[best_move[0]][best_move[1]] = 'O'
# 极小极大算法
def minimax(board, depth, is_maximizing):
score = evaluate_board()
if score!= 0 or is_board_full():
return score
if is_maximizing:
best_score = float('-inf')
for i in range(3):
for j in range(3):
if board[i][j] =='':
board[i][j] = 'O'
score = minimax(board, depth + 1, False)
board[i][j] =''
best_score = max(score, best_score)
return best_score
else:
best_score = float('inf')
for i in range(3):
for j in range(3):
if board[i][j] =='':
board[i][j] = 'X'
score = minimax(board, depth + 1, True)
board[i][j] =''
best_score = min(score, best_score)
return best_score
# 检查棋盘是否已满
def is_board_full():
for row in board:
for cell in row:
if cell =='':
return False
return True
# 游戏主循环
def play_game():
while True:
print_board()
x = int(input("玩家 X 请输入横坐标: "))
y = int(input("玩家 X 请输入纵坐标: "))
if x < 0 or x > 2 or y < 0 or y > 2 or board[x][y]!= '':
print("无效输入,请重新输入")
continue
board[x][y] = 'X'
if check_win('X'):
print_board()
print("玩家 X 获胜!")
break
if is_board_full():
print_board()
print("平局!")
break
ai_move()
if check_win('O'):
print_board()
print("AI 获胜!")
break
if is_board_full():
print_board()
print("平局!")
break
play_game()
(也不知道对不对)