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.
exit(0);
ReplyDelete}
}
void main() // MAIN FUNTION
i got warning: function should return a value
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.
DeleteHello, 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!! :)
ReplyDeleteThanx 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.
DeleteThanks 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?
DeleteThanx 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.
Deletethe 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.
ReplyDeletePlease confirm which compiler you are using.
DeleteIt 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.
Try to do this. In the main funtion where graph is initialized -> initgraph(&gd,&gm,"C:\\tc\\bgi");
DeleteHere 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");
well that helped. thanks a lot,
Deleteand I must say that this was a pretty good game. well done.
Welcome and also thank you.
DeleteHappy coding :)
same with WangMaya's problem..
ReplyDeletefunction should return a value.
i'd try to run with that error but it won't run.
what should i do..pls help
Please confirm your compiler.
DeleteIf it is a DosBox it should run fine. You might be compiling it. Please run it. If no tell the problem briefly.
I tried as what u say..but it's still the same problem :(
DeleteThis comment has been removed by the author.
DeleteOk 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");
DeleteHere 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");
thanks a lot rishabh.. it works :(
DeleteNew Program Sudoku solver https://www.youtube.com/watch?v=AVOriVB67Wg
ReplyDeletePlease Share and Subscribe and show some support. Thanx for your interest.
Happy Coding. Stay tuned for more.
This comment has been removed by the author.
ReplyDeleteBhai mai jab program run kar raha hoon toh snake ki tohdi body wahin rah jaa rahi hai
ReplyDeleteMight have not copied the full code.
DeleteBhai mujhe ek student dbms ki zarrorat hai with structures pls help mr
ReplyDeleteDetails Please.
DeleteHi Rishabh Bhaiya, i'm glad i found the video on youtube and i must say i've become a fan of your work.
ReplyDeleteIs there any way to make the ellipses more round, like a circle or a different shape like a square ?
ReplyDeleteThank 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.
DeleteHappy coding.
This comment has been removed by the author.
ReplyDeleteWarning is because of the check() function change it to void or you may return a value there. it wouldn't make a difference
Deletecan you tell me exactly what corrections I have to make please.
DeleteJust put a return 0 at the end of the function int check()
DeleteWhat is the features of this game?
ReplyDeleteit 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.
Deleteplease sent report for UG final year project
ReplyDeleteI'm sorry are u asking for format of report?
ReplyDeleteERROR: must use c++ for the type iostream.
ReplyDeletewhat to do now.
m using DOSBox v0.74 Manual
DeleteSave it with the extension .cpp
Deletecan u send the link for turboc++....its not running on my turbo
Deletehttps://turboc.codeplex.com/
DeleteHere You Go.
Hey ! Rishabh. Why you have used while(1) in move function ?
ReplyDeleteCould you please explain it.
Thank-you
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.
Deleteand your snake can not be longer than 50 number of ellipse.
DeleteDid you also use Data structures in it ?
And can you explain me the move function which you have used in it ?
Thank-You
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.
DeleteHow 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?
ReplyDeleteThere 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?
DeletePlease Rishabh Aggarwal answer my question?
ReplyDeleteBhai yeh bata sakte ho examiner ne kya poocha tha jab aapne ye project submit kia tha(viva)...
ReplyDeleteAsked 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?
DeleteFunction should not return a value warning occur
ReplyDeleteI 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!!
ReplyDeletehttps://breakthecodenow.blogspot.in/2018/05/2048-c-code-if-you-any-bugs-in-this.html
DeleteRishabh sir when i run my program it will not run.. it says tha reload and cntrl+f9 press then game not opening
ReplyDeleteThe 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.
DeleteI am getting 3 error declaration syntax error in int check () declaration Missing and compound statement missing after closegraph();
ReplyDelete} Ke baad plzz help me
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();
DeleteHats of bhai
ReplyDeleteThanks
Delete
Deleteer();
//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
Rishabh bhai ,how can i make this program in totally c language ..
ReplyDeleteIt's mostly in c. Just try to replace c++ functions with something equivalent in c.
Deletesnake
ReplyDeletesnake game
snake cool math
snake cool math games
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