用python写五子棋
时间: 2023-10-01 22:06:55 浏览: 77
好的,我可以为您提供一个基本的五子棋游戏的 Python 代码。下面是代码:
```python
import numpy as np
# 初始化棋盘
def init_board():
board = np.zeros((15, 15), dtype=int)
return board
# 判断是否有一方胜利
def check_win(board, row, col, player):
# 判断行
if col <= 10:
if np.all(board[row, col:col+5] == player):
return True
# 判断列
if row <= 10:
if np.all(board[row:row+5, col] == player):
return True
# 判断对角线
if row <= 10 and col <= 10:
if np.all(board[row:row+5, col:col+5].diagonal() == player):
return True
# 判断反对角线
if row <= 10 and col >= 4:
if np.all(np.fliplr(board[row:row+5, col-4:col+1]).diagonal() == player):
return True
return False
# 判断是否下满棋子
def check_full(board):
return np.all(board != 0)
# 打印棋盘
def print_board(board):
print(" ", end="")
for i in range(15):
print(chr(i+ord('a')), end="")
print()
for i in range(15):
print("{:2d}".format(i+1), end="")
for j in range(15):
if board[i, j] == 1:
print("●", end="")
elif board[i, j] == -1:
print("○", end="")
else:
print("┼", end="")
print()
# 主函数
def main():
board = init_board()
player = 1 # 玩家先手
while True:
print_board(board)
if player == 1:
print("黑方落子:")
else:
print("白方落子:")
move = input() # 输入落子坐标
col = ord(move[0].lower()) - ord('a')
row = int(move[1:]) - 1
if board[row, col] != 0:
print("此处已有棋子,请重新输入!")
continue
board[row, col] = player
if check_win(board, row, col, player):
print_board(board)
print("恭喜玩家{}获得胜利!".format("黑方" if player == 1 else "白方"))
break
if check_full(board):
print_board(board)
print("棋盘已满,双方打成平局!")
break
player = -player # 轮换玩家
if __name__ == "__main__":
main()
```
这个代码中,我们使用了 numpy 库来实现二维数组的操作,使用了一些基本的 Python 语法和控制结构来实现五子棋的逻辑。其中, `init_board()` 函数用于初始化棋盘, `check_win()` 函数用于判断是否有一方胜利, `check_full()` 函数用于判断是否下满棋子, `print_board()` 函数用于打印棋盘, `main()` 函数用于实现游戏的主逻辑。
阅读全文