Example #1
0
 public ChunkTable(GameSave gameSave, Tuple<int, int, Chunk>[] chunks)
     : this(gameSave,
         chunks.Select(x => x.Item1).ToArray(),
         chunks.Select(x => x.Item2).ToArray(),
         chunks.Select(x => x.Item3).ToArray())
 {
 }
Example #2
0
        public static void TestAddChunkToUnloadedChunks(GameSave gameSave, Header header)
        {
            ChunkTable oldChunkTable = header.SaveIndex.ChunkTable;

            var octree = new Octree(gameSave, new BitArray(new[] { false, false }), new byte[] { 1 });
            var blockTypeTable = new BlockTypeTable(gameSave,
                                                    new[]
                                                        {
                                                            new StringBlock(gameSave, "Block 0"),
                                                            new StringBlock(gameSave, "Block 1"),
                                                            new StringBlock(gameSave, "Block 2"),
                                                            new StringBlock(gameSave, "Block 2")
                                                        },
                                                    new[] { 0, 0, 0, 1 });
            var chunk = new Chunk(gameSave, blockTypeTable, new[] { octree });

            var r = new Random();

            int x = r.Next();
            int z = r.Next();

            List<Tuple<int, int, Chunk>> chunks =
                oldChunkTable.GetChunks().Where(c => c.Item1 != x || c.Item2 != z).ToList();
            chunks.Add(new Tuple<int, int, Chunk>(x, z, chunk));

            var chunkTable = new ChunkTable(gameSave, chunks.ToArray());
            var mainIndex = new SavedStateIndex(gameSave, DateTime.UtcNow.Ticks,
                                                new StringBlock(gameSave, "ChunkTable Length: " + chunkTable.Length),
                                                chunkTable);
            var newHeader = new Header(gameSave, mainIndex);

            newHeader.Write(true);
        }
Example #3
0
        public Header(GameSave gameSave, SavedStateIndex saveIndex)
            : base(gameSave)
        {
            Address = new Tuple<int, uint>(0, 0);
            SaveIndex = saveIndex;

            UpdateLength();
        }
 public GameSettings()
 {
     _gameMode = GameMode.Adventure;
     _numberOfPlayers  = NumberOfPlayersSelected.OnePlayer;
     _levelSelected = LevelSelection.Tropical;
     _adventureMode = AdventureMode.Continue;
     _gameSave = GameSave.SaveFile1;
 }
 public static void DeleteSaves()
 {
     if (File.Exists(Application.persistentDataPath + "/savedGame.Tendresse")) {
         File.Delete(Application.persistentDataPath + "/savedGame.Tendresse");
     }
     savedGame = new GameSave();
     GameSave.current = savedGame;
 }
Example #6
0
        public Chunk(GameSave gameSave, BlockTypeTable blockTypeTable, Octree[] octrees)
            : base(gameSave)
        {
            _blockTypeTable = blockTypeTable;
            _octrees = octrees;

            UpdateLength();
        }
Example #7
0
        public Octree(GameSave gameSave, BitArray octreeFlags, byte[] octreeValues)
            : base(gameSave)
        {
            _octreeFlags = octreeFlags;
            _octreeValues = octreeValues;

            UpdateLength();
        }
Example #8
0
        public SavedStateIndex(GameSave gameSave, long timestamp, StringBlock saveName, ChunkTable chunkTable)
            : base(gameSave)
        {
            _timestamp = timestamp;
            _saveName = saveName;
            _chunkTable = chunkTable;

            UpdateLength();
        }
Example #9
0
 internal static ByteArray FromSave(GameSave gameSave, Tuple<int, uint> address)
 {
     ByteArray byteArray;
     if (!gameSave.TryGetFromBlockStructureCache(address, out byteArray))
     {
         byteArray = new ByteArray(gameSave, address);
         gameSave.AddToBlockStructureCache(address, byteArray);
     }
     return byteArray;
 }
Example #10
0
	// Use this for initialization
	void Awake () {
		if(control == null)
		{
			DontDestroyOnLoad (gameObject);
			control = this;
		}
		else if (control != this)
		{
			Destroy(gameObject);
		}
		Load ();
	}
Example #11
0
        public ChunkTable(GameSave gameSave, int[] xLocations, int[] zLocations, Chunk[] chunks)
            : base(gameSave)
        {
            if (xLocations.Length != zLocations.Length || zLocations.Length != chunks.Length)
            {
                throw new ArgumentException("Argument arrays must have the same length!");
            }
            _xLocations = xLocations;
            _zLocations = zLocations;
            _chunks = chunks;

            UpdateLength();
        }
Example #12
0
    void Awake()
    {
        control = this;

        created = PlayerPrefs.GetInt("GameCreated");

        if (created !=1)
        {
            StatCreation();
        }

        LoadStats();

        InGameStats();
    }
Example #13
0
        public static void TestMarkModify(GameSave gameSave, Header header)
        {
            var newChunkTable =
                new ChunkTable(gameSave,
                               header.SaveIndex.ChunkTable.GetChunks().Concat(
                                   header.SaveIndex.ChunkTable.GetChunks().Take(1).Select(
                                       x => new Tuple<int, int, Chunk>(x.Item1 + 1, x.Item2 - 1, x.Item3))).ToArray());

            var newHeader = new Header(gameSave,
                                       new SavedStateIndex(gameSave, DateTime.UtcNow.Ticks,
                                                           new StringBlock(gameSave, "Modified Save"),
                                                           newChunkTable));

            newHeader.Write(true);
        }
 public static void Load()
 {
     //Debug.Log("Loading at Destination : " + Application.persistentDataPath); //Debug Save Path
     if (File.Exists(Application.persistentDataPath + "/savedGame.Tendresse")) {
         Debug.Log("File exists!");
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Open(Application.persistentDataPath + "/savedGame.Tendresse", FileMode.Open);
         SaveAndLoad.savedGame = (GameSave)bf.Deserialize(file);
         GameSave.current = SaveAndLoad.savedGame;
         file.Close();
     } else {
         Debug.Log("File does not exists!");
         savedGame = new GameSave();
         GameSave.current = savedGame;
     }
 }
Example #15
0
 private Chunk(GameSave gameSave, Tuple<int, uint> address)
     : base(gameSave, address)
 {
 }
Example #16
0
 public void UpdatePersistentData(GameSave newSave)
 {
     levelsData = newSave.levels;
     statsData = newSave.stats;
 }
Example #17
0
        private void InputManager_Update(On.InputManager.orig_Update orig, InputManager self)
        {
            // Do the recording, pausing, resetting, and playing here.
            // Updates the state
            UpdateState();
            // Performs an action depending on the state
            if (SingletonManager.Get <Dungeon>(false) == null)
            {
                // We don't have a Dungeon to work with yet!
                // This should be removed soon and instead of having levels, have time stamps or something else.
                // That would allow for TAS in menus (without a Dungeon)
                orig(self);
                return;
            }
            int level = SingletonManager.Get <Dungeon>(false).Level;

            if (HasFlag(State.Pausing))
            {
                // Need to find some way of doing standard processing except for actually updating the game
            }
            if (HasFlag(State.Playing) && !HasFlag(State.Pausing))
            {
                // Read Inputs from file/RAM and perform them
                if (TASInput.HasNext(level))
                {
                    TASInputPlayer.Update(TASInput.GetNext(level));
                    mod.Log("Playing input: " + TASInputPlayer.Current);
                }
                else
                {
                    mod.Log("Completed input playback!");
                    ToggleState(State.Playing);
                }
            }
            if (HasFlag(State.Recording))
            {
                // Read Inputs from real action into file/RAM
                // Assumes the current level exists.
                TASInput.CreateAndAdd(level);
                // Also make sure that the seed is correctly set
                mod.Log("Recording input: " + TASInput.inputs[level][TASInput.inputs[level].Count - 1].ToString());
                // TODO: REMOVE LINE BELOW
                ToggleState(State.Recording);
            }
            if (HasFlag(State.Saving))
            {
                // Save the current floor as a start point (somehow)
                // Probably just save the SeedData and do a "generateForLevel" or something
                SaveKey = GameSave.GenerateSaveKey();
                SingletonManager.Get <Dungeon>(false).SaveGameData(SaveKey);
                mod.Log("Saved Key: " + SaveKey + " saved successfully!");
                ToggleState(State.Saving);
            }
            if (HasFlag(State.SavingToFile))
            {
                // Assume the Dungeon exists, use it to determine the level to write the TAS for.
                mod.Log("Writing files with *" + tasFileExtensionWrapper.Value);
                TASIO.WriteTAS(TASInput.inputs, tasFileExtensionWrapper.Value);
                ToggleState(State.SavingToFile);
            }
            if (HasFlag(State.ReadingFromFiles))
            {
                // Don't assume that the Dungeon exists, but read the many information things from the TAS file.
                // The trick with this is that the seed also needs to be read.
                TASInput.Clear();
                mod.Log("Reading from *" + tasFileExtensionWrapper.Value + " files...");
                foreach (string file in System.IO.Directory.GetFiles(".", "*" + tasFileExtensionWrapper.Value))
                {
                    // Let's just load all of the info into the TASInput RAM
                    mod.Log("Reading file: " + file);
                    TASIO.ReadTAS(file);
                }
                ToggleState(State.ReadingFromFiles);
            }
            if (HasFlag(State.Resetting))
            {
                // Reset to the current save point (whatever floor it is)
                // Probably just do a "generateForLevel" or something (make the game think the data was saved in a certain way)
                mod.Log("Attempting to load SaveKey: " + SaveKey);
                if (SaveKey.Length > 0)
                {
                    // Only now can we load valid data.
                    mod.Log("Preparing Dungeon for SaveKey!");
                    Dungeon.PrepareForSavedGame(SaveKey, false);
                }
                ToggleState(State.Resetting);
            }
            if (HasFlag(State.Clearing))
            {
                // Clear the data for this level
                TASInput.ClearForLevel(level);
                mod.Log("Cleared all TAS data for level: " + level);
                ToggleState(State.Clearing);
            }
            orig(self);
        }
Example #18
0
 public LocalGameSave(GameSave gameSave, string filePath)
 {
     GameSave = gameSave;
     LocalFilePath = filePath;
 }
Example #19
0
 public bool IsOtherHasBetterProgress(GameSave other)
 {
     return(completedQuests.Count < other.completedQuests.Count);
 }
 private void Save(IAsyncResult result)
 {
     _storageDevice = StorageDevice.EndShowSelector(result);
     if (_storageDevice != null && _storageDevice.IsConnected)
     {
         var filename = String.Format("save{0:00}.dat", _slot);
         var player = PlayerManager.Instance;
         GameSave save = new GameSave()
         {
             Ammo = player.Ammo,
             Lives = player.Lives,
             Hearts = player.Hearts,
             Coins = player.Coins,
             StagesCompleted = player.StagesCompleted
         };
         IAsyncResult r = _storageDevice.BeginOpenContainer(_storageContainerName, null, null);
         result.AsyncWaitHandle.WaitOne();
         Thread.Sleep(1500);
         StorageContainer container = _storageDevice.EndOpenContainer(r);
         if (container.FileExists(filename))
             container.DeleteFile(filename);
         Stream stream = container.CreateFile(filename);
         IFormatter formatter = new BinaryFormatter();
         formatter.Serialize(stream, save);
         stream.Close();
         container.Dispose();
         result.AsyncWaitHandle.Close();
         if (_saveCallback != null)
             _saveCallback();
     }
 }
Example #21
0
 /// <summary>
 /// <para>Initializes a new UniqueBlockStructure instance.</para>
 /// <para>This constructor is for blocks that are newly created.</para>
 /// </summary>
 /// <param name="gameSave">The GameSave instance this block is attached to.</param>
 protected UniqueBlockStructure(GameSave gameSave)
     : base(gameSave)
 {
 }
Example #22
0
 public void CmdLoadBackup()
 {
     GameSave.LoadBackup();
 }
Example #23
0
 public void CmdResetConnections()
 {
     GameSave.ResetConnections();
     RpcResetConnections();
     Debug.Log("All connections reset.");
 }
Example #24
0
 public void RpcResetConnections()
 {
     //TODO: Does this help?
     GameSave.ResetConnections();
 }
Example #25
0
 public QuestItem(GameSave gameSave, QuestItemDefinition definition, int offset) =>
 (_gameSave, _definition, Offset) = (gameSave, definition, offset);
Example #26
0
        void InterpretServerOrder(Connection conn, Order o)
        {
            // Only accept handshake responses from unvalidated clients
            // Anything else may be an attempt to exploit the server
            if (!conn.Validated)
            {
                if (o.OrderString == "HandshakeResponse")
                {
                    ValidateClient(conn, o.TargetString);
                }
                else
                {
                    Log.Write("server", "Rejected connection from {0}; Order `{1}` is not a `HandshakeResponse`.",
                              conn.Socket.RemoteEndPoint, o.OrderString);

                    DropClient(conn);
                }

                return;
            }

            switch (o.OrderString)
            {
            case "Command":
            {
                var handledBy = serverTraits.WithInterface <IInterpretCommand>()
                                .FirstOrDefault(t => t.InterpretCommand(this, conn, GetClient(conn), o.TargetString));

                if (handledBy == null)
                {
                    Log.Write("server", "Unknown server command: {0}", o.TargetString);
                    SendOrderTo(conn, "Message", "Unknown server command: {0}".F(o.TargetString));
                }

                break;
            }

            case "Chat":
                DispatchOrdersToClients(conn, 0, o.Serialize());
                break;

            case "Pong":
            {
                long pingSent;
                if (!OpenRA.Exts.TryParseInt64Invariant(o.TargetString, out pingSent))
                {
                    Log.Write("server", "Invalid order pong payload: {0}", o.TargetString);
                    break;
                }

                var client = GetClient(conn);
                if (client == null)
                {
                    return;
                }

                var pingFromClient = LobbyInfo.PingFromClient(client);
                if (pingFromClient == null)
                {
                    return;
                }

                var history = pingFromClient.LatencyHistory.ToList();
                history.Add(Game.RunTime - pingSent);

                // Cap ping history at 5 values (25 seconds)
                if (history.Count > 5)
                {
                    history.RemoveRange(0, history.Count - 5);
                }

                pingFromClient.Latency        = history.Sum() / history.Count;
                pingFromClient.LatencyJitter  = (history.Max() - history.Min()) / 2;
                pingFromClient.LatencyHistory = history.ToArray();

                SyncClientPing();

                break;
            }

            case "GameSaveTraitData":
            {
                if (GameSave != null)
                {
                    var data = MiniYaml.FromString(o.TargetString)[0];
                    GameSave.AddTraitData(int.Parse(data.Key), data.Value);
                }

                break;
            }

            case "CreateGameSave":
            {
                if (GameSave != null)
                {
                    // Sanitize potentially malicious input
                    var filename     = o.TargetString;
                    var invalidIndex = -1;
                    var invalidChars = Path.GetInvalidFileNameChars();
                    while ((invalidIndex = filename.IndexOfAny(invalidChars)) != -1)
                    {
                        filename = filename.Remove(invalidIndex, 1);
                    }

                    var baseSavePath = Platform.ResolvePath(
                        Platform.SupportDirPrefix,
                        "Saves",
                        ModData.Manifest.Id,
                        ModData.Manifest.Metadata.Version);

                    if (!Directory.Exists(baseSavePath))
                    {
                        Directory.CreateDirectory(baseSavePath);
                    }

                    GameSave.Save(Path.Combine(baseSavePath, filename));
                    DispatchOrdersToClients(null, 0, Order.FromTargetString("GameSaved", filename, true).Serialize());
                }

                break;
            }

            case "LoadGameSave":
            {
                if (Type == ServerType.Dedicated || State >= ServerState.GameStarted)
                {
                    break;
                }

                // Sanitize potentially malicious input
                var filename     = o.TargetString;
                var invalidIndex = -1;
                var invalidChars = Path.GetInvalidFileNameChars();
                while ((invalidIndex = filename.IndexOfAny(invalidChars)) != -1)
                {
                    filename = filename.Remove(invalidIndex, 1);
                }

                var savePath = Platform.ResolvePath(
                    Platform.SupportDirPrefix,
                    "Saves",
                    ModData.Manifest.Id,
                    ModData.Manifest.Metadata.Version,
                    filename);

                GameSave = new GameSave(savePath);
                LobbyInfo.GlobalSettings = GameSave.GlobalSettings;
                LobbyInfo.Slots          = GameSave.Slots;

                // Reassign clients to slots
                //  - Bot ordering is preserved
                //  - Humans are assigned on a first-come-first-serve basis
                //  - Leftover humans become spectators

                // Start by removing all bots and assigning all players as spectators
                foreach (var c in LobbyInfo.Clients)
                {
                    if (c.Bot != null)
                    {
                        LobbyInfo.Clients.Remove(c);
                        var ping = LobbyInfo.PingFromClient(c);
                        if (ping != null)
                        {
                            LobbyInfo.ClientPings.Remove(ping);
                        }
                    }
                    else
                    {
                        c.Slot = null;
                    }
                }

                // Rebuild/remap the saved client state
                // TODO: Multiplayer saves should leave all humans as spectators so they can manually pick slots
                var adminClientIndex = LobbyInfo.Clients.First(c => c.IsAdmin).Index;
                foreach (var kv in GameSave.SlotClients)
                {
                    if (kv.Value.Bot != null)
                    {
                        var bot = new Session.Client()
                        {
                            Index = ChooseFreePlayerIndex(),
                            State = Session.ClientState.NotReady,
                            BotControllerClientIndex = adminClientIndex
                        };

                        kv.Value.ApplyTo(bot);
                        LobbyInfo.Clients.Add(bot);
                    }
                    else
                    {
                        // This will throw if the server doesn't have enough human clients to fill all player slots
                        // See TODO above - this isn't a problem in practice because MP saves won't use this
                        var client = LobbyInfo.Clients.First(c => c.Slot == null);
                        kv.Value.ApplyTo(client);
                    }
                }

                SyncLobbyInfo();
                SyncLobbyClients();
                SyncClientPing();

                break;
            }
            }
        }
Example #27
0
        public void StartGame()
        {
            listener.Stop();

            Console.WriteLine("[{0}] Game started", DateTime.Now.ToString(Settings.TimestampFormat));

            // Drop any unvalidated clients
            foreach (var c in PreConns.ToArray())
            {
                DropClient(c);
            }

            // Drop any players who are not ready
            foreach (var c in Conns.Where(c => GetClient(c).IsInvalid).ToArray())
            {
                SendOrderTo(c, "ServerError", "You have been kicked from the server!");
                DropClient(c);
            }

            // HACK: Turn down the latency if there is only one real player
            if (LobbyInfo.NonBotClients.Count() == 1)
            {
                LobbyInfo.GlobalSettings.OrderLatency = 1;
            }

            // Enable game saves for singleplayer missions only
            // TODO: Enable for multiplayer (non-dedicated servers only) once the lobby UI has been created
            LobbyInfo.GlobalSettings.GameSavesEnabled = Type != ServerType.Dedicated && LobbyInfo.NonBotClients.Count() == 1;

            SyncLobbyInfo();
            State = ServerState.GameStarted;

            foreach (var c in Conns)
            {
                foreach (var d in Conns)
                {
                    DispatchOrdersToClient(c, d.PlayerIndex, 0x7FFFFFFF, new[] { (byte)OrderType.Disconnect });
                }
            }

            if (GameSave == null && LobbyInfo.GlobalSettings.GameSavesEnabled)
            {
                GameSave = new GameSave();
            }

            var startGameData = "";

            if (GameSave != null)
            {
                GameSave.StartGame(LobbyInfo, Map);
                if (GameSave.LastOrdersFrame >= 0)
                {
                    startGameData = new List <MiniYamlNode>()
                    {
                        new MiniYamlNode("SaveLastOrdersFrame", GameSave.LastOrdersFrame.ToString()),
                        new MiniYamlNode("SaveSyncFrame", GameSave.LastSyncFrame.ToString())
                    }.WriteToString();
                }
            }

            DispatchOrders(null, 0,
                           Order.FromTargetString("StartGame", startGameData, true).Serialize());

            foreach (var t in serverTraits.WithInterface <IStartGame>())
            {
                t.GameStarted(this);
            }

            if (GameSave != null && GameSave.LastOrdersFrame >= 0)
            {
                GameSave.ParseOrders(LobbyInfo, (frame, client, data) =>
                {
                    foreach (var c in Conns)
                    {
                        DispatchOrdersToClient(c, client, frame, data);
                    }
                });
            }
        }
Example #28
0
 public void CmdAdjustGameSave(GameObject con, float thresh, float recovery, float absolute, float relative)
 {
     GameSave.NeuronParametersChanged(con.GetComponent <Controller>(), thresh, recovery, absolute, relative);
 }
Example #29
0
 /// <summary>
 /// <para>Initializes a new UniqueBlockStructure instance.</para>
 /// <para>This constructor is for blocks that are read from disk.</para>
 /// </summary>
 /// <param name="gameSave">The GameSave instance this block is attached to.</param>
 /// <param name="address">This block's address.</param>
 protected UniqueBlockStructure(GameSave gameSave,
     Tuple<int, uint> address)
     : base(gameSave, address)
 {
 }
 void Start()
 {
     GS = GameManager.gm.GetComponent<GameSave>();
     Gold.text = GS._gold.currentValue.ToString();
 }
        private void Load(IAsyncResult result)
        {
            _storageDevice = StorageDevice.EndShowSelector(result);
            if (_storageDevice != null && _storageDevice.IsConnected)
            {
                GameSave saveData = new GameSave();
                var filename = String.Format("save{0:00}.dat", _slot);
                IAsyncResult r = _storageDevice.BeginOpenContainer(_storageContainerName, null, null);
                result.AsyncWaitHandle.WaitOne();
                StorageContainer container = _storageDevice.EndOpenContainer(r);
                if (container.FileExists(filename))
                {
                    Stream stream = container.OpenFile(filename, FileMode.Open);
                    try
                    {
                        IFormatter formatter = new BinaryFormatter();
                        saveData = (GameSave)formatter.Deserialize(stream);
                        stream.Close();
                        container.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                        stream.Close();
                        container.Dispose();
                        container.DeleteFile(filename);
                    }
                }

                result.AsyncWaitHandle.Close();

                if (_loadCallback != null)
                    _loadCallback(_slot, saveData);
            }
        }
Example #32
0
    /**
     * LoadFromDisk()
     *  --> loads a GameSave from the Hard Disk if stand alone, from the playerPrefs if in WebPlayer
     * */
    public static void LoadFromDisk()
    {
        if(Application.isWebPlayer)
        {
            var serializer = new XmlSerializer(typeof(GameSave));
         	if(!PlayerPrefs.HasKey("save"))
                return;

            TextReader textReader = new StringReader(PlayerPrefs.GetString("save"));
            GameSave gamesave;
         	gamesave = (GameSave)serializer.Deserialize(textReader);
            if(gamesave == null)
            {
                Debug.Log ("Warning : deserialization fail");
                return;
            }
            last_save = gamesave;
        }
        else
        {
            GameSave gamesave = null;
            try
            {
                Stream s = System.IO.File.Open(m_FilePath,System.IO.FileMode.Open);
                if(s == null)
                    return;
                BinaryFormatter f = new BinaryFormatter();
                f.Binder = new VersionDeserializationBinder();

                gamesave = (GameSave)f.Deserialize(s);
                s.Close();
            }
            catch (IOException e)
            {
            }
            if (gamesave == null)
            {
                Debug.Log("Warning : deserialization fail");
                return;
            }
            last_save = gamesave;
        }
    }
Example #33
0
 internal static SavedStateIndex FromSave(GameSave gameSave, Tuple<int, uint> address)
 {
     SavedStateIndex savedStateIndex;
     if (!gameSave.TryGetFromBlockStructureCache(address, out savedStateIndex))
     {
         savedStateIndex = new SavedStateIndex(gameSave, address);
         gameSave.AddToBlockStructureCache(address, savedStateIndex);
     }
     return savedStateIndex;
 }
Example #34
0
 private void LoadSave(GameSave save)
 {
 }
Example #35
0
 private SavedStateIndex(GameSave gameSave, Tuple<int, uint> address)
     : base(gameSave, address)
 {
 }
Example #36
0
 private ByteArray(GameSave gameSave, Tuple<int, uint> address)
     : base(gameSave, address)
 {
 }
Example #37
0
 public bool IsSimilarForCloudSaving(GameSave other)
 {
     return(completedQuests.Count == other.completedQuests.Count && starCount == other.starCount && ticketsCount == other.ticketsCount);
 }
Example #38
0
 public void CmdLoadGame()
 {
     GameSave.LoadGame();
 }
Example #39
0
 internal static ChunkTable FromSave(GameSave gameSave, Tuple<int, uint> address)
 {
     ChunkTable chunkTable;
     if (!gameSave.TryGetFromBlockStructureCache(address, out chunkTable))
     {
         chunkTable = new ChunkTable(gameSave, address);
         gameSave.AddToBlockStructureCache(address, chunkTable);
     }
     return chunkTable;
 }
Example #40
0
 public void CmdSaveGame(bool backup)
 {
     GameSave.SaveGame(backup);
 }
Example #41
0
        public override void Paint(Level level)
        {
            if (LevelSave.BiomeGenerated is IceBiome)
            {
                var clip = Painter.Clip;
                Painter.Clip = null;
                Painter.Rect(level, this, 0, Tile.WallB);
                Painter.Clip = clip;
            }

            var scourged = Rnd.Chance(Run.Scourge + 1);

            if (Rnd.Chance(30))
            {
                var t = Tiles.Pick(Tile.FloorC, Tile.FloorD);

                if (Rnd.Chance())
                {
                    Painter.FillEllipse(level, this, 3, t);
                }
                else
                {
                    Painter.Fill(level, this, 3, t);
                }

                if (Rnd.Chance())
                {
                    t = Tiles.Pick(Tile.FloorC, Tile.FloorD);

                    if (Rnd.Chance())
                    {
                        Painter.FillEllipse(level, this, 4, t);
                    }
                    else
                    {
                        Painter.Fill(level, this, 4, t);
                    }
                }
            }

            if (Rnd.Chance())
            {
                if (Rnd.Chance())
                {
                    PaintTunnel(level, Tiles.RandomFloor(), GetCenterRect(), true);
                    PaintTunnel(level, Tiles.RandomNewFloor(), GetCenterRect());
                }
                else
                {
                    PaintTunnel(level, Tiles.RandomNewFloor(), GetCenterRect(), Rnd.Chance());
                }
            }

            if (GameSave.IsTrue("sk_enraged"))
            {
                var rp  = GetCenter();
                var rsk = new ShopKeeper();

                level.Area.Add(rsk);
                rsk.Center = new Vector2(rp.X * 16 + 8, rp.Y * 16 + 16);

                return;
            }

            var stands = ValidateStands(level, GenerateStands());

            if (stands.Count < 4)
            {
                Painter.Fill(level, this, 1, Tile.FloorD);
                Paint(level);
                return;
            }

            if (scourged)
            {
                var f = Tiles.RandomFloor();

                for (var m = Left + 1; m <= Right - 1; m++)
                {
                    for (var j = Top + 1; j <= Bottom - 1; j++)
                    {
                        var t = level.Get(m, j);

                        if (t.IsPassable() && t != f)
                        {
                            level.Set(m, j, Tile.EvilFloor);
                        }
                    }
                }
            }

            var pool           = Items.GeneratePool(Items.GetPool(Run.Type == RunType.BossRush ? ItemPool.BossRush : ItemPool.Shop));
            var consumablePool = Items.GeneratePool(Items.GetPool(ItemPool.ShopConsumable));

            var con = Math.Max(1, Math.Ceiling(stands.Count / 4f));
            var i   = 0;
            var g   = (Run.Depth == 5 && Run.Loop == 0 && LevelSave.GenerateMarket) ? Rnd.Int(stands.Count) : -1;

            foreach (var s in stands)
            {
                var stand = new ShopStand();
                level.Area.Add(stand);
                stand.Center = new Vector2(s.X * 16 + 8, s.Y * 16 + 8);

                var id   = g == i ? "bk:bucket" : Items.GenerateAndRemove(i < con && consumablePool.Count > 0 ? consumablePool : pool, null, true);
                var item = Items.CreateAndAdd(id, level.Area, false);

                if (scourged)
                {
                    item.Scourged = true;
                }

                stand.SetItem(item, null);

                if (pool.Count == 0)
                {
                    break;
                }

                i++;
            }

            var p  = stands[Rnd.Int(stands.Count)];
            var sk = new ShopKeeper();

            level.Area.Add(sk);
            sk.Center = new Vector2(p.X * 16 + 8, p.Y * 16 + 16);

            // Painter.DrawLine(level, new Dot(Left + 1, Top + 1), new Dot(Right - 1, Top + 1), Tiles.RandomFloor());

            var points = new List <Point>();

            for (var x = Left + 2; x < Right - 1; x++)
            {
                var found = false;

                foreach (var c in Connected.Values)
                {
                    if (c.X == x && c.Y == Top)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    points.Add(new Point(x, Top + 2));
                }
            }

            var props = new List <Entity> {
                new Gramophone()
            };

            if (Rnd.Chance(40 + Run.Luck * 7))
            {
                props.Add(new RerollMachine());
            }

            if (Rnd.Chance(40 + Run.Luck * 7))
            {
                props.Add(new VendingMachine());
            }

            foreach (var prop in props)
            {
                var pl = points[Rnd.Int(points.Count)];
                points.Remove(pl);

                level.Area.Add(prop);
                prop.CenterX = pl.X * 16 + 8 + Rnd.Int(-4, 4);
                prop.Bottom  = pl.Y * 16;

                if (points.Count == 0)
                {
                    break;
                }
            }

            var tt = Tiles.RandomFloor();

            Painter.Call(level, this, 1, (x, y) => {
                if (level.Get(x, y).Matches(Tile.SpikeOffTmp, Tile.SensingSpikeTmp, Tile.Chasm, Tile.Lava))
                {
                    level.Set(x, y, tt);
                }
            });

            var letters = new[] { 'a', 'b', 'c' };
            var spr     = $"mat_{letters[Rnd.Int(letters.Length)]}";

            foreach (var pair in Connected)
            {
                if (pair.Key is SubShopRoom)
                {
                    continue;
                }

                var door = pair.Value;
                var mat  = new SlicedProp(spr, Layers.Entrance);
                level.Area.Add(mat);

                if (door.X == Left)
                {
                    PlaceSign(level, new Vector2(door.X * 16 - 8, door.Y * 16 - 5));
                    mat.Center = new Vector2(door.X * 16 - 8, door.Y * 16 + 8);
                }
                else if (door.X == Right)
                {
                    PlaceSign(level, new Vector2(door.X * 16 + 24, door.Y * 16 - 5));
                    mat.Center = new Vector2(door.X * 16 + 24, door.Y * 16 + 8);
                }
                else if (door.Y == Top)
                {
                    mat.Center = new Vector2(door.X * 16 + 8, door.Y * 16 - 8);
                }
                else
                {
                    mat.Center = new Vector2(door.X * 16 + 8, door.Y * 16 + 24);
                }
            }
        }
