Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions C7/C7Game.tscn
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
37 changes: 26 additions & 11 deletions C7/Game.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -1175,6 +1185,11 @@ private void ProcessAction(string currentAction) {
return;
}

if (currentAction == C7Action.NewGame) {
EmitNewGameConfirmationSignal();
return;
}

if (currentAction == C7Action.Retire) {
EmitRetireConfirmationSignal();
return;
Expand Down
73 changes: 69 additions & 4 deletions C7/Game_EmitMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)",
Expand Down Expand Up @@ -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
)
));
}

/// <summary>
/// Shown after the player confirms retiring, matching the base game's "We are disgraced!" popup.
/// Dismissing it returns to the main menu.
/// </summary>
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<InteractablePopUp>(
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<InteractablePopUp>(
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
)
));
Expand Down Expand Up @@ -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<ButtonAction>() {
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<MsgUiDisengaged>();
EmitRetireDefeatSignal();
}
},
new ButtonAction() {
message = "Let the game play on without me",
Expand All @@ -332,7 +394,7 @@ private void EmitDefeatSignal(ID playerId) {
Mood.Sad,
hSize: 600,
margins: new Margins(top: 100)
) { hasCancel = false }
) { hasCancel = false, disallowEscape = true }
));
}

Expand Down Expand Up @@ -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";
Expand All @@ -740,6 +804,7 @@ private void EmitVictorySignal(MsgVictory msg) {
var options = new List<ButtonAction> {
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() {
Expand Down
4 changes: 2 additions & 2 deletions C7/UIElements/Popups/GameMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public override void _Ready() {
Tuple<string, Action>[] 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),
Expand Down Expand Up @@ -63,7 +63,7 @@ private void Quit() {
}

private void NewGame() {
// TODO: Wire to a NewGame scene
GetParent().EmitSignal(PopupOverlay.SignalName.NewGame);
}

private void OpenPreferences() {
Expand Down
5 changes: 4 additions & 1 deletion C7/UIElements/Popups/InformationPopup.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using C7GameData;
using Serilog;
using static AdvisorHead;
Expand All @@ -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;
Expand Down
4 changes: 4 additions & 0 deletions C7/UIElements/Popups/InteractablePopUp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ public class InteractablePopUp {
public List<ButtonAction> 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;
Expand Down
35 changes: 34 additions & 1 deletion C7/UIElements/Popups/InteractablePopUpController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down Expand 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;
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions C7/UIElements/Popups/PopupOverlay.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
5 changes: 5 additions & 0 deletions C7/project.godot
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions C7Engine/Actions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
4 changes: 4 additions & 0 deletions C7Engine/C7GameData/GameData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading