对于井字游戏在python3中的循环问题

时间:2020-02-28 04:20:42

标签: python-3.x tic-tac-toe

enter image description here当井字游戏中的所有方块都填满时,它应该返回True。但是,这样做的错误是,如果我将row2 column2填充为正方形,它将立即返回True。有人可以帮我吗?非常感谢你! :)

def boardFull(self):
  '''
  Checks if the board has any remaining "empty" squares.
  Inputs: none
  Returns: True if the board has no "empty" squares (full); False otherwise
  '''
  check = True
  for row in local_board:
    for col in row:
      if col == ' ':
        check = False
      elif col != ' ':
        check = True
  return check

这是我的本地董事会:

local_board = [[' ','0','1','2'],['0',' ',' ',' '],['1',' ',' ',' '],['2',' ',' ',' ']]
def display_local_board():
  print(local_board[0][0]+' '+local_board[0][1]+'   '+local_board[0][2]+'   '+local_board[0][3])
  print(local_board[1][0]+' '+local_board[1][1]+' | '+local_board[1][2]+' | '+local_board[1][3])
  print('------------')
  print(local_board[2][0]+' '+local_board[2][1]+' | '+local_board[2][2]+' | '+local_board[2][3])
  print('------------')
  print(local_board[3][0]+' '+local_board[3][1]+' | '+local_board[3][2]+' | '+local_board[3][3])
class ClassicTicTacToe:
    def __init__(self):
        '''
        Initializes an empty Classic Tic Tac Toe board.
        Inputs: none
        Returns: None
        '''
        print('------------------------------\nThis is a Classic Tic Tac Toe.')
        self.drawBoard()


    def drawBoard(self):
        '''
        Displays the current state of the board, formatted with column and row 
        indices shown.
        Inputs: none
        Returns: None
        '''
        global continue_game
        display_local_board()
        if self.boardFull():
          continue_game = False
        while continue_game:
          self.pos_y_c = int(input('Player '+ player +', please enter a row: '))
          self.pos_x_c = int(input('Player '+ player +', please enter a column: '))
          self.update(self.pos_y_c,self.pos_x_c,'X')



    def squareIsEmpty(self, row, col):
        '''
        Checks if a given square is "empty", or if it already contains an X or O.
        Inputs:
           row (int) - row index of square to check
           col (int) - column index of square to check
        Returns: True if square is "empty"; False otherwise
        '''
        return {row, col} <= {0, 1, 2} and local_board[row+1][col+1]  == ' '


    def update(self, row, col, mark):
        '''
        Assigns the string, mark, to the board at the provided row and column, 
        but only if that square is "empty".
        Inputs:
           row (int) - row index of square to update
           col (int) - column index of square to update
           mark (str) - entry to place in square
        Returns: True if attempted update was successful; False otherwise
        '''
        if row < 0 or row > 2:
          row = int(input('Error: row not in correct range. Player'+ player +', please enter a row:  '))
          self.update(row,col,mark)
        elif col < 0 or col > 2:
          col = int(input('Error: column not in correct range. Player'+ player +', please enter a column: '))
          self.update(row,col,mark)

        if self.squareIsEmpty(row,col):
          local_board[row+1][col+1] = mark
          self.drawBoard()
        else:
          print('Error: could not make move!')
          self.drawBoard()



    def boardFull(self):
        '''
        Checks if the board has any remaining "empty" squares.
        Inputs: none
        Returns: True if the board has no "empty" squares (full); False otherwise
        '''
        check = True
        def boardFull(self):
          for row in local_board:
            for col in row:
              if col == ' ':
                return False
          return True


    def isWinner(self):
        '''
        Checks whether the current player has just made a winning move.  In order
        to win, the player must have just completed a line (of 3 squares) with 
        matching marks (i.e. 3 Xs  or 3 Os). That line can be horizontal, vertical,
        or diagonal.
        Inputs: none
        Returns: True if current player has won with their most recent move; 
                 False otherwise
        '''
        def switch_players():
          global turn
          players = [1,2]
          player = players[turn]
          turn = (turn + 1) % len(players)

我在下面尝试了两种解决方案,但是都没有解决我的问题。我敢打赌我的代码的其他部分有问题。请帮我检查一下!非常感谢!

3 个答案:

答案 0 :(得分:0)

问题在于您在boardFull中的状况。例如,如果填充了最后一行last col,而rest为空,则它将返回True。修复并使其紧凑的简单方法是这样的。一旦col为空,则无需进一步检查并返回并保存CPU周期:)

def boardFull(self):
  for row in local_board:
    for col in row:
      if col == ' ':
        return False
  return True

答案 1 :(得分:0)

使用&运算符,但对您的方法有些困惑

 for row in local_board:
    for col in row:
      if col == ' ':
        check = False
      elif col != ' ':
        check = True
  return check

因此,如果您希望它在任何col ==''的情况下返回false,则执行此操作

for row in local_board:
for col in row:
  if col == ' ':
    check = False
  elif col != ' ':
    check &= True

退货支票 因此,如果您有&= b,则仅当a和b为true时才返回true。这意味着您最初想为a设置一个真值(也就是说,您认为棋盘为空),并且如果证明自己错了:b == false,那么a也将变为false。一旦对a进行了错误处理,则由于&=要求双方均为true才能得出true语句,因此您将永远不会返回true。 Lmk,如果您需要其他信息。

答案 2 :(得分:0)

如果板上还有一个空单元格,则此代码将返回False。

local_board = [[' ','0','1','2'],['0',' ',' ',' '],['1',' ',' ',' '],['2',' ',' ',' ']]

def boardFull(board):
    check = True
    for row in local_board:
        if " " in row:
            check = False
    return check

boardFull(local_board)

我已经检查了您的代码。 boardFull 函数仍返回False,因为在您的 local_board [0] [0] 中仍然为空。要修复代码,请将local_board更改为:

local_board = [['T','0','1','2'],['0',' ',' ',' '],['1',' ',' ',' '],['2',' ',' ',' ']]