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:
- Go to the tree
- Chop the tree
- Deliver wood to the stockpile
- Go to another tree
- 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
- Go to stockpile
- bring wood to construction area
- go back to stockpile
- Bring stone to construction area
- animate building sprite
Planting
- Go to stockpile
- bring seed to farm plot
Brewing
- Go to stockpile
- Bring plant to still
- 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