kivy:在remove_widget之后,它会从屏幕上消失,但会保留在ID

时间:2017-04-30 08:35:50

标签: python python-2.7 kivy kivy-language

我正在制作一个arkanoid游戏并遇到问题:碰撞后我使用remove_widget方法从布局中删除小部件。所以它从屏幕上消失但它仍在那里,ids可以使用它,如果球再次进入该点,它仍会与小部件发生碰撞。

以下是一些代码:

gemsgrid.kv

<Brick@Widget>:
    canvas:
        Rectangle:
            size: self.size
            pos: self.pos

<GemsGrid@FloatLayout>:
    size_hint: None, None
    Brick:
        pos: 300, 100
        id: 1
    Brick:
        pos: 300,200
        id: 2

main.py

from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import NumericProperty


Builder.load_file('paddle.kv')
Builder.load_file('ball.kv')
Builder.load_file('gemsgrid.kv')


class Game(RelativeLayout):
    lives = NumericProperty(5)

    def __init__(self, **kwargs):
        super(Game, self).__init__(**kwargs)
        self.game_started = False

    def on_touch_move(self, touch):
        if touch.y < self.height / 3:
            self.ids.paddle_widget.center_x = touch.x
            if not self.game_started:
                self.ids.ball_widget.serve_ball()
                self.game_started = True

    def update(self, dt):
        if self.game_started:
            self.ids.ball_widget.move()
            self.ids.paddle_widget.bounce_ball(self.ids.ball_widget)
            for id, gem in self.gemsgrid.ids.iteritems():
                if self.ids.ball_widget.collide_widget(gem):
                    self.gemsgrid.remove_widget(gem)
                    self.right_left_collissioned(self.ids.ball_widget, gem)
                    self.top_bottom_collissioned(self.ids.ball_widget, gem)

        # bounce off top and bottom
        if (self.ids.ball_widget.top > self.height):
            self.ids.ball_widget.velocity_y *= -1

        # bounce off left and right
        if (self.ids.ball_widget.x < 0) or (self.ids.ball_widget.right > self.width):
            self.ids.ball_widget.velocity_x *= -1

        # subtract one life if hit the bottom but not the paddle
        if (self.ids.ball_widget.y < self.y):
            self.lives -= 1
            self.ids.ball_widget.reset()
            self.game_started = False

    def right_left_collissioned(self, ball, gem):
        if ball.y > gem.y and ball.y < (gem.y + gem.height):
            ball.velocity_x *= -1

    def top_bottom_collissioned(self, ball, gem):
            if ball.x > gem.x and ball.x < gem.x + gem.width:
                ball.velocity_y *= -1


class MainApp(App):
    def on_pause(self):
        return True

    def build(self):
        game = Game()
        Clock.schedule_interval(game.update, 1/60)
        return game


if __name__ == '__main__':
    MainApp().run()

我错过了什么?

2 个答案:

答案 0 :(得分:1)

ids dict是静态的,并不打算像这样更新(虽然我不明白为什么如果人们真的想要这个功能就无法改变它)。听起来它不适合你的问题,我会手动管理对象引用。

答案 1 :(得分:1)

解析ids时会生成.kv。 所以它会保持这种状态。

使用self.children来检查它是否仍然存在。