Friday, December 6, 2013

Snake Game in c++ : Part 2

Snake Game in CPP : Part 1
Snake game in c++ : Part 2

Now contuning 2nd part of Snake game in c++. In previous code there was a problem that screen was flickring while running game.
This can be eliminated by drawing the things that are updated in loop. Like the snake, fruit and wall is constant it not needed to draw wall every loop.

First remove system("CLS"); from main method because clearing the screen drawing it takes time.

Now alter our draw method. From the previous code remove the drawwall()  method from draw() ,so wall will not be drawn again and again.

Now the thing how to make snake look  like it moving because screen is not cleared and drawn again. So snake become larger and larger.

To remove this problem we to further alter our draw method. Insted of using system("CLS"); to clear whole screen ,we can use space ‘  ‘ to make screen clear. Space can be put on place where we want to remove things.

Now to make snake appear moving we will just replace its last tail with blank space ‘ ‘. So as snake is moving its last position is been replaced with space.

Here is the draw method code

void snake::draw()
{
     /*
cur_cord.X=10;
cur_cord.Y=5;

SetConsoleCursorPosition(console_handle,cur_cord);
cout << "hi";  
*/



tail *tmp , *last;
tmp=start;
last = current;

                     

while(tmp!=NULL)
                      {
                        cur_cord.X=tmp->x;
                        cur_cord.Y=tmp->y;
                        SetConsoleCursorPosition(console_handle,cur_cord);
                        //cout << "*" << cur_cord.X <<"-" <<  cur_cord.Y  ;
                        cout << "#";
                        tmp=tmp->next;                         
                      }
// remove tail
cur_cord.X=last->x;
cur_cord.Y=last->y;
SetConsoleCursorPosition(console_handle,cur_cord);
cout << ' ';
//draw the food
 cur_cord.X=foodx;
 cur_cord.Y=foody;
 SetConsoleCursorPosition(console_handle,cur_cord);
  cout << "?";
 
}

To draw wall just call drawWall() in main method.
Thus the game works fine now.

//------------------ hope enjoy it
The code used in this tutorial is little bit different from the code in the archive
use DEV C++ to compile the code.
Download the full code and study it

Download
https://app.box.com/s/jjfbfs94r8nukmdgynr7


1 comment: