public void CreateSavedGameButtonPressed() { statusText.text = "Saving..."; canvasGroup.interactable = false; largestSlot++; var savedGameFileName = "SavedGame" + largestSlot; // Creates a new SavedGame object. var savedGame = new SavedGame( new SavedGameMetadata(savedGameFileName, largestSlot), new SaveData() ); // Saves the SavedGame object and adds it to the scroll view. SaveManager.SaveGame(savedGame, () => { var save = CreateSaveElement(savedGame.metadata); save.transform.SetParent(savesGroup.transform, false); statusText.text = "Game saved successfully!"; canvasGroup.interactable = true; }); }
public static void RoundTripTest(string baseDir) { var mapping = AssetMapping.Global; // TODO: Base game mapping. var saveDir = Path.Combine(baseDir, "re", "TestSaves"); var regex = new Regex(@"\.[0-9][0-9][0-9]$"); foreach (var file in Directory.EnumerateFiles(saveDir)) { if (!regex.IsMatch(file)) { continue; } Console.WriteLine("Round-trip testing " + file); using var stream = File.Open(file, FileMode.Open); using var br = new BinaryReader(stream); using var ar = new AlbionReader(br, stream.Length); var save = SavedGame.Serdes(null, mapping, ar); using var ms = new MemoryStream(); using var bw = new BinaryWriter(ms); using var aw = new AlbionWriter(bw); SavedGame.Serdes(save, mapping, aw); br.BaseStream.Position = 0; var originalBytes = br.ReadBytes((int)stream.Length); var roundTripBytes = ms.ToArray(); //* Save round-tripped and annotated text output for debugging File.WriteAllBytes(file + ".bin", roundTripBytes); using var ts = new MemoryStream(); using var tw = new StreamWriter(ts); using var afw = new AnnotatedFormatWriter(tw); SavedGame.Serdes(save, mapping, afw); ts.Position = 0; File.WriteAllBytes(file + ".txt", ts.ToArray()); //*/ ApiUtil.Assert(originalBytes.Length == roundTripBytes.Length); ApiUtil.Assert(originalBytes.SequenceEqual(roundTripBytes)); var sw = new StringWriter(); using var jw = new JsonWriter(sw); SavedGame.Serdes(save, mapping, jw); File.WriteAllText(file + ".json", sw.ToString()); break; } Console.WriteLine("Done"); Console.ReadLine(); }
void OnSavedGameSelectedFromScrollableList(ScrollableList list, string title, string subtitle) { list.ItemSelected -= OnSavedGameSelectedFromScrollableList; foreach (SavedGame game in allSavedGames) { if (game.Name.Equals(title)) { selectedSavedGame = game; NativeUI.Alert("Saved Game Selected", "You selected saved game: " + selectedSavedGame.Name); return; } } }
// SavedGameInfoUpdate is not really used on iOS. public void WriteSavedGameData(SavedGame savedGame, byte[] data, SavedGameInfoUpdate infoUpdate, Action <SavedGame, string> callback) { Util.NullArgumentTest(savedGame); Util.NullArgumentTest(data); Util.NullArgumentTest(callback); InternalSaveGameData( savedGame.GKSavedGame, data, (iOSGKSavedGame gkSavedGame, string error) => { callback(gkSavedGame != null ? new SavedGame(gkSavedGame) : null, error); }); }
void LoadSavedGameInfo() { if (ES2.Exists(SavedGameFilename)) { string[] tags = ES2.GetTags(SavedGameFilename); foreach (string tag in tags) { string gameLocation = SavedGameFilename + "?tag=" + tag; SavedGame game = new SavedGame(); game = ES2.Load <SavedGame>(gameLocation); games.Add(game); } } }
private void Load(SavedGame savedGame) { try { Debug.Log("进入读档"); BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/" + savedGame.gameObject.name + ".dat", FileMode.Open); Debug.Log(file); Debug.Log(file.Name); SaveData data = (SaveData)bf.Deserialize(file); file.Close(); Debug.Log("1"); LoadPlayer(data); Debug.Log("2"); LoadChests(data); Debug.Log("3"); LoadBags(data); Debug.Log("4"); LoadEquipment(data); Debug.Log("5"); LoadActionButtons(data); Debug.Log("6"); LoadInventory(data); Debug.Log("7"); LoadQuests(data); Debug.Log("8"); LoadQuestGiver(data); } catch (System.Exception) { //This is for handling errors Debug.Log("读档出现问题"); //This is for handling errors //Delete(savedGame); //PlayerPrefs.DeleteKey("Load"); //SceneManager.LoadScene(0); } }
/// <summary> /// Adds SavedGame to saves.xml /// </summary> /// <param name="savedGame">Game result to save</param> public static void SaveGame(SavedGame savedGame) { var SavedGames = LoadGames(); SavedGames.Add(savedGame); var filePath = Path.Combine(Application.dataPath, SaveFileName); XmlSerializer writer = new XmlSerializer(typeof(List <SavedGame>)); using (StreamWriter file = new StreamWriter(filePath)) { writer.Serialize(file, SavedGames); } }
public void SaveGame(string path) { SavedGame saved = new SavedGame(); saved.turrets = new List <SavedGame.SavedAssembly> (); saved.difficulty = difficulty; saved.selectedTurrets = purchaseMenu.GetAssemblies(); for (int i = 0; i < currentModules.Count; i++) { if (currentModules[i].isRoot) { saved.turrets.Add(new SavedGame.SavedAssembly(currentModules[i])); } } saved.battlefieldData = new BattlefieldData(battlefieldName, "", game.battlefieldWidth, game.battlefieldHeight, Game.isWalled, game.enemySpawnPoints); saved.waveSetPath = WAVESET_SAVE_DIRECTORY + "DEFAULT" + EnemyManager.WAVESET_FILE_EXTENSION; saved.researchedResearch = new List <int> (); for (int i = 0; i < researchMenu.research.Count; i++) { if (ResearchMenu.cur.research[i].isBought) { saved.researchedResearch.Add(ResearchMenu.cur.research[i].index); } } saved.researchPoints = new SavedGame.SavedResearchPoint[researchPoints.Count]; for (int i = 0; i < researchPoints.Count; i++) { saved.researchPoints[i] = new SavedGame.SavedResearchPoint(researchPoints[i]); } saved.credits = credits; saved.research = research; saved.researchProgress = researchProgress; saved.flushTimer = PlayerInput.flushTimer; saved.waveNumber = EnemyManager.cur.waveNumber; saved.totalWaveNumber = EnemyManager.ExternalWaveNumber; saved.masteryNumber = EnemyManager.cur.waveMasteryIndex; saved.gameProgress = EnemyManager.gameProgress; saved.enemiesKilled = EnemyManager.cur.enemiesKilled; saved.health = Datastream.healthAmount; saved.Save(path); }
//-------------------------------------------------------------------------------------------- public bool loadSavedGame(string name) { //if our games map doesn't contain a game w/ the given name... if(!mGamesMap.ContainsKey(name)) { //return false -- no game loaded return false; } //otherwise, set the current game object mCurrentGame = mGamesMap[name]; return true; }
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } SavedGame = await _context.SavedGames.FirstOrDefaultAsync(m => m.SavedGameId == id); if (SavedGame == null) { return(NotFound()); } return(Page()); }
private void BtnDelete_LeftClick(object sender, EventArgs e) { SavedGame sg = savedGames[lbSaveGameList.SelectedIndex]; var msgBox = new XNAMessageBox(WindowManager, "Delete Confirmation", "The following saved game will be deleted permanently:" + Environment.NewLine + Environment.NewLine + "Filename: " + sg.FileName + Environment.NewLine + "Saved game name: " + Renderer.GetSafeString(sg.GUIName, lbSaveGameList.FontIndex) + Environment.NewLine + "Date and time: " + sg.LastModified.ToString() + Environment.NewLine + Environment.NewLine + "Are you sure you want to proceed?", XNAMessageBoxButtons.YesNo); msgBox.Show(); msgBox.YesClickedAction = DeleteMsgBox_YesClicked; }
private void LoadScene(SavedGame savedGame) { savedGame = saveSlots[saveSlotsindex]; Debug.Log(savedGame); if (File.Exists(Application.persistentDataPath + "/" + savedGame.gameObject.name + ".dat")) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/" + savedGame.gameObject.name + ".dat", FileMode.Open); SaveData data = (SaveData)bf.Deserialize(file); file.Close(); PlayerPrefs.SetInt("Load", savedGame.MyIndex); SceneManager.LoadScene(data.MyScene); } }
private void ShowSavedFiles(SavedGame savedGame) { if (File.Exists(Application.persistentDataPath + "/" + savedGame.gameObject.name + ".dat")) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/" + savedGame.gameObject.name + ".dat", FileMode.Open); SaveData data = (SaveData)bf.Deserialize(file); file.Close(); savedGame.ShowInfo(data); } }
//-------------------------------------------------------------------------------------------- public bool createNewGame(string name) { //if our games map contains a game w/ the given name... if(mGamesMap.ContainsKey(name)) { //return false -- no new game created return false; } //otherwise, create a new game object mCurrentGame = new SavedGame(name); mGamesMap.Add(name, mCurrentGame); return true; }
public void SavedGame_DecodeSaveData(string testDataName, bool expectedValid) { var encodedSaveData = File.ReadAllText(Path.Combine("TestData", testDataName + ".txt")); var reader = SavedGame.DecodeSaveData(encodedSaveData); if (expectedValid) { Assert.NotNull(reader); Assert.NotEqual(-1, reader.Peek()); } else { Assert.Null(reader); } }
// Save the game to xml public void SaveGame(string filename) { SavedGame savedGame = new SavedGame(); savedGame.BuildFromScene(); string path = Application.persistentDataPath + "/" + filename + extension; SavedGame.WriteToFile(path, savedGame); if (filename != reservedFilename) { Debug.Log("File saved to " + path); } }
public async Task <IActionResult> SaveGame(SavedGame savedGame) { ApplicationUser user = await _userManager.GetUserAsync(HttpContext.User); if (ValidateCategoryAndLevel(savedGame.Category, savedGame.Level) && !String.IsNullOrEmpty(savedGame.Json) && savedGame.Progress >= 0 && savedGame.Progress <= 100) { savedGame.UserId = user.Id; _dbContext.Add(savedGame); _dbContext.SaveChanges(); return(Ok()); } return(BadRequest()); }
void OnSavedGameUpdated(SavedGame game, string error) { if (!string.IsNullOrEmpty(error)) { isSuccess.Value = false; errorDescription.Value = error; Fsm.Event(eventTarget, isNotSuccessEvent); Finish(); } else { isSuccess.Value = true; Fsm.Event(eventTarget, isSuccessEvent); Finish(); } }
/// <summary> /// Gets the saved games /// </summary> public void GetSaves() { var(buttons, savedGames) = SlotButtons.GetSaves(slotTemplateButton, canDelete: false); foreach (Button slotButton in buttons) { int index = buttons.IndexOf(slotButton); slotButton.onClick.AddListener(() => ImportSave(index + 1)); SavedGame savedGame = savedGames.FirstOrDefault(x => x.Slot == index + 1); if (savedGame != null) { tempSavedGames[index] = savedGame; } } }
/// <summary> /// Saves the game /// </summary> /// <param name="saveGame">The game to save</param> /// <param name="slot">The slot to save in</param> /// <returns>True if the save was a success, false if it wasn't</returns> public static bool SaveGame(SavedGame saveGame, int slot) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); try { formatter.Serialize(stream, saveGame); File.WriteAllBytes(GetSavePath(slot), stream.ToArray()); return(true); } catch (Exception) { return(false); } }
void LoadGame() { if (PlayerPrefs.HasKey("SavedGame")) { SavedGame savedGame = new SavedGame(); string jsonString = PlayerPrefs.GetString("SavedGame"); savedGame = JsonUtility.FromJson <SavedGame>(jsonString); shotsMadeText.text = savedGame.shotsMade.ToString(); pointsText.text = savedGame.playerPoints.ToString(); timeText.text = Manager.manager.SecondsToTimeString(savedGame.secondsSpent); } }
void DefaultCallback(SavedGame savedGame, string error) { if (string.IsNullOrEmpty(error)) { savedGameName.Value = savedGame.Name; isSuccess.Value = true; Fsm.Event(eventTarget, isSuccessEvent); } else { isSuccess.Value = false; errorDescription.Value = error; Fsm.Event(eventTarget, isNotSuccessEvent); } Finish(); }
private void WriteSaveData(SavedGame savedGame) { if (File.Exists(filePath)) { File.Delete(filePath); } FileStream dataStream = new FileStream(filePath, FileMode.Create); BinaryFormatter converter = new BinaryFormatter(); converter.Serialize(dataStream, savedGame); dataStream.Close(); currentSave = savedGame; }
public IEnumerator hydrate(SavedGame saved, Dictionary <int, List <StarNode> > toFill) { yield return(null); var stateTable = saved.loadedModel.objectTable; foreach (var referenceBranch in saved.loadedModel.starNodes) { var newBranch = new List <StarNode>(); foreach (var starReference in referenceBranch.Value) { yield return(starFactory.createStar(holder.transform, starReference, stateTable, (star) => newBranch.Add(star))); } toFill[referenceBranch.Key] = newBranch; } }
private SavedGame LoadSavedGameData() { if (!File.Exists(filePath)) { return(null); } FileStream dataStream = new FileStream(filePath, FileMode.Open); BinaryFormatter converter = new BinaryFormatter(); SavedGame saveData = converter.Deserialize(dataStream) as SavedGame; dataStream.Close(); return(saveData); }
public Galaxy(CultCache cultCache, SavedGame savedGame, Action <string> log) { Log = log; Background = savedGame.Background; Factions = savedGame.Factions.Select(cultCache.Get <Faction>).ToArray(); for (var i = 0; i < Factions.Length; i++) { FactionRelationships[Factions[i]] = savedGame.Relationships[i]; } Zones = savedGame.Zones.Select(zone => { return(new GalaxyZone { Name = zone.Name, Position = zone.Position, PackedContents = zone.Contents }); }).ToArray(); foreach (var i in savedGame.DiscoveredZones) { DiscoveredZones.Add(Zones[i]); } for (var i = 0; i < Zones.Length; i++) { Zones[i].AdjacentZones = savedGame.Zones[i].AdjacentZones.Select(azi => Zones[azi]).ToList(); Zones[i].Factions = savedGame.Zones[i].Factions.Select(mi => Factions[mi]).ToArray(); Zones[i].Owner = savedGame.Zones[i].Owner < 0 ? null : Factions[savedGame.Zones[i].Owner]; } HomeZones = savedGame.HomeZones.ToDictionary( x => Factions[x.Key], x => Zones[x.Value]); BossZones = savedGame.BossZones.ToDictionary( x => Factions[x.Key], x => Zones[x.Value]); Entrance = Zones[savedGame.Entrance]; if (savedGame.Exit != -1) { Exit = Zones[savedGame.Exit]; } CalculateDistanceMatrix(); }
public List <SavedGame> GetSavedGames() { var savedGames = new List <SavedGame>(); string saveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley", "Saves"); if (Directory.Exists(saveDirectory)) { string[] directories = Directory.GetDirectories(saveDirectory); foreach (string savedGameDirectory in directories) { try { FileInfo file = new FileInfo(Path.Combine(savedGameDirectory, "SaveGameInfo")); if (file.Exists) { var saveGameFolder = file.Directory.Name; var fileContents = File.ReadAllText(file.FullName); var farmerNodeStart = fileContents.IndexOf("<Farmer"); var farmerNodeEnd = fileContents.IndexOf("</Farmer>"); var farmerNode = fileContents.Substring(farmerNodeStart, farmerNodeEnd - farmerNodeStart); var playerNameNodeStart = farmerNode.IndexOf("<name>") + 6; var playerNameNodeEnd = farmerNode.IndexOf("</name>"); var playerName = farmerNode.Substring(playerNameNodeStart, playerNameNodeEnd - playerNameNodeStart); var farmNameNodeStart = fileContents.IndexOf("<farmName>") + 10; var farmNameNodeEnd = fileContents.IndexOf("</farmName>"); var farmName = fileContents.Substring(farmNameNodeStart, farmNameNodeEnd - farmNameNodeStart); var savedGame = new SavedGame { Id = saveGameFolder, Name = playerName, FarmName = farmName }; savedGames.Add(savedGame); } } catch (Exception ex) { throw new Exception($"error searching for saved games", ex); } } } return(savedGames); }
public static SavedGame current() { SavedGame sg = new SavedGame (); sg.UnlockedCards = SaveDataControl.UnlockedCards; sg.StartingDeckCards = SaveDataControl.StartingDeckCards; sg.UnlockedGods = SaveDataControl.UnlockedGods.Select(i=>(int)i).ToList(); sg.DefeatedEnemies = SaveDataControl.DefeatedEnemies; sg.FinishedTutorial = SaveDataControl.FinishedTutorial; sg.NewCardsAvailable = SaveDataControl.NewCardsAvailable; Debug.Log("Saving! unlocked gods: " + SaveDataControl.UnlockedGods.Count.ToString() + ", " + "New cards available = " + NewCardsAvailable.ToString() + ", Finished tutorial = " + FinishedTutorial.ToString() + "\nunlocked cards: " + SaveDataControl.UnlockedCards.Count.ToString () + ", starting deck cards: " + SaveDataControl.StartingDeckCards.Count.ToString() + ", defeated enemies: " + SaveDataControl.DefeatedEnemies.Count.ToString()); return sg; }
private Game(Module module, string fileName) { FileName = fileName; Module = module; Data = SavedGame.Create(); Data.Game = this; _entities = new EntityContainer(Module.EntityDefinitions); _entities.AddEntities(() => Data.factions); _entities.AddEntities(() => Data.info_pages); _entities.AddEntities(() => Data.item_kinds); _entities.AddEntities(() => Data.parties); _entities.AddEntities(() => Data.party_templates); _entities.AddEntities(() => Data.quests); _entities.AddEntities(() => Data.scenes); _entities.AddEntities(() => Data.troops); }
void OnGUI() { //If this button is pressed, we will save the game to the new path and name if (GUI.Button(new Rect(170, 10, 150, 25), "Create New Save")) { SaveGame(Application.dataPath + "/" + saveDirectory + currentSaveFile, currentSaveFile); } //the currentSaveFile field. currentSaveFile = GUI.TextField(new Rect(10, 10, 150, 25), currentSaveFile); //Itterate through the saved game list for (int i = 0; i < savedGames.Length; i++) { //Get the saved game SavedGame game = savedGames[i]; //Draw the background box GUI.Box(new Rect(10, 45 + (i * 60), 310, 50), game.name); //Load the file at the game's path when Load Game is pressed if (GUI.Button(new Rect(25, 45 + (i * 60) + 20, 100, 25), "Load Game")) { LoadGame(game.path); } //Save the game with its name to the appropriate path when Save Game is pressed if (GUI.Button(new Rect(140, 45 + (i * 60) + 20, 100, 25), "Save Game")) { SaveGame(game.path, game.name); } if (GUI.Button(new Rect(255, 45 + (i * 60) + 20, 50, 25), "Delete")) { //The delete button was pressed, we need to delete the file and then fresh everything. if (File.Exists(game.path)) { File.Delete(game.path); } //Reload the list RefreshSaveData(true); } } }
protected void Button1_Click(object sender, EventArgs e) { if (TextBox1.Text != "") { this.Session["userName"] = TextBox1.Text; if (Request.Cookies[TextBox1.Text + "SaveGame"] != null) { saveGame = (SavedGame) new JavaScriptSerializer().Deserialize(Request.Cookies[TextBox1.Text + "SaveGame"].Value, saveGame.GetType()); this.Session["savedGame"] = saveGame; Response.Redirect(saveGame._URL); } else { Response.Redirect("http://localhost:1580/memory%20game/Level2.aspx"); } } }
public static void ComputedStats() { string encodedSaveData = TestData.ReadAllText("ValidZlib.txt"); SavedGame savedGame = SavedGame.Parse(encodedSaveData); ComputedStats computedStats = new(savedGame); Assert.Equal("1.002390000000000000e+005", computedStats.HeroSoulsSpent); Assert.Equal("5.223865765430567e99", computedStats.HeroSoulsSacrificed); Assert.Equal("5.22386475134114e99", computedStats.TitanDamage); Assert.Equal(498, computedStats.TotalAncientSouls); Assert.Equal(0.051918352081052083, computedStats.TranscendentPower); Assert.Equal(260, computedStats.Rubies); Assert.Equal(695, computedStats.HighestZoneThisTranscension); Assert.Equal(23274, computedStats.HighestZoneLifetime); Assert.Equal(4, computedStats.AscensionsThisTranscension); Assert.Equal(3080, computedStats.AscensionsLifetime); }
void OnSavedGameRead(SavedGame game, byte[] bytesData, string error) { if (!string.IsNullOrEmpty(error)) { isSuccess.Value = false; errorDescription.Value = error; Fsm.Event(eventTarget, isNotSuccessEvent); Finish(); } else { data.Value = Convert.ToBase64String(bytesData); isSuccess.Value = true; Fsm.Event(eventTarget, isSuccessEvent); Finish(); } }
public static void Init(int _seed) { buildingsByPos.Clear(); resourceTilesByPos.Clear(); data = new SavedGame(); data.seed = _seed; //HACK: can we get this value from somewhere else? data.augmentIndexes = new List <int> (); for (int i = 0; i < 4; i++) { data.augmentIndexes.Add(0); } GameManager.instance.SaveThisTurn(); }
private void doLoadGame(object i_MethodInvoker) { Thread.Sleep(1000); m_SavedGame = (SavedGame)FileIO.ReadObjectFrom(m_CurrentFileName); (i_MethodInvoker as MethodInvoker).Invoke(); }
//-------------------------------------------------------------------------------------------- public bool loadSavedGame(string name) { //if our games map doesn't contain a game w/ the given name... if(!mGamesMap.ContainsKey(name) || name == "") { //return false -- no game loaded return false; } Debug.Log("LOADING SAVED GAME: " + name); //otherwise, set the current game object mCurrentGame = mGamesMap[name]; return true; }
public static void Serialize(SavedGame sg, string filename) { FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write); try { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, sg); } finally { fs.Close(); Console.WriteLine("Saved!"); } }
public override object Read(ES2Reader reader) { SavedGame data = new SavedGame(); Read(reader, data); return data; }
//-------------------------------------------------------------------------------------------- public bool deleteSavedGame(string name) { //if the games map doesn't contain a game w/ the given name... if(!mGamesMap.ContainsKey(name) || name == "") { //return false -- no game deleted return false; } Debug.Log("DELETING SAVED GAME: " + name); //otherwise, delete the saved game object mGamesMap.Remove(name); //delete the current game if it is being deleted if(mCurrentGame != null && mCurrentGame.getName() == name) { mCurrentGame = null; } //major change -- write out to file writeSavedGameFile(); return true; }
//-------------------------------------------------------------------------------------------- public bool createNewGame(string name) { //if our games map contains a game w/ the given name... if(mGamesMap.ContainsKey(name) || name == "") { //return false -- no new game created return false; } Debug.Log("CREATING NEW SAVED GAME: " + name); //otherwise, create a new game object mCurrentGame = new SavedGame(name); mGamesMap.Add(name, mCurrentGame); //major change -- write out to file writeSavedGameFile(); return true; }
//-------------------------------------------------------------------------------------------- private bool readSavedGameFile() { //init global high scores to default values globalHighScores = new int[NUM_GAMEPLAY_LEVELS]; for(int i = 0; i < globalHighScores.Length; ++i) { globalHighScores[i] = 0; } //try to create a file reader StreamReader reader; try { reader = new StreamReader(mSavedGameFile); } catch { Debug.Log("ERROR: UNABLE TO CREATE STREAM READER"); return false; } //if the file is not empty... if(reader.Peek() != -1) { //tokenize the first line, return if there's an error int[] array = new int[NUM_GAMEPLAY_LEVELS]; if(!tokenizeInts(reader.ReadLine(), array)) { Debug.Log("ERROR: ERROR READING GLOBAL HIGH SCORES"); reader.Close(); return false; } globalHighScores = array; } else { Debug.Log("ERROR: ERROR READING GLOBAL HIGH SCORES"); reader.Close(); return false; } //read saved game data until the end of the file... while(!reader.EndOfStream) { string name = ""; //read the next line (game name) name = reader.ReadLine(); if(name == null || name == "" || name[0] != '$') //skip if there was any problem continue; //create a new saved game object name = name.Remove(0, 1); SavedGame game = new SavedGame(name); //read high scores for current game int[] highscores = new int[NUM_GAMEPLAY_LEVELS]; if(!tokenizeInts(reader.ReadLine(), highscores)) continue; //read level unlocks for current game bool[] levelUnlocks = new bool[NUM_GAMEPLAY_LEVELS]; if(!tokenizeBools(reader.ReadLine(), levelUnlocks)) continue; //read final chassis use for current game bool[] finalChassis = new bool[NUM_GAMEPLAY_LEVELS]; if(!tokenizeBools(reader.ReadLine(), finalChassis)) continue; //read chasis unlocks for current game bool[] chasis = new bool[Loadout.NUM_LOADOUTS]; if(!tokenizeBools(reader.ReadLine(), chasis)) continue; //read primary unlocks for current game bool[] primary = new bool[Loadout.NUM_LOADOUTS]; if(!tokenizeBools(reader.ReadLine(), primary)) continue; //read secondary unlocks for current game bool[] secondary = new bool[Loadout.NUM_LOADOUTS]; if(!tokenizeBools(reader.ReadLine(), secondary)) continue; //set the values for the current game game.highScores = highscores; game.unlockedLevels = levelUnlocks; game.finalChassis = finalChassis; game.unlockedChasis = chasis; game.unlockedPrimary = primary; game.unlockedSecondary = secondary; //add the game to the list of saved games mGamesMap.Add(name, game); } reader.Close(); return true; }
private void doSaveGame(object i_MethodInvoker) { Thread.Sleep(1000); var savedGame = new SavedGame { Board = r_BoardController.GetModel().GetBoard(), MovesHistory = r_StatusController.GetMovesLog(), CurrentTurn = r_BoardController.getCurrentPlayer() }; FileIO.SaveObjectToFile(m_CurrentFileName, savedGame); (i_MethodInvoker as MethodInvoker).Invoke(); }
//-------------------------------------------------------------------------------------------- public bool deleteSavedGame(string name) { //if the games map doesn't contain a game w/ the given name... if(!mGamesMap.ContainsKey(name)) { //return false -- no game deleted return false; } //otherwise, delete the saved game object mGamesMap.Remove(name); if(mCurrentGame.getName() == name) { mCurrentGame = null; } return true; }