【问题标题】:kivy AttributeError while trying to add score in game尝试在游戏中添加分数时出现kivy AttributeError
【发布时间】:2021-12-04 00:12:41
【问题描述】:

我正在用 kivy 制作游戏,我想添加一个分数,所以每次我按下足球时,我都希望分数增加 1。我收到错误“self.root.ids. game_screen.ids.score.text = str(int(self.root.ids.game_screen.score.text) + 1) AttributeError: 'Ball' object has no attribute 'root' " 下面是我的代码!

main.py

    class Ball(Image):
    velocity = NumericProperty(0)


    def on_touch_down(self, touch):
        if Vector(self.center).distance(touch.pos) <= 33:
            self.root.ids.game_screen.ids.score.text = 
    str(int(self.root.ids.game_screen.ids.score.text) + 1)
        sound = SoundLoader.load('Soccer ball sound.wav')
        sound.play()
        self.source = "icons/ball.png"
        self.velocity = 275
    return super().on_touch_down(touch)


    def on_touch_up(self, touch):
        if Vector(self.center).distance(touch.pos) <= 33:
            self.source = "icons/ball.png"
    return super().on_touch_up(touch)


    class MainApp(App):
        GRAVITY = 300


    def move_ball(self, time_passed):
        ball = self.root.ids.game_screen.ids.ball
        ball.y = ball.y + ball.velocity * time_passed
        ball.velocity = ball.velocity - self.GRAVITY * time_passed


    def start_game(self):
        Clock.schedule_interval(self.move_ball, 1/60.)




    




    MainApp().run()

gamescreen.kv

    Label:
        id: score
        size_hint: None, None
        font_size: dp(25)
        font_name: 'SackersGothicStd-Medium.otf'
        text: "0"
        color: "gold"
        pos_hint: { "center_x": 0.1, "center_y": 0.9}

    

【问题讨论】:

  • @JohnAnderson 我编辑了代码并使其更短!我想要做的是“on_touch_down”我希望分数增加1。

标签: python kivy kivy-language


【解决方案1】:

你的代码缩进很乱,所以我不得不猜测一些东西,请清理你的代码以获得更好的答案。

无论如何,您似乎是在小部件类中的 python 代码中引用root。您只能从 App 子类中引用 self.root。为了在rootapp之类的python代码中引用特殊的kv lang变量,您必须在两种语言中执行self.get_root_window()self.parentApp.get_running_app()selfself。如果您指的是存储在小部件中的 id,只需执行 self.ids

此外,覆盖on_touch_down 是针对特殊情况,例如在满足特定条件时不调度触摸事件。为了获得您想要实现的按钮行为,请执行from kivy.uix.behaviors import ButtonBehavior 并让您的球类继承自它。这允许您为您的小部件使用on_presson_release 事件,因此您不必覆盖on_touch_down

kivy 行为文档链接:kivy behaviors doc

【讨论】:

    猜你喜欢
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多