Создаем цветное сообщение игрокам с помощью Colorchat.inc

Сообщения
2,291
Реакции
1,737
Помог
31 раз(а)
Источник - http://amxxmodx.ru

Colorchat - С помощью данного инклюда, очень просто "раскрасить" привычные всем желтые сообщения в чате.
Данный инклуд дает одноименную функцию ColorChat

Синтаксис:
Код:
ColorChat(index,Color:type,const msg[],{Float,Sql,Result,_}:...)
Синтаксис для Amxmodx 1.8.3 и Re AMX Mod X :
Код:
client_print_color(index, sender, const message[], any:...);
  • index - id Игрока кому показывать сообщение, выставите 0 если хотите показать сообщение сразу всем игрокам
  • Color:type - Цвет сообщения по умолчанию. Стандартное сообщение желтого цвета, но мы можем поставить RED и все сообщение будет красным, но в дальнейшем мы сможем менять цвет отдельным словам
  • const msg[] - Само сообщение в виде массива или текст заключенный в кавычки "text"
  • {Float,Sql,Result,_}:... - Если сообщение не в виде массива, а в виде "text %s text", то тут мы записываем массивы для вывода в соответствующих местах %* Пример:
Код:
ColorChat(id,RED,"[Color Chat] ^1 You name is ^4 %s  ",UserName)
^1,^3,^4 - изменение цвета

Как изменять цвета отдельных слов в сообщении:
  • ^1 - Обычный цвет сообщения
  • ^3 - Цвет по умолчанию что мы установили Color:type
  • ^4 - Зеленый цвет
Пример:
Код:
ColorChat(id,NORMAL,"Colordefault ^1Color1 ^3Color3 ^4Color4")
Что вы получите если Вы:
Counter
- ColorDefault Color1 Color3 Color4
Terrorist - ColorDefault Color1 Color3 Color4
Spectator - ColorDefault Color1 Color3 Color4
Заметили систему? Попробуйте поэкспериментировать, это легко и занимательно.

И так, теперь к конкретному рабочему примеру:
Первое что нам необходимо сделать, это подключить инклуд:
Код:
#include <colorchat>
Примечание: Для Amxmodx 1.8.3 и Re AMX Mod X данный инклуд не нужен

Рабочий пример, показывающий все возможные варианты:
Код:
#include <amxmodx>
#include <amxmisc>
#include <colorchat>
 
#define PLUGIN "Color message in chat"
#define VERSION "1.0"
#define AUTHOR "Admin"
 
 
public plugin_init ( )
{
    register_plugin ( PLUGIN, VERSION, AUTHOR )
    
    register_clcmd("say /normal","default_normal")// clients scr_concolor cvar color
    register_clcmd("say /green","default_green")
    register_clcmd("say /teamcolor","default_team_color") // Red, grey, blue
    register_clcmd("say /grey","default_grey")
    register_clcmd("say /red","default_red")
    register_clcmd("say /blue","default_blue")
    
}
public    default_normal(id){
    
    ColorChat(id,NORMAL,"Color default NORMAL ^1Color1 ^3Color3 ^4Color4")
}
public default_green (id){
    
    ColorChat(id,GREEN,"Color default GREEN ^1Color1 ^3Color3 ^4Color4")
}
public default_team_color (id){
    
    ColorChat(id,TEAM_COLOR,"Color default Team Color ^1Color1 ^3Color3 ^4Color4")
}
public default_grey (id){
    
    ColorChat(id,GREY,"Color default GREY ^1Color1 ^3Color3 ^4Color4")
}
public default_red (id){
    
    ColorChat(id,RED,"Color default RED ^1Color1 ^3Color3 ^4Color4")
}
public default_blue (id){
    
    ColorChat(id,BLUE,"Color default BLUE ^1Color1 ^3Color3 ^4Color4")
}
Описание:
В принципе описывать здесь особо нечего,подключили инклуд, зарегистрировали шесть команд:
  1. say /normal
  2. say /green
  3. say /teamcolor
  4. say /grey
  5. say /red
  6. say /blue
В каждой команде после знака / ( слеш) следует тип цвета установленный по умолчанию в функции.
Далее в каждой функции мы устанавливаем цвет по умолчанию, соответствующий имени форварда и берем 4 блока для цвета.
Все они аналогичные для всех цветов, разница только в цвете по умолчанию, что бы вы смогли заметить разницу.
 
Сообщения
2,144
Реакции
1,223
Помог
44 раз(а)
Стандартное сообщение желтого цвета, но мы можем поставить RED и все сообщение будет красным, но в дальнейшем мы сможем менять цвет отдельным словам
C++:
/**
* Color types for client_print_color()
*/
enum
{
    print_team_default = 0,
    print_team_grey = -1,
    print_team_red = -2,
    print_team_blue = -3,
};
Где ты увидел RED, BLUE и т.п.? Не путай читателей. Либо print_team_* , либо цифрами (0, -1, -2, -3), либо вторым id, которое будет ставить цвет команды, в которой игрок находится.
4 Дек 2017
В дополнение.
Код:
/**
* Sends colored chat messages to clients.
*
* @note This only works in Counter-Strike 1.6 and Condition Zero.
* @note The colors can be modified inside of the format string using special
*       characters. These characters can be included using the escape character
*          green           x04   ; use location color from this point forward
*          red/blue/grey   x03   ; use team color from this point forward
*          red/blue/grey   x02   ; use team color to the end of the client name
*                                ; This only works at the start of the string,
*                                ; and precludes using other control characters
*          default         x01   ; use default color from this point forward
* @note The team color is defined by the sender's index. Alternatively, a
*       specific team color can be enforced using the print_team_* constants in
*       amxconst.inc
* @note Usage examples:
*       client_print_color(id, print_team_red, "^4Green ^3Red ^1Default")
*       client_print_color(id, id2, "^4Green ^3id2's team color, ^1Default")
* @note Including colors in ML can be done using the same escaping method:
*       EXAMPLE_ML_KEY = ^4Green ^3Team color ^1Default
* @note This functions return value behaves differently depending on what is
*       used as the client index: If 0 is specified, then the function will
*       return 0 if nothing has been sent (no client connected). If either a
*       single client is specified, or there is at least one client connected,
*       the number of printed characters will refer to the message that is sent
*       last, to the client with the highest index.
*
* @param index     Client index, use 0 to display to all clients
* @param sender    Client index used as the message sender
* @param fmt       Formatting rules
* @param ...       Variable number of formatting parameters
*
* @return          Number of printed characters
* @error           If a single client is specified and the index is not within
*                  the range of 1 to MaxClients, an error will be thrown.
*/
native client_print_color(index, sender, const message[], any:...);
4 Дек 2017
И ^1, ^3, ^4 можно заменить на x01, x02, x03 и x04, но это зависит от удобства. Каждому нравится по-своему.
 
Последнее редактирование:

d3m37r4

111111
Сообщения
1,420
Реакции
1,162
Помог
10 раз(а)
Надо было в шапку прикрепить инклуд колорчата от Lev, он вроде в основном везде юзается, и уже от него танцевать в плане написания мануалов, + еще ни слова не сказано о передаче цвета тимы какого-нибудь игрока в аргументе sender, куда можно впилить индекс игрока, чтобы при использовании ^3 текст был цвета тимы игрока, индекс которого мы имеем.
 
Сообщения
493
Реакции
108
Помог
16 раз(а)
Подскажите всегда с этим путался.

  • index - id Игрока кому показывать сообщение, выставите 0 если хотите показать сообщение сразу всем игрокам
как узнать id игрока? на примере плагина
Best player of the round 0.61

если надо отправить сообщение только игроку.

Код:
#if defined AES_MAX_LEVEL_LENGTH
        if (g_MoneyBonus || g_AesExp || g_AesBonus > 0) {
#else
        if (g_MoneyBonus) {
#endif
            if (player == maxId)
                 client_print_color(player, maxId, "%L %L", player, "BPR_PREFIX", player, "BPR_BONUS", message);
            else if (g_ShowAll == 1) 
                client_print_color(player, maxId, "%L %L", player, "BPR_PREFIX", player, "BPR_BONUS_ALL", name, message);
        }
    }
}
Так?)

