I want to create a child class Cell with parent Class pygame.Rect but I cannot get the attribute top of the instance of the class Cell to change and it's just set to zero. My Code is:
import pygame
light = pygame.Color('#D3D3D3')
dark = pygame.Color('#222222')
class Cell(pygame.Rect):
def __init__(self, index, side):
self.index = index
self.side = side
self.color = None # Index is a tuple from (0, 0) to (2, 2)
self.has_pawn = None
# Setting coordinates
for i in range(3):
if index[1] == i:
self.x = i*self.side
if index[0] == i:
self.y == (2-i)*self.side
self.left = self.x
self.top = self.y
self.width = self.side
self.height = self.side
# self.rect = pygame.Rect(x, y, width, height)
# Setting color
sum = self.index[0] + self.index[1]
if sum % 2 == 0:
self.color = light
if sum % 2 == 1:
self.color = dark
# Setting has_pawn
if index[0] == 0 | index[1] == 2:
self.has_pawn = True
b2 = Cell((1, 1), 5)
print(b2)
which gives the output:
pygame 2.0.1 (SDL 2.0.14, Python 3.9.1)
Hello from the pygame community. https://www.pygame.org/contribute.html
<rect(5, 0, 5, 5)>
[Finished in 0.6s]
I hope someone can help me to get the attribute top of the Cell object to change.
I don't see what the problem here is. Your self.top
is 0, that is why y
in self.rect
value is 0 as well. In following loop,
# Setting coordinates
for i in range(3):
if index[1] == i:
self.x = i*self.side
if index[0] == i:
self.y == (2-i)*self.side
The value of i
in the last iteration is 2
, which means in the last iteration this happens.
self.y == (2-2)*5 # 0*5 = 0
This results in self.y
being set to 0, which in turn sets self.top
to 0. So, it's not a surprise that you get the result you are getting.
If you do
super().__init__(pygame.Rect(10, 10, 10, 10))
The result printed is in fact <rect(10, 10, 10, 10)>
, so you should focus on fixing the loop instead.
You can simplify your code. You don't need the loop at all. Cell
is a subclass of pygame.Rect
. Compute the coordinate of the call:
x = index[1] * self.side
y = (index[0]-2) * self.side
Use super()
to delegate to the constructor of pygame.Rect
:
super().__init__(x, y, self.side, self.side)
However, I don't know where -2
comes from. You may want something like:
x = offsetx + index[1] * self.side
y = offsety + index[0] * self.side
Class Cell
:
class Cell(pygame.Rect):
def __init__(self, index, side):
self.index = index
self.side = side
self.color = None # Index is a tuple from (0, 0) to (2, 2)
self.has_pawn = None
x = index[1] * self.side
y = (index[0]-2) * self.side
super().__init__(x, y, self.side, self.side)
# Setting color
sum = self.index[0] + self.index[1]
if sum % 2 == 0:
self.color = light
if sum % 2 == 1:
self.color = dark
# Setting has_pawn
if index[0] == 0 | index[1] == 2:
self.has_pawn = True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.