Kivy サブ画面でボールを動かす(Python Kivyの取説・使い方 第6回)
サブ画面でボールを動かす方法
第5回の続きです。ボールが動くようになりました。
KivyのチュートリアルにあるPong Gameを参考にしていきます。チュートリアルの「ボールのアニメーションを追加する」からです。
プログラムのコード
# フル画面を解除して画面の幅と高さを設定 from kivy.config import Config Config.set('graphics', 'fullscreen', 0) Config.set('graphics', 'width', 320) Config.set('graphics', 'height', 568) Config.set('graphics', 'resizable', 0) from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.vector import Vector from kivy.clock import Clock from random import randint 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(BoxLayout): ball = ObjectProperty(None) def serve_ball(self): self.ball.center = self.center self.ball.velocity = Vector(4, 0).rotate(randint(0, 360)) def update(self, dt): self.ball.move() # bounce off top and bottom if (self.ball.y < self.screen.y) or (self.ball.top > self.screen.top): self.ball.velocity_y *= -1 # bounce off left and right if (self.ball.x < 0) or (self.ball.right > self.width): self.ball.velocity_x *= -1 class PongApp(App): def build(self): self.title = 'テスト' game = PongGame() game.serve_ball() Clock.schedule_interval(game.update, 1.0 / 60.0) return game if __name__ == '__main__': PongApp().run()
kvファイル(pong.kv)
<PongGame>: screen: main_screen ball: pong_ball BoxLayout: orientation: "vertical" BoxLayout: Button: size_hint_x: 0.2 text: "1" Label: size_hint_x: 0.6 text: "today" Button: size_hint_x: 0.2 text: "2" Widget: id: main_screen size_hint_y: 10 canvas: Rectangle: pos: self.center_x - 5, self.y size: 10, self.height Label: font_size: 70 center_x: root.width / 4 top: root.top - 50 text: "0" Label: font_size: 70 center_x: root.width * 3 / 4 top: root.top - 50 text: "0" PongBall: id: pong_ball center: self.parent.center BoxLayout: Button: text: "3" Button: text: "4" Button: text: "5" <PongBall>: size: 50, 50 canvas: Ellipse: pos: self.pos size: self.size
実行してみます。
見事にサブ画面の中でボールが動きました!
解説
メインプログラムはほとんどチュートリアルのままです。
if (self.ball.y < self.screen.y) or (self.ball.top > self.screen.top):
この一行だけ「0」を「self.screen.y」に、「self.height」を「self.screen.top」に変えています。
kvファイルを少し編集しました。前回作った<CustomLayout>:の部分はなかったことにして、<PongGame>:で一つにまとめました。
サブ画面を子の「Widget:」で定義して、2行目の「screen: main_screen」で「id: main_screen」を「screen」に設定してメインプログラムの方に「self.screen.top」などで呼び出せるようにしています。(説明が下手でごめんなさい)
あとはチュートリアル通りにやればPong Gameをサブ画面で動かせると思いますので、次回はボタンを押してボールのスピードを変えたいと思います。
保存ファイル
lesson58.py
pong.kv
文責:Luke