Universal Windows Platform – Deal or Not

Deal or Not demonstrates how to create a box-opening game where every so often there is a Deal and you can choose Not to accept it and Continue but risk winning a smaller amount – the last box at the end will be the winning amount or the Deal if you took that or you can see what the other boxes contained if you did Deal but you won’t win those!

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 a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

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-library

Step 7

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

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

public class Library
{
    private const string app_title = "Deal or Not";
    private double[] box_values =
    {
            0.01, 0.10, 0.50, 1, 5, 10, 50, 100, 250, 500, 750,
            1000, 3000, 5000, 10000, 15000, 20000, 35000, 50000, 75000, 100000, 250000
    };
    private string[] box_colors =
    {
        "0026ff", "0039ff", "004dff", "0060ff", "0073ff", "0086ff", "0099ff", "0099ff", "0099ff", "00acff", "00bfff",
        "ff5900", "ff4d00", "ff4000", "ff3300", "ff2600", "ff2600", "ff2600", "ff2600", "ff1a00", "ff1c00", "ff0d00",
    };
    private string[] box_names = {
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v"
    };

    private ContentDialog _dialog;
    static TaskCompletionSource<bool> _awaiter = new TaskCompletionSource<bool>();
    private Random _random = new Random((int)DateTime.Now.Ticks);
    private List<double> _amounts = new List<double>();
    private double _amount;
    private bool _dealt;
    private int _turn;

    private Color ConvertHexToColor(string hex)
    {
        hex = hex.Remove(0, 1);
        byte a = hex.Length == 8 ? Byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber) : (byte)255;
        byte r = Byte.Parse(hex.Substring(hex.Length - 6, 2), NumberStyles.HexNumber);
        byte g = Byte.Parse(hex.Substring(hex.Length - 4, 2), NumberStyles.HexNumber);
        byte b = Byte.Parse(hex.Substring(hex.Length - 2), NumberStyles.HexNumber);
        return Color.FromArgb(a, r, g, b);
    }

    private async Task<ContentDialogResult> ShowDialogAsync(string primary, string secondary, object content)
    {
        if (_dialog != null)
        {
            _dialog.Hide();
        }
        _dialog = new ContentDialog()
        {
            Title = app_title,
            PrimaryButtonText = primary,
            SecondaryButtonText = secondary,
            Content = content
        };
        return await _dialog.ShowAsync();
    }

    private List<int> Shuffle(int total)
    {
        return Enumerable.Range(0, total).OrderBy(r => _random.Next(0, total)).ToList();
    }

    private Grid GetAmount(double value, Color background)
    {
        Grid grid = new Grid()
        {
            Background = new SolidColorBrush(background)
        };
        TextBlock text = new TextBlock()
        {
            Text = String.Format(new CultureInfo("en-GB"), "{0:c}", value),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
            Foreground = new SolidColorBrush(Colors.White),
            Margin = new Thickness(10),
            FontSize = 33
        };
        grid.Children.Add(text);
        return grid;
    }

    private double GetOffer()
    {
        int count = 0;
        double total = 0.0;
        foreach (double amount in _amounts)
        {
            total += amount;
            count++;
        }
        double average = total / count;
        double offer = (average * _turn) / 10;
        return Math.Round(offer, 0);
    }

    private Color GetBackground(double amount)
    {
        int position = 0;
        while (amount != box_values[position])
        {
            position++;
        }
        return ConvertHexToColor($"#ff{box_colors[position]}");
    }

    private async void Choose(Button button, string name)
    {
        if (_turn < box_names.Length)
        {
            double offer = 0;
            button.Opacity = 0;
            _amount = _amounts[Array.IndexOf(box_names, name)];
            ContentDialogResult response = await ShowDialogAsync("Ok", string.Empty, GetAmount(_amount, GetBackground(_amount)));
            if (response == ContentDialogResult.Primary)
            {
                if (!_dealt && _turn % 5 == 0 && _turn > 1)
                {
                    offer = GetOffer();
                    ContentDialogResult result = await ShowDialogAsync("Deal", "Not", GetAmount(offer, Colors.Black));
                    if (result == ContentDialogResult.Primary)
                    {
                        _amount = offer;
                        _dealt = true;
                    }
                }
                _turn++;
            }
        }
        if (_turn == box_names.Length || _dealt)
        {
            object content = _dealt ? GetAmount(_amount, Colors.Black) : GetAmount(_amount, GetBackground(_amount));
            await ShowDialogAsync("Game Over", string.Empty, content);
        }
    }

    private void Add(ref StackPanel panel, string name, int value)
    {
        Button button = new Button()
        {
            Name = $"box.{name}",
            Margin = new Thickness(5)
        };
        button.Click += (object sender, RoutedEventArgs e) =>
        {
            Choose((Button)sender, name);
        };
        StackPanel box = new StackPanel()
        {
            Width = 100
        };
        Rectangle lid = new Rectangle()
        {
            Height = 10,
            Fill = new SolidColorBrush(Colors.DarkRed)
        };
        Grid front = new Grid()
        {
            Height = 75,
            Background = new SolidColorBrush(Colors.Red)
        };
        Grid label = new Grid()
        {
            Width = 50,
            Background = new SolidColorBrush(Colors.White),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center
        };
        TextBlock text = new TextBlock()
        {
            TextAlignment = TextAlignment.Center,
            FontWeight = FontWeights.Bold,
            Foreground = new SolidColorBrush(Colors.Black),
            FontSize = 32,
            Text = value.ToString()
        };
        label.Children.Add(text);
        front.Children.Add(label);
        box.Children.Add(lid);
        box.Children.Add(front);
        button.Content = box;
        panel.Children.Add(button);
    }

    private StackPanel AddRow()
    {
        StackPanel panel = new StackPanel();
        int[] rows = { 5, 6, 6, 5 };
        int count = 0;
        for (int r = 0; r < 4; r++)
        {
            StackPanel places = new StackPanel()
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center
            };
            for (int c = 0; c < rows[r]; c++)
            {
                Add(ref places, box_names[count], count + 1);
                count++;
            }
            panel.Children.Add(places);
        }
        return panel;
    }

    private void Layout(ref Grid grid)
    {
        grid.Children.Clear();
        Viewbox view = new Viewbox()
        {
            Child = AddRow()
        };
        grid.Children.Add(view);
    }

    public void New(ref Grid grid)
    {
        _turn = 0;
        _dealt = false;
        List<int> positions = Shuffle(22);
        _amounts = new List<double>();
        foreach (int position in positions)
        {
            _amounts.Add(box_values[position]);
        }
        Layout(ref grid);
    }
}

Within the game there are the box values as a double[] – this contains all the possible amounts that a box can contain, each of those amounts has a corresponding colour which is in the string[] of box colours then there’s the names of the boxes as another string[]. The box colours are stored as hexadecimal colour values and these are converted using the ConvertHexToColor to a colour that can be used in the code. There’s a good use of the ContentDialog to show different content with different Primary and Secondary buttons which is made use of to display any amounts of opened boxes and any Deals too. There’s a Shuffle method combined with a random number generator which is used to randomise the contents of the boxes. The amount is obtained with the GetAmount method which also displays the passed in background colour and displays the amount as currency – you can change the CultureInfo to your own region e.g. “en-US” to display a different currency symbol.

In the game there are Offers and these are calculated with the GetOffer method which uses a simple algorithm to work out what the offer should be, there’s also a GetBackground method to get the correct background colour for an amount. The Pick method is the core part of the game – when each box is selected it will display the Amount in that box, after every five turns there will be a message to Deal or Not – if you deal the game is over and you win the amount that was offered or you can Continue. The layout of the game is formed from the Add method which creates the look of a box with colours and a label on the front, the Boxes method creates the full layout of boxes to be displayed and is called from the Layout method. You can start a New game which will reset everything to start again.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

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 the main user interface of the Application, this features a ViewBox containing a Grid Control that will be use for the contents of the game. The second block of XAML is is the CommandBar which contains New – to start a Game.

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();

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

Below the MainPage() Method an instance of the Library Class is created, then New_Click is used to call the New method to setup the game and start playing.

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

After the Application has started running you can then select Newto start the game then select one of the boxes between 1 and 22 to display the amount after each five turns the next turn will result on an Offer and you can Deal or Not until there’s just one box left and that’s what you’ll win or if you did Deal you win that Offer.

ran-deal-or-not

Step 15

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

vs2017-close

Deal Or Not is quite a fun game and contains many elements of a certain game show and shows off how something like that can be encapsulated in a game you can play on a computer – it features a fun look and feel with the boxes displayed and amounts shown in a more pleasing visual manner, it was important for each amount to show as closely to the game show as possible and demonstrates the flexability of dialogs to display quite sophisticated content and hopefully is as fun a game to write as it is to playf.

Creative Commons License

Advertisements

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 )

w

Connecting to %s