生成五子棋python代码
时间: 2023-10-08 22:13:42 浏览: 77
以下是一个简单的五子棋Python代码:
```
import numpy as np
# 棋盘大小
BOARD_SIZE = 15
# 初始化棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE))
# 当前玩家
player = 1
# 检查是否胜利
def check_win(row, col):
# 水平方向
count = 0
for i in range(BOARD_SIZE):
if board[row][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 垂直方向
count = 0
for i in range(BOARD_SIZE):
if board[i][col] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 左上到右下方向
count = 0
for i in range(-4, 5):
r = row + i
c = col + i
if r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE:
continue
if board[r][c] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 左下到右上方向
count = 0
for i in range(-4, 5):
r = row - i
c = col + i
if r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE:
continue
if board[r][c] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 如果都没有胜利,返回False
return False
# 下棋
def play(row, col):
global player
# 判断是否可以下棋
if board[row][col] != 0:
print("此处已有棋子,请重新落子")
return
# 下棋
board[row][col] = player
# 检查是否胜利
if check_win(row, col):
print("玩家", player, "获胜!")
return
# 切换玩家
player = 3 - player
# 打印棋盘
def print_board():
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
print(int(board[i][j]), end=' ')
print()
# 开始游戏
while True:
print("玩家", player, "落子:")
row = int(input("请输入行号(0~14):"))
col = int(input("请输入列号(0~14):"))
play(row, col)
print_board()
```
这个代码实现了一个简单的五子棋游戏,包括下棋、打印棋盘、判断胜负等功能。玩家可以通过输入行号和列号来下棋,程序会自动判断胜负并输出结果。
阅读全文