Skip to content

Instantly share code, notes, and snippets.

@back2dos
Created April 4, 2018 08:01
Show Gist options
  • Save back2dos/e7e173fb14472e88b5f104d44803b8bb to your computer and use it in GitHub Desktop.
Save back2dos/e7e173fb14472e88b5f104d44803b8bb to your computer and use it in GitHub Desktop.
Example usage for tink_xml.
// items.xml to be found at https://raw.githubusercontent.com/dougmencken/HeadOverHeels/master/gamedata/items.xml
// Run per `haxe -lib tink_xml --run Main`
using sys.io.File;
class Main {
static function main() {
var s = new tink.xml.Structure<Array<Entry>>();
switch s.read('items.xml'.getContent()) {
case Success(entries):
var doors = [],
items = [];
for (e in entries) switch e {
case Door(d): doors.push(d);
case Item(i): items.push(i);
}
Sys.println('Found ${entries.length} entries total (${items.length} items and ${doors.length} doors)');
Sys.println('Random item: ${items[Std.random(items.length)]}');
Sys.println('Random door: ${doors[Std.random(doors.length)]}');
case Failure(e):
Sys.println(e.message);
Sys.exit(e.code);
}
}
}
enum Entry {
@:if({
var found = false;
for (c in x.elements())
if (c.name == 'door') {
found = true;
break;
}
found;
}) Door(d:Door);
@:default Item(i:Item);
}
typedef Base = {
@:attr var label:String;
var directionFrames:Int;
var mortal:Bool;
var framesDelay:Int;
var speed:Float;
var picture:{
@:attr var file:String;
var frameWidth:Int;
var frameHeight:Int;
}
@:optional var shadow:{
@:attr var file:String;
var shadowWidth:Int;
var shadowHeight:Int;
}
@:list("frame") var frames:Array<Int>;
}
@:enum abstract Direction(String) {
var North = 'north';
var East = 'east';
var South = 'south';
var West = 'west';
static public function readXml(x:tink.xml.Source)
return switch x.getText() {
case 'north': North;
case 'east': East;
case 'south': South;
case 'west': West;
case v: throw 'invalid direction $v';
}
}
typedef Door = {>Base,
var door:Direction;
@:list("widthX") var widthX:Array<Int>;
@:list("widthY") var widthY:Array<Int>;
@:list("height") var height:Array<Int>;
}
typedef Item = {>Base,
var widthX:Int;
var widthY:Int;
var height:Int;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment