1

I just finished trying to implement my move function. It seems to work to a certain extent, except that some of the tiles keep turning into blanks. I have the following code for my swapping:

for (int i = 0; i < d; i++)
   {
        for (int j = 0; j < d; j++)
        {
            if (board[i][j] == tile)
            {
                if (board[i][j+1] == 0)
                {
                    board[i][j+1] = tile;
                    board[i][j] = 0;
                    return true;
                }

I couldn't figure out how to store the position of the blank, but this should work too, right?

0

2 Answers 2

1

if (board[i][j+1] == 0)

So you are using 0 to represent the blank in your array? That's fine, but consider that if you've got a 3x3 game, your bottom right corner is board[2][2] and anything outside those bounds will probably also be 0, because the global board array was declared with board[MAX][MAX]

Are you limiting your i and j so that you never end up testing board[2][3] for example?

What if the blank 0 is at board[2][2] (where i and j are both 2)? Your next if statement says if (board[2][2+1] == 0 and you've now gone outside the bounds of the game board.

4
  • yes, I have nested for loops to limit my i and j. I updated my code above so you can see.
    – dottified
    Commented Jul 8, 2014 at 1:59
  • I added to my reply. Can you see why it still is an issue?
    – curiouskiwi
    Commented Jul 8, 2014 at 2:16
  • 1
    yes, I understand now! I added some conditions to take account of that and it seems to have fixed it. Thanks!
    – dottified
    Commented Jul 8, 2014 at 2:34
  • Glad to hear. Feel free to vote the answer if it was helpful. :)
    – curiouskiwi
    Commented Jul 8, 2014 at 3:32
0

As @curiouskiwi said, you should consider the case in which your don't have a tile above, down, to the right or to the left of the current tile (i.e., board[i][j]), but I'd like to add that if you wanna define a constant value for the blank tile, you may define a constant atop your program. For example,

#include <stdio.h>

#define BLANK 0 // defines a constant named BLANK whose value is 0

int main(void)
{
    // do something
}

Now, whenever you want to refer to the blank tile, you may just use BLANK. For example,

board[i][j] = BLANK; // assigns board[i][j] to 0

You must log in to answer this question.

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