开发者

How to evaluate other elements in an array

Basically I'm creating a forest fire program that depends on the wind / dryness of the surround elements. I have an array var Trees [,] that is 20 x 20. The开发者_如何学运维 middle square is set "on fire". This is what needs to be done once you click button1: Evaluate each square around the one that is set on fire to determine the probability for the others to catch fire.

Color[,] map = new Color[WIDTH, HEIGHT];
for (int x = 0; x < WIDTH; x++)
    for (int y = 0; y < HEIGHT; y++)
    {
        if (x == WIDTH / 2 && y == HEIGHT / 2)
            map[x, y] = Color.Red;
        else
            map[x, y] = Color.Green;
    }

        fireBox1.box = map;

This is the 20 x 20 array that I have setup with the middle square set on fire. I just have no idea how to get the squares (array elements) around the one that is currently on fire.


You can start with a simple loop.

for (int i = 0; i < 20; i++)
{
    for (int j = 0; j < 20; j++)
    {
        var tree = Trees[i, j];
        // ...
    }
}

After you have built your matrix the center should look like this.

[G][G][G]
[G][R][G]
[G][G][G]

Then we can loop through only the points that touch the center point.

int centerX = 9;
int centerY = 9;
int beginX = centerX - 1; 
int endX = centerX + 1; 
int beginY = centerY - 1; 
int endY = centerY + 1; 

for (int y = beginY; y <= endY; y++)
{    
    for (int x = beginX ; x <= endX; x++)
    {
        //Skip the center
        if (x == centerX && y == centerY)
            continue;       
        // Calculate the chance of catching on fire.
        if (IsWindyPoint(x, y) || IsDryPoint(x, y))
            map[x, y] = Color.Yellow;
    }
}

So assuming we have wind blowing east we should see this as the matrix.

[G][G][G]
[G][R][Y]
[G][G][G]

And eventually it will expand out like this.

[G][G][G][G]
[G][G][Y][Y]
[G][R][R][Y]
[G][G][Y][Y]
[G][G][G][G]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