用python写五子棋项目
时间: 2023-08-10 18:17:00 浏览: 88
好的,下面是五子棋的 Python 代码示例:
```python
import numpy as np
# 初始化棋盘
def init_board():
board = np.zeros((15, 15), dtype=int)
return board
# 判断当前位置是否可以落子
def is_valid_move(board, row, col):
if board[row, col] == 0:
return True
else:
return False
# 落子
def make_move(board, player, row, col):
board[row, col] = player
return board
# 判断是否有五子连珠
def has_won(board, player):
for i in range(15):
for j in range(11):
if np.all(board[i, j:j+5] == player):
return True
for i in range(11):
for j in range(15):
if np.all(board[i:i+5, j] == player):
return True
for i in range(11):
for j in range(11):
if np.all(board[i:i+5, j:j+5].diagonal() == player):
return True
if np.all(np.fliplr(board[i:i+5, j:j+5]).diagonal() == player):
return True
return False
# 判断是否棋盘已满
def is_full(board):
if np.count_nonzero(board) == board.size:
return True
else:
return False
# 主函数
def main():
# 初始化棋盘、玩家和第一步
board = init_board()
player = 1
step = 1
# 开始游戏
while True:
print("第%d步,玩家%d,请落子:" % (step, player))
row = int(input("请输入行:"))
col = int(input("请输入列:"))
if not is_valid_move(board, row, col):
print("该位置已有棋子,请重新落子!")
continue
board = make_move(board, player, row, col)
if has_won(board, player):
print("恭喜玩家%d获胜!" % player)
break
if is_full(board):
print("棋盘已满,平局!")
break
# 切换玩家
player = 3 - player
step += 1
if __name__ == '__main__':
main()
```
这是一个比较简单的五子棋实现,使用了 NumPy 库来处理棋盘。玩家通过输入行和列来落子,程序会判断该位置是否可以落子,如果可以则在该位置落子,并判断是否胜利或平局,同时切换玩家。
阅读全文