Late in the night, whilst the baby feeds, I continue to develop Dr Nic’s Civilizations game. This led me to develop a DSL for the specification of game rules. You need to see this.
Here’s an example definition of some terrain:
class Desert < Terrain title "Desert" letter "d" graphic "desert" movement_cost 1 defense_bonus 10 food 0 shield 1 trade 0 end class Oasis < Desert title "Oasis" special_code 1 food 3 shield 1 trade 0 graphic "oasis" end
An Oasis is a special version of the Desert terrain, so Ruby subclasses offer a compatible relationship.
This is seriously cool. All in Ruby.
Why write a DSL for something trite like game rules?
The descriptions of terrain (plains, hills, ocean), the improvements (roads, irrigation, mines), etc. all need defining somewhere. Here are the standard options:
- Rows in a database, imported into ActiveRecords at startup
- Files that are loaded at startup, parsed and converted into an internal data model
- Ruby DSL
The sort of configuration we're dealing with is static: its a part of the game design to a certain extent. Yes, I could put the configuration in a database and access/modify it via an admin console, though version control becomes an additional administrative hassle.
Storing game rule configuration in external files makes version control trivial, though there is a one-time cost of implementing special purpose syntax, parsers, internal game data models and testing.
A Ruby DSL is exactly the same as implementing option 2 - the configuration is stored in files, though as the syntax is pure Ruby, there is no need to implement a parser and internal data model.
"Yes, smart arse, but you still had to write up all those Ruby classes"
An irrelevant argument, you'd have to enter the configuration for any of the 3 options, but...
I wrote a generator to build the Ruby class definitions for me from the Freeciv's GPL rule sets. Sweet.
 The definition of the
Terrain class, using the
traits mechanism, is simple:
class Terrain traits :title, :letter, :graphic, :movement_cost, :defense_bonus, :food, :shield, :trade, :special_code end
- Magic Multi-Connections: A “facility in Rails to talk to more than one database at a time” At this point in time thereâ€™s no facility in Rails...
- Coming home to Brisbane I left Australia on the 3rd of July last year...
- Extending _why’s Creature class Many Rubist’s first explanation of metaprogramming is by why the...
- So, cattr_accessor doesn’t work like it should? Rails’ active_support library adds some wonderful functions into standard Ruby...
- [BTS] Dr Nic’s Civilizations 2.0 I’m not promising there ever will be a Dr Nic’s...