用python生成五子棋博弈算法
时间: 2023-07-27 13:31:26 浏览: 125
python实现五子棋
好的,我可以为你提供一个简单的五子棋博弈算法的Python代码。以下是代码:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋子类型
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义胜利条件
WIN_COUNT = 5
# 创建棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
# 定义落子函数
def move(x, y, player):
if board[x][y] == EMPTY:
board[x][y] = player
return True
else:
return False
# 定义判断胜利函数
def is_win(x, y, player):
# 判断横向是否有五子连珠
count = 0
for i in range(max(0, x - WIN_COUNT + 1), min(BOARD_SIZE, x + WIN_COUNT)):
if board[i][y] == player:
count += 1
if count == WIN_COUNT:
return True
else:
count = 0
# 判断纵向是否有五子连珠
count = 0
for j in range(max(0, y - WIN_COUNT + 1), min(BOARD_SIZE, y + WIN_COUNT)):
if board[x][j] == player:
count += 1
if count == WIN_COUNT:
return True
else:
count = 0
# 判断左上到右下是否有五子连珠
count = 0
for i, j in zip(range(max(0, x - WIN_COUNT + 1), min(BOARD_SIZE, x + WIN_COUNT)),
range(max(0, y - WIN_COUNT + 1), min(BOARD_SIZE, y + WIN_COUNT))):
if board[i][j] == player:
count += 1
if count == WIN_COUNT:
return True
else:
count = 0
# 判断右上到左下是否有五子连珠
count = 0
for i, j in zip(range(max(0, x - WIN_COUNT + 1), min(BOARD_SIZE, x + WIN_COUNT)),
range(min(BOARD_SIZE - 1, y + WIN_COUNT - 1), max(-1, y - WIN_COUNT), -1)):
if board[i][j] == player:
count += 1
if count == WIN_COUNT:
return True
else:
count = 0
return False
# 定义主函数
def main():
# 初始化玩家和落子位置
player = BLACK
x, y = -1, -1
# 游戏开始
print("游戏开始!")
while True:
# 输出棋盘
print(board)
# 获取玩家输入
if player == BLACK:
print("轮到黑方落子:")
else:
print("轮到白方落子:")
x = int(input("请输入落子横坐标:"))
y = int(input("请输入落子纵坐标:"))
# 落子
if move(x, y, player):
# 判断胜负
if is_win(x, y, player):
print("恭喜玩家 %s 获胜!" % ("黑方" if player == BLACK else "白方"))
print(board)
break
# 切换玩家
player = BLACK if player == WHITE else WHITE
else:
print("此处已有棋子,请重新输入!")
if __name__ == "__main__":
main()
```
这个代码实现了一个简单的五子棋博弈,玩家可以通过输入横纵坐标来落子,程序会判断落子是否合法,并且判断胜负。你可以在此基础上进行修改和扩展,实现更加完整的五子棋博弈算法。
阅读全文