TextRPG/scenes/ConsoleUI.cs

233 lines
7.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Godot;
using System;
using System.Collections.Generic;
using TextRPG.Commands;
using TextRPG.PlayerSystem;
public partial class ConsoleUI : CanvasLayer
{
private Player player;
// UI Elements
private RichTextLabel consoleOutput;
private LineEdit consoleInput;
// Command History
private List<string> commandHistory = new List<string>();
private int historyIndex = -1;
public override void _Ready()
{
// Get UI references
consoleOutput = FindChild("ConsoleOutput", true, false) as RichTextLabel;
consoleInput = FindChild("ConsoleInput", true, false) as LineEdit;
if (consoleOutput == null || consoleInput == null)
{
GD.PrintErr("Failed to find console nodes!");
return;
}
// DON'T use SetAnchorsAndOffsetsPreset with containers
// Instead, let the containers work naturally
// Configure the VBoxContainer to expand and fill
var vbox = consoleOutput.GetParent() as VBoxContainer;
if (vbox != null)
{
vbox.SizeFlagsVertical = Control.SizeFlags.ExpandFill;
vbox.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
vbox.AnchorRight = 1;
vbox.AnchorBottom = 1;
}
// Make the console output expand to fill available space
consoleOutput.SizeFlagsVertical = Control.SizeFlags.ExpandFill;
consoleOutput.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
// Set the LineEdit to not expand vertically (fixed height)
consoleInput.SizeFlagsVertical = Control.SizeFlags.ShrinkCenter;
consoleInput.CustomMinimumSize = new Vector2(0, 35);
// Configure the console
SetupConsole();
// Connect signals
consoleInput.TextSubmitted += OnTextSubmitted;
consoleInput.GuiInput += OnGuiInput;
// Set initial focus
Callable.From(() => consoleInput.GrabFocus()).CallDeferred();
// Display welcome message
DisplayWelcomeMessage();
player = GetNode<Player>("/root/Player");
if (player != null)
{
player.HealthChanged += OnPlayerHealthChanged;
player.PlayerDied += OnPlayerDied;
player.InventoryChanged += OnInventoryChanged;
}
}
private void OnPlayerHealthChanged(int current, int max)
{
AddToConsole($"[color=orange]Health changed: {current}/{max}[/color]");
}
private void OnPlayerDied()
{
AddToConsole("[color=red]You have died... Game Over.[/color]");
// Optionally disable input or reload
}
private void OnInventoryChanged()
{
// Optional: show a subtle message or nothing you decide
// AddToConsole("[dim]Inventory updated.[/dim]");
}
private void SetupConsole()
{
// Enable BBCode
consoleOutput.BbcodeEnabled = true;
// CRITICAL FOR NEWLINES AND WRAPPING:
consoleOutput.AutowrapMode = TextServer.AutowrapMode.Word;
consoleOutput.SizeFlagsVertical = Control.SizeFlags.ExpandFill;
// Make sure newlines are preserved
consoleOutput.ScrollFollowing = true;
consoleOutput.ScrollActive = true;
consoleOutput.SelectionEnabled = true;
consoleOutput.FitContent = false; // Keep false - this is important!
// Styling
var styleBox = new StyleBoxFlat();
styleBox.BgColor = new Color(0.08f, 0.08f, 0.12f);
styleBox.SetCornerRadiusAll(5);
consoleOutput.AddThemeStyleboxOverride("normal", styleBox);
consoleOutput.AddThemeColorOverride("default_color", new Color(0.8f, 0.8f, 0.9f));
var lineEditStyle = new StyleBoxFlat();
lineEditStyle.BgColor = new Color(0.05f, 0.05f, 0.08f);
lineEditStyle.SetCornerRadiusAll(5);
consoleInput.AddThemeStyleboxOverride("normal", lineEditStyle);
consoleInput.AddThemeColorOverride("font_color", new Color(0.9f, 0.9f, 1.0f));
consoleInput.AddThemeColorOverride("caret_color", new Color(0.9f, 0.9f, 1.0f));
}
private void PrintFullTree(Node node, int depth)
{
string indent = new string(' ', depth * 2);
GD.Print($"{indent}{node.Name} ({node.GetType().Name}) - Path: {node.GetPath()}");
foreach (Node child in node.GetChildren())
{
PrintFullTree(child, depth + 1);
}
}
private void DisplayWelcomeMessage()
{
AddToConsole("Welcome!");
AddToConsole("Test");
}
private void OnTextSubmitted(string submittedText)
{
if (string.IsNullOrWhiteSpace(submittedText))
{
consoleInput.Clear();
return;
}
// Add to command history
commandHistory.Add(submittedText);
historyIndex = commandHistory.Count;
// Echo the command
AddToConsole($"[color=yellow]>>[/color] {submittedText}");
// Execute the command using ConsoleManager
bool commandExecuted = ConsoleManager.Execute(submittedText, (output) =>
{
if (output == "CLEAR_CONSOLE")
{
consoleOutput.Clear();
}
else
{
AddToConsole(output);
}
});
if (!commandExecuted)
{
AddToConsole($"[color=red]Unknown command.[/color] Type 'help' for available commands.");
}
consoleInput.Clear();
Callable.From(() => consoleInput.GrabFocus()).CallDeferred();
}
private void OnGuiInput(InputEvent @event)
{
if (@event is InputEventKey key && key.Pressed)
{
if (key.Keycode == Key.Up)
{
if (commandHistory.Count > 0 && historyIndex > 0)
{
historyIndex--;
consoleInput.Text = commandHistory[historyIndex];
consoleInput.CaretColumn = consoleInput.Text.Length;
}
GetViewport().SetInputAsHandled();
}
else if (key.Keycode == Key.Down)
{
if (historyIndex < commandHistory.Count - 1)
{
historyIndex++;
consoleInput.Text = commandHistory[historyIndex];
consoleInput.CaretColumn = consoleInput.Text.Length;
}
else if (historyIndex == commandHistory.Count - 1)
{
historyIndex = commandHistory.Count;
consoleInput.Text = "";
}
GetViewport().SetInputAsHandled();
}
}
}
private void AddToConsole(string text)
{
// Force a newline before adding if console already has text
if (!string.IsNullOrEmpty(consoleOutput.Text))
{
consoleOutput.AppendText("\n");
}
// Add the text
consoleOutput.AppendText(text + "\n");
// Force scroll to bottom
consoleOutput.ScrollToLine(consoleOutput.GetLineCount() - 1);
}
public void LogMessage(string message, string color = "white")
{
AddToConsole($"[color={color}]{message}[/color]");
}
public void ClearConsole()
{
consoleOutput.Clear();
}
}