Programming with Passion

Make the best out of everything.

Wednesday 16 March 2016

Snake Game I made in C++

Why not Take A look at this Snake Game I made in C++


#include<iostream.h>

#include<conio.h>

#include<dos.h>
#include<graphics.h>
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<fstream.h>
int p,h,c[50],a,b,x1[50],n=5,x=320,y=200,y1[50],j=1,q,m,sc=-5,hs=0;
char *hr,*sr,st='p';

void hsc()  //TO CALCULATE & STORE HIGH SCORE
{
ifstream fin("High.txt"); //DATA HANDLING USED
fin.seekg(0);
fin>>hs;
fin.close();
settextstyle(1,0,1);
setcolor(BLUE);
itoa(hs,hr,10);
outtextxy(600,300,hr);
if(sc>hs)
{
hs=sc;
ofstream fout("High.txt"); //FILE NAMED HIGH.txt STORES THE HIGH SCORE
fout<<hs;
fout.close();
setcolor(0);
outtextxy(600,300,hr);
ltoa(hs,hr,10);
setcolor(BLUE);
outtextxy(600,300,hr);
}
}
void cd()  //TO CLEAR THE SNAKE BODY
{
setcolor(WHITE);
setfillstyle(SOLID_FILL,WHITE);
if(c[n-1])
fillellipse(x1[n-1],y1[n-1],10,5);
else
fillellipse(x1[n-1],y1[n-1],5,10);
}

void er()
{
setcolor(WHITE);
setfillstyle(SOLID_FILL,WHITE);
fillellipse(p,h,5,5);
}

void ins()   // TO PROVIDE INSTRUCTIONS AND SCORES
{
line(500,0,500,400);
line(0,400,640,400);
line(500,100,640,100);
  setcolor(BLUE);
  settextstyle(7,0,1);
  outtextxy(10,410,"Project by -  RISHABH AGGARWAL       Submitted to ");

  outtextxy(135,440,"XII - A                         Amit Gupta ");
  settextstyle(7,0,4);
  outtextxy(510,5,"Snake");
  outtextxy(520,50,"Game");
  settextstyle(11,0,2);
  outtextxy(524,110," CONTROLS ");
  outtextxy(522,135,"p = PAUSE");
  outtextxy(522,155,"g = RESUME");
  outtextxy(522,175,"e = EXIT");
  outtextxy(513,195,"ARROWS");
  outtextxy(512,205,"    -MOVEMENT");
  outtextxy(524,250,"SCORE -  ");
  outtextxy(524,280,"High Score -");
}
void score() //TO CALCULATE SCORE OF THE PLAYER
{
ltoa(sc,sr,10);
settextstyle(1,0,1);
setcolor(0);
outtextxy(600,240,sr);
sc+=5;
ltoa(sc,sr,10);
setcolor(BLUE);
outtextxy(600,240,sr);

}


void crd()  //TO GET THE CO-ORDINATES OF THE FOOD
{
p=(rand()%485)+10;
h=(rand()%385)+10;
score();
hsc();
}

void gnr()   // TO GENERATE THE FOOD
{
setcolor(BLUE);
setfillstyle(SOLID_FILL,rand()%15+1);
fillellipse(p,h,5,5);
}


int move()  // TO MOVE THE SNAKE BODY
{
setcolor(BLUE);
int m=1,z;
x1[0]=x;
y1[0]=y;
while(1)
{
cd();
gnr();
ins();

if(m==0)
{
c[0]=1;
x1[0]=x1[0]-20;
y=y1[0];
if(x1[0]<0)
x1[0]=490;
}

else
if(m==1)
{
c[0]=1;
x1[0]=x1[0]+20;
if(x1[0]>500)
x1[0]=10;
}

else
if(m==2)
{
y1[0]=y1[0]+20;
//x=x1[0];
c[0]=0;
if(y1[0]>400)
y1[0]=10;
}

else
{
y1[0]=y1[0]-20;
c[0]=0;
if(y1[0]<0)y1[0]=390;
}
for(int i=n-1;i>0;i--)
{
x1[i]=x1[i-1];
c[i]=c[i-1];
y1[i]=y1[i-1];
setfillstyle(CLOSE_DOT_FILL,rand()%15+1);
if(c[i])
{
ellipse(x1[i],y1[i],0,360,10,5);
fillellipse(x1[i],y1[i],10,5);
}
else
{
ellipse(x1[i],y1[i],0,360,5,10);
fillellipse(x1[i],y1[i],5,10);
}
}
if(c[0])
ellipse(x1[0],y1[0],0,360,10,5);
else
ellipse(x1[0],y1[0],0,360,5,10);
delay(100);
int check(); // PROTOTYPE OF CHECK FUNTION

check();   // FUNCTION CALL TO CHECK THE SNAKE'S HEAD DON'T CUT HIS BODY

if((p<=x1[0]+10&&p>=x1[0]-10) && (h<=y1[0]+10&&h>=y1[0]-10))
{
er();
crd();   // FUNTION CALL TO GET THE NEW COORDINATES OF THE FOOD
if(n<50)
++n;
}
if(kbhit())
{
z=getch(); // TO CHECK KEYBOARD INPUTS
switch(z)
{
case(72):m=3;j=1;  //HERE 72,77,80,75 ARE DIRECTIONAL KEYS
break;
case(77):m=1;j=1;  // USED TO NAVIGATE THE SNAKE
break;
case(80):m=2;j=1;
break;
case(75):m=0;j=1;
break;
case('p'):if(!kbhit()) //TO PAUSE THE GAME
getch();
break;
case('e'):exit(0); //TO EXIT THE GAME
default:break;
}
}
}
}

int check() // FUNTION TO CHECK THE SNAKE DO NOT CUT IT'S BODY
{
for(int i=3;i<n;++i)
if(x1[0]==x1[i] && y1[0]==y1[i])
{
while(!kbhit())
{
setcolor(RED);
settextstyle(EUROPEAN_FONT,HORIZ_DIR,2);
outtextxy(250,200,"GAME OVER");
delay(100);
setcolor(WHITE);
outtextxy(250,200,"GAME OVER");
delay(100);
}getch();
exit(0);
}
}


void main()  // MAIN FUNTION
{
clrscr();
int gd=DETECT,gm;
initgraph(&gd,&gm,"C:\\tc\\bgi");
setbkcolor(WHITE);
setcolor(BLUE);
crd();
gnr();
move();
getch();
closegraph();
}

I'll Keep posting more exciting things. Give me programming problems to solve for you. I'll give you the best of it.

62 comments:

  1. exit(0);
    }
    }


    void main() // MAIN FUNTION

    i got warning: function should return a value

    ReplyDelete
    Replies
    1. int check(). Because of this funtion there is warning. You may change it to "void" or return a value from the funtion or just ignore the warning just run the program. It'll run fine. Happy Coding @WangMaya.

      Delete
  2. Hello, great work...I'm try to understand the move function and am having a bit of trouble, I would appreciate if you could explain each line. Just discovered your blog...thanks for all the work you put into it...so far have found it really helpful!! :)

    ReplyDelete
    Replies
    1. Thanx for your feedbacks. Here i used arrays to move our little snake. If you had run the program you could see that snake body is made up of ellipses. So every ellipse need centers to be created. So i stored them in array. And to change the position of the snake I changed the value of the end ellipse that would be the tail and the rest will just change the position of the adjacent ellipse. Couldn't find a better logic. Hope this Help. If you want me to explain line by line I'll explain. But it will only take time. So I posted the logic. Happy coding.

      Delete
    2. Thanks for replying...I've run the program a few times and I think I have understood most of the logic...I ve only one doubt-in the check() function why is i=3 at the start of the for loop? Can it be one? Because when the snake is moving up and I press the down arrow ,the game is over..isn't that because the coordinate of the head = the coordinate of head-1?

      Delete
    3. Thanx for showing interest. You asked me "why is i=3... can it be one" It is because head is at the position i=0 and practically it can cut the fourth positioned ellipse. "Not its neck" so i started it with i=0. and by the way game over message is because of it matches the body coordinates so it shows the message. This code is lacking it i.e. if you go right it and you press the left arrow key it will go to left and will show game over. i'll improve it. Happy coding.

      Delete
  3. the code does not show any errors after the addition of return(0); in the int check(), but the problem is that the code isn't running even though there are 0 errors.

    ReplyDelete
    Replies
    1. Please confirm which compiler you are using.
      It works with DosBox.
      If you're running DosBox then you might be compiling it, run this. If no, please tell briefly what is the problem exactly.

      Delete
    2. Try to do this. In the main funtion where graph is initialized -> initgraph(&gd,&gm,"C:\\tc\\bgi");
      Here you have to change this path according to your computer go to your turbo c++ folder and locate the bgi folder in it. Then enter that path here. One different path would look like -> initgraph(&gd,&gm,"C:\\turboc3\\bgi");

      Delete
    3. well that helped. thanks a lot,
      and I must say that this was a pretty good game. well done.

      Delete
    4. Welcome and also thank you.
      Happy coding :)

      Delete
  4. same with WangMaya's problem..

    function should return a value.

    i'd try to run with that error but it won't run.

    what should i do..pls help

    ReplyDelete
    Replies
    1. Please confirm your compiler.
      If it is a DosBox it should run fine. You might be compiling it. Please run it. If no tell the problem briefly.

      Delete
    2. I tried as what u say..but it's still the same problem :(

      Delete
    3. This comment has been removed by the author.

      Delete
    4. Ok now i got what was wrong actually. Try to do this. In the main funtion where graph is initialized -> initgraph(&gd,&gm,"C:\\tc\\bgi");
      Here you have to change this path according to your computer go to your turbo c++ folder and locate the bgi folder in it. Then enter that path here. One different path would look like -> initgraph(&gd,&gm,"C:\\turboc3\\bgi");

      Delete
    5. thanks a lot rishabh.. it works :(

      Delete
  5. New Program Sudoku solver https://www.youtube.com/watch?v=AVOriVB67Wg
    Please Share and Subscribe and show some support. Thanx for your interest.
    Happy Coding. Stay tuned for more.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Bhai mai jab program run kar raha hoon toh snake ki tohdi body wahin rah jaa rahi hai

    ReplyDelete
  8. Bhai mujhe ek student dbms ki zarrorat hai with structures pls help mr

    ReplyDelete
  9. Hi Rishabh Bhaiya, i'm glad i found the video on youtube and i must say i've become a fan of your work.

    ReplyDelete
  10. Is there any way to make the ellipses more round, like a circle or a different shape like a square ?

    ReplyDelete
    Replies
    1. Thank you for your appreciation. I m glad that u are showing interest. And not only one way . U could do it in many ways . Like if u want circle instead of ellipses you can simply use circle syntax instead of ellipse or you can change the radius of the ellipses. For square you may go for the rect syntax. Hope u get my point.
      Happy coding.

      Delete
  11. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Warning is because of the check() function change it to void or you may return a value there. it wouldn't make a difference

      Delete
    2. can you tell me exactly what corrections I have to make please.

      Delete
    3. Just put a return 0 at the end of the function int check()

      Delete
  12. What is the features of this game?

    ReplyDelete
    Replies
    1. it is just a simple game in which the snake will eat the food displayed randomly on the screen after eating the food it increases its body length. It stores the high score of the player. The snake will bite its body to lead to game over. Just like it used to be in the nokia mobiles just different looks cause I'm still learning to improve. In summary it is just for educational purpose to help different coders to get different different logics.

      Delete
  13. please sent report for UG final year project

    ReplyDelete
  14. I'm sorry are u asking for format of report?

    ReplyDelete
  15. ERROR: must use c++ for the type iostream.

    what to do now.

    ReplyDelete
    Replies
    1. m using DOSBox v0.74 Manual

      Delete
    2. Save it with the extension .cpp

      Delete
    3. can u send the link for turboc++....its not running on my turbo

      Delete
    4. https://turboc.codeplex.com/
      Here You Go.

      Delete
  16. Hey ! Rishabh. Why you have used while(1) in move function ?
    Could you please explain it.

    Thank-you

    ReplyDelete
    Replies
    1. Because i have to make it an infinite loop. So i put 1 which means true. So the loop will never end until it meets an exit statement inside it.

      Delete
    2. and your snake can not be longer than 50 number of ellipse.
      Did you also use Data structures in it ?
      And can you explain me the move function which you have used in it ?

      Thank-You

      Delete
    3. 50 is just a number you can increase or decrease. Nobody would play it for that long it was just for education purpose. and the move function follows the idea that the body should follow the head so in the move function when the head gets a new set of coordinate the second ellipse takes place of the head, the third one takes place of second and so on.. Thats how it works. I hope that would work.

      Delete
  17. How to navigate the snake I am unable to navigate the snake if I move it up or down it stops when 2 ellipses have bended.How to solve this problem?what changes should I make?

    ReplyDelete
    Replies
    1. There is no problem with the code maybe you've not copied it correctly. Does it terminates the program or it gets stuck at the graphic window?

      Delete
  18. Please Rishabh Aggarwal answer my question?

    ReplyDelete
  19. Bhai yeh bata sakte ho examiner ne kya poocha tha jab aapne ye project submit kia tha(viva)...

    ReplyDelete
    Replies
    1. Asked me about some functions like why i've used ltoa and some variables what do they do. She also asked me what does this program do?

      Delete
  20. Function should not return a value warning occur

    ReplyDelete
  21. I need a program for my upcoming project which i plan to maek. Its 2048 and i have tried a lot but can't get exactly what i want. Can you give a source code for that along with explanation of how that works and it would be helpful if you give me two codes with a little variation. One with Graphics and other Without! thanks in Advance!!

    ReplyDelete
    Replies
    1. https://breakthecodenow.blogspot.in/2018/05/2048-c-code-if-you-any-bugs-in-this.html

      Delete
  22. Rishabh sir when i run my program it will not run.. it says tha reload and cntrl+f9 press then game not opening

    ReplyDelete
    Replies
    1. The issue may be because of the bgi directory path, you need to tell the program where to look for the bgi folder in your system. In the line initgraph in main() change the path from "C:\\tc\\bgi" to wherever it is located in your system. It's location is where your turbo compiler is installed.

      Delete
  23. I am getting 3 error declaration syntax error in int check () declaration Missing and compound statement missing after closegraph();
    } Ke baad plzz help me

    ReplyDelete
    Replies
    1. It might be that you may not have copied it correctly, the code is tested and can't have a compound statement missing, make sure there is a compound statement after the closegraph();

      Delete
  24. Replies

    1. er();
      //the compiler asking me the function should have a prototype

      settextstyle(EUROPEAN_FONT,HORIZ_DIR,2);
      //the compiler asking me the function should have a prototype

      Sir please help me

      Delete
  25. Rishabh bhai ,how can i make this program in totally c language ..

    ReplyDelete
    Replies
    1. It's mostly in c. Just try to replace c++ functions with something equivalent in c.

      Delete
  26. Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. Snake games

    ReplyDelete