0

I'm very new to C++ and was wondering if if there is a better way of doing this. It's going to run on an Arduino so I can't use ArrayLists or anything.

byte GetFreeCell(short x, short y)
{
    byte possibleMoves[4] = {0,0,0,0};
    if (y - 2 >= 0 && _grid[y - 2][x] == 0)
        possibleMoves[0] = 1;
    if (x + 2 < WIDTH && _grid[y][x + 2] == 0)
        possibleMoves[1] = 2;
    if (y + 2 < HEIGHT && _grid[y + 2][x] == 0)
        possibleMoves[2] = 3;
    if (x - 2 >= 0 && _grid[y][x - 2] == 0)
        possibleMoves[3] = 4;

    if (possibleMoves[0] == 0 && possibleMoves[1] == 0 && possibleMoves[2] == 0 && possibleMoves[3] == 0) {
        return 0;
    }

    byte move = 0;
    while(move == 0){
        move = possibleMoves[random(4)];
    }
    return move;
}

Thanks,

Joe

1
  • Define "better"? Do you want a more concise way of doing it? Commented Jan 25, 2013 at 20:08

2 Answers 2

4
byte GetFreeCell(short x, short y)
{
    byte possibleMoves[4];
    byte index = 0;
    if (y - 2 >= 0 && _grid[y - 2][x] == 0)
        possibleMoves[index++] = 1;
    if (x + 2 < WIDTH && _grid[y][x + 2] == 0)
        possibleMoves[index++] = 2;
    if (y + 2 < HEIGHT && _grid[y + 2][x] == 0)
        possibleMoves[index++] = 3;
    if (x - 2 >= 0 && _grid[y][x - 2] == 0)
        possibleMoves[index++] = 4;

    return index ? possibleMoves[random(index)] : 0;
}
Sign up to request clarification or add additional context in comments.

5 Comments

+1, beat me to it. Maybe make index a byte, it's an unsigned 8bit type on arduino (vs int, which is signed 16bit).
I was just going to suggest what you edited in, but it's not really neccesary (it does help readability, though) +1
@billz read carefully, OP's code has return 0; earlier, for the same condition that mine.
Thanks, makes perfect sense. Not sure why I didn't think of that, I'm a little embarrased now.
us2012: The last ++ operator acts as the index when setting the array and then increments meaning that the random(index) is random(4) which can be 0,1,2 or 3.
0

You can do yourself a favor and use this:

https://github.com/maniacbug/StandardCplusplus/#readme

Then you can sanitize your code by using standard containers.

Also, there's no ArrayList in C++. That's Java. With the above library, you can use std::vector instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.