0

For an assignement for school I need to make a chess game in python. But I'm stuck at a little obstacle.

I want the user to make a chess-piece like this:

p=Pawn(White)

And I want a print to work like this:

print(p)  ##Output: White pawn

And in order to get this done I need to use class inheritance, but it doesn't work for me. Here is what I have currently:

WHITE=1
BLACK=2

class ChessPiece:

     def __init__(self,color):
         self.color=color

     def __str__(self):
         if self.color==1:
             print('Witte',self.name)
         else:
             print("Zwart ",self.name)

class Pawn(ChessPiece):
    def __init__(self):
         self.naam='pawn'
         self.kleur=kleur
5
  • Is the name self.naam or self.name. You must choose and use the same everywhere. Commented Nov 6, 2016 at 11:51
  • Shouldn't the variables be called the same? I mean, name and color on both classes, not naam and kleur. Commented Nov 6, 2016 at 11:51
  • As a sidenote, a common trick with inheritance is to use self.__class__.__name__. That gives you the name of the class, here that would be Pawn. Commented Nov 6, 2016 at 11:52
  • 2
    "it doesn't work" isn't a useful problem description; give a minimal reproducible example. Commented Nov 6, 2016 at 11:59
  • Since you have only two colours in chess, a somewhat better choice than 1,2 would be 0,1 or True,False. Commented Nov 6, 2016 at 18:30

1 Answer 1

1

This is modified version of your code:

WHITE=1
BLACK=2

class ChessPiece:

     def __init__(self,color):
         self.color=color

     def __str__(self):
         if self.color==1:
             return "White {}".format(self.__class__.__name__)
         else:
             return "Black {}".format(self.__class__.__name__)

class Pawn(ChessPiece):
    def __init__(self, color):
         ChessPiece.__init__(self,color)
         self.naam = 'pawn'
         self.kleur = 'kleur'


p = Pawn(WHITE)
print(p) 

Some points was neglected in your code that is __str__ should return a string and not to print it and you should call base class __init__ in successor

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.