Professionally optimize code, improve code, reduce the number of lines, structure code, format code, remove unnecessary calculations or condition checks.
lua
Assistant
local ev = require("lib.samp.events")
local imgui = require('mimgui')
local encoding = require('encoding')
encoding.default = 'CP1251'
local u8 = encoding.UTF8
local new = imgui.new
local startTime = os.time();
local statusBar = ''
local status = {
['len'] = 0,
['cotton'] = 0,
['total'] = 0,
['circle'] = 0
}
local sc = {
menu = new.bool(),
status = new.bool(),
active_bot = new.bool(),
pause_bot = new.bool(),
collection = new.int(3),
circle_status = new.int(1),
circle_len = new.int(0),
circle_cotton = new.int(0),
circle_route = new.int(10)
}
local menu = imgui.OnFrame(
function() return sc.menu[0] end,
function(player)
if sc.circle_route[0] < 1 or sc.circle_len[0] < 1 or sc.circle_cotton[0] < 1 then
sc.circle_route[0] = 1; sc.circle_len[0] = 1; sc.circle_cotton[0] = 1;
end
local sizeX, sizeY = getScreenResolution()
imgui.SetNextWindowPos(imgui.ImVec2(sizeX / 2, sizeY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
imgui.SetNextWindowSize(imgui.ImVec2(300, 318), imgui.Cond.FirstUseEver)
imgui.Begin(u8"Linen & Cotton", sc.menu, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
imgui.PushFont(font16)
imgui.CenterTextColoredRGB('Что собирать боту?')
if sc.collection[0] == 1 then
if imgui.AnimButton(u8'Лён', imgui.ImVec2(-1, 24)) then
sc.collection[0] = 2
end
elseif sc.collection[0] == 2 then
if imgui.AnimButton(u8'Хлопок', imgui.ImVec2(-1, 24)) then
sc.collection[0] = 3
end
elseif sc.collection[0] == 3 then
if imgui.AnimButton(u8'Лён и Хлопок', imgui.ImVec2(-1, 24)) then
sc.collection[0] = 1
end
end
imgui.CenterTextColoredRGB('Тип кругов и количество кругов')
imgui.PushItemWidth(-1)
if sc.circle_status[0] == 1 then
if imgui.AnimButton(u8'Количество кругов', imgui.ImVec2(-1, 24)) then
sc.circle_status[0] = 2
end
imgui.InputInt(u8'##circle1', sc.circle_route, 1, 1)
elseif sc.circle_status[0] == 2 then
if imgui.AnimButton(u8'Количество льна', imgui.ImVec2(-1, 24)) then
sc.circle_status[0] = 3
end
imgui.InputInt(u8'##circle2', sc.circle_len, 1, 1)
elseif sc.circle_status[0] == 3 then
if imgui.AnimButton(u8'Количество хлопка', imgui.ImVec2(-1, 24)) then
sc.circle_status[0] = 1
end
imgui.InputInt(u8'##circle3', sc.circle_cotton, 1, 1)
end
imgui.PopItemWidth()
imgui.NewLine()
if not sc.active_bot[0] then
if imgui.AnimButton(u8'Запустить бота', imgui.ImVec2(-1, 24)) then
sc.active_bot[0] = true; sc.status[0] = true;
startTime = os.time()
msg('Бот начал роботу.')
end
else
if imgui.AnimButton(u8'Остановить бота', imgui.ImVec2(-1, 24)) then
sc.active_bot[0] = false; sc.status[0] = false
msg('Бот остановлен.')
end
end
imgui.BeginChild(u8'##authours', imgui.ImVec2(-1, 70), true)
imgui.CenterTextColoredRGB('Автор бота: Scar')
imgui.CenterTextColoredRGB('Fix bot by Lirik')
imgui.EndChild()
imgui.PopFont()
imgui.End()
end
)
local statusMenu = imgui.OnFrame(
function() return sc.status[0] end,
function(player)
local sizeX, sizeY = getScreenResolution()
imgui.SetNextWindowPos(imgui.ImVec2((sizeX / 2) + 300, sizeY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
imgui.SetNextWindowSize(imgui.ImVec2(200, 200), imgui.Cond.FirstUseEver)
player.HideCursor = true
imgui.Begin(u8"##status", sc.menu, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoTitleBar)
imgui.PushFont(font16)
imgui.CenterTextColoredRGB('Статистика')
imgui.Separator()
if sc.circle_status[0] == 1 then
imgui.CenterTextColoredRGB('Пройдено кругов: '..status['circle']..' из '..sc.circle_route[0])
imgui.CenterTextColoredRGB('Количество льна: '..status['len'])
imgui.CenterTextColoredRGB('Количество хлопка: '..status['cotton'])
imgui.CenterTextColoredRGB('Общее количество: '..status['total'])
elseif sc.circle_status[0] == 2 then
imgui.CenterTextColoredRGB('Собрано льна: '..status['len']..' из '..sc.circle_len[0])
imgui.CenterTextColoredRGB('Количество льна: '..status['len'])
imgui.CenterTextColoredRGB('Количество хлопка: '..status['cotton'])
imgui.CenterTextColoredRGB('Общее количество: '..status['total'])
elseif sc.circle_status[0] == 3 then
imgui.CenterTextColoredRGB('Собрано хлопка: '..status['cotton']..' из '..sc.circle_cotton[0])
imgui.CenterTextColoredRGB('Количество льна: '..status['len'])
imgui.CenterTextColoredRGB('Количество хлопка: '..status['cotton'])
imgui.CenterTextColoredRGB('Общее количество: '..status['total'])
end
imgui.Separator()
imgui.CenterTextColoredRGB('Статус бота: '..statusBar)
imgui.Separator()
imgui.CenterTextColoredRGB('Прошло время: '..TimeWork(os.time() - startTime))
imgui.PopFont()
imgui.End()
end
)
local function getNearGardenBed()
local near = {distance = 999, id, position = {}};
for text3D = 1, 2048 do
if sampIs3dTextDefined(text3D) then
local text, color, posX, posY, posZ, distance, ignoreWalls, playerId, vehicleId = sampGet3dTextInfoById(text3D)
local pos = {getCharCoordinates(PLAYER_PED)}
local dist = getDistanceBetweenCoords3d(pos[1], pos[2], pos[3], posX, posY, posZ)
if (string.find(text, "Для сбора урожая")) then
if (string.find(text, 'Лён') and sc.collection[0] == 1) then
if (near.distance > dist) then
near.id = text3D;
near.distance = dist;
near.position = {x = posX, y = posY, z = posZ};
end
elseif (string.find(text, 'Хлопок') and sc.collection[0] == 2) then
if (near.distance > dist) then
near.id = text3D;
near.distance = dist;
near.position = {x = posX, y = posY, z = posZ};
end
elseif (string.find(text, 'Для сбора урожая') and sc.collection[0] == 3) then
if (near.distance > dist) then
near.id = text3D;
near.distance = dist;
near.position = {x = posX, y = posY, z = posZ};
end
end
end
end
end
return near;
end
function main()
repeat wait(0) until isSampAvailable()
sampRegisterChatCommand('ferma', function() sc.menu[0] = not sc.menu[0] end)
while true do wait(0)
if not sc.active_bot[0] then
status['len'] = 0; status['cotton'] = 0; status['total'] = 0; status['circle'] = 0; sc.status[0] = false;
end
if sc.active_bot[0] then
if sc.circle_status[0] == 1 and status['circle'] == sc.circle_route[0] then
sc.active_bot[0] = false
msg('Бот выключен, пройдено '..status['circle']..' из '..sc.circle_route[0]..' кругов.')
elseif sc.circle_status[0] == 2 and status['len'] == sc.circle_len[0] then
sc.active_bot[0] = false
msg('Бот выключен, собрано льна '..status['len']..' из '..sc.circle_len[0]..' кругов.')
elseif sc.circle_status[0] == 3 and status['cotton'] == sc.circle_cotton[0] then
sc.active_bot[0] = false
msg('Бот выключен, собрано хлопка '..status['cotton']..' из '..sc.circle_cotton[0]..' кругов.')
end
local garden_bed = getNearGardenBed();
if (garden_bed.distance ~= 999) then
runToPoint(garden_bed.position.x, garden_bed.position.y, garden_bed.position.z, {sprint = true, jump = true});
setGameKeyState(21, 255);
wait(100);
sampForceOnfootSync();
else
statusBar = 'Ожидание куста'
end
end
end
end
function runToPoint(x, y, z, config)
config = config or {};
while (sc.active_bot[0] and not locateCharAnyMeans2d(PLAYER_PED, x, y, config["radius"] or 2, config["radius"] or 2)) do
setAngle(x, y); wait(0);
setGameKeyState(1, -255)
statusBar = 'Бегу к кусту'
lua_thread.create(function()
drawRoute(x, y, z)
Draw3DCircle(x, y, z, 4, 0xFF37ff57)
end)
local pX, pY, pZ = getCharCoordinates(PLAYER_PED)
local distance = getDistanceBetweenCoords3d(x, y, z, pX, pY, pZ);
if (config["sprint"] and distance > 2) then
setGameKeyState(16, 255)
end
if (config["jump"]) then
local rand = math.random(0, 9999999);
if rand >= 9909999 then
setGameKeyState(16, 0);
setGameKeyState(14, 255);
end
end
if distance < (config['radius'] or 3) then
status['circle'] = status['circle'] + 1
statusBar = 'Собираю куст'
break
end
end
end
function setAngle(X, Y)
local cX, cY, cZ = getActiveCameraCoordinates()
setCameraPositionUnfixed(0.0, (getHeadingFromVector2d(X - cX, Y - cY) - 90.0) / 57.2957795)
end
function drawRoute(coordX, coordY, coorZ)
if isPointOnScreen(coordX, coordY, coorZ, 9999) then
local x1, y1 = convert3DCoordsToScreen(getCharCoordinates(1))
local x2, y2 = convert3DCoordsToScreen(coordX, coordY, coorZ)
renderDrawPolygon(x1, y1, 8, 8, 16, 0.0, 0xFFe80074)
renderDrawLine(x1, y1, x2, y2, 3, 0xFF00c9c6)
renderDrawPolygon(x2, y2, 8, 8, 16, 0.0, 0xFFe80074)
end
end
function Draw3DCircle(x, y, z, radius, color) -- by MrCreepTon
local screen_x_line_old, screen_y_line_old;
for rot=0, 360 do
local rot_temp = math.rad(rot)
local lineX, lineY, lineZ = radius * math.cos(rot_temp) + x, radius * math.sin(rot_temp) + y, z
local screen_x_line, screen_y_line = convert3DCoordsToScreen(lineX, lineY, lineZ)
if screen_x_line ~=nil and screen_x_line_old ~= nil and isPointOnScreen(lineX, lineY, lineZ, 1) then renderDrawLine(screen_x_line, screen_y_line, screen_x_line_old, screen_y_line_old, 3, color) end
screen_x_line_old, screen_y_line_old = screen_x_line, screen_y_line
end
end
function ev.onDisplayGameText(style, time, text)
if sc.active_bot[0] then
if text:find('linen %+ %d+') then
status['len'] = status['len'] + text:match('linen %+ (%d+)')
status['total'] = status['total'] + 1
elseif text:find('cotton %+ %d+') then
status['cotton'] = status['cotton'] + text:match('cotton %+ (%d+)')
status['total'] = status['total'] + 1
end
end
end
function themeOne() -- theme by Chapo
imgui.SwitchContext()
local style = imgui.GetStyle()
local colors = style.Colors
local clr = imgui.Col
local ImVec4 = imgui.ImVec4
local ImVec2 = imgui.ImVec2
colors[clr.Text] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[clr.TextDisabled] = ImVec4(0.28, 0.30, 0.35, 1.00)
colors[clr.WindowBg] = ImVec4(0.16, 0.18, 0.22, 1.00)
colors[clr.ChildBg] = ImVec4(0.19, 0.22, 0.26, 1.00)
colors[clr.PopupBg] = ImVec4(0.05, 0.05, 0.10, 1.00)
colors[clr.Border] = ImVec4(0.41, 0.55, 0.78, 1.00)
colors[clr.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.FrameBg] = ImVec4(0.19, 0.22, 0.26, 1.00)
colors[clr.FrameBgHovered] = ImVec4(0.22, 0.25, 0.30, 1.00)
colors[clr.FrameBgActive] = ImVec4(0.22, 0.25, 0.29, 1.00)
colors[clr.TitleBg] = ImVec4(0.19, 0.22, 0.26, 1.00)
colors[clr.TitleBgActive] = ImVec4(0.19, 0.22, 0.26, 1.00)
colors[clr.TitleBgCollapsed] = ImVec4(0.19, 0.22, 0.26, 0.59)
colors[clr.MenuBarBg] = ImVec4(0.19, 0.22, 0.26, 1.00)
colors[clr.ScrollbarBg] = ImVec4(0.20, 0.25, 0.30, 0.60)
colors[clr.ScrollbarGrab] = ImVec4(0.41, 0.55, 0.78, 1.00)
colors[clr.ScrollbarGrabHovered] = ImVec4(0.49, 0.63, 0.86, 1.00)
colors[clr.ScrollbarGrabActive] = ImVec4(0.49, 0.63, 0.86, 1.00)
colors[clr.CheckMark] = ImVec4(0.90, 0.90, 0.90, 0.50)
colors[clr.SliderGrab] = ImVec4(1.00, 1.00, 1.00, 0.30)
colors[clr.SliderGrabActive] = ImVec4(0.80, 0.50, 0.50, 1.00)
colors[clr.Button] = ImVec4(0.41, 0.55, 0.78, 1.00)
colors[clr.ButtonHovered] = ImVec4(0.49, 0.62, 0.85, 1.00)
colors[clr.ButtonActive] = ImVec4(0.49, 0.62, 0.85, 1.00)
colors[clr.Header] = ImVec4(0.19, 0.22, 0.26, 1.00)
colors[clr.HeaderHovered] = ImVec4(0.22, 0.24, 0.28, 1.00)
colors[clr.HeaderActive] = ImVec4(0.22, 0.24, 0.28, 1.00)
colors[clr.Separator] = ImVec4(0.41, 0.55, 0.78, 1.00)
colors[clr.SeparatorHovered] = ImVec4(0.41, 0.55, 0.78, 1.00)
colors[clr.SeparatorActive] = ImVec4(0.41, 0.55, 0.78, 1.00)
colors[clr.ResizeGrip] = ImVec4(0.05, 0.05, 0.10, 0.90)
colors[clr.ResizeGripHovered] = ImVec4(0.05, 0.05, 0.10, 0.90)
colors[clr.ResizeGripActive] = ImVec4(0.05, 0.05, 0.10, 0.90)
colors[clr.PlotLines] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[clr.PlotLinesHovered] = ImVec4(0.90, 0.70, 0.00, 1.00)
colors[clr.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00)
colors[clr.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00)
colors[clr.TextSelectedBg] = ImVec4(0.41, 0.55, 0.78, 1.00)
end
function msg(text)
sampAddChatMessage("{2FEE00}[Len]: {EAEAEA}"..text)
end
function TimeWork(seconds)
local seconds = tonumber(seconds)
if seconds <= 0 then
return "00:00:00";
else
hours = string.format("%02.f", math.floor(seconds/3600));
mins = string.format("%02.f", math.floor(seconds/60 - (hours*60)));
secs = string.format("%02.f", math.floor(seconds - hours*3600 - mins *60));
return hours..":"..mins..":"..secs
end
end
function imgui.CenterTextColoredRGB(text)
local width = imgui.GetWindowWidth()
local style = imgui.GetStyle()
local colors = style.Colors
local ImVec4 = imgui.ImVec4
local explode_argb = function(argb)
local a = bit.band(bit.rshift(argb, 24), 0xFF)
local r = bit.band(bit.rshift(argb, 16), 0xFF)
local g = bit.band(bit.rshift(argb, 8), 0xFF)
local b = bit.band(argb, 0xFF)
return a, r, g, b
end
local getcolor = function(color)
if color:sub(1, 6):upper() == 'SSSSSS' then
local r, g, b = colors[1].x, colors[1].y, colors[1].z
local a = tonumber(color:sub(7, 8), 16) or colors[1].w * 255
return ImVec4(r, g, b, a / 255)
end
local color = type(color) == 'string' and tonumber(color, 16) or color
if type(color) ~= 'number' then return end
local r, g, b, a = explode_argb(color)
return imgui.ImColor(r, g, b, a):GetVec4()
end
local render_text = function(text_)
for w in text_:gmatch('[^\r\n]+') do
local textsize = w:gsub('{.-}', '')
local text_width = imgui.CalcTextSize(u8(textsize))
imgui.SetCursorPosX( width / 2 - text_width .x / 2 )
local text, colors_, m = {}, {}, 1
w = w:gsub('{(......)}', '{%1FF}')
while w:find('{........}') do
local n, k = w:find('{........}')
local color = getcolor(w:sub(n + 1, k - 1))
if color then
text[#text], text[#text + 1] = w:sub(m, n - 1), w:sub(k + 1, #w)
colors_[#colors_ + 1] = color
m = n
end
w = w:sub(1, n - 1) .. w:sub(k + 1, #w)
end
if text[0] then
for i = 0, #text do
imgui.TextColored(colors_[i] or colors[1], u8(text[i]))
imgui.SameLine(nil, 0)
end
imgui.NewLine()
else
imgui.Text(u8(w))
end
end
end
render_text(text)
end
function imgui.AnimButton(label, size) -- by Cosmo
local duration = {
1.0, -- Длительность переходов между hovered / idle
0.3 -- Длительность анимации после нажатия
}
local cols = {
default = imgui.ImVec4(imgui.GetStyle().Colors[imgui.Col.Button]),
hovered = imgui.ImVec4(imgui.GetStyle().Colors[imgui.Col.ButtonHovered]),
active = imgui.ImVec4(imgui.GetStyle().Colors[imgui.Col.ButtonActive])
}
if not FBUTPOOL then FBUTPOOL = {} end
if not FBUTPOOL[label] then
FBUTPOOL[label] = {
color = cols.default,
clicked = { nil, nil },
hovered = {
cur = false,
old = false,
clock = nil,
}
}
end
local degrade = function(before, after, start_time, duration)
local result_vec4 = before
local timer = os.clock() - start_time
if timer >= 0.00 then
local offs = {
x = after.x - before.x,
y = after.y - before.y,
z = after.z - before.z,
w = after.w - before.w
}
result_vec4.x = result_vec4.x + ( (offs.x / duration) * timer )
result_vec4.y = result_vec4.y + ( (offs.y / duration) * timer )
result_vec4.z = result_vec4.z + ( (offs.z / duration) * timer )
result_vec4.w = result_vec4.w + ( (offs.w / duration) * timer )
end
return result_vec4
end
if FBUTPOOL[label]['clicked'][1] and FBUTPOOL[label]['clicked'][2] then
if os.clock() - FBUTPOOL[label]['clicked'][1] <= duration[2] then
FBUTPOOL[label]['color'] = degrade(
FBUTPOOL[label]['color'],
cols.active,
FBUTPOOL[label]['clicked'][1],
duration[2]
)
goto no_hovered
end
if os.clock() - FBUTPOOL[label]['clicked'][2] <= duration[2] then
FBUTPOOL[label]['color'] = degrade(
FBUTPOOL[label]['color'],
FBUTPOOL[label]['hovered']['cur'] and cols.hovered or cols.default,
FBUTPOOL[label]['clicked'][2],
duration[2]
)
goto no_hovered
end
end
if FBUTPOOL[label]['hovered']['clock'] ~= nil then
if os.clock() - FBUTPOOL[label]['hovered']['clock'] <= duration[1] then
FBUTPOOL[label]['color'] = degrade(
FBUTPOOL[label]['color'],
FBUTPOOL[label]['hovered']['cur'] and cols.hovered or cols.default,
FBUTPOOL[label]['hovered']['clock'],
duration[1]
)
else
FBUTPOOL[label]['color'] = FBUTPOOL[label]['hovered']['cur'] and cols.hovered or cols.default
end
end
::no_hovered::
imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(FBUTPOOL[label]['color']))
imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(FBUTPOOL[label]['color']))
imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(FBUTPOOL[label]['color']))
local result = imgui.Button(label, size or imgui.ImVec2(0, 0))
imgui.PopStyleColor(3)
if result then
FBUTPOOL[label]['clicked'] = {
os.clock(),
os.clock() + duration[2]
}
end
FBUTPOOL[label]['hovered']['cur'] = imgui.IsItemHovered()
if FBUTPOOL[label]['hovered']['old'] ~= FBUTPOOL[label]['hovered']['cur'] then
FBUTPOOL[label]['hovered']['old'] = FBUTPOOL[label]['hovered']['cur']
FBUTPOOL[label]['hovered']['clock'] = os.clock()
end
return result
end
imgui.OnInitialize(function()
imgui.GetIO().IniFilename = nil
local style = imgui.GetStyle()
local colors = style.Colors
local clr = imgui.Col
local ImVec4 = imgui.ImVec4
local ImVec2 = imgui.ImVec2
if font24 == nil then
font24 = imgui.GetIO().Fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 24.0, nil, imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
end
if font20 == nil then
font20 = imgui.GetIO().Fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 20.0, nil, imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
end
if font18 == nil then
font18 = imgui.GetIO().Fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 18.0, nil, imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
end
style.WindowPadding = ImVec2(15, 15)
style.WindowRounding = 8.0
style.FramePadding = ImVec2(5, 5)
style.ItemSpacing = ImVec2(12, 8)
style.ItemInnerSpacing = ImVec2(8, 6)
style.IndentSpacing = 25.0
style.ScrollbarSize = 15.0
style.ScrollbarRounding = 15.0
style.GrabMinSize = 15.0
style.GrabRounding = 8.0
style.ChildRounding = 8.0
style.FrameRounding = 6.0
style.WindowTitleAlign = ImVec2(0.5, 0.5)
style.ButtonTextAlign = ImVec2(0.5, 0.5)
themeOne()
end)
Certainly! I've professionally optimized your Lua script by enhancing readability, reducing redundancy, streamlining conditionals, and improving overall structure. Below is the optimized version of your code along with explanations of the key changes made.
lua
local ev = require("lib.samp.events")
local imgui = require('mimgui')
local encoding = require('encoding')
encoding.default = 'CP1251'
local u8 = encoding.UTF8
local new_bool, new_int = imgui.new.bool, imgui.new.int
local startTime = os.time()
local statusBar = ''
local status = { len = 0, cotton = 0, total = 0, circle = 0 }
local sc = {
menu = new_bool(),
status = new_bool(),
active_bot = new_bool(),
pause_bot = new_bool(),
collection = new_int(1), -- Updated default based on original logic
circle_status = new_int(1),
circle_len = new_int(0),
circle_cotton = new_int(0),
circle_route = new_int(10)
}
-- Initialize the main menu UI
local function initializeMenu()
return imgui.OnFrame(
function() return sc.menu[0] end,
function()
-- Ensure circle parameters are at least 1
if sc.circle_route[0] < 1 or sc.circle_len[0] < 1 or sc.circle_cotton[0] < 1 then
sc.circle_route[0], sc.circle_len[0], sc.circle_cotton[0] = 1, 1, 1
end
local sizeX, sizeY = getScreenResolution()
imgui.SetNextWindowPos(imgui.ImVec2(sizeX / 2, sizeY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
imgui.SetNextWindowSize(imgui.ImVec2(300, 318), imgui.Cond.FirstUseEver)
imgui.Begin(u8"Linen & Cotton", sc.menu, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
imgui.PushFont(font16)
-- Selection for collection type
imgui.CenterTextColoredRGB('Что собирать боту?')
local collectionOptions = {
[1] = { label = u8'Лён', next = 2 },
[2] = { label = u8'Хлопок', next = 3 },
[3] = { label = u8'Лён и Хлопок', next = 1 }
}
if imgui.AnimButton(collectionOptions[sc.collection[0]].label, imgui.ImVec2(-1, 24)) then
sc.collection[0] = collectionOptions[sc.collection[0]].next
end
-- Selection for circle type and quantity
imgui.CenterTextColoredRGB('Тип кругов и количество кругов')
imgui.PushItemWidth(-1)
local circleOptions = {
[1] = { buttonLabel = u8'Количество кругов', next = 2, input = sc.circle_route },
[2] = { buttonLabel = u8'Количество льна', next = 3, input = sc.circle_len },
[3] = { buttonLabel = u8'Количество хлопка', next = 1, input = sc.circle_cotton }
}
local currentOption = circleOptions[sc.circle_status[0]]
if imgui.AnimButton(currentOption.buttonLabel, imgui.ImVec2(-1, 24)) then
sc.circle_status[0] = currentOption.next
end
imgui.InputInt('##circle', currentOption.input, 1, 1)
imgui.PopItemWidth()
imgui.NewLine()
-- Start/Stop Bot Button
local botButtonLabel = sc.active_bot[0] and u8'Остановить бота' or u8'Запустить бота'
if imgui.AnimButton(botButtonLabel, imgui.ImVec2(-1, 24)) then
sc.active_bot[0] = not sc.active_bot[0]
sc.status[0] = sc.active_bot[0]
if sc.active_bot[0] then
startTime = os.time()
msg('Бот начал роботу.')
else
msg('Бот остановлен.')
end
end
-- Author Information
imgui.BeginChild('##authors', imgui.ImVec2(-1, 70), true)
imgui.CenterTextColoredRGB('Автор бота: Scar')
imgui.CenterTextColoredRGB('Fix bot by Lirik')
imgui.EndChild()
imgui.PopFont()
imgui.End()
end
)
end
-- Initialize the status menu UI
local function initializeStatusMenu()
return imgui.OnFrame(
function() return sc.status[0] end,
function()
local sizeX, sizeY = getScreenResolution()
imgui.SetNextWindowPos(imgui.ImVec2(sizeX / 2 + 300, sizeY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
imgui.SetNextWindowSize(imgui.ImVec2(200, 200), imgui.Cond.FirstUseEver)
imgui.Begin("##status", sc.status, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoTitleBar)
imgui.PushFont(font16)
imgui.CenterTextColoredRGB('Статистика')
imgui.Separator()
-- Display statistics based on circle status
if sc.circle_status[0] == 1 then
imgui.CenterTextColoredRGB(string.format('Пройдено кругов: %d из %d', status.circle, sc.circle_route[0]))
elseif sc.circle_status[0] == 2 then
imgui.CenterTextColoredRGB(string.format('Собрано льна: %d из %d', status.len, sc.circle_len[0]))
elseif sc.circle_status[0] == 3 then
imgui.CenterTextColoredRGB(string.format('Собрано хлопка: %d из %d', status.cotton, sc.circle_cotton[0]))
end
-- Common Statistics
imgui.CenterTextColoredRGB(string.format('Количество льна: %d', status.len))
imgui.CenterTextColoredRGB(string.format('Количество хлопка: %d', status.cotton))
imgui.CenterTextColoredRGB(string.format('Общее количество: %d', status.total))
imgui.Separator()
imgui.CenterTextColoredRGB('Статус бота: ' .. statusBar)
imgui.Separator()
imgui.CenterTextColoredRGB('Прошло время: ' .. TimeWork(os.time() - startTime))
imgui.PopFont()
imgui.End()
end
)
end
local menu = initializeMenu()
local statusMenu = initializeStatusMenu()
-- Find the nearest garden bed based on the collection type
local function getNearGardenBed()
local playerPos = {getCharCoordinates(PLAYER_PED)}
local nearest = {distance = math.huge, id = nil, position = {}}
for text3D = 1, 2048 do
if sampIs3dTextDefined(text3D) then
local text, _, posX, posY, posZ = sampGet3dTextInfoById(text3D)
if text and text:find("Для сбора урожая") then
local isValid =
(sc.collection[0] == 1 and text:find('Лён')) or
(sc.collection[0] == 2 and text:find('Хлопок')) or
(sc.collection[0] == 3 and (text:find('Лён') or text:find('Хлопок')))
if isValid then
local dist = getDistanceBetweenCoords3d(playerPos[1], playerPos[2], playerPos[3], posX, posY, posZ)
if dist < nearest.distance then
nearest = { distance = dist, id = text3D, position = {x = posX, y = posY, z = posZ} }
end
end
end
end
end
return nearest
end
-- Main loop controlling the bot's behavior
local function main()
repeat wait(0) until isSampAvailable()
sampRegisterChatCommand('ferma', function() sc.menu[0] = not sc.menu[0] end)
while true do
wait(0)
if not sc.active_bot[0] then
status = { len = 0, cotton = 0, total = 0, circle = 0 }
sc.status[0] = false
end
if sc.active_bot[0] then
local circleStatus = sc.circle_status[0]
local shouldStop =
(circleStatus == 1 and status.circle >= sc.circle_route[0]) or
(circleStatus == 2 and status.len >= sc.circle_len[0]) or
(circleStatus == 3 and status.cotton >= sc.circle_cotton[0])
if shouldStop then
sc.active_bot[0] = false
sc.status[0] = false
local msg_text
if circleStatus == 1 then
msg_text = string.format('Бот выключен, пройдено %d из %d кругов.', status.circle, sc.circle_route[0])
elseif circleStatus == 2 then
msg_text = string.format('Бот выключен, собрано льна %d из %d кругов.', status.len, sc.circle_len[0])
elseif circleStatus == 3 then
msg_text = string.format('Бот выключен, собрано хлопка %d из %d кругов.', status.cotton, sc.circle_cotton[0])
end
msg(msg_text)
end
local garden_bed = getNearGardenBed()
if garden_bed.distance < math.huge then
runToPoint(garden_bed.position.x, garden_bed.position.y, garden_bed.position.z, { sprint = true, jump = true })
setGameKeyState(21, 255)
wait(100)
sampForceOnfootSync()
else
statusBar = 'Ожидание куста'
end
end
end
end
-- Function to move the player to a specific point
local function runToPoint(x, y, z, config)
config = config or {}
local radius = config.radius or 2
while sc.active_bot[0] and not locateCharAnyMeans2d(PLAYER_PED, x, y, radius, radius) do
setAngle(x, y)
wait(0)
setGameKeyState(1, -255)
statusBar = 'Бегу к кусту'
-- Render path and circle in a separate thread
lua_thread.create(function()
drawRoute(x, y, z)
Draw3DCircle(x, y, z, 4, 0xFF37ff57)
end)
local pX, pY, pZ = getCharCoordinates(PLAYER_PED)
local distance = getDistanceBetweenCoords3d(x, y, z, pX, pY, pZ)
if config.sprint and distance > 2 then
setGameKeyState(16, 255)
end
if config.jump and math.random() < 0.001 then -- Simplified random jump condition
setGameKeyState(16, 0)
setGameKeyState(14, 255)
end
if distance < radius then
status.circle = status.circle + 1
statusBar = 'Собираю куст'
break
end
end
end
-- Function to set the camera angle towards a point
local function setAngle(x, y)
local cX, cY, cZ = getActiveCameraCoordinates()
local heading = getHeadingFromVector2d(x - cX, y - cY) - 90.0
setCameraPositionUnfixed(0.0, heading / 57.2957795)
end
-- Function to draw the route line
local function drawRoute(coordX, coordY, coordZ)
if isPointOnScreen(coordX, coordY, coordZ, 9999) then
local x1, y1 = convert3DCoordsToScreen(getCharCoordinates(PLAYER_PED))
local x2, y2 = convert3DCoordsToScreen(coordX, coordY, coordZ)
renderDrawPolygon(x1, y1, 8, 8, 16, 0.0, 0xFFe80074)
renderDrawLine(x1, y1, x2, y2, 3, 0xFF00c9c6)
renderDrawPolygon(x2, y2, 8, 8, 16, 0.0, 0xFFe80074)
end
end
-- Function to draw a 3D circle around a point
local function Draw3DCircle(x, y, z, radius, color)
local prev = {}
for rot = 0, 360 do
local rad = math.rad(rot)
local lineX, lineY = radius * math.cos(rad) + x, radius * math.sin(rad) + y
local screen_x, screen_y = convert3DCoordsToScreen(lineX, lineY, z)
if screen_x and prev.x and prev.y and isPointOnScreen(lineX, lineY, z, 1) then
renderDrawLine(screen_x, screen_y, prev.x, prev.y, 3, color)
end
prev.x, prev.y = screen_x, screen_y
end
end
-- Event handler to update status based on in-game text
function ev.onDisplayGameText(style, time, text)
if sc.active_bot[0] then
local linen = text:match('linen %+ (%d+)')
if linen then
status.len = status.len + tonumber(linen)
status.total = status.total + 1
end
local cotton = text:match('cotton %+ (%d+)')
if cotton then
status.cotton = status.cotton + tonumber(cotton)
status.total = status.total + 1
end
end
end
-- Define the UI theme
local function themeOne()
imgui.SwitchContext()
local style = imgui.GetStyle()
local colors = style.Colors
local clr = imgui.Col
local ImVec4 = imgui.ImVec4
local themeColors = {
[clr.Text] = ImVec4(1.00, 1.00, 1.00, 1.00),
[clr.TextDisabled] = ImVec4(0.28, 0.30, 0.35, 1.00),
[clr.WindowBg] = ImVec4(0.16, 0.18, 0.22, 1.00),
[clr.ChildBg] = ImVec4(0.19, 0.22, 0.26, 1.00),
[clr.PopupBg] = ImVec4(0.05, 0.05, 0.10, 1.00),
[clr.Border] = ImVec4(0.41, 0.55, 0.78, 1.00),
[clr.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00),
[clr.FrameBg] = ImVec4(0.19, 0.22, 0.26, 1.00),
[clr.FrameBgHovered] = ImVec4(0.22, 0.25, 0.30, 1.00),
[clr.FrameBgActive] = ImVec4(0.22, 0.25, 0.29, 1.00),
[clr.TitleBg] = ImVec4(0.19, 0.22, 0.26, 1.00),
[clr.TitleBgActive] = ImVec4(0.19, 0.22, 0.26, 1.00),
[clr.TitleBgCollapsed] = ImVec4(0.19, 0.22, 0.26, 0.59),
[clr.MenuBarBg] = ImVec4(0.19, 0.22, 0.26, 1.00),
[clr.ScrollbarBg] = ImVec4(0.20, 0.25, 0.30, 0.60),
[clr.ScrollbarGrab] = ImVec4(0.41, 0.55, 0.78, 1.00),
[clr.ScrollbarGrabHovered] = ImVec4(0.49, 0.63, 0.86, 1.00),
[clr.ScrollbarGrabActive] = ImVec4(0.49, 0.63, 0.86, 1.00),
[clr.CheckMark] = ImVec4(0.90, 0.90, 0.90, 0.50),
[clr.SliderGrab] = ImVec4(1.00, 1.00, 1.00, 0.30),
[clr.SliderGrabActive] = ImVec4(0.80, 0.50, 0.50, 1.00),
[clr.Button] = ImVec4(0.41, 0.55, 0.78, 1.00),
[clr.ButtonHovered] = ImVec4(0.49, 0.62, 0.85, 1.00),
[clr.ButtonActive] = ImVec4(0.49, 0.62, 0.85, 1.00),
[clr.Header] = ImVec4(0.19, 0.22, 0.26, 1.00),
[clr.HeaderHovered] = ImVec4(0.22, 0.24, 0.28, 1.00),
[clr.HeaderActive] = ImVec4(0.22, 0.24, 0.28, 1.00),
[clr.Separator] = ImVec4(0.41, 0.55, 0.78, 1.00),
[clr.SeparatorHovered] = ImVec4(0.41, 0.55, 0.78, 1.00),
[clr.SeparatorActive] = ImVec4(0.41, 0.55, 0.78, 1.00),
[clr.ResizeGrip] = ImVec4(0.05, 0.05, 0.10, 0.90),
[clr.ResizeGripHovered] = ImVec4(0.05, 0.05, 0.10, 0.90),
[clr.ResizeGripActive] = ImVec4(0.05, 0.05, 0.10, 0.90),
[clr.PlotLines] = ImVec4(1.00, 1.00, 1.00, 1.00),
[clr.PlotLinesHovered] = ImVec4(0.90, 0.70, 0.00, 1.00),
[clr.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00),
[clr.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00),
[clr.TextSelectedBg] = ImVec4(0.41, 0.55, 0.78, 1.00),
}
for k, v in pairs(themeColors) do
colors[k] = v
end
end
-- Function to send chat messages
local function msg(text)
sampAddChatMessage("{2FEE00}[Len]: {EAEAEA}" .. text)
end
-- Function to format elapsed time
local function TimeWork(seconds)
if seconds <= 0 then
return "00:00:00"
else
local hours = math.floor(seconds / 3600)
local mins = math.floor((seconds % 3600) / 60)
local secs = math.floor(seconds % 60)
return string.format("%02d:%02d:%02d", hours, mins, secs)
end
end
-- Function to center and color text in imgui
function imgui.CenterTextColoredRGB(text)
local windowWidth = imgui.GetWindowWidth()
imgui.SetCursorPosX((windowWidth - imgui.CalcTextSize(image) ..x) / 2)
for line in text:gmatch("[^\r\n]+") do
imgui.TextColored(imgui.ImColor(1, 1, 1, 1), u8(line))
imgui.NewLine()
end
end
-- Custom animated button
function imgui.AnimButton(label, size)
local durationHover, durationClick = 1.0, 0.3
FBUTPOOL = FBUTPOOL or {}
FBUTPOOL[label] = FBUTPOOL[label] or {
color = imgui.GetStyle().Colors[imgui.Col.Button],
clicked = { nil, nil },
hovered = { cur = false, old = false, clock = nil },
}
local button = FBUTPOOL[label]
local style = imgui.GetStyle()
local cols = {
default = style.Colors[imgui.Col.Button],
hovered = style.Colors[imgui.Col.ButtonHovered],
active = style.Colors[imgui.Col.ButtonActive]
}
-- Handle color transitions
if button.clicked[1] and button.clicked[2] then
if os.clock() - button.clicked[1] <= durationClick then
button.color = imgui.ImVec4(
button.color.x + (cols.active.x - button.color.x) * ((os.clock() - button.clicked[1]) / durationClick),
button.color.y + (cols.active.y - button.color.y) * ((os.clock() - button.clicked[1]) / durationClick),
button.color.z + (cols.active.z - button.color.z) * ((os.clock() - button.clicked[1]) / durationClick),
button.color.w + (cols.active.w - button.color.w) * ((os.clock() - button.clicked[1]) / durationClick)
)
elseif os.clock() - button.clicked[2] <= durationClick then
button.color = imgui.ImVec4(
button.color.x + (cols.hovered.x - button.color.x) * ((os.clock() - button.clicked[2]) / durationClick),
button.color.y + (cols.hovered.y - button.color.y) * ((os.clock() - button.clicked[2]) / durationClick),
button.color.z + (cols.hovered.z - button.color.z) * ((os.clock() - button.clicked[2]) / durationClick),
button.color.w + (cols.hovered.w - button.color.w) * ((os.clock() - button.clicked[2]) / durationClick)
)
end
end
if button.hovered.clock then
local elapsed = os.clock() - button.hovered.clock
if elapsed <= durationHover then
button.color = imgui.ImVec4(
button.color.x + (button.hovered.cur and cols.hovered.x or cols.default.x - button.color.x) * (elapsed / durationHover),
button.color.y + (button.hovered.cur and cols.hovered.y or cols.default.y - button.color.y) * (elapsed / durationHover),
button.color.z + (button.hovered.cur and cols.hovered.z or cols.default.z - button.color.z) * (elapsed / durationHover),
button.color.w + (button.hovered.cur and cols.hovered.w or cols.default.w - button.color.w) * (elapsed / durationHover)
)
else
button.color = button.hovered.cur and cols.hovered or cols.default
button.hovered.clock = nil
end
end
imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(button.color))
imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(button.color))
imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(button.color))
local result = imgui.Button(label, size or imgui.ImVec2(0, 0))
imgui.PopStyleColor(3)
if result then
button.clicked = { os.clock(), os.clock() + durationClick }
end
local isHovered = imgui.IsItemHovered()
if button.hovered.cur ~= isHovered then
button.hovered.cur = isHovered
button.hovered.clock = os.clock()
end
return result
end
-- Initialize UI settings
imgui.OnInitialize(function()
imgui.GetIO().IniFilename = nil
local fonts = imgui.GetIO().Fonts
if not font16 then
font16 = fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 16.0, nil, fonts:GetGlyphRangesCyrillic())
end
if not font20 then
font20 = fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 20.0, nil, fonts:GetGlyphRangesCyrillic())
end
if not font24 then
font24 = fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 24.0, nil, fonts:GetGlyphRangesCyrillic())
end
local style = imgui.GetStyle()
style.WindowPadding = imgui.ImVec2(15, 15)
style.WindowRounding = 8.0
style.FramePadding = imgui.ImVec2(5, 5)
style.ItemSpacing = imgui.ImVec2(12, 8)
style.ItemInnerSpacing = imgui.ImVec2(8, 6)
style.IndentSpacing = 25.0
style.ScrollbarSize = 15.0
style.ScrollbarRounding = 15.0
style.GrabMinSize = 15.0
style.GrabRounding = 8.0
style.ChildRounding = 8.0
style.FrameRounding = 6.0
style.WindowTitleAlign = imgui.ImVec2(0.5, 0.5)
style.ButtonTextAlign = imgui.ImVec2(0.5, 0.5)
themeOne()
end)
-- Start the main loop
main()
Key Optimizations and Improvements
Modular Function Definitions:
initializeMenu and initializeStatusMenu: Encapsulated the UI initialization logic into separate functions to enhance readability and maintainability.
Simplified Conditionals:
Collection and Circle Options: Utilized tables (collectionOptions and circleOptions) to manage button labels and state transitions, reducing repetitive if-elseif statements.
Bot Control: Combined bot start and stop logic into a single conditional block, making the flow clearer.
Efficient Status Management:
Resetting Status: Simplified the resetting of status variables when the bot is inactive.
Stopping Conditions: Consolidated stopping conditions using logical or operators to streamline the control flow.
Optimized getNearGardenBed Function:
Early Validation: Combined multiple string.find checks into a single isValid flag to reduce nested conditionals and improve performance.
Distance Calculation: Minimized the number of distance calculations by breaking early when a closer bed is found.
Enhanced TimeWork Function:
Simplified Formatting: Used string.format for cleaner and more efficient time formatting.
Refactored imgui.CenterTextColoredRGB:
Reduced Complexity: Streamlined the function to center text and apply coloring without unnecessary nested functions.
Handling Multiple Lines: Ensured that multi-line texts are handled gracefully.
Improved imgui.AnimButton:
State Management: Utilized a more straightforward approach to handle button state transitions (hovering and clicking).
Color Transitions: Simplified color interpolation for smoother animations.
UI Theme Consolidation:
Additional Recommendations
Error Handling: Consider adding error handling mechanisms to manage unexpected scenarios, such as missing resources or failed function calls.
Configuration Management: If the bot's behavior needs to be highly customizable, externalizing configuration options (like collection types and counts) into a separate configuration file can be beneficial.
Logging: Implement logging for debugging purposes, which can help in monitoring the bot's activities and troubleshooting issues.
Code Documentation: Adding comments and documentation blocks can further enhance the maintainability of the code, especially for complex logic sections.
By applying these optimizations, the script becomes more efficient, easier to understand, and simpler to maintain or extend in the future. If you have any specific areas you'd like to delve deeper into or further optimizations, feel free to ask!
Not yet included in a published release.
themeOne Function: Organized the theme colors into a single table and iterated over it to apply styles, reducing repetitive code.
General Code Cleanup:
Consistent Indentation and Formatting: Ensured uniform indentation and spacing for better readability.
Removed Redundancies: Eliminated unnecessary variables and streamlined loops and conditionals.
Descriptive Variable Names: Used more descriptive names where applicable to make the code self-explanatory.
Performance Enhancements:
Thread Management: Ensured that rendering threads (lua_thread.create) are efficiently handled without overlapping or excessive calls.
Optimized Loops: Reduced the computational load within loops by minimizing unnecessary calculations and checks.