Скрипт - Инвентарь API / Inventory API для RAGE Multiplayer
Этот ресурс предоставляет API инвентаря, полезно для разработчиков серверов.
Этот ресурс ничего не сохраняет, он просто предоставляет вам функции для создания собственной системы инвентаря с помощью CEF/NativeUI или команд.

Установка:
  • Поместите загруженные файлы в соответствующие места
  • Прочитайте документацию и примеры, чтобы настроить некоторые элементы и т.д.
  • Все готово
Особенности:
  • Простота в использовании (надеюсь!)
  • События
  • Пользовательские атрибуты для итемов (см. примеры)
API Инвентаря(Inventory API)
const invAPI = require("../inventory-api");
/**
 * Adds an item to the inventory system.
 * @param {string} key         Item identifier, such as "item_medkit".
 * @param {string} name        Item name, such as "Medkit".
 * @param {string} description Item description, such as "Gives you 10 health".
 * @param {function} [onUse]       Optional - Function that gets called when the item is used.
 * @return {object} The added item, will be null if there are any mistakes.
 * @fires itemDefined
 */
invAPI.addItem(key, name, description, onUse);

/**
 * Returns whether the specified key is a registered or not.
 * @param  {string}  key Item identifier, such as "item_medkit".
 * @return {Boolean}     True if registered, false otherwise.
 */
invAPI.hasItem(key);

/**
 * Returns the specified item.
 * @param  {string} key Item identifier, such as "item_medkit".
 * @return {object}     The item at the specified key, will be undefined if the key isn't registered.
 */
invAPI.getItem(key);

/**
 * Returns all registered item identifiers.
 * @return {string[]} An array of registered item identifiers.
 */
invAPI.getAllItems();

/**
 * Returns the human readable name of the specified item.
 * @param  {string} key Item identifier, such as "item_medkit".
 * @return {string}     Human readable item name.
 */
invAPI.getItemName(key);

/**
 * Returns the description of the specified item.
 * @param  {string} key Item identifier, such as "item_medkit".
 * @return {string}     Item's description.
 */
invAPI.getItemDescription(key);
API События Инвентаря(Inventory API Events)
/**
 * itemDefined
 * This event is called when an item is added to the system with invAPI.addItem()
 * @param {string} key Item identifier.
 * @param {string} name Human readable name of the item.
 * @param {string} description Description of the item.
 */
invAPI.on("itemDefined", (key, name, description) => {
    // Example: console.log(`Item defined, key: ${key} | name: ${name} | description: ${description}`);
});
/**
 * itemAdded
 * This event is called when a player receives an item.
 * @param {player} player The player who received the item.
 * @param {string} key Item identifier.
 * @param {number} amount Amount the player received.
 * @param {object} data Item attributes.
 */
invAPI.on("itemAdded", (player, key, amount, data) => {
    // Example: console.log(`${player.name} received ${amount}x ${key}.`);
});
/**
 * itemUsed
 * This event is called when a player uses an item.
 * @param {player} player The player who used the item.
 * @param {number} invIdx Index of the item in player's inventory.
 * @param {string} key Item identifier.
 * @param {object} data Item attributes.
 */
invAPI.on("itemUsed", (player, invIdx, key, data) => {
    // Example: console.log(`${player.name} used ${key}.`);
});
/**
 * itemRemoved
 * This event is called when an item is removed from a player's inventory.
 * @param {player} player The player who lost an item.
 * @param {number} invIdx Index of the item that got removed in player's inventory.
 * @param {string} key Item identifier.
 * @param {number} amount Removed item amount.
 * @param {object} data Item attributes.
 */
invAPI.on("itemRemoved", (player, invIdx, key, amount, data) => {
    // Example: console.log(`${player.name} lost ${amount}x ${key}.`);
});
/**
 * itemRemovedCompletely
 * This event is called when an item is no longer in a player's inventory.
 * @param {player} player The player who lost an item.
 * @param {string} key Item identifier.
 * @param {object} data Item attributes.
 */
invAPI.on("itemRemovedCompletely", (player, key, data) => {
    // Example: console.log(`${player.name} no longer has ${key} (${data ? "with data" : "without data"}) in their inventory.`);
});
/**
 * inventoryReplaced
 * This event is called when a player's inventory array gets changed by player.setInventory()
 * @param {player} player The player who had an inventory change.
 * @param {object[]} oldInventory The player's old inventory array.
 * @param {object[]} newInventory The player's new inventory array.
 */
