# file: tumbleWhileTrig.py # # author: Bob Muller # date: November 11, 2007 # # 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 uses the block function to draw the block at a specified angle # r (for radians). # def fall(x, y, width, height, r, delta): while r > 0.0: # Draw the block. # block(x, y, width, height, r, 'Brown') # Erase the block. # block(x, y, width, height, r, 'White') # Now decrease the angle. We use the max function to # prevent the block from falling below the line y == 0. # r = max(0.0, r - delta) # tumble is the top-level. width is the block width, height is the height and delta is # the rate of change. # def tumble(width, height, delta): # The center is x == 0 so -halfWidth is left edge and halfWidth is right edge. # halfWidth = turtle.window_width() / 2.0 x = -halfWidth + width while (x - width) < halfWidth: # Use the fall function to make the block fall. NB: math.pi / 2.0 == 90 degrees. # fall(x, 0, width, height, math.pi / 2.0, delta) # Now that the block has fallen over, move the block to the right, # x = x + height # and swap the height and width. NB: A temp is required. # temp = height height = width width = temp