python程序设计思维，井字棋游戏：构建棋盘3X3的棋盘，X和O分别下棋，当三个棋连成线时胜出。已在board中给出棋盘的位置以及初始的字符串,并可以通过print_board()打印每次下棋后的棋盘结果。

``````# 打印棋盘
def print_board(board):
for row in board:
print('|',end = '')
for value in row:
print(value, '|', end = ' ')
print('\n'+' — ' * len(row))

# 输入位置并打印棋盘
def inp(board, who, position):
row, col = position
repeat_inp = False # 是否重复下入
if  board[int(row)-1][int(col)-1] =='?':
# 输入位置
board[int(row)-1][int(col)-1] = who
# 打印棋盘
print_board(board)
else:
print('此位置已下')
repeat_inp = True
return board, repeat_inp``````

判断结果：

``````# 判断棋盘结果,n:连续n个子则胜利
def panduan(board, n):
# 给棋盘左右两边加上（n-1）列,以及下方加上（n-1）行
board_ = [['?'  for g in range(len(board[0]) + 2*(n - 1))] for i in range(len(board) + (n-1))]
for row in range(len(board)):
for col in range(len(board[0])):
board_[row][col+(n-1)] = board[row][col]

for row in range(len(board)):
for col in range(len(board[0])):
who = board_[row][col+(n-1)]
# 横向获胜
for i in range(1,n):
if not (who == board_[row][col +(n-1)+ i] != '?'):
break
else:
return who

# 纵向获胜
for i in range(1,n):
if not (who == board_[row + i][col+(n-1)] != '?'):
break
else:
return who

# 右斜向获胜
for i in range(1,n):
if not (who == board_[row + i][col +(n-1)+ i] != '?'):
break
else:
return who

# 左斜向获胜
for i in range(1,n):
if not (who == board_[row + i][col +(n-1)- i] != '?'):
break
else:
return who

return None``````

``````# 判断是否（提前）平局; n:连续n个子则胜利
def earlyTermination(board, n):
# 思路：对未下入的坐标填充满某方，然后判断该方人员是否还有获胜的机会
result = [] # 存储x/o是否还有获胜的机会
for who in ['X', 'O']:
board_ = [row.copy() for row in board]  # 直接copy是浅拷贝
# 对为？的位置（即还未下入的坐标）填充满x/o
for row in range(len(board_)):
for col in range(len(board_[0])):
board_[row][col] = who if board_[row][col] == '?' else board_[row][col]
result.append(panduan(board_, n))
# 若全为False，则游戏结束，平局
if not any(result):
return True
else:
return False``````

``````# jupyter中动态显示需要
from IPython import display
# 启动：slideLength：棋盘边长，n:连续几个子
def start(sideLength, n):
assert n<= sideLength, '不合规则：n must <= sideLength'
# 初始化棋盘
board = [['?' for i in range(sideLength)] for  i in range(sideLength)]
positions = ''.join(list(map(str,range(1,sideLength+1))))
# 开始方
who  = 'X'
# 获胜方
champion = None

# 若还没人获胜，则继续游戏
while not champion:
display.clear_output(wait=True)    # 清除输出
while True:
position = input(f'请{who}方输入坐标:')
if position[0] not in positions or position[1] not in positions:
print('请输入正确的坐标')
else:
break
# 输入坐标并打印棋盘
board, repeat = inp(board, who, position)
# 获取获胜方
champion = panduan(board, n)
# 判断是否提前平局
pingju = earlyTermination(board,n)
if pingju:
break
# 如果重复下入，则该方重新输入
if not repeat:
who = 'X' if who =='O'  else 'O'

print(f'胜方:{champion}') if champion else print('平局')``````