TurtleGraphics Python: Bouncing turtle off the walls?

后端 未结 2 488

So, I am trying to make a realistic bouncing function, where the turtle hits a wall and bounces off at the corresponding angle. My code looks like this:

def boun         


        
2条回答
  •  余生分开走
    2021-01-24 08:53

    Gday,

    Your problem seems to be that you are using the same trigonometry to calculate the right and left walls, as you are the top and bottom. A piece of paper and a pencil should suffice to calculate the required deflections.

    def inbounds(limit, value):
        'returns boolean answer to question "is turtle position within my axis limits"'
        return -limit < value * 2 < limit
    
    def bounce(num_steps, step_size, initial_heading):
        '''given the number of steps, the size of the steps 
            and an initial heading in degrees, plot the resultant course
            on a turtle window, taking into account elastic collisions 
            with window borders.
        '''
    
        turtle.reset()
        height = turtle.window_height()
        width = turtle.window_width()
        turtle.left(initial_heading)
    
        for step in xrange(num_steps):
            turtle.forward(step_size)
            x, y = turtle.position()
    
            if not inbounds(height, y):
                turtle.setheading(-turtle.heading())
    
            if not inbounds(width, x):
                turtle.setheading(180 - turtle.heading())
    

    I've used the setheading function and a helper function (inbounds) to further declare the intent of the code here. Providing some kind of doc-string is also good practice in any code that you write (provided the message it states is accurate!!)

    Your mileage may vary on the use of xrange, Python 3.0+ renames it to simply range.

提交回复
热议问题