invAPI.on("inventoryReplaced", (player, oldInventory, newInventory) => {
    // Example: console.log(`${player.name} had their inventory replaced. (Old item count: ${oldInventory.length}, new: ${newInventory.length})`);
});
API игрока
/**
 * Returns the inventory array of the player.
 * @return {object[]} An array that holds all items of the player.
 */
player.getInventory();

/**
 * Replaces the inventory array of the player with the specified one.
 * @param {Array} newInventory An array that's going to be the new inventory of the player.
 * @return {Boolean} True if successful, false otherwise.
 * @fires inventoryReplaced
 */
player.setInventory(newInventory);

/**
 * Returns whether the player has the specified item or not.
 * @param  {string}  itemKey Item identifier.
 * @return {Boolean}         True if player has the item, false otherwise.
 */
player.hasItem(itemKey);

/**
 * Same as hasItem but for items with custom attributes.
 * @param  {string}  itemKey Item identifier.
 * @param  {object}  data    An object that has item attributes.
 * @return {Boolean}         True if player has the item, false otherwise.
 */
player.hasItemWithData(itemKey, data);

/**
 * Gets the item's index in the player's inventory.
 * @param  {string} itemKey Item identifier.
 * @return {number}         Index of the item, -1 if not found.
 */
player.getItemIndex(itemKey);

/**
 * Same as getItemIndex but for items with custom attributes.
 * @param  {string} itemKey Item identifier.
 * @param  {object} data    An object that has item attributes.
 * @return {number}         Index of the item, -1 if not found.
 */
player.getItemIndexWithData(itemKey, data);

/**
 * Gets how many of the specified item exists in the player's inventory.
 * @param  {string} itemKey Item identifier.
 * @return {number}         Item amount.
 */
player.getItemAmount(itemKey);

/**
 * Same as getItemAmount but for items with custom attributes.
 * @param  {string} itemKey Item identifier.
 * @param  {object} data    An object that has item attributes.
 * @return {number}         Item amount.
 */
player.getItemAmountWithData(itemKey, data);

/**
 * Gets total amount of items the player has in their inventory.
 * @return {number} Amount of all items.
 */
player.getTotalItemAmount();

/**
 * Gives the specified item to the player.
 * @param  {string} itemKey Item identifier.
 * @param  {number} amount  Amount to give.
 * @param  {object} [data]    Optional - An object that has item attributes.
 * @return {Boolean}         True if successful, false otherwise.
 * @fires itemAdded
 */
player.giveItem(itemKey, amount, data);

/**
 * Uses the item at the specified index of the player's inventory array.
 * @param  {number} itemIdx Index of the item in player's inventory array.
 * @return {Boolean}         True if successful, false otherwise.
 * @fires itemUsed
 */
player.useItem(itemIdx);

/**
 * Removes the item at the specified index of the player's inventory array.
 * @param  {number} itemIdx Index of the item in player's inventory array.
 * @param  {number} [amount]  Optional - Amount to remove.
 * @return {Boolean}         True if successful, false otherwise.
 * @fires itemRemoved
 * @fires itemRemovedCompletely
 */
player.removeItem(itemIdx, amount);
Полный тестовый скрипт (Для разработки)
const invAPI = require("../inventory-api");

// Subscribe to some events...
invAPI.on("itemDefined", (key, name, description) => {
    console.log(`Item defined, key: ${key} | name: ${name} | description: ${description}`);
});

invAPI.on("itemAdded", (player, key, amount, data) => {
    console.log(`${player.name} received ${amount}x ${key}.`);
});

invAPI.on("itemUsed", (player, invIdx, key, data) => {
    console.log(`${player.name} used ${key}.`);
});

invAPI.on("itemRemoved", (player, invIdx, key, amount, data) => {
    console.log(`${player.name} lost ${amount}x ${key}.`);
});

invAPI.on("itemRemovedCompletely", (player, key, data) => {
    console.log(`${player.name} no longer has ${key} (${data ? "with data" : "without data"}) in their inventory.`);
});

invAPI.on("inventoryReplaced", (player, oldInventory, newInventory) => {
    console.log(`${player.name} had their inventory replaced. (Old item count: ${oldInventory.length}, new: ${newInventory.length})`);
});

// Add some items...
invAPI.addItem("item_bodyarmor", "Body Armor", "Refills your armor when used.", (player, inventoryIndex, itemKey, data) => {
    player.armour = 100;
    player.outputChatBox("Armor refilled.");
    player.removeItem(inventoryIndex);
});

invAPI.addItem("item_firstaid", "First Aid Kit", "Gives 20 health when used.", (player, inventoryIndex, itemKey, data) => {
    let amountOfHealth = 20;
    if (data && data.hasOwnProperty("effectMultiplier")) amountOfHealth = Math.floor(amountOfHealth * data.effectMultiplier);

    if (player.health + amountOfHealth > 100) {
        player.outputChatBox("You don't need to use a first aid kit.");
        return;
    }

    player.health += amountOfHealth;
    player.outputChatBox(`Used a first aid kit for ${amountOfHealth} health.`);
    player.removeItem(inventoryIndex);
});

invAPI.addItem("item_male_hoodie", "Hoodie (Male)", "A hoodie for freemode male model.", (player, inventoryIndex, itemKey, data) => {
    if (player.model !== mp.joaat("mp_m_freemode_01")) {
        player.outputChatBox("Can't use this item with your current model.");
        return;
    }

    let texture = 0;
    if (data && data.hasOwnProperty("texture")) texture = data.texture;

    player.setClothes(11, 7, texture, 2);
    player.outputChatBox(`Now wearing: Hoodie with texture variation ${texture}.`);
    player.removeItem(inventoryIndex);
});

invAPI.addItem("item_copoutfit", "Police Outfit", "To protect and to serve.");
invAPI.addItem("item_repairkit", "Repair Kit", "Repairs your car.");

// Since item_copoutfit and item_repairkit has no onUse defined, you can give them functionality like this
invAPI.on("itemUsed", (player, invIdx, key, data) => {
    switch (key) {
        case "item_copoutfit":
            // imaginary function here that applies the police outfit
            player.outputChatBox("Now wearing the police outfit.");
            player.removeItem(invIdx);
        break;

        case "item_repairkit":
            const playerVehicle = player.vehicle;

            if (playerVehicle) {
                playerVehicle.repair();
                player.outputChatBox("Vehicle repaired.");
                player.removeItem(invIdx);
            } else {
                player.outputChatBox("You're not in a vehicle.");
            }
        break;
    }
});

// Bunch of inventory commands
const fs = require("fs");
const path = require("path");

// Do /saveinventory to save your inventory to a JSON file. (file path will be printed to console)
mp.events.addCommand("saveinventory", (player) => {
    const saveDir = path.join(__dirname, "inventories");
    if (!fs.existsSync(saveDir)) fs.mkdirSync(saveDir);

    const playerPath = path.join(saveDir, `${player.socialClub}.json`);
    fs.writeFileSync(playerPath, JSON.stringify(player.getInventory(), null, 2));

    player.outputChatBox("Inventory saved.");
    console.log(`Player ${player.name} saved their inventory. (${playerPath})`);
});

// Do /loadinventory to load your inventory from a JSON file.
mp.events.addCommand("loadinventory", (player) => {
    const playerPath = path.join(__dirname, "inventories", `${player.socialClub}.json`);

    if (fs.existsSync(playerPath)) {
        player.setInventory(JSON.parse(fs.readFileSync(playerPath)));
        player.outputChatBox("Inventory loaded.");
    } else {
        player.outputChatBox("Inventory file not found.");
    }
});

// Do /inventory to list your items in "slot | name | amount" format.
mp.events.addCommand("inventory", (player) => {
    const inventory = player.getInventory();

    player.outputChatBox("Your inventory:");
    inventory.forEach((item, index) => {
        player.outputChatBox(`${index} | ${invAPI.getItemName(item.key)} (${item.key}) | ${item.amount}x`);
    });
});

// Do /giveitem [key] [amount] to give yourself an item.
mp.events.addCommand("giveitem", (player, _, itemKey, amount) => {
    amount = Number(amount);

    if (player.giveItem(itemKey, amount)) {
        player.outputChatBox(`Added ${amount}x ${invAPI.getItemName(itemKey)} (${itemKey}) to your inventory.`);
    } else {
        player.outputChatBox("Failed to give item.");
    }
});

// Do /useitem [slot] to use an item from your inventory.
mp.events.addCommand("useitem", (player, _, itemIndex) => {
    itemIndex = Number(itemIndex);

    if (player.useItem(itemIndex)) {
        player.outputChatBox(`Used item at index ${itemIndex}.`);
    } else {
        player.outputChatBox("Failed to use item.");
    }
});

// Do /removeitem [slot] [amount] to remove an item from your inventory.
mp.events.addCommand("removeitem", (player, _, itemIndex, amount) => {
    itemIndex = Number(itemIndex);
    amount = Number(amount);

    if (player.removeItem(itemIndex, amount)) {
        player.outputChatBox(`Removed ${amount} of item at index ${itemIndex}.`);
    } else {
        player.outputChatBox("Failed to remove item.");
    }
});

// Custom attribute commands
// Do /betterfirstaid to give yourself a first aid kit that gives +50 health instead of the usual 20.
mp.events.addCommand("betterfirstaid", (player) => {
    const giveItemResult = player.giveItem("item_firstaid", 1, {
        effectMultiplier: 2.5
    });

    if (giveItemResult) {
        player.outputChatBox("Received +50 HP first aid kit.");
    } else {
        player.outputChatBox("Failed to give item.");
    }
});

// Do /givehoodie [texture] to give yourself a hoodie item with the variation you specified.
mp.events.addCommand("givehoodie", (player, _, texture) => {
    const giveItemResult = player.giveItem("item_male_hoodie", 1, {
        texture: Number(texture)
    });

    if (giveItemResult) {
        player.outputChatBox(`Received a male hoodie with texture variation ${texture}.`);
    } else {
        player.outputChatBox("Failed to give item.");
    }
});
Автор: rootcause
Версия:
1.0
У вас нет доступа к скачиванию файлов с нашего сервера
Версия: 1.1.0
- Добавлены свойства nameFunc и descFunc для определенных элементов. Вы можете изменить возвращаемые значения invAPI.getItemName() и invAPI.getItemDescription(), определив функции name и description.
- Функции invAPI.getItemName() и invAPI.getItemDescriptio () теперь могут принимать объект атрибутов элемента в качестве второго аргумента.
Пример названия(name)/описания(description) функции:
const drinkItem = invAPI.addItem("item_drink", "Drink", "Generic drink.");

drinkItem.nameFunc = function(data) {
    if (data && data.hasOwnProperty("drinkType")) {
        return `Drink (${data.drinkType})`;
    } else {
        return "Drink";
    }
};

drinkItem.descFunc = function(data) {
    if (data && data.hasOwnProperty("drinkType")) {
        switch (data.drinkType) {
            case "wine":
                return "Wine description.";

            case "water":
                return "Water description.";
        }
    } else {
        return "Generic drink.";
    }
};

// Outputs
console.log(invAPI.getItemName("item_drink")); // Drink
console.log(invAPI.getItemName("item_drink", { drinkType: "wine" })); // Drink (wine)
console.log(invAPI.getItemName("item_drink", { drinkType: "water" })); // Drink (water)

console.log(invAPI.getItemDescription("item_drink")); // Generic drink.
console.log(invAPI.getItemDescription("item_drink", { drinkType: "wine" })); // Wine description.
console.log(invAPI.getItemDescription("item_drink", { drinkType: "water" })); // Water description.
У вас нет доступа к скачиванию файлов с нашего сервера

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

Комментариев 6
  1. Не плохо!
    #1
  2. Блин на си шарпе есть?
    #2
  3. Норм скрипт
    #3
  4. спасибо автору
    #4
  5. красава
    #5
  6. WutFace таааак
    #6
Информация
Посетители, находящиеся в группе Гости, не могут оставлять комментарии к данной публикации.
Наши сервисы
12 посетителей на сайте. Из них:
Гости5
Роботы7

Как вы нас нашли?
Информация

Добро пожаловать на RAGE-MULTIPLAYER.RU!

Для того чтобы стать полноценным пользователем нашего портала, вам необходимо пройти регистрацию.
Зарегистрироваться
Создайте собственную учетную запить!

Пройти регистрацию
Авторизоваться
Уже зарегистрированны? А ну-ка живо авторизуйтесь!

Войти на сайт
Яндекс.Метрика
18+