Esempio n. 1
0
 protected override void saveMe(SaveGameData savegame)
 {
     base.saveMe(savegame);
     SaveGameData.BarrelData barrelData = savegame.findBarrelDataByID(ID);
     if (barrelData == null)
     {
         barrelData = new SaveGameData.BarrelData();
         savegame.barrelData.Add(barrelData);
     }
     barrelData.ID       = ID;
     barrelData.position = transform.position;
     barrelData.rotation = transform.rotation.eulerAngles;
 }
Esempio n. 2
0
        protected override void Initialize()
        {
            wreckingBall = new WreckingBall(this, new Vector2(500, 0), Color.White, 0.5f);
            mouse        = new MouseHandler(this);
            brickManager = new BrickManager(this, new Vector2(600, 0));
            _turn        = 1;

            HighScoreManager hsm = new HighScoreManager(this);

            highScore = hsm.ReadData();

            base.Initialize();
        }
Esempio n. 3
0
    override protected void saveme(SaveGameData savegame)
    {
        base.saveme(savegame);

        SaveGameData.BarrelData data = savegame.findBarrelDataByID(ID);
        if (data == null)
        {
            data = new SaveGameData.BarrelData();
            savegame.barrelData.Add(data);
        }
        data.ID       = ID;
        data.position = transform.position;
    }
 public void Load(SaveGameData p_data)
 {
     if (p_data != null)
     {
         Int32 num = p_data.Get <Int32>("Count", 0);
         for (Int32 i = 0; i < num; i++)
         {
             Int32  p_type = p_data.Get <Int32>("buffType_" + i, 1);
             Single p_castersMagicFactor = p_data.Get <Single>("castersMagicValue_" + i, 1f);
             m_buffList.Add(BuffFactory.CreateMonsterBuff((EMonsterBuffType)p_type, p_castersMagicFactor));
         }
     }
 }
        public override void Save(SaveGameData p_data)
        {
            base.Save(p_data);
            p_data.Set <Int32>("ConditionCount", m_conditions.Count);
            Int32 num = 0;

            foreach (ObjectCondition objectCondition in m_conditions)
            {
                p_data.Set <Int32>("ID" + num, objectCondition.id);
                p_data.Set <Int32>("State" + num, (Int32)objectCondition.wantedState);
                num++;
            }
        }
        internal void Load(SaveGameData p_data)
        {
            m_Existent = p_data.Get <Boolean>("Existent", false);
            Int32    x              = p_data.Get <Int32>("X", 0);
            Int32    y              = p_data.Get <Int32>("Y", 0);
            String   p_mapname      = p_data.Get <String>("MapName", null);
            String   p_locaKey      = p_data.Get <String>("LocaMapName", null);
            Int32    p_worldPointID = p_data.Get <Int32>("MapPointID", 0);
            Position p_position     = new Position(x, y);

            m_SpiritBeacon = new SpiritBeaconPosition(p_position, p_mapname, p_locaKey, p_worldPointID);
            LegacyLogic.Instance.EventManager.InvokeEvent(this, EEventType.SPIRIT_BEACON_UPDATE, EventArgs.Empty);
        }
        //Called when loading a save game
        void TryEnableEnemyRandomizerFromSave(SaveGameData data)
        {
            if (Settings != null)
            {
                GameSeed = PlayerSettingsSeed;
            }
            else
            {
                GameSeed = OptionsMenuSeed;
            }

            EnableEnemyRandomizer();
        }
Esempio n. 8
0
        async Task SaveAsync(SaveGameData saveData)
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("SynesthesiaSave", CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);

            using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
            {
                // Serialize the Session State.
                DataContractSerializer serializer = new DataContractSerializer(typeof(SaveGameData));
                serializer.WriteObject(outStream.AsStreamForWrite(), saveData);
                await outStream.FlushAsync();
            }
        }
 private void Loadme(SaveGameData savegame)
 {
     if (savegame != null &&
         gameObject.scene.buildIndex == savegame.currentLevel)
     {
         SaveObject saveObject = savegame.FindObjectById(gameObject.name);
         switch ((saveObject != null) ? saveObject.Tag : "")
         {
         case "barrel":
             transform.position = saveObject.Position;
             break;
         }
     }
 }
Esempio n. 10
0
        public void Save(SaveGameData p_data)
        {
            p_data.Set <Int32>("NpcFactoryCount", m_npcs.Count);
            Int32 num = 0;

            foreach (KeyValuePair <Int32, Npc> keyValuePair in m_npcs)
            {
                p_data.Set <Int32>("NpcID" + num, keyValuePair.Key);
                SaveGameData saveGameData = new SaveGameData("Npc" + num);
                keyValuePair.Value.Save(saveGameData);
                p_data.Set <SaveGameData>(saveGameData.ID, saveGameData);
                num++;
            }
        }
Esempio n. 11
0
    public static void SaveGameSystem()
    {
        Debug.Log("Saving Game");
        // Save all values into binary or smth
        BinaryFormatter formatter = new BinaryFormatter();
        //string path = Application.persistentDataPath + "/ingredients.bla";
        string     path   = "SaveGame.bla";
        FileStream stream = new FileStream(path, FileMode.Create);

        SaveGameData data = new SaveGameData();

        formatter.Serialize(stream, data);
        stream.Close();
    }
Esempio n. 12
0
 public static void SaveGame(SaveGameData data)
 {
     try
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream      fs = new FileStream(Path + "/game.save", FileMode.Create);
         bf.Serialize(fs, data);
         fs.Close();
     }
     catch (Exception e)
     {
         Debug.LogWarning("Load Game: " + e.Message);
     }
 }
Esempio n. 13
0
 public void LoadSaveGame(SaveGameData savegame)
 {
     this.Health             = savegame.Health;
     this.Mana               = savegame.Mana;
     this.Knowledge          = savegame.Knowledge;
     this.Defense            = savegame.Defense;
     this.Experience         = savegame.Experience;
     this.IsFighting         = savegame.IsFighting;
     this.Level              = savegame.Level;
     this.Location           = new PointF(savegame.Location);
     this.Position           = new Point(savegame.Position);
     this.NextUpgrade        = savegame.NextUpgradeExperience;
     this.IsAnimationEnabled = false;
 }
Esempio n. 14
0
        public override void Load(SaveGameData p_data)
        {
            m_conditions.Clear();
            base.Load(p_data);
            Int32 num = p_data.Get <Int32>("ConditionCount", 0);

            for (Int32 i = 0; i < num; i++)
            {
                ObjectCondition item;
                item.id          = p_data.Get <Int32>("ID" + i, 0);
                item.wantedState = p_data.Get <EInteractiveObjectState>("State" + i, EInteractiveObjectState.NONE);
                m_conditions.Add(item);
            }
        }
        public void Save(SaveGameData p_data)
        {
            p_data.Set <Int32>("OfferCount", m_offers.Count);
            Int32 num = 0;

            foreach (TradingItemOffer tradingItemOffer in m_offers)
            {
                p_data.Set <Int32>("OfferID" + num, tradingItemOffer.OfferData.StaticID);
                SaveGameData saveGameData = new SaveGameData("Offer" + num);
                tradingItemOffer.Save(saveGameData);
                p_data.Set <SaveGameData>(saveGameData.ID, saveGameData);
                num++;
            }
        }
    public void loadGame(bool restartLevel, int slot = 0)
    {
        string saveFile = "/save00" + slot + ".dat";

        Debug.Log(" $$$$$$$$$$$$$$$$$$ loading file: " + saveFile + " $$$$$$$$$$$$ ");
        if (restartLevel)
        {
            saveFile = "/save000.cp.dat";
        }

        if (File.Exists(Application.persistentDataPath + saveFile))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream      file      = File.Open(Application.persistentDataPath + saveFile, FileMode.Open);
            SaveGameData    data      = (SaveGameData)formatter.Deserialize(file);
            file.Close();

            savedLocation = data.locationName;

            /* rebuild storage from serialized data */
            pickedUpObjectDB         = data.pickedUpObjectDB;
            currentPickedUpListIndex = data.currentPickedUpListIndex;

            SerializableDictionary dict = data.dict;
            _storage = new DataStorage();
            _storage.initialize();
            for (int i = 0; i < dict.bKey.Count; ++i)
            {
                _storage.storeBoolValue(dict.bKey[i], dict.bValue[i]);
            }
            for (int i = 0; i < dict.fKey.Count; ++i)
            {
                _storage.storeFloatValue(dict.fKey[i], dict.fValue[i]);
            }
            for (int i = 0; i < dict.iKey.Count; ++i)
            {
                _storage.storeIntValue(dict.iKey[i], dict.iValue[i]);
            }
            for (int i = 0; i < dict.sKey.Count; ++i)
            {
                _storage.storeStringValue(dict.sKey[i], dict.sValue[i]);
            }
        }
        else             // new game

        {
            _storage.storeBoolValue("PlayerMustMaterialize", true);
        }
    }
        public Int32 SaveItem(EEquipSlots p_slot, Int32 p_counter, BaseItem p_item, SaveGameData p_data)
        {
            p_data.Set <Int32>("Slot" + p_counter, (Int32)p_slot);
            EDataType itemType = p_item.GetItemType();

            p_data.Set <Int32>("DataType" + p_counter, (Int32)itemType);
            if (itemType != EDataType.NONE)
            {
                SaveGameData saveGameData = new SaveGameData("Item" + p_counter);
                p_item.Save(saveGameData);
                p_data.Set <SaveGameData>(saveGameData.ID, saveGameData);
            }
            p_counter++;
            return(p_counter);
        }
Esempio n. 18
0
    public static SaveGameData loadSave()
    {
        if (!File.Exists(savePath))
        {
            Debug.LogError("Save file not found");
            return(null);
        }

        BinaryFormatter formatter    = new BinaryFormatter();
        FileStream      fileStream   = new FileStream(savePath, FileMode.Open);
        SaveGameData    saveGameData = formatter.Deserialize(fileStream) as SaveGameData;

        fileStream.Close();
        return(saveGameData);
    }
Esempio n. 19
0
    private void OnTriggerEnter(Collider other)
    {
        Player player = FindObjectOfType <Player>();

        if (other.gameObject == player.gameObject)
        {
            SaveGameData saveGame = SaveGameData.current;

            if (player.health > 0 && saveGame.lastSaveGameTriggerID != saveGameTriggerID)
            {
                saveGame.lastSaveGameTriggerID = saveGameTriggerID;
                saveGame.save();
            }
        }
    }
Esempio n. 20
0
    /// <summary>
    /// Call this to save our game in its current state
    /// </summary>
    public void SaveGame()
    {
        if (GameCurrentlySaving)
        {
            return;
        }
        GameCurrentlySaving = true;
        SaveGameData SaveData = new SaveGameData();

        SaveData.TimeOfSave = DateTime.Now;

        Thread SaveGameThread = new Thread(() => Threaded_SaveGame(SaveData, SAVE_GAME_PATH));

        SaveGameThread.Start();
    }
Esempio n. 21
0
 public void Save(SaveGameData p_data)
 {
     p_data.Set <Int32>("HirelingCount", 2);
     for (Int32 i = 0; i < 2; i++)
     {
         if (m_hirelings[i] != null)
         {
             p_data.Set <Int32>("Hireling" + i, m_hirelings[i].StaticID);
         }
         else
         {
             p_data.Set <Int32>("Hireling" + i, -1);
         }
     }
 }
Esempio n. 22
0
        public void Save(SaveGameData p_data)
        {
            Int32 num = 0;

            foreach (KeyValuePair <Int32, Int32> keyValuePair in m_tokens)
            {
                if (keyValuePair.Value > 0)
                {
                    p_data.Set <Int32>("TokenKey" + num, keyValuePair.Key);
                    p_data.Set <Int32>("TokenValue" + num, keyValuePair.Value);
                    num++;
                }
            }
            p_data.Set <Int32>("Count", num);
        }
Esempio n. 23
0
    public void SaveGame(int val)
    {
        BinaryFormatter bf   = new BinaryFormatter();
        FileStream      file = File.Create(Path.Combine(Application.streamingAssetsPath, FILE_PATH));

        SaveGameData save = new SaveGameData
        {
            lifes = vidas,
            coins = moedas
        };

        bf.Serialize(file, save);

        file.Close();
    }
Esempio n. 24
0
        public void Load(SaveGameData p_data)
        {
            m_tokens.Clear();
            Int32 num = p_data.Get <Int32>("Count", 0);

            for (Int32 i = 0; i < num; i++)
            {
                Int32 num2 = p_data.Get <Int32>("TokenKey" + i, -1);
                Int32 num3 = p_data.Get <Int32>("TokenValue" + i, -1);
                if (num2 != -1 && num3 != -1)
                {
                    m_tokens.Add(num2, num3);
                }
            }
        }
Esempio n. 25
0
 void LoadWorld(string filename)
 {
     if (File.Exists(Application.persistentDataPath + filename))
     {
         // then load it
         string jsonString = File.ReadAllText(Application.persistentDataPath + filename);
         // do something with the json file:
         SaveGameData gameData = JsonUtility.FromJson <SaveGameData>(jsonString);
         // then apply that savegamedata to the world
     }
     else
     {
         // error
     }
 }
    /// <summary>
    /// Lädt einen Spielstand.
    /// </summary>
    public static SaveGameData LoadData()
    {
        SaveGameData save     = new SaveGameData();
        string       fileName = GetFilename(dataName);

        if (File.Exists(fileName))
        {
            save = XmlUtils.Load <SaveGameData>(File.ReadAllText(fileName));
        }
        if (OnLoad != null)
        {
            OnLoad(save);
        }
        return(save);
    }
Esempio n. 27
0
    public bool LoadPlayerData()
    {
        GameLog log = SaveGameData.LoadPlayerDetails();

        if (log != null)
        {
            isMuted        = log.muteStats;
            levelsUnlocked = log.levelsUnlocked;
            return(true);
        }
        else
        {
            return(false);
        }
    }
Esempio n. 28
0
        public void Load(SaveGameData p_data)
        {
            Int32 num = p_data.Get <Int32>("FoundBooksCount", 0);

            for (Int32 i = 0; i < num; i++)
            {
                AddLoreBook(p_data.Get <Int32>("FoundBookID" + i, 0), true);
            }
            Int32 num2 = p_data.Get <Int32>("FoundBooksNewEntriesCount", 0);

            for (Int32 j = 0; j < num2; j++)
            {
                m_newEntries.Add(p_data.Get <Int32>("FoundBooksNewEntry" + j, 0));
            }
        }
    private void Saveme(SaveGameData savegame)
    {
        SaveObject saveObject = savegame.FindObjectById(gameObject.name);

        if (saveObject == null)
        {
            saveObject = new SaveObject();
            UpdateSaveObject(saveObject);
            savegame.saveObject.Add(saveObject);
        }
        else
        {
            UpdateSaveObject(saveObject);
        }
    }
