예제 #1
0
 /// <summary>
 /// update which slots are selectible and the info displayed on them
 /// </summary>
 public void refresh()
 {
     for (int i = 2; i >= 0; i--)             // for each save: (reverse order, so first valid slot is set at selected)
     {
         if (SaveObj.SaveExists(i + 1))       // if exists, set name and number-unlocked to match info in save, and make button interactible
         {
             SaveObj save = SaveObj.LoadGame(i + 1);
             slotNameText[i].text = save.slotName;
             int count = 0;
             for (int j = 0; j < GameManager.numLevels; j++)
             {
                 if (save.canAccess(j))
                 {
                     count++;
                 }
             }
             numUnlockedText[i].text    = count + "/" + GameManager.numLevels;
             slotButton[i].interactable = true;
             firstSelected = slotButton[i]; // set valid slot as selected
         }
         else                               // else set text to defualt and set non-interactible
         {
             slotNameText[i].text       = "-";
             numUnlockedText[i].text    = "~/" + GameManager.numLevels;
             slotButton[i].interactable = false;
         }
     }
 }
예제 #2
0
    /// <summary>
    /// Called by confirmMenu when returning.
    /// If gets success value, will create save the slot at number, else will do nothing
    /// </summary>
    /// <param name="retVal"></param>
    /// <param name="retString"></param>
    public override void _RespondToConfirm(int retVal, string retString)
    {
        switch (retVal)
        {
        case 0:
            if (GameManager.settings.saveNum <= 3 && GameManager.settings.saveNum >= 1 && GameManager.saveGame != null)                         // save existing game if it exists
            {
                SaveObj.SaveGame(GameManager.settings.saveNum, GameManager.saveGame);
            }

            GameManager.saveGame         = new SaveObj(!retString.Equals("") ? retString : "Slot " + number);
            GameManager.settings.saveNum = number;
            SaveObj.SaveGame(number, GameManager.saveGame);
            SettingsObj.saveSettings(GameManager.settings);
            if (GameManager.saveGame.levelNumber >= 0 && GameManager.saveGame.levelNumber < levelSelector.levelButtons.Length)
            {
                LevelSelector.changeLevelHelper(GameManager.saveGame.levelNumber);
                GameManager.changeState(GameManager.gameplay, this);
            }
            else
            {
                onClick(levelSelector);
            }
            break;

        default:                        // canceled, do nothing
            break;
        }
    }
예제 #3
0
    static string processTransform(Transform t, bool makeSubmeshes)
    {
        StringBuilder meshString = new StringBuilder();

        meshString.Append("#" + t.name
                          + "\n#-------"
                          + "\n");

        if (makeSubmeshes)
        {
            meshString.Append("g ").Append(t.name).Append("\n");
        }

        MeshFilter mf = t.GetComponent <MeshFilter>();

        if (mf)
        {
            meshString.Append(SaveObj.MeshToString(mf, t));
        }

        for (int i = 0; i < t.childCount; i++)
        {
            meshString.Append(processTransform(t.GetChild(i), makeSubmeshes));
        }

        return(meshString.ToString());
    }
예제 #4
0
	/// <summary>
	/// Load the save object from the file at the standard loaction and using the given number, if it exists
	/// </summary>
	/// <param name="saveNum"></param>
	/// <returns></returns>
	public static SaveObj LoadGame(int saveNum) {
		if (saveNum > 3 || saveNum < 1) {   // only use the save numbers 1-3
			throw new System.ArgumentException("Parameter saveNum should be in range [1,3]");
		}
		
		if (File.Exists(Application.persistentDataPath + "\\Save_" + saveNum + ".txt")) {	// can only load it if it exists
			Stream stream = null;
			try {   // don't want a file I/O exception to cause issues
				System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
				stream = new FileStream(Application.persistentDataPath + "\\Save_" + saveNum + ".txt", FileMode.Open, FileAccess.Read);
				SaveObj save = (SaveObj)formatter.Deserialize(stream);
				stream.Close();
				return save;
			} catch (System.Exception e) {
				Debug.Log(e.Message);   // notify me about any exceptions.
				if (stream != null) {   // make sure the stream is closed if an exception was generated.
					stream.Close();
				}
				return null;
			}
		} else {	// file does not exist, return null
			Debug.Log("Error: Save file " + saveNum + " not found.");
			return null;
		}
	}
예제 #5
0
        public void DeserArr(string xmlPath)
        {
            ArrayList people = new ArrayList();

            //people.Add(new Person("abc", "123"));

            //people.Add(new Person("def", "123"));
            SaveObj sj = new SaveObj();

            sj.A1   = 1;
            sj.A2   = 2;
            sj.s.B1 = 3;
            sj.s.B2 = 4;
            //List<SaveObj> people = new List<SaveObj>();

            people.Add(sj);
            SaveObj sj2 = new SaveObj();

            sj2.A1   = 11;
            sj2.A2   = 22;
            sj2.s.B1 = 33;
            sj2.s.B2 = 44;
            people.Add(sj2);
            //你需要告诉系统关于数组的信息

            XmlSerializer s =

                new XmlSerializer(typeof(ArrayList),

                                  new Type[] { typeof(SaveObj) });
            TextWriter w = new StreamWriter(xmlPath);

            s.Serialize(w, people);
            w.Close();
        }
예제 #6
0
 protected override void _StartState(IState oldstate)
 {
     this.gameObject.SetActive(true);
     firstSelected = returnButton;
     for (int i = 2; i >= 0; i--)             // for each potential save:
     {
         if (SaveObj.SaveExists(i + 1))       // if exists, set name and number-unlocked to match info in save, and make button non-interactible
         {
             SaveObj save = SaveObj.LoadGame(i + 1);
             slotNameText[i].text = save.slotName;
             int count = 0;
             for (int j = 0; j < GameManager.numLevels; j++)
             {
                 if (save.canAccess(j))
                 {
                     count++;
                 }
             }
             numUnlockedText[i].text    = count + "/" + GameManager.numLevels;
             slotButton[i].interactable = false;
         }
         else                    // else set text to defualt and set interactible
         {
             slotNameText[i].text       = "-";
             numUnlockedText[i].text    = "~/" + GameManager.numLevels;
             slotButton[i].interactable = true;
             firstSelected = slotButton[i];
         }
     }
     //resetSelected();
 }
예제 #7
0
    public void DoExport(bool makeSubmeshes)
    {
        string meshName = "SpatialMapping";
        string fileName = "cube.obj";

        SaveObj.Start();

        StringBuilder meshString = new StringBuilder();

        meshString.Append("#" + meshName + ".obj"
                          //  + "\n#" + System.DateTime.Now.ToLongDateString()
                          //  + "\n#" + System.DateTime.Now.ToLongTimeString()
                          + "\n#-------"
                          + "\n\n");
        Transform t = GameObject.Find("SpatialMapping").transform;
        Vector3   originalPosition = t.position;

        t.position = Vector3.zero;

        if (!makeSubmeshes)
        {
            meshString.Append("g ").Append(t.name).Append("\n");
        }
        meshString.Append(processTransform(t, makeSubmeshes));

        WriteToFile(meshString.ToString(), fileName);

        t.position = originalPosition;

        SaveObj.End();
        Debug.Log("Exported Mesh: " + fileName);
    }
예제 #8
0
 protected override void _StartState(IState oldstate)
 {
     this.gameObject.SetActive(true);
     if (GameManager.settings.saveNum < 1 ||                 // set up save slot info display
         GameManager.settings.saveNum > 3 ||
         !SaveObj.SaveExists(GameManager.settings.saveNum))
     {
         slotNameText.text              = "-";
         numUnlockedText.text           = "~/" + GameManager.numLevels;
         resumeButton.interactable      = false;     // set buttons unusable
         levelSelectButton.interactable = false;
         firstSelected = newGameButton;              // if resume/level select are greyed out, set newgame as default selected
     }
     else
     {
         slotNameText.text = GameManager.saveGame.slotName;
         int count = 0;
         for (int i = 0; i < GameManager.numLevels; i++)
         {
             if (GameManager.saveGame.canAccess(i))
             {
                 count++;
             }
         }
         numUnlockedText.text           = count + "/" + GameManager.numLevels;
         resumeButton.interactable      = true;      // set buttons accesible
         levelSelectButton.interactable = true;
         firstSelected = resumeButton;               // set as default selected button
     }
 }
예제 #9
0
    /// <summary>
    /// set up the dialog and return value on the ConfirmMenu
    /// </summary>
    /// <param name="num"></param>
    public void deleteSlot(int num)
    {
        // ask to confirm delete?
        number = num;
        SaveObj save = SaveObj.LoadGame(num);

        GameManager.confirmMenu.setupDialog(0, "Are you sure you want to delete the save file \"" + save.slotName + "\"", false, true);
    }
예제 #10
0
    private static string path;                 //путь к сохранению, позже будет заменено на клауд сохранение и код снизу немного видо исменится
    public void Awake()                         //при запуске приложения до старта
    {
        Save.datetimeachiv = DateTime.Now;
#if UNITY_ANDROID && !UNITY_EDITOR                                                             //проверка, что это андроид, и не юнити редактор
        path = Path.Combine(Application.persistentDataPath, "Save.json");                      //путь на андроиде в корневую папку
#else
        path = Path.Combine(Application.dataPath, "Save.json");                                //путь на компе в корневую папку
#endif
        if (File.Exists(path))                                                                 //если файл существует
        {
            obj                      = JsonUtility.FromJson <SaveObj>(File.ReadAllText(path)); //распаковываем файл в обьект
            Save.coins               = obj.coinsToSave;                                        //возвращаем значения
            Save.logs                = obj.logsToSave;
            Save.stone               = obj.stonesToSave;
            Save.emeralds            = obj.emeraldsToSave;
            Save.lvlBuildings        = obj.LvLsToSave;
            Save.DayUpdate           = obj.DayUpdateToSave;
            Save.countGetted         = obj.countGettedToSave;
            Save.countQuest          = obj.countquestToSave;
            Save.giveQuest           = obj.giveQuestToSave;
            Save.questcomplete       = obj.questcompletesave;
            Save.questgetted         = obj.questgettedsave;
            Save.resourseforquest    = obj.resourseforquestsave;
            Save.avatarid            = obj.skinidToSave;
            Save.achivlvl            = obj.achivlvlsave;
            Save.persent             = obj.persentsave;
            Save.treesAll            = obj.treesAllsave;
            Save.stonesAll           = obj.stonesAllsave;
            Save.cionsAll            = obj.cionsAllsave;
            Save.countlvlbuildings   = obj.countlvlbuildingssave;
            Save.donat               = obj.donatsave;
            Save.countview           = obj.countviewsave;
            Save.timeingame          = obj.timeingamesave;
            Save.exchangeAll         = obj.exchangeAllsave;
            Save.achiv1              = obj.achiv1ToSave;
            Save.achiv2              = obj.achiv2ToSave;
            Save.achiv3              = obj.achiv3ToSave;
            Save.achiv4              = obj.achiv4ToSave;
            Save.achiv5              = obj.achiv5ToSave;
            Save.TopScore3inRow      = obj.tsMiner;
            Save.TopScoreClicker     = obj.tsTimber;
            Save.TopScoreRunner      = obj.tsrunner;
            Save.isachiv             = obj.isachivsave;
            Save.isachivgetted       = obj.isgettedsave;
            Save.chanse              = obj.chansetosave;
            Save.rewive              = obj.rewivetosave;
            Save.isachivgettedreward = obj.isachivgettedreward;
            Save.islastgettedachiv   = obj.islastgettedachiv;
            Save.firstleft           = obj.firstleft;
            Save.firstmane           = obj.firstmane;
            Save.firstright          = obj.firstright;
            Save.everydayview        = obj.everydayview;
            Save.everydayreklam      = obj.everydayreklam;
            //Save.lvlsNow = obj.lvlsNowToSave;
            Debug.Log("time" + Save.timeingame[2] + ":" + Save.timeingame[1] + ":" + Save.timeingame[0]);
        }
    }
예제 #11
0
    public int index;           // changed this to use ints, so loading the levels from other scripts is easier
    // This is set when instatiating from prefab

    /*public void changeString(string s)
     * {
     * this.s = s;
     * }*/

    //This method is called on button pressed.
    public void doButtonThing()
    {
        //LevelSelector.changeLevel(s);
        //LevelSelector.changeLevel(index);
        if (index != GameManager.saveGame.levelNumber)                  // update and save the last level visited if it is different from the current last level visited.
        {
            GameManager.saveGame.levelNumber = index;
            SaveObj.SaveGame(GameManager.settings.saveNum, GameManager.saveGame);
        }
        LevelSelector.changeLevelHelper(index);                                // load level with given index number
        GameManager.changeState(GameManager.gameplay, LevelSelector.instance); // switch to game-mode
    }
예제 #12
0
        public void Serialize(string xmlPath)
        {
            SaveObj sj = new SaveObj();

            sj.A1   = 1;
            sj.A2   = 2;
            sj.s.B1 = 3;
            sj.s.B2 = 4;
            XmlSerializer s = new XmlSerializer(typeof(SaveObj));
            TextReader    r = new StreamReader(xmlPath);

            SaveObj person2 = (SaveObj)s.Deserialize(r);

            r.Close();
        }
예제 #13
0
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            ClearCubes();
        }

        if (Input.GetKeyDown(KeyCode.L))
        {
            ClearCubes();

            int numObjs = PreloadObjects();
            for (int i = 0; i < numObjs; ++i)
            {
                GameObject cubieboy = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubieboy.GetComponent <MeshRenderer>().material.color = Color.blue;
                cubieboy.AddComponent <BoxCollider>();
                cubieboy.tag = "Saveable";

                SaveObj data = LoadObject(i);

                cubieboy.transform.position   = data.position;
                cubieboy.transform.rotation   = Quaternion.Euler(data.rotation);
                cubieboy.transform.localScale = data.scale;
            }
        }


        if (Input.GetKeyDown(KeyCode.P))
        {
            //PushToSaveStack(transform.position, transform.rotation.eulerAngles, transform.localScale);
            GameObject[] objectsToSave = GameObject.FindGameObjectsWithTag("Saveable");
            foreach (GameObject go in objectsToSave)
            {
                SaveObj obj = new SaveObj();
                obj.position = go.transform.position;
                obj.rotation = go.transform.rotation.eulerAngles;
                obj.scale    = go.transform.localScale;

                PushToStack(obj);
            }
            Save();
            //if (!)
            //    Debug.Log("ERROR: Failed to save");
            //else
            Debug.Log("Save successful!");
        }
    }
예제 #14
0
 public static void LoadData(byte[] data)
 {
     obj                      = JsonUtility.FromJson <SaveObj>(Encoding.UTF8.GetString(data, 0, data.Length));
     Save.coins               = obj.coinsToSave;//возвращаем значения
     Save.logs                = obj.logsToSave;
     Save.stone               = obj.stonesToSave;
     Save.emeralds            = obj.emeraldsToSave;
     Save.lvlBuildings        = obj.LvLsToSave;
     Save.DayUpdate           = obj.DayUpdateToSave;
     Save.countGetted         = obj.countGettedToSave;
     Save.countQuest          = obj.countquestToSave;
     Save.giveQuest           = obj.giveQuestToSave;
     Save.questcomplete       = obj.questcompletesave;
     Save.questgetted         = obj.questgettedsave;
     Save.resourseforquest    = obj.resourseforquestsave;
     Save.avatarid            = obj.skinidToSave;
     Save.achivlvl            = obj.achivlvlsave;
     Save.persent             = obj.persentsave;
     Save.treesAll            = obj.treesAllsave;
     Save.stonesAll           = obj.stonesAllsave;
     Save.cionsAll            = obj.cionsAllsave;
     Save.countlvlbuildings   = obj.countlvlbuildingssave;
     Save.donat               = obj.donatsave;
     Save.countview           = obj.countviewsave;
     Save.timeingame          = obj.timeingamesave;
     Save.exchangeAll         = obj.exchangeAllsave;
     Save.achiv1              = obj.achiv1ToSave;
     Save.achiv2              = obj.achiv2ToSave;
     Save.achiv3              = obj.achiv3ToSave;
     Save.achiv4              = obj.achiv4ToSave;
     Save.achiv5              = obj.achiv5ToSave;
     Save.TopScore3inRow      = obj.tsMiner;
     Save.TopScoreClicker     = obj.tsTimber;
     Save.TopScoreRunner      = obj.tsrunner;
     Save.isachiv             = obj.isachivsave;
     Save.isachivgetted       = obj.isgettedsave;
     Save.chanse              = obj.chansetosave;
     Save.rewive              = obj.rewivetosave;
     Save.isachivgettedreward = obj.isachivgettedreward;
     Save.islastgettedachiv   = obj.islastgettedachiv;
     Save.firstleft           = obj.firstleft;
     Save.firstmane           = obj.firstmane;
     Save.firstright          = obj.firstright;
     Save.everydayview        = obj.everydayview;
     Save.everydayreklam      = obj.everydayreklam;
     //Save.lvlsNow = obj.lvlsNowToSave;
 }
예제 #15
0
            public async Task SaveObjF(SaveObj so, WebSocket webSocket, Random rm)
            {
                if (this.addModel)
                {
                    var index   = rm.Next(0, roomUrls.Count);
                    var roomUrl = roomUrls[index];
                    var sendMsg = Newtonsoft.Json.JsonConvert.SerializeObject(new SaveObjInfo()
                    {
                        c       = "SaveObjInfo",
                        amodel  = material[this.indexOfSelect].modelName,
                        modelID = this.ID,
                        rotatey = so.rotationY,
                        x       = so.x,
                        y       = so.y,
                        z       = so.z
                    });
                    await Startup.sendInmationToUrlAndGetRes(roomUrl, sendMsg);
                }
                else
                {
                    var index   = rm.Next(0, roomUrls.Count);
                    var roomUrl = roomUrls[index];
                    var sendMsg = Newtonsoft.Json.JsonConvert.SerializeObject(new UpdateObjInfo()
                    {
                        c       = "UpdateObjInfo",
                        modelID = this.ID,
                        rotatey = so.rotationY,
                        x       = so.x,
                        y       = so.y,
                        z       = so.z
                    });
                    await Startup.sendInmationToUrlAndGetRes(roomUrl, sendMsg);

                    ShowOBJFile sf = new ShowOBJFile()
                    {
                        c = "ShowOBJFile",
                        x = so.x,
                        z = so.z
                    };
                    await this.ShowObj(sf, webSocket, rm);
                }
                //var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonClass.MapEditor.Position>(json);
                //return obj;
                //  throw new NotImplementedException();
            }
예제 #16
0
        public void Deserialize(string xmlPath)
        {
            SaveObj sj = new SaveObj();

            sj.A1   = 1;
            sj.A2   = 2;
            sj.s.B1 = 3;
            sj.s.B2 = 4;

            //subObj sss=new subObj();
            //sss.B1 = 3;
            //sss.B2 = 4;
            XmlSerializer s = new XmlSerializer(typeof(SaveObj));

            TextWriter w = new StreamWriter(xmlPath);

            //sss = sj.s;
            s.Serialize(w, sj);

            w.Close();
        }
예제 #17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="num"></param>
 public void loadSlot(int num)
 {
     GameManager.saveGame = SaveObj.LoadGame(num);
     if (GameManager.saveGame == null)               // complain if save file doesn't exist/error
     // give file-doesn't exist notification here
     {
         Debug.Log("Error: Can't find save file \"" + num + "\"");
         return;
     }
     GameManager.settings.saveNum = num;                                                                                // set the last-save-used to this num, and save that change
     SettingsObj.saveSettings(GameManager.settings);
     if (GameManager.saveGame.levelNumber >= 0 && GameManager.saveGame.levelNumber < levelSelector.levelButtons.Length) // load straight to the last visited level if it exists
     {
         LevelSelector.changeLevelHelper(GameManager.saveGame.levelNumber);
         GameManager.changeState(GameManager.gameplay, this);
     }
     else
     {
         onClick(levelSelector);             // else, go to level selector
     }
 }
예제 #18
0
    /// <summary>
    /// Called by confirmMenu when returning.
    /// If gets success value, will delete the slot at number, else will do nothing
    /// </summary>
    /// <param name="retVal"></param>
    /// <param name="retString"></param>
    public override void _RespondToConfirm(int retVal, string retString)        // if get success va
    {
        switch (retVal)
        {
        case 0:                     // accept delete
            if (number == GameManager.settings.saveNum)
            {
                GameManager.settings.saveNum = 0;
                SettingsObj.saveSettings(GameManager.settings);
                GameManager.saveGame = null;
            }
            SaveObj.DeleteGame(number);
            //refresh();
            onClick(previous);
            break;

        default:                        // canceled, do nothing
            //refresh();
            break;
        }
    }
예제 #19
0
	/// <summary>
	/// Save the given save object at the standard location using the given integer in the name
	/// </summary>
	/// <param name="saveNum"></param>
	/// <param name="save"></param>
	public static void SaveGame(int saveNum, SaveObj save) {
		if (saveNum > 3 || saveNum < 1) {	// right now, only use three save slots total
			throw new System.ArgumentException("Parameter \"saveNum\" should be in range [1,3]");
		}
		if (save == null) {	// can't save the object if there is no object
			throw new System.ArgumentException("Parameter \"save\" cannot be null");
		}
		Stream stream = null;
		try {	// don't want a file I/O exception to cause issues
			System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			//Debug.Log("Saving to File: \"" + Application.persistentDataPath + "\\Save_" + saveNum + ".txt\"");
			stream = new FileStream(Application.persistentDataPath + "\\Save_" + saveNum + ".txt", FileMode.Create, FileAccess.Write);
			formatter.Serialize(stream, save);
			stream.Close();
		} catch (System.Exception e) {
			Debug.Log(e.Message);   // notify me about any exceptions.
			if (stream != null) {   // make sure the stream is closed if an exception was generated.
				stream.Close();
			}
		}
		return;
	}
예제 #20
0
        public void DeserList(string xmlPath)
        {
            SaveObj sj = new SaveObj();

            sj.A1   = 1;
            sj.A2   = 2;
            sj.s.B1 = 3;
            sj.s.B2 = 4;
            List <SaveObj> people = new List <SaveObj>();

            people.Add(sj);
            SaveObj sj2 = new SaveObj();

            sj2.A1   = 1;
            sj2.A2   = 2;
            sj2.s.B1 = 3;
            sj2.s.B2 = 4;
            people.Add(sj2);
            TextWriter    w = new StreamWriter(xmlPath);
            XmlSerializer s = new XmlSerializer(typeof(List <SaveObj>));

            s.Serialize(w, people);
            w.Close();
        }
예제 #21
0
 public static extern void PushToStack(SaveObj toSave);
예제 #22
0
    public void onArrive(bool canMove, Node otherNode, GameManager.Direction dir)
    {
        if (!canMove)
        {
            animLockout = false;
            return;
        }
        //Handle fake connection stacking
        {
            //If the connection from this node to the other is one-way
            if (otherNode[(int)dir.inverse()] != currentPosition.index)
            {
                // temp override connection to that node
                otherNode[(int)dir.inverse()] = currentPosition.index;
            }
        }

        if (hasBall)
        {
            //Tag the current square with line exit dir
            if (!otherNode.hasLeave)
            {
                currentPosition.leave    = dir;
                currentPosition.hasLeave = true;
                otherNode.enter          = dir.inverse();
                otherNode.hasEnter       = true;
                stringLeft--;
            }
            else
            {
                //Do a backup
                currentPosition.hasEnter = false;
                otherNode.hasLeave       = false;
                stringLeft++;
            }
        }

        currentPosition = otherNode;

#if UNITY_EDITOR    // if this is in the editor, call getCurrentNode() every time movement happens,
        // and apply copied colors and sprites to the new tile is currently drawing.
        if (editLevel != null)
        {
            editLevel.getCurrentNode();
            editLevel.drawTiles();              // only changes stuff if currently drawing
            //Debug.Log("calling getCurrentNode()...")
        }
        else
        {
            Debug.Log("Cannot call getCurrentNode(), there is no reference to editLevel script/object");
        }
#endif
        nonEuclidRenderer.HandleRender(dir, currentPosition);
        animLockout = false;
        setUItext();            // apply changes to UI text: string left, checkpoints.

        if (map.winConditions())
        {
            winTrigger = true;
            wintext.SetActive(true);                                              // make win text visible
            winSound.SetActive(true);                                             // play sound
            // play win sound here
            levelSelector.unlockLevel();                                          // unlocks next level
            GameManager.saveGame.levelNumber++;                                   // advance last level visited, so will auto-load next level
            SaveObj.SaveGame(GameManager.settings.saveNum, GameManager.saveGame); // save changes to levels accessible and last-level-visited
            //Debug.Log("You win!");
        }
        //if (currentPosition.hasSign && !signsVisited.Contains(currentPosition.index)) {
        if (currentPosition.type == Node.TileType.sign && !signsVisited.Contains(currentPosition.index))
        {
            signsVisited.Add(currentPosition.index);
            signText.text = currentPosition.signMessage;
            signImage.gameObject.SetActive(true);
        }
    }
예제 #23
0
    public void Awake()
    {
        #region finding objects/setting refferences
        if ((instance == null) || (instance == this))           // singleton pattern
        {
            instance = this;
        }
        else
        {
            Debug.Log("Duplicate GameManager destroyed");
            DestroyImmediate(this.gameObject);
        }

        IState[] objList = (IState[])Resources.FindObjectsOfTypeAll(typeof(IState));            // find all IState objects
        // should be easily tweakable to work when switching between scenes
        foreach (IState state in objList)
        {
            if (istates[(int)state._stateType] == null)                 // add one of each type to list of istates, delete any duplicates
            {
                istates[(int)state._stateType] = state;                 // the type enum is used to put each istate in a unique nd predictable slot
                state.gameObject.SetActive(false);
            }
            else
            {
                Debug.Log("Destroyed duplicate of IState " + state._stateType);
                DestroyImmediate(state.gameObject);
            }
        }
        for (int i = 0; i < istates.Length; i++)                // check that one of each type exists
        {
            if (istates[i] == null)
            {
                Debug.Log("Error: IState object of type \"" + (IStateType)i + "\" not found");
            }
            else
            {
                istates[i].initialize();                        // initialize each that exists
            }
        }

        ConfirmMenu[] conList = (ConfirmMenu[])Resources.FindObjectsOfTypeAll(typeof(ConfirmMenu));
        if (conList.Length > 0)
        {
            confirmMenu = conList[0];               // only use one copy of the ConfirmMenu object
            confirmMenu.gameObject.SetActive(false);
        }
        else
        {
            Debug.Log("Error: No ConfirmMenu object is exists");
        }
        for (int i = 1; i < conList.Length; i++)
        {
            DestroyImmediate(conList[i].gameObject);                                                // destroy extras
        }
        #endregion

        //settup spritebook & index
        spriteBook  = _spriteBook;                  // move info from non-static variables to static variables
        errorSprite = _errorSprite;
        for (int s = 0; s < spriteBook.Length; s++) // get the index and name of every sprite, so you can look them up by name
        {
            if (spriteBook[s] != null)
            {
                string lowercase = spriteBook[s].name.ToLowerInvariant();
                //Debug.Log(string.Format("Trying to add sprite {0} to sprite index", lowercase));
                if (!spriteIndex.ContainsKey(lowercase))                        // don't add any duplicate names
                {
                    spriteIndex.Add(lowercase, s);
                }
                else
                {
                    throw new System.Exception("Error: sprite with name" + spriteBook[s].name + " present in spritebook more than once");
                }
            }
        }

        // load settings stuff, and apply them.
        if (SettingsObj.settingsExists())               //load the settings if the file exists
        {
            settings = SettingsObj.loadSettings();
        }
        else                    // else create new file
        {
            Debug.Log("Creating new settings file");
            settings = new SettingsObj();
            SettingsObj.saveSettings(settings);
        }
        applySettings(settings);            // apply the saved settings
        // consider changing so that it keeps resolution settings from start-up menu

        // load from save if possible, or load default save.
        if (settings.saveNum >= 1 && settings.saveNum <= 3)             // if saveNum = 1, 2, or 3, savefile should exist, else one won't
        {
            saveGame = SaveObj.LoadGame(settings.saveNum);
            if (saveGame == null)
            {
                Debug.Log("Indicated save does not exist, load an existing save or create a new one.");
                settings.saveNum = 0;
                SettingsObj.saveSettings(settings);
            }
        }


        gameplay = (Gameplay)istates[(int)GameManager.IStateType.gameplay];     // get gameplay IState from istate[Enum.gameplay] slot of array

        if (istates[(int)GameManager.IStateType.gameMenu] != null)              // set current state to gamemenu, or complain if gameMenu istate doesn't exist
        {
            currentstate = istates[(int)GameManager.IStateType.gameMenu];
            currentstate.StartState(null);
            istates[(int)GameManager.IStateType.gameMenu].gameObject.SetActive(true);
        }

        //InputManager.instance.LoadKeybinds();   // load keybindings

        eventSystem = (EventSystem)FindObjectOfType(typeof(EventSystem));
    }
예제 #24
0
        private static async Task Echo(System.Net.WebSockets.WebSocket webSocket)
        {
            WebSocketReceiveResult wResult;

            {
                var returnResult = await ReceiveStringAsync(webSocket, webWsSize);

                wResult = returnResult.wr;
                Console.WriteLine($"receive from web:{returnResult.result}");
                var hash = CommonClass.Random.GetMD5HashFromStr(DateTime.Now.ToString("yyyyMMddHHmmss") + "yrq");
                {
                    /*
                     * 前台的汽车模型
                     */
                    var msg = Newtonsoft.Json.JsonConvert.SerializeObject(new
                    {
                        c    = "SetHash",
                        hash = hash
                    });
                    var sendData = Encoding.ASCII.GetBytes(msg);
                    await webSocket.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), WebSocketMessageType.Text, true, CancellationToken.None);
                }
                returnResult = await ReceiveStringAsync(webSocket, webWsSize);

                wResult = returnResult.wr;
                Console.WriteLine($"receive from web:{returnResult.result}");

                List <string> allowedAddress = new List <string>()
                {
                    "1NyrqneGRxTpCohjJdwKruM88JyARB2Ljr",
                    "1NyrqNVai7uCP4CwZoDfQVAJ6EbdgaG6bg"
                };
                bool signIsRight = false;
                //if (CommonClass.Format.IsBase64(returnResult.result))
                //{
                //    for (var i = 0; i < allowedAddress.Count; i++)
                //    {

                //        var address = allowedAddress[i];
                //        signIsRight = BitCoin.Sign.checkSign(returnResult.result, hash, address);
                //        if (signIsRight)
                //        {
                //            break;
                //        }
                //    }
                //}
                signIsRight = true;
                if (signIsRight)
                {
                    Random     rm = new Random(DateTime.Now.GetHashCode());
                    ModeManger mm = new ModeManger();
                    await mm.GetCatege(rm);

                    Dictionary <string, bool> roads = new Dictionary <string, bool>();
                    //stateOfSelection ss = stateOfSelection.roadCross;
                    //string roadCode;
                    //int roadOrder;
                    //string anotherRoadCode;
                    //int anotherRoadOrder;

                    var firstRoad = await getFirstRoad(rm);

                    //roadCode = firstRoad.roadCode;
                    //roadOrder = firstRoad.roadOrder;
                    //anotherRoadCode = firstRoad.anotherRoadCode;
                    //anotherRoadOrder = firstRoad.anotherRoadOrder;
                    await SetView(firstRoad, webSocket);

                    roads = await Draw(firstRoad, roads, webSocket, rm);

                    stateOfSelection ss = stateOfSelection.roadCross;
                    do
                    {
                        try
                        {
                            returnResult = await ReceiveStringAsync(webSocket, webWsSize);

                            wResult = returnResult.wr;
                            Console.WriteLine($"receive from web:{returnResult.result}");
                            //CommonClass.Command
                            var c = Newtonsoft.Json.JsonConvert.DeserializeObject <CommonClass.Command>(returnResult.result);
                            if (c.c == "change")
                            {
                                // if(ss==stateOfSelection)
                                if (ss == stateOfSelection.roadCross)
                                {
                                    ss = stateOfSelection.modelEdit;
                                }
                                else
                                {
                                    ss = stateOfSelection.roadCross;
                                }
                                await SetState(ss, webSocket);

                                continue;
                            }
                            else if (c.c == "ShowOBJFile")
                            {
                                ShowOBJFile sf = Newtonsoft.Json.JsonConvert.DeserializeObject <CommonClass.MapEditor.ShowOBJFile>(returnResult.result);
                                await mm.ShowObj(sf, webSocket, rm);

                                continue;
                            }
                            switch (ss)
                            {
                            case stateOfSelection.roadCross:
                            {
                                // var c = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonClass.Command>(returnResult.result);
                                switch (c.c)
                                {
                                case "nextCross":
                                {
                                    firstRoad = await getNextCross(firstRoad, rm);
                                }; break;

                                case "previousCross":
                                {
                                    firstRoad = await getPreviousCross(firstRoad, rm);
                                }; break;

                                case "changeRoad":
                                {
                                    var secondRoad = new Position()
                                    {
                                        anotherRoadCode  = firstRoad.roadCode,
                                        anotherRoadOrder = firstRoad.roadOrder,
                                        roadCode         = firstRoad.anotherRoadCode,
                                        roadOrder        = firstRoad.anotherRoadOrder,
                                        c         = "Position",
                                        latitude  = firstRoad.latitude,
                                        longitude = firstRoad.longitude
                                    };
                                    firstRoad = secondRoad;
                                }; break;
                                    //case "addModel":
                                    //    {

                                    //        var secondRoad = new Position()
                                    //        {
                                    //            anotherRoadCode = firstRoad.roadCode,
                                    //            anotherRoadOrder = firstRoad.roadOrder,
                                    //            roadCode = firstRoad.anotherRoadCode,
                                    //            roadOrder = firstRoad.anotherRoadOrder,
                                    //            c = "Position",
                                    //            latitude = firstRoad.latitude,
                                    //            longitude = firstRoad.longitude
                                    //        };
                                    //        firstRoad = secondRoad;
                                    //    }; break;
                                }
                                await SetView(firstRoad, webSocket);

                                roads = await Draw(firstRoad, roads, webSocket, rm);
                            }; break;

                            case stateOfSelection.modelEdit:
                            {
                                switch (c.c)
                                {
                                case "AddModel":
                                {
                                    mm.addModel = true;
                                    var m = await mm.GetModel(rm);

                                    await mm.AddModel(m, webSocket);
                                }; break;

                                case "PreviousModel":
                                {
                                    mm.PreviousModel();
                                    if (mm.addModel)
                                    {
                                        var m = await mm.GetModel(rm);

                                        await mm.AddModel(m, webSocket);
                                    }
                                }; break;

                                case "NextModel":
                                {
                                    mm.NextModel();
                                    if (mm.addModel)
                                    {
                                        var m = await mm.GetModel(rm);

                                        await mm.AddModel(m, webSocket);
                                    }
                                }; break;

                                case "PreviousCategory":
                                {
                                    mm.PreviousCategory();
                                    if (mm.addModel)
                                    {
                                        var m = await mm.GetModel(rm);

                                        await mm.AddModel(m, webSocket);
                                    }
                                }; break;

                                case "NextCategory":
                                {
                                    mm.NextCategory();
                                    if (mm.addModel)
                                    {
                                        var m = await mm.GetModel(rm);

                                        await mm.AddModel(m, webSocket);
                                    }
                                }; break;

                                case "SaveObj":
                                {
                                    SaveObj so = Newtonsoft.Json.JsonConvert.DeserializeObject <SaveObj>(returnResult.result);
                                    await mm.SaveObjF(so, webSocket, rm);
                                }; break;

                                case "EditModel":
                                {
                                    mm.addModel = false;
                                    EditModel em = Newtonsoft.Json.JsonConvert.DeserializeObject <EditModel>(returnResult.result);
                                    mm.ID = em.name;
                                    await mm.EditModel(webSocket);
                                }; break;

                                case "DeleteModel":
                                {
                                    mm.addModel = false;
                                    DeleteModel dm = Newtonsoft.Json.JsonConvert.DeserializeObject <DeleteModel>(returnResult.result);
                                    mm.ID = dm.name;
                                    await mm.DeleteModel(webSocket, dm, rm);
                                }; break;
                                }
                            }; break;
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"{ Newtonsoft.Json.JsonConvert.SerializeObject(e)}");
                            //await Room.setOffLine(s);
                            //removeWs(s.WebsocketID);
                            // Console.WriteLine($"step2:webSockets数量:{   BufferImage.webSockets.Count}");
                            // return;
                            throw e;
                        }
                    }while (!wResult.CloseStatus.HasValue);
                }
            };
        }