Square Game:
"Its a challenge!!!!!"
"/" is used instead of "<" and ">".
#include/stdio.h/
#include/conio.h/
#include/graphics.h/
#include/dos.h/
#include/math.h/
#include/stdlib.h/
int a[4][4]={9,2,7,14,5,1,18,4,6,3,11,16,15,19,13,1024},X[4],Y[4],xcount=3,ycount=3,ax=0,ay=0,nom=0; //nom---> no. of moves
void create(),fun(),disp(int),swap();
char getke();
void main()
{
int gd=DETECT,gm,i,j,k;
initgraph(&gd,&gm,"e:\\tc"); //give correct path(bgi directory)
create();
disp(nom);
fun(); //a[4][4] is an 2-d array in which the elements are stored
getch();
//x[4],y[4] are taken for display purpose where the screen positions are stored
}
char getke() //detecting characters
{
char ch;
ch=getch();
if(ch==27)
return('e'); //for exit
if(ch==0) //procedure for retrieving scan code for usage of arrow keys
{
ch=getch();
if(ch==72)
return('u'); //up arrow
if(ch==80) //down arrow
return('d');
if(ch==75) //left arrow
return('l');
if(ch==77)
return('r'); //right arrow
}
}
void create() //rectangular framework
{
int i,j,x=150,y=150;
rectangle(150,150,350,350);
for(i=150;i<350;i+=50)
{
line(i,150,i,350);
}
for(j=150;j<350;j+=50)
{
line(150,j,350,j);
}
for(i=0;i<4;i++,y+=50)
{
Y[i]= y+25;
X[i]=y+25;
}
}
void fun() //procedure after certain key is detected
{
char ch;
while((ch=getke())!='e')
{
if(ch=='u')
{
ax=1;
ay=0;
if(xcount!=0) //boundary condition
{
nom++;
xcount--;
swap();
}
disp(nom); //used to display the elements (refresh).
}
if(ch=='d')
{
ax=-1;
ay=0;
if(xcount!=3)
{
nom++;
xcount++;
swap();
}
disp(nom);
}
if(ch=='l')
{
ax=0;
ay=1;
if(ycount!=0)
{
nom++;
ycount--;
swap();
}
disp(nom);
}
if(ch=='r')
{
ax=0;
ay=-1;
if(ycount!=3)
{
nom++;
ycount++;
swap();
}
disp(nom);
}
}
}
void disp(int x)
{
char *s,*p;
int i,j;
cleardevice();
rectangle(1,1,639,479);
line(500,0,500,479);
itoa(x,p,10);
outtextxy(510,200,"MOVES = ");
outtextxy(580,200,p);
create();
for(i=0;i<4;i++)
{
for(j=0;j<4;j++) //1024 some element
{
if(a[i][j]!=1024)
{
itoa(a[i][j],s,10); //function which converts intezer to string
outtextxy(X[j],Y[i],s);
}
else
{
setfillstyle(1,2);
bar(X[j]-24,Y[i]-24,X[j]+24,Y[i]+24);
}
}
}
}
void swap()
{
int t;
t=a[xcount+ax][ycount+ay];
a[xcount+ax][ycount+ay]=a[xcount][ycount];
a[xcount][ycount]=t;
}
0 comments:
Post a Comment