簡體   English   中英

未調用 BlockLogic 超類中的命中 Object

[英]The Hit Object Within the BlockLogic Superclass is Not Being Called

當我按下小寫的 L 鍵時,我想要調用 hit object,每次將方塊的長度和寬度減少 5。 似乎 BlockNorm 中的代碼沒有正確引用 BlockLogic 中的命中 object。 按下 l 時沒有效果,但也沒有錯誤。

我嘗試放置 print('test'),但沒有打印任何內容。 如果我將 self.blen -=5 和 self.bwid -= 5 粘貼到 BlockNorm 的 def init中,它就會起作用。 這就是為什么我懷疑它沒有連接到超類的命中。


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()

據我所知,類BlockNormBlockLogic已正確連接,但未調用hit方法。

將 class 定義( BlockLogicBlockNorm )放在運行循環之外,然后您可以創建實例並使用它們的方法。 未執行print('test')調用,因為從未調用方法hit 它在BlockNorm.__init__中“有效”,因為當您使用BlockNorm(200, 200)BlockNorm(500, 250)創建實例時會自動調用該方法。

這是代碼的示例:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM