用python写一个五子棋代码
时间: 2023-12-17 15:47:14 浏览: 101
好的,以下是一个简单的五子棋代码:
```python
import numpy as np
# 初始化棋盘
def init_board():
board = np.zeros((15, 15))
return board
# 判断胜利条件
def check_win(board, row, col, player):
# 判断行
if np.sum(board[row, :] == player) >= 5:
return True
# 判断列
if np.sum(board[:, col] == player) >= 5:
return True
# 判断对角线
if np.sum(np.diag(board, k=col-row) == player) >= 5:
return True
# 判断反对角线
if np.sum(np.diag(np.fliplr(board), k=15-col-row) == player) >= 5:
return True
return False
# 玩家下棋
def player_move(board, player):
while True:
move = input("请落子(例如:3,4):")
row, col = move.split(",")
row, col = int(row), int(col)
if board[row, col] != 0:
print("此处已有棋子,请重新落子!")
else:
board[row, col] = player
break
# AI下棋
def ai_move(board, player):
# 随机下棋
while True:
row, col = np.random.randint(0, 15, size=2)
if board[row, col] == 0:
board[row, col] = player
break
# 主函数
def main():
board = init_board()
player = 1
while True:
if player == 1:
player_move(board, player)
else:
ai_move(board, player)
print(board)
if check_win(board, row, col, player):
print("玩家{}胜利!".format(player))
break
player = 3 - player # 切换玩家
if __name__ == '__main__':
main()
```
该代码使用numpy数组实现了五子棋的基本功能,包括初始化棋盘、判断胜利条件、玩家下棋、AI下棋等。当一方胜利时,程序会输出胜利信息并结束游戏。
阅读全文