写一个python五子棋代码
时间: 2024-01-31 12:04:24 浏览: 93
好的,以下是一个简单的 Python 五子棋游戏示例代码:
```python
import numpy as np
# 棋盘大小
BOARD_SIZE = 15
# 定义棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
# 定义棋子标志
PLAYER1 = 1
PLAYER2 = 2
# 定义当前玩家
current_player = PLAYER1
# 定义落子函数
def drop_piece(row, col, player):
board[row][col] = player
# 定义判断胜利函数
def check_win(player):
# 检查横向
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE - 4):
if board[row][col] == player and board[row][col+1] == player and board[row][col+2] == player and board[row][col+3] == player and board[row][col+4] == player:
return True
# 检查纵向
for row in range(BOARD_SIZE - 4):
for col in range(BOARD_SIZE):
if board[row][col] == player and board[row+1][col] == player and board[row+2][col] == player and board[row+3][col] == player and board[row+4][col] == player:
return True
# 检查正斜向
for row in range(BOARD_SIZE - 4):
for col in range(BOARD_SIZE - 4):
if board[row][col] == player and board[row+1][col+1] == player and board[row+2][col+2] == player and board[row+3][col+3] == player and board[row+4][col+4] == player:
return True
# 检查反斜向
for row in range(4, BOARD_SIZE):
for col in range(BOARD_SIZE - 4):
if board[row][col] == player and board[row-1][col+1] == player and board[row-2][col+2] == player and board[row-3][col+3] == player and board[row-4][col+4] == player:
return True
return False
# 定义主函数
def main():
# 打印初始棋盘
print(board)
# 循环下棋
while True:
# 获取玩家下棋位置
row = int(input("请输入行数:"))
col = int(input("请输入列数:"))
# 检查位置是否合法
if row < 0 or row >= BOARD_SIZE or col < 0 or col >= BOARD_SIZE:
print("位置不合法,请重新输入!")
continue
elif board[row][col] != 0:
print("该位置已经有棋子,请重新输入!")
continue
# 落子
drop_piece(row, col, current_player)
# 打印棋盘
print(board)
# 判断胜利
if check_win(current_player):
print("恭喜玩家", current_player, "获胜!")
break
# 切换玩家
if current_player == PLAYER1:
current_player = PLAYER2
else:
current_player = PLAYER1
if __name__ == "__main__":
main()
```
这个示例代码中,我们使用了 numpy 库来创建二维数组作为棋盘,使用 1 和 2 代表两个玩家的棋子,使用 `drop_piece` 函数来落子,使用 `check_win` 函数来判断胜利情况,使用主函数 `main` 来控制游戏的进行。在主函数中,我们循环进行下棋,每次获取玩家输入的位置,检查位置是否合法,落子,打印棋盘,判断胜利,切换玩家。当有玩家获胜时,游戏结束。
阅读全文