/// <summary> /// Save the current game state to a file for later loading /// </summary> public void SaveGame() { //Save game state to our static variable SerializableGame memento = SaveToMemento(); // Open the file where we would serialize. FileStream fs = new FileStream(MainMenu.SaveGameDataPath, FileMode.OpenOrCreate); // Construct a BinaryFormatter and use it to serialize the data to the stream. BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(fs, memento); StartCoroutine(Helpers.ShowPopUpMessage(gameSavedPopup, 0.3f, 1, 0.3f, "Game saved")); } catch (SerializationException ex) { //Debug.Log("Failed to serialize. Reason: " + ex.Message); //throw ex; StartCoroutine(Helpers.ShowPopUpMessage(gameSavedPopup, 0.3f, 1, 0.3f, (string.Format("Unable to save game ({0})", ex.Message)))); } finally { fs.Close(); } }
/// <summary> /// Prepares the game for entering the minigame. This means respawning the PVC and saving the /// game state to allow restoring later. This function will also show a loading panel so /// the player knows what is going on. /// </summary> public void PrepareForMinigame() { PvcDiscoveredByLast = currentPlayer; SpawnPVC(); GameToRestore = SaveToMemento(); minigameLoading.SetActive(true); }
internal static SerializableGame NewGame(int playerCount) { SerializableGame result = new SerializableGame(); //{ result.currentPosition = new SerializableVector3(0, 0, 0); result.currentRotation = new SerializableVector3(0, 0, 0); result.currentScene = 1; GameObject configObject = GameObject.FindGameObjectWithTag("New Game"); NewGameConfig config = configObject.GetComponent <NewGameConfig>(); config.InstantiateGame(playerCount); List <Frame> frames = config.InstantiateGame(playerCount); List <SerializedFrame> serializedFrames = new List <SerializedFrame>(); foreach (Frame frame in frames) { serializedFrames.Add(frame.SerializeTo(result)); } foreach (SerializedFrame frame in serializedFrames) { frame.scene = 1; } return(result); }
public void StartNewGame(int playerCount) { _loadingScreen.Show(1.0f); SerializableGame newGameData = SerializableGame.NewGame(playerCount); StartCoroutine(loadGame(newGameData, 1.0f)); }
public static void Save(SerializableGame data, string saveGameName) { BinaryFormatter bf = new BinaryFormatter(); FileStream files = File.Open(Application.persistentDataPath + "/" + saveGameName + PLAYER_DATA_FILE_ENDING, FileMode.OpenOrCreate); bf.Serialize(files, data); files.Close(); }
public static bool Load(string saveGameName, out SerializableGame data) { if (File.Exists(Application.persistentDataPath + "/" + saveGameName + PLAYER_DATA_FILE_ENDING)) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/" + saveGameName + PLAYER_DATA_FILE_ENDING, FileMode.Open); data = (SerializableGame)bf.Deserialize(file); file.Close(); return(true); } data = new SerializableGame(); return(false); }
public static void SaveGame(SerializableGame game, int slot) { using (FileStream fs = new FileStream(GetSavePath(slot), FileMode.OpenOrCreate)) { try { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, game); } catch (SerializationException ex) { Debug.Log("Failed to serialize. Reason: " + ex.Message); throw ex; } } }
public void LoadGame(SerializableGame sg) { bossName = sg.bossName; age = sg.age; money = sg.money; policemanKilled = sg.policemanKilled; employedKilled = sg.employedKilled; robberies = sg.robberies; arrested = sg.arrested; full = sg.full; int count = banks.Count; for (int i = 0; count > i; i++) { banks [i].securityLevel = sg.banks [i]; } }
private IEnumerator loadGame(SerializableGame data, float delay = 0.0f) { yield return(new WaitForSeconds(delay)); _currentGame = data; AsyncOperation async = SceneManager.LoadSceneAsync(data.currentScene); while (!async.isDone) { _loadingScreen.SetProgress(Mathf.Clamp01(async.progress / 0.9f)); yield return(null); } _generalGuiPage.Show(); _loadingScreen.Hide(1.0f); NeverdawnCamera.HideGrid(); yield return(new WaitForSeconds(1.0f)); }
internal SerializedFrame SerializeTo(SerializableGame data) { if (data == null) { return(null); } data[id] = new SerializedFrame() { id = id, prefab = prefab, scene = SceneManager.GetActiveScene().buildIndex, destroyed = destroyed, position = SerializableVector3.FromVector3(transform.position), rotation = SerializableVector3.FromVector3(transform.eulerAngles), componentData = SerializeComponents() }; return(data[id]); }
public void RestoreMemento(SerializableGame memento) { _processEvents = memento.processEvents; // load map so we have access to actual sectors LoadMapObject(); // just load map object using default system for now // restore all the players Players.RestoreMemento(memento.playerManager); _currentPlayerId = memento.currentPlayerId; // restore all the sectors Map.RestoreMemento(memento.map); enabled = true; EndTurnButtonEnabled = true; if (MinigameRewardApply != null) // if a minigame reward exists, then apply it to the player StartCoroutine(ApplyReward()); CurrentPlayer.Gui.IsActive = true; UpdateGUI(); }
internal void Initialize(SerializableGame game) { foreach (InputModule module in DeviceController.inputModules) { if (!moduleInUse(module)) { createAvatarController(module); } } foreach (AvatarController controller in controllers) { if (controller.character == null) { controller.character = GameController.instance.party[controller.preferredCharacterId]; if (controller.character != null) { controller.character.solid.Show(); controller.character.GetComponentInChildren <NavMeshAnimator>().Reset(); NeverdawnCamera.AddTargetLerped(controller.character.transform); } else { Debug.LogWarning("A character was lost during scene transition"); return; } } } foreach (AvatarController controller in controllers) { controller.character.position = game.currentPosition.ToVector3(); controller.character.eulerAngles = game.currentRotation.ToVector3(); } DeviceController.onModuleActivated -= createAvatarController; DeviceController.onModuleActivated += createAvatarController; }
IEnumerator FetchGame() { UnityWebRequest request = UnityWebRequest.Get(APIConfiguration.HostURL + APIConfiguration.GameRoute); yield return(request.SendWebRequest()); if (request.isNetworkError || request.isHttpError) { StartCoroutine(FetchGame()); } else { string text = request.downloadHandler.text; SerializableGame game = JsonUtility.FromJson <SerializableGame>(text); Game.State = (GameState)Enum.Parse(typeof(GameState), game.state, true); Game.EndTime = DateTime.Parse(game.endTime); Game.Round = game.round; Game.Mode = !string.IsNullOrEmpty(game.mode) ? (GameMode)Enum.Parse(typeof(GameMode), game.mode, true) : GameMode.None; OnGameUpdated.Raise(); } }
/// <summary> /// Restores the game state from a memento. This is the top level memento handler, /// meaning that the entire game state can be restored from the given memento. /// </summary> /// <param name="memento">The memento to restore.</param> public void RestoreFromMemento(SerializableGame memento) { turnState = memento.turnState; Sector[] sectors = gameMap.GetComponentsInChildren <Sector>(); for (int i = 0; i < memento.sectors.Length; i++) { sectors[i].RestoreFromMemento(memento.sectors[i], players); } for (int i = 0; i < memento.players.Length; i++) { players[i].RestoreFromMemento(memento.players[i]); players[i].Game = this; players[i].Gui.Initialize(players[i], i + 1); } currentPlayer = players[memento.currentPlayerId]; currentPlayer.Gui.Activate(); if (memento.lastDiscovererOfPvcId.HasValue) { PvcDiscoveredByLast = players[memento.lastDiscovererOfPvcId.Value]; } MinigameFinishedProcess(); UpdateGUI(); }
public SerializableGame SerializeGame() { SerializableGame sg = new SerializableGame(); sg.banks = new List <int> (); sg.bossName = bossName; sg.age = age; sg.money = money; sg.policemanKilled = policemanKilled; sg.employedKilled = employedKilled; sg.robberies = robberies; sg.arrested = arrested; sg.full = full; int count = banks.Count; Debug.Log(count); for (int i = 0; count > i; i++) { Debug.Log("iterazione"); sg.banks.Add(banks[i].securityLevel); } return(sg); }
public void SaveLoadTest() { // set up a game state Game.HumanPlayersCount = new List <int> { 0, 1, 0, 1 }; game.Initialize(); Game.HumanPlayersCount = null; map.sectors[0].Unit = InitUnit(2); map.sectors[0].Unit.Owner = players[2]; map.sectors[0].Unit.LevelUp(); map.sectors[0].Unit.LevelUp(); int unitLevel = map.sectors[0].Unit.Level; map.sectors[0].Owner = players[2]; map.sectors[1].Owner = players[1]; // test saving SerializableGame memento = game.SaveToMemento(); // clear game UnitTestsUtil.TearDownGameTest(ref game, ref map, ref players, ref gui); // re-init game to make it *fresh* UnitTestsUtil.SetupGameTest(out game, out map, out players, out gui); // test loading game.RestoreFromMemento(memento); // test if game restored properly Assert.That(players[0].IsHuman); Assert.That(players[1].IsHuman, Is.False); Assert.That(players[2].IsHuman); Assert.That(players[3].IsHuman, Is.False); Assert.That(map.sectors[0].Unit, Is.Not.Null); Assert.That(map.sectors[0].Unit.Owner, Is.EqualTo(players[2])); Assert.That(map.sectors[0].Unit.Level, Is.EqualTo(unitLevel)); Assert.That(map.sectors[1].Owner, Is.EqualTo(players[1])); }
/// <summary> /// Deserializes a set of serialized frames into the scene /// </summary> /// <param name="frames"></param> internal static void DeserializeFrames(SerializableGame gameData, int sceneBuildIndex) { SerializableGame data = GameController.instance.currentGame; // Create a dictionarry with ALL saved frames foreach (SerializedFrame serializedFrame in gameData.frames) { data[serializedFrame.id] = serializedFrame; } _frames = new List <Frame>(); _frames.AddRange(FindObjectsOfType <Frame>()); // Check the current scene of all stationary frames foreach (Frame frame in _frames) { if (data.ContainsKey(frame.id)) { SerializedFrame serializedFrame = data[frame.id]; // stationary is not in the scene.. if (serializedFrame.scene != sceneBuildIndex) { Destroy(frame.gameObject); } } } SerializedFrame[] sceneFrames = gameData.GetFramesBySceneBuildIndex(sceneBuildIndex); // Create all the frames needed in the scene foreach (SerializedFrame serializedFrame in sceneFrames) { Frame frame = FindFrameById(serializedFrame.id); // If the frame doesn't exist in the level yet, create it! if (frame == null) { // If the frame has been destroyed in the last session, we won't need it ever again! if (serializedFrame.destroyed) { data.Remove(serializedFrame.id); continue; } frame = Instantiate(NeverdawnDatabase.GetPrefab(serializedFrame.prefab)); } if (serializedFrame.destroyed) { Destroy(frame.gameObject); continue; } frame.id = serializedFrame.id; frame.prefab = serializedFrame.prefab; frame.transform.position = serializedFrame.position.ToVector3(); frame.transform.eulerAngles = serializedFrame.rotation.ToVector3(); frame.Init(); } // Load the frame components foreach (SerializedFrame serializedFrame in sceneFrames) { Frame frame = FindFrameById(serializedFrame.id); frame.DeserializeComponents(serializedFrame.componentData); } }
/// <summary> /// To save the game, with the specified file name /// </summary> /// <param name="FileName">The file name without path</param> public static void SaveAll(string FileName) { SerializableGame.SaveAll(FileName); current.Saved = true; }
/// <summary> /// To load the game, with the specified file name /// </summary> /// <param name="FileName">The file name without path</param> public static void LoadAll(string FileName) { SerializableGame.Load(FileName); current.Loaded = true; }
internal void Initialize(SerializableGame data) { instance = this; }