'Pygame object class comparision with a tuple
So i am trying to create a game in pygame. Everything is going well, but I have a problem where I am trying to set the winning condition. For this I made some for loops to go through the rows and columns and without too many details, the point is if the white piece is in the first or the 5th row, the game is won.
def winner(self):
for row in range(ROWS):
for col in range(COLS):
piece = self.get_piece(row, col)
if piece == WHITE:
print("hello")
if row == 0:
return YELLOW
if row == 4:
return BLUE
Both WHITE and piece return (250, 250, 250), but WHITE is a tuple, and piece is a '<class 'mygame.piece.Piece'>' class object, so I guess they are not comparable. I changed my code in the 5th row like this:
if piece == Piece(row, col, WHITE):
This returns a '<class 'mygame.piece.Piece'>' object as well, but for some reason it still doesn't print hello, meaning it doesn't compare the two object. My question would be how can I compare two pygame objects? Or can I convert a pygame object to a tuple? I have the same problem with another function. I haven't found anything on this.
Solution 1:[1]
Piece(row, col, WHITE) creates an new object, so Piece(row, col, WHITE) is not equal to piece. Objects are not compared attribute-wise unless you implement the comparison method (__eq__).
You need to compare the object's color attribute to WHITE:
if piece and piece.color == WHITE:
If the object doesn't have an attribute color, then add one.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
