Skip to content

Instantly share code, notes, and snippets.

@yankooliveira
Created December 25, 2020 11:07
Show Gist options
  • Save yankooliveira/61d36f46ba641c65c7b7575aca7c25d0 to your computer and use it in GitHub Desktop.
Save yankooliveira/61d36f46ba641c65c7b7575aca7c25d0 to your computer and use it in GitHub Desktop.
A recursive grammar replacer based on [tags].
// ! Gamejam code, proceed with caution!
// GetFromList is an extension method:
// public static T GetFromList<T>(this Random rnd, List<T> list) {
// var index = rnd.Next(list.Count);
// return list[index];
// }
namespace deVoid.Apothecary {
[CreateAssetMenu(fileName = "GrammarConfig", menuName = "Apothecary/Grammar Config")]
public class GrammarConfig : ScriptableObject {
[TextArea]
public List<string> Elements;
[TextArea]
public List<string> Grammars;
public string Divider = ";";
private Dictionary<string, List<string>> _grammarElementCacheInternal;
private Dictionary<string, List<string>> _grammarElementCache {
get {
if (_grammarElementCacheInternal == null || _grammarElementCacheInternal.Count <= 1) {
RefreshCaches();
}
return _grammarElementCacheInternal;
}
}
private void OnValidate() {
_grammarElementCacheInternal = null;
}
public void RefreshCaches() {
_grammarElementCacheInternal = new Dictionary<string, List<string>>();
foreach (var contents in Elements) {
var grammarBits = contents.Split('=');
_grammarElementCacheInternal.Add(grammarBits[0], new List<string>(grammarBits[1].Split(Divider[0])));
}
}
public string GetRandomFromGrammar(Random rnd) {
var grammar = rnd.GetFromList(Grammars);
grammar = ReplaceAllInGrammar(rnd, grammar);
return grammar;
}
public string GetRandomFromGrammarIndex(Random rnd, int grammarIndex) {
var grammar = Grammars[grammarIndex];
grammar = ReplaceAllInGrammar(rnd, grammar);
return grammar;
}
public string ReplaceAllInGrammar(Random rnd, string grammar) {
foreach (var kvPair in _grammarElementCache) {
grammar = grammar.Replace(kvPair.Key, rnd.GetFromList(kvPair.Value));
}
var matches = Regex.Matches(grammar,@"\[([^][]*)]");
foreach (Match match in matches) {
if (_grammarElementCache.ContainsKey(match.Value)) {
return ReplaceAllInGrammar(rnd, grammar);
}
}
return grammar;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment