3. Program Object

Preview

In this chapter, we begin our overview of objects used to build the Small Basic programs.  For each object, we summarize the properties, methods and events.  Then, we build several example programs illustrating use of the object.  We begin with the Small Basic Program object.

Program Object

The Program object (or more properly class) helps with program execution.  We use it identify what folder your program is saved in, implement delays and stop the program.

Program Properties:

Directory
Gets the executing program's directory.

Program Methods:

Delay(milliseconds)
Delays program execution by the specified amount of milliseconds.

End()
Ends the program.

The Developer’s Reference Guide

This chapter is adapted from the book The Developer’s Reference Guide To Microsoft Small Basic by Philip Conrod and Lou Tylee.

To purchase this book in its entirety, please see the Computer Science For Kids web site.

Example 3-1.  Program Directory

Write a program that displays the directory (folder) your program is stored in.

Small Basic Code:

' Guide to Small Basic, Example 3-1 TextWindow.Title = "Example 3-1" TextWindow.WriteLine("Directory: " + Program.Directory)

Saved as Example 3-1 in  Guide to Small Basic\Programs\Chapter 3 folder.

Save and Run the program.  The program directory will be written in the text window:

Your directory will be different, assuming you saved your program in a folder of a different name.

Example 3-2.  Program Delay

Write a program that writes a line, delays a second, writes another line, then delays two seconds, before ending.

Small Basic Code:

' Guide to Small Basic, Example 3-2 TextWindow.Title = "Example 3-2" TextWindow.WriteLine("Line 1") Program.Delay(1000) TextWindow.WriteLine("Line 2") Program.Delay(2000)

Saved as Example 3-2 in  Guide to Small Basic\Programs\Chapter 3 folder.

Save and Run the program.  In the text window, you will see Line 1 display, a delay of 1 second (1000 milliseconds), Line 2 display, then a 2 second delay before the program ends:

Program End Method

In the short text window programs we have written, they end with this statement:

Press any key to continue…

This allows us to see the contents of the window before the program closes.

If you end a program with:

Program.End()

The “Press any key to continue…” statement will not be seen and the text window will close.

Example 3-3.  Program End

Repeat Example 3-2, but add an End statement.  That is, write a program that writes a line, delays a second, writes another line, then delays two seconds, before ending with an End statement.

Small Basic Code:

' Guide to Small Basic, Example 3-3 TextWindow.Title = "Example 3-3" TextWindow.WriteLine("Line 1") Program.Delay(1000) TextWindow.WriteLine("Line 2") Program.Delay(2000) Program.End()

Saved as Example 3-3 in  Guide to Small Basic\Programs\Chapter 3 folder.

Save and Run the program.  In the text window, you will see Line 1 display, a delay of 1 second (1000 milliseconds), Line 2 display, then a 2 second delay, then the text window will disappear.

Chapter Review

After completing this chapter, you should understand:

  • Use of the Property object.
  • How to identify your program directory.
  • How to implement a program delay.
  • How to stop a program and make the text window disappear.

Next, we look in more detail at the TextWindow object we have been using.

String Methods

Stuff for text methods

  • Small Basic offers a powerful set of methods to work with string type variables, which are very important in Small Basic.  These methods are associated with the Text object.
  • To determine the number of characters in (or length of) a string variable, we use the GetLength method.  Using MyString as example:

MyString = "Small Basic is fun!" LenString = Text.GetLength(MyString)
  • You can extract substrings of characters.  The GetSubText method is used for this task.  You specify the string, the starting position and the number of characters to extract.  This example starts at character 2 and extracts 6 characters:
MyString = "Small Basic is fun!" SubString = Text.GetSubText(MyString, 2, 6)
  • Perhaps, you just want a far left portion of a string.  Use the GetSubText method with a starting position of 1.  This example extracts the 3 left-most characters from a string:
MyString = "Small Basic is fun!" LeftString = Text.GetSubText(MyString, 1, 3)
  • To get the far right portion of a string, use the GetSubTextToEnd method.  Specify the character to start with and the right portion of the string is returned.  To get 6 characters at the end of our example, you would use:
MyString = "Small Basic is fun!" RightString = Text.GetSubTextToEnd(MyString, 13)
  • Many times, you want to convert letters to upper case or vice versa.  Small Basic provides two methods for this purpose:  ConvertToUpperCase and ConvertToLowerCase.  The ConvertToUpperCase method will convert all letters in a string variable to upper case, while the ConvertToLowerCase method will convert all letters to lower case.  Any non-alphabetic characters are ignored in the conversion.  And, if a letter is already in the desired case, it is left unmodified.  For our example (modified a bit):
MyString = "Read About Small Basic in 2010!” A = Text.ConvertToUpperCase(MyString) B = Text.ConvertToLowerCase(MyString)

The first conversion using ConvertToUpperCase will result in:

A = “READ ABOUT SMALL BASIC IN 2010!”

And the second conversion using ConvertToLowerCase will yield:

B = “read about small basic in 2010!”

Graphics Methods

  • All of our games will be “hosted” by the Small Basic graphics window.  To put anything in the graphics window, it must be “drawn” there using one of the many Small Basic graphics methods.  Even text has to be drawn!  Let’s take a look at these methods.
  • The coordinate system used by the graphics window is:

    The window is Width pixels wide and Height pixels high.  We use two values (coordinates) to identify a single pixel in the window.  The x (horizontal) coordinate increases from left to right, starting at 0.  The y (vertical) coordinate increases from top to bottom, also starting at 0.  Points in the region are referred to by the two coordinates enclosed in parentheses, or (x, y).

  • To draw lines and shapes, we use a pen.  You can choose color and width.  Lines of code that accomplish this task are:
GraphicsWindow.PenColor = Color GraphicsWindow.PenWidth = Width

where Color is the color your pen will draw in and Width is the integer width (a value of 1 by default) of the line (in pixels) drawn.  This pen will draw a solid line.  To specify a color, you use a color name like “Red”, “White” or “Blue”.  Appendix I lists the multitude of colors available with Small Basic.

  • The Small Basic DrawLine method is used to connect two points with a straight-line segment.  If we wish to connect the point (x1, y1) with (x2, y2), the statement is:

    GraphicsWindow.DrawLine(x1, y1, x2, y2)

    The line will draw in the current pen Color and Width.  Example that draws a blue line of width 1:

GraphicsWindow.PenColor = "Blue" GraphicsWindow.PenWidth = 1 GraphicsWindowGraphicsWindow.DrawLine(20, 50, 380, 280)
  • The Small Basic DrawRectangle method is used to draw a rectangle.  To draw a rectangle, we specify the upper left hand corner’s coordinate (x, y) and the width and height of the rectangle.  To draw such a rectangle in the graphics window:

    GraphicsWindow.DrawRectangle(x, y, width, height)

    The rectangle will draw with the current pen.  To draw a blue rectangle (pen width 2) with the upper left corner at (20, 50), width 150 and height 100, use this code:

GraphicsWindow.PenColor = "Blue" GraphicsWindow.PenWidth = 2 GraphicsWindow.DrawRectangle(20, 50, 150, 100)
  • The Small Basic DrawEllipse method is used to draw an ellipse.  To draw an ellipse, we specify the upper left hand corner’s coordinate (x, y) and the width and height of the ellipse.  To draw such an ellipse in the graphics window:

    GraphicsWindow.DrawEllipse(x, y, width, height)

    The ellipse will draw with the current pen.  To draw a green ellipse (pen width 3) with the upper left corner at (20, 50), width 150 and height 100, use this code:

GraphicsWindow.PenColor = "Green" GraphicsWindow.PenWidth = 3 GraphicsWindow.DrawEllipse(20, 50, 150, 100)
  • A brush is like a “wide” pen.  It is used to fill areas with a color.  It has a single property (Color).  To set the brush color, use:

    GraphicsWindow.BrushColor = Color

    A brush is ‘solid’ – filling areas completely with the specified color

  • To fill rectangles and ellipses with the current brush color, use the FillRectangle and FillEllipse methods.  They have the same arguments as DrawRectangle and DrawEllipse, respectively.
  • To add text information to the graphics window, we use the Small Basic DrawText method – yes, text is “drawn” to the window.  The DrawText method is:

    GraphicsWindow.DrawText(x, y, text)

    In this statement, text represents the string to print in the window and the point (x, y) is where the string will be located.  The string will draw in the graphics window using the current brush color using the default font.  Note this method uses the brush color, not the pen color – text is truly drawn like other graphics objects. 

  • Here’s an example using DrawText:
GraphicsWindow.BrushColor = "Blue" GraphicsWindow.DrawText(40, 100, "Isn't Small Basic fun?")

This puts the line “Isn’t Small Basic fun?” at (40, 100) in the graphics window.  The text will be blue in color.  By setting the (x, y) point, you can left or right justify the text, or center it horizontally and/or vertically by knowing the window dimensions.  The font size can be changed by setting the FontSize property and FontBold determines if the font is bold or not.

Shapes Objects

  • Related to graphics methods are Shapesobjects.  A Shapes object is a rectangular region we can add, move and remove within the graphics window.  Such an object makes animation (moving objects) very simple.  We can have shapes that are rectangles, ellipses and even images!  Let’s look at each.
  • To create a rectangular shape (MyRectangle) that is W pixels wide and  Hpixels high, use the AddRectangle method:

    MyRectangle = Shapes.AddRectangle(W, H)

    This will create a ‘bordered’ rectangle.  The current pen color and pen width establishes the rectangle’s border color, while the current brush color establishes the fill color.  By default, it will be put in the upper left corner of the graphics window.

  • Analogously, to create an elliptical shape (MyEllipse) that is W pixels wide and H pixels high, use the AddEllipse method:

    MyEllipse = Shapes.AddEllipse(W, H)

    This will create a ‘bordered’ ellipse.  The current pen color and pen width establishes the ellipse border color, while the current brush color establishes the fill color.  By default, it will be put in the upper left corner of the graphics window.

  • To create a shape with an image, we need two steps.  First, we must load the image, then create the shape.  Assume you have jpg image file (a digital photo) named MyImage.jpg.  (You can use other image files types too).  The file with this image must be in the same folder as your Small Basic program.  The image is loaded using the LoadImage method of the ImageList object:

    MyImage = ImageList.LoadImage(Program.Directory + "\MyImage.jpg")

    Then the image shape (MyImageShape) is created using:

    MyImageShape = Shapes.AddImage(MyImage)

    The shape will be placed in the upper left corner of the graphics window.

  • Moving Shapes objects in a graphics window is easy to do.  It is a simple two step process:  use some rule to determine a new position, then redraw it in this new position using the Shapes object Move method.  If you have a shape object named MyShape and you want to move it to (NewX, NewY), the code is:

    Shapes.Move(MyShape, NewX, NewY)

    This code will ‘erase’ MyShape at its current position, then ‘redraw’ it at the newly specified position.  Successive transfers (or moves) gives the impression of motion, or animation.

  • We will see many examples of using Shapesobjects in the game programs we build.  We will provide the image files for any Shapes requiring images.

Small Basic Methods

  • Small Basic offers a rich assortment of built-in methods that compute or provide various quantities.  The general form of a method is:

    ReturnedValue = ObjectName.MethodName(Arguments)

    where Arguments represents a comma-delimited list of information needed by MethodName to perform its computation.  Once the arguments are supplied to the method it returns a value (ReturnedValue) for use in an application. 

  • Some methods do not return a value, but only perform a task.  To use these methods, just type:

    ObjectName.MethodName(Arguments)

Math Methods

  • One set of methods we need are mathematical methods (yes, programming involves math!)  Small Basic provides a set of methods that perform tasks such as square roots, trigonometric relationships, and exponential functions.
  • Each of the Small Basic math functions comes from the Math class.  All this means is that each method name must be preceded by Math. (say Math-dot) to work properly.  The methods and the returned values are:

    Math Method Value Returned
    Math.Abs Returns the absolute value of a specified number.
    Math.Ceiling Gets an integer that is greater than or equal to the specified decimal number. For example, 32.233 will return 33.
    Math.Cos Returns a value containing the cosine of the specified angle in radians.
    Math.Floor Gets an integer that is less than or equal to the specified decimal number. For example, 32.233 will return 32.
    Math.GetDegrees Converts a given angle in radians to degrees.
    Math.GetRadians Converts a given angle in degrees to radians.
    Math.Log Gets the logarithm (base 10) value of the given number.
    Math.Max Returns the larger of two numbers.
    Math.Min Returns the smaller of two numbers.
    Math.NaturalLog Gets the natural logarithm value of the given number.
    Math.Pi A constant that specifies the ratio of the circumference of a circle to its diameter (3.14159265359…).
    Math.Power Raises a number to a specified power.
    Math.Remainder Divides the first number by the second and returns the remainder.
    Math.Round Returns the number nearest the specified value.
    Math.Sin Returns a value containing the sine of the specified angle in radians.
    Math.SquareRoot Returns a value specifying the square root of a number.
    Math.Tan Returns a value containing the tangent of an angle in radians.
  • Examples:

Math.Abs(-5.4) returns the absolute value of –5.4 (returns 5.4) Math.Cos(2.3) returns the cosine of an angle of 2.3 radians Math.Max(7, 10) returns the larger of the two numbers (returns 10) Math.Power(2, 4) returns 2 raised to the fourth power (16) Math.SquareRoot(4.5) returns the square root of 4.5

Random Numbers

  • We single out one math method for its importance.  In writing games and learning software, we use a random number generator to introduce unpredictability.  The Math.GetRandomNumber method is used in Small Basic for random numbers.
  • Whenever you need a random whole number (integer) value, use this method:

    Math.GetRandomNumber(Limit)

    This statement generates a random value that is between 1 and Limit.  For example, the method:

    Math.GetRandomNumber(5)

    will generate random numbers from 1 to 5.  The possible values will be 1, 2, 3, 4 and 5.

  • A roll of a die can produce a number from 1 to 6.  To use GetRandomNumber to roll a die, we would write:

    DieNumber = Math.GetRandomNumber(6)

  • For a deck of cards, the random integers would range from 1 to 52 since there are 52 cards in a standard playing deck.  Code to do this:

    CardNumber = Math.GetRandomNumber(52)

  • If we want a number between -100 and 100, we would use:

    YourNumber = 101 -Math.GetRandomNumber(201)

  • Check the examples above to make sure you see how the random number generator produces the desired range of integers.

Next Chapter > >

© Copyright 2010 By BibleByte Books. All Rights Reserved. BibleByte Books, the BibleByte Books Logo, Computer Science For Kids, the Computer Science For Kids logo, and related trade dress are trademarks or registered trademarks of BibleByte Books.