小球碰壁反弹python tkinter
时间: 2023-11-01 21:07:26 浏览: 176
小球碰撞反弹
5星 · 资源好评率100%
小球碰壁反弹是一款基于Python tkinter模块的小游戏,通过绘制一个小球和一个矩形框,让小球在框内自由运动,并且碰到框的边缘时会反弹。实现的主要思路是通过定时器不断更新小球的位置,并且判断小球是否碰到了框的边缘,如果碰到了就改变小球的运动方向。下面是一个简单的实现代码:
```
import tkinter as tk
class Ball:
def __init__(self, canvas, color, size):
self.canvas = canvas
self.id = canvas.create_oval(10, 10, size, size, fill=color)
self.canvas.move(self.id, 245, 100)
self.xspeed = 3
self.yspeed = -3
self.canvas_width = self.canvas.winfo_width()
self.canvas_height = self.canvas.winfo_height()
def draw(self):
self.canvas.move(self.id, self.xspeed, self.yspeed)
pos = self.canvas.coords(self.id)
if pos[1] <= 0:
self.yspeed = 3
if pos[3] >= self.canvas_height:
self.yspeed = -3
if pos[0] <= 0:
self.xspeed = 3
if pos[2] >= self.canvas_width:
self.xspeed = -3
def main():
tkobj = tk.Tk()
tkobj.title("Ball Game")
canvas = tk.Canvas(tkobj, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
ball = Ball(canvas, 'red', 50)
while True:
ball.draw()
tkobj.update_idletasks()
tkobj.update()
tkobj.after(10)
if __name__ == '__main__':
main()
```
阅读全文