Lines 100.00% 36 / 36
Methods 100.00% 4 / 4
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 describe 100.00% 1 / 1 100.00% 1 / 1 1
 play 100.00% 26 / 26 100.00% 1 / 1 7
 equipped 100.00% 8 / 8 100.00% 1 / 1 3
25final readonly class Enhance implements Action
26{
27    public function __construct(
28        public EnhancementType $type,
29    ) {}
30
31    #[Override]
32    public function describe(): string
33    {
34        return "Enhance the equipped gear with {$this->type->name}";
35    }
36
37    #[Override]
38    public function play(StepScript $bot): Generator
39    {
40        $shop = EnhancementShops::selling($this->type, $bot->me()->hero()->level);
41        if ($shop === null) {
42            return new Failed("no shop sells {$this->type->name} enhancements");
43        }
44
45        yield from $bot->rest();
46        $area = $bot->me()->location()->area;
47        $loading = $bot->paced($bot->send(new LoadShopCommand($area, $shop))->awaits(
48            Duration::seconds(10),
49            ShopLoadedEvent::class,
50        ));
51        yield from $loading;
52        $loaded = $loading->getReturn();
53        $selling = $loaded instanceof ShopLoadedEvent ? $loaded->shop : null;
54        if (!$selling instanceof CurrencyShop) {
55            return new Failed("the {$this->type->name} enhancement shop did not open");
56        }
57
58        foreach (self::equipped($bot) as $held) {
59            $best = BestEnhancement::for($held, $this->type, $selling, $bot->me()->hero());
60            if ($best === null) {
61                continue;
62            }
63
64            $enhancing = $bot->paced($bot->send(new EnhanceItemCommand($area, $held->id, $best->id, $shop))->awaits(
65                Duration::seconds(10),
66                ItemsEnhancedEvent::class,
67            ));
68            yield from $enhancing;
69            if (!$enhancing->getReturn() instanceof ItemsEnhancedEvent) {
70                return new Failed("the game would not enhance {$held->name->value}");
71            }
72        }
73
74        return null;
75    }
76
77    /** @return list<Equipment&Enchantable> */
78    private static function equipped(StepScript $bot): array
79    {
80        $equipment = $bot->me()->hero()->inventory->equipment;
81        $equipped = [];
82        foreach (EquipmentSlot::cases() as $slot) {
83            $item = $equipment->equipped($slot)->unwrapOr(null);
84            if (!$item instanceof Enchantable) {
85                continue;
86            }
87
88            $equipped[] = $item;
89        }
90
91        return $equipped;
92    }
93}