python;李峋同款跳动爱心代码
时间: 2023-12-15 17:33:29 浏览: 160
以下是李峋同款跳动爱心代码的Python实现:
```python
import random
from math import sin, cos, pi, log
from tkinter import *
class Heart:
def __init__(self, canvas, x, y, size):
self.canvas = canvas
self.x = x
self.y = y
self.size = size
self.id = canvas.create_oval(x, y, x+size, y+size, fill='red', outline='')
def jump(self):
dx = random.randint(-10, 10)
dy = random.randint(-10, 10)
self.canvas.move(self.id, dx, dy)
def beat(self):
r = self.size / 2
t = 0
while True:
x = self.x + r * 16 * sin(t)**3
y = self.y - r * (13*cos(t) - 5*cos(2*t) - 2*cos(3*t) - cos(4*t))
self.canvas.coords(self.id, x, y, x+self.size, y+self.size)
t += pi / 16
if t >= 2 * pi:
t = 0
self.canvas.update()
def main():
root = Tk()
root.title('Jumping Hearts')
canvas = Canvas(root, width=500, height=500)
canvas.pack()
hearts = []
for i in range(20):
x = random.randint(50, 450)
y = random.randint(50, 450)
size = random.randint(20, 50)
heart = Heart(canvas, x, y, size)
hearts.append(heart)
while True:
for heart in hearts:
heart.jump()
heart.beat()
canvas.update()
canvas.after(50)
root.mainloop()
if __name__ == '__main__':
main()
```
阅读全文