# Ball Fountain for CodeSkulptor3 # with acknowledgements to James Brown # http://codepen.io/jsbrown/pen/nqDIp import random, simplegui # dimensions of screen are in pixels width = 200 height = 200 numBalls = 5 radius = 5 gravity = 0.02 class Ball: def __init__(self, colour): # set initial position and velocities self.reset() # colour is the ball number from 0 to numBalls - 1 self.col = 'hsl(' + str(360*colour//numBalls) + ', 100%, 50%)' # colour # reset position and velocities, but keep colour def reset(self): self.x = width // 2 # x centred self.y = height # y bottom of screen self.vx = random.random() * 1.4 - 0.7 # horizontal velocity left or right self.vy = random.random() * -2 - 1.2 # vertical velocity up # Handler to draw on canvas def draw(canvas): for b in balls: # move b.vy += gravity b.x += b.vx b.y += b.vy # canvas.draw_circle(center_point, radius, line_width, line_color, fill_color) canvas.draw_circle([b.x, b.y], radius, 1, b.col, b.col) if ( b.x - radius > width or b.x + radius < 0 or b.y - radius > height or b.y + radius < 0 ): b.reset() # move back to start # colour stays the same def init(): global balls balls = [] for n in range(numBalls): balls.append(Ball(n)) # n is used to set the colour def main(): # Create a frame and assign callbacks to event handlers frame = simplegui.create_frame("Fountain", width, height) frame.set_canvas_background('white') frame.set_draw_handler(draw) init() # Start the frame animation frame.start() main()