I am going through a learning process by coding in C# the Game of Life. I have been able to use a pictureBox and display a grid above so the user can easily click each cell. In button1 I am able to assign the bool variable fill_in a value that will fill in a certain cell when clicked on. But I am now experimenting with loading x and y coordinates of selected cells grabbed from a textfile. Such text file will have on the first line the values: 260 (space) 50. Any Ideas how i can do this?
CODE
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();
//randomly populate grid squares
fill_in[50, 50] = true;
fill_in[60, 50] = true;
fill_in[30, 40] = true;
fill_in[40, 40] = true;
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 button2_Click(object sender, EventArgs e)
{
OpenFileDialog openReport = new OpenFileDialog();
openReport.Filter = "Text Files | *.txt";
openReport.ShowDialog();
StreamReader infile = File.OpenText(openReport.FileName);
//Need Help/Guidance read text file coordinates and populate grid
}
I assume that when you get a value pair “x y” from the text file you want to set fill_in[x, y] to true. So here is a code snip-it to do so.
The basic idea is simple, you read in lines from the file until there are none left. Then you split up said lines based on the criteria that there will be two ints separated by a space. This method is pretty quick and crude because it doesn’t check for malformed data in the text file and doesn’t handle exception, but it will get the job done if you’re careful with forming the text files.
Reading and parsing data from a file is pretty important in programming, so I’d suggest googling the subject and familiarize yourself with the concepts.