在游戏中将按钮放置在哪里的代码

时间:2018-09-28 10:08:27

标签: python button kivy

你好,我的问题是我不知道如何在游戏屏幕上不放置按钮。 每当我尝试在代码中添加 return btn1 时,它只会显示按钮。但不是游戏。我确定这是一个初学者的问题,但对我来说查找无效。

顺便说一句,这是我私人使用的教程中的代码

我的代码是:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
import kivy.uix.button
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.button import Button

def callback(instance):
 print('The button <%s> is being pressed' % instance.text)

btn1 = Button(text='Hello world 1')
btn1.bind(on_press=callback)
btn2 = Button(text='Hello world 2')
btn2.bind(on_press=callback)




class PongPaddle(Widget):

 score = NumericProperty(0)

def bounce_ball(self, ball):
    if self.collide_widget(ball):
        vx, vy = ball.velocity
        offset = (ball.center_y - self.center_y) / (self.height / 2)
        bounced = Vector(-1 * vx, vy)
        vel = bounced * 1.1
        ball.velocity = vel.x, vel.y + offset


class PongBall(Widget):
 velocity_x = NumericProperty(0)
 velocity_y = NumericProperty(0)
 velocity = ReferenceListProperty(velocity_x, velocity_y)

 def move(self):
    self.pos = Vector(*self.velocity) + self.pos


 class PongGame(Widget):

 ball = ObjectProperty(None)
 player1 = ObjectProperty(None)
 player2 = ObjectProperty(None)


 def serve_ball(self, vel=(4, 0)):
    self.ball.center = self.center
    self.ball.velocity = vel


def update(self, dt):
    self.ball.move()

    # bounce of paddles
    self.player1.bounce_ball(self.ball)
    self.player2.bounce_ball(self.ball)

    # bounce ball off bottom or top
    if (self.ball.y < self.y) or (self.ball.top > self.top):
        self.ball.velocity_y *= -1

    # went of to a side to score point?
    if self.ball.x < self.x:
        self.player2.score += 1
        self.serve_ball(vel=(4, 0))
    if self.ball.x > self.width:
        self.player1.score += 1
        self.serve_ball(vel=(-4, 0))

def on_touch_move(self, touch):
    if touch.x < self.width / 3:
        self.player1.center_y = touch.y
    if touch.x > self.width - self.width / 3:
        self.player2.center_y = touch.y 


class PongApp(App):
 def build(self):
    game = PongGame()
    game.serve_ball()
    Clock.schedule_interval(game.update, 1.0 / 60.0)





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

1 个答案:

答案 0 :(得分:1)

如果您希望一个窗口小部件成为另一个窗口小部件的一部分,则该窗口小部件必须是另一个窗口小部件的儿子,或者其祖先是该窗口小部件的儿子,并且当您在build()中返回btn1时,表示它是根,即窗口,不显示游戏,它使小部件的儿子可以选择使用add_widget()

class PongApp(App):
    def build(self):
        game = PongGame()
        game.add_widget(btn1) # <--
        btn2.pos = 100, 100
        game.add_widget(btn2) # <--
        game.serve_ball()
        Clock.schedule_interval(game.update, 1.0 / 60.0)
        return game