public void SaveGame(SaveGame save, string filename) { BinaryFormatter bf = new BinaryFormatter (); // then create a file stream that can be opened or created, with write access to it FileStream fs = File.OpenWrite (Application.persistentDataPath + "/" + filename + ".dat"); // set up our data before writing, and we assume we have access to the game model GameObject Player = GameObject.FindGameObjectWithTag ("Player"); GameObject Boat = GameObject.FindGameObjectWithTag ("Boat"); sg.PlayerPos = Player.GetComponent<Transform> ().localPosition; sg.Health = Player.GetComponent<ResourceHandler> ().health; sg.Water = Player.GetComponent<ResourceHandler> ().hydration; sg.Lumber = Player.GetComponent<ResourceHandler> ().lumber; sg.Palm = Player.GetComponent<ResourceHandler> ().Palm; sg.Stone = Player.GetComponent<ResourceHandler> ().stone; sg.String = Player.GetComponent<ResourceHandler> ().String; sg.Axe = Player.GetComponent<ResourceHandler> ().axeON; sg.Coconut = Player.GetComponent<ResourceHandler> ().Coconut; sg.BoatPOS = Boat.GetComponent<Transform> ().localPosition; // now write our stuff bf.Serialize (fs, save); fs.Close (); }
public IGame SaveGame(IGame game) { var winner = GetPlayerById(game.Winner.Id); var loser = GetPlayerById(game.Loser.Id); var dbGame = GameFactory.MakeGame(game); var command = new SaveGame(dbGame); _executer.Execute(command); dbGame.Winner = winner; dbGame.Loser = loser; return command.Result; }
private void loadSaveGameToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog d = new OpenFileDialog(); d.Filter = "*.MassEffectSave|*.MassEffectSave"; if (d.ShowDialog() == DialogResult.OK) { Save = new SaveGame(d.FileName); Save.Loaded = true; LoadData(); } }
public void SaveGame() { SaveGame game = new SaveGame (); game.x = button.transform.position.x; game.y = button.transform.position.y; game.z = button.transform.position.z; BinaryFormatter bf = new BinaryFormatter (); FileStream fs = File.Open (Application.persistentDataPath+ "/saveGame.Steve", FileMode.OpenOrCreate); bf.Serialize (fs, game); fs.Close (); }
void Awake() { if (save == null) { save = this; DontDestroyOnLoad(this.gameObject); } else { Destroy(this.gameObject); } //print(Application.persistentDataPath); }
private void loadSaveGameToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog d = new OpenFileDialog(); d.Filter = "*.MassEffectSave|*.MassEffectSave"; if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK) { BitConverter.IsLittleEndian = true; Save = new SaveGame(d.FileName); Save.Loaded = true; LoadData(); } }
public void Save() { BinaryFormatter binary = new BinaryFormatter(); FileStream fstream = File.Create(Application.persistentDataPath + "/Game.dat"); SaveGame sg = new SaveGame(); GameObject lsContainer = GameObject.FindWithTag("LevelSystem"); LevelSystem ls = lsContainer.GetComponent<LevelSystem>(); sg.level = ls.Level; sg.experience = ls.Experience; sg.neededExperience = ls.NeededExperience; binary.Serialize(fstream, sg); fstream.Close(); }
void Start() { itemDatabase = GameObject.FindGameObjectWithTag("ItemDatabase").GetComponent<ItemDatabase>(); inventory = GameObject.FindGameObjectWithTag("Player").GetComponent<Inventory>(); if(File.Exists(Application.persistentDataPath+"/saveGame.serious")) { print("SaveGame Exists"); save = SaveLoad.Load(); itemDatabase.items = save.itemDatabaseItems; inventory.inventoryItems = save.inventoryItems; inventory.equippedItems = save.equippedItems; //inventory.RefreshInventoryVisuals(); //inventory.RefreshEquippedVisuals(); } }
public static void Save(SaveGame save) { BinaryFormatter bf = new BinaryFormatter(); //surrogate serializer setup. SurrogateSelector ss = new SurrogateSelector(); ColorSerializationSurrogate css = new ColorSerializationSurrogate(); ss.AddSurrogate(typeof(Color),new StreamingContext(StreamingContextStates.All),css); //use surrogate selector. bf.SurrogateSelector = ss; FileStream file = File.Create(Application.persistentDataPath+"/saveGame.serious"); bf.Serialize(file, save); file.Close (); Debug.Log(Application.persistentDataPath+"/saveGame.serious"); }
public static void Save(SaveGame currentSaveGame) { try { savedGames.Add(currentSaveGame); BinaryFormatter binaryFormatter = new BinaryFormatter(); FileStream saveFile = File.Create(Application.persistentDataPath + "/AsteroidSaveGame.asg"); binaryFormatter.Serialize(saveFile, SaveHandler.savedGames); saveFile.Close(); MonoBehaviour.print("FLAG : Saved"); //DEBUG } catch { Debug.Log("ERROR : Unable to save"); } }
public static bool SaveGame(SaveGame saveGame, string name) { BinaryFormatter formmater = new BinaryFormatter(); using(FileStream stream = new FileStream(GetSavePath(name), FileMode.Create)) { try { formmater.Serialize(stream, saveGame); } catch (Exception e) { Debug.LogError(e); return false; } } return true; }
private void openSaveGameToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog d = new OpenFileDialog(); d.Filter = "*.MassEffectSave|*.MassEffectSave"; if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK) { MemoryStream m = new MemoryStream(); FileStream fs = new FileStream(d.FileName, FileMode.Open, FileAccess.Read); int len = (int)fs.Length; byte[] buff = new byte[len]; fs.Read(buff, 0, len); m.Write(buff, 0, len); fs.Close(); Save = new SaveGame(); Save.complete = m; BitConverter.IsLittleEndian = true; m.Seek(8, SeekOrigin.Begin); int off = ReadInt(m); int len2 = len - off; m.Seek(off, SeekOrigin.Begin); buff = new byte[len2]; m.Read(buff, 0, len2); Save.zipfile = new MemoryStream(buff); Save.zipfile.Seek(0, SeekOrigin.Begin); ZipFile zip = ZipFile.Read(Save.zipfile); Save.Files = new List<SaveFileEntry>(); foreach (ZipEntry file in zip) { SaveFileEntry ent = new SaveFileEntry(); ent.FileName = file.FileName; ent.memory = new MemoryStream(); file.Extract(ent.memory); Save.Files.Add(ent); } Save.zip = zip; RefreshList(); } }
public void GetSavedGames() { //Get saved games is ran during the game select screen, this grabs the base file //of all of our game saves myLoadedGames.Clear (); //my loaded games is a list that holds games 1-3, we store those in a static list for easy access if (_gamesInstance == null) { _gamesInstance = new MyGames (); //if we don't have an instance of _gamesIntance, make a new one //just to store data in when we load the file } if (GameSaver == null) { GameSaver = SaveGame.GetGameSaver; //if we don't have a refrence to the GameSaver, get one //This will also make GameSaver finding itself it has not yet //found an instance of itself } _gamesInstance = GameSaver.GetMyGames (); //GameSaver.GetMyGames will return our full save file, which are storing in the //local variable, _gamesInstance myLoadedGames.Add (_gamesInstance.GameOne); //once we have our game file, add each save to the list myLoadedGames.Add (_gamesInstance.GameTwo); //we don't technically need to do this, I was just doing it myLoadedGames.Add (_gamesInstance.GameThree); //for ease of testing. }
void Awake() { directory = "/Resources/SaveGames"; saveGames = new List<SaveGame>(); canvas = GetComponentInChildren<Canvas>(); image = canvas.GetComponentInChildren<Image>().sprite; buttonSpace = 8; if(!Directory.Exists(Application.dataPath + directory)) { Directory.CreateDirectory(Application.dataPath + directory); } DirectoryInfo dir = new DirectoryInfo(Application.dataPath + directory); FileInfo[] info = dir.GetFiles("*.xml"); foreach(FileInfo fileInfo in info) { SaveGame saveGame = new SaveGame(fileInfo.Name.Replace(".xml", ""), fileInfo.FullName, fileInfo.DirectoryName + "/" + fileInfo.Name.Replace(".xml", "")); saveGames.Add(saveGame); int ID = System.Array.IndexOf(info, fileInfo); CreateSaveGameButtons(saveGame, ID); } }
public void Save() { this.saveSettings.EncryptionPassword = this.password.text; SaveGame.Save(this.identifier, this.dataField.text, this.saveSettings); Debug.Log("Encrypted Data has been saved successfully"); }
/// <summary> /// Saves to slot. /// </summary> /// <param name="SlotNo">Slot no.</param> private void SaveToSlot(int SlotNo) { //if (_RES==GAME_UW2) //{ // UWHUD.instance.MessageScroll.Add("Saving only supported in UW1"); // return; //} //000~001~159~Impossible, you are between worlds. \n if ((_RES == GAME_UW1) && (GameWorldController.instance.LevelNo == 8)) { UWHUD.instance.MessageScroll.Add(StringController.instance.GetString(1, StringController.str_impossible_you_are_between_worlds_)); return; } if (!Directory.Exists(Loader.BasePath + "SAVE" + (SlotNo + 1))) { Directory.CreateDirectory(Loader.BasePath + "SAVE" + (SlotNo + 1)); } //Write a player.dat file if (_RES == GAME_UW2) { //Write lev.ark file and object lists LevArk.WriteBackLevArkUW2(SlotNo + 1); //Write bglobals.dat GameWorldController.instance.WriteBGlobals(SlotNo + 1); //Write a desc file File.WriteAllText(Loader.BasePath + "SAVE" + (SlotNo + 1) + sep + "DESC", SaveGame.SaveGameName(SlotNo + 1)); //Write player.dat SaveGame.WritePlayerDatUW2(SlotNo + 1); //TODO:Write scd.ark } else { //Write lev.ark file and object lists LevArk.WriteBackLevArkUW1(SlotNo + 1); //Write bglobals.dat GameWorldController.instance.WriteBGlobals(SlotNo + 1); //Write a desc file File.WriteAllText(Loader.BasePath + "SAVE" + (SlotNo + 1) + sep + "DESC", SaveGame.SaveGameName(SlotNo + 1)); //Write player.dat SaveGame.WritePlayerDatUW1(SlotNo + 1); // SaveGame.WritePlayerDatOriginal(SlotNo+1); } UWHUD.instance.MessageScroll.Set(StringController.instance.GetString(1, StringController.str_save_game_succeeded_)); UWHUD.instance.RefreshPanels(UWHUD.HUD_MODE_INVENTORY); ReturnToGame(); }
//Adding stuf for Save system lern more about it here https://www.youtube.com/watch?v=XOjd_qU2Ido public void SaveData() { SaveGame.saveData(this); }
public void Save() { SaveGame.Save <int>("currenthp", playerCurrentHealth); SaveGame.Save <int>("maxhp", playerMaxHealth); }
private void Awake() { saveGame = Saver.Load(); }
public override void Save(int index) { base.Save(index); SaveGame.SaveVal("TrapArmed" + index, this.m_Armed); SaveGame.SaveVal("TrapAI" + index, (int)((!this.m_AI) ? AI.AIID.None : this.m_AI.m_ID)); }
public void Save() { SaveGame.Save(); }
// Use this for initialization void Start() { Reset(); SG = new SaveGame(); SG.LoadGameData(); }
protected virtual void OnApplicationQuit() { SaveGame.Save <int>("serializer", value, false, "", new SaveGameJsonSerializer(), null, SaveGame.DefaultEncoding, SaveGame.SavePath); }
void LoadFromDevice() { //added by chad loadData = new SaveGame(); try { XmlSerializer reader = new XmlSerializer(typeof(SaveGame)); if (File.Exists(filename)) { using (FileStream input = File.OpenRead(filename)) { StreamReader read = new StreamReader(filename); loadData = (SaveGame)reader.Deserialize(read); read.Close(); } } } catch (InvalidOperationException) { Console.WriteLine("Your mom is an invalid operation, when loading data from SaveLoadScreen"); loadData = new SaveGame(); } }
//MÅSTE LÖSA SÅ ATT BANAN SPARAS OCKSÅ. public void SaveToDevice(IAsyncResult result) { device = StorageDevice.EndShowSelector(result); if (device != null && device.IsConnected) { SaveGame SaveData = new SaveGame(); { SaveData.playerHealthPoints = m_player.GetLife(); } IAsyncResult r = device.BeginOpenContainer(containerName, null, null); result.AsyncWaitHandle.WaitOne(); StorageContainer container = device.EndOpenContainer(r); if (container.FileExists(filename)) container.DeleteFile(filename); Stream stream = container.CreateFile(filename); XmlSerializer serializer = new XmlSerializer(typeof(SaveGame)); serializer.Serialize(stream, SaveData); stream.Close(); container.Dispose(); result.AsyncWaitHandle.Close(); } }
void Awake() { if (sg == null) { instance = this.gameObject; sg = new SaveGame (); DontDestroyOnLoad (gameObject); } else { //Destroy (gameObject); } //sg.Health = 100; //sg.Water = 100; }
// ####################################################################################################################################### Buttons /// <summary> /// Press savegame /// </summary> /// <param name="ID"></param> public void LoadSavegame(int ID) { SelectedID = ID; SaveGame save = SaveGame.Load(ID); LoadedSaveGame = save; if (save.ID == 0) { mm.Navigate(menu_main.menu_main_state.NewGame, menu_main.menu_sound.Click); } else { mm.Navigate(menu_main.menu_main_state.LoadGame, menu_main.menu_sound.Click); } }
public void LoadGame() { sg = LoadGame (filename); Application.LoadLevel ("Game"); }
public static void update() { // Really don't understand why it breaks without this // But as soon as you get to the second day, it does. Ugh. Game1.player.FarmerSprite.setOwner(Game1.player); // Or in this case, as soon as you load the game. fixDisposedFarmerTexture(Game1.player); if (Multiplayer.mode == Mode.Singleplayer) { return; } if (MultiplayerUtility.latestID > prevLatestId) { sendFunc(new LatestIdPacket()); } prevLatestId = MultiplayerUtility.latestID; //Log.Async("pos:" + Game1.player.position.X + " " + Game1.player.position.Y); // Clients sometimes get stuck in the top-right corner and can't move on second day+ if (Game1.player.currentLocation != null && Game1.player.currentLocation.name == "FarmHouse" && Game1.player.currentLocation == Game1.currentLocation && Game1.player.currentLocation != Game1.getLocationFromName(Game1.player.currentLocation.name)) { Game1.player.currentLocation = Game1.getLocationFromName(Game1.player.currentLocation.name); Game1.currentLocation = Game1.player.currentLocation; Game1.currentLocation.resetForPlayerEntry(); } if (Game1.newDay) { didNewDay = true; Game1.freezeControls = prevFreezeControls = true; Game1.player.CanMove = false; if (!sentNextDayPacket) { ChatMenu.chat.Add(new ChatEntry(null, Game1.player.name + " is in bed.")); if (mode == Mode.Host) { server.broadcast(new ChatPacket(255, Game1.player.name + " is in bed.")); } else if (mode == Mode.Client) { client.stage = Client.NetStage.Waiting; try { SaveGame oldLoaded = SaveGame.loaded; var it = NewSaveGame.Save(true); while (it.Current < 100) { it.MoveNext(); Thread.Sleep(5); } foreach (GameLocation loc in SaveGame.loaded.locations) { List <NPC> toRemove = new List <NPC>(); foreach (NPC npc in loc.characters) { if (npc is StardewValley.Monsters.RockGolem || npc is StardewValley.Monsters.Bat) { toRemove.Add(npc); } } foreach (NPC npc in toRemove) { loc.characters.Remove(npc); } } MemoryStream tmp = new MemoryStream(); SaveGame.serializer.Serialize(tmp, SaveGame.loaded); sendFunc(new NextDayPacket()); sendFunc(new ClientFarmerDataPacket(Encoding.UTF8.GetString(tmp.ToArray()))); //SaveGame.loaded = oldLoaded; } catch (Exception e) { Log.error("Exception transitioning to next day: " + e); ChatMenu.chat.Add(new ChatEntry(null, "Something went wrong transitioning days.")); ChatMenu.chat.Add(new ChatEntry(null, "Report this bug, providing the full log file.")); ChatMenu.chat.Add(new ChatEntry(null, "You might be stuck in bed now. Attempting to unstuck you, more stuff might go wrong though.")); Game1.freezeControls = prevFreezeControls = false; Game1.newDay = false; Game1.fadeToBlackAlpha = 0; client.stage = Client.NetStage.Playing; } } sentNextDayPacket = true; } if (waitingOnOthers() && Game1.fadeToBlackAlpha > 0.625f) { Game1.fadeToBlackAlpha = 0.625f; } } else { sentNextDayPacket = false; } // We want people to wait for everyone //Log.Async("menu:"+Game1.activeClickableMenu); if (Game1.activeClickableMenu is SaveGameMenu && Game1.activeClickableMenu.GetType() != typeof(NewSaveGameMenu)) { Game1.activeClickableMenu = new NewSaveGameMenu(); } else if (Game1.activeClickableMenu is ShippingMenu) { //Log.Async("Savegame:" + Util.GetInstanceField(typeof(ShippingMenu), Game1.activeClickableMenu, "saveGameMenu")); SaveGameMenu menu = ( SaveGameMenu )Util.GetInstanceField(typeof(ShippingMenu), Game1.activeClickableMenu, "saveGameMenu"); if (menu != null && menu.GetType() != typeof(NewSaveGameMenu)) { Util.SetInstanceField(typeof(ShippingMenu), Game1.activeClickableMenu, "saveGameMenu", new NewSaveGameMenu()); } } if (Game1.currentLocation != null && Game1.currentLocation.currentEvent != null) { Events.fix(); } else { Events.reset(); } // Causing issues after going a day? Maybe? // Plus it only fixes a few of the time pauses /*Game1.player.forceTimePass = true; * Game1.paused = false; * if ( prevFreezeControls != Game1.freezeControls ) * { * sendFunc( new PauseTimePacket() ); * } * prevFreezeControls = Game1.freezeControls;*/ if (Multiplayer.mode == Mode.Host && server != null) { server.update(); if (server == null) { return; } if (server.clients == null) { return; } foreach (Server.Client client_ in server.clients) { if (client_.stage != Server.Client.NetStage.Playing) { continue; } if (client_.farmer == null) { continue; } doUpdatePlayer(client_.farmer); } } else if (Multiplayer.mode == Mode.Client && client != null) { client.update(); if (client == null) { return; } if (client.others == null) { return; } foreach (KeyValuePair <byte, SFarmer> other in client.others) { if (other.Value == null) { continue; } doUpdatePlayer(other.Value); } } if (Game1.gameMode == 6) { return; // Loading? } // ^ TODO: Check if != 3 works if (Multiplayer.mode == Mode.Host && server != null && server.playing || Multiplayer.mode == Mode.Client && client != null && client.stage == Client.NetStage.Playing) { if (Game1.newDay) { return; } NPCMonitor.startChecks(); foreach (GameLocation loc in Game1.locations) { if (!locations.ContainsKey(loc.name)) { locations.Add(loc.name, new LocationCache(loc)); } locations[loc.name].miniUpdate(); if (Game1.player.currentLocation == loc) { locations[loc.name].update(); } if (loc is Farm) { BuildableGameLocation farm = loc as BuildableGameLocation; foreach (Building building in farm.buildings) { if (building.indoors == null) { continue; } if (!locations.ContainsKey(building.nameOfIndoors)) { locations.Add(building.nameOfIndoors, new LocationCache(building.indoors)); } locations[loc.name].miniUpdate(); if (Game1.currentLocation != loc) { locations[building.nameOfIndoors].update(); } NPCMonitor.check(building.indoors); } } if (loc.name == "FarmHouse") { //Log.Async("Terrain features count for " + loc.name + " " + loc + ": " + loc.terrainFeatures.Count); //Log.Async("Object count for " + loc.name + " " + loc + ": " + loc.objects.Count); } } NPCMonitor.endChecks(); } Game1.player.FarmerSprite.setOwner(Game1.player); }
// Use this for initialization void Start() { var text = SaveGame.getTotalStars() + " / 50"; whiteLabel.text = text; }
public void Save() { SaveGame.SaveVal("HUDObjectiveDur", this.m_ObjectiveDuration); }
/// <summary> /// Initializes the world entity manager from a saved game. /// </summary> /// <param name="save">The save game data.</param> public abstract void Load(SaveGame save);
//SPARAR NER SPELARENS POSITION; HÄLSA; VILKEN BANA OCH VILKEN SVÅRIGHETSGRAD public void SaveToDevice(IAsyncResult result) { device = StorageDevice.EndShowSelector(result); if (device != null && device.IsConnected) { SaveGame SaveData = new SaveGame(); { SaveData.PlayerPosition = m_player.GetPosition(); SaveData.PlayerHp = m_player.GetLife(); SaveData.CurrentLevel = m_levels.GetLevel(); SaveData.Difficulty = m_stateHandler.GetDifficulty(); // SaveData.Level = m_level.GenerateLevel(); } IAsyncResult r = device.BeginOpenContainer(containerName, null, null); result.AsyncWaitHandle.WaitOne(); StorageContainer container = device.EndOpenContainer(r); if (container.FileExists(filename)) container.DeleteFile(filename); Stream stream = container.CreateFile(filename); XmlSerializer serializer = new XmlSerializer(typeof(SaveGame)); serializer.Serialize(stream, SaveData); stream.Close(); container.Dispose(); result.AsyncWaitHandle.Close(); } }
/// <summary> /// Fills a save game with data from the world entity manager. /// </summary> /// <param name="save">The save game data.</param> public abstract void Save(ref SaveGame save);
public void Load() { playerCurrentHealth = SaveGame.Load <int>("currenthp"); playerMaxHealth = SaveGame.Load <int>("maxhp"); }
public override void Save(int index) { base.Save(index); SaveGame.SaveVal("ShowerAmount" + index, this.m_Amount); SaveGame.SaveVal("ShowerActive" + index, this.m_Active); }
public void Save() { Debug.Log("saved"); SaveGame.Save <GameObject[]>("objects", objects); }
public void FinishLevel() { SaveGame.BeatLevel(episode, level); LeaveLevel(); }
protected virtual void OnApplicationQuit() { SaveGame.Save <int> ("serializer", value, new SaveGameJsonSerializer()); }
public void Save() { SaveGame.Save <Vector3Save> (identifier, target.localScale, SerializerDropdown.Singleton.ActiveSerializer); }
void ProgressToNextLevel() { SaveGame.KeepHighScore(currentLevel, Score.Total); isTransitionning = true; delayToNextLevel = LEVEL_TRANSITION_DELAY; }
/// <summary> /// Press done /// </summary> public void Done() { SaveGame save = new SaveGame(mms.SelectedID); save.Name = txt_name.text; save.Save(); mm.Navigate(menu_main.menu_main_state.SaveGame, menu_main.menu_sound.Finish); }
public void Save() { SaveGame.Save <int>("lvl", currentLevel); SaveGame.Save <int>("xp", currentExp); }
private void importFile_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); if (openFileDialog1.ShowDialog() != DialogResult.OK) // Test result. return; try { Save = new SaveGame(File.ReadAllBytes(openFileDialog1.FileName)); } catch (IOException) { MessageBox.Show("You didn't import any file."); } if (!Save.Valid) { MessageBox.Show("You didn't import a valid save file."); return; } // Load save contents. heartsUpDown.Value = BitConverter.ToInt32(Save.Data, Save.Hearts); updateAchievements(); palutenaBox.Value = BitConverter.ToInt32(Save.Data, Save.Palutena); viridiBox.Value = BitConverter.ToInt32(Save.Data, Save.Viridi); countTrophies(); }
public void SaveGameEvent() { UpdateLists(0); SaveGame.SaveGameButton(); }
private void SaveToDevice(IAsyncResult r) { try { device = StorageDevice.EndShowSelector(r); SaveGame data = new SaveGame() { PlayerPosition = playerPosition, PlayerSize = playerSize, Terrain = terrain, ModelRotation = modelRotation, ModelActivated = modelActivated, }; IAsyncResult result = device.BeginOpenContainer(containerName, null, null); result.AsyncWaitHandle.WaitOne(); StorageContainer container = device.EndOpenContainer(result); result.AsyncWaitHandle.Close(); if (container.FileExists(this.filename)) { container.DeleteFile(this.filename); } Stream stream = container.CreateFile(this.filename); XmlSerializer serializer = new XmlSerializer(typeof(SaveGame)); serializer.Serialize(stream, data); stream.Close(); container.Dispose(); } catch (System.ArgumentException e) { Console.WriteLine(e.Message); } }
void Awake() { System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone(); customCulture.NumberFormat.NumberDecimalSeparator = "."; System.Threading.Thread.CurrentThread.CurrentCulture = customCulture; if (m_Singleton != null) { Destroy(gameObject); return; } SaveGame.Serializer = new SaveGameBinarySerializer(); m_Singleton = this; m_Score = 0f; if (SaveGame.Exists("coin") && !m_MainCharacter.PlayerAiTraining) { m_Coin.Value = SaveGame.Load <int>("coin"); } else { m_Coin.Value = 0; } if (SaveGame.Exists("chest") && !m_MainCharacter.PlayerAiTraining) { this.chest_user = SaveGame.Load <int>("chest"); } else { this.chest_user = 0; } if (SaveGame.Exists("id")) { game_id = SaveGame.Load <int>("id") + 1; } else { game_id = 0; } if (SaveGame.Exists("audioEnabled")) { SetAudioEnabled(SaveGame.Load <bool>("audioEnabled")); } else { SetAudioEnabled(true); } if (SaveGame.Exists("lastScore") && !m_MainCharacter.PlayerAiTraining) { m_LastScore = SaveGame.Load <float>("lastScore"); } else { m_LastScore = 0f; } if (SaveGame.Exists("highScore") && !m_MainCharacter.PlayerAiTraining) { m_HighScore = SaveGame.Load <float>("highScore"); } else { m_HighScore = 0f; } if (SaveGame.Exists("livesLostUser") && !m_MainCharacter.PlayerAiTraining) { this.lives_lost_user = SaveGame.Load <int>("livesLostUser"); } else { this.lives_lost_user = 0; } if (SaveGame.Exists("livesLostMovingUser") && !m_MainCharacter.PlayerAiTraining) { this.lives_lost_enemy_moving_user = SaveGame.Load <int>("livesLostMovingUser"); } else { this.lives_lost_enemy_moving_user = 0; } if (SaveGame.Exists("livesLostStaticUser") && !m_MainCharacter.PlayerAiTraining) { this.lives_lost_enemy_static_user = SaveGame.Load <int>("livesLostStaticUser"); } else { this.lives_lost_enemy_static_user = 0; } if (SaveGame.Exists("livesLostWaterUser") && !m_MainCharacter.PlayerAiTraining) { this.lives_lost_enemy_water_user = SaveGame.Load <int>("livesLostWaterUser"); } else { this.lives_lost_enemy_water_user = 0; } if (SaveGame.Exists("averageVelocityUser") && !m_MainCharacter.PlayerAiTraining) { this.average_velocity_user = SaveGame.Load <float>("averageVelocityUser"); } else { this.average_velocity_user = 0f; } if (SaveGame.Exists("averageVelocityUserI") && !m_MainCharacter.PlayerAiTraining) { this.average_velocity_user_i = SaveGame.Load <int>("averageVelocityUserI"); } else { this.average_velocity_user_i = 0; } if (SaveGame.Exists("averageVelocityUserM2") && !m_MainCharacter.PlayerAiTraining) { this.average_velocity_user_m2 = SaveGame.Load <float>("averageVelocityUserM2"); } else { this.average_velocity_user_m2 = 0f; } if (SaveGame.Exists("adaptivityStartOn") && !m_MainCharacter.PlayerAiTraining) { this.adaptivityOn = SaveGame.Load <bool>("adaptivityStartOn"); } else { int randomNumberAdaptivity = UnityEngine.Random.Range(0, 2); if (randomNumberAdaptivity == 0) { this.adaptivityOn = false; } else { this.adaptivityOn = true; } SaveGame.Save <bool>("adaptivityStartOn", this.adaptivityOn); } if (!File.Exists(Application.persistentDataPath + csv_section_path)) { this.csv_section = File.AppendText(Application.persistentDataPath + csv_section_path); this.csv_section.WriteLine("unique_identifier;session_id;section;adaptivity;round_letter;total_coins;captured_coins;easy_captured_coins;hard_captured_coins;chest_normals;chest_hard;total_time;total_time_gained;lives_lost;lives_lost_water;lives_lost_static;lives_lost_moving;best_score;end_score;player_backtracked;jumps;average_velocity"); } else { this.csv_section = File.AppendText(Application.persistentDataPath + csv_section_path); } if (!File.Exists(Application.persistentDataPath + csv_game_path)) { this.csv_game = File.AppendText(Application.persistentDataPath + csv_game_path); this.csv_game.WriteLine("unique_identifier;session_id;adaptivity;round_letter;total_coins;captured_coins;easy_captured_coins;hard_captured_coins;chest_normals;chest_hard;total_time;total_time_gained;lives_lost;lives_lost_water;lives_lost_static;lives_lost_moving;best_score;end_score;player_backtracked;jumps;average_velocity;variance"); } else { this.csv_game = File.AppendText(Application.persistentDataPath + csv_game_path); } this.roundInfoLetter = "B"; }
public void ResetData() { SG = new SaveGame(); SG.SaveGameData(); }
public void Load() { this.m_ObjectiveDuration = SaveGame.LoadFVal("HUDObjectiveDur"); }
public BioMass() { this.Log_DebugOnly("Constructor BioMass"); Instance = this; globalSettings = new Settings(); saveGame = new SaveGame(); }
public void DeleteSave() { SaveGame.Delete("player.txt"); SaveGame.Delete("shop.txt"); Hide(); }
private void btnLoadGame_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); SaveGame game = new SaveGame(); if (dlg.ShowDialog() == DialogResult.OK) { //follow GameFile::read_file_2() in OGFILE2.cpp @ line 532 /* BOOKMARK = 4096 * + 101 = 4197 * -- read file size * + 102 = 4198 * -- config.read_file() * + 103 = 4199 * -- sys.read_file() * + 104 = 4200 * -- info.read_file() * + 105 = 4201 * -- power.read_file() * + 106 = 4202 * -- weather.read_file() */ FileStream savfile_stream = File.OpenRead(dlg.FileName); // Maintained the Byte[] config line from the old branch. // hadn't yet merged that into master. // <<<<<<< HEAD Byte[] header = new Byte[302]; Byte[] duo = new Byte[2]; //for getting sizes and bookmarks Byte[] config = new Byte[144]; Byte[] game_dot_read_file = new Byte[2060]; // ======= // byte[] header = new byte[304]; // byte[] duo = new byte[2]; //for getting sizes and bookmarks // byte[] config = new byte[144]; // >>>>>>> master //Byte[] sys = new Byte[]; //Byte[] info = new Byte[]; //Byte[] power = new Byte[]; //Byte[] weather = new Byte[]; // *** Read header *** savfile_stream.Read(duo, 0, 2); //read header size (0x012e = 302) savfile_stream.Read(header, 0, 302); // *** Read version *** savfile_stream.Read(duo, 0, 2); //read game version (0x00d4 = 212) game.Version = BitConverter.ToInt16(duo, 0); savfile_stream.Read(duo, 0, 2); //read bookmark+101 (0x1065 = 4197) // *** Read GameFile *** savfile_stream.Read(duo, 0, 2); //GameFile object's size (0x80c0 = 2060d) savfile_stream.Read(game_dot_read_file, 0, BitConverter.ToInt16(duo, 0)); savfile_stream.Read(duo, 0, 2); //read bookmark+102 (0x1066 = 4198) // *** Read config *** savfile_stream.Read(duo, 0, 2); //read config recordSize (0x0090 = 144) savfile_stream.Read(config, 0, BitConverter.ToInt16(duo, 0)); savfile_stream.Read(duo, 0, 2); //read bookmark (0x1067 = 4199) savfile_stream.Close(); } }
public async Task <ActionResult <SaveGame> > CreateAsync(SaveGame saveGame) { await this.saveGameService.CreateAsync(saveGame); return(CreatedAtRoute("GetSaveGame", new { id = saveGame.Id.ToString() }, saveGame)); }
public override void update(GameTime time) { if (this.quit) { return; } base.update(time); if (!Game1.saveOnNewDay) { this.quit = true; if (Game1.activeClickableMenu.Equals(this)) { Game1.player.checkForLevelTenStatus(); Game1.exitActiveMenu(); } return; } if (this.loader != null) { this.loader.MoveNext(); if (this.loader.Current >= 100) { this.margin -= time.ElapsedGameTime.Milliseconds; if (this.margin <= 0) { Game1.playSound("money"); this.completePause = 1500; this.loader = null; Game1.game1.IsSaving = false; } } this._ellipsisDelay -= (float)time.ElapsedGameTime.TotalSeconds; if (this._ellipsisDelay <= 0f) { this._ellipsisDelay += 0.75f; this._ellipsisCount++; if (this._ellipsisCount > 3) { this._ellipsisCount = 1; } } } else if (this.hasDrawn && this.completePause == -1) { Game1.game1.IsSaving = true; this.loader = SaveGame.Save(); } if (this.completePause >= 0) { this.completePause -= time.ElapsedGameTime.Milliseconds; this.saveText.update(time); if (this.completePause < 0) { this.quit = true; this.completePause = -9999; if (Game1.activeClickableMenu.Equals(this)) { Game1.player.checkForLevelTenStatus(); Game1.exitActiveMenu(); } Game1.currentLocation.resetForPlayerEntry(); } } }
void CreateSaveGameButtons(SaveGame saveGame, int ID) { GameObject loadSaveGameButtonObject = new GameObject("SaveGame " + saveGame.SaveGameName); Button loadButton = loadSaveGameButtonObject.AddComponent<Button>(); Image loadButtonImage = loadSaveGameButtonObject.AddComponent<Image>(); GameObject loadSaveGameTextObject = new GameObject("SaveGameText " + saveGame.SaveGameName); Text loadButtonText = loadSaveGameTextObject.AddComponent<Text>(); Outline loadButtonTextOutline = loadSaveGameTextObject.AddComponent<Outline>(); loadButtonImage.type = Image.Type.Sliced; loadButtonImage.sprite = image; loadSaveGameButtonObject.transform.SetParent(canvas.transform); loadSaveGameTextObject.transform.SetParent(loadSaveGameButtonObject.transform); loadSaveGameTextObject.GetComponent<RectTransform>().localPosition = new Vector2(0.0f, -6.5f); loadSaveGameButtonObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(450, (ID * (150 + buttonSpace)) - 362); loadSaveGameButtonObject.GetComponent<RectTransform>().anchorMin = new Vector2(0.5f, 0.5f); loadSaveGameButtonObject.GetComponent<RectTransform>().anchorMax = new Vector2(0.5f, 0.5f); loadButtonText.text = saveGame.SaveGameName.ToUpper(); loadButtonText.alignment = TextAnchor.MiddleCenter; loadButtonText.font = GameManager.gameFont; loadButtonText.fontSize = 38; loadButtonText.color = Color.white; loadButtonTextOutline.effectColor = Color.black; loadButtonTextOutline.effectDistance = new Vector2(3.0f, 3.0f); loadSaveGameButtonObject.GetComponent<RectTransform>().localScale = new Vector3(1f, 1f, 1f); loadSaveGameTextObject.GetComponent<RectTransform>().localScale = new Vector3(1f, 1f, 1f); loadSaveGameButtonObject.GetComponent<RectTransform>().sizeDelta = new Vector2(400, 150); loadSaveGameTextObject.GetComponent<RectTransform>().sizeDelta = new Vector2(400, 150); loadSaveGameTextObject.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 0.5f); loadSaveGameButtonObject.layer = LayerMask.NameToLayer("UI"); loadSaveGameTextObject.layer = LayerMask.NameToLayer("UI"); loadButton.targetGraphic = loadButton.GetComponent<Image>(); loadButton.colors = GameManager.colorBlock; loadButton.onClick.AddListener(delegate {LoadSaveGame(saveGame);}); // ********************************************************************************************************************************************************* GameObject deleteSaveGameButtonObject = new GameObject("Delete " + saveGame.SaveGameName); Button deleteButton = deleteSaveGameButtonObject.AddComponent<Button>(); Image deleteButtonImage = deleteSaveGameButtonObject.AddComponent<Image>(); GameObject deleteSaveGameTextObject = new GameObject("DeleteText " + saveGame.SaveGameName); Text deleteButtonText = deleteSaveGameTextObject.AddComponent<Text>(); Outline deleteButtonTextOutline = deleteSaveGameTextObject.AddComponent<Outline>(); deleteButtonImage.type = Image.Type.Sliced; deleteButtonImage.sprite = image; deleteSaveGameButtonObject.transform.SetParent(canvas.transform); deleteSaveGameTextObject.transform.SetParent(deleteSaveGameButtonObject.transform); deleteSaveGameTextObject.GetComponent<RectTransform>().localPosition = new Vector2(0.0f, -6.5f); deleteSaveGameButtonObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(800, (ID * (150 + buttonSpace)) - 362); deleteSaveGameButtonObject.GetComponent<RectTransform>().anchorMin = new Vector2(0.5f, 0.5f); deleteSaveGameButtonObject.GetComponent<RectTransform>().anchorMax = new Vector2(0.5f, 0.5f); deleteButtonText.text = "X"; deleteButtonText.alignment = TextAnchor.MiddleCenter; deleteButtonText.font = GameManager.gameFont; deleteButtonText.fontSize = 38; deleteButtonText.color = Color.white; deleteButtonTextOutline.effectColor = Color.black; deleteButtonTextOutline.effectDistance = new Vector2(3.0f, 3.0f); deleteSaveGameButtonObject.GetComponent<RectTransform>().localScale = new Vector3(1f, 1f, 1f); deleteSaveGameTextObject.GetComponent<RectTransform>().localScale = new Vector3(1f, 1f, 1f); deleteSaveGameButtonObject.GetComponent<RectTransform>().sizeDelta = new Vector2(150, 150); deleteSaveGameTextObject.GetComponent<RectTransform>().sizeDelta = new Vector2(150, 150); deleteSaveGameTextObject.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 0.5f); deleteSaveGameButtonObject.layer = LayerMask.NameToLayer("UI"); deleteSaveGameTextObject.layer = LayerMask.NameToLayer("UI"); deleteSaveGameButtonObject.transform.SetParent(loadSaveGameButtonObject.transform); deleteButton.targetGraphic = deleteButton.GetComponent<Image>(); deleteButton.colors = GameManager.colorBlock; deleteButton.onClick.AddListener(delegate {DeleteSaveGame(saveGame, loadSaveGameButtonObject);}); }
public void Load() { SaveGame.Load(); }
public override void process(Server server, Server.Client client) { Log.debug("Got farmer data for client " + client.id); //SFarmer old = client.farmer; SaveGame theirs = (SaveGame)SaveGame.serializer.Deserialize(Util.stringStream(xml)); foreach (var quest in theirs.player.questLog) { if (quest is SlayMonsterQuest) { (quest as SlayMonsterQuest).loadQuestInfo(); } } if (client.farmer == null) { ChatMenu.chat.Add(new ChatEntry(null, theirs.player.name + " has connected.")); server.broadcast(new ChatPacket(255, theirs.player.name + " has connected."), client.id); String str = "Currently playing: "; str += NewLoadMenu.pendingSelected.name; foreach (Server.Client other in server.clients) { if (other == client || other.farmer == null) { continue; } str += ", " + other.farmer.name; } client.send(new ChatPacket(255, str)); } client.farmerXml = Util.serialize <SFarmer>(theirs.player); client.farmer = theirs.player; client.farmer.uniqueMultiplayerID += 1 + client.id; client.farmType = theirs.whichFarm; NewSaveGame.loadDataToFarmer(client.farmer); client.farmer.FarmerSprite.setOwner(client.farmer); Game1.player.FarmerSprite.setOwner(Game1.player); //if(!server.playing) //if (server.playing) client.farmer = old; // About second-day-sleeping crashes: // So just adding the location directly puts the raw deserialized one into the game. // The raw deserialized one doesn't have the tiles and stuff loaded. Just the game data. // I think this is why vanilla copies data over in loadDataToLocations instead of using // the loaded objects directly. Why not just postpone loading until later, I don't know. // // So, when the second day begins, otherFarmer.currentLocation was still set to the // previous day's farm house[*]. On day two, the 'good' one[**] was removed, so when they go // back in, the bad one is used. Basically, I need to make them all the 'good' one. // For now, I'm just going to reload the needed data for this client's farmhouse. // I'll figure out how to do it 'properly' later. Maybe. (My mind is muddled today.) // // [*] Looking at addFixedLocationToOurWorld now you'll see that this isn't the case. // I added the part about fixing SFarmer.currentLocation as I was going through this // thought process. So things will break more obviously if something like this happens // again. // // [**] The first day's farmhouse is okay because in loadDataToLocations, (called in // NewSaveGame.getLoadEnumerator), the map is reloaded from FarmHouse_setMapForUpgradeLevel. // If CO-OP weren't on, worse things would happen, because things besides the farm house // would need loading (see Multiplayer.isPlayerUnique). The client doesn't have this // issue because they do the whole loading process each day anyways. // // Of course, the whole second-day-crash doesn't happen when I test it on localhost. Hence // why this was so annoying. And probably why I documented all this. foreach (GameLocation theirLoc in theirs.locations) { if (theirLoc.name == "FarmHouse") { NewSaveGame.FarmHouse_setMapForUpgradeLevel(theirLoc as FarmHouse); } } fixPetDuplicates(theirs); Multiplayer.fixLocations(theirs.locations, client.farmer, addFixedLocationToOurWorld, client); foreach (string mail in Multiplayer.checkMail) { if (client.farmer.mailForTomorrow.Contains(mail)) { if (!SaveGame.loaded.player.mailForTomorrow.Contains(mail)) { SaveGame.loaded.player.mailForTomorrow.Add(mail); } if (Game1.player != null && !Game1.player.mailForTomorrow.Contains(mail)) { Game1.player.mailForTomorrow.Add(mail); } } if (client.farmer.mailForTomorrow.Contains(mail + "%&NL&%")) { if (!SaveGame.loaded.player.mailForTomorrow.Contains(mail + "%&NL&%")) { SaveGame.loaded.player.mailForTomorrow.Add(mail + "%&NL&%"); } if (Game1.player != null && !Game1.player.mailForTomorrow.Contains(mail + "%&NL&%")) { Game1.player.mailForTomorrow.Add(mail + "%&NL&%"); } } } client.stage = Server.Client.NetStage.WaitingForStart; --server.currentlyAccepting; }
void OnApplicationQuit() { save = new SaveGame(itemDatabase,inventory); SaveLoad.Save(save); }
void SaveToDevice(IAsyncResult result) { device = StorageDevice.EndShowSelector(result); if (device != null && device.IsConnected) { SaveGame SaveData = new SaveGame() { skinSave = skin, soundONSave = soundON, showFPSSave = showFps, difficultySave = difficulty, classicModeSave = classicMode }; IAsyncResult r = device.BeginOpenContainer(containerName, null, null); result.AsyncWaitHandle.WaitOne(); StorageContainer container = device.EndOpenContainer(r); if (container.FileExists(filename)) container.DeleteFile(filename); Stream stream = container.CreateFile(filename); XmlSerializer serializer = new XmlSerializer(typeof(SaveGame)); serializer.Serialize(stream, SaveData); stream.Close(); container.Dispose(); result.AsyncWaitHandle.Close(); } }
public async Task <ActionResult <DateTime> > SimulateDay() { SaveGame newSaveGame = await this.saveGameService.IncrementIngameDateAsync(); return(Ok(newSaveGame.InGameDate)); }