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): mod = 5 # The ball isn't bouncing... stop! if abs(self.yVelocity) < 10 and self.yLoc >= (self.bottomWall-5): self.yVelocity = 0 self.xVelocity = 0 return else: self.yVelocity += 2 #9.8/5 # Bounce off the "floor" if self.yLoc > self.bottomWall or self.yLoc + self.yVelocity > self.bottomWall: self.yVelocity = -1 * self.yVelocity * self.bouncyness deltaY = self.bottomWall - self.yLoc else: deltaY = int(self.yVelocity) self.yLoc += deltaY # Bounce off the "wall" if self.xLoc > self.rightWall or self.xLoc < self.leftWall: self.xVelocity *= -1 deltaX = self.xVelocity/5 self.xLoc += deltaX 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) for i in range(10): rcolor = '#%d%d%d' %(randint(0,9), randint(0,9), randint(0,9)) ball = Ball(randint(left,right), randint(top,bottom), 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()