Xamarin September – Touch 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 GameGrid : Grid
{
    public int Value { get; set; }
}

public class Library
{
    private const string app_title = "Touch Game";
    private const int size = 2;
    private const int speed = 800;
    private const int light = 400;
    private const int click = 200;
    private const int level = 100;

    private Color[] _colours =
    {
        Color.Crimson, Color.Green,
        Color.Blue, Color.Gold
    };
    private Color clicked = Color.Accent;
    private Color lighted = Color.WhiteSmoke;

    private ContentPage _page;
    private int _turn = 0;
    private int _count = 0;
    private bool _play = false;
    private bool _isTimer = false;
    private bool _isHighlight = false;
    private List<int> _items = new List<int>();
    private Random _random = new Random((int)DateTime.Now.Ticks);

    public void Show(string content, string title)
    {
        Device.BeginInvokeOnMainThread(() => {
            _page.DisplayAlert(title, content, "Ok");
        });
    }

    private void Highlight(Grid grid, int value, int period, Color background)
    {
        GameGrid element = (GameGrid)grid.Children.Single(s =>
            ((GameGrid)s).Value == value);
        Device.BeginInvokeOnMainThread(() =>
        {
            element.BackgroundColor = background; // New Background
        });
        Device.StartTimer(TimeSpan.FromMilliseconds(period), () =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                element.BackgroundColor = _colours[element.Value]; // Original Background
            });
            return false;
        });
    }

    private List<int> Shuffle(int start, int finish, int total)
    {
        int number;
        List<int> numbers = new List<int>();
        while ((numbers.Count < total)) // Select Numbers
        {
            // Random non-unique Number between Start and Finish
            number = _random.Next(start, finish + 1);
            numbers.Add(number); // Add Number
        }
        return numbers;
    }

    private void Add(Grid grid, int row, int column, int count)
    {
        GameGrid element = new GameGrid()
        {
            HeightRequest = 120,
            WidthRequest = 120,
            Value = count,
            BackgroundColor = _colours[count]
        };
        TapGestureRecognizer tapped = new TapGestureRecognizer();
        tapped.Tapped += (sender, e) =>
        {
            if (_play)
            {
                int value = ((GameGrid)sender).Value;
                Highlight(grid, value, click, clicked);
                if (value == _items[_count])
                {
                    if (_count < _turn)
                    {
                        _count++;
                    }
                    else
                    {
                        _play = false;
                        _turn++;
                        _count = 0;
                        _isTimer = true;
                    }
                }
                else
                {
                    _isTimer = false;
                    Show($"Game Over! You scored {_turn}!", app_title);
                    _play = false;
                    _turn = 0;
                    _count = 0;
                }
            }
        };
        element.GestureRecognizers.Add(tapped);
        element.SetValue(Grid.ColumnProperty, column);
        element.SetValue(Grid.RowProperty, row);
        grid.Children.Add(element);
    }

    private void Layout(ref Grid grid)
    {
        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());
        }
        int count = 0;
        // Setup Board
        for (int column = 0; (column < size); column++)
        {
            for (int row = 0; (row < size); row++)
            {
                Add(grid, row, column, count);
                count++;
            }
        }
    }

    public void New(ContentPage page, Grid grid)
    {
        _page = page;
        Layout(ref grid);
        _items = Shuffle(0, 3, level);
        _play = false;
        _turn = 0;
        _count = 0;
        _isTimer = true;
        Device.StartTimer(TimeSpan.FromMilliseconds(speed), () =>
        {
            if (_isTimer)
            {
                if (_count <= _turn)
                {
                    Highlight(grid, _items[_count], light, lighted);
                    _count++;
                }
                if (_count > _turn)
                {
                    _isTimer = false;
                    _play = true;
                    _count = 0;
                }
            }
            return true;
        });
    }
}

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>
	<Grid Grid.Row="0" x:Name="Display" HorizontalOptions="Center" VerticalOptions="Center"/>
	<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-touch-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, Display);
}

It should then appear as such:

xamarin-code-touch-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-touch-game

Step 19

After the Application has started running you can then tap the New Button, then one of the squares will highlight, select the correct one, then each time one more square will highlight each turn, match the patterns to continue

xamarin-android-ran-touch-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-touch-game

Step 25

After the Application has started running you can then tap the New Button, then one of the squares will highlight, select the correct one, then each time one more square will highlight each turn, match the patterns to continue

xamarin-uwp-ran-touch-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 tap the New Button, then one of the squares will highlight, select the correct one, then each time one more square will highlight each turn, match the patterns to continue

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

Leave a comment