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}
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:
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:
Con estos cambios, deberías poder aumentar la puntuación cada vez que presiones sobre el balón de fútbol.