请用python编写一个五子棋程序?
时间: 2023-08-09 16:09:13 浏览: 103
好的,以下是一个简单的五子棋程序的 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 make_move(player, row, col):
board[row][col] = player
# 定义判断胜利函数
def check_win(player):
# 检查行
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE - WIN_COUNT + 1):
if all(board[row][col+i] == player for i in range(WIN_COUNT)):
return True
# 检查列
for col in range(BOARD_SIZE):
for row in range(BOARD_SIZE - WIN_COUNT + 1):
if all(board[row+i][col] == player for i in range(WIN_COUNT)):
return True
# 检查正对角线
for row in range(BOARD_SIZE - WIN_COUNT + 1):
for col in range(BOARD_SIZE - WIN_COUNT + 1):
if all(board[row+i][col+i] == player for i in range(WIN_COUNT)):
return True
# 检查反对角线
for row in range(WIN_COUNT - 1, BOARD_SIZE):
for col in range(BOARD_SIZE - WIN_COUNT + 1):
if all(board[row-i][col+i] == player for i in range(WIN_COUNT)):
return True
return False
# 定义主函数
def main():
# 初始化玩家和游戏状态
player = BLACK
game_over = False
# 游戏循环
while not game_over:
# 打印棋盘
print(board)
# 玩家落子
row = int(input("Enter row: "))
col = int(input("Enter col: "))
make_move(player, row, col)
# 判断胜利
if check_win(player):
print("Player", player, "wins!")
game_over = True
# 切换玩家
player = WHITE if player == BLACK else BLACK
# 运行主函数
if __name__ == '__main__':
main()
```
这个程序使用了 NumPy 库来创建和操作二维数组,可以在命令行中输入行号和列号来落子。注意这个程序只是一个简单的演示,没有考虑很多棋局中的特殊情况,比如禁手等。
阅读全文