BFOIT - Introduction to Computer Programming

New TurtleGraphics Features - February 13, 2014

Introduction

I must first apologize for how long it has taken to provide an update to BFOIT's turtle graphics for Java.  TG has seen many enhancements since I first broke out its turtle graphics support for use in a Java program.  I just didn't think it would be of much interest to anyone.  But over the past year there have been so many ftp downloads I've decided to get a new version out.

There are two areas that have changed.  First, the graphics primitives have been expanded to include images/pictures and additional fonts.  Second, keyboard and mouse input stuff was extended and renamed.

New Turtle Graphics Functionality

The following list of methods details the additional graphical functionality.  See the TurtleGraphicsWindow javadoc webpage for updated, complete documentation.

colorsunder

int[ ] colorsunder()
Return an array of the unique colors this turtle's image is positioned over.

See Also:
pencolor(), setpc(int), setpencolor(int)

labelwidth

int labelwidth(String label)
Return the width of the provided String, when rendered in the current font, in turtle steps (pixels).

Parameters:
label - text to be measured.

See Also:
label(String), setlabelfont(int), setlabelheight(int)

loadpicture

boolean loadpicture(String fileName)
Draw a picture from a file onto the background of the graphics canvas. Returns true if successful, * otherwise false.

Parameters:
fileName - String that identifies the source image file

See Also:
clean() setbg(int)

loadshape

boolean loadshape(String fileName, int shapeNum)
Load an image file; it can then be used for a turtle's shape, its image. Returns true if successful, otherwise false.

Parameters:
fileName - String that identifies the source image file
shapeNum - an integer that is between FIRST_USER_SUPPLIED_SHAPE and LAST_USER_SUPPLIED_SHAPE, inclusive. This number can then be used with setshape() to change the turtle's appearance.

See Also:
setshape(int)

pencolor

public int pencolor()
Return the color the pen is currently drawing in.

See Also:
setpc(int), setpencolor(int)

setbg

public void setbg(int colorNum)
Sets the background color of the graphics canvas.

*NOTE* a side-effect of changeing the background color is that all current graphics is cleared.

Parameters:
colorNum - Either a built-in Logo color number in the range 0-31, else a 24-bit RGB color value.

	Number Color        Number Color        Number Color
	------ ----------   ------ ----------   ------ ---------
	   0   black          11   aqua           22   gold
	   1   blue           12   salmon         23   lightgray
	   2   green          13   violet         24   peru
	   3   cyan           14   orange         25   wheat
	   4   red            15   grey           26   palegreen
	   5   magenta        16   navy           27   lightblue
	   6   yellow         17   skyblue        28   khaki
	   7   white          18   lime           29   pink
	   8   brown          19   steelblue      30   lawngreen
	   9   light brown    20   chocolate      31   olive
	  10   forest         21   purple
			
Color numbers greater than 31 will be assumed to be RGB values. Assuming bits are numbered 0-31, left to right, the red component is in bits 8-15, the green component in bits 16-23, and the blue component in bits 24-31. The actual color used in rendering will depend on finding the best match given the color space available for a given display.

See Also:
loadpicture(String), setpencolor(int), BLACK, BLUE, AQUA, BROWN, CHOCOLATE, CYAN, GOLD, FOREST, GRAY, GREEN, KHAKI, LAWNGREEN, LIGHTBLUE, LIGHTGRAY, LIME, MAGENTA, NAVY, OLIVE, ORANGE, PALEGREEN, PERU, PINK, PURPLE, RED, SALMON, SKYBLUE, STEELBLUE, TAN, VIOLET, WHEAT, WHITE, YELLOW

setlabelfont

public void setlabelfont(int fontNumber)
Set the font for LABELs, text drawn on the graphics canvas by the turtle.

Parameters:
fontNumber - an integer representing a font face and font style.

	Number   Font         Style
	------   ----------   -----------
	   0     Courier      Plain
	   1     Courier      Bold
	   2     Courier      Italic
	   3     Courier      Bold Italic
	   4     Sans Serif   Plain
	   5     Sans Serif   Bold
	   6     Sans Serif   Italic
	   7     Sans Serif   Bold Italic
	   8     Serif        Plain
	   9     Serif        Bold
	  10     Serif        Italic
	  11     Serif        Bold Italic
			
See Also:
label(String), labelwidth(String), setlabelheight(int), COURIER, COURIER_BOLD, COURIER_ITALIC, COURIER_BOLD_ITALIC, SANS_SERIF, SANS_SERIF_BOLD, SANS_SERIF_ITALIC, SANS_SERIF_BOLD_ITALIC, SERIF, SERIF_BOLD, SERIF_ITALIC, SERIF_BOLD_ITALIC

setshape

public boolean setshape(int shapeNum)
Sets the shape of the turtle - its pixel image. Returns true if shape successfully set, else false failure.

Parameters:
shapeNum - small positive number for either a built-in shape (see constants (e.g., BALL, BOX, etc...) or a user-supplied image via loadShape() method.

	 Number  Shape
	 ------  --------
	    0    Turtle
	    1    Arrow
	    2    Ball
	    3    Box
	    4    Cross
	    5    Triangle
	    6    Diamond
			
See Also:
loadshape(String, int), stamp(), ARROW, BALL, BOX, CROSS, DIAMOND, TRIANGLE, TURTLE

setshape

public boolean setshape(int shapeNum, int[ ] params)
Sets the shape of the turtle - its pixel image. Returns true if shape successfully set, else false failure.

Parameters:
shapeNum - small positive number for either a built-in shape (see constants (e.g., BALL, BOX, etc...) or a user-supplied image via loadShape() method.
params - an optional int array containing sizing information hints, e.g., radius of a ball, width and height of a box, etc...

                             Optional Size
        Number   Shape         Parameters
        ------   --------    -------------
           0     Turtle
           1     Arrow       width, height
           2     Ball        diameter
           3     Box         width, height
           4     Cross       width, height
           5     Triangle    width, height
           6     Diamond     width, height
                        
See Also:
loadshape(String, int), stamp(), ARROW, BALL, BOX, CROSS, DIAMOND, TRIANGLE, TURTLE

shapeheight

public int shapeheight()
Return the height of the current image of the turtle, as it appears in its current heading.

See Also:
setshape(int), setshape(int, int[ ])

shapewidth

public int shapewidth()
Return the width of the current image of the turtle, as it appears in its current heading.

See Also:
setshape(int), setshape(int, int[ ])

shownp

public boolean shownp()
Return true if this turtle's image is being displayed on the graphics canvas, else return false.

See Also:
hideturtle(), ht(), showturtle(), st()

stamp

public void stamp()
Draw the current turtle's image onto the graphics canvas.

See Also:
setshape(int), setshape(int,int[ ])

Keyboard and Mouse Input

Previously there were three methods that could be overridden in order to gain access to keyboard and mouse input: keypressed(int keyNum), mouseClicked(), and mouseMoved().  As the capabilities of TG have grown over the past couple of years, its use as an introduction to Java programming has improved.  Changes made recently, to support writing programs that can replace Java applets in the Logo lessons, have forced me to rename the methods and symbolic constants associated with keyboard and mouse input.

Here is a list of the new keyboard and mouse methods that you should override to receive input events.

tgKeyPressed

void tgKeyPressed(int keyNum)
TurtleGraphicsWindow implements the TGKeyHandler interface and registers with TGCanvas to receive keyboard key events.

Override this method to do something when a key on the keyboard is pressed while the graphics canvas is active, has focus.

Parameters:
keyNum - an integer representing a key identifier, either a character or an action key code (e.g., arrow keys)

See Also:
TGKeyHandler.ALT, TGKeyHandler.CONTROL, TGKeyHandler.DOWN_ARROW, TGKeyHandler.LEFT_ARROW, TGKeyHandler.RIGHT_ARROW, TGKeyHandler.SHIFT, TGKeyHandler.UP_ARROW,

tgKeyReleased

void tgKeyReleased(int keyNum)
TurtleGraphicsWindow implements the TGKeyHandler interface and registers with TGCanvas to receive keyboard key events.

Override this method to do something when a key on the keyboard is released while the graphics canvas is active, has focus.

Parameters:
keyNum - an integer representing a key identifier, either a character or an action key code (e.g., arrow keys)

See Also:
TGKeyHandler.ALT, TGKeyHandler.CONTROL, TGKeyHandler.DOWN_ARROW, TGKeyHandler.LEFT_ARROW, TGKeyHandler.RIGHT_ARROW, TGKeyHandler.SHIFT, TGKeyHandler.UP_ARROW,

tgKeyTyped

void tgKeyTyped(char keyChar)
TurtleGraphicsWindow implements the TGKeyHandler interface and registers with TGCanvas to receive keyboard key events.

Override this method to do something when a key on the keyboard which generates a character is pressed and released while the graphics canvas is active, has focus.

Parameters:
keyChar - a character generated by a keyboard key

tgMouseClicked

void tgMouseClicked(int x, int y)
TurtleGraphicsWindow implements the TGMouseHandler interface and registers with TGCanvas to receive mouse events.

Override this method to do something when the left mouse button is clicked in the graphics canvas when it is active.

Parameters:
x - X coordinate of mouse's location on the graphics canvas
y - Y coordinate of mouse's location on the graphics canvas

tgMouseMoved

void tgMouseMoved(int x, int y)
TurtleGraphicsWindow implements the TGMouseHandler interface and registers with TGCanvas to receive mouse events.

Override this method to do something when the mouse is moved within the graphics canvas when it is active.

Parameters:
x - X coordinate of mouse's location on the graphics canvas
y - Y coordinate of mouse's location on the graphics canvas

Example Programs

Here are three programs which demonstrate use of some of the new features.

Spiral Of Boxes

TGWexample1.java does a bunch of drawing. A box is drawn repetitively (30 times) as the turtle turns in a full circle. These 30 boxes form 60 isosceles triangles with their vertex angle at 0,0 (or HOME).

Then, two more for-loops fill the triangles with Logo's built-in colors (except for black and white). The first loop fills every other triangle in a clockwise direction with ascending color numbers. The second loop fills in the remaining triangles with descending color numbers.

Keyboard and Mouse Interaction

The following program (TGWexample2.java) demonstrates use of the keyboard and mouse to control the turtle, described above.

The arrow keys, which do not generate characters, are processed in the tgKeyReleased() method.  The left/right arrow keys rotate the turtle.  The up/down arrow keys move the turtle forward and backward respectively.

The 'u' and 'd' keys generate characters and so are processed in the tgKeyTyped() method.  These keys lift and lower the turtle's pen.

The mouse can be used to jump the turtle to a point on the graphics canvas.  The tgMouseClicked() method simply moves the turtle to where the mouse is when its left button is pressed/released.

Here is the source code. It is also in the TGW_Src.jar or TurtleGraphics.zip files you can download (see: Java TurtleGraphics Source Code).


   class TGWexample2 extends TurtleGraphicsWindow
   {

      public void tgKeyReleased(int keyNum)
      {
         switch ( keyNum )
         {
            case TGKeyHandler.DOWN_ARROW:
               back( 5 );
               break;
            case TGKeyHandler.LEFT_ARROW:
               left( 5 );
               break;
            case TGKeyHandler.RIGHT_ARROW:
               right( 5 );
               break;
            case TGKeyHandler.UP_ARROW:
               forward( 5 );
               break;
         }
      }

      public void tgKeyTyped(char keyChar)
      {
         switch ( keyChar )
         {
            case 'd':
	       setpencolor( BLACK );
               pendown();
               break;
            case 'u':
	       setpencolor( WHITE );
               penup();
               break;
         }
      }

      public void tgMouseClicked( int x, int y )
      {
         System.out.println( "tgMouseClicked( " + x + ", " + y + ")" );
         setxy( x, y );
      }

      public static void main(String[] args)
      {
         TGWexample2 me = new TGWexample2();
         me.setpensize( 8 );
         me.setshape( ARROW );
      }

   } // end class TGWexample2
			

Example of Loading and Displaying Pictures

The following program (TGWexample3.java) demonstrates loading a .jpg image file onto the background of the graphics canvas and loading a .png file for use as the turtle's image.


   class TGWexample3 extends TurtleGraphicsWindow
   {

      private void drawScene()
      {
         boolean status = loadpicture( "Clouds.jpg" );
         if ( ! status )
         {
            System.out.println( "loadpicture() failed" );
            return;
         }
         status = loadshape( "Parrot.png", FIRST_USER_SUPPLIED_SHAPE );
         if ( ! status )
         {
            System.out.println( "loadshape() failed" );
            return;
         }
         status = setshape( FIRST_USER_SUPPLIED_SHAPE );
         if ( ! status )
            System.out.println( "setshape() failed" );
      }

      public static void main(String[] args)
      {
         TGWexample3 me = new TGWexample3();
         me.drawScene();
      }

} // end class TGWexample3
			

Finally

Checkout details at:

Public Domain Mark
This work (BFOIT: Introduction to Computer Programming, by Guy M. Haas),
identified by Berkeley Foundation for Opportunities in IT (BFOIT),
is free of known copyright restrictions.