Kivy 乒乓游戏教程 基于Minconda或Anconda 运行
文章目录
- Kivy 乒乓游戏教程 基于Minconda或Anconda 运行
- 为什么写这篇笔记
- 扩展阅读
- 笔者环境
- 安装`Kivy`
- 参考
- 运行演示
- 乒乓球游戏教程
- main.py
- pong.kv
Kivy 乒乓游戏教程 基于Minconda或Anconda 运行
为什么写这篇笔记
Python部署Android软件apk或者aak早有耳闻,而Kivy就是其中最臭名昭著的(开玩笑),所以有了这篇用于展示 乒乓游戏教程 的文章
不过这篇文章 不会讲解具体的代码 逻辑以及意义,只是单纯的测试与演示 ,有望在其他文章中编写
扩展阅读
Kivy应用程序
笔者环境
- 系统环境: Fedora Linux 42 (Workstation Edition)
- Python环境: Python 3.13.X
- Conda/Minconda环境:conda 25.7.0
安装Kivy
因为笔者的环境是 Linux上的Minconda所以使用如下命令
conda install kivy -c conda-forge
参考
Anconda安装Kivy
其他各种平台安装
运行演示

乒乓球游戏教程
下面的俩个文件要在同一文件夹下
main.py
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 Clockclass PongPaddle(Widget):score = NumericProperty(0)def bounce_ball(self, ball):if self.collide_widget(ball):vx, vy = ball.velocityoffset = (ball.center_y - self.center_y) / (self.height / 2)bounced = Vector(-1 * vx, vy)vel = bounced * 1.1ball.velocity = vel.x, vel.y + offsetclass 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.posclass PongGame(Widget):ball = ObjectProperty(None)player1 = ObjectProperty(None)player2 = ObjectProperty(None)def serve_ball(self, vel=(4, 0)):self.ball.center = self.centerself.ball.velocity = veldef update(self, dt):self.ball.move()# bounce off paddlesself.player1.bounce_ball(self.ball)self.player2.bounce_ball(self.ball)# bounce ball off bottom or topif (self.ball.y < self.y) or (self.ball.top > self.top):self.ball.velocity_y *= -1# went off to a side to score point?if self.ball.x < self.x:self.player2.score += 1self.serve_ball(vel=(4, 0))if self.ball.right > self.width:self.player1.score += 1self.serve_ball(vel=(-4, 0))def on_touch_move(self, touch):if touch.x < self.width / 3:self.player1.center_y = touch.yif touch.x > self.width - self.width / 3:self.player2.center_y = touch.yclass PongApp(App):def build(self):game = PongGame()game.serve_ball()Clock.schedule_interval(game.update, 1.0 / 60.0)return gameif __name__ == '__main__':PongApp().run()
pong.kv
#:kivy 1.0.9<PongBall>:size: 50, 50 canvas:Ellipse:pos: self.possize: self.size <PongPaddle>:size: 25, 200canvas:Rectangle:pos: self.possize: self.size<PongGame>:ball: pong_ballplayer1: player_leftplayer2: player_rightcanvas:Rectangle:pos: self.center_x - 5, 0size: 10, self.heightLabel:font_size: 70 center_x: root.width / 4top: root.top - 50text: str(root.player1.score)Label:font_size: 70 center_x: root.width * 3 / 4top: root.top - 50text: str(root.player2.score)PongBall:id: pong_ballcenter: self.parent.centerPongPaddle:id: player_leftx: root.xcenter_y: root.center_yPongPaddle:id: player_rightx: root.width - self.widthcenter_y: root.center_y
