-- server.lua
-- Таблица игроков с их данными
local playerData = {}
-- Обработка начала работы
RegisterServerEvent("PizzaDelivery:StartJob")
AddEventHandler("PizzaDelivery:StartJob", function()
local sourcePlayer = source
if playerData[sourcePlayer] and playerData[sourcePlayer].isWorking then
triggerClientEvent(sourcePlayer, "PizzaDelivery:ShowNotification", sourcePlayer, "Вы уже работаете!")
return
end
-- Создание мопеда
local moped = createVehicle(426, PizzaDeliveryConfig.JobStartMarker.x, PizzaDeliveryConfig.JobStartMarker.y, PizzaDeliveryConfig.JobStartMarker.z)
if moped then
setElementLocked(moped, true)
setElementData(moped, "owner", getPlayerName(sourcePlayer))
setElementData(moped, "jobVehicle", true) -- Метка, что это рабочее транспортное средство
warpPedIntoVehicle(sourcePlayer, moped)
-- Запись данных игрока
playerData[sourcePlayer] = {
isWorking = true,
vehicle = moped,
deliveries = 0,
money = 0,
currentDelivery = nil
}
-- Отправка подтверждения клиенту
triggerClientEvent(sourcePlayer, "PizzaDelivery:JobStarted", sourcePlayer)
else
triggerClientEvent(sourcePlayer, "PizzaDelivery:ShowNotification", sourcePlayer, "Не удалось создать мопед.")
end
end)
-- Обработка получения денег
RegisterServerEvent("PizzaDelivery:GiveMoney")
AddEventHandler("PizzaDelivery:GiveMoney", function(amount)
local sourcePlayer = source
if playerData[sourcePlayer] and playerData[sourcePlayer].isWorking then
playerData[sourcePlayer].money = playerData[sourcePlayer].money + amount
-- Здесь можно интегрировать систему банков или экономики вашего сервера
triggerClientEvent(sourcePlayer, "PizzaDelivery:UpdateMoney", sourcePlayer, playerData[sourcePlayer].money)
end
end)
-- Обработка повышения количества доставок
RegisterServerEvent("PizzaDelivery:IncrementDelivery")
AddEventHandler("PizzaDelivery:IncrementDelivery", function()
local sourcePlayer = source
if playerData[sourcePlayer] and playerData[sourcePlayer].isWorking then
playerData[sourcePlayer].deliveries = playerData[sourcePlayer].deliveries + 1
triggerClientEvent(sourcePlayer, "PizzaDelivery:UpdateDeliveries", sourcePlayer, playerData[sourcePlayer].deliveries)
end
end)
-- Обработка завершения работы
RegisterServerEvent("PizzaDelivery:StopJob")
AddEventHandler("PizzaDelivery:StopJob", function()
local sourcePlayer = source
if playerData[sourcePlayer] and playerData[sourcePlayer].isWorking then
destroyElement(playerData[sourcePlayer].vehicle)
playerData[sourcePlayer] = nil
triggerClientEvent(sourcePlayer, "PizzaDelivery:JobStopped", sourcePlayer)
end
end)
-- Проверка использования рабочего мопеда
addCommandHandler("checkmoped", function(player)
if playerData[player] and playerData[player].isWorking then
local veh = getPedOccupiedVehicle(player)
if veh then
if getElementData(veh, "jobVehicle") and getElementData(veh, "owner") == getPlayerName(player) then
outputChatBox("Это ваш рабочий мопед.", player, 0, 255, 0)
else
outputChatBox("Это не ваш рабочий мопед.", player, 255, 0, 0)
end
else
outputChatBox("Вы не находитесь в транспортном средстве.", player, 255, 255, 0)
end
else
outputChatBox("Вы не работаете развозчиком пиццы.", player, 255, 0, 0)
end
end)
-- client.lua
-- Загрузка конфигурации
local startMarker = createMarker(PizzaDeliveryConfig.JobStartMarker.x, PizzaDeliveryConfig.JobStartMarker.y, PizzaDeliveryConfig.JobStartMarker.z - 1, "cylinder", 1.5, 0, 255, 0, 150)
local pickupMarker = createMarker(PizzaDeliveryConfig.PizzaPickupMarker.x, PizzaDeliveryConfig.PizzaPickupMarker.y, PizzaDeliveryConfig.PizzaPickupMarker.z - 1, "cylinder", 1.5, 255, 165, 0, 150)
local guiTimer = nil
local deliveryTimer = nil
local returnTimer = nil
local hasPizza = false
local pizzaObject = nil
local currentDelivery = nil
local deliveryDeadline = 0
local isOnDelivery = false
local tipAmount = 0
-- Таблицы фраз
local successPhrases = PizzaDeliveryConfig.SuccessPhrases
local latePhrases = PizzaDeliveryConfig.LatePhrases
-- UI элементы
function showTimer(seconds)
-- Здесь можно использовать dxDraw для отображения таймера
-- Для простоты используем вывод в чат
addEventHandler("onClientRender", root, function()
local timeLeft = math.max(0, math.floor(deliveryDeadline - getTickCount()/1000))
dxDrawText("Время на доставку: " .. timeLeft .. " секунд", 10, 10, _, _, tocolor(255,255,255,255), 1.0, "default-bold")
end)
end
function hideTimer()
removeEventHandler("onClientRender", root, nil)
end
-- Функция отображения уведомлений
function showNotification(message)
exports['my_custom_notification']:show(message) -- Предполагается, что есть ресурс для кастомных уведомлений
end
-- Обработка входа в маркер начала работы
addEventHandler("onClientMarkerHit", startMarker, function(hitPlayer, matchingDimension)
if hitPlayer ~= localPlayer then return end
if isPedInVehicle(localPlayer) then
showNotification("Выйдите из транспортного средства, чтобы приступить к работе.")
return
end
showNotification("Нажмите E, чтобы принять работу.")
bindKey("e", "down", function()
triggerServerEvent("PizzaDelivery:StartJob", localPlayer)
unbindKey("e", "down")
end)
end)
-- Обработка начала работы
addEvent("PizzaDelivery:JobStarted", true)
addEventHandler("PizzaDelivery:JobStarted", root, function()
showNotification("Работа начата! Ваш мопед выдан.")
end)
-- Обработка окончания работы
addEvent("PizzaDelivery:JobStopped", true)
addEventHandler("PizzaDelivery:JobStopped", root, function()
showNotification("Вы уволены. Ваш мопед удален.")
end)
-- Обработка входа в маркер взятия пиццы
addEventHandler("onClientMarkerHit", pickupMarker, function(hitPlayer, matchingDimension)
if hitPlayer ~= localPlayer then return end
if not isPedInVehicle(localPlayer) then
showNotification("Нажмите E, чтобы взять пиццу.")
bindKey("e", "down", takePizza)
else
showNotification("Вы должны быть вне транспортного средства, чтобы взять пиццу.")
end
end)
-- Функция взятия пиццы
function takePizza()
unbindKey("e", "down")
if hasPizza then
showNotification("У вас уже есть пицца.")
return
end
-- Проигрывание анимации
triggerServerEvent("PizzaDelivery:PlayAnimation", localPlayer, "take_pizza")
-- Выбор случайной пиццы
local pizza = PizzaDeliveryConfig.Pizzas[math.random(#PizzaDeliveryConfig.Pizzas)]
showNotification("Вы взяли пиццу: " .. pizza.name .. " за $" .. pizza.price)
-- Создание объекта пиццы и прикрепление к игроку
pizzaObject = createObject(1234, 0, 0, 0) -- 1234 замените на ID модели пиццы
if pizzaObject then
attachElements(pizzaObject, localPlayer, 0.5, 0.2, 1.0) -- Настройте положение пиццы относительно игрока
hasPizza = true
end
-- Сохранение текущей пиццы
triggerServerEvent("PizzaDelivery:SelectPizza", localPlayer, pizza.price)
end
-- Обработка нажатия E для положить пиццу в мопед
function placePizzaInMoped()
if not hasPizza then return end
local veh = getPedOccupiedVehicle(localPlayer)
if not veh then
showNotification("Вы должны быть в мопеде, чтобы положить пиццу.")
return
end
if not getElementData(veh, "jobVehicle") or getElementData(veh, "owner") ~= getPlayerName(localPlayer) then
showNotification("Вы должны использовать свой рабочий мопед.")
return
end
-- Проигрывание анимации
triggerServerEvent("PizzaDelivery:PlayAnimation", localPlayer, "place_pizza")
-- Удаление объекта пиццы
if isElement(pizzaObject) then
destroyElement(pizzaObject)
pizzaObject = nil
end
hasPizza = false
showNotification("Пицца положена в мопед.")
-- Назначение доставки
assignDelivery()
end
-- Функция назначения доставки
function assignDelivery()
local delivery = PizzaDeliveryConfig.DeliveryPoints[math.random(#PizzaDeliveryConfig.DeliveryPoints)]
currentDelivery = delivery
-- Создание маркера доставки
local deliveryMarker = createMarker(delivery.delivery.x, delivery.delivery.y, delivery.delivery.z -1, "checkpoint", 2.0, 0, 0, 255, 150)
addEventHandler("onClientMarkerHit", deliveryMarker, onDeliveryMarkerHit)
-- Установка таймера
deliveryDeadline = getTickCount()/1000 + PizzaDeliveryConfig.PickupTimer
showTimer(PizzaDeliveryConfig.PickupTimer)
-- Отправка данных серверу при необходимости
end
-- Обработка входа в маркер доставки
function onDeliveryMarkerHit(hitPlayer, matchingDimension)
if hitPlayer ~= localPlayer then return end
if not isOnDelivery then
isOnDelivery = true
showNotification("Нажмите E, чтобы завершить доставку.")
bindKey("e", "down", completeDelivery)
end
end
-- Функция завершения доставки
function completeDelivery()
unbindKey("e", "down")
if not isOnDelivery then return end
-- Проверка времени
local currentTime = getTickCount()/1000
local onTime = currentTime <= deliveryDeadline
if onTime then
showNotification("Доставка выполнена вовремя!")
-- Выбор случайной фразы
local phrase = successPhrases[math.random(#successPhrases)]
showNotification(phrase)
-- Шанс чаевых
if math.random(100) <= PizzaDeliveryConfig.TipChance then
tipAmount = math.random(PizzaDeliveryConfig.TipRange.min, PizzaDeliveryConfig.TipRange.max)
showNotification("Вы получили чаевые: $" .. tipAmount)
triggerServerEvent("PizzaDelivery:GiveMoney", localPlayer, tipAmount)
else
tipAmount = 0
end
-- Плата за доставку
triggerServerEvent("PizzaDelivery:GiveMoney", localPlayer, PizzaDeliveryConfig.Pizzas[math.random(#PizzaDeliveryConfig.Pizzas)].price)
else
showNotification("Вы опоздали с доставкой.")
-- Выбор случайной фразы
local phrase = latePhrases[math.random(#latePhrases)]
showNotification(phrase)
-- Плата за доставку в 50%
local halfPrice = math.floor(PizzaDeliveryConfig.Pizzas[math.random(#PizzaDeliveryConfig.Pizzas)].price / 2)
triggerServerEvent("PizzaDelivery:GiveMoney", localPlayer, halfPrice)
end
-- Проигрывание анимации педа (предполагается, что NPC существует и синхронизирован)
triggerServerEvent("PizzaDelivery:PedAnimation", localPlayer)
-- Увеличение счетчика доставок
triggerServerEvent("PizzaDelivery:IncrementDelivery", localPlayer)
-- Удаление маркера доставки
-- Предполагается, что у нас есть способ идентифицировать маркер, например, сохранить его в currentDeliveryMarker
-- Сброс состояний
isOnDelivery = false
currentDelivery = nil
hideTimer()
-- Проверка на максимальное количество доставок
-- Логика может быть добавлена на сервере
-- Начало таймера возврата
returnTimer = getTickCount()/1000 + PizzaDeliveryConfig.ReturnTimer
showNotification("Вернитесь к мопеду в течение 30 секунд.")
setTimer(checkReturnToMoped, PizzaDeliveryConfig.ReturnTimer * 1000, 1)
end
-- Проверка возврата к мопеду
function checkReturnToMoped()
local veh = getPedOccupiedVehicle(localPlayer)
if veh and getElementData(veh, "jobVehicle") and getElementData(veh, "owner") == getPlayerName(localPlayer) then
showNotification("Вы вернулись к мопеду.")
-- Назначение следующей доставки или возврат на базу
else
showNotification("Вы не вернулись к мопеду вовремя. Работа завершена.")
triggerServerEvent("PizzaDelivery:StopJob", localPlayer)
end
end
-- Обработка взаимодействия с задней частью мопеда
addEventHandler("onClientVehicleEnter", root, function(theVehicle, seat, jacked)
if theVehicle ~= playerData.vehicle then return end
if seat ~= 0 then return end -- Сидение за водительским местом
showNotification("Нажмите E, чтобы взаимодействовать с мопедом.")
bindKey("e", "down", placePizzaInMoped)
end)
-- Обработка синхронизации данных от сервера
addEvent("PizzaDelivery:ShowNotification", true)
addEventHandler("PizzaDelivery:ShowNotification", root, function(message)
showNotification(message)
end)
addEvent("PizzaDelivery:UpdateMoney", true)
addEventHandler("PizzaDelivery:UpdateMoney", root, function(amount)
-- Обновление UI для отображения денег
showNotification("Ваш баланс: $" .. amount)
end)
addEvent("PizzaDelivery:UpdateDeliveries", true)
addEventHandler("PizzaDelivery:UpdateDeliveries", root, function(count)
-- Обновление UI для отображения количества доставок
showNotification("Доставок выполнено: " .. count)
end)
-- Инициализация UI
function initUI()
-- Здесь можно создать элементы интерфейса с использованием dxDraw или GUI
end
addEventHandler("onClientResourceStart", resourceRoot, function()
initUI()
end)