我正在通过实现生命游戏的副本来学习 C#。我已经能够成功地在pictureBox
使用 for 循环上绘制网格。名为的布尔值fill_in
是填充正方形。我请求帮助使方块可点击。我已将属性属性设置pictureBox
为允许pictureBox_MouseClick
。在 mouseClick 事件中,我设置了坐标x
和y
. 问题是该事件中的 if 语句不正确,因为==
不能应用于 bool 操作数。
fill_in
如果 bool为真,我该如何做一个用黑色填充的 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 语句后: