Приведи следующий код к профессиональному уровню с использованием принципов ООП, сделай архитектуру модульной и расширяемой, добавь инкапсуляцию, абстракцию и наследование там, где это уместно, оптимизируй производительность и читаемость, улучшай именования переменных и функций, убери дублирование, применяй паттерны проектирования, обеспечь обработку ошибок и логирование, добавь комментарии и документацию для основных классов и методов.
lua
Assistant
if CLIENT then
local interactKey = KEY_E
local interactionDistance = 150
local progressMax = 3 -- секунд удержания
local progress = 0
local targetPlayer = nil
local menuOpen = false
local buttons = {
{
label = "Кнопка 1",
func = function() print("Кнопка 1 нажата") end
},
{
label = "Кнопка 2",
func = function() print("Кнопка 2 нажата") end
},
{
label = "Кнопка 3",
func = function() print("Кнопка 3 нажата") end
},
}
local ButtonPositions = {} -- Для хранения параметров кнопок и hovered состояния
local function GetClosestPlayer()
local localPly = LocalPlayer()
local pos = localPly:GetPos()
local closest = nil
local closestDist = interactionDistance
for _, ply in ipairs(player.GetAll()) do
if ply ~= localPly and ply:Alive() then
local dist = pos:Distance(ply:GetPos())
if dist < closestDist then
closest = ply
closestDist = dist
end
end
end
return closest
end
local function ScreenPosFrom3D(pos)
local sp = pos:ToScreen()
return {
x = sp.x,
y = sp.y
}
end
local function DrawProgressBar(pos, ang, fraction)
cam.Start3D2D(pos, ang, 0.05)
surface.SetDrawColor(50, 50, 50, 180)
surface.DrawRect(-50, 0, 100, 10)
surface.SetDrawColor(100, 200, 100, 255)
surface.DrawRect(-50, 0, 100 * fraction, 10)
draw.SimpleText("Взаимодействие...", "DermaDefaultBold", 0, -20, Color(255, 255, 255), TEXT_ALIGN_CENTER)
cam.End3D2D()
end
local function DrawButton(x, y, w, h, label, hovered)
surface.SetDrawColor(hovered and Color(100, 180, 100) or Color(70, 130, 70))
surface.DrawRect(x, y, w, h)
draw.SimpleText(label, "DermaDefaultBold", x + w / 2, y + h / 2, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
local function PointInRect(point, rectX, rectY, w, h)
return point.x >= rectX and point.x <= rectX + w and point.y >= rectY and point.y <= rectY + h
end
hook.Add("Think", "PlayerInteractionThink", function()
local localPly = LocalPlayer()
if not localPly:Alive() then
progress = 0
targetPlayer = nil
menuOpen = false
return
end
if menuOpen then return end
local ply = GetClosestPlayer()
if not ply then
progress = 0
targetPlayer = nil
return
end
if localPly:GetPos():Distance(ply:GetPos()) > interactionDistance then
progress = 0
targetPlayer = nil
return
end
if input.IsKeyDown(interactKey) then
if targetPlayer ~= ply then
targetPlayer = ply
progress = 0
end
progress = math.min(progress + FrameTime(), progressMax)
if progress >= progressMax then menuOpen = true end
else
progress = 0
targetPlayer = nil
end
end)
hook.Add("PostDrawTranslucentRenderables", "DrawInteractionUI3D", function()
if targetPlayer and not menuOpen and IsValid(targetPlayer) then
local pos = targetPlayer:GetPos() + Vector(0, 0, 85)
local ang = Angle(0, EyeAngles().y - 90, 90)
DrawProgressBar(pos, ang, progress / progressMax)
end
end)
hook.Add("PostDrawTranslucentRenderables", "Draw3DMenuWindowAndButtons", function()
if not menuOpen or not IsValid(targetPlayer) then return end
local ply = targetPlayer
-- Позиция поднята выше на 20 единиц по Z относительно предыдущего варианта
local pos = ply:GetPos() + ply:GetUp() * 60 + ply:GetForward() * 10
local ang = EyeAngles()
ang:RotateAroundAxis(ang:Forward(), 90)
ang:RotateAroundAxis(ang:Right(), 90)
local w, h = 250, 220 -- увеличенный размер окна
local padding = 15
local btnW, btnH = w - padding * 2, 60 -- увеличенный размер кнопок
cam.Start3D2D(pos, ang, 0.02)
-- Рисуем фон окна
surface.SetDrawColor(50, 50, 50, 220)
surface.DrawRect(-w / 2, -h / 2, w, h)
local mx, my = input.GetCursorPos()
local mousePos = {
x = mx,
y = my
}
ButtonPositions = {}
for i, btn in ipairs(buttons) do
local x = -w / 2 + padding
local y = -h / 2 + padding + (i - 1) * (btnH + padding)
local btnWorldPos = pos + ang:Right() * (x + btnW / 2) + ang:Up() * (y + btnH / 2)
local screenPos = ScreenPosFrom3D(btnWorldPos)
local hovered = PointInRect(mousePos, screenPos.x - btnW / 2, screenPos.y - btnH / 2, btnW, btnH)
DrawButton(x, y, btnW, btnH, btn.label, hovered)
ButtonPositions[i] = {
func = btn.func,
hovered = hovered
}
end
cam.End3D2D()
end)
hook.Add("GUIMousePressed", "Interaction3DMenuClick", function(mc)
if mc ~= MOUSE_LEFT then return end
if not menuOpen then return end
if not IsValid(targetPlayer) then
menuOpen = false
return
end
for _, btn in ipairs(ButtonPositions) do
if btn.hovered then
btn.func()
menuOpen = false
targetPlayer = nil
progress = 0
return true
end
end
end)
end
lua
if CLIENT then
---@class Logger
---Простой логгер с уровнем логирования
local Logger = {}
Logger.__index = Logger
function Logger.new()
local self = setmetatable({}, Logger)
self.levels = { ERROR = 1, WARN = 2, INFO = 3, DEBUG = 4 }
self.currentLevel = self.levels.DEBUG
return self
end
function Logger:log(levelName, ...)
local level = self.levels[levelName]
if level and level <= self.currentLevel then
MsgC(Color(100, 255, 100), "[" .. levelName .. "] ", Color(255, 255, 255), ...)
MsgN()
end
end
function Logger:error(...) self:log("ERROR", ...) end
function Logger:warn(...) self:log("WARN", ...) end
function Logger:info(...) self:log("INFO", ...) end
function Logger:debug(...) self:log("DEBUG", ...) end
local logger = Logger.new()
---@class Vector2D
---Утилиты для работы с 2D координатами
local Vector2D = {}
Vector2D.__index = Vector2D
---Проверяет, находится ли точка внутри прямоугольника
---@param point table {x:number, y:number}
---@param rectX number
---@param rectY number
---@param width number
---@param height number
---@return boolean
function Vector2D.PointInRect(point, rectX, rectY, width, height)
return point.x >= rectX and point.x <= rectX + width and point.y >= rectY and point.y <= rectY + height
end
---Класс для 3D интерфейса кнопки
local InteractionButton = {}
InteractionButton.__index = InteractionButton
---Создает кнопку для 3D меню
---@param label string Текст на кнопке
---@param callback function Функция для вызова по нажатию
function InteractionButton.new(label, callback)
assert(type(label) == "string", "Label must be a string")
assert(type(callback) == "function", "Callback must be a function")
local self = setmetatable({}, InteractionButton)
self.label = label
self.callback = callback
self.hovered = false
self.position = { x = 0, y = 0 }
self.size = { w = 0, h = 0 }
return self
end
---Отрисовывает кнопку в 3D2D пространстве
---@param x number
---@param y number
---@param w number
---@param h number
---@param hovered boolean
function InteractionButton:draw(x, y, w, h, hovered)
self.hovered = hovered
self.position.x = x
self.position.y = y
self.size.w = w
self.size.h = h
surface.SetDrawColor(hovered and Color(100, 180, 100) or Color(70, 130, 70))
surface.DrawRect(x, y, w, h)
draw.SimpleText(self.label, "DermaDefaultBold", x + w / 2, y + h / 2, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
---Вызывается при нажатии на кнопку (если курсор наведён)
function InteractionButton:click()
local success, err = pcall(self.callback)
if not success then
logger:error("Ошибка в callback кнопки '" .. self.label .. "': " .. tostring(err))
end
end
---Класс для управления взаимодействием с игроками и меню
local InteractionManager = {}
InteractionManager.__index = InteractionManager
---Создает менеджер взаимодействия
---@param interactKey number Клавиша взаимодействия
---@param interactionDistance number Максимальная дистанция взаимодействия
---@param holdTime number Время удержания для открытия меню (сек)
---@param buttons table<InteractionButton> Массив кнопок меню
function InteractionManager.new(interactKey, interactionDistance, holdTime, buttons)
assert(type(interactKey) == "number", "interactKey must be a number")
assert(type(interactionDistance) == "number", "interactionDistance must be a number")
assert(type(holdTime) == "number", "holdTime must be a number")
assert(type(buttons) == "table", "buttons must be a table")
local self = setmetatable({}, InteractionManager)
self.interactKey = interactKey
self.interactionDistance = interactionDistance
self.holdTime = holdTime
self.buttons = buttons or {}
self.progress = 0
self.targetPlayer = nil
self.menuOpen = false
self.buttonPositions = {}
return self
end
---Поиск ближайшего игрока в радиусе взаимодействия
---@return Player|nil
function InteractionManager:getClosestPlayer()
local localPly = LocalPlayer()
if not IsValid(localPly) then return nil end
local pos = localPly:GetPos()
local closest = nil
local closestDist = self.interactionDistance
for _, ply in ipairs(player.GetAll()) do
if ply ~= localPly and ply:Alive() and IsValid(ply) then
local dist = pos:Distance(ply:GetPos())
if dist < closestDist then
closest = ply
closestDist = dist
end
end
end
return closest
end
---Преобразует 3D позицию в экранную для UI взаимодействия с кнопками
---@param pos Vector
---@return table {x:number, y:number}
function InteractionManager:worldToScreen(pos)
local screenPos = pos:ToScreen()
return { x = screenPos.x, y = screenPos.y }
end
---Отрисовывает индикатор прогресса взаимодействия над игроком
---@param pos Vector Позиция для отрисовки
---@param ang Angle Ориентация для 3D2D
---@param fraction number Прогресс от 0 до 1
function InteractionManager:drawProgressBar(pos, ang, fraction)
cam.Start3D2D(pos, ang, 0.05)
surface.SetDrawColor(50, 50, 50, 180)
surface.DrawRect(-50, 0, 100, 10)
surface.SetDrawColor(100, 200, 100, 255)
surface.DrawRect(-50, 0, 100 * fraction, 10)
draw.SimpleText("Взаимодействие...", "DermaDefaultBold", 0, -20, Color(255, 255, 255), TEXT_ALIGN_CENTER)
cam.End3D2D()
end
---Обновляет логику взаимодействия, вызывается каждый кадр "Think"
function InteractionManager:updateThink()
local localPly = LocalPlayer()
if not IsValid(localPly) or not localPly:Alive() then
self:resetInteraction()
return
end
if self.menuOpen then return end
local closest = self:getClosestPlayer()
if not closest then
self:resetInteraction()
return
end
if localPly:GetPos():Distance(closest:GetPos()) > self.interactionDistance then
self:resetInteraction()
return
end
if input.IsKeyDown(self.interactKey) then
if self.targetPlayer ~= closest then
self.targetPlayer = closest
self.progress = 0
logger:debug("Новое взаимодействие с игроком: " .. tostring(self.targetPlayer:Nick()))
end
self.progress = math.min(self.progress + FrameTime(), self.holdTime)
if self.progress >= self.holdTime then
self.menuOpen = true
logger:info("Меню взаимодействия открыто")
end
else
self:resetInteraction()
end
end
---Сбрасывает состояние взаимодействия
function InteractionManager:resetInteraction()
if self.progress > 0 or self.targetPlayer or self.menuOpen then
logger:debug("Сброс состояния взаимодействия")
end
self.progress = 0
self.targetPlayer = nil
self.menuOpen = false
self.buttonPositions = {}
end
---Рисует UI индикатор прогресса над игроком
function InteractionManager:drawInteractionProgress()
if self.targetPlayer and not self.menuOpen and IsValid(self.targetPlayer) then
local pos = self.targetPlayer:GetPos() + Vector(0, 0, 85)
local ang = Angle(0, EyeAngles().y - 90, 90)
self:drawProgressBar(pos, ang, self.progress / self.holdTime)
end
end
---Рисует меню и кнопки в 3D. Обновляет состояние наведения мыши
function InteractionManager:draw3DMenuAndButtons()
if not self.menuOpen or not IsValid(self.targetPlayer) then return end
local ply = self.targetPlayer
local pos = ply:GetPos() + ply:GetUp() * 60 + ply:GetForward() * 10
local ang = EyeAngles()
ang:RotateAroundAxis(ang:Forward(), 90)
ang:RotateAroundAxis(ang:Right(), 90)
local windowWidth, windowHeight = 250, 220
local padding = 15
local btnWidth, btnHeight = windowWidth - padding * 2, 60
cam.Start3D2D(pos, ang, 0.02)
-- Рисуем фон окна
surface.SetDrawColor(50, 50, 50, 220)
surface.DrawRect(-windowWidth / 2, -windowHeight / 2, windowWidth, windowHeight)
local mouseX, mouseY = input.GetCursorPos()
local mousePos = { x = mouseX, y = mouseY }
self.buttonPositions = {}
for i, button in ipairs(self.buttons) do
local x = -windowWidth / 2 + padding
local y = -windowHeight / 2 + padding + (i - 1) * (btnHeight + padding)
local btnWorldPos = pos + ang:Right() * (x + btnWidth / 2) + ang:Up() * (y + btnHeight / 2)
local screenPos = self:worldToScreen(btnWorldPos)
local hovered = Vector2D.PointInRect(mousePos, screenPos.x - btnWidth / 2, screenPos.y - btnHeight / 2, btnWidth, btnHeight)
button:draw(x, y, btnWidth, btnHeight, hovered)
table.insert(self.buttonPositions, { button = button, hovered = hovered })
end
cam.End3D2D()
end
---Обрабатывает нажатия мыши по 3D меню
---@param mouseCode number Код кнопки мыши
---@return boolean Возвращает true, если нажатие обработано
function InteractionManager:onMousePressed(mouseCode)
if mouseCode ~= MOUSE_LEFT then return false end
if not self.menuOpen then return false end
if not IsValid(self.targetPlayer) then
self:resetInteraction()
return true
end
for _, btnEntry in ipairs(self.buttonPositions) do
if btnEntry.hovered then
btnEntry.button:click()
self:resetInteraction()
return true
end
end
return false
end
-- ======================
-- Инициализация кнопок и менеджера
-- ======================
local buttons = {
InteractionButton.new("Кнопка 1", function() logger:info("Кнопка 1 нажата") end),
InteractionButton.new("Кнопка 2", function() logger:info("Кнопка 2 нажата") end),
InteractionButton.new("Кнопка 3", function() logger:info("Кнопка 3 нажата") end),
}
local interactionManager = InteractionManager.new(KEY_E, 150, 3, buttons)
-- ======================
-- Хуки
-- ======================
hook.Add("Think", "PlayerInteractionThink", function()
local ok, err = pcall(function() interactionManager:updateThink() end)
if not ok then logger:error("Ошибка в Think InteractionManager: " .. tostring(err)) end
end)
hook.Add("PostDrawTranslucentRenderables", "DrawInteractionProgressUI3D", function()
local ok, err = pcall(function() interactionManager:drawInteractionProgress() end)
if not ok then logger:error("Ошибка при отрисовке прогресса: " .. tostring(err)) end
end)
hook.Add("PostDrawTranslucentRenderables", "Draw3DInteractionMenu", function()
local ok, err = pcall(function() interactionManager:draw3DMenuAndButtons() end)
if not ok then logger:error("Ошибка при отрисовке меню: " .. tostring(err)) end
end)
hook.Add("GUIMousePressed", "Handle3DInteractionMenuClick", function(mc)
local ok, handled = pcall(function() return interactionManager:onMousePressed(mc) end)
if not ok then
logger:error("Ошибка при обработке клика меню: " .. tostring(handled))
return
end
return handled
end)
end
Объяснение улучшений
Инкапсуляция и модульность:
Весь функционал взаимодействия обернут в классы InteractionManager и InteractionButton.
Добавлен класс Logger, чтобы централизованно логировать события и ошибки.
Вспомогательный класс Vector2D для работы с точками и прямоугольниками.
Абстракция и наследование:
Кнопки являются отдельными объектами с собственным состоянием и логикой.
В критических местах применяется pcall для обработки исключений и логирования.
В колбэках кнопок тоже применяется pcall.
Паттерны проектирования:
Используется паттерн "Команда" — кнопка вызывает колбэк.
Применён паттерн "Менеджер" для централизованного управления состояниями.
Комментарии и документация:
Добавлены docstring-комментарии для классов и ключевых методов.
Простые комментарии для блоков с логикой.
Данный рефакторинг повышает поддерживаемость и расширяемость кода, упрощает тестирование и диагностику.
“Приведи следующий код к профессиональному уровню с использованием принципов ООП, сделай….” Conversation with gpt-4.1-mini-2025-04-14, from the WildChat-4.8M (AI2) dataset. The Chat Archive, 2025. https://thechatarchive.com/c/01m7h42n7t0gntttq8n8dczk01