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

Breakout Game in a Win32 Console

By , 5 Jun 2010
 

Introduction

Designing apps in a Win32 Console environment is quite an adventure. There exist little or no game libraries. This simple app demonstrates how easy it is to create a simple breakout game in a Win32 Console with Visual C++ 6.0. But before we begin, let's talk about a header file called CTextMode.h.

The C Header File CTextMode.h contains the functions that are of outmost importance for the game to be able to position the cursor and text characters in the correct x and y location. Also included in the file CTextMode.h are the functions to draw simple dialogs, draw lines, plot points and of course set a text character's color.

Functions in CTextMode.h:

 delay()         delays x milliseconds
 gotoxy()        Goes to position on 80x25 console screen
 setcolor()      Changes text and background color
 clrbox()        draws colored box without frames
 box()           draws framed box
 gotoxy()        only works with printf(), cprintf() and not cout 

The gotoxy(int x, int y) Method

The gotoxy(int x, int y) method is called upon to set the cursor at a specific x and y location.

void gotoxy(int x, int y)
{
    COORD coord;
    coord.X = x; coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	return;
}

The setcolor(WORD color) Method

The setcolor(WORD color) method is called upon to set the color of text characters.

void setcolor(WORD color)
{
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color);
	return;
}

The clrscr() Method

The clrscr() method is called upon to clear the screen or to fill the screen with specific color.

void clrscr()
{
    COORD coordScreen = { 0, 0 };
    DWORD cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD dwConSize;
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    GetConsoleScreenBufferInfo(hConsole, &csbi);
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacter(hConsole, TEXT(' '), 
		dwConSize, coordScreen, &cCharsWritten);
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    FillConsoleOutputAttribute(hConsole, csbi.wAttributes, 
		dwConSize, coordScreen, &cCharsWritten);
    SetConsoleCursorPosition(hConsole, coordScreen);
	return;
}  

The Game

Our class CBrickGame inherits function methods from the class CTextMode so we need to include this syntax:

CBrickGame::CBrickGame( int i) : CTextMode()

Now after the inheritance, the function methods in CTextMode.h have become "one" with the function methods in our class CBrickGame. We can now treat those methods as if they were native to CBrickGame.
We have also placed function calls we want to be initialized at start up in the constructor so that when our class is being instantiated, those function methods get called and executed.

The project files are:

CBrickGame_main.cpp The main file
CBrickGame.cpp The class definition and method body file
CBrickGame.h The class declaration file
CTextMode.h The Console textmode graphics class

The CBrickGame::putPad(void) Method

The game code itself is quite simple. The user controls the pad by pressing down the left or right key on the keyboard. A function call is made to kbhit().

if (kbhit())
{
	ch=getch();
	getBall();

	switch(ch)
	{
	    case LEFT:
			padX=padX-PADSTEP;
			if (padX<4) padX=4;
	    break;

	    case RIGHT:
			padX=padX+PADSTEP;
			if (padX>52) padX=52;
	    break;
         }
} 

After the user makes an input, the game will update the pad's position by making a function call to CBrickGame::putPad().

void CBrickGame::putPad(void)
{
	int i;
	setcolor(111);

	for (i=0;i<6;i++)
	{
		gotoxy(padX+i,padY);cprintf("Ü");
	}
} 

The CBrickGame::moveBall(void) Method

The CBrickGame::moveBall(void) method is called upon to move the ball. Then the position of the ball is compared to the location of the bricks, when the locations match, i.e., when the ball hits bricks or hits the pad, the states of these objects are altered.

void CBrickGame::moveBall(void)
{
	ballX=ballX+dirX;
	if (ballX<4 || ballX >55) dirX=-dirX;

	ballY=ballY+dirY;
	if (ballY<4 ) dirY=-dirY;
} 

The CBrickGame::setupBricks(void) Method

The CBrickGame::setupBricks(void) method is called upon to reset the brick hit flag and to put up a fresh batch of unhit bricks.

   void CBrickGame::setupBricks(void)
   {
   	for (i=0;i<=MAXBRICKS;i++) bricks[i]=true;
   	setcolor(15);
   	for (i=1;i<=MAXBRICKS;i++)
   	{
   		if (i>0 && i<=6){gotoxy(8*i,6);cprintf("ÛÛÛÛÛÛÛ");}
   		if (i>6 && i<=12){gotoxy(8*(i-6),8);cprintf("ÛÛÛÛÛÛÛ");}
   		if (i>12 && i<=18){gotoxy(8*(i-12),10);cprintf("ÛÛÛÛÛÛÛ");}
   		if (i>18 && i<=24){gotoxy(8*(i-18),12);cprintf("ÛÛÛÛÛÛÛ");}
   	}
   }   

The CBrickGame::checkBricks(void) Method

The CBrickGame::checkBricks(void) method is called upon to check if a specific brick has been hit. If the brick was hit, then its flag is set to bricks[i]=false and is cleared from the ball's path.

