-
Notifications
You must be signed in to change notification settings - Fork 16
/
TrainerBot.cs
411 lines (345 loc) · 18.1 KB
/
TrainerBot.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
using EOLib;
using EOLib.Domain.Account;
using EOLib.Domain.Character;
using EOLib.Domain.Chat;
using EOLib.Domain.Extensions;
using EOLib.Domain.Item;
using EOLib.Domain.Login;
using EOLib.Domain.Map;
using EOLib.IO;
using EOLib.IO.Pub;
using EOLib.IO.Repositories;
using EOLib.Net;
using EOLib.Net.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace EOBot
{
internal class TrainerBot : BotBase
{
private const int CONSECUTIVE_ATTACK_COUNT = 150;
private const int ATTACK_BACKOFF_MS = 600;
private const int WALK_BACKOFF_MS = 480;
private const int FACE_BACKOFF_MS = 120;
private static readonly int[] JunkItemIds = new[]
{
// Dragon Blade, enchanted boots (red/green/blue)
37, 124, 125, 126
// cava staff
//329
};
private readonly string _account;
private readonly string _password;
private readonly string _character;
private ICharacterActions _characterActions;
private IMapActions _mapActions;
private IItemActions _itemActions;
private ICharacterRepository _characterRepository;
private IFixedTimeStepRepository _fixedTimeStepRepository;
private IPubFile<EIFRecord> _itemData;
private IPubFile<ENFRecord> _npcData;
private IPubFile<ESFRecord> _spellData;
private IChatProvider _chatProvider;
private HashSet<ChatData> _cachedChat;
public TrainerBot(int botIndex, string account, string password, string character)
: base(botIndex)
{
_account = account;
_password = password;
_character = character;
}
protected override async Task DoWorkAsync(CancellationToken ct)
{
var helper = new BotHelper(_index);
var res = await helper.LoginToAccountAsync(_account, _password);
if (res == LoginReply.WrongUser)
{
var createRes = await helper.CreateAccountAsync(_account, _password);
if (createRes != AccountReply.Created)
throw new InvalidOperationException($"Unable to create account: invalid response {Enum.GetName(typeof(AccountReply), createRes)}");
res = await helper.LoginToAccountAsync(_account, _password);
}
if (res != LoginReply.Ok)
throw new InvalidOperationException($"Unable to log in to account: invalid response {Enum.GetName(typeof(LoginReply), res)}");
await helper.LoginToCharacterAsync(_character);
var c = DependencyMaster.TypeRegistry[_index];
_mapActions = c.Resolve<IMapActions>();
_itemActions = c.Resolve<IItemActions>();
_characterRepository = c.Resolve<ICharacterRepository>();
_characterActions = c.Resolve<ICharacterActions>();
var mapCellStateProvider = c.Resolve<IMapCellStateProvider>();
var mapStateProvider = c.Resolve<ICurrentMapStateProvider>();
var handler = c.Resolve<IOutOfBandPacketHandler>();
_itemData = c.Resolve<IEIFFileProvider>().EIFFile;
_npcData = c.Resolve<IENFFileProvider>().ENFFile;
_spellData = c.Resolve<IESFFileProvider>().ESFFile;
var charInventoryRepo = c.Resolve<ICharacterInventoryRepository>();
var walkValidator = c.Resolve<IWalkValidationActions>();
_chatProvider = c.Resolve<IChatProvider>();
_cachedChat = new HashSet<ChatData>();
_fixedTimeStepRepository = c.Resolve<IFixedTimeStepRepository>();
var healItems = new List<InventoryItem>();
var healSpells = new List<InventorySpell>();
int attackCount = 0, cachedPlayerCount = 0;
bool time_to_die = false;
MapCoordinate? priorityCoord = null;
while (!ct.IsCancellationRequested)
{
handler.PollForPacketsAndHandle();
if (!_cachedChat.SetEquals(_chatProvider.AllChat[ChatTab.Local]))
{
foreach (var message in _chatProvider.AllChat[ChatTab.Local].Except(_cachedChat))
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Chat, $"{message.Who}: {message.Message}", ConsoleColor.Cyan);
_cachedChat = _chatProvider.AllChat[ChatTab.Local].ToHashSet();
if (OperatingSystem.IsWindows())
{
Console.Beep(261, 1500);
}
}
var character = _characterRepository.MainCharacter;
var charRenderProps = character.RenderProperties;
var currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY);
if (cachedPlayerCount != mapStateProvider.Characters.Count())
{
cachedPlayerCount = mapStateProvider.Characters.Count();
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"{cachedPlayerCount,7} - Players on map - You may not be able to train here", ConsoleColor.DarkYellow);
if (OperatingSystem.IsWindows())
{
Console.Beep(220, 500);
Console.Beep(247, 500);
Console.Beep(220, 500);
}
}
var coords = new MapCoordinate[]
{
new MapCoordinate(charRenderProps.MapX + 1, charRenderProps.MapY),
new MapCoordinate(charRenderProps.MapX - 1, charRenderProps.MapY),
new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY + 1),
new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY - 1)
};
if (priorityCoord != null)
{
// ensure if there's an attack in progress that we finish killing that NPC before moving around
var tmp = new[] { priorityCoord.Value };
coords = tmp.Concat(coords.Except(tmp)).ToArray();
}
var action_taken = false;
foreach (var coord in coords)
{
if (action_taken)
break;
if (!time_to_die)
{
var cellState = mapCellStateProvider.GetCellStateAt(coord.X, coord.Y);
if (priorityCoord.HasValue && !cellState.NPC.HasValue)
priorityCoord = null;
if (character.Stats[CharacterStat.Weight] >= character.Stats[CharacterStat.MaxWeight])
{
ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"OVER WEIGHT LIMIT - TIME TO DIE", ConsoleColor.DarkYellow);
await ToggleSit();
action_taken = true;
time_to_die = true;
}
else if ((attackCount < CONSECUTIVE_ATTACK_COUNT && !currentPositionCellState.NPC.HasValue) || cellState.NPC.HasValue)
{
if (cellState.NPC.HasValue && character.Stats[CharacterStat.HP] > character.Stats[CharacterStat.MaxHP] * .1)
{
await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), coord);
await Attack(cellState);
attackCount++;
action_taken = true;
priorityCoord = coord;
}
else if (cellState.Items.Any())
{
await PickUpItems(cellState);
action_taken = true;
}
else if (healItems.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .3)
{
var stats = _characterRepository.MainCharacter.Stats;
while (!ct.IsCancellationRequested && stats[CharacterStat.HP] < stats[CharacterStat.MaxHP] * .6)
{
await UseHealItem(healItems);
handler.PollForPacketsAndHandle();
stats = _characterRepository.MainCharacter.Stats;
}
action_taken = true;
}
else if (healSpells.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .9
&& character.Stats[CharacterStat.TP] > character.Stats[CharacterStat.MaxTP] * .5)
{
await CastHealSpell(healSpells);
action_taken = true;
}
healItems = charInventoryRepo.ItemInventory
.Where(x => _itemData.Any(y => y.ID == x.ItemID && y.Type == ItemType.Heal))
.ToList();
healSpells = charInventoryRepo.SpellInventory
.Where(x => _spellData.Any(y => y.ID == x.ID && y.Type == SpellType.Heal))
.ToList();
}
else
{
if (!currentPositionCellState.NPC.HasValue)
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Walking due to consecutive attacks: {attackCount}");
else
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Killing NPC at player location");
// find a direction that's open to walk to
var targetWalkCell = coords.Select(z => mapCellStateProvider.GetCellStateAt(z.X, z.Y))
.FirstOrDefault(z => walkValidator.IsCellStateWalkable(z));
if (targetWalkCell == null)
{
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Couldn't find open space to walk!", ConsoleColor.DarkYellow);
break;
}
await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), targetWalkCell.Coordinate);
var originalDirection = charRenderProps.Direction;
await Walk();
await Face(originalDirection.Opposite());
// kill NPC if it was in our starting point
while (currentPositionCellState.NPC.HasValue && !ct.IsCancellationRequested)
{
await Attack(currentPositionCellState);
handler.PollForPacketsAndHandle();
currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY);
}
await PickUpItems(currentPositionCellState);
await Walk();
await Face(originalDirection);
attackCount = 0;
action_taken = true;
}
}
}
await Delay(120);
}
}
private async Task Attack(IMapCellState cellState)
{
cellState.NPC.MatchSome(npc => ConsoleHelper.WriteMessage(ConsoleHelper.Type.Attack, $"{npc.Index,7} - {_npcData.Single(x => x.ID == npc.ID).Name}"));
await TrySend(_characterActions.Attack);
await Delay(ATTACK_BACKOFF_MS);
}
private async Task Walk()
{
var renderProps = _characterRepository.MainCharacter.RenderProperties;
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Walk, $"{renderProps.GetDestinationX(),3},{renderProps.GetDestinationY(),3}");
await TrySend(_characterActions.Walk);
await Delay(WALK_BACKOFF_MS);
}
private async Task Face(EODirection direction)
{
var rp = _characterRepository.MainCharacter.RenderProperties;
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Face, $"{Enum.GetName(typeof(EODirection), direction),7} - at {rp.MapX},{rp.MapY}");
await TrySend(() => _characterActions.Face(direction));
// todo: character actions Face() should also change the character's direction instead of relying on client to update it separately
_characterRepository.MainCharacter = _characterRepository.MainCharacter
.WithRenderProperties(_characterRepository.MainCharacter.RenderProperties.WithDirection(direction));
await Delay(FACE_BACKOFF_MS);
}
private async Task FaceCoordinateIfNeeded(MapCoordinate originalCoord, MapCoordinate targetCoord)
{
var charRenderProps = _characterRepository.MainCharacter.RenderProperties;
var nextCoord = new MapCoordinate(charRenderProps.GetDestinationX(), charRenderProps.GetDestinationY());
if (nextCoord != targetCoord)
{
var diff = targetCoord - originalCoord;
var direction = diff.X > 0 ? EODirection.Right
: diff.X < 0 ? EODirection.Left
: diff.Y > 0 ? EODirection.Down
: diff.Y < 0 ? EODirection.Up : charRenderProps.Direction;
if (direction != charRenderProps.Direction)
await Face(direction);
}
}
private async Task PickUpItems(IMapCellState cellState)
{
foreach (var item in cellState.Items)
{
await PickUpItem(item);
if (JunkItemIds.Contains(item.ItemID))
{
await Delay(1000);
await JunkItem(item);
}
}
}
private async Task PickUpItem(MapItem item)
{
await TrySend(() =>
{
var itemName = _itemData.Single(x => x.ID == item.ItemID).Name;
var pickupResult = _mapActions.PickUpItem(item);
if (pickupResult == ItemPickupResult.Ok)
ConsoleHelper.WriteMessage(ConsoleHelper.Type.TakeItem, $"{item.Amount,7} - {itemName}");
else
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Ignoring item {itemName} x{item.Amount} due to pickup error {pickupResult}", ConsoleColor.DarkYellow);
});
await Delay(ATTACK_BACKOFF_MS);
}
private async Task JunkItem(MapItem item)
{
ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{item.Amount,7} - {_itemData.Single(x => x.ID == item.ItemID).Name}");
await TrySend(() => _itemActions.JunkItem(item.ItemID, item.Amount));
await Delay(ATTACK_BACKOFF_MS);
}
private async Task CastHealSpell(IEnumerable<InventorySpell> healSpells)
{
var spellToUse = _spellData
.Where(x => healSpells.Any(y => y.ID == x.ID) && x.Target != SpellTarget.Group)
.OrderByDescending(x => x.HP)
.First();
var stats = _characterRepository.MainCharacter.Stats.Stats;
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Cast, $"{spellToUse.HP,4} HP - {spellToUse.Name} - TP {stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}");
await TrySend(() => _characterActions.PrepareCastSpell(spellToUse.ID));
await Delay((uint)spellToUse.CastTime * 480);
await TrySend(() => _characterActions.CastSpell(spellToUse.ID, _characterRepository.MainCharacter));
await Delay(ATTACK_BACKOFF_MS); // 600ms cooldown between spell casts
}
private async Task UseHealItem(IEnumerable<InventoryItem> healItems)
{
var itemToUse = _itemData
.Where(x => healItems.Any(y => y.ItemID == x.ID))
.OrderBy(x => x.HP)
.First();
var amount = healItems.Single(x => x.ItemID == itemToUse.ID).Amount;
ConsoleHelper.WriteMessage(ConsoleHelper.Type.UseItem, $"{itemToUse.Name} - {itemToUse.HP} HP - inventory: {amount - 1} - (other heal item types: {healItems.Count() - 1})");
await TrySend(() => _itemActions.UseItem(itemToUse.ID));
await Delay(ATTACK_BACKOFF_MS);
}
private async Task ToggleSit()
{
var renderProps = _characterRepository.MainCharacter.RenderProperties;
var nextState = renderProps.SitState == SitState.Standing ? "Floor" : "Stand";
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Sit, $"{nextState,7} - Toggling from: {Enum.GetName(typeof(SitState), renderProps.SitState)}");
await TrySend(_characterActions.ToggleSit);
}
private async Task TrySend(Action action, uint attempts = 3)
{
for (uint i = 1; i <= attempts; i++)
{
try
{
action();
break;
}
catch (NoDataSentException)
{
ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"{i} / {attempts} - No data sent", ConsoleColor.DarkRed);
if (i == attempts)
throw;
await Delay(i * i * 1000);
}
}
}
private Task Delay(uint milliseconds)
{
_fixedTimeStepRepository.Tick(milliseconds / 10);
return Task.Delay((int)milliseconds);
}
}
}