TweetFollow Us on Twitter

REALbasic Sprites Volume Number: 16 (2000)
Issue Number: 8
Column Tag: Programming

REALbasic Sprites

By Erick J. Tejkowski

Develop powerful games in minutes

Introduction

Game programming has long been a tradition of highly specialized source code, libraries, and programming trickery, strictly for übergeeks. Until now. Armed with a copy of REALbasic and this article, you will be writing your own games in no time at all.

For high-speed games, it is customary for programmers to use special code to draw at high speeds (often referred to as "blitting" routines). This stems from the fact that the native drawing routines available in the Mac Toolbox are too slow for fast drawing, such as that required by animation. Beginners will be glad to learn that REALbasic has these abilities built in. With only a few lines of code, a programmer can attain high-speed sprite-based animation. Add a few more lines of code and you have a game. REALbasic takes care of all the nasty drawing routines behind the scenes and lets us focus on the elements of the game. This article will demonstrate animation and game creation using REALbasic sprites. By the end of the article, you should be able to complete a small arcade-style game.

Building the Sprites

Begin the game project by opening your favorite resource editor. For our purposes, the free ResEdit from Apple will do just fine. Create a new file and name it "Resources". This is the only name REALbasic understands for resource files added directly to projects in the IDE, so be sure to spell it correctly. In this new resource file, create three resources of type 'cicn' and change the ID# to 1280, 1290, and 1300 respectively by selecting the Resource:Get Resource Info menu. In cicn #1280, create a graphic for the hero of our game. In cicn #1290, draw an adversary. Finally, cicn #1300 contains a picture of a projectile. For this example, we will use an airplane theme. By now, you should have something that looks like Figure 1.


Figure 1. The Sprite Graphics.

Now that the sprite graphics have been created, save the Resources file and start REALbasic.

Building the Project

When REALbasic starts, a new project is created automatically. Drag the newly created resource file into the project. Now, open Window1 and drag a StaticText , a PushButton , and a SpriteSurface control onto the window. The StaticText will display the results of the game (i.e. win or lose), the PushButton will start the game, and the SpriteSurface will control all of the animation and game play. Figure 2 shows the completed interface.


Figure 2. The Completed Window1 Interface.

Once the interface has been built, double click Window1 to open the Code Editor. With the Code Editor opened, create the Properties in Listing 1 by selecting New Property from the Edit menu.

Listing 1. Window1 Properties.

BadguySprite(10) as Sprite
GoodGuySprite as Sprite
GunSprite as Sprite	
gunvisible as Boolean
NumOfBadGuys as Integer
leftEdge as Integer
topEdge as Integer

Sprite properties are pictures that can be controlled by a SpriteSurface. We will need 10 sprites representing the attacking enemies, one representing the hero, and one used for the gunfire that the hero can shoot. The Boolean variable gunvisible will allow us to turn the gunfire on and off. The integer NumOfBadGuys , as one might expect, will keep track of the number of BadguySprites remaining. The final two integer variables (leftEdge and topEdge) will be used to center the SpriteSurface on the screen.

In addition to these properties, create three methods named InitSprites, ClearAllSprites, and RemakeGun by selecting New Method from the Edit menu. The InitSprites method will initialize all of the sprites defined in Listing 1. Open the Code Editor to the InitSprites method and enter the code from Listing 2.

Listing 2. The InitSprites Method.

Sub InitSprites()
dim p as picture
dim i as integer

//init the good guy
p=app.resourceFork.getcicn(1280)
GoodGuySprite=SpriteSurface1.NewSprite(p,32,32)
GoodGuySprite.x=300
GoodGuySprite.y=435
GoodGuySprite.group=1

//init the gunfire
p=app.resourceFork.getcicn(1300)
GunSprite=SpriteSurface1.NewSprite(p,32,32)
GunSprite.x=-200
GunSprite.y=467
GunSprite.group=2
gunvisible=false

//init the bad guys
p=app.resourceFork.getcicn(1290)
for i=1 to 10
BadguySprite(i)=SpriteSurface1.NewSprite(p,32,32)
BadguySprite(i).x=rnd*600
BadguySprite(i).y=rnd*200-250
BadguySprite(i).group=3
next

