> For the complete documentation index, see [llms.txt](https://docs.quickclient.cc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.quickclient.cc/examples/auto-soup.md).

# Автосуп

Скрипт, который ест грибной суп при низком здоровье и возвращает слот.

Когда здоровье падает, скрипт ест грибной суп: переключается на него в хотбаре, держит пару тиков, нажимает правую кнопку и возвращает слот обратно. Пример показывает, как работать с ручкой слота, считать время в тиках и не мешать собственным действиям игрока.

```java
package my;

import hex.script.api.CheckBox;
import hex.script.api.HeldSlot;
import hex.script.api.Script;
import hex.script.api.Slider;

import java.util.Random;

public class AutoSoup extends Script {

    private static final String SOUP = "mushroom_stew";

    private final Slider health = slider("Здоровье", 12f, 1f, 19f, 1f);
    private final Slider delayFrom = slider("Пауза от", 3f, 0f, 20f, 1f).postfix("t");
    private final Slider delayTo = slider("Пауза до", 5f, 0f, 20f, 1f).postfix("t");
    private final Slider holdTicks = slider("Держать перед едой", 2f, 0f, 20f, 1f).postfix("t");
    private final CheckBox keepItemUse = checkBox("Не прерывать использование", true);

    private final Random random = new Random();

    private HeldSlot held;
    private int sinceSoup;
    private int sinceHold;
    private int nextDelay;

    @Override
    public String description() {
        return "Ест суп, когда мало здоровья, и возвращает слот";
    }

    @Override
    public void activate() {
        held = null;
        sinceSoup = 0;
        nextDelay = 0;
    }

    @Override
    public void deactivate() {
        release();
    }

    @Override
    public void onTick() {
        sinceSoup++;
        if (!player().present()) {
            release();
            return;
        }

        if (held != null) {
            holdTick();
            return;
        }

        int soup = inventory().findHotbar(SOUP);
        boolean handFree = !keepItemUse.value() || !player().using();
        if (soup >= 0 && handFree && player().health() <= health.value() && sinceSoup >= nextDelay) {
            held = slots().select(soup);
            sinceHold = 0;
        }
    }

    private void holdTick() {
        if (!inventory().slot(held.slot()).is(SOUP)) {
            release();
            return;
        }
        if (++sinceHold < holdTicks.intValue()) return;

        interaction().useItem(false);
        release();
        rollDelay();
        sinceSoup = 0;
    }

    private void release() {
        if (held == null) return;
        held.restoreWhenSafe();
        held = null;
    }

    private void rollDelay() {
        int from = delayFrom.intValue();
        int to = delayTo.intValue();
        nextDelay = to <= from ? from : from + random.nextInt(to - from);
    }
}
```

## Разбор

**Выбор слота и клик в разных тиках.** `slots().using(...)` сделал бы и то и другое сразу. Здесь слот выбирается через `slots().select(...)`, удерживается `holdTicks` тиков, и только потом происходит клик. Для этого и нужна ручная форма `HeldSlot`. `restoreWhenSafe()` вернёт слот на следующем тике и не прервёт использование предмета.

**Проверка ручки каждый тик.** Пока слот удерживается, суп может из него пропасть: его съели, выбросили или переложил другой модуль. Тогда проверка `is(SOUP)` не пройдёт, и слот вернётся сразу. Самая частая ошибка в таких скриптах это ручка, которую забыли отпустить, поэтому `deactivate()` тоже её отпускает.

**Случайная пауза между супами.** Два ползунка задают диапазон, а `rollDelay()` после каждого супа выбирает число внутри него. Интервал каждый раз разный.

**Счёт в тиках.** `tasks()` считает реальное время, а серверу важны тики. Счётчики в полях и `onTick()` дают ровно то время, которое видит сервер.

**Настройка keepItemUse.** Правый клик нужен не только для еды. Без этой настройки скрипт прерывал бы натянутый лук или зелье, которое игрок пьёт.

**Суп только из хотбара.** Перекладывать суп из инвентаря в хотбар скрипт не умеет: API позволяет кликать только по открытому контейнеру, а не по своему инвентарю. Подробнее в [Контейнерах и экранах](/game/containers.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.quickclient.cc/examples/auto-soup.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
