Universal Windows Platform – Lucky Chess

Lucky Chess demonstrates how to create a game where you can play a simple game of Chess for two players.

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 the Name as LuckyChess and select a Location and then select Ok to create the Project
vs2017-new-project-lucky-chess

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-lucky-chess

Step 7

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Markup;

namespace LuckyChess
{
    public enum ChessBackground
    {
        Light, Dark
    }

    public enum PieceSet
    {
        White, Black
    }

    public enum PieceType
    {
        Pawn, Knight, Bishop, Rook, Queen, King
    }

    public class BindableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected bool SetProperty<T>(ref T field, T value,
        [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        public void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }

    public class ChessCoordinate
    {
        private static string[] chess_ranks = { "8", "7", "6", "5", "4", "3", "2", "1" };
        private static string[] chess_files = { "A", "B", "C", "D", "E", "F", "G", "H" };

        public int Id { get; set; }
        public int Row { get; set; }
        public int Column { get; set; }

        public ChessBackground Background { get; set; }
        public string Notation { get; set; }

        public ChessCoordinate(int id)
        {
            Id = id;
            Row = Id / 8;
            Column = Id % 8;
            Background = (Row + Column) % 2 == 0 ? ChessBackground.Light : ChessBackground.Dark;
            Notation = chess_files[Column] + chess_ranks[Row];
        }
    }

    public class ChessPiece : BindableBase
    {
        private PieceType _type;
        private PieceSet _set;

        public ChessPiece(PieceType type, PieceSet set)
        {
            _type = type;
            _set = set;
        }

        public PieceType Type
        {
            get { return _type; }
            set { SetProperty(ref _type, value); }
        }

        public PieceSet Set
        {
            get { return _set; }
            set { SetProperty(ref _set, value); }
        }
    }

    public class ChessSquare : BindableBase
    {
        private int _id;
        private ChessPiece _piece;
        private ChessCoordinate _coordinate;
        private bool _isSelected;

        public int Id
        {
            get { return _id; }
            set { SetProperty(ref _id, value); }
        }

        public ChessPiece Piece
        {
            get { return _piece; }
            set { SetProperty(ref _piece, value); }
        }

        public ChessCoordinate Coordinate
        {
            get { return _coordinate; }
            set { SetProperty(ref _coordinate, value); }
        }

        public bool IsSelected
        {
            get { return _isSelected; }
            set { SetProperty(ref _isSelected, value); }
        }
    }

    public class ChessPosition : List<ChessPiece>
    {
        public ChessPosition() : base(new ChessPiece[64]) { }

        public ChessPosition(string position) : this()
        {
            int i = 0;
            foreach (char item in position)
            {
                switch (item)
                {
                    case 'p': this[i++] = new ChessPiece(PieceType.Pawn, PieceSet.Black); break;
                    case 'n': this[i++] = new ChessPiece(PieceType.Knight, PieceSet.Black); break;
                    case 'b': this[i++] = new ChessPiece(PieceType.Bishop, PieceSet.Black); break;
                    case 'r': this[i++] = new ChessPiece(PieceType.Rook, PieceSet.Black); break;
                    case 'q': this[i++] = new ChessPiece(PieceType.Queen, PieceSet.Black); break;
                    case 'k': this[i++] = new ChessPiece(PieceType.King, PieceSet.Black); break;
                    case 'P': this[i++] = new ChessPiece(PieceType.Pawn, PieceSet.White); break;
                    case 'N': this[i++] = new ChessPiece(PieceType.Knight, PieceSet.White); break;
                    case 'B': this[i++] = new ChessPiece(PieceType.Bishop, PieceSet.White); break;
                    case 'R': this[i++] = new ChessPiece(PieceType.Rook, PieceSet.White); break;
                    case 'Q': this[i++] = new ChessPiece(PieceType.Queen, PieceSet.White); break;
                    case 'K': this[i++] = new ChessPiece(PieceType.King, PieceSet.White); break;
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8': i += int.Parse(item.ToString()); break;
                    case '/': if (i % 8 != 0) throw new ArgumentException("Invalid FEN"); break;
                    default: throw new ArgumentException($"Invalid FEN Character: '{item}'");
                }
            }
        }
    }

    public class ChessBoard
    {
        public ChessSquare[] ChessSquares { get; set; } = new ChessSquare[64];

        public ChessBoard(string fen)
        {
            ChessPosition position = new ChessPosition(fen);
            for (int i = 0; i < position.Count; i++)
            {
                ChessSquares[i] = new ChessSquare
                {
                    Id = i,
                    Piece = position[i],
                    Coordinate = new ChessCoordinate(i)
                };
            }
        }
    }

    public class ChessSquareStyleSelector : StyleSelector
    {
        public Style Light { get; set; }
        public Style Dark { get; set; }

        protected override Style SelectStyleCore(object item, DependencyObject container)
        {
            if (item is ChessSquare square)
            {
                int row = square.Id / 8;
                int col = square.Id % 8;
                return (row + col) % 2 == 0 ? Light : Dark;
            }
            return base.SelectStyleCore(item, container);
        }
    }

    public class ChessPieceToGlyphConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is ChessPiece piece)
            {
                if (piece.Set == PieceSet.White)
                {
                    switch (piece.Type)
                    {
                        case PieceType.King: return "\u2654";
                        case PieceType.Queen: return "\u2655";
                        case PieceType.Rook: return "\u2656";
                        case PieceType.Bishop: return "\u2657";
                        case PieceType.Knight: return "\u2658";
                        case PieceType.Pawn: return "\u2659";
                    }
                }
                else
                {
                    switch (piece.Type)
                    {
                        case PieceType.King: return "\u265A";
                        case PieceType.Queen: return "\u265B";
                        case PieceType.Rook: return "\u265C";
                        case PieceType.Bishop: return "\u265D";
                        case PieceType.Knight: return "\u265E";
                        case PieceType.Pawn: return "\u265F";
                    }
                }
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }

    public class BoolToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            bool isVisible = (bool)value;
            return isVisible ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }

    public class Binder
    {
        public static readonly DependencyProperty GridColumnBindingPathProperty =
        DependencyProperty.RegisterAttached("GridColumnBindingPath", typeof(string), typeof(Binder),
        new PropertyMetadata(null, GridBindingPathPropertyChanged));

        public static readonly DependencyProperty GridRowBindingPathProperty =
        DependencyProperty.RegisterAttached("GridRowBindingPath", typeof(string), typeof(Binder),
        new PropertyMetadata(null, GridBindingPathPropertyChanged));

        public static string GetGridColumnBindingPath(DependencyObject obj)
        {
            return (string)obj.GetValue(GridColumnBindingPathProperty);
        }

        public static void SetGridColumnBindingPath(DependencyObject obj, string value)
        {
            obj.SetValue(GridColumnBindingPathProperty, value);
        }

        public static string GetGridRowBindingPath(DependencyObject obj)
        {
            return (string)obj.GetValue(GridRowBindingPathProperty);
        }

        public static void SetGridRowBindingPath(DependencyObject obj, string value)
        {
            obj.SetValue(GridRowBindingPathProperty, value);
        }

        private static void GridBindingPathPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is string path)
            {
                DependencyProperty property = null;
                if (e.Property == GridColumnBindingPathProperty)
                    property = Grid.ColumnProperty;
                else if (e.Property == GridRowBindingPathProperty)
                    property = Grid.RowProperty;

                BindingOperations.SetBinding(obj, property,
                new Binding { Path = new PropertyPath(path) });
            }
        }
    }

    public class Library
    {
        private const string fen_start = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";

        ChessSquare _square = null;

        public ChessBoard Board { get; set; } = new ChessBoard(fen_start);

        private ItemsPanelTemplate Layout()
        {
            StringBuilder columns = new StringBuilder();
            StringBuilder rows = new StringBuilder();
            for (int i = 0; i < 8; i++)
            {
                columns.Append("<ColumnDefinition Width=\"*\"/>");
                rows.Append("<RowDefinition Height=\"*\"/>");
            }
            return (ItemsPanelTemplate)
            XamlReader.Load($@"<ItemsPanelTemplate 
            xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
            xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                <Grid>
                    <Grid.ColumnDefinitions>{columns}</Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>{rows}</Grid.RowDefinitions>
                </Grid>
            </ItemsPanelTemplate>");
        }

        public void Init(ref ItemsControl display)
        {
            display.ItemsPanel = Layout();
            display.ItemsSource = Board.ChessSquares;
        }

        public void Tapped(ItemsControl display, ContentPresenter container)
        {
            ChessSquare square = (ChessSquare)display.ItemFromContainer(container);
            if (_square == null &&
                square.Piece != null)
            {
                square.IsSelected = true;
                _square = square;
            }
            else if (square == _square)
            {
                square.IsSelected = false;
                _square = null;
            }
            else if (_square != null &&
            _square.Piece != null &&
            _square.Piece.Set != square?.Piece?.Set)
            {
                square.Piece = _square.Piece;
                _square.IsSelected = false;
                _square.Piece = null;
                _square = null;
            }
        }

        public void New(ref ItemsControl display)
        {
            Board = new ChessBoard(fen_start);
            display.ItemsSource = Board.ChessSquares;
        }
    }
}

In the Code File for Library there are using statements to include the necessary functionality. There are enum values for the Game. There is a BindableBase Class which implements INotifyPropertyChanged there are SetProperty and OnPropertyChanged Methods.

There is a ChessCoordinate Class which represents the possible coordinates for Chess Pieces on a Chess Board such as “A6” there are int Properties for Id, Row and Column. There’s a ChessPiece Class which has Properties for PieceType and PieceSet and Implements BindableBase. The ChessSquare which Implements BindableBase congtains properties for ChessPiece and ChessCoordinate along with an int Property for an identifier and bool Property for selection.

The ChessPosition Class represents a List of ChessPiece and takes a string Parameter of a Chess Layout in Forsyth–Edwards Notation which is what the foreach and switch parts perform. There is a ChessBoard Class which represents a set of ChessSquare for a given Forsyth–Edwards Notation layout.

ChessSquareStyleSelector is used to select the appropriate Style for the squares of a Chess Board and will set the relevant ChessSquare Properties. The ChessPieceToGlyphConverter is used when displaying a ChessPiece Class and to use the relevant PieceSet and PieceType values to return the correct Unicode Character sequence to represent the given Chess Piece and BoolToVisibilityConverter is an IValueConverter to convert a bool to Visibility. The Binder Class is used to help with the Binding of DependencyProperty for the GridRow and GridColumn of the Layout

The Library Class contains a const string which is the Forsyth–Edwards Notation for the start of standard Chess game and there is a ChessBoard Property for the Chess Board itself, the Layout Method returns an ItemsPanelTemplate for the look-and-feel of the Game, the Init Method will initialse the Game and call the Layout Method. The Tapped Event Handler is used on a ChessSquare and will be used to set the “IsSelected” Property and remove any when the relevant conditions are met within the if … else Statements. The New Method is used to start the Game.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-lucky-chess

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 above the Grid element, enter the following XAML:

<Page.Resources>
	<Style TargetType="ContentPresenter" x:Key="SquareStyle">
		<Setter Property="local:Binder.GridRowBindingPath" Value="Coordinate.Row"/>
		<Setter Property="local:Binder.GridColumnBindingPath" Value="Coordinate.Column"/>
	</Style>
	<Style TargetType="ContentPresenter" BasedOn="{StaticResource SquareStyle}" x:Key="DarkStyle">
		<Setter Property="Background" Value="Peru"/>
		<Setter Property="Foreground" Value="Wheat"/>
	</Style>
	<Style TargetType="ContentPresenter" BasedOn="{StaticResource SquareStyle}" x:Key="LightStyle">
		<Setter Property="Background" Value="Wheat"/>
		<Setter Property="Foreground" Value="Peru"/>
	</Style>
	<local:ChessSquareStyleSelector x:Key="ChessSquareStyleSelector" 
	Dark="{StaticResource DarkStyle}" Light="{StaticResource LightStyle}"/>
	<local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
	<local:ChessPieceToGlyphConverter x:Key="ChessPieceToGlyphConverter"/>
	<DataTemplate x:Key="ChessTemplate" x:DataType="local:ChessSquare">
		<Grid IsHitTestVisible="False">
			<Grid.RowDefinitions>
				<RowDefinition Height="*"/>
				<RowDefinition Height="Auto"/>
			</Grid.RowDefinitions>
			<Ellipse Grid.Row="0" Grid.RowSpan="2" Fill="Gray" Opacity="0.75" 
			HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
			Visibility="{x:Bind IsSelected, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}}">
			</Ellipse>
			<Viewbox Grid.Row="0" Grid.RowSpan="2">
				<TextBlock IsColorFontEnabled="True" FontFamily="Segoe UI Emoji"
				Text="{x:Bind Piece, Mode=OneWay, Converter={StaticResource ChessPieceToGlyphConverter}}"/>
			</Viewbox>
			<TextBlock Grid.Row="1" Margin="1" FontSize="4" 
			Text="{x:Bind Coordinate.Notation}"/>
		</Grid>
	</DataTemplate>
</Page.Resources>

Then while still in the XAML View between the Grid and /Grid elements, enter the following XAML:

<Viewbox>
	<ItemsControl Name="Display" Margin="50" Width="400" Height="400" 
		ItemContainerStyleSelector="{StaticResource ChessSquareStyleSelector}" 
		ItemTemplate="{StaticResource ChessTemplate}" Tapped="Display_Tapped">
	</ItemsControl>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Page2" Label="New" Click="New_Click"/>
</CommandBar>

Within the Page.Resources block of XAML above the Grid Element contains Style definitions including a DarkStyle and LightStyle. There is also the ChessSquareStyleSelector, BoolToVisibilityConverter and ChessPieceToGlyphConverter. There is a DataTemplate which is for a ChessSquare which contains a Grid with elements to show the Notation value in a TextBlock including another within a Viewbox for the ChessPiece itself and an Ellipse which will be displayed when the “IsSelected” Property is set to true and hidden when this is false.

Within the main Grid Element, the first block of XAML is a Viewbox Control which contains a ItemsControl Control. The second block of XAML is a CommandBar with AppBarButton for New which calls New_Click.

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();

protected override void OnNavigatedTo(NavigationEventArgs e)
{
	library.Init(ref Display);
}

private void Display_Tapped(object sender, TappedRoutedEventArgs e)
{
	library.Tapped(sender as ItemsControl, e.OriginalSource as ContentPresenter);
}

private void New_Click(object sender, RoutedEventArgs e)
{
	library.New(ref Display);
}

There is an OnNavigatedTo Event Handler which will call the Init Method from the Library Class, Display_Tapped which handles when the ItemsControl has been Tapped and New_Click which will call the New Method of 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

Once the Application has started running you can tap on the appropriate Chess Piece and either move it to an Empty square or use to remove an opponent’s Piece from the Board.

uwp-ran-lucky-chess

Step 15

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

vs2017-close

Lucky Chess is based upon the UwpChess and UniversalChess examples by Chuck Ries and shows how to create a simple two-player Chess Board with a full set of pieces, you could extend this to show more pre-defined layouts or as an advanced exercise have it enforce the rules of Chess!

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