我正在通过实现 Game of Life 的副本来学习 C#。我已经能够使用 for 循环在 pictureBox
上成功绘制网格。名为 fill_in
的 bool 用于填充正方形。我请求帮助使方 block 可点击。我已将 pictureBox
的属性设置为允许 pictureBox_MouseClick
。在 mouseClick 事件中,我设置了坐标 x
和 y
。问题是该事件中的 if 语句不正确,因为 ==
不能应用于 bool 操作数。
如果 bool fill_in
为真,我如何做一个将用黑色填充的 if 条件语句?
代码
namespace life
{
public partial class Form1 : Form
{
Graphics paper;
bool[,] fill_in = new bool[450, 450];
public Form1()
{
InitializeComponent();
paper = pictureBox1.CreateGraphics();
}
//makes grid in picture box
private void drawGrid()
{
int numOfCells = 100;
int cellSize = 10;
Pen p = new Pen(Color.Blue);
paper.Clear(Color.White);
for (int i = 0; i < numOfCells; i++)
{
// Vertical
paper.DrawLine(p, i * cellSize, 0, i * cellSize, numOfCells * cellSize);
// Horizontal
paper.DrawLine(p, 0, i * cellSize, numOfCells * cellSize, i * cellSize);
}
}
// populate bool fill_in with true (alive) or false (dead)
private void clearGrid()
{
for (int x = 0; x < 450; x = x + 10)
{
for (int y = 0; y < 450; y = y + 10)
{
fill_in[x, y] = false;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
drawGrid();
clearGrid();
for (int x = 0; x < 440; x = x + 10)
{
for (int y = 0; y < 440; y = y + 10)
{
if (fill_in[x, y] == true)
paper.FillRectangle(Brushes.Black, x, y, 10, 10);
}
}
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
int x = e.X;
int y = e.Y;
int i = x / 10;
int j = y / 10;
fill_in[i, j] = !fill_in[i, j];
if (fill_in[i, j])
{
paper.FillRectangle(Brushes.Black, x, y, 10, 10);
}
else
{
paper.FillRectangle(Brushes.White, x, y, 10, 10);
}
}
}
}
if 语句更改后:
最佳答案
pictureBox1_MouseClick
中的 if (fill_in == true)
缺少数组下标(fill_in
是一个数组,还记得吗?)。
不过没关系;你已经知道 fill_in[i, j]
是真的,因为你就是这样做的,所以你可以完全删除 if
。
如果您希望在第一次点击时填充它,然后取消填充(将其恢复为“未填充”),您只需稍微更改您的事件处理程序:
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
int x = e.X;
int y = e.Y;
int i = x / 10;
int j = y / 10;
// Reverse the value of fill_in[i, j] - if it was false, change to true,
// and if true change to false
fill_in[i, j] = !fill_in[i, j];
if (fill_in[i, j])
{
// Fill grid square with the filled color
}
else
{
// Fill grid square with unfilled color
}
}
关于c# - PictureBox- 网格和正方形填充(生命游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737103/