Example #42
0
 void CmdPlayerEntered(GameObject obj, int table, int seat)
 {
     GameSave.PlayerEntered(obj, table, seat, false);
 }
Example #43
0
 internal static Chunk FromSave(GameSave gameSave, Tuple<int, uint> address)
 {
     Chunk chunk;
     if (!gameSave.TryGetFromBlockStructureCache(address, out chunk))
     {
         chunk = new Chunk(gameSave, address);
         gameSave.AddToBlockStructureCache(address, chunk);
     }
     return chunk;
 }
Example #44
0
 public void CmdSpawnAllNeurons(GameObject swapper)
 {
     GameSave.SpawnAllInstructorNeurons(swapper.GetComponent <SphereSwapper>());
 }
Example #45
0
    /**
     * SaveLastSave()
     *  --> overwrite the last GameSave allocated
     * */
    public static void SaveLastSave()
    {
        if(m_MustLoad)
            return;
        Debug.Log("SAVE");
        GameSave gamesave = new GameSave();

        WorldControllerScript worldController = null;
        GameObject worldControllerGo = GameObject.Find("GameWorld");
        if(worldControllerGo != null)
        {
            if((worldController = worldControllerGo.GetComponent<WorldControllerScript>()) != null)
                gamesave.world = worldController.GetCurrentWorldNumber();
        }

        GameObject[] gameObject = (GameObject[])GameObject.FindObjectsOfType(typeof(GameObject));
        int id = 1;
        foreach(GameObject go in gameObject)
        {
            Saveable savecomponent = null;
            if((savecomponent = go.GetComponent<Saveable>()) != null)
            {
                Save save = savecomponent.SaveTo();
                save.m_Id = id;
                gamesave.AddSave(save);
                id++;
            }
        }

        gamesave.level = Application.loadedLevel;
        if(last_save != null)
        {
            gamesave.time = last_save.time;
            gamesave.deathCount = last_save.deathCount;
            gamesave.score = last_save.score;
        }
        if(gamesave == null)
        {
            Debug.Log ("Warning : save fail");
            return;
        }
        last_save = gamesave;
    }
Example #46
0
 public ByteArray(GameSave gameSave, byte[] data)
     : base(gameSave)
 {
     _data = new byte[data.Length];
     data.CopyTo(_data, 0);
 }