Код:
#if defined AES_MAX_LEVEL_LENGTH
        if (g_MoneyBonus || g_AesExp || g_AesBonus > 0) {
#else
        if (g_MoneyBonus) {
#endif
            if (player == maxId)
                 client_print_color(id, maxId, "%L %L", player, "BPR_PREFIX", player, "BPR_BONUS", message);
            else if (g_ShowAll == 1) 
                client_print_color(id, maxId, "%L %L", player, "BPR_PREFIX", player, "BPR_BONUS_ALL", name, message);
        }
    }
}
 
Последнее редактирование:
Сообщения
1,175
Реакции
2,144
Помог
57 раз(а)
r1nk0, откуда вы id взяли? Нет такой локальной переменной, не создаётся она тут. В данном случае у вас единственная переменная с индексом игрока, это pKiller. Её и нужно использовать. Т.е. client_print_color(pKiller, print_team_default, ...)
 
Сообщения
493
Реакции
108
Помог
16 раз(а)
BlackSignature, немного переделал пример в вопросе когда вы ответили.
в обновленном примере тогда какая? maxId что ли? Я вообще запутался в коде,да и не шарю я.



Вот весь код плагина

Код:
/**
*
* Name: Best player of the round
* Version: 0.61 (07.01.2018)
* Author: F@nt0M
* Thanks: Got Milk?, HoHoL, Safety1st
*
* Requirements: AmxModX 1.8.3 or higher, ReAPI
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/

/**
* Use Advanced Experience System points as bonus
*/
// #define USE_AES

#include <amxmodx>
#include <reapi>

#if defined USE_AES
    #include <aes_v>
#endif

#define CheckBit(%1,%2)        (%1 &    (1 << (%2 & 31)))
#define SetBit(%1,%2)        (%1 |=    (1 << (%2 & 31)))
#define ClearBit(%1,%2)        (%1 &= ~(1 << (%2 & 31)))
#define ToggleBit(%1,%2)    (%1 ^=     (1 << (%2 & 31)))
#define ResetBits(%1)        (%1 &=     0)
#define FillBits(%1)        (%1 &= ~0)

new const g_Cases[] = {2, 0, 1, 1, 1, 2};
new const g_Titles[2][3][] = {
    {"BPR_KILL_1", "BPR_KILL_2", "BPR_KILL_3"},
    {"BPR_HS_1", "BPR_HS_2", "BPR_HS_3"}
}

new g_HudSync;
new g_FriendlyFire = 0;
new g_ShowAll = 1;
new g_ShowInfo = 1;
new g_NameNewLine = 1;
new g_MoneyBonus = 200;
#if defined AES_MAX_LEVEL_LENGTH
new g_AesExp = 5;
new g_AesBonus = 1;
#endif
new g_HudEnabled;

enum _:PLAYER_DATA {
    PLAYER_KILLS,
    PLAYER_DMG,
    PLAYER_HS
}

new g_PlayerData[MAX_CLIENTS + 1][PLAYER_DATA];

public plugin_init() {
    register_plugin("[ReAPI] Best player of the round", "0.6", "F@nt0M");

    register_dictionary("best_player_of_the_round.txt");

    RegisterHookChain(RG_CSGameRules_RestartRound, "CSGameRules_RestartRound", 1);
    RegisterHookChain(RG_RoundEnd, "RoundEnd", 1);
    RegisterHookChain(RG_CBasePlayer_TakeDamage, "CBasePlayer_TakeDamage", 1);
    RegisterHookChain(RG_CBasePlayer_Killed, "CBasePlayer_Killed", 1);

    g_HudSync = CreateHudSyncObj();

    new pcvar;

    pcvar = register_cvar("bpr_money", "1000");
    bind_pcvar_num(pcvar, g_MoneyBonus);

    pcvar = register_cvar("bpr_show_all", "1");
    bind_pcvar_num(pcvar, g_ShowAll);

    pcvar = register_cvar("bpr_show_info", "1");
    bind_pcvar_num(pcvar, g_ShowInfo);

    pcvar = register_cvar("bpr_name_newline", "1");
    bind_pcvar_num(pcvar, g_NameNewLine);

#if defined AES_MAX_LEVEL_LENGTH
    pcvar = register_cvar("bpr_aes_exp", "5");
    bind_pcvar_num(pcvar, g_AesExp);

    pcvar = register_cvar("bpr_aes_bonus", "1");
    bind_pcvar_num(pcvar, g_AesBonus);
#endif

    pcvar = get_cvar_pointer("mp_friendlyfire");
    bind_pcvar_num(pcvar, g_FriendlyFire);

    register_clcmd("say /hud", "CmdToggle");
    register_clcmd("say_team /hud", "CmdToggle");

    FillBits(g_HudEnabled);
}

public OnConfigsExecuted() {
    g_MoneyBonus = get_cvar_num("bpr_money");
    g_ShowAll = get_cvar_num("bpr_show_all");
    g_ShowInfo = get_cvar_num("bpr_show_info");
    g_NameNewLine = get_cvar_num("bpr_name_newline");
#if defined AES_MAX_LEVEL_LENGTH
    g_AesExp = get_cvar_num("bpr_aes_exp");
    g_AesBonus = get_cvar_num("bpr_aes_bonus");
#endif
    g_FriendlyFire = get_cvar_num("mp_friendlyfire");
}

public client_putinserver(id) {
    arrayset(g_PlayerData[id], 0, PLAYER_DATA);
    SetBit(g_HudEnabled, id);
}

public client_disconnected(id) {
    arrayset(g_PlayerData[id], 0, PLAYER_DATA);
    ClearBit(g_HudEnabled, id);
}

public CmdToggle(id) {
    ToggleBit(g_HudEnabled, id);
    if (CheckBit(g_HudEnabled, id)) {
        client_print_color(id, print_team_default, "%L", id, "BPR_HUD_ENABLED");
    } else {
        client_print_color(id, print_team_default, "%L", id, "BPR_HUD_DISABLED");
    }
}

public CSGameRules_RestartRound() {
    for(new i = 0; i <= MAX_CLIENTS; i++) {
        arrayset(g_PlayerData[i], 0, PLAYER_DATA);
    }
}

public RoundEnd(WinStatus:status, ScenarioEventEndRound:event) {
    #pragma unused status

    if (event == ROUND_GAME_COMMENCE || event == ROUND_GAME_RESTART || event == ROUND_GAME_OVER) {
        return HC_CONTINUE;
    }

    if (get_playersnum(0) <= 0) {
        return HC_CONTINUE;
    }

    set_task(1.0, "TaskRoundEnd");

    return HC_CONTINUE;
}

public CBasePlayer_TakeDamage(id, inflictor, attacker, Float:damage, damageType) {
    if (id == attacker || attacker < 1 || attacker > MaxClients) {
        return HC_CONTINUE;
    }

    if (g_FriendlyFire != 0 && get_member(id, m_iTeam) == get_member(attacker, m_iTeam)) {
        return HC_CONTINUE;
    }

    if (inflictor != attacker && ~damageType & DMG_GRENADE) {
        return HC_CONTINUE;
    }

    g_PlayerData[attacker][PLAYER_DMG] += floatround(damage);

    if( get_member(id, m_LastHitGroup) == HIT_HEAD) {
        g_PlayerData[attacker][PLAYER_HS]++;
    }

    return HC_CONTINUE;
}

public CBasePlayer_Killed(id, attacker) {
    if (id == attacker || attacker < 1 || attacker > MaxClients) {
        return HC_CONTINUE;
    }

    if (g_FriendlyFire != 0 && get_member(id, m_iTeam) == get_member(attacker, m_iTeam)) {
        return HC_CONTINUE;
    }

    g_PlayerData[attacker][PLAYER_KILLS]++;

    return HC_CONTINUE;
}

public TaskRoundEnd(id) {
    new players[MAX_CLIENTS], num, player, i;
    new maxId, maxKills, maxDmg;
    new name[MAX_NAME_LENGTH], num1, num2;

    new message[190], len;

    get_players(players, num, "h");
    for (i = 0; i < num; i++) {
        player = players[i];
        if (g_PlayerData[player][PLAYER_KILLS] > maxKills || g_PlayerData[player][PLAYER_DMG] > maxDmg) {
            maxId = player;
            maxKills = g_PlayerData[player][PLAYER_KILLS];
            maxDmg = g_PlayerData[player][PLAYER_DMG];
        }
    }

    if (maxId == 0) {
        return;
    }
   
    if (g_MoneyBonus > 0) {
        rg_add_account(maxId, g_MoneyBonus, AS_ADD, true);
    }

#if defined AES_MAX_LEVEL_LENGTH
    if (g_AesExp > 0) {
        aes_set_player_exp(maxId, aes_get_player_exp(maxId) + float(g_AesExp));
    }

    if (g_AesBonus > 0) {
        aes_set_player_bonus(maxId, aes_get_player_bonus(maxId) + g_AesBonus);
    }
#endif

    get_user_name(maxId, name, charsmax(name));
    num1 = makeNumber(g_PlayerData[maxId][PLAYER_KILLS]);
    num2 = makeNumber(g_PlayerData[maxId][PLAYER_HS]);
    set_hudmessage(0, 255, 255, -1.0, 0.17, 0, .fxtime = 0.0, .holdtime = 5.0, .channel = 4);

    if (g_MoneyBonus > 0)
        len += formatex(message[len], charsmax(message) - len, "^1[^4%d $^1] ", g_MoneyBonus);
#if defined AES_MAX_LEVEL_LENGTH
    if (g_AesExp > 0)
        len += formatex(message[len], charsmax(message) - len, "^1[^4%d EXP^1] ", g_AesExp);
    if (g_AesBonus > 0)
        len += formatex(message[len], charsmax(message) - len, "^1[^4%d BONUS^1] ", g_AesBonus);
#endif
    for (i = 0; i < num; i++) {
        player = players[i];

        if (!CheckBit(g_HudEnabled, player) || is_user_bot(player)) {
            continue;
        }

        if (g_ShowInfo == 1) {
            ShowSyncHudMsg(player, g_HudSync, "%L:%c%s^n%d %L, %d %L %L %d %L",
                player, "BRP_MESSAGE", (g_NameNewLine == 1 ? "^n" : " "), name,
                g_PlayerData[maxId][PLAYER_KILLS], player, g_Titles[0][num1],
                g_PlayerData[maxId][PLAYER_HS], player, g_Titles[1][num2],
                player, "BPR_AND",
                g_PlayerData[maxId][PLAYER_DMG], player, "BPR_DMG"
            );
        } else if (g_ShowInfo == 2) {
            ShowSyncHudMsg(player, g_HudSync, "%L:%c%s",
                player, "BRP_MESSAGE", (g_NameNewLine == 1 ? "^n" : " "), name
            );
        }
#if defined AES_MAX_LEVEL_LENGTH
        if (g_MoneyBonus || g_AesExp || g_AesBonus > 0) {
#else
        if (g_MoneyBonus) {
#endif
            if (player == maxId)
                 client_print_color(player, maxId, "%L %L", player, "BPR_PREFIX", player, "BPR_BONUS", message);
            else if (g_ShowAll == 1)
                client_print_color(player, maxId, "%L %L", player, "BPR_PREFIX", player, "BPR_BONUS_ALL", name, message);
        }
    }
}

stock makeNumber(number) {
    if (4 < (number % 100) < 20) {
        return 2;
    } else if ((number % 10) < 5) {
        return g_Cases[number % 10];
    } else {
        return 2;
    }
}
 
Сообщения
1,175
Реакции
2,144
Помог
57 раз(а)
r1nk0, что вы хотите сделать? Показ в этом куске кода пляшет от квара bpr_show_all. Если 1 - показывает инфу всем, иначе только тому, кто получил. Сама конструкция это цикл по присутствующим игрокам. Индексы помещаются в массив players и затем циклом перебираются от начала до конца, и для каждого игрока гонится этот кусок кода, если предшествующие ему условия позволяют до него добраться.
 
Сообщения
493
Реакции
108
Помог
16 раз(а)
BlackSignature, я хочу что бы только показывало игроку который лучший в раунде.
в описании плагина сказано.

bpr_show_all // Выводить сообщение в чат всем, 1 - включить , 0 - отключить

0 отключить, а не показывать только лучшему.

При 0 получается он так и показывает как мне надо что ли?)
 
Сообщения
1,175
Реакции
2,144
Помог
57 раз(а)
r1nk0, да, всё правильно.
 
Сообщения
9
Реакции
0
Как сделать? чтоб выводило: команде а не всем игрокам
пример с плагина ideal_vip 3.8.9
[VIP] The End, Вы взяли: Deagle
чтоб выводило команде
а то выводит всем.
 

Пользователи, просматривающие эту тему

Сейчас на форуме нет ни одного пользователя.
Сверху Снизу