BİLGİSAYAR

Game Programming Tutorials
Hello everybody, here is my old game programming Tutorials if you missed them last time.
They discuss coming up with ideas, through to, simple implementation techniques. I hope they are still some use.
Which arm is longer?

Ideas
Ideas are the starting point of any program – game or not. Some ideas are more original than others - Doom clone anyone?
Originality is great, but you need a good game. Despite the latest in modern gaming I had to offer, my flatmates most popular game was DX-Ball, an arkanoid clone (try www.windows95.com). (They were playing DX-Ball because they were bored with freecell!)
I may seem to be arguing with myself in the two previous paragraphs, but this is merely friendly discussion. I propose that originality of the individual idea is not required as long as you think you can implement that idea better than those before you have.
So what I am saying is;
• Intermediate, beginner level programmers should come up with an original idea to be successful – people don’t want clones that aren’t as good as the real thing.
• Expert programmers can afford to release Slamm III and Slapshot 98, just a bit more advanced than last years version for a proven market.
What are ideas anyhow?
Well don’t worry this is not a metaphysical discussion – here is David’s definition of ideas;
“what you think you’re going to do - before you do it.”
Ideas form the blueprint for your game. These ideas may include plot or character sketches, action moves, diagrams of puzzles, interface concepts, dialog, even a specific programming technique to exploit.
How do I get them?
If you are anything like me, you will probably have way to many ideas, both for projects to do, and for aspects of those projects. But lets face it you are better off finishing 1 game than starting 30. (I really should learn from that)
Here’s a simple three step process to better abs… ideas, (too many American infomercials) you can repeat as many times as you require;
1. Stimulation (e.g. play other games, watch videos, movies, read books, music whatever)
2. Scribble (write down a bunch of stuff you are thinking of so you can remember it later)
3. Discuss ( brainstorm – with a group of people to refine your ideas and come up with new ones)
Just hope that the people you brainstorm with aren’t too critical of your lame ideas, even the most stupid suggestion may surprise you. Who would have thought a game with odd shaped falling blocks would take the world by storm (Tetris for those of you who don’t remember the 8-bit days).
The real world
With these wonderful ideas firmly in mind you go about implementing your program. You will probably find it’s just not possible to do it the way you had planned, or you come up with better ideas along the way.
This is probably a good thing, if you were able to achieve your ideas exactly you would have to be a master at planning. It is almost inevitable that as you develop your game you find your ideas were perhaps a bit ambitious or you think of a new idea or twist (within reason say the schedulers among us).
Now you have ideas, what makes a game?
For more on this topic see Greg Costikyan’s article “I have no words & I must design”
What’s not a game
• Puzzles – puzzles are static, not interactive. Good games probably have puzzle elements, but they should not be JUST a puzzle.
• Toys – toys are interactive, but have no goal. e.g. playing with blocks, sim-city.
• Stories – stories are linear, games are not. Any presentation of narrative should still allow for the user to make their own decisions.
What is a game
• Decision making - Interaction in itself does not make a game, the interaction must have outcomes. Hence the player makes a decision about what action to take which results in an outcome.
• Goals – There needs to be goals in a game so players can mark their progress – the quality of their decisions. E.g. points, survival, increased functions.
• Opposition – It is no fun playing with yourself. Remember it should be a struggle, it is also no fun to win too easily.
• Managing Resources – Part of the decision making progress is management of resources. E.g. should you use the extra ammo?, the health shield?, send those extra troops to the front?, spend the money on new tyres?.
• Information – A player needs information to make decisions. Information adds to the experience and realism of the game, also as a player becomes more experienced the information can be understood at greater levels of subtlety resulting in better tactics. E.g. use the wind meter when making the golf shot, listen for screams round the corner in an action game, read up background biographies in an adventure game.
What can make a better game
• Diplomacy – Multi-player games should encourage diplomacy (read social interaction). e.g. gang up on someone, go easy on a new member, perhaps help another group in an RPG although the long term goal may be different.
• Art – Not just graphic art, but the art of presentation. Anyone prefers a game with atmosphere that looks and sounds great - and plays easily (read good user interface).
• Simulation – This is taking real (or fictional) situations which people are familiar with and handing them the controls. This immediately gives you a basis of communication – famous characters or objects, the history and background, and the basic premise. E.g. fly a plane, control a city, command an army…
• Variety – Well this stands to reason, tic-tac-toe won’t keep people interested for long. You can provide variety in several ways, a) variety through random elements e.g. bonuses, good fortune, luck, b) through complexity of environment, c) progressive gameplay, e.g. the game changes as you progress
• Role-playing – Role playing is not simply presenting the player with a persona to assume e.g. batman, duke nukem, but putting the player in a social environment were they play a role in respect to their interactions with other players. E.g. the player is Barry the barbarian or Tracy the ruthless tycoon.
• Socializing – It is an interesting aspect that most computer games have been a solitary pass time, yet other forms of games are almost all social in nature, e.g. sport, cards, board games… The Internet is now making multiplayer gaming a technical possibility, but I would suggest they will really take off when the social aspect is exploited. I don’t know about you, but after my first game of Net Doom with my friends, the big difference I noticed was not the improvement over computer AI (infact charging the enemy.. or walls with rocket launchers seemed very popular) but the social aspect (never yelled over a computer game before).
• Tension – Just like at the movies, the key element of an exciting story is to keep the tension rising until reaching the dramatic ending. Try and save the toughest problems for last, e.g. beat the end of level bad guy, disarm the bomb, save the world.
Basic game categories
Games generally fall into basic categories. You should keep these in mind as far as implementing your game, but you may choose to mix and match parts of each genre.
• Platform Games - Run, Jump and Avoid e.g. Mario, Jazz Jackrabbit, Prince of Persia. Can be non-violent and non-threatening.
• Shooting – If it moves shoot it, you know doom, quake…
• Adventure – Multiple locations, objects, characters and actions aimed at a goal in a specific carefully defined world. Kings Quest, Sam and Max…
• RPG – Multiple locations, objects, characters and actions in a more free form exploration of a usually larger less defined world. Ultima..
• Strategy – Combination of planning, analysis resource management or logic. Chess, Tetris, Civilization, Command and Conquer..
• Fighting – Spinning back kick to the jaw, Mortal Kombat, Street Fighter…
• Simulation – General term to describe “real world games”, flying, driving, sports..
Two basic implementation techniques
You can generally divide the graphics of games programming into two distinct areas (although a game may combine aspects of both.)
• 2D – Sprites, scrolling, bitmaps, video and animation - FLAT
• 3D – Free viewpoint, textured polygons - NOT FLAT
That may seem simplistic, but basically 2D and 3D graphics are very different techniques.
We will cover the basics of 2D graphics later on. Its basically a fairly straightforward concept – images (like paper cut-outs) are located where you want on the screen…
3D games meanwhile involve a lot more work (and maths!). Luckily (?) there are all sorts of people trying to develop 3D API’s for you to use.
I will be including some samples of Microsoft’s Direct3D Retained Mode interface (the easy one) and have a look at OpenGL (despite Microsoft’s claims, a competing API). Thanks to Patrice Scribe for the wonderful type libraries that make this possible.
Implementing your ideas
Where do you start?
Technique
You need to establish early on (read start) of your project what techniques you will use – and you need to make sure you can do it.
The techniques required may be obvious from your ideas, or they may still be undefined. E.g. will your adventure game be first person like Myst (scale and character not required), will characters be able to walk around like in Sam and Max, or will you have a little 2D square playing field like Indiana Jones’s desktop adventures?
Now you need to research and test until you have a mock up of the technique sufficient to satisfy you that you can do the whole project. There is no point starting on a quake clone, 6 months into the project with music, textures and 3D models – but no hope of a 3D engine.
Research is not as bad as it sounds, there are tonnes of books, articles, web sites and source code to point you in the right direction. I will even include a modest sample of 2D stuff later on including three worked examples. You never know you may have some new ideas everyone else might want to hear.

Brief
Its time to do a rough plan. Before you commit all you spare time for months to a project, sketch out a storyboard for your game, illustrating it cool points – and its basic premise.
Draw up a list or resources required Personnel (you may need artists, music gurus, programmers, writers…), time (you know that stuff that there is NEVER enough of - unless you’re at the dentist), and equipment (computers, software, video, midi keyboards..)
Reality Check
Right - you have got your technique tested, you have a concise brief describing your game - now check the following.
1. Possible – just make sure (again) you genuinely think you can pull off the technical bits
2. Practical – is the scope of the project within your grasp, remember the best game is a finished game
3. Property – do you have the money and resources (or the right contacts). Remember video equipment, artists, ILM special effects and Arnold Schwarzenegger don’t come cheap.
4. Potential – what do your friends (publisher, co-worker..) think of your game, would they want to play what you are describing?
This stage can save a lot of disappointment and lost work. Should you fail the reality check its time to rework your brief.
How do you start?
Break your game into components
Basic categories of “components” that you will need for your planning include;
• Game engine
• Extra programming (installation, extra puzzles..)
• User Interface design
• Assets (Models, Art, Sound Effects, Music, Video)
• Content editor and utilities (e.g. level editor and sound conversion..)
• Content designs (e.g. level’s)
Plan, Plan and Plan some more
If your game is a large project, especially if your team is larger than one person, you owe it to yourselves to get organised. Get some idea on a timeline of who does what when. E.g. tell your artist roughly what art, when, what size, resolution and colour depth.. etc
Evaluate Key techniques in detail
Well you have made sure you can blit a screen full of diamond tiles fast enough, now its time to add buildings and trees and get the whole thing scrolling.
Early on in the implementation phase you need to break the back of the main technical issues, these will make planning difficult. If you don’t know how to do it, how can you estimate how long it will take?
If its not working fast enough, or just not working then you need to;
1. do some more research,
2. buy some technology, or
3. scale down your game.
Huh?
If at this point you are wondering what you missed (where are all the explanations of how to MAKE A GAME? ) well that’s still pretty much up to you, programming is fairly creative and there are lots of different styles and techniques.
Don’t worry though, here are some links to some good places to start, and I have even included some basic techniques along with some worked examples.
Following through
Working in teams
Milestones
Tie up the loose ends
Some programming techniques for you to use
Classes & collections
Relatively new to VB is the ability to take advantage of classes, your own little object templates. MS has also been considerate enough to provide collections, the ability to dynamically manage a group of objects.
Very quick OOP tutorial
A class is a template from which you can create objects.
Each object has its own data space for its properties, and shares the methods and event code with other objects of the same class.
Think state housing, you can take the blueprint of a state house and build 30 different identical buildings. You can then go through and alter the properties of the individual objects (houses) and paint each one a different, disgusting pastel shade.

The VB manual even describes classes and “user-defined types with attitude” because you can store the events and methods along with the data (encapsulation).
So why bother?
Well collections make all this new-age OOP stuff worthwhile. They provide a simple way to dynamically manage objects. Collections also provide indexing so you can find specific objects quickly in large collections.
Because objects can contain collections of other objects you can create structures that you would have needed pointers (urgh) for before.
For example in a RPG;
Player Class contains properties like name, age, gender, height, experience, speed, agility, strength, stamina… and a collection called holding
This collection contains a group of other objects like clothes, knife, backpack. Each of these objects has their own properties. The backpack for example contains properties like size, colour AND a collection called holding. This collection can in turn “hold” other objects!
Even better VB5 provides a class wizard that makes it easy to create and maintain the interfaces to your classes.
Some Source Code!
Here’s some fragments of code you will want to get familiar with;
• Dim my_axe as Axe (dimension a variable of type Axe)
• Set my_axe as new Axe (set the variable to a new instance of a Axe class, a new object)
This means you now have a working and ready to use object, my_axe which is explicitly of type Axe (your class). If you want to be really flexible you can define my_axe as Object. This means you can set my_axe to any new object.
• Dim my_axe as Object (dimension a variable of type any object)
• Set my_axe as new Whatever (set the variable to a new instance of any object)
However this uses late binding, because it does not know what object will be used until you do the set statement. This is slightly slower, so if you can help it try and be explicit as above.
p.s. now you have an object you can use it just like other vb objects, e.g. text1.text=”test” or my_axe.sharpness=400.
What about collections? Right, good point.
• Dim holding As New Collection
I now have a variable called holding which is a collection which can contain a group of any sort of objects.
• holding.Add my_axe, “axe” (adds a new objects, my_axe, and an optional text index “axe”)
• holding.count (tells you how many objects in the collection)
• holding.remove “axe” (removes the object from the collection which has a text index “axe”, you could equally remove the item in ordinal position, e.g. holding.remove 2 removes the 2nd item in the collection.)
p.s. before you could add the item my_axe, you have to dimension a variable my_axe as axe, and set my_axe = new axe – then set any properties you want for that specific axe before you add it to the collection.
That’s how to add, count and remove items in a collection. But I have saved the best till last – the for each construct.
• For Each player In players
• Next
Where players is a collection of objects of class player. You can now write code that will work on each object in a collection.
• For Each player In players
o If player.speed < 50 Then
 player.die
o End If
• Next
BitBlt
The taxonomy of a bitblt. Lets just say that bltblt’s are still faster than the new VB paintpicture method. Essentially what you are doing is copying a chunk of memory from one place to another. This chunk is visually rectangular in shape.
Declare Function BitBlt Lib “gdi32″ (ByVal hDestDC As Long, ByVal X As Long, ByVal Y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long, ByVal dwRop As Long) As Long
Public Const SRCAND = &H8800C6 ‘ (DWORD) dest = source AND dest
Public Const SRCCOPY = &HCC0020 ‘ (DWORD) dest = source
Public Const SRCINVERT = &H660046 ‘ (DWORD) dest = source XOR dest
Declare Function sndPlaySound Lib “winmm.dll” Alias “sndPlaySoundA” (ByVal lpszSoundName As String, ByVal uFlags As Long) As Long
Add these declares to a BAS module in you project. (I added the sndPlaySound function cause it’s a really easy way of playing wave files, just tmp&=sndPlaySound(”mywave.wav”,1))
Right, what does the different parameters of the bitblt do?
• HDestDC this is the destination HDC (handle to a Device Context) read - form or picture box
• X,Y is the position the destination rectangle will start at
• NWidth, nHeight is the width and height of the rectangle
• HSrcDC is the source HDC – read form or picturebox
• XSrc, ySrc provide the offset, or position the source rectangle starts at
• DwRop is the Raster Operation – read what boolean operation to apply
The key to using bitblt easily is that pictureboxes make great sources for BitBlting. If you make a picturebox autoredraw=true and visible=false then load a picture into the picturebox, it will create an offscreen buffer for you to blt from.
e.g. tmp& = bitblt(form1.hdc,10,10,20,20,picture1.hdc,0,0,srccopy)
Now, form1 is the destination for the bitblt, (where you want the picture to appear). 10,10 is the pixel offset into form1 while the rectangle will be 20 pixels square. Picture1 (invisible and autoredraw=true) is the source image, the chunk taken from 0,0 and srccopy the operation. (srccopy just copies the data)
Sprites
Whats a sprite
Well now that you know a bit about bitblting, lets find out how to blt sprites. Sprites are little irregular images, i.e. NON rectangular.
To make these irregular shaped images we need some trickery, now while you may eventually, or already have, custom routines to blt sprites rotated, sheared, transparent and lit – I am going to focus on using bitblt.
The technique I will show is called masking. The idea is that an image has an associated mask. This mask is applied first, leaving a hole for the image. This is achieved through ROP’s or raster operations. This is boolean logic on a large scale.
Masks are designed white, with black where they should leave a “hole”. To apply the mask to the destination image, rather than just copying the image, we need to SCRAND the mask with the image. This means to make a logical AND of each pixel. The result is that the destination pixel AND’ed with white is the destination pixel, while the destination pixel AND’ed with black is black (the “hole”).
The image can then be applied. The image should be designed to be black where the mask was white, and coloured where the mask was black. Once again a straight copy is not appropriate as this would not be irregularly shaped. We use SCRINVERT, this is a logical XOR. The result of this is that the destination XOR’ed with the black surroundings is the destination, and equally the black destination pixels from our mask, XOR’ed with the coloured centre of the sprite result in the coloured centre of the sprite.
Here’s a diagram,
Check out the example programs later on for some source code. (whackarat)
Double Buffering
Well the problem with masking, and games in general is that things move around all the time, if computers were infinitely fast this would not be a problem – but as we well know, they bloody well are not. Hence to stop a nasty looking kind of partial redrawing, half done, flickery kind of look, adding buffering to your games is a good plan.
This can be easily described – draw it offscreen, then when you have done all the messy stuff, copy the whole lot to screen.

To see some samples of this in use, check out the examples later on. (whackarat)
DirectDraw
Well MS have come to the “rescue” of beleaguered game developers, providing a standard hardware independent API for fast gaming. However despite its critics, it has made Windows95 gaming a reality. Whats more all that masking and double buffering stuff above is BUILT IN!
Now thanks to Patrice Scribe VB programmers can use DirectX too. I am just going to stick to DirectDraw (the basics) for now. I would recommend downloading the MS SDK to find out more.
Remember you need Patrice Scribes type libraries.—
Steps
• Choose windowed, or a specific full screen mode (e.g. 640 x 480, 16 bit colour)
• Dimension a directdraw object
• Make some DirectDraw surfaces
• Load bitmaps into some surfaces (apply a transparent colour key if required)
• Do your bitblting in a game loop until game finishes
• Set objects to nothing
• Restore the screen
Sounds easy?, well I hope so, cause that’s a real simple overview of the main steps. Luckily, you can just use code from someone else, you don’t really need to know the details of what each bit does.
Hence heres a simple framework to download don’t forget to check out the menace sample code.
Here is the code and descriptions of what It does.
Boring Declares, you need to add your variables, and any surfaces for bitmaps you want to add.
Dim u As Long
Dim blnend As Boolean
‘ Win32
Const IMAGE_BITMAP = 0
Const LR_LOADFROMFILE = &H10
Const LR_CREATEDIBSECTION = &H2000
Const SRCCOPY = &HCC0020
Private Type BITMAP
bmType As Long
bmWidth As Long
bmHeight As Long
bmWidthBytes As Long
bmPlanes As Integer
bmBitsPixel As Integer
bmBits As Long
End Type
‘ GDI32
Private Declare Function GetPixel Lib “gdi32″ (ByVal hdc As Long, ByVal x As Long, ByVal y As Long) As Long
Private Declare Function CreateCompatibleDC Lib “gdi32″ (ByVal hdc As Long) As Long
Private Declare Function DeleteDC Lib “gdi32″ (ByVal hdc As Long) As Long
Private Declare Function DeleteObject Lib “gdi32″ (ByVal hObject As Long) As Long
Private Declare Function GetObject Lib “gdi32″ Alias “GetObjectA” (ByVal hObject As Long, ByVal nCount As Long, lpObject As Any) As Long
Private Declare Function SelectObject Lib “gdi32″ (ByVal hdc As Long, ByVal hObject As Long) As Long
‘ USER32
Private Declare Function GetDC Lib “user32″ (ByVal hwnd As Long) As Long
Private Declare Function LoadImage Lib “user32″ Alias “LoadImageA” (ByVal hInst As Long, ByVal lpsz As String, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
Private Declare Function StretchBlt Lib “gdi32″ (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long, ByVal nSrcWidth As Long, ByVal nSrcHeight As Long, ByVal dwRop As Long) As Long
Private Declare Function ShowCursor Lib “user32″ (ByVal bShow As Long) As Long
Const ResolutionX = 640 ‘ Width for the display mode
Const ResolutionY = 480 ‘ Height for the display mode
Dim dd As DirectDraw2 ‘ DirectDraw object
Dim ddsdFront As DDSURFACEDESC ‘ Front surface description
Dim ddsFront As DirectDrawSurface2 ‘ Front buffer
Dim ddsBack As DirectDrawSurface2 ‘ Back buffer
Dim ddCaps As DDSCAPS ‘ Capabilities for search
Dim fx As DDBLTFX
‘******************************
‘your own surfaces here , e.g.
Dim aDDS As DirectDrawSurface2 ‘ Images to blit
Dim tDDS As DirectDrawSurface2 ‘ tiles to blit
‘ Loads a bitmap in a DirectDraw surface
Private Function CreateDDSFromBitmap(dd As DirectDraw2, ByVal strFile As String) As DirectDrawSurface2
Dim hbm As Long ‘ Handle on bitmap
Dim bm As BITMAP ‘ Bitmap header
Dim ddsd As DDSURFACEDESC ‘ Surface description
Dim dds As DirectDrawSurface2 ‘ Created surface
Dim hdcImage As Long ‘ Handle on image
Dim mhdc As Long ‘ Handle on surface context
Dim clr As Long ‘hold the colour top left to be made transparent
‘ Load bitmap
hbm = LoadImage(ByVal 0&, strFile, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE Or LR_CREATEDIBSECTION)
‘ Get bitmap info
GetObject hbm, Len(bm), bm
‘ Fill surface description
With ddsd
.dwSize = Len(ddsd)
.dwFlags = DDSD_CAPS Or DDSD_HEIGHT Or DDSD_WIDTH
.DDSCAPS.dwCaps = DDSCAPS_OFFSCREENPLAIN
.dwWidth = bm.bmWidth
.dwHeight = bm.bmHeight
End With
‘ Create surface
dd.CreateSurface ddsd, dds, Nothing
‘ Create memory device
hdcImage = CreateCompatibleDC(ByVal 0&)
‘ Select the bitmap in this memory device
SelectObject hdcImage, hbm
‘ Restore the surface
dds.Restore
‘ Get the surface’s DC
dds.GetDC mhdc
‘ Copy from the memory device to the DirectDrawSurface
StretchBlt mhdc, 0, 0, ddsd.dwWidth, ddsd.dwHeight, hdcImage, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY
‘get the top left colour
clr = GetPixel(mhdc, 0, 0)
‘ Release the surface’s DC
dds.ReleaseDC mhdc
‘ Release the memory device and the bitmap
DeleteDC hdcImage
DeleteObject hbm
‘make surface transparent
Dim mhddck As DDCOLORKEY
mhddck.dwColorSpaceLowValue = clr ‘really works only for 24 bit colour
mhddck.dwColorSpaceHighValue = clr ‘but as sprites have black is all 0 at any rate
dds.SetColorKey DDCKEY_SRCBLT, mhddck
‘ Returns the new surface
Set CreateDDSFromBitmap = dds
End Function
Private Sub Form_KeyPress(KeyAscii As Integer)
‘quit out for now
blnend = True
End Sub
Add you own images to be loaded in here, and any data you may want to load like maps…
Private Sub Form_Load()
ShowCursor 0
‘ Create the DirectDraw object
DirectDrawCreate ByVal 0&, dd, Nothing
‘ This app is full screen and will change the display mode
dd.SetCooperativeLevel Me.hwnd, DDSCL_EXCLUSIVE Or DDSCL_FULLSCREEN
‘ Set the display mode (16 is the bit depth)
dd.SetDisplayMode ResolutionX, ResolutionY, 16, 0, 0
‘ *****************************
‘ Load your own images, e.g.
Set aDDS = CreateDDSFromBitmap(dd, App.Path & “\menace.BMP”)
Set tDDS = CreateDDSFromBitmap(dd, App.Path & “\tiles.BMP”)
‘ Fill front buffer description structure…
With ddsdFront
‘ Structure size
.dwSize = Len(ddsdFront)
‘ Use DDSD_CAPS and BackBufferCount
.dwFlags = DDSD_CAPS Or DDSD_BACKBUFFERCOUNT
‘ Primary, flipable surface
.DDSCAPS.dwCaps = DDSCAPS_PRIMARYSURFACE Or DDSCAPS_FLIP Or DDSCAPS_COMPLEX Or DDSCAPS_SYSTEMMEMORY
‘ One back buffer (you can try 2)
.dwBackBufferCount = 1
End With
‘ Create front buffer
dd.CreateSurface ddsdFront, ddsFront, Nothing
‘ Retrieve the back buffer object
ddCaps.dwCaps = DDSCAPS_BACKBUFFER
ddsFront.GetAttachedSurface ddCaps, ddsBack
End Sub
Heres where everything happens, insert your game here! The drawnextframe subroutine is called in a tight loop – updating as fast as possible.
I have put a stupid example in here for you, painting the backbuffer black, and copying a bit of bitmap to the same place every frame.
Useless I know, but I included the clearbackbuffer, as it may come in handy for asteroids type games where you want to start with a new black screen every frame.
The sample bltfast routine is just to show you how it works. You basically use the RECT to describe where from your surface you want to pull the graphics from. You then reference ddsBack (the back buffer you draw on, and we later flip to the front) method bltfast with the x and y position for the sprite, your sprite surface, the aforementioned RECT and some constants.
p.s. If you want your blit to be a solid rectangle rather than irregular use DDBLTFAST_NOCOLORKEY instead of DDBLTFAST_SRCCOLORKEY
Private Sub DrawNextFrame()
‘you may wish to clear the beackground first e.g.
ClearBackBuffer
‘do your bltting in here. This is where all the good
’stuff goes e.g. a simple example
Dim t As RECT
t.Top = 10
t.Left = 10
t.Right = 100
t.bottom = 100
ddsBack.BltFast xx%, yy%, tDDS, t, DDBLTFAST_SRCCOLORKEY Or DDBLTFAST_WAIT
‘beware BltFast relies on you making sure
‘the rectangle is not bigger than the
’screen.
‘flip the buffers
Do
ddsFront.Flip Nothing, 0
If Err.Number = DDERR_SURFACELOST Then ddsFront.Restore
Loop Until Err.Number = 0
End Sub
Sub ClearBackBuffer()
Dim t As RECT
‘On Error Resume Next
‘ Clear the back buffer
With fx
.dwSize = Len(fx)
.dwFillColor = RGB(0, 0, 0)
End With
t.Top = 0
t.Left = 0
t.bottom = ResolutionY
t.Right = ResolutionX
ddsBack.Blt t, Nothing, t, DDBLT_COLORFILL, fx
End Sub
Here’s the main tight loop, followed by the clean up stuff…
Private Sub Timer1_Timer()
Timer1.Enabled = 0
‘Render loop
While Not blnend
DrawNextFrame
u = DoEvents
Wend
‘clean up
Set aDDS = Nothing
Set tDDS = Nothing
dd.FlipToGDISurface
dd.RestoreDisplayMode
dd.SetCooperativeLevel 0, DDSCL_NORMAL
Set ddsBack = Nothing
Set ddsFront = Nothing
Set dd = Nothing
ShowCursor 1
Unload Form2

Related posts

Etiketler:

Korku Oyunları

Komik Videolar

Aşk Şiirleri