#---------------------------------------------------------------------- # Program to bounce a centered square around the canvas. # # Copyright (C) March 30, 2018 -- Dr. William T. Verts #---------------------------------------------------------------------- import time # Library of time routines (like time.sleep) #---------------------------------------------------------------------- # Paint a square centered at with side radius R. Note the # default parameters for the colors. This function can be called as # follows: # addSquare(Canvas, Xc, Yc, green, blue) # Override both # addSquare(Canvas, Xc, Yc, green) # Override Interior # addSquare(Canvas, Xc, Yc) # Defaults for both #---------------------------------------------------------------------- def addSquare (Canvas, Xc, Yc, R, Interior=white, Exterior=black): Diameter = 2 * R addRectFilled(Canvas, Xc-R, Yc-R, Diameter, Diameter, Interior) addRect (Canvas, Xc-R, Yc-R, Diameter, Diameter, Exterior) return #---------------------------------------------------------------------- # Main program #---------------------------------------------------------------------- def Main(): W = 600 H = 500 Canvas = makeEmptyPicture(W,H) X = W / 2 # Start in the middle Y = H / 2 # of the canvas R = 50 # Size of box XDirection = 1 # Start moving to the YDirection = 1 # SouthEast while True: # Infinite loop addRectFilled(Canvas, 0, 0, W, H, white) # Can also use setAllPixelsToAColor addSquare(Canvas, X, Y, R, yellow, red) # Paint the square repaint(Canvas) # Update the view time.sleep(0.01) # Do nothing for 0.01 seconds X = X + XDirection # Move the box Y = Y + YDirection # if X+R >= W: XDirection = -1 # Change direction if the if X-R <= 0: XDirection = +1 # box hits one of the if Y+R >= H: YDirection = -1 # boundary walls if Y-R <= 0: YDirection = +1 # return # Never executed