예제 #1
0
        private void StartGame(Submarine selectedSub, string saveName, string mapSeed)
        {
            if (string.IsNullOrEmpty(saveName))
            {
                return;
            }

            string[] existingSaveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Singleplayer);

            if (Array.Find(existingSaveFiles, s => s == saveName) != null)
            {
                new GUIMessageBox("Save name already in use", "Please choose another name for the save file");
                return;
            }

            if (selectedSub == null)
            {
                new GUIMessageBox(TextManager.Get("SubNotSelected"), TextManager.Get("SelectSubRequest"));
                return;
            }

            if (!Directory.Exists(SaveUtil.TempPath))
            {
                Directory.CreateDirectory(SaveUtil.TempPath);
            }

            File.Copy(selectedSub.FilePath, Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), true);

            selectedSub = new Submarine(Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), "");

            GameMain.GameSession = new GameSession(selectedSub, saveName, GameModePreset.list.Find(gm => gm.Name == "Single Player"));
            (GameMain.GameSession.GameMode as CampaignMode).GenerateMap(mapSeed);

            GameMain.LobbyScreen.Select();
        }
예제 #2
0
        private void UpdateLoadScreen()
        {
            menuTabs[(int)Tab.LoadGame].ClearChildren();

            string[] saveFiles = SaveUtil.GetSaveFiles();

            saveList            = new GUIListBox(new Rectangle(0, 0, 200, menuTabs[(int)Tab.LoadGame].Rect.Height - 80), Color.White, "", menuTabs[(int)Tab.LoadGame]);
            saveList.OnSelected = SelectSaveFile;

            foreach (string saveFile in saveFiles)
            {
                GUITextBlock textBlock = new GUITextBlock(
                    new Rectangle(0, 0, 0, 25),
                    saveFile,
                    "ListBoxElement",
                    Alignment.Left,
                    Alignment.Left,
                    saveList);
                textBlock.Padding  = new Vector4(10.0f, 0.0f, 0.0f, 0.0f);
                textBlock.UserData = saveFile;
            }

            var button = new GUIButton(new Rectangle(0, 0, 100, 30), "Start", Alignment.Right | Alignment.Bottom, "", menuTabs[(int)Tab.LoadGame]);

            button.OnClicked = LoadGame;
        }
        public static void StartCampaignSetup()
        {
            DebugConsole.NewMessage("********* CAMPAIGN SETUP *********", Color.White);
            DebugConsole.ShowQuestionPrompt("Do you want to start a new campaign? Y/N", (string arg) =>
            {
                if (arg.ToLowerInvariant() == "y" || arg.ToLowerInvariant() == "yes")
                {
                    DebugConsole.ShowQuestionPrompt("Enter a save name for the campaign:", (string saveName) =>
                    {
                        StartNewCampaign(saveName, GameMain.NetLobbyScreen.SelectedSub.FilePath, GameMain.NetLobbyScreen.LevelSeed);
                    });
                }
                else
                {
                    var saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Multiplayer).ToArray();
                    DebugConsole.NewMessage("Saved campaigns:", Color.White);
                    for (int i = 0; i < saveFiles.Length; i++)
                    {
                        DebugConsole.NewMessage("   " + i + ". " + saveFiles[i], Color.White);
                    }
                    DebugConsole.ShowQuestionPrompt("Select a save file to load (0 - " + (saveFiles.Length - 1) + "):", (string selectedSave) =>
                    {
                        int saveIndex = -1;
                        if (!int.TryParse(selectedSave, out saveIndex))
                        {
                            return;
                        }

                        LoadCampaign(saveFiles[saveIndex]);
                    });
                }
            });
        }
예제 #4
0
        public void UpdateLoadMenu()
        {
            loadGameContainer.ClearChildren();

            string[] saveFiles = SaveUtil.GetSaveFiles(isMultiplayer ? SaveUtil.SaveType.Multiplayer : SaveUtil.SaveType.Singleplayer);

            saveList            = new GUIListBox(new Rectangle(0, 0, 200, loadGameContainer.Rect.Height - 80), Color.White, "", loadGameContainer);
            saveList.OnSelected = SelectSaveFile;

            foreach (string saveFile in saveFiles)
            {
                GUITextBlock textBlock = new GUITextBlock(
                    new Rectangle(0, 0, 0, 25),
                    Path.GetFileNameWithoutExtension(saveFile),
                    "ListBoxElement",
                    Alignment.Left,
                    Alignment.Left,
                    saveList);
                textBlock.Padding  = new Vector4(10.0f, 0.0f, 0.0f, 0.0f);
                textBlock.UserData = saveFile;
            }

            loadGameButton           = new GUIButton(new Rectangle(0, 0, 100, 30), TextManager.Get("LoadButton"), Alignment.Right | Alignment.Bottom, "", loadGameContainer);
            loadGameButton.OnClicked = (btn, obj) =>
            {
                if (string.IsNullOrWhiteSpace(saveList.SelectedData as string))
                {
                    return(false);
                }
                LoadGame?.Invoke(saveList.SelectedData as string);
                return(true);
            };
            loadGameButton.Enabled = false;
        }
예제 #5
0
        public void UpdateLoadMenu()
        {
            loadGameContainer.ClearChildren();

            string[] saveFiles = SaveUtil.GetSaveFiles(isMultiplayer ? SaveUtil.SaveType.Multiplayer : SaveUtil.SaveType.Singleplayer);

            saveList = new GUIListBox(new RectTransform(new Vector2(0.5f, 1.0f), loadGameContainer.RectTransform, Anchor.CenterLeft))
            {
                OnSelected = SelectSaveFile
            };

            foreach (string saveFile in saveFiles)
            {
                new GUITextBlock(new RectTransform(new Vector2(1, 0.1f), saveList.Content.RectTransform),
                                 text: Path.GetFileNameWithoutExtension(saveFile), style: "ListBoxElement")
                {
                    UserData = saveFile
                };
            }

            loadGameButton           = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomRight), TextManager.Get("LoadButton"), style: "GUIButtonLarge");
            loadGameButton.OnClicked = (btn, obj) =>
            {
                if (string.IsNullOrWhiteSpace(saveList.SelectedData as string))
                {
                    return(false);
                }
                LoadGame?.Invoke(saveList.SelectedData as string);
                return(true);
            };
            loadGameButton.Enabled = false;
        }
예제 #6
0
        public static void StartCampaignSetup()
        {
            DebugConsole.NewMessage("********* CAMPAIGN SETUP *********", Color.White);
            DebugConsole.ShowQuestionPrompt("Do you want to start a new campaign? Y/N", (string arg) =>
            {
                if (arg.ToLowerInvariant() == "y" || arg.ToLowerInvariant() == "yes")
                {
                    DebugConsole.ShowQuestionPrompt("Enter a save name for the campaign:", (string saveName) =>
                    {
                        if (string.IsNullOrWhiteSpace(saveName))
                        {
                            return;
                        }

                        string savePath      = SaveUtil.CreateSavePath(SaveUtil.SaveType.Multiplayer, saveName);
                        GameMain.GameSession = new GameSession(new Submarine(GameMain.NetLobbyScreen.SelectedSub.FilePath, ""), savePath,
                                                               GameModePreset.List.Find(g => g.Identifier == "multiplayercampaign"));
                        var campaign = ((MultiPlayerCampaign)GameMain.GameSession.GameMode);
                        campaign.GenerateMap(GameMain.NetLobbyScreen.LevelSeed);
                        campaign.SetDelegates();

                        GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                        GameMain.GameSession.Map.SelectRandomLocation(true);
                        SaveUtil.SaveGame(GameMain.GameSession.SavePath);
                        campaign.LastSaveID++;

                        DebugConsole.NewMessage("Campaign started!", Color.Cyan);
                    });
                }
                else
                {
                    string[] saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Multiplayer);
                    DebugConsole.NewMessage("Saved campaigns:", Color.White);
                    for (int i = 0; i < saveFiles.Length; i++)
                    {
                        DebugConsole.NewMessage("   " + i + ". " + saveFiles[i], Color.White);
                    }
                    DebugConsole.ShowQuestionPrompt("Select a save file to load (0 - " + (saveFiles.Length - 1) + "):", (string selectedSave) =>
                    {
                        int saveIndex = -1;
                        if (!int.TryParse(selectedSave, out saveIndex))
                        {
                            return;
                        }

                        SaveUtil.LoadGame(saveFiles[saveIndex]);
                        ((MultiPlayerCampaign)GameMain.GameSession.GameMode).LastSaveID++;
                        GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                        GameMain.GameSession.Map.SelectRandomLocation(true);

                        DebugConsole.NewMessage("Campaign loaded!", Color.Cyan);
                    });
                }
            });
        }
예제 #7
0
        private void StartGame(Submarine selectedSub, string saveName, string mapSeed)
        {
            if (string.IsNullOrEmpty(saveName))
            {
                return;
            }

            string[] existingSaveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Singleplayer);

            if (Array.Find(existingSaveFiles, s => s == saveName) != null)
            {
                new GUIMessageBox("Save name already in use", "Please choose another name for the save file");
                return;
            }

            if (selectedSub == null)
            {
                new GUIMessageBox(TextManager.Get("SubNotSelected"), TextManager.Get("SelectSubRequest"));
                return;
            }

            if (!Directory.Exists(SaveUtil.TempPath))
            {
                Directory.CreateDirectory(SaveUtil.TempPath);
            }

            try
            {
                File.Copy(selectedSub.FilePath, Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), true);
            }
            catch (IOException e)
            {
                DebugConsole.ThrowError("Copying the file \"" + selectedSub.FilePath + "\" failed. The file may have been deleted or in use by another process. Try again or select another submarine.", e);
                GameAnalyticsManager.AddErrorEventOnce(
                    "MainMenuScreen.StartGame:IOException" + selectedSub.Name,
                    GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                    "Copying the file \"" + selectedSub.FilePath + "\" failed.\n" + e.Message + "\n" + Environment.StackTrace);
                return;
            }

            selectedSub = new Submarine(Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), "");

            GameMain.GameSession = new GameSession(selectedSub, saveName, GameModePreset.list.Find(gm => gm.Name == "Single Player"));
            (GameMain.GameSession.GameMode as CampaignMode).GenerateMap(mapSeed);

            GameSession.inGameInfo.Initialize();

            GameMain.NilMod.GameInitialize(true);

            GameMain.LobbyScreen.Select();
        }
예제 #8
0
        public static void StartCampaignSetup()
        {
            DebugConsole.NewMessage("********* CAMPAIGN SETUP *********", Color.White);
            DebugConsole.ShowQuestionPrompt("Do you want to start a new campaign? Y/N", (string arg) =>
            {
                if (arg.Equals("y", StringComparison.OrdinalIgnoreCase) || arg.Equals("yes", StringComparison.OrdinalIgnoreCase))
                {
                    DebugConsole.ShowQuestionPrompt("Enter a save name for the campaign:", (string saveName) =>
                    {
                        string savePath = SaveUtil.CreateSavePath(SaveUtil.SaveType.Multiplayer, saveName);
                        StartNewCampaign(savePath, GameMain.NetLobbyScreen.SelectedSub.FilePath, GameMain.NetLobbyScreen.LevelSeed, CampaignSettings.Empty);
                    });
                }
                else
                {
                    var saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Multiplayer, includeInCompatible: false).ToArray();
                    if (saveFiles.Length == 0)
                    {
                        DebugConsole.ThrowError("No save files found.");
                        return;
                    }
                    DebugConsole.NewMessage("Saved campaigns:", Color.White);
                    for (int i = 0; i < saveFiles.Length; i++)
                    {
                        DebugConsole.NewMessage("   " + i + ". " + saveFiles[i], Color.White);
                    }
                    DebugConsole.ShowQuestionPrompt("Select a save file to load (0 - " + (saveFiles.Length - 1) + "):", (string selectedSave) =>
                    {
                        int saveIndex = -1;
                        if (!int.TryParse(selectedSave, out saveIndex))
                        {
                            return;
                        }

                        if (saveIndex < 0 || saveIndex >= saveFiles.Length)
                        {
                            DebugConsole.ThrowError("Invalid save file index.");
                        }
                        else
                        {
                            LoadCampaign(saveFiles[saveIndex]);
                        }
                    });
                }
            });
        }
예제 #9
0
        private bool StartGame(GUIButton button, object userData)
        {
            if (string.IsNullOrEmpty(saveNameBox.Text))
            {
                return(false);
            }

            string[] existingSaveFiles = SaveUtil.GetSaveFiles();

            if (Array.Find(existingSaveFiles, s => s == saveNameBox.Text) != null)
            {
                new GUIMessageBox("Save name already in use", "Please choose another name for the save file");
                return(false);
            }

            Submarine selectedSub = subList.SelectedData as Submarine;

            if (selectedSub == null)
            {
                new GUIMessageBox("Submarine not selected", "Please select a submarine");
                return(false);
            }

            if (!Directory.Exists(SaveUtil.TempPath))
            {
                Directory.CreateDirectory(SaveUtil.TempPath);
            }

            File.Copy(selectedSub.FilePath, Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), true);

            selectedSub = new Submarine(Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), "");

            GameMain.GameSession = new GameSession(selectedSub, saveNameBox.Text, GameModePreset.list.Find(gm => gm.Name == "Single Player"));
            (GameMain.GameSession.gameMode as SinglePlayerMode).GenerateMap(seedBox.Text);

            GameMain.LobbyScreen.Select();

            //new GUIMessageBox("Welcome to Barotrauma!", "Please note that the single player mode is very unfinished at the moment; "+
            //"for example, the NPCs don't have an AI yet and there are only a couple of different quests to complete. The multiplayer "+
            //"mode should be much more enjoyable to play at the moment, so my recommendation is to try out and get a hang of the game mechanics "+
            //"in the single player mode and then move on to multiplayer. Have fun!\n - Regalis, the main dev of Subsurface", 400, 350);

            return(true);
        }
예제 #10
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            Timing.Accumulator += gameTime.ElapsedGameTime.TotalSeconds;
            int updateIterations = (int)Math.Floor(Timing.Accumulator / Timing.Step);

            if (Timing.Accumulator > Timing.Step * 6.0)
            {
                //if the game's running too slowly then we have no choice
                //but to skip a bunch of steps
                //otherwise it snowballs and becomes unplayable
                Timing.Accumulator = Timing.Step;
            }

            CrossThread.ProcessTasks();

            PlayerInput.UpdateVariable();

            if (SoundManager != null)
            {
                if (WindowActive || !Config.MuteOnFocusLost)
                {
                    SoundManager.ListenerGain = SoundManager.CompressionDynamicRangeGain;
                }
                else
                {
                    SoundManager.ListenerGain = 0.0f;
                }
            }

            while (Timing.Accumulator >= Timing.Step)
            {
                Timing.TotalTime += Timing.Step;

                Stopwatch sw = new Stopwatch();
                sw.Start();

                fixedTime.IsRunningSlowly = gameTime.IsRunningSlowly;
                TimeSpan addTime = new TimeSpan(0, 0, 0, 0, 16);
                fixedTime.ElapsedGameTime = addTime;
                fixedTime.TotalGameTime.Add(addTime);
                base.Update(fixedTime);

                PlayerInput.Update(Timing.Step);


                if (loadingScreenOpen)
                {
                    //reset accumulator if loading
                    // -> less choppy loading screens because the screen is rendered after each update
                    // -> no pause caused by leftover time in the accumulator when starting a new shift
                    ResetFrameTime();

                    if (!TitleScreen.PlayingSplashScreen)
                    {
                        SoundPlayer.Update((float)Timing.Step);
                    }

                    if (TitleScreen.LoadState >= 100.0f && !TitleScreen.PlayingSplashScreen &&
                        (!waitForKeyHit || ((PlayerInput.GetKeyboardState.GetPressedKeys().Length > 0 || PlayerInput.PrimaryMouseButtonClicked()) && WindowActive)))
                    {
                        loadingScreenOpen = false;
                    }

#if DEBUG
                    if (TitleScreen.LoadState >= 100.0f && !TitleScreen.PlayingSplashScreen && (Config.AutomaticQuickStartEnabled || Config.AutomaticCampaignLoadEnabled) && FirstLoad && !PlayerInput.KeyDown(Keys.LeftShift))
                    {
                        loadingScreenOpen = false;
                        FirstLoad         = false;

                        if (Config.AutomaticQuickStartEnabled)
                        {
                            MainMenuScreen.QuickStart();
                        }
                        else if (Config.AutomaticCampaignLoadEnabled)
                        {
                            IEnumerable <string> saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Singleplayer);

                            if (saveFiles.Count() > 0)
                            {
                                saveFiles = saveFiles.OrderBy(file => File.GetLastWriteTime(file));
                                try
                                {
                                    SaveUtil.LoadGame(saveFiles.Last());
                                }
                                catch (Exception e)
                                {
                                    DebugConsole.ThrowError("Loading save \"" + saveFiles.Last() + "\" failed", e);
                                    return;
                                }
                            }
                        }
                    }
#endif

                    if (!hasLoaded && !CoroutineManager.IsCoroutineRunning(loadingCoroutine))
                    {
                        throw new LoadingException(loadingCoroutine.Exception);
                    }
                }
                else if (hasLoaded)
                {
                    if (ConnectLobby != 0)
                    {
                        if (Client != null)
                        {
                            Client.Disconnect();
                            Client = null;

                            GameMain.MainMenuScreen.Select();
                        }
                        Steam.SteamManager.JoinLobby(ConnectLobby, true);

                        ConnectLobby    = 0;
                        ConnectEndpoint = null;
                        ConnectName     = null;
                    }
                    else if (!string.IsNullOrWhiteSpace(ConnectEndpoint))
                    {
                        if (Client != null)
                        {
                            Client.Disconnect();
                            Client = null;

                            GameMain.MainMenuScreen.Select();
                        }
                        UInt64 serverSteamId = SteamManager.SteamIDStringToUInt64(ConnectEndpoint);
                        Client = new GameClient(Config.PlayerName,
                                                serverSteamId != 0 ? null : ConnectEndpoint,
                                                serverSteamId,
                                                string.IsNullOrWhiteSpace(ConnectName) ? ConnectEndpoint : ConnectName);
                        ConnectLobby    = 0;
                        ConnectEndpoint = null;
                        ConnectName     = null;
                    }

                    SoundPlayer.Update((float)Timing.Step);

                    if (PlayerInput.KeyHit(Keys.Escape) && WindowActive)
                    {
                        // Check if a text input is selected.
                        if (GUI.KeyboardDispatcher.Subscriber != null)
                        {
                            if (GUI.KeyboardDispatcher.Subscriber is GUITextBox textBox)
                            {
                                textBox.Deselect();
                            }
                            GUI.KeyboardDispatcher.Subscriber = null;
                        }
                        //if a verification prompt (are you sure you want to x) is open, close it
                        else if (GUIMessageBox.VisibleBox as GUIMessageBox != null &&
                                 GUIMessageBox.VisibleBox.UserData as string == "verificationprompt")
                        {
                            ((GUIMessageBox)GUIMessageBox.VisibleBox).Close();
                        }
                        else if (GUIMessageBox.VisibleBox?.UserData is RoundSummary roundSummary &&
                                 roundSummary.ContinueButton != null &&
                                 roundSummary.ContinueButton.Visible)
                        {
                            GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox);
                        }
                        else if (Tutorial.Initialized && Tutorial.ContentRunning)
                        {
                            (GameSession.GameMode as TutorialMode).Tutorial.CloseActiveContentGUI();
                        }
                        else if (GameSession.IsTabMenuOpen)
                        {
                            gameSession.ToggleTabMenu();
                        }
                        else if (GUI.PauseMenuOpen)
                        {
                            GUI.TogglePauseMenu();
                        }
                        //open the pause menu if not controlling a character OR if the character has no UIs active that can be closed with ESC
                        else if ((Character.Controlled == null || !itemHudActive())
                                 //TODO: do we need to check Inventory.SelectedSlot?
                                 && Inventory.SelectedSlot == null && CharacterHealth.OpenHealthWindow == null &&
                                 !CrewManager.IsCommandInterfaceOpen &&
                                 !(Screen.Selected is SubEditorScreen editor && !editor.WiringMode && Character.Controlled?.SelectedConstruction != null))
                        {
                            // Otherwise toggle pausing, unless another window/interface is open.
                            GUI.TogglePauseMenu();
                        }
예제 #11
0
        public void UpdateLoadMenu(IEnumerable <string> saveFiles = null)
        {
            prevSaveFiles?.Clear();
            loadGameContainer.ClearChildren();

            if (saveFiles == null)
            {
                saveFiles = SaveUtil.GetSaveFiles(isMultiplayer ? SaveUtil.SaveType.Multiplayer : SaveUtil.SaveType.Singleplayer);
            }

            var leftColumn = new GUILayoutGroup(new RectTransform(isMultiplayer ? new Vector2(1.0f, 0.85f) : new Vector2(0.5f, 1.0f), loadGameContainer.RectTransform), childAnchor: Anchor.TopCenter)
            {
                Stretch         = true,
                RelativeSpacing = 0.03f
            };

            saveList = new GUIListBox(new RectTransform(Vector2.One, leftColumn.RectTransform))
            {
                OnSelected = SelectSaveFile
            };

            if (!isMultiplayer)
            {
                new GUIButton(new RectTransform(new Vector2(0.6f, 0.08f), leftColumn.RectTransform), TextManager.Get("showinfolder"))
                {
                    OnClicked = (btn, userdata) =>
                    {
                        try
                        {
                            ToolBox.OpenFileWithShell(SaveUtil.SaveFolder);
                        }
                        catch (Exception e)
                        {
                            new GUIMessageBox(
                                TextManager.Get("error"),
                                TextManager.GetWithVariables("showinfoldererror", new string[] { "[folder]", "[errormessage]" }, new string[] { SaveUtil.SaveFolder, e.Message }));
                        }
                        return(true);
                    }
                };
            }

            foreach (string saveFile in saveFiles)
            {
                string fileName          = saveFile;
                string subName           = "";
                string saveTime          = "";
                string contentPackageStr = "";
                var    saveFrame         = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), saveList.Content.RectTransform)
                {
                    MinSize = new Point(0, 45)
                }, style: "ListBoxElement")
                {
                    UserData = saveFile
                };

                var nameText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform), "")
                {
                    CanBeFocused = false
                };

                if (!isMultiplayer)
                {
                    nameText.Text = Path.GetFileNameWithoutExtension(saveFile);
                    XDocument doc = SaveUtil.LoadGameSessionDoc(saveFile);

                    if (doc?.Root == null)
                    {
                        DebugConsole.ThrowError("Error loading save file \"" + saveFile + "\". The file may be corrupted.");
                        nameText.TextColor = GUI.Style.Red;
                        continue;
                    }
                    if (doc.Root.GetChildElement("multiplayercampaign") != null)
                    {
                        //multiplayer campaign save in the wrong folder -> don't show the save
                        saveList.Content.RemoveChild(saveFrame);
                        continue;
                    }
                    subName           = doc.Root.GetAttributeString("submarine", "");
                    saveTime          = doc.Root.GetAttributeString("savetime", "");
                    contentPackageStr = doc.Root.GetAttributeString("selectedcontentpackages", "");

                    prevSaveFiles?.Add(saveFile);
                }
                else
                {
                    string[] splitSaveFile = saveFile.Split(';');
                    saveFrame.UserData = splitSaveFile[0];
                    fileName           = nameText.Text = Path.GetFileNameWithoutExtension(splitSaveFile[0]);
                    prevSaveFiles?.Add(fileName);
                    if (splitSaveFile.Length > 1)
                    {
                        subName = splitSaveFile[1];
                    }
                    if (splitSaveFile.Length > 2)
                    {
                        saveTime = splitSaveFile[2];
                    }
                    if (splitSaveFile.Length > 3)
                    {
                        contentPackageStr = splitSaveFile[3];
                    }
                }
                if (!string.IsNullOrEmpty(saveTime) && long.TryParse(saveTime, out long unixTime))
                {
                    DateTime time = ToolBox.Epoch.ToDateTime(unixTime);
                    saveTime = time.ToString();
                }
                if (!string.IsNullOrEmpty(contentPackageStr))
                {
                    List <string> contentPackagePaths = contentPackageStr.Split('|').ToList();
                    if (!GameSession.IsCompatibleWithSelectedContentPackages(contentPackagePaths, out string errorMsg))
                    {
                        nameText.TextColor = GUI.Style.Red;
                        saveFrame.ToolTip  = string.Join("\n", errorMsg, TextManager.Get("campaignmode.contentpackagemismatchwarning"));
                    }
                }

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform, Anchor.BottomLeft),
                                 text: subName, font: GUI.SmallFont)
                {
                    CanBeFocused = false,
                    UserData     = fileName
                };

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), saveFrame.RectTransform),
                                 text: saveTime, textAlignment: Alignment.Right, font: GUI.SmallFont)
                {
                    CanBeFocused = false,
                    UserData     = fileName
                };
            }

            saveList.Content.RectTransform.SortChildren((c1, c2) =>
            {
                string file1            = c1.GUIComponent.UserData as string;
                string file2            = c2.GUIComponent.UserData as string;
                DateTime file1WriteTime = DateTime.MinValue;
                DateTime file2WriteTime = DateTime.MinValue;
                try
                {
                    file1WriteTime = File.GetLastWriteTime(file1);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                try
                {
                    file2WriteTime = File.GetLastWriteTime(file2);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                return(file2WriteTime.CompareTo(file1WriteTime));
            });

            loadGameButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomRight), TextManager.Get("LoadButton"))
            {
                OnClicked = (btn, obj) =>
                {
                    if (string.IsNullOrWhiteSpace(saveList.SelectedData as string))
                    {
                        return(false);
                    }
                    LoadGame?.Invoke(saveList.SelectedData as string);
                    if (isMultiplayer)
                    {
                        CoroutineManager.StartCoroutine(WaitForCampaignSetup(), "WaitForCampaignSetup");
                    }
                    return(true);
                },
                Enabled = false
            };
            deleteMpSaveButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomLeft),
                                               TextManager.Get("Delete"), style: "GUIButtonSmall")
            {
                OnClicked = DeleteSave,
                Visible   = false
            };
        }
        public void UpdateLoadMenu(IEnumerable <string> saveFiles = null)
        {
            prevSaveFiles?.Clear();
            prevSaveFiles = null;
            loadGameContainer.ClearChildren();

            if (saveFiles == null)
            {
                saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Multiplayer);
            }

            var leftColumn = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.85f), loadGameContainer.RectTransform), childAnchor: Anchor.TopCenter)
            {
                Stretch         = true,
                RelativeSpacing = 0.03f
            };

            saveList = new GUIListBox(new RectTransform(Vector2.One, leftColumn.RectTransform))
            {
                OnSelected = SelectSaveFile
            };

            foreach (string saveFile in saveFiles)
            {
                string fileName          = saveFile;
                string subName           = "";
                string saveTime          = "";
                string contentPackageStr = "";
                var    saveFrame         = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), saveList.Content.RectTransform)
                {
                    MinSize = new Point(0, 45)
                }, style: "ListBoxElement")
                {
                    UserData = saveFile
                };

                var nameText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform), "")
                {
                    CanBeFocused = false
                };

                bool isCompatible = true;
                prevSaveFiles ??= new List <string>();

                prevSaveFiles?.Add(saveFile);
                string[] splitSaveFile = saveFile.Split(';');
                saveFrame.UserData = splitSaveFile[0];
                fileName           = nameText.Text = Path.GetFileNameWithoutExtension(splitSaveFile[0]);
                if (splitSaveFile.Length > 1)
                {
                    subName = splitSaveFile[1];
                }
                if (splitSaveFile.Length > 2)
                {
                    saveTime = splitSaveFile[2];
                }
                if (splitSaveFile.Length > 3)
                {
                    contentPackageStr = splitSaveFile[3];
                }

                if (!string.IsNullOrEmpty(saveTime) && long.TryParse(saveTime, out long unixTime))
                {
                    DateTime time = ToolBox.Epoch.ToDateTime(unixTime);
                    saveTime = time.ToString();
                }
                if (!string.IsNullOrEmpty(contentPackageStr))
                {
                    List <string> contentPackagePaths = contentPackageStr.Split('|').ToList();
                    if (!GameSession.IsCompatibleWithEnabledContentPackages(contentPackagePaths, out string errorMsg))
                    {
                        nameText.TextColor = GUI.Style.Red;
                        saveFrame.ToolTip  = string.Join("\n", errorMsg, TextManager.Get("campaignmode.contentpackagemismatchwarning"));
                    }
                }
                if (!isCompatible)
                {
                    nameText.TextColor = GUI.Style.Red;
                    saveFrame.ToolTip  = TextManager.Get("campaignmode.incompatiblesave");
                }

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform, Anchor.BottomLeft),
                                 text: subName, font: GUI.SmallFont)
                {
                    CanBeFocused = false,
                    UserData     = fileName
                };

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), saveFrame.RectTransform),
                                 text: saveTime, textAlignment: Alignment.Right, font: GUI.SmallFont)
                {
                    CanBeFocused = false,
                    UserData     = fileName
                };
            }

            saveList.Content.RectTransform.SortChildren((c1, c2) =>
            {
                string file1            = c1.GUIComponent.UserData as string;
                string file2            = c2.GUIComponent.UserData as string;
                DateTime file1WriteTime = DateTime.MinValue;
                DateTime file2WriteTime = DateTime.MinValue;
                try
                {
                    file1WriteTime = File.GetLastWriteTime(file1);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                try
                {
                    file2WriteTime = File.GetLastWriteTime(file2);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                return(file2WriteTime.CompareTo(file1WriteTime));
            });

            loadGameButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomRight), TextManager.Get("LoadButton"))
            {
                OnClicked = (btn, obj) =>
                {
                    if (string.IsNullOrWhiteSpace(saveList.SelectedData as string))
                    {
                        return(false);
                    }
                    LoadGame?.Invoke(saveList.SelectedData as string);
                    CoroutineManager.StartCoroutine(WaitForCampaignSetup(), "WaitForCampaignSetup");
                    return(true);
                },
                Enabled = false
            };
            deleteMpSaveButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomLeft),
                                               TextManager.Get("Delete"), style: "GUIButtonSmall")
            {
                OnClicked = DeleteSave,
                Visible   = false
            };
        }
예제 #13
0
        public void UpdateLoadMenu(IEnumerable <string> saveFiles = null)
        {
            loadGameContainer.ClearChildren();

            if (saveFiles == null)
            {
                saveFiles = SaveUtil.GetSaveFiles(isMultiplayer ? SaveUtil.SaveType.Multiplayer : SaveUtil.SaveType.Singleplayer);
            }

            saveList = new GUIListBox(new RectTransform(
                                          isMultiplayer ? new Vector2(1.0f, 0.85f) : new Vector2(0.5f, 1.0f), loadGameContainer.RectTransform))
            {
                OnSelected = SelectSaveFile
            };

            foreach (string saveFile in saveFiles)
            {
                string fileName  = saveFile;
                string subName   = "";
                string saveTime  = "";
                var    saveFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), saveList.Content.RectTransform)
                {
                    MinSize = new Point(0, 45)
                }, style: "ListBoxElement")
                {
                    UserData = saveFile
                };

                var nameText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform),
                                                text: Path.GetFileNameWithoutExtension(saveFile));

                if (!isMultiplayer)
                {
                    XDocument doc = SaveUtil.LoadGameSessionDoc(saveFile);
                    if (doc?.Root == null)
                    {
                        DebugConsole.ThrowError("Error loading save file \"" + saveFile + "\". The file may be corrupted.");
                        nameText.Color = Color.Red;
                        continue;
                    }
                    subName  = doc.Root.GetAttributeString("submarine", "");
                    saveTime = doc.Root.GetAttributeString("savetime", "");
                }
                else
                {
                    string[] splitSaveFile = saveFile.Split(';');
                    saveFrame.UserData = splitSaveFile[0];
                    fileName           = nameText.Text = Path.GetFileNameWithoutExtension(splitSaveFile[0]);
                    if (splitSaveFile.Length > 1)
                    {
                        subName = splitSaveFile[1];
                    }
                    if (splitSaveFile.Length > 2)
                    {
                        saveTime = splitSaveFile[2];
                    }
                }
                if (!string.IsNullOrEmpty(saveTime) && long.TryParse(saveTime, out long unixTime))
                {
                    DateTime time = ToolBox.Epoch.ToDateTime(unixTime);
                    saveTime = time.ToString();
                }

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform, Anchor.BottomLeft),
                                 text: subName, font: GUI.SmallFont)
                {
                    UserData = fileName
                };

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), saveFrame.RectTransform),
                                 text: saveTime, textAlignment: Alignment.Right, font: GUI.SmallFont)
                {
                    UserData = fileName
                };
            }

            saveList.Content.RectTransform.SortChildren((c1, c2) =>
            {
                string file1            = c1.GUIComponent.UserData as string;
                string file2            = c2.GUIComponent.UserData as string;
                DateTime file1WriteTime = DateTime.MinValue;
                DateTime file2WriteTime = DateTime.MinValue;
                try
                {
                    file1WriteTime = File.GetLastWriteTime(file1);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                try
                {
                    file2WriteTime = File.GetLastWriteTime(file2);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                return(file2WriteTime.CompareTo(file1WriteTime));
            });

            loadGameButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomRight), TextManager.Get("LoadButton"), style: "GUIButtonLarge")
            {
                OnClicked = (btn, obj) =>
                {
                    if (string.IsNullOrWhiteSpace(saveList.SelectedData as string))
                    {
                        return(false);
                    }
                    LoadGame?.Invoke(saveList.SelectedData as string);
                    if (isMultiplayer)
                    {
                        CoroutineManager.StartCoroutine(WaitForCampaignSetup(), "WaitForCampaignSetup");
                    }
                    return(true);
                },
                Enabled = false
            };
        }
        public static void StartCampaignSetup(Boolean AutoSetup = false)
        {
            if (!AutoSetup)
            {
                DebugConsole.NewMessage("********* CAMPAIGN SETUP *********", Color.White);
                DebugConsole.ShowQuestionPrompt("Do you want to start a new campaign? Y/N", (string arg) =>
                {
                    if (arg.ToLowerInvariant() == "y" || arg.ToLowerInvariant() == "yes")
                    {
                        DebugConsole.ShowQuestionPrompt("Enter a save name for the campaign:", (string saveName) =>
                        {
                            if (string.IsNullOrWhiteSpace(saveName))
                            {
                                return;
                            }

                            string savePath      = SaveUtil.CreateSavePath(SaveUtil.SaveType.Multiplayer, saveName);
                            GameMain.GameSession = new GameSession(new Submarine(GameMain.NetLobbyScreen.SelectedSub.FilePath, ""), savePath, GameModePreset.list.Find(g => g.Name == "Campaign"));
                            var campaign         = ((MultiPlayerCampaign)GameMain.GameSession.GameMode);
                            campaign.GenerateMap(GameMain.NetLobbyScreen.LevelSeed);
                            campaign.SetDelegates();

                            GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                            GameMain.GameSession.Map.SelectRandomLocation(true);
                            SaveUtil.SaveGame(GameMain.GameSession.SavePath);
                            campaign.LastSaveID++;

                            campaign.AutoPurchaseNew();

                            DebugConsole.NewMessage("Campaign started!", Color.Cyan);
                        });
                    }
                    else
                    {
                        string[] saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Multiplayer);
                        DebugConsole.NewMessage("Saved campaigns:", Color.White);
                        for (int i = 0; i < saveFiles.Length; i++)
                        {
                            DebugConsole.NewMessage("   " + i + ". " + saveFiles[i], Color.White);
                        }
                        DebugConsole.ShowQuestionPrompt("Select a save file to load (0 - " + (saveFiles.Length - 1) + "):", (string selectedSave) =>
                        {
                            int saveIndex = -1;
                            if (!int.TryParse(selectedSave, out saveIndex))
                            {
                                return;
                            }

                            SaveUtil.LoadGame(saveFiles[saveIndex]);
                            var campaign = ((MultiPlayerCampaign)GameMain.GameSession.GameMode);
                            campaign.LastSaveID++;
                            GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                            GameMain.GameSession.Map.SelectRandomLocation(true);

                            if (GameMain.NilMod.CampaignAutoPurchase)
                            {
                                //If money is exactly the same as what we start as, assume its actually a new game that was saved and reloaded!
                                if (campaign.Money == GameMain.NilMod.CampaignInitialMoney)
                                {
                                    campaign.AutoPurchaseNew();
                                }
                            }
                            //Money is not the default amount on loading, so its likely a game in progress
                            else
                            {
                                campaign.AutoPurchaseExisting();
                            }

                            DebugConsole.NewMessage("Campaign loaded!", Color.Cyan);
                        });
                    }
                });
            }
        }
        public static GUIComponent StartCampaignSetup(Boolean AutoSetup = false)
        {
            if (!AutoSetup)
            {
                GUIFrame background = new GUIFrame(new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight), Color.Black * 0.5f, null);

                GUIFrame setupBox = new GUIFrame(new Rectangle(0, 0, 500, 500), null, Alignment.Center, "", background);
                setupBox.Padding = new Vector4(20.0f, 20.0f, 20.0f, 20.0f);
                new GUITextBlock(new Rectangle(0, 0, 10, 10), "Campaign Setup", "", setupBox, GUI.LargeFont);
                setupBox.Padding = new Vector4(20.0f, 80.0f, 20.0f, 20.0f);

                var newCampaignContainer  = new GUIFrame(new Rectangle(0, 40, 0, 0), null, setupBox);
                var loadCampaignContainer = new GUIFrame(new Rectangle(0, 40, 0, 0), null, setupBox);

                var campaignSetupUI = new CampaignSetupUI(true, newCampaignContainer, loadCampaignContainer);

                var newCampaignButton = new GUIButton(new Rectangle(0, 0, 120, 20), "New campaign", "", setupBox);
                newCampaignButton.OnClicked += (btn, obj) =>
                {
                    newCampaignContainer.Visible  = true;
                    loadCampaignContainer.Visible = false;
                    return(true);
                };

                var loadCampaignButton = new GUIButton(new Rectangle(130, 0, 120, 20), "Load campaign", "", setupBox);
                loadCampaignButton.OnClicked += (btn, obj) =>
                {
                    newCampaignContainer.Visible  = false;
                    loadCampaignContainer.Visible = true;
                    return(true);
                };

                loadCampaignContainer.Visible = false;

                campaignSetupUI.StartNewGame = (Submarine sub, string saveName, string mapSeed) =>
                {
                    GameMain.GameSession = new GameSession(new Submarine(sub.FilePath, ""), saveName, GameModePreset.list.Find(g => g.Name == "Campaign"));
                    var campaign = ((MultiPlayerCampaign)GameMain.GameSession.GameMode);
                    campaign.GenerateMap(mapSeed);
                    campaign.SetDelegates();

                    background.Visible = false;

                    GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                    campaign.Map.SelectRandomLocation(true);
                    SaveUtil.SaveGame(GameMain.GameSession.SavePath);
                    campaign.LastSaveID++;

                    campaign.AutoPurchaseNew();
                };

                campaignSetupUI.LoadGame = (string fileName) =>
                {
                    SaveUtil.LoadGame(fileName);
                    var campaign = ((MultiPlayerCampaign)GameMain.GameSession.GameMode);
                    campaign.LastSaveID++;

                    background.Visible = false;

                    GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                    campaign.Map.SelectRandomLocation(true);

                    if (GameMain.NilMod.CampaignAutoPurchase)
                    {
                        //If money is exactly the same as what we start as, assume its actually a new game that was saved and reloaded!
                        if (campaign.Money == GameMain.NilMod.CampaignInitialMoney)
                        {
                            campaign.AutoPurchaseNew();
                        }
                    }
                    //Money is not the default amount on loading, so its likely a game in progress
                    else
                    {
                        campaign.AutoPurchaseExisting();
                    }
                };

                var cancelButton = new GUIButton(new Rectangle(0, 0, 120, 30), "Cancel", Alignment.BottomLeft, "", setupBox);
                cancelButton.OnClicked += (btn, obj) =>
                {
                    background.Visible = false;
                    int otherModeIndex = 0;
                    for (otherModeIndex = 0; otherModeIndex < GameMain.NetLobbyScreen.ModeList.children.Count; otherModeIndex++)
                    {
                        if (GameMain.NetLobbyScreen.ModeList.children[otherModeIndex].UserData is MultiPlayerCampaign)
                        {
                            continue;
                        }
                        break;
                    }

                    GameMain.NetLobbyScreen.SelectMode(otherModeIndex);
                    return(true);
                };

                return(background);
            }
            else
            {
                string[] saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Multiplayer);
                string   Savepath  = "Data" + System.IO.Path.DirectorySeparatorChar + "Saves" + System.IO.Path.DirectorySeparatorChar + "Multiplayer" + System.IO.Path.DirectorySeparatorChar + GameMain.NilMod.CampaignDefaultSaveName + ".save";
                if (saveFiles.Contains(Savepath))
                {
                    SaveUtil.LoadGame(Savepath);
                    var campaign = ((MultiPlayerCampaign)GameMain.GameSession.GameMode);
                    campaign.LastSaveID++;
                    GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                    GameMain.GameSession.Map.SelectRandomLocation(true);

                    //If money is exactly the same as what we start as, assume its actually a new game that was saved and reloaded!
                    if (campaign.Money == GameMain.NilMod.CampaignInitialMoney)
                    {
                        campaign.AutoPurchaseNew();
                    }
                    //Money is not the default amount on loading, so its likely a game in progress
                    else
                    {
                        campaign.AutoPurchaseExisting();
                    }

                    DebugConsole.NewMessage(@"Campaign save """ + GameMain.NilMod.CampaignDefaultSaveName + @""" automatically loaded!", Color.Cyan);
                    DebugConsole.NewMessage("On Submarine: " + GameMain.GameSession.Submarine.Name, Color.Cyan);
                    DebugConsole.NewMessage("Using Level Seed: " + GameMain.NetLobbyScreen.LevelSeed, Color.Cyan);
                    DebugConsole.NewMessage(GameMain.NetLobbyScreen.SelectedMode.Name, Color.Cyan);
                }
                else
                {
                    string    savePath    = SaveUtil.CreateSavePath(SaveUtil.SaveType.Multiplayer, GameMain.NilMod.CampaignDefaultSaveName);
                    Submarine CampaignSub = null;

                    var subsToShow = Submarine.SavedSubmarines.Where(s => !s.HasTag(SubmarineTag.HideInMenus)).ToList <Submarine>();

                    if (!GameMain.NilMod.CampaignUseRandomSubmarine)
                    {
                        if (GameMain.NilMod.DefaultSubmarine != "" && subsToShow.Count >= 0)
                        {
                            CampaignSub = subsToShow.Find(s => s.Name.ToLowerInvariant() == GameMain.NilMod.DefaultSubmarine.ToLowerInvariant());

                            if (CampaignSub == null)
                            {
                                subsToShow = Submarine.SavedSubmarines.Where(s => !s.HasTag(SubmarineTag.HideInMenus) && !s.HasTag(SubmarineTag.Shuttle)).ToList <Submarine>();
                                if (subsToShow.Count > 0)
                                {
                                    CampaignSub = subsToShow[Rand.Range((int)0, subsToShow.Count())];
                                }
                                else
                                {
                                    subsToShow = Submarine.SavedSubmarines.Where(s => !s.HasTag(SubmarineTag.HideInMenus)).ToList <Submarine>();
                                    if (subsToShow.Count > 0)
                                    {
                                        DebugConsole.NewMessage("Error - No default submarine found in nilmodsettings, a random submarine has been chosen", Color.Red);
                                        CampaignSub = subsToShow[Rand.Range((int)0, subsToShow.Count())];
                                    }
                                    else
                                    {
                                        DebugConsole.NewMessage("Error - No saved submarines to initialize campaign with.", Color.Red);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        subsToShow = Submarine.SavedSubmarines.Where(s => !s.HasTag(SubmarineTag.HideInMenus) && !s.HasTag(SubmarineTag.Shuttle)).ToList <Submarine>();

                        if (subsToShow.Count >= 0)
                        {
                            CampaignSub = subsToShow[Rand.Range((int)0, subsToShow.Count())];
                        }
                        else
                        {
                            subsToShow = Submarine.SavedSubmarines.Where(s => !s.HasTag(SubmarineTag.HideInMenus)).ToList <Submarine>();
                            if (subsToShow.Count >= 0)
                            {
                                CampaignSub = subsToShow[Rand.Range((int)0, subsToShow.Count())];
                            }
                        }
                    }

                    if (CampaignSub != null)
                    {
                        GameMain.NilMod.CampaignFails = 0;
                        GameMain.GameSession          = new GameSession(new Submarine(CampaignSub.FilePath, ""), savePath, GameModePreset.list.Find(g => g.Name == "Campaign"));
                        var campaign = ((MultiPlayerCampaign)GameMain.GameSession.GameMode);
                        campaign.GenerateMap(GameMain.NetLobbyScreen.LevelSeed);
                        campaign.SetDelegates();

                        GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                        GameMain.GameSession.Map.SelectRandomLocation(true);

                        GameMain.NilMod.CampaignStart = true;

                        SaveUtil.SaveGame(GameMain.GameSession.SavePath);
                        campaign.LastSaveID++;

                        campaign.AutoPurchaseNew();



                        DebugConsole.NewMessage(@"New campaign """ + GameMain.NilMod.CampaignDefaultSaveName + @""" automatically started!", Color.Cyan);
                        DebugConsole.NewMessage("On Submarine: " + CampaignSub.Name, Color.Cyan);
                        DebugConsole.NewMessage("Using Level Seed: " + GameMain.NetLobbyScreen.LevelSeed, Color.Cyan);
                    }
                    else
                    {
                        GameMain.NetLobbyScreen.ToggleCampaignMode(false);
                        GameMain.NetLobbyScreen.SelectedModeIndex = 0;
                        GameMain.NetLobbyScreen.SelectMode(0);
                        //Cancel it here
                    }
                }
                return(null);
            }
        }
예제 #16
0
        public void UpdateLoadMenu()
        {
            loadGameContainer.ClearChildren();

            string[] saveFiles = SaveUtil.GetSaveFiles(isMultiplayer ? SaveUtil.SaveType.Multiplayer : SaveUtil.SaveType.Singleplayer);

            saveList = new GUIListBox(new RectTransform(new Vector2(0.5f, 1.0f), loadGameContainer.RectTransform, Anchor.CenterLeft))
            {
                OnSelected = SelectSaveFile
            };

            foreach (string saveFile in saveFiles)
            {
                XDocument doc       = SaveUtil.LoadGameSessionDoc(saveFile);
                var       saveFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), saveList.Content.RectTransform), style: "ListBoxElement")
                {
                    UserData = saveFile
                };

                var nameText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform),
                                                text: Path.GetFileNameWithoutExtension(saveFile));
                if (doc?.Root == null)
                {
                    DebugConsole.ThrowError("Error loading save file \"" + saveFile + "\". The file may be corrupted.");
                    nameText.Color = Color.Red;
                    continue;
                }

                string submarineName = doc.Root.GetAttributeString("submarine", "");
                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform, Anchor.BottomLeft),
                                 text: submarineName, font: GUI.SmallFont)
                {
                    UserData = saveFile
                };

                string saveTime = doc.Root.GetAttributeString("savetime", "");
                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), saveFrame.RectTransform),
                                 text: saveTime, textAlignment: Alignment.Right, font: GUI.SmallFont)
                {
                    UserData = saveFile
                };
            }

            saveList.Content.RectTransform.SortChildren((c1, c2) =>
            {
                string file1            = c1.GUIComponent.UserData as string;
                string file2            = c2.GUIComponent.UserData as string;
                DateTime file1WriteTime = DateTime.MinValue;
                DateTime file2WriteTime = DateTime.MinValue;
                try
                {
                    file1WriteTime = File.GetLastWriteTime(file1);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                try
                {
                    file2WriteTime = File.GetLastWriteTime(file2);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                return(file2WriteTime.CompareTo(file1WriteTime));
            });

            loadGameButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomRight), TextManager.Get("LoadButton"), style: "GUIButtonLarge")
            {
                OnClicked = (btn, obj) =>
                {
                    if (string.IsNullOrWhiteSpace(saveList.SelectedData as string))
                    {
                        return(false);
                    }
                    LoadGame?.Invoke(saveList.SelectedData as string);
                    return(true);
                },
                Enabled = false
            };
        }