设置两人对战五子棋,代码如下:
# 定义棋盘大小
BOARD_SIZE = 15
# 初始化棋盘
def init_board():
board = [['+' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
return board
# 打印棋盘
def print_board(board):
for row in board:
print(' '.join(row))
print()
# 判断是否五子连珠
def check_win(board, row, col, piece):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)] # 横、竖、左斜、右斜
for dr, dc in directions:
count = 1
r, c = row + dr, col + dc
while 0 <= r < BOARD_SIZE and 0 <= c < BOARD_SIZE and board[r][c] == piece:
count += 1
r += dr
c += dc
r, c = row - dr, col - dc
while 0 <= r < BOARD_SIZE and 0 <= c < BOARD_SIZE and board[r][c] == piece:
count += 1
r -= dr
c -= dc
if count >= 5:
return True
return False
# 主程序
def main():
print("欢迎来到五子棋游戏!")
print("请按照行号和列号输入你的下棋位置,例如:3,4 表示第3行第4列。")
board = init_board()