#Key Balls - Using Calico Graphics #Like bouncing balls, but they all reverse when you press a key. from Graphics import * from Myro import timer #used for the animation. import random #random starting positions and speeds NUMBALLS = 10 WINSIZE = 500 win = Window("Pong", WINSIZE, WINSIZE) win.mode = "manual" #Trick to make the animation smoother.... balls = [] dx = [] dy = [] #This function gets called when somebody releases a key while the window has the focus def handleKeyRelease(win, event): #All it does is print a message and reverse the direction of the balls print("Key Released!", event.key) for idx in range(len(dy) ): dy[idx] = -dy[idx] dx[idx] = -dx[idx] #Bind the key handler funciton! (Note that this works even after the timer runs out!) onKeyPress( handleKeyRelease ) #make each of the balls with a random starting position and dx,dy. for x in range(NUMBALLS): #Generate a random startX and startY position for this ball. startX = int( random.random() * WINSIZE) startY = int( random.random() * WINSIZE ) #create this ball thisBall = Circle((startX,startY), 10) thisBall.draw(win) #Draw it on the window. balls.append(thisBall) #Add it to the list of balls. #make a random color for this ball: co = Color( random.random() * 255, random.random() *255, random.random() *255) thisBall.color = co #Generate random DX and DY for this ball, and save them to the dx and dy lists. ballDX = int( random.random() * 30) - 15 ballDY = int( random.random() * 30) - 15 dx.append(ballDX) dy.append(ballDY) #Now, animate all the balls for 15 seconds: for i in timer(15): #Now, move all the balls and check to make sure they don't go off the edges! for index in range(len(balls) ): b = balls[index] ballDX = dx[index] ballDY = dy[index] b.move(ballDX,ballDY) if b.getX() > WINSIZE or b.getX() < 0: dx[index] = -dx[index] if b.getY() > WINSIZE or b.getY() < 0: dy[index] = -dy[index] #Outside of the "for index of each ball" loop, but inside the timer loop. wait(0.1) #Wait for 1/10th of a second so the user can see the ball moving! win.update() #Because we set the window mode to manual, we must tell it when to update!