A simple 2D pong game in darkGDK

In case you are wondering, Pong is a video game that simulates ping pong. It is a game where you maneuver a bat or paddle by pressing a control or joystick and the goal of the game is to return the ball to the opposing side just like the real ping pong. If you totally don't have any idea how pong works, I suggest googling it first before moving onto the next section. Being accustomed with the game and how it works greatly aids in trasforming it into codes.

Apart from familiarizing the game, we also need to learn few darkGDK game operations and the underlying commands behind them. These operations and commands are enumerated below:

1. Displaying an Image

Before you can display an image in darkGDK, you'll need to load it first into the computer memory. To be able to do that, use the dbLoadImage command which has the following syntax:
dbLoadImage("Imagefilename",imageloadid);
Where;
1. Imagefilename is an existent image file saved inside your game project folder. darkGDK supports .bmp, .jpg, and .png image file types.

2. imageloadid is a unique image numeric id that can be used later on to refer to a loaded image.

Example:
dbLoadImage("Galaxian.jpg",1);
Once an image is loaded in the computer memory, you can then display it by using dbPasteImage or dbSprite. dbSprite has the following syntax:
dbSprite(spriteid, x-coordinate, y-coordinate, imageloadid);
Where;
1. spriteid is a numerical id that can be use to manipulate the displayed image. spriteid can be identical to the imageloadid.

2. x-coordinate and y-coordinate are the x and y coordinate of the upper-left corner of your sprite or image. If you are unfamiliar of x and y coordinate, think of the screen as the fourth quadrant of the Cartesian coordinate system. The upper left corner is the origin which has the coordinate of x=0,y=0. The value of x coordinate increases as you move right. The value of the y coordinate increases as you move down.

3. imageloadid is the numeric id of a loaded image that you wanted to display.

Example:
dbSprite(1,0,01);
2. Moving Sprites

Sprites and images can be moved or animated by using dbMoveSprite or by simply incrementing or decrementing the x and y coordinate of an image. If you are familiar with java, c++, or visual basic, you probably know what I am talking about.

3. Detecting Collisions

darkGDK comes with powerful command that can be used to detect sprite or object collision. To detect collision, simply use dbSpriteCollission or dbSpriteHit. dbSpriteHit has the following syntax:
dbSpriteHit(Spriteid1, Spriteid2);
Where;
1. Spriteid1 and Spriteid2 are the numeric spriteids of the images that you wanted to test for collision.

Now that you have learned few basic commands and operations in darkGDK,I guess we can proceed into making our pong game. The following steps demonstrates how:

1. Click Start>All Programs>Microsoft Visual C++ Express Edition.

2. Click on File>New>Project. In the Project Types tree control, select on Wizards.

3. Select Dark GDK-Game from the available Game project options.

4. Type “Pong” no quotes in the Project Name textbox then Click Ok.

5. Click on View>Solution Explorer. Locate Main.cpp in the Solution Explorer Window then double-click it.

6. The following should then appear:

// Dark GDK - The Game Creators - www.thegamecreators.com   
// the wizard has created a very simple project that uses Dark GDK   
// it contains the basic code for a GDK application     
// whenever using Dark GDK you must ensure you include the header file   
#include "DarkGDK.h"    
// the main entry point for the application is this function   
void DarkGDK ( void )   
{   
// turn on sync rate and set maximum rate to 60 fps   
dbSyncOn   ( );   
dbSyncRate ( 60 );     
// our main loop   
while ( LoopGDK ( ) )   
{   
// update the screen   
dbSync ( );   
}     
// return back to windows   
return;   
}   

7. Locate the line #include "DarkGDK.h" and declare the following variables below it:
//handles the ball velocity, the larger the value 
//the faster the ball will move
int ballxvelocity=5,ballyvelocity=5;
//handles the updated x and y coordinate of the ball
int ballxcoord,ballycoord;
//handles the updated x and y coordinate 
//of player1's paddle
int bat1xcoord,bat1ycoord;
//handles the updated x and y coordinate 
//of player2's paddle
int bat2xcoord,bat2ycoord;

8. Locate the line dbSyncOn and dbSynRate(60) then type the following below it:
//sets the window title to pong
dbSetWindowTitle("Pong");
//sets the window size to 600x400 that is
//x coordinates runs from 0-600
//y coordinates runs from 0-400
dbSetWindowSize(600,400);
//loads an image located in your game project folder
//and gives it an id of 1
dbLoadImage("ball.png",1);
//loads an image located in your game project folder
//and gives it an id of 2
dbLoadImage("bat1.jpg",2);
//loads an image located in your game project folder
//and gives it an id of 3
dbLoadImage("bat2.jpg",3);

//displays the ball at the center of the screen
dbSprite(1,300,200,1);
//player1 paddle at the left side of the screen
dbSprite(2,50,150,2); 
//player2 paddle at the right side of the screen 
dbSprite(3,500,150,3);


9. Locate the line while ( LoopGDK ( ) ) and type the following after the open curly bracket:
//move the ball
//adds the value of ballxvelocity 
//and the current x coordinate of the ball
//and assign it as a new ball x coord value
ballxcoord=dbSpriteX(1) + ballxvelocity;
//do the same with y
ballycoord=dbSpriteY(1) + ballyvelocity;
//displays the ball in the updated x and y coord positions
dbSprite(1,ballxcoord,ballycoord,1);
//if the ball collides with the 
//top or bottom of the screen then
if (ballycoord <= 0 || ballycoord >= 400) 
{
//Multiply ballyvelocity by negative 1
//The result will  later on be added to the
//current y coordinate of the ball
//causing the ball to change position
//depending on the value of ballyvelocity and
//the current coord of the ball
ballyvelocity=ballyvelocity*-1;
}
//if the ball collides with the left side 
//or right side of the screen then
if (ballxcoord <= 0 || ballxcoord >= 600)
{
//Multiply ballxvelocity by negative 1
//The result will later on be added to the
//current x coordinate of the ball
//causing the ball to change position
//depending on the value of ballxvelocity and
//the current x coord of the ball
ballxvelocity=ballxvelocity*-1;
}

//check bat collision
//if the ball collides with player 1's paddle
if (dbSpriteHit(1,2)==1)
{
//if at this point you still don't 
//understand what this do
//I suggest recalling the rules in multiplying
//and adding negative numbers
ballxvelocity=ballxvelocity*-1;
}
//if the ball collides with player 2's paddle
if (dbSpriteHit(1,3)==1)
{
//reverse the direction of the ball
ballxvelocity=ballxvelocity*-1;
}

//move the player 1 bat
//if the enter key is pressed
if (dbReturnKey()==1)
{
//decrement the paddle y coord value
//causing the paddle to move up
bat1ycoord=dbSpriteY(2)-5;
//display the paddle in the
//updated position
dbSprite(2,bat1xcoord,bat1ycoord,2);
}
//if the down arrow is pressed
if (dbShiftKey()==1)
{  
//increment the paddle y coord value
//causing the paddle to move down
bat1ycoord=dbSpriteY(2)+5;
//display the paddle in its
//updated position



//move player 2 bat
//if the up arrow is pressed
if (dbUpKey()==1)
{
//decrement the paddle y coord value
//causing the paddle to move up
bat2ycoord=dbSpriteY(3)-5;
dbSprite(3,bat2xcoord,bat2ycoord,3);
}
//if the shift key is pressed
if (dbDownKey()==1)
{
//increment the paddle y coord value
//causing the paddle to move down
bat2ycoord=dbSpriteY(3)+5;
dbSprite(3,bat2xcoord,bat2ycoord,3);
}
10. Locate the line dbSync ( ); and type the following after the open curly bracket:
//Deletes the loaded image
//and sprites when the game is closed
//this will free up the used memory
for ( int i = 1; i < 30; i++ )
dbDeleteSprite ( i );
dbDeleteImage ( 1 );
11. Let's have a glance of our codes again and this time comments omitted:
// Dark GDK - The Game Creators - www.thegamecreators.com

// the wizard has created a very simple project that uses Dark GDK
// it contains the basic code for a GDK application

// whenever using Dark GDK you must ensure you include the header file
#include "DarkGDK.h"
int ballxvelocity=5,ballyvelocity=5;
int ballxcoord,ballycoord;
int bat1xcoord,bat1ycoord;
int bat2xcoord,bat2ycoord;
// the main entry point for the application is this function
void DarkGDK ( void )
{
// turn on sync rate and set maximum rate to 60 fps
dbSyncOn   ( );
dbSyncRate ( 60 );
dbSetWindowTitle("Pong");
dbSetWindowSize(600,400);
dbLoadImage("ball.png",1);
dbLoadImage("bat1.jpg",2);
dbLoadImage("bat2.jpg",3);

 
dbSprite(1,300,200,1);   
dbSprite(2,50,150,2);  
dbSprite(3,500,150,3);  



// our main loop
while ( LoopGDK ( ) )
{
//move the ball
ballxcoord=dbSpriteX(1) + ballxvelocity;
ballycoord=dbSpriteY(1) + ballyvelocity;
dbSprite(1,ballxcoord,ballycoord,1);
if (ballycoord <= 0 || ballycoord >= 400) 
{
ballyvelocity=ballyvelocity*-1;
}
if (ballxcoord <= 0 || ballxcoord >= 600)
{
ballxvelocity=ballxvelocity*-1;
}

//check bat collission
if (dbSpriteHit(1,2)==1)
{

ballxvelocity=ballxvelocity*-1;
}
if (dbSpriteHit(1,3)==1)
{

ballxvelocity=ballxvelocity*-1;
}

//moves player 1 bat
if (dbReturnKey()==1)
{
bat1ycoord=dbSpriteY(2)-5;
dbSprite(2,bat1xcoord,bat1ycoord,2);
}
if (dbShiftKey()==1)
{
bat1ycoord=dbSpriteY(2)+5;
dbSprite(2,bat1xcoord,bat1ycoord,2);
}


//moves player 2 bat
if (dbUpKey()==1)
{
bat2ycoord=dbSpriteY(3)-5;
dbSprite(3,bat2xcoord,bat2ycoord,3);
}
if (dbDownKey()==1)
{
bat2ycoord=dbSpriteY(3)+5;
dbSprite(3,bat2xcoord,bat2ycoord,3);
}


// update the screen
dbSync ( );
}
for ( int i = 1; i < 30; i++ )
{
dbDeleteSprite ( i );
dbDeleteImage ( 1 );
}
// return back to windows
return;
}

12. Press F5 to test the game. You can press the Enter key and shift key to move player1's bat and the up and down arrow to move player2's bat.

13. And that's it. A very simple pong game using few lines of codes. At the point of writing I guess this was the very first pong game tutorial written using darkGDK. I will add attract mode animation, menus, scores, and AI enemy to this when I have time but for now, though it's incomplete, you can use it as starting point. Hope you'll learn something from it and enjoy the game.

A simple 2D Color Slot Machine in Dark GDK

I’m sure every one of us is familiar with slot machine or fruit machine game. Today we will be making a slight version of that game, and we are going to name it as “Color Slot Machine”. There are several elements missing in this game such as the game title screen and the game overview screen so I’ll just explain to you the mechanics of the game. Before the game starts you have an initial account of 100000. To play the game, click on the Spin button. After clicking on the Spin button the computer will generate random colors and your score depends upon the generated color. The scoring system is presented below:

ColorWin
Red-Green-Blue+2000
Red-Red-Red+1000
Green-Green-Green+1000
Blue-Blue-Blue+1000
Others-1000
The following steps demonstrate how to create this game:

1.Prepare the images that will be needed in your game. You can use Ms-Paint, Photoshop or GIMP. The following images are required for this game:



2. After preparing the images, Start Visual C++>File>New>Projects>Wizards>Select Dark GDK-Game>Type “Color Machine” in the name textbox (no quotes).

3. Assuming that you have saved the project in the default directory, minimize Microsoft Visual C++ then go to My Documents>Visual Studio 2008>Projects>Color Machine>Color Machine>Then paste the images that you have made in Step 1.



4. Maximize Visual C++>View>Solution Explorer>Double-click Main.cpp. The following should then come into view:

// Dark GDK - The Game Creators - www.thegamecreators.com

// the wizard has created a very simple project that uses Dark GDK
// it contains the basic code for a GDK application

// whenever using Dark GDK you must ensure you include the header file
#include "DarkGDK.h"

// the main entry point for the application is this function
void DarkGDK ( void )
{
 // turn on sync rate and set maximum rate to 60 fps
 dbSyncOn   ( );
 dbSyncRate ( 60 );

 // our main loop
 while ( LoopGDK ( ) )
 {
  // update the screen
  dbSync ( );
 }

 // return back to windows
 return;
}

5. Locate the line #include "DarkGDK.h" then declare the following variables below it:
//handles the spriteid of the left box
int intred;
//handles the spriteid of the middle box
int intgreen;
//handles the spriteid of the right box
int intblue;
//handles our loop
int intcounter;
//determines if the spin button has been clicked
int intclicked;
//displays our status text
char* chrmessage;
//handles the balance
int intbalance=100000;

6. Locate the line dbSynRate(60); then replace the 60 with 10 so that dark GDK will try to play 10 frames per second and our loop will not play funny , then type the following after it:
//sets the window title
dbSetWindowTitle("Color Slot Machine");
//sets the window size
dbSetWindowSize(400,400);
//loads our images
dbLoadImage("red.png",1);
dbLoadImage("green.png",2);
dbLoadImage("blue.png",3);
dbLoadImage("backdrop.png",4);
dbLoadImage("Spin.png",5);
dbLoadImage("pointer.png",6);
//displays our images
dbSprite(4,0,0,4);
//sets our backdrop alpha transparency
//so that our text will be visible
dbSetSpriteAlpha(4,150);
dbSprite(5,240,380,5);
dbSprite(1,130,100,1);
dbSprite(2,260,100,2);
dbSprite(3,390,100,3);

7. Locate the Line while ( LoopGDK ( ) ) then type the following after the open curly brace:
//sets text size to 30 points
dbSetTextSize(30);
//displays the balance
//I still don’t know how to concanate text
dbText(0,0,"Balance:");
dbText(150,0,dbStr(intbalance));
  //displays our status text
  dbText(250,250,chrmessage);
  //pessimistic programming
  //assume that the button has not yet been clicked
  intclicked=0;
  //hides our customized mouse pointer
  //so that only the mouse pointer is visible
  dbHideSprite(6);
  //Enables dbRnd to generate an unpredictable
  //random number generation
  dbRandomize(dbTimer());
  dbSetSprite(6,1,100);
  //enables our sprite to follow the mouse
  dbSprite(6,dbMouseX(),dbMouseY(),6);
  //if our hidden sprite collided with the mouse
  //and the button has been clicked
  if(dbSpriteHit(6,5)==1 && dbMouseClick()==1)
  {
  //assigns 1 to inclicked variable
  //resets the value of chrmessage
  intclicked=1;
  chrmessage="";
  //generate a random color 10 times
  for(intcounter=1;intcounter<=10;intcounter++)
  {
   intred=1 + dbRnd(2);
   intblue=1 + dbRnd(2);
   intgreen=dbRnd(2)+1;
   dbSprite(1,130,100,intred);
   dbSprite(2,260,100,intgreen);
   dbSprite(3,390,100,intblue);
   dbSync();
  }
  }
  
  //check if the button has been clicked
  //if it was clicked then

  if (intclicked==1)
  {
   //check for color matches
   if (intred==1 && intblue==1 && intgreen==1)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
  
   }
   else if (intred==2 && intblue==2 && intgreen==2)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
   }
   else if (intred==3 && intblue==3 && intgreen==3)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
   }
   else if (intred==1 && intblue==2 && intgreen==3)
   {
   chrmessage="You win 2000!";
   intbalance=intbalance+1000;
   }
   //if no color matches then
   else
   {
   chrmessage="You Lose!";
   intbalance=intbalance-1000;
   }
  }
  //if the balance is less than or equal to zero
  if (intbalance<=0)
  {
  dbCLS();
  dbSetTextSize(32);
  dbText(180,250,"Insufficient balance");
  dbText(250,300,"GAME OVER");
  dbSync();
  dbWait(4000);
  return;
 }
8. Let’s have a look of our code once again and this time, crappy comments ommitted.
// Dark GDK - The Game Creators - www.thegamecreators.com

// the wizard has created a very simple project that uses Dark GDK
// it contains the basic code for a GDK application

// whenever using Dark GDK you must ensure you include the header file
#include "DarkGDK.h"
int intred;
int intblue;
int intgreen;
int intcounter;
int intclicked;
char* chrmessage;
int intbalance=100000;
// the main entry point for the application is this function
void DarkGDK ( void )
{

 // turn on sync rate and set maximum rate to 60 fps
 dbSyncOn   ( );
 dbSyncRate ( 20 );
 dbSetWindowTitle("Color Slot Machine");
 dbSetWindowSize(400,400);
 dbSetGamma(500,255,500);
 dbLoadImage("red.png",1);
 dbLoadImage("green.png",2);
 dbLoadImage("blue.png",3);
 dbLoadImage("backdrop.png",4);
 dbLoadImage("Spin.png",5);
 dbLoadImage("pointer.png",6);
 dbSprite(4,0,0,4);
 dbSetSpriteAlpha(4,150);
 dbSprite(5,240,380,5);
 dbSprite(1,130,100,1);
 dbSprite(2,260,100,2);
 dbSprite(3,390,100,3);

 // our main loop
 while ( LoopGDK ( ) )
 {

  dbSetTextSize(30);
  dbText(0,0,"Balance:");
  dbText(150,0,dbStr(intbalance));
  dbText(250,250,chrmessage);
  intclicked=0;
  dbHideSprite(6);
  dbRandomize(dbTimer());
  dbSetSprite(6,1,100);
  dbSprite(6,dbMouseX(),dbMouseY(),6);
  if(dbSpriteHit(6,5)==1 && dbMouseClick()==1)
  {
  intclicked=1;
  chrmessage="";
   for(intcounter=1;intcounter<=10;intcounter++)
   {
   intred=1 + dbRnd(2);
   intblue=1 + dbRnd(2);
   intgreen=dbRnd(2)+1;
   dbSprite(1,130,100,intred);
   dbSprite(2,260,100,intgreen);
   dbSprite(3,390,100,intblue);
   dbSync();
   }
  }

  if (intclicked==1)
  {
   if (intred==1 && intblue==1 && intgreen==1)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
  
   }
   else if (intred==2 && intblue==2 && intgreen==2)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
   }
   else if (intred==3 && intblue==3 && intgreen==3)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
   }
   else if (intred==1 && intblue==2 && intgreen==3)
   {
   chrmessage="You win 2000!";
   intbalance=intbalance+1000;
   }
   else
   {
   chrmessage="You Lose!";
   intbalance=intbalance-1000;
   }
  }
  
  if (intbalance<=0)
  {
  dbCLS();
  dbSetTextSize(32);
  dbText(180,250,"Insufficient balance");
  dbText(250,300,"GAME OVER");
  dbSync();
  dbWait(4000);
  return;
  }

  // update the screen
  
  dbSync ( );
 }

 // return back to windows
 return;
}
9. Press F5 to test our game. Click the Spin button and see what happens.

