一切结束,也是伊始
你们好啊,早上好~
import tkinter as tk
import random
import time
class BounceBallApp:
def __init__(self, master):
self.master = master
self.master.title("Bouncing Ball Simulator")
self.master.geometry("800x600")
self.master.configure(bg="#2E3440")
# 物理参数
self.gravity = 980 # 像素/秒²
self.damping = 0.8
self.ball_radius = 20
# 初始化画布
self.canvas = tk.Canvas(self.master, bg="#2E3440", highlightthickness=0)
self.canvas.pack(fill=tk.BOTH, expand=True)
# 弹球初始化
self.ball = self.create_ball()
self.velocity = [random.uniform(-400, 400), random.uniform(-600, -300)]
self.trail_points = []
# 拖拽状态变量
self.dragging = False
self.drag_start_pos = (0, 0)
self.drag_start_time = 0
# 事件绑定
self.canvas.bind("<Button-1>", self.start_drag)
self.canvas.bind("<B1-Motion>", self.drag_ball)
self.canvas.bind("<ButtonRelease-1>", self.release_ball)
# 启动动画循环
self.last_time = time.time()
self.animate()
def create_ball(self):
"""创建弹球图形(带异常保护)"""
try:
x0 = 400 - self.ball_radius
y0 = 300 - self.ball_radius
x1 = 400 + self.ball_radius
y1 = 300 + self.ball_radius
return self.canvas.create_oval(x0, y0, x1, y1,
fill="#88C0D0",
outline="#E5E9F0",
width=2)
except Exception as e:
print(f"创建弹球时出错: {e}")
return None
def start_drag(self, event):
"""安全的拖拽开始处理"""
try:
self.dragging = True
self.drag_start_pos = (event.x, event.y)
self.drag_start_time = time.time()
self.velocity = [0.0, 0.0]
self.trail_points.clear()
except AttributeError:
pass
def drag_ball(self, event):
"""带校验的拖拽处理"""
if not self.dragging or not self.ball:
return
try:
# 限制坐标在画布范围内
canvas_width = self.canvas.winfo_width()
canvas_height = self.canvas.winfo_height()
x = max(self.ball_radius, min(event.x, canvas_width - self.ball_radius))
y = max(self.ball_radius, min(event.y, canvas_height - self.ball_radius))
self.canvas.coords(self.ball,
x - self.ball_radius,
y - self.ball_radius,
x + self.ball_radius,
y + self.ball_radius)
# 安全计算速度
dt = max(0.01, time.time() - self.drag_start_time)
dx = (x - self.drag_start_pos[0]) / dt
dy = (y - self.drag_start_pos[1]) / dt
self.velocity = [dx * 0.3, dy * 0.3]
except Exception as e:
print(f"拖拽过程中出错: {e}")
def release_ball(self, event):
"""带异常处理的释放操作"""
try:
if self.dragging and self.ball:
self.dragging = False
dt = max(0.01, time.time() - self.drag_start_time)
# 获取有效坐标
coords = self.canvas.coords(self.ball)
if not coords or len(coords) < 4:
return
current_x = coords[0] + self.ball_radius
current_y = coords[1] + self.ball_radius
# 计算安全速度
dx = (event.x - current_x) / dt
dy = (event.y - current_y) / dt
self.velocity = [
max(-2000, min(2000, dx * 0.5)),
max(-2000, min(2000, dy * 0.5))
]
except Exception as e:
print(f"释放时出错: {e}")
def animate(self):
"""健壮的动画循环"""
try:
current_time = time.time()
dt = max(0.001, current_time - self.last_time)
self.last_time = current_time
if not self.dragging and self.ball:
self.apply_physics(dt)
self.update_trail()
self.master.after(10, self.animate)
except Exception as e:
print(f"动画循环出错: {e}")
def apply_physics(self, dt):
"""带校验的物理引擎"""
try:
coords = self.canvas.coords(self.ball)
if not coords or len(coords) < 4:
return
canvas_width = self.canvas.winfo_width()
canvas_height = self.canvas.winfo_height()
if canvas_width <= 0 or canvas_height <= 0:
return
# 应用重力
self.velocity[1] += self.gravity * dt
# 计算位移
dx = self.velocity[0] * dt
dy = self.velocity[1] * dt
# 计算新位置
new_left = coords[0] + dx
new_top = coords[1] + dy
new_right = new_left + 2 * self.ball_radius
new_bottom = new_top + 2 * self.ball_radius
# 水平边界处理
if new_left < 0 or new_right > canvas_width:
self.velocity[0] *= -self.damping
dx = 0
new_left = max(0, min(new_left, canvas_width - 2*self.ball_radius))
# 垂直边界处理
if new_top < 0 or new_bottom > canvas_height:
self.velocity[1] *= -self.damping
self.velocity[0] *= 0.95
dy = 0
new_top = max(0, min(new_top, canvas_height - 2*self.ball_radius))
# 安全更新位置
if self.ball:
self.canvas.coords(self.ball,
new_left,
new_top,
new_left + 2*self.ball_radius,
new_top + 2*self.ball_radius)
except Exception as e:
print(f"物理计算出错: {e}")
def update_trail(self):
"""安全的轨迹更新"""
try:
if not self.ball:
return
coords = self.canvas.coords(self.ball)
if not coords or len(coords) < 4:
return
cx = coords[0] + self.ball_radius
cy = coords[1] + self.ball_radius
# 添加轨迹点
self.trail_points.append((cx, cy, time.time()))
# 清理旧轨迹(保留0.5秒)
now = time.time()
self.trail_points = [(x, y, t) for x, y, t in self.trail_points if now - t < 0.5]
# 绘制轨迹
self.canvas.delete("trail")
for x, y, t in self.trail_points:
age = now - t
size = max(2, 8 * (1 - age/0.5))
alpha = max(0.0, min(1.0, 1 - age/0.5))
self.canvas.create_oval(
x-size/2, y-size/2, x+size/2, y+size/2,
fill=self.rgba(0x88, 0xC0, 0xD0, alpha),
outline="",
tags="trail"
)
except Exception as e:
print(f"轨迹更新出错: {e}")
def rgba(self, r, g, b, a):
"""安全的颜色生成"""
try:
a = max(0.0, min(1.0, a))
return f'#{int(r*a):02x}{int(g*a):02x}{int(b*a):02x}'
except:
return "#88C0D0"
if __name__ == "__main__":
root = tk.Tk()
try:
app = BounceBallApp(root)
root.mainloop()
except Exception as e:
print(f"程序异常: {e}")