Activities/TurtleArt

From Sugar Labs

Jump to: navigation, search
english | español | HowTo [ID# 71478] 

Contents

What is Turtle Blocks (AKA Turtle Art)

Turtle Blocks is an activity with a Logo-inspired graphical "turtle" that draws colorful art based on snap-together visual programming elements. Its "low floor" provides an easy entry point for beginners. It also has "high ceiling" programming features which will challenge the more adventurous student.

Where to get Turtle Blocks

http://activities.sugarlabs.org/en-US/sugar/addon/4027

Note: There are two inter-compatible programs: Turtle Art and Turtle Blocks. Turtle Art, which closely parallels the Java version of Turtle Art maintained by Brian Silverman, offers a small subset of the functionality of Turtle Blocks. Sugar users probably want to use Turtle Blocks rather than Turtle Art. (Also see Turtle Confusion, a collection of programming challenges designed by Barry Newell.)


Getting Started

Screenshot of "Turtle Art Activity" getting started.png

Start by clicking on (or dragging) blocks from the Turtle palette. Use multiple blocks to create drawings; as the turtle moves under your control, colorful lines are drawn.

You add blocks to your program by clicking on or dragging them from the palette to the main area. You can delete a block by dragging it back onto the palette. Click anywhere on a "stack" of blocks to start executing that stack or by clicking in the Rabbit (fast) , Turtle (slow) or Bug (debug) buttons Rabbitturtle.jpg on the Project Toolbar.

The basics

Drawing shapes

Displaying things

Boxes, Stacks and the Heap

(aka variables, subroutines and the stack)

Mathematics

Keyboard, mouse and sensor input

Challenges

Do Barry Newell's 40 shapes challenge [4] (The Turtle Confusion puzzles have been incorporated into a new activity (See Turtle Confusion).

Newellchallenges.jpg


Do Daniel Ajoy's Geometry Exercises [5]

Ajoy1-20.jpg

Ajoy21-40.jpg

Ajoy41-60.jpg

Ajoy61-84.jpg


Mike Leishman's 10 Green Bottles Competition.

The idea is that you write a program to display the words of the song "10 green bottles" [6]

Can you get the computer to sing in tune using the espeak -p option


Mike Leishman's Guess the Number

Write a guessing game computer program. It must ask the user to guess a secret number between 1 and 100 and continue until the secret number is guessed. If the user guesses the wrong number, display a message stating that they are too high or too low such as "Bad Guess – Too High - Try again". Make your program count the number of guesses taken. When the user guesses the correct number, display the Message "You guessed it in <number of guesses> guesses" and stop the program.

Extension: You can also provide the user with other information such as “cold”, “warm” and “hot” depending on how far out their guess is. [7]


Generating numbers

Calculate the values of pi [8] and e [9], find the prime numbers up to 1000

How many different ways can you do it?

How fast can you do it?


Pizzas

Write a program to solve: A small pizza costs 120 pesos. A large pizza costs 160 pesos. You spent 920 pesos in total. How many small and many large pizzas have you bought? [10]


Project Euler [11]

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.


Python Challenge [12]

The Python Challenge is a set of riddles that require a little bit of Python programming to be solved. The solutions are entered by changing the address of the page (URL). You get used to the idea pretty fast after solving the first few levels.


Toolbars

Main Toolbar

TAmain.png

From left to right:

Keyboard short cuts for the above: Alt+ palette; blocks; run; walk; stop; erase; e.g., Alt+e will erase the screen. Esc will return from full-screen mode.

Notes: The run buttons are tied to the Start Block. If no Start Block is used, then all blocks are run when either run button is clicked. The "rabbit" button runs the blocks at maximum speed. The "turtle" button pauses and displays the turtle between each step. The "bug" button pauses between each step and shows status information.

On older versions of Sugar (e.g., 0.84), the main toolbar will look like this:

TA0.84.png

Project Toolbar

TurtleBlocks Toolbar 1.png

From left to right:

Note: On older Sugar systems, these controls appear on the Import/Export toolbar.

Edit Toolbar

TurtleBlocks Toolbar 2.png

The Edit toolbar is used to copy stacks of blocks to the clipboard and to paste stacks from the clipboard. To copy a stack, place the cursor on any block in the stack and then type Ctrl-c. To paste a stack from the clipboard, type Ctrl-v.

From left to right:

View Toolbar

TurtleBlocks Toolbar 4.png

From left to right:

Help Toolbar

TurtleBlocks Toolbar 6.png

Palettes Toolbar

The palette menus are revealed by clicking on the Block icon on the main toolbar. (On older Sugar systems, select the Projects toolbar. When running Turtle Art from GNOME, the palettes are visible by default.)

TurtleBlocks Toolbar 5.png

As of Version 106 of Turtle Art, there are ten palettes of program elements available for program construction: Turtle movements; Pen attributes; Color attributes; Numeric operators; Logical operators; Logical blocks; Sensor blocks; Media blocks; Customization functions; and Presentation blocks. An eleventh palette is used for restoring blocks from the trash.

Blocks are dragged from the palette onto the canvas surface. To dispose of a block, drag it back onto the palette. (It will be placed onto the trash palette.)

The palettes can be displayed horizontally or vertically (See below). Orientation is adjusted by clicking on the TAorientation0.svg and TAorientation1.svg buttons on the upper-left corner of the palette. The palette can be hidden by clicking on the TAhide.svg button on the lower-right corner of the palette. The next palette in the menu can be accessed by clicking on the TAnext.svg button on the upper-right corner of the palette.

The Hide-blocks.png button is used to hide/reveal the program blocks. Individual palettes can be hidden by clicking on their highlighted tab.

Turtle Palette

TAturtle.png

These blocks are used to control the movements of the turtle.

Pen Palette

TApen.png

These blocks are used to control the attributes of the turtle's pen.

Color Palette

TAcolors.png

These blocks can be used with the set-pen-color block in place of a number block.

Numbers Palette

TAnumbers.png

These blocks are arithmetic and boolean operators.

Flow Palette

TAflow.png

These blocks control program flow.

Blocks Palette

TAblocks.png

These blocks are for defining variables and subroutines.

Media Palette

TAmedia.png

These are a collection of blocks used for displaying media objects, such as images from the Journal.

Sensors Palette

TAsensors.png

The OLPC XO can measure external inputs with its microphone jack:

The OLPC XO 1.75 also includes an accelerometer.

See Activities/TurtleArt/Using Turtle Art Sensors for more details about the sensor blocks.

(Activities/TurtleArt/Uso_de_TortugaArte_Sensores español)

Extras Palette

TAextras.png

These are a collection of extra blocks for accessing advanced features only available in Turtle Blocks.

add your own math equation in the block, e.g., sin(x); This block is expandable to support up to three variables, e.g. f(x,y,z)
To use the collapsible-stack blocks, place them around the blocks you want to hide

Portfolio Palette

TAportfolio.png

These blocks are used to make multimedia presentations only available in Turtle Blocks.

Only available in Turtle Blocks:

Note: The slide blocks expand into stacks that can be edited for customized presentations.

Trash Palette

TAtrash.png

This palette holds any blocks that have been put in the trash. You can drag blocks out of the trash to restore them. The trash palette is emptied when you quit Turtle Art.

Vertical palettes

TAvertical.png

An example of a vertical palette. Vertical palettes are used by default on the OLPC XO laptops running older versions of Sugar.

Palettes en español

Extras

Keyboard shortcuts

Note for OLPC-XO laptop users: the buttons on the display can also be used.

Copying and Pasting

Did you know that you can copy/paste stacks to/from the clipboard? You type Ctrl-C to copy whatever stack is under the cursor to the clipboard. Ctrl-V will paste from the clipboard onto whatever TA project you have open. Try pasting this code into your Turtle Art project.

[[0, "clean", 258, 217, [12, 1]],
 [1, "repeat", 258, 251, [0, 2, 3, null]],
 [2, ["number", 36], 309, 251, [1, null]],
 [3, "repeat", 323, 311, [1, 4, 5, 9]],
 [4,  ["number", 4], 374, 311, [3, null]],
 [5, "forward", 388, 371, [3, 6, 7]],
 [6, ["number", 300], 459, 371, [5, null]],
 [7, "right", 388, 413, [5, 8, null]],
 [8, ["number", 90], 446, 413, [7, null]],
 [9, ["vspace", 20], 323, 389, [3, 10]],
 [10, "right", 323, 463, [9, 11, null]],
 [11, ["number", 10], 381, 463, [10, null]],
 [12, "start", 258, 175, [null, 0]]]

You can also paste text from the clipboard into text blocks.

Note: You can duplicate individual blocks with copy and paste, when duplicating a text block, deselect the text block after copying if you want to duplicate the block rather than duplicating the text within the block.

Speed

Turtle Art has three 'run' buttons:

Sharing

Turtle Art supports a simple sharing model. Whomever joins a shared activity will share turtles with the other participants, e.g., whatever any turtle draws will appear on every screen. Share can consume a lot of network bandwidth, so it is not recommended to share among more than 2–3 people at a time if the screen is frequently changing. As with all Sugar activities, you can use the Share-with feature of the Journal to share your Turtle Art projects with others.

Note: as of Version 83, Turtle Art will not share correctly with older versions.

Note: as of Version 106, Turtle Art will share between Sugar and GNOME.

Running Turtle Art outsde of Sugar

TAGnome.png

Turtle Art can be run in the GNOME desktop outside of Sugar.

PC HARDWARE:

OLPC XO HARDWARE

Tutorials

Tony Forster's Blog

Tony Forster has written a number of blog posts about his experiments with Turtle Art:

An bringing it all together, the Turtle Art Oscilloscope.

Untitled.jpg

Tony has also used the programmable block to do file IO.

Video Tutorials

I know there are a few but they are not categorized on this page... we'll make that happen soon. Help would be appreciated.

A list of further video clips can be found here.

Mokurai's Tutorials

Mokurai has been working on how to teach Sugar by guided discovery, rather than by explicit direction, with only the necessary minimum of hints. At the same time, he has been working on Turtle Art examples to teach concepts of mathematics, programming, Computer Science, and physics, aiming where possible at presentations suitable for pre-literate pre-schoolers. Thus, no text, no formulas, no calculations. Those can come later in sequences on the same topics as children develop, including a transition from Turtle Art to Python, Logo, and Smalltalk, with options for other languages. However, it is necessary to provide texts, sometimes with formulas and calculations, for the teacher or parent helping the child. These will appear on Mokurai's Replacing Textbooks blog, available at PlanetSugarlabs, and will be incorporated into Open Education Resources on the Sugar Labs Replacing Textbooks server.

Topics

Planned topics

Primary school

Higher

At this level it is not necessary to use Turtle Art_to_introduce ideas. Nevertheless the ability to display a topic in Turtle Art demonstrates that it is of only a moderate level of complexity.

Galleries

Play with Turtle Art to draw colorful art patterns using a turtle that accepts instructions for movement.

With visual programming blocks, you can snap together programs by compiling (combining) them in ways to create anything you can imagine.

more maths

Tony Forster describes his "adventures" with on-the-fly definitions to create an analog clock in his blog.

Try any of the time or math library functions, e.g.,

localtime().tm_min 
sin(x) + sin(pi/2)

presentations

games

Turtle Art can be used to write games, such as a simple falling block game:

sensors

Turtle Art supports sensor input:

More ideas for sensors [[13]] [[14]]

student work

Students from Caacupé have been sending me examples of their work:

Just for fun

Recent features

Presentations and Portfolios

A portfolio feature lets you use Turtle Art to create multimedia slide shows from material retrieved from your Journal. The basic idea is to import images (and eventually movies, audio, and text files) into slide templates, not unlike Powerpoint, and then show a presentation by stepping through them. The portfolio includes the typical major functions of presentation software: an editor that allows text to be inserted and formatted (this is largely incomplete), a method for inserting images (from the Journal), and a slide-show system to display the content. What makes it a bit different than tools such as Powerpoint is that you can program your slides using Turtle Art blocks. Turtle Art also has an export-to-HTML function so that presentations can be viewed outside of the Sugar environment. (These features have been merged into the main branch of Turtle Art.)

Background

In the era of high-stakes testing, we have the means to measure “which child knows more”; these data tell us about relative merit of the school in which a child is enrolled. The Turtle Art portfolio feature is an assessment tool that shows “what a child knows”; children become the curators of their own work. They advance their own learning and help their teachers, parents, and school administrators understand better the depth and breadth of what they have learned.

A recent article in the Chronicle of Higher Education claims:

  1. ePortfolios can integrate student learning in an expanded range of media, literacies, and viable intellectual work;
  2. ePortfolios enable students to link together diverse parts of their learning including the formal and informal curriculum;
  3. ePortfolios engage students with their learning;
  4. ePortfolios offer colleges a meaningful mechanism for accessing and organizing the evidence of student learning.

Turtle Art portfolios engage children in the process of reflecting on their work—what they have done, how they have done it, and how success these efforts have been—as they create a multimedia narrative to show their teachers, parents and peers what they have learned. Turtle Art Portfolio builds upon the journaling functionality of the Sugar learning platform, where every action or activity a child takes in the classroom is automatically recorded in a folder: (1) by enabling the child to select important learning achievements, be they in reading, writing, arithmetic, arts, music, physical education, history and social science, etc. Children answer questions such as “I chose this piece because...” (2) creating a multimedia narrative presentation from their selections (including audio voice-overs and video), reflective of the multiple ways in which children learn; and (3) sharing their presentation with classmates, both to celebrate what they have learned, but also to engage in a critical dialog about their work.

Turtle Art portfolio is innovative in three ways: (1) it builds upon a journal of *all* learning activities that is automatically collected; (2) it has unique programmability, fun and accessible to even the youngest elementary school children, but interesting and engaging to middle-school children as well; and (3) it has unique tools for both collaborating on the construction of the portfolio and its subsequent sharing with others.

Portfolios have been shown to be “a powerful means for children to assess their own work, set goals, and take responsibility for their future learning.” But portfolio assessment has seen limited applicability. It is a practical, engaging means to using portfolios. By building upon the automatic accumulation of work in journal (including a “screen capture” of their work) the portfolio process can readily be integrated into the classroom routine. Reflection becomes the norm: children are encouraged write in their journals (young children record audio notes) for a few minutes after *every* class. The numbing question, “what did you do in school today?” need no longer a necessary part of the parent-child dialog. Instead, the parent can talk to the child about actual artifacts.

Culling from the journal becomes part of the end-of-term assessment process. The process of telling one's story as a learning requires further reflection. At a “portfolio social”, parents are invited to view presentations and ask children about their learning; the child's voice is heard.

The classroom teacher can add addition assessment slides to the portfolio about themes such as work habits and personal growth, as part of an archive that travels with a child across grade levels. Through juxtaposition, the child and teacher can see what has changed over the course of the years, trends, and areas for improvement, Also, a classroom portfolio can be assembled as part of a teacher-assessment process.

Some additional background on ePortfolios can be found here:

Sharing a presentation

From version 106, pen trails, fill, show text and show images are shared with other laptops in a shared session. Screen erase is not shared. A slideshow can be broadcast to other laptops. Its simple, just these 2 blocks are required to broadcast a slide to all the laptops in the shared session.

Show-media.jpg

Use set scale to set image size. Full screen images take longer than smaller images. See below for using the keyboard to advance slides and other presentation ideas.

Quick Tutorial on using the portfolio features

A video of the portfolio basics is available here.

A PDF of a Turtle Art portfolio presentation can be downloaded File:Desktop-Summit.pdf.

Turtle Art can export its projects to Berkeley Logo (using either View Source or the Save as Logo button on the Project Toolbar) You can download the Berkeley Logo activity here.

Logo code generated from your project is viewable in the View Source panel in some versions of Turtle Art, but as of v100, the Turtle Art project itself is shown instead.

Note: The Save-as-Logo button saves to the Journal as "logosession.lg". UCB Logo does not yet access the Journal directly, so it is necessary to copy the project out of the Journal using the "copy-from-journal" command in the Terminal Activity and then accessing the project using the File menu within the UCB Logo Activity.

copy-from-journal logosession.lg

Alternatively, you can open the logosession in 'Write', copy the Logo code to the clipboard, and then paste it into the UCB Logo Activity.

Shown here is the Logo code generated from the Turtle Art project shown above.

Firstly the Logo code contains procedures for setting up the palette and the shade functionality:

to tasetpalette :i :r :g :b :myshade
make "s ((:myshade - 50) / 50)
ifelse lessp :s 0 [
make "s (1 + (:s *0.8))
make "r (:r * :s) 
make "g (:g * :s) 
make "b (:b * :s)
] [
make "s (:s * 0.9)
make "r (:r + ((100-:r) * :s)) 
make "g (:g + ((100-:g) * :s)) 
make "b (:b + ((100-:b) * :s))
]
setpalette :i (list :r :g :b)
end
to rgb :myi :mycolors :myshade
make "myr first :mycolors
make "mycolors butfirst :mycolors
make "myg first :mycolors
make "mycolors butfirst :mycolors
make "myb first :mycolors
make "mycolors butfirst :mycolors
tasetpalette :myi :myr :myg :myb :myshade
output :mycolors
end
to processcolor :mycolors :myshade
if emptyp :mycolors [stop]
make "i :i + 1
processcolor (rgb :i :mycolors :myshade) :myshade
end
to tasetshade :shade
make "myshade modulo :shade 200
if greaterp :myshade 99 [make "myshade (199-:myshade)]
make "i 7
make "mycolors :colors 
processcolor :mycolors :myshade
end
to tasetpencolor :c
make "color modulo round :c 100
setpencolor :color + 8
end
make "colors [
100 0 0 100 5 0 100 10 0 100 15 0 100 20 0 100 25 0 100 30 0 100 35 0 100 40 0 100 45 0 
100 50 0 100 55 0 100 60 0 100 65 0 100 70 0 100 75 0 100 80 0 100 85 0 100 90 0 100 95 0 
100 100 0 90 100 0 80 100 0 70 100 0 60 100 0 50 100 0 40 100 0 30 100 0 20 100 0 10 100 0 
0 100 0 0 100 5 0 100 10 0 100 15 0 100 20 0 100 25 0 100 30 0 100 35 0 100 40 0 100 45 
0 100 50 0 100 55 0 100 60 0 100 65 0 100 70 0 100 75 0 100 80 0 100 85 0 100 90 0 100 95 
0 100 100 0 95 100 0 90 100 0 85 100 0 80 100 0 75 100 0 70 100 0 65 100 0 60 100 0 55 100 
0 50 100 0 45 100 0 40 100 0 35 100 0 30 100 0 25 100 0 20 100 0 15 100 0 10 100 0 5 100 
0 0 100 5 0 100 10 0 100 15 0 100 20 0 100 25 0 100 30 0 100 35 0 100 40 0 100 45 0 100 
50 0 100 55 0 100 60 0 100 65 0 100 70 0 100 75 0 100 80 0 100 85 0 100 90 0 100 95 0 100 
100 0 100 100 0 90 100 0 80 100 0 70 100 0 60 100 0 50 100 0 40 100 0 30 100 0 20 100 0 10]
make "shade 50
tasetshade :shade
to tasetbackground :color :shade
tasetshade :shade
setbackground :color + 8
end

Then the Logo code contains the project:

to ta
clearscreen tasetbackground 21 100 setpensize 25.0 make "box1 0.0 
repeat 300.0 [ tasetpencolor xcor / 6.0 tasetshade heading forward :box1 right 91.0 make "box1 :box1 + 1.0 ] 
end
ta

Programmable Brick

The following feature—a block Pythoncodeblock.jpg that can be programmed by the Pippy activity—is available in versions 44+ of Turtle Art.

Version 44 to 103

A copy of the tamyblock.py module is stored in the Journal when you first launch Turtle Art. All the sample modules are in this one file but all except one are commented out with #

You can edit the tamyblock.py module in Pippy. Then load the Python code into the Python block using the Pippy button on the Project toolbar. TAPippyButton.svg You can only have one type of Python block in your Turtle Art program.


TA-pippy.png

Another way to load the Python block, is to click the Python code block Pythoncodeblock.jpg found on the the Extras palette.

Version 104 onwards

There are two ways to create Python blocks: by loading sample code provided with Turtle Art or by loading Python code the your Journal.

loading sample code

A number of individual sample programs are provided. Clicking on the Load Python Block button on the Load/Save Toolbar Loadpythonsamples.jpg will invoke a file-selector dialog. Select the sample that you want and it will be both copied to the Journal and loaded into a Python block.

Pythonsampleselector.jpg

loading code from the Journal

Clicking on a Python block Pythoncodeblock.jpg that has been dragged onto the canvas from the Extras palette will invoke an object-selector dialog.

Pythonobjectselector.jpg

Select the Python code that that you want and that code will be loaded into the selected block.

You can't run a Python block by clicking on it, as that opens the object selector; instead attach the block to another one and click elsewhere on the stack you have created.

Which ever way you create them, multiple Python blocks can have different code loaded in them.

Sample code

TA-dotted-line.png

def myblock(tw, line_length):
    ''' Draw a dotted line of length line_length. '''
    try:  # make sure line_length is a number
        line_length = float(line_length)
    except ValueError:
        return
    if tw.canvas.pendown:
        dist = 0
        while dist + tw.canvas.pensize < line_length:  # repeat drawing dots
            tw.canvas.setpen(True)
            tw.canvas.forward(1)
            tw.canvas.setpen(False)
            tw.canvas.forward((tw.canvas.pensize * 2) - 1)
            dist += (tw.canvas.pensize * 2)
        # make sure we have moved exactly line_length
        tw.canvas.forward(line_length - dist)
        tw.canvas.setpen(True)
    else:
        tw.canvas.forward(line_length)
    return

You can pass a list of up to three arguments to tamyblock.py as in the example below that converts the input to an rgb value.

TA-rgb.png

def myblock(tw, rgb_array):
    ''' Set rgb color from values '''
    tw.canvas.fgrgb = [(int(rgb_array[0]) % 256),
                       (int(rgb_array[1]) % 256),
                       (int(rgb_array[2]) % 256)]
def myblock(tw, x):
   ###########################################################################
   #
   # Push an uppercase version of a string onto the heap.
   # Use a 'pop' block to use the new string.
   #
   ###########################################################################
   if type(x) != str:
       X = str(x).upper()
   else:
       X = x.upper()
   tw.lc.heap.append(X)
   return
def myblock(tw, x):
   ###########################################################################
   #
   # Push hours, minutes, seconds onto the FILO.
   # Use three 'pop' blocks to retrieve these values.
   # Note: because we use a FILO (first in, last out heap),
   # the first value you will pop will be seconds.
   #
   ###########################################################################
   tw.lc.heap.append(localtime().tm_hour)
   tw.lc.heap.append(localtime().tm_min)
   tw.lc.heap.append(localtime().tm_sec)
   return
def myblock(tw, x):
   ###########################################################################
   #
   # Add a third dimension (gray) to the color model.
   #
   ###########################################################################
   val = 0.3 * tw.rgb[0] + 0.6 * tw.rgb[1] + 0.1 * tw.rgb[2]
   if x != 100:
       x = int(x)%100
   r = int((val*(100-x) + tw.rgb[0]*x)/100)
   g = int((val*(100-x) + tw.rgb[1]*x)/100)
   b = int((val*(100-x) + tw.rgb[2]*x)/100)
   # reallocate current color
   rgb = "#%02x%02x%02x" % (r,g,b)
   tw.fgcolor = tw.canvas.cm.alloc_color(rgb)
   return
def myblock(tw, x):
   ###########################################################################
   #
   # Save an image named x to the Sugar Journal.
   #
   ###########################################################################
   tw.save_as_image(str(x))
   return

def myblock(tw, x):

   ###########################################################################
   #
   # Push mouse event to stack
   #
   ###########################################################################
   if tw.mouse_flag == 1:
       # push y first so x will be popped first
       tw.lc.heap.append((tw.canvas.height / 2) - tw.mouse_y)
       tw.lc.heap.append(tw.mouse_x - (tw.canvas.width / 2))
       tw.lc.heap.append(1) # mouse event
       tw.mouse_flag = 0
   else:
       tw.lc.heap.append(0) # no mouse event

Device I/O

This Python block returns with the brightness sensor value in the heap. A range of parameters can be measured, for example, substitute any of the path strings in the table for the 'device' in the program below.


device path notes
battery current /sys/devices/platform/olpc-battery.0/power_supply/olpc-battery/current_now OLPC XO
battery voltage /sys/devices/platform/olpc-battery.0/power_supply/olpc-battery/voltage_now OLPC XO
screen brightness /sys/devices/platform/dcon/backlight/dcon-bl/actual_brightness OLPC XO
accelerometer /sys/devices/platform/lis3lv02d/position OLPC XO 1.75, 3.0
light sensor /sys/devices/platform/olpc-ols.0/level OLPC XO 1.75, 3.0
screen mode /sys/devices/platform/dcon/monochrome OLPC XO 1.75, 3.0
charging /sys/devices/platform/olpc-battery.0/power_supply/olpc-ac/online OLPC XO
clock date /sys/devices/platform/pxa2xx-i2c.1/i2c-1/1-0068/rtc/rtc0/date OLPC XO 1.75
clock time /sys/devices/platform/pxa2xx-i2c.1/i2c-1/1-0068/rtc/rtc0/time OLPC XO 1.75
cpu temperature /sys/devices/platform/via_cputemp.0/temp1_input OLPC XO 1.5


def myblock(tw, x):  # ignores second argument
   import os
  
   # The light sensor is only available on the XO 1.75
   device = '/sys/devices/platform/olpc-ols.0/level'
   
   if os.path.exists(device):
       fh = open(device)
       string = fh.read()
       fh.close()
       tw.lc.heap.append(float(string))  # append as float value to heap
   else:
       tw.lc.heap.append(-1)

Look in /sys/devices on your computer to find other devices you may be able to access.

You can also read events in /dev/input . Use the od (octal dump) command to inspect these events, eg

sudo od /dev/input/event0 

You can access the following events on the X0-1.75, (some on X0-1.0 -1.5)


For example, the code below waits till the ebook switch state changes and pushes the status to the heap

def myblock(tw, x):  # ignores second argument
  
  import os
  devicestr='/dev/input/event3'              #the ebook switch
  cmd='sudo chmod 777 {!s}'.format(devicestr)
  os.system(cmd)                             #caution! changing system file permissions
  fd = open(devicestr, 'rb')
  for x in range(12):
     fd.read(1)                              #does not return till the switch state changes
  tw.lc.heap.append( ord(fd.read(1)))        #push ebook switch state to heap
  fd.close

Understanding the structure of the Turtle Art program

Turtle Art offers two blocks for adding Python code,

Python function block

The Python function block is processed through tajail.py. For security reasons, it cannot access Turtle Art objects. It can it only access the Python language and the time and math libraries as the following extract from tajail.py shows.

from time import *
from math import *

For more information on allowable syntax for this block:

Python code block

Turtle Art is created in object oriented Python code. This is based around the definition of classes and the creation of object(s) which are instance(s) of that class. These objects then have properties and methods which are defined by their class.

See http://docs.python.org/tutorial/classes.html for a description of classes in Python.

See the file TurtleArtActivity.py. This is where it starts. When an instance of TurtleArtActivity is created, setup_canvas() creates an instance of TurtleArtWindow: self.tw This instance of TurtleArtWindow creates an instance of LogoCode: self.tw.lc and an instance of TurtleGraphics: self.tw.canvas

tamyblock.py gets passed a LogoCode instance, lc, and everything is relative to that instance. tw is passed to lc and set as an instance data object at init. This allows referral back to tw when needed. Consequently, Class TurtleArtWindow is accessed through lc.tw. and Class TurtleGraphics is accessed through lc.tw.canvas


ClassDefined inInstanceCreated in
TurtleArtActivityTurtleArtActivity.py inherits from sugar.activity
TurtleArtWindowtawindow.pytwTurtleArtActivity.py
LogoCodetalogo.pylctawindow.py
TurtleGraphicstacanvas.pycanvastawindow.py
Turtles, Turtletaturtle.pyturtlestawindow.py, tacanvas.py
Blocks, Blocktablock.pyblock_listtawindow.py

Class TurtleArtWindow – useful properties and methods (from within tamyblock.py, lc.tw is the class instance)

Methods and data attributesExampleNotes
set_fullscreen(self)lc.tw.set_fullscreen()Hides the Sugar toolbar
set_cartesian(self, flag)lc.tw.set_cartesian(True)True will make the overlay visible; False will make it invisible
set_polar(self, flag)lc.tw.set_polar(True)True will make the overlay visible; False will make it invisible
hideshow_button(self, flag)lc.tw.hideshow_button()Toggles visibility of blocks and palettes
self.active_turtlelc.tw.active_turtleThe active turtle instance

Class TurtleGraphics – useful properties and methods (from within tamyblock.py, lc.tw.canvas is the class instance)

Methods and data attributesExampleNotes
clearscreen(self)lc.tw.canvas.clearscreen()Clears the screen and resets all turtle and pen attributes to default values
setpen(self, flag)lc.tw.canvas.setpen(True)True will set the pen "down", enabling drawing; False will set the pen "up"
forward(self, n)lc.tw.canvas.forward(100)Move the turtle forward 100 units
arc(self, a, r)lc.tw.canvas.arc(120, 50)Move the turtle along an arc of 120 degrees (clockwise) and radius of 50 units
setheading(self, a)lc.tw.canvas.setheading(180)Set the turtle heading to 180 (towards the bottom of the screen)
self.headinglc.tw.canvas.headingThe current heading
setpensize(self, n)lc.tw.canvas.setpensize(25)Set the turtle pensize to 25 units
self.pensizelc.tw.canvas.pensizeThe current pensize
setcolor(self, c)lc.tw.canvas.color(70)Set the pen color to 70 (blue)
self.colorlc.tw.canvas.colorThe current pen color
setshade(self, s)lc.tw.canvas.shade(50)Set the pen shade to 50
self.shadelc.tw.canvas.shadeThe current pen shade
fillscreen(self, c, s)lc.tw.canvas.fillscreen(70, 90)Fill the screen with color 70, shade 90 (light blue)
setxy(self, x, y)lc.tw.canvas.setxy(100,100)Move the turtle to position (100, 100)
self.xcorlc.tw.canvas.xcorThe current x coordinate of the turtle (scaled to current units)
self.ycorlc.tw.canvas.ycorThe current y coordinate of the turtle (scaled to current units)
self.set_turtle(name)lc.tw.canvas.set_turtle(1)Set the current turtle to turtle '1'

Other useful Python functions

ModuleMethods and data attributesExampleNotes
from math import powpow(2,3)returns 2 to the 3rd power (8)See http://docs.python.org/library/math.html
from math import sin, pisin(45*pi/180)returns sin of 45 (0.707)See http://docs.python.org/library/math.html
from time import localtimelocaltime().tm_hourreturns the current hourSee http://docs.python.org/library/time.html
lc.heap.append(data)add data to the FILOSee http://docs.python.org/tutorial/datastructures.html
data = lc.heap.pop(-1)pop data off of the FILOSee http://docs.python.org/tutorial/datastructures.html

Plugins

As of Version 106, there is plugin support for Turtle Art. The basic idea is to let developers add new palettes and blocks to support additional functionality without having to make changes to any of the core Turtle Art packages. If a plugin is present, it is loaded when Turtle Art is launched and any palettes or blocks defined by the plugin are made available to the user.

The plugin mechanism is currently used to provide support for sensors, the camera, RFID, and the Media, Extras, and Portfolio palettes. A plugin has been developed for WeDo (and here) and additional plugins are being developed for Arduino, NXT, and GoGo.

How to install a plugin

Plugins are typically distributed as a *.tar.gz archive

Archivemanager.jpg

In Gnome, click on the link in your browser and open with Archive Manager, extract the files in the plugins directory of the archive to

/home/olpc/Activities/TurtleArt.activity/plugins

you may need to make the Activities directory writeable first, in Terminal type

chmod 777 /home/olpc/Activities

If your distribution does not include Gnome, the following commands in Terminal will download the Physics archive to the current directory

cd ~/Activities/TurtleArt.activity
wget http://wiki.sugarlabs.org/images/c/c1/Physics-plugin.tar.gz
gunzip Physics-plugin.tar.gz
tar xvf Physics-plugin.tar

Note that you should not need root access to install plugins into your home directory.

Available plugins

These plugins would typically already be installed

Project Butia

Add a palette to control the Butiá robot

Butia palette.png

Proyecto Butiá

Download: butia_plugin.tar.gz

FollowMe

This plugin uses the camera and get the position of an object of a color. The plugin add this palette: Turtleart-followme-palette2.png

Download: followme_ta_plugin.zip

Examples:

The "classic" use: on "Start", use the "Calibrate" block to open a window that shows the camera output. In the center of that window there is red square. The FollowMe Plugin uses an algorithm that obtains the "promedial" color of the object in the square. The result of that algorithm is shown in a small square in the corner. When you consider that the color is a good "representation of the object", press any key, the window will close, and FollowMe will use this color. After calibration, you can use the "X position" and "Y position" blocks. The block "X position" is the "center" of the object seen by the camera along the "X" (horizontal) axis. This value is an integer between 0 and 320. When the object is not detected,the algorithm returns -1. The operation of the "Y position" block are the same, but returns the position respect the "Y" (vertical) axis. The value returned is between 0 and 240.

Turtleart-followme-classic.png

When you know the color to "follow" (it occurs rarely, since the color varies under changing light conditions) you can use the "Follow RGB" block. This block sets the color directly to the algorithm. In all cases, the color has a threshold of 25 in each component set by default. With the "Threshold" block this value can be changed.

Turtleart-followme-specificcolor.png

The third option, is to use the "FollowMe" block that "follows" a generic color similar to that shown.

Turtleart-followme-turtlecolor.png

Videos of the plugin ongoing:

FollowMe plugin in TurtleArt - Part 1

FollowMe plugin in TurtleArt - Part 2

The code used in this videos:

Turtleart-followme-example-ongoing.png

WeDo

Tony Forster created a WeDo plugin based on the work of I.T. Daniher.

WeDo plugin.png

File:Wedo plugin.tar.gz WeDo plugin

Note: Check out https://github.com/itdaniher/WeDoMore/tree/master/udev for instructions on how to setup the proper permissions talk to the device.

Currency

This plugin adds a pallette of currency (notes and coins), these items can be acted on by arithmetic operators

Oz currency.png

File:Oz-coins.tar.gz Australian coins plugin
File:Oz-bills.tar.gz Australian bills plugin
File:Oz-coins-and-bills.tar.gz Australian coins and bills plugin
File:Colombia-currency.tar.gz Colombian peso plugin
File:Mexican-currency.tar.gz Mexican peso plugin
File:Paraguay-currency.tar.gz Paraguay Gurani plugin
File:Rwanda-currency.tar.gz Rwanda francs plugin
File:UY-currency.tar.gz Uruguayan peso plugin
File:US-bills.tar.gz US bills plugin
File:US-currency.tar.gz US dollar plugin

Nutrition

This is just a first rough pass at a plugin do calculations on the nutritional value of different food types. The plugin itself comes with some sample foods: apples, bananas, cookies, and cake. It is expected that the food choices will be customized by deployment. See https://www.choosemyplate.gov/SuperTracker/ for nutritional values (calories, protein, carbohydrates, fiber, and fat) of different foods.

Food-plugin.png

File:Food-plugin.tar.gz (Note: Requires TurtleBlocks v133 or greater)

Physics

This plugin allows you to construct a Physics model which can be saved to the Journal and run with the Physics Activity Activities/Physics

Physics pallette.jpg

Use these blocks to create objects that are added to the bodylist and jointlist of a Box2d database used by the Physics Activity. Objects are positioned by the turtle x,y and colored based on the current pen attributes. From left to right:

Note: The polygon must be 'normal', e.g., no crossed lines; no holes. Since Box2d does not support concave polygons, all polygons are converted to triangles (triangulation). (In Turtle Blocks, these triangles are shown by slight variations in color.)

Note: The current model is cleared whenever the Erase button is pressed or a Clean block is run.

Where to get the Physics plugin
File:Physics-plugin.tar.gz Physics plugin
Example

A simple gear and motor generated in Turtle Art:

TAGearTA.png TAGear.png

File:TAgear.ta File:Gear.physics

How to write a plugin

Your plugin should be placed in a subdirectory of the plugins directory. In that subdirectory, you need to create a .py file that defines a subclass of the Plugin class. The directory and .py file must have the same name and the subclass must also have the same name, with the additional requirement that the first letter of the class name be capitalized.

For example:

from plugins.plugin import Plugin
class Camera_sensor(Plugin):

In that subdirectory, you will also need a __init__.py file (which can be empty) and optionally, an icon subdirectory for your palette icon.

Turtle Art calls the __init__ method when starting up and traps import errors as its means to determine whether or not a plugin has the resources it needs to run. (You may want to remove this exception handler when debugging your plugin. It is in the _init_plugins method in tawindow.py.) It then calls the setup method when creating the palettes. It calls the start method whenever a stack of blocks is run and the stop method when execution is over. Also, there are methods for goto_background, return_to_foreground, and quit. (These methods are typically ignored.)

Adding a new palette is simply a matter of:

   palette = make_palette('mypalette',  # the name of your palette
                          colors=["#00FF00", "#00A000"],
                          help_string=_('Palette of my custom commands'))

For example, if we want to add a new turtle command, 'uturn', we'd use the add_block method in the Palette class.

   palette.add_block('uturn',  # the name of your block
                     style='basic-style',  # the block style
                     label=_('u turn'),  # the label for the block
                     prim_name='uturn',  # code reference (see below)
                     help_string=_('turns the turtle 180 degrees'))
   # Next, you need to define what your block will do:
   # def_prim takes 3 arguments: the primitive name, the number of
   # of arguments, 0 in this case, and the function to call, in this
   # case, the canvas function to set the heading.
   self.tw.lc.def_prim('uturn', 0, lambda self: self.tw.canvas.seth(self.tw.canvas.heading + 180))


That's it. When you next run Turtle Art, you will have a 'uturn' block on the 'mypalette' palette.

You will have to create icons for the palette-selector buttons. These are kept in the icons subdirectory. You need two icons: mypaletteoff.svg and mypaletteon.svg, where 'mypalette' is the same string as the entry you used in instantiating the Palette class. Note that the icons should be the same size (55x55) as the others. (This is the default icon size for Sugar toolbars.)


Turtle Art with Arduino

There are several efforts to develop Turtle Art support for Arduino.

Andrés Aguirre is part of the Butiá team in Montevideo:

We have released the 1.0 version of the sources, which has full integration with tortugarte (http://www.fing.edu.uy/inco/proyectos/butia/publicaciones.html). Last month we gave away nearly 30 Butiá robots in a robotic event organized by the University. These robots were given to secondary schools throughout the country, in this event we gave some tutorials and exercises to do with our help. One of the schools made a great line follower in tortugarte ;) : http://www.youtube.com/watch?v=Szp0LWLyPIg Then on the second day we give some tutorials and some children really enjoyed the experience, like Pedro a 10 year old child who really has programming skills! http://www.flickr.com/photos/butiarobot/5059177334/ http://www.youtube.com/aguirrea#p/u/7/p0y11iyhFko
In future months we will go to the schools where we give the robots to continue teaching and giving new challenges. If you would like to see more about Butiá, we have a flickr site: http://www.flickr.com/photos/butiarobot/ and also a web page: http://www.fing.edu.uy/inco/proyectos/butia

examples

Blink led in Arduino pin 13

descriptions

Based on the existing version on TurtleArt with Arduino: http://wiki.sugarlabs.org/go/Development_Team/Arduino#Turtle_Art

and the base work for refactoring adapting the Arduino version to the latest Turtleart structure: http://git.sugarlabs.org/projects/turtleart/repos/refact-for-arduino

This version is based on the mainline version of TurtleArt 0.86

The Arduino functionality was corrected from previous versions:

It requires the Firmata protocol to be uploaded to the Arduino board. Use the latest Firmata version (2.1 as of now) downloaded from the Firmata page (firmata.org) The Firmata version included with the Arduino IDE has some inconsistencies.

This version has english and spanish translations. Other localizations may require some code adjustments due to inconsistencies in the file naming scheme.

downloads

The .xo file can be downloaded from here.

Getting it working

For hints on getting it working on different Sugar versions see http://tonyforster.blogspot.com/2010/10/arduino-fork-of-turtle-art.html

TurtleArt (sugar) + icaro = Tortucaro

See http://proyectofedora.org/argentina/?p=320

About Turtle Art

Activity-turtleart.png

Turtle Art is a Fructose module, so it is included as part of the standard Sugar (Sucrose = Glucose+Fructose) distribution.

Background

Turtle Art was written by Brian Silverman and is maintained by Walter Bender. Arjun Sarwal added the sensor features. Luis Michelena contributed to the "named" action and box blocks. Tony Forster has been the lead test engineer and has really stretched the boundaries of Turtle Art. Raúl Gutiérrez Segalés has been a major contributor to the refactoring of the Turtle Art code base starting with Version 0.83.

Links

Sugar Activity Library

Sources

Manuals & Guides

Galleries

Feedback

Blogs

Other wiki pages

Release notes

Video

Bugs

i18n

Turtle Art currently has support for: de, el, en, es, fa_AF, fi, fr, hi, it, mn, nl, ps, pt, ru, sl, sv, ta, tr, vi, and zh_TW

(See our Pootle server for details about how to translate Turtle Art into your language.)

Reporting bugs

Please file bug reports here.

Looking under the hood

Turtle Art projects are stored as a .ta file contains a json-encoded serialization of the project.

The json encoding of a repeat 4 forward 100 right 90 project:

[
 [0,"repeat",331,158,[null,1,2,null]],
 [1,["number","4"],417,167,[0,null]],
 [2,"forward",426,207,[0,3,4]],
 [3,["number","100"],500,216,[2,null]],
 [4,"right",426,246,[2,5,null]],
 [5,["number","90"],500,255,[4,null]],
 [-1,"turtle",0,0,0,0,50,5]
]

The basic structure of the encoding is a list of lists, where each block has these elements:

  1. block number
  2. block name or [block name, block value]
  3. x position (deprecated)
  4. y position (deprecated)
  5. list of connections to other blocks

Turtles are encoded at the end of the list:

  1. -1
  2. turtle or [turtle, turtle name]
  3. x position
  4. y position
  5. heading
  6. pen color
  7. pen shade
  8. pen width

Modifying Turtle Art

Turtle Art is under the MIT license. You are free to use it and learn with it. You are also encourage to modify it to suit your needs or just for a further opportunity to learn.

Much of the motivation behind the Version 83 refactoring of the code was to make it easier for you to make changes. Most changes can be confined to two modules: taconstants.py and talogo.py. The former defines the blocks and palettes; the latter defines what code is executed by a block.

Note: As of Version 106, there is also support for plugins. If you can use the plugin mechanism to add support for additional devices, e.g., Arduino, or for making modifications such as are described below without making changes to the standard code base. (The advantage to the latter is that your changes will remain intact even after you upgrade to a newer version.)

The tabasics.py file contains the constants that by-in-large determine the behavior of Turtle Art. Notably, the block palettes are defined below. If you want to add a new block to Turtle Art, you could simply add a block of code to that file or to turtle_block_plugin.py, which contains additional blocks. (Even better, write your own plugin!!)

Adding a new palette is simply a matter of:

   palette = make_palette('mypalette',  # the name of your palette
                          colors=["#00FF00", "#00A000"],
                          help_string=_('Palette of my custom commands'))

For example, if we want to add a new turtle command, 'uturn', we'd use the add_block method in the Palette class.

   palette.add_block('uturn',  # the name of your block
                     style='basic-style',  # the block style
                     label=_('u turn'),  # the label for the block
                     prim_name='uturn',  # code reference (see below)
                     help_string=_('turns the turtle 180 degrees'))

Next, you need to define what your block will do. def_prim takes 3 arguments: the primitive name, the number of arguments—0 in this case—and the function to call—in this case, the canvas.seth function to set the heading.

   self.tw.lc.def_prim('uturn', 0,
       lambda self: self.tw.canvas.seth(self.tw.canvas.heading + 180))

That's it. When you next run Turtle Art, you will have a 'uturn' block on the 'mypalette' palette.

You will have to create icons for the palette-selector buttons. These are kept in the icons subdirectory. You need two icons: mypaletteoff.svg and mypaletteon.svg, where 'mypalette' is the same string as the entry you used in instantiating the Palette class. Note that the icons should be the same size (55x55) as the others. (This is the default icon size for Sugar toolbars.)

How to write a plugin

In Spanish: http://valentinbasel.fedorapeople.org/pdfs/turtle_art.pdf

Packaging

TurtleArt has both a Sugar and GNOME front-end. To package TurtleArt for your distro the following layout is recommended:

turtleart-core

TurtleArt/

icons/

images/

locale/

utils/

setup.py

NEWS

COPYING

turtleart-data

pysamples/

samples/

samples/images

turtleart-sugar

activity/

TurtleArtActivity.py

turtleart-gnome

collaboration/

turtleart.py

turtleart.desktop

gnome-plugins/

plugins

Included in each plugin would be:

plugins/plugin.py

plugins/__init__.py

turtleart-extras

plugins/turtle_blocks_extras/

plugins/turtle_blocks_extras/icons/

turtleart-camera

plugins/camera_sensor/

plugins/camera_sensor/icons/

turtleart-sensors

plugins/audio_sensors/

plugins/audio_sensors/icons/

turtleart-rfid

plugins/rfid/

plugins/rfid/icons/

plugins/rfid/serial/

turtleart-butia

plugins/butia/

plugins/butia/icons

plugins/butia/butia_support/

plugins/butia/butia_support/bobot/

plugins/butia/butia_support/bobot/drivers

plugins/butia/butia_support/bobot/lib

plugins/butia/butia_support/bobot/share

turtle-art currency

plugins/currency/

plugins/currency/icons

plugins/currency/images

Note: Requires v113 or greater

File:Oz-coins.tar.gz Australian coins plugin
File:Oz-bills.tar.gz Australian bills plugin
File:Oz-coins-and-bills.tar.gz Australian coins and bills plugin
File:US-currency.tar.gz US dollar plugin
File:Rwanda-currency.tar.gz Rwanda francs plugin
File:Paraguay-currency.tar.gz Paraguay Gurani plugin
File:Colombia-currency.tar.gz Colombian peso plugin
File:Mexican-currency.tar.gz Mexican peso plugin
File:US-bills.tar.gz US bills plugin
File:UY-currency.tar.gz Uruguayan peso plugin

turtleart-physics

plugins/physics/

plugins/physics/icons

File:Physics-plugin.tar.gz Physics plugin

Credits

Personal tools
Namespaces
Variants
Actions
Sugar
Projects
Teams
Local Labs
Using the Wiki
Google translations