【发布时间】: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