forked from kwsch/SysBot.NET
-
Notifications
You must be signed in to change notification settings - Fork 10
/
AutoCorrectShowdown.cs
362 lines (308 loc) · 15.6 KB
/
AutoCorrectShowdown.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
using PKHeX.Core;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SysBot.Pokemon.Helpers.ShowdownHelpers;
namespace SysBot.Pokemon;
public static class AutoCorrectShowdown<T> where T : PKM, new()
{
private static readonly char[] separator = ['\r', '\n'];
public static async Task<(string CorrectedContent, List<string> CorrectionMessages)> PerformAutoCorrect(string content, PKM originalPk, LegalityAnalysis originalLa)
{
return await Task.Run(async () =>
{
var autoCorrectConfig = new TradeSettings.AutoCorrectShowdownCategory();
if (!autoCorrectConfig.EnableAutoCorrect)
return (content, new List<string>());
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
var gameStrings = GameInfoHelpers<T>.GetGameStrings();
var generation = GameInfoHelpers<T>.GetGeneration();
var itemlist = gameStrings.itemlist;
(string speciesName, string formName, string gender, string heldItem, string nickname) = ParseSpeciesLine(lines[0]);
string originalSpeciesName = speciesName;
string originalFormName = formName;
string correctedSpeciesName = autoCorrectConfig.AutoCorrectSpeciesAndForm ? await FirstLine<T>.GetClosestSpecies(speciesName) ?? speciesName : speciesName;
ushort speciesIndex = (ushort)Array.IndexOf(gameStrings.specieslist, correctedSpeciesName);
string[] formNames = Array.Empty<string>();
string correctedFormName = formName;
if (!string.IsNullOrEmpty(formName))
{
formNames = FormConverter.GetFormList(speciesIndex, gameStrings.types, gameStrings.forms, new List<string>(), generation);
correctedFormName = await FirstLine<T>.GetClosestFormName(formName, formNames) ?? formName;
}
// Combine corrected species and form names
string finalCorrectedName = string.IsNullOrEmpty(correctedFormName) ? correctedSpeciesName : $"{correctedSpeciesName}-{correctedFormName}";
// Update speciesName to be the same as finalCorrectedName
speciesName = finalCorrectedName;
PKM pk = originalPk.Clone();
LegalityAnalysis la = originalLa;
var correctionMessages = new List<string>();
bool speciesOrFormCorrected = finalCorrectedName != $"{originalSpeciesName}-{originalFormName}".Trim('-');
if (speciesOrFormCorrected)
{
pk.Species = speciesIndex;
var personalFormInfo = GameInfoHelpers<T>.GetPersonalFormInfo(speciesIndex);
pk.Form = correctedFormName != null ? (byte)personalFormInfo.FormIndex(speciesIndex, (byte)Array.IndexOf(formNames, correctedFormName)) : (byte)0;
la = new LegalityAnalysis(pk);
// Add separate messages for species and form corrections
if (correctedSpeciesName != originalSpeciesName)
{
correctionMessages.Add($"Species was incorrect. Adjusted from **{originalSpeciesName}** to **{correctedSpeciesName}**.");
}
if (correctedFormName != originalFormName)
{
correctionMessages.Add($"Form was incorrect. Adjusted from **{originalFormName}** to **{correctedFormName}**.");
}
if (correctedSpeciesName == originalSpeciesName && correctedFormName == originalFormName)
{
correctionMessages.Add($"Species or form was incorrect. Adjusted to **{finalCorrectedName}**.");
}
}
(string abilityName, string natureName, string ballName, string levelValue) = ParseLines(lines);
string correctedAbilityName = string.Empty;
if (!string.IsNullOrEmpty(abilityName) && autoCorrectConfig.AutoCorrectAbility)
{
var personalAbilityInfo = GameInfoHelpers<T>.GetPersonalInfo(speciesIndex);
var closestAbility = await AbilityHelper<T>.GetClosestAbility(abilityName, speciesIndex, gameStrings, personalAbilityInfo);
correctedAbilityName = closestAbility.Ability ?? abilityName;
if (!string.IsNullOrEmpty(correctedAbilityName) && correctedAbilityName != abilityName)
{
correctionMessages.Add($"{speciesName} can't have the ability {abilityName}. Adjusted to **{correctedAbilityName}**.");
}
}
string correctedNatureName = string.Empty;
if (!string.IsNullOrEmpty(natureName) && autoCorrectConfig.AutoCorrectNature)
{
var closestNature = await NatureHelper<T>.GetClosestNature(natureName, gameStrings);
correctedNatureName = closestNature.Nature ?? natureName;
if (!string.IsNullOrEmpty(correctedNatureName) && correctedNatureName != natureName)
{
correctionMessages.Add($"Nature was incorrect. Adjusted to **{correctedNatureName}** Nature.");
}
}
string formNameForBallVerification = correctedSpeciesName == speciesName ? formName : correctedFormName;
string correctedBallName = string.Empty;
if (!string.IsNullOrEmpty(ballName) && autoCorrectConfig.AutoCorrectBall)
{
var legalBall = await BallHelper<T>.GetLegalBall(speciesIndex, formNameForBallVerification, ballName, gameStrings, pk);
correctedBallName = legalBall;
if (!string.IsNullOrEmpty(correctedBallName) && correctedBallName != ballName)
{
correctionMessages.Add($"{speciesName} can't be in a {ballName}. Adjusted to **{correctedBallName}**.");
}
}
if (autoCorrectConfig.AutoCorrectLevel && !string.IsNullOrWhiteSpace(levelValue))
{
var levelVerifier = new LevelVerifier();
levelVerifier.Verify(la);
if (!la.Valid)
{
correctionMessages.Add($"Level was incorrect. Adjusted to **Level 100**.");
}
}
if (autoCorrectConfig.AutoCorrectMovesLearnset && lines.Any(line => line.StartsWith("- ")))
{
await MoveHelper<T>.ValidateMovesAsync(lines, pk, la, gameStrings, speciesName, correctedFormName ?? formName, correctionMessages);
}
if (autoCorrectConfig.AutoCorrectIVs && lines.Any(line => line.StartsWith("IVs:")))
{
if (!IVEVHelper<T>.ValidateIVs(pk, la, lines))
IVEVHelper<T>.RemoveIVLine(lines);
}
if (autoCorrectConfig.AutoCorrectEVs && lines.Any(line => line.StartsWith("EVs:")))
{
if (!IVEVHelper<T>.ValidateEVs(lines))
IVEVHelper<T>.RemoveEVLine(lines);
}
if (lines.Any(line => line.StartsWith("Shiny:", StringComparison.OrdinalIgnoreCase)))
{
ShinyHelper<T>.VerifyShiny(pk, la, lines, correctionMessages, speciesName);
}
string? markLine = null;
List<string> markCorrectionMessages = new List<string>();
if (autoCorrectConfig.AutoCorrectMarks && lines.Any(line => line.StartsWith(".RibbonMark")))
{
var markVerifier = new MarkVerifier();
markVerifier.Verify(la);
if (!la.Valid)
{
(markLine, markCorrectionMessages) = await MarkHelper<T>.CorrectMarks(pk, la.EncounterOriginal, lines);
}
}
correctionMessages.AddRange(markCorrectionMessages);
(string correctedHeldItem, string heldItemCorrectionMessage) = FirstLine<T>.ValidateHeldItem(lines, pk, itemlist, heldItem);
if (!string.IsNullOrEmpty(heldItemCorrectionMessage))
{
correctionMessages.Add(heldItemCorrectionMessage);
}
string correctedGender = gender;
string genderCorrectionMessage = string.Empty;
if (autoCorrectConfig.AutoCorrectGender && !string.IsNullOrEmpty(gender))
{
(correctedGender, genderCorrectionMessage) = FirstLine<T>.ValidateGender(pk, gender, speciesName);
if (!string.IsNullOrEmpty(genderCorrectionMessage))
{
correctionMessages.Add(genderCorrectionMessage);
}
}
string[] correctedLines = lines.Select((line, i) => CorrectLine(line, i, speciesName, correctedSpeciesName, correctedFormName ?? formName, formName, correctedGender, gender, correctedHeldItem, heldItem, correctedAbilityName, correctedNatureName, correctedBallName, levelValue, la, nickname)).ToArray();
// TODO: Validate Scale Line and remove if necessary.
// Find the index of the first move line
int moveSetIndex = Array.FindIndex(correctedLines, line => line.StartsWith("- "));
// Insert the mark line above the move set if it exists, otherwise add it at the end
if (!string.IsNullOrEmpty(markLine))
{
if (moveSetIndex != -1)
{
var updatedLines = new List<string>(correctedLines);
updatedLines.Insert(moveSetIndex, markLine);
correctedLines = updatedLines.ToArray();
}
else
{
// Replace the invalid mark line with the corrected line
int invalidMarkIndex = Array.FindIndex(correctedLines, line => line.StartsWith(".RibbonMark"));
if (invalidMarkIndex != -1)
correctedLines[invalidMarkIndex] = markLine;
else
correctedLines = correctedLines.Append(markLine).ToArray();
}
}
string finalShowdownSet = string.Join(Environment.NewLine, correctedLines.Where(line => !string.IsNullOrWhiteSpace(line)));
return (finalShowdownSet, correctionMessages);
});
}
private static (string speciesName, string formName, string gender, string heldItem, string nickname) ParseSpeciesLine(string speciesLine)
{
string formName = string.Empty;
string gender = string.Empty;
string heldItem = string.Empty;
string nickname = string.Empty;
string speciesName = string.Empty;
int heldItemIndex = speciesLine.IndexOf(" @ ");
if (heldItemIndex != -1)
{
heldItem = speciesLine[(heldItemIndex + 3)..].Trim();
speciesLine = speciesLine[..heldItemIndex].Trim();
}
int firstParenIndex = speciesLine.IndexOf('(');
int lastParenIndex = speciesLine.LastIndexOf(')');
if (firstParenIndex != -1 && lastParenIndex != -1 && firstParenIndex < lastParenIndex)
{
string textInParentheses = speciesLine[(firstParenIndex + 1)..lastParenIndex].Trim();
if (textInParentheses == "M" || textInParentheses == "F")
{
gender = textInParentheses;
speciesName = speciesLine[..firstParenIndex].Trim();
}
else
{
int secondParenIndex = textInParentheses.IndexOf('(');
if (secondParenIndex != -1)
{
string genderInParentheses = textInParentheses[(secondParenIndex + 1)..].Trim();
if (genderInParentheses == "M" || genderInParentheses == "F")
{
gender = genderInParentheses;
textInParentheses = textInParentheses[..secondParenIndex].Trim();
}
}
speciesName = textInParentheses;
string remainingText = speciesLine[..firstParenIndex].Trim();
if (!string.IsNullOrEmpty(remainingText))
{
nickname = remainingText;
}
}
}
else
{
speciesName = speciesLine.Trim();
}
speciesName = speciesName.Replace(")", string.Empty);
int formSeparatorIndex = speciesName.IndexOf('-');
if (formSeparatorIndex != -1)
{
formName = speciesName[(formSeparatorIndex + 1)..].Trim();
speciesName = speciesName[..formSeparatorIndex].Trim();
}
return (speciesName, formName, gender, heldItem, nickname);
}
private static (string abilityName, string natureName, string ballName, string levelValue) ParseLines(string[] lines)
{
string abilityName = string.Empty;
string natureName = string.Empty;
string ballName = string.Empty;
string levelValue = string.Empty;
foreach (string line in lines)
{
string trimmedLine = line.Trim();
if (trimmedLine.StartsWith("Ability:"))
abilityName = trimmedLine["Ability:".Length..].Trim();
else if (trimmedLine.EndsWith(" Nature"))
natureName = trimmedLine[..^" Nature".Length].Trim();
else if (trimmedLine.StartsWith("Ball:"))
ballName = trimmedLine["Ball:".Length..].Trim();
else if (trimmedLine.StartsWith("Level:"))
levelValue = trimmedLine["Level:".Length..].Trim();
}
return (abilityName, natureName, ballName, levelValue);
}
private static string CorrectLine(string line, int index, string speciesName, string correctedSpeciesName, string correctedFormName, string formName, string correctedGender, string gender, string correctedHeldItem, string heldItem, string correctedAbilityName, string correctedNatureName, string correctedBallName, string levelValue, LegalityAnalysis la, string nickname)
{
if (index == 0) // Species line
{
StringBuilder sb = new StringBuilder();
string finalCorrectedName = string.IsNullOrEmpty(correctedFormName) ? correctedSpeciesName : $"{correctedSpeciesName}-{correctedFormName}";
if (!string.IsNullOrEmpty(nickname))
{
sb.Append(nickname);
sb.Append(" (");
sb.Append(finalCorrectedName);
sb.Append(')');
}
else
{
sb.Append(finalCorrectedName);
}
// Add gender if present
if (!string.IsNullOrEmpty(correctedGender))
{
sb.Append(" (");
sb.Append(correctedGender);
sb.Append(')');
}
// Only add the item if correctedHeldItem is not empty
if (!string.IsNullOrEmpty(correctedHeldItem))
{
sb.Append(" @ ");
sb.Append(correctedHeldItem);
}
return sb.ToString();
}
else if (line.StartsWith("Ability:"))
{
return $"Ability: {correctedAbilityName}";
}
else if (line.EndsWith(" Nature"))
{
return $"{correctedNatureName} Nature";
}
else if (line.StartsWith("Ball:"))
{
return $"Ball: {correctedBallName}";
}
else if (line.StartsWith("Level:"))
{
return !la.Valid ? "Level: 100" : $"Level: {levelValue}";
}
else if (line.StartsWith("Shiny:", StringComparison.OrdinalIgnoreCase))
{
return la.EncounterMatch.Shiny.IsValid(la.Entity) ? "Shiny: Yes" : "Shiny: No";
}
return line;
}
}