python字符型五子棋人机对战
时间: 2023-10-01 14:03:44 浏览: 82
基于python实现五子棋人机对战
5星 · 资源好评率100%
好的,我可以为您提供一个简单的五子棋人机对战的 Python 代码。这个代码使用了 Minimax 算法,以及 Alpha-Beta 剪枝来优化搜索。代码如下:
```
import numpy as np
# 定义棋盘大小和胜利条件
BOARD_SIZE = 15
WIN_CONDITION = 5
# 定义棋子类型
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
# 定义评估函数,用于评估当前局面分值
def evaluate(board, player):
# 统计每个玩家的分数
score = 0
oppo = BLACK if player == WHITE else WHITE
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == player:
score += 1
elif board[i][j] == oppo:
score -= 1
return score
# 定义Minimax算法
def minimax(board, depth, alpha, beta, player):
if depth == 0:
return None, evaluate(board, player)
if player == BLACK:
best_move = None
best_score = -float('inf')
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == EMPTY:
board[i][j] = player
_, score = minimax(board, depth - 1, alpha, beta, WHITE)
board[i][j] = EMPTY
if score > best_score:
best_move = (i, j)
best_score = score
alpha = max(alpha, best_score)
if beta <= alpha:
break
return best_move, best_score
else:
best_move = None
best_score = float('inf')
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == EMPTY:
board[i][j] = player
_, score = minimax(board, depth - 1, alpha, beta, BLACK)
board[i][j] = EMPTY
if score < best_score:
best_move = (i, j)
best_score = score
beta = min(beta, best_score)
if beta <= alpha:
break
return best_move, best_score
# 定义落子函数
def make_move(player):
if player == BLACK:
print("轮到黑方落子:")
else:
print("轮到白方落子:")
while True:
x, y = input("请输入棋子坐标(以逗号分隔):").split(",")
x, y = int(x), int(y)
if x >= 0 and x < BOARD_SIZE and y >= 0 and y < BOARD_SIZE and board[x][y] == EMPTY:
break
else:
print("坐标无效,请重新输入!")
board[x][y] = player
# 定义判断胜负函数
def check_win(player):
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == player:
# 判断横向
if j <= BOARD_SIZE - WIN_CONDITION:
if np.all(board[i, j:j+WIN_CONDITION] == player):
return True
# 判断纵向
if i <= BOARD_SIZE - WIN_CONDITION:
if np.all(board[i:i+WIN_CONDITION, j] == player):
return True
# 判断右上方向
if j <= BOARD_SIZE - WIN_CONDITION and i >= WIN_CONDITION - 1:
if np.all(board[i-4:i+1, j+4:j-1] == player):
return True
# 判断左上方向
if j >= WIN_CONDITION - 1 and i >= WIN_CONDITION - 1:
if np.all(board[i-4:i+1, j-4:j+1] == player):
return True
return False
# 定义主函数
def main():
print("欢迎来到五子棋游戏!")
print("黑方先手,白方后手。")
while True:
make_move(BLACK)
if check_win(BLACK):
print("黑方胜利!")
break
_, score = minimax(board, 3, -float('inf'), float('inf'), WHITE)
print("白方选择落子坐标:", _)
board[_[0]][_[1]] = WHITE
if check_win(WHITE):
print("白方胜利!")
break
if __name__ == '__main__':
main()
```
这个代码会在命令行中运行,每次轮到玩家输入坐标时,需要输入两个数字,以逗号分隔。例如,输入“7,7”表示在棋盘的第8行第8列落子。在每次轮到电脑落子时,程序会使用 Minimax 算法搜索最佳的落子点。
阅读全文