Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
  • Need help?

    Create a topic in the appropriate section
    Don't write everything in the chat!
  • Take a look at the marketplace

    There you can buy
    everything related to game servers
  • Don't want a ban?

    Please read our rules
    Don't disturb the order!
  • Sell or buy?

    Use services of the guarantor
    We will make your deal safe
  • 0
Sign in to follow this  
SemKa1407

Помощь в создании серверного мода.

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

Скрытый текст

Код написан нейронкой)

class FakeChatNotifier
{
    ref Timer m_Timer;
    ref Timer m_MessageTimer;
    bool m_IsActive;

    // Списки диалогов
    ref array<ref array<string>> m_WelcomeDialogs;
    ref array<ref array<string>> m_RegularDialogs;
    ref array<ref array<string>> m_ThreatDialogs;

    void FakeChatNotifier()
    {
        m_Timer = new Timer();
        m_MessageTimer = new Timer();
        m_IsActive = false;

        // Инициализация диалогов
        InitializeDialogs();
        Print("[FakeChatNotifier] Initialized"); // Лог для проверки инициализации
    }

    void InitializeDialogs()
    {
        // Приветственные диалоги
        m_WelcomeDialogs = new array<ref array<string>>;
        m_WelcomeDialogs.Insert({"Hello!", "How are you?"});
        m_WelcomeDialogs.Insert({"Anyone alive?", "Yes, I am here. What's new?"});
        m_WelcomeDialogs.Insert({"What's the situation?", "It seems quiet, but stay sharp."});

        // Обычные диалоги
        m_RegularDialogs = new array<ref array<string>>;
        m_RegularDialogs.Insert({"Check radio frequency 98.7", "Got it, I'll stay alert."});
        m_RegularDialogs.Insert({"Never trust strangers", "Right, it's every man for himself here."});
        m_RegularDialogs.Insert({"I saw someone near the old factory", "Thanks for the info, I'll check it out."});

        // Угрозы
        m_ThreatDialogs = new array<ref array<string>>;
        m_ThreatDialogs.Insert({"We will find you...", "Try, but I won't give up."});
        m_ThreatDialogs.Insert({"You won't escape", "I'm ready for this."});
        m_ThreatDialogs.Insert({"Your loot will be ours", "You wish."});
    }

    void Start()
    {
        if (!m_IsActive)
        {
            m_IsActive = true;
            m_Timer.Run(60, this, "CheckTime", NULL, true); // Запуск таймера на проверку каждые 60 секунд
            Print("[FakeChatNotifier] Started main timer"); // Лог для проверки запуска
        }
    }

    void Stop()
    {
        m_IsActive = false;
        m_Timer.Stop();
        m_MessageTimer.Stop();
        Print("[FakeChatNotifier] Stopped timers"); // Лог для проверки остановки
    }

    // Функция для получения текущего времени
    void GetCurrentHour(out int hour)
    {
        int year, month, day, minute;
        GetGame().GetWorld().GetDate(year, month, day, hour, minute); // Получаем текущий час из даты
        Print("[FakeChatNotifier] Current hour: " + hour); // Лог для проверки текущего времени
    }

    void CheckTime()
    {
        int hour;
        GetCurrentHour(hour);  // Используем нашу функцию для получения текущего часа

        if (hour >= 22 || hour < 6)
        {
            if (!m_IsActive)
            {
                Print("[FakeChatNotifier] Night time detected, starting dialog cycle"); // Лог для ночного времени
                StartDialogCycle(hour);
            }
        }
        else
        {
            Print("[FakeChatNotifier] Day time, stopping dialogs"); // Лог для дневного времени
            Stop();
        }
    }

    void StartDialogCycle(int hour)
    {
        if (!m_IsActive) return;

        array<string> dialog;

        if (hour >= 22 && hour < 23)
        {
            dialog = m_WelcomeDialogs.GetRandomElement();  // Приветственные диалоги
            Print("[FakeChatNotifier] Sending welcome dialog"); // Лог для приветственных диалогов
        }
        else if (hour >= 23 && hour < 3)
        {
            dialog = m_RegularDialogs.GetRandomElement();  // Обычные диалоги
            Print("[FakeChatNotifier] Sending regular dialog"); // Лог для обычных диалогов
        }
        else if (hour >= 3 && hour < 6)
        {
            dialog = m_ThreatDialogs.GetRandomElement();  // Угрозы
            Print("[FakeChatNotifier] Sending threat dialog"); // Лог для угроз
        }

        SendDialog(dialog);
        ScheduleNextDialog();  // Планирование следующего диалога
    }

    void ScheduleNextDialog()
    {
        int interval = Math.RandomIntInclusive(900, 1500); // Интервал (15-25 минут в секундах)
        m_MessageTimer.Run(interval, this, "StartDialogCycle", NULL, false);
        Print("[FakeChatNotifier] Scheduled next dialog in " + interval + " seconds"); // Лог для планирования следующего диалога
    }

    void SendDialog(array<string> dialog)
    {
        for (int i = 0; i < dialog.Count(); i++)
        {
            float delay = i * Math.RandomIntInclusive(5, 9); // Задержка между сообщениями в диалоге (5-9 секунд)
            m_MessageTimer.Run(delay, this, "SendMessageToPlayers", new Param1<string>(dialog[i]), false);
            Print("[FakeChatNotifier] Scheduled message with delay " + delay + " seconds: " + dialog[i]); // Лог для отправки сообщения
        }
    }

    void SendMessageToPlayers(Param1<string> param)
    {
        string message = param.param1;
        array<Man> players = new array<Man>;
        GetGame().GetPlayers(players);

        if (players.Count() > 0)
        {
            foreach (Man player : players)
            {
                Param1<string> globalMessage = new Param1<string>(message);
                GetGame().RPCSingleParam(player, ERPCs.RPC_USER_ACTION_MESSAGE, globalMessage, true, player.GetIdentity());
            }
            Print("[FakeChatNotifier] Sent message to all players: " + message); // Лог для отправленного сообщения
        }
        else
        {
            Print("[FakeChatNotifier] No players online to send message: " + message); // Лог для случая, если нет игроков
        }
    }
}

 

Share this post


Link to post
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • By Troy1
      Всем привет. пишу мод и столкнулся с проблемой в реализации.
      Суть: Пытаюсь сделать проверку, если игрок стоит прям у окна или у дверного проёма он должен получать урон.
      Делал вот так.
      int wallHits = 0; float d = 2.2; // Дистанция до стены. Если стена дальше — считаем, что там окно или проем. // 8 направлений "снежинкой" для проверки стен вокруг игрока // Используем Vector(x, y, z) для точности ref array<vector> checkDirs = { Vector(d,0,0), Vector(-d,0,0), Vector(0,0,d), Vector(0,0,-d), Vector(d,0,d), Vector(-d,0,-d), Vector(d,0,-d), Vector(-d,0,d) }; foreach (vector dir : checkDirs) { // Пускаем горизонтальные лучи от позиции игрока (from) if (DayZPhysics.RayCastBullet(from, from + dir, collisionLayerMask, this, hitObject, hitPosition, hitNormal, hitFraction)) { // ПРОВЕРКА: Это должна быть вертикальная стена (Y нормали < 0.5) // Чтобы не засчитать низкий потолок за стену if (Math.AbsFloat(hitNormal[1]) < 0.5) { wallHits++; } } } // УСЛОВИЕ БЕЗОПАСНОСТИ: // В комнате wallHits будет 6-8. У окна или в проеме — 1-4. if (wallHits < 5) { hasSafeCeiling = false; // Слишком открытое пространство (окно/дверь) } Пытался менять дистанции, но всё ровно не как не хочет работать.
      Что я делаю не так, или я вообще делаю не то?
      Мне нужно проверять игрока, в укрытии он или нет.
      С высотой я разобрался, а вот с боковыми лучами у меня траблы и не во всех помещениях работает как нужно.
      В некоторых помещениях вообще не работает, удаляешь строки проверки, начинает работать и то по высоте.
      Просто забегаешь по навес и игрок под защитой, так не должно быть.
      Помогите пожалуйста  решить задачу.
    • By Troy1
      Всем привет. Суть в чём, пишу мод на событие и когда происходит событие, параллельно должна меняться скорость ветра, не могу понять как заставить скрипт управлять силой ветра. Понижать силу ветра получилось сделать, а вот повышать не как. Только после перезагрузки сервера сила ветра задаётся в нужном значение.
      Как сделать, что бы по вызову функции менялась сила ветра в большую или в меньшую сторону?
      protected void SetWind(float wind, float time) { if (!g_Game) return; Weather m_Weather = g_Game.GetWeather(); if (!m_Weather) return; m_Weather.SetWindMaximumSpeed(wind); m_Weather.SetWind(Vector(1/Math.Sqrt(3), 1/Math.Sqrt(3), 1/Math.Sqrt(3)) * wind); m_Weather.SetWindSpeed(wind); m_Weather.SetWindFunctionParams(1.0, 1.0, -1); } Это скрипт на понижение силы ветра.
      Работает понижение силы ветра в том случае, если до этого сила ветра была выше.
      Пример:
      Изначально на сервере сила ветра = 20 m/s А нужно понизить до 10 m/s
      Только в этом случае сработает скрипт который я приложил выше.
      Помогите пожалуйста решить этот вопрос.
      За ранние благодарю.
    • By Troy1
      Пока ждал помощи, решил вопрос!
      Тема закрыта!!!
    • By -Reks-
      Продам сервер по DayZ/ Есть 
      Пожалуйста, Войдите или Зарегистрируйтесь, чтобы увидеть это: Вложение.
  • Our picks

×
×
  • Create New...

Important Information

By using this site, you automaticly agree to our Guidelines and Privacy Policy.
We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.

Поддержка