Universal Windows Platform – Flags Game

Flags Game demonstrates how to create a flag-based game where you need to choose which is the correct flag based on the country name displayed and if you get them all correct you win and also a good way to learn a small selection of the world’s flags and maybe even get into vexillology – which is the study or interest in flags.

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 Windows.Foundation;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

public class Flag
{
    public enum Designs
    {
        HorizonalStripes = 1,
        VerticalStripes = 2
    };
    public Designs Design { get; set; }
    public string Name { get; set; }
    public string[] Colours { get; set; }
}

public class Library
{
    private const string app_title = "Flags Game";
    private const int size = 3;

    private readonly List<Flag> flags = new List<Flag>()
    {
        new Flag() {
            Name = "Armenia",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "DE1018", "002984", "EF7b21" }
        },
        new Flag()
        {
            Name = "Austria",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "DE1018", "FFFFFF", "DE1018" }
        },
        new Flag()
        {
            Name = "Belgium",
            Design = Flag.Designs.VerticalStripes,
            Colours = new string[] { "000000", "FFEF08", "DE1018" }
        },
        new Flag()
        {
            Name = "Bulgaria",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "FFFFFF", "109452", "DE1018" }
        },
        new Flag()
        {
            Name = "Estonia",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "295AA5", "000000", "FFFFFF" }
        },
        new Flag()
        {
            Name = "France",
            Design = Flag.Designs.VerticalStripes,
            Colours = new string[] { "080863", "FFFFFF", "D60818" }
        },
        new Flag() {
            Name = "Gabon",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "109452", "FFEF08", "002984" }
        },
        new Flag()
        {
            Name = "Germany",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "000000", "DE0008", "FFDE08" }
        },
        new Flag()
        {
            Name = "Guinea",
            Design = Flag.Designs.VerticalStripes,
            Colours = new string[] { "DE1018", "FFEF08", "109452" }
        },
        new Flag()
        {
            Name = "Hungary",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "DE0008", "FFFFFF", "087B39" }
        },
        new Flag()
        {
            Name = "Ireland",
            Design = Flag.Designs.VerticalStripes,
            Colours = new string[] { "007339", "FFFFFF", "E76300" }
        },
        new Flag()
        {
            Name = "Italy",
            Design = Flag.Designs.VerticalStripes,
            Colours = new string[] { "109452", "FFFFFF", "DE1018" }
        },
        new Flag()
        {
            Name = "Lithuania",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "FFEF08", "109452", "DE1018" }
        },
        new Flag()
        {
            Name = "Luxembourg",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "DE1018", "FFFFFF", "2984B5" }
        },
        new Flag()
        {
            Name = "Mali",
            Design = Flag.Designs.VerticalStripes,
            Colours = new string[] { "109452", "FFEF08", "DE1018" }
        },
        new Flag()
        {
            Name = "Netherlands",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "DE1018", "FFFFFF", "002984" }
        },
        new Flag()
        {
            Name = "Nigeria",
            Design = Flag.Designs.VerticalStripes,
            Colours = new string[] { "087B39", "FFFFFF", "087B39" }
        },
        new Flag()
        {
            Name = "Romania",
            Design = Flag.Designs.VerticalStripes,
            Colours = new string[] { "002984", "FFEF08", "DE1018" }
        },
        new Flag()
        {
            Name = "Russia",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "FFFFFF", "0852A5", "DE1018" }
        },
        new Flag()
        {
            Name = "Sierra Leone",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "5AB521", "FFFFFF", "0852A5" }
        },
        new Flag()
        {
            Name = "Yemen",
            Design = Flag.Designs.HorizonalStripes,
            Colours = new string[] { "DE1018", "FFFFFF", "000000" }
        }
    };

    private Random _random = new Random((int)DateTime.Now.Ticks);
    private List<int> _indexes = new List<int>();
    private List<int> _choices = new List<int>();
    private int _turns = 0;
    private string _country = string.Empty;
    private bool _lost = false;

    public 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 List<int> Shuffle(int start, int total)
    {
        return Enumerable.Range(start, total).OrderBy(r => _random.Next(start, total)).ToList();
    }

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

    private Viewbox GetFlag(ref string name, int index)
    {
        int pos = _indexes[index];
        Flag flag = flags[pos];
        name = flag.Name;
        bool horizontal = flag.Design == Flag.Designs.HorizonalStripes;
        StackPanel panel = new StackPanel()
        {
            Height = 120,
            Width = 120,
            Orientation = horizontal ? Orientation.Vertical : Orientation.Horizontal
        };
        for (int f = 0; f < 3; f++)
        {
            Rectangle rect = new Rectangle()
            {
                Width = horizontal ? 120 : 40,
                Height = horizontal ? 40 : 120,
                Fill = new SolidColorBrush(ConvertHexToColor($"#FF{flag.Colours[f]}"))
            };
            panel.Children.Add(rect);
        }
        Viewbox view = new Viewbox()
        {
            Height = 100,
            Width = 100,
            Child = panel
        };
        return view;
    }

    private void SetButton(ref Grid grid, string name, bool show)
    {
        Button button = (Button)grid.FindName(name);
        button.Opacity = show ? 1 : 0;
    }

    private void Add(Grid grid, TextBlock text, int row, int column, int index)
    {
        string name = string.Empty;
        Viewbox view = GetFlag(ref name, index);
        Button button = new Button()
        {
            Name = name,
            Height = 120,
            Width = 120,
            Content = view
        };
        button.Click += (object sender, RoutedEventArgs e) =>
        {
            if (!_lost)
            {
                string current = ((Button)sender).Name;
                if (_country == current)
                {
                    SetButton(ref grid, current, false);
                    if (_turns < 9)
                    {
                        Choose(ref grid, ref text);
                    }
                    else
                    {
                        text.Text = string.Empty;
                        Show("You Won!", app_title);
                    }
                }
                else
                {
                    _lost = true;
                }
            }
            if (_lost)
            {
                Show("Game Over!", app_title);
            }
        };
        button.SetValue(Grid.ColumnProperty, column);
        button.SetValue(Grid.RowProperty, row);
        grid.Children.Add(button);
    }

    private void Layout(ref Grid grid, ref TextBlock text)
    {
        text.Text = string.Empty;
        grid.Children.Clear();
        grid.ColumnDefinitions.Clear();
        grid.RowDefinitions.Clear();
        // Setup Grid
        for (int layout = 0; layout < size; layout++)
        {
            grid.RowDefinitions.Add(new RowDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
        }
        // Setup Board
        int index = 0;
        for (int column = 0; column < size; column++)
        {
            for (int row = 0; row < size; row++)
            {
                Add(grid, text, row, column, index);
                index++;
            }
        }
    }

    private void Choose(ref Grid grid, ref TextBlock text)
    {
        int choice = _choices[_turns];
        int index = _indexes[choice];
        _country = flags[index].Name;
        text.Text = _country;
        _turns++;
    }

    public void New(ref Grid grid, ref TextBlock text)
    {
        _lost = false;
        _turns = 0;
        text.Text = string.Empty;
        _indexes = Shuffle(0, flags.Count);
        _choices = Shuffle(0, 9);
        Layout(ref grid, ref text);
        Choose(ref grid, ref text);
    }
}

There’s a Class to represent a Flag with Design property for the Designs possible with either HorizontalStripes or VerticalStripes, then a Name and list of Colours for the flag. In the main Class there’s a list of flags with each Country’s flag properties set to the correct Design and Colours. There’s a Random number generator plus a list of indexes and choices, also there’s a ConvertHexToColor method which converts the colour used in a flag to a system Color that can be used plus there’s a Shuffle method to use the random number generator to create a list of values and a Show method to display a message on screen.

The GetFlag method helps to create the correct look of a flag using a StackPanel with the correct Orientation based on the Design then creates a Rectangle for each colour in the correct Height and Width for the Design. There’s a SetButton method which will set a Button to be visible or not by setting the Opacity, the Add method is used to add all the flags plus this handles when you guess all nine and win the game by showing a message, the Layout method sets up the game to show all the flags and the Choose method gets the next flag to choose and the name of the country’s flag to find with the New method starting the game and setting the first flag to find.

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 Margin="50">
	<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
		<TextBlock Name="Label" TextAlignment="Center" HorizontalAlignment="Center" 
		Style="{StaticResource SubtitleTextBlockStyle}" Width="400"/>
		<Grid Name="Display" HorizontalAlignment="Center" Height="400" Width="400"/>
	</StackPanel>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Page2" Label="New" Click="New_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Game, this features a ViewBox containing a StackPanel with a TextBlock to show the Country Flag to guess and a Grid to display the game itself within. 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, ref Label);
}

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 New to start the game then nine Flags will be displayed and on the Label there will be displayed a Country and you need to guess the correct Flag if you guessed incorrectly then it will be Game Over otherwise you can keep going until you get all nine to Win!

ran-flags-game

Step 15

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

vs2017-close

There’s a lot to be said for having fun with flags and interesting to see how similar the world’s flags are and there’s the whole subject of vexillology to get into if you want, the selection of flags used was chosen because each of the country’s flags are just solid colours – there’s Argentina or Spain that could be used or Canada but each of these has an extra element such as the Maple leaf which if missed off wouldn’t be correct and with this example it was important to include flags only made of solid colours and to make it easier with three horizontal or vertical stripes. For those who do have an interest in flags may notice that some of the proportions of the coloured bands isn’t 100% correct such as with Nigeria or France but hopefully the representations of all the flags is as those who call those countries home would be happy with and it would be possible to add more designs and add more flags such as the Union Flag for the United Kingdom or for other countries such as the United States of America or South Africa. Hopefully it’s a fun game to play and to learn from and a chance to learn to identify a small selection of world flags!

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