Wednesday, February 16, 2011

XMLImageLoader


I've just completed the XMLImageLoader class (and accompanying XMLImage class). XMLImageLoader loads up an XML file containing data on images for use in the game, then puts each images data into an XMLImage object. These are held together by a Dictionary, and have strings to identify them by. Later, support for animations will be added, but Snake doesn't require animations, it can be done programatically.

Something I had some difficulty with is reading the XML files. Reading an XML file is painful, as your best option is to just scan through each node and make some seriously bad assumptions. I couldn't seem to find a way to do it more effectively, and resulted in this:

while (reader.NodeType != XmlNodeType.EndElement && reader.Name != "image")
{
    if (reader.NodeType == XmlNodeType.Element)
    {
        switch (reader.Name)
        {
            case "name":
                reader.Read(); //Read to XmlNodeType.Text
                name = reader.Value;
                reader.Read(); //Read to XmlNodeType.EndElement
                break;
            case "width":
                reader.Read(); //Read to XmlNodeType.Text
                width = int.Parse(reader.Value);
                reader.Read(); //Read to XmlNodeType.EndElement
                break;
            case "height":
                reader.Read(); //Read to XmlNodeType.Text
                height = int.Parse(reader.Value);
                reader.Read(); //Read to XmlNodeType.EndElement
                break;
            case "file":
                reader.Read(); //Read to XmlNodeType.Text
                file = reader.Value;
                reader.Read(); //Read to XmlNodeType.EndElement
                break;
        }
    }
    reader.Read();
}


XMLTextReader (which is what "reader" is in the above code snippet) only seems to have the ability to read to the next node. I can't tell it to read to the next element, or to read to a specific element. I would have to create loops to do specifically that. Perhaps it would be useful to later create a class that inherits from XMLTextReader but has a better selection of functions to move around the XML file? Certainly something like this already exists... Oh well.

However, this code now lays the groundwork for image loading in our games. It's built in a way that we can expand upon it later if need be.

Tomorrow, will add support for the actual loading of images into the game.

No comments:

Post a Comment