编写五子棋的完整python代码_python实现五子棋程序
时间: 2023-07-23 14:21:26 浏览: 87
以下是一个简单的五子棋程序的Python代码实现:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
# 定义黑白棋子的常量
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE))
# 定义落子函数
def move(row, col, player):
board[row][col] = player
# 定义判断胜利的函数
def check_win(player):
# 横向连续棋子的数量
for i in range(BOARD_SIZE):
count = 0
for j in range(BOARD_SIZE):
if board[i][j] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 竖向连续棋子的数量
for i in range(BOARD_SIZE):
count = 0
for j in range(BOARD_SIZE):
if board[j][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 左上到右下斜向连续棋子的数量
for i in range(BOARD_SIZE - 4):
for j in range(BOARD_SIZE - 4):
count = 0
for k in range(5):
if board[i+k][j+k] == player:
count += 1
if count == 5:
return True
# 右上到左下斜向连续棋子的数量
for i in range(BOARD_SIZE - 4):
for j in range(4, BOARD_SIZE):
count = 0
for k in range(5):
if board[i+k][j-k] == player:
count += 1
if count == 5:
return True
return False
# 游戏主循环
player = BLACK
while True:
# 打印棋盘
print(board)
# 落子
row = int(input("请输入行号:"))
col = int(input("请输入列号:"))
move(row, col, player)
# 判断胜利
if check_win(player):
print("恭喜玩家{}获胜!".format(player))
break
# 切换玩家
if player == BLACK:
player = WHITE
else:
player = BLACK
```
这个程序使用了NumPy数组来表示棋盘,实现了落子和判断胜利的函数,以及游戏的主循环。在游戏中,玩家通过输入行号和列号来落子,程序会交替切换黑白棋手并判断胜利。
阅读全文