Turtle examples for loops and variables, or even something else

Computer Science Educators Asked by user9137 on February 1, 2021

I’m going to teach using the well known drawing turtle, with one developed by me to fit my students, so in case it can also be modified. It features drawing movement, non-drawing movement and pen color change.

The main goal is letting them have a strong visual feedback and appreciate the decomposition of complex movements. I have some examples that use functions to represent “subtasks” and repetitions to generate nice drawings.

I’m anyway a bit stuck here, say at the visual artist stage, I’d like to show them the use of a while kind of loop instead of a statically limited for, but I don’t have good ideas besides using the “while” condition to stop some recursion based for example on the next step length (imagine drawing a spiral with increasing step length and wanting to halt at some point).

It seems to me that my main difficulty has to do with the absence of interesting states from the examples, the only one that comes to mind being precisely the use of a step length.

The system also features 2 things.

  • A stack for saving turtle configurations, you can push the current position and pop it later… Fractals? It seems that those coming to my mind are more easily accessed by recursion than by a stack.
  • The ability to save a user state and access it, it can be used for example to keep a counter that changes when desired and is then used to choose a pen color from a palette. It can contain arbitrary data and the motivation was to use it as an aid for learning about mutating variables.

I anyway seem to not have good ideas for examples to link these tools to actual interesting problems. Any suggestions?

What can be easily computed by the turtle?

4 Answers

What your system is missing, actually, seems to be a feedback mechanism in which the turtle can "sense" something about the world it is in. If it, for example, could sense edge walls, then it could use that sense for conditional constructs. In Karel the Robot and its successors (Karel J Robot, Monty Karel, ...) there are a number of things that a robot can sense such as walls and "beepers".

while (karel.frontIsClear())...

If you can have multiple turtles then one turtle sensing something about another is another possibility for feedback.

But, until you get something like that (sensing about the world) you can probably only write conditional and looping constructs based on stored information in the program itself, such as counters.

Answered by Buffy on February 1, 2021

I agree with Buffy's fine answer if your imagination is running towards feedback systems. In terms of the ubiquitous turtle, however, there are still a few interesting things you could do off the top of my head.

First, having students simply create drawings is already a plus. Have them draw a face. Have them draw a car. Have them draw a face and then draw over it to change its expression. (Fill gets a little funny here!)

  1. Fractals are a wonderful way to illustrate recursion. No base case is actually strictly necessary in order to get the effect, and you could use the fact that the turtle continue to soldier on long past the point that it matters as a nice motivator for a base case. Later, when you are determining values prior to displaying them, you can hark back to the turtle to show why you need the base case there as well. We can't display until the computation ends, so we need to figure out when to "stop the turtle".

  2. Tally Marks are a great way to do unary addition and multiplication, no edge detection required.

  3. For stacks, create a randomized, symmetrical rainbow in which the order of the colors you use at the top of the rainbow must be the same order of colors at the bottom, but reversed. Something like this: enter image description here

Answered by Ben I. on February 1, 2021

I make a different take on Turtle for complete beginners. I plan to introduce concepts gradually, to minimize cognitive load, hence my curriculum is not like one found on internet. For example, bounded loops, conditionals, variables and variable modifications are not introduced from start. And so, any examples with variables are not allowed.

  1. Introduce turtle.forward(50), turtle.left(90), turtle.color("green") and how they compose and make an angle. Ask to draw a square using this framework. Ask to draw an octagon, a hexagon (huh, hexagon causes beginners to start experimenting!). In my experience it can take full hour for them (12-yo) to actually grab the idea and environment. Extra bonus for those who can draw arbitrary regular N-gon.

  2. Introduce turtle.right(X), turtle.penup(), turtle.pendown() and ask to draw some regular frames: cage, pyramid, etc. The images to reproduce are currently stored here:

  3. Part of previous task is to draw a few letters using turtle and make a word of those. The whole idea of those tasks is to make students write hundred of lines to get comfortable (or bored) with typing.

  4. Next concept to introduce is eternal loop. Show how N-gon can be drawn using infinitely running turtle with just 2-3 commands. Show how small change to angle can make turtle go wild (the turtle.left(91) example). It is best if student makes this change on it's own, as it causes WOW effect. Extremely unexpected.

  5. Next concept to introduce is delayed code. The thing called "procedure", or "function", "abstraction" I name as "delayed named code". Look, while True: makes code block execute forever, and def one_side(): makes code block not execute at all, but available to run later many times.

  6. Also it is still easy to introduce mathematical operations / 2 and * 3, which can be used to calculate angles to rotate (e.g., half of 90 is 45, but half of 45 is fractional, so maybe it makes sense to use 45 / 2 or 90 / 4 instead).

  7. And finally, introduce function parameters and how they are used when calling a procedure. Also introduce "default" argument value, to simplify code. Treat arguments as read-only -- use many times but don't change them.

