Inheritance: MonoBehaviour
Esempio n. 1
0
        public virtual void OnInit(Game currentGame, System.Windows.Forms.Form owner, Save settings)
        {
            owner.Controls.Add(this);
            this.Dock = DockStyle.Fill;

            this.currentGame = currentGame;
            this.owner = owner;
            this.info = settings;

            this.DoubleBuffered = true;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);
            this.UpdateStyles();

            try
            {
                if (string.IsNullOrEmpty(settings.Background))
                    this.BackgroundImage = Image.FromFile(System.IO.Path.Combine(Application.StartupPath, "Images", "Image.jpg"));
                else
                    this.BackgroundImage = Image.FromFile(settings.Background);
            }
            catch (Exception)
            { }
            this.BackgroundImageLayout = ImageLayout.Stretch;

            this.FinishedInit = true;
        }
Esempio n. 2
0
        public HUDManager(GraphicsDevice device, SpriteBatch spriteBatch, SpawnerManager spawnerManager, SpriteFont font, SpriteFont hudfont, SpriteFont hudfontsmall, Texture2D[] radarImages,
            ShipOverlay friendOverlay, ShipOverlay enemyOverlay, Texture2D[] hudImages, Texture2D crosshair, Save save)
        {
            _font = font;
            _spriteBatch = spriteBatch;
            _elapsedTimeSeconds = TimeSpan.Zero;
            _contactList = new List<Contact>();
            _radarImages = radarImages;
            _device = device;
            _life = "0";
            _speed = "";
            _missles = "";
            _friendOverlay = friendOverlay;
            _enemyOverlay = enemyOverlay;
            _HUDImages = hudImages;
            _HUDFont = hudfont;
            _spawnerManager = spawnerManager;
            _crosshair = crosshair;
            _spaceBattle = save.Config.SpaceBattle;

            _spawnerManager.Selected += (object sender, EventArgs args) =>
                {
                    //A ship has been selected, therefore respawn is false.
                    _respawn = false;
                };
            _respawn = false;
            _HUDFontSmall = hudfontsmall;
        }
Esempio n. 3
0
 public static void Create()
 {
     save = new Save();
     save.filename = saveFilename;
     save.worldUnlocked = 1;
     save.levelUnlocked = 1;
     save.Write();
 }
Esempio n. 4
0
			public Game() {
				manager = new Manager();
				watcher = new Watcher(manager);
				instance = new Instance();
				save = new Save();
				env = new Environments();
				env.GUID = Guid.NewGuid();
			}
Esempio n. 5
0
        static void Main()
        {
            try
            {
                var thing = new DapperThing
                {
                    Id = Guid.NewGuid(),
                    CreateDate = DateTime.UtcNow,
                    ModifiedDate = DateTime.UtcNow,
                    SomeData = Guid.NewGuid(),
                };

                Console.WriteLine("*** Save ***");
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();
                    var save = new Save<DapperThing, Guid>(connection);
                    save.Run(thing);
                }
                Console.WriteLine(thing);

                Console.WriteLine("*** Update ***");
                thing.SomeData = Guid.NewGuid();
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();
                    new SaveOrUpdate<DapperThing, Guid>(connection).Run(thing);
                }
                Console.WriteLine(thing);

                Console.WriteLine("*** Get ***");
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();
                    var getById = new GetById<DapperThing, Guid>(connection);
                    var fromDb = getById.Run(new{thing.Id});
                    Console.WriteLine(fromDb);
                }

                Console.WriteLine("*** Update ***");
                thing.SomeData = Guid.NewGuid();
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();
                    new SaveOrUpdate<DapperThing, Guid>(connection).Run(thing);
                }
                Console.WriteLine(thing);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
Esempio n. 6
0
        public SelectBike(string mode,Save.CManager manager,MainWindow mw)
        {
            _mw = mw;
            genBListBNList();
            _mode = mode;
            _manager = manager;

            InitializeComponent();
        }
Esempio n. 7
0
 // Use this for initialization
 void Awake()
 {
     save = new Save();
     if (!File.Exists(Application.dataPath + saveFilePath)) {
         WriteData();
     } else {
         ReadData();
     }
 }
Esempio n. 8
0
        public void SaveCanParse()
        {
            string data = "EU4txt\r\ndate=\"1821.1.1\"";
            Save savegame;
            using (var stream = new MemoryStream(Globals.ParadoxEncoding.GetBytes(data)))
            {
                savegame = new Save(stream);
            }

            Assert.That(savegame.Date, Is.EqualTo(new DateTime(1821, 1, 1)));
        }
Esempio n. 9
0
    public static void addSave(int slot, Hero hero, int score, int levelId)
    {
        saves = parseLevelFile();

        Save save = new Save(hero, levelId, score);

        saves[slot].Hero = hero;
        saves[slot].LevelId = levelId;
        saves[slot].Score = score;

        saveSaveToFile();
    }
Esempio n. 10
0
    public static void SaveChunk(Chunk chunk)
    {
        Save save = new Save(chunk);    //The Save class checks how many blocks were changed then adds them to a list.
        if (save.blocks.Count == 0)     //Checks if 0 blocks were changed.
            return;                     //Exits saving becuase nothing changed.

        string saveFile = SaveLocation(chunk.world.worldName);
        saveFile += FileName(chunk.pos);

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None);
        formatter.Serialize(stream, chunk.blocks);
        stream.Close();
    }
    public static void SaveChunk(Chunk chunk)
    {
        Save save = new Save(chunk);
        if (save.blocks.Count == 0)
            return;

        string saveFile = SaveLocation(chunk.world.worldName);
        saveFile += FileName(chunk.pos);

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None);
        formatter.Serialize(stream, save);
        stream.Close();
    }
Esempio n. 12
0
	public static void SaveChunk(Chunk chunk)
	{
		Save save = new Save(chunk);    //Add these lines
		if (save.blocks.Count == 0)     //to the start
			return;                     //of the function

		string saveFile = SaveLocation(chunk.world.worldName);
		saveFile += FileName(chunk.pos);

		IFormatter formatter = new BinaryFormatter();
		Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None);

		formatter.Serialize(stream, save);  //And change this to use save instead of chunk.blocks
		stream.Close();
	}
Esempio n. 13
0
        public SoundEngine(SoundEffect[] soundEffects, SoundEffect[] voiceChatterSounds, SoundEffect[] music, List<SoundEffect[]> soundVoiceEffects, Save save)
        {
            SoundEffects = soundEffects;
            SoundList = new List<Sound>();
            SoundInstances = new List<SoundEffectInstance>();
            _randVar = new Random();
            VoiceInstances = new List<SoundEffectInstance>();
            VoiceChatterSounds = voiceChatterSounds;

            SoundVoiceList = new List<SoundVoice>();
            SoundVoiceEffects = soundVoiceEffects;
            SoundVoiceInstances = new List<SoundEffectInstance>();
            _music = music;
            _selectedMusic = _randVar.Next(_music.Length);
            _save = save;
        }
Esempio n. 14
0
        public static void CreateSave(int saveIndex)
        {
            if (!SaveSlotAvailable[saveIndex])
              {
            Save save = new Save();
            CurrentSave = save;
            CurrentSave.Init();
            CurrentSave.ID = saveIndex;

            if (Planets == null)
              Planets = GenerateDefaultPlanetData();

            // Save to Disk
            SaveToDisk();
              }
        }
Esempio n. 15
0
    public static int GetStars(Save.LevelHighScore score, Level level)
    {
        // Get a star for winning
        int stars = 1;

        // Get a star for surpassing score
        if (HasSurpassedSpeed(score, level))
        {
            stars++;
        }

        // Get a star for surpassing time
        if (HasSurpassedTime(score, level))
        {
            stars++;
        }

        return stars;
    }
Esempio n. 16
0
    /**
     * SaveTo
     *  --> saves the selected data in order to serialize it later
     * */
    public Save SaveTo()
    {
        Save _save = new Save(this.gameObject.GetInstanceID());
        if(m_SaveTransform)
            _save.m_Transform = new TransformSerializable(transform);
        if(m_SavePhysics)
            _save.m_RigidBody = new RigidBodySerializable(rigidbody);
        if(m_SaveGravity)
        {
            LocalGravityScript script = null;
            if((script = GetComponent<LocalGravityScript>()) != null)
                _save.m_Gravity = new Vector3Serializable(script.GetGravityDir());
        }
        if(m_SaveEnable && gameObject.tag.Equals("Checkpoint"))
            _save.m_Enable = GetComponent<CheckpointScript>().GetActive();

        _save.m_Name = (string)gameObject.name.Clone();
        return _save;
    }
        //Hauptmethode
        public static void saveReservation(Save.XFile elementSave)
        {
            string donename = "done_";

            //pro datei, reservierungen
            List<XFile> xmlReservations = new List<XFile>();

            //ob ein XFile element mitgegeben wurde 
            if (elementSave == null)
            {
                //alle namen die mit bookings anfangen
                FileInfo[] files = getFileNames("bookings*");

                //speichert alle Reservierungen pro Datei 
                foreach (FileInfo info in files)
                {
                    xmlReservations.Add(new XFile{
                        xmlRes = splitXmlTree(Wired_XMLRpc.getXmlFile(info.FullName)),
                        filename = info
                    });
                }
            }
            else
            {
                xmlReservations.Add(new XFile
                {
                    xmlRes = splitXmlTree(elementSave.xmlRes.First()),
                    filename = elementSave.filename
                });
            }

            //läuft alle xml dateien durch (1 xml kann mehrer Buchungen enthalten)
            foreach (XFile list in xmlReservations)
            {
                var returnvalue = getParameters(list.xmlRes);

                //erst wenn speichern erfolgreich war dann name ändern
                if(returnvalue && list.filename != null)
                    File.Move(list.filename.FullName, (list.filename.Directory + "\\" + donename + list.filename.Name));
                donename = "done_";
            }
        }
Esempio n. 18
0
    /**
     * Load()
     *  --> restore the saved data onto the gameObject
     * */
    public void Load(Save save)
    {
        if(m_SavePhysics)
            save.m_RigidBody.CopyTo(rigidbody);

        if(m_SaveTransform)
        {
            AttachableObjectScript attach;
            if((attach = GetComponent<AttachableObjectScript>()) != null)
                transform.parent = attach.GetOriginalTransform();
            save.m_Transform.CopyTo(transform);
        }
        if(m_SaveGravity)
        {
            LocalGravityScript script = null;
            if((script = GetComponent<LocalGravityScript>()) != null)
                script.SetGravityDir(save.m_Gravity.ToVector3(), false);
        }

        if(m_SaveEnable && gameObject.tag.Equals("Checkpoint"))
            GetComponent<CheckpointScript>().SetActive(save.m_Enable);
    }
Esempio n. 19
0
        public override void OnInit(Game currentGame, Form owner, Save settings)
        {
            base.currentGame = currentGame;
            base.owner = owner;
            base.info = settings;

            this.owner.Controls.Add(this);
            this.Dock = DockStyle.Fill;

            try
            {
                SlimDX.DirectWrite.Factory m = new SlimDX.DirectWrite.Factory(FactoryType.Shared);
                textFormatCentered = m.CreateTextFormat(this.Font.FontFamily.Name, SlimDX.DirectWrite.FontWeight.Regular, SlimDX.DirectWrite.FontStyle.Normal, SlimDX.DirectWrite.FontStretch.Expanded, 50, "de-de");
                textFormatCentered.TextAlignment = SlimDX.DirectWrite.TextAlignment.Center;
                textFormatCentered.ParagraphAlignment = SlimDX.DirectWrite.ParagraphAlignment.Center;
            }
            catch (Exception)
            { }

            this.initializeGraphics();

            this.FinishedInit = true;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque | ControlStyles.ResizeRedraw, true);
            this.UpdateStyles();

            try
            {
                if (string.IsNullOrEmpty(settings.Background))
                    this.BackgroundImage = Image.FromFile(System.IO.Path.Combine(Application.StartupPath, "Images", "Image.jpg"));
                else
                    this.BackgroundImage = Image.FromFile(settings.Background);
            }
            catch (Exception)
            { }

            this.e = new Graphics.DirectGraphics(this.renderTarget);
            this.Invalidate();
        }
Esempio n. 20
0
        internal void ShareskillEdit()
        {
            //Explicit wait to find element
            GlobalDefinitions.WaitForElement(GlobalDefinitions.driver, By.XPath("//section//a[contains(.,'Manage Listings')]"));

            //click managelisting
            manageListingsLink.Click();

            GlobalDefinitions.WaitForElement(GlobalDefinitions.driver, By.XPath("(//i[@class='outline write icon'])[1]"));
            Editbutton.Click();
            // Populate the excel data
            GlobalDefinitions.ExcelLib.PopulateInCollection(Base.ExcelPath, "ShareSkill");

            //Enter title
            Title.SendKeys(GlobalDefinitions.ExcelLib.ReadData(3, "Title"));

            //Enter Description
            Description.SendKeys(GlobalDefinitions.ExcelLib.ReadData(3, "Description"));

            // Select on Category Dropdown
            GlobalDefinitions.wait(10);
            SelectElement catg = new SelectElement(CategoryDropDown);

            catg.SelectByText(GlobalDefinitions.ExcelLib.ReadData(3, "Category"));

            //Select on SubCategory Dropdown
            GlobalDefinitions.wait(10);
            SelectElement subcatg = new SelectElement(SubCategoryDropDown);

            subcatg.SelectByText(GlobalDefinitions.ExcelLib.ReadData(3, "SubCategory"));

            //Enter Tag names in textbox
            Tags.SendKeys(GlobalDefinitions.ExcelLib.ReadData(3, "Tags"));
            Tags.SendKeys(Keys.Return);

            //Select the Service type
            if (GlobalDefinitions.ExcelLib.ReadData(3, "ServiceType") == "Hourly basis service")
            {
                Hourly.Click();
            }
            else if (GlobalDefinitions.ExcelLib.ReadData(3, "ServiceType") == "One-off service")
            {
                Oneoff.Click();
            }

            //Select the Location type
            if (GlobalDefinitions.ExcelLib.ReadData(3, "LocationType") == "On-site")
            {
                Onsite.Click();
            }
            else if (GlobalDefinitions.ExcelLib.ReadData(3, "LocationType") == "Online")
            {
                Online.Click();
            }

            //Click on Start Date dropdown
            StartDateDropDown.SendKeys(GlobalDefinitions.ExcelLib.ReadData(3, "Startdate"));

            //Click on End Date dropdown
            EndDateDropDown.SendKeys(GlobalDefinitions.ExcelLib.ReadData(3, "Enddate"));

            //Select available days
            Days.Click();

            //Select startTime
            StartTime.SendKeys(GlobalDefinitions.ExcelLib.ReadData(3, "Starttime"));

            //select endtime
            EndTimeDropDown.SendKeys(GlobalDefinitions.ExcelLib.ReadData(3, "Endtime"));

            if (GlobalDefinitions.ExcelLib.ReadData(3, "SkillTrade") == "Skill-Exchange")
            {
                //select SkillTradeOption
                SkillTradeOption.Click();
                //Enter SkillExchange
                SkillExchange.SendKeys(GlobalDefinitions.ExcelLib.ReadData(3, "Skill-Exchange"));
                SkillExchange.SendKeys(Keys.Return);
            }
            else if (GlobalDefinitions.ExcelLib.ReadData(3, "SkillTrade") == "Credit")
            {
                Credit.Click();
                Creditvalue.SendKeys(Global.GlobalDefinitions.ExcelLib.ReadData(2, "Credit"));
                Creditvalue.SendKeys(Keys.Enter);
            }
            //Click worksample
            Worksample.Click();
            //Worksample.SendKeys("path");

            //upload file using AutoIT
            AutoItX3 autoit = new AutoItX3();

            //Activate so that next action happens on this window
            autoit.WinActivate("Open");
            //autoit.Send(@"D:\Shareskillmars\FileUploadScript.exe");
            autoit.Send(@"D:\Shareskillmars\sample.txt");
            autoit.Send("{ENTER}");

            Thread.Sleep(20000);
            //Select user option
            if (GlobalDefinitions.ExcelLib.ReadData(3, "UserStatus") == "Active")
            {
                StatusActive.Click();
            }
            else if (GlobalDefinitions.ExcelLib.ReadData(3, "UserStatus") == "Hidden")
            {
                StatusHidden.Click();
            }

            //click save or cancel
            if (Global.GlobalDefinitions.ExcelLib.ReadData(3, "SaveOrCancel") == "Save")
            {
                Save.Click();
            }
            else if (Global.GlobalDefinitions.ExcelLib.ReadData(3, "SaveOrCancel") == "Cancel")
            {
                Cancel.Click();
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Loads any buildings that exist in a specific <see cref="SaveGeneration"/>.
        /// </summary>
        /// <param name="save">The current <see cref="Save"/> file.</param>
        /// <param name="islandBuildings">Load regular buildings or island buildings?</param>
        /// <returns></returns>
        public static Building[] LoadBuildings(Save save, bool islandBuildings = false)
        {
            var buildings = new List <Building>();

            switch (save.SaveGeneration)
            {
            case SaveGeneration.Wii:
                IslandBuildings = null;

                for (var i = 0; i < 33; i++)
                {
                    var dataOffset = save.SaveDataStartOffset + SaveDataManager.CityFolkOffsets.Buildings + i * 2;
                    buildings.Add(new Building((byte)i, save.ReadByte(dataOffset), save.ReadByte(dataOffset + 1),
                                               SaveType.CityFolk));
                }

                //Add Pave's Table
                var paveOffset = save.SaveDataStartOffset + 0x5EB90;
                var paveTable  = new Building(0x21, save.ReadByte(paveOffset), save.ReadByte(paveOffset + 1),
                                              SaveType.CityFolk);
                buildings.Add(paveTable);

                //Add Bus Stop
                var busStopOffset = save.SaveDataStartOffset + 0x5EB8A;
                var busStop       = new Building(0x22, save.ReadByte(busStopOffset), save.ReadByte(busStopOffset + 1),
                                                 SaveType.CityFolk);
                buildings.Add(busStop);

                //Add Signs
                for (var i = 0; i < 100; i++)
                {
                    var dataOffset = save.SaveDataStartOffset + 0x5EB92 + i * 2;
                    var sign       = new Building(0x23, save.ReadByte(dataOffset), save.ReadByte(dataOffset + 1),
                                                  SaveType.CityFolk);
                    buildings.Add(sign);
                }

                break;

            case SaveGeneration.N3DS:
                if (islandBuildings == false)
                {
                    for (var i = 0; i < 58; i++)
                    {
                        var dataOffset = save.SaveDataStartOffset + Save.SaveInstance.SaveInfo.SaveOffsets.Buildings +
                                         i * 4;
                        buildings.Add(new Building(save.ReadByte(dataOffset), save.ReadByte(dataOffset + 2),
                                                   save.ReadByte(dataOffset + 3), save.SaveType));
                        //Technically, Building IDs are shorts, but since they only use the lower byte, we'll just ignore that
                    }
                }
                else
                {
                    for (var i = 0; i < 2; i++)
                    {
                        var dataOffset = save.SaveDataStartOffset +
                                         Save.SaveInstance.SaveInfo.SaveOffsets.IslandBuildings + i * 4;
                        buildings.Add(new Building(save.ReadByte(dataOffset), save.ReadByte(dataOffset + 2),
                                                   save.ReadByte(dataOffset + 3), save.SaveType));
                    }
                }

                break;

            default:
                IslandBuildings = null;
                return(Buildings = null);
            }

            if (islandBuildings)
            {
                return(IslandBuildings = buildings.ToArray());
            }

            return(Buildings = buildings.ToArray());
        }
 public void Save()
 {
     save = new Save(GameManager.Player.transform.position);
     onSave?.Invoke();
 }
Esempio n. 23
0
    void Start()
    {
        _scoreKeeper = GameObject.FindObjectOfType<ScoreKeeper> ();
        _particles = GameObject.FindObjectOfType<ParticleSystem> ();
        _shaker = GameObject.FindObjectOfType<Shaker> ();
        _successAudio = GameObject.Find ("Success SFX").GetComponent<AudioSource> ();
        _shrinkCurve = new AnimationCurve (new Keyframe (0, 1), new Keyframe (10000, 1), new Keyframe (10000 + (shrinkDuration * 0.1F), 1.25F), new Keyframe (10000 + shrinkDuration, 0));
        _numberOfRings = transform.childCount;
        _startTime = Time.time;
        _lastTriggerTime = 0;
        _save = FindObjectOfType <Save> ();

        SetTargetScaleMultiplier();
    }
Esempio n. 24
0
    public static bool HasSurpassedSpeed(Save.LevelHighScore score, Level level)
    {
        if (level != null)
            return score.Speed >= level.ranks.SpeedThreshold;

        return false;
    }
Esempio n. 25
0
    void Awake()
    {
        if (save == null)
        {
            save = Save.Read(saveFilename);

            // Initialise new save
            if (save == null)
            {
                Create();
            }
        }
    }
Esempio n. 26
0
    /// <summary>
    /// Creates a Json file representing the empty save at the index "save"
    /// </summary>
    /// <param name="save"></param>
    /// <param name="nbPlayer"></param>
    public void CreateSaveFile(int save, int nbPlayer)
    {
        //création du file
        StreamWriter streamWriter = File.CreateText(Application.persistentDataPath + "/Saves/SaveFile" + save + ".json");

        //création des dictionnaires de metadonnées
        StringIntDictionary mInt = new StringIntDictionary();

        mInt.Add("jumpNumber1", 0);
        mInt.Add("playerDeath1", 0);

        StringFloatDictionary mFloat = new StringFloatDictionary();

        mFloat.Add("distance1", 0);
        mFloat.Add("totalTimePlayed", 0);

        List <Chapter> chapters = new List <Chapter>();

        if (nbPlayer == 1)
        {
            //On créer les chapitres et les tableaux, puis on l'écrit sur le nouveau fichier.
            List <Level> lvlPrologque_Solo = new List <Level>();
            lvlPrologque_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, true));
            lvlPrologque_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));
            lvlPrologque_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));
            lvlPrologque_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));
            lvlPrologque_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));

            List <Level> lvlChap1_Solo = new List <Level>();
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, true));        //0   - The entrance - 2 Collectibles
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //1
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //2
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //3
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //4
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //5
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //6
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, true));        //7   - The room of a thousand stairs - 2 Collectibles
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       // GhostRoom
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //8
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //9
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //10
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //11
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //12
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //13
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, true));        //14 - The second encounter - 3 Collectibles
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //15
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //16
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //17
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //18
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //19
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //20
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //21
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //22
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, true));        //  - Fresh air - 4 Collectibles
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //23
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //24
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //25
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //26
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //27
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //28
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //29
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //30
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, true));        //31 - The third encounter - 3 Collectibles
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //32
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //33
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //34
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //35
            lvlChap1_Solo.Add(new Level(false, new bool[] { false }, new bool[] { }, false)); //36
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, true));        //37 - The show - 0 Collectibles
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //38
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //39
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //40
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //41
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, false));       //42
            lvlChap1_Solo.Add(new Level(false, new bool[] { }, new bool[] { }, true));        //43 - The confrontation - 0 Collectibles

            chapters.Add(new Chapter(lvlPrologque_Solo));
            chapters.Add(new Chapter(lvlChap1_Solo));
        }

        if (nbPlayer == 2)
        {
            mInt.Add("jumpNumber2", 0);
            mInt.Add("playerDeath2", 0);
            mFloat.Add("distance2", 0);

            //On créer les chapitres et les tableaux, puis on l'écrit sur le nouveau fichier.
            List <Level> lvlPrologque_Duo = new List <Level>();
            lvlPrologque_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, true));
            lvlPrologque_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));
            lvlPrologque_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));
            lvlPrologque_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));
            lvlPrologque_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));

            List <Level> lvlChap1_Duo = new List <Level>();
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, true));              //0   - The entrance - 2 Collectibles
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { false }, false));       //1
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //2
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //3
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //4
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //5
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { false }, false));       //6
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, true));              //7   - The room of a thousand stairs - 4 Collectibles
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             // GhostRoom
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //8
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { false }, false));       //9
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //10
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //11
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { false }, false)); //12
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { }, false));       //13
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, true));              //14 - The second encounter - 3 Collectibles
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //15
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { }, false));       //16
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //17
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //18
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { }, false));       //19
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { false }, false));       //20
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //21
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //22
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, true));              //  - Fresh air - 5 Collectibles
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //23
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //24
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { }, false));       //25
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { false }, false)); //26
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //27
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //28
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //29
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { false }, false)); //30
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, true));              //31 - The third encounter - 4 Collectibles
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //32
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { false }, false));       //33
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { }, false));       //34
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //35
            lvlChap1_Duo.Add(new Level(false, new bool[] { false }, new bool[] { false }, false)); //36
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, true));              //37 - The show - 0 Collectibles
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //38
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //39
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //40
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //41
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, false));             //42
            lvlChap1_Duo.Add(new Level(false, new bool[] { }, new bool[] { }, true));              //43 - The confrontation - 0 Collectibles

            chapters.Add(new Chapter(lvlPrologque_Duo));
            chapters.Add(new Chapter(lvlChap1_Duo));
        }


        // chapters.Add(new Chapter(lvlChap1));

        //enfin, on créer la save qui contient toutes les informations
        Save createdSave = new Save(chapters, nbPlayer, mInt, mFloat, new SerializableDate(DateTime.Now));


        string saveFileContent = JsonUtility.ToJson(createdSave, true);

        //On rempli le nouveau SaveFile
        streamWriter.Write(saveFileContent);
        streamWriter.Close();

        LoadSaveFile(save);
    }
Esempio n. 27
0
    private Save CreateSaveGameObject()
    { // 세이브 과정
        Save save = new Save();

        // 저장 장소 저장
        if (scene.name == "HOME")
        {
            save.save_home = 0;
        }
        else
        {
            save.save_home = 1;
        }

        // 캐릭터 정보 저장
        save.nickname = player_.player_info_nick;
        save.lavel    = player_.player_info_level;
        save.hp       = player_.player_info_hp;
        save.exp      = player_.player_info_exp;
        save.money    = player_.player_info_money;
        save.attack   = player_.player_info_attack;

        // 맵 관련
        save.animation_off      = map_.animation_off;
        save.first_slot_setting = inventory_.first_slot_setting;
        save.town_off           = map_.town_off;

        // 무기 저장
        save.hasWeapon1 = inventory_.hasWeapon1;
        save.hasWeapon2 = inventory_.hasWeapon2;
        save.hasWeapon3 = inventory_.hasWeapon3;
        save.hasWeapon4 = inventory_.hasWeapon4;
        save.hasWeapon5 = inventory_.hasWeapon5;
        save.hasWeapon6 = inventory_.hasWeapon6;

        // 인벤토리 저장
        for (int i = 0; i < 9; i++)
        {
            save.weapon_items[i] = inventory_.weapon_items[i];
            save.potion_items[i] = inventory_.potion_items[i];
            save.etc_items[i]    = inventory_.etc_items[i];

            save.weapon_name[i] = inventory_.weapon_name[i];
            save.potion_name[i] = inventory_.potion_name[i];
            save.etc_name[i]    = inventory_.etc_name[i];

            save.weapon_items_number[i] = inventory_.weapon_items_number[i];
            save.potion_items_number[i] = inventory_.potion_items_number[i];
            save.etc_items_number[i]    = inventory_.etc_items_number[i];
        }

        // 퀘스트 저장
        save.monsterDie = Quest.monsterDie;
        for (int j = 0; j < 10; j++)
        {
            save.isclear[j]      = Quest.isclear[j];
            save.iscomplete[j]   = Quest.iscomplete[j];
            save.viewing[j]      = Quest.viewing[j];
            save.questplaying[j] = Quest.questplaying[j];
        }

        return(save);
    }
Esempio n. 28
0
    public SaveData()
    {
        Save save = GameObject.FindObjectOfType <Save>();

        dwarfPosX = save.dwarf.transform.position.x;
        dwarfPosY = save.dwarf.transform.position.y;
        dwarfPosZ = save.dwarf.transform.position.z;

        lampPosX = save.lamp.transform.position.x;
        lampPosY = save.lamp.transform.position.y;
        lampPosZ = save.lamp.transform.position.z;

        mapSeed         = save.world.seed;
        mountainHeights = save.world.mountainHeights;

        int i = 0;

        destroyedTiles = new mapElement[save.world.destroyedTiles.Count];
        foreach (KeyValuePair <Vector2, bool> elem in save.world.destroyedTiles)
        {
            destroyedTiles[i++] = new mapElement(elem.Key.x, elem.Key.y, elem.Value);
        }

        i = 0;
        isWaterNotLava = new mapElement[save.world.isWaterNotLava.Count];
        foreach (KeyValuePair <Vector2, bool> elem in save.world.isWaterNotLava)
        {
            isWaterNotLava[i++] = new mapElement(elem.Key.x, elem.Key.y, elem.Value);
        }

        i = 0;
        generatedStone = new mapElement[save.world.generatedStone.Count];
        foreach (KeyValuePair <Vector2, bool> elem in save.world.isWaterNotLava)
        {
            generatedStone[i++] = new mapElement(elem.Key.x, elem.Key.y, elem.Value);
        }

        vLevel             = save.stat.vLevel;
        vCurrExp           = save.stat.vCurrExp;
        vExpBase           = save.stat.vExpBase;
        vExpLeft           = save.stat.vExpLeft;
        vStrength          = save.stat.vStrength;
        vAgility           = save.stat.vAgility;
        vEndurance         = save.stat.vEndurance;
        vPerception        = save.stat.vPerception;
        vLuck              = save.stat.vLuck;
        strengthMultiplier = save.stat.strengthMultiplier;
        climbingDifficulty = save.stat.climbingDifficulty;
        vFatigue           = save.stat.vFatigue;
        maxFatigue         = save.stat.maxFatigue;
        totalIron          = save.stat.totalIron;
        totalSilver        = save.stat.totalSilver;
        totalGold          = save.stat.totalGold;
        totalMithril       = save.stat.totalMithril;
        totalTopaz         = save.stat.totalTopaz;
        totalSapphire      = save.stat.totalSapphire;
        totalRuby          = save.stat.totalRuby;
        totalDiamond       = save.stat.totalDiamond;
        totalDeaths        = save.stat.totalDeaths;
        totalDigs          = save.stat.totalDigs;
        totalMoves         = save.stat.totalMoves;
        totalFatigues      = save.stat.totalFatigues;
        totalPlaytime      = save.stat.totalPlaytime;
        maxDepth           = save.stat.maxDepth;
        currentDepth       = save.stat.currentDepth;
        itemsCrafted       = save.stat.itemsCrafted;
        itemsBought        = save.stat.itemsBought;
        itemsSold          = save.stat.itemsSold;
        itemsBroken        = save.stat.itemsBroken;
        depthTrig          = save.stat.depthTrig;
        levelUpTrig        = save.stat.levelUpTrig;
        craftTrig          = save.stat.craftTrig;
        shopTrig           = save.stat.shopTrig;
        fatigueTrig        = save.stat.fatigueTrig;
        firstPlayTrig      = save.stat.firstPlayTrig;
        firstBlockDigTrig  = save.stat.firstBlockDigTrig;
        mineEntranceTrig   = save.stat.mineEntranceTrig;

        gold = save.gold.gold;
        bags = save.stat.totalBags;

        Item1 item = save.pickaxeSlot.MyItem;

        pickaxe = new itemElement("");
        if (item != null)
        {
            pickaxe.title      = item.MyTitle;
            pickaxe.durability = item.myDurability;
        }

        items = new List <itemElement>();

        SlotScript[] slots = GameObject.FindObjectsOfType <SlotScript>();
        foreach (SlotScript slot in slots)
        {
            if (slot != save.pickaxeSlot)
            {
                if (slot.MyItem != null)
                {
                    itemElement elem = new itemElement(slot.MyItem.MyTitle, slot.MyItem.myDurability);
                    for (i = 0; i < slot.MyCount; i++)
                    {
                        items.Add(elem);
                    }
                }
            }
        }
    }
 public void NewSave()
 {
     File.Delete(dir);
     currentGame = new Save(LVLS);
     SaveGame();
 }
Esempio n. 30
0
 public void OnFinishLoading(Save save)
 {
     OnFinishLoading();
 }
Esempio n. 31
0
        static void Main(string[] args)
        {
            CreateDebugWindow();

            Engine.Run(true, args).Wait();

            Engine.OnStop += () => End.Set();

            Debug.Log("\n\n");

            Time.PhysicsRate = 128D;
            Vector3D soloPlayerSpawnpoint = /*new Vector3D(32_000_000D, 0, 32_000_000D);//*/
                                            new Vector3D(572, 66, 459);


            //MainLoadScreen.Show();

            new Sound(@"assets/sounds/button_click.mp3");
            //new Shader("assets/shaders/Debug/Volume/DebugVolume.vert", "assets/shaders/Debug/Volume/DebugVolume.frag");

            Tester = new WObject("tester").AddModule <ClientTester>();

            /* ego mode enabled */
            Player.LocalPlayer = new Player("Arthur_" + new Random().Next(1000, 10000));

            Camera.Main.WObject.Delete();
            Camera.Main = null;



            WObject localPlayerWobj = new WObject("Local Player");

            localPlayerWobj.Enabled = false;
            PlayerController pc = localPlayerWobj.AddModule <PlayerController>();

            WObject camW = new WObject("Player Camera");

            camW.Parent        = localPlayerWobj;
            camW.LocalPosition = Vector3D.Up * 1.62D;
            Camera main = Camera.Main = camW.AddModule <Camera>();

            main.FOV           = 80;
            main.NearClip      = 0.01D;
            main.FarClip       = 4096.0D;
            main.RenderLayers &= ~(ulong)Layers.UI;
            main.WObject.AddModule <PanoramicPhotographer>();

            Winecrash.RenderDistance = 5;

            GameApplication app = (GameApplication)Graphics.Window;

            app.VSync = VSyncMode.On;

            string title = $"Winecrash {Winecrash.Version} ({IntPtr.Size * 8}bits)";

#if DEBUG
            title += " <DEBUG BUILD>";
#endif

            app.Title = title;

            app.OnLoaded += () =>
            {
                new Shader("assets/shaders/player/Player.vert", "assets/shaders/player/Player.frag");
                new Shader("assets/shaders/Unlit/Unlit.vert", "assets/shaders/Unlit/Unlit.frag");
                new Shader("assets/shaders/chunk/Chunk.vert", "assets/shaders/chunk/Chunk.frag");
                new Shader("assets/shaders/skybox/Skybox.vert", "assets/shaders/skybox/Skybox.frag");
                new Shader("assets/shaders/celestialbody/CelestialBody.vert", "assets/shaders/celestialbody/CelestialBody.frag");
                new Shader("assets/shaders/item/Item.vert", "assets/shaders/item/Item.frag");
                //new Shader("assets/shaders/fun/Fun.vert", "assets/shaders/fun/Fun.frag");


                Package.Load("assets/winecrash.package");
                ItemCache.BuildChunkTexture(out int xsize, out int ysize);
                //Chunk.Texture.Save(Folders.UserData + "items_atlas.png");

                Winecrash.CurrentSave = new Save(Save.DefaultName, Save.Exists(Save.DefaultName));

                Canvas.Main.UICamera.NearClip = -8192.0D;
                Canvas.Main.UICamera.FarClip  = 8192.0D;

                EngineCore.Instance.WObject.AddModule <GameDebug>();

                GameUI gui = Canvas.Main.WObject.AddModule <GameUI>();
                gui.Enabled = false;

                Client = new GameClient();
                Client.OnDisconnected += client =>
                {
                    Game.InvokePartyLeft(PartyType.Multiplayer);
                };

                MainMenu.Show();
            };

            Game.OnPartyJoined += type =>
            {
                GameUI.Instance.Enabled = true;
                Input.LockMode          = CursorLockModes.Lock;
                Input.CursorVisible     = false;
                MainMenu.Hide();

                localPlayerWobj.Enabled = true;
                Player.LocalPlayer.CreateEntity(localPlayerWobj);

                localPlayerWobj.Position = new Vector3D(soloPlayerSpawnpoint.X, 0, soloPlayerSpawnpoint.Z) + Vector3D.Up * (World.GetSurface(soloPlayerSpawnpoint, "winecraft:dimension") + 1);

                if (SkyboxController.Instance)
                {
                    SkyboxController.Instance.Show();
                }
                else
                {
                    new WObject("Skybox").AddModule <SkyboxController>();
                }

                Player.LocalPlayer.Entity.OnRotate += rotation =>
                {
                    if (!PlayerController.CameraLocked)
                    {
                        Camera.Main.WObject.Rotation = rotation;
                    }
                };

                if (type == PartyType.Singleplayer)
                {
                    Player.LocalPlayer.CameraAngles = Vector2I.Zero;

                    //Player.LocalPlayer.Entity.WObject.AddModule<DebugArrow>();

                    Task.Run(() =>
                    {
                        World.GlobalToLocal(soloPlayerSpawnpoint, out Vector2I cpos, out _);

                        Parallel.ForEach(World.GetCoordsInRange(cpos, Winecrash.RenderDistance),
                                         vector => { World.GetOrCreateChunk(vector, "winecrash:overworld"); });
                    });
                }
            };
            Game.OnPartyLeft += type =>
            {
                GameUI.Instance.Enabled = false;
                Input.LockMode          = CursorLockModes.Free;
                Input.CursorVisible     = true;
                World.Unload();

                localPlayerWobj.Enabled = false;
                Player.LocalPlayer.Entity?.Delete();
                Player.LocalPlayer.Entity = null;

                if (SkyboxController.Instance)
                {
                    SkyboxController.Instance.Hide();
                }

                MainMenu.Show();

                if (type == PartyType.Multiplayer)
                {
                    MainMenu.HideMain();
                }

                //Camera.Main._FarClip = 4096;
                //Camera.Main.WObject.Position = Vector3D.Zero;
            };


            Task.Run(() => End.WaitOne()).Wait();
        }
Esempio n. 32
0
        public void LoadJSON(string text)
        {
            //string save = System.IO.File.ReadAllText("..\\..\\save.json");
            data = JsonConvert.DeserializeObject <Save>(text);
            foreach (Monster mon in data.Monsters)
            {
                var equipedRunes = data.Runes.Where(r => r.AssignedId == mon.ID);

                mon.Name = mon.Name.Replace(" (In Storage)", "");

                foreach (Rune rune in equipedRunes)
                {
                    mon.ApplyRune(rune);
                }

                if (mon.priority == 0 && mon.Current.runeCount > 0)
                {
                    mon.priority = priority++;
                }

                var stats = mon.GetStats();

                string pri = "";
                if (mon.priority != 0)
                {
                    pri = mon.priority.ToString();
                }

                ListViewItem item = new ListViewItem(new string[] {
                    mon.Name,
                    mon.ID.ToString(),
                    pri,
                });
                item.Tag = mon;
                listView1.Items.Add(item);
            }
            foreach (Rune rune in data.Runes)
            {
                ListViewItem item = new ListViewItem(new string[] {
                    rune.Set.ToString(),
                    rune.ID.ToString(),
                    rune.Grade.ToString(),
                    Rune.StringIt(rune.MainType, true),
                    rune.MainValue.ToString()
                });
                item.Tag = rune;
                listView2.Items.Add(item);
            }

            if (data.shrines == null)
            {
                data.shrines = new Stats();
            }

            if (config != null)
            {
                if (config.AppSettings.Settings.AllKeys.Contains("shrineSpeed"))
                {
                    int val = 0;
                    int.TryParse(config.AppSettings.Settings["shrineSpeed"].Value, out val);
                    data.shrines.Speed = val;
                    int level = (int)Math.Floor(val / (double)1.5);
                    ((ToolStripMenuItem)speedToolStripMenuItem.DropDownItems[level]).Checked = true;
                }
            }
        }
Esempio n. 33
0
        public static void LoadData(int saveNumber)
        {
            JsonSerializer serializer = new JsonSerializer();

              string save = saveNumber.ToString("D2");

              // Load specific Player
              using (StreamReader file = File.OpenText("character" + save + ".json"))
              {
            CurrentSave = (Save)serializer.Deserialize(file, typeof(Save));
            CurrentPlanet = CurrentSave.OnPlanetID;
              }

              // Load specific Planets
              using (StreamReader file = File.OpenText("planets" + save + ".json"))
              {
            Planets = (List<Planet>)serializer.Deserialize(file, typeof(List<Planet>));
              }
        }
Esempio n. 34
0
 private async void TSB_Save_Click(object sender, EventArgs e)
 {
     await Save?.Invoke();
 }
Esempio n. 35
0
    public static void SaveGame(this Save save, string path)
    {
        var data = JsonUtility.ToJson(save);

        PlayerPrefs.SetString(path, data);
    }
Esempio n. 36
0
 private static void Export()
 {
     Save.WriteToFile(ModSettings.MyIniFileName, MyIni, typeof(IniSupport));
 }
Esempio n. 37
0
        private static readonly Bitmap VillagerList = Properties.Resources.Villagers; // currently for GC only

        /// <inheritdoc/>
        /// <summary>
        /// Initializes a new VillagerControl object.
        /// </summary>
        /// <param name="mainFormReference">The main form reference, which is used by the item editor subcontrols.</param>
        /// <param name="index">The index of the control.</param>
        /// <param name="saveFile">The currently open <see cref="T:ACSE.Save" />.</param>
        /// <param name="villager">The <see cref="T:ACSE.Villager" /> that is being edited.</param>
        /// <param name="villagers">A dictionary of <see cref="T:ACSE.SimpleVillager" />s and their villager ids.</param>
        /// <param name="villagerNames">An array of villager names.</param>
        /// <param name="personalityTypes">An array of personality names.</param>
        public VillagerControl(MainForm mainFormReference, int index, Save saveFile, Villager villager,
                               Dictionary <ushort, SimpleVillager> villagers,
                               string[] villagerNames, string[] personalityTypes)
        {
            Index             = index;
            _saveFile         = saveFile;
            _villager         = villager;
            _villagers        = villagers;
            _villagerNames    = villagerNames;
            _personalityTypes = personalityTypes;

            FlowDirection = FlowDirection.LeftToRight;
            AutoSize      = true;
            Margin        = new Padding(0);
            MaximumSize   = new Size(0, 66);

            // Set up controls that are always used

            _indexLabel = new Label
            {
                AutoSize  = false,
                Size      = new Size(45, 32),
                TextAlign = ContentAlignment.MiddleCenter,
                Text      = index == 16 ? "Islander" : (index + 1).ToString()
            };

            var margin = CalculateControlVerticalMargin(_indexLabel);

            _indexLabel.Margin = new Padding(0, margin, 0, margin);

            _villagerSelectionBox = new ComboBox
            {
                Size          = new Size(120, 32),
                DropDownStyle = ComboBoxStyle.DropDownList
            };

            margin = CalculateControlVerticalMargin(_villagerSelectionBox);
            _villagerSelectionBox.Margin = new Padding(0, margin, 10, margin);
            _villagerSelectionBox.Items.AddRange(_villagerNames);

            for (var i = 0; i < _villagers.Count; i++)
            {
                if (villagers.ElementAt(i).Key != _villager.Data.VillagerId)
                {
                    continue;
                }
                _villagerSelectionBox.SelectedIndex = i;
                break;
            }

            _villagerSelectionBox.SelectedIndexChanged += (s, e) => VillagerSelectionBoxChanged();

            _personalityBox = new ComboBox
            {
                Size          = new Size(80, 32),
                DropDownStyle = ComboBoxStyle.DropDownList
            };

            margin = CalculateControlVerticalMargin(_personalityBox);
            _personalityBox.Margin = new Padding(0, margin, 10, margin);
            _personalityBox.Items.AddRange(_personalityTypes);
            _personalityBox.SelectedIndex         = _villager.Data.Personality % _personalityTypes.Length;
            _personalityBox.SelectedIndexChanged += (o, e) => PersonalityChanged();

            _catchphraseBox = new TextBox
            {
                Size      = new Size(100, 32),
                MaxLength = _villager.Offsets.CatchphraseSize,
                Text      = _villager.Data.Catchphrase
            };

            margin = CalculateControlVerticalMargin(_catchphraseBox);
            _catchphraseBox.Margin       = new Padding(0, margin, 10, margin);
            _catchphraseBox.TextChanged += (s, e) => CatchphraseChanged();

            _shirtEditor              = new SingleItemEditor(mainFormReference, _villager.Data.Shirt, 16);
            margin                    = CalculateControlVerticalMargin(_shirtEditor);
            _shirtEditor.Margin       = new Padding(0, margin, 10, margin);
            _shirtEditor.ItemChanged += delegate(object sender, ItemChangedEventArgs e)
            {
                _villager.Data.Shirt = e.NewItem;
            };

            if (_villager.Data.Umbrella != null)
            {
                _umbrellaEditor        = new SingleItemEditor(mainFormReference, _villager.Data.Umbrella, 16);
                margin                 = CalculateControlVerticalMargin(_umbrellaEditor);
                _umbrellaEditor.Margin = new Padding(0, margin, 10, margin);
            }

            // Add controls to flow panel

            Controls.Add(_indexLabel);
            Controls.Add(_villagerSelectionBox);
            Controls.Add(_personalityBox);
            Controls.Add(_catchphraseBox);
            Controls.Add(_shirtEditor);
            Controls.Add(_umbrellaEditor);

            // Set up controls that are used on a per-save generation basis

            switch (_saveFile.SaveGeneration)
            {
            case SaveGeneration.N64:
            case SaveGeneration.GCN:
            case SaveGeneration.iQue:
                // e+ exclusive controls TODO: These will probably be used in City Folk as well.
                if (_saveFile.SaveType == SaveType.DoubutsuNoMoriEPlus || _saveFile.SaveType == SaveType.AnimalForestEPlus)
                {
                    _nameBox = new TextBox
                    {
                        Size      = new Size(60, 32),
                        Text      = _villager.Name,
                        MaxLength = _saveFile.SaveType == SaveType.AnimalForestEPlus ? 8 : 6
                    };

                    margin                = CalculateControlVerticalMargin(_nameBox);
                    _nameBox.Margin       = new Padding(0, margin, 10, margin);
                    _nameBox.TextChanged += (s, e) => NameTextChanged();

                    _importDlcButton = new Button
                    {
                        Text     = "Import DLC Data",
                        AutoSize = true
                    };

                    margin = CalculateControlVerticalMargin(_importDlcButton);
                    _importDlcButton.Margin = new Padding(0, margin, 10, margin);
                    _importDlcButton.Click += (s, e) => ImportDlcVillager();

                    Controls.Add(_nameBox);
                    Controls.Add(_importDlcButton);
                }

                _villagerPreviewBox = new OffsetablePictureBox
                {
                    Size   = new Size(64, 64),
                    Image  = VillagerList,
                    Offset = (_villager.Data.VillagerId < 0xE000 || _villager.Data.VillagerId > 0xE0EB) ? new Point(64 * 6, 64 * 23)
                            : new Point(64 * ((_villager.Data.VillagerId & 0xFF) % 10), 64 * ((_villager.Data.VillagerId & 0xFF) / 10))
                };
                Controls.Add(_villagerPreviewBox);

                break;

            case SaveGeneration.NDS:
            case SaveGeneration.Wii:
            case SaveGeneration.N3DS:
                _carpetWallpaperEditor = new ItemEditor(mainFormReference,
                                                        new[] { _villager.Data.Carpet, _villager.Data.Wallpaper }, 2, 16);
                margin = CalculateControlVerticalMargin(_carpetWallpaperEditor);
                _carpetWallpaperEditor.Margin = new Padding(0, margin, 10, margin);

                _musicEditor        = new SingleItemEditor(mainFormReference, _villager.Data.Song, 16);
                margin              = CalculateControlVerticalMargin(_musicEditor);
                _musicEditor.Margin = new Padding(0, margin, 10, margin);

                _furnitureEditor = new ItemEditor(mainFormReference, _villager.Data.Furniture,
                                                  _villager.Data.Furniture.Length, 16);
                margin = CalculateControlVerticalMargin(_furnitureEditor);
                _furnitureEditor.Margin = new Padding(0, margin, 10, margin);

                Controls.Add(_carpetWallpaperEditor);
                Controls.Add(_musicEditor);
                Controls.Add(_furnitureEditor);

                if (_saveFile.SaveGeneration == SaveGeneration.N3DS)
                {
                    _boxedCheckBox = new CheckBox
                    {
                        Text    = "Boxed",
                        Checked = _villager.Boxed()
                    };

                    margin = CalculateControlVerticalMargin(_boxedCheckBox);
                    _boxedCheckBox.Margin          = new Padding(0, margin, 10, margin);
                    _boxedCheckBox.CheckedChanged += (o, e) => BoxedCheckBoxChanged();

                    Controls.Add(_boxedCheckBox);
                }

                break;

            case SaveGeneration.Unknown:
                break;

            default:
                Console.Write($"Unhandled save generation {_saveFile.SaveGeneration}!");
                break;
            }
        }
Esempio n. 38
0
        public static void UpdateEndurance(PlayerSetup.Player player, HubContext context)
        {
            try
            {
                if (player == null)
                {
                    return;
                }

                if (player.MovePoints <= player.MaxMovePoints)
                {
                    var die     = new Helpers();
                    var maxGain = player.Dexterity / 4;

                    if (player.Status == Player.PlayerStatus.Fighting)
                    {
                        maxGain = maxGain / 4;
                    }

                    if (player.Status == Player.PlayerStatus.Sleeping)
                    {
                        maxGain = maxGain * 2;
                    }


                    if (player.Status == Player.PlayerStatus.Resting)
                    {
                        maxGain = (maxGain * 2) / 2;
                    }

                    player.MovePoints += die.dice(1, 1, maxGain);

                    if (player.MovePoints > player.MaxMovePoints)
                    {
                        player.MovePoints = player.MaxMovePoints;
                    }


                    if (player.Type == Player.PlayerTypes.Player)
                    {
                        if (player.HubGuid == null)
                        {
                            return;
                        }

                        context.UpdateStat(player.HubGuid, player.MovePoints, player.MaxMovePoints, "endurance");
                    }

                    Score.ReturnScoreUI(player);
                }
            }
            catch (Exception ex)
            {
                var log = new Error.Error
                {
                    Date         = DateTime.Now,
                    ErrorMessage = ex.InnerException.ToString(),
                    MethodName   = "Update endurance"
                };

                Save.LogError(log);
            }
        }
Esempio n. 39
0
    public static bool HasSurpassedTime(Save.LevelHighScore score, Level level)
    {
        if (level != null)
            return score.Time <= level.ranks.TimeThreshold;

        return false;
    }
Esempio n. 40
0
        private void cache_btn_Click(object sender, EventArgs e)
        {
            if (Interface.Device == null)
            {
                Interface = new iDevice();
            }
            if (Interface.Device == null)
            {
                lblStatus.Text = "No device connected";
                return;
            }
            grpCache.Enabled       = false;
            activate_btn.Enabled   = false;
            deactivate_btn.Enabled = false;
            cache_btn.Enabled      = false;
            MessageBox.Show("The process of creating a cache is simple: perform a legit activation, storing all the required data. That way, you can borrow (or, I guess, steal (don't do that, though)) a sim for the carrier your iPhone is locked to, and be able to reactivate without having to get that sim back.\nThis data is stored in a folder where you want it. It does not get sent to me (iSn0wra1n) or anyone else. Plus, we really have better things to do than look at your activation data.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //This really isn't needed for iPod Touches or Wi-Fi only iPads (and I don't know if 3G iPad users need this, but be safe and do it).\n\nPress any key to continue or CONTROL-C to abort...\n\n");
            if (activationticket.Checked == true && Interface.CopyValue("ActivationState") == "Unactivated")
            {
                #region Get Wildcard Ticket
                string response = null;
                if (IsConnected() == false)
                {
                    lblStatus.Text = "No Internet connection available";
                    return;
                }
                lblStatus.Text = "Getting Wildcard ticket from Apple";
                ThreadStart starter = delegate
                {
                    SslTcpClient.RunClient("albert.apple.com", Albert_Apple_Stuff(null), ref response);
                };
                Thread albertThread = new Thread(starter);
                albertThread.Start();
                while (albertThread.IsAlive == true)
                {
                    Application.DoEvents();
                }
                if (response == "")
                {
                    lblStatus.Text = "No response returned from Apple";
                    return;
                }
                #endregion
                #region Grab necessary information
                lblStatus.Text = "Grabbing information from the Wildcard ticket";
                string[] keys   = { "AccountTokenCertificate", "AccountToken", "FairPlayKeyData", "DeviceCertificate", "AccountTokenSignature" };
                IntPtr[] values = GrabTheData(response);
                #endregion
activationticket:
                Save.Filter     = "Activation Ticket|*.iTicket";
                Save.DefaultExt = "iTicket";
                Save.ShowDialog();
                if (Save.FileName == "")
                {
                    MessageBox.Show("Please select a location!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    goto activationticket;
                }
                File.WriteAllText(Save.FileName, new CFDictionary(keys, values).ToString());
                lblStatus.Text = "Activation Ticket saved";
                Save.FileName  = "";
            }
            else if (activationdata.Checked == true)
            {
activationdata:
                try
                {
                    Save.Filter     = "Activation Data|*.iData";
                    Save.DefaultExt = "iData";
                    Save.ShowDialog();
                    if (Save.FileName == "")
                    {
                        MessageBox.Show("Please select a location!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        goto activationdata;
                    }
                    File.WriteAllText(Save.FileName, new CFDictionary(Interface.CopyDictionary("ActivationInfo")).ToString());
                    lblStatus.Text = "Activation Data Saved";
                    Save.FileName  = "";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                }
            }
            else if (activationticket.Checked == true && Interface.CopyValue("ActivationState") != "Unactivated")
            {
                lblStatus.Text = "Deactivate device to cache Activation Ticket";
            }
            else
            {
                lblStatus.Text = "No cache option selected";
            }
            activate_btn.Enabled   = true;
            deactivate_btn.Enabled = true;
            cache_btn.Enabled      = true;
            grpCache.Enabled       = true;
        }
Esempio n. 41
0
        public ActionResult Create(Order order)
        {
            if (Session["UserID"] == null)
            {
                return(RedirectToAction("Index", "Home", new { area = "" }));
            }

            int user_id = Convert.ToInt32(Session["UserID"]);

            var shopcart = (from s in db.Cart where (s.UserID == user_id) select s).ToList();

            foreach (var i in shopcart)
            {
                order.Time       = DateTime.Now;
                order.Count      = i.Number;
                order.TotalPrice = i.Number * i.Item.Price;
                order.ItemID     = i.ItemID;
                order.UserID     = i.UserID;
                order.State      = 0;

                //
                var point = (from l in db.Save where (l.UserID == user_id) select l).ToList();
                if ((order.TotalPrice - point[0].Money) >= 0)
                {
                    TempData["message"] = "餘額不足";
                    return(RedirectToAction("Index", "ShoppingCart", new { area = "" }));;
                }

                var item_count = (from l in db.Item where (l.ID == order.ItemID) select l).ToList();
                if ((order.Count - item_count[0].Count) > 0)
                {
                    TempData["message"] = "庫存不足";
                    return(RedirectToAction("Index", "ShoppingCart", new { area = "" }));;
                }



                if (ModelState.IsValid)
                {
                    db.Order.Add(order);
                    db.SaveChanges();


                    Save save = db.Save.Find(point[0].ID);
                    save.Money = save.Money - order.TotalPrice;
                    db.SaveChanges();

                    Item item = db.Item.Find(item_count[0].ID);
                    item.Count = item.Count - order.Count;
                    db.SaveChanges();



                    Cart bye = db.Cart.Find(i.ID);
                    db.Cart.Remove(bye);
                    db.SaveChanges();
                }
            }

            Session["Money"] = db.Save.AsNoTracking().FirstOrDefault(a => a.UserID == user_id).Money;
            return(RedirectToAction("Index"));
        }
Esempio n. 42
0
        public static void UpdateAffects(PlayerSetup.Player player, HubContext context)
        {
            try
            {
                if (player?.Effects == null)
                {
                    return;
                }

                foreach (var af in player.Effects.ToList())
                {
                    if (af.Duration == 0 || af.Duration <= 0)
                    {
                        // put in method? or change way we handle invis
                        if (af.Name == "Invis")
                        {
                            player.invis = false;
                        }

                        if (af.Name == "Detect Invis")
                        {
                            player.DetectInvis = false;
                        }


                        if (af.Name == "Armour")
                        {
                            player.ArmorRating -= 20;
                        }

                        if (af.Name == "Chill Touch")
                        {
                            player.Equipment.Wielded = "Nothing";
                            var chillTouch = player.Inventory.FirstOrDefault(x => x.name.Equals("Chill Touch"));
                            player.Inventory.Remove(chillTouch);
                        }

                        if (af.AffectLossMessageRoom != null)
                        {
                            HubContext.Instance.SendToClient(af.AffectLossMessagePlayer, player.HubGuid);
                        }

                        if (af.AffectLossMessageRoom != null)
                        {
                            var room = Cache.getRoom(player);

                            foreach (var character in room.players.ToList())
                            {
                                if (player != character && character.HubGuid != null)
                                {
                                    HubContext.Instance.SendToClient(
                                        Helpers.ReturnName(character, player, string.Empty) + " " +
                                        af.AffectLossMessageRoom, character.HubGuid);
                                }
                            }
                        }

                        player.Effects.Remove(af);
                    }
                    else
                    {
                        af.Duration -= 1;
                    }
                }

                Score.UpdateUiAffects(player);
            }
            catch (Exception ex)
            {
                var log = new Error.Error
                {
                    Date         = DateTime.Now,
                    ErrorMessage = ex.InnerException.ToString(),
                    MethodName   = "Update Effects"
                };

                Save.LogError(log);
            }
        }
Esempio n. 43
0
 /// <summary>
 /// 保存ボタン
 /// </summary>
 private void btn_Save_Click(object sender, EventArgs e)
 {
     if (_saveFileDialog.ShowDialog() == DialogResult.OK)
     {
         var save = new Save(this.ReignManager);
         using (FileStream stream = new FileStream(
             _saveFileDialog.FileName,
             FileMode.Create,
             FileAccess.Write))
         {
             var bf = new BinaryFormatter();
             bf.Serialize(stream, save);
         }
     }
 }
 void Start()
 {
     // 读取存档
     save = Save.ReadSave();
 }
Esempio n. 45
0
 public void Bind(Save data, int index)
 {
     SaveName.text = data.Name;
     Index         = index;
     gameObject.SetActive(true);
 }
Esempio n. 46
0
    public static Save Read5(BinaryReader reader)
    {
        // Create a new save to read into.
        Save save = new Save();

        // Read in the unlocked levels
        save.worldUnlocked = reader.ReadInt32();
        save.levelUnlocked = reader.ReadInt32();

        // Read the player name
        save.playerName = reader.ReadString();

        // Read the options
        save.OnlineEnabled = reader.ReadBoolean();

        reader.ReadSingle();
        reader.ReadSingle();

        // Read in the high scores.
        int levelCount = reader.ReadInt32();
        save.highScores = new LevelHighScore[levelCount];

        // Load the scores
        for (int i = 0; i < levelCount; ++i)
        {
            save.highScores[i].Score = reader.ReadSingle();
            save.highScores[i].Speed = reader.ReadSingle();
            save.highScores[i].Time = reader.ReadSingle();
            save.highScores[i].Stars = reader.ReadInt32();
        }

        // Load drone count
        save.droneCount = reader.ReadInt32();

        // Return the new save.
        return save;
    }
Esempio n. 47
0
        public static void UpdateHp(PlayerSetup.Player player, HubContext context)
        {
            try
            {
                if (player == null)
                {
                    return;
                }

                if (player.HitPoints <= player.MaxHitPoints)
                {
                    var divideBy = 4;
                    var die      = new Helpers();

                    if (Skill.CheckPlayerHasSkill(player, "Fast Healing"))
                    {
                        var chanceOfSuccess = Helpers.Rand(1, 100);

                        var fastHealingSkill = player.Skills.FirstOrDefault(x => x.Name.Equals("Fast Healing"));
                        if (fastHealingSkill != null && fastHealingSkill.Proficiency >= chanceOfSuccess)
                        {
                            divideBy = 2;
                        }
                    }

                    var maxGain = player.Constitution / divideBy;


                    if (player.Status == Player.PlayerStatus.Fighting)
                    {
                        maxGain = maxGain / 4;
                    }

                    if (player.Status == Player.PlayerStatus.Sleeping)
                    {
                        maxGain = maxGain * 2;
                    }


                    if (player.Status == Player.PlayerStatus.Resting)
                    {
                        maxGain = (maxGain * 2) / 2;
                    }


                    player.HitPoints += die.dice(1, 1, maxGain);

                    if (player.HitPoints > player.MaxHitPoints)
                    {
                        player.HitPoints = player.MaxHitPoints;
                    }

                    if (player.Type == Player.PlayerTypes.Player)
                    {
                        if (player.HubGuid == null)
                        {
                            return;
                        }

                        context.UpdateStat(player.HubGuid, player.HitPoints, player.MaxHitPoints, "hp");
                    }
                }
            }
            catch (Exception ex)
            {
                var log = new Error.Error
                {
                    Date         = DateTime.Now,
                    ErrorMessage = ex.InnerException.ToString(),
                    MethodName   = "updateHP"
                };

                Save.LogError(log);
            }
        }
Esempio n. 48
0
 protected override ICalculatorState OnSave(Save save)
 {
     save.Invoke(Ctx);
     return(this);
 }
Esempio n. 49
0
    public static Save Read1(BinaryReader reader)
    {
        // Create a new save to read into.
        Save save = new Save();

        // Read in the unlocked levels
        save.worldUnlocked = reader.ReadInt32();
        save.levelUnlocked = reader.ReadInt32();

        // Read in the high scores.
        int levelCount = reader.ReadInt32();
        save.highScores = new LevelHighScore[levelCount];

        // Load the scores
        for (int i = 0; i < levelCount; ++i)
        {
            save.highScores[i].Score = reader.ReadSingle();
            save.highScores[i].Speed = reader.ReadSingle();
            save.highScores[i].Time = reader.ReadSingle();
            save.highScores[i].Stars = reader.ReadInt32();
        }

        // Return the new save.
        return save;
    }
    // Obtem o resultado da conexao
    private void handleConnection(WWW conn, string id, object state, byte[] form_data, Hashtable headers)
    {
        //Debug.Log(conn.text);
        // Verifica se houve erro
        if (conn.error != null)
        {
            Debug.LogError("Internal server error (" + url + "): " + conn.error);

            string error = "";
            if (!messages.TryGetValue("server_error", out error))
            {
                error = DEFAULT_ERROR_MESSAGE;
            }
            sendToCallbackPersistent(error, null, state, id, conn.url, form_data, headers);

            return;
        }

        JSonReader  reader = new JSonReader();
        IJSonObject data   = null;

        // Faz o parse da resposta
        try
        {
            data = reader.ReadAsJSonObject(conn.text);
        }
        catch (JSonReaderException)
        {
            string fbError = conn.text;

            if (fbError.Contains("ask") && fbError.Contains("fb_token"))
            {
                new GameFacebook().login();
                sendToCallbackPersistent(DEFAULT_FB_TOKEN_ERROR_MESSAGE, null, state, id, conn.url, form_data, headers);
                return;
            }

            Debug.LogError("Error parsing Json: " + conn.text);

            string error = "";
            if (!messages.TryGetValue("json_error", out error))
            {
                error = DEFAULT_ERROR_MESSAGE;
            }
            sendToCallbackPersistent(error, null, state, id, conn.url, form_data, headers);

            return;
        }
        // Verifica se nao houve resultado
        if (data == null)
        {
            sendToCallbackPersistent(null, null, state, id, conn.url, form_data, headers);
            return;
        }

        if (data.Contains("ask"))
        {
            // Caso peca senha,s avisa o erro
            if (data["ask"].ToString() == "password")
            {
                sendToCallbackPersistent(DEFAULT_ERROR_MESSAGE + "j", null, state, id, conn.url, form_data, headers);

                Save.Delete(PlayerPrefsKeys.TOKEN.ToString());
                // Invalid token
                //Scene.Load("Login", Info.firstScene);
            }
            // Obtem o token do Facebook, caso necessario
            else if (data["ask"].ToString() == "fb_token")
            {
                new GameFacebook().login();
                sendToCallbackPersistent(DEFAULT_FB_TOKEN_ERROR_MESSAGE, null, state, id, conn.url, form_data, headers);
            }

            // Refaz a conexao caso necessario e possivel
            //if (redo && GameGUI.components != null) GameGUI.components.StartCoroutine(startConnection(form, state, false));
            //else Application.LoadLevel(GameGUI.components.login_scene);

            return;
        }

        // Salva o token enviado pelo caso necessario
        if (data.Contains("token"))
        {
            if (!Save.HasKey(PlayerPrefsKeys.TOKEN_EXPIRATION.ToString()))
            {
                Save.Set(PlayerPrefsKeys.TOKEN_EXPIRATION.ToString(), data["expiration"].ToString(), true);
                Save.Set(PlayerPrefsKeys.TOKEN.ToString(), data["token"].ToString(), true);
            }

            else
            {
                System.DateTime old_date = System.DateTime.Parse(Save.GetString(PlayerPrefsKeys.TOKEN_EXPIRATION.ToString()));
                System.DateTime new_date = System.DateTime.Parse(data["expiration"].ToString());

                if (new_date > old_date)
                {
                    Save.Set(PlayerPrefsKeys.TOKEN.ToString(), data["token"].ToString(), true);
                }
            }
        }

        // Trata a mensagem de erro
        if (data.Contains("error"))
        {
            Debug.LogError("Server error: " + data["error"].ToString());

            string error = "";
            if (!messages.TryGetValue(data["error"].ToString(), out error))
            {
                error = DEFAULT_ERROR_MESSAGE;
            }

            sendToCallbackPersistent(error, ExtensionJSon.Empty(), state, id, conn.url, form_data, headers);

            return;
        }

        // Chama o callback com o resultado
        /*if (Scene.GetCurrent() != GameGUI.components.login_scene) */ data = data["result", (IJSonObject)null];
        sendToCallbackPersistent(null, data, state, id, conn.url, form_data, headers);
    }
Esempio n. 51
0
        public static void GenerateTestDataAndFile()
        {
            Planets = GenerateDefaultPlanetData();

              // Output Data
              Save[] Saves;
              List<Planet>[] PlanetSaves;

              PlanetSaves = new List<Planet>[]
              {
            Planets,
            Planets,
            Planets,
              };

              // Player Save Data
              Saves = new Save[]
              {
            new Save(),
            new Save(),
            new Save()
              };

              Saves[0] = new Save();
              Saves[0].Character = (int)CharacterTypes.Norman;
              Saves[0].Whale = (int)WhaleTypes.Pilot;
              Saves[0].PositionInSpace = Vector2.Zero;
              Saves[0].PositionOnPlanet = Vector2.Zero;
              Saves[0].InSpace = true;
              Saves[0].OnPlanetID = -1;

              Saves[1] = new Save();
              Saves[1].Character = (int)CharacterTypes.Captain;
              Saves[1].Whale = (int)WhaleTypes.Humpback;
              Saves[1].PositionInSpace = Vector2.Zero;
              Saves[1].PositionOnPlanet = Vector2.Zero;
              Saves[1].InSpace = true;
              Saves[1].OnPlanetID = -1;

              Saves[2] = new Save();
              Saves[2].Character = (int)CharacterTypes.Dapper;
              Saves[2].Whale = (int)WhaleTypes.Orca;
              Saves[2].PositionInSpace = Vector2.Zero;
              Saves[2].PositionOnPlanet = Vector2.Zero;
              Saves[2].InSpace = true;
              Saves[2].OnPlanetID = -1;

              // Save to file
              try
              {
            for (int i = 0; i < Saves.Length; i++)
            {
              string json = JsonConvert.SerializeObject(Saves[i], Formatting.Indented);
              File.WriteAllText(@"character" + i.ToString("D2") + ".json", json);
            }

            for (int i = 0; i < PlanetSaves.Length; i++)
            {
              string json = JsonConvert.SerializeObject(PlanetSaves[i], Formatting.Indented);
              File.WriteAllText(@"planets" + i.ToString("D2") + ".json", json);
            }
              }
              catch (Exception ex)
              {
            Console.WriteLine("JSON error: " + ex.Message);
            throw;
              }
        }
Esempio n. 52
0
 public void set()
 {
     Save.curSave = field.text;
     Save.SaveData();
 }
Esempio n. 53
0
    private void BindCommands(CompositeDisposable disposables)
    {
        this.BindCommand(this.ViewModel !, vm => vm.GoToSeries, v => v.GoToSeriesButton)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.GoToSeries, v => v.GoToSeriesIconButton)
        .DisposeWith(disposables);

        this.ViewModel !.GoToSeries.CanExecute
        .BindTo(this, v => v.GoToSeriesIconButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.Cancel, v => v.CancelButton)
        .DisposeWith(disposables);

        this.ViewModel !.Cancel.CanExecute
        .BindTo(this, v => v.CancelButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.Close, v => v.CloseButton)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.GoToNext, v => v.GoToNextButton)
        .DisposeWith(disposables);

        this.ViewModel !.GoToNext.CanExecute
        .BindTo(this, v => v.GoToNextButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.GoToPrevious, v => v.GoToPreviousButton)
        .DisposeWith(disposables);

        this.ViewModel !.GoToPrevious.CanExecute
        .BindTo(this, v => v.GoToPreviousButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.Close, v => v.CloseButton)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.Delete, v => v.DeleteButton)
        .DisposeWith(disposables);

        this.ViewModel !.Delete.CanExecute
        .BindTo(this, v => v.DeleteButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.AddTitle, v => v.AddTitleButton)
        .DisposeWith(disposables);

        this.ViewModel !.AddTitle.CanExecute
        .BindTo(this, v => v.AddTitleButton.IsVisible)
        .DisposeWith(disposables);

        this.BindCommand(this.ViewModel !, vm => vm.AddOriginalTitle, v => v.AddOriginalTitleButton)
        .DisposeWith(disposables);

        this.ViewModel !.AddOriginalTitle.CanExecute
        .BindTo(this, v => v.AddOriginalTitleButton.IsVisible)
        .DisposeWith(disposables);

        this.ViewModel !.Save
        .Subscribe(_ => this.LoadPoster())
        .DisposeWith(disposables);
    }
Esempio n. 54
0
 public static void OpenSaveMenu(Save save)
 {
     _save = save;
     menu  = new ChoseLevel(_screenWidth, _screenHeight, _save);
 }
Esempio n. 55
0
 public MainChartWindow(Save.CManager manager)
 {
     _manager = manager;
     InitializeComponent();
 }
Esempio n. 56
0
        public Gameplay(Save save)
        {
            var factory = new DbContextFactory();
            var context = factory.CreateDbContext(null);

            this.Save   = save;
            this.Player = context.Players.First(player => player.Id == Save.PlayerId);

            // Check if Monster is Present
            try
            {
                Monster          = context.Monsters.First(monster => monster.SaveId == Save.Id && monster.Latitude == Player.Latitude && monster.Longitude == Player.Longitude);
                isMonsterPresent = true;
            } catch
            {
                Monster          = null;
                isMonsterPresent = false;
            }

            do
            {
                try
                {
                    Exit          = context.Exits.First(e => e.Id == Save.Id && e.Latitude == Player.Latitude && e.Longitude == Player.Longitude);
                    isExitPresent = true;
                }
                catch
                {
                    isExitPresent = false;
                }

                if (isInputValid)
                {
                    Console.WriteLine("Erreur : Veuillez rentrer une valeur correcte.");
                    Thread.Sleep(2000);
                }

                Console.Clear();

                if (!isMonsterPresent)
                {
                    if (!isExitPresent)
                    {
                        if (Player.DropItem())
                        {
                            Console.ReadLine();
                            Console.Clear();
                        }
                        Console.WriteLine("Vous êtes en  X : {0} - Y : {1}", Player.Latitude, Player.Longitude);
                        Console.WriteLine("Vous arrivez dans une salle vide. Vous êtes seuls");
                        Console.WriteLine("Que voulez-vous faire ?");
                        Console.WriteLine("");
                        Console.WriteLine("1 - Se déplacer");
                        Console.WriteLine("2 - Afficher l'inventaire");
                        Console.WriteLine("3 - Afficher les statistiques");
                        Console.WriteLine("4 - Quitter");

                        try
                        {
                            selectorChoice = Int32.Parse(Console.ReadLine());
                        }
                        catch
                        {
                            selectorChoice = 0;
                        }


                        if (selectorChoice > 0 && selectorChoice < 5)
                        {
                            isInputValid = true;
                        }
                        else
                        {
                            isInputValid = false;
                        }
                    }
                    else
                    {
                        new Win(save);
                    }
                }
                else
                {
                    new Fight(Player, Monster, true);
                }
            } while (!isInputValid);

            switch (selectorChoice)
            {
            case 1:
                new Move(Player);
                new Gameplay(save);
                break;

            case 2:
                new ListInventory(Player);
                new Gameplay(save);
                break;

            case 3:
                new ListStats(Player);
                new Gameplay(save);
                break;

            case 4:
                new Home();
                break;

            default:
                Console.WriteLine("Veuillez rentrez un choix valide");
                Console.ReadLine();
                new Gameplay(Save);
                break;
            }
        }
Esempio n. 57
0
        public virtual IEnumerable CheckForDuplicates(PXAdapter adapter)
        {
            foreach (Contact rec in adapter.Get())
            {
                Contact.Current = rec;
                Contact contact = rec;

                if (adapter.ExternalCall || rec.DuplicateStatus == DuplicateStatusAttribute.NotValidated)
                {
                    contact = Contact.Cache.CreateCopy(Contact.Current) as Contact;
                    contact.DuplicateStatus = DuplicateStatusAttribute.NotValidated;
                    Contact.Update(contact);

                    Contact.Current.DuplicateFound = true;
                    Duplicates.View.Clear();
                    var result = Duplicates.Select();


                    contact = Contact.Cache.CreateCopy(Contact.Current) as Contact;
                    contact.DuplicateFound  = (result != null && result.Count > 0);
                    contact.DuplicateStatus = DuplicateStatusAttribute.Validated;

                    Decimal?score = 0;
                    foreach (PXResult <CRDuplicateRecord, Contact, CRLeadContactValidationProcess.Contact2> r in result)
                    {
                        CRLeadContactValidationProcess.Contact2 duplicate = r;
                        CRDuplicateRecord contactScore = r;
                        int duplicateWeight            = GetContactWeight(duplicate);
                        int currentWeight = GetContactWeight(Contact.Current);
                        if (duplicateWeight > currentWeight ||
                            (duplicateWeight == currentWeight &&
                             duplicate.ContactID < Contact.Current.ContactID))
                        {
                            contact.DuplicateStatus = DuplicateStatusAttribute.PossibleDuplicated;
                            if (contactScore.Score > score)
                            {
                                score = contactScore.Score;
                            }
                        }
                    }
                    contact = Contact.Update(contact);

                    if (Contact.Current.DuplicateFound == false)
                    {
                        if (adapter.ExternalCall)
                        {
                            Contact.Cache.RaiseExceptionHandling <Contact.duplicateStatus>(contact, null,
                                                                                           new PXSetPropertyException(
                                                                                               Messages.NoPossibleDuplicates,
                                                                                               PXErrorLevel.RowInfo));
                        }
                        else
                        {
                            Contact.Cache.RaiseExceptionHandling <Contact.duplicateStatus>(contact, null, null);
                        }
                    }
                }
                yield return(contact);
            }

            if (Contact.Cache.IsDirty)
            {
                Save.Press();
            }
        }
Esempio n. 58
0
        public static void UpdateRooms()
        {
            var context = HubContext.Instance;
            var rooms   = Cache.ReturnRooms();

            if (rooms.Count == 0)
            {
                return;
            }

            try
            {
                foreach (var room in rooms)
                {
                    foreach (var mob in room.mobs.ToList())
                    {
                        if (mob.Status != Player.PlayerStatus.Dead || mob.HitPoints > 0)
                        {
                            UpdateHp(mob, context);
                            UpdateMana(mob, context);
                            UpdateEndurance(mob, context);
                            UpdateAffects(mob, context);
                        }
                    }


                    #region add Mobs back

                    if (room.players.Count >= 1)
                    {
                        continue; //don't remove corpse incase player is in room so they have chance to loot it.
                                  // maybe decay corpse and eventually remove
                    }

                    if (room.corpses.Count > 0)
                    {
                        // decay corpse

                        foreach (var corpse in room.corpses.ToList())
                        {
                            if (corpse.Type.Equals(Player.PlayerTypes.Player))
                            {
                                continue;
                            }

                            var mobRoomOrigin =
                                rooms.Find(
                                    x =>
                                    x.areaId == corpse.Recall.AreaId && x.area == corpse.Recall.Area &&
                                    x.region == corpse.Recall.Region);
                            var originalArea = Startup.ReturnRooms.FirstOrDefault(x =>
                                                                                  x.area == mobRoomOrigin.area && x.areaId == mobRoomOrigin.areaId &&
                                                                                  x.region == mobRoomOrigin.region);

                            if (originalArea != null)
                            {
                                // potential bug with mobs that have the same name but only one carries an item
                                // finding the origianl mob will probbaly match for one but not the other so the
                                // mob with the other item never gets loaded.
                                // potential way round it. random loot drops for mobs that don't have a name and are genric ie. rat
                                // mobs like village idiot have set items
                                var originalMob = originalArea.mobs.Find(x => x.Name == corpse.Name);

                                if (originalMob != null)
                                {
                                    room.items.Remove(room.items.Find(x => x.name.Contains(originalMob.Name)));
                                    room.corpses.Remove(room.corpses.Find(x => x.Name.Equals(originalMob.Name)));

                                    if (room.mobs.FirstOrDefault(x => x.Name.Contains(originalMob.Name)) == null)
                                    {
                                        var mobHomeRoom = rooms.FirstOrDefault(x => x.areaId == originalMob.Recall.AreaId && x.area == originalMob.Recall.Area && x.region == originalMob.Recall.Region);
                                        mobHomeRoom.mobs.Add(originalMob);
                                    }
                                }
                            }
                        }
                    }


                    #endregion

                    foreach (var item in room.items.Where(x => x.Duration > -1).ToList())
                    {
                        if (item.name.Contains("corpse"))
                        {
                            if (item.Duration > 3 && item.Duration <= 5 && !item.name.Contains("rotting"))
                            {
                                var newCorpseName = item.name.Replace("corpse", "rotting corpse");
                                item.name = newCorpseName;
                            }

                            if (item.Duration <= 3 && !item.name.Contains("decayed"))
                            {
                                var newCorpseName = item.name.Replace("rotting corpse", "decayed corpse");
                                item.name = newCorpseName;
                            }

                            if (item.Duration == 0)
                            {
                                foreach (var loot in item.containerItems)
                                {
                                    room.items.Add(loot);
                                }

                                room.items.Remove(item);
                                continue;
                            }
                        }
                        else
                        {
                            if (item.Duration == 0)
                            {
                                room.items.Remove(item);
                                continue;
                            }
                        }

                        item.Duration -= 1;
                    }

                    #region add Items back

                    for (int j = Startup.ReturnRooms.Count - 1; j >= 0; j--)
                    {
                        if (Startup.ReturnRooms[j].area == room.area &&
                            Startup.ReturnRooms[j].areaId == room.areaId &&
                            Startup.ReturnRooms[j].region == room.region)
                        {
                            for (int k = Startup.ReturnRooms[j].items.Count - 1; k >= 0; k--)
                            {
                                var itemAlreadyThere =
                                    room.items.Find(x => x.name.Equals(Startup.ReturnRooms[j].items[k].name));

                                if (itemAlreadyThere == null)
                                {
                                    room.items.Add(Startup.ReturnRooms[j].items[k]);
                                }

                                if (room.items.Count(x => x.name.Equals(Startup.ReturnRooms[j].items[k].name)) < Startup.ReturnRooms[j].items.Count(x => x.name.Equals(Startup.ReturnRooms[j].items[k].name)))
                                {
                                    room.items.Add(Startup.ReturnRooms[j].items[k]);
                                }

                                if (itemAlreadyThere?.container == true)
                                {
                                    for (int l = Startup.ReturnRooms[j].items[k].containerItems.Count - 1; l >= 0; l--)
                                    {
                                        var containerItemAlreadyThere =
                                            itemAlreadyThere.containerItems.Find(
                                                x =>
                                                x.name.Equals(
                                                    Startup.ReturnRooms[j].items[k].containerItems[l].name));

                                        if (containerItemAlreadyThere == null)
                                        {
                                            itemAlreadyThere.containerItems.Add(
                                                Startup.ReturnRooms[j].items[k].containerItems[l]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    if (!string.IsNullOrEmpty(room.updateMessage) && room.players.Count != 0)
                    {
                        foreach (var player in room.players)
                        {
                            HubContext.Instance.SendToClient(room.updateMessage, player.HubGuid);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var log = new Error.Error
                {
                    Date         = DateTime.Now,
                    ErrorMessage = ex.InnerException.ToString(),
                    MethodName   = "Room update f****d"
                };

                Save.LogError(log);
            }
        }
Esempio n. 59
0
 public void AddSave(Save save)
 {
     m_Saves.Add(save);
 }
Esempio n. 60
0
 protected void OnSave()
 {
     Save?.Invoke(this, EventArgs.Empty);
 }