Developing VB Games

Embed Size (px)

Citation preview

  • 8/6/2019 Developing VB Games

    1/10

    Developing VB Games

    By Trent Jackson

    Recently, I have spent some considerable time searching through PSCs library ofgame submissions. Upon viewing, almost all of the 600 or so submissions, which dateback from 1999 to now, a number of impressions and, final conclusions about makinggames will be forever left engraved in my mind. Most of the submissions all share onesimilar thing in common. Any guesses? Well, mostly, theyre all unfinished projects.Some of them, shamefully unfinished since they are actually quite good. For someonewho comes across these submissions and, is just starting out with VB, its all very badnews because it causes serve procrastination.

    It makes them possibly ask themselves, why so many incomplete projects? Is thelanguage simply no good for making games? Truth be known, I once thought that VBwas neither intended nor practical for making games with. I was wrong. Lacking therequired essential knowledge with the language, and not knowing how to do things theright way very quickly imposed this conclusion. Very few books actually promote VBgame programming. Even fewer explain the benefits of using API calls. Out of interest,some of the latest commercial quality games have been written in a variant of Basic.3D games that will astound you. All written in Basic. Blitz Basic that is

    I recently took a quick glance at the Blitz language only to make one very, almostimmediate conclusion. Why would you bother with it if you have Microsofts Visual

    Studio! First impressions with Blitz reminded me of QB. Quick Basic for DOS. Theresno physical objects to click on, no form of any visual aspects whatsoever. Making agame in Blitz looks to be twice as more involved than doing it in VB. Having said that,some of the games that evolve out of Blitz are incredible! Ive seen them with my owneyes. If these games can be developed in Blitz, why cant they be done in VB? Answeris they can! Admittedly, Blitz does support the insertion of assembly code along with afavor towards polymorphism. But still, its a variant of Basic with commands that sharealmost identical syntax to VB

    Some incredible Blitz Basic games can be seen at www.imphenzia.com

    Techniques Used For Making VB Games

    1. Pure VB, OOP Object Orientated Programming2. BitBlt and or StretchDIBits, API Application Programming Interface3. Direct X

    Games that are developed without bare minimal API necessities or Direct Xingredients turn out to be very disappointing. VB by itself, without any otherexternals is not possible for quality video game development. Unless yourintentions are to just mess about and have a bit of fun, dont even give pure VBprogramming a milliseconds thought for when it comes to making games. Dontget me wrong, if youre new to VB, sure play around with all the objects, movethem around on the screen and learn from it.

  • 8/6/2019 Developing VB Games

    2/10

    But just dont expect to make any sort of decent game by relying solely on theseobjects. The objects that Im referring to are the image & picture box controls.Whilst they are entirely more than adequate for displaying almost all types ofgraphic, placing multiple instances of them on the screen and trying to movethem about causes nothing but a whole lot of disappointing flicker. Part of the

    reason for this is lack of vertical synchronization with the monitor. These objectswere never designed to be shifted around on the screen at varying speeds withina video game. A host of API solutions exist which are specifically designed forthis purpose. They work reasonably well. More on this later

    Implementation Stages

    Arguably, the best way to program, and if youre any good at it, is to just divestraight in and code it. I personally feel this to be entirely non-applicable tomaking games. Normally turns out a mess if you adopt this approach. My adviceand the rules that I currently follow; paint a clear, crystal like image In your mind

    of exactly what you want. Think it through, question its integrity at all possibleangles, most importantly; dont over complicate it at the start. Build on it as youprogress. Trying to clone games is the hardest. If the games extremely good,you have set yourself a very high target to live up to.

    1. Game type i.e. (platform or shooter? horizontal or vertical?)2. Concept (purpose of the game)3. Title (the name says it all)4. Complexity (reality check, can I really do this?)5. Layout (visualization of what it will all look like)

    I think most video game projects fail because people bite off more than they canchew. Settle for something modest to begin with, learn from it and watch it grow!Its a tall order for average people like myself to deliver the top-notch goods forwhen it comes to video games. I have about 5 years of experience with VB andonly just quite recently that I can say that, I can make an O.K. game. Few peoplestart off with making Quake, Tomb Raider style games. Often though, I thinkmany people however place these high expectations on themselves only to bevery disappointed with the end result. As the saying goes, quality, not quantity!60 finished O.K games are far more worth their value than 600 unfinished ones.Even if therere simple but at least playable and completed ones, theres muchgreater value in them. Always finish something that you start. No matter what!

    Desired Ingredients

    So, to break it all down, what physical elements do you need to make game?

    1. Background graphics2. Background music3. Sound effects4. Sprites & Animation5. Coded Procedures6. Error handling7. Input handling8. Speed regulation

  • 8/6/2019 Developing VB Games

    3/10

    Graphical Hurdles

    It seems clear to me that making games is not just about programming. You

    need to have other skill sets as well. Namely the ability to draw. Sure you canalways rip graphics from other games, perhaps even modify them to suit yourrequirements. But, this takes away a significant amount of credit to the game ifit turns out to be good. Not to mention also that its a violation of copyright lawsthat would obviously restrict the game to personal use or at best non-profitabledistribution. This would of course depend on the source of the graphics. Takenfrom 20-year-old games Id say there would be little concern. From somethingmore recent, undoubted lawsuits would be the result if the game were sold.

    Theres just as much effort in designing graphics as there is with programmingthe game. I have just recently spent about 2 solid hrs drawing a jet ski for my

    next video game project. Theres 3 ways to generate graphics for games.

    1. Bitmaps, jpegs, gifs, generated from graphics packages.2. Code drawn graphics at run time using pixels, circles, lines etc3. Character maps.

    In times gone by, graphics for games were drawn pixel by pixel by dedicatedteams of professional people. True, much easier nowadays with the aid ofmodern graphics packages like; QuarkXPress, Illustrator, Indesign and so on.Still very time consuming though. Prior to 1990, character maps were usedextensively throughout because of memory restrictions. Character maps are kind

    of like a text font in my understanding. Possibly, the reason why they are oftencalled text graphics. Character maps consume less storage space because oftheir low resolution. Some of the characters in the extended ASCII set have blockcharacters, which are primarily directed towards generating memory conservativegraphics. Also, having the graphics laid out in a map, in separated pieces allowsfor extensive reusability. There are a lot of very smart algorithms that are behindthe successful usage of character maps.

    Physical Design

    Once you know the type of game that you want, and you have the concept in

    tact, you have decided a name for it, you have a clear mental visualization of thelayout for it, youre ready to put pen to paper! With the graphics that is!

    Figure 1 Figure 2

    Design the graphics first. This not only gives you more time to think about thegame but rather an opportunity to build your confidence up for the coding side ofit. Hype yourself up for the amount of action that you intend to have if its going to

  • 8/6/2019 Developing VB Games

    4/10

    an action packed game. Do the graphics and do them well. If you settle forsecond best in the early stages then, chances are youll settle for further secondbest solutions in the later stages. Set your goals marginally higher than what youreally expect to achieve. Youll come off somewhere in between. Lastly, allowyourself time limits to enforce on any particular task. Set a deadline for it all.

    I personally use a package called QuarkXPress for most of my graphics work.Using a combination of shapes and textures to produce the image that you see infigure 2. Then I export the image to Photoshop where it gets pixilated and furtherre-touched. The output is satisfactory and more than sufficient enough for myintentions with it. Few more sessions in Photoshop will render vast improvementsof higher graphical detail and clarity. I create the required masks in Photoshoplike you see in figure 1. Using masks allows us to clip out the background, whitearea, so that the background graphics in the game can be preserved.This is achieved by first placing the mask on the screen, then by registering theactual image on top and applying logical AND to the colours, we successfully clip

    out the background area of the image.

    After completion of all your graphics, start focusing some thought towards otherphysical elements that include; screen dimensions, animation, and characterbehavior. Namely character movement. Arguably, decided screen dimensionsshould occur before actually drawing up the graphics. But, as good luck wouldhave it, modern versions of Photoshop make it easy to resize your images to suitchanged requirements. Within reason, you can reduce or enlarge without loss ofquality. During the stages of actual coding you may need to tweak their size toovercome any unfortunate oversights with the initial design.

    Screen Dimensions

    Games which use large screen dimensions of (1024 x 768) along with (200 x200) sprites will be nothing but a huge disappointment when run on much lessthan todays very latest performing systems. As a general rule of thumb, I havefound that (600 x 400) is a good choice. Now, Im not necessarily talking aboutscreen resolution, but rather the amount of occupancy of the screen that yourgame will take up. You can define in your game a playable area of (600 x 400)without having to resort to changing the resolution of the users monitor. This isextremely annoying and puts your user at risk with their other applications.

    Character Animation

    Animation can be achieved with as little as two images. This is more than enoughIn most cases. Using ridiculous quantities of images for animation is completelyunnecessary. Assuming that there are only a few different images, the humaneye starts to preserve this as one still like image at more than about 20 or so fps,running animation at 20 fps would require at least 10 very distinctly differentimages in order to have any real effect. Ideally your game will run at about (10-20 fps) and your animation between (2-5) fps using (2-5) different images. Thereason that TV console games run so high at 50 fps is because of the TVsvertical 50Hz. It has to be matched, synchronized if you like. Most of the framesare simply repeated the same. The rate of animation is nowhere near this sincevery few games use more than a few or so images for character animation.

  • 8/6/2019 Developing VB Games

    5/10

    Of course, another consideration is graphical movement. 50 fps would be justfine if the frames only changed by 1 or 2 pixels each time. Way, way too fast forcharacters that were incremented by 5 or 10 pixels. The animation of only a fewdifferent images would go entirely unnoticed. For PC games that you dont want

    to spend 10 years drawing up graphics for, scrolling speeds of 10 fps andanimation speeds of 2 fps are just fine. I have seen a few games where thebiggest complaint about them is being slow. Mainly because the increment ofmovement was not enough. At 10 fps, incrementing something across the screenone pixel at a time, it all looks terribly slow. Yes, at first thought, If the computerhas the performance, simply increase the frame rate. Or, make the wiser choiceof increasing the increment of movement. This way, the game will be morecompatible with a wider range of machines. Slow and fast, everyone will get toplay it. Dont over do it though, too large an increment just doesnt look right.

    Character Behavior

    Directly along side of animation is the characters behavior. When the gamereceives player input, be it from the keyboard or joystick, something normallytends to happen. The players character may jump, move left or move right, oralternatively, surrounding sprites may start to chase the player. These are allconsiderations that require immense thought. Animation and character behavioris in my humble opinion what truly makes modern video gaming. Its where allthe excitement of the game exists. Timing plays a key role mostly. Everythingmust be synchronized, from player input right through to scrolling the scenery.

    Speed Regulation

    Possibly the most common problem that most VB games have is the lack ofspeed regulation. Heres a commonly seen statement; runs at perfect speed onmy computer, PIII 866 MHz, but the games unplayable on yours, P4 3.0GHz.Not any more! Part of the solution is to use the timegettime API. The other partis program structure. Never use VBs timer control for games. Instead, implementone base delay, if you need counters and procedures executed at set intervals,pre-scale variables from this base. For example; base delay is 100mS and youwish to increment a variable every 5 seconds. To do this you use a pre-scalerwhich triggers this variable after a count of (50 x 100mS) = 5 seconds. Now, thisvariable may be used to perhaps flash a message on the screen every 5 seconds

    or, move a sprite around. VBs timer control has a lot to be desired. In actual fact,multiple instances of this control fail!!! Theres a time and a place for this controland its certainly not for games. Other than that, code is far, far easier to followwhen you have only one, very distinct central delay.

    timegettime API Allows For Smooth Arcade Like Games

    Heres a practical example of a tried, true and tested procedure that uses thetimegettime API to provide a pretty nifty speed throttle that does a lot more thanyou may first think.

  • 8/6/2019 Developing VB Games

    6/10

    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

    Public Declare Function timeGetTime Lib "winmm.dll" () As Long

    Public Function Speed_Throttle()

    '//

    Base_Delay = 100Time_Taken = (timeGetTime - Time_Sample_mS)

    If (Time_Taken < Base_Delay) Then Sleep (Base_Delay - Time_Taken)

    Time_Sample_mS = timeGetTime

    End Function

    The base delay will always be 100mS no matter what! The speed throttle does anice job of balancing the amount of time that the Sleep API needs in order tomaintain a delay of precisely 100mS. The Sleep in effect does the actual delaybut for how long exactly is all dependant on the return value of the timegettimecall. In greater depth, if a frame takes 20mS of time to process then Sleep will beexecuted with 80mS. On a faster system this same frame may take just 5mS.

    therefore Sleep will be issued with 95mS of time.

    Theres more than meets the eye to the advantages of this procedure. Windowsand API calls can be unpredictable sometimes with how long certain processestake. This is called latency, or better know as lag. The speed throttle provides allthe necessary compensation for this, providing that this latency is no greater thanthe base. 100mS of lag would almost be unheard of, which makes the throttleextremely superior when you consider its outright sheer simplicity. One of themain reasons that a lot of games dont run smooth and consistent is because ofthis latency. Fluctuations of just a few mS in delay can ruin a games playability.

    Coding Structure

    Break procedures down into as many sections as you possibly can. Keep thecode minimal, tight and efficient. The use of Static variables highly promotes wellorganized, less confusing code, which require variables that share a similarpurpose to be repeatedly used with the same name. Of course Dim them if theirvalue doesnt need to be retained at the end of the procedure. For example; if Ichoose to use a variable named animate, and its a requirement in a number ofprocedures, plus its value must be retained, simply Static it in each procedureinstead of resorting to Public or Global alternatives which will require unique non-conflicting names for each and every use. Static variables may be a tad more

    memory hungry but, the extra clarity that your code will gain is well worth thetrade off. Also, despite many peoples belief, DoEvents is absolutely positively nothreat whatsoever to the performance of your program. Placing it in a conditionwill likely consume more resources than you think you might be saving. However,how you use it in your program makes all the difference. You need but only oneoccurrence of it. Using multiple occurrences is unnecessary. Plus, too, placingDoEvents before and after rendering to the screen will result in a lot of flicker.

  • 8/6/2019 Developing VB Games

    7/10

    Main Loop

    Do While Game_Over = FalseDoEvents

    Play_Field.Cls

    Call Flash_High_Score(True)

    Call Scroll_Background(True)Call Poll_User_Input

    Call Level_Control

    Call Background_Jumping_Fish

    Call Speed_Throttle

    Loop

    A lot of good games use the approach like the one shown above. I feel this to bethe most logical way and agree with it all mostly. One tight main loop, whichyields to all of the appropriate calls. The sequence of these calls can be critical.Really depends on the game. But one things for sure, DoEvents first, wipe thescreen next if youre using an API based approach, branch accordingly to what

    else is required in the game

    Coding Style

    Widely agreed upon is the fact that Select Case arguments are far superior tousing IF conditions. Not only will you gain additional speed in your program, butthe overall improved readability, and clarity of your code will really surprise you.Of course, not everything is feasible to do with Select Case, but normally themain structure of a procedure can be easily handled with its use. Inside this mainstructure you can place your additional code that may contain a combinationof almost anything. IFs, Dos, any mathematical expressions, you name it. While

    a tad more complex than using IFs for conditions, alternative Boolean algebraexpressions are well worth the extra effort. You will gain extra speed and muchless required code. Consider the following

    Instead of this

    IF Player_X < 100 Then Player_X = Player_X + 1

    Do this

    Player_X = Player_X + (Player_X < 100) * - 1

    Inside the brackets is the actual condition. The Player_X variable will always beincremented by 1 on the condition that its less than 100. You can also place ahost of many different conditions inside the brackets which may include othervariables that maybe outside the scope of what youre actually incrementing.Theres no need to use IFs for such simple things. Dont make things complexwhen they dont need to be. Restrict IFs for other more complex scenarios.

    Sprites

    There is no exact, official definition for a sprite. The terminology for it is extremely

    broad and quite confusing. Arguably, traditional sprites were developed to quicklycomposite acollection of individual pieces together from character maps that

  • 8/6/2019 Developing VB Games

    8/10

    gave the illusion of one actual image. Most commonly, nowadays with moremodern video games, sprites refer to separate images that are integrated into thebackground scenery. The characters that you see moving around on your screenare in fact considered as sprites. Nintendo refer to sprites as objects that storescreen coordinate information for obvious collision detection purposes. This is far

    closer to my first initial suspicions. Another synonym for sprite is BOBs, or BlitterObjects. I personally perserve sprites as graphical objects.

    For you, as a Visual Basic programmer, a sprite should represent something thatthats a way in which you can collate a collection of one or more graphicalimages and screen coordinates together into one neat package. You essentiallycreate the sprites by blitting the images to the screen and keeping tabs on theirexact location by either using Type variables or, by using objects like VBs shapeor Line to constantly track / monitor their location on the screen.

    Collision Detection

    By using VBs internal shape object we can constantly monitor the graphics bytracking their movement. When the images on the screen are moved, the shapesmove in the exact same manner. When required, the shapes can be passed to acollision detection procedure for checking. The shape object is perfect for thissince it has all the directional and size properties that we need. X-axis, Y-axis,height and width parameters that will need to be set to match the size of theimage. This method helps with debugging since you can make the shapes visibleand watch them move in the exact same accordance as the images. Obviously,at any other time the shapes visible property will be set to false. If some of thegraphics need to be rotated, VBs line object will do nicely.

    Public Function Sprite_Collision(Player As Object, Target As Object) As Boolean'-------------------------------------------------------------------------------

    'This is quite comprehensive, checking all 4 corners and also to see if the '

    'sprite is inside another which may occur if one is much larger than the other '

    '-------------------------------------------------------------------------------

    '//

    Dim Player_X1 As Long

    Dim Player_X2 As Long

    Dim Player_Y1 As Long

    Dim Player_Y2 As Long

    Dim Target_X1 As Long

    Dim Target_X2 As Long

    Dim Target_Y1 As Long

    Dim Target_Y2 As Long'//

    'wall locations player and targetPlayer_X1 = Player.Left 'left Wall

    Player_X2 = Player.Left + Player.Width 'right Wall

    Player_Y1 = Player.Top 'top Wall

    Player_Y2 = Player.Top + Player.Height 'bottom Wall

    '//

    Target_X1 = Target.Left 'left Wall

    Target_X2 = Target.Left + Target.Width 'right Wall

    Target_Y1 = Target.Top 'top Wall

    Target_Y2 = Target.Top + Target.Height 'bottom Wall

    '//

    '-----------------------------------------------------------------------------

    'all 4 corners, sprite to sprite '

    '-----------------------------------------------------------------------------

    If ((Player_X2 >= Target_X1) And (Player_X1 =

    Target_Y1) And (Player_Y1

  • 8/6/2019 Developing VB Games

    9/10

    'sprite inside sprite?, check all 4 corners again, sprite to sprite '

    'a sprite inside another sprite occurs when on is much larger than the other '

    '-----------------------------------------------------------------------------

    ElseIf ((Target_X2 >= Player_X1) And (Target_X1 =

    Player_Y1) And (Target_Y1

  • 8/6/2019 Developing VB Games

    10/10

    for even further desired precision, I think its really uncalled for. Especially whenyou consider that youll probably move the image with increments of at least 5pixels at a time. The bottom shape in figure 4 only overlaps the image by a fewmere pixels. Plus, most images that you will use will be far more symmetrical.

    DirectX or API ?

    Personally, I have never as such made a game using Direct X. I do know all itsstrengths and I also know its weakness. The further in depth that I travel with VBthe more Im starting to favor the possibilities of implementing it within a game.I see using Direct X as something of questionable practicality. The questions youneed to ask yourself in attempts of deciding as to if you need it or not are

    1. Is the game 3D?2. How complex are the graphics for?

    3. Does the targeted audience have the computing power for it?

    I have seen two similar like NES emulators that both share almost identical codewith the exception that one uses Direct X and the other implements an array ofAPIs to do most of the work. In terms of performance, theyre almost on par. Thegraphics are neither 3D nor complex in any of the NES games. With the Direct Xemulator, I see this as a waste of resources with power that will never be fullyunleashed. I will reserve my final conclusions about DirectX until I actually havethe chance to fully use it within a completed project.

    There are a number of restrictions with relying solely on APIs. Especially with

    sound. I have seen no real easy way of being able to channel through multipleoccurrences of different sound effects. In other words, mixing. Direct X allowsyou to easily mix music and sound effects with minimal code. I see the biggestweakness of Direct X as being compatibility. There are too many versions of itthat will undoubtedly restrict your game to a limited audience.

    Playing The Game Is All Part Of It

    In the final stages of developing a game, theres a lot of time thats required toensure that your users get the most possible entertainment out of it. The onlyway to do this is to play it. On a trial and error basis, youll need to tweak things

    as you play. If you dont enjoy playing it, chances are then, neither will youraudience. As the old saying goes, dont feed someone else something to eatthat you wouldnt eat yourself A big, big part of it all really is playing the game.