NumOfBadGuys=10
End Sub

The InitSprites method demonstrates how each of the Sprites is created. First, the icons created earlier are opened into a Picture object. Next, the NewSprite method of SpriteSurface1 is called, passing the Picture, and Width and Height of the Picture as parameters. Once the Sprite has been created, its X and Y positions are initialized. The SpriteSurface will measure 640x480, so the GoodGuySprite will begin life somewhere near the bottom middle of the screen. The gunfire starts off as not being visible (i.e. gunvisible=false), so we assign its X postion somewhere off the screen (GunSprite.x=-200). Later, when we want it visible to the user, we will simply move it to a positive X position. The ten BadguySprites will begin at random X positions and Y positions somewhere between -250 and -50, making them initially invisible. This will change later, however, when they move down the screen towards the GoodyguySprite. The last thing to notice here is the Group property of each of the Sprites. The Group number is used for detecting collisions. Sprites with the same Group number will not collide with each other. Sprites with different Group numbers produce collisions. Now, when we talk about producing collisions, what this really means is that the Collision Event of the SpriteSurface will be fired. For now, it is sufficient to know that the GunSprite and the BadGuys have different Group numbers so that they may collide. Further, the BadGuySprites have a Group number that is different from the GoodguySprite, allowing them to collide.

Since all good things must come to an end, we need to include some code to destroy everything we have created. Open the Code Editor, navigate to the ClearAllSprites method, and enter the code in Listing 3. During the execution of the game, we may need to kill a sprite (e.g. when GunSprite and badguySprite collide). Therefore, we should not assume that all sprites will always be around. This is the reason we check for nil status of a sprite before trying to kill it. If we try to kill a non-existent sprite, an error will result causing the application to crash.

Listing 3. The ClearAllSprites Method.

Sub ClearAllSprites()
dim i as integer
//kill the GoodguySprite
if GoodGuySprite<>nil then
GoodGuySprite.close
end if
//kill the GunSprite
if GunSprite<>nil then
GunSprite.close
end if
//kill the BadguySprites
for i=1 to 10
if BadguySprite(i)<>nil then
BadguySprite(i).close
end if
next
End Sub

One final auxiliary method to code is called RemakeGun. This method will allow us to recreate a GunSprite in the middle of game play. Although we already created one in the InitSprites method, it might be destroyed during game play when it collides with a BadguySprite. Open the Code Editor window, navigate to the RemakeGun method, and enter the code in Listing 4.

Listing 4. The RemakeGun Method.

Sub RemakeGun()
dim p as picture
//reinitialize the gunfire
p=app.resourceFork.getcicn(1300)
GunSprite=SpriteSurface1.NewSprite(p,32,32)
GunSprite.x=-200
GunSprite.y=467
GunSprite.group=2
gunvisible=false
End Sub

With the window's properties and methods defined, it is time to add functionality to the various controls. To begin, fill the screen with Window1 by adding code into its Open event. This is really only cosmetic in nature. The SpriteSurface will later take over the whole screen anyway. This is what the player will see before the game begins and in between rounds.

Sub Open()
me.top=0
me.left=0
me.width=screen(0).width
me.height=screen(0).height
End Sub

To get the game started, enter the code in Listing 5 into the Action Event of PushButton1.

Listing 5. The Action Event of PushButton1.

Sub Action
ClearAllSprites
InitSprites
SpriteSurface1.run
End Sub

If any sprites are still around from previous games, they are cleared by the ClearAllSprites method. Next all of the sprites are initialized with InitSprites and the game play begins by calling the Run method of SpriteSurface1.

The SpriteSurface

At the heart of REALbasic sprite animation is the SpriteSurface control. It is a bit of an unusual control in that it has a dual personality. It acts like a Canvas control drawing graphics in a similar fashion, while periodically executing code like a Timer. The FrameSpeed property of the SpriteSurface is the rate at which the timed functions of a SpriteSurface fire. To calculate the FrameSpeed, divide 60 by the desired frames per second and round up to an integer. For example, to achieve a speed 30 frames per second:

60 / 30 = 2 (the FrameSpeed)

