单游戏 - 创建复选框对象

本文关键字:创建 复选框 对象 游戏 单游戏 | 更新日期: 2023-09-27 18:37:04

我一直在为我的游戏开发GUI。到目前为止,我已经使用代码来创建看起来像"表单"的对象(不要与winforms混淆,我使用的是monogame)。我还创建了按钮。但是现在我很难创建复选框。这是我的CheckBoxGUI课:

// take a look into the recent edits for this post if you need to see my old code.

我的TextOutliner课曾经用边框/轮廓绘制文本:

// take a look into the recent edits for this post if you need to see my old code.

最后,这是我如何在TitleScreen中使用CheckBoxGUI类:

// take a look into the recent edits for this post if you need to see my old code.

这是我的问题(至少我认为在处理复选框逻辑的方法中

):
// take a look into the recent edits for this post if you need to see my old code.

最后,Draw()

// take a look into the recent edits for this post if you need to see my old code.

因此,CheckBoxInputTS的方法允许我通过单击鼠标来选中/取消选中 CheckBoxGUI 项目,但我实际上无法为此附加任何功能。例如,我可以在同一方法中执行以下操作:

// take a look into the recent edits for this post if you need to see my old code.

也许我错过了一些简单的东西,或者我不明白如何实际对我已经必须的代码进行进一步改进,以使其支持checkBoxes的不同功能......但是,当我对此进行测试时,如果我打开窗口并选中该框,窗口会粘住并且不会再次打开。WindowGUI类的IsOpen成员通过类的 Draw() 方法中的 if 语句控制窗口是否可见。

如果我尝试为复选框使用其他示例,也会发生同样的事情......一旦checkBox.IsChecked有一个用户给定的值,我就无法更改它。

如果有人能找到我做错了什么并帮助我清理此代码,将不胜感激。提前感谢!

编辑:根据提议的答案,这是我到目前为止所拥有的:

public class CheckBoxGUI : GUIElement
{
    Texture2D checkBoxTexEmpty, checkBoxTexSelected;
    public Rectangle CheckBoxTxtRect { get; set; }
    public Rectangle CheckBoxMiddleRect { get; set; }
    public bool IsChecked { get; set; }
    public event Action<CheckBoxGUI> CheckedChanged;
    public CheckBoxGUI(Rectangle rectangle, string text, bool isDisabled, ContentManager content)
    : base(rectangle, text, isDisabled, content)
    {
        CheckBoxTxtRect = new Rectangle((Bounds.X + 19), (Bounds.Y - 3), ((int)FontName.MeasureString(Text).X), ((int)FontName.MeasureString(Text).Y));
        CheckBoxMiddleRect = new Rectangle((Bounds.X + 16), Bounds.Y, 4, 16);
        if (checkBoxTexEmpty == null) checkBoxTexEmpty = content.Load<Texture2D>(Game1.CheckBoxPath + @"0") as Texture2D;
        if (checkBoxTexSelected == null) checkBoxTexSelected = content.Load<Texture2D>(Game1.CheckBoxPath + @"1") as Texture2D;
    }
    public void OnCheckedChanged()
    {
        var h = CheckedChanged;
        if (h != null)
            h(this);
    }
    public override void UnloadContent()
    {
        base.UnloadContent();
        if (checkBoxTexEmpty != null) checkBoxTexEmpty = null;
        if (checkBoxTexSelected != null) checkBoxTexSelected = null;
    }
    public override void Update(GameTime gameTime)
    {
        base.Update(gameTime);
        if (!Game1.IsSoundDisabled)
        {
            if ((IsHovered) && (!IsDisabled))
            {
                if (InputManager.IsLeftClicked())
                {
                    ClickSFX.Play();
                    IsHovered = false;
                }
            }
        }
        if (IsClicked) OnCheckedChanged();
    }
    public void Draw(SpriteBatch spriteBatch)
    {
        if ((FontName != null) && ((Text != string.Empty) && (Text != null)))
        {
            if (IsChecked) spriteBatch.Draw(checkBoxTexSelected, Bounds, Color.White);
            else if (IsDisabled) spriteBatch.Draw(checkBoxTexEmpty, Bounds, Color.Gray);
            else spriteBatch.Draw(checkBoxTexEmpty, Bounds, Color.Gray);
            TextOutliner.DrawBorderedText(spriteBatch, FontName, Text, CheckBoxTxtRect.X, CheckBoxTxtRect.Y, ForeColor);
        }
    }
}

然后是GUIElement类:

public abstract class GUIElement
{
    protected SpriteFont FontName { get; set; }
    protected string Text { get; set; }
    protected SoundEffect ClickSFX { get; set; }
    public Rectangle Bounds { get; set; }
    public Color ForeColor { get; set; }
    public Color BackColor { get; set; }
    public bool IsDisabled { get; set; }
    public bool IsHovered { get; set; }
    public bool IsClicked { get; set; }
    public GUIElement(Rectangle newBounds, string newText, bool isDisabled, ContentManager content)
    {
        Bounds = newBounds;
        Text = newText;
        IsDisabled = isDisabled;
        FontName = Game1.GameFontSmall;
        ForeColor = Color.White;
        BackColor = Color.White;
        ClickSFX = content.Load<SoundEffect>(Game1.BGSoundPath + @"1") as SoundEffect;
    }
    public virtual void UnloadContent()
    {
        if (Bounds != Rectangle.Empty) Bounds = Rectangle.Empty;
        if (FontName != null) FontName = null;
        if (Text != string.Empty) Text = string.Empty;
        if (ClickSFX != null) ClickSFX = null;
    }
    public virtual void Update(GameTime gameTime)
    {
        if (!IsDisabled)
        {
            if (Bounds.Contains(InputManager.MouseRect))
            {
                if (InputManager.IsLeftClicked()) IsClicked = true;
                ForeColor = Color.Yellow;
                IsHovered = true;
            }
            else if (!Bounds.Contains(InputManager.MouseRect))
            {
                IsHovered = false;
                ForeColor = Color.White;
            }
        }
        else ForeColor = Color.Gray;
    }
}

这是我的用法:

// Fields
readonly List<GUIElement> elements = new List<GUIElement>();
CheckBoxGUI chk;
bool check = true;
string text;
// LoadContent()
chk = new CheckBoxGUI(new Rectangle(800, 200, 16, 16), "Hide FPS", false, content);
chk.CheckedChanged += cb => check = cb.IsChecked;
elements.Add(chk);
// UnloadContent()
foreach (GUIElement element in elements) element.UnloadContent();
// Update()
for (int i = 0; i < elements.Count; i++) elements[i].Update(gameTime);
foreach (CheckBoxGUI chk in elements) chk.Update(gameTime);
// Draw()
if (chk.IsChecked) check = true;
else check = false;
if (check) text = "True";
else text = "False";
spriteBatch.DrawString(Game1.GameFontLarge, text, new Vector2(800, 400), Color.White);
if (optionsWindow.IsOpen) chk.Draw(spriteBatch);

单游戏 - 创建复选框对象

作为@craftworkgames建议的替代方法,您还可以通过复选框构造函数传递委托,并直接调用它。这与事件之间的差异是微不足道的;事件基本上是一个委托列表(即指向函数的托管指针),"触发事件"只是连续调用您附加的所有处理程序(使用 +=)。使用事件将提供更统一的方式(至少对 .NET 开发人员来说更舒适),但我也会在我的答案中提到其他一些方面。

这是一般的想法:

public class CheckBoxGUI : GUIElement
{
    public bool IsChecked { get; set; }
    // instead of using the event, you can use a single delegate
    readonly Action<CheckBoxGUI> OnCheckedChanged;
    public CheckBoxGUI(Action<CheckBoxGUI> onCheckedChanged, Rectangle rectangle)
        : base(rectangle) // we need to pass the rectangle to the base class
    {
        OnCheckedChanged = onCheckedChanged;
    }
    public override bool Update(GameTime gameTime, InputState inputState)
    {
        if (WasClicked(inputState)) // imaginary method
        {
            // if we are here, it means we need to handle the inputState
            IsChecked = !IsChecked;
            // this method will be invoked 
            OnCheckedChanged(this);
            return true;
        } 
        else 
        {
            return false;
        }
    }
    ... drawing methods, load/unload content
}

当您实例化该复选框时,您只需传递一个匿名方法,该方法将在状态更改时调用:

var checkbox = new CheckBoxGUI(
    // when state is changed, `win.IsOpen` will be set to a new value
    cb => win.IsOpen = cb.IsChecked, 
    new Rectangle(0, 0, 100, 100)
);

(顺便说一句,这种方法与事件之间的差异可以忽略不计:)

// if you had a 'CheckedChanged' event, instantiation would look something like this
var checkbox = new CheckBoxGUI(...);
checkbox.CheckedChanged += cb => win.IsOpen = cb.IsChecked;

创建具有共享功能的基 gui 类

我还会将大多数功能提取到基类中。这与类作为 WinForms 中的基类存在的原因相同Control除非您使用基类,否则您将一遍又一遍地重复此操作。

如果没有别的,所有元素都有一个边框和相同的检查鼠标单击的方法:

public class GUIElement
{
    public Rectangle Bounds { get; set; }
    public GUIElement(Rectangle rect)
    {
        Bounds = rect;
    }
    public virtual bool Update(GameTime game, InputState inputState)
    {
        // if another element already handled this click,
        // no need to bother
        if (inputState.Handled)
            return false;           
        // you should actually check if mouse was both clicked and released 
        // within these bounds, but this is just a demo:
        if (!inputState.Pressed)
            return false;
        // within bounds?
        if (!this.Bounds.Contains(inputState.Position))
            return false;
        // mark as handled: we don't want this event to 
        // propagate further
        inputState.Handled = true;
        return true;
    }
    public virtual void Draw(GameTime gameTime, SpriteBatch sb) { }
}

当您决定要在鼠标向上事件时触发鼠标单击时(就像通常所做的那样),代码中只有一个位置应该发生此更改。

顺便说一句,这个类还应该实现所有 UI 元素之间共享的其他属性。无需通过构造函数指定其值,但必须指定默认值。这类似于WinForms的功能:

public class GUIElement
{
    public Rectangle Bounds { get; set; }
    public SpriteFont Font { get; set; }
    public Color ForeColor { get; set; }
    public Color BackColor { get; set; }
    // make sure you specify all defaults inside the constructor 
    // (except for Bounds, of course)
}

为了抽象鼠标/触摸/游戏手柄输入,我在上面使用了一个相当简单的InputState(您可能希望稍后扩展它):

public class InputState
{
    // true if this event has already been handled
    public bool Handled;
    // true if mouse is being held down 
    public bool Pressed;
    // mouse position
    public Point Position;
}

从基类继承

有了这个,你的CheckBoxGUI现在继承了GUIElement的好东西:

// this is the class from above
public class CheckBoxGUI : GUIElement
{
    public bool IsChecked { get; set; }
    readonly Action<CheckBoxGUI> OnCheckedChanged;
    public CheckBoxGUI(Action<CheckBoxGUI> onCheckedChanged, Rectangle rectangle)
        : base(rectangle) // we need to pass the rectangle to the base class
    {
        OnCheckedChanged = onCheckedChanged;
    }
    // Note that this method returns bool, unlike 'void Update'.
    // Also, intersections should be handled here, not outside.
    public override bool Update(GameTime gameTime, InputState inputState)
    {
        var handled = base.Update(gameTime, inputState);
        if (!handled)
            return false;
        // if we are here, it means we need to handle the inputState
        IsChecked = !IsChecked;
        OnCheckedChanged(this);
        return true;
    }
    ... drawing methods, load/unload content
}

您的游戏/场景类

在主游戏(或场景)更新方法开始时,只需创建InputState实例并对所有元素调用HandleInput

public void Update(GameTime gameTime)
{
    var mouse = Mouse.GetState();
    var inputState = new InputState()
    {
        Pressed = mouse.LeftButton == ButtonState.Pressed,
        Position = mouse.Position
    };
    foreach (var element in this.Elements)
    {
        element.Update(gameTime, inputState);
    }
}

基于事件的替代方案

使用基于事件的方法,可以将复选框更改为:

// this is the class from above
public class CheckBoxGUI : GUIElement
{
    public bool IsChecked { get; set; }
    public event Action<CheckBoxGUI> CheckedChanged;
    protected virtual void OnCheckedChanged()
    {
        var h = CheckedChanged;
        if (h != null)
            h(this);
    }
    public CheckBoxGUI(Rectangle rectangle)
        : base(rectangle) // we need to pass the rectangle to the base class
    { }
    // the rest of the class remains the same
}

并实例化它:

var cb = new CheckBoxGUI(new Rectangle(0, 0, 100, 100));
cb.CheckedChanged += cb => win.IsOpen = cb.IsChecked;

更新

这是您的Update调用堆栈的外观:

  • Game.Update

    • 呼叫TitleScreen.Update
  • TitleScreen.Update

    • 调用 GUI 元素element.Update(不仅仅是复选框)
  • GuiElement.Update

    • 检查是否单击了此元素(由派生类重用)
  • CheckBoxGUI.Update

    • 调用 GuiElement.Update (base.更新)以检查是否刚刚单击
    • 如果单击,则更改其状态、视觉属性并触发事件

如果你做对了,你应该在你的屏幕类中有一个 gui 元素列表,而不是实际实例。屏幕不应该知道或关心正在绘制的元素的确切类型:

readonly List<GuiElement> elements = new LIst<GuiElement>();
var chk = new CheckBoxGUI(new Rectangle(800, 200, 16, 16), "Window", false, content);
chk.CheckedChanged += cb => win.IsOpen = cb.IsChecked;
// from now on, your checkbox is just a "gui element" which knows how to
// update itself and draw itself
elements.Add(chk);
// your screen update method
foreach (var e in elements) 
    e.Update(gameTime);
// your screen draw method
foreach (var e in elements) 
    e.Draw(gameTime);

听起来您正在努力解决的主要问题是弄清楚如何实现事件。因此,我将用一个非常简单的例子来回顾这一点。

假设我们要实现一个简单的Click事件。首先在类上创建一个事件成员,如下所示:

public event EventHandler Click;

然后,在Update方法中,您需要以与播放声音效果大致相同的方式引发该事件。

public void Update(GameTime gameTime)
{
    if (!Game1.IsSoundDisabled)
    {
        if ((IsHovered) && (!IsDisabled))
            if (InputManager.Instance.IsLeftClicked())
            {
                clickSFX.Play();
                IsHovered = false;
                if(Click != null)
                    Click(this, EventArgs.Empty);
            }
    }
}

这几乎就是它的全部内容。现在可以在代码的其他部分中注册该事件。例如:

checkBox.Click += CheckBox_Click;

并像在WinForms中一样实现事件。

private void CheckBox_Click(object sender, EventArgs args)
{
    // do something when the check box is clicked.
}

您无需了解太多有关事件的信息即可开始使用。我唯一想说的是,如果线程安全是一个问题,你应该养成像这样引发事件的习惯:

var eventHandler = Click;
if(eventHandler != null)
    eventHandler(this, EventArgs.Empty);

但那是另一个时代的故事了。

关于你的代码还有很多其他的东西可以使用一些改进,但我认为这超出了这个问题的范围。如果你想获得更多关于你的代码的反馈,我建议把它发布在代码审查中。