A simple gravity program, designed to roughly simulate gravity (For a better simulation, see my 3D gravity simulator). To launch balls, click and drag with the mouse. The further back you pull, the further it will go. This isn’t on repl.it because repl.it can’t cope with Tkinter, so just copy the code into your Python IDE.
IDE means Integrated Development Environment. An IDE is basically an improved text editor configured for that language, so print() might be bold or a different colour in the python IDE.
from tkinter import *
root=Tk()
w=1000
h=1000
c=Canvas(width=w,height=h,bg='black')
c.pack()
origin=[]
bricks=[]
class Ball:
def __init__(self,x,y,r,xv,yv):
self.myId=c.create_oval(x-r,y-r,x+r,y+r,fill='gold')
self.spdX=xv
self.spdY=yv
self.rad=r
self.diff=True
def step(self,check=True):
try:
c.move(self.myId,self.spdX,self.spdY)
if check:
self.hitBrick()
pos=c.coords(self.myId)
if pos[2] >= w or pos[0] <= 0:
self.spdX *= -0.9
if pos[1] <= 0:
self.spdY *= -1
if pos[3] >= h:
x,y,x2,y2=c.coords(self.myId)
c.coords(self.myId,x,h-(self.rad*2)-1,x2,h-1)
self.spdY*=-0.5
c.move(self.myId,0,self.spdY)
self.spdX*=0.99
self.spdY+=2
root.update()
c.pack()
root.after(30,self.step)
except:
pass
def hitBrick(self):
global bricks
for brick in bricks:
try:
pos=c.coords(brick.myId)
x,y,x2,y2=c.coords(self.myId)
r=self.rad
if (pos[0] < x2 and pos[2] > x) and (pos[1] < y2 and pos[3] > y):
c=1
while ((pos[0] < x2-c and pos[2] > x+c) and (pos[1] < y2-c and pos[3] > y+c)):
c+=1
if not ((pos[0] < x2-c) or (pos[2] > x+c)):
if not (pos[0] < x2-c):
c.coords(self.myId,pos[0]-(r*2)-1,y,pos[0]-(r*2)-1,y2)
else:
c.coords(self.myId,x,pos[3]+1,x2,pos[3]+(r*2)+1)
self.spdX*-0.9
else:
if not (pos[1] < y2-c):
c.coords(self.myId,x,pos[1]-(r*2)-1,x2,pos[1]-1)
else:
c.coords(self.myId,x,pos[3]+1,x2,pos[3]+(r*2)+1)
self.spdY*=-0.5
root.update()
c.pack()
except:
pass
class Brick:
def __init__(self,x,y,x2,y2):
self.myId=c.create_rectangle(x,y,x2,y2,fill='pink')
def makeball(event):
Ball(event.x,event.y,30,(origin[0]-event.x)/10,(origin[1]-event.y)/10).step()
def log(event):
global origin
origin=[event.x,event.y]
bricks.append(Brick(450,900,550,1000))
c.bind("<Button1>",log)
c.bind("<Button-Release1>",makeball)
root.mainloop()