Gabriele Monti
Gabriele Monti

Reputation: 31

Print out chess board from list of objects

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)

Upvotes: 1

Views: 1964

Answers (4)

Mohammed Abuhallala
Mohammed Abuhallala

Reputation: 1

class Piece: def init(self, color, symbol): self.color = color # 'white' أو 'black' self.symbol = symbol

def __repr__(self):
    return self.symbol

class Pawn(Piece): def init(self, color): super().init(color, '♙' if color == 'white' else '♟') self.first_move = True

class Rook(Piece): def init(self, color): super().init(color, '♖' if color == 'white' else '♜')

class Knight(Piece): def init(self, color): super().init(color, '♘' if color == 'white' else '♞')

class Bishop(Piece): def init(self, color): super().init(color, '♗' if color == 'white' else '♝')

class Queen(Piece): def init(self, color): super().init(color, '♕' if color == 'white' else '♛')

class King(Piece): def init(self, color): super().init(color, '♔' if color == 'white' else '♚')

class ChessBoard: def init(self): self.board = [[None for _ in range(8)] for _ in range(8)] self.current_player = 'white' self.setup_board()

def setup_board(self):
    # ترتيب القطع السوداء
    self.board[0] = [
        Rook('black'), Knight('black'), Bishop('black'), Queen('black'),
        King('black'), Bishop('black'), Knight('black'), Rook('black')
    ]
    self.board[1] = [Pawn('black') for _ in range(8)]
    
    # ترتيب القطع البيضاء
    self.board[7] = [
        Rook('white'), Knight('white'), Bishop('white'), Queen('white'),
        King('white'), Bishop('white'), Knight('white'), Rook('white')
    ]
    self.board[6] = [Pawn('white') for _ in range(8)]

def print_board(self):
    print('  a b c d e f g h')
    for i, row in enumerate(self.board):
        print(8 - i, end=' ')
        for piece in row:
            print(piece.symbol if piece else '·', end=' ')
        print(8 - i)
    print('  a b c d e f g h')

def move_piece(self, start, end):
    start_col, start_row = ord(start[0]) - ord('a'), 8 - int(start[1])
    end_col, end_row = ord(end[0]) - ord('a'), 8 - int(end[1])
    
    piece = self.board[start_row][start_col]
    if not piece or piece.color != self.current_player:
        print("حركة غير صالحة: القطعة ليست لك")
        return False
    
    target = self.board[end_row][end_col]
    if target and target.color == self.current_player:
        print("حركة غير صالحة: لا يمكن أكل قطعك الخاصة")
        return False
    
    # تنفيذ الحركة (بدون تحقق كامل من القواعد)
    self.board[end_row][end_col] = piece
    self.board[start_row][start_col] = None
    
    self.current_player = 'black' if self.current_player == 'white' else 'white'
    return True

def main(): game = ChessBoard() while True: game.print_board() move = input(f"لاعب {game.current_player} أدخل الحركة (مثال: e2e4): ") if move.lower() == 'exit': break

    if len(move) != 4 or not move[:2].isalpha() or not move[2:].isdigit():
        print("صيغة غير صحيحة! استخدم الصيغة مثل e2e4")
        continue
        
    start = move[:2].lower()
    end = move[2:].lower()
    
    if game.move_piece(start, end):
        print("حركة ناجحة!")
    else:
        print("حركة فاشلة، حاول مرة أخرى")

if name == "main": main()

Upvotes: 0

trincot
trincot

Reputation: 350270

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.

Upvotes: 1

CrazyPhil
CrazyPhil

Reputation: 73

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.

Upvotes: 1

Olav Aga
Olav Aga

Reputation: 143

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.

Upvotes: 0

Related Questions