-1

在纸笔游戏中,井字游戏中,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。那么,请任何人都可以帮助我吗?谢谢

4

2 回答 2

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检查对角线的语句移出循环。它们不依赖于rand c

于 2012-08-08T02:12:19.653 回答
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.'
于 2014-07-14T03:46:33.197 回答