编写五子棋的完整python代码_python实现五子棋程序
时间: 2023-07-23 20:21:09 浏览: 94
好的,以下是一个简单的五子棋Python程序的代码实现:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE))
# 定义落子函数
def drop_piece(row, col, player):
board[row][col] = player
# 定义判断胜利函数
def is_win(player):
# 判断行
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE - 4):
if np.all(board[row][col:col+5] == player):
return True
# 判断列
for row in range(BOARD_SIZE - 4):
for col in range(BOARD_SIZE):
if np.all(board[row:row+5, col] == player):
return True
# 判断正斜线
for row in range(BOARD_SIZE - 4):
for col in range(BOARD_SIZE - 4):
if np.all(board[row:row+5, col:col+5].diagonal() == player):
return True
# 判断反斜线
for row in range(4, BOARD_SIZE):
for col in range(BOARD_SIZE - 4):
if np.all(board[row-4:row+1, col:col+5].diagonal()[::-1] == player):
return True
return False
# 定义主函数
def main():
# 定义黑棋为1,白棋为2
players = [1, 2]
cur_player = 0
while True:
# 打印棋盘
print(board)
# 获取当前玩家
player = players[cur_player]
# 玩家输入落子位置
row = int(input("Player " + str(player) + ", enter row: "))
col = int(input("Player " + str(player) + ", enter column: "))
# 落子
drop_piece(row, col, player)
# 判断胜利
if is_win(player):
print("Player " + str(player) + " wins!")
break
# 切换玩家
cur_player = (cur_player + 1) % 2
if __name__ == '__main__':
main()
```
这是一个比较简单的五子棋程序,实现了落子和判断胜利的功能。你可以根据自己的需求进行修改和扩展。
阅读全文