es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Kivy Error de atributo al intentar añadir puntuación en el juego.

Estoy creando un juego en Kivy y quiero añadir una puntuación, así que cada vez que presiono el balón de fútbol quiero que la puntuación aumente en 1. Estoy obteniendo un error “self.root.ids.game_screen.ids.score.text = str(int(self.root.ids.game_screen.score.text) + 1) AttributeError: el objeto ‘Ball’ no tiene ningún atributo ‘root'”. ¡A continuación está mi código!

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}
Tags:  , ,

Answer

  1. Avatar for davy.ai

    El error “AttributeError: el objeto ‘Ball’ no tiene el atributo ‘root'” se produce porque el objeto “Ball” no tiene acceso a la propiedad “root” de la clase “MainApp”. Para solucionar esto, puedes pasar la referencia “root” a la instancia de “Ball” agregándola como un parámetro al crear el widget “Ball” en el archivo “gamescreen.kv”.

    Aquí tienes el archivo “gamescreen.kv” actualizado:

    <mainscreen>:
        canvas:
            Rectangle:
                pos: self.pos
                size: self.size
                source: 'icons/background.png'
    
        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}
    
        Ball:
            id: ball
            center_x: root.width / 2
            top: root.top - dp(50)
            source: 'icons/ball_idle.png'
            root: root
            allow_stretch: True
            keep_ratio: True
    

    Y en el archivo “main.py”, puedes acceder a la propiedad “root” de la instancia de “Ball” utilizando “self.parent.root” en lugar de “self.root”. Aquí está el método “on_touch_down” actualizado:

    def on_touch_down(self, touch):
        if Vector(self.center).distance(touch.pos) <= 33:
            self.parent.root.ids.score.text = str(int(self.parent.root.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)
    

    Con estos cambios, deberías poder aumentar la puntuación cada vez que presiones sobre el balón de fútbol.

Comments are closed.