This question has come up while writing a simple text adventure game where your character has an inventory, which can include containers that also have things in them. I want a clean way to style the inventory output, like so:
You are carrying:
a bag containing:
a ring
a backpack containing:
a loaf of bread
Currently I just include the formatting in the result returned by the query, all in one shot. For example,
DoInventoryCommand():
result = QueryInventory(...recursively checks inventory adding multiples of tabs depending on nesting level...)
print(result)
What I would like is a cleaner separation between content and presentation so that the query would just return a data structure that a separate pass could style.
But how should the styling pass handle the n-levels deep data structure? Just for example, how would a styling tool like CSS handle it? Do you need to procedurally generate the CSS once you have the data structure?
0
Your data structure should be recursive, like this:
public class Node
{
public string Value { get; set; }
public List<Node> Children { get; set; }
public override string GetString()
{
return this.Value;
}
}
Add four spaces to the beginning of the display line for each new recursion level. You can maintain a “level” variable that you pass along during the recursion (or make it static), increment it during each recursive call, and decrement it during each recursive return
.
int indent = 0;
public string GetDisplayString()
{
var s = new StringBuilder(new string(' ', indent) + node.ToString());
if (node.Children != null)
foreach (var child in node.Children)
{
indent += 4;
s.Append(GetString(child));
indent -= 4;
}
return s.ToString();
}
1