用python写一段五子棋代码
时间: 2023-12-17 09:46:36 浏览: 71
好的,下面是一个简单的五子棋代码,使用Python语言实现:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋盘状态
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义赢法
wins = np.zeros((BOARD_SIZE, BOARD_SIZE, 572))
count = 0
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE - 4):
for k in range(5):
wins[i][j+k][count] = 1
count += 1
for i in range(BOARD_SIZE - 4):
for j in range(BOARD_SIZE):
for k in range(5):
wins[i+k][j][count] = 1
count += 1
for i in range(BOARD_SIZE - 4):
for j in range(BOARD_SIZE - 4):
for k in range(5):
wins[i+k][j+k][count] = 1
count += 1
for i in range(BOARD_SIZE - 4):
for j in range(4, BOARD_SIZE):
for k in range(5):
wins[i+k][j-k][count] = 1
count += 1
# 初始化棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
# 定义当前落子方
player = BLACK
# 定义游戏结束标志
game_over = False
while not game_over:
# 渲染棋盘
print(board)
if player == BLACK:
print("黑方落子")
else:
print("白方落子")
# 读取玩家输入
x = int(input("请输入落子的行号:"))
y = int(input("请输入落子的列号:"))
# 判断落子是否合法
if board[x][y] == EMPTY:
board[x][y] = player
# 判断是否获胜
for i in range(count):
if wins[x][y][i] == 1:
if board[wins[:, :, i] == 1] == 5:
if player == BLACK:
print("黑方获胜")
else:
print("白方获胜")
game_over = True
# 判断是否棋盘已满
if np.sum(board == EMPTY) == 0:
print("平局")
game_over = True
# 切换落子方
player = WHITE if player == BLACK else BLACK
else:
print("该位置已经落子,请重新输入")
```
这是一个简单的五子棋代码,使用了numpy库来实现棋盘的操作。游戏流程是玩家输入落子位置,程序判断落子是否合法,并且判断是否获胜或者平局。程序使用了赢法数组来进行判断胜负,这是一种比较高效的方法。
阅读全文