~ruther/NosSmooth.Local

ref: 06f078dcbeef77ec800477bc8057e5ac9bcde926 NosSmooth.Local/src/Samples/HighLevel/SimplePiiBot/Bot.cs -rw-r--r-- 6.5 KiB
06f078dc — František Boháček chore: update dependencies 2 years ago
                                                                                
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
//
//  Bot.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Extensions.Logging;
using NosSmooth.Core.Extensions;
using NosSmooth.Core.Stateful;
using NosSmooth.Extensions.Combat;
using NosSmooth.Extensions.Combat.Policies;
using NosSmooth.Extensions.Combat.Techniques;
using NosSmooth.Extensions.Pathfinding;
using NosSmooth.Game;
using NosSmooth.Game.Apis;
using NosSmooth.Game.Data.Characters;
using NosSmooth.Game.Data.Entities;
using NosSmooth.Game.Data.Info;
using NosSmooth.Game.Data.Maps;
using Remora.Results;

namespace SimplePiiBot;

/// <summary>
/// The pii bot.
/// </summary>
public class Bot : IStatefulEntity
{
    private static readonly long[] PiiPods = { 45, 46, 47, 48, 49, 50, 51, 52, 53 };
    private static readonly long[] Piis = { 36, 37, 38, 39, 40, 41, 42, 43, 44 };
    private static readonly long RangeSquared = 15 * 15;
    private static readonly long MaxPiiCount = 15;

    private readonly NostaleChatPacketApi _chatPacketApi;
    private readonly CombatManager _combatManager;
    private readonly Game _game;
    private readonly WalkManager _walkManager;
    private readonly ILogger<Bot> _logger;
    private CancellationTokenSource? _startCt;

    /// <summary>
    /// Initializes a new instance of the <see cref="Bot"/> class.
    /// </summary>
    /// <param name="chatPacketApi">The chat packet api.</param>
    /// <param name="combatManager">The combat manager.</param>
    /// <param name="game">The game.</param>
    /// <param name="walkManager">The walk manager.</param>
    /// <param name="logger">The logger.</param>
    public Bot
    (
        NostaleChatPacketApi chatPacketApi,
        CombatManager combatManager,
        Game game,
        WalkManager walkManager,
        ILogger<Bot> logger
    )
    {
        _chatPacketApi = chatPacketApi;
        _combatManager = combatManager;
        _game = game;
        _walkManager = walkManager;
        _logger = logger;
    }

    /// <summary>
    /// Start the bot.
    /// </summary>
    /// <param name="ct">The cancellation token used for cancelling the operation.</param>
    /// <returns>A result that may or may not succeed.</returns>
    public async Task<Result> StartAsync(CancellationToken ct = default)
    {
        if (_startCt is not null)
        {
            return new GenericError("The bot is already running.");
        }

        Task.Run
        (
            async () =>
            {
                try
                {
                    await Run(ct);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "The bot threw an exception");
                }
            }
        );

        return Result.FromSuccess();
    }

    private async Task Run(CancellationToken ct)
    {
        await _chatPacketApi.ReceiveSystemMessageAsync("Starting the bot.", ct: ct);
        _startCt = CancellationTokenSource.CreateLinkedTokenSource(ct);
        ct = _startCt.Token;
        while (!ct.IsCancellationRequested)
        {
            var map = _game.CurrentMap;
            if (map is null)
            {
                await _chatPacketApi.ReceiveSystemMessageAsync("The map is null, quitting. Change the map.", ct: ct);
                await StopAsync();
                return;
            }

            var character = _game.Character;
            if (character is null || character.Position is null)
            {
                await _chatPacketApi.ReceiveSystemMessageAsync
                    ("The character is null, quitting. Change the map.", ct: ct);
                await StopAsync();
                return;
            }

            var entity = ChooseNextEntity(map, character, character.Position.Value);
            if (entity is null)
            {
                await _chatPacketApi.ReceiveSystemMessageAsync
                    ("There are no piis in range.", ct: ct);
                await StopAsync();
                return;
            }

            var combatResult = await _combatManager.EnterCombatAsync
            (
                new SimpleAttackTechnique
                (
                    entity.Id,
                    _walkManager,
                    new SkillSelector(Piis.Contains(entity.VNum))
                ),
                ct
            );

            if (!combatResult.IsSuccess)
            {
                _logger.LogResultError(combatResult);
                await StopAsync();
                return;
            }
        }
    }

    private Monster? ChooseNextEntity(Map map, Character character, Position characterPosition)
    {
        var piisCount = map.Entities
            .GetEntities()
            .Where(x => x.Position?.DistanceSquared(characterPosition) <= RangeSquared)
            .OfType<Monster>()
            .Count(x => Piis.Contains(x.VNum) && x.Hp?.Percentage > 0);

        var choosingList = PiiPods;
        if (piisCount >= MaxPiiCount)
        { // max count of piis reached, choose pii instead of a pad
            choosingList = Piis;
        }

        var piiOrPod = GetEntity(choosingList, map, characterPosition);

        if (piiOrPod is null && piisCount != 0)
        {
            piiOrPod = GetEntity(Piis, map, characterPosition);
        }

        return piiOrPod;
    }

    private Monster? GetEntity(long[] choosingList, Map map, Position characterPosition)
    {
        return map.Entities.GetEntities()
            .OfType<Monster>()
            .Where(x => x.Hp?.Percentage > 0)
            .Where(x => x.Position?.DistanceSquared(characterPosition) <= RangeSquared)
            .Where(x => choosingList.Contains(x.VNum))
            .MinBy
            (
                x => x.Position is null
                    ? long.MaxValue
                    : characterPosition.DistanceSquared(x.Position.Value)
            );
    }

    /// <summary>
    /// Stop the bot.
    /// </summary>
    /// <param name="ct">The cancellation token used for cancelling the operation.</param>
    /// <returns>A result that may or may not succeed.</returns>
    public async Task<Result> StopAsync(CancellationToken ct = default)
    {
        var startCt = _startCt;
        var messageResult = await _chatPacketApi.ReceiveSystemMessageAsync("Stopping the bot.", ct: ct);
        if (startCt is not null)
        {
            try
            {
                startCt.Cancel();
            }
            catch
            {
                // ignored
            }
            startCt.Dispose();
        }
        _startCt = null;

        return messageResult;
    }
}
Do not follow this link