Adventures in YAML

As one final example of using YAML, I’ve provided an elementary framework for an adventure game (gamesave_y.rb). This creates some Treasure objects and some Room objects. The Treasure objects are put “into” the Room objects (that is, they are placed into arrays contained by the Rooms), and the Room objects are then put into a Map object. This has the effect of constructing a moderately complex data structure in which an object of one type (a Map) contains an arbitrary number of objects of another type (Rooms), each of which may contain zero or more objects of yet other types (Treasures).

At first sight, finding a way of storing this entire network of mixed object types to disk and reconstructing that network at a later stage might look like a programming nightmare. In fact, thanks to the serialization capabilities supplied by Ruby’s YAML library, saving and restoring this data could hardly be easier. This is because serialization relieves you of the chore of saving each object one by one. Instead, you have to “dump” only the top-level object; here, that is the Map object, mymap.

When this is done, any objects that the top-level object “contains” (such as Rooms) or that the contained objects themselves contain (such as Treasures) are automatically saved for you. They can then be reconstructed just by loading all the saved data in a single operation and assigning it to the “top-level” object (here the map):

gamesave_y.rb

# Save mymap
File.open( 'game.yml', 'w' ){ |f|
    YAML.dump( mymap, f )
}

# Reload mymap
File.open( 'game.yml' ){ |f|
    mymap = YAML.load(f)
}

The full code of this program is too long to show here, so I suggest you try the program supplied in the source code archive in order to appreciate how simple it is to save and load a fairly complex data structure with YAML.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.252.204