At this point (procedures, arguments and math expressions) Turtle becomes complex enough to teach concepts of code structuring and namings (of procedures and arguments). It makes sense to spend a few lessons on this stage and ask to draw many diagrams ( for inspiration). Factoring letters from 3 each into it's own procedure can help creating larger words, which is, well, why procedures are really needed.

After this stage, I plan to introduce event listeners, lists of colors and angles, loop over list, coordinate system, pair type and such. Variables and conditionals (and loops in loops) should be introduced very gradually and only after previous concepts have clicked.

The bigger problem is to provoke drawing or experimenting ideas in student heads...

Answered by danbst on February 1, 2021

They're in LOGO so you might need to translate them ...

Random Walk

to random_walk :s

repeat :s [ifelse [(random 10) >= 5] [lt 45 fd 10 rt 45] [rt 45 fd 10 lt 45]]


Sierpinski Gasket

    ; this creates the "filled" version; to display the outline, make the
    ; last two lines of  this procedure into comments - by placing
    ; a semi-colon at the beginning of the lines

    IF (:LEVEL < 0) [STOP]
    REPEAT 3 [SIERPINSKI :LENGTH * (1 / 2) (:LEVEL - 1) FD :LENGTH RT 120]
    PU RT 30 FD 3 PD FILL
    PU BK 3 LT 30 PD

Might need a bit of debugging but there are some ideas in there

; Author    Jon Guiton
; Date      2/10/2011
; Usage     demo

; The cat/mouse demo uses these two functions to calculate the distance
; between the turtle (cat) and mouse (mouse). This is used to decide when
; the cat has caught the mouse.

to distance :xdif :ydif
    output sqrt ((xdif * xdif) + (ydif * ydif))

to distance_to_mouse :tpos :mpos
    output distance ((first :tpos) - (first :mpos)) ((last :tpos) - (last :mpos)) 

; This is the main procedure for the cat/mouse demo. The cat just keeps moving
; towards the mouse until it has caught up with it.
to cat_mouse_demo :difficulty
    while [(distance_to_mouse pos mousepos) > 5] [
        setheading towards mousepos
        fd 10
        wait (10 - :difficulty)
    label [GAME OVER]

; This is the main procedure for the UPPERCASE demo. Just keep reading text
; and converting it to uppercase until an empty line is read in.
to to_upper_demo
    print [Type some text, a blank line ends the demo...]
    make "text readword
    while [not emptyp :text] [
        print uppercase :text
        make "text readword

; This is the main procedure for the sounds demo. It uses the sound [frequency, duration]
; predicate to make the sounds. The formulas just scale the frequency and sounds to a
; better range of values.
to sounds_demo
    while ["true] [
        sound [exp(((last mousepos) + 100) / 20), (((first mousepos) + 100) / 3)]
        wait 10

; This is the stub for the menus demo which is actually the main program.
to menus_demo
    print [You are using the menus demo!]
    print [Press any key to continue...]
    ignore readchar

; This is the main menu procedure. This also clears the text screen to make things
; work more neatly and checks for input errors. Notice that it uses a CASE statement
; which is more convenient than lots of IF statements.
to main_menu
    make "time_to_exit "false
    while [not :time_to_exit] [
        print [---------------------------]
        print [Logo Demonstration Programs]
        print [---------------------------]
        print []
        print [1. Cat and Mouse game demo.]
        print [2. To Upper demo.]
        print [3. Sound demo.]
        print [4. Menus demo.]
        print [5. Exit demo.]
        print []
        print [Please enter a number...]
        case readchar [
            [ [1] cat_mouse_demo 5]
            [ [2] to_upper_demo]
            [ [3] sounds_demo]
            [ [4] menus_demo]
            [ [5] make "time_to_exit "true]
            [ else 
                print [] 
                print [Sorry, that is not a valid option]
                print [press any key to continue...]
                ignore readchar
                print []

; This is the main demo program. It just initialises the screen, runs the main loop
; procedure and finishes the program nicely.
to demo
    print [Bye! Have a nice day!]

Answered by Jon Guiton on February 1, 2021

Add your own answers!

Related Questions

Is there a word for mathematics/physics/data-analytics/….?

3  Asked on August 21, 2021 by loizos-vasileiou


Any good beginner tutorials for learning LLVM

2  Asked on August 21, 2021 by joshua-segal


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir