四子棋是一种经典的棋盘游戏,游戏规则是玩家轮流在棋盘的空格上放置棋子,如果有一个玩家在横、竖、斜线上连续放置了四颗棋子,则该玩家胜利。
下面是一份基于 Python 的四子棋代码的示例:
```
定义棋盘大小
BOARD_SIZE = 15
初始化棋盘
board = [['-' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
定义棋子颜色
BLACK = 'B' WHITE = 'W'
初始化当前玩家为黑棋
current_player = BLACK
定义获胜条件
def check_win(x, y):
检查水平方向是否有连续四个棋子
count = 1 for i in range(1, 4): if y + i < BOARD_SIZE and board[x][y + i] == current_player: count += 1 else: break for i in range(1, 4): if y - i >= 0 and board[x][y - i] == current_player: count += 1 else: break if count >= 4: return True
检查垂直方向是否有连续四个棋子
count = 1 for i in range(1, 4): if x + i < BOARD_SIZE and board[x + i][y] == current_player: count += 1 else: break for i in range(1, 4): if x - i >= 0 and board[x - i][y] == current_player: count += 1 else: break if count >= 4: return True
检查左上 - 右下方向是否有连续四个棋子
count = 1 for i in range(1, 4): if x + i < BOARD_SIZE and y + i < BOARD_SIZE and board[x + i][y + i] == current_player: count += 1 else: break for i in range(1, 4): if x - i >= 0 and y - i >= 0 and board[x - i