0

我正在使用 Python 和 Kivy(也借助 The Python Book 的“帮助”)创建一个 Breakout 游戏。

流程是:构建游戏(创建并放置小部件),时钟启动并定期运行更新以更新玩家和球的位置。

当球与桨碰撞时,它起作用了!它按预期反弹并改变速度。然而,当球接近积木时,它直接穿过积木,甚至没有意识到那里有小部件!谁能看到我错过的明显东西?

我附上了一些代码:

class Ball(Widget):
    def update(self,dt):
        #code not included which updates velocity ( works )
        self.bounce_from_player(self.parent.player) #this works

    def bounce_from_player( self,player ):
        if self.collide_widget(player):
        #code not included which update velocity ( works )
            self.parent.destroy_blocks(self) #this doesn't work (below)


class Game(FloatLayout):
    blocks=ListProperty([])
    player=ObjectProperty([])
    ball=ObjectProperty([])

    def setup_blocks( self ):
        self.blocks=[]
        for y_jump in range(5):
            for x_jump in range(10):
                block=Block(pos_hint={'x':0.05+0.09*x_jump,'y':0.55+0.09*y_jump})
                block.colour=random.choice([(0.78,0.28,0),(0.28,0.63,0.28),(0.25,0.28,0.78)])
                self.add_widget(block)
                self.blocks.append(block)

    def update( self,d t):
        self.ball.update(dt) 
        self.player.update(dt) #code not included - this works

    def start( self,*args ):
        Clock.schedule_interval(self.update,1./60.)

    def destroy_blocks( self,ball ): #doesn't work
        for block in enumerate(self.blocks):
            if ball.collide_widget(block):
                y_overlap=(ball.top - block.y if ball.velocity[1]>0 else block.top - ball.y)/block.size_hint_y
                x_overlap=(ball.right - block.x if ball.velocity[0]>0 else block.right - ball.x)/block.size_hint_x
                if x_overlap<y_overlap:
                    ball.velocity[0]*=-1
                else:
                    ball.velocity[1]*=-1
                    self.remove_widget(block)
                if len(self.blocks)==0:
                    self.win()
                return #remove 1 block per frame
4

0 回答 0