Sunday, September 20, 2009

PHP - SimpleXML forever

Part of the Kriegsland game is to be a modular customizable rule system. Now, I have a lot ideas for this game and the prospect of hard-coding the entire rule system seemed a bit short sighted. I don't want to end up with pages and pages of spaghetti code down the road.

So instead I've thought about the extent of the rule systems power. Based on stats it will generate a random variable which will determine the success or failure of a possible action based on its probability which will be predetermined by the specific weighting of the various variables.

So... Yeah, if you got through that well done. It's a bit to get ones head around but I think I've almost cracked it. I'm going to write the engine once and then have an easily editable xml file to fine tune until I'm happy with the rule system.

Which brings me to programmatic XML handling. There are basically two types, event based (Eats XML piece by piece to avoid a large memory footprint) and DOM based (Eats the entire XML file and creates a nice file to play with).

I've looked around for a nice DOM solution in Java and C-Sharp but was actually having trouble finding something that fit the bill. Eventually on my return to PHP I've found SimpleXML. Sample code here.


// displays contents of nodes
if(!$xml=simplexml_load_file('rules.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}
echo 'Displaying rule names of XML file...
';
foreach($xml as $rule){
echo 'Name: '.$rule->name.'
';
}

?>

Simple as that! The elements of the XML file are all exposed as arrays. If the rule element given as an example above had multiple elements of type name you could create another loop like this.

echo 'Displaying rule names of XML file...
';
foreach($xml as $rule){

foreach($rule->name as $name) {
echo 'Name: '.$name.'
';
}

}


Great, simple and short. I'm going with this. The rule system will have a single instance kicked off by a cron-job so the memory footprint isn't an issue. My Plan is now to create a unified Rules object that can handle the parsing of the XML and then act as a DAO for the game engine.

Good fun anyway.

No comments:

Post a Comment