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 = 10 bouncyness = 0.85 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 # Divide by modifier, since we want fractions of a second deltaY = int(self.yVelocity) self.yLoc += deltaY # y Location increases by the velocity (per 1/5 of a second) deltaX = self.xVelocity self.xLoc += deltaX if self.yLoc >= self.bottomWall - self.radius: # Bounce self.yVelocity = self.yVelocity * -1 * self.bouncyness if self.yLoc <= self.topWall : self.yVelocity = abs(self.yVelocity) #if self.yLoc >= self.bottomWall if self.xLoc >= self.rightWall or self.xLoc <= self.leftWall: self.xVelocity *= -1 * self.bouncyness print "DEBUG: %f " %(self.yVelocity) self.canvas.move(self.itm, deltaX, deltaY) # ------------------------------------ # Outside the class # ------------------------------------ balls = [] def moveIt(): # Update all the balls for ball in balls: ball.update() # After 20 milliseconds (1/5 second).... fire an event to call moveIt canvas.after(5, moveIt) def main(): global ball, canvas root = Tk() # Create a big canvas 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) # Left wall canvas.create_line(left,top,right,top) # Top wall canvas.create_line(right,top,right,bottom) # Right wall canvas.create_line(left,bottom,right,bottom) # Bottom wall # Create some balls for i in range(100): rcolor = '#%d%d%d' %(randint(0,9), randint(0,9), randint(0,9)) # Random color 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 = Ball(130, 130, 0, 12, color=rcolor, \ #leftWall=left, rightWall=right, topWall=top, bottomWall=bottom) ball.draw(canvas) balls.append(ball) # After 1000 milliseconds (1 second).... fire an event to call moveIt canvas.after(1000, moveIt) root.mainloop() main()