Sunday, November 6, 2011

PEBL Programming Tutorial II

This is Part II of a series of tutorials on PEBL

In this PEBL Programming tutorial, we will cover the basics of creating a window and displaying text there.  As in the previous post, we will use a single Start function. We start by creating a window, and assigning it to a variable we call 'win'.

define Start(p)
{
    win <- MakeWindow("black") #You can set the color of the window at startup
    label <- EasyLabel("one two three", 100,100, win,18)
    Draw()
    WaitForAnyKeyPress()
}





Just as a variable can store a number or text string, it can hold more complex data structures.  One important one is a window objectc.  You create a window with the MakeWindow() function, and later if you want to add things to it, you'll need the object later, so you store it in a variable (typically called something like win).

The next line creates a similar object called a label.  Labels are single lines of text, which involve a specific font, a specific text string, and a location.  You can create labels with a lot of flexibility using the MakeLabel() function, but typically the EasyLabel() function we use here is enough.  The first argument is the text, the next two arguments are the x and y position, in pixels (from the upper left corner of the screen), the next argument is a variable storing the window, and the last argument is the font size that should be used.

In order for the label to show up, you need to issue a Draw() command.  Pending changes will not get Drawn to the screen without this command.  It is useful because you may want to add several labels or other graphical objects to the screen and have them all appear at once.  Using the Draw() command allows you to do this.

Finally, once the script gets done with all its commands, it will end immediately.  Thus, without something to pause the program after the Draw command, you will only see a flash.    One way to pause is to use the function WaitForAnyKeyPress(), which will (as you might guess), wait for a key to be pressed before continuing.  Another function you can use is Wait(), which waits a specified number of milliseconds before continuing.


In order to make changes to the label, you can edit different properties of the label and issue a Draw() command.  For example, the .x and .y properties change the position of the object on the window.  And the .text property changes the text of the label:

define Start(p)
{
    win <- MakeWindow("black") #You can set the color of the window at startup
    label <- EasyLabel("one two three", 100,100, win,18)
    Draw()
    Wait(500) ##This waits 500 ms before continuing
    #Do a mini-animation
    label.x <- 120
    Draw()
    Wait(100)
    label.x <- 140
    Draw()
 
    Wait(100)
    label.x <- 160
    Draw()
    label.text <- "Done"
    Draw()
    WaitForAnyKeyPress()
}


A basic animation of the script is shown here:


This tutorial series will continue in two weeks.

No comments: