Universal Windows Platform – Hit or Miss

Hit or Miss demonstrates how to create a simple random game where you can score a Hit or a Miss based on which Grid is Tapped.

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 Fall Creators Update (10.0; Build 16299) 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 Windows.Foundation;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

public class Library
{
    private const string app_title = "Hit or Miss";

    private const int score = 18;
    private const int size = 6;
    private const int hit = 1;
    private const int miss = 0;
    private readonly List<string> values = new List<string> { "Miss", "Hit" };

    private int _moves = 0;
    private int _hits = 0;
    private int _misses = 0;
    private bool _won = false;
    private int[,] _board = new int[size, size];
    private Random _random = new Random((int)DateTime.Now.Ticks);

    public void Show(string content, string title)
    {
        IAsyncOperation<IUICommand> command = new MessageDialog(content, title).ShowAsync();
    }

    private List<int> Select(int start, int finish, int total)
    {
        int number;
        List<int> numbers = new List<int>();
        while ((numbers.Count < total)) // Select Numbers
        {
            // Random Number between Start and Finish
            number = _random.Next(start, finish + 1);
            if ((!numbers.Contains(number)) || (numbers.Count < 1))
            {
                numbers.Add(number); // Add if number Chosen or None
            }
        }
        return numbers;
    }

    private Path GetPiece(string value)
    {
        Path path = new Path
        {
            Stretch = Stretch.Uniform,
            StrokeThickness = 5,
            Margin = new Thickness(5),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center
        };
        if ((value == "Miss")) // Draw Miss
        {
            LineGeometry line1 = new LineGeometry
            {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(30, 30)
            };
            LineGeometry line2 = new LineGeometry
            {
                StartPoint = new Point(30, 0),
                EndPoint = new Point(0, 30)
            };
            GeometryGroup linegroup = new GeometryGroup();
            linegroup.Children.Add(line1);
            linegroup.Children.Add(line2);
            path.Data = linegroup;
            path.Stroke = new SolidColorBrush(Colors.Red);
        }
        else // Draw Hit
        {
            EllipseGeometry ellipse = new EllipseGeometry
            {
                Center = new Point(15, 15),
                RadiusX = 15,
                RadiusY = 15
            };
            path.Data = ellipse;
            path.Stroke = new SolidColorBrush(Colors.Blue);
        }
        return path;
    }

    private void Add(ref Grid grid, int row, int column)
    {
        Grid element = new Grid
        {
            Height = 50,
            Width = 50,
            Margin = new Thickness(5),
            Background = new SolidColorBrush(Colors.WhiteSmoke)
        };
        element.Tapped += (object sender, TappedRoutedEventArgs e) =>
        {
            if (!_won)
            {
                int selected;
                element = ((Grid)(sender));
                selected = _board[(int)element.GetValue(Grid.RowProperty), 
                    (int)element.GetValue(Grid.ColumnProperty)];
                if (element.Children.Count <= 0)
                {
                    element.Children.Clear();
                    element.Children.Add(GetPiece(values[selected]));
                    if (selected == hit)
                    {
                        _hits++;
                    }
                    else if (selected == miss)
                    {
                        _misses++;
                    }
                    _moves++;
                }
                if (_moves < (size * size) && _misses < score)
                {
                    if (_hits == score)
                    {
                        Show($"Well Done! You scored {_hits} hits and {_misses} misses!", app_title);
                        _won = true;
                    }
                }
                else
                {
                    Show($"Game Over! You scored {_hits} hits and {_misses} misses!", app_title);
                    _won = true;
                }
            }
        };
        element.SetValue(Grid.ColumnProperty, column);
        element.SetValue(Grid.RowProperty, row);
        grid.Children.Add(element);
    }

    private void Layout(ref Grid grid)
    {
        _moves = 0;
        _hits = 0;
        _misses = 0;
        grid.Children.Clear();
        grid.ColumnDefinitions.Clear();
        grid.RowDefinitions.Clear();
        // Setup Grid
        for (int index = 0; (index < size); index++)
        {
            grid.RowDefinitions.Add(new RowDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
        }
        for (int row = 0; (row < size); row++)
        {
            for (int column = 0; (column < size); column++)
            {
                Add(ref grid, row, column);
            }
        }
    }

    public void New(ref Grid grid)
    {
        Layout(ref grid);
        List<int> values = new List<int>();
        List<int> indices = new List<int>();
        _won = false;
        int counter = 0;
        while (values.Count < (size * size))
        {
            values.Add(hit);
            values.Add(miss);
        }
        indices = Select(1, (size * size), (size * size));
        // Setup Board
        for (int column = 0; (column < size); column++)
        {
            for (int row = 0; (row < size); row++)
            {
                _board[column, row] = values[indices[counter] - 1];
                counter++;
            }
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. Show is used to display a MessageDialog and Select is used along with Random to pick a set of numbers. GetPiece is used to generate the pieces to use in the game, Add is used to help setup the look-and-feel of the game along with Layout which is a set of Grid elements within a Grid. The New Method is used to begin a game and configure the game board and call Layout.

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 Name="New" 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 the look-and-feel 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 in 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

After the Application has started running use New to start the playing, to win need to get more hits (Circles) than misses (Crosses) up to a total of 18 in the Application

ran-hit-or-miss

Step 15

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

vs2017-close

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