Esempio n. 30
0
        public void SaveGame(SaveGameData saveGameData, string containerName, string fileName)
        {
            device = null;
            this.saveGameData = saveGameData;
            this.containerName = containerName;
            this.fileName = fileName;

            try
            {
                StorageDevice.BeginShowSelector(PlayerIndex.One, this.SaveToFile, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 31
0
        private void load_button_Click(object sender, EventArgs e)
        {
            combatLog.Clear();
            combatLog.AppendText("Game has been loaded.\n");
            string path = Environment.CurrentDirectory + @"\Saves\Stats";

            Utilities.DeserializeXML <SaveGameData>(path);
            SaveGameData save = Utilities.DeserializeXML <SaveGameData>(path);

            player.health     = save.SaveHealth;
            player.strength   = save.SaveStrength;
            player.level      = save.SaveLevel;
            player.experience = save.SaveExperience;
            enemy.health      = 50;
            updateLabels();
        }
Esempio n. 32
0
 public Form1()
 {
     InitializeComponent();
     phase_label.Text = GameState.init.ToString();
     attack.Enabled = false;
     enemy_attack.Enabled = false;
     GAMEFSM = new FSM<GameState>(GameState.init);
     GAMEFSM.AddState(GameState.init);
     GAMEFSM.AddState(GameState.player);
     GAMEFSM.AddState(GameState.enemy);
     GAMEFSM.AddState(GameState.end);
     GAMEFSM.AddTransition(GameState.init, GameState.player);
     GAMEFSM.AddTransition(GameState.player, GameState.enemy);
     GAMEFSM.AddTransition(GameState.enemy, GameState.player);
     GAMEFSM.AddTransition(GameState.player, GameState.end);
     GAMEFSM.AddTransition(GameState.enemy, GameState.end);
     SuperSave = new SaveGameData();
 }
Esempio n. 33
0
    public static void SaveGame(SaveGameData saveGameData, string name)
    {

        BinaryFormatter formatter = new BinaryFormatter();

        string fullpath = GetSavePath(name);

        using (FileStream stream = new FileStream(fullpath, FileMode.Create))
        {
            try
            {
                formatter.Serialize(stream, saveGameData);
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
                return;
            }
        }

        Debug.Log("Saved to " + fullpath);
    }
Esempio n. 34
0
        public void saveGame(StorageDevice device)
        {
            Console.WriteLine("Saving");
            SaveGameData data = new SaveGameData();
            data.currentPlayerZone = -4;
            data.currentPlayerLevel = 0;
            data.playerPosition = new Vector2(400, 600);
            data.fireEnergy = 9999;
            data.waterEnergy = 9999;
            data.natureEnergy = 9999;
            data.currentFireEnergy = 100;
            data.currentWaterEnergy = 9375;
            data.currentNatureEnergy = 9;

            IAsyncResult result = device.BeginOpenContainer("Container", null, null);
            result.AsyncWaitHandle.WaitOne();
            StorageContainer container = device.EndOpenContainer(result);
            result.AsyncWaitHandle.Close();

            string filename = "savegame.sav";

            if (container.FileExists(filename))
            {
                container.DeleteFile(filename);
            }

            Stream stream = container.CreateFile(filename);

            XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
            serializer.Serialize(stream, data);

            stream.Close();

            container.Dispose();

            saveRequested = false;
            Console.WriteLine("save complete");
        }
Esempio n. 35
0
    public TitleScreen(GraphicsDeviceManager gdm, SaveGameData _gameData)
    {
        PersonalLoadContent();
        int levelReach = _gameData.levelReached[_gameData.worldReached];
        menuState = GameMenuState.MenuStateMain;
        nextState = GameMenuState.MenuStateMain;

        SetDrawFrame(position);
        SetDrawTexture(titleScreenTexture);

        gamePlay = new Button(
            new Rectangle(  GraphicsDeviceManager.DefaultBackBufferWidth/2 - playButtonTexture.Width/2,
                            GraphicsDeviceManager.DefaultBackBufferHeight/2 - playButtonTexture.Height/2,
                            playButtonTexture.Width, playButtonTexture.Height), playButtonTexture);
        gamePlay.animatedBlink(15,-1);

        gameOption = new Button(new Rectangle(30, 380, 70, 70), gameOptionsTexture);

        back = new Button(new Rectangle(10, 60, 128, 64), backButtonTexture);

        cityChapterButton = new Button(new Rectangle(60, 140, 167, 99), cityChapterSelectTexture);
        caveChapterButton = new Button(new Rectangle(60, 330, 167, 99), caveChapterSelectTexture);
        cityChallengeChapterButton = new Button(new Rectangle(560, 140, 167, 99), cityChallengeChapterSelectTexture);
        caveChallengeChapterButton = new Button(new Rectangle(560, 330, 167, 99), caveChallengeChapterSelectTexture);
        tempContinueButton = new Button(new Rectangle(80, 380, 200, 80), devContinueTexture);
        // this if else is for checking if you are in the top row or bottom row of levels
        if (levelReach <= MAX_LEVELS/2)
        {
            for (int i = 0; i <= levelReach; i++)
            {
                Button b = new Button(new Rectangle(10 + i * 160, 150, 150, 100), devUnlockedTexture);
                b.setExtra(i);
                lockedLevels.AddLast(b);

            }
            for (int i = levelReach + 1; i <= MAX_LEVELS/2; i++)
            {
                Button b = new Button(new Rectangle(10 + i * 160, 150, 150, 100), devLockedTexture);
                b.setExtra(i);
                lockedLevels.AddLast(b);
            }
            for (int i = 0; i < MAX_LEVELS/2; i++)
            {
                Button b = new Button(new Rectangle(10 + i * 160, 300, 150, 100), devLockedTexture);
                b.setExtra(MAX_LEVELS/2+i);
                lockedLevels.AddLast(b);
            }
        }
        else
        {
            for (int i = 0; i < MAX_LEVELS/2; i++)
            {
                Button b = new Button(new Rectangle(10 + i * 160, 150, 150, 100), devUnlockedTexture);
                b.setExtra(i);
                lockedLevels.AddLast(b);
            }
            for (int i = 0; i <= levelReach-MAX_LEVELS/2; i++)
            {
                Button b = new Button(new Rectangle(10 + i * 160, 300, 150, 100), devUnlockedTexture);
                b.setExtra(MAX_LEVELS / 2 + i);
                lockedLevels.AddLast(b);
            }
            for (int i = levelReach-MAX_LEVELS/2 + 1; i < MAX_LEVELS- MAX_LEVELS/2; i++)
            {
                Button b = new Button(new Rectangle(10 + i * 160, 300, 150, 100), devLockedTexture);
                b.setExtra(MAX_LEVELS/2 + i);
                lockedLevels.AddLast(b);
            }
        }
        flag = GameMenuFlag.NoFlag;

        MusicManager.SetSong(associatedMusic);
        MusicManager.StartMusic();

        //Not sure why this doesnt work, but we'll need it eventually
        //System.IO.DirectoryInfo contentDir = new System.IO.DirectoryInfo("Level");
        //chapterFiles = contentDir.GetFiles();

        showOptionMenu = false;
        //optionAnimationTransition = false;
        optionsListView = new View(optionsClosed, gameOptionsTexture);

        pressedButton = cityChapterButton;

        PrepareNextState();
    }
Esempio n. 36
0
File: Game.cs Progetto: bmh10/RedMan
        // This method serializes a data object into
        // the StorageContainer for this game.
        public static void DoSaveGame()
        {
            IAsyncResult r = StorageDevice.BeginShowSelector(
                         PlayerIndex.One, null, null);
            StorageDevice device = StorageDevice.EndShowSelector(r);

            // Create the data to save.
            SaveGameData data = new SaveGameData();
            data.furthestLevelReached = Level.FurthestLevelReached;
            data.Score = Player.Score;

            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("SavedGames", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string filename = "savegame.sav";

            // Check to see whether the save exists.
            if (container.FileExists(filename))
                // Delete it so that we can create one fresh.
                container.DeleteFile(filename);

            // Create the file.
            Stream stream = container.CreateFile(filename);

            // Convert the object to XML data and put it in the stream.
            XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
            serializer.Serialize(stream, data);

            // Close the file.
            stream.Close();

            // Dispose the container, to commit changes.
            container.Dispose();
        }
Esempio n. 37
0
 /* Sprite cannot be serialized beacuse Texture2D is not serializable! */
 public SaveGameData GetSaveGameData()
 {
     SaveGameData data = new SaveGameData();
     /*data.sprite = sprite;
     data.shot = shot;
     data.enemies = enemies;*/
     data.time = time;
     data.lifes = lifes;
     data.score = score;
     return data;
 }
Esempio n. 38
0
 private void enemy_attack_Click(object sender, EventArgs e)
 {
     enemyHandler();
     SaveGameData save = new SaveGameData(player.health, player.strength, player.level, player.experience);
     SuperSave = save;
 }
Esempio n. 39
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            //Keyboard
            oldstate = new KeyboardState();

            //Initialize the player
            player.Initialize(playerWidth, playerHeight, Content, (screenCenter - playerWidth/2), 2 * screenHeight / 3);

            //Load Heart sprite
            heart_sprite = Content.Load<Texture2D>("heart");


            //Load Backgrounds
            bg[0] = Content.Load<Texture2D>("background/bg0");
            bg[1] = Content.Load<Texture2D>("background/bg1");
            bg[2] = Content.Load<Texture2D>("background/bg2");
            bg[3] = Content.Load<Texture2D>("background/bg3");
            bg[4] = Content.Load<Texture2D>("background/bg4");
            bg[5] = Content.Load<Texture2D>("background/bg5");
            bg[6] = Content.Load<Texture2D>("background/bg6");
            bg[7] = Content.Load<Texture2D>("background/bg7");
            bg[8] = Content.Load<Texture2D>("background/bg8");
            bg[9] = Content.Load<Texture2D>("background/bg9");
            bg[10] = Content.Load<Texture2D>("background/bg10");
            bg[11] = Content.Load<Texture2D>("background/bg11");
            bg[12] = Content.Load<Texture2D>("background/bg12");
            bg[13] = Content.Load<Texture2D>("background/bg13");
            bg[14] = Content.Load<Texture2D>("background/bg14");
            bg[15] = Content.Load<Texture2D>("background/bg15");
            bg[16] = Content.Load<Texture2D>("background/bg16");
            bg[17] = Content.Load<Texture2D>("background/bg17");
            bg[18] = Content.Load<Texture2D>("background/bg18");
            bgx = Content.Load<Texture2D>("background/bgx");
            blocker_bg = Content.Load<Texture2D>("background/blocker_bg");
            parallaxImage[0] = Content.Load<Texture2D>("background/parallax");
            parallaxImage[1] = Content.Load<Texture2D>("background/parallax2");
            parallaxImage[2] = Content.Load<Texture2D>("background/parallax3");
            parallaxImage[3] = Content.Load<Texture2D>("background/parallax4");
            title = Content.Load<Texture2D>("title");
            gameover = Content.Load<Texture2D>("gameover");
            paused = Content.Load<Texture2D>("paused");

            for (int i = 0; i < numParallax; i++)
            {
                parallaxPosition[0, i] = new Vector2(-parallaxImage[i].Width, 0);
                parallaxPosition[1, i] = new Vector2(0, 0);
            }


            //Load Collisions
            cm[0] = Content.Load<Texture2D>("cm/cm0");
            cm[1] = Content.Load<Texture2D>("cm/cm1");
            cm[2] = Content.Load<Texture2D>("cm/cm2");
            cm[3] = Content.Load<Texture2D>("cm/cm3");
            cm[4] = Content.Load<Texture2D>("cm/cm4");
            cm[5] = Content.Load<Texture2D>("cm/cm5");
            cm[6] = Content.Load<Texture2D>("cm/cm6");
            cm[7] = Content.Load<Texture2D>("cm/cm7");
            cm[8] = Content.Load<Texture2D>("cm/cm8");
            cm[9] = Content.Load<Texture2D>("cm/cm9");
            cm[10] = Content.Load<Texture2D>("cm/cm10");
            cm[11] = Content.Load<Texture2D>("cm/cm11");
            cm[12] = Content.Load<Texture2D>("cm/cm12");
            cm[13] = Content.Load<Texture2D>("cm/cm13");
            cm[14] = Content.Load<Texture2D>("cm/cm14");
            cm[15] = Content.Load<Texture2D>("cm/cm15");
            cm[16] = Content.Load<Texture2D>("cm/cm16");
            cm[17] = Content.Load<Texture2D>("cm/cm17");
            cm[18] = Content.Load<Texture2D>("cm/cm18");
            cmx = Content.Load<Texture2D>("cm/cmx");
            blocker_cm = Content.Load<Texture2D>("cm/blocker_cm");
            for (int i = 0; i < numStages; i++)
            {
                //Make an array out of each cm and add it to the list.
                collisionColorArray.AddLast(make_collision_color(cm[i]));
            }
            //Add the last 2 cms
            collisionColorArray.AddLast(make_collision_color(cmx));
            collisionColorArray.AddLast(make_collision_color(blocker_cm));

            //Fonts
            scoreFont = Content.Load<SpriteFont>("fonts/ScoreFont");

            //Stages
            stages.AddLast(new Stage(bg[0], cm[0], collisionColorArray.ElementAt(0), -bg[0].Width/2, 0, graphics.GraphicsDevice));
            stages.AddLast(new Stage(bg[1], cm[1], collisionColorArray.ElementAt(1), stages.ElementAt(0).position.X + stages.ElementAt(0).width, 0, graphics.GraphicsDevice));

            //Score
            if (!dataLoaded)
            {
                highscores = new SaveGameData(10);
                load_data();
                dataLoaded = true;
            }
            
            //Sound
            waveManager.LoadWave("Content/music.wav", "bgm");
            beat = Content.Load<SoundEffect>("beat");
            offbeat = Content.Load<SoundEffect>("offbeat");
            clap = Content.Load<SoundEffect>("clap");
            snare = Content.Load<SoundEffect>("snare");
            hihat = Content.Load<SoundEffect>("hihat");
            hit = Content.Load<SoundEffect>("hit");
            ground = Content.Load<SoundEffect>("ground");

            ground_instance = ground.CreateInstance();
            ground_instance.Volume = 0.5f;
        }
        /// <summary>
        /// Load the save game.
        /// </summary>
        /// <remarks>Only works on Windows Phone.</remarks>
        public void ReadSaveGameXML()
        {
#if WINDOWS_PHONE || __ANDROID__
            try
            {
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(fileName, FileMode.Open))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
                        mSaveData = (SaveGameData)serializer.Deserialize(stream);
                        LeaderBoardManager.pInstance.SetRecords(mSaveData.mRecords);
                        TutorialManager.pInstance.pTutorialCompleted = mSaveData.mTutorialComplete;
                    }
                }
            }
            catch
            {
                // Something
            }
#endif
        }
Esempio n. 41
0
        public static void SaveGame(StorageDevice device, SignedInGamer gamer)
        {
            SaveGameData data = new SaveGameData();
            data.CurrentLevel = level;
            data.SavedPlayerScore = score;
            data.SavedCheckPoint = checkPoint;

            IAsyncResult result =
                device.BeginOpenContainer(gamer.Gamertag, null, null);

            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();
            //.sav is important
            string filename = "LbKSavedInfo.sav";

            if (!container.FileExists(filename))
            {
                Stream file = container.CreateFile(filename);

                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

                serializer.Serialize(file, data);

                file.Close();
            }
            else
            {

                container.DeleteFile(filename);

                Stream file = container.CreateFile(filename);

                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

                serializer.Serialize(file, data);

                file.Close();
            }

            // Dispose the container, to commit the data.
            container.Dispose();
        }
Esempio n. 42
0
        void PutLevelStats()
        {
            save = new SaveGameData();
            save.LevelStat = new LevelStats[32];

            for (int i = 0; i < 32; ++i)
               save.LevelStat[i] = LevelStat[i];
        }
Esempio n. 43
0
        async Task RestoreAsync()
        {
            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("SynesthesiaSave");
                IRandomAccessStream inStream = await file.OpenReadAsync();
                // Deserialize the Session State.
                DataContractSerializer serializer = new DataContractSerializer(typeof(SaveGameData));
                highscores = (SaveGameData)serializer.ReadObject(inStream.AsStreamForRead());

                inStream.Dispose();
            }
            catch
            {
                return;
            }
        }
Esempio n. 44
0
 public void SetSaveGameData(SaveGameData data)
 {
     /*sprite = data.sprite;
     shot = data.shot;
     enemies = data.enemies;*/
     time = data.time;
     lifes = data.lifes;
     score = data.score;
 }
Esempio n. 45
0
        void OpenSave(StorageDevice device)
        {
            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer(GameTitle, null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string filename = "savegame.sav";

            // Check to see whether the save exists.
            if (!container.FileExists(filename))
            {
                GetLevelStats();
                // If not, dispose of the container and return.
                container.Dispose();
                return;
            }

            // Open the file.
            Stream stream = container.OpenFile(filename, FileMode.Open);

            XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

            SaveGameData data = (SaveGameData)serializer.Deserialize(stream);

            save = data;

            GetLevelStats(save);

            GetLevelNum();

            // Close the file.
            stream.Close();

            // Dispose the container.
            container.Dispose();
        }
Esempio n. 46
0
 private void newGame_button_Click(object sender, EventArgs e)
 {
     combatLog.Clear();
     player.health = 100;
     player.strength = 10;
     player.level = 1;
     player.experience = 0;
     enemy.health = 50;
     enemy.strength = 3;
     GAMEFSM.Switch(GameState.player);
     updateLabels();
     attack.Enabled = true;
     enemy_attack.Enabled = false;
     SaveGameData save = new SaveGameData(player.health, player.strength, player.level, player.experience);
     SuperSave = save;
 }
Esempio n. 47
0
    public string ProcessTouch(GestureSample gesture, SaveGameData _gameData)
    {
        //base.ProcessInput(gesture);
        int level = _gameData.levelReached[_gameData.worldReached];
        if (!pressedButton.isAnimating())
        {

            if (menuState == GameMenuState.MenuStateMain && this.RespondsToGesture(gesture))
            {
                gamePlay.animatedBlink(1, 30);
                pressedButton = gamePlay;
                nextState = GameMenuState.MenuStateChapterSelect;
            }
            else if (cityChapterButton.RespondsToGesture(gesture) && !cityChapterButton.hidden)
            {
                _gameData.worldReached = 0;
                updateButtons(_gameData.levelReached[_gameData.worldReached]);
                cityChapterButton.animatedBlink(1, 30);
                pressedButton = cityChapterButton;
                SelectedChapterNum = 0;
                nextState = GameMenuState.MenuStateLevelSelect;
            }

            else if (caveChapterButton.RespondsToGesture(gesture) && !caveChapterButton.hidden)
            {
                _gameData.worldReached = 2;
                updateButtons(_gameData.levelReached[_gameData.worldReached]);
                caveChapterButton.animatedBlink(1, 30);
                pressedButton = caveChapterButton;
                SelectedChapterNum = 2;
                nextState = GameMenuState.MenuStateLevelSelect;
            }

            else if (cityChallengeChapterButton.RespondsToGesture(gesture) && !cityChallengeChapterButton.hidden)
            {
                _gameData.worldReached = 1;
                updateButtons(_gameData.levelReached[_gameData.worldReached]);
                cityChallengeChapterButton.animatedBlink(1, 30);
                pressedButton = cityChallengeChapterButton;
                SelectedChapterNum = 1;
                nextState = GameMenuState.MenuStateLevelSelect;
            }

            else if (caveChallengeChapterButton.RespondsToGesture(gesture) && !caveChallengeChapterButton.hidden)
            {
                _gameData.worldReached = 3;
                updateButtons(_gameData.levelReached[_gameData.worldReached]);
                caveChallengeChapterButton.animatedBlink(1, 30);
                pressedButton = caveChallengeChapterButton;
                SelectedChapterNum = 3;
                nextState = GameMenuState.MenuStateLevelSelect;
            }

            else if (back.RespondsToGesture(gesture))
            {
                pressedButton = back;
                nextState = menuState - 1;
            }
            foreach (Button b in lockedLevels)
            {
                if (b.RespondsToGesture(gesture))
                {
                    int buttonLevel = b.getExtra();
                    if (buttonLevel <= level && buttonLevel >= 0)
                    {
                        unloadContent();
                        SelectedLevelNum = buttonLevel;
                        return "i am not a null string. don't use this anymore";
                    }
                }
            }
        }

        return null;
    }
Esempio n. 48
0
 async Task SaveAsync(SaveGameData saveData)
 {
     StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("SynesthesiaSave", CreationCollisionOption.ReplaceExisting);
     IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);
     using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
     {
         // Serialize the Session State.
         DataContractSerializer serializer = new DataContractSerializer(typeof(SaveGameData));
         serializer.WriteObject(outStream.AsStreamForWrite(), saveData);
         await outStream.FlushAsync();
     }
     
 }
Esempio n. 49
0
        private void LoadLastLevel()
        {
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (storage.FileExists(FileName))
                {
                    using (var stream = storage.OpenFile(FileName, FileMode.Open))
                    {
                        var xml = new XmlSerializer(typeof(SaveGameData));
                        _gameData = (SaveGameData)xml.Deserialize(stream);
                    }

                }
                else
                {
                    _gameData = new SaveGameData();
                }
            }
        }
Esempio n. 50
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) &&
                    oldstate.IsKeyUp(Keys.Escape))
            {
                if (gameState == PAUSED || gameState == GAMEOVER)
                {
                    gameState = TITLE;
                    waveManager.StopSong();
                }
            }

            //Touch input
            TouchPanelCapabilities tc = TouchPanel.GetCapabilities();//Determine if there is a touch panel connected or not.
            GestureSample gesture;
            if (tc.IsConnected && TouchPanel.IsGestureAvailable)
                gesture = TouchPanel.ReadGesture();
            else
                gesture = new GestureSample();//Reset it so it's not stuck on one touch method.
            //Get the number of fingers on the screen.
            int numTaps = 0;
            TouchCollection touchCollection = TouchPanel.GetState();
            foreach (TouchLocation tl in touchCollection)
            {
                if ((tl.State == TouchLocationState.Pressed)
                        || (tl.State == TouchLocationState.Moved))
                {
                    numTaps++;//All of this to get the number of fingers on the screen and each one's position.
                }
            }



            //Pausing
            if ((Keyboard.GetState().IsKeyDown(Keys.P) || Keyboard.GetState().IsKeyDown(Keys.Enter)) &&
                (oldstate.IsKeyUp(Keys.P) && oldstate.IsKeyUp(Keys.Enter)))
            {
                if (gameState == GAME)
                    gameState = PAUSED;
                else if (gameState == PAUSED)
                    gameState = GAME;
            }
            else if(numTaps >= 3 || gesture.GestureType == GestureType.Flick)
            {
                if (gameState == GAME && numTaps >= 3)
                    gameState = PAUSED;
                else if (gameState == PAUSED && gesture.GestureType == GestureType.Flick)
                    gameState = GAME;
            }

            //Delete Scores
            if (Keyboard.GetState().IsKeyUp(Keys.X) && oldstate.IsKeyDown(Keys.X))
            {
                clear_scores(10);
                //save_data();
            }

            //Title
            if (gameState == TITLE)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Enter) || gesture.GestureType == GestureType.Tap)
                {
                    gameState = GAME;

                    //Reset the game
                    Initialize();
                    waveManager.PlayWave("bgm");
                }
            }
            //Game
            else if (gameState == GAME)
            {
                //Do all of the player stuff.
                player.Update(stages, gameTime, level, gesture);

                //Update the camera.
                camera(player);

                //Add new stage if necessary
                add_new_stage(stages);

                //Play sound on beat
                beat_timer(gameTime);

                //Fireworks
                for (int i = 0; i < fireworks.Count(); i++)
                {
                    fireworks.ElementAt(i).Update();
                }

                //Fragments
                for (int i = 0; i < fragments.Count(); i++)
                {
                    fragments.ElementAt(i).Update();
                    paint_sky(fragments.ElementAt(i));

                    bool hit_ground = fragments.ElementAt(i).hit_ground(fragments.ElementAt(i).position, stages);
                    bool hit_player = player.rectangle.Intersects(fragments.ElementAt(i).rectangle);
                    
                    //Hit the player
                    if (hit_player)
                    {
                        if (!player.spinning)
                        {
                            if (playerHurtTimer <= 0)//Don't let the player get hurt too much.
                            {
                                lives -= 1;
                                hit.Play();
                                playerHurtTimer = playerHurtTimerMax;
                                paint_splat(fragments.ElementAt(i).color);
                            }
                            fragments.Remove(fragments.ElementAt(i));
                        }
                        //If the player is spinning
                        else
                        {
                            fragments.ElementAt(i).speedY = -5;
                            score += 30;
                        }
                    }
                    //Remove frags that hit the ground or go offscreen.
                    else if (hit_ground || fragments.ElementAt(i).position.Y > screenHeight)
                    {
                        fragments.Remove(fragments.ElementAt(i));
                        ground_instance.Play();//Use instance so only one can play at a time.
                    }
                }

                //Check if the player is in the safehouse
                for (int i = 0; i < stages.Count(); i++)
                {
                    //Reach the safehouse
                    if (player.rectangle.Intersects(stages.ElementAt(i).rectangle) && stages.ElementAt(i).safehouse)
                    {
                        inSafehouse = true;
                    }
                    else if(player.rectangle.Intersects(stages.ElementAt(i).rectangle) && !stages.ElementAt(i).safehouse)
                    {
                        inSafehouse = false;
                    }
                }

                //Paint the ground
                paint_the_ground();

                //Manage Lives
                if (lives <= 0)
                {
                    gameState = GAMEOVER;
                    //Show them their score
                    add_score(displayedScore);
                }
                //Subtract lives if the player falls off the stage.
                if (player.position.Y >= screenHeight)
                {
                    lives -= 1;
                    hit.Play();
                    player.position.Y = screenHeight / 3;
                    player.speedY = 0;//They don't have momentum built up.
                    player.spinning = false;
                    player.burstMode = false;
                }

                //Pause the game if the screen is snapped.
                if (Windows8._windowState == WindowState.Snap1Quarter)
                {
                    gameState = PAUSED;
                }

                //Update the camera
                //cameraView.Update(new Vector2(player.position.X - (screenWidth / 2), player.position.Y - (screenHeight / 2)));

                //Decrement timers
                if (playerHurtTimer > 0)
                    playerHurtTimer--;
            }
            else if (gameState == GAMEOVER)
            {
                if ((Keyboard.GetState().IsKeyUp(Keys.Enter) && oldstate.IsKeyDown(Keys.Enter)) || gesture.GestureType == GestureType.Tap)
                {
                    //Reset the game
                    SaveGameData temp = highscores;
                    Initialize();
                    highscores = temp;
                    gameState = GAME;
                    waveManager.RestartSong();
                }
            }
            else if (gameState == PAUSED)
            {
                
            }
            //Update the old keyboard state each frame.
            oldstate = Keyboard.GetState();

            base.Update(gameTime);
        }
Esempio n. 51
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            XmlSerializer serializer = new XmlSerializer(typeof(Game));

            var sr = new StreamReader(Assets.Open("game.xml"));
            this.GameSource = (Game)serializer.Deserialize(sr);
            sr.Close();

            this.Game = new SaveGameData();
            this.isLoadedGame = this.LoadGame("Autosave.xml");
            if (isLoadedGame == false)
            {
                this.InitializeGame();
            }
            this.ExecuteEpizode(this.Game.CurrentEpizode);
        }
Esempio n. 52
0
        void GetLevelStats(SaveGameData save)
        {
            LevelStat = new LevelStats[32];

            for (int i = 0; i < save.LevelStat.Length; ++i)
                LevelStat[i] = save.LevelStat[i];
        }
Esempio n. 53
0
        /// <summary>
        /// This method serializes a data object into
        /// the StorageContainer for this game.
        /// </summary>
        /// <param name="device"></param>
        private static void DoSaveGame(StorageDevice device)
        {
            // Create the data to save.
            SaveGameData data = new SaveGameData();
            data.PlayerName = "Hiro";
            data.AvatarPosition = new Vector2(360, 360);
            data.Level = 11;
            data.Score = 4200;

            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("StorageDemo", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string filename = "savegame.sav";

            // Check to see whether the save exists.
            if (container.FileExists(filename))
                // Delete it so that we can create one fresh.
                container.DeleteFile(filename);

            // Create the file.
            Stream stream = container.CreateFile(filename);

            // Convert the object to XML data and put it in the stream.
            XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
            serializer.Serialize(stream, data);

            // Close the file.
            stream.Close();

            // Dispose the container, to commit changes.
            container.Dispose();
        }
Esempio n. 54
0
        /// <summary>
        /// Saves level unlock and scoring information
        /// 
        /// PC saving is straightforward - but xDoc.Save() will not work on xbox360.
        /// Instead we use the built in XmlSerializer class to serialize an element out to an xml file.
        /// We build our Xelement like normal - but instead of saving that directly using XDocument.Save()
        /// we place this XElement into a struct, and use XmlSerializer to serialize the data out into a storage
        /// device on the xbox.
        /// </summary>
        /// 
        public void Save()
        {
            XElement xLevels = new XElement(XmlKeys.LEVELS);
            foreach (LevelInfo l in mLevels)
                xLevels.Add(l.Export());
            XDocument xDoc = new XDocument();
            xDoc.Add(xLevels);

            #if XBOX360
            IAsyncResult result;
            try
            {
                if (!mDeviceSelected)
                {
                    StorageDevice.BeginShowSelector(((ControllerControl)mControls).ControllerIndex, this.SelectDevice, null);
                    mDeviceSelected = true;
                }
            }
            catch (Exception e)
            {
                string errTemp = e.ToString();
                return;
            }

            if (device == null || !device.IsConnected)
            {
                return;
            }
            try
            {
                result = device.BeginOpenContainer("Mr Gravity", null, null);
                result.AsyncWaitHandle.WaitOne();
                container = device.EndOpenContainer(result);

                //container.DeleteFile("TrialLevelList.xml");
                //container.DeleteFile("LevelList.xml");

                Stream stream;
                if (container.FileExists("LevelList.xml"))
                {
                    container.DeleteFile("LevelList.xml");
                }
                stream = container.CreateFile("LevelList.xml");
                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
                SaveGameData data = new SaveGameData();
                data.SaveData = xLevels;
                serializer.Serialize(stream, data);
                stream.Close();
                container.Dispose();
                result.AsyncWaitHandle.Close();
            }
            catch (Exception e)
            {
                string execTemp = e.ToString();
                return;
            }

            #else
            xDoc.Save("..\\..\\..\\Content\\Levels\\Info\\LevelList.xml");
            #endif
        }
Esempio n. 55
0
        //private void Load_Click_1(object sender, RoutedEventArgs e)
        //{
        //    var ofd = new OpenFileDialog();
        //    Nullable<bool> result = ofd.ShowDialog();
        //    string file = ofd.FileName;
        //    if (result == true)
        //    {
        //        LoadGame(file);
        //    }
        //    this.ExecuteEpizode(this.Game.CurrentEpizode);
        //}
        private bool LoadGame(string file)
        {
            string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string filename = System.IO.Path.Combine(path, file);

            if (System.IO.File.Exists(filename) == true)
            {
                MemoryStream ms = new MemoryStream();
                FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                try
                {
                    fs.CopyTo(ms);
                    ms.Flush();
                    var sr = new StreamReader(fs);
                    string line;
                    this.Game = new SaveGameData();
                    this.Game.lstInventory = new List<Inventory>();
                    this.Game.lstStats = new List<PersonStats>();

                    string Arr = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                    var Lines = Arr.Split(new char[] { '\n'});
                    int i = Lines.Length;

                    for (int j = 0; j < i; j++ )
                    {
                        var linarr = Lines[j].Split(new char[] { '=' });
                        switch (linarr[0])
                        {
                            case "CurrentEpizode":
                                this.Game.CurrentEpizode = int.Parse(linarr[1]);
                                break;
                            case "Inventory":
                                var inv = new Inventory();
                                inv.Name = linarr[1];
                                inv.Quantity = int.Parse(linarr[2]);
                                this.Game.lstInventory.Add(inv);
                                break;
                            case "Stat":
                                var stat = new PersonStats();
                                stat.Name = linarr[1];
                                stat.Value = int.Parse(linarr[2]);
                                this.Game.lstStats.Add(stat);
                                break;
                        }
                    }
                    fs.Close();
                    if(this.Game.CurrentEpizode == 0)
                    {
                        this.Game.CurrentEpizode = 1;
                    }

                    this.isLoadedGame = true;
                    return true;
                }
                catch (Exception ex)
                {
                    fs.Close();
                    //StringReader tr = new StringReader();
                }
            }
            return false;
        }
Esempio n. 56
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns>bool true if loaded from file. false if not file to load</returns>
        private bool Load()
        {
            GetContainer();
            // Check to see whether the save exists.
            if (!container.FileExists(filename))
            {
                // If not, dispose of the container and return.
                container.Dispose();
                return false;
            }

            // Open the file.
            Stream stream = container.OpenFile(filename, FileMode.Open);
            XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData)); // create XML serializer object
            saveGameData = (SaveGameData)serializer.Deserialize(stream); // get saved data from stream(file)
            stream.Close();
            container.Dispose();
            return true;
        }
	/**
	 * Load resources from save game data.
	 */ 
	virtual public void Load(SaveGameData data) {
		Resources = data.resources;
		Gold = data.gold;
		Xp = data.xp;

		foreach (CustomResource c in data.otherResources) {
			// Only add data for resources that we have a type for
			if (customResourceData.ContainsKey(c.id)) {
				customResourceData.Remove (c.id);
				customResourceData.Add(c.id, c.amount);
			}
		}
		view.SendMessage ("UpdateResource", true, SendMessageOptions.DontRequireReceiver);
		view.SendMessage ("UpdateGold", true, SendMessageOptions.DontRequireReceiver);
		if (customResourceTypes.Count > 0) view.SendMessage ("UpdateCustomResource1", true, SendMessageOptions.DontRequireReceiver);
		if (customResourceTypes.Count > 1) view.SendMessage ("UpdateCustomResource2", true, SendMessageOptions.DontRequireReceiver);
		view.SendMessage("UpdateLevel", false, SendMessageOptions.DontRequireReceiver);
	}
        /// <summary>
        /// This method save to the filename indicated by the user.  Also it saves to the universal file LbKTileData so as to get filenames to load from
        /// separately later
        /// </summary>
        /// <param name="device"></param>
        /// <param name="gamer"></param>
        /// <param name="playTest"></param>
        public static void SaveGame(StorageDevice device, SignedInGamer gamer, bool playTest)
        {
            SaveGameData data = new SaveGameData();
            data.TilePosition = new Vector2[position.Length];
            data.TilePosition = position;

            data.TileType = new TileType[type.Length];
            data.TileType = type;

            data.TileObjectNumber = new int[objectNumber.Length];
            data.TileObjectNumber = objectNumber;

            data.TileCount = count;

            data.Names = new List<string>();
            data.Names = fileNames;

            IAsyncResult result =
                device.BeginOpenContainer(gamer.Gamertag, null, null);

            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            //string filename = "LbKTileData.sav";
            string filename = string.Empty;

            filename = fileNames[fileNames.Count - 1] + ".sav";

            if (playTest)
            {
                filename = "TemporaryTileSave.sav";
            }

            if (!container.FileExists(filename))
            {
                Stream file = container.CreateFile(filename);

                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

                serializer.Serialize(file, data);

                file.Close();
            }
            else
            {

                container.DeleteFile(filename);

                Stream file = container.CreateFile(filename);

                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

                serializer.Serialize(file, data);

                file.Close();
            }

            /*
            // Dispose the container, to commit the data.
            container.Dispose();

            //do secondary save

            result =
                device.BeginOpenContainer(gamer.Gamertag, null, null);

            result.AsyncWaitHandle.WaitOne();

            container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();
            */

            filename = "LbKTileData.sav";

            if (!container.FileExists(filename))
            {
                Stream file = container.CreateFile(filename);

                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

                serializer.Serialize(file, data);

                file.Close();
            }
            else
            {

                container.DeleteFile(filename);

                Stream file = container.CreateFile(filename);

                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

                serializer.Serialize(file, data);

                file.Close();
            }

            // Dispose the container, to commit the data.
            container.Dispose();
        }
Esempio n. 59
0
        public static void SaveGame(StorageDevice device, SignedInGamer gamer)
        {
            SaveGameData data = new SaveGameData();
            data.PlayerName = "Alex";
            data.playerPosition = new Vector2(100.0f);
            data.Level = 11;
            data.PlayerScore = 4200;
            data.CheckPoint = 1;

            IAsyncResult result =
                device.BeginOpenContainer("LbK Storage Device", null, null);

            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string filename = "LbKSavedItems.sav";

            if (!container.FileExists(filename))
            {
                Stream file = container.CreateFile(filename);

                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

                serializer.Serialize(file, data);

                file.Close();
            }
            else
            {

                container.DeleteFile(filename);

                Stream file = container.CreateFile(filename);

                XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));

                serializer.Serialize(file, data);

                file.Close();
            }

            // Dispose the container, to commit the data.
            container.Dispose();
        }
        /// <summary>
        /// Call this before using the singleton.
        /// </summary>
        public void Inititalize()
        {
#if WINDOWS_PHONE || __ANDROID__
            mSaveData = new SaveGameData();
#endif
        }