Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void init(void)
- {
- {
- n = d * d - 1;
- blank_tile = n;
- for (int i = 0; i < d; i++){
- for (int j = 0; j < d; j++) {
- board[i][j] = n;
- n--;
- }
- }
- n = blank_tile;
- // switches the last two tiles if the board is of an odd dimension
- if ((d % 2) != 0) {
- int temp = board[d][d-1];
- board[d][d-1] = board[d][d-2];
- board[d][d-2] = temp;
- }
- }
- }
- /**
- * Prints the board in its current state.
- */
- void draw(void)
- {
- int current = 0;
- for (int i = 0; i < d; i++){
- for (int j = 0; j < d; j++) {
- // prints the underscore or blank tile
- if (current == blank_tile){
- printf("|_|");
- } else {
- printf("|%d|", board[i][j]);
- }
- current++;
- }
- printf("\n");
- }
- }
- /**
- * If tile borders empty space, moves tile and returns true, else
- * returns false.
- */
- bool move(int tile)
- {
- int temp = n - tile + 1;
- tile = temp;
- if (tile < 0 || tile > n)
- return false;
- //printf("Value: %d\n", tile);
- if (((tile % d) != 0 && (tile - 1) == blank_tile) || // checks to the left and makes sure that it it is not up against left edge
- ((tile % d) != (d-1) && (tile + 1) == blank_tile) || // makes sure that it is not up against right edge and checks to the right
- (tile - d) == blank_tile || // checks upward
- (tile + d) == blank_tile) { // checks downward
- int blank_row = blank_tile / d;
- int blank_col = blank_tile % d;
- int tile_row = tile / d;
- int tile_col = tile % d;
- board[blank_row][blank_col] = board[tile_row][tile_col];
- blank_tile = tile;
- return true;
- }
- return false;
- }
- /**
- * Returns true if game is won (i.e., board is in winning configuration),
- * else false.
- */
- bool won(void)
- {
- int current_tile = -1;
- for (int i = 0; i < d; i++){
- for (int j = 0; j < d; j++) {
- if (board[i][j] > current_tile) {
- current_tile = board[i][j];
- } else {
- return false;
- }
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement