-
Notifications
You must be signed in to change notification settings - Fork 0
/
Encounter.cs
335 lines (286 loc) · 12.3 KB
/
Encounter.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using System.Net.Http;
namespace Temtem_EncounterTracker
{
public class Encounter
{
[JsonIgnore]
public Dictionary<string, Temtem> Temtems;
[JsonIgnore]
public Dictionary<string, Dictionary<string, double>> AttackValues;
public event MainEventHandler OnTemtemEncountered;
public delegate Task MainEventHandler(string Temtem, int counter);
public Dictionary<string, EncounterInfo> Encounters;
[JsonIgnore]
public TemtemWindow temtem;
[JsonIgnore]
public List<DateTime> EncountersLast10Minutes = new List<DateTime>();
[JsonIgnore]
public string temtemA = null, temtemB = null;
private Encounter()
{
Encounters = new Dictionary<string, EncounterInfo>();
HttpClient client = new HttpClient();
string result = client.GetStringAsync("https://temtem-api.mael.tech/api/temtems").Result;
var tempTems = JsonConvert.DeserializeObject<List<Temtem>>(result);
result = client.GetStringAsync("https://temtem-api.mael.tech/api/weaknesses").Result;
AttackValues = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, double>>>(result);
Temtems = tempTems.ToDictionary(x => x.name);
WriteTesseractWordlist();
}
public async Task CheckForEncounters()
{
temtem = new TemtemWindow();
Console.WriteLine("Waiting for Temtem to start...");
await temtem.WaitForTemtemStart();
Console.WriteLine("Temtem process found!");
Task.Run(() => HandleEncounterList());
int[] textMargins = {70, 100, 130, 170};
while (true)
{
if (temtem.IsTemtemActive())
{
int loopCount = 0;
temtemA = null;
temtemB = null;
while (temtem.IsInEncounter())
{
bool updateUI = false;
if (temtemA == null)
{
var text = temtem.GetScreenText(await temtem.GetTemtem(true, textMargins[loopCount % 4], (loopCount / 4) % 2 == 1)).Replace("\n", "").Split(" ").First();
text = GetClosestMatch(text, out double accuracy);
if (accuracy >= 0.61)
{
//Console.WriteLine($"Found a {text} with {Math.Round(accuracy * 100, 2)}% certainty!");
temtemA = text;
AddEncounter(temtemA);
EncountersLast10Minutes.Add(DateTime.UtcNow);
Program.currentEncounter = new HashSet<string> { temtemA, temtemB };
updateUI = true;
}
}
if (temtemB == null)
{
var text = temtem.GetScreenText(await temtem.GetTemtem(false, textMargins[loopCount % 4], (loopCount / 4) % 2 == 1)).Replace("\n", "").Split(" ").First();
text = GetClosestMatch(text, out double accuracy);
if (accuracy >= 0.61)
{
//Console.WriteLine($"Found a {text} with {Math.Round(accuracy * 100, 2)}% certainty!");
temtemB = text;
AddEncounter(temtemB);
EncountersLast10Minutes.Add(DateTime.UtcNow);
Program.currentEncounter = new HashSet<string> { temtemA, temtemB };
updateUI = true;
}
}
if (updateUI)
{
await Program.DrawEncounterTable();
Save(this);
}
await Task.Delay(100);
loopCount++;
}
await Task.Delay(200);
}
}
}
public async Task HandleEncounterList(){
while(true){
for(int i = 0; i < EncountersLast10Minutes.Count; i++){
if((DateTime.UtcNow - EncountersLast10Minutes[i]).TotalMinutes > 10){
EncountersLast10Minutes.RemoveAt(i);
i--;
} else {
break;
}
}
WriteEncounterRate();
await Task.Delay(5000);
}
}
public void WriteEncounterRate(){
double temtemPerHour = EncountersLast10Minutes.Count * 6;
Console.SetCursorPosition(47, Encounters.Count < 10 ? 4 + Encounters.Count : 14);
Console.WriteLine($"{Math.Round(temtemPerHour, 2) + " Temtems per hour", -40}");
}
public void AddEncounter(string temtemName)
{
if (!Encounters.ContainsKey(temtemName))
Encounters[temtemName] = new EncounterInfo();
Encounters[temtemName].HowOften += 1;
Encounters[temtemName].HowOftenToday += 1;
Encounters[temtemName].LastEncounter = DateTime.UtcNow;
}
public bool NameIsLegit(string temtemName)
{
return Temtems.ContainsKey(temtemName ?? "");
}
public string GetClosestMatch(string temtemName, out double accuracy)
{
accuracy = 0;
if (NameIsLegit(temtemName)){
accuracy = 1;
return temtemName;
}
string closestName = "";
foreach (var name in Temtems.Keys)
{
if (temtemName.Length > 2)
{
var relDistance = 1 - DamerauLevenshteinDistance(temtemName.Select(x => (int)x).ToArray(), name.Select(x => (int)x).ToArray(), 10) / (double)(name.Length > temtemName.Length ? name.Length : temtemName.Length);
if (relDistance > accuracy)
{
accuracy = relDistance;
closestName = name;
}
if(relDistance > 0.99) break;
}
}
return closestName;
}
private async Task temtemEncountered(string Temtem)
{
if (OnTemtemEncountered != null)
await OnTemtemEncountered(Temtem, Encounters[Temtem].HowOften);
Save(this);
}
public static void Save(Encounter toSave)
{
if (!Directory.Exists("data"))
Directory.CreateDirectory("data");
var json = JsonConvert.SerializeObject(toSave);
using (StreamWriter sw = new StreamWriter(new FileStream("data//Encounters.json", FileMode.OpenOrCreate)))
sw.WriteLine(json);
}
public static Encounter Load()
{
try
{
using (StreamReader sr = new StreamReader(new FileStream("data//Encounters.json", FileMode.Open)))
return JsonConvert.DeserializeObject<Encounter>(sr.ReadToEnd());
}
catch (Exception e)
{
return new Encounter();
}
}
public Dictionary<string, double> GetAttackValues(List<string> defendingElements)
{
Dictionary<string, double> attackValues = new Dictionary<string, double>();
foreach (var attackingElement in AttackValues.Keys)
{
double attackValue = 1;
foreach (var element in defendingElements)
{
attackValue *= AttackValues[attackingElement][element];
}
attackValues[attackingElement] = attackValue;
}
return attackValues;
}
public void WriteTesseractWordlist()
{
using (StreamWriter sw = new StreamWriter(new FileStream("tessdata//eng.user-words", FileMode.OpenOrCreate)))
{
sw.WriteLine(string.Join("\n", Temtems.Keys));
sw.WriteLine("Temtem");
sw.WriteLine("Early");
sw.Write("Access");
}
}
public List<KeyValuePair<string, EncounterInfo>> GetSortedEncounters(Columns column)
{
switch (column)
{
case Columns.Date:
return Encounters.OrderByDescending(x => x.Value.LastEncounter).ToList();
case Columns.Name:
return Encounters.OrderByDescending(x => x.Key).ToList();
default:
return Encounters.OrderByDescending(x => x.Value.HowOften).ToList();
}
}
/// <summary>
/// Computes the Damerau-Levenshtein Distance between two strings, represented as arrays of
/// integers, where each integer represents the code point of a character in the source string.
/// Includes an optional threshhold which can be used to indicate the maximum allowable distance.
/// </summary>
/// <param name="source">An array of the code points of the first string</param>
/// <param name="target">An array of the code points of the second string</param>
/// <param name="threshold">Maximum allowable distance</param>
/// <returns>Int.MaxValue if threshhold exceeded; otherwise the Damerau-Leveshteim distance between the strings</returns>
public static int DamerauLevenshteinDistance(int[] source, int[] target, int threshold)
{
int length1 = source.Length;
int length2 = target.Length;
// Return trivial case - difference in string lengths exceeds threshhold
if (Math.Abs(length1 - length2) > threshold) { return int.MaxValue; }
// Ensure arrays [i] / length1 use shorter length
if (length1 > length2)
{
Swap(ref target, ref source);
Swap(ref length1, ref length2);
}
int maxi = length1;
int maxj = length2;
int[] dCurrent = new int[maxi + 1];
int[] dMinus1 = new int[maxi + 1];
int[] dMinus2 = new int[maxi + 1];
int[] dSwap;
for (int i = 0; i <= maxi; i++) { dCurrent[i] = i; }
int jm1 = 0, im1 = 0, im2 = -1;
for (int j = 1; j <= maxj; j++)
{
// Rotate
dSwap = dMinus2;
dMinus2 = dMinus1;
dMinus1 = dCurrent;
dCurrent = dSwap;
// Initialize
int minDistance = int.MaxValue;
dCurrent[0] = j;
im1 = 0;
im2 = -1;
for (int i = 1; i <= maxi; i++)
{
int cost = source[im1] == target[jm1] ? 0 : 1;
int del = dCurrent[im1] + 1;
int ins = dMinus1[i] + 1;
int sub = dMinus1[im1] + cost;
//Fastest execution for min value of 3 integers
int min = (del > ins) ? (ins > sub ? sub : ins) : (del > sub ? sub : del);
if (i > 1 && j > 1 && source[im2] == target[jm1] && source[im1] == target[j - 2])
min = Math.Min(min, dMinus2[im2] + cost);
dCurrent[i] = min;
if (min < minDistance) { minDistance = min; }
im1++;
im2++;
}
jm1++;
if (minDistance > threshold) { return int.MaxValue; }
}
int result = dCurrent[maxi];
return (result > threshold) ? int.MaxValue : result;
}
static void Swap<T>(ref T arg1, ref T arg2)
{
T temp = arg1;
arg1 = arg2;
arg2 = temp;
}
}
public class EncounterInfo
{
public DateTime LastEncounter;
public int HowOften;
[JsonIgnore]
public int HowOftenToday;
}
}