Ejemplo n.º 1
0
 public void Iterate()
 {
     lock (this.matrix){
         this.matrix.Iterate();
         lock (this.ready){
             this.ready = (ConwayMatrix)this.matrix.Clone();
         }
     }
 }
Ejemplo n.º 2
0
        public void LoadFile(string file)
        {
            ConwayMatrix matrix = null;

            try{
                matrix = new File.Rle(file).ConwayMatrix;
            }catch (Exception) {
                try{
                    matrix = new File.Vaca(file).ConwayMatrix;
                }catch (Exception) {
                }
            };
            this.matrix = matrix;
            this.ready  = (ConwayMatrix)this.matrix.Clone();
        }
Ejemplo n.º 3
0
        public void TestMatrix()
        {
            string test1  = @"....
....
....
....
";
            string test2  = @".....
.....
.....
.....
....X
";
            string test3  = @"X.....
......
......
......
......
.....X
";
            string test4  = @"X......
.......
.......
.......
......X
.....X.
";
            string test5  = @"X......
.......
.......
.......
......X
.....X.
....X..
";
            var    matrix = new ConwayMatrix();

            matrix.SetSize(4, 4);
            Assert.Equal(test1, matrix.ToString());
            matrix[4, 4] = true;
            Assert.Equal(test2, matrix.ToString());
            matrix[-1, -1] = true;
            Assert.Equal(test3, matrix.GetFinalResult().LimitedMatrix.ToString());
            matrix[4, 6] = true;
            Assert.Equal(test4, matrix.GetFinalResult().LimitedMatrix.ToString());
            matrix[6, 4] = true;
            Assert.Equal(test5, matrix.GetFinalResult().LimitedMatrix.ToString());
        }
Ejemplo n.º 4
0
        public void Load(string path)
        {
            ConwayMatrix = new ConwayMatrix();
            var lines  = System.IO.File.ReadAllLines(path);
            var column = Int32.Parse(lines[1].Trim());

            for (var i = 2; i < lines.Length; i++)
            {
                var line  = lines[i];
                var array = line.ToCharArray();
                for (var j = 0; j < array.Length; j++)
                {
                    ConwayMatrix[i - 2, j] = (array[j] == 'X');
                }
            }
        }
Ejemplo n.º 5
0
        public void BoolMatrixToConwayMatrix()
        {
            string test   = @"...X
.X.X
....
....
";
            var    matrix = new bool[][] {
                new bool[] { false, false, false, true },
                new bool[] { false, true, false, true },
                new bool[] { false, false, false, false },
                new bool[] { false, false, false, false }
            };
            var conway = new ConwayMatrix(matrix);

            Assert.Equal(test, conway.ToString());
        }
        public void GetCellsBehavior_WithinputElement_ReturnsLiveCell()
        {
            Mock <ConwayMatrixService> mockService = new Mock <ConwayMatrixService>();
            int numberOfLiveCells = 2;
            int matrixElement     = 1;

            int[,] matrix = new int[, ]
            {
                { 1, 0, 0, 0 },
                { 0, 0, 1, 0 },
                { 1, 1, 1, 0 },
                { 0, 1, 0, 0 },
            };
            mockService.Setup(x => x.GetCellsBehaviour(matrixElement, numberOfLiveCells)).Returns(1);
            _conwayMatrix = new ConwayMatrix(mockService.Object);
            _conwayMatrix.ActiveMatrix(matrix);
            Assert.IsNotNull(_conwayMatrix);
        }
        public void GetLiveCells_WithinputMatrix_ReturnsNotNull()
        {
            Mock <ConwayMatrixService> mockService = new Mock <ConwayMatrixService>();
            int matrixRow = 2;
            int matrixCol = 1;

            int[,] matrix = new int[, ]
            {
                { 1, 0, 0, 0 },
                { 0, 0, 1, 0 },
                { 1, 1, 1, 0 },
                { 0, 1, 0, 0 },
            };
            mockService.Setup(x => x.GetLiveCells(matrixRow, matrixCol, matrix)).Returns(1);
            _conwayMatrix = new ConwayMatrix(mockService.Object);
            _conwayMatrix.ActiveMatrix(matrix);
            Assert.IsNotNull(_conwayMatrix);
        }
        static void Main(string[] args)
        {
            bool endgame   = false;
            var  container = new UnityContainer();

            int[,] matrix = new int[, ]
            {
                { 1, 0, 0, 0 },
                { 0, 0, 1, 0 },
                { 1, 1, 1, 0 },
                { 0, 1, 0, 0 },
            };
            ConwayMatrix conwayMatrix = new ConwayMatrix(new ConwayMatrixService());

            while (endgame == false)
            {
                Console.WriteLine();
                conwayMatrix.ActiveMatrix(matrix);
            }
        }
Ejemplo n.º 9
0
 public void New()
 {
     this.matrix = new ConwayMatrix();
     this.ready  = new ConwayMatrix();
 }
Ejemplo n.º 10
0
        public void Load(string path)
        {
            string patterName = string.Empty;
            string author     = string.Empty;
            int    x          = 0;
            int    y          = 0;
            // TODO: falta rule name
            Regex regex = new Regex(@"^x = ([0-9]*), y = ([0-9]*)", RegexOptions.IgnoreCase);

            string[] lines = System.IO.File.ReadAllLines(path);
            string   rule  = string.Empty;

            foreach (string line in lines)
            {
                if (line.StartsWith("#"))
                {
                    char c = line.ToCharArray()[1];
                    switch (c)
                    {
                    case 'C':        // comentarios
                    case 'c': break; // comentarios

                    case 'N': patterName = line.Substring(2); break;

                    case 'O': author = line.Substring(2); break;

                    case 'P':        // sin implementar
                    case 'R':        // sin implementar
                    case 'r': break; // sin implementar
                    }
                }
                else if (regex.IsMatch(line))
                {
                    var matches = regex.Matches(line);
                    var g       = matches[0].Groups;
                    try{
                        x = Int32.Parse(g[1].Value);
                        y = Int32.Parse(g[2].Value);
                    }catch (Exception ex) when(ex is FormatException || ex is OverflowException)
                    {
                        x = -1;
                        y = -1;
                        throw new Exception("Error while reading RLE headers");
                    }
                }
                else
                {
                    rule += line;
                }
            }

            // comprobar si la cabecera ha sido leída correctamente
            if (x < 1 || y < 1)
            {
                throw new Exception("Corrupt file");
            }

            ConwayMatrix = new ConwayMatrix();
            ConwayMatrix.SetSize(y, x);

            // lee y almacena en un ConwayMatrix los datos codificados en RLE
            string[] ruleLines = rule.Split('$');    // cada línea en la matriz se separa por $
            var      r = new Regex(@"([0-9]*)[bo]"); // contar cuantos grupos hay en cada match
            var      end = new Regex(@"([0-9]*)$");  // comprobar saltos de linea
            int      a = 0, b = 0;

            // por cada línea aplicamos un regex de vivas/muertas y su números. Se procesan en orden
            // al final se añaden celdas muertas hasta acabar la longitud de la matriz
            foreach (var line in ruleLines)
            {
                foreach (Match m in r.Matches(line))
                {
                    bool alive;
                    int  c = 1;

                    if (String.IsNullOrWhiteSpace(m.Groups[1].Value))
                    {
                        switch (m.Groups[0].Value)
                        {
                        case "o": alive = true; break;

                        case "b": alive = false; break;

                        default: throw new Exception("Corrupt file. Illegal character found");
                        }
                    }
                    else
                    {
                        var array = m.Groups[0].Value.ToCharArray();
                        c = Int32.Parse(m.Groups[1].Value);
                        char cell = array[array.Length - 1];
                        switch (cell)
                        {
                        case 'o': alive = true; break;

                        case 'b': alive = false; break;

                        default: throw new Exception("Corrupt file. Illegal character found");
                        }
                    }

                    for (int i = 0; i < c; i++)
                    {
                        ConwayMatrix[b, a] = alive;
                        a++;
                    }
                }

                while (a < x)
                {
                    ConwayMatrix[b, a] = false;
                    a++;
                }
                b++;
                a = 0;
                try{
                    Match m  = end.Matches(line)[0];
                    int   ln = Int32.Parse(m.Groups[1].Value) - 1;
                    for (var i = 0; i < ln; i++)
                    {
                        while (a < x)
                        {
                            ConwayMatrix[b, a] = false;
                            a++;
                        }
                        b++;
                        a = 0;
                    }
                }catch (Exception) {
                }
            }
        }
Ejemplo n.º 11
0
 // constructor cargando un archivo existente
 public Rle(string file)
 {
     ConwayMatrix = new ConwayMatrix();
     Load(file);
 }
Ejemplo n.º 12
0
 // constructor sin carga
 public Rle()
 {
     ConwayMatrix = new ConwayMatrix();
 }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine("Conway - Game of Life");
            var app = new CommandLineApplication();


            app.Name = "Conway";
            app.HelpOption("-?|-h|--help");
            app.VersionOption("-v|--version", "Conway 1.0.0");


            var inputFile  = app.Option("-i <inputfile>|--input <inputfile>", "Input file", CommandOptionType.SingleValue);
            var iterations = app.Option("-n <n>|--iter <n>", "Number of iterations", CommandOptionType.SingleValue);

            app.OnExecute(() => {
                // procesar entrada de comandos
                try{
                    // algoritmo de Quadtree
                    if (!inputFile.HasValue())
                    {
                        throw new Exception("Please, specify an input file");
                    }
                    if (!System.IO.File.Exists(inputFile.Value()))
                    {
                        throw new Exception("Please, check that the specified file exists");
                    }
                    if (!iterations.HasValue())
                    {
                        throw new Exception("Please, specify a number of iterations");
                    }
                    var iter = Int32.Parse(iterations.Value());

                    // TODO: ser capaz de detectar el formato correcto

                    bool[][] matrix = null;
                    try{
                        matrix = new File.Rle(inputFile.Value()).GetMatrix();
                    }catch (Exception) {
                        matrix = new File.Vaca(inputFile.Value()).GetMatrix();
                    };
                    if (matrix == null)
                    {
                        throw new Exception("File format error");
                    }
                    Cuadrante cuadrante = Cuadrante.crear(matrix);
                    Console.WriteLine($"{cuadrante}");
                    var sw = Stopwatch.StartNew();
                    for (var i = 0; i < iter; i++)
                    {
                        while (!(cuadrante.isCentrado() && cuadrante.getCuadranteCentral().isCentrado()))
                        {
                            cuadrante = cuadrante.expandir();
                        }
                        cuadrante = cuadrante.generacionEtapa4();
                    }
                    sw.Stop();

                    var conway = new ConwayMatrix(cuadrante.GetMatrix());
                    var final  = conway.GetFinalResult();
                    // report final
                    Console.WriteLine($"{iter} iteraciones");
                    Console.WriteLine($"{final.CeldasVivas} celdas vivas");
                    Console.WriteLine($"Dimensiones: {final.LimitedMatrix.Width} x {final.LimitedMatrix.Height}");
                    Console.WriteLine($"Tiempo: {sw.Elapsed.TotalMilliseconds} ms");

                    // guardar
                    Console.Write("Fichero de salida: ");
                    var filename = Console.ReadLine().Trim();
                    if (filename == string.Empty)
                    {
                        Console.WriteLine(final.LimitedMatrix);
                    }
                    else
                    {
                        var file          = new File.Vaca();
                        file.ConwayMatrix = final.LimitedMatrix;
                        file.Save(filename);
                        Console.WriteLine($"Matriz final guardada en {filename}");
                    }
                }catch (Exception e) {
                    Console.WriteLine($"WARNING: {e.Message}");
                    Console.WriteLine("Starting UI");

                    // arrancar gui (algoritmo de ConwayMatrix)
                    AppBuilder.Configure <App>().UseSkia().UseX11().Start <GUI.MainWindow>();
                }
                return(0);
            });

            app.Execute(args);
        }