Skip to content

Instantly share code, notes, and snippets.

/fifteen.c Secret

Created November 30, 2016 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5fa45dd76833593badc7df9d432fdf6f to your computer and use it in GitHub Desktop.
Save anonymous/5fa45dd76833593badc7df9d432fdf6f to your computer and use it in GitHub Desktop.
fifteen.c - shared from CS50 IDE
/**
* 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