Thursday, 2 April 2009

Getting Started with XNA Game Development Studio 3.0

XNA Game Studio is now in it's third incarnation and well worth having a play with if you've even a passing interest in developing your own games. It includes Hardware acceleration and an API geared towards moving 2D and 3D graphics around the screen - and is so much easier to pick up than the old Managed DirectX.

You can download it here, and it can even be used in conjunction with the Microsoft C# Express edition.

I'm going to illustrate how easy it is to get started, by displaying a 2D Sprite, which will be hardware accelerated, and subsequently moving it around the screen.

Here's the sprite we'll be using:



I know, I'm so artistic.

Once you've got XNA installed, load up Visual Studio and create a new XNA Game Studio project, selecting the one labelled Windows Game (3.0).

Open up the solution explorer if it's not already visible, right click content, then Add Exisiting, and choose the location that you saved the above sprite to. You should then see Sprite1.png appear under Content in the solution explorer.

Now, open up Game1.cs and add the following two declarations inside the Game1 class:


Texture2D playerTexture;
Vector2 playerPosition;

These will hold the sprite texture, and position respectively. Now we need to load our sprite into memory. Find the LoadContent method, and add to it so it looks like the following:

protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);

// TODO: use this.Content to load your game content here
playerTexture = Content.Load<Texture2D>("Sprite1");
}

Likewise, do the same for the Initialise method, where we'll set the initial position of the player:

protected override void Initialize()
{
// TODO: Add your initialization logic here
playerPosition = new Vector2(20, 20);

base.Initialize();
}

Done that? Good. Finally, we need to draw the sprite on the screen. Find the Draw method, and add code so it looks as follows:

protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);

// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(playerTexture, playerPosition, Color.White);
spriteBatch.End();

base.Draw(gameTime);
}

Now press F5, and all being well you'll see your sprite on the screen:



Now let's add the ability to move our sprite up and down. Find the Update method and add the following code to allow our player to be moved up and down with the arrow keys:

protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();

// TODO: Add your update logic here

if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Down))
{
float y = playerPosition.Y;
float x = playerPosition.X;
playerPosition = new Vector2(x, y + 2);
}

if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Up))
{
float y = playerPosition.Y;
float x = playerPosition.X;
playerPosition = new Vector2(x, y - 2);
}

base.Update(gameTime);
}

Hit F5 again, and congratulations! You successfully displayed a 2D hardware accelerated sprite on the screen and enabled it to be moved up and down. This is a simple example, but hopefully you get an idea of how rapidly you can put together a simple game using XNA Game Develpopment Studio.

Labels: , , ,

Bookmark and Share

Tuesday, 10 March 2009

Obfuscating a String with XOR in C#

Related to my recent posts on conversion and bitwise operators, I'm going to talk a little bit about obfuscating a string with XOR as a practical example of both string to byte conversion, and the bitwise XOR operator.

Although this could also be considered encryption in some schools of thought, on its own this is so weak as an encryption technique I prefer to think of it as obfuscation.

XOR obfuscation does have its place. It can be used to easily thwart simple plain text searches, for example. If you have hardcoded strings in an assembly, you could hardcode obfuscated strings instead, so that the plain text string value does not show up in a search. You could also apply obfuscation before subsequently performing a secure encryption method, thus making it harder for a determined hacker to determine whether or not a valid decryption has been performed - since the decrypted string will still be obfuscated.

But by itself, think of it as one of those magic pens that writes in ink that is only visible under ultraviolet light. Enough to protect data from a casual user or passer-by, but absolutely useless in protecting information from someone that knows what they're trying to do and has some degree of competency.

Here's a function that will obfuscate a string then:


private string XORString(string inputString, byte key)
{
ASCIIEncoding Encoder = new ASCIIEncoding();
byte[] ByteArray = Encoder.GetBytes(inputString);
for (int i = 0; i < ByteArray.Length; i++)
{
ByteArray[i] ^= key;
}

return Encoder.GetString(ByteArray);
}

Pretty simple. Convert our input string into a byte array, then XOR each byte in the array with a key value, and return the reconstructed string.

And here's why you shouldn't rely on this technique to protect anything you want to keep secret:


private void BruteForceXORString(string inputString)
{
ASCIIEncoding Encoder = new ASCIIEncoding();

byte XORVal = 0;
byte[] ByteArray;

while (XORVal < 255)
{
ByteArray = Encoder.GetBytes(inputString);

for (int i = 0; i < ByteArray.Length; i++)
{
ByteArray[i] ^= XORVal;
}

Debug.WriteLine(string.Format(
"{0}: {1}",
XORVal,
Encoder.GetString(ByteArray)));

XORVal++;
}
}

In next to no time, this function will output every possible decoding of an obfuscated string which has been XOR'd with a byte value. Say I'd obfuscated the string "Visual Studio" with an XOR value of 16:


As you can see, there is the original string plain to see after very little effort.

Use with caution, and always ask yourself, "Am I happy hiding this information with a virtual magic pen?"

Labels: ,

Bookmark and Share

Thursday, 5 March 2009

C# Bitwise Operators

It's essential to master the logical bitwise operators if you're working with the individual bits of a byte on a regular basis. In the real world, it's especially useful when interfacing with industrial hardware (hardware engineers love digital I/O), working with flags, or if you're writing an emulator, in which case it's what you'll spend a lot of time doing. So here's a quick reference.

Note that you wouldn't usually create a seperate function just to perform a logical bitwise operation, I've done it in the examples below for clarity.

To test the value of a bit, use the Logical AND operator. In the following code, the bit parameter is the bit(s) to check, and the mask parameter is the value in which to test the set bit.

private bool TestBit(ushort bit, uint mask)
{
// AND
return (mask & bit) == bit ? true : false;
}

i.e. to check if bit 4 was set in a uint called MyValue:

bool Result = TestBit(8, MyValue);

To set the value of a bit, use the Logical OR operator.

private void SetBit(ushort bit, ref uint mask)
{
// OR
mask = (mask | bit);
}

Note that this could also be reduced to the following by using the bitwise OR compound assignment operator:

private void SetBit(ushort bit, ref uint mask)
{
// OR
mask |= bit;
}

To toggle bits between zero and one, use eXclusive OR, also known as XOR. Exculsive OR looks at the two values to be XOR'd together bit by bit and asks, "Is only one of these bits set in each value?" If so, the resultant bit is set. Otherwise, it is cleared.

To clarify, consider the following:

Decimal 7 = Binary 0111
Decimal 2 = Binary 0010
Decimal 5 = Binary 0101

7 XOR 2 = 5

You should be able to see why from looking at the above binary representation. Here's how we'd do it in C#:


private void ToggleBits(uint key, ref uint value)
{
// XOR parameters together
value ^= key;
}

private void PerformOp()
{
uint Value = 7;
uint Key = 2;
ToggleBits(Key, ref Value);
}

Shifting Bits


To shift bits left and right, you can use the << (shift left) or >> (shift right) operators. As with all the other logical bitwise operators, you can also combine these with an equals sign to get a compound shift operator, e.g. <<= Shifting bits to the left has the effect of multiplying your original value by 2. Consider: Decimal 7 = Binary 00111 Shifting the bits left by 1 bit gives us 01110, which is, as expected, 7 multiplied by 2, which is 14. Shifting left again gives us 11100, which is 28, or 14 multiplied by 2. In C#:

private void ShiftLeft(ref uint value, ushort numberOfBitsToShift)
{
// Shift bits left
value <<= numberOfBitsToShift;
}

If you shift a set bit outside the range of your variable, the value is lost. For example, if I shift a whole byte set to 255 to the left, I end up with 254:

11111111 << 1 = 11111110

As shifting bits is less computationally expensive than multiplying values together, historically bit shifting is a common technique employed in assembly language when something has to run as fast as possible. Graphics rendering, for example.


Shifting right has a similar effect, but divides a number by 2. I won't post code for shifting right, I'm sure you get the idea by now. If not, you're in trouble!

I should probably also cover One's and Two's Complement. I'll do that in Part II.

Labels: ,

Bookmark and Share

Wednesday, 11 February 2009

Creating a C# MenuStrip with Custom Colours

If you've ever wanted to create an application with it's own theme settings, it's likely that at some point you'll want to have a MenuStrip Control that doesn't inherit either the colours of your current system theme or the default system colours. Here's how you can create a derived System.Windows.Forms.MenuStrip control, with custom colours applied. To do this, we're going to need to create two new classes - one that derives from System.Windows.Forms.MenuStrip and one that derives from System.Windows.Forms.ProfessionalColorTable. Firstly, add a class and derive it from ProfessionalColorTable. You'll need to reference the System.Windows.Forms namespace.

class CustomToolStripColorTable : ProfessionalColorTable { }

In this class, you can override the colour properties that you wish to change. Let's start with the two that will be immediately obvious -
MenuStripGradientBegin and MenuStripGradientEnd:

public override Color MenuStripGradientBegin
{
get { return Color.FromArgb(132, 168, 206); }
}

public override Color MenuStripGradientEnd
{
get { return Color.FromArgb(192, 192, 192); }
}

Ok. Now let's create our
MenuStrip and assign the custom ColorTable to it. Add a new class which derives from MenuStrip. Visual Studio will automatically work out you're deriving from a control and create InitializeComponent etc. :

public partial class CustomMenuStrip : MenuStrip
{
InitializeComponent();
}

To ensure visual styles are enabled, add the line:

ToolStripManager.VisualStylesEnabled = true;

To declare an instance of our Colour Table, and assign to the
MenuStrip, add the lines of code:

CustomToolStripColorTable CustomTable = new CustomToolStripColorTable();
CustomTable.UseSystemColors = false;
this.Renderer = new ToolStripProfessionalRenderer(CustomTable);


It's very important to set
UseSystemColors to false, or your colour changes won't show up.

Add a form, and add a custom
MenuStrip to it. Add a few menu items so you get a feel for how it's going to look. The custom colours should show up in the designer, but run the project to see the final result. Override the additional ProfessionalColorTable properties to change the colour of other elements in the MenuStrip.

You can also apply a custom
ProfessionalColorTable to a ToolStrip Control, should you want a custom toolbar to match your custom menu.



Be sensible with those colours, you've now got the power to do truly hideous things.

Labels:

Bookmark and Share

Wednesday, 28 January 2009

Visual Studio - Dock or Anchor?

There's two very important UI concepts to grasp when designing windows Forms in Visual Studio - Dock, and Anchor. These can be used to make the best use of available space when your form scales to different screen resolutions.

Dock

Dock effectively sticks a control to one, or all sides of the parent container, with 'Fill' being the option that docks to all sides. The gap that is left between the sides of the parent container and the child control(s) docked in it can be controlled using the parent's Padding property.

In the following example, you can see the effect the dock property has on a standard button when applying each particular dock setting. Padding is left at the default value of zero:

And here you can see the effect of having the Dock Property set to 'Fill', with the padding property on the parent container set to a value of 10:

Even if the form is resized, dock will cause controls docked to an edge to move or scale appropriately.

Anchor

Anchor works differently, and is used to maintain a constant distance between the edge of a control and the container it is in. The anchor property can be applied to between zero and four sides - left, right, top and bottom. Controls default to docking to the top and left sides of a form. If you dock a button on a form to the bottom and right, your button will move both down and right when a user resizes the form in those directions. For example, here's our button, anchored bottom and right, moving as the form is resized:

Finally, it's worth bearing in mind that unlike their nautical equivalents, you can't dock and anchor at the same time. But that's ok; we're not on a boat.

Labels:

Bookmark and Share

Sunday, 25 January 2009

How to Bind an Enumerated Type to a ComboBox

Simple, when you know how. Let's say we have a custom enumerated type of car manufacturers:



Now I'm going to create a method whose purpose is to bind the manufacturers enum to a ComboBox:




You might also want to change the "DropDownStyle" property on your ComboBox to "DropDownList" to stop people typing their own data into the ComboBox. And that's all there is to it. Call your binding method, and you've bound your enum.



Labels:

Bookmark and Share