Universal Windows Platform – Chase Game

Chase Game demonstrates how to create a game where after a certain amount of time four squares will appear then within a countdown you must select all of them and shows how to create a simple game mechanic based on time.

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, 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-library

Step 7

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

using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

public class Library
{
    private const int size = 4;
    private const int on = 1;
    private const int off = 0;

    private readonly Color light_on = Colors.White;
    private readonly Color light_off = Colors.Black;

    private int[,] _board = new int[size, size];
    private DispatcherTimer _timer = null;
    private Random _random = new Random((int)DateTime.Now.Ticks);
    private List _positions = new List();
    private int _counter = 0;
    private int _turns = 0;
    private int _hits = 0;
    private int _wait = 0;
    private bool _waiting = false;
    private bool _lost = false;

    private List Shuffle(int start, int end, int total)
    {
        return Enumerable.Range(start, total).OrderBy(r => _random.Next(start, end)).ToList();
    }

    private Rectangle Get(Color foreground)
    {
        Rectangle rect = new Rectangle()
        {
            Height = 80,
            Width = 80,
            Fill = new SolidColorBrush(foreground)
        };
        return rect;
    }

    private void Set(ref Grid grid, int row, int column)
    {
        Button button = (Button)grid.Children.Single(
                       w => Grid.GetRow((Button)w) == row
                       && Grid.GetColumn((Button)w) == column);
        button.Content = Get(_board[row, column] == on ? light_on : light_off);
    }

    private void Add(Grid grid, TextBlock text, int row, int column, int index)
    {
        string name = string.Empty;
        Button button = new Button()
        {
            Height = 100,
            Width = 100,
            Content = Get(light_off)
        };
        button.Click += (object sender, RoutedEventArgs e) =>
        {
            if (!_lost)
            {
                button = (Button)sender;
                row = (int)button.GetValue(Grid.RowProperty);
                column = (int)button.GetValue(Grid.ColumnProperty);
                if (_board[row, column] == on)
                {
                    _board[row, column] = off;
                    Set(ref grid, row, column);
                    _hits++;
                }
                else
                {
                    _lost = true;
                }
            }
            else
            {
                text.Text = $"Game Over in {_turns} Turns!";
            }
        };
        button.SetValue(Grid.ColumnProperty, column);
        button.SetValue(Grid.RowProperty, row);
        grid.Children.Add(button);
    }

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

    private void Reset(Grid grid)
    {
        for (int column = 0; column < size; column++)
        {
            for (int row = 0; row < size; row++)
            {
                _board[row, column] = off;
                Set(ref grid, row, column);
            }
        }
        _hits = 0;
        _counter = 0;
        _wait = Shuffle(3, 7, 1).First();
        _waiting = true;
    }

    private void Choose(Grid grid)
    {
        int row = 0;
        int column = 0;
        _positions = Shuffle(0, _board.Length, _board.Length);
        for (int i = 0; i < size; i++)
        {
            column = _positions[i] % size;
            switch (_positions[i])
            {
                case int n when n = 4 && n = 8 && n = 12 && n 
        {
            if (!_lost)
            {
                int countdown = 0;
                if (_waiting)
                {
                    countdown = (_wait - _counter) + 1;
                    text.Text = $"Waiting {countdown}";
                    if (countdown == 0)
                    {
                        text.Text = string.Empty;
                        Choose(grid);
                    }
                }
                else
                {
                    countdown = (size - _counter) + 1;
                    text.Text = $"Solve In {countdown}";
                    if (countdown == 0)
                    {
                        if (_hits == size)
                        {
                            _turns++;
                            text.Text = string.Empty;
                            Reset(grid);
                        }
                        else
                        {
                            _lost = true;
                            text.Text = $"Game Over in {_turns} Turns!";
                            Reset(grid);
                        }
                    }
                }
                _counter++;
            }
        };
        _timer.Start();
    }

    public void New(ref Grid grid, ref TextBlock text)
    {
        _lost = false;
        _waiting = true;
        _wait = 3;
        _turns = 1;
        Layout(ref grid, ref text);
        Timer(grid, text);
    }
}

Within the Library Class there’s some int values for On and Off states plus a corresponding Color for each of these, there’s a int[,] for the game board plus the DispatcherTimer which will be used as the timer – the usual random number generator for a game is used along with variables for state information. There is the Shuffle method that uses the random number generator to generate a sequence of numbers but with “start”, “end” and “total” parameters and the Get method returns a Rectangle with a given Foreground colour, also there’s a Set method to set a Button to use that Get method. The Add method creates a Button with a Click event that will get the Row and Column and if it is “lit up” then it will set that to off otherwise it will count as a miss and the game will be over – controlled by lost variable being set to true.

The Layout method creates the initial layout for the game and Reset will clear the board so that all the Button elements will appear in their Off state, Choose uses the Shuffle method to randomly select which four Button elements will appear in the On state. The Timer method is what controls the flow of the game with the first part of this checking for an existing Timer and stopping and clearing it – by setting to null then a new DispatcherTimer is created with a one second interval then on the Tick event of the time which will occur each second there is a check to see if the game is “lost” then two countdowns for either a Waiting or Solve In countdown – the former will have a random time used which is set from the Reset method or a four second countdown to solve the puzzle by clicking on the buttons.

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 Margin="50">
	<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
		<TextBlock Name="Label" TextAlignment="Center" HorizontalAlignment="Center" 
		Style="{StaticResource SubtitleTextBlockStyle}" Width="400"/>
		<Grid Name="Display" HorizontalAlignment="Center" Height="400" Width="400"/>
	</StackPanel>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Page2" Label="New" Click="New_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Game, this features a ViewBox containing a StackPanel with a TextBlock and a Grid to display the game itself within. 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.New(ref Display, ref Label);
}

Below the MainPage() Method an instance of the Library Class is created, then New_Click is used to call the New Method to setup the game and start playing.

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 you can then select New to start the game then begins a timer which will be displayed on the TextBlock with Waiting Countdown and once complete a Random selection of Squares will be lit up White within a set of Black squares and you need to hit them all within the Solve Countdown otherwise it will be Game Over and you can keep going for as many Turns as you can!

ran-chase-game

Step 15

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

vs2017-close

There are many games based on this concept but this is just a simple way of creating a timer based game. The concept of a game loop is common to games large and small and it was a good excuse to use this and show it off, the timer interval is probably too long but make it easy to see what’s going on, if want to increase the difficulty could reduce the tick interval to half or even a quarter of a second, that might make it more interesting as if you hit the black buttons you’ll lose which is more likely the faster you make it! The concept of using a timer to drive the game can be used to create any kind of game so this example was just a simple way of doing that without the game itself being too complex, although as-is the game is very easy to play, just need to make those modifications!

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 )

w

Connecting to %s