写一个基于Python的五子棋程序
时间: 2023-05-23 17:06:09 浏览: 57
A:好的,我可以为您提供一个简单的五子棋程序的代码示例,如下所示:
```
import numpy as np
# 创建一个 15x15 的棋盘
board = np.zeros((15, 15), dtype=int)
# 定义棋子类型
BLACK = 1
WHITE = 2
# 定义胜利条件
WIN_CONDITION = 5
# 定义下棋函数
def play(chess_type, row, col):
board[row][col] = chess_type
# 定义胜利函数
def is_win(chess_type):
for i in range(15):
for j in range(15):
if board[i][j] == chess_type:
if j <= 10 and len(set(board[i][j:j+WIN_CONDITION])) == 1:
return True
if i <= 10 and len(set(board[i:i+WIN_CONDITION, j]))) == 1:
return True
if j <= 10 and i <= 10 and len(set(board[i:i+WIN_CONDITION, j:j+WIN_CONDITION].diagonal())) == 1:
return True
if j >= 4 and i <= 10 and len(set(board[i:i+WIN_CONDITION, j-4:j+1].diagonal())) == 1:
return True
return False
# 开始游戏
current_player = BLACK
while True:
print(board)
# 等待玩家输入行列位置
row, col = map(int, input("请输入你要下的位置(格式:行 列):").split())
if board[row][col] == 0:
play(current_player, row, col)
if is_win(current_player):
print(f"恭喜 {current_player} 获胜!")
print(board)
break
current_player = WHITE if current_player == BLACK else BLACK
else:
print("这个位置已经下过了,请再次输入。")
```
说明:
以上是一个简单的五子棋程序,通过 Python 语言实现。
程序中通过 numpy 库创建了一个 15x15 的二维数组,用于表示棋盘。棋子类型使用了 BLACK 和 WHITE 两种类型,0 表示该位置没有棋子。
is_win 函数用来判断当前是否达到了胜利条件,以决定游戏是否结束。
程序通过一个 while 循环实现游戏轮流进行,每轮先等待玩家输入下棋的位置,如果该位置还没下过,则在该位置下棋,并调用 is_win 判断下完当前这手棋是否胜利。
如果某一方胜利,则程序结束,否则通过交替 BLACK 和 WHITE 的值实现轮流下棋。
以上是一个简单的 Python 语言编写的五子棋程序,您可以根据需要进行改进和扩展。