-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTraceryDecoder.cs
96 lines (80 loc) · 2.54 KB
/
TraceryDecoder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text.RegularExpressions;
using System.Linq;
using LitJson;
public class TraceryGrammar {
public string source;
Dictionary<string,string[]> grammar;
Regex rgx = new Regex(@"\#(?<expand>[^\#]*?)\#", RegexOptions.IgnoreCase);
[ThreadStatic] private static System.Random random;
public string Generate(int? randomSeed = null)
{
return GenerateFromNode("origin", randomSeed);
}
public string GenerateFromNode(string token, int? randomSeed = null)
{
if (randomSeed.HasValue)
{
random = new System.Random(randomSeed.Value);
}
if (grammar.ContainsKey(token))
{
var ret = Shuffle(grammar[token]).First();
return rgx.Replace(ret, m => GenerateFromNode(m.Groups[1].Value));
}
else
{
return "[" + token + "]";
}
}
public static List<T> Shuffle<T>(IEnumerable<T> list)
{
var rand = random ?? (random = new System.Random(unchecked(Environment.TickCount * 31 + System.Threading.Thread.CurrentThread.ManagedThreadId)));
var output = new List<T>(list);
int n = output.Count;
while (n > 1)
{
n--;
int k = rand.Next(n + 1);
T value = output[k];
output[k] = output[n];
output[n] = value;
}
return output;
}
Dictionary<string,string[]> Decode(string source)
{
Dictionary<string,string[]> traceryStruct = new Dictionary<string, string[]>();
var map = JsonToMapper(source);
foreach (var key in map.Keys) {
if (map[key].IsArray)
{
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);
}
else if (map[key].IsString)
{
string[] entries = {map[key].ToString()};
traceryStruct.Add(key, entries);
}
}
return traceryStruct;
}
public static JsonData JsonToMapper(string tracery)
{
var traceryStructure = JsonMapper.ToObject(tracery);
return traceryStructure;
}
public TraceryGrammar(string source)
{
this.source = source;
this.grammar = Decode(source);
}
}