Turtle Graphics Programming with Newt

by Steve Weyer

This tutorial is available as a collection of HTML and graphics files, and as an interactive Newton book created by Newt's Cape from these files (version and distribution information). NewtTurT may also be available as an Acrobat PDF file, viewable with Adobe Acrobat Reader on your desktop system.

Introduction

The "Newt" (aka NewtDevEnv) discussed in this article is a shareware native programming environment on the Newton. Like a chameleon, Newt has evolved to provide different functionality to different users. The first version of Newt in Oct. '93, inspired by the Inspector Gadget and Dot2Dot examples from Apple, allowed you to draw graphics using NewtonScript -- the "turtle", its amphibious cousin and name inspiration, used Logo. You, the learner, could explore mathematics via a turtle microworld, or add NewtonScript methods to emulate Logo commands and data structures. This book will let you explore Newt as a graphics programming environment.

You will get the most out of this interactive article/tutorial if you have Newt (application), NewtDraw (plugin) and NewtTurT (book) installed on your Newton; you need Newt's Cape or Newt's Cape Lite installed for NewtonScript links to work. If you are using a desktop web browser, you may wish to view graphics (there are some GIF screen shots). NewtTurT 1.6 requires Newt 3.3 (or later) and NewtDraw plugin.

With enthusiastic feedback from early users, I shifted efforts and emphasis so that you could create objects based on Newton interface prototypes and save an application. Newt's icon (next) reflects both its original turtle personality (on left) as well as its later application personality (on right). Newt icon

Newt's "application personality" will not be covered here. However, if you are interested in building applications on your Newton with interface objects such as buttons, text fields and checkboxes, look for the related Newton book: NewtATut: Building Newton Applications with Newt. The North Atlanta Newton User Group (NANUG) _protoReality newsletter contains an interview with me and a turtle-oriented article by my daughter. Erica Sadun reviewed Newt as turtle in PDA Developers (formerly PIE Developers), Vol. 2.4, July 1994.

Using Newt from this book

If you are using the book version and have Newt and NewtDraw installed, you can tap on its icon earlier to start it (if Newt was already open, you should close it). If successful, Newt opens, then a few seconds later, the book reappears. You can return to Newt later by closing this book. You can return to this book from Newt by selecting its title "Turtle Graphics Programming with Newt" from Newt's overview list (bottom dot between two scroll arrows).

Later in this book, you can tap on underlined code to copy and evaluate it in Newt. Newt also saves the source text in the Notepad -- and usually exits the book when there is a visible result. If you accidentally close Newt too soon, just start over.

For desktop web browsers, an initial Newt screen shot may appear. Use your web browser's "Back" command to return to this page. Tapping on underlined code will show you the related screen shot (if available).

Turtles and Logo

I would like to provide some brief history and context -- the first two topics -- before focusing on the third:

  1. past -- the history of turtles and Logo
  2. pedagogy -- how students learn by engaging in programming and problem solving
  3. practical -- how to use Newt to draw a picture and write a method

The original turtle began life in the early 70's as a floor robot that could draw pictures when the user gave it commands like "forward", "right", "penup" and "pendown". By using information from its touch sensors, the turtle could be programmed to maneuver around objects. Turtles evolved and inspired work in several directions:

In LegoLogo, students construct vehicles and devices using motors, lights and sensors which are controlled by programs. As wireless control systems become economical, and as the Newton's infrared communication range increases, it will be fun to use Newt and Newton as a remote controller.

Although turtles are practically synonymous with the Logo programming language, other languages such as Lisp and Smalltalk have also implemented turtle objects and environments. In addition to graphics, Logo (and other languages) have been used to teach children other aspects of programming, e.g., list processing and pattern matching. Logo is similar to Lisp in its structure and expressiveness, but much simpler in syntax.

The Newt environment uses NewtonScript (NS), Newton's built-in object-oriented language. NS shares ancestry with dynamic object-oriented languages such as Smalltalk, Self, Common Lisp, and ObjectLogo. For more advanced users, familiarity with object-oriented concepts and constructs is useful; for those familiar with Logo, it is easy to translate ideas and code; for others, Newt serves as a brief introduction to these ideas.

Learning by Children of all Ages

Seymour Papert at MIT, applying the learning theories of Swiss psychologist Jean Piaget, used the turtle as a "mathematics microworld" that children could explore by writing Logo programs. Piaget's experiments identified three modalities of learning: enactive, iconic and symbolic. At early ages, children learn most naturally through concrete aspects or physical manipulation, i.e., by touching and doing. Later, they are ready to interpret and reason with the help of other senses, e.g., by seeing and hearing. Finally, they are ready to reason using abstract concepts and symbols, in addition to the earlier learning styles.

In the turtle microworld, the students integrated information from the physical domain of the turtle, visual feedback from graphics, and symbolic representations via programs. Students role-played the turtle in order to experience a relative coordinate system and to understand how programs might not reflect what the student had intended. The students engaged in planning, problem solving and "learning by debugging". They learned by breaking problems down into subproblems in order to use recursion.

Over the years, many people have been involved in Logo and similar learning environments. I will note just a few, and apologize in advance to those I have omitted: Logo and LegoLogo at MIT (Papert), Smalltalk at Xerox PARC and Vivarium at Apple (Alan Kay), Boxer at Berkeley (diSessa), and numerous other projects in Logo (BBN, Bank Street, Stanford). In the hands of a well-trained coach or teacher, such exploratory environments go beyond just programming or drawing pictures toward an experiential understanding of mathematics.

Newt follows in the footsteps of these earlier efforts by providing a portable, turtle-like learning environment.

Getting Started with Newt

Newt requires only a willingness to learn -- not any extensive programming experience. Much of what I will describe here can also be found in turtle.htm file and other files that accompany Newt, or is discussed in more detail in the manual if you register.

You can draw with Newt using pen gestures:

tap
draw a line to current position
drag
move Newt without drawing
line
change Newt's direction or draw a line along the same heading
scrub
erase the drawing

If you would like to try this in Newt, close this book. A Newt pen should be visible in the center of the screen. Remember that you can return to this book by selecting its title from the overview list. You can also re-open the Newt Drawing area and Newt Controls palette from the same overview list if you accidentally close them.

In the description below, Dist, Deg and Times are buttons in Newt Controls: each has an input fields to the right.

Sample Activities
User ActionsNewt response
Write a number for Dist, e.g., 80tap DistNewt draws a line
Write a number for Deg, e.g., 90tap DegNewt turns
tap Disttap Deg (alternate)Newt creates a closed polygon or other figure
Write a number for TimesTap TimesNewt repeats Dist and Deg.
Tap Eraseor use scrub gestureNewt clears the drawing area
Tap HomeNewt returns to center.

Interesting Values
TimesDistDeg
54072
64060
84045
94040

Other Interesting Values
TimesDistDeg
570144
97080
970160
970160
157048
157096
1570168

Could you discover a pattern between the number of sides and degrees for each set of values?

If you use larger values for Dist, Newt will clip the line at the edge of its drawing area. Negative numbers mean go backwards. If you use larger values for Deg, Newt will just ignore multiples of 360 and use the remainder. Negative values for Deg mean turn left (counterclockwise) instead of right. Unless you want to use the reset button or wait awhile, you should not use very large values for Times since the default behavior for Newt is to finish executing the entire expression before checking for user actions like button taps. There is a facility provided in Newt to replace the NewtonScript "for" iteration construct. This facility executes each step in the background and allows you to interrupt Newt -- that's discussed in the manual and perhaps in a future article.

Consumer Alert!

Before delving into programming details, I offer a warning. Apple and Newton developers are still learning how to implement system and application software. In addition, while learning with Newt, you will take risks and make mistakes. For example, Newt allows you to execute arbitrary NewtonScript expressions. This can be a formula for enlightenment or disaster. So, remember that this is your Newton with your information and listen to your mother's advice about backing up your system.

Using common sense in following examples and suggestions, and limiting yourself to documented commands, you should reap many benefits and long hours of enjoyment from using Newt. At the same time, "a little learning [about programming] is a dangerous thing" (my apologies to Alexander Pope). I would caution against too much experimenting with random functions or methods. "Gee, I wonder what xxx does" might yield a simple error message, or it might zap a frame or soup in your system.

This tutorial is only a brief introduction to Newt and even less for NewtonScript. As noted elsewhere, look at Newt files and later in this article for pointers to further information.

Writing Methods

You can write a method to group the commands that you were executing one-at-time yourself. For example, if you are a Logo fan, you might prefer to use forward instead of go, and right instead of turn (tap on a method to define it):

