Universal Windows Platform – Four in Row

Four in Row demonstrates how to create a simple two-player game where the objective is to get four pieces in a row in either horizontal, vertical or diagonal directions.

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.Linq;
using System.Threading.Tasks;
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 = "Four In Row";
    private const int size = 7;

    private bool _won = false;
    private int[,] _board = new int[size, size];
    private int _player = 0;

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

    public async Task<bool> ConfirmAsync(string content, string title, string ok, string cancel)
    {
        bool result = false;
        MessageDialog dialog = new MessageDialog(content, title);
        dialog.Commands.Add(new UICommand(ok, new UICommandInvokedHandler((cmd) => result = true)));
        dialog.Commands.Add(new UICommand(cancel, new UICommandInvokedHandler((cmd) => result = false)));
        await dialog.ShowAsync();
        return result;
    }

    public bool Winner(int column, int row)
    {
        int total = 3; // Total Excluding Current
        int value = 0; // Value in Line
        int amend = 0; // Add or Remove
        // Check Vertical
        do
        {
            value++;
        }
        while (row + value < size &&
        _board[column, row + value] == _player);
        if (value > total)
        {
            return true;
        }
        value = 0;
        amend = 0;
        // Check Horizontal - From Left
        do
        {
            value++;
        }
        while (column - value >= 0 &&
        _board[column - value, row] == _player);
        if (value > total)
        {
            return true;
        }
        value -= 1; // Deduct Middle - Prevent double count
        // Then Right
        do
        {
            value++;
            amend++;
        }
        while (column + amend < size &&
        _board[column + amend, row] == _player);
        if (value > total)
        {
            return true;
        }
        value = 0;
        amend = 0;
        // Diagonal - Left Top
        do
        {
            value++;
        }
        while (column - value >= 0 && row - value >= 0 &&
        _board[column - value, row - value] == _player);
        if (value > total)
        {
            return true;
        }
        value -= 1; // Deduct Middle - Prevent double count
        // To Right Bottom
        do
        {
            value++;
            amend++;
        }
        while (column + amend < size && row + amend < size &&
        _board[column + amend, row + amend] == _player);
        if (value > total)
        {
            return true;
        }
        value = 0;
        amend = 0;
        // Diagonal - From Right Top
        do
        {
            value++;
        }
        while (column + value < size && row - value >= 0 &&
        _board[column + value, row - value] == _player);
        if (value > total)
        {
            return true;
        }
        value -= 1; // Deduct Middle - Prevent double count
        // To Left Bottom
        do
        {
            value++;
            amend++;
        }
        while (column - amend >= 0 &&
        row + amend < size &&
        _board[column - amend, row + amend] == _player);
        if (value > total)
        {
            return true;
        }
        return false;
    }

    private bool Full()
    {
        for (int row = 0; row < size; row++)
        {
            for (int column = 0; column < size; column++)
            {
                if (_board[column, row] == 0)
                {
                    return false;
                }
            }
        }
        return true;
    }

    private Path GetPiece(int player)
    {
        Path path = new Path
        {
            Stretch = Stretch.Uniform,
            StrokeThickness = 5,
            Margin = new Thickness(5),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center
        };
        if ((player == 1))
        {
            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
        {
            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 Place(Grid grid, int column, int row)
    {
        for (int i = size - 1; i > -1; i--)
        {
            if (_board[column, i] == 0)
            {
                _board[column, i] = _player;
                Grid element = (Grid)grid.Children.Single(
                    w => Grid.GetRow((Grid)w) == i
                    && Grid.GetColumn((Grid)w) == column);
                element.Children.Add(GetPiece(_player));
                row = i;
                break;
            }
        }
        if (Winner(column, row))
        {
            _won = true;
            Show($"Player {_player} has won!", app_title);
        }
        else if (Full())
        {
            Show("Board Full!", app_title);
        }
        _player = _player == 1 ? 2 : 1; // Set Player
    }

    private void Add(Grid grid, int row, int column)
    {
        Grid element = new Grid
        {
            Height = 40,
            Width = 40,
            Margin = new Thickness(5),
            Background = new SolidColorBrush(Colors.WhiteSmoke),
        };
        element.Tapped += (object sender, TappedRoutedEventArgs e) =>
        {
            if (!_won)
            {
                element = ((Grid)(sender));
                row = (int)element.GetValue(Grid.RowProperty);
                column = (int)element.GetValue(Grid.ColumnProperty);
                if (_board[column, 0] == 0) // Check Free Row
                {
                    Place(grid, column, row);
                }
            }
            else
            {
                Show("Game Over!", app_title);
            }
        };
        element.SetValue(Grid.ColumnProperty, column);
        element.SetValue(Grid.RowProperty, row);
        grid.Children.Add(element);
    }

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

    public async void NewAsync(Grid grid)
    {
        Layout(ref grid);
        _won = false;
        _player = await ConfirmAsync("Who goes First?", app_title, "X", "O") ? 1 : 2;
    }
}

In the Library.cs there are using statements to include the necessary functionality. The Show Method is used to display a MessageDialog to display a message, the ConfirmAsync Method is used to display a MessageDialog to get a response from the player. Winner is used to determine if a winning solution has been provided, which is four pieces in a row and the Method is used for this purpose. The Full Method is used to determine if the board is completely full, GetPiece is used to generate the pieces to use in the game, Place is used to position a game piecewhen playing and 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 and is called by the NewAsync Method.

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.NewAsync(Display);
}

Below the MainPage() Method an instance of the Library Class is created, then New_Click is used to call the NewAsync 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, first can chose to play as “X” or “O”, you can win by getting four pieces in a horizontal, vertical or diagonal row in the Application

ran-four-in-row

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