0

I tried to make the move function recently, and it doesn't put the tile where it is supposed to go. It moves the blank over, and only once. Please help me fix this. My code is `

    bool move(int tile)
    {
    int blank_col = d-1;
    int blank_row = d-1;
    for (int i = 0; i < d; i++) {
        for (int j = 0; j < d; j++) {
            if (board[i][j] == tile) {
                tile_col = i;
                tile_row = j;
            }
        }
    }
    if (tile_col != -1 && tile_row != -1) {
        if (board[tile_col + 1][tile_row] == board[blank_col][blank_row] || 
      board[tile_col - 1][tile_row] == board[blank_col][blank_row] || 
    board[tile_col][tile_row + 1] == board[blank_col][blank_row] || 
    board[tile_col][tile_row - 1] == board[blank_col][blank_row]) {

            /* The swap */
            int temp = board[tile_col][tile_row];
     board[tile_col][tile_row] = board[blank_col][blank_row];
     board[blank_col][blank_row] = temp;


     return true;
        }
    }
    return false;
}`
0

I am new to CS so take this with a grain of salt. From what I can tell in your code, the first iteration will run fine but starting with the second move, your blank_col and blank_row are reset to (d-1) which is not true anymore. That is why it only works once. I would suggest that in the second if, you would want to change "board[blank_col][blank_row]" to the value that you put in the blank tile (e.g. value 0 or whatever you set it to)

 if (board[tile_col + 1][tile_row] == board[blank_col][blank_row] || 
  board[tile_col - 1][tile_row] == board[blank_col][blank_row] || 
board[tile_col][tile_row + 1] == board[blank_col][blank_row] || 
board[tile_col][tile_row - 1] == board[blank_col][blank_row])

After that in the "swap" function, you would want to change board[blank_col][blank_row] = temp; to board[tile_col + 1][tile_row] = temp (if the row is tile below). I don't know a better way but you might want to set up 4 different swaps (top, bottom, left, or right).

Also, while your swap function is good, you don't actually need it since you have tile already. You can do something like this (one example for swapping a tile with the bottom blank tile:

board[tile_col][tile_row] = 0; //assume you used 0 (zero) as the value of your blank board[tile_col + 1][tile_row] = tile;

If this works for you, please increase the vote for my post please. Good luck if you still need it!

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .