from Tkinter import * from random import * # These are variables I will define as instance variables #xLoc - Where is the ball? (X) #yLoc - Where is the ball? (Y) #xVelocity - How fast is the ball moving (X) #yVelocity - How fast is the bal moving (Y) #color - Color of the ball class Ball: # These are class variables, one copy of these variables are stored among all instances # of this class radius = 5 bouncyness = 0.88 def __init__(self, xLoc, yLoc, xVelocity, yVelocity, color='green', leftWall=0, rightWall=400, \ topWall=0, bottomWall=400): self.xLoc = xLoc self.yLoc = yLoc self.xVelocity = xVelocity self.yVelocity = yVelocity self.leftWall = leftWall self.rightWall = rightWall self.topWall = topWall self.bottomWall = bottomWall self.color = color # Draw the initial ball def draw(self, canvas): x1 = self.xLoc-self.radius y1 = self.yLoc-self.radius x2 = self.xLoc+self.radius y2 = self.yLoc+self.radius self.itm = canvas.create_oval(x1, y1, x2, y2, fill=self.color) self.canvas = canvas # Update to the new location of the ball def update(self): # What fraction of a second are we simulating? 1/5 of a second mod = 50 # Gravity self.yVelocity += 9.8/mod deltaY = int(self.yVelocity) self.yLoc += deltaY deltaX = self.xVelocity self.xLoc += deltaX if self.yLoc >= self.bottomWall-5: self.yVelocity = self.yVelocity * -1 * 0.75 if self.xLoc >= self.rightWall or self.xLoc <= self.leftWall: self.xVelocity *= -1 * 0.98 if self.yLoc >= self.bottomWall and abs(self.yVelocity) <= 1: self.xVelocity = 0 self.canvas.move(self.itm, deltaX, deltaY) # ------------------------------------ # Outside the class # ------------------------------------ balls = [] def moveIt(): for ball in balls: ball.update() canvas.after(20, moveIt) def main(): global ball, canvas root = Tk() canvas = Canvas(root, width=800, height=800) canvas.pack() left = 20 right = 600 top = 20 bottom = 600 # Draw the walls canvas.create_line(left,top,left,bottom) canvas.create_line(left,top,right,top) canvas.create_line(right,top,right,bottom) canvas.create_line(left,bottom,right,bottom) # Bottom wall for i in range(100): rcolor = '#%d%d%d' %(randint(0,9), randint(0,9), randint(0,9)) ball = Ball(randint(10,300), randint(10,300), randint(2,20), randint(2,20), color=rcolor, \ leftWall=left, rightWall=right, topWall=top, bottomWall=bottom) ball.draw(canvas) balls.append(ball) canvas.after(1000, moveIt) root.mainloop() main()