五子棋规则和玩法

五子棋是一种非常古老且广泛流行的棋类游戏,它通常在一个15x15的棋盘上进行。这个问题要求使用Python编写一段五子棋的规则和玩法。

游戏规则

  1. 棋盘:五子棋棋盘是一个15x15的方格棋盘,玩家可以在其中放置棋子。
  2. 玩家角色:五子棋游戏中有两个玩家,一方执黑棋,另一方执白棋。
  3. 走棋规则:两名玩家交替进行走棋,黑棋先手。每次走棋时,玩家可以在空白的位置放置一个棋子。一旦放置完成,棋子不能再次移动。
  4. 获胜条件:当任意一方在横线、竖线或对角线上连续放置五颗相同颜色的棋子时,该方获得胜利。如果棋盘填满且没有达到获胜条件,则游戏以平局结束。

代码实现

以下是使用Python实现五子棋游戏规则和玩法的示例代码:

# 创建一个15x15的空棋盘
board = [[0] * 15 for _ in range(15)]

# 定义棋子的常量
EMPTY = 0
BLACK = 1
WHITE = 2

# 定义当前轮到哪个玩家走棋的变量
current_player = BLACK

# 定义函数用于检查是否有玩家获胜
def check_win(player):
    # 检查横向是否有五子相连
    for i in range(15):
        for j in range(11):
            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(11):
        for j in range(15):
            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(11):
        for j in range(11):
            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(4, 15):
        for j in range(11):
            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

# 游戏主循环
while True:
    # 打印当前棋盘状态
    for i in range(15):
        for j in range(15):
            if board[i][j] == EMPTY:
                print('.', end=' ')
            elif board[i][j] == BLACK:
                print('X', end=' ')
            elif board[i][j] == WHITE:
                print('O', end=' ')
        print()
    
    # 提示当前轮到哪个玩家走棋
    if current_player == BLACK:
        print("轮到黑棋走棋")
    else:
        print("轮到白棋走棋")
    
    # 获取玩家输入的走棋位置
    row = int(input("请输入行号(1-15): ")) - 1
    col = int(input("请输入列号(1-15): ")) - 1
    
    # 检查走棋位置是否合法
    if row < 0 or row >= 15 or col < 0 or col >= 15 or board[row][col] != EMPTY:
        print("走棋位置非法,请重新输入