Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

why won't this print the position.

0 votes
asked Jul 15, 2020 by Alon Liubovitch (130 points)
class TikTacToeBoard:
    def __init__(self):
        self.board = [['_'] * 3, ['_'] * 3, ['_'] * 3]
       
    def set_x(self,r,c):
        x.position[0] = [r]
        x.position[1] = [c]
        
   
    def set_o(self,r,c):
        o.position = (r,c)
        [r,c] = 2,4
        o.position[0] = [r]
        o.position[1] = [c]
        print(o.position)
   
    def clear(self):
        pass
       
    def __str__(self):
         return '\n'.join([' '.join(row) for row in self.board])
         ['_ _ _', '_ _ _', '_ _ _']
       
      
       

   

# Representation

my_board = TikTacToeBoard()
print(my_board)

1 Answer

0 votes
answered Jul 15, 2020 by xDELLx (6,200 points)

If you invoke "my_board.set_o(1,2)"  after printing the board, the error in pyhton is

Traceback (most recent call last):
  File "t.py", line 35, in <module>
    my_board.set_o(2,4)
  File "t.py", line 11, in set_o
    o.position = (r,c)
NameError: global name 'o' is not defined

I think in set_o only the position on board has to be marked as 'O' & can be easily done by :

self.board[r][c]='O'

Below I have tried to correct hte prog:

class TikTacToeBoard:
    def __init__(self):
        self.board = [['-'] * 3, ['-'] * 3, ['-'] * 3]

    def validate(self,r,c):
        if r<3 and c < 3 and self.board[r][c] == '-':
            return True
        else:
            return False
       
    def set_x(self,r,c):
        '''x.position[0] = [r]
        x.position[1] = [c]'''
        if self.validate(r,c) :
            self.board[r][c]='X'
            return True
        return False
        
   
    def set_o(self,r,c):
        '''
        o.position = (r,c)
        [r,c] = 2,4
        o.position[0] = [r]
        o.position[1] = [c]
        print(o.position)
        '''
        if self.validate(r,c) :
            self.board[r][c]='O'
            return True
        return False

   
    def clear(self):
        self.board = [['-'] * 3, ['-'] * 3, ['-'] * 3]
        pass
       
    def __str__(self):
        #return "Brd Seldf\n"
        return '\n'.join([' '.join(row) for row in self.board])
        #['_ * _', '_ * _', '_ * _']
         
# Representation

my_board = TikTacToeBoard()
print(my_board)
my_board.set_o(1,2)
print ("After 0 set at 1,2 \n")
print(my_board)
#my_board.clear()
print ("Try to set X on 1,2 & print \n")
my_board.set_x(1,2)
print(my_board)

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...