iCeCee
iCeCee

Reputation: 29

How to make a For Loop of a nested IF Statement?

I am trying to make a for loop for this nested if statement in a Bejeweled clone I am practicing to code. As you can see it's pretty dumb to do it this way, because I want to loop through more matches, so I was wondering if there is a more efficient way than going through and making even more silly If statement nests about 7 times AND for each direction since the grid is 8 by 8.

The if ( i !== 0 ) bit is to prevent null errors. I think with the For statement if it were to be used it can be something like if ( i < loopvar ) instead

Thank you :3

            if (i !== 0 && map[i][j].name == map[i-1][j].name) // this nest of if statements are gonna check the one to the left of the jewel we are looping through, and see if they match.
                {
                    map[i][j].jewelsWest++;
                    if ( i !== 1 && map[i-1][j].name == map[i-2][j].name)
                    {
                        map[i][j].jewelsWest++;
                    }
            }

Upvotes: 1

Views: 75

Answers (1)

3vilguy
3vilguy

Reputation: 981

I think recursion might me handy in this case:

map[i][j].jewelsWest = countMe(i, j, -1, 0);
map[i][j].jewelsEast = countMe(i, j, 1, 0);
map[i][j].jewelsNorth = countMe(i, j, 0, -1);
map[i][j].jewelsSouth = countMe(i, j, 0, 1);


private function countMe(x, y, xDiff, yDiff):int
{
    if(map[x+xDiff] && map[x+xDiff][y+yDiff] && map[x][y].name == map[x+xDiff][y+yDiff].name)
    {
        return 1 + countMe(x+xDiff, y+yDiff, xDiff, yDiff);
    }
    else
    {
        return 0;
    }
}

Upvotes: 1

Related Questions