Sunday, May 15, 2016

ai - Command Ordering Architecture of Dwarf Fortress


What is the most elegant way to implement a command ordering system for AI? for example in dwarf fortress when you mark a forested area for wood cutting, the dwarfs then would do the following sequence:



  1. Go to the tree

  2. Chop the tree

  3. Deliver wood to the stockpile

  4. Go to another tree

  5. and so on..



I already have a stack command working no. 1 which goes from idle state to reaching the destination tile of the tree.


What I'm afraid of is how this would get messy when I create more orders like this:


Build a house



  1. Go to stockpile

  2. bring wood to construction area

  3. go back to stockpile

  4. Bring stone to construction area

  5. animate building sprite



Planting



  1. Go to stockpile

  2. bring seed to farm plot


Brewing



  1. Go to stockpile

  2. Bring plant to still

  3. animate brewing sprite



So my question is, how do I implement a command ordering system like dwarf fortress and avoiding spaghetti code at the same time? are there any data structures that I need to study? Do I need to put the command sequence on a separate xml file?



Answer



At first you see that your commands are in the form of a list, so your first instinct might be to recreate that structure, and each dwarf will run through that list in sequence. What I suggest though is to break the list into steps, with each step having prerequisite(s), and then you run the entire command in reverse. Let me demonstrate with an example:


Wood cutting



  • Am I carrying wood, and at a stockpile? Yes: drop it off

  • Am I carrying wood? Yes: go to a stockpile

  • Am I at a tree? Yes: chop it

  • No to all above: go to a tree



The advantages of this is:



  • Very simple to implement

  • Flexible - you can freely decompose this list, add items, remove items, combine items

  • No state - you can run this list from the top for any dwarf in any state, and the dwarf will just Do the Right ThingTM


Disadvantages:



  • It's easy to get stuck in loops, since there is no state and no awareness of being stuck



Logically, you can represent these commands as a flow chart, that is run from the top each time, and what you do depends on whether you answer yes/no at each step. Whether you implement this in code or in an external file like XML is up to you.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...