0

Im creating a mini chess game, and for good practice, rather than do it procedurally, I wanted to do it in oop (python because Im lazy with syntax). I managed to created a class for the game board, as well as classes for pawns. The game board class has a method called create_board:

def create_board(self, empty_cell, player_pawn, computer_pawn):        
    for row in range(self.size):
        if row == 0:
            self.board.append([computer_pawn] * self.size)
        if row == self.size - 1:
            self.board.append([player_pawn] * self.size)
        if row != 0 and row != self.size - 1:
            self.board.append([empty_cell] * self.size)
    return board

where computer_pawn, player_pawn and empty_cell are their own individual classes (right now they all look the same):

class player_pawn:

      #player_pawn constructor
      def __init__(self, value):
            self.value = value

The issue is my print method in the game_board class:

  def print_board(self):

        self.board_string = ""
        for row in range(self.size):
              for col in range(self.size):
                    self.board_string += str(self.board[row][col]) + "  "
              self.board_string += "\n"
        print self.board_string

instead of outputting a string of numbers in a square:

   "2  2  2
    0  0  0
    1  1  1"

it outputs:

<main.computer_pawn instance at 0x107742cb0> <main.computer_pawn instance at 0x107742cb0> <main.computer_pawn instance at 0x107742cb0>
<main.empty_cell instance at 0x107742c20> <main.empty_cell instance at 0x107742c20> <main.empty_cell instance at 0x107742c20>
<main.player_pawn instance at 0x107742c68> <main.player_pawn instance at 0x107742c68> <main.player_pawn instance at 0x107742c68>

for reference, my current method calls and object creation looks like this:

board = game_board(3)
board.create_board(empty_cell(0), player_pawn(1), computer_pawn(2))
board.print_board()

Im trying to make it output the string style, so does anyone have any suggestions?

user11717481
  • 1
  • 9
  • 15
  • 25
  • 1
    define `__str__(self)` method for all the mentioned classes that returns the representation you want. – matszwecja Sep 16 '22 at 13:18
  • Use `self.board[row][col].value` – Peter Wood Sep 16 '22 at 13:20
  • 1
    `print self.board_string`: don't use Python 2. Use a recent Python 3 to (learn to) code in, otherwise you'll run into issues in the (near) future. – 9769953 Sep 16 '22 at 13:27
  • Welcome to Stack Overflow. Please read [ask] and try to ask the question that you actually have. Clearly, the list contains the objects; they just don't look right when printing. So the title is wrong. – Karl Knechtel Sep 17 '22 at 15:17

0 Answers0