When I press the lowercase L key, I want the hit object to be called, reducing the length and width of the squares by 5 each time. It seems that the code within BlockNorm is not referencing the hit object within BlockLogic properly. There is no effect when l is pressed, but no errors either.
I attempted placing print(‘test’), and nothing was printed. If I paste self.blen -=5 and self.bwid -= 5 inside BlockNorm’s def init, it has effect. That is why I suspect it is not being connected to the superclass’s hit.
win = pygame.display.set_mode((800, 500))
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
class BlockLogic:
def __init__(self, blen, bwid, posx, posy):
self.blen = blen # the block’s length, width, & position
self.bwid = bwid
self.posx = posx
self.posy = posy
def hit(self):
self.blen -= 5 # should reduce length and width by 5 each time l is pressed
self.bwid -= 5
if self.blen < 1:
insertscorestuff = 'hi'
else:
placeholder = 'here'
class BlockNorm(BlockLogic):
def __init__(self, posx=None, posy=None):
super().__init__(20, 20, posx, posy) # features for the normal block type
pygame.draw.rect(win, (250, 0, 0), (self.posx, self.posy, self.blen, self.bwid))
def hit(self):
if keys[pygame.K_l]: # testing the hit, change later
print('test') # test does not print
super().hit()
win.fill((0, 0, 0))
BlockNorm(200, 200)
BlockNorm(500, 250)
pygame.display.update()
CodePudding user response:
As far as I can tell, the classes BlockNorm and BlockLogic are properly connected but the hit method is not called.
Put the class definitions (BlockLogic and BlockNorm) outside the run loop, then you can create instances and use their methods. The print('test') call is not executed because the method hit is never called. It "works" inside BlockNorm.__init__ because that method is automatically called when you create the instances with BlockNorm(200, 200) and BlockNorm(500, 250).
Here is an example how the code could look like:
class BlockLogic:
def __init__(self, ...):
...
def hit(self):
...
class BlockNorm(BlockLogic):
def __init__(self, ...):
...
def draw(self, win):
pygame.draw.rect(win, (250, 0, 0), (self.posx, self.posy, self.blen, self.bwid))
# ...
block_norm1 = BlockNorm(200, 200)
block_norm2 = BlockNorm(500, 250)
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
win.fill((0, 0, 0))
if keys[pygame.K_l]:
block_norm1.hit()
block_norm2.hit()
block_norm1.draw(win)
block_norm2.draw(win)
pygame.display.update()
