Пример #1
0
        public void UpdateNetworkEvents()
        {
            void handleReceivedData(IRemote source, INetworkData data, ResponseHandler responseHandler)
            {
                if (!(source is IRemoteServer server))
                {
                    Log.Error.Write(ErrorSystemType.Network, "Client received data from a non-server.");
                    responseHandler?.Invoke(ResponseType.BadDestination);
                    return;
                }

                ProcessData(server, data, responseHandler);
            }

            NetworkDataReceiver?.ProcessReceivedData(handleReceivedData);

            if (Game != null && client != null && client.Connected)
            {
                lock (Game)
                {
                    var gameTime = Game.GameTime;

                    // Save game state from time to time to avoid huge syncs.
                    if (gameTime - lastSavedGameStateGameTime >= SavedGameState.SyncDelay && SavedGameState.TimeToSync(Game))
                    {
                        Log.Verbose.Write(ErrorSystemType.Network, $"Saving game state with game time {Misc.SecondsToTime(gameTime)}.");

                        lastSavedGameStateGameTime = gameTime;
                        lastSavedGameStates.Add(gameTime, SavedGameState.FromGame(Game));

                        Log.Verbose.Write(ErrorSystemType.Network, $"Finished saving game state with game time {Misc.SecondsToTime(gameTime)}.");
                    }
                }
            }
        }
Пример #2
0
    public void Save(string basePath, string currentSaveDir)
    {
        if (GameState == null)
        {
            throw new CorruptSaveException("Missing GameState.");
        }

        if (UiState == null)
        {
            throw new CorruptSaveException("Missing UiState.");
        }

        var serializedGameState = SavedGameState.Save(GameState, Co8State != null);

        var serializedUiState = SavedUiState.Save(UiState, Co8State != null);

        // Write the files to the current save directory so they are added to the save archive afterwards
        WriteStateToDirectory(serializedGameState, serializedUiState, currentSaveDir);

        try
        {
            ArchiveWriter.Compress(basePath + ".tfai", basePath + ".tfaf", currentSaveDir);
        }
        finally
        {
            DeleteStateFromDirectory(currentSaveDir);
        }
    }
        private NinthPlanetGameState ToStoredState(DbGameInfo gameInfo, SavedGameState state)
        {
            var playerStates = state.PlayersInLobby
                               .Select(x => new NinthPlanetPlayerState {
                PlayerId = x
            })
                               .ToList();

            var dbGameState = new NinthPlanetGameState
            {
                GameInfo          = gameInfo,
                RoundIsInProgress = state.RoundState != null,
                PlayerStates      = playerStates,
            };

            if (state.RoundState != null)
            {
                foreach (var playerState in state.RoundState.PlayerStates)
                {
                    var storedState = playerStates.First(x => x.PlayerId == playerState.Key);
                    storedState.PlayOrder = state.RoundState.PlayerOrder.IndexOf(playerState.Key);

                    storedState.FinishedTasks              = playerState.Value.FinishedTasks;
                    storedState.UnfinishedTasks            = playerState.Value.UnfinishedTasks;
                    storedState.CardsInHand                = playerState.Value.CardsInHand;
                    storedState.ComunicatedCardColor       = playerState.Value.DisplayedCard.Color;
                    storedState.ComunicatedCardValue       = playerState.Value.DisplayedCard.Value;
                    storedState.CommunicationTokenPosition = playerState.Value.DisplayedCardTokenPosition;
                }
            }

            return(dbGameState);
        }
 /// <summary>
 /// Called from Copy's OnClick
 /// </summary>
 public void EnterSavedGamesCopyView()
 {
     State = SavedGameState.Copy;
     savedGameController.InitializeState();
     EnterSavedGamesSelectView();
     ActivateViewState();
 }
    /// <summary>
    /// Called from SavedGameTitle's OnClick in COPY STATE
    /// </summary>
    public void HandleEnterPasteView(Script_SavedGameTitle savedGame)
    {
        int slotId = savedGame.GetComponent <Script_Slot>().Id;

        if (savedGame.isRendered)
        {
            copiedSlotId = slotId;
            State        = SavedGameState.Paste;

            // initialize with next open slot
            int         nextOpenSlotId = slotId + 1;
            Transform[] slots          = savedGameController.GetSlots();
            for (int j = 0; j < slots.Length - 1; nextOpenSlotId++, j++)
            {
                if (nextOpenSlotId >= slots.Length)
                {
                    nextOpenSlotId = 0;
                }
                if (!slots[nextOpenSlotId].GetComponent <Script_SavedGameTitle>().isRendered)
                {
                    break;
                }
            }

            savedGameController.InitializeState(nextOpenSlotId);
            EnterSavedGamesSelectView();
            ActivateViewState();
        }
        else
        {
            ErrorSFX();
        }
    }
 public void SaveGame(SavedGameState savedGameState)
 {
     savedGameState.SecretDoorState = new SavedSecretDoorState
     {
         SeenSceneryNames = new List <int>(_nameListSeen)
     };
 }
Пример #7
0
        private void MainWindow_FormClosing(Object sender, FormClosingEventArgs e)
        {
            //DataBaseWriter dataBaseWrite = new DataBaseWriter();
            this.mapper         = new BoardDataMapper();
            this.savedGameState = new SavedGameState
            {
                BoardSize        = this.matrixAlgorithm.BoardSize,
                CurrentTurn      = this.matrixAlgorithm.CurrentTurn,
                CurrentTurnCount = this.matrixAlgorithm.CurrentTurnCount,
                BoardData        = this.mapper.WriteCurrentBoardToString(this.matrixAlgorithm),
            };
            Data data = new Data
            {
                CurrentGame = this.savedGameState,
                Round       = this.settings.RoundCount,
                HistoryList = this.settings.HistoryList,
                Difficulty  = this.ChooseDifficulty()
            };
            HistoryData historyData = new HistoryData
            {
                HistoryList = this.settings.HistoryList,
            };

            dataBaseWriter.WriteDatabaseFile(historyData);
            this.serialize = (ISerializeData)SerDesFactory.Create(typeof(ISerializeData));
            this.serialize.SerializeJson(Application.StartupPath + "/settings/autosave.json", data);
            this.serialize.SerializeXml(Application.StartupPath + "/settings/autosave.xml", data);
        }
    public void LoadGame(SavedGameState savedGameState)
    {
        var savedFormationState = savedGameState.FormationState;

        _formationPositions = savedFormationState.Positions.Select(t => t.ToArray()).ToArray();
        _formationSelected  = savedFormationState.FormationSelected;
    }
 public void SaveGame(SavedGameState savedGameState)
 {
     savedGameState.FormationState = new SavedFormationState
     {
         FormationSelected = _formationSelected,
         Positions         = _formationPositions.Select(t => t.ToArray()).ToArray()
     };
 }
 public void LoadGame(SavedGameState savedGameState)
 {
     foreach (var savedSpawner in savedGameState.MonsterGenState.Spawners)
     {
         _globalSpawnerState[savedSpawner.Id].IsDisabled       = savedSpawner.IsDisabled;
         _globalSpawnerState[savedSpawner.Id].CurrentlySpawned = savedSpawner.CurrentlySpawned;
     }
 }
Пример #11
0
    public void LoadGame(SavedGameState savedGameState)
    {
        var areaState = savedGameState.AreaState;

        _areaLastDiscovered = areaState.AreaDiscoveredLast;
        for (var i = 0; i < _areas.Length; i++)
        {
            _areas[i].Known = areaState.DiscoveredAreas.Contains(i);
        }
    }
        private Games.NinthPlanet StartGameFromState(NinthPlanetGameState dbGameState)
        {
            SavedGameState gameState = ToGameState(dbGameState);

            var gameServer = gameServerFactory.CreateGameFromState(gameState);
            var game       = new Games.NinthPlanet(gameServer);

            this.gameCache.TryAddGame(dbGameState.GameId, game);
            return(game);
        }
    public void InitializeSavedGamesState()
    {
        State = SavedGameState.Start;

        EnterSavedGamesSelectView();

        deleteBanner.gameObject.SetActive(false);
        copyBanner.gameObject.SetActive(false);
        pasteBanner.gameObject.SetActive(false);
    }
Пример #14
0
        public Data ReadIni(String fileName)
        {
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentOutOfRangeException(nameof(fileName), "file name may not be empty, null or whitespace");
            }

            this.MatrixAlgorithm = (IMatrixAlgorithm)GlobalFactory.Create(typeof(IMatrixAlgorithm));
            FileIniDataParser parser         = new FileIniDataParser();
            IniData           iniData        = parser.ReadFile(fileName);
            SavedGameState    savedGameState = new SavedGameState
            {
                BoardSize        = this.MatrixAlgorithm.BoardSize,
                CurrentTurn      = this.MatrixAlgorithm.CurrentTurn,
                CurrentTurnCount = this.MatrixAlgorithm.CurrentTurnCount,
            };
            Data data = new Data
            {
                CurrentGame = savedGameState,
                HistoryList = new List <History>()
            };

            data.CurrentGame.CurrentTurnCount = Convert.ToInt32(iniData["CurrentGame"]["CurrentTurnCount"]);
            data.CurrentGame.BoardSize        = Convert.ToInt32(iniData["CurrentGame"]["BoardSize"]);
            data.Round      = Convert.ToInt32(iniData["Settings"]["Difficutly"]);
            data.Difficulty = (Difficulty)Enum.Parse(typeof(Difficulty), iniData["Settings"]["Difficulty"]);
            Int32 sectionIndex = 0;

            using (StreamReader sr = File.OpenText(fileName))
            {
                foreach (SectionData section in iniData.Sections)
                {
                    sectionIndex++;
                }
            }

            for (Int32 i = 0; i < sectionIndex - 2; i++)
            {
                History history = new History
                {
                    Winner     = iniData[$"HistoryList-{i}"]["Winner"],
                    RoundCount = Convert.ToInt32(iniData[$"HistoryList-{i}"]["RoundCount"])
                };
                data.HistoryList.Add(history);
            }

            String key   = $"Board";
            String value = iniData["CurrentGame"][key];

            data.CurrentGame.BoardData = value;

            return(data);
        }
Пример #15
0
 public void SaveGame(SavedGameState savedGameState)
 {
     savedGameState.AreaState = new SavedAreaState
     {
         AreaDiscoveredLast = _areaLastDiscovered
     };
     for (var i = 0; i < _areas.Length; i++)
     {
         if (_areas[i].Known)
         {
             savedGameState.AreaState.DiscoveredAreas.Add(i);
         }
     }
 }
Пример #16
0
 /*
  * isNew : true if starting new game else false
  * sav: null if isNew else comes from SaveState.load()
  */
 private void startGame(bool isNew, SavedGameState sav)
 {
     print("Starting Game");
     //Tell Unity not to destroy this instance when we load up a new scene
     DontDestroyOnLoad(gameManager.Instance);
     if (isNew)
     {
         //Calling a method in our state manager to start a new game
         gameManager.Instance.startState();
     }
     else
     {
         gameManager.Instance.setState(sav);
     }
 }
Пример #17
0
        private void RecoverData(Data data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            this.boardSizeTrackBar.Value = data.CurrentGame.BoardSize;
            this.settings.HistoryList    = data.HistoryList;
            this.dataGrid.DataSource     = this.settings.HistoryList;
            this.RecoverDifficulty(data);
            this.UpdateScrollBar();
            this.RestartGame();
            this.savedGameState      = data.CurrentGame;
            this.settings.RoundCount = data.Round;
            this.RecoverBoard(data.Difficulty);
        }
    public void DeleteGame(int i)
    {
        Script_SaveGameControl.saveSlotId = i;

        if (Script_SaveGameControl.Delete())
        {
            // update that slot
            savedGameController
            .GetSlotTransform(i)
            .GetComponent <Script_SavedGameTitle>()
            .InitializeState();
        }

        // end delete mode
        State = SavedGameState.Start;
        EnterSavedGamesSelectView();
    }
        private SavedGameState ToGameState(NinthPlanetGameState dbGameState)
        {
            var gameState = new SavedGameState
            {
                GameInfo       = dbGameState.GameInfo,
                PlayersInLobby = dbGameState.PlayerStates.Select(x => x.PlayerId).ToList(),
            };

            if (dbGameState.RoundIsInProgress)
            {
                var playerOrder = dbGameState.PlayerStates
                                  .Where(x => x.PlayOrder.HasValue)
                                  .OrderBy(x => x.PlayOrder.Value)
                                  .Select(x => x.PlayerId)
                                  .ToList();

                var playerStates = dbGameState.PlayerStates
                                   .Where(x => x.PlayOrder.HasValue)
                                   .ToDictionary(
                    x => x.PlayerId,
                    x => new PlayerPrivateState
                {
                    CardsInHand   = x.CardsInHand,
                    DisplayedCard = x.ComunicatedCardValue.HasValue ? new Card
                    {
                        Value = x.ComunicatedCardValue.Value,
                        Color = x.ComunicatedCardColor.Value
                    } : null,
                    DisplayedCardTokenPosition = x.CommunicationTokenPosition,
                    UnfinishedTasks            = x.UnfinishedTasks,
                    FinishedTasks = x.FinishedTasks,
                });

                gameState.RoundState = new SavedRoundState
                {
                    PlayerOrder         = playerOrder,
                    CurrentPlayerId     = dbGameState.CurrentPlayerId,
                    CaptainPlayerId     = dbGameState.CaptainPlayerId,
                    ColorOfCurrentTrick = dbGameState.ColorOfCurrentTrick,
                    PlayerStates        = playerStates,
                };
            }

            return(gameState);
        }
Пример #20
0
    public static void save(string saveFile)
    {
        if(!Directory.Exists(savePath)) {
            Directory.CreateDirectory(savePath);
        }
        SavedGameState sav = new SavedGameState();
        FileStream fs = new FileStream(savePath+saveFile, FileMode.Create);

        try {
            binaryFormatter.Serialize(fs, sav);
        }
        catch (SerializationException ex) {
            throw new ApplicationException("The object graph could not be serialized", ex);
        }
        finally {
            fs.Close();
        }
    }
Пример #21
0
    public static void save(string saveFile)
    {
        if (!Directory.Exists(savePath))
        {
            Directory.CreateDirectory(savePath);
        }
        SavedGameState sav = new SavedGameState();
        FileStream     fs  = new FileStream(savePath + saveFile, FileMode.Create);

        try {
            binaryFormatter.Serialize(fs, sav);
        }
        catch (SerializationException ex) {
            throw new ApplicationException("The object graph could not be serialized", ex);
        }
        finally {
            fs.Close();
        }
    }
    public void CopyGame(int targetSlotId)
    {
        Debug.Log("Trying to Copy");

        Script_SaveGameControl.saveSlotId = copiedSlotId;

        if (Script_SaveGameControl.Copy(copiedSlotId, targetSlotId))
        {
            // update that slot
            savedGameController
            .GetSlotTransform(targetSlotId)
            .GetComponent <Script_SavedGameTitle>()
            .InitializeState();
        }

        // end copy mode
        State = SavedGameState.Start;
        EnterSavedGamesSelectView();
    }
Пример #23
0
        public NinthPlanetServer CreateGameFromState(SavedGameState gameState)
        {
            var gameInfo = gameState.GameInfo;

            if (gameInfo is null)
            {
                throw new ArgumentException("Game info is empty.", nameof(gameState));
            }

            if (gameInfo.GameType != GameType.NinthPlanet)
            {
                throw new ArgumentException($"Expected game type to be {GameType.NinthPlanet} but {gameInfo.GameType} was found.", nameof(gameState));
            }

            if (loggerFactory is null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            var gameLobby = new GameLobby(
                gameInfo.Id,
                gameInfo.MaximumNumberOfPlayers,
                gameState.PlayersInLobby,
                loggerFactory.CreateLogger <GameLobby>());

            gameLobby.AddPlayer(gameInfo.OwnerId);

            GameRound gameRound = null;

            if (gameState.RoundState != null)
            {
                gameRound = gameRoundFactory.CreateGameRound(gameInfo, null);
            }

            return(new NinthPlanetServer(
                       gameInfo,
                       gameLobby,
                       gameRound,
                       gameRoundFactory,
                       loggerFactory.CreateLogger <NinthPlanetServer>()));
        }
Пример #24
0
    // Start from saved game
    public void setState(SavedGameState save)
    {
        this.money               = save.money;
        this.funding             = save.funding;
        this.time                = save.time;
        this.pendingRequests     = save.pendingRequests;
        this.currentBase         = save.currentBase;
        this.availableId         = save.availableId;
        this.availableWeapons    = save.availableWeapons;
        this.unresearchedWeapons = save.unresearchedWeapons;
        this.nameList            = save.nameList;
        this.random              = new System.Random();
        this.bases               = save.bases;

        missionsSuccess = save.missionsSuccess;
        missionsFailed  = save.missionsFailed;
        CiviliansKilled = save.CiviliansKilled;
        CiviliansSaved  = save.CiviliansSaved;

        setLevel("WorldMap");
    }
    public void SaveGame(SavedGameState savedGameState)
    {
        var savedSpawners = new List <SavedSpawnerState>();

        for (var i = 0; i < _globalSpawnerState.Length; i++)
        {
            var globalSpawnerState = _globalSpawnerState[i];
            if (globalSpawnerState.IsDisabled || globalSpawnerState.CurrentlySpawned > 0)
            {
                savedSpawners.Add(new SavedSpawnerState
                {
                    Id               = i,
                    IsDisabled       = globalSpawnerState.IsDisabled,
                    CurrentlySpawned = globalSpawnerState.CurrentlySpawned
                });
            }
        }

        savedGameState.MonsterGenState = new SavedMonsterGenState
        {
            Spawners = savedSpawners
        };
    }
Пример #26
0
        public void BeginNewRound()
        {
            var rng     = TestContext.CurrentContext.Random;
            var players = new List <int>();

            for (int i = 0; i < 5; ++i)
            {
                players.Add(rng.Next(1, 1000));
            }

            var gameOwner = players[0];

            var gameInfo = CreateGameInfo(gameOwnerId: gameOwner);

            var savedState = new SavedGameState
            {
                GameInfo       = gameInfo,
                PlayersInLobby = players,
                RoundState     = null,
            };

            var game          = this.GameFactory.CreateGameFromState(savedState);
            var gameMessanger = NSubstitute.Substitute.For <IGameMessenger>();

            game.BeginRound(gameOwner, gameMessanger);

            savedState = game.SaveCurrentState();

            var roundState = savedState.RoundState;

            Assert.NotNull(roundState);

            Assert.Null(roundState.ColorOfCurrentTrick);
            Assert.Contains(roundState.CaptainPlayerId, players);
            Assert.True(players.TrueForAll(x => roundState.PlayerOrder.Contains(x)));
            Assert.True(players.TrueForAll(x => roundState.PlayerStates.ContainsKey(x)));
        }
Пример #27
0
    // Start from saved game
    public void setState(SavedGameState save)
    {
        this.money = save.money;
        this.funding = save.funding;
        this.time = save.time;
        this.pendingRequests = save.pendingRequests;
        this.currentBase = save.currentBase;
        this.availableId = save.availableId;
        this.availableWeapons = save.availableWeapons;
        this.unresearchedWeapons = save.unresearchedWeapons;
        this.nameList = save.nameList;
        this.random = new System.Random();
        this.bases = save.bases;

        missionsSuccess = save.missionsSuccess;
        missionsFailed = save.missionsFailed;
        CiviliansKilled = save.CiviliansKilled;
        CiviliansSaved = save.CiviliansSaved;

        setLevel("WorldMap");
    }
 public void LoadGame(SavedGameState savedGameState)
 {
     _nameListSeen.Clear();
     _nameListSeen.AddRange(savedGameState.SecretDoorState.SeenSceneryNames);
 }
Пример #29
0
    //Function holding all the GUI interfaces
    void OnGUI()
    {
        //The followings represent the different menuds, encapsulated by an if-statement checking which menu is to be shown
        //Main Menu
        GUI.skin = menuSkin;
        if (showMain)
        {
            GUI.DrawTexture(new Rect(Screen.width - 420, Screen.height - 120, 400, 100), XCOMLogo);

            GUI.Box(new Rect(Screen.width * 2 / 3, Screen.height / 5, Screen.width / 4 * 0.95f, Screen.height * 3 / 5), "");
            GUI.skin = menuSkin;
            if (GUI.Button(new Rect(Screen.width * 2 / 3 + (Screen.width / 3 * 0.05f), Screen.height / 5 + (Screen.height * 3 / 5 * 0.15f), Screen.width / 4 * 0.85f, Screen.height / 15), "Singleplayer Campain"))
            {
                showMain   = false;
                showSingle = true;
            }
            if (GUI.Button(new Rect(Screen.width * 2 / 3 + (Screen.width / 3 * 0.05f), Screen.height / 5 + (Screen.height * 3 / 5 * 0.3f), Screen.width / 4 * 0.85f, Screen.height / 15), "Multiplayer"))
            {
                showMain        = false;
                showMultiplayer = true;
            }
            if (GUI.Button(new Rect(Screen.width * 2 / 3 + (Screen.width / 3 * 0.05f), Screen.height / 5 + (Screen.height * 3 / 5 * 0.65f), Screen.width / 4 * 0.85f, Screen.height / 15), "Credits"))
            {
                showMain    = false;
                showCredits = true;
            }
            if (GUI.Button(new Rect(Screen.width * 2 / 3 + (Screen.width / 3 * 0.05f), Screen.height / 5 + (Screen.height * 3 / 5 * 0.8f), Screen.width / 4 * 0.85f, Screen.height / 15), "Quit Game"))
            {
                Application.Quit();
                print("Currently quitting the game");
            }
            GUI.skin = null;
        }
        //Singleplayer menu
        if (showSingle)
        {
            // Left side
            GUI.Box(new Rect(Screen.width * 0.05f, Screen.height * 0.15f, Screen.width * 0.25f, Screen.height * 0.7f), "");
            if (GUI.Button(new Rect(Screen.width * 0.075f, Screen.height * 0.15f + (Screen.height * 0.7f / 10), Screen.width * 0.2f, (Screen.height * 0.7f / 5)), "Start new Campain"))
            {
                //Call game manager to create a new instance of game manager, and incidently start the game
                startGame(true, null);
                print("Attempting to create new game");
            }
            if (GUI.Button(new Rect(Screen.width * 0.075f, Screen.height * 0.15f + (4 * Screen.height * 0.7f / 10), Screen.width * 0.2f, (Screen.height * 0.7f / 5)), "Load existing game"))
            {
                //Load a past saved game
                showLoad = true;
                //SavedGameState save = SaveState.load();
                //startGame(false, save);
            }
            if (GUI.Button(new Rect(Screen.width * 0.075f, Screen.height * 0.15f + (7 * Screen.height * 0.7f / 10), Screen.width * 0.2f, (Screen.height * 0.7f / 5)), "Back"))
            {
                showSingle = false;
                showLoad   = false;
                showMain   = true;
            }

            // Right side
            GUIStyle titleLabelStyle = new GUIStyle(GUI.skin.GetStyle("label"));
            titleLabelStyle.alignment = TextAnchor.MiddleCenter;
            titleLabelStyle.fontSize  = 30;

            GUILayout.BeginArea(new Rect(Screen.width * 2 / 3, Screen.height * 0.1f, Screen.width / 3 * 0.95f, Screen.height * 0.8f), GUI.skin.box);
            GUILayout.BeginVertical();
            scrollPosition = GUILayout.BeginScrollView(scrollPosition);
            GUILayout.Label("X-COM Origin:", titleLabelStyle);
            GUILayout.Space(20);
            int year = System.DateTime.Now.Year;
            GUILayout.Label("It is the year " + year + ". Unidentified Flying Objects (UFOs) have started appearing with disturbing regularity in the night skies. Reports of violent human abductions and horrific experimentation has struck terror into the hearts of millions. Mass public hysteria has only served to expose Earth's impotence against a vastly superior technology.Many countries have attempted to deal independently with the aliens. \n\nIn August " + (year - 1) + ", Japan established an anti-alien combat force; the Kiryu-Kai. Equipped with Japanese-made fighter aircraft, the Kiryu-Kai certainly looked like a powerful force. However, after 5 months of expensive operations they had yet to intercept their first UFO. The lesson was clear: this was a worldwide problem which could not be dealt with by individual countries.\n\nOn December 11, " + (year - 1) + ", representatives from the world's most economically powerful countries gathered secretly in Geneva. After much debate, the decision was made to establish a covert independent body to combat, investigate and defeat the alien threat. This organization would be equipped with the world's finest pilots, soldiers, scientists and engineers, working together as one multi-national force.");
            GUILayout.EndScrollView();
            GUILayout.EndVertical();
            GUILayout.EndArea();
        }

        if (showCredits)
        {
            GUILayout.BeginArea(new Rect(Screen.width * 2 / 3, Screen.height * 0.1f, Screen.width / 3 * 0.95f, Screen.height * 0.8f), GUI.skin.box);
            GUILayout.BeginVertical();

            GUIStyle titleLabelStyle = new GUIStyle(GUI.skin.GetStyle("label"));
            titleLabelStyle.alignment = TextAnchor.MiddleCenter;
            titleLabelStyle.fontSize  = 30;

            float colWidth = Screen.width / 3 * 0.95f / 2;
            GUILayout.Space(15);
            GUILayout.Label("Credits", titleLabelStyle);
            GUILayout.Space(15);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Development Team", GUILayout.Width(colWidth));
            GUILayout.BeginVertical();
            GUILayout.Label("Jeremie Bedard", GUILayout.Width(colWidth));
            GUILayout.Label("Jake Shamash", GUILayout.Width(colWidth));
            GUILayout.Label("Jonathan Fokkan", GUILayout.Width(colWidth));
            GUILayout.Label("Christina Tran", GUILayout.Width(colWidth));
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();

            GUILayout.Space(15);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Original music", GUILayout.Width(colWidth));
            GUILayout.Label("Costa Damoulianos", GUILayout.Width(colWidth));
            GUILayout.EndHorizontal();

            GUILayout.FlexibleSpace();
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Back", GUILayout.Width(70), GUILayout.Height(50)))
            {
                showCredits = false;
                showMain    = true;
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.Space(15);
            GUILayout.EndVertical();
            GUILayout.EndArea();
        }

        if (showLoad)
        {
            GUI.Box(new Rect(Screen.width * 0.05f + Screen.width * 0.25f, Screen.height * 0.15f, Screen.width * 0.25f, Screen.height * 0.7f), "Load A Previous Game");

            /*
             * FileInfo[] savePaths = DirectoryInfo.GetFiles(SaveState.savePath, "*.save");
             * string[] saveFiles;
             * if(savePaths.Length == 0){
             *      GUI.Label(new Rect(Screen.width*0.05f+Screen.width*0.25f+Screen.width*0.25f,Screen.height*0.15f+20,Screen.width*0.25f,Screen.height*0.7f),"No Save File");
             * } else {
             *      saveFiles = new string[savePaths.Length];
             *      for(int i = 0; i < savePaths.Length; i++){
             *              saveFiles[i] = Path.GetFileName(savePaths[i]);
             *      }
             * }
             * float buttonHeight = Screen.height*0.15f+(7*Screen.height*0.7f/10);
             * foreach(string iS in saveFiles){
             *      if(GUI.Button(new Rect(Screen.width*0.075f,buttonHeight,Screen.width*0.2f,(Screen.height*0.7f/5)), iS)) {
             *              SavedGameState save = SaveState.load(iS);
             *              startGame(false, save);
             *      }
             *      buttonHeight += (Screen.height*0.7f/5);
             * }
             */
            float buttonHeight = Screen.height * 0.15f + (Screen.height * 0.7f / 10);
            float buttonleft   = Screen.width * 0.05f + Screen.width * 0.25f + Screen.width * 0.05f / 2;
            if (GUI.Button(new Rect(buttonleft, buttonHeight, Screen.width * 0.2f, (Screen.height * 0.7f / 5)), "Load File 1"))
            {
                SavedGameState save = SaveState.load("xcomsavefile1.save");
                startGame(false, save);
            }
            buttonHeight += (Screen.height * 0.9f / 5);
            if (GUI.Button(new Rect(buttonleft, buttonHeight, Screen.width * 0.2f, (Screen.height * 0.7f / 5)), "Load File 2"))
            {
                SavedGameState save = SaveState.load("xcomsavefile2.save");
                startGame(false, save);
            }
            buttonHeight += (Screen.height * 0.9f / 5);
            if (GUI.Button(new Rect(buttonleft, buttonHeight, Screen.width * 0.2f, (Screen.height * 0.7f / 5)), "Load File 3"))
            {
                SavedGameState save = SaveState.load("xcomsavefile3.save");
                startGame(false, save);
            }
        }


        //Multiplayer Menu
        if (showMultiplayer)
        {
            // ag = available games, gd = game description
            float left         = Screen.width / 2 + Screen.width / 2 * 0.05f;
            float agTop        = Screen.height * 0.10f;
            float boxWidth     = Screen.width / 2 * 0.85f;
            float agHeight     = Screen.height * 0.45f;
            float margin       = 30;
            float gdHeight     = Screen.height - 2 * agTop - agHeight - margin;
            float buttonWidth  = 100;
            float buttonHeight = 50;
            float contentWidth = 250;

            GUILayout.BeginArea(new Rect(left, agTop, boxWidth, agHeight), GUI.skin.box);
            GUILayout.BeginVertical();

            GUILayout.Label("Available Games");


            scrollPosition = GUILayout.BeginScrollView(scrollPosition);
            if (hostData == null || hostData.Length <= 0)
            {
                GUILayout.Label("No active hosts");
            }
            else
            {
                // Copy game names to string array
                string[] names = new string[hostData.Length];
                for (int i = 0; i < hostData.Length; i++)
                {
                    names[i] = hostData[i].gameName;
                }

                // Selection grid showing game names
                GUILayout.FlexibleSpace();
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                gameSelected = GUILayout.SelectionGrid(gameSelected, names, 1, GUILayout.MinWidth(contentWidth), GUILayout.ExpandWidth(false));
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
                GUILayout.FlexibleSpace();
            }
            GUILayout.EndScrollView();

            // Refresh button
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Refresh", GUILayout.Width(buttonWidth), GUILayout.Height(buttonHeight)))
            {
                //Refresh available game instances
                refreshHostList();
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();
            GUILayout.EndArea();


            GUILayout.BeginArea(new Rect(left, agTop + agHeight + margin, boxWidth, gdHeight), GUI.skin.box);
            GUILayout.BeginVertical();

            if (gameSelected < 0 || hostData == null || hostData.Length <= 0)
            {
                GUILayout.Label("Select a game");
            }
            else if (hostData[gameSelected].connectedPlayers >= 2)
            {
                GUILayout.Label("This game is full");
            }
            else
            {
                GUILayout.Label(hostData[gameSelected].gameName);
                GUILayout.FlexibleSpace();
                if (hostData[gameSelected].comment == "0")
                {
                    GUILayout.Label("Your side: Soldiers");
                }
                else if (hostData[gameSelected].comment == "1")
                {
                    GUILayout.Label("Your side: Aliens");
                }
                else
                {
                    Debug.Log("Got a weird comment: " + hostData[gameSelected].comment);
                }
                GUILayout.FlexibleSpace();

                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Join", GUILayout.Width(buttonWidth), GUILayout.Height(buttonHeight)))
                {
                    Debug.Log("Start game " + hostData[gameSelected].gameName);
                    showMultiplayer = false;
                    Network.Connect(hostData[gameSelected]);
                }
                GUILayout.Space(5);
                GUILayout.Label(joinGameMessage);
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
            }

            GUILayout.EndVertical();
            GUILayout.EndArea();


            // Left panel
            GUI.Box(new Rect(Screen.width * 0.05f, Screen.height * 0.15f, Screen.width * 0.25f, Screen.height * 0.7f), "");
            if (GUI.Button(new Rect(Screen.width * 0.075f, Screen.height * 0.15f + (Screen.height * 0.7f / 10), Screen.width * 0.2f, (Screen.height * 0.7f / 5)), "Create game"))
            {
                //Create a multiplayer instance
                showMultiplayer = false;
                showCreateGame  = true;
                print("Creating new game");
            }
            if (GUI.Button(new Rect(Screen.width * 0.075f, Screen.height * 0.15f + (7 * Screen.height * 0.7f / 10), Screen.width * 0.2f, (Screen.height * 0.7f / 5)), "Back"))
            {
                // Go back
                showMultiplayer = false;
                showMain        = true;
            }
        }


        //Create Game menu (Multiplayer)
        if (showCreateGame)
        {
            float buttonWidth  = 100;
            float buttonHeight = 50;

            GUILayout.BeginArea(new Rect(Screen.width / 2, Screen.height * 0.05f, Screen.width / 2 * 0.95f, Screen.height * 0.9f), GUI.skin.box);
            GUILayout.BeginVertical();

            GUILayout.FlexibleSpace();

            GUILayout.Label("Host a game");

            GUILayout.FlexibleSpace();

            //Text field for writing name of the game
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Label("Game name: ");
            GUILayout.Space(100);
            gameName = GUILayout.TextField(gameName, 50, GUILayout.MinWidth(200));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.FlexibleSpace();
            //GUILayout.Space(vSpace);

            // Toolbar for selecting game type
            GUILayout.Label("Pick your side: ");
            GUILayout.Space(10);
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            sideSelected = GUILayout.Toolbar(sideSelected, new string[] { "Aliens", "Soldiers" }, GUILayout.Height(50), GUILayout.Width(200));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.FlexibleSpace();
            //GUILayout.Space(vSpace);

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Back", GUILayout.Width(buttonWidth), GUILayout.Height(buttonHeight)))
            {
                //Get back to Multiplayer menu
                createGameMessage = "";
                showCreateGame    = false;
                showMultiplayer   = true;
            }
            GUILayout.Space(60);
            if (GUILayout.Button("Create", GUILayout.Width(buttonWidth), GUILayout.Height(buttonHeight)))
            {
                //Create new game instance.  Make certain all fields are used
                if (gameName == "")
                {
                    //Print message saying information are missing
                    createGameMessage = "ERROR: Enter name";
                }
                else if (sideSelected < 0)
                {
                    createGameMessage = "ERROR: Pick a side";
                }
                else
                {
                    //All conditions are met to create a new game instance, create game instance
                    createGameMessage = "";
                    startServer(gameName);
                }
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.Space(10);
            GUILayout.Label(createGameMessage);
            GUILayout.FlexibleSpace();

            GUILayout.EndVertical();
            GUILayout.EndArea();

            //GUI.skin=null;
        }
        if (waitForPlayer)
        {
            showCreateGame = false;
            Rect windowRect = new Rect(
                Screen.width / 2 - Screen.width / 6,
                Screen.height / 2 - Screen.height / 6,
                Screen.width / 3,
                Screen.height / 3
                );
            GUI.Window(0, windowRect, waitWindow, "");
        }
    }
Пример #30
0
    public static SaveGameFile Load(string basePath, string currentSaveDir)
    {
        var result = new SaveGameFile();

        var indexPath = basePath + ".tfai";

        var archiveIndex = ArchiveIndexReader.ReadIndex(indexPath);

        using var dataStream = new FileStream(basePath + ".tfaf", FileMode.Open);

        byte[] gameStateData   = null;
        byte[] spellPacketData = null;
        byte[] partyConfigData = null;
        byte[] mapFleeData     = null;
        byte[] uiStateData     = null;

        bool GrabData(ArchiveIndexEntry entry, string filename, ref byte[] bufferOut)
        {
            if (entry.Path == filename)
            {
                if (bufferOut != null)
                {
                    throw new CorruptSaveException($"File {filename} exists twice in the save game!");
                }

                var buffer = new byte[entry.Size];
                dataStream.Read(buffer);
                if (Debugger.IsAttached)
                {
                    var fullPath = Path.Join(currentSaveDir, entry.Path);
                    File.WriteAllBytes(fullPath, buffer);
                }

                bufferOut = buffer;
                return(true);
            }

            return(false);
        }

        foreach (var entry in archiveIndex)
        {
            var fullPath = Path.Join(currentSaveDir, entry.Path);

            if (entry.Directory)
            {
                Directory.CreateDirectory(fullPath);
                continue;
            }

            if (GrabData(entry, MainStateFile, ref gameStateData) ||
                GrabData(entry, ActionSequencesSpellsFile, ref spellPacketData) ||
                GrabData(entry, PartyConfigFile, ref partyConfigData) ||
                GrabData(entry, MapFleeFile, ref mapFleeData) ||
                GrabData(entry, UiStateFile, ref uiStateData))
            {
                continue;
            }

            CopyStreamToFile(dataStream, entry.Size, fullPath);
        }

        if (gameStateData == null)
        {
            throw new CorruptSaveException($"Save file is missing {MainStateFile}");
        }

        if (spellPacketData == null)
        {
            throw new CorruptSaveException($"Save file is missing {ActionSequencesSpellsFile}");
        }

        if (partyConfigData == null)
        {
            throw new CorruptSaveException($"Save file is missing {PartyConfigFile}");
        }

        if (mapFleeData == null)
        {
            throw new CorruptSaveException($"Save file is missing {MapFleeFile}");
        }

        if (uiStateData == null)
        {
            throw new CorruptSaveException($"Save file is missing {UiStateFile}");
        }

        result.GameState = SavedGameState.Load(gameStateData, spellPacketData, partyConfigData, mapFleeData);

        result.UiState = SavedUiState.Load(uiStateData);

        // Load the optional Co8 data if it exists
        var co8Path = basePath + ".co8";

        if (File.Exists(co8Path))
        {
            result.Co8State = SavedCo8State.Load(co8Path);
        }

        return(result);
    }
Пример #31
0
        void ProcessData(IRemoteServer server, INetworkData networkData, ResponseHandler responseHandler)
        {
            switch (networkData.Type)
            {
            case NetworkDataType.Request:
                HandleRequest(networkData as RequestData, responseHandler);
                break;

            case NetworkDataType.Heartbeat:
            {
                var heartbeat = networkData as Heartbeat;
                // Last heartbeat time was set before.
                if (PlayerIndex == 0u)
                {
                    PlayerIndex = heartbeat.PlayerId;
                }
                foreach (var registeredHeartbeatHandler in registeredHeartbeatHandlers.ToArray())
                {
                    registeredHeartbeatHandler?.Invoke(heartbeat);
                }
                responseHandler?.Invoke(ResponseType.Ok);
                break;
            }

            case NetworkDataType.LobbyData:
                if (serverState != ServerState.Lobby)
                {
                    responseHandler?.Invoke(ResponseType.BadState);
                }
                else
                {
                    responseHandler?.Invoke(ResponseType.Ok);
                    UpdateLobbyData(networkData as LobbyData);
                }
                break;

            case NetworkDataType.Response:
            {
                var responseData = networkData as ResponseData;
                foreach (var registeredResponseHandler in registeredResponseHandlers.ToArray())
                {
                    registeredResponseHandler?.Invoke(responseData);
                }
                break;
            }

            case NetworkDataType.InSync:
            {
                if (serverState != ServerState.Game &&
                    serverState != ServerState.Loading)
                {
                    responseHandler?.Invoke(ResponseType.BadState);
                }
                else
                {
                    if (Game == null)
                    {
                        serverState = ServerState.Offline;
                        responseHandler?.Invoke(ResponseType.BadState);
                        return;
                    }

                    try
                    {
                        var insyncData = networkData as InSyncData;

                        Log.Verbose.Write(ErrorSystemType.Network, $"Processing in-sync message with game time {Misc.SecondsToTime(insyncData.GameTime)}.");

                        if (!lastSavedGameStates.ContainsKey(insyncData.GameTime))         // We don't have the saved state anymore -> need full update
                        {
                            Log.Verbose.Write(ErrorSystemType.Network, $"Last saved game state with game time {Misc.SecondsToTime(insyncData.GameTime)} not available. Requesting re-sync.");
                            RequestGameStateUpdate();
                            return;
                        }

                        Log.Verbose.Write(ErrorSystemType.Network, $"Updating last synced saved state to game time {Misc.SecondsToTime(insyncData.GameTime)} and discarding outdated saved game states.");
                        lastVerifiedSavedGameState = lastSavedGameStates[insyncData.GameTime];
                        // Remove all outdated (timestamp before in-sync game time) saved states.
                        foreach (var outdatedSavedGameState in lastSavedGameStates.Where(s => s.Key <= insyncData.GameTime).ToList())
                        {
                            lastSavedGameStates.Remove(outdatedSavedGameState.Key);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error.Write(ErrorSystemType.Network, "Failed to update game state: " + ex.Message);
                        Disconnect();
                        throw ex;         // TODO: Close game instead of crash?
                    }
                }
                break;
            }

            case NetworkDataType.SyncData:
            {
                if (serverState != ServerState.Game &&
                    serverState != ServerState.Loading)
                {
                    responseHandler?.Invoke(ResponseType.BadState);
                }
                else
                {
                    if (Game == null)
                    {
                        serverState = ServerState.Offline;
                        responseHandler?.Invoke(ResponseType.BadState);
                        return;
                    }

                    try
                    {
                        var syncData = networkData as SyncData;

#if DEBUG
                        var stopWatch = System.Diagnostics.Stopwatch.StartNew();
                        Log.Verbose.Write(ErrorSystemType.Network, "Processing sync ... ");
#endif
                        lock (Game)
                        {
                            lastSavedGameStates.Clear();
                            if (lastVerifiedSavedGameState == null)
                            {
                                lastVerifiedSavedGameState = SavedGameState.FromGame(Game);
                            }
                            lastVerifiedSavedGameState = SavedGameState.UpdateGameAndLastState(Game, lastVerifiedSavedGameState, syncData.SerializedData, syncData.Full);
                        }

#if DEBUG
                        Log.Verbose.Write(ErrorSystemType.Network, $"Processing sync done in {stopWatch.ElapsedMilliseconds / 1000.0} seconds");
#endif
                    }
                    catch (Exception ex)
                    {
                        Log.Error.Write(ErrorSystemType.Network, "Failed to update game state: " + ex.Message);
                        Disconnect();
                        throw ex;         // TODO: Close game instead of crash?
                    }
                }
                break;
            }

            default:
                // Should have been handled by Server_DataReceived already.
                break;
            }
        }
Пример #32
0
 public void SaveGame(SavedGameState savedGameState)
 {
Пример #33
0
 /*
  * isNew : true if starting new game else false
  * sav: null if isNew else comes from SaveState.load()
  */
 private void startGame(bool isNew, SavedGameState sav)
 {
     print("Starting Game");
     //Tell Unity not to destroy this instance when we load up a new scene
     DontDestroyOnLoad(gameManager.Instance);
     if(isNew) {
         //Calling a method in our state manager to start a new game
         gameManager.Instance.startState();
     } else {
         gameManager.Instance.setState(sav);
     }
 }