1

I'm trying to write a little text rpg kind of game. What I'm trying to do is make it so that there are multiple little adventures, each contained in their own source file. I want to be able to select one source file at random, create an instance of its contained class, and then call a function (we'll call it Adventure#start). I'm having trouble thinking of a way to accomplish this without using a crazy array/hash and a big case tree, all of which would need to be updated with every adventure added...

I feel like there's something obvious I'm missing, but is there a practical way to go about this? The main point being that I would want to not have to update other code just to add a new adventure, but rather simply add the source for said adventure, drop the file into the appropriate folder, and be done with it.

jeremiah
  • 49
  • 1
  • 6
  • You'd basically go with (auto)loading all files and having classes inherit from a abstract base class, and implementing `self.inherited` which will let you list all the children and then pick one randomly. I can't think of having too many of those files for Ruby to handle. – Bart Jan 12 '14 at 06:11

1 Answers1

0

You can do it with the following steps:

  1. Get all the files from the folder containing adventure files
  2. Choose a random file
  3. Require the chosen file
  4. Parse the content of the chosen file for the class name
  5. Create an instance of the adventure using (Kernel.const_get class_name).new
  6. Call #start on the newly created instance
vidang
  • 1,761
  • 13
  • 13
  • sorry, bit of a newbie here - i follow except for number 4 - i'm not sure how to, and maybe i'm just completely missing something - could you point me in a direction to find how to parse for a class name? – jeremiah Jan 12 '14 at 17:22
  • or is this something as simple as reading the entire file looking for the line that starts with 'class' which, now i think on it, seems pretty bloody obvious, as i could easily leave it in the first line of code, and save documentation for after the first line. lol. – jeremiah Jan 12 '14 at 17:36
  • You don't need to put the class statement at the first line of code, and put the documentation after it. You just need to find for a line start with 'class', take it out and parse for the class name. Remember, there are many ways to define a class in ruby, this trick only work if you use 'class Name' to define a class. – vidang Jan 13 '14 at 01:03
  • agreed, vidaica, for now, i am in fact using `class Name`, and putting documentation below, for this particular facet, is not a problem, as every single file that can and will be picked up by the function will be to the same purpose. the documentation will probably be further down once it gets to the details. thanks by the way, i got it running wonderfully with `Kernel.const_get` – jeremiah Jan 13 '14 at 05:32
  • It's nothing, I'm glad that I could give you some help. – vidang Jan 13 '14 at 05:42