Click here to Skip to main content
Click here to Skip to main content

Falling Blocks

By , 17 Apr 2008
 

Falling Blocks

The controls for the game are simple. Use the Left arrow and the Right arrow to move the block left or right. Up arrow or R to rotate the block. Down arrow to move the block down faster and the center key (5) to drop the block.

The objective is to get continuous blocks in a row. A row filled with blocks are removed and points are given.

Sample Image

Software required to build the project:

  1. Visual C++ 6.0
  2. DirectX 8.0 SDK (DirectX 7.0 SDK should also work but I have not tried it)

Software required to run the game:

  1. DirectX 7.0
  2. Windows 2000 or Win9x

This code should help you create small games using DirectX. I have sprinkled comments all over the code so it should help you with understanding the code.

The Code

The project consists of the following classes:

  1. CBlockList
  2. CDisplay
  3. CFlooredBlocks
  4. CShape
  5. CSurface

The classes CDisplay and CSurface are created by Microsoft and are shipped along with the DirectX SDK. I developed this game using DirectX 8 SDK. It should work fine with DirectX 7 but I have not tried it. To run the game, DirectX 7 is all that is required. You will have to adjust the project setting to reflect your DirectX SDK paths.

The game creates two shapes when the game starts. One is the shape currently falling and the other is the next shape. When a shape hits the bottom, it is added to the Floored Block list and a new Next shape is created.

For each line of blocks removed, 10* NumberOfLinesRemoved* NumberOfLinesRemoved * GameSpeed points are given.

Game is over when a shape hits the bottom and some of the blocks are above the grey line. You can start a new game from the menu.

Under the level menu, you can select the game speed. If you set the game to crazy mode, you will get weird shapes. It is easy to add your own shapes in this game. All you have to do is add the shape to the array and update the array information.

m_pStockShapes array holds the shape definitions.

const short CShape::m_pStockShapes[] = { 
     11,   // No Of shapes in the array
     2 /*No of orientation shapes */, 4 /*No Of blocks for this shape*/,
     2,1, 2,2, 3,2, 3,3,     //  O
     1,2, 2,2, 2,1, 3,1,     //  OO 
                             //   O 
     0,   // Each shape ends with a 0
}

SBlock structure holds the block coordinates and the color.

struct SBlock {
  Short nX,nY,nColor;
};

CBlockList will be the parent class for the CShape class and the CFlooredBlocks class. It contains the methods to maintain the linked list.

class CBlockList {
public:
    // Return true if the given location is already occupied
    bool IsOccupied(short nX, short ,nY) ;
    //Inserts the block based on the value in linked list.
    bool Insert(Sblock Block);
    // Adds the block to the end of the list.
    bool Add (const Sblock Block) ;
    // Displays the block on the screen offsetting it by nX and nY.
    void Display(short nX=0; short nY);
    //Deletes the block from the list.
    bool Delete(Sblock Block);
    // Empties the linked list.
    void Destroy();
   
};

The CFlooredBlocks maintains the list of blocks that have been placed on the floor. All the shapes that fall down are added to this list.

class CFlooredBlocks: public CBlockList {
   RECT m_rcBoundary;   // Holds the playing area
public:
   void Display();
   short CheckAndRemoveContinuousBlocks(); 
     // Returns the number of lines removed. 
     // This can be used to calculate the score. 
     
   IncrementYabove(short nY); 
     // Helper function for CheckAndRemoveContinuousBlocks 
     // used to drop the blocks above the removed line.
     
   bool IsOccupied(nX,nY);
   // Returns true if the coordinates are occupied.
   
   bool Insert(Sblock Block);
};

CShape class creates the shapes from the given array. It helps with moving the shape and checks if it had gone outside the boundary or hit any other blocks.

class CShape:public CBlockList {
     CFlooredBlocks* m_pFlooredBlocks;
public:
     bool CreateRandShape(); 
       // Creates a shape from the build in shapes at random. 
       // This function creates the blocks and gives it the color;

     bool MoveTo(x1,y1);  //Moves the shape to the given coordinates.
     bool MoveRight(); // Moves the shape right. Returns true if successful.
     bool MoveLeft();
     bool MoveDown(); // Moves the shape down. 
     bool Rotate();   // Rotates based on the shape.
     void Display();  // Displays the shape
     
     void ConvertToSpaceCoord(); 
       // Converts the internal SBlock to contain the actual 
       // coordinates so that it can be added to the floored list.
       
     bool SetMaxNoOfShapesAllowed(short nMac); 
       // Sets the maximum number of shapes that 
       // will be used from the array. This way you 
       // can added new shapes to the array and active
       // it by changing this value.
};

Look at the code and everything should be self-explanatory. Have fun. Make games and share your knowledge :)

History

5 Apr 2002 - new VC7 project, with files to make it easier for those having difficulties setting directories for SDK files.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Xavier John
Software Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralSyntax Error / RedefinitionsussAnonymous14 Jan '03 - 7:54 
Hello,
I'm trying to compile this code under .NET
I get a series of compile errors
C2501 -- missing storage-class or type specifiers
C2227 -- -> must point to class/struct/union
C2086 -- int CSurface redefinition
C2061 -- sytax error : identifier CDisplay
C2143 -- syntax error : missing ; before *
------------------------------------------------------
I have all the mssdk files in my compile directories
 
any help would be greatly appreciated Confused | :confused:

GeneralGreat game, Great code!sussAnonymous6 Nov '02 - 22:50 
It's 100% working! and people, plz configure your vc++ and dxsdk properly before saying anything
 

Great thanks to the author Smile | :)
 


Questionhow to add new blockssusswei10 Sep '02 - 21:00 
Hi,
 
could some one give more explaination about the shape array?
 
for example, why do
1,2, 2,2, 3,2, 4,2,
2,1, 2,2, 2,3, 2,4,
 
represent a bar?
 
thanks
 
willy
AnswerRe: how to add new blocksmemberPaul Watt30 Oct '02 - 6:24 
It looks like he defines how many different orientations the piece has, then for each orientation he defines where a block should be located. for the example he displayed, the line piece, and there are basically only two orientations for the line, vertical and horizontal. He defines both of them there. Then when the pieces rotate, he simply cycles through the orientations that he has recorded for each piece.
 

Build a man a fire, and he will be warm for a day
Light a man on fire, and he will be warm for the rest of his life!

GeneralCompiler Error :(memberSelevercin21 Jul '02 - 3:42 
Hi,
 
I know I'm doing something very stupid. I keep getting this compile error:
 
fatal error C1083: Cannot open source file: 'C:\My Documents\Nic\Visual C++\Visual C++ Programms\DirectX games\common\src\ddutil.cpp': No such file or directory
 
I think I need to change the directory information, but how and where?
 
Thanks,
 
~ Selevercin
 
If you have a problem with my spelling, just remember that's not my fault. I [as well as everyone
else who learned to spell after 1976] blame it on
Robert A. Kolpek for U.S. Patent 4,136,395.

GeneralRe: Compiler Error :(sussAnonymous22 Jul '02 - 4:18 
Maybe you haven't install the directx sdk in your system, or maybe you haven't set the proper directories for your dx system. check it in the option menu
GeneralRe: Compiler Error :(memberYoshua9 Feb '04 - 4:37 
Hey
 
I get the same error? I have the DirectX 8.1 SDK, and other DirectX stuff seems to compile fine :\
 
I also searched for ddutil.h inside my DirectX SDK Include folder, and ddutil.h dont even exist in ther?
 
Any ideas? Could someone possibly send me ddutil.h?
 
Edit Here: Nevermind, i actually found ddutil.h along with the Invasion Source Code. You can find the Invasion Article and Source Code download here, its anyother DirectX example Smile | :)
 
Another Edit: Agh, now i get a ton of other errors, and it also says I need "dxutil.cpp"
 
Cya
GeneralRe: Compiler Error, Fixed :)memberYoshua9 Feb '04 - 5:31 
Hey
 
Its me again, I finally got it to compile. Now this is what I did...
 
You need to get, ddutil.h, ddutil.cpp, dxutil.h, dxutil.cpp. I got them from the Source Code HERE in the Adventures In Abattoirville article.
 
After i got these files, it said (in compile error) it was searching for them in the following directory... Desktop\common\src\ So i simply placed the files there and it compiled fine Smile | :) You can probly specify where the files should be somehow :\ Ohh, you also have to copy ddutil.h to wher you extracted the FallingBlocks_src.zip Source Code.
 
Edit Here: Well I just quickly looked into changing wher to find them files, its easy. The files should be listed under the Common Folder, in the FileView of Visual C++ 6. So just change ther properties... Simple :\
 
Cya
Questionhow to compile your codememberThanks15 May '02 - 21:28 
Hi! I've just download the source code but I don't know how to compile it.
 
What project should I open in the VC6 - a "Win32 Application"?
 
ThanksSmile | :)
AnswerRe: how to compile your codememberXavier John17 Jun '02 - 14:01 
The VC7 project has everything you need to compile.
Generallittle bugmemberAnonymous12 Apr '02 - 10:47 
Snip of code near the end of the loop in CheckAndRemoveContinuousBlocks:
 
pPrev = pCurr;
pCurr=pCurr->pNext;
 
If someone were lucky enough to have removed all the rows, then pCurr->pNext will throw an exception because pCurr will be null.   A simple if statement to check pCurr before that assignment corrects the problem:
 
pPrev = pCurr;
if ( pCurr )
   pCurr=pCurr->pNext;

GeneralRe: little bugmemberLukeV30 Aug '02 - 4:29 
yeah it happened to me twice! Big Grin | :-D
 
---------------
http://www.edovia.com
GeneralRe: little bugmemberXavier John22 Apr '08 - 7:56 
Thanks for the information.
 
The bug is fixed in the VS 2008 zip file.
GeneralImage ToolmemberDon Burton9 Apr '02 - 16:15 
What do you recommend to create the gifs?
 
BTW: My kids love your game. Wink | ;)
GeneralRe: Image ToolmemberJeremy Falcon9 Apr '02 - 17:27 
For me, I use Photoshop and ImageReady. I used to use GIF Workshop until I realized it added extra info in the GIF file.
 
Jeremy L. Falcon
"The One Who Said, 'The One Who Said...'"

Homepage : Feature Article : Sonork = 100.16311

GeneralDX versionmemberMike Nordell9 Apr '02 - 8:27 
Why do you require DX7? Are you actually using anything that's not supported by DX3?
GeneralRe: DX versionmemberXavier John9 Apr '02 - 9:05 
Probably not. I think Dx 3 is good enough for me but I had no interest in going our and finding which is the oldest SDK version I can work with. Besides everything is free so why not use what is there now???
Would you go to a store and ask for 1996 camry because that is all the functionality you need?
And what do I care if my project does not work on NT 4. I make this for my learning and decided to share it. The code ain’t too great either. I could rewrite it much better now if I had the time.

GeneralCoolmemberHockeyDude3 Apr '02 - 3:53 
I love tetris...
 
good job!
 
"An expert is someone who has made all the mistakes in his or her field" - Niels Bohr
GeneralThanks for the article !!memberBraulio Díez21 Jan '02 - 20:49 
Hi,
 
I think tetris is the game the every programmer should make Wink | ;-)
 
Thanks for the sample, if someday I have sometime it will be one of the first examples that I take a look.
 
I don´t if you have written that in your article, but maybe it would be nice in two lines tell in your article how to compile the whole thing, how to get Dll´s and stuff.

Anyway good job ( I´m gonna rate it with excellent)
 
Bye !
Braulio
Generalprobs in NT4.0memberAli Issa7 Jan '02 - 5:40 
i'm trying to get this to work with NT4.0 sp 6a.. but i'm missing some directx dlls .. any idea where i can get these from??
 
CheersOMG | :OMG:
GeneralRe: probs in NT4.0memberXavier John7 Jan '02 - 7:01 
The new versions of DirectX are not supported on Windows NT. Sorry.
www.microsoft.com/directx
 
Regards,
Xavier
 
PS: Windows XP is a great Operating System Smile | :)
GeneralGreat!memberamanjit.gill20 Oct '01 - 14:00 

Nice and comprehensive sample, this will get a lot of people started!
 
at least some real life sample _and_ techn. article
 
good work!! Wink | ;)
GeneralRe: Great!memberXavier John7 Jan '02 - 7:02 
Thanks Smile | :)
GeneralThanksmemberAnonymous5 Sep '01 - 13:37 
After having read all the bad comments about your article from people who would have wanted you to send them files from Microsoft I felt I needed to write something positive cause it is one of the first comprehensive article I find about Direct X and games (a small one...).
 
Thanks for your knowledge
 
Mr Pink
 
P.S. I would need kernel32.dll and gdi32.dll cause you use it in your game and there are not in the zip file with the sources........(Just a joke!!!)
Poke tongue | ;-P
 
Mr Pink
GeneralRe: ThanksmemberTantalus16 Sep '01 - 3:27 
-nt
 
-- Remember your are but a lowly hair on my s*r*t*m
GeneralRe: ThanksmemberXavier John8 Oct '01 - 8:57 
Thanks for the encouragement Smile | :)
 
Guess some people just don’t take the time to read the article properly.

GeneralTotally brokenmemberChristian Graus9 Feb '01 - 11:12 
I downloaded this project to look at how to put a game together in DX with Win32. Unfortunately, you've not written this in a way that will work on other peoples machines. Hard coded include paths, objects I've never seen before ( what on earth is a CDisplay ? Is it a DIRECTDRAWSURFACE ??? ). This could be very useful if you wanted to take the time to make it work properly outside of your system configuration.
 
Christian
 
The content of this post is not necessarily the opinion of my yadda yadda yadda.
 
To understand recursion, we must first understand recursion.
GeneralRe: Totally brokenmemberAnonymous4 Jun '01 - 4:40 
Read the article first then complain
 
The classes CDisplay and CSurface are created by Microsoft and are shipped along with the Direct X SDK. I developed this game using Direct X 8 SDK. It should work fine with Direct X 7 but I have not tried it. To run the game Direct X 7 is all that is required. You will have to adjust the project setting to reflect your Direct X SDK paths
GeneralFailed to rebuild this projectmemberwogo3 Jan '01 - 16:47 
Hi,
It seems taht you forgot to pack the following files in the subdirectories of this project (i.e common, res). So, I'm failed to rebuild this project. The error messages are as following,

--------------------Configuration: FallingBlocks - Win32 Release--------------------
Build : warning : failed to (or don't know how to) build 'D:\TEST\common\src\dxutil.cpp'
Compiling...
FallingBlocks.cpp
D:\TEST\FallingBlock\FallingBlocks\FallingBlocks.cpp(9) : fatal error C1083: Cannot open include file: 'ddutil.h': No such file or directory
ddutil.cpp
fatal error C1083: Cannot open source file: 'D:\TEST\common\src\ddutil.cpp': No such file or directory
dxutil.cpp
fatal error C1083: Cannot open source file: 'D:\TEST\common\src\dxutil.cpp': No such file or directory
Error executing cl.exe.
 
FallingBlocks.exe - 3 error(s), 1 warning(s)

GeneralRe: Failed to rebuild this projectmemberXavier John3 Jan '01 - 17:22 
Those files ship with the Direct X 8 Platform SDK.
I am not allowed to redistribute them in Source Code format. That is Microsoft's EULA.
 
Read the Microsoft's End User License Agreement for more information.
 
To get the program to compile just copy those files from the Direct X 8 SDK or modify the project to point to the correct path.
 
Let me know if you have any questions.
 
Regards,
Xavier
Big Grin | :-D
GeneralRe: Failed to rebuild this projectmemberDon Lazov15 Feb '01 - 1:08 
Yep, those files do exist the author is correct. Just look in your SDK path and look for the headers. I was confused at first when I first got SDK 8, the Microsoft crew used CDisplay for a cool demo but I was baffled until I found the hidden and undocumented class files. Nice of Microsoft to lead us in confusion eh?
 
Zovs
GeneralRe: Failed to rebuild this projectmemberAnonymous13 Aug '01 - 3:02 
My problem is that the DX8 sdk came with many different ddutil.h etc of different sizes. Which ones do I copy?
GeneralRe: Failed to rebuild this projectmemberAnonymous9 Mar '02 - 23:19 
please send this header file.
 
merci.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 17 Apr 2008
Article Copyright 2001 by Xavier John
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid