我正在通过编写 LIFE 游戏来试验和学习 C#。目前我有一个pictureBox
和一个drawGrid
创建网格覆盖的函数。为了点击里面的每个单元格,pictureBox
我已经实现了一个属性pictureBox1_MouseClick
,其中有一个 if 决策逻辑来知道是否选择了一个单元格。我遇到的问题是当我快速单击方块时出现错误:System.IndexOutOfRangeException
指向fill_in[x, y] = !fill_in[x, y];
.
如何提高pictureBox1_MouseClick
事件的点击准确性,以免出现该错误?
具体错误:
`life.exe 中发生了“System.IndexOutOfRangeException”类型的未处理异常
附加信息:索引超出了数组的范围。`
代码
namespace life
{
public partial class Form1 : Form
{
Graphics paper;
bool[,] fill_in = new bool[450, 450];
int cellSize = 10;
private void drawGrid()
{
int numOfCells = 100;
Pen p = new Pen(Color.Blue);
paper.Clear(Color.White);
for (int i = 0; i < numOfCells; i++)
{
// Vertical Lines
paper.DrawLine(p, i * cellSize, 0, i * cellSize, numOfCells * cellSize);
// Horizontal Lines
paper.DrawLine(p, 0, i * cellSize, numOfCells * cellSize, i * cellSize);
}
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
int x = cellSize * (e.X / cellSize);
int y = cellSize * (e.Y / cellSize);
// Reverse the value of fill_in[i, j] - if it was false, change to true,
// and if true change to false
fill_in[x, y] = !fill_in[x, y];
if (fill_in[x, y])
{
// Fill grid square with the filled color
paper.FillRectangle(Brushes.Red, x, y, 10, 10);
}
else
{
// Fill grid square with unfilled color
paper.FillRectangle(Brushes.White, x, y, 10, 10);
}
}
}
}