几天前,我问过有关使用tkinter在画布上的球的问题,但我仍然不知道该怎么办

时间:2018-12-08 14:44:22

标签: python canvas tkinter

原始源代码在这里。

import time
import random
from tkinter import *
import numpy as np
import math
window = Tk()
canvas = Canvas(window,width=600,height=400)
canvas.pack()

#create canvas#

canvas.create_rectangle(50,50,550,350)

#R = radius, x,y = initial position, vx,vy = velocity factor for x,y, dt = changing time
R = 15
x1 = random.randrange(50+R,550-R)
y1 = random.randrange(50+R,350-R)
x2 = random.randrange(50+R,550-R)
y2 = random.randrange(50+R,350-R)
vx1 = random.randrange(1 , 10)
vy1 = random.randrange(1 , 10)
vx2 = random.randrange(1 , 10)
vy2 = random.randrange(1 , 10)
ntime = 100000
dt = .1

#create balls and moving
for iter in range(ntime):
    #position change after time passed as dt
    x1 += vx1*dt
    y1 += vy1*dt
    x2 += vx2*dt
    y2 += vy2*dt
    #crate oval
    c1 = canvas.create_oval(x1-R,y1-R,x1+R,y1+R,fill="red")
    c2 = canvas.create_oval(x2-R,y2-R,x2+R,y2+R,fill="blue")
    #when balls are crashed with walls, change velocity factor
    if (x1 > 550-R):
        vx1 = -vx1
    if (x1 < 50+R ):
        vx1 = -vx1
    if (x2 > 550-R):
        vx2 = -vx2
    if (x2 < 50+R ):
        vx2 = -vx2
    if (y1 > 350-R) or (y1 < 50+R):
        vy1 = -vy1
    if (y2 > 350-R) or (y2 < 50+R):
        vy2 = -vy2
    if (x2-x1)**2 + (y2-y1)**2 <= 4*R*R:
        #when two balls make collides, follow this rule
        vector1 = np.array([x1,y1])
        vector2 = np.array([x2,y2])
        vvector1 = np.array([vx1,vy1])
        vvector2 = np.array([vx2,vy2])
        nvector = np.array([x2-x1,y2-y1])
        un = (nvector)/((sum(nvector*nvector))**(1/2))
        tvector = np.array([y1-y2,x2-x1])
        ut = tvector/((sum(nvector*nvector))**(1/2))
        vector1midn = sum(vvector1*un)
        vector2midn = sum(vvector2*un)
        vector1midt = sum(vvector1*ut)
        vector2midt = sum(vvector2*ut)
        vector1after = vector2midn*un + vector1midt*ut
        vector2after = vector1midn*un + vector2midt*ut
        vx1 = vector1after[0]
        vy1 = vector1after[1]
        vx2 = vector2after[0]
        vy2 = vector2after[1]


    #make clock
    txt = canvas.create_text(100,30,text=str(iter),font=('consolas', '20', 
'bold'))


    window.update()
    time.sleep(0.002)


    #delete old balls
    if iter == ntime-1 : break  

    canvas.delete(c1)
    canvas.delete(c2)
    canvas.delete(txt)


window.mainloop()

问题是我如何才能将画布中的球相乘,并在相乘的同时如何使球沿刚设置的矢量规则运动? 有些人建议我,但现在仍然无法正常工作。如果可以的话,我可以通过python中的列表系统来做到这一点吗?还是只能通过上课?

0 个答案:

没有答案