1

I've been attempting many different ways to make this work and I either come up with everything stopping once the game looks like it's been won and an "illegal move" and "retry" message, or I end up with a successful end "ftw" when in fact it's not actually won. (See result below code).

So sorry to repeat similar questions. I can't seem to find the answers in what I've reviewed from others. Where am I going wrong?

bool won(void)
{
// TODO
    for (int i = 0; i < d - 1; i++)
    {
        for (int j = 0;j < d - 1;j++)
        {
            if (board[d - 1][d - 1] == 0)
            {
                if (board[0][0] == 1 && board [i][j - 2] < board[i][j - 1])
                {
                    return true;
                }
            }

        }
    }
    {
        return false;
    }
}

Here's what I get with this:

1   2   3  
4   8   7  
6   5   _  
ftw!

2 Answers 2

2

You are checking if everything is alright. And if the first part is alright you are returning true right away.

This piece of code is exiting if the second box is correct without checking the rest of the board.

if (board[d - 1][d - 1] == 0)
{
    if (board[0][0] == 1 && board [i][j - 2] < board[i][j - 1])
    {
        return true;
    }    
}

If you return the function ends; it does not keep checking the rest of the loop.

I suggest you check for a wrong case. In case something is wrong return false.

For example:

Instead of checking for less than, check for greater than. And instead of returning true, return false.

if (board[d - 1][d - 1] == 0)
{
    if (board[0][0] == 1 && board [i][j - 2] > board[i][j - 1])
    {
        return false;
    }    
}

Return true at the very end of the function in case nothing went wrong.

0
1

Basically, you code will always return true when 0 and 1 in the right positions, no matter where the other tiles are.

Mistakes:

  1. You loop not from 0 to d - 1, but from 0 to d - 2 (i < d - 1). Thus, for d = 3 you check just 2*2 not 3*3

  2. Even if you correct #1, the problem is still here, as you your use j - 2 and j - 1. So for i = 0, j = 0, you compare board[0][-2] and board [0][-1] which makes no sense. Try to change this.

  3. Last mistake, as previous comment says, is that your function returns true if just any two tiles are in order, while you need to check that all tiles are in order. Changing logic to "return false" should help.

You must log in to answer this question.

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