Share via


Adding shapes to your Windows Phone using some simple XAML and C# code

If you are starting out building games, and want to check out XNA development, you might want to take a look at my blog at https://blogs.msdn.com/devschool.  It discusses lot’s of things, randomly.

How do you add shapes to a silverlight based project in Windows Phone.  First you have to have a root for your game.  So open Visual Studio Windows Phone Express and on the MainPage.XAML (this is for version 4.0 if you are looking at this in the year 2015).

First off, when we get to the code piece, you will see that I use one of the Security components: RNGCryptoServiceProvider, this allows me to use a random number generator that creates a more random number, or in my way of thinking a random number that has less “color”.  The random number class that is generally included in the .NET Framework is random, but the number generated isn’t colorless, if you looked at it through a spectrum analyzer, you would see that there is a number of numbers it is usually generating.  For some games, that isn’t good enough.  In this case, if you try to use the random number generator included in the .NET Framework you would see that the circles and squares have a pattern.  If you use the RNGCryptoServiceProvider, the circles and squares are shown more randomly, feel free to experiment.  And students in my class at CSUDH are expected to demonstrate the difference in their homework (so I won’t show the solution here, yet).  URLs are provided with the code, in comments that show you where to go to get more information about the RNGCryptoServiceProvider.

 

Now get started building code:

Change the default code, which in the Visual Studio WIndows Phone Express 4.0 looks like the following:

<—Stuff above here keep, find the code that looks like the below -->

<Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style='{StaticResource PhoneTextNormalStyle}'/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="-3,-8,0,0" Style='{StaticResource PhoneTextTitle1Style}'/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentGrid" Grid.Row="1">
        </Grid>
    </Grid>

<—Keep the code below here, you might use it  –>

<—Replace the code between comments above with –->

<Grid x:Name="LayoutRoot" Background="Black">
       <Canvas x:Name="root" Width="480" Height=" 700" Background="White">
       </Canvas>
   </Grid>

<—End additional code, make sure that the x:Name=”root” isn’t changed that is how you reference the XAML in CSharp –>

image

 

Now click on the small triangle, in the Solution Explorer next to the mainpage.xaml (shown in a dotted circle in the graphic)

Double click on MainPage.XAML.cs, this is the code behind the presentation

 

 

 

 

 

 

In the code behind, MainPage.xaml.cs, you need to add a using statement at the top of the code window, make sure it is below the “using System” line, but above the namespace line:

using System.Security.Cryptography;

 

If you named your project CirclesandSquares, then you should see below the “using” statements:

namespace CirclesandSquares
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

//
    }
}

 

Now add some code:

//Place this code below the InitializeComponent(); line

GenerateBackGroundShapes(10);

//End

 

You will need to add some code to draw the circle and squares using random numbers, the method will called GenerateBackGroundShapes(10), and there will be 10 shapes drawn:

//Start the copy here, place the code directly below the right facing brace below “GenerateBackGroundShapes(10);

void GenerateBackGroundShapes(int numberOfShapes)
        {
            for (int i = 0; i < numberOfShapes; i++)
            {
                Ellipse ellipse = new Ellipse();               
                Rectangle square = new Rectangle();
                Random SimpleRandom = new Random();
                double size = GetRandInt(10, 800) * .05;
                int varyShape = SimpleRandom.Next(0,3);

                ellipse.Width = size*2 ;
                ellipse.Height = size*2 ;
                ellipse.Fill = new SolidColorBrush(Colors.Blue);

                ellipse.Opacity = 1; // GetRandInt(1, 5) * .1;
                square.Width = size;
                square.Height = size;
                square.Opacity = 1; // GetRandInt(1, 5) * .1;
                square.Fill = new SolidColorBrush(Colors.Red);

                int x = GetRandInt(0, (int)Math.Round(root.Height, 0));
                int y = GetRandInt(0, (int)Math.Round(root.Width, 0));

                if (varyShape == 2)
                {
                    square.SetValue(Canvas.TopProperty, (double)x + 1);
                    square.SetValue(Canvas.LeftProperty, (double)y + 1);
                    root.Children.Add(square);                   
                }
                else
                {
                    ellipse.SetValue(Canvas.TopProperty, (double)x);
                    ellipse.SetValue(Canvas.LeftProperty, (double)y);
                    root.Children.Add(ellipse);
                }
            }
        }

//end copy here

 

Now we need to add another procedure to randomize things, so right after the line last line, //end copy here, add the following:

//start code copy

public int GetRandInt(int min, int max)
    {
        Byte[] randomBytes = new Byte[10];

        /*****************************************************************
         *Implements a cryptographic Random Number Generator (RNG)
         *using the implementation provided by the cryptographic
         * service provider (CSP). This class cannot be inherited.
         ****************************************************************/
        RNGCryptoServiceProvider randomCrypto = new RNGCryptoServiceProvider();

        /*****************************************************************
         * Fills an array of bytes with a cryptographically strong sequence
         * of random values.
         * See: https://bit.ly/silverlightgames_GetByte
         ******************************************************************/
        randomCrypto.GetBytes(randomBytes);

        /*****************************************************************
         * Now convert the rndBytes to 32 bit integers using BitConvertor
         * BitConvertor: Converts base data types to an array of bytes,
         * and an array of bytes to base data types
         * For examples see: https://bit.ly/silverlightgames_bitconvertor
         *****************************************************************/
        int ShapeSeed = BitConverter.ToInt32(randomBytes, 0);
        Random rand = new Random(ShapeSeed);
        return rand.Next(min, max);
    }

//end code copy

If you have entered the code correctly, you should be able to run your project and see a screen that looks like the following:

image