Programming Basics: A website for teaching people how to program
 

Programming Basics: Guide to Creating Your Own Exercises

This guide describes how the exercises in Programming Basics work, so as to help you create your own exercises. Exercise files are currently only supported by the Java version of the Programming Basics editor (this is the one that you can download from the Downloads section of the site and the one that appears when you have recent version of Java installed and visit the site). Much of the functionality described in this document is still in development, so it may change in future versions of the website. If you are creating exercises for a classroom setting, you may want to download a copy of the Programming Basics editor in advance so that students will have a version of the editor available that is compatible with your exercises.

Basic Graphics

The Programming Basics website currently offers some basic functionality for handling user interfaces and graphics. To draw any graphics, you first have to create a new window where you can do your drawing. You do this by calling the function ui.window(), which creates a new window and returns it to you. The window() function lets you optionally specify a name for the window and specify a fixed width and height for the window. Once you have the window, you must call the method setUseCartesianCoordinates(true) in order to configure the window for use.

win = ui.window("My Window", 200, 200);
win.setUseCartesianCoordinates(true);

// We use a sleep command to pause the program for 2s so that
// you can see the window before the program ends
sleep(2);

The window object accepts various drawing commands. Currently, the windows use a Cartesian coordinate system where the origin point (0,0) is in the lower-left of the window. Having the origin be in the lower-left is consistent with how things are taught in most math classes. In the future, Programming Basics may switch to having the origin in the upper-left, which is more consistent with modern computer graphics libraries.

To draw a line near the bottom of a window, you would use the code shown below. The window object has a drawLine() method for drawing lines. That functions expects the x,y coordinates of two points that form a line and a color for the line. To get a color, you need to use the ui.color() function. The function takes a string that encodes a color using the standard html/css color format.

// Create a window of size 100x100
win = ui.window(100, 100);
win.setUseCartesianCoordinates(true);

// Draw a blue line from (0,5) to (80, 5)
win.drawLine(0, 5, 80, 5, ui.color("#0000ff"));

sleep(2);

A brief reference of all the graphics and user interface functionality is available at the end of this document.

Attachments

Some exercises need to make use of image files for their graphics. For security reasons, programs and libraries run in the Programming Basics editor cannot access files. Instead, these images must be bundled with the exercises. This is done using attachments.

The Programming Basics editor only lets you to modify the attachments of programs that have been saved to disk. So to use attachments, you must either save your work first or open an existing on-disk program file.

To work with attachments, go to the File...Attachments... menu. From there, you can take existing image files that you have on-disk and add them as an attachment to your program.

Once an image file is attached to your program, you can access it using the openAttachmentImage() function. For example, if you added an image called smiley.png to your program, you can display that image using the code below.

// Get the image
img = openAttachmentImage("smiley.png");

// Open a window
win = ui.window();
win.setUseCartesianCoordinates(true);

// Display the image
win.drawImage(img, 10, 10);

sleep(2);

Libraries

Libraries allow you to run some JavaScript code before the main program code runs. This allows you to configure the coding environment with extra functions and objects that students can use in their exercises. Although you could include all this code in the main program itself, some students might find this confusing, which is why the library functionality has been provided.

As with attachments, the Programming Basics editor only lets you to modify the libraries of programs that have been saved to disk. So to use libraries, you must either save your work first or open an existing on-disk program file.

To work with libraries, go to the File...Libraries... menu. From there, you can add text files containing library code to your program. The Programming Basics editor prefers text files that are in the UTF-8 format (in Windows Notepad, when saving files, you can change the encoding to be UTF-8). If the text files containing your code are already encoded in UTF-8, you can add them to your program using the "Add UTF-8" button. If you aren't sure about the encoding of your file, you can add the text file as a library using the "Add" button, and the editor will try to automatically convert the files to UTF-8.

Once some libraries have been added to a program, these libraries will be run, in order, each time that the program is run.

Internationalization

The Programming Basics editor runs a modified version of the Mozilla's Rhino JavaScript engine. The editor is able to run a multilingual version JavaScript known as Babylscript. This allows code to be written in French, Chinese, Arabic, or other non-English languages.

Normal English JavaScript code will not run correctly in the Spanish version of JavaScript. As such, if you want your library code to run properly in non-English versions of Programming Basics, you have to specify that your libraries should use a specific language version. You do this by adding the following to the top of each of your library files:

---en---

This tells the Programming Basics editor to run the library code in using the English version of JavaScript (if your library code is written using a non-English version of JavaScript, you should replace en with the language code that corresponds with the language you want).

The functions and objects that you create in your library code can be given alternate names for different languages. For example, if you a have a function draw() and you would like the function to have a different name in French, you would use the following code:

// In French, use dessiner() for the draw() function
this["fr":"dessiner"] = "draw";

Currently, there is no way to provide different language versions for the main program code in an exercise. If you want an exercise to have different initial program code depending on the langauge, you need to create different exercise files for each language.

Sample

In this section, we will give an example of how you might create an exercise for some students. Suppose you are creating an exercise where students will create some sort of card game. To make things simpler for the students, you want to give them some code for drawing cards on the screen.

To start, you will write your code in the Programming Basics editor so that you can test to see if your drawing code works correctly. In this case, you discover that you can draw cards without using image files if you use the special characters for the suits of cards. Since you don't need image files, you have no need to use attachments.

win = ui.window(150, 100);
win.setUseCartesianCoordinates(true);
win.drawRect(0,0,150,100, ui.color("green"));

// Draws a picture of a card on the window win at position (x,y)
//   value is from 1-13 
//   suit is from 1-4 (for hearts, diamonds, clubs, and spades)
//
function drawCard(x, y, value, suit)
{
   var suits = ['\u2665', '\u2666', '\u2663', '\u2660'];
   var vals = ['A','2','3','4','5','6','7','8',
      '9','10','J','Q','K'];
   var fontFamily = ui.isHTML5 ? "sans-serif" : "SansSerif";
   var font = win.getFontWithPixelSize(fontFamily, 
      true, false, 15);
   win.drawRect(x, y, x+27, y+37, ui.color("black"));
   win.drawRect(x+1, y+1, x+26, y+36, ui.color("white"));
   var color = ui.color("black");
   if (suit <= 2)
      color = ui.color("red");
   win.drawString(x+5, y+20, vals[value-1], font, color);
   win.drawString(x+5, y+5, suits[suit-1], font, color);
}

drawCard(5,  10, 10, 1);
drawCard(35, 10, 1, 2);
drawCard(65, 10, 12, 3);
drawCard(95, 10, 8, 4);

sleep(2);

If you were to run the above program, this is what you would see:

You want the students to focus on their own programs and not be distracted by the complicated code for drawing the cards on the screen. So you should take out that code and put it in a library. First, you would cut&paste the code in italics into a text file, and put a ---en--- at the start of the file. Students might create their own variable called win, which will conflict with the variable in the library, so to be safe, you should also rename the win variable to _win. Then, you can import the text file as a library.

---en---
_win = ui.window(150, 100);
_win.setUseCartesianCoordinates(true);
_win.drawRect(0,0,150,100, ui.color("green"));

// Draws a picture of a card on the window win at position (x,y)
//   value is from 1-13 
//   suit is from 1-4 (for hearts, diamonds, clubs, and spades)
//
function drawCard(x, y, value, suit)
{
   var suits = ['\u2665', '\u2666', '\u2663', '\u2660'];
   var vals = ['A','2','3','4','5','6','7','8',
      '9','10','J','Q','K'];
   var fontFamily = ui.isHTML5 ? "sans-serif" : "SansSerif";
   var font = _win.getFontWithPixelSize(fontFamily, 
      true, false, 15);
   _win.drawRect(x, y, x+27, y+37, ui.color("black"));
   _win.drawRect(x+1, y+1, x+26, y+36, ui.color("white"));
   var color = ui.color("black");
   if (suit <= 2)
      color = ui.color("red");
   _win.drawString(x+5, y+20, vals[value-1], font, color);
   _win.drawString(x+5, y+5, suits[suit-1], font, color);
}

That leaves the following code as the main program that the students would see when they do the exercise:

drawCard(5,  10, 10, 1);
drawCard(35, 10, 1, 2);
drawCard(65, 10, 12, 3);
drawCard(95, 10, 8, 4);

Unfortunately, the resulting program doesn't leave things on the screen long enough for students to see what happened. In that case, you may want to put code at the end of the library which will pause the program before it exits.

addUnloadListener(function() {
   sleep(0.5);
   var button = new ui.Button('Click to end program');
   var w = button.getWidth();
   var h = button.getHeight();
   _win.add(button);
   button.setPos(150 / 2 - w / 2, 100 / 2 - h / 2);
   while (!button.wasClicked() && !_win.wasClosed()) { sleep(0.1); }
   _win.close();
});

Technical Aspects of the Exercise Files

The program files saved by the Programming Basics editor are simply .tar files. You can open them and inspect them using a standard untar program. The main program code is saved in tha tar file under the name "code/main.js". This program is encoded in UTF-8 format. The first two lines at the beginning of the file are ignored by the Programming Basics editor (the first two lines are intended for language and locale information, but currently aren't used). Attachments are stored in the tar file with the prefix "attachments/". Similarly, library files are stored with the prefix "lib/".

It is possible to assemble your own Programming Basics exercise files by creating a tar file from scratch with appropriately named files.

Reference for Graphics and Other Functions

As noted as the start of the document, these interfaces may change in future versions of the Programming Basics website.

Graphics methods for the window object

drawRect(Number x1, Number y1, Number x2, Number y2, Color c)
Draws a rectangle with one corner at (x1,y1) and the other corner at (x2,y2) using the color c.
drawLine(Number x1, Number y1, Number x2, Number y2, Color c)
Draws a line between the points (x1,y1) and (x2,y2) using the color c.
drawText(Number x, Number y, String text, Color c)
Draws the string text to the screen at point (x,y) using color c.
Font getDefaultFont()
Returns a font object that describes the default font used by the window to draw text.
Font getFontWithPixelSize(String fontName, Boolean isBold, Boolean isItalic, Number sizeInPixels)
Returns a font object that can be used to draw text to the window with the specified size and style. isBold and isItalic can be set to true or false depending on the style that you want. sizeInPixels specifies the height of the font in pixels.
drawString(Number x, Number y, String text, Font font, Color c)
Draws the string text at point (x,y) using the given font and color.
{width: Number} measureString(String text, Font font)
Returns the measurements of the string text when displayed using the specified font. The measurements are returned in an array with a single property width specifying the width in pixels of the text when displayed.
Number breakString(Number width, String text, Font font)
This method checks whether a string will be wider than the given width when displayed. If the text is wider than the width, it will suggest a place where you can safely "break" the string into a separate line. It returns the number of characters from text that can be displayed on a single line using font font without exceeding the width width
drawImage(Image img, Number x, Number y)
Draws the image img at point (x,y). Images are discussed in more detail in the Attachments section of this document.
drawResizedImage(Image img, Number x, Number y, Number w, Number h)
Draws the image img at point (x,y), but resizes the image to fit the width w and height h
startBuffer()
If you draw a lot of things on the screen at once, sometimes it is too slow, and you can see the drawing take place. This is distracting when trying to make animations. To avoid this problem, you can gather all of your drawing steps together without showing anything by buffering them. Then later, you can draw them all to the screen in one step. This method starts the buffering of drawing commands.
endBuffer()
This method ends the buffering of drawing commands and displays the results of all the drawing.

User interface methods for the window object

setUseCartesianCoordinates(Boolean flag)
Configures the window object to use the Cartesian coordinate system where the origin is in the lower-left of the window.
close()
Closes the window.
Boolean wasClosed()
Returns true if the user has clicked on the close button of the window.
Boolean isKeyDown(Number key)
Checks if the key corresponding to the given key code is currently down.
Boolean wasKeyDown(Number key)
Checks if the key corresponding to the given key code was being pressed down sometime since the last time the programmer called this method.
[] getAllDownKeys()
Returns an array of all the keyboard keys currently being pressed down.
[] getAllPressedKeys()
Returns an array of the keyboard keys that were pressed since the last time this method was called.
add(Component component)
Adds a user interface component to the window. Currently, only buttons are supported.

UI and other miscellaneous functions

sleep(Number seconds)
The program will pause for the specified number of seconds. The pause time can be a decimal number like 0.2 or 3.6.
Image openAttachmentImage(String attachmentName)
Returns an Image object for the image attachment with the supplied name attachmentName.
addUnloadListener(function() f)
Provides a function to the Programming Basics editor that will be run when a program has finished running all of its code. This is useful for adding a pause before a program exits so that users can see the output of the program.
Returns a color object for the color specified in the html/css color string c. Colors can be specified using the form #rrggbb where rr,gg,bb represent the red, green, and blue components of a color respectively. These values can range from 0 to 255 and are expressed using hexadecimal digits. Alternately, common html/css/svg color names can be used instead like "black", "brown", "white", or "orange".
Window ui.window(optional String name, optional Number width, optional Number height)
Creates a new window.
Button ui.button(String label)
Creates a button with the specified label.

Button object methods

setPos(Number x, Number y)
Moves the button to position (x,y).
setSize(Number w, Number h)
Sets the width of the button to w and its height to h.
Number getWidth()
Returns the width of the button.
Number getHeight()
Returns the height of the button.
Boolean wasClicked()
Returns true if the button has been clicked on since the last time this method was called.

Programming Basics

E-mail | Sobre | Política de Privacidade