A FrameSpeed of 0 (zero) is the fastest speed at which a SpriteSurface can draw. A setting of 1 or 2 is typical, depending on speed and complexity required. The Run method of SpriteSurface1 was called earlier in the PushButton1 Action event. This causes the SpriteSurface to periodically fire the NextFrame event at the FrameSpeed rate until the SpriteSurface1.close method is called. As the NextFrame event fires, we look at the current conditions of all of the sprites and change them if necessary. For example, it is in the NextFrame event where we check for keys being pressed. If a key is pressed, then some aspect of a sprite can be changed (e.g. position). REALbasic takes care of doing all the redrawing for us. We simply tell it where to draw.

Listing 5 shows the NextFrame event of SpriteSurface1. In it, you will notice some other things going on. First off, a scoreboard is drawn. The scoreboard is simply a string that displays the number of BadguySprites remaining. Behind this string is a small blue rectangle, which serves the purpose of erasing the number each time. The color blue is used, because it will also be the color of the entire background of the SpriteSurface. After redrawing the scoreboard, the code checks the keyboard for keys being pressed. It looks at the left, right, up, and down arrow keys, as well as the space bar. If any of them are depressed, appropriate actions are taken. One piece of code specific to the GunSprite here is ShootingSound.play. ShootingSound is a sound file that has been dragged into the project window. Be sure to make your sounds relatively short, because long sounds can impede smooth animation. Finally the BadGuySprites are moved.

Listing 5. The SpriteSurface1 NextFrame event.

Sub NextFrame()
dim i as integer
//draw the scoreboard
me.graphics.forecolor=rgb(0,0,100)
me.graphics.fillrect 150+leftEdge,467+topEdge,40,13
me.graphics.forecolor=rgb(255,255,255)
me.graphics.textfont="Geneva"
me.graphics.textsize=10
// ! put the following code all on one line !
me.graphics.drawstring "Bad Guys Remaining: " + str(NumOfBadGuys), 50+leftEdge,477+topEdge

if me.keyTest(123) then //check left arrow key 
//plane moves left
GoodGuySprite.x=GoodGuySprite.x-10
if GoodGuySprite.x<=0 then
GoodGuySprite.x=2
end if
end if
if me.keyTest(124) then //check right arrow key 
//plane moves right
GoodGuySprite.x=GoodGuySprite.x+10
if GoodGuySprite.x>600 then
GoodGuySprite.x=598
end if
end if
if me.keyTest(126) then //check up arrow key 
//plane moves up 
GoodGuySprite.y=GoodGuySprite.y-4
if GoodGuySprite.y<350 then
GoodGuySprite.y=350
end if
end if
if me.keyTest(125) then //check down arrow key 
//plane moves down
GoodGuySprite.y=GoodGuySprite.y+4
if GoodGuySprite.y>435 then
GoodGuySprite.y=435
end if
end if

if me.keyTest(49) then //fire=spacebar
//shoot the gun
ShootingSound.play
if gunvisible=false then
//init the gunfire position here
GunSprite.x=GoodGuySprite.x+12
GunSprite.y=GoodGuySprite.y
gunvisible=true
end if
end if

//now check the position of gun only if it's turned on
if gunvisible=true then
GunSprite.y=GunSprite.y-30
//if the gun has reached the top of the screen
//hide it again and turn it off
if GunSprite.y<0 then
GunSprite.x=-200
GunSprite.y=447
gunvisible=false
end if
end if
    
//advance the badguys  
for i=1 to 10
//this is the speed of descent (increase for faster movement)
BadguySprite(i).y=BadguySprite(i).y+5
//if we have reached the bottom of the screen
//go back up to the top at some random x position
if BadguySprite(i).y>447 then
BadguySprite(i).x=rnd*600
BadguySprite(i).y=40
end if
next

End Sub

So far, this code will produce a nice animation where the GoodguySprite can navigate and shoot at the approaching BadguySprites.

SpriteSurface Collisions

