from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Color, Ellipse from kivy.core.window import Window from kivy.clock import Clock # ウィンドウサイズ Window.size = (400, 400) class Ball: def __init__(self, canvas, x, y, radius, dx, dy, color=(1, 0, 0)): self.x = x self.y = y self.radius = radius self.dx = dx self.dy = dy self.color = color with canvas: Color(*self.color) self.ellipse = Ellipse(pos=(self.x - self.radius, self.y - self.radius), size=(2 * self.radius, 2 * self.radius)) def update(self): # 移動 self.x += self.dx self.y += self.dy # 壁との反射 if self.x - self.radius <= 0 or self.x + self.radius >= Window.width: self.dx *= -1 if self.y - self.radius <= 0 or self.y + self.radius >= Window.height: self.dy *= -1 # 描画更新 self.ellipse.pos = (self.x - self.radius, self.y - self.radius) class BouncingBallApp(Widget): def __init__(self, **kwargs): super().__init__(**kwargs) # ボール生成 self.ball = Ball(self.canvas, x=200, y=50, radius=10, dx=2, dy=2) Clock.schedule_interval(self.update, 1/60) # 60FPS更新 def update(self, dt): self.ball.update() class MyApp(App): def build(self): return BouncingBallApp() if __name__ == "__main__": MyApp().run()