Home > Software design >  Print out chess board from list of objects
Print out chess board from list of objects

Time:12-04

I have the following task to print on screen the pieces of the chees board, they have to be in this format ♔ but this is the least of the problem.

if I loop through I get this <main.Rook object at 0x7fc8fa510790>, how can I code --> if main.Rook == ♖,

The output when the code is completed should be like that:

♖ ♔  
 ♜  ♜
 ♚ ♜ 
♖   ♗
♗    

at the moment I build the board like that



class Piece:
    pos_x : int 
    pos_y : int
    side_ : bool #True for White and False for Black
    def __init__(self, pos_X : int, pos_Y : int, side_ : bool):
        '''sets initial values'''
        self.pos_x=pos_X 
        self.pos_y=pos_Y
        self.side_=side_ #maybe set it to True?

    def __str__(self):#
        return f"{self.pos_x} {self.pos_y} {self.side_}"

    def get_side(self):
        return side_
      
class Rook(Piece):
    def __init__(self, pos_X : int, pos_Y : int, side_ : bool):
        '''sets initial values by calling the constructor of Piece'''
        super().__init__(pos_X, pos_Y, side_)
    def __repr__(self):
      if self.side_==False:
           return "♜" 
      else:
        return "♖"  


wr1 = Rook(1,2,True)
br1 = Rook(4,3,False)
br2 = Rook(2,4,False)
br3 = Rook(5,4, False)
wr2 = Rook(1,5, True)
B1 = (10, [wr1,br1, br2, br3, wr2])

so now I am working on the following function, I did not go to far, I can get the piece position, side and so on but how would I know if they are ROOK or something else, if I had a variable I could use their name for example, but here I have an object, can someone illustrate a method how to approach this?

def conf2unicode(B: Board) -> str: 
    '''converts board cofiguration B to unicode format string (see section Unicode board configurations)'''
    for piece in B[1]:
      print (piece)

CodePudding user response:

Why not set Rook's __repr__ to return something like "♜":

def __repr__(self):
   return "♜"

You can then print out B1 and get your icons nice and tidy.

CodePudding user response:

One approach is to break down the bigger tasks into several smaller steps i.e:

  1. Loop through each row
  2. Find all pieces in that row and build a string to represent it
  3. Print that row

A partial solution could be to print the board without the pieces and then expand from there.

To get the symbol to represent the rook, you could add a method to the class which returns the correct symbol.

Note, the modulo-operator is nice for creating alternating black and white squares.

CodePudding user response:

I would define a class for the board, so that you can save the pieces in a 2-D grid. You could then also have some cross-references with dictionaries, so you can quickly find a piece on a board by its color and type (i.e. class).

Here are some ideas:

WHITE = True
BLACK = False

class Piece:
    pos_x: int 
    pos_y: int
    side: bool # BLACK or WHITE
    def __init__(self, side: bool, symbol: str):
        self.side = side
        self.symbol = symbol
        self.pos_x = self.pos_y = None

    def set_position(self, pos_x: int, pos_y: int):
        self.pos_x = pos_x
        self.pos_y = pos_y

    def clear_position(self):
        self.pos_x = self.pos_y = None

    def __repr__(self) -> str:
        return self.symbol

      
class Rook(Piece):
    def __init__(self, side: bool):
        super().__init__(side, "♜♖"[int(side)])

class King(Piece):
    def __init__(self, side: bool):
        super().__init__(side, "♚♔"[int(side)])

class Bisshop(Piece):
    def __init__(self, side: bool):
        super().__init__(side, "♝♗"[int(side)])



class Board:
    def __init__(self, row_count: int = 8, col_count: int = 8):
        self.rows = [[None] * col_count for _ in range(row_count)]
        self.pieces = [{  # BLACK pieces by type
            King: [],
            Rook: [],
            Bisshop: []
        }, {  # WHITE pieces by type
            King: [],
            Rook: [],
            Bisshop: []
        }]

    def add(self, piece: Piece, pos_x: int, pos_y: int):
        piece.set_position(pos_x, pos_y)
        self.rows[pos_y][pos_x] = piece
        self.pieces[piece.side][type(piece)].append(piece)

    def remove(self, piece: Piece):
        self.rows[piece.pos_y][piece.pos_x] = None
        piece.clear_position()
        self.pieces[piece.side][type(piece)].remove(piece)

    def move(self, piece: Piece, to_x: int, to_y: int):
        self.remove(piece)
        self.add(piece, to_x, to_y) 

    def __repr__(self):
        return "\n".join(
            "".join(repr(piece) if piece else "." for piece in row)
                for row in self.rows
        )


board = Board(5, 5)
# coordinates are zero-index based:
board.add(Rook(WHITE), 0, 0)
board.add(King(WHITE), 2, 0)
board.add(Rook(BLACK), 1, 1)
board.add(Rook(BLACK), 4, 1)
board.add(King(BLACK), 1, 2)
board.add(Rook(BLACK), 3, 2)
board.add(Rook(WHITE), 0, 3)
board.add(Bisshop(WHITE), 4, 3)
board.add(Bisshop(WHITE), 0, 4)
print(board)

And if you wanted to move a piece that's already on the board, you could do:

board.move(board.pieces[WHITE][Bisshop][1], 1, 4)

This will move the second white bisshop.

  • Related