In: Computer Science
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def __str__(self): s = "" for j in range(7, -1, -1): #for each row for i in range(8): # for each column if self.pieces[j][i] is None: # if self.pieces[j][i] is None s += "." # populate the row with '.' val for each column else: s += self.pieces [j][i].get_symbol() s += "\n" #after each row add a new line return s # return after iterating through all rows and columns class Piece: def __init__(self, board, row, col, is_white): self.row = row self.col = col self.is_white = is_white board.pieces[row][col] = self def get_symbol(self): pass class Rook(Piece): def __init__(self, board, row, col, is_white): Piece.__init__(board, row, col, is_white) def get_symbol(self): if self.is_white: return '\u2656' else: return '\u265C'
board = Board() Rook(board, 0, 0, True) Rook(board, 0, 7, True) Rook(board, 7, 0, False) Rook(board, 7, 7, False) print(str(board))
It comes up as a problem with is_white can you tell me whats wrong. it's supose to print out an 8x8 matrix with the rooks on the board.
You forgot to pass self when you are calling the super class constructor in line 31 in class Rook.
Your code
class Rook(Piece):
def __init__(self, board, row, col, is_white):
Piece.__init__(board, row, col, is_white)
def get_symbol(self):
if self.is_white:
return '\u2656'
else:
return '\u265C'
Correct Code
class Rook(Piece):
def __init__(self, board, row, col, is_white):
Piece.__init__(self,board, row, col, is_white)
def get_symbol(self):
if self.is_white:
return '\u2656'
else:
return '\u265C'
Explanation
In your code, Rook is a subclass of Piece, so when we call the Piece's constructor from Rook's constructor we have to supply the self object as well because this is not an object creation instead this object is created and we are just passing the reference.
When we create a new object, in that case we dont need to pass the self object.
Sample Output