When a GunSprite hits a BadguySprite, nothing happens yet. Nor will anything occur if the BadguySprite manages to run into the GoodguySprite. This is the function of the SpriteSurface1 Collision Event. Listing 6 details the code for the SpriteSurface's Collision Event. This is where the Sprite Group numbers from earlier in this article become important. The Collision Event of a SpriteSurface is automatically passed the Group numbers of the sprites that have collided. In the event, we simply check to see which two sprites have collided and then take some action. In this example, we will only look at two types of collisions - both the GunSprite and BadguySprite have collided or the GoodguySprite and BadguySprite have collided. If the GunSprite has collided with a BadguySprite, then we close both of the sprites (in effect "killing" them), play a sound, decrease the number of NumOfBadGuys variable, and call RemakeGun for the next time a user fires the gun. We must also check to see if all of the BadguySprites have been killed. If so, then the game is over and the player has won. Finally, if a BadguySprite has managed to collide with the GoodguySprite then the game is over and the player has lost.

Listing 6. The Collision Event of SpriteSurface1.

Sub Collision (s1 as Sprite, s2 as Sprite)
//GunSprite and BadguySprite have collided
if s1.group=2 and s2.group=3 then
BadGuyCrashSound.play
s1.close
s2.close
RemakeGun // since we killed the gun sprite, init it again
NumOfBadGuys=NumOfBadGuys-1
if NumOfBadGuys=0 then
s1.close
s2.close
spritesurface1.close
Statictext1.text="You Win!"
CheeringSound.play
end if
end if

//GoodguySprite and BadguySprite have collided
if s1.group=1 and s2.group=3 then
s1.close
s2.close
spritesurface1.close
Statictext1.text="You Lose!"
GoodGuyCrashSound.play
end if
End Sub

To spice things up a little, it is often desirable to draw a background behind the game. The SpriteSurface background is broken up into a grid of 64x64 squares. The PaintTile event takes care of refreshing these background tiles. To fill the background with a solid blue color, enter this code into the PaintTile event of SpriteSurface1.

Sub PaintTile (g as Graphics, xpos as Integer, ypos as Integer)
g.forecolor=rgb(0,0,100)
g.fillrect 0,0,64,64
End Sub

Keep in mind that any standard graphics drawing can take place in the PaintTile event. The final step is to add some code to the Open event of SpriteSurface1. Like the Window1 Open event code, this code is strictly cosmetic. It has been adopted from code by Matt Neuberg in his book REALbasic: The Definitive Guide. It centers SpriteSurface1 on the screen.

Sub Open()
leftEdge = (Screen(0).width - 640) \ 2
topEdge = (Screen(0).height - 480) \ 2
me.surfaceleft = leftEdge + ((640-me.surfacewidth) \ 2)
me.surfacetop=topEdge
End Sub

Having completed the code, it is time to test the finished application. Select Debug:Run menu. Click PushButton1 and play the game. If something goes wrong, recheck your code for accuracy and make sure that you have added all of the necessary auxiliary files (the resource file and the sound files). If all else fails, you can download the finished source code from MacTech's web site.

Conclusions

In this article, we took a brief look at Sprites in REALbasic by constructing a game. The game could be upgraded in a number of ways. Hopefully, this article gives you some basic background about how to make some of these changes yourself. If you would like more information about game development on the Macintosh particularly with regard to REALbasic, be certain to check the Reference section at the end of this article.

References


