Monogame - 创建CheckBox对象

时间:2016-03-01 16:49:57

标签: c# checkbox monogame

我一直在为我的游戏制作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.

最后,我在CheckBoxGUI中使用TitleScreen课程的方式如下:

// 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的不同功能......但是,当我测试这个时,如果我打开窗户并检查窗口关闭窗口并再次打开。 IsOpen类的WindowGUI成员通过类中的if语句控制窗口是否可见。 Draw()方法。

如果我尝试使用复选框的其他示例,也会发生同样的事情......一旦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);

2 个答案:

答案 0 :(得分:1)

听起来你正在努力解决的主要问题是如何实现事件。所以我将用一个非常简单的例子来讨论它。

想象一下,我们想要实现一个简单的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);

但那是另一个故事。

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

答案 1 :(得分:1)

作为@craftworkgames建议的替代方法,您还可以通过复选框构造函数传递委托,并直接调用它。这与事件的区别是微不足道的;一个事件基本上是一个代表列表(即函数的托管指针),以及&#34;触发一个事件&#34;只需连续调用您附加的所有处理程序(使用+=)。使用事件将提供更统一的方式(至少对.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类

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

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

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.Update)来检查是否单击了
    • 如果单击,则更改其状态,可视属性并触发事件

如果你做得对,你应该在你的屏幕类中有一个 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);