From ced3d03bdb3ce866d832e03fb212865140905a9a Mon Sep 17 00:00:00 2001 From: Thomas Leyh Date: Sun, 24 Jul 2016 08:14:18 +0200 Subject: Add project files. --- V3/Widgets/AbstractMenu.cs | 96 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 V3/Widgets/AbstractMenu.cs (limited to 'V3/Widgets/AbstractMenu.cs') diff --git a/V3/Widgets/AbstractMenu.cs b/V3/Widgets/AbstractMenu.cs new file mode 100644 index 0000000..f179b5e --- /dev/null +++ b/V3/Widgets/AbstractMenu.cs @@ -0,0 +1,96 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using System.Collections.Generic; +using System.Linq; +using V3.Input; + +namespace V3.Widgets +{ + /// + /// An abstract menu that handles the updating and drawing of widgtes. + /// + public abstract class AbstractMenu : IMenu + { + public List Widgets { get; } = new List(); + public Vector2 Size { get; private set; } + public Vector2 Position { get; private set; } + + private readonly GraphicsDeviceManager mGraphicsDeviceManager; + + protected AbstractMenu(GraphicsDeviceManager graphicsDeviceManager) + { + mGraphicsDeviceManager = graphicsDeviceManager; + } + + public void HandleMouseEvent(IMouseEvent mouseEvent) + { + foreach (var clickable in Widgets.OfType()) + clickable.HandleMouseEvent(mouseEvent); + } + + public void Draw(SpriteBatch spriteBatch) + { + UpdateWidgetRelativePositions(); + UpdateWidgetAbsolutePositions(); + spriteBatch.Begin(); + Widgets.ForEach(w => w.Draw(spriteBatch)); + spriteBatch.End(); + } + + public void Update() + { + ResetClicked(); + UpdateMouseSelection(); + UpdateWidgetSizes(); + } + + protected abstract void UpdateWidgetSizes(); + + protected abstract void UpdateWidgetRelativePositions(); + + protected abstract Vector2 GetTotalSize(); + + private void UpdateWidgetAbsolutePositions() + { + var viewport = mGraphicsDeviceManager.GraphicsDevice.Viewport; + Size = GetTotalSize(); + var viewportSize = new Vector2(viewport.Bounds.Width, viewport.Bounds.Height); + Position = (viewportSize - Size) / 2; + Widgets.ForEach(w => w.Position = w.Position + Position); + } + + private void ResetClicked() + { + foreach (var clickable in Widgets.OfType()) + clickable.IsClicked = false; + } + + private void UpdateMouseSelection() + { + var position = Mouse.GetState().Position; + foreach (var selectable in Widgets.OfType()) + selectable.IsSelected = selectable.CheckSelected(position); + } + + protected static void MakeWidgetsSameSize(IEnumerable widgets) + { + var xMax = 0f; + var yMax = 0f; + + var widgetsCopy = widgets as IList ?? widgets.ToList(); + foreach (var widget in widgetsCopy) + { + var size = widget.GetMinimumSize(); + if (size.X > xMax) + xMax = size.X; + if (size.Y > yMax) + yMax = size.Y; + } + + var sizeMax = new Vector2(xMax, yMax); + foreach (var widget in widgetsCopy) + widget.Size = sizeMax; + } + } +} -- cgit v1.2.1