Here is a really quick and very dirty implementation in C#. It uses a picturebox 599 by 399 pixels wide, a timer and a button. You should be able to figure out the events handled from the code below. I thought it could be fun to pick apart as some kind of collective code review.
You need to draw your starting colony with the mouse in the picturebox. Enjoy!
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GameOfLife
{
public partial class MainForm : Form
{
cField Field = new cField();
bool MouseIsDown = false;
public MainForm()
{
InitializeComponent();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < 150; i++)
for (int j = 0; j < 100; j++)
if (Field.Cells[i, j] > 0)
e.Graphics.DrawRectangle(new Pen(Color.FromArgb(Math.Min(Field.Cells[i,j], 255), Math.Min(Math.Max(Field.Cells[i,j]-255, 1), 255), Math.Min(Math.Max(Field.Cells[i,j]-512, 1), 255)), 2), i * 4, j * 4, 2, 2);
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
pictureBox1.Refresh();
btnStart.Text = timer1.Enabled ? "Stop" : "Start";
}
private void timer1_Tick(object sender, EventArgs e)
{
Field.Recalculate();
pictureBox1.Refresh();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
timer1.Enabled = false;
MouseIsDown = true;
Field.Cells[e.X / 4, e.Y / 4] = 1;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X < 0) return;
if (e.Y < 0) return;
if (e.X / 4 > 149) return;
if (e.Y / 4 > 99) return;
if (MouseIsDown)
{
Field.Cells[e.X / 4, e.Y / 4] = 1;
pictureBox1.Refresh();
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
MouseIsDown = false;
if (btnStart.Text == "Stop")
timer1.Enabled = true;
}
}
public class cField
{
public int[,] Cells = new int[150,100];
public int[,] newCells = new int[150, 100];
public void Recalculate()
{
int neighbours = 0;
for (int i = 0; i < 150; i++)
for (int j = 0; j < 100; j++)
newCells[i, j] = 0;
for (int i = 0; i < 149; i++)
for (int j = 0; j < 99; j++)
{
neighbours = 0;
if (i > 0 && j > 0)
{
if (Cells[i - 1, j - 1] > 0)
neighbours++;
if (Cells[i - 1, j] > 0)
neighbours++;
if (Cells[i - 1, j + 1] > 0)
neighbours++;
if (Cells[i, j - 1] > 0)
neighbours++;
if (Cells[i, j + 1] > 0)
neighbours++;
if (Cells[i + 1, j - 1] > 0)
neighbours++;
}
if (Cells[i + 1, j] > 0)
neighbours++;
if (Cells[i + 1, j + 1] > 0)
neighbours++;
if (neighbours < 2)
newCells[i, j] = 0;
if (neighbours > 3)
newCells[i, j] = 0;
if ((neighbours == 2 || neighbours == 3) && Cells[i, j] > 0)
newCells[i, j] = Cells[i,j]+10;
if (neighbours == 3 && Cells[i, j] == 0)
newCells[i, j] = 1;
}
for (int i = 0; i < 150; i++)
for (int j = 0; j < 100; j++)
Cells[i, j] = newCells[i,j];
}
}
}