コード例 #1
0
ファイル: Game1.cs プロジェクト: perkky/SlidingPuzzleGui
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            base.Initialize();

            aniTime = ANIMATION_TIME;

            //Preforms the Puzzle initialisation
            SlidingPuzzle puzzle = new SlidingPuzzle();

            //puzzle.SetState("{1,2,3,4,8,6,7,5,0}");
            puzzle.ShuffleBoard();
            var path = A_StarSearch <string, SlidingPuzzleAction> .Search(
                puzzle,
                "{1,2,3,4,5,6,7,8,0}");

            System.Console.WriteLine("Num steps = " + path.Count);

            //adds the steps to the board object
            board = new GUISrc.Board(this, ConvertToIntArray(path.Pop()), BOARD_SIZE);
            while (path.Count > 0)
            {
                board.AddState(ConvertToIntArray(path.Pop()));
            }
        }
コード例 #2
0
        // Devuelve la posición que se ve afectada por este operador (la que se movería si lo aplicásemos)
        public Position GetOperatedPosition(SlidingPuzzle puzzle, Operator op)
        {
            if (puzzle == null)
            {
                throw new ArgumentException("Argument is not valid", "puzzle");
            }

            if (SlidingPuzzleSolver.UP.Equals(op))
            {
                return(puzzle.GapPosition.Up());
            }
            if (SlidingPuzzleSolver.DOWN.Equals(op))
            {
                return(puzzle.GapPosition.Down());
            }
            if (SlidingPuzzleSolver.LEFT.Equals(op))
            {
                return(puzzle.GapPosition.Left());
            }
            if (SlidingPuzzleSolver.RIGHT.Equals(op))
            {
                return(puzzle.GapPosition.Right());
            }

            // Si el operador es nulo, no se entiende o directamente es NoOp respondemos con una excepción
            throw new ArgumentException("Argument is not a valid operator", "op");
        }
コード例 #3
0
ファイル: SlidingPuzzleEditor.cs プロジェクト: nanalucky/AP
//--> Move tile in scene view
    private void MoveTileInSceneView(int oldPosition, string direction, SlidingPuzzle myScript)
    {
        if (oldPosition != -1)
        {
            // Debug.Log("oldPosition : " + oldPosition);
            SerializedObject serializedObject2 = new UnityEditor.SerializedObject(myScript.tilesList[myScript.positionList[oldPosition]].GetComponent <Transform>());
            serializedObject2.Update();
            SerializedProperty m_Position = serializedObject2.FindProperty("m_LocalPosition");

            if (direction == "Down")
            {
                m_Position.vector3Value = new Vector3(m_Position.vector3Value.x, m_Position.vector3Value.y - .25f, 0);
            }
            if (direction == "Up")
            {
                m_Position.vector3Value = new Vector3(m_Position.vector3Value.x, m_Position.vector3Value.y + .25f, 0);
            }
            if (direction == "Left")
            {
                m_Position.vector3Value = new Vector3(m_Position.vector3Value.x - .25f, m_Position.vector3Value.y, 0);
            }
            if (direction == "Right")
            {
                m_Position.vector3Value = new Vector3(m_Position.vector3Value.x + .25f, m_Position.vector3Value.y, 0);
            }

            serializedObject2.ApplyModifiedProperties();
        }
    }
コード例 #4
0
    void Awake()
    {
        player         = GameObject.FindGameObjectWithTag("Player");
        slidingPuzzle  = GameObject.FindObjectOfType <SlidingPuzzle>();
        switchesPuzzle = GameObject.FindObjectOfType <SwitchPuzzle>();
        colorPuzzle    = GameObject.FindGameObjectWithTag("ColorPuzzle");

        treeCollider = GameObject.FindGameObjectWithTag("Tree").GetComponent <Collider>();

        if (slidingPuzzle && switchesPuzzle && colorPuzzle)
        {
            Destroy(treeCollider);
        }

        if (colorPuzzle)
        {
            player.transform.position = new Vector3(70, 9, 86);
            player.transform.Rotate(0, 20f, 0);
        }
        else if (switchesPuzzle.solved())
        {
            player.transform.position = new Vector3(11, 9, 86);
        }
        else if (slidingPuzzle.solved())
        {
            player.transform.position = new Vector3(-48, 9, 86);
            player.transform.Rotate(0, -37f, 0);
        }
    }
コード例 #5
0
        public void TestSwapTile()
        {
            SlidingPuzzle puzzle = new SlidingPuzzle();

            int[] expected1 = { 1, 0, 2, 3, 4, 5, 6, 7, 8 };
            int[] expected2 = { 1, 4, 2, 3, 0, 5, 6, 7, 8 };
            int[] expected3 = { 1, 4, 2, 0, 3, 5, 6, 7, 8 };
            int[] expected4 = { 1, 4, 2, 6, 3, 5, 0, 7, 8 };
            int[] expected5 = { 1, 4, 2, 6, 3, 5, 7, 0, 8 };
            int[] expected6 = { 1, 4, 2, 6, 3, 5, 7, 8, 0 };
            int[] expected7 = { 1, 4, 2, 6, 3, 0, 7, 8, 5 };

            System.Console.WriteLine("Testing sequential swapping of tiles...");
            puzzle.SwapTile(0, 1);
            Assert.True(Enumerable.SequenceEqual(puzzle.Board, expected1));
            System.Console.WriteLine("\tSwapped 0,1");
            puzzle.SwapTile(1, 4);
            Assert.True(Enumerable.SequenceEqual(puzzle.Board, expected2));
            System.Console.WriteLine("\tSwapped 1,4");
            puzzle.SwapTile(4, 3);
            Assert.True(Enumerable.SequenceEqual(puzzle.Board, expected3));
            System.Console.WriteLine("\tSwapped 4,3");
            puzzle.SwapTile(3, 6);
            Assert.True(Enumerable.SequenceEqual(puzzle.Board, expected4));
            System.Console.WriteLine("\tSwapped 3,6");
            puzzle.SwapTile(6, 7);
            Assert.True(Enumerable.SequenceEqual(puzzle.Board, expected5));
            System.Console.WriteLine("\tSwapped 6,7");
            puzzle.SwapTile(7, 8);
            Assert.True(Enumerable.SequenceEqual(puzzle.Board, expected6));
            System.Console.WriteLine("\tSwapped 7,8");
            puzzle.SwapTile(8, 5);
            Assert.True(Enumerable.SequenceEqual(puzzle.Board, expected7));
            System.Console.WriteLine("\tSwapped 8,5");
        }
コード例 #6
0
        public void TestTransitionState()
        {
            int[]         board     = { 1, 2, 3, 4, 0, 5, 6, 7, 8 };
            SlidingPuzzle puzzle    = new SlidingPuzzle(board);
            Queue <int[]> expectedQ = new Queue <int[]>();

            SlidingPuzzleAction[] actions = new SlidingPuzzleAction[4];
            actions[0] = new SlidingPuzzleAction(4, 4 - 1);
            actions[1] = new SlidingPuzzleAction(4, 4 + 1);
            actions[2] = new SlidingPuzzleAction(4, 4 - 3);
            actions[3] = new SlidingPuzzleAction(4, 4 + 3);
            expectedQ.Enqueue(new int[] { 1, 2, 3, 0, 4, 5, 6, 7, 8 });
            expectedQ.Enqueue(new int[] { 1, 2, 3, 4, 5, 0, 6, 7, 8 });
            expectedQ.Enqueue(new int[] { 1, 0, 3, 4, 2, 5, 6, 7, 8 });
            expectedQ.Enqueue(new int[] { 1, 2, 3, 4, 7, 5, 6, 0, 8 });


            for (int i = 0; i < 4; i++)
            {
                System.Console.WriteLine("Testing TransitionState(" +
                                         string.Format("SlidingPuzzleAction {0}",
                                                       actions[i].ToString()));
                string actual   = puzzle.TransitionState(actions[i]);
                string expected = "{" + string.Join(",",
                                                    expectedQ.Dequeue()) + "}";

                Assert.Equal(actual, expected);
            }
        }
コード例 #7
0
ファイル: SlidingPuzzleEditor.cs プロジェクト: nanalucky/AP
//--> Reset Tile Mixing
    private void ResetPosition(SlidingPuzzle myScript)
    {
        Undo.RegisterFullObjectHierarchyUndo(myScript, myScript.name);
        myScript.currentSelectedSprite = -2;
        for (var i = 0; i < myScript.positionList.Count; i++)
        {
            myScript.positionList[i] = i;
        }
        myScript.positionList[myScript.positionList.Count - 1] = -1;
        myScript.currentSelectedSprite = 0;

        int number = 0;

        for (var i = 0; i < _Raw.intValue; i++)
        {
            for (var j = 0; j < _Column.intValue; j++)
            {
                if (i == _Raw.intValue - 1 && j == _Column.intValue - 1)
                {
                }
                else
                {
                    myScript.tilesList[number].transform.localPosition = new Vector3(.25f * j, -.25f * i, 0);
                }

                number++;
            }
        }
    }
コード例 #8
0
            // Devuelve los operadores aplicables a una determinada configuración del problema
            // Se devuelve HashSet porque es un conjunto sin orden, aunque también se podría haber decidido devolver una lista
            public HashSet <Operator> GetApplicableOperators(object setup)
            {
                if (setup == null || !(setup is SlidingPuzzle))
                {
                    throw new ArgumentException("Setup is not a valid SlidingPuzzle");
                }

                // Lo que recibe es un SlidingPuzzle
                SlidingPuzzle puzzle = (SlidingPuzzle)setup;

                HashSet <Operator> operators = new HashSet <Operator>();

                if (puzzle.CanMoveUp(puzzle.GapPosition))
                {
                    operators.Add(SlidingPuzzleSolver.UP);
                }
                if (puzzle.CanMoveDown(puzzle.GapPosition))
                {
                    operators.Add(SlidingPuzzleSolver.DOWN);
                }
                if (puzzle.CanMoveLeft(puzzle.GapPosition))
                {
                    operators.Add(SlidingPuzzleSolver.LEFT);
                }
                if (puzzle.CanMoveRight(puzzle.GapPosition))
                {
                    operators.Add(SlidingPuzzleSolver.RIGHT);
                }

                return(operators);
            }
コード例 #9
0
            // SUSTITUÍ EL LINKEDHASHSET DE JAVA POR HASHSET SOLAMENTE... SE ME HACE RARO QUE SE DEVUELVA UN HASHSET, LO NORMAL SERÍA UNA LIST, Y POR DENTRO IMPLEMENTAR CON ARRAYLIST O ALGO
            public HashSet <Operator> Operators(object setup)
            {
                // Lo que entra es un problema, un SlidingPuzzle
                SlidingPuzzle puzzle = (SlidingPuzzle)setup;

                HashSet <Operator> operators = new HashSet <Operator>();

                // Esto se lee: Puedo mover el hueco hacia arriba, o puedo mover la pieza de arriba del hueco
                if (puzzle.CanMoveUp(puzzle.GapPosition))
                {
                    operators.Add(SlidingPuzzleSolver.UP);
                }
                if (puzzle.CanMoveDown(puzzle.GapPosition))
                {
                    operators.Add(SlidingPuzzleSolver.DOWN);
                }
                if (puzzle.CanMoveLeft(puzzle.GapPosition))
                {
                    operators.Add(SlidingPuzzleSolver.LEFT);
                }
                if (puzzle.CanMoveRight(puzzle.GapPosition))
                {
                    operators.Add(SlidingPuzzleSolver.RIGHT);
                }

                return(operators);
            }
コード例 #10
0
        // Resuelve el puzle, en su configuración actual, utilizando la estrategia introducida como parámetro
        public List <Operator> Solve(SlidingPuzzle initialSetup, SlidingPuzzleSolver.Strategy strategy)
        {
            // Construimos el problema a partir del puzle que nos llega, que actúa como configuración inicial
            // No se indica función de coste de paso, con lo que se utilizará la que viene por defecto
            Problem problem = new Problem(initialSetup, aoFunction, tModel, gTest);

            // Se crea la búsqueda según la estrategia escogida
            Search search = null;

            switch (strategy)
            {
            case Strategy.BFS: search = new BreadthFirstSearch(); break;                // Por defecto se usa un GraphSearch

            case Strategy.DFS: search = new DepthFirstSearch(new GraphSearch()); break; // Por defecto se usa un GraphSearch
                // ... hay cabida para otras estrategias
            }

            // Se realiza la búsqueda sobre el problema
            List <Operator> operators = search.Search(problem);

            // Al terminar, se guardan las métricas resultantes
            metrics = search.GetMetrics();

            return(operators);
        }
コード例 #11
0
ファイル: SlidingPuzzleSolver.cs プロジェクト: gonzsa04/IA
        /*
         * // Para copiar el puzle con el que este trabajando otro resolutor... raro
         * public SlidingPuzzleSolver(SlidingPuzzleSolver copyBoard) : this(copyBoard.getPuzle()) {
         *
         * }
         */


        // A ver si esto tiene que estar aquí o puede ser otra cosa (en el propio SlidingPuzzleManager)
        public List <Operator> Solve(SlidingPuzzle setup, SlidingPuzzleSolver.Strategy strategy)
        {
            // Construimos el problema a partir del puzle.
            //Pieza a pieza (el puzle tal cual será el initialSetup -lo mismo debería sacar el array-)



            //Aquí construimos el problema en base al puzle actual (la CONFIGURACIÓN del puzle actual), que no me gusta como es porque es el puzle con unas pocas cosas por encima!!! El dominio de problema no es un objeto
            Problem problem = new Problem(setup, oFunction, rFunction, goalTest); //Me molaría más que el problema no sea el solver, sino el puzle... pero bueno, quizá sea PROBLEM lo que debería llamarse el solver
            //public Problem(Object initialSetup, OperatorsFunction operatorsFunction, ResultFunction resultFunction, GoalTest goalTest)

            // AQUÍ CREARÍAMOS LA ESTRATEGIA, EL TIPO DE BÚSQUEDA, pidiéndole que use búsqueda de coste uniforme por ejemplo. Y lo llamamos

            Search search = null;

            switch (strategy)
            {
            case Strategy.BFS: search = new BreadthFirstSearch(); break;                //por defecto te crea un GraphSearch, no hay que meterle nada

            case Strategy.DFS: search = new DepthFirstSearch(new GraphSearch()); break; // NO ENTIENDO PORQUE ESTE CONSTRUCTOR NO TE HACE NADA POR DEFECTO, Y SOY YO QUE LE ESTOY METIENDO UN GRAPHSEARCH
                // ...
            }
            List <Operator> operators = search.Search(problem);

            metrics = search.GetMetrics();

            return(operators); // Deberíamos devolver también las métricas, seguramente
        }
コード例 #12
0
            public object GetResult(object setup, Operator op)
            {
                // Lo recibido es un puzle deslizante
                SlidingPuzzle puzzle = (SlidingPuzzle)setup;
                // Un puzle deslizante se puede clonar a nivel profundo
                SlidingPuzzle puzzleClone = puzzle.DeepClone();


                if (SlidingPuzzleSolver.UP.Equals(op))
                {
                    if (puzzleClone.CanMoveUp(puzzleClone.GapPosition))
                    {
                        puzzleClone.MoveUp(puzzleClone.GapPosition);
                    }
                    else // No puede ocurrir que el operador aplicable no funcione, porque ya se comprobó que era aplicable
                    {
                        throw new InvalidOperationException("This operator is not working propertly");
                    }
                }

                if (SlidingPuzzleSolver.DOWN.Equals(op))
                {
                    if (puzzleClone.CanMoveDown(puzzleClone.GapPosition))
                    {
                        puzzleClone.MoveDown(puzzleClone.GapPosition);
                    }
                    else // No puede ocurrir que el operador aplicable no funcione, porque ya se comprobó que era aplicable
                    {
                        throw new InvalidOperationException("This operator is not working propertly");
                    }
                }

                if (SlidingPuzzleSolver.LEFT.Equals(op))
                {
                    if (puzzleClone.CanMoveLeft(puzzleClone.GapPosition))
                    {
                        puzzleClone.MoveLeft(puzzleClone.GapPosition);
                    }
                    else // No puede ocurrir que el operador aplicable no funcione, porque ya se comprobó que era aplicable
                    {
                        throw new InvalidOperationException("This operator is not working propertly");
                    }
                }

                if (SlidingPuzzleSolver.RIGHT.Equals(op))
                {
                    if (puzzleClone.CanMoveRight(puzzleClone.GapPosition))
                    {
                        puzzleClone.MoveRight(puzzleClone.GapPosition);
                    }
                    else // No puede ocurrir que el operador aplicable no funcione, porque ya se comprobó que era aplicable
                    {
                        throw new InvalidOperationException("This operator is not working propertly");
                    }
                }

                // Si el operador no se reconoce o es un NoOp, se devolverá la configuración actual (que sería idéntica a la original, no ha habido cambios)
                return(puzzleClone);
            }
コード例 #13
0
        public void TestGetState(int[] board)
        {
            SlidingPuzzle puzzle = new SlidingPuzzle(board);
            string        str    = "{" + string.Join(",", board) + "}";

            System.Console.WriteLine("Testing GetState() - Expect{0}", str);
            Assert.Equal(str, puzzle.GetState());
        }
コード例 #14
0
        public void TestConstructo2(int[] board)
        {
            SlidingPuzzle puzzle = new SlidingPuzzle(board);
            string        str    = "{" + string.Join(",", board) + "}";

            System.Console.WriteLine("Testing SlidingPuzzle(int[] {0})", str);
            Assert.True(Enumerable.SequenceEqual(puzzle.Board, board));
        }
コード例 #15
0
        public void TestConstructor1(int size)
        {
            SlidingPuzzle puzzle;

            System.Console.WriteLine("Testing SlidingPuzzle(int {0})", size);
            puzzle = new SlidingPuzzle(size);
            Assert.Equal(puzzle.GetSize(), size);
        }
コード例 #16
0
ファイル: SlidingPuzzleEditor.cs プロジェクト: nanalucky/AP
//--> Random Mixing method
    private void RandomMix(SlidingPuzzle myScript)
    {
        for (var i = 0; i < randomNumber.intValue; i++)
        {
            int value = UnityEngine.Random.Range(0, tilesList.arraySize + 1);
            MoveTile(myScript, value, false);
        }
        InitMixPosition(myScript);
    }
コード例 #17
0
        public void TestSetState(string state)
        {
            SlidingPuzzle puzzle = new SlidingPuzzle();

            puzzle.SetState(state);
            string board = "{" + string.Join(",", puzzle.Board) + "}";

            System.Console.WriteLine("Testing SetState({0})", state);
            Assert.Equal(board, state);
        }
コード例 #18
0
        public void TestEquals()
        {
            var puzzle =
                new SlidingPuzzle(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });

            System.Console.WriteLine("Testing Equals method");

            Assert.True(puzzle.Equals("{0,1,2,3,4,5,6,7,8}"));
            Assert.False(puzzle.Equals("{1,2,3,4,0,5,6,7,8}"));
            // Private
        }
コード例 #19
0
ファイル: SlidingPuzzleEditor.cs プロジェクト: nanalucky/AP
//--> Init tile position when tab is clicked
    private void InitSelectSpritesPosition(SlidingPuzzle myScript)
    {
        Undo.RegisterFullObjectHierarchyUndo(myScript, myScript.name);
        for (var i = 0; i < myScript.tilesList.Count; i++)
        {
            int numRaw    = i / _Column.intValue;
            int numColumn = i % _Column.intValue;

            myScript.tilesList[i].transform.localPosition = new Vector3(.25f * numColumn, -.25f * numRaw, 0);
        }
    }
コード例 #20
0
ファイル: SlidingPuzzleEditor.cs プロジェクト: nanalucky/AP
    void OnEnable()
    {
        // Setup the SerializedProperties.
        SeeInspector  = serializedObject.FindProperty("SeeInspector");
        helpBoxEditor = serializedObject.FindProperty("helpBoxEditor");

        SlidingPuzzle myScript = (SlidingPuzzle)target;

        _Raw                = serializedObject.FindProperty("_Raw");
        _Column             = serializedObject.FindProperty("_Column");
        toolbarCurrentValue = serializedObject.FindProperty("toolbarCurrentValue");
        SquareSize          = serializedObject.FindProperty("SquareSize");

        tilesList = serializedObject.FindProperty("tilesList");

        currentSelectedSprite = serializedObject.FindProperty("currentSelectedSprite");
        positionList          = serializedObject.FindProperty("positionList");
        randomNumber          = serializedObject.FindProperty("randomNumber");


        validationButtonJoystick = serializedObject.FindProperty("validationButtonJoystick");

        a_TileMove       = serializedObject.FindProperty("a_TileMove");
        a_TileMoveVolume = serializedObject.FindProperty("a_TileMoveVolume");
        a_Reset          = serializedObject.FindProperty("a_Reset");
        a_ResetVolume    = serializedObject.FindProperty("a_ResetVolume");


        popUpObject = serializedObject.FindProperty("popUpObject");
        popupSpeed  = serializedObject.FindProperty("popupSpeed");

        feedbackIDList      = serializedObject.FindProperty("feedbackIDList");
        b_feedbackActivated = serializedObject.FindProperty("b_feedbackActivated");



        GameObject tmp = GameObject.Find("InputsManager");

        if (tmp)
        {
            for (var i = 0; i < tmp.GetComponent <MM_MenuInputs>().remapButtons[1].buttonsList.Count; i++)
            {
                s_inputListJoystickButton.Add(tmp.GetComponent <MM_MenuInputs>().remapButtons[1].buttonsList[i].name);
            }
        }


        Tex_01 = MakeTex(2, 2, new Color(1, .5f, 0.3F, .4f));
        Tex_02 = MakeTex(2, 2, new Color(1, .5f, 0.3F, .4f));
        Tex_03 = MakeTex(2, 2, new Color(1, .5f, 0.3F, .4f));
        Tex_04 = MakeTex(2, 2, new Color(1, .5f, 0.3F, .4f));
        Tex_05 = MakeTex(2, 2, new Color(1, .5f, 0.3F, .4f));
    }
コード例 #21
0
ファイル: SlidingPuzzleGoalTest.cs プロジェクト: gonzsa04/IA
        // Devuelve cierto o falso según la configuración que nos pasan sea o no objetivo
        public bool IsGoal(object setup)
        {
            if (setup == null || !(setup is SlidingPuzzle))
            {
                return(false);
            }

            SlidingPuzzle puzzle = (SlidingPuzzle)setup;

            // Si no tienen las mismas dimensiones, el equals va a fallar
            return(puzzle.Equals(goal));
        }
コード例 #22
0
ファイル: SlidingPuzzleEditor.cs プロジェクト: nanalucky/AP
//--> Section Other Options
    private void otherSection(SlidingPuzzle myScript, GUIStyle style_Orange)
    {
        EditorGUILayout.BeginVertical(style_Orange);

        EditorGUILayout.HelpBox("Section : Other Options.", MessageType.Info);

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Validation Button Joystick : ", GUILayout.Width(150));
        validationButtonJoystick.intValue = EditorGUILayout.Popup(validationButtonJoystick.intValue, s_inputListJoystickButton.ToArray());
        EditorGUILayout.EndHorizontal();
        GUILayout.Label("");


        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Play Audio when tile move : ", GUILayout.Width(180));
        EditorGUILayout.PropertyField(a_TileMove, new GUIContent(""), GUILayout.Width(100));
        GUILayout.Label("Volume : ", GUILayout.Width(60));
        a_TileMoveVolume.floatValue = EditorGUILayout.Slider(a_TileMoveVolume.floatValue, 0, 1);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Play Audio when puzzle is Reset : ", GUILayout.Width(180));
        EditorGUILayout.PropertyField(a_Reset, new GUIContent(""), GUILayout.Width(100));
        GUILayout.Label("Volume : ", GUILayout.Width(60));
        a_ResetVolume.floatValue = EditorGUILayout.Slider(a_ResetVolume.floatValue, 0, 1);
        EditorGUILayout.EndHorizontal();


        GUILayout.Label("");

        EditorGUILayout.BeginVertical(style_Orange);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Actions when the puzzle start the first time : ", EditorStyles.boldLabel);


        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndVertical();

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("PopUp an object : ", GUILayout.Width(100));
        EditorGUILayout.PropertyField(popUpObject, new GUIContent(""), GUILayout.Width(160));
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("PopUp Speed : ", GUILayout.Width(100));
        EditorGUILayout.PropertyField(popupSpeed, new GUIContent(""), GUILayout.Width(30));
        EditorGUILayout.EndHorizontal();

        //-> Display feedback ID used when the puzzle is not available
        displayFeedbackWhenPuzzleIsLocked();

        EditorGUILayout.EndVertical();
    }
コード例 #23
0
ファイル: SlidingPuzzleGoalTest.cs プロジェクト: gonzsa04/IA
        // Construye una prueba de objetivo de dimensiones (rows) por (columns)
        // Como mínimo las dimensiones tienen que ser de 1x1
        public SlidingPuzzleGoalTest(uint rows, uint columns)
        {
            if (rows == 0)
            {
                throw new ArgumentException(string.Format("{0} is not a valid rows value", rows), "rows");
            }
            if (columns == 0)
            {
                throw new ArgumentException(string.Format("{0} is not a valid columns value", columns), "columns");
            }

            goal = new SlidingPuzzle(rows, columns); // Por defecto estará en la configuración objetivo, que es también la inicial
        }
コード例 #24
0
        // Inicializa o reinicia el gestor
        private void Initialize(uint rows, uint columns)
        {
            if (board == null)
            {
                throw new InvalidOperationException("The board reference is null");
            }
            if (infoPanel == null)
            {
                throw new InvalidOperationException("The infoPanel reference is null");
            }
            if (timeNumber == null)
            {
                throw new InvalidOperationException("The timeNumber reference is null");
            }
            if (stepsNumber == null)
            {
                throw new InvalidOperationException("The stepsNumber reference is null");
            }
            if (rowsInput == null)
            {
                throw new InvalidOperationException("The rowsInputText reference is null");
            }
            if (columnsInput == null)
            {
                throw new InvalidOperationException("The columnsInputText reference is null");
            }

            this.rows         = rows;
            this.columns      = columns;
            rowsInput.text    = rows.ToString();
            columnsInput.text = columns.ToString();



            // Se crea el puzle internamente
            puzzle = new SlidingPuzzle(rows, columns);
            // Se crea el resolutor (que puede admitir varias estrategias)

            // Inicializar todo el tablero de bloques
            board.Initialize(this, puzzle);

            //Inicializar tanque
            tank.Initialize(board);

            CleanInfo();

            // Podríamos asumir que tras cada inicialización o reinicio, el puzle está ordenado y se puede mostrar todo el panel de información
            UpdateInfo();

            flag.transform.position = new Vector3(-8000, flag.transform.position.y, -8000);
        }
コード例 #25
0
        public void TestGenerateAction2()
        {
            // Center case
            int[]         board  = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
            SlidingPuzzle puzzle = new SlidingPuzzle(board);

            SlidingPuzzleAction[] actual   = puzzle.GetActions().ToArray();
            SlidingPuzzleAction[] expected = new SlidingPuzzleAction[2];
            expected[0] = new SlidingPuzzleAction(0, 0 + 1);
            expected[1] = new SlidingPuzzleAction(0, 0 + 3);

            System.Console.WriteLine("Testing GenerateActions()");
            System.Console.WriteLine("\tTop-Left Case");
            Assert.Equal(actual, expected);
        }
コード例 #26
0
        public void TestGenerateAction3()
        {
            // Center case
            int[]         board  = { 8, 1, 2, 3, 4, 5, 6, 7, 0 };
            SlidingPuzzle puzzle = new SlidingPuzzle(board);

            SlidingPuzzleAction[] actual   = puzzle.GetActions().ToArray();
            SlidingPuzzleAction[] expected = new SlidingPuzzleAction[2];
            expected[0] = new SlidingPuzzleAction(8, 8 - 1);
            expected[1] = new SlidingPuzzleAction(8, 8 - 3);

            System.Console.WriteLine("Testing GenerateActions()");
            System.Console.WriteLine("\tBottom-Right Case");
            Assert.Equal(actual, expected);
        }
コード例 #27
0
        // Inicializa o reinicia el gestor de la escena del puzle de bloques deslizantes
        private void Initialize(uint rows, uint columns)
        {
            // Lanza excepciones si el objeto no ha sido inicializado con gameobjects en todos sus campos clave
            if (board == null)
            {
                throw new InvalidOperationException("The board reference is null");
            }
            if (infoPanel == null)
            {
                throw new InvalidOperationException("The infoPanel reference is null");
            }
            if (metricsPanel == null)
            {
                throw new InvalidOperationException("The metricsPanel reference is null");
            }
            if (timeNumber == null)
            {
                throw new InvalidOperationException("The timeNumber reference is null");
            }
            if (stepsNumber == null)
            {
                throw new InvalidOperationException("The stepsNumber reference is null");
            }
            if (rowsInput == null)
            {
                throw new InvalidOperationException("The rowsInputText reference is null");
            }
            if (columnsInput == null)
            {
                throw new InvalidOperationException("The columnsInputText reference is null");
            }

            this.rows         = rows;
            this.columns      = columns;
            rowsInput.text    = rows.ToString();
            columnsInput.text = columns.ToString();

            // Se crea el puzle internamente
            puzzle = new SlidingPuzzle(rows, columns);

            // Inicializar todo el tablero de bloques
            board.Initialize(this, puzzle);

            CleanInfoAndMetrics();

            // Podríamos asumir que tras cada inicialización o reinicio, el puzle está ordenado y se puede mostrar todo el panel de información
            UpdateHUD();
        }
コード例 #28
0
        public static void Main(String[] args)
        {
            SlidingPuzzle puzzle = new SlidingPuzzle();

            //puzzle.SetState("{1,2,3,4,8,6,7,5,0}");
            puzzle.ShuffleBoard();
            var path = A_StarSearch <string, SlidingPuzzleAction> .Search(
                puzzle,
                "{1,2,3,4,5,6,7,8,0}");

            System.Console.WriteLine("Num steps = " + path.Count);
            while (path.Count > 0)
            {
                System.Console.WriteLine(path.Pop());
            }
        }
コード例 #29
0
        public Tuple <Matrix <float>, Vector <float> > BuildData(List <TrainingInstance> trainingInstances)
        {
            IState[] states = trainingInstances.Select(x => x.State).ToArray();

            double[] pathCosts = trainingInstances.Select(x => x.Response).ToArray();

            Matrix <float> trainingData = DenseMatrix.Create(states.Length, numInputs, 0);

            for (int r = 0; r < trainingData.RowCount; r++)
            {
                IState state = states[r];

                byte[] stateArr = state.Arr;

                int count = 0;

                for (byte i = 0; i < stateArr.Length; i++)
                {
                    int index = Array.IndexOf(stateArr, i);

                    var coord = SlidingPuzzle.IndexToCoord(index);

                    trainingData[r, count + coord.Item1 - 1] = 1;

                    trainingData[r, count + dim + coord.Item2 - 1] = 1;

                    count += dim + dim;
                }
            }

            Vector <float> response = DenseVector.Create(pathCosts.Length, 0);

            for (int i = 0; i < pathCosts.Length; i++)
            {
                double y = pathCosts[i];

                if (responseFunc != null)
                {
                    y = responseFunc(y);
                }

                response[i] = (float)y;
            }

            return(new Tuple <Matrix <float>, Vector <float> >(trainingData, response));
        }
コード例 #30
0
        public void TestGenerateAction1()
        {
            // Center case
            int[]         board  = { 1, 2, 3, 4, 0, 5, 6, 7, 8 };
            SlidingPuzzle puzzle = new SlidingPuzzle(board);

            SlidingPuzzleAction[] actual   = puzzle.GetActions().ToArray();
            SlidingPuzzleAction[] expected = new SlidingPuzzleAction[4];
            expected[0] = new SlidingPuzzleAction(4, 4 - 1);
            expected[1] = new SlidingPuzzleAction(4, 4 + 1);
            expected[2] = new SlidingPuzzleAction(4, 4 - 3);
            expected[3] = new SlidingPuzzleAction(4, 4 + 3);

            System.Console.WriteLine("Testing GenerateActions()");
            System.Console.WriteLine("\tCenter Case");
            Assert.Equal(actual, expected);
        }