请编写一段代码,实现简单的五子棋游戏
时间: 2023-11-27 20:53:38 浏览: 76
简单的五子棋游戏代码
以下是一个简单的五子棋游戏代码示例:
```python
import numpy as np
# 定义棋盘大小
board_size = 15
# 初始化棋盘
board = np.zeros((board_size, board_size))
# 定义落子函数
def play(board, row, col, player):
board[row][col] = player
# 定义判断胜负函数
def is_win(board, player):
# 判断行
for i in range(board_size):
for j in range(board_size-4):
if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player and board[i][j+4] == player:
return True
# 判断列
for i in range(board_size-4):
for j in range(board_size):
if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player and board[i+4][j] == player:
return True
# 判断对角线
for i in range(board_size-4):
for j in range(board_size-4):
if board[i][j] == player and board[i+1][j+1] == player and board[i+2][j+2] == player and board[i+3][j+3] == player and board[i+4][j+4] == player:
return True
# 判断反对角线
for i in range(board_size-4):
for j in range(4, board_size):
if board[i][j] == player and board[i+1][j-1] == player and board[i+2][j-2] == player and board[i+3][j-3] == player and board[i+4][j-4] == player:
return True
return False
# 定义两个玩家
player1 = 1
player2 = 2
# 开始游戏
while True:
# 玩家1落子
row, col = map(int, input("Player 1's turn: ").split())
play(board, row, col, player1)
if is_win(board, player1):
print("Player 1 wins!")
break
# 玩家2落子
row, col = map(int, input("Player 2's turn: ").split())
play(board, row, col, player2)
if is_win(board, player2):
print("Player 2 wins!")
break
```
在这个示例中,我们使用了numpy库来创建一个二维数组作为棋盘。落子函数play接受一个二维数组board、落子的行列坐标和玩家编号,将玩家的棋子标记在对应位置。判断胜负函数is_win则遍历棋盘,判断是否存在五个相同的棋子连成一线。最后使用while循环轮流让两个玩家落子,直到有一方胜利。
阅读全文