Xamarin September – Flags Game

Standard

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 locate and select Visual Studio 2017.

xamarin-vs2017-home

Step 2

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

xamarin-vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Cross Platform App (Xamarin) and then type in a Name and select a Location and then select Ok to create the Project

xamarin-vs2017-new-project

Step 4

Then in New Cross Platform App you need to select the Blank App Template then from UI Technology select Xamarin.Forms and in Code Sharing Strategy select Shared Project and then select Ok to continue

xamarin-vs2017-cross-platform

Step 5

The Xamarin Mac Agent will be displayed allowing connection to an Apple Mac but this can be dismissed with Close if running solely on Windows 10

xamarin-vs2017-mac-agent

Step 6

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to Windows 10 Creators Update (10.0; Build 15063) and then select Ok

xamarin-vs2017-target

Step 7

From the Menu choose Project, then Add New Item…

xamarin-vs2017-add-new-item

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then in the Name as Library.cs and then select Add to add the file to the Project

xamarin-vs2017-library

Step 9

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

using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;

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 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 ContentPage _page;
    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;

    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)
    {
        Device.BeginInvokeOnMainThread(() => {
            _page.DisplayAlert(title, content, "Ok");
        });
    }

    private StackLayout GetFlag(ref string name, int index)
    {
        int pos = _indexes[index];
        Flag flag = flags[pos];
        name = flag.Name;
        bool horizontal = flag.Design == Flag.Designs.HorizonalStripes;
        StackLayout panel = new StackLayout()
        {
            InputTransparent = true,
            HeightRequest = 60,
            WidthRequest = 60,
            Orientation = horizontal ? StackOrientation.Vertical : StackOrientation.Horizontal,
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center,
            Spacing = 0
        };
        for (int f = 0; f < 3; f++)
        {
            BoxView box = new BoxView()
            {
                InputTransparent = true,
                WidthRequest = horizontal ? 60 : 20,
                HeightRequest = horizontal ? 20 : 60,
                BackgroundColor = Color.FromHex($"#FF{flag.Colours[f]}"),
            };
            panel.Children.Add(box);
        }
        return panel;
    }

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

    private void Add(Grid grid, Label text, int row, int column, int index)
    {
        string name = string.Empty;
        StackLayout view = GetFlag(ref name, index);
        Grid element = new Grid()
        {
            ClassId = name,
            BackgroundColor = Color.WhiteSmoke,
            HeightRequest = 80,
            WidthRequest = 80
        };
        element.Children.Add(view);
        TapGestureRecognizer tapped = new TapGestureRecognizer();
        tapped.Tapped += (sender, e) =>
        {
            if (!_lost)
            {
                element = ((Grid)sender);
                row = (int)element.GetValue(Grid.RowProperty);
                column = (int)element.GetValue(Grid.ColumnProperty);
                string current = element.ClassId;
                if (_country == current)
                {
                    element.Opacity = 0;
                    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);
            }
        };
        element.GestureRecognizers.Add(tapped);
        element.SetValue(Grid.ColumnProperty, column);
        element.SetValue(Grid.RowProperty, row);
        grid.Children.Add(element);
    }

    private void Layout(ref Grid grid, ref Label text)
    {
        text.Text = string.Empty;
        grid.HeightRequest = 300;
        grid.WidthRequest = 300;
        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++;
            }
        }
    }

    public void New(ContentPage page, ref Grid grid, ref Label text)
    {
        _page = page;
        _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);
    }
}

Step 10

In the Solution Explorer select MainPage.xaml from the Shared Project

xamarin-vs2017-library-mainpage-xaml

Step 11

From the Menu choose View and then Open

xamarin-vs2017-view-open

Step 12

The XAML View will be displayed, and in this remove the Label then between the ContentPage and /ContentPage elements, enter the following XAML:

<Grid>
	<Grid.RowDefinitions>
		<RowDefinition Height="*" />
		<RowDefinition Height="Auto" />
	</Grid.RowDefinitions>
	<StackLayout Grid.Row="0" HorizontalOptions="Center" VerticalOptions="Center">
		<Label x:Name="Label" HorizontalOptions="Center" VerticalOptions="Center" FontSize="Medium"/>
		<Grid x:Name="Display" HorizontalOptions="Center" VerticalOptions="Center"/>
	</StackLayout>
	<Grid Grid.Row="1" Margin="10">
		<Button Text="New" HorizontalOptions="Center" WidthRequest="100" Clicked="New_Clicked"/>
	</Grid>
</Grid>

It should appear as such:

xamarin-xaml-flags-game

Step 13

In the Solution Explorer select the Expand arrow next to MainPage.xaml to open MainPage.cs, then select this from the Shared Project

xamarin-vs2017-library-mainpage-cs

Step 14

From the Menu choose View and then Open

xamarin-vs2017-view-open

Step 15

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

Library library = new Library();

private void New_Clicked(object sender, EventArgs e)
{
	library.New(this, ref Display, ref Label);
}

It should then appear as such:

xamarin-code-flags-game

Step 16

That completes the application, so from the Menu choose Build and then Build Solution

xamarin-vs2017-build-solution

Step 17

Then from the Menu choose Debug then Start Debugging to run the Application in the Android Emulator

xamarin-vs2017-debug-start

Step 18

Once started the Application should then appear in the Android Emulator

xamarin-android-run-flags-game

Step 19

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, then you Win!

xamarin-android-ran-flags-game

Step 20

To Exit the Application select Stop in Visual Studio

xamarin-vs2017-stop

Step 21

Another option is to run as a Universal Windows Application. From Solution Explorer select the Project ending with .UWP (Universal Windows), then from the Menu choose Project then Set as StartUp Project

xamarin-vs2017-project-startup

Step 22

Then again from the Menu choose Build and then select the Deploy option ending with .UWP

xamarin-vs2017-uwp-deploy

Step 23

Then once again from the Menu choose Debug then Start Debugging to run the Application in Windows 10

xamarin-vs2017-debug-start

Step 24

Once started the Application should then appear

xamarin-uwp-run-flags-game

Step 25

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, then you Win!

xamarin-uwp-ran-flags-game

Step 26

To Exit the Application select Stop in Visual Studio

xamarin-vs2017-stop

Step 27

Also if you have Mac with the Xamarin tools installed and have enabled and connected to the Xamarin Mac Agent. From Solution Explorer select the Project ending with .iOS, then from the Menu choose Project then Set as StartUp Project

xamarin-vs2017-project-startup

Step 28

Then once again from the Menu choose Debug then Start Debugging to run the Application for iOS

xamarin-vs2017-debug-start

Step 29

Once started the Application should then appear

Screenshots provided by Julia Boichentsova

Step 30

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, then you Win!

Screenshots provided by Julia Boichentsova

Step 31

To Exit the Application select Stop in Visual Studio

xamarin-vs2017-stop

Thanks for Julia Boichentsova for helping with iOS screenshots

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 )

Connecting to %s