Archive for 'Programming'

Game in development – at last!

I’m not sure exactly why. Confidence?  Time?  Simply being in awe of daring to do something that I hold in such high regard?  I simply don’t know but I’ve tried and tried to motivate myself to write a modern version of Laser Squad for a long, long time.  (Same goes with Dark Side, Hydrofool, Tau Ceti and Auf Wiedersehen Monty)  I got as far as a buggy version of Monty before real life took over.  Now I’ve got some motivation and I’ve pulled my finger out…

Rebel Forces is now in development!!!

I feel it would be a heresy to simply remake Laser Squad since, although it’s a classic, it’s also quite limited by the machine it was originally written on.  My intention is to remake an enhanced Laser Squad.  Cleverer, more flexible and with many more scenarios – even a campaign!

The current state of things is that I have defined the core C# objects and am building using MonoGame which should allow me to (eventually) publish for all the major platforms.  I’m going to charge a nominal fee for the game.  It would be nice to actually make some cash to pay for licences, etc. but I’m not planning on charging more than a pound for each version.

Currently in scope are:

Windows 8 Store, Windows, Windows Phone

in scope but lacking a licence:

Linux, Android, Ouya, PS Mobile, iOS, Mac OSX

Anyway, I digress.  I currently have the core objects in place albeit slightly threadbare.  I’m in the process of building an editor to allow me to build scenarios.  Naturally, once I have some scenarios ready, I can build an engine to process the moves, etc.

I don’t like to make detailed timescales since real life has a nasty habit of interfering in your plans but if all goes well, I’m hoping to have the editor up and running properly by mid-March.  Then I’d hope the engine would take another month to 6 weeks to build.  Finally, I’d hope that while testing, I can get my sprite sheets cleaned up with nicer graphics and ping in some music and sound effects.  Then a final round of beta testing (any volunteers?) and I can start putting together the releasable campaigns – with free future updates/campaigns subject to time and demand.

I also plan to contact Julian Gollop for permission to include the original missions as unlockable rewards in-game.  I’ve heard he’s made the game public domain but to have his blessing would make it even better.

One final thing, I’ve made the editor with a rule builder which should (hopefully) give stronger conditions and scoring for gameplay.  For example, I’ve included some sabotage/subterfuge rules to allow for missions where you hack a computer for data or even plant a virus.  Also, you could plant bombs or transponders for mother ships to target a particular location :)

If anyone has any other suggestions or ideas, please leave a comment.

VN:F [1.9.22_1171]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

Hello people. Is it really 10 months since my last post? I really need to pull my finger out. Sorry guys!

Anyway, onto the subject at hand. Why is the XML Serializer so piss poor?

Well, apart from being text-based meaning it’s quite large and bulky to begin with, it also has a massive overhead trying to work out what is what, what is not and how it’s going to store everything. We were working on a large(ish) quantity of data (about 150mb) and getting load times of 10+ seconds and save times of up to 40 seconds. Not ideal for a product that needs almost instant response.

A little bit of googling and I came across the following article in Code Project:

http://www.codeproject.com/Articles/15700/Optimizing-Serialization-in-NET

Ok, it means a little more work in understanding what the guy has done but my goodness! We got data serialization down from 40+ seconds to around 180ms! That was jaw-dropping!

The key is using the binary serializer and the library abstracts the detail quite simply so you literally tell the serializer what you want to save, what order and let it do its thing. The author deserves an award. The code isn’t rocket science and the implementation is very straight forward but the results are simply amazing.

Be careful though, you need to pay attention to the order and structure of your data but once written, it simply does it! Brilliant work Simon Hewitt!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

C# – The world of Events and Delegates

Those of us who have been playing with C# over the years have gotten used to the concepts of a delegate and an event but what use are they and how do we implement them?

Basically, an event is something that happens within the application and the application notifies the rest of the application about this event taking place. This could be useful for other parts of the application to take advantage of.

A delegate is a reference that allows you to run code based on the event that has taken place. But what use is that? It sounds all well and good but why would we want to do this?

Well, how about we write a game that has things shooting at each other. We don’t really want to write code that keeps checking things all the time. It’s much quicker and easier to just let the application tell you something has happened and react to it. So how do we do this?

Ok, here is a simple class:


namespace EventsAndDelegates
{
public class Firing
{
public event FireHandler Shot;
public delegate void FireHandler(Firing f, ShotOnTarget e);
public void Start()
{
while (true)
{
System.Threading.Thread.Sleep(1000);
if (Shot != null)
{
Random random = new Random();
int randomNumber = random.Next(0, 100);

ShotOnTarget SOT = new ShotOnTarget();
if (randomNumber > 80)
SOT.HitTheTarget = true;
else
SOT.HitTheTarget = false;
Shot(this, SOT);
}
}
}
}
}

This basically has a method that continuously loops. The method pauses for a second then generates a random number between 0 and 100, if the number is over 80 it sets the event’s argument ‘HitTheTarget’ to true, otherwise it’s set to false. It then fires the event indicating a shot has occurred.

Also, to make things a little easier on the eye, an EventArg class:


namespace EventsAndDelegates
{
public class ShotOnTarget : EventArgs
{
private bool wasHit;
public bool HitTheTarget
{
set
{
wasHit = value;
}
get
{
return wasHit;
}
}
}
}

This is nothing special, it just allows us to put data into the Event arguments which could come in useful later on…

Now the main form:


namespace EventsAndDelegates
{
public partial class frmMain : Form
{
private Firing fir;
private Thread oThread;
delegate void SetFireCallback(Firing f, EventArgs e);

public frmMain()
{
InitializeComponent();

fir = new Firing();
Subscribe(fir);
}

private void btnFire_Click(object sender, EventArgs e)
{
oThread = new Thread(fir.Start);
oThread.Start();
}

public void Subscribe(Firing f)
{
f.Shot += Hit;
}

private void Hit(Firing f, EventArgs e)
{
if (lbFeedback.InvokeRequired)
{
SetFireCallback d = Hit;
Invoke(d, new object[] { f, e });
}
else
{
ShotOnTarget feedback = (ShotOnTarget) e;
if (feedback.HitTheTarget)
lbFeedback.Items.Add("Hit the target");
else
lbFeedback.Items.Add("Missed the target");
}
}

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
// Stops crashing while closing form
oThread.Abort();
}
}
}

As you can probably work out, the form consists of a button called btnFire and a ListBox called lbFeedback. When you start the application, you are presented with the button and the empty listbox. Behind the scenes, the main form subscribes the Hit Method to the Firing delegate (which is observing the Shot event) allowing us to get feedback when the event is fired.

Now if we click the button, we create a thread that runs forever. This thread will contain the Firing object and will be running the Start routine within the object. As you know, every second the Start method will be taking a shot and reporting if it has hit or missed its target to the Shot event. Since we have subscribed the Hit method in the main form to the delegate, each time the event is fired, the Main Form’s Hit even gets fired also. Pretty neat eh? There is some code to allow safe threading to take place (for the curious, you can’t access objects via separate threads but you can create a local object with the same data which you can access. You create the local object, then call the Hit method again with the new objects and we don’t get an exception!) but then we add text to the ListBox. Either a hit or a miss notification.

The final method (formMain_FormClosing) just kills the thread before we close the applicaton or we get another exception when closing the application once we’re done.

So there you have it, Events and Delegates in a fairly simple example. Using this functionality should significantly help people componentise their code and allow them to be able to drop whole classes easily into other applications with practically no code changes to the class required! Much, much easier in the long run!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Assembler – How it works!

Ok, I wanted this to be a C# and XNA blog but, as a related aside, I’ve been wanting to learn Assembly Language since I first became aware of it as a 7 year old. It was the language all the great 8-bit games were written in and nearly 30 years later my interest hasn’t really diminished. I’ve always felt that knowing how the machine under the hood processes your code is going to be a help in writing more efficient programs in whatever your language of choice is. I just never really got around to it. I’ve been toying with remaking Laser Squad for years. It’s a personal favourite and still very playable some 23 years later. Extracting the stats and learning how some of the pathfinding routines work would require some reverse engineering meaning I’d need to learn Assembly.

Anyway, a few weeks ago I asked fellow members of RR if they knew of some good resources to learn Z80 Assembler for the Amstrad or Spectrum. Emulators are freely available and generally have some excellent features so I thought that if I could get hold of some tutorials, I could have a read during my lunchbreaks and pick up the language over a number of weeks. I’ve done computing at GCSE, A-Level and degree level and knew loads of theory but never actually got taught how to write Assembler code. Lessons on “Twos Compliment” and “Binary Coded Decimal” as well as learning what a mantissa is, understanding how stacks and linked lists work is… Yawn-o-rama! I expected it to be a hard trek but…

THERE IS NOTHING TO IT!

All those lessons. All that boring theory. What would have helped? Giving a bloody context as to why we were learning all this. I expected numbers and things to be stored automagically in these formats and I had to be aware of them. I was also very confused as to how we’d know what was stored in which format. If the lecturer had simply said, “These are not mandatory, they are just efficient ways to storing numbers on a computer. It is up to YOU as to which you use, when and why you use them” I’d have probably learnt Assembly language years ago. I can sum up Assembler as the following bullet points:

    – You move numbers around using memory addresses and registers
    – Some registers are more important/useful than others
    – There are flags indicating something has happened
    – You can change bits using AND, OR and XOR
    – There are conditional jumps – basically ‘goto’ and ‘gosub’
    – You can call firmware routines directly to do stuff
    – There is a stack to store information while you use a register for something else

That’s pretty much it! If you want to store numbers as 16-bit values or 8-bit twos compliment, IT’S UP TO YOU! Naturally it requires a lot of coding to do some very simple stuff but you are poking about with the giblets of the machine and that’s delicate.

If you’ve been thinking about learning it for a while and have (like me) been put off by A-level teachers teaching theory without explaining its purpose, give it a go! The thread is easy enough to find on RR, the Amstrad tutorials are great and WinAPE is incredibly powerful. If you have any problems, drop me a line and I’ll try and point you in the right direction.

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

C# – goto, the spawn of satan

Oops, it’s been a week since I last posted but I guess I earned a break from working hard and I was struggling for an issue I came across recently. Then a quick google and I noticed some code that used something I haven’t seen since I was a teenager programming in locomotive basic on my Amstrad CPC 6128… a goto statement. I knew that C# does have this command and there are people out there who argue that it is useful. It probably is, but for the sake of your (and anyone who would be maintaining your code in future) sanity, DON’T do it!

I had another skim through the internet and found the following source code that uses goto:


for(int i = 0; i < size.Width; i++) { for(int j = 0; j < size.Height; j++) { Color c = Color.FromArgb((int)pixels[i,j]); if(c.A < 255) { hasAlpha = true; goto breakSpot; } } } breakSpot:

as you can see, the user is trying to iterate through a 2D array looking for a pixel with a value larger than 255 (meaning it has an alpha value) and is then exiting the loop. Despite this being a (relatively) safe usage of the goto statement, it makes for lazy coding.

How would I do it? well, here is what I'd do...


for(int i = 0; (i < size.Width && !hasAlpha); i++) { for(int j = 0; (j < size.Height && !hasAlpha); j++) { Color c = Color.FromArgb((int)pixels[i,j]); if(c.A < 255) { hasAlpha = true; } } }

Oooh, you didn't know you could do that did you? It's a for loop! You have a start value, an adjuster and a condition. The condition doesn't even have to have anything to do with the value used to count the loop. It generally does but it isn't required.

Anyway, I hope someone found that useful and that I've advanced the cause of the 'anti goto' movement. Enjoy!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

C# – Interfaces… why?

Yep, you read right. Why on earth do we use interfaces? I’ve seen a plethora of crappy examples involving shapes, fruits, vegetables, etc. attempting to explain why we use inheritance and interfaces. Bloody useless! Why? They have no proper real-world application that we can associate with. Unless you’re a mathematician or a greengrocer, why on earth would you care about fruit or shapes?

Ok, lets start with a definition of an interface.

An interface is a contract of service within a programming language.

Ok, what on earth does THAT mean? It means when you implement an interface, you are agreeing to provide functionality that satisfies the interface contract.

So… what use is that exactly?

An interface would be a structure with no implemented methods. A (terrible) example from MSDN is:


interface IMyInterface: IBase1, IBase2
{
void MethodA();
void MethodB();
}

This defines an interface with two methods. MethodA and MethodB. It has no implementation code. It also can inherit other interfaces (IBase1, IBase2) so you can structure them. That’s more a FYI than anything because that complicates things far too much for the simple explanation I want to give out.

Interfaces can be very useful. Let’s use a real-world example that we should all be fairly familiar with. Let’s pick an ATM at a bank. (I pinched this example for a C# design book I picked up about 7 years ago. I don’t have the book to hand or recall the exact name. I may add it here at a later date)

A bank ATM has the following basic functionality:

– Enter Pin Number
– Check balance
– Pay in Money
– Withdraw Money
– Print Mini-Statement
– Sign out

If I pop over to my bank branch, I get a few more functions but that’s nice and simple for now. In the UK, we have a system called ‘LINK’. Basically, this allows account holders of a LINK member bank to use basic functionality at another LINK member bank’s ATM for free. Naturally, this would have limited functionality since it can get quite busy on banking networks and you really want minimal traffic so the banks will want to provide basic functionality on their ATMs for LINK member account holders. So, how do we guarantee the same functionality on all ATMs? Every bank functions slightly differently to the other so what are we going to do? Yep, that’s right, we use an interface!

The interface could be structured as follows:


interface ILinkFunctions:
{
double balance;

void CheckPin();
void ShowBalance();
void WithdrawCash();
void PayInMoney();
}

If every bank implemented this interface for their ATM software when dealing with LINK customers, they all get the same functionality!!

This now means that when you use a LINK machine, you will have the same basic functions wherever you go. Not only can you use this to guarantee that certain functionality exists, you can also use the interface as a type when making use of the functionality in other parts of your code. Here’s a simple example of that in use:


public void SpecificLinkFunction(ILinkFunctions source)
{
--Implementation here--
}

The above code allows you to make use of the knowledge that ILinkFunctions has certain guarantees. Think of how you could be writing a game in XNA and you want to process ALL sprites rather than have to process individual categories of sprite (baddies, hero, bosses, bullets, etc.). If all these sprite classes implemented an interface, you could process all sprites of that type in one simple function that made use of the interface they all share! Doesn’t that make life so much easier?

I’ve barely touched the surface here and I’m waffling on but a nice little example involving pencils is online here

Good luck!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

C#, XNA – The problem with Monty

Ah! Monty Mole! That loveable character from the 1980s series of games for the Amstrad, Spectrum and Commadore. As some may already know, I’m in the process of remaking “Auf Wiedersehen Monty” with the outstanding help of Lobo and Infamous. Sadly, finding time to complete this while my work/financial situation is so bad at the moment is a bit of a problem. Despite needing to re-work the collision detection and pretty much finish the thing, it is gone quite well so far. I thought I’d share one of the interesting ideas that some people may not realise they can do in C# and XNA which is storing the state of the user controlled sprite as an enum! Here’s a snippit of code from the game:


// Deals with Stationary and moving for animation purposes
if ((((mCurrentState == MontyState.WalkingLeft) || (mCurrentState == MontyState.WalkingRight)) || ((mCurrentState == MontyState.ClimbingUp) || (mCurrentState == MontyState.ClimbingDown))) || (mCurrentState == MontyState.Stationary))

It looks a little complex doesn’t it? Simply translated, it basically checks whether the Monty character is walking left, walking right, climbing up, climbing down or stationary. I’m sure you could have worked that out but it is so much more readable like that isn’t it? Much more readable and efficient than creating loads of flags or a numerical variable with sokme kind of coded number representing the character’s status.

So… how did I do this? Well, I used an enum! The code is here:


public enum MontyState
{
Stationary,
WalkingLeft,
WalkingRight,
JumpLeft,
JumpRight,
JumpUp,
UpsideDown,
InCableCar,
ClimbingUp,
ClimbingDown,
SuperJumping,
FlyingPlane,
Dead
}

This now means I can create a variable like this:


public MontyState mCurrentState = MontyState.Stationary;

Whenever something happens, I change Monty’s state to whatever it should be and the program can react accordingly. I’m probably teaching some people how to suck eggs here but I did have a good think before I decided to take this approach. Making it public means you can use the status in other parts of the application too. You can even make it static if you wish.

Enjoy!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

C# – Accessing attributes directly in XML

Well hello and welcome to my blog.  God knows if it’ll be of any use to anyone but if it is, I’d appreciate a comment saying so.  It isn’t much but it’ll make me think that I do occasionally do something worthwhile for the world.

Right, onto the topic of the first post.  If, like me, you get pissed off with hunting the internet for an example of some code that does something similar to what you’re trying to achieve but never seem to find it, read on.  That’s pretty much the main reason I set this blog up;  to highlight minor (and major) issues in development that crop up from time to time and post a solution (even code, you never know) for others to make use of.

Anyway, the other day I was working on some code that processed some XML and I was required to produce some C# that extracted a particular value from this file.

Use LINQ I hear you cry!  Not in .NET 2.0 you can’t.  I hunted around for examples and, lo and behold, I found nothing of any real use.  Plenty of examples that use foreach loops to iterate through the many attributes and writes them out to the console but nothing exactly describing what I needed. (By the way, who the hell does that in the first place?  MSDN!  I’m looking at you here.  Producing piss-poor examples is no help to anyone!)

Anyway, onto the code.  Let’s take an example XML file like the following:

<?xml version=”1.0″?>
<TheDocument xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”>
<TheHeader Version=”3″ FileType=”1″ Size=”44″/>
<Data>
<DataRow>454,500,544,525,474,484,484,553</DataRow>
<DataRow>454,500,544,525,474,484,484,553</DataRow>
<DataRow>454,500,544,525,474,484,484,553</DataRow>
</Data>
</TheDocument>

Ok, it’s a bit crappy but it is an example.  Anyway, I need to access “FileType” from “TheHeader”.  How do I do it?

Here’s how:

// Create the XML Document
XmlDocument _xmlFile = new XmlDocument();

// Create an XmlTextReader to load the file
XmlTextReader reader = new XmlTextReader(@”C:\SampleFile.xml”);

// Load the file into the XML Document using the reader
_xmlFile.Load(reader);

// Set up an XML element and pop the document into it
XmlElement root = _xmlFile.DocumentElement;

// OK, now select that attribute
int _fileVersion = Int32.Parse(root.SelectSingleNode(“/TheDocument/TheHeader/@Version”).Value);

Although this example is fairly specific, you should be able to create a C# project, paste the code in and get it working quite quickly.  You will need to include the following using statements at the top though:

using System.Xml;
using System.IO;

You’d have to hunt high and low to find anything that useful on t’internet.

Anyway, please be gentle as it was my first post.  All feedback welcome and any suggestions for future posts would be nice too.

Toodle pip!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)