Escriu per cercar…

Motion

Aquesta pàgina encara no s'ha traduït — es mostra en l'idioma original:English

Introduction

We watch an ant make his laborious way across a wind- and wave-molded beach. He moves ahead, angles to the right to ease his climb up a steep dunelet, detours around a pebble, stops for a moment to exchange information with a compatriot. Thus he makes his weaving, halting way back home. … His horizons are very close, so that he deals with each obstacle as he comes to it; he probes for ways around or over it, without much thought for future obstacles. It is easy to trap him into deep detours.

Let’s pursue the point of view of turtle as mathematical “animal” by thinking of the turtle’s motion as a behavior pattern and the turtle programs as models of simple animal behavior.

Turtle geometry is particularly well suited to such modeling because of the local and intrinsic ways we specify the turtle’s movements.

Expressing motions in terms of forwards and rights is a much more direct way of dealing with an animal’s behavior than, say, describing movements in response to stimuli as changes in x and y coordinates.

Random Motion

Perhaps the simplest kind of motion to model with the turtle is random motion (repeatedly going forward and turning random amounts).

To implement this in a function, Python has a random-number generator random.uniform(low,high) that outputs a random number between low and high.

Using this we can write a function that takes four inputs specifying the ranges from which to select the inputs to forward and left:

python
random_motion.py
from turtle import *
import random

def random_move(d1, d2, a1, a2):
    while True:
        left(random.uniform(a1, a2))
        forward(random.uniform(d1, d2))

random_move(10, 50, -45, 45)

Even with this simple program, there is much to investigate.

How do the bounds on the forwards or the turns affect the path? For instance, unless you make a1 negative, the turtle will always turn left and the path will look roughly like a circle.

In fact, except when a1 is chosen to be the negative of a2, the turtle’s turning will be biased in one direction or the other and this will be reflected in the shape of the path.

How about the case where the turning is unbiased? Would you expect the turtle to go off “to infinity”? Or will it instead travel in a very large circle? More generally, can you say anything about the radius of the “average path” as a function of the bounds on the turns?

One way to investigate these random motions is to write a record-keeping procedure that repeatedly runs, say, loo rounds of the random_move loop and automatically records such statistics as the turtle’s heading and distance from the origin after those 100 rounds.

Can you say anything about the average values of these quantities?

Box

Random-motion procedures such as this will often run the turtle off the edge of the display screen.

Forcing the turtle to stay on the screen suggests modifying the random motion to model the behavior of an animal crawling in a box.

To enable the turtle to do this, we implement the check_forward function, which is just like forward except that it won’t allow the turtle to move if the result takes it outside some fixed square box around the origin:

python
from turtle import *
import random

# Initializing global variables
BOXSIZE = 200


def check_forward(distance):
    """
    Checks if moving forward by the given distance will stay within the box boundaries.
    If it stays within bounds, it moves the turtle and returns True.
    Otherwise, it stays at the original position and returns False.
    """

    # Save current position to restore it after boundary check
    old_pos = pos()
    penup()
    hideturtle()

    # Tentatively move forward to check if it would go out of bounds
    forward(distance)
    out_of_bounds = abs(xcor()) > BOXSIZE or abs(ycor()) > BOXSIZE

    # Restore original position and state
    goto(old_pos)
    pendown()
    showturtle()

    if out_of_bounds:
        return False
    else:
        forward(distance)
        return True


def random_move(d1, d2, a1, a2):
    """
    Continuously moves the turtle randomly within the box.
    d1, d2: range for random distance.
    a1, a2: range for random angle.
    """
    while True:
        left(random.uniform(a1, a2))
        check_forward(random.uniform(d1, d2))


def box():
    """
    Draws a square box centered at (0, 0) with side length 2 * BOXSIZE.
    Restores turtle to (0, 0) after drawing.
    """
    penup()
    goto(-BOXSIZE, -BOXSIZE)
    pendown()
    for _ in range(4):
        forward(BOXSIZE * 2)
        left(90)
    goto(0, 0)
    pendown()


box()
random_move(10, 50, -45, 45)

This procedure makes use of some new functions in our turtle graphics system:

  • hideturtle() causes the turtle indicator not to be displayed
  • showturtle()restores the indicator;
  • xcor() and ycor() output, respectively, the x and y coordinates of the turtle;

We can use these procedures to model appropriate behaviors that will keep the turtle in the box.

Here, for example, is a version of random_move that has the turtle turn 180° whenever it runs into an edge:

python
def random_move(d1, d2, a1, a2):
    while True:
        left(random.uniform(a1, a2))
        if not check_forward(random.uniform(d1, d2)):
            right(180)

A second possibility for edge behavior is to have the turtle turn a little at a time, until it can go forward again.

python
def random_move(d1, d2, a1, a2):

    while True:
        left(random.uniform(a1, a2))
        while not check_forward(random.uniform(d1, d2)):
            right(5)

Estàs llegint una vista prèvia.

Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.

Inicia sessió