forward
func(distance)
:go(distance)
right
func(angle)
:turn(angle)

You can now invoke these methods in expressions or other methods, for example:

local i; for i:=1 to 5 do begin :forward(100); :right(144); end

Here is a method that defines a polygon (using the usual go and turn):

poly
//:poly (4,100)
//:poly (times,dist)
//local i; for i:=3 to times do :poly(i,dist)
//:poly(Random(3,15),Random(10,20))
func(nsides, len)
if nsides > 0
then begin
  local i, ang := 360/nsides;
  for i:=1 to nsides
  do begin
    :go(len);
    :turn(ang);
    end;
  end
else :beep()

To make things easier for you, this book tells Newt to do Erase and Home before evaluating expressions, for example:

:poly(5,70)

You can use variables for fields like Times, Dist, and Deg. The following nested polygons uses the dist variable that corresponds to the number in the Dist field. It uses times to limit iteration:

local sides; for sides:=3 to times do :poly(sides,dist)

If Newt did not draw anything, were Dist and Times non-zero? Once an expression is in the Eval field in Newt, you can edit it and/or tap the Eval button to re-evaluate it.

:poly(Random(3,15),Random(10,20))

Here is a noisy figure:

local i; for i:=5 to 160 by 5 do begin :go(i); :turn(90); :beep(); end

Here is a classic "squiral" method involving rotated squares:

squiral
//:squiral(10,75)
func (num,len)
/* draw 'num' squares, each of size 'len'
after each, turn 360/num */
if num > 0
then begin
  local i, ang2 := 360/num;
  for i:=1 to num
  do begin
    :poly (4,len);
    :turn(ang2);
    end;
  end
else :beep()

Ten rotated squares:

:squiral(10,75)

cCurve draws a fractal-like pattern.

cCurve
//:cCurve(6,8,0)
func(num,dist,deg)
if num > 0
then begin
  :cCurve(num-1, dist, deg+45);
  :cCurve(num-1, dist, deg-45);
  end
else begin
  :turnTo(deg);
  :go(dist);
  end

Since cCurve uses a double recursion (not a simple "tail recursion"), avoid large values for the first parameter. If you find a pattern that you like, you can tap the Save button (in Eval Controls), and Newt will save the current picture to your Notepad.

:cCurve(6,8,0)

You can also have multiple Newts. This expression creates four of them with different homes and pen sizes:

:addNewt('[[newt1,-55,75,1], [newt2,55,75,2], [newt3,55,-75,1], [newt4,-55,-75,2]],nil,nil,nil)

Generally, messages are sent to the default Newt object. Now as a default, the message is broadcast to the collection of Newts. (This is covered in more detail in the manual). Try this expression to see how multiple Newts draw in tandem:

:squiral(8,40)

Or, if you would like to see four Newts drawing doubly-recursive cCurves in parallel (you may wish to exit to NewtTurT first and turn off the Newt? checkbox for faster drawing):

:cCurve(6,4,0)

Or, you can send a message to a specific object

newt1:poly(6,20)

This expression removes multiple Newts, returning you to the lonely default Newt:

:removeNewt(all_Newts)

Finally, an interesting variation on poly where the side increments each time:

polyspi
//:polyspi(80,25,89)
func (n,len,ang)
begin
  local i;
  for i:=len to len+n by 1
  do begin
    :go (i);
    :turn (ang);
    end;
end

Here is an example expression to try:

:polyspi(80,25,89)

In order to keep this book relatively small, I will now end the tour of Newt's graphics environment. You can experiment on your own with Newt directly using turtle.htm and graphic0.nwt for a partial guide. If you are intrigued by the possibilities of programming your own Newton to create graphics or applications, I would encourage to register to receive a more detailed manual and set of examples.

For More Info

NewtTurT (in all its formats) is © 1994-2007, Steve Weyer. All Rights Reserved Worldwide. NewtTurT is freeware. If all of its files are included, NewtTurT may be freely distributed on online services. Book version created from HTML by Newt's Cape.

Version: 1.6

Last updated: 4-May-2004

Over the past 30+ years, Steve has managed and implemented R&D projects in object-oriented languages and prototyping environments, AI tools, hypertext systems, education and pharmaceutical applications. A Silicon Valley emigre and Seattle native, Steve lives with his family in rural Pennsylvania, develops Newton apps in his spare time, and currently consults on wireless and Java-based projects.