Неправильная обработка выхода за пределы массива. Муравей Лэнгтона

Хочу сделать, чтобы муравей при выходе за пределы игрового поля, выходил с другой стороны.

Таймер

private void timer1_Tick(object sender, EventArgs e)
        {
            foreach (Ant ant in Ants)
            {
                ant.NewPos();
                ant.NextStep();
            }
            GameDraw();            
        }

класс муравья

public class Ant
    {
        private Vector AntPos;
        private Vector OldAntPos;

        private static int rows;
        private static int cols;

        private static bool[,] oldFild;

        private Vector[] queue = new Vector[4];
        private Vector Right = new Vector(1, 0);
        private Vector Up = new Vector(0, 1);
        private Vector Left = new Vector(-1, 0);
        private Vector Down = new Vector(0, -1);
        private Vector Increment;
        private int i; //first increment from -1 to 3     

        Random random = new Random();

        public Ant(int rows, int cols)
        {
            AntPos = new Vector(cols / 2, rows / 2);
            OldAntPos = new Vector(cols / 2, rows / 2);

            Ant.rows = rows;
            Ant.cols = cols;

            oldFild = new bool [cols,rows];

            queue[0] = Right;
            queue[1] = Up;
            queue[2] = Left;
            queue[3] = Down;

            i = random.Next(0, 4) - 1;        
        }

        public Vector NewPos()

        {
            while (i <= 3)
            {
                if (!oldFild[AntPos.X, AntPos.Y])
                {
                    i++;
                    if (i > 3) { i = 0; }

                    Increment = new Vector(queue[i].X, queue[i].Y);

                    return Increment;
                }
                if (oldFild[AntPos.X, AntPos.Y])
                {
                    i--;
                    if (i == -1) { i = 3; }

                    Increment = new Vector(queue[i].X, queue[i].Y);

                    if (i > 3) { i = 0; }

                    return Increment;
                }
            }
            return Increment;
        }

        public void NextStep()
        {
            AntPos = AntPos + Increment;
            AntPos = new Vector(Math.Abs(AntPos.X) % cols, Math.Abs(AntPos.Y) % rows);
            oldFild[OldAntPos.X, OldAntPos.Y] = !oldFild[OldAntPos.X, OldAntPos.Y];
            OldAntPos = AntPos;
        }

        public static bool[,] GetFildCopy()
        {
            var CopyFild = new bool[cols, rows];

            for (int x = 0; x < cols; x++)
            {
                for(int y = 0; y < rows; y++)
                {
                    CopyFild[x, y] = oldFild[x, y];
                }
            }
            return CopyFild;
        }

        public static int GetCols()
        {
            var cols = Ant.cols;
            return cols;
        }

        public static int GetRows()
        {
            var rows = Ant.rows;
            return rows;
        }

        public Vector GetAntPos()
        {
            var AntPos = this.AntPos;

            return AntPos;
        }
    }

Функция рисования

private void GameDraw()
        {

            graphics.Clear(Color.Black);

            var Fild = Ant.GetFildCopy();

            for (int x = 0; x < Ant.GetCols(); x++)
            {
                for (int y = 0; y < Ant.GetRows(); y++)
                {
                    if (Fild[x, y])
                    {
                        graphics.FillRectangle(Brushes.Goldenrod, x * Resolution, y * Resolution, Resolution - 1, Resolution - 1);
                    }
                }
            }
            pictureBox1.Refresh();
        }

Пытался брать остаток от деления координат муравья по модулю на длину и ширину поля.

AntPos = new Vector(Math.Abs(AntPos.X) % cols, Math.Abs(AntPos.Y) % rows);

Но увы, работает это некорректно, муравей появляется с другой стороны, но не рисует магистраль.

вот так это выглядит Прошу прощение за не самый хороший код, я только изучаю C#.


Ответы (1 шт):

Автор решения: aepot

К примеру у вас массив и есть индекс, который допустим в диапазоне от 0 до 99. Тогда, чтобы добиться цикличности можно применить вот такой код.

int array = new int[100];
int position = 100; // -1
int index = (position + array.Length) % array.Length;

Тогда 100 превратится в 0 (100 + 100 = 200 % 100 = 0), а -1 в 99 (-1 + 100 = 99 % 100 = 99). Выхода за пределы не будет.

→ Ссылка