我对C ++还是很陌生,想知道是否有更好的方法可以做到这一点。它要在Arduino上运行,所以我不能使用ArrayLists或其他任何东西。

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;
}


谢谢,

最佳答案

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;
}

10-04 19:54