Windows 10 Universal Windows Platform – Noughts and Crosses

Step 1

Download Visual Studio Community 2015 and install it onto your computer, if it’s already downloaded and installed select Launch to start Visual Studio Community 2015 or if it has already been downloaded and installed then start the application you may also need to Enable your device for development.

10-home

Step 2

Once Visual Studio Community 2015 has started select File, then New, then Project… from the Menu.

10-file-new-project

Step 3

From the New Project window select Visual C# from Installed, Templates then select Blank App (Windows Universal) from the list, then type in a Name and select a Location to save to before selecting Ok to create the Project.

10-new-project

Step 4

Once done select from the Menu, Project, then Add New Item…

10-project-add-new-item

Step 5

From the Add New Item window select Visual C# 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

10-add-new-item-library

Step 6

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

using System;
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 nought = "O";
    private const string cross = "X";

    private bool won = false;
    private string piece = "";
    private string[,] board = new string[3, 3];

    public Brush Background { get; set; }

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

    public async Task<bool> Confirm(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;
    }

    private bool winner()
    {
        return
        (board[0, 0] == piece && board[0, 1] == piece && board[0, 2] == piece) ||
        (board[1, 0] == piece && board[1, 1] == piece && board[1, 2] == piece) ||
        (board[2, 0] == piece && board[2, 1] == piece && board[2, 2] == piece) ||
        (board[0, 0] == piece && board[1, 0] == piece && board[2, 0] == piece) ||
        (board[0, 1] == piece && board[1, 1] == piece && board[2, 1] == piece) ||
        (board[0, 2] == piece && board[1, 2] == piece && board[2, 2] == piece) ||
        (board[0, 0] == piece && board[1, 1] == piece && board[2, 2] == piece) ||
        (board[0, 2] == piece && board[1, 1] == piece && board[2, 0] == piece);
    }

    private bool drawn()
    {
        return
        board[0, 0] != string.Empty && board[0, 1] != string.Empty && board[0, 2] != string.Empty &&
        board[1, 0] != string.Empty && board[1, 1] != string.Empty && board[1, 2] != string.Empty &&
        board[2, 0] != string.Empty && board[2, 1] != string.Empty && board[2, 2] != string.Empty;
    }

    private Path getPiece()
    {
        if ((piece == cross)) // Draw X
        {
            Path lines = new Path();
            LineGeometry line1 = new LineGeometry();
            LineGeometry line2 = new LineGeometry();
            GeometryGroup linegroup = new GeometryGroup();
            line1.StartPoint = new Point(0, 0);
            line1.EndPoint = new Point(60, 60);
            line2.StartPoint = new Point(60, 0);
            line2.EndPoint = new Point(0, 60);
            linegroup.Children.Add(line1);
            linegroup.Children.Add(line2);
            lines.Data = linegroup;
            lines.Stroke = new SolidColorBrush(Colors.Red);
            lines.StrokeThickness = 5;
            lines.Margin = new Thickness(10);
            return lines;
        }
        else // Draw O
        {
            EllipseGeometry ellipse = new EllipseGeometry();
            Path circle = new Path();
            ellipse.Center = new Point(30, 30);
            ellipse.RadiusX = 30;
            ellipse.RadiusY = 30;
            circle.Data = ellipse;
            circle.Stroke = new SolidColorBrush(Colors.Blue);
            circle.StrokeThickness = 5;
            circle.Margin = new Thickness(10);
            return circle;
        }
    }

    private void add(ref Grid grid, int row, int column)
    {
        Canvas canvas = new Canvas();
        canvas.Height = 80;
        canvas.Width = 80;
        canvas.Background = Background;
        canvas.Tapped += (object sender, TappedRoutedEventArgs e) =>
        {
            if (!won)
            {
                canvas = ((Canvas)(sender));
                if ((canvas.Children.Count < 1))
                {
                    canvas.Children.Add(getPiece());
                    board[(int)canvas.GetValue(Grid.RowProperty),
                    (int)canvas.GetValue(Grid.ColumnProperty)] = piece;
                }
                if (winner())
                {
                    won = true;
                    Show((piece + " wins!"), "Noughts and Crosses");
                }
                else if (drawn())
                {
                    Show("Draw!", "Noughts and Crosses");
                }
                else
                {
                    piece = ((piece == cross) ? nought : cross); // Swap Players
                }
            }
            else
            {
                Show("Game Over!", "Noughts and Crosses");
            }
        };
        canvas.SetValue(Grid.ColumnProperty, column);
        canvas.SetValue(Grid.RowProperty, row);
        grid.Children.Add(canvas);
    }

    private void layout(ref Grid grid)
    {
        grid.Children.Clear();
        grid.ColumnDefinitions.Clear();
        grid.RowDefinitions.Clear();
        // Setup 3x3 Grid
        for (int Index = 0; (Index <= 2); Index++)
        {
            grid.RowDefinitions.Add(new RowDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
        }
        add(ref grid, 0, 0); // Top Left
        add(ref grid, 0, 1); // Top Middle
        add(ref grid, 0, 2); // Top Right
        add(ref grid, 1, 0); // Middle Left
        add(ref grid, 1, 1); // Centre
        add(ref grid, 1, 2); // Middle Right
        add(ref grid, 2, 0); // Bottom Left
        add(ref grid, 2, 1); // Bottom Middle
        add(ref grid, 2, 2); // Bottom Right
    }

    public async void New(Grid grid)
    {
        layout(ref grid);
        board[0, 0] = "";
        board[0, 1] = "";
        board[0, 2] = "";
        board[1, 0] = "";
        board[1, 1] = "";
        board[1, 2] = "";
        board[2, 0] = "";
        board[2, 1] = "";
        board[2, 2] = "";
        won = false;
        if (await Confirm("Who goes First?", "Noughts and Crosses", nought, cross))
        {
            piece = nought;
        }
        else
        {
            piece = cross;
        }
    }
}

It should then appear as such:

10-library-noughtsandcrosses

Step 7

From the Solution Explorer select MainPage.xaml

10-mainpage

Step 8

Select from the Menu, View then Designer

10-designer

Step 9

The Design View will be displayed along with the XAML View and in this above <Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”> enter the following XAML:

<Page.BottomAppBar>
	<AppBar IsOpen="True" IsSticky="True">
		<StackPanel Orientation="Horizontal">
			<AppBarButton Icon="Page" Label="New" Click="New_Click"/>
		</StackPanel>
	</AppBar>
</Page.BottomAppBar>

While still in the XAML View below <Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”>enter the following XAML:

<Grid Name="Display" HorizontalAlignment="Center" Height="300" Width="300"/>

It should appear as such:

10-xaml-noughtsandcrosses

Step 10

Select from the Menu, View then Code

10-code

Step 11

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

public Library Library = new Library();

private void New_Click(object sender, RoutedEventArgs e)
{
	Library.Background = ((Brush)App.Current.Resources["ApplicationSecondaryForegroundThemeBrush"]);
	Library.New(Display);
}

It should then appear as such:

10-code-noughtsandcrosses

Step 12

That completes the Windows Universal Application so Save the Project then select the Debug and Simulator option to run the Application

10-simulator

Step 13

Once the Simulator has started the Application should then appear

10-simulator-run-noughtsandcrosses

Step 14

After the Application has started running you can then tap the New Button, then choose X or O then can start playing the game

10-simulator-ran-noughtsandcrosses

Step 15

To Exit the application select Stop Debugging in Visual Studio Community 2015

10-stop

Step 16

Another option is to run as a Windows Phone application, select Debug and select Emulator 10.0.1.0 WVGA 4 inch 512MB option to run the Application

10-emulator

Step 17

Once the Emulator has started the Application should then appear

10-emulator-run-noughtsandcrosses

Step 18

After the Application has started running you can then tap the New Button, then choose X or O then can start playing the game

10-emulator-ran-noughtsandcrosses

Step 19

To Exit the application select Stop Debugging in Visual Studio Community 2015

10-stop

Creative Commons License

Advertisements

2 thoughts on “Windows 10 Universal Windows Platform – Noughts and Crosses

  1. This demo is very good, but it has a bug. When I tapped the grid which already has a piece, the piece’s kind will change. So, I think below the “if (canvas.Children.Count < 1)" there need to a statement "else return" right?

    Like

    • Well spotted, indeed it does do that, it’s also possible by extending the “if” to be after the logic for checking and swapping players – but the return would also do the job.

      Like

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s