Skip to content

Instantly share code, notes, and snippets.

@v21
Created October 24, 2015 14:57
Show Gist options
  • Save v21/46f2a1be37959956329f to your computer and use it in GitHub Desktop.
Save v21/46f2a1be37959956329f to your computer and use it in GitHub Desktop.
you also need LitJson.dll
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using System;
using System.Text.RegularExpressions;
public class TraceryDecoder : MonoBehaviour {
public string tracery;
public bool bangDecode;
public bool bangGenerate;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (bangDecode)
{
bangDecode = false;
Decode();
}
if (bangGenerate)
{
bangGenerate = false;
var ret = Generate(Decode());
Debug.Log(ret);
}
}
Regex rgx = new Regex(@"\#(?<expand>[^\#]*?)\#", RegexOptions.IgnoreCase);
public string Generate(Dictionary<string,string[]> parsed)
{
return Expand("origin", parsed);
}
public string Expand(string token, Dictionary<string,string[]> parsed)
{
if (parsed.ContainsKey(token))
{
var ret = parsed[token].PickRandom();
return rgx.Replace(ret, m => Expand(m.Groups[1].Value, parsed));
}
else
{
return "[" + token + "]";
}
}
Dictionary<string,string[]> Decode()
{
Dictionary<string,string[]> traceryStruct = new Dictionary<string, string[]>();
var map = JsonToMapper(tracery);
foreach (var key in map.Keys) {
string[] entries = new string[map[key].Count];
for (int i = 0; i < map[key].Count; i++) {
var entry = map[key][i];
entries[i] = (string)entry;
}
traceryStruct.Add(key, entries);
}
return traceryStruct;
}
public static JsonData JsonToMapper(string tracery)
{
var traceryStructure = JsonMapper.ToObject(tracery);
return traceryStructure;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment