fifteen puzzle - c src code
TRANSCRIPT
-
7/29/2019 Fifteen Puzzle - C Src Code
1/5
/* The Fifteen Puzzle *//* Author: K. Raghunathan */
# include # include # include # include
int cheklist[16];const int solution[16]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0};int gridstat[16]; /* tile nos. existing now in the 16 squares */int tileloc[16]; /* square nos. in which the 16 tiles exist now */
/* starting col & row of tile for the 16 squares */int stloc[16][2] = { 6,6, 13,6, 20,6, 27,6,
6,10, 13,10, 20,10, 27,10,6,14, 13,14, 20,14, 27,14,6,18, 13,18, 20,18, 27,18};
/* for the 16 possible locs of blank, the sqr-num from which a tile can bemoved by pressing Left/Right/Up/Down arrows;sqr-num 20 means move in that direction is not possible. */
int movsqr[16][4]={ 1,20, 4,20,
2, 0, 5,20,3, 1, 6,20,20, 2, 7,20,
5,20, 8, 0,6, 4, 9, 1,7, 5,10, 2,
20, 6,11, 3,9,20,12, 4,
10, 8,13, 5,11, 9,14, 6,20,10,15, 7,13,20,20, 8,14,12,20, 9,15,13,20,10,20,14,20,11};
void drawbox(){ int row=5, col=5;
int i,j;gotoxy(col, row);printf("%c", 201);for (i=0; i
-
7/29/2019 Fifteen Puzzle - C Src Code
2/5
for (row=9; row
-
7/29/2019 Fifteen Puzzle - C Src Code
3/5
printf("%d", tnum);}
void erasetile (sqnum){ int i,j, stcol,strow;
stcol = stloc[sqnum][0];strow = stloc[sqnum][1];for (i=0; i
-
7/29/2019 Fifteen Puzzle - C Src Code
4/5
while (again) /* outer loop */{ clrscr();
generate();drawbox();for (i=0; i0)drawtile(i, gridstat[i]);
done = 0;while (!done) /* inner loop */{ blank = tileloc[0];
kval = getkey();kscan = kval / 256;nomove=0;switch (kscan){ case 75: /* Left arrow */
if ((blank%4)==3)nomove = 1;
elsesqrnum = movsqr[blank][0];
break;case 77: /* Right arrow */
if ((blank%4)==0)
nomove = 1;elsesqrnum = movsqr[blank][1];
break;case 72: /* Up arrow */
if (blank > 11)nomove = 1;
elsesqrnum = movsqr[blank][2];
break;case 80: /* Down arrow */
if (blank < 4)nomove = 1;
elsesqrnum = movsqr[blank][3];
break;case 1: return; /* Escape key = Quit */default: nomove=1;
}
if (nomove)continue;
else{ tilnum = gridstat[sqrnum];
erasetile(sqrnum);drawtile(blank, tilnum);gridstat[sqrnum] = 0;gridstat[blank] = tilnum;tileloc[tilnum] = blank;tileloc[0] = sqrnum;done=checkend();
}} /* inner while loop */
if (done){ gotoxy(40, 22);
printf("Congrats !");printf(" Play again ? (y/n): ");again = getch();
}if (again=='y' || again=='Y')
Page 4
-
7/29/2019 Fifteen Puzzle - C Src Code
5/5
again = 1;else
again = 0;} /* outer while loop */
getch();
}
/* -- eof -- */
Page 5