static void RandomGenPositions(Vector2 xRange, PuzzleData puzzle, ref List <NodeBlock> currentBlocks, int num)
    {
        int cap = 1000;

        while (num > 0 && --cap > 0)
        {
            Vector2 randPos = new Vector2(Random.Range(Mathf.RoundToInt(xRange.x), Mathf.RoundToInt(xRange.y)), Random.Range(0, puzzle.gridSize[1]));
            bool    skip    = false;
            foreach (NodeBlock block in currentBlocks)
            {
                if ((block.pos - randPos).magnitude < 1.0f)
                {
                    skip = true;
                }
            }
            if (skip)
            {
                continue;
            }

            NodeBlock newBlock = new NodeBlock();
            newBlock.pos = randPos;
            currentBlocks.Add(newBlock);
            --num;
        }
    }
Example #2
0
    public void AssignPuzzleData(PuzzleData puzzleData)
    {
        //puzzleData = new List<PuzzleData>();
        questionText.text = puzzleData.question;
        puzzleAnswer      = puzzleData.answer;

        System.Random random = new System.Random();
        string[]      puzzleButtonOptions = new string[]
        {
            puzzleData.answer,
            puzzleData.wrongAnswer1,
            puzzleData.wrongAnswer2,
            puzzleData.wrongAnswer3,
        };

        if (puzzleData.answer == puzzleData.wrongAnswer1 || puzzleData.answer == puzzleData.wrongAnswer2 || puzzleData.answer == puzzleData.wrongAnswer3 || puzzleData.wrongAnswer1 == puzzleData.wrongAnswer2 || puzzleData.wrongAnswer1 == puzzleData.wrongAnswer3 || puzzleData.wrongAnswer2 == puzzleData.wrongAnswer3)
        {
            AssignPuzzleData(puzzleData);
            return;
        }

        reshuffledData = puzzleButtonOptions.OrderBy(x => random.Next()).ToArray();

        answerButtonText.text       = reshuffledData[0];
        wrongAnswer1ButtonText.text = reshuffledData[1];
        wrongAnswer2ButtonText.text = reshuffledData[2];
        wrongAnswer3ButtonText.text = reshuffledData[3];

        //answerButton.onClick.AddListener(delegate { PlayerManager.instance.checkPuzzleAnswer(reshuffledData[0]); });
        //wrongAnswer1Button.onClick.AddListener(delegate { PlayerManager.instance.checkPuzzleAnswer(reshuffledData[1]); });
        //wrongAnswer2Button.onClick.AddListener(delegate { PlayerManager.instance.checkPuzzleAnswer(reshuffledData[2]); });
        //wrongAnswer3Button.onClick.AddListener(delegate { PlayerManager.instance.checkPuzzleAnswer(reshuffledData[3]); });

        puzzleQuestionBackground.SetActive(true);
    }
    public static void CreateAtEmpty(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam,Material[] puzzleColorList)
    {
        // Rearranged in ascending order of ID puzzles
        puzzleData.Sort();
        // Create
        puzzleData.pieceObjectList.ForEach((GameObject pieceObject) =>
        {
            PuzzlePiece targetPiece = pieceObject.GetComponent<PuzzlePiece>();
            // Create a new puzzle piece ID that is not used
            if(targetPiece.used == false)
            {
                // Resume Puzzle Piece
                targetPiece.Resume();

                // Set Puzzle position
                Vector3 endPos 		= PuzzleCalculator.GetPiecePosition(puzzleParam,targetPiece.ID);
                Vector3 startPos	= endPos;
                endPos.z			= -50;
                targetPiece.Move(startPos,endPos,puzzleParam.moveTime);

                // Set the color to random.
                int typeNo = Random.Range(0,puzzleColorList.Length);
                targetPiece.SetColor(typeNo,puzzleColorList[typeNo]);
            }
        } );
    }
    public static void RandomGenObjectives(Vector2 xRange, Vector2 valueRange, PuzzleData puzzle, ref List <NodeBlock> objs)
    {
        int num = objs.Count;

        RandomGenPositions(xRange, puzzle, ref objs, num);
        RandomGenValues(valueRange, ref objs);
    }
Example #5
0
        public bool GetPuzzleData(int imageId, int iDifficultyLevel, out PuzzleData puzzleData, out string errorString)
        {
            puzzleData  = null;
            errorString = string.Empty;

            puzzleData = new PuzzleData();

            ImageData imageData = null;

            if (!GetImageData(imageId, out imageData, out errorString))
            {
                return(false);
            }

            puzzleData.ImageData = imageData;

            List <PuzzlePartData> puzzlePartsData = null;

            if (!GetPuzzlePartsData(imageId, iDifficultyLevel, out puzzlePartsData, out errorString))
            {
                return(false);
            }

            puzzleData.PuzzlePartData = puzzlePartsData;

            return(true);
        }
Example #6
0
    void Start()
    {
        puzzleInputData = JsonManager.DefinePath("Sudoku");
        puzzleUI        = GetComponent <PuzzleBoardUI>();

        NextPuzzle();
    }
    public static PuzzleData RandomGenLevel()
    {
        PuzzleData retPuzzle = new PuzzleData();

        // Randomize grid size
        //int[] gridSize = new int[2] { Random.Range(3, 6), Random.Range(3, 5) };
        int[] gridSize = new int[2] {
            5, 4
        };
        retPuzzle.gridSize = gridSize;

        // Randomize start and end blocks
        int numStart = Random.Range(1, 3);
        int numEnd   = Random.Range(1, 2);

        retPuzzle.startBlocks = new List <NodeBlock>(new NodeBlock[numStart]);
        retPuzzle.endBlocks   = new List <NodeBlock>(new NodeBlock[numEnd]);

        Vector2 startXRange = new Vector2(0, (gridSize[0] / 2) + gridSize[0] % 2);
        Vector2 startValues = new Vector2(1, 10);

        RandomGenObjectives(startXRange, startValues, retPuzzle, ref retPuzzle.startBlocks);

        Vector2 endXRange = new Vector2(gridSize[0] - gridSize[0] / 2, gridSize[0]);
        Vector2 endValues = new Vector2(1, 15);

        RandomGenObjectives(endXRange, endValues, retPuzzle, ref retPuzzle.endBlocks);

        return(retPuzzle);
    }
Example #8
0
    static private void movePuzzle()
    {
        int direction = (int)stackDFS.Pop();

        if (direction == 0)
        {
            PuzzleData.moveLeft(xTempPuzzle, yTempPuzzle);
        }
        else if (direction == 1)
        {
            PuzzleData.moveUp(xTempPuzzle, yTempPuzzle);
        }
        else if (direction == 2)
        {
            PuzzleData.moveRight(xTempPuzzle, yTempPuzzle);
        }
        else if (direction == 3)
        {
            PuzzleData.moveDown(xTempPuzzle, yTempPuzzle);
        }
        if (!trackBack)
        {
            addMove(direction);
        }
        addVisitedList();

        trackBack = false;
    }
    private static void Matched(int nowIndex,int numChaine,ref PuzzleData puzzleData,Func<int,int> NextIndex)
    {
        PuzzlePiece nowPiece 	= puzzleData.FindPiece(nowIndex);
        nowPiece.used 			= false;

        puzzleData.numChaine++;

        if(nowPiece.chaineID < 0)
            nowPiece.chaineID	= puzzleData.numChaine;

        for(int i = 1;i < numChaine;i++)
        {
            int nextIndex = NextIndex(i);
            if(PuzzleStateChecker.HasIndexOutOfRange(puzzleData,nextIndex) == false)
            {
                PuzzlePiece nextPiece 	= puzzleData.FindPiece(nextIndex);
                nextPiece.used 			= false;

                // Connect the chain if you are chained already
                if(nextPiece.chaineID < 0)
                    nextPiece.chaineID	= puzzleData.numChaine;
                else
                    puzzleData.SetChaine(nextPiece.chaineID,nowPiece.chaineID);
            }
        }
    }
Example #10
0
    public void NotifyPuzzleSolved(PuzzleData solvedPuzzle)
    {
        currentLevel++;
        SolvedPuzzles.Add(solvedPuzzle);

        if (IsGameCompleted())
        {
            StartCoroutine(CoroutineSequence(new List <IEnumerator>
            {
                FinishLevelCoroutine(),
                // diálogo final
                ActionCoroutine(eventGameCompleted),
                WaitTimeCoroutine(5f),
                ActionCoroutine(() =>
                {
                    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
                }),
            }));
            print("me gané el juego");
        }
        else
        {
            StartCoroutine(CoroutineSequence(new List <IEnumerator>
            {
                FinishLevelCoroutine(),
                SelectItemsCoroutine(),
                ActionCoroutine(() => eventPuzzleSolved?.Invoke(solvedPuzzle)),
                StartLevelCoroutine()
            }));
        }
    }
Example #11
0
    public void LoadProcGenScene(int level)
    {
        //currentLevel = level;
        currentLevel = 14;
        lineMan.ResetLines();
        lineMan.currentLineBeingDrawn = null;

        // Hand crafted levels
        //gridMan.ConstructLevel(LevelData.puzzleData[currentLevel]);

        // Full random level gen
        //PuzzleData puzzle = ProcGenManager.RandomGenLevel();

        // Proc. queued level gen
        // Remove used start blocks here
        for (int i = 0; i < currentPuzzle.startBlocks.Count; ++i)
        {
            NodeBlock        startB = currentPuzzle.startBlocks[i];
            StartBlockScript sbs    = grid[(int)startB.pos.x][(int)startB.pos.y].GetComponent <StartBlockScript>();

            if (sbs.isInUse)
            {
                currentPuzzle.startBlocks.Remove(startB);
                --i;
            }
        }
        currentPuzzle = ProcGenManager.RandomGenQueuedLevel(currentPuzzle);

        gridMan.ConstructLevel(currentPuzzle);
        uiMan.UpdateLevelUI();

        // Reset number of objects intersection
        objsIntersect  = 0;
        levelCompleted = false;
    }
Example #12
0
    private void CreatePuzzle()
    {
        Vector2 diff;
        Vector2 mpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        diff.x = mpos.x - target.transform.position.x;
        diff.y = mpos.y - target.transform.position.x;

        //Debug.Log("mpos: " + mpos);
        //Debug.Log("target position: " + target.transform.position);

        // negative value = left move
        if (mpos.x <= leftMargin)
        {
            // Debug.Log("diff.x: " + diff.x);
            if (createFlag == false)
            {
                createFlag = true;
                ButtonPuzzle targetBP = target.GetComponent <ButtonPuzzle>();
                PuzzleData   pd       = puzzleData.GetComponent <PuzzleData>();
                target = Instantiate(targetBP.pfPuzz, mpos, Quaternion.identity);
                pd.AddPuzzle(target);

                worldOriginPosition = mpos;
            }
        }

        return;
    }
    public static void ChangeID(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam,int targetID)
    {
        PuzzlePiece selectedPuzzle = puzzleData.pieceObjectList[puzzleData.selectedPieceNo].GetComponent<PuzzlePiece>();
        PuzzlePiece nowPiece;
        int targetObjectIdx 	= puzzleData.FindPieceObjectIndex(targetID);
        int tempID 				= selectedPuzzle.ID;

        // debug
        if(PuzzleStateChecker.HasIndexOutOfRange(puzzleData,targetObjectIdx))
            return;

        // The amount of movement becomes a constant value,Change ID
        Vector3 amount = puzzleData.pieceObjectList[targetObjectIdx].transform.position - selectedPuzzle.transform.position;
        if( amount.x < puzzleParam.puzzleSpace && amount.x > -puzzleParam.puzzleSpace &&
           	amount.z < puzzleParam.puzzleSpace && amount.z > -puzzleParam.puzzleSpace )
        {
            nowPiece 		= puzzleData.pieceObjectList[targetObjectIdx].GetComponent<PuzzlePiece>();
            nowPiece.ID	 	= tempID;
            selectedPuzzle.ID 	= targetID;

            selectedPuzzle.MoveAmountClear(PuzzleCalculator.GetPiecePosition(puzzleParam,targetID));
            nowPiece.Move(PuzzleCalculator.GetPiecePosition(puzzleParam,tempID),puzzleParam.moveTime);
        }

        // Register puzzles traced
        puzzleData.selectedPieceNameList.Add(puzzleData.pieceObjectList[targetObjectIdx].name);
    }
    public static bool HasMatch(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam)
    {
        bool hasMatch = false;

        foreach(var pieceObject in puzzleData.pieceObjectList)
        {
            PuzzlePiece nowPiece = pieceObject.GetComponent<PuzzlePiece>();

            if(nowPiece.used)
            {
                int nowColumNo 			= PuzzleCalculator.GetPieceColumnNo(puzzleParam,(nowPiece.ID));
                int nowRowNo 			= PuzzleCalculator.GetPieceRowNo(puzzleParam,nowPiece.ID);
                int rowLimitBorder		= PuzzleCalculator.GetRowLimitBorder(puzzleParam);
                int columnLimitBorder	= PuzzleCalculator.GetColumnLimitBorder(puzzleParam);
                int numChaine 			= 1;

                // Check Column
                if(nowColumNo < columnLimitBorder)
                {
                    // Search to the last column
                    for(int i = 1;
                        nowRowNo == PuzzleCalculator.GetPieceRowNo(puzzleParam,(i + nowPiece.ID));
                        i++,numChaine++)
                    {
                        int targetIndex = i + nowPiece.ID;
                        if(HasNoChaine(puzzleData,nowPiece.ID,targetIndex))
                            break;
                    }
                    if(numChaine >= puzzleParam.stdNumChaines)
                    {
                        Matched(nowPiece.ID,numChaine,ref puzzleData,(nextIndex) => nextIndex + nowPiece.ID);
                        hasMatch = true;
                    }
                }

                // Check Row
                numChaine = 1;
                if(nowRowNo < rowLimitBorder)
                {
                    // Search to the last line
                    int targetIndex;
                    for(int i = puzzleParam.maxColumns;
                        nowColumNo == PuzzleCalculator.GetPieceColumnNo(puzzleParam,(i + nowPiece.ID));
                        i += puzzleParam.maxColumns,numChaine++)
                    {
                        targetIndex = i + nowPiece.ID;
                        if(HasNoChaine(puzzleData,nowPiece.ID,targetIndex))
                            break;
                    }

                    if(numChaine >= puzzleParam.stdNumChaines)
                    {
                        Matched(nowPiece.ID,numChaine,ref  puzzleData,(nextIndex) => nextIndex * puzzleParam.maxColumns + nowPiece.ID);
                        hasMatch = true;
                    }
                }
            }
        }
        return hasMatch;
    }
    public static void Operate(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam)
    {
        PuzzlePiece selectedPiece 	= puzzleData.pieceObjectList[puzzleData.selectedPieceNo].GetComponent<PuzzlePiece>();
        Vector3 moveAmount 			= selectedPiece.moveAmount;
        float amountRange 			= PuzzleCalculator.GetAmountRangeCrissCross(puzzleParam);
        float amountRangeDiagonal 	= PuzzleCalculator.GetAmountRangeDiagonal(puzzleParam);

        // The amount of movement becomes a constant value,Move it

        // Move diagonal
        if(moveAmount.x >= amountRangeDiagonal && moveAmount.z >= amountRangeDiagonal)
            ChangeID(ref puzzleData,puzzleParam,selectedPiece.ID + 1 + puzzleParam.maxColumns);
        else if(moveAmount.x >= amountRangeDiagonal && moveAmount.z <= -amountRangeDiagonal)
            ChangeID(ref puzzleData,puzzleParam,selectedPiece.ID + 1 - puzzleParam.maxColumns);
        else if(moveAmount.x <= -amountRangeDiagonal && moveAmount.z >= amountRangeDiagonal)
            ChangeID(ref puzzleData,puzzleParam,selectedPiece.ID - 1 + puzzleParam.maxColumns);
        else if(moveAmount.x <= -amountRangeDiagonal && moveAmount.z <= -amountRangeDiagonal)
            ChangeID(ref puzzleData,puzzleParam,selectedPiece.ID - 1 - puzzleParam.maxColumns);
        // Move right.
        else if(moveAmount.x >= amountRange)
            ChangeID(ref puzzleData,puzzleParam,selectedPiece.ID + 1);
        // Move left.
        else if(moveAmount.x <= -amountRange)
            ChangeID(ref puzzleData,puzzleParam,selectedPiece.ID - 1);
        // Move up.
        else if(moveAmount.z >= amountRange)
            ChangeID(ref puzzleData,puzzleParam,selectedPiece.ID + puzzleParam.maxColumns);
        // Move down.
        else if(moveAmount.z <= -amountRange)
            ChangeID(ref puzzleData,puzzleParam,selectedPiece.ID - puzzleParam.maxColumns);
    }
Example #16
0
        private void SaveLevel(Puzzle.Puzzle puzzle, string name)
        {
            PuzzleData puzzleData = new PuzzleData(puzzle);

            puzzleData.Save(name);

            Debug.Log("Puzzle Saved. Wait for the file to update");
        }
    public void SetUpPuzzle(int roomID, bool removePuzzleData = true)
    {
        int id = GameplayManager.random.Next(puzzleData.Count);

        Room       room   = GameplayManager.rooms[roomID];                              // Pokój w którym umieszczana jest zagadka
        PuzzleData puzzle = puzzleData[id];                                             // Zagadka, która będzie przypisywana
        int        clamp  = Mathf.Clamp(roomID - 2, 0, roomID);

        // Lista wszystkich skrzyń z danego pokoju oraz pokoi poprzednich:
        List <Storage> storages = GameplayManager.rooms.GetRange(0, roomID + 1).Where(x => x.roomID >= clamp).SelectMany(x => x.roomObjects).Where(x => x.items.Count == 0).ToList();


        Storage previousStorage = null;                                                 // Ostatnio dodana skrzynia
        Storage storage         = null;                                                 // Aktualnie rozpatrywana skrzynia
        Item    firstItem       = null;

        /*bool canLock = true;*/
        for (int i = 0; i < puzzle.storages.Length; i++)
        {
            storage = FindStorage(puzzle.storages[i], storages);                       // Wyszukuje losowej skrzynki w zanelżności od parametrów
            /* if (storage.items.Count > 0) canLock = false;*/
            storages.Remove(storage);                                                  // Usuwanie z repozytorium skrzynki, aby się nie powtórzyła w wyszukiwaniu


            for (int j = 0; j < puzzle.storages[i].itemsPrefabs.Length; j++)            // Dodawanie itemów do skrzyni
            {
                GameObject gOItem = Instantiate(puzzle.storages[i].itemsPrefabs[j], storage.transform);
                Item       item   = gOItem.GetComponent <Item>();
                item.SetupItem();
                storage.items.Add(item.gameObject);

                //      Debug.LogFormat("Dodano przedmiot {0} do skrzynki {1} w pokoju {2}", item.objectType, storage.name, room.roomName);

                if (j == 0)
                {
                    firstItem = item;
                }
            }

            if (i == 0 /*&& canLock*/)
            {
                LockObject(room.door, firstItem);
            }
            else if (puzzle.storages[i].closePreviousObject && !previousStorage.locked /*&& canLock*/)
            {
                LockObject(previousStorage, firstItem);
            }


            previousStorage = storage;
        }

        // Debug.LogFormat("Pułapka: {0} została ustawiona.", puzzle.name);
        if (removePuzzleData)
        {
            puzzleData.RemoveAt(id);
        }
    }
Example #18
0
    public void RestartProcGenScene()
    {
        ProcGenManager.LoadInitPGW();
        currentPuzzle = new PuzzleData();
        currentPuzzle = ProcGenManager.RandomGenQueuedLevel(currentPuzzle);
        scoreMan.ResetScoreMan();

        ResetProcGenScene();
    }
Example #19
0
 public void ReadPuzzleData(string info)
 {
     puzzleData = JsonMapper.ToObject <PuzzleData> (info);
     //  Debug.Log ("Crossy Count "+);
     if (ReadCompelte != null)
     {
         ReadCompelte();
     }
 }
    //saves current puzzle layout as a new xml doucument
    //esentially a level editor
    //does not make a corresponding solution image
    void savePuzzle()
    {
        PuzzleData data = new PuzzleData();

        data.start    = start;
        data.solution = new List <Vector3>();
        foreach (GameObject block in blocks)
        {
            data.solution.Add(block.transform.position);
        }

        //stadardize solution
        int minX = int.MaxValue;
        int minY = int.MaxValue;
        int minZ = int.MaxValue;

        foreach (Vector3 vec in data.solution)
        {
            if (vec.x < minX)
            {
                minX = (int)vec.x;
            }
            if (vec.y < minY)
            {
                minY = (int)vec.y;
            }
            if (vec.z < minZ)
            {
                minZ = (int)vec.z;
            }
        }

        for (int i = 0; i < data.solution.Count; i++)
        {
            Vector3 tempVec = data.solution[i];
            tempVec.x       -= minX;
            tempVec.y       -= minY;
            tempVec.z       -= minZ;
            data.solution[i] = tempVec;
        }

        //foreach(Vector3 vec in data.solution)
        //{
        //    Debug.Log(vec + " ");
        //}

        //store to xml
        XmlSerializer serializer = new XmlSerializer(typeof(PuzzleData));
        FileStream    stream     = new FileStream(Application.dataPath + "/Resources/PuzzleData/newPuzzle.xml", FileMode.Create);

        serializer.Serialize(stream, data);
        if (File.Exists(Application.dataPath + "/Resources/PuzzleData/newPuzzle.xml"))
        {
            Debug.Log("level saved");
        }
        stream.Close();
    }
    private void ShowSolvedPuzzleDialogue(PuzzleData puzzle)
    {
        var dialogue = GetSolvedPuzzleDialogue(puzzle);

        if (dialogue != null)
        {
            ShowDialogue(dialogue);
        }
    }
Example #22
0
 static PuzzleData ReadJson()
 {
     puzzleData = new PuzzleData();
     content    = File.ReadAllText(path);
     Debug.Log(content);
     puzzleData = JsonConvert.DeserializeObject <PuzzleData>(content);
     puzzleData.FillGridList();
     puzzleData.solvedGridList = new List <int[][]>();
     return(puzzleData);
 }
    void readFile()
    {
        XmlSerializer serializer = new XmlSerializer(typeof(PuzzleData));
        FileStream    stream     = new FileStream(Application.dataPath + "/PuzzleData/XML/tutorial.xml", FileMode.Open);
        PuzzleData    tutorial   = serializer.Deserialize(stream) as PuzzleData;

        stream.Close();
        //Debug.Log(tutorial.start[0]);
        //Debug.Log(tutorial.solution[0]);
    }
Example #24
0
 private void ChoosedChange(object sender, EventArgs args)
 {
     if (puzzlesList.SelectedItem != null)
     {
         PuzzleData choosed = parent.Parent.readyPuzzles[(String)puzzlesList.SelectedItem];
         heightText.Text = choosed.height.ToString();
         widthText.Text  = choosed.width.ToString();
         typeText.Text   = choosed.puzzleType.Name;
     }
 }
 public static bool HasIndexOutOfRange(PuzzleData puzzleData,int targetIdx)
 {
     bool isError = false;
     if(targetIdx < 0 || targetIdx >=  puzzleData.pieceObjectList.Count)
     {
         Debug.LogWarning ("Index " + targetIdx + " Out of range");
         isError = true;
     }
     return isError;
 }
Example #26
0
        public PathGridView(PuzzleData puzzle, int width, int height)
            : base(puzzle, width, height, AppDelegate.UserInterfaceIdiomIsPhone ? CELL_SIZE_IPHONE : CELL_SIZE_IPAD)
        {
            // Create the view
            PathGridViewInternal theView = new PathGridViewInternal(this, new RectangleF(0, 0, width * CellSize, height * CellSize));

            // Create the grid and cells views
            CreateGrid(0, 0, theView);

            GridViewInternal = theView;
        }
Example #27
0
    static void CreatePuzzle()
    {
        string path = EditorUtility.SaveFilePanel("Create Puzzle", "Assets/Resources/", "puzzle.asset", "asset");

        path = FileUtil.GetProjectRelativePath(path);

        PuzzleData pd = CreateInstance <PuzzleData>();

        AssetDatabase.CreateAsset(pd, path);
        AssetDatabase.SaveAssets();
    }
Example #28
0
 private void Initialize()
 {
     readyPuzzles = new Dictionary <string, PuzzleData>();
     System.IO.StreamReader file = new System.IO.StreamReader("ReadyPuzzles/List.ls");
     while (!file.EndOfStream)
     {
         PuzzleData newElem = new PuzzleData(file.ReadLine());
         readyPuzzles.Add(newElem.name, newElem);
     }
     file.Close();
 }
Example #29
0
        internal void ResetPuzzle()
        {
            if (this.puzzleItem == null)
            {
                return;
            }

            if (imageStream != null)
            {
                imageStream.Dispose();
                imageStream = null;
            }

            byte[] imageData = PuzzleData.LoadImageData(this.puzzleItem.ImageFile);

            this.imageStream = new System.IO.MemoryStream(imageData);

            BitmapImage bi = new BitmapImage();

            bi.BeginInit();
            bi.StreamSource = imageStream;
            bi.EndInit();

            Image image = new Image();

            image.Source  = bi;
            image.Stretch = Stretch.Uniform;

            this.CalcPuzzleSize(bi.PixelWidth, bi.PixelHeight);

            image.MouseDown += this.puzzleImageMouseButtonEventHandler;

            Border border = new Border();

            border.Style = App.Current.FindResource("puzzleBorderStyle") as Style;

            border.Child  = image;
            border.Width  = puzzleSize.Width;
            border.Height = puzzleSize.Height;

            this.unsubscribEvent();

            this.puzzleHostingPanel.Children.Clear();
            this.puzzleHostingPanel.Children.Add(border);

            this.statusLabel.Text       = "";
            this.answerLabel.Text       = "";
            this.totalSteps             = -1;
            this.usedSteps              = -1;
            this.getAnswerBtn.IsEnabled = false;
            this.nextStepBtn.IsEnabled  = false;
            this.movedSteps             = 0;
        }
Example #30
0
 // Based on the information in puzzleData, this function will respectively instantiate cards
 // into the card hand. For each card, the function generates a unique hexidecimal address and
 // attaches the necessary card script to the object.
 public void GenerateHand(PuzzleData puzzleData)
 {
     System.Random random = new System.Random(puzzleData.CardAddressSeed);
     if (puzzleData.NumRegisterCards + puzzleData.NumStackCards + puzzleData.NumQueueCards + puzzleData.NumHeapCards == 0)
     {
         Destroy(GameObject.FindGameObjectWithTag("CardElements"));
     }
     SpawnCard(RegisterCardPrefab, puzzleData.NumRegisterCards, random);
     SpawnCard(StackCardPrefab, puzzleData.NumStackCards, random);
     SpawnCard(QueueCardPrefab, puzzleData.NumQueueCards, random);
     SpawnCard(HeapCardPrefab, puzzleData.NumHeapCards, random);
 }
    public static void SavePuzzle(Puzzle puzzle, string fileName)
    {
        fileName += ".txt";

        BinaryFormatter bf     = new BinaryFormatter();
        FileStream      stream = new FileStream(Application.streamingAssetsPath + @"/" + fileName, FileMode.Create);

        PuzzleData data = new PuzzleData(puzzle);

        bf.Serialize(stream, data);
        stream.Close();
    }
        private ThumbnailItem win_DataItemLoadedEvent(string file)
        {
            PuzzleItem pi = PuzzleData.LoadPuzzleItem(file);

            if (pi.Type != PuzzleSetting.Instance.Type)
            {
                return(null);
            }
            pi.ImageFile = file;
            ControlMgr.Instance.DataMgr.Add(pi);
            return(pi);
        }
    private static bool HasNoChaine(PuzzleData puzzleData,int nowIndex,int nextIndex)
    {
        if(PuzzleStateChecker.HasIndexOutOfRange(puzzleData,nextIndex))
            return true;

        PuzzlePiece nowPiece 	= puzzleData.FindPiece(nowIndex);
        PuzzlePiece nextPiece 	= puzzleData.FindPiece(nextIndex);
        if(nowPiece.type != nextPiece.type)
            return true;

        return false;
    }
    public DialogueSequenceBase GetSolvedPuzzleDialogue(PuzzleData puzzleData)
    {
        foreach (var puzzleDialogue in puzzlesDialogues)
        {
            if (puzzleDialogue.puzzleData == puzzleData)
            {
                return(puzzleDialogue.dialogues);
            }
        }

        return(null);
    }
Example #35
0
 private void SetReadData()
 {
     data = CSVReadManager.Instance.puzzleData;
     if (data != null)
     {
         wordInfo = data.wordInfo;
         SetWordGrid();
         SetHintInfo(tipRow, data.tipsRow, rowContent, true);
         SetHintInfo(tipCol, data.tipsCol, colContent, false);
         SetBlockInfo();
     }
 }
Example #36
0
    public static Rect InspectKara(Rect position, PuzzleData tarPuz)
    {
        Rect saveOrig = position;


        tarPuz.m_width = EditorGUI.IntField(new Rect(position.x,
                                                     position.y,
                                                     position.width * 0.5f,
                                                     EditorGUIUtility.singleLineHeight),
                                            "Width",
                                            tarPuz.m_width);

        tarPuz.m_height = EditorGUI.IntField(new Rect(position.x + position.width * 0.5f,
                                                      position.y,
                                                      position.width * 0.5f,
                                                      EditorGUIUtility.singleLineHeight),
                                             "Height",
                                             tarPuz.m_height);

        position.y      += EditorGUIUtility.singleLineHeight;
        position.height -= EditorGUIUtility.singleLineHeight;

        EditorGUI.BeginChangeCheck();
        float xWidth = Mathf.Min(position.width / Mathf.Max(1, tarPuz.m_width),
                                 position.height / Mathf.Max(1, tarPuz.m_height));

        if (EditorGUI.EndChangeCheck() ||
            (tarPuz.m_data == null) ||
            (tarPuz.m_data.Length != (tarPuz.m_width * tarPuz.m_height)))
        {
            tarPuz.m_data = new int[tarPuz.m_width * tarPuz.m_height];
        }


        GUIStyle kaFontStyle = new GUIStyle(EditorStyles.textField);

        kaFontStyle.fontSize = Mathf.FloorToInt(xWidth * 0.7f);
        for (int x = 0; x < tarPuz.m_width; x++)
        {
            for (int y = 0; y < tarPuz.m_height; y++)
            {
                tarPuz.m_data [x + y * tarPuz.m_width] =
                    EditorGUI.IntField(new Rect(position.x + xWidth * x,
                                                position.y + xWidth * y,
                                                xWidth,
                                                xWidth),
                                       tarPuz.m_data [x + y * tarPuz.m_width], kaFontStyle);
            }
        }

        return(new Rect(saveOrig.x, saveOrig.y, saveOrig.width, EditorGUIUtility.singleLineHeight * (tarPuz.m_height + 1)));
    }
    public RegularHexpressionsController(KMBombInfo bomb, string logPrefix)
    {
        this.logPrefix = logPrefix;

        regexCoords = SampleRegexCoordinates(bomb);
        puzzle      = PuzzleData.SamplePuzzle(
            regexCoords.rowNorth, regexCoords.rowSouth, regexCoords.colWest, regexCoords.colEast);

        Debug.LogFormat("{0} North-west regex '{1}' matches word '{2}'.",
                        logPrefix, puzzle.regexData[0].realStr, puzzle.matchingWords[0]);
        Debug.LogFormat("{0} North-east regex '{1}' matches word '{2}'.",
                        logPrefix, puzzle.regexData[1].realStr, puzzle.matchingWords[1]);
        Debug.LogFormat("{0} South-east regex '{1}' matches word '{2}'.",
                        logPrefix, puzzle.regexData[2].realStr, puzzle.matchingWords[2]);
        Debug.LogFormat("{0} South-west regex '{1}' matches word '{2}'.",
                        logPrefix, puzzle.regexData[3].realStr, puzzle.matchingWords[3]);

        // Assign words to vertices such that at most 2 words are in the correct locations
        string[] wordOrder = puzzle.matchingWords.Concat(puzzle.decoyWords).ToArray();
        int      correctLocations;

        do
        {
            wordOrder.Shuffle();
            correctLocations = CENTER_COLUMN_VERTICES
                               .Where((vertex, i) => wordOrder[(int)vertex] == puzzle.matchingWords[i])
                               .Count();
        } while (correctLocations > 2);
        vertexWords        = new Dictionary <HV, string>(wordOrder.Length);
        vertexLabeledWords = new Dictionary <HV, string>(wordOrder.Length);
        for (int i = 0; i < wordOrder.Length; i++)
        {
            HV vertex = (HV)i;
            vertexWords[vertex]        = wordOrder[i];
            vertexLabeledWords[vertex] = string.Format("({0} {1})", VERTEX_LABELS[vertex], wordOrder[i]);
        }
        Debug.LogFormat("{0} Vertex labels and words: {1}",
                        logPrefix,
                        vertexLabeledWords.Select(pair => pair.Value).Join(" "));

        // Both permutation and inverse are identity
        vertexPermutation = new VP();
        foreach (HV vertex in System.Enum.GetValues(typeof(HV)))
        {
            vertexPermutation[vertex] = vertex;
        }
        vertexPermutationInverse = new VP(vertexPermutation);
        AssertPermutationInverseIsValid();

        isSolved    = false;
        turningFace = null;
    }
 public static bool IsSelectedPiece(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam)
 {
     bool existsSelectedPiece = false;
     foreach(var peiceObject in puzzleData.pieceObjectList.Select((piece, index) => new {piece,index}))
     {
         if(peiceObject.piece.GetComponent<PuzzlePiece>().selected)
         {
             puzzleData.selectedPieceNo = peiceObject.index;
             existsSelectedPiece = true;
             break;
         }
     }
     return existsSelectedPiece;
 }
    public static bool IsCompletedDestroy(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam)
    {
        bool isCompleted = false;

        if(TimeCounter.IsTimeOver(ref puzzleData.destroyTimeCounter,puzzleParam.destroyTime))
        {
            int nowChaineID = puzzleData.numChaine;
            puzzleData.pieceObjectList.ForEach((GameObject pieceObject) =>
            {
                PuzzlePiece nowPiece = pieceObject.GetComponent<PuzzlePiece>();
                if(nowPiece.chaineID == nowChaineID)
                    nowPiece.Stop();
            });

            TimeCounter.StartTimer(ref puzzleData.destroyTimeCounter);
            puzzleData.numChaine--;
            if(puzzleData.numChaine < 0)
                isCompleted = true;
        }
        return isCompleted;
    }
    public static void CreatePuzzlePieceObject(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam,
	                       GameObject puzzlePiecePrefab,Material[] puzzleColorList)
    {
        for(int i = 0;i < puzzleParam.maxPuzzles;i++)
        {
            // Create new piece.
            puzzleData.pieceObjectList.Add(Object.Instantiate(puzzlePiecePrefab,
                                                              PuzzleCalculator.GetPiecePosition(puzzleParam,i),
                                                              Quaternion.identity) as GameObject);
            puzzleData.pieceObjectList[i].name = "Puzzle" + i.ToString();

            // Set Parameters
            PuzzlePiece newPiece = puzzleData.pieceObjectList[i].GetComponent<PuzzlePiece>();
            newPiece.ID = i;
            newPiece.Resume();

            // Set the color to random.
            int colorIdx = Random.Range(0,puzzleColorList.Length);
            newPiece.SetColor(colorIdx,puzzleColorList[colorIdx]);
        }
    }
    public static void SortByRefEmpty(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam)
    {
        // Rearranged in ascending order of ID puzzles
        puzzleData.Sort();

        for(int puzzleNo = puzzleData.pieceObjectList.Count - 1; puzzleNo >= 0;puzzleNo--)
        {
            Vector3 puzzlePos = Vector3.zero;
            PuzzlePiece nowPiece = puzzleData.pieceObjectList[puzzleNo].GetComponent<PuzzlePiece>();

            // It moves one on the target is empty
            int targetRowNo = PuzzleCalculator.GetPieceRowNo(puzzleParam,nowPiece.ID);
            if(targetRowNo < puzzleParam.maxRows - 1)
            {
                // Check until it can move
                for(int id = nowPiece.ID + puzzleParam.maxColumns;id < puzzleParam.maxPuzzles;id += puzzleParam.maxColumns)
                {
                    GameObject emptyTemp = puzzleData.pieceObjectList[puzzleData.FindPieceObjectIndex(id)];
                    PuzzlePiece emptyPuzzle = emptyTemp.GetComponent<PuzzlePiece>();
                    if(emptyPuzzle.used == false)
                    {
                        emptyPuzzle.ID 	= nowPiece.ID;
                        nowPiece.ID = id;
                        emptyPuzzle.Stop();
                        emptyTemp.transform.position = PuzzleCalculator.GetPiecePosition(puzzleParam,emptyPuzzle.ID);
                    }
                }
            }

            nowPiece.MoveAmountClear();

            // Move puzzle piece
            Vector3 nowPos 		= puzzleData.pieceObjectList[puzzleNo].transform.position;
            Vector3 targetPos 	= PuzzleCalculator.GetPiecePosition(puzzleParam,nowPiece.ID);
            if(Vector3.Distance(nowPos,targetPos) > PuzzleCalculator.GetPieceSpaceOffset(puzzleParam))
                nowPiece.Move(targetPos,puzzleParam.moveTime);
        }
    }
    public static void SortByRefID(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam)
    {
        // Rearranged in ascending order of ID puzzles
        puzzleData.Sort();

        puzzleData.pieceObjectList.ForEach((GameObject pieceObject) =>
        {
            PuzzlePiece targetPiece = pieceObject.GetComponent<PuzzlePiece>();
            Vector3 targetPos = PuzzleCalculator.GetPiecePosition(puzzleParam,targetPiece.ID);
            targetPiece.Move(targetPos,puzzleParam.moveTime);

        });
    }
 public static bool IsFinishedSelectTime(ref PuzzleData puzzleData,PuzzleOperaterParam puzzleParam)
 {
     bool isFinished = false;
     return isFinished;
 }