Thursday, 2 August 2018

C++ Programming To Create Snake Game

If you want to create snake game by C++ programming then type the following program :-




#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<stdlib.h>
#include<time.h>
#include<graphics.h>
#include<iostream.h>


void wall(void);
void food(void);
int x[100],y[100],i,length=9,score=0,lk=0,eat=0,xf,yf,c=0;

void main()
{
clrscr();

textcolor(15);
gotoxy(22,11);
cout<<"Use the arrow keys to change direction";
gotoxy(23,12);
cout<<"Press 'p' to PAUSE and 'Esc' to EXIT";
gotoxy(27,13);
cout<<"Press ENTER to continue...";
getch();
clrscr();
wall();
for(i=length-1;i>=0;i--)             //positioning the snake initially
{
x[i]=45-i;
y[i]=20;
}


while(1)
{


while(kbhit()==0)
{
gotoxy(60,1);
cout<<"TOTAL SCORE : "<<score;
for(i=length-1;i>0;i--)
{
x[i]=x[i-1];
y[i]=y[i-1];

}
textcolor(YELLOW);
for(i=length-1;i>0;i--)        //snake structure
{
gotoxy(x[i],y[i]);
cprintf("0");
}
gotoxy(x[0],y[0]);
textcolor(4);
cprintf(" ");
textcolor(15);
gotoxy(x[length-1],y[length-1]);
cout<<" ";
food();
if(lk==0 || lk==1)       //main delays
{
delay(100);
}
if(lk==2 || lk==3)
{
delay(150);
}
if(x[0]==78 || x[0]==3 || y[0]==2 || y[0]==25) //hit wall
{
delay(1000);
clrscr();
wall();
gotoxy(30,13);
cout<<"You have hit the wall.";
gotoxy(33,14);
cout<<"Total score : "<<score;
getch();
exit(0);
}


if(lk==0)
{
x[0]++;
}
if(lk==1)
{
x[0]--;
}
if(lk==2)
{
y[0]--;
}
if(lk==3)
{
y[0]++;
}


for(i=length-1;i>1;i--)      //hit itself
{
if(x[0]==x[i] && y[0]==y[i])
{
delay(1000);
clrscr();
wall();
gotoxy(32,13);
cout<<"You have hit Yourself";
gotoxy(33,14);
cout<<"Total score : "<<score;
getch();
getch();
exit(0);
}
}

}
int g;
g=getch();

if(g==72)
{
lk=2;
}
else if(g==77)
{
lk=0;
}
else if(g==80)
{
lk=3;
}
else if(g==75)
{
lk=1;
}
else if(g=='p')
{
while(g=='p')
{
int o;
o=getch();
if(o==13)
g='13';
}
}
else if(g==27)
{
gotoxy(30,14);
int y;
textcolor(15);
cprintf("ARE YOU SURE TO EXIT(y/n) ?");

y=getch();
if(y=='y')
{
clrscr();
wall();
gotoxy(35,14);
cout<<"EXITING...";
delay(1000);
exit(0);

}
else
{
gotoxy(30,14);
cout<<"                            ";
}

}




}
}


void wall(void)
{
int x1,y1;
for(x1=2;x1<=79;x1++)
{
gotoxy(x1,2);
cout<<"=";
if(c==0)
delay(10);
gotoxy(x1,25);
cout<<"=";
}
for(y1=3;y1<=24;y1++)
{
gotoxy(2,y1);
cout<<"||";
if(c==0)
delay(10);
gotoxy(78,y1);
cout<<"||";
}
c=1;
}


void food(void)
{
if(eat==0)
{
xf=random(68)+6;
yf=random(18)+6;
eat=1;
}
gotoxy(xf,yf);
textcolor(10);
cprintf("*");
textcolor(15);
if((xf==x[0])&&(yf==y[0]))
{
score=score+9;
length++;
eat=0;
}

}

If you want more programing then tell me in the comment box.

By Theory Duke
       theory duke

Related Posts:

0 comments:

Plz. comment