Newest Tutorials: An Introduction to Stacks | Templates Menu
10-29-03
Introduction to SpriteSurfaces by
The SpriteSurface control is a fairly power animation system for two-dimensional (2d) graphics. Although it may not be king of the mountain for any and every 2d game, it certainly deserves a good look as it can accomplish a lot if used cleverly.
A "SpriteSurface" is an area of the screen in which images are moved around on the screen independently of the background. These images, or "sprites," are typically characters or objects such as the ghosts in PacMan or a boomerang thrown by Link in the Legends of Zelda. To create the illusion of seamless movement, a SpriteSurface runs, or redraws, at a specified rate which is typically about 20-40 frames per second depending on the type of game. On each redraw or "frame" of the animation, the sprites may move a certain small distance and/or change its image. For example, the PacMan sprite changes its image by opening and closing it's mouth (or what I assume is supposed to be a mouth) a tiny portion on each frame. When the sprite's image is changed fast enough or moves a short distance on the screen several times in very quick succession, our eyes are fooled into believing that we're seeing a smooth movement.

The frames of a PacMan sprite.
The SpriteSurface class in REALbasic is a RectControl subclass which must be embedded in a window. In REALbasic 2.x and earlier, the SpriteSurface was a bit different and would essentially create it's own window, but in 3.0, it behaves in the same manner as any other RectControl such as a PushButton or canvas. The objects which move around inside of our SpriteSurface, our sprites, are implemented through the Sprite class. Sprites are attached to a SpriteSurface and thereafter are involved in any collisions that happen in and all drawing that the SpriteSurface does.
If you drag a SpriteSurface instance to a window, you will see some of its properties in the Properties window. There are of course the standard left, top, width, and height properties, but there are also SurfaceLeft, SurfaceTop, SurfaceWidth, and SurfaceHeight properties. What are they, and what do they do? Well, they're actually carry overs from the previous SpriteSurface implementation and no longer do anything. You can completely ignore them. Although they maybe the same values as left, top, width, and height, don't count it because they can be changed at anytime.
Other properties include Backdrop, which is a picture just as in a Canvas, Depth, which is the bit depth of the surface (8 is 256 colors, 16 is 65k colors, and 32 is millions), FrameSpeed, and ClickToStop. The last two properties, FrameSpeed and ClickToStop, are related in that they both only affect the SpriteSurface if its Run method is called which brings us to our next point.
The SpriteSurface in REALbasic can be driven in one of two ways. I can be ran with the Run method, or it can be updating using the Update method. Run is a synchronous method which will halt all processing in your application, enter a tight loop, and continue to redraw the surface at a specified rate, which is (60/FrameSpeed) times a second. So if you set the FrameSpeed property of a SpriteSurface to 2, then the surface will run at 30 frames per second. The ClickToStop property allows the end user to be able to click the mouse button to make the SpriteSurface stop animating. If the CickToStop property is unchecked, then the programer (you), has to at some point call the SpriteSurface's Stop method from within the NextFrame event.
What's the NextFrame event, you say? Well, in order to animate any of the sprites within our SpriteSurface we need an event which is fired before each time the SpriteSurface redraws. Inside of this event is where we would make changes to our sprite's properties such as position after the player presses a key, or the image when the game character dies. After we're done making any changes we want to make for that particular frame, the SpriteSurface then draws itself onto the screen.
What the Run method does is enter a loop which continually calls the NextFrame event, checks for collisions (and if any occur, the Collision event is fired), and then draws to the screen. The second way to drive a SpriteSurface is to use our own loop and continually call the Update method of the surface. The update method is the same thing as one iteration of the make believe look that the Run method uses. Each time Update is called, the NextFrame event is fired, the surface checks for collisions, fires the Collision event if needed, and then draws to the screen. Simple. To compare the Run and Update methods, consider the following bits of code:
Sub Action()
SpriteSurface.ClickToStop = true
SpriteSurface.Run
End Sub
Sub Action()
do
SpriteSurface.Update
while System.MouseDown = false
End Sub
These two pieces of code function in the same way except for one. The top method will make the surface run at 60/FrameSpeed frames per second, but the bottom method will make the surface run as fast as it possibly can, and both stop when the user clicks the mouse. The flexibility of using the Update method gives you a little bit more control as you can write code which calls invokes a redraw of the surface exactly when you want it to, but they really are the same for all practical purposes. The Update method allows you to update the surface one frame at a time if you wish. So which should you use? It's up to you.
Alright, so we're just going to get our hands wet today, so drag a spritesurface to a window and resize it to be 640 pixels wide and 480 tall and fit exactly into a 640x480 window. Set FrameSpeed to 2 (which will give us 30 frames per second) and make sure that ClickToStop is checked. Next, create a menu item in the File menu named "Run" and implement a menu handler in the same window as the spritesurface for the menu item and use the following code:
Function Action As Boolean
SpriteSurface1.Run
End Function

If you run the project and select Run from the File menu, you should see absolutely nothing happen. If you wait, your cursor may turn into a spinning beachball or watch, but that's it. The black still stays black, but that black is being drawn by a sprite surface! Pretty cool huh? No. It's not. So lets make it cool.
In many games there's a background which we're always looking at and which the characters are on top of. In asteroids, we're looking at space, in Mario we're looking at the sky and clouds. Well the background in this games is usually just a single image which doesn't change but moves. For this tutorial we're going to drop in a background and make it move. So go ahead and download this image, rename it "Space.jpg", and drop it inside of your REALbasic project.

Control/Right-Click the image to save it.
Next, set the the Background property of the spritesurface in the Properties Window to the "Space" image. The background is exactly as you'd expect. It's the background of whatever is drawn to the spritesurface. Anything drawn in the surface including sprites will always appear in front of the background.
If you run the project again, you'll now see the space background in the window. Well, it's a little nicer now, at least we know something's being drawn, but lets make it move! The SpriteSurface class has a handy method (although demanding on the CPU) called "Scroll" which is very similar to the canvas' Scroll(dx, dy) method. Scroll takes two integer values, an "x" delta, and a "y" delta. The dx and dy passed to Scroll determine in which direction and to what degree the SpriteSurface's background and all objects inside of it are moved. If you were to pass scroll (-1, 2), then the background and objects would move 10 pixels to the right and 2 pixels up. When you use small numbers like this and have a relatively high frame rate, then the movement of the surface will look smooth. This effect is used all over. In fact, most 2d platform games (Super Mario Bros, Megaman, Captain Bumper, etc.) use it.
So how can we scroll? Remember that the NextFrame event is fired for each time the SpriteSurface is redrawn. So if we place "me.Scroll 1, 0" in the NextFrame event of the SpriteSurface, then for each of the 30 frames per second that our surface updates, the surface will scroll one pixel to the left and not move vertically.
I realize this is a very short introduction to sprite surfaces, but you've got to start somewhere! Next week we'll learn about sprites and begin to actually build something interesting!
10-25-03
REALbasic News by
Seth Willits
REAL Software Looking for a Tech Writer
REAL Software announced Tuesday that it is looking to hire a new employee responsible for updating documentation, writing new tutorials and examples, and helping the engineering team with making REALbasic even easier to learn. Candidates must be willing to relocation to Austin, Texas. Contact Geoff Pearlman, President and CEO of REAL Software, Inc. for more information:
512-328-7325 x711 (voice)
512-328-7372 (fax)
REALbasic Items
ReX-T v1.1
RBOpenSource, a collaborative effort of REALbasic developers to bring free open source software to other developers, announces version 1.1 of ReX-T. Rex-T is a utility designed to help REALbasic developers master Regular Expressions by giving them a testbench to experiment with different search patterns. ReX-T is released as Open Source under the GNU GPL License.
SavePicture Module
Toon Van Acker released a new module on Sunday which allows developers to read and write pictures, with masks, to a binary stream. Previously developers would have to have written their own code which would write the picture to disk, read it with a binary stream, and then written it to another. The process is now much simpler thanks to this easy-to-use solution.
P2 Toolbar Icon Browser
Ever needed to see what all of the system icons available for use in toolbars on Mac OS X will look like? P2 Toolbar Icon Browser lets you browse through a collection of 75 standard icons that you can use in Mac OS X toolbars. Presenting a toolbar in a floating window, you can browse through all 75 icons and click on them to copy the code necessary to use the icon to the clipboard. P2 Toolbar Icon Browser is distribute as a REALbasic project and requires REALbasic 5.0 or later.
String Functions Module
After deciding that he liked creating his Split Module (which we liked too!), Thom McGrath decided to work on and release a new String Functions Module which adds 7 new handy functions including Character() which simply grabs a character from a string, Condense() which turns all tabas and space runs into single spaces, IsAlpha() which decides if the string contains only letters and spaces, IsNumber() which deteremines if the string is a digit-represented number, IsWhitespace() which does the same for non-printable characters, MultiIndex() which populates an integer array with indexes of every location of a the target string in the source string, and Strip() which removes undesired characters from a string. <whew!> The module requires REALbasic 5.2 or higher.
Base64 Class
Charles Yeomans posted a minor update to his Base64 class, a class that implements the Base64 encoding scheme, which fixes a small bug which would remove legal characters along with illegals.
UniHelp 1.5.1
UniHelp, from the fine folks at Electric Butterfly, is a cross-platform HELP engine to be embedded in REALbasic applications allowing fast, powerful, and consistent Help viewing on Mac OS 8/9, Mac OS X, Windows 98/NT/ME/2000 and Windows XP. Allowing the display of both HTML and ASCII files, UniHelp just requires a few drag and drops of the mouse and a few lines of code to be up an running. Version 1.5.1 fixes a few minor bugs as well as a major one which wouldn't allow European OS users to register! UniHelp is $49 US and is royalty-free.
Made With REALbasic:
ProSQL v2.0
Intelli Innovations has released version 2.0, a major upgrade, to their popular database management software, ProSQL. ProSQL 2.0 includes numerous new features and improvements including SQL Favorites, a collection of commonly used SQL statements, new AppleScript query automation capabilities, a new rendering system with a speed increase up to 400%, a redesigned database connection dialog, refinements to the interface on Mac OS X, support for Mac OS X 10.3, and more. ProSQL requires Mac OS X 10.1 or later or Mac OS 9.1 or later and is available for purchase starting at $99.95
An Introduction to Stacks by
Now, when you think of a stack you may think of a stack of papers, or a stack of dirty plates. Unless you've used some older programming languages or delt with the Classic Mac OS's System Stack in Pascal or C, you probably don't think of a data structure. Whether we're talking about programming or in life, a stack is an association of items such that the last item stored is the first item retrieved. With our dirty dishes, we remove the last plate from the table and place it on the top of the stack in the sink. Days later when we decide it's time to wash those dishes, the first plate we grab is the one from the top, the last one which was placed on the stack. We recognize this attribute of stacks and give it the caption "First in Last Out", or FILO. FIFOs on the other hand, (first in first out) are called "queues" but we won't be getting into those.
In programming, a stack is basically an array where there are two functions; one to add an item or "push" it on to the stack, and one to remove an item, or "pop" it. In REALbasic, there is no such thing as a "stack" or a Stack class, but instead, we can treat an array of any datatype as a stack by using the Append and Pop methods. (Pop was added to REALbasic 5.) When we want to push an item on to the stack, we call the Append method, and to retrieve it, we call Pop. If for instance we did this:
dim nums(-1), x as integer
nums.Append 1
nums.Append 2
nums.Append 3
nums.Append 4
nums.Append 5
When we use the the Pop method we get this:
x = nums.Pop // x = 5
x = nums.Pop // x = 4
x = nums.Pop // x = 3
x = nums.Pop // x = 2
x = nums.Pop // x = 1
As you can see, Pop not only retrieves the topmost item in the stack, it also removes it. It's important to remember this.
So when are stacks used? Stacks are most offen used in the place of recursion, which is where a function will call itself when some condition is met. A specific example where a stack is used is searching for a specific file in a given folder. Typically, a SearchFolder(filename as string, rootFolder as folderItem) as FolderItem method may be written which returns the folderitem for the file if it was found. SearchFolder would examine all of the items in the rootFolder, and if it comes across a folder within rootFolder, it would call itself again, passing the appropriate rootFolder.Item(n) as the rootFolder. This recursive method of searching is done all the time, not only for files, but also whenever any kind of tree-like heirarchial structure needs to be examined. However it does have some downsides. If you've used recursion before, you may have caused a StackOverflowException* by having too many levels of recursion (SearchFolder called itself too many times for REALbasic to handle). By using a stack, you can rid of this problem and actually pick up a little bit of a performance boost too.
* If you've never used recursion or don't know what a StackOverflowException is, don't worry about and pretend you never read that. While the "Stack" does refer to a stack of what we're talking about, you'll never receive a StackOverflowException when using a stack since the conceptual idea of a stack is used differently.
Using a Stack
The project for this tutorial is simply going to display a dialog to select a folder, and display all of the files inside of that folder, it's subfolder, their subfolders, and their subfolders, aaaalllll the way down to the deepest level. For example, if you selected the root folder on your hard drive, the project would a row to the listbox for every file on your hard drive. (By the way, don't do that. It'll take a very long time! :-)
The interface for the project is simply a listbox named "FilesList" and a pushbutton with the following code:
dim folders(-1), rootFolder as FolderItem
dim currentFolder, itemInFolder as FolderItem
dim index, count as integer
// Select Root Folder
rootFolder = SelectFolder()
if rootFolder = nil then return
// Add rootFolder to stack
folders.Append rootFolder
// For each folder in the stack
while UBound(Folders) > -1
// Get the folder at the top of the stack
currentFolder = folders.Pop
// For each item in the current folder
for index = currentFolder.Count DownTo 1
itemInFolder = currentFolder.Item(index)
if itemInFolder <> nil then
// If item is a folder
if itemInFolder.Directory = true then
// Add folder to the stack
folders.Append itemInFolder
else
// Add file to the listbox
FilesList.AddRow itemInFolder.Name
end if
end if
next
wend
As you can follow from the comments, a dialog is displayed in which the user selects a folder. That folder then becomes the first item in the stack. The While-Wend loop then Pops each item in stack (one per iteration of the While loop) and then the For loop goes through each item inside of the folder that was popped from the stack. If and only if the itemInFolder is a folder itself, is it added to the stack. The only items ever in the stack are folder since only the folders need to be inspected.
|