检查对象是否在矩阵范围内

Check if object is in range in a matrix

我想检查一个对象是否在矩阵的范围内。
1 范围是玩家周围 9 个方块 (橙色)
但是两个范围是 25 个方块 (蓝色)玩家是红十字

我试了下面的代码:
`

int size = ((range * 2) +1) * ((range * 2) + 1);
    int sq = (range * 2) + 1;
    int startX = x - range; if (startX < 0) startX = 0;
    int startY = y - range; if (startY < 0) startY = 0;
    int endX = x + range; if (endX > arrayWitdth) endX = arrayWitdth;
    int endY = y + range; if (endY > arrayLenght) endY = arrayLenght;
    //printf("Range: %d\n", range);
    for (size_t i = startX; i < endX; i++)
    {
        for (size_t j = startY; j < endY; j++)
        {
            //printf("Looking at (%d,%d)\n", i, j);
            if (map[i][j] == charTocheck) return 1;
        }
    }

`

你没有检查最后一个块,所以正确的实现是:

int size = ((range * 2) +1) * ((range * 2) + 1);
int sq = (range * 2) + 1;
int startX = x - range; if (startX < 0) startX = 0;
int startY = y - range; if (startY < 0) startY = 0;
int endX = x + range + 1; if (endX > arrayWitdth) endX = arrayWitdth;
int endY = y + range + 1; if (endY > arrayLenght) endY = arrayLenght;
//printf("Range: %d\n", range);
for (size_t i = startX; i < endX; i++)
{
    for (size_t j = startY; j < endY; j++)
    {
        //printf("Looking at (%d,%d)\n", i, j);
        if (map[i][j] == charTocheck) return 1;
    }
}

注意 endX 和 endY 略有变化。