Universal Windows Platform – Lucky Wheel

Lucky Wheel demonstrates how to create a game where you can Spin a Wheel to see how high a score you can get before you Lose.

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in the Name as LuckyWheel and select a Location and then select Ok to create the Project
vs2017-new-project-lucky-wheel

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10, version 1803 (10.0; Build 17134) which is the April 2018 Update and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-lucky-wheel

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Shapes;

namespace LuckyWheel
{
    public class WheelWedge
    {
        public string Value { get; set; }
        public Color Colour { get; set; }
        public double Sector { get; set; }

        public WheelWedge(string value, Color colour)
        {
            Value = value;
            Colour = colour;
        }
    }

    public class WheelBoard
    {
        private const double axis = 180.0;
        private const double circle = 360;
        private const double radius = 200;
        private const double diameter = 400;
        private readonly List<WheelWedge> wedges = new List<WheelWedge>()
        {
            new WheelWedge("1000", Colors.WhiteSmoke),
            new WheelWedge("600", Colors.LightGreen),
            new WheelWedge("500", Colors.Yellow),
            new WheelWedge("300", Colors.Red),
            new WheelWedge("500", Colors.Azure),
            new WheelWedge("800", Colors.Orange),
            new WheelWedge("550", Colors.Violet),
            new WheelWedge("400", Colors.Yellow),
            new WheelWedge("300", Colors.Pink),
            new WheelWedge("900", Colors.Red),
            new WheelWedge("500", Colors.Azure),
            new WheelWedge("300", Colors.LightGreen),
            new WheelWedge("900", Colors.Pink),
            new WheelWedge("LOSE", Colors.Black),
            new WheelWedge("600", Colors.Violet),
            new WheelWedge("400", Colors.Yellow),
            new WheelWedge("300", Colors.Azure),
            new WheelWedge("LOSE", Colors.Black),
            new WheelWedge("800", Colors.Red),
            new WheelWedge("350", Colors.Violet),
            new WheelWedge("450", Colors.Pink),
            new WheelWedge("700", Colors.LightGreen),
            new WheelWedge("300", Colors.Orange),
            new WheelWedge("600", Colors.Violet)
        };
        private readonly Random random = new Random((int)DateTime.Now.Ticks);

        private Storyboard _storyboard;
        private double _selected;
        private double _sector;
        private double _position;
        private Canvas _wheel;
        private int _total;
        private bool _lost;
        private bool _spin;

        public delegate void DialogHandler(string content);
        public event DialogHandler Dialog;

        private int Choose()
        {
            return random.Next(1, (int)circle);
        }

        private Path GetWedgePath(Color fill, ref double angle, double sector)
        {
            double DegreeToRadian(double degree)
            {
                return Math.PI * degree / axis;
            }
            Path path = new Path()
            {
                Fill = new SolidColorBrush(fill),
            };
            PathGeometry geometry = new PathGeometry();
            double x = Math.Cos(angle) * radius + radius;
            double y = Math.Sin(angle) * radius + radius;
            LineSegment lineOne = new LineSegment()
            {
                Point = new Point(x, y)
            };
            angle += DegreeToRadian(sector);
            x = Math.Cos(angle) * radius + radius;
            y = Math.Sin(angle) * radius + radius;
            ArcSegment arc = new ArcSegment()
            {
                RotationAngle = sector,
                Point = new Point(x, y),
                IsLargeArc = sector >= axis,
                Size = new Size(radius, radius),
                SweepDirection = SweepDirection.Clockwise,
            };
            LineSegment lineTwo = new LineSegment()
            {
                Point = new Point(radius, radius)
            };
            PathFigure figure = new PathFigure()
            {
                StartPoint = new Point(radius, radius)
            };
            figure.Segments.Add(lineOne);
            figure.Segments.Add(arc);
            figure.Segments.Add(lineTwo);
            geometry.Figures.Add(figure);
            path.Data = geometry;
            return path;
        }

        private Grid GetWedgeLabel(Color foreground, string value,
        double x, double y, ref double rotate, double sector)
        {
            Grid grid = new Grid()
            {
                Height = radius
            };
            TextBlock textblock = new TextBlock()
            {
                Text = value,
                FontSize = 20,
                Margin = new Thickness(2),
                FontWeight = FontWeights.SemiBold,
                TextAlignment = TextAlignment.Center,
                Foreground = new SolidColorBrush(foreground),
            };
            rotate += sector;
            textblock.Inlines.Clear();
            for (int i = 0; i < value.Length; i++)
            {
                textblock.Inlines.Add(new Run() { Text = value[i] + Environment.NewLine });
            }
            textblock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            double width = textblock.DesiredSize.Width;
            double left = y - (width / 2);
            grid.RenderTransform = new RotateTransform()
            {
                Angle = rotate,
                CenterY = radius,
                CenterX = width / 2
            };
            grid.Children.Add(textblock);
            Canvas.SetZIndex(grid, 99);
            Canvas.SetLeft(grid, left);
            Canvas.SetTop(grid, x);
            return grid;
        }

        private Ellipse GetCircle(Color fill, Color stroke,
            double x, double y, double dimension)
        {
            Ellipse ellipse = new Ellipse()
            {
                Width = dimension,
                Height = dimension,
                StrokeThickness = 5,
                Fill = new SolidColorBrush(fill),
                Stroke = new SolidColorBrush(stroke)
            };
            Canvas.SetLeft(ellipse, x - (dimension / 2));
            Canvas.SetTop(ellipse, y - (dimension / 2));
            return ellipse;
        }

        private Polygon GetMarker(Color fill, Color stroke, double dimension)
        {
            Polygon polygon = new Polygon
            {
                Width = dimension,
                Height = dimension,
                StrokeThickness = 5,
                Stretch = Stretch.Uniform,
                Fill = new SolidColorBrush(fill),
                StrokeLineJoin = PenLineJoin.Round,
                Stroke = new SolidColorBrush(stroke),
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center,
                Points = { new Point(0, 0), new Point(100, 0), new Point(50, 50) }
            };
            return polygon;
        }

        private WheelWedge GetWedge(double selected)
        {
            double value = circle - selected;
            return wedges.First(w => value >= w.Sector && value < (w.Sector + _sector));
        }

        private void Rotation_Completed(object sender, object e)
        {
            _spin = false;
            WheelWedge wedge = GetWedge(_selected);
            if (int.TryParse(wedge.Value, out int result) && !_lost)
            {
                Dialog?.Invoke($"You Won {result}, Total is {_total}");
                _total += result;
            }
            else
            {
                Dialog?.Invoke($"You Lose, Total was {_total}!");
                _lost = true;
            }
        }

        private void Rotation(ref Canvas wheel, double angle)
        {
            DoubleAnimation animation = new DoubleAnimation()
            {
                From = _position,
                To = (circle * 2) + angle,
                EasingFunction = new QuadraticEase(),
                RepeatBehavior = new RepeatBehavior(1),
                Duration = new Duration(TimeSpan.FromSeconds(5)),
            };
            Storyboard.SetTargetProperty(animation, "(Canvas.RenderTransform).(RotateTransform.Angle)");
            Storyboard.SetTarget(animation, wheel);
            _storyboard = new Storyboard();
            _storyboard.Completed += Rotation_Completed;
            _storyboard.Children.Add(animation);
            _storyboard.Begin();
        }

        private void Reset()
        {
            _total = 0;
            _spin = false;
            _lost = false;
            _selected = 0;
        }

        private void Wheel_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            if (!_spin)
            {
                _spin = true;
                if (_lost)
                {
                    Dialog?.Invoke($"You Lost, Total was {_total}, Starting New Game");
                    Reset();
                }
                if (!_lost)
                {
                    _position = _selected;
                    _selected = Choose();
                    Rotation(ref _wheel, _selected);
                }
            }
        }

        private Canvas GetWheel()
        {
            double current = 0;
            double total = wedges.Count;
            double angle = -(Math.PI / 2);
            _sector = (360 / total);
            _position = -(_sector / 2);
            double rotate = -(_sector / 2);
            Canvas canvas = new Canvas()
            {
                Width = diameter,
                Height = diameter,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center,
                RenderTransform = new RotateTransform()
                {
                    Angle = rotate,
                    CenterX = radius,
                    CenterY = radius
                }
            };
            canvas.Children.Add(GetCircle(Colors.Transparent, Colors.Gold, radius, radius, diameter + 10));
            foreach (WheelWedge wedge in wedges)
            {
                wedge.Sector = current;
                Path path = GetWedgePath(wedge.Colour, ref angle, _sector);
                Grid label = GetWedgeLabel(wedge.Colour == Colors.Black ? Colors.White : Colors.Black,
                wedge.Value, 0, radius, ref rotate, _sector);
                canvas.Children.Add(path);
                canvas.Children.Add(label);
                current += _sector;
            }
            canvas.Children.Add(GetCircle(Colors.Green, Colors.Gold, radius, radius, 120));
            canvas.Tapped += Wheel_Tapped;
            return canvas;
        }

        public void Layout(ref Grid grid)
        {
            grid.Children.Clear();
            _wheel = GetWheel();
            StackPanel panel = new StackPanel();
            panel.Children.Add(GetMarker(Colors.WhiteSmoke, Colors.Black, 30));
            panel.Children.Add(_wheel);
            grid.Children.Add(panel);
        }

        public void New()
        {
            Reset();
        }
    }

    public class Library
    {
        private const string app_title = "Lucky Wheel";

        private IAsyncOperation<IUICommand> _dialogCommand = null;
        private WheelBoard _board = new WheelBoard();

        private async Task<bool> ShowDialogAsync(string content, string title = app_title)
        {
            try
            {
                if (_dialogCommand != null)
                {
                    _dialogCommand.Cancel();
                    _dialogCommand = null;
                }
                _dialogCommand = new MessageDialog(content, title).ShowAsync();
                await _dialogCommand;
                return true;
            }
            catch (TaskCanceledException)
            {
                return false;
            }
        }

        private async void Board_Dialog(string content)
        {
            await ShowDialogAsync(content);
        }

        public void Init(ref Grid grid)
        {
            _board.Layout(ref grid);
            _board.Dialog += Board_Dialog;
        }

        public void New(ref Grid grid)
        {
            _board.Layout(ref grid);
            _board.New();
        }
    }
}

In the Code File for Library there are using statements to include the necessary functionality. There is a WheelWedge Class which has string, Color and double Properties.

There is a WheelBoard Class which contains the private const and private readonly for the Game including Random for selecting randomised numbers. There are also some private Members and an event for Dialog. There are also some private Methods including Choose for selecting randomised numbers between 1 and 360. The GetWedgePath Method is used to create the necessary elements to make up the layout of a Wedge of the Wheel created with a combination of LineSegment and ArcSegment Controls.

Also in the WheelBoard Class is the GetWedgeLabel which is used to return a TextBlock with the required appearance with a RotateTransform. The GetCircle Method is used to return an Ellipse with a given Color for the Stroke and Fill. The GetMarker Method is used to return a Polygon to represent a Marker for use with the Wheel

GetWedge is used to return a WheelWedge with a value between the Sector values in all the Wedges, Rotation_Completed is an Event Handler triggered when the Wheel has finished rotating and will indicate if have Won or Lost. There is a Rotation Method which will perform the rotation of the Wheel with a DoubleAnimation in a Storyboard with a QuadraticEase to make it behave more like a real “Lucky Wheel”. The Reset Method is used to reset Game values, it is also called by the New Method and there is a Wheel_Tapped Event Handler which will be triggered when the Wheel is tapped and GetWheel is used to create the look-and-feel of the Wheel itself made up of various WheelWedge and other Elements and is called from Layout

The Library Class contains a ShowDialogAsync Method to display a MessageDialog and a Board_Dialog Event Handler which will use that Method. The Init Method will initialise the look-and-feel of all the visual elements of the Game and New will start a Game.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-lucky-wheel

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<Viewbox>
	<Grid Margin="50" Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Page2" Label="New" Click="New_Click"/>
</CommandBar>

The first block of XAML is a Viewbox Control which contains a Grid Control. The second block of XAML is a CommandBar with AppBarButton for New which calls New_Click.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

protected override void OnNavigatedTo(NavigationEventArgs e)
{
	library.Init(ref Display);
}

private void New_Click(object sender, RoutedEventArgs e)
{
	library.New(ref Display);
}

There is an OnNavigatedTo Event Handler which will call the Init Method from the Library Class and New_Click which will call the New Method of the Library Class.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

Once the Application has started running you can tap on the Wheel and it will Rotate once its stops on a Value that is the amount you will win, if it lands on LOSE the Game will be over.

uwp-ran-lucky-wheel

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

This example shows how to create a Fortune Wheel Game which shows how to create the shapes of the Wedge of the Wheel, just like it’s real-life counterpart, it makes a fun game to create and play or just as the basis of a more complex Game.

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s