python双人五子棋代码
时间: 2023-07-03 13:28:21 浏览: 45
以下一个简单的双人五子棋Python代码:
```python
import numpy as np
# 创建一个15x15的棋盘
board = np.zeros((15, 15), dtype=int)
# 定义黑白棋子
BLACK = 1
WHITE = 2
# 定义棋子落下的函数
def put_stone(x, y, stone):
board[x][y] = stone
# 定义判断胜负的函数
def check_win(x, y, stone):
# 判断横向是否有五子相连
count = 0
for i in range(15):
if board[x][i] == stone:
count += 1
if count == 5:
return True
else:
count = 0
# 判断纵向是否有五子相连
count = 0
for i in range(15):
if board[i][y] == stone:
count += 1
if count == 5:
return True
else:
count = 0
# 判断左上到右下是否有五子相连
count = 0
for i in range(-4, 5):
if 0 <= x+i < 15 and 0 <= y+i < 15 and board[x+i][y+i] == stone:
count += 1
if count == 5:
return True
else:
count = 0
# 判断左下到右上是否有五子相连
count = 0
for i in range(-4, 5):
if 0 <= x+i < 15 and 0 <= y-i < 15 and board[x+i][y-i] == stone:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 定义主程序
def main():
# 定义黑白棋子
BLACK = 1
WHITE = 2
# 定义当前下棋的人
current_player = BLACK
# 开始下棋
while True:
# 打印棋盘
print(board)
# 获取玩家落子的位置
x, y = map(int, input("请玩家{}落子:".format(current_player)).split())
# 判断该位置是否已经有棋子
if board[x][y] != 0:
print("该位置已有棋子,请重新落子!")
continue
# 落子
put_stone(x, y, current_player)
# 判断是否胜利
if check_win(x, y, current_player):
print("玩家{}获胜!".format(current_player))
break
# 切换下棋的人
current_player = WHITE if current_player == BLACK else BLACK
if __name__ == '__main__':
main()
```
这个代码实现了一个简单的双人五子棋游戏,运行后可以通过输入坐标来落子,当有一方获胜时游戏结束。