Hallo Leute.
Ich brauchte eine Matrix für mein GameOfLife.
Dazu habe ich mir eine Programmiert.
Das ist im Grunde nichts anderes als eine List<T> in einer List<>.
Man hat noch eine Size (breite / höhe) und man kann spiegeln.
Hoffe gefällt euch.
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace GameOfLife
{
public class CellMatrix<T>
{
private List<List<T>> data = new List<List<T>>();
private Size size = new Size(0, 0);
public T this[int x, int y]
{
get
{
while (x < 0)
x += this.size.Width;
while (x >= this.size.Width)
x -= this.size.Width;
while (y < 0)
y += this.size.Height;
while (y >= this.size.Height)
y -= this.size.Height;
return this.data[y][x];
}
set
{
while (x < 0)
x += this.size.Width;
while (x >= this.size.Width)
x -= this.size.Width;
while (y < 0)
y += this.size.Height;
while (y >= this.size.Height)
y -= this.size.Height;
this.data[y][x] = value;
}
}
public Size Size
{
get
{
return this.size;
}
set
{
if (this.size != value)
{
this.size = value;
Refresh();
}
}
}
public CellMatrix()
{
}
public CellMatrix(int width, int height)
{
this.size = new Size(width, height);
Refresh();
}
public void Flip(bool hor, bool ver)
{
if ((!hor) && (!ver))
return;
List<List<T>> tmp = new List<List<T>>();
for (int y = 0; y < this.size.Height; y++)
{
int y2 = (ver) ? 0 : tmp.Count;
tmp.Insert(y2, new List<T>());
for (int x = 0; x < this.size.Width; x++)
{
int x2 = (hor) ? 0 : tmp[y2].Count;
tmp[y2].Insert(x2, this.data[y][x]);
}
}
this.data = tmp;
}
private void Refresh()
{
if (this.data.Count < this.size.Height)
{
int diff = this.size.Height - this.data.Count;
for (int i = 0; i < diff; i++)
this.data.Add(new List<T>());
}
else if (this.data.Count > this.size.Height)
{
int diff = this.data.Count - this.size.Height;
for (int i = 0; i < diff; i++)
this.data.RemoveAt(this.data.Count - 1);
}
for (int y = 0; y < this.size.Height; y++)
{
if (this.data[y].Count < this.size.Width)
{
int diff = this.size.Width - this.data[y].Count;
for (int i = 0; i < diff; i++)
this.data[y].Add((T)new object());
}
else if (this.data[y].Count > this.size.Width)
{
int diff = this.data[y].Count - this.size.Width;
for (int i = 0; i < diff; i++)
this.data[y].RemoveAt(this.data[y].Count - 1);
}
}
}
}
}
Danke.