Erick Tejkowski is still looking for a decent version of Moon Patrol[TM] for the Mac. You can reach him at ejt@norcom2000.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Delve back into the Sanctum of Rebirth t...
I don’t know about you, but I am all for a big, interconnected tree of lore in games or series. The MCU, the fabulous marathon that is The Legend of Heroes, and the long-running MMO Runescape. The Ode of the Devourer quest has released and is the... | Read more »
TouchArcade is Shutting Down
This is a post that I’ve known was coming for quite some time, but that doesn’t make it any easier to write. After more than 16 years TouchArcade will be closing its doors and shutting down operations. There may be an additional post here or there... | Read more »
Combo Quest (Games)
Combo Quest 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Combo Quest is an epic, time tap role-playing adventure. In this unique masterpiece, you are a knight on a heroic quest to retrieve... | Read more »
Hero Emblems (Games)
Hero Emblems 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: ** 25% OFF for a limited time to celebrate the release ** ** Note for iPhone 6 user: If it doesn't run fullscreen on your device... | Read more »
Puzzle Blitz (Games)
Puzzle Blitz 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Puzzle Blitz is a frantic puzzle solving race against the clock! Solve as many puzzles as you can, before time runs out! You have... | Read more »
Sky Patrol (Games)
Sky Patrol 1.0.1 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.1 (iTunes) Description: 'Strategic Twist On The Classic Shooter Genre' - Indie Game Mag... | Read more »
The Princess Bride - The Official Game...
The Princess Bride - The Official Game 1.1 Device: iOS Universal Category: Games Price: $3.99, Version: 1.1 (iTunes) Description: An epic game based on the beloved classic movie? Inconceivable! Play the world of The Princess Bride... | Read more »
Frozen Synapse (Games)
Frozen Synapse 1.0 Device: iOS iPhone Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Frozen Synapse is a multi-award-winning tactical game. (Full cross-play with desktop and tablet versions) 9/10 Edge 9/10 Eurogamer... | Read more »
Space Marshals (Games)
Space Marshals 1.0.1 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.1 (iTunes) Description: ### IMPORTANT ### Please note that iPhone 4 is not supported. Space Marshals is a Sci-fi Wild West adventure taking place... | Read more »
Battle Slimes (Games)
Battle Slimes 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: BATTLE SLIMES is a fun local multiplayer game. Control speedy & bouncy slime blobs as you compete with friends and family.... | Read more »

Price Scanner via MacPrices.net

Amazon and Best Buy have Apple’s 10th-generat...
Amazon and Best Buy are offering $50-$30 discounts on Apple’s 10th-generation iPads this week, with models now available starting at only $299. These are the lowest prices available for Apple’s... Read more
Red Pocket Mobile is offering a $300 rebate o...
Red Pocket Mobile has new Apple iPhone 16’s on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
New at Xfinity Mobile: iPhone 16 Pros for $40...
Switch to Xfinity Mobile with a new line of service, and take $400 off the price of any new iPhone 16 Pro through October 10, 2024. Final value is applied to your account, monthly, over a 24-month... Read more
16-inch Apple MacBook Pros on sale this week...
Best Buy has 16″ M3 Pro and M3 Max Apple MacBook Pros on sale for $500 off MSRP on their online store this week. Prices valid for online orders only, in-store prices may vary. Order online and choose... Read more
iPhone 15 and 15 Plus free at Verizon for new...
Verizon has the iPhone 15 and iPhone 15 Plus now on sale for $0 per month (that’s free!) when you add a new line of service. No trade-in is required. Discount is applied to your account monthly over... Read more
Verizon offers free iPhone 16 and 16 Pro mode...
Verizon is offering $1000 discounts on the new iPhone 16 Pro, $830 for the 16 and 16 Plus, for customers opening a new line of service. Discount is applied via monthly bill credits over a 36 month... Read more
AT&T offers free iPhone 16 and 16 Pro mod...
AT&T is offering $1000 discounts on the new iPhone 16 Pro, $830 for the 16 and 16 Plus, for new and existing customers with an eligible trade-in. Discount is applied via monthly bill credits over... Read more
Buy a new iPhone 16 at Visible, and get $10 o...
Switch to Visible, and buy a new iPhone 16 (full price or financed), and Visible will take $10 off their monthly Visible+ service for 36 months. Visible is Verizon’s low-cost service. Visible+ is... Read more
Apple iPhone 16 deals are live at Xfinity Mob...
Switch to Xfinity Mobile with a new line of service, and take up to $1000 off the price of a new iPhone 16 through October 10, 2024. Final value is applied to your account, monthly, after qualifying... Read more
Get a free iPhone 16 at Boost Mobile plus Unl...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 16 or 16 Pro including service with their Unlimited plan (30GB of premium data) for a total charge of $65... Read more

Jobs Board

EUC *Apple* /MAC Platform Engineer - Corning...
EUC Apple /MAC Platform Engineer **Date:** Sep 13, 2024 **Location:** Charlotte, NC, US, 28216Corning, NY, US, 14831 **Company:** Corning Requisition Number: 64844 Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Secret *Apple* MacOS Workspace ONE AirWatch...
Job Description The Apple MacOS Workspace ONE AirWatch Engineer role is primarily responsible for managing a fleet of 400-500 MacBook computers. The ideal candidate Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.