For loop question of Tic Tac Toe game in python3

守給你的承諾、 提交于 2020-03-06 11:09:08

问题


It should return True while all squares in Tic Tac Toe are filled. However, the bug of this is, if I fill the row2 column2 square, it will return True immediately. Can someone help me out? Thank you very much! :)

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

This is my local board:

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)

I try both solutions below, but none of them solved my problems. I bet some other parts of my code has problems. Please help me check them out! Thank you very much!


回答1:


The problem is with your condition in boardFull. It will return True if for example the last row last col is populated and rest is empty it will return True. The simple way to fix & make it compact is like this. Once a col is empty no need to check further and return & save cpu cycles :)

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



回答2:


use the & operator but im a little confused as to your methods

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

so if you want it to return false if any col == ' ' then do this

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

return check so if you have a &= b you will only return true if a and b are true. this means you want to initially have a true value for a(which is saying you believe the board is empty) and if you get proved wrong: b == false then a will become false as well. once you have a false for a then you will never return true due to the fact &= requires both sides to be true to result in a true statement. Lmk if you want additional info.




回答3:


This code will return False if there is still one empty cell in the board else True.

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)

I have checked your code. The boardFull function still returning False because in your local_board[0][0] is still empty. To fix your code, change you local_board to:

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


来源:https://stackoverflow.com/questions/60445213/for-loop-question-of-tic-tac-toe-game-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!