Binding a fieldname to a control programmatically in Visual J#

Before the Database Connection and Binding process I want you to make an Ms-Access database file named “dbEmployee” containing a table named “tblEmployee”. Use the following specifications:
Field Name Data Type Description
chrempno text Handles employee id
chrfname text Handles employee’s name
chrlname text Holds employee’s last name

After designing the structure of your table, you can enter appropriate values for each field. For instance:
chrempno chrfname Chrlname
2010A John Doe

Now that we are done creating a table and adding appropriate values to it, we can now link to that table and bind the fields to our windows application control by following these steps:

1. Start>All programs>Visual J# 2005 Express Edition.

2. Click File>New>Project>Select Windows Application from the windows studio installed templates then click Ok.

3. A new form will appear. Before adding appropriate controls to our form let us first establish a connection to our dbEmployee database file. To do this we will use a database access tool called OleDbDataAdapter. OleDbDataAdapter will enable us to set the filename of a database file and the name of the table that we wanted to be made available in our project. It also permits us to set-up how the record values will be displayed on our form by using an appropriate SQL statement.

4. By default, OleDbDataAdapter is not shown on the Visual J# 2005 Express control toolbox, to add it, click Tools>Choose control toolbox>Type “ole” (no quotes ) on the filter textbox then check all the items that starts with “ole” and finally click the Ok button. OleDbDataAdapter should now appear on your toolbox.

5. Expand the All Windows Forms toolbox category then double-click OleDbDataAdapter.

6. A Data Adapter configuration wizard will then appear. Click the new connection button>Select Microsoft Access Database File from the data source list.

7. Click the browse button then locate your dbEmployee.mdb file then click the Ok button.

8. Click Next>A message box containing the following prompt will appear:
“The connection you selected uses a local data file that is not in the current project would you like to your project for the connection? If you copy the data file to your project, it will be copied to the project’s output directory”> just click the Ok button then click next.

9. A Generate SQL statement, type “SELECT * FROM tblEmployee” (no quotes) this will export all the record value of our table to our project then. Click Next after typing the SQL statement and finally click the Finish Button.

10. After specifying the table name, right-click OleDbDataAdapter1 from the bottom portion of Visual J# IDE then click Generate Data Set then click the Ok button. If you are wondering what a dataset is, a Dataset is an imaginary box the holds the field names of your table. It is use a temporary storage box for table data.

11. At this point, you will need to design the interface of your application. Double-click the label tool. In the properties window, change its text to “Employee number:” (no quotes).

12. Double-click the label tool and put it in the right-side of your Employee number label. Change its name to Empnumberlabel.

13. Add another label below the Employee number label and change its text to “Firstname:” (no quotes). Put a label on its right side and name it Fnamelabel.

14. Add another label below the Firstname label and change its text to “Lastname:” (no quotes). Put another label on its right side and name it Lnamelabel.

15. Double-click your form, type the following code:
//fills our dataset with record values
this.oleDbDataAdapter1.Fill(this.dataSet11);
//Use the dataset methods collection to retrieve the record values
//The get_Item() method after the get_Rows() method retrieves the table row value
//while the last get_Item retrieves the table column value
Empnumberlabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(0)));
//The index number of the first table row is 0, the second row is 1 and so on.
//Column index number starts from 0, the second table column is 1 and so on.
Fnamelabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(1)));
//Dataset collection methods returns an object data that is why we use the 
//String.valueOf data conversion function to convert it to string.
Lnamelabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(2)));
16. Your code should now look like this:
private void Form1_Load(Object sender, System.EventArgs e)
{
this.oleDbDataAdapter1.Fill(this.dataSet11);
Empnumberlabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(0)));
Fnamelabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(1)));
Lnamelabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(2)));
}
17. Press F5 to test your application.You should now see the following output: