# file: tumble.py # # author: Bob Muller # date: March 17, 2008 # # This file contains python code using the turtle graphics system. # The code in this file, causes a block to tumble across the x-axis. # # Note that the solution presented here uses the math.sin and math.cos # functions and recursive functions. # # The code contained here is used in CS074 The Digital World. # import turtle import math def setup(h, w): turtle.setup(height=h,width=w) turtle.radians() turtle.up() # block draws a colored block with corner at point (x,y) and inclined # at (radian) angle r. # def block(x, y, width, height, r, color): turtle.color(color) # Compute the Cartesian coordinates of the 3 other # corners of the block. # rightAngle = math.pi / 2.0 x1 = x + math.cos(r) * height y1 = y + math.sin(r) * height x2 = x1 + math.cos(r + rightAngle) * width y2 = y1 + math.sin(r + rightAngle) * width x3 = x + math.cos(r + rightAngle) * width y3 = y + math.sin(r + rightAngle) * width # Now do the drawing. # turtle.goto(x,y) turtle.begin_fill() turtle.goto(x1, y1) turtle.goto(x2, y2) turtle.goto(x3, y3) turtle.goto(x,y) turtle.end_fill() # fall is a simple recursive function. It first draws the block # at a specified angle r (for radians) and then, if the block hasn't # hit the surface, it erases the block and calls itself again having # decreased the angle r. # def fall(x, y, width, height, r, delta): # Draw the block. # block(x, y, width, height, r, 'Brown') if r > 0: # Erase the block. # block(x, y, width, height, r, 'White') fall(x, y, width, height, max(0.0,r-delta), delta) # tumble is the top-level function. It simply calls tumbleHelp so that it # can pass along an x-coordinate. # def tumble(width, height, delta): initialX = -(turtle.window_width() / 2.0) + width tumbleHelp(initialX, width, height, delta) def tumbleHelp(x, width, height, delta): if (x - width) < turtle.window_width() / 2.0: fall(x, 0, width, height, math.pi / 2.0, delta) # The block has now fallen to the right. Now continue # by calling this routine again with an increased x # component and swapping the values of the height and # width variables. # tumbleHelp(x + height, height, width, delta)