如标题所示,我使用的是把所有可能性都列出来判断,但希望可以得到简化!非常感谢,下面是代码:
the_board = {'top-L': '', 'top-M': '', 'top-R': '',
'mid-L': '', 'mid-M': '', 'mid-R': '',
'low-L': '', 'low-M': '', 'low-R': ''}
# print(the_board)
def print_board(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
# print_board(the_board)
turn = 'X'
for i in range(9):
print_board(the_board)
move = input('把' + turn + '画在哪:')
if move not in the_board.keys():
print('请输入正确的位置')
continue
the_board[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
if the_board['top-L'] == the_board['top-M'] == the_board['top-R'] == 'X' or the_board['mid-L'] == the_board['mid-M'] == the_board['mid-R'] == 'X' or the_board['low-L'] == the_board['low-M'] == the_board['low-R'] == 'X' or the_board['top-L'] == the_board['mid-L'] == the_board['low-L'] == 'X' or the_board['top-M'] == the_board['mid-M'] == the_board['low-M'] == 'X' or the_board['top-R'] == the_board['mid-R'] == the_board['low-R'] == 'X' or the_board['top-L'] == the_board['mid-M'] == the_board['low-R'] == 'X' or the_board['top-R'] == the_board['mid-M'] == the_board['low-L'] == 'X' :
print('X,获胜')
break
elif the_board['top-L'] == the_board['top-M'] == the_board['top-R'] == 'O' or the_board['mid-L'] == the_board['mid-M'] == the_board['mid-R'] == 'O' or the_board['low-L'] == the_board['low-M'] == the_board['low-R'] == 'O' or the_board['top-L'] == the_board['mid-L'] == the_board['low-L'] == 'O' or the_board['top-M'] == the_board['mid-M'] == the_board['low-M'] == 'O' or the_board['top-R'] == the_board['mid-R'] == the_board['low-R'] == 'O' or the_board['top-L'] == the_board['mid-M'] == the_board['low-R'] == 'O' or the_board['top-R'] == the_board['mid-M'] == the_board['low-L'] == 'O':
print('O,获胜')
break
print_board(the_board)
**
```**
```
board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
s = 'XO' # 棋子符号,因为只有两个,所以我们用步数取2的余来确定落子方
step = 0 # 落子步数
while True:
for row in range(3):
if row > 0:
print('-+-+-')
print('|'.join(board[2 - row])) # 为了符合数字小键盘样子,我们反着输出行
c = s[step % 2] # 获得当前落子方的棋子符号
print('当前落子为{}'.format(c))
n = input('输入落子位置(1-9),0退出本局:')
if n.isnumeric() and n in '0123456789':
n = int(n)
if n == 0:
print('你中断了本局游戏')
break
n -= 1
board[n // 3][n % 3] = s[step % 2]
# 行或列判断胜利
if ''.join(board[n // 3]) == c * 3 or ''.join([row[n % 3] for row in board]) == c * 3:
print('游戏结束,{}胜利'.format(c))
break
# 斜线判断胜利
if board[0][0] + board[1][1] + board[2][2] == c * 3 or board[0][2] + board[1][1] + board[2][0] == c * 3:
print('游戏结束,{}胜利'.format(c))
break
step += 1
先循环一遍,判断横竖斜有没有都相同的
如果有,再判断它到底是O还是X
更简单的办法是,你打印的时候打印O和X,但list里存的其实是0和1
然后按行按列分别sum一下,如果是0或者3就说明一行都相同