void CBrickGame::checkBricks(void)
{
	for (i=1;i<=6;i++)
	{
	   if (ballX>(8*i) && ballX<8*(i+1))
	   {
		   if (ballY==6 && bricks[i]==true)
		   {
		     bricks[i]=false;
		     gotoxy(8*i,6);cprintf("       ");
			 processHits();
		   }

		   if (ballY==8 && bricks[i+6]==true)
		   {
		     bricks[i+6]=false;
		     gotoxy(8*i,8);cprintf("       ");
			 processHits();		   }

		   if (ballY==10 && bricks[i+12]==true)
		   {
		     bricks[i+12]=false;
		     gotoxy(8*i,10);cprintf("       ");
			 processHits();		   }

		   if (ballY==12 && bricks[i+18]==true)
		   {
		     bricks[i+18]=false;
		     gotoxy(8*i,12);cprintf("       ");
			 processHits();		   }
	   }
	}
}

The CBrickGame::gameMain(void) Method is our Message Pump

Keyboard input is the games' only means of control. In here, key codes are processed and translated into instructions.

void CBrickGame::gameMain(void)
{
  if (kbhit())
  {
	ch=getch();
	op=toupper((char)ch);
	getPad();
	getBall();

	switch (ch)
	{
	    case LEFT:
			padX=padX-PADSTEP;
			//ballX=padX;
			if (padX<4) padX=4;
		break;

		case RIGHT:
			padX=padX+PADSTEP;
 			//ballX=padX;
			if (padX>52) padX=52;
		break;

		case UP:
		break;

		case DOWN:
		break;

		case ENTER:
		break;

		case SPACE:
		break;

		case F1:
			help();
			resumeGame();
		break;

		case TAB:
			autoplay=-autoplay;
		break;
	}
  }
}

The Main File

Finally the file CBrickGame_main.cpp is where we create an instance for our class and run our application.

//CBrickGame.cpp

#include "CBrickGame.h"

int main()
{
  CBrickGame *brickGame = new CBrickGame(1);

  return 0;
}

And that is how easy it is to create a simple breakout game in a Win32 Console.

Thanks for reading.

License

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

About the Author

Clark Kent SuperCoder
Sweden Sweden
Member
About me:
I attended programming School and I have a degree in three programming languages.
C/C++, Visual Basic and Java. So i know i can code. And there is a diploma hanging on my wall to prove it.
I am a professional, I've gotten paid to teach coding. I am roughly 20 years old and i have been a teacher's assistant in programming ,
i have held a lecture in Visual basic programming. I have also coached students in C++, Java and Visual basic.

In my spare time i do enjoy developing computer games, and i am developing a rather simple flight simulator game
in the c++ programming language using the openGL graphics libray.
 
I've written about a dozen small simple applications and games.

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   
GeneralInterestingmemberJ_Madden8 Jun '10 - 13:26 
Despite the fact that console games are passe, I liked the article primarily because not much is done in C/C++ console world anymore. This doesn't mean your stuff was not relative, I think much of the newer languages are overkill for things that could get done much more efficiently in C. Congrats and hope to see more from you in the future...
"For what benefit a man to gain the world but lose his soul?"

GeneralPerplexing license...memberyafan7 Jun '10 - 10:01 
// * This software is made available only to individuals and only *
// * for educational purposes. Any and all commercial use is *
// * stricly prohibited.
 

Typo's aside. Did you really mean to add such a restritive license?
RantI don't understandmemberkornakar6 Jun '10 - 20:37 
Why do you keep publishing these console-related articles? Obviously no one is interested in them and the code quality is very bad. I don't mean to be mean, it's just that when I open an article, I expect to be learning something. Most of your articles are just a bunch of code and a brief comment "this routine does the magic".
 
You say you're a "professional programmer". A true professional admints that he's wrong and corrects his errors. But you seem just to ignore all feedback. But hey, you're a TOP CODER aren't you? Dead | X|
General[My vote of 1] 30 years too latememberJohnny J.3 Jun '10 - 21:26 
I don't mean to be rude. I'm sure you're a nice person and that you do a great job.
 
But I cannot for the life of me see ANY reason to program a console game that looks like a 30 year old old game (which wasn't even funny back then, but you had to play it because there was nothing else). Wanna program games? Try something a little more up to date...
GeneralInteresting but...memberhector santos25 May '10 - 5:43 
Comments:
 
1) Clean up your code. Remove commented out code, structure the layout so it isn't ragged.
 
2) Make use of the CONSOLE dimension, maxY, maxX. Not all DOS windows are 25x80.
 

GeneralRe: Interesting but...memberTopCoder2329 May '10 - 23:07 
Thanks sir i will
GeneralArticle writing suggestionmemberDavid MacDermot14 May '10 - 8:37 
Please see my comment posted Here[^]
GeneralWell then...memberelchupathingy11 May '10 - 18:20 
That is a lot simpler then I had thought it was going to be...good stuff Big Grin | :-D
GeneralRe: Iam a simple personmemberTopCoder2323 May '10 - 21:01 
Smile | :)

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.130516.1 | Last Updated 6 Jun 2010
Article Copyright 2010 by Clark Kent SuperCoder
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid