diff --git a/C7/C7Game.tscn b/C7/C7Game.tscn
index d5799f248..ecfbbff0c 100644
--- a/C7/C7Game.tscn
+++ b/C7/C7Game.tscn
@@ -393,6 +393,7 @@ visible = false
[connection signal="DiplomacySelection" from="CanvasLayer/PopupOverlay" to="." method="OnDiplomacySelected"]
[connection signal="HidePopup" from="CanvasLayer/PopupOverlay" to="CanvasLayer/PopupOverlay" method="OnHidePopup"]
[connection signal="LoadGame" from="CanvasLayer/PopupOverlay" to="." method="OnLoadGame"]
+[connection signal="NewGame" from="CanvasLayer/PopupOverlay" to="." method="EmitNewGameConfirmationSignal"]
[connection signal="OpenPreferences" from="CanvasLayer/PopupOverlay" to="." method="OnOpenPreferences"]
[connection signal="Quit" from="CanvasLayer/PopupOverlay" to="." method="OnQuitTheGame"]
[connection signal="Retire" from="CanvasLayer/PopupOverlay" to="." method="OnRetire"]
diff --git a/C7/Game.cs b/C7/Game.cs
index e0ca7c6e0..b5663858c 100644
--- a/C7/Game.cs
+++ b/C7/Game.cs
@@ -492,6 +492,11 @@ private void InterestingEvent() {
}
public override void _Process(double delta) {
+ // Persisted with the save so time played carries across saves and loads
+ if (EngineStorage.gameData != null) {
+ EngineStorage.gameData.timePlayedSeconds += delta;
+ }
+
ProcessActions();
if (!EngineStorage.HasPendingAnimations())
@@ -623,10 +628,18 @@ private void DoActualEndTurn() {
}
public void OnRetire() {
+ // TODO: Retire should also show the end-of-game results (score graphs, etc.) before returning
+ // to the main menu. That screen doesn't exist yet; per-turn score data is already recorded in
+ // gameData.history (HistTurnRecord). The defeat popup is shown by EmitRetireDefeatSignal.
// Quit to main menu, freeing previous scene data
GetTree().ChangeSceneToFile("res://UIElements/MainMenu/main_menu.tscn");
}
+ public void OnNewGame() {
+ // Same as the original game: return to the main entry screen
+ GetTree().ChangeSceneToFile("res://UIElements/MainMenu/main_menu.tscn");
+ }
+
public void OnSaveGame() {
SavePaths.EnsureSaveFolderExists();
FileDialog.SetDirectoryForSaving(SavePaths.SaveFolder);
@@ -910,15 +923,6 @@ private void HandleKeyboardInput(InputEventKey eventKeyDown) {
return;
}
- if (eventKeyDown.Keycode == Godot.Key.P && eventKeyDown.IsCommandOrControlPressed()) {
- if (preferences.Visible) {
- preferences.HidePreferences();
- } else {
- preferences.ShowPreferences();
- }
- return;
- }
-
if (eventKeyDown.Keycode == Godot.Key.F1) {
EmitSignal(SignalName.ShowSpecificAdvisor, C7Action.ShowDomesticAdvisor);
}
@@ -1098,7 +1102,11 @@ private bool IsModalSwitchEvent(InputEvent @event) {
private void ProcessAction(string currentAction) {
if (currentAction == C7Action.Escape && interactablePopUpController.Visible) {
- interactablePopUpController.Visible = false;
+ // Some popups (e.g. the defeat ones) must be answered, since closing them this way
+ // skips their actions and would leave the player stuck in a finished game.
+ if (interactablePopUpController.CanDismissWithEscape) {
+ interactablePopUpController.Visible = false;
+ }
return;
}
@@ -1126,10 +1134,12 @@ private void ProcessAction(string currentAction) {
return;
}
+ // Ctrl-P is handled only here (not in HandleKeyboardInput), otherwise the
+ // key event and the action poll both toggle in the same frame and cancel out.
if (currentAction == C7Action.OpenPreferences) {
if (preferences.Visible) {
preferences.HidePreferences();
- } else {
+ } else if (!HasVisibleModal()) {
preferences.ShowPreferences();
}
return;
@@ -1175,6 +1185,11 @@ private void ProcessAction(string currentAction) {
return;
}
+ if (currentAction == C7Action.NewGame) {
+ EmitNewGameConfirmationSignal();
+ return;
+ }
+
if (currentAction == C7Action.Retire) {
EmitRetireConfirmationSignal();
return;
diff --git a/C7/Game_EmitMessages.cs b/C7/Game_EmitMessages.cs
index dfbc10a71..3b1b738b1 100644
--- a/C7/Game_EmitMessages.cs
+++ b/C7/Game_EmitMessages.cs
@@ -84,7 +84,11 @@ public void EmitGameMainMenuSignal() {
};
options.Add(loadGameBtn);
- // TODO: add New Game option. This seems to do exactly the same as Retire in the original game
+ var newGameBtn = new ButtonAction() {
+ message = "New Game (Ctrl-Shift-Q)",
+ action = () => EmitNewGameConfirmationSignal(),
+ };
+ options.Add(newGameBtn);
var preferencesBtn = new ButtonAction() {
message = "Preferences (Ctrl-P)",
@@ -136,7 +140,58 @@ public void EmitRetireConfirmationSignal() {
Mood.None,
"Yes, retire from this game",
"No, let me keep playing",
- () => OnRetire(),
+ () => { },
+ // Wait for this popup to close before showing the defeat popup
+ yesCallback: () => EmitRetireDefeatSignal(),
+ hSize: 500
+ )
+ ));
+ }
+
+ ///
+ /// Shown after the player confirms retiring, matching the base game's "We are disgraced!" popup.
+ /// Dismissing it returns to the main menu.
+ ///
+ private void EmitRetireDefeatSignal() {
+ var elapsed = TimeSpan.FromSeconds(EngineStorage.gameData.timePlayedSeconds);
+ var message = "You have suffered a humiliating loss.\n\n"
+ + $"Time Spent: {Pluralize((int)elapsed.TotalHours, "hour")}, "
+ + $"{Pluralize(elapsed.Minutes, "minute")}, and {Pluralize(elapsed.Seconds, "second")}.";
+
+ EmitSignal(SignalName.InteractivePopUp, new ParameterWrapper(
+ new InformationPopup(
+ controller.id,
+ "We are disgraced!",
+ message,
+ Advisor.None,
+ Mood.None,
+ hSize: 375,
+ margins: new Margins(top: 50),
+ onConfirm: () => {
+ // TODO: Show the end-of-game score graphs here once they exist (see OnRetire)
+ OnRetire();
+ }
+ ) { disallowEscape = true }
+ ));
+ }
+
+ private static string Pluralize(int count, string noun) {
+ return $"{count} {noun}{(count == 1 ? "" : "s")}";
+ }
+
+ public void EmitNewGameConfirmationSignal() {
+ var message = "Leave this game and start a new one? All progress since your last save will be lost.";
+
+ EmitSignal(SignalName.InteractivePopUp, new ParameterWrapper(
+ new ConfirmPopUp(
+ controller.id,
+ "Do you want to start a new game?",
+ message,
+ Advisor.None,
+ Mood.None,
+ "Yes, start a new game",
+ "No, let me keep playing",
+ () => OnNewGame(),
hSize: 500
)
));
@@ -310,10 +365,17 @@ public void EmitCivilizationDestroyedSignal(MsgCivilizationDestroyed msg) {
}
private void EmitDefeatSignal(ID playerId) {
+ // TODO: Consider adding the time played (gameData.timePlayedSeconds) to this popup's message.
+ // It is currently only shown on the "We are disgraced!" popup (see EmitRetireDefeatSignal).
var options = new List() {
new ButtonAction() {
message = "Return to the main menu",
- action = () => OnRetire()
+ // Wait for this popup to close before showing the defeat popup, otherwise
+ // closing this one would also close the new one.
+ action = async () => {
+ await EngineStorage.WaitForMessageToEngine();
+ EmitRetireDefeatSignal();
+ }
},
new ButtonAction() {
message = "Let the game play on without me",
@@ -332,7 +394,7 @@ private void EmitDefeatSignal(ID playerId) {
Mood.Sad,
hSize: 600,
margins: new Margins(top: 100)
- ) { hasCancel = false }
+ ) { hasCancel = false, disallowEscape = true }
));
}
@@ -731,6 +793,8 @@ private void EmitDisbandUnitConfirmationSignal(MsgDisbandUnitConfirmation msg) {
}
private void EmitVictorySignal(MsgVictory msg) {
+ // TODO: Consider adding the time played (gameData.timePlayedSeconds) to this popup's message,
+ // sharing the formatting used by EmitRetireDefeatSignal.
var endMsg =
$"The {msg.winner.civilization.noun} have won a {msg.victory.Header()} victory!\n"
+ "This game is over: No further score will be entered.\n\n";
@@ -740,6 +804,7 @@ private void EmitVictorySignal(MsgVictory msg) {
var options = new List {
new ButtonAction() {
message = "Good! I’m Done!",
+ // TODO: Show the victory screen and end-of-game score graphs here once they exist (see OnRetire)
action = () => OnRetire()
},
new ButtonAction() {
diff --git a/C7/UIElements/Popups/GameMenu.cs b/C7/UIElements/Popups/GameMenu.cs
index e7929d870..9d23aca34 100644
--- a/C7/UIElements/Popups/GameMenu.cs
+++ b/C7/UIElements/Popups/GameMenu.cs
@@ -22,7 +22,7 @@ public override void _Ready() {
Tuple[] buttons = [
new("Map", ShowMap),
new("Load Game", Load),
- // new("New Game (Ctrl-Shift-Q)", NewGame),
+ new("New Game (Ctrl-Shift-Q)", NewGame),
// TODO: Quick Start?
new("Preferences (Ctrl-P)", OpenPreferences),
new("Retire", Retire),
@@ -63,7 +63,7 @@ private void Quit() {
}
private void NewGame() {
- // TODO: Wire to a NewGame scene
+ GetParent().EmitSignal(PopupOverlay.SignalName.NewGame);
}
private void OpenPreferences() {
diff --git a/C7/UIElements/Popups/InformationPopup.cs b/C7/UIElements/Popups/InformationPopup.cs
index cbcdade16..c2520add6 100644
--- a/C7/UIElements/Popups/InformationPopup.cs
+++ b/C7/UIElements/Popups/InformationPopup.cs
@@ -1,3 +1,4 @@
+using System;
using C7GameData;
using Serilog;
using static AdvisorHead;
@@ -15,8 +16,10 @@ public class InformationPopup : InteractablePopUp {
public InformationPopup(
ID controllerId, string header, string message,
Advisor advisor, Mood mood, int hSize = 400,
- LayoutPreset layoutPreset = DEFAULT_LAYOUT_PRESET, Margins margins = null)
+ LayoutPreset layoutPreset = DEFAULT_LAYOUT_PRESET, Margins margins = null,
+ Action onConfirm = null)
: base(controllerId, header, layoutPreset, margins) {
+ this.confirmAction = onConfirm;
this.controllerId = controllerId;
this.hSize = hSize;
this.message = message;
diff --git a/C7/UIElements/Popups/InteractablePopUp.cs b/C7/UIElements/Popups/InteractablePopUp.cs
index b70225e03..9e5f706f3 100644
--- a/C7/UIElements/Popups/InteractablePopUp.cs
+++ b/C7/UIElements/Popups/InteractablePopUp.cs
@@ -24,6 +24,10 @@ public class InteractablePopUp {
public List buttonActions { get; init; }
public bool hasConfirm { get; init; }
public bool hasCancel { get; init; }
+ // When true, Esc won't dismiss the popup, so the player has to choose one of its options
+ public bool disallowEscape { get; init; }
+ // Invoked after the popup has closed because the player pressed the confirm (OK) button or Enter
+ public Action confirmAction { get; init; }
protected InteractablePopUp(ID controllerId, string header, LayoutPreset layoutPreset, Margins margins) {
this.controllerId = controllerId;
diff --git a/C7/UIElements/Popups/InteractablePopUpController.cs b/C7/UIElements/Popups/InteractablePopUpController.cs
index 678d9e5ea..6a96cc90e 100644
--- a/C7/UIElements/Popups/InteractablePopUpController.cs
+++ b/C7/UIElements/Popups/InteractablePopUpController.cs
@@ -43,6 +43,10 @@ public partial class InteractablePopUpController : Control {
private LayoutPreset layoutPreset = DEFAULT_LAYOUT_PRESET;
private LineEditComponent lineEditComponent;
+ private Action confirmAction;
+
+ // Whether Esc may dismiss the popup that is currently showing
+ public bool CanDismissWithEscape { get; private set; } = true;
private float defaultOffsetTop;
private float defaultOffsetBottom;
@@ -82,6 +86,22 @@ public override void _Ready() {
this.confirm.Pressed += this.OnConfirm;
this.cancel.Pressed += this.OnCancel;
this.lineEdit.TextSubmitted += this.LineTextSubmitted;
+ this.mainBgContainer.Resized += this.RefreshBackground;
+ }
+
+ // The message label finishes wrapping (and so changes the content height) after the popup is first shown.
+ // Redraw the background whenever the content resizes, otherwise the box can end up shorter than its
+ // content and leave the confirm button hanging below it.
+ private void RefreshBackground() {
+ if (!this.Visible || this.bgTextureRect.Texture == null) {
+ return;
+ }
+
+ int width = (int)this.mainBgContainer.GetSize().X;
+ int height = (int)this.mainBgContainer.GetSize().Y;
+ if (width > 0 && height > 0) {
+ this.bgTextureRect.Texture = this.CreateTextureBackGround(width, height);
+ }
}
// An intermediary method so that we can edit and submit text without having to grab/release focus
@@ -91,8 +111,11 @@ private void LineTextSubmitted(string text) {
public override void _UnhandledInput(InputEvent @event) {
base._UnhandledInput(@event);
- if (this.Visible && @event is InputEventKey eventKey && eventKey.Pressed) {
+ // Echo events are key repeats from a held key. Ignoring them means only a fresh key press acts, so
+ // the Enter that confirmed the previous popup can't also confirm the popup that replaces it.
+ if (this.Visible && @event is InputEventKey eventKey && eventKey.Pressed && !eventKey.Echo) {
if (eventKey.Keycode == Key.Enter || eventKey.Keycode == Key.KpEnter) {
+ GetViewport().SetInputAsHandled();
this.OnConfirm();
}
if (eventKey.Keycode == Key.Up) {
@@ -148,6 +171,8 @@ private async void OnShowInteractablePopUpLocked(InteractablePopUp value) {
this.mainTextContainer.Visible = true;
this.mainTextLabel.Visible = true;
this.mainTextLabel.Text = value.message;
+ this.confirmAction = value.confirmAction;
+ this.CanDismissWithEscape = !value.disallowEscape;
if (string.IsNullOrEmpty(this.mainTextLabel.Text)) {
this.mainTextContainer.Visible = false;
@@ -281,10 +306,15 @@ private void OnConfirm() {
this.lineEditComponent.callback.Invoke(this.lineEdit.Text.StripEdges());
}
+ // Take the action before closing, since closing clears it
+ Action action = this.confirmAction;
+
this.audioManager.PlayUIAudio("buttons.button_ok");
this.Hide();
this.CloseAndDelete();
new MsgUiDisengaged().send();
+
+ action?.Invoke();
}
private void AddCancelButton() {
@@ -328,6 +358,8 @@ private void CloseAndDelete() {
this.advisorTextureRect.Texture = null;
this.lineEditContainer.Hide();
this.lineEditComponent = null;
+ this.confirmAction = null;
+ this.CanDismissWithEscape = true;
foreach (var child in buttonContainer.GetChildren()) {
buttonContainer.RemoveChild(child);
@@ -342,6 +374,7 @@ public override void _ExitTree() {
base._ExitTree();
this.confirm.Pressed -= this.OnConfirm;
this.cancel.Pressed -= this.OnCancel;
+ this.mainBgContainer.Resized -= this.RefreshBackground;
}
const int HTILE_SIZE = 61;
diff --git a/C7/UIElements/Popups/PopupOverlay.cs b/C7/UIElements/Popups/PopupOverlay.cs
index 6b5f2cb20..75122af13 100644
--- a/C7/UIElements/Popups/PopupOverlay.cs
+++ b/C7/UIElements/Popups/PopupOverlay.cs
@@ -21,6 +21,7 @@ public partial class PopupOverlay : HBoxContainer {
[Signal] public delegate void SaveGameEventHandler();
[Signal] public delegate void LoadGameEventHandler();
[Signal] public delegate void RetireEventHandler();
+ [Signal] public delegate void NewGameEventHandler();
[Signal] public delegate void QuitEventHandler();
[Signal] public delegate void OpenPreferencesEventHandler();
diff --git a/C7/project.godot b/C7/project.godot
index a6b1f5dc5..0ef3a3cb4 100644
--- a/C7/project.godot
+++ b/C7/project.godot
@@ -70,6 +70,11 @@ retire={
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":true,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":81,"key_label":0,"unicode":113,"location":0,"echo":false,"script":null)
]
}
+new_game={
+"deadzone": 0.5,
+"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":true,"ctrl_pressed":true,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":81,"key_label":0,"unicode":113,"location":0,"echo":false,"script":null)
+]
+}
open_game_menu={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":true,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":77,"key_label":0,"unicode":109,"location":0,"echo":false,"script":null)
diff --git a/C7Engine/Actions.cs b/C7Engine/Actions.cs
index 15d518c7b..e122d0d99 100644
--- a/C7Engine/Actions.cs
+++ b/C7Engine/Actions.cs
@@ -28,6 +28,7 @@ public static class C7Action {
public const string SaveGame = "save_game"; // Ctrl-S
public const string LoadGame = "load_game"; // Ctrl-L
public const string Retire = "retire"; // Ctrl-Q
+ public const string NewGame = "new_game"; // Ctrl-Shift-Q
public const string ShowDomesticAdvisor = "show_domestic_advisor"; // F1
public const string ShowTradeAdvisor = "show_trade_advisor";
diff --git a/C7Engine/C7GameData/GameData.cs b/C7Engine/C7GameData/GameData.cs
index 37a782174..98615aa43 100644
--- a/C7Engine/C7GameData/GameData.cs
+++ b/C7Engine/C7GameData/GameData.cs
@@ -72,6 +72,10 @@ public class GameData {
public int healRateInHostileField;
public int healRateInCity;
+ // Real-world time the player has spent in this game, accumulated by the UI
+ // and persisted across saves and loads.
+ public double timePlayedSeconds = 0;
+
public bool observerMode = false;
public bool showGridCoordinates = false;
public bool revealMap = false;
diff --git a/C7Engine/C7GameData/Save/SaveGame.cs b/C7Engine/C7GameData/Save/SaveGame.cs
index 928e5ffec..c728e0d3c 100644
--- a/C7Engine/C7GameData/Save/SaveGame.cs
+++ b/C7Engine/C7GameData/Save/SaveGame.cs
@@ -55,6 +55,7 @@ public static SaveGame FromGameData(GameData data) {
Seed = data.seed,
WorldCharacteristics = data.worldCharacteristics,
TurnNumber = data.turn,
+ TimePlayedSeconds = data.timePlayedSeconds,
Civilizations = data.civilizations,
CultureGroups = data.cultureGroups,
Alliances = data.alliances,
@@ -237,6 +238,7 @@ private GameData InitializeGameData() {
// copy data without references
var data = new GameData(Seed) {
turn = TurnNumber,
+ timePlayedSeconds = TimePlayedSeconds,
worldCharacteristics = WorldCharacteristics,
terrainTypes = TerrainTypes,
Resources = Resources,
@@ -508,6 +510,8 @@ private void ConvertAllianceWars(GameData data) {
public int Seed = -1;
public WorldCharacteristics WorldCharacteristics;
public int TurnNumber = 0;
+ // Real-world seconds the player has spent in this game. Absent in older saves, so defaults to 0.
+ public double TimePlayedSeconds = 0;
public SaveMap Map = new SaveMap();
public List TerrainTypes = new List();
public List TerrainImprovements = [];
diff --git a/EngineTests/GameData/SaveTest.cs b/EngineTests/GameData/SaveTest.cs
index e9b036be8..b336e1e36 100644
--- a/EngineTests/GameData/SaveTest.cs
+++ b/EngineTests/GameData/SaveTest.cs
@@ -310,6 +310,22 @@ public async Task SaveInObserverModeIsLoadable() {
Assert.DoesNotContain(game.players, p => p.isHuman);
}
+ [Fact]
+ public async Task TimePlayedSurvivesSaveAndLoad() {
+ await CreateHeadlessGame(fixture.saveGame);
+ WaitForStartTurnMessage();
+
+ C7GameData.GameData game = null;
+ EngineStorage.ReadGameData((C7GameData.GameData gameData) => { game = gameData; });
+ game.timePlayedSeconds = 3723.5;
+
+ string savePath = PathUtils.getDataPath("output/time-played-save.json");
+ SaveGame.FromGameData(game).Save(savePath);
+
+ C7GameData.GameData loaded = ToGameData(SaveGame.Load(savePath, (string unused) => { return unused; }, (string unused) => { return unused; }));
+ Assert.Equal(3723.5, loaded.timePlayedSeconds);
+ }
+
[Fact]
public async Task WorldWrapDetails() {
Player human = await CreateHeadlessGame(fixture.saveGame);