-
-
Save anonymous/fb943980ec3ee81f98d9ff6ff1b4cfef 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
void init(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(k%2==0) | |
{ | |
if(board[d-1][d-3]==2 && board[d-1][d-2]==1) | |
me_swap(&board[d-1][d-3], &board[d-1][d-2]); | |
} | |
} | |
/** | |
* Prints the board in its current state. | |
*/ | |
void draw(void) | |
{ | |
// TODO | |
for(int i=0;i<d;i++) | |
{ | |
for(int j=0;j<d;j++) | |
{ | |
if(board[i][j]==0) | |
{ | |
printf("_ \t"); | |
} | |
else | |
{ | |
printf("%2d \t ",board[i][j]); | |
} | |
} | |
printf("\n"); | |
} | |
} | |
/** | |
* If tile borders empty space, moves tile and returns true, else | |
* returns false. | |
*/ | |
bool move(int tile) | |
{ | |
// TODO | |
int blank_space=0; | |
for(int i=0;i<d;i++) | |
{ | |
for(int j=0;j<d;j++) | |
{ | |
if(tile==board[i][j] && tile<(d*d-1) && tile>0) | |
{ | |
if(board[i-1][j]==blank_space) | |
{ | |
me_swap(&board[i][j],&board[i-1][j]); | |
return true; | |
} | |
if( board[i][j-1]==blank_space) | |
{ | |
me_swap(&board[i][j-1],&board[i][j]); | |
return true; | |
} | |
if(board[i+1][j]==blank_space ) | |
{ | |
me_swap(&board[i][j],&board[i+1][j]); | |
return true; | |
} | |
if(board[i][j+1]==blank_space) | |
{ | |
me_swap(&board[i][j],&board[i][j+1]); | |
return true; | |
} | |
} | |
} | |
} | |
return false; | |
} | |
/** | |
* Returns true if game is won (i.e., board is in winning configuration), | |
* else false. | |
*/ | |
bool won(void) | |
{ | |
// TODO | |
int a=0; | |
int won_board[d][d]; | |
for(int i=0;i<d;i++) | |
{ | |
for(int j=0;j<d;j++) | |
{ | |
won_board[i][j]= a++; | |
} | |
} | |
for(int i=0;i<d;i++) | |
{ | |
for(int j=0;j<d;j++) | |
{ | |
if(board[i][j]==won_board[i][j]) | |
{ | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
//call swap when in need to | |
void me_swap (int *a, int *b) | |
{ | |
int temp=*a; | |
*a=*b; | |
*b=temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment