#----------------------------------------------------------------- # particle.py - by Claudio Fin marzo 2008 #----------------------------------------------------------------- import Tkinter import random import math #----------------------------------------------------------------- N_PARTICELLE = 40 # numero di particelle F_PARTICELLE = 500.0 # forza respingente tra particelle RAGGIO = 5 # raggio particelle SMORZAMENTO = 0.99 # fattore smorzamento del moto #----------------------------------------------------------------- class Particella: def __init__ (self): self.x=random.randint(-200,200)+300.0 self.y=random.randint(-200,200)+300.0 self.vx=random.randint(-1,1)*1.0 self.vy=random.randint(-1,1)*1.0 self.icona=None #----------------------------------------------------------------- def calcola_particelle(forzac,part): #------calcola contributo campo esterno for p in part: dx=p.x-300.0 dy=300.0-p.y dist=math.hypot(dx,dy) distc=300.0-dist forza=-forzac/(distc*distc)*360 forzax=forza*dx/dist forzay=-forza*dy/dist p.vx+=forzax p.vy+=forzay #------calcola contributo altre particelle if len(part)>1: for i in xrange(len(part)): for j in xrange(len(part)): if j!=i: dx=part[i].x-part[j].x dy=part[i].y-part[j].y dist=math.hypot(dx,dy) if dist<12: dist=12 forza=-F_PARTICELLE/(dist*dist) forzax=-forza*dx/dist forzay=-forza*dy/dist part[i].vx+=forzax part[i].vy+=forzay #------aggiorna posizioni for p in part: p.vx*=SMORZAMENTO p.vy*=SMORZAMENTO p.x+=p.vx p.y+=p.vy #----------------------------------------------------------------- def disegna_particelle(canvas,part): for p in part: canvas.coords(p.icona, p.x-RAGGIO, p.y-RAGGIO, p.x+RAGGIO, p.y+RAGGIO) #----------------------------------------------------------------- class Applicazione: def __init__ (self): self.form1=Tkinter.Tk() self.form1.title("Particelle") self.form1.resizable(False,False) self.frame1=Tkinter.Frame(self.form1, width=100, relief="raised", bd=2) self.frame1.grid_propagate(0) self.frame1.grid(row=0, column=0, sticky="ns") self.canvas1=Tkinter.Canvas(self.form1, width=600, height=600, bg="white") self.canvas1.grid(row=0, column=1) self.scale1=Tkinter.Scale(self.frame1, from_=100, to=10, command=self.chgscale) self.scale1.grid(row=0, column=0) self.campo1=self.canvas1.create_oval( (10,10,590,590) ,outline="red",width=0) self.f_campo=1.0 self.p=[] for i in xrange(N_PARTICELLE): self.p.append(Particella()) self.p[i].icona=self.canvas1.create_oval( (self.p[i].x-RAGGIO, self.p[i].y-RAGGIO, self.p[i].x+RAGGIO, self.p[i].y+RAGGIO), fill="green" ,outline="black") self.animazione() def chgscale(self,valore): self.f_campo=float(valore) self.canvas1.itemconfig(self.campo1, width=int(self.f_campo)/10) def animazione(self): calcola_particelle(self.f_campo,self.p) disegna_particelle(self.canvas1,self.p) self.form1.after(20, self.animazione) #---------------------------------------------------------------------------- app=Applicazione() app.form1.mainloop()