-
-
Save anonymous/5fa45dd76833593badc7df9d432fdf6f to your computer and use it in GitHub Desktop.
fifteen.c - shared from CS50 IDE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Initializes the game's board with tiles numbered 1 through d*d - 1 | |
* (i.e., fills 2D array with values but does not actually print them). | |
*/ | |
void init(void) | |
{ | |
// TODO | |
int i,j; | |
int k=d*d-1; | |
for(i=0;i<d;i++) | |
{ | |
for(j=0;j<d;j++) | |
{ | |
board[i][j]=k--; | |
if(k%2!=0) | |
{ | |
break; | |
} | |
else | |
{ | |
if((board[i][j]==2) && (board[i][j-1]==1)) | |
metrytoexchange(&board[i][j],&board[i][j-1]); | |
} | |
} | |
} | |
} | |
/** | |
* Prints the board in its current state. | |
*/ | |
void draw(void) | |
{// TODO | |
int k=d*d-1; | |
for(int i=0;i<d;i++) | |
{ | |
for(int j=0;j<d;j++) | |
{ | |
board[i][j]=k--; | |
if(board[i][j]==0) | |
{ | |
printf("_"); | |
} | |
else | |
printf("%d \t",board[i][j]); | |
} | |
printf("\n"); | |
} | |
} | |
void metrytoexchange(int *a,int *b) | |
{ | |
int temp= *a; | |
*a = *b; | |
*b = temp; | |
} | |
/** | |
* If tile borders empty space, moves tile and returns true, else | |
* returns false. | |
*/ | |
bool move(int tile) | |
{ | |
int k=d*d-1; | |
int blank_space=0; | |
//dont go beyond the grid | |
for(int i=0;i<d;i++) | |
{ | |
for(int j=0;j<d;j++) | |
{ | |
if(tile<k && tile>0 && tile==board[i][j]) | |
{ | |
continue; | |
} | |
else | |
{ | |
break; | |
} | |
//iterate to check the position of of blank tile;left to right up and down if not return false | |
if(board[i-1][j]!=blank_space || board[i][j-1]!=blank_space || board[i+1][j]!=blank_space || board[i][j+1]!=blank_space) | |
{ | |
return false; | |
} | |
//else swap tile with blank_space | |
else | |
{ | |
metrytoexchange(&tile,&blank_space); | |
return true; | |
} | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment