在铅笔纸游戏中,2名玩家轮流在3x3方格的棋盘上标记'X'和'O'。成功在垂直,水平或斜条纹上标记3个连续'X'或'O'的玩家赢得了游戏。编写一个确定井字游戏结果的函数。
实施例
>>> tictactoe([('X', ' ', 'O'),
(' ', 'O', 'O'),
('X', 'X', 'X') ])
"'X' wins (horizontal)."
>>> tictactoe([('X', 'O', 'X'),
... ('O', 'X', 'O'),
... ('O', 'X', 'O') ])
'Draw.'
>>> tictactoe([('X', 'O', 'O'),
... ('X', 'O', ' '),
... ('O', 'X', ' ') ])
"'O' wins (diagonal)."
>>> tictactoe([('X', 'O', 'X'),
... ('O', 'O', 'X'),
... ('O', 'X', 'X') ])
"'X' wins (vertical)."
def tictactoe(moves):
for r in range(len(moves)):
for c in range(len(moves[r])):
if moves[0][c]==moves[1][c]==moves[2][c]:
a="'%s' wins (%s)."%((moves[0][c]),'vertical')
elif moves[r][0]==moves[r][1]==moves[r][2]:
a="'%s' wins (%s)."%((moves[r][0]),'horizontal')
elif moves[0][0]==moves[1][1]==moves[2][2]:
a="'%s' wins (%s)."%((moves[0][0]),'diagonal')
elif moves[0][2]==moves[1][1]==moves[2][0]:
a="'%s' wins (%s)."%((moves[0][2]),'diagonal')
else:
a='Draw.'
print(a)
我写了这样的代码,我的范围不起作用(我认为)。因为,它将r和c的值取为3,而不是0,1,2,3。那么,请有人帮我这个吗? 谢谢
答案 0 :(得分:0)
当玩家获胜时,你的循环不会退出。我会尝试这样的事情:
def tictactoe_state(moves):
for r in range(len(moves)):
for c in range(len(moves[r])):
if moves[0][c] == moves[1][c] == moves[2][c]:
return "'%s' wins (%s)." % (moves[0][c], 'vertical')
elif moves[r][0] == moves[r][1] == moves[r][2]:
return "'%s' wins (%s)." % (moves[r][0], 'horizontal')
elif moves[0][0] == moves[1][1] == moves[2][2]:
return "'%s' wins (%s)." % (moves[0][0], 'diagonal')
elif moves[0][2] == moves[1][1] == moves[2][0]:
return "'%s' wins (%s)." % (moves[0][2], 'diagonal')
# You still have to make sure the game isn't a draw.
# To do that, see if there are any blank squares.
return 'Still playing'
另外,我会移动检查对角线的if
语句。他们不依赖于r
和c
。
答案 1 :(得分:0)
试试这个..
def tictactoe(moves):
for r in range(len(moves)):
for c in range(len(moves[r])):
if moves[0][c]==moves[1][c]==moves[2][c]:
return "\'%s\' wins (%s)." % ((moves[0][c]),'vertical')
elif moves[r][0]==moves[r][1]==moves[r][2]:
return "\'%s\' wins (%s)."%((moves[r][0]),'horizontal')
elif moves[0][0]==moves[1][1]==moves[2][2]:
return "\'%s\' wins (%s)."%((moves[0][0]),'diagonal')
elif moves[0][2]==moves[1][1]==moves[2][0]:
return "\'%s\' wins (%s)."%((moves[0][2]),'diagonal')
return 'Draw.'