- 46
- 3
- Версия SA-MP
-
- Любая
Писал короче скрипт с помощью perplexity
Скрипт нацелен на саморучный сбор цен скупа и продажи на предметы на цр
После запуска игры появляется курсор и не исчезает, тоже самое после открытия окна скрипта и его закрытия
Сам код ниже
Скрипт нацелен на саморучный сбор цен скупа и продажи на предметы на цр
После запуска игры появляется курсор и не исчезает, тоже самое после открытия окна скрипта и его закрытия
Сам код ниже
ясос убибу:
local imgui = require 'imgui'
local json = require 'dkjson' -- или 'json', если так называется у вас
local windowOpen = imgui.ImBool(false)
local items = {}
local inputName = imgui.ImBuffer(128)
local inputBuyPrice = imgui.ImBuffer(20)
local inputSellPrice = imgui.ImBuffer(20)
local selectedDate = imgui.ImBuffer(os.date("%Y-%m-%d"), 12)
local centerWindowNextOpen = false -- флаг для центрирования окна
-- Получение пути к скрипту
local function getScriptDir()
local info = debug.getinfo(1, 'S')
local script = info.source:match("@(.*)$")
return script:match("^(.*)[/\\]")
end
local scriptDir = getScriptDir()
local savePath = scriptDir .. '\\PriceTrackerRP\\'
-- Проверка и создание папки
local function ensureDirectory(path)
-- Windows: mkdir не выдаст ошибку если папка уже есть
os.execute('if not exist "' .. path .. '" mkdir "' .. path .. '"')
end
local function addItem()
local buy = tonumber(inputBuyPrice.v)
local sell = tonumber(inputSellPrice.v)
if inputName.v ~= '' and buy and sell then
local found = false
for i, item in ipairs(items) do
if item.name == inputName.v then
item.buyPrice = buy
item.sellPrice = sell
item.date = selectedDate.v
found = true
break
end
end
if not found then
table.insert(items, {
name = inputName.v,
buyPrice = buy,
sellPrice = sell,
date = selectedDate.v
})
end
inputName.v = ''
inputBuyPrice.v = ''
inputSellPrice.v = ''
end
end
local function saveItemsForDate(date)
-- Собираем только предметы с нужной датой
local filtered = {}
for _, item in ipairs(items) do
if item.date == date then
table.insert(filtered, item)
end
end
if #filtered == 0 then return false, "Нет предметов с такой датой" end
ensureDirectory(savePath) -- Создаём папку, если её нет
local jsonText = json.encode(filtered, { indent = true, keyorder = { "name", "buyPrice", "sellPrice", "date" } })
local fileName = savePath .. 'Price_' .. date .. '.json'
local file = io.open(fileName, 'w+')
if not file then return false, "Не удалось открыть файл для записи:\n" .. fileName end
file:write(jsonText)
file:close()
return true, fileName
end
local function loadItemsForDate(date)
local fileName = savePath .. 'Price_' .. date .. '.json'
local file = io.open(fileName, 'r')
if not file then return false, "Файл не найден:\n" .. fileName end
local contents = file:read("*a")
file:close()
local loaded, pos, err = json.decode(contents, 1, nil)
if type(loaded) ~= "table" then
return false, "Ошибка чтения JSON:\n" .. (err or "Неизвестная ошибка")
end
-- Очищаем текущие items с этой датой и добавляем новые
for i = #items, 1, -1 do
if items[i].date == date then
table.remove(items, i)
end
end
for _, v in ipairs(loaded) do
table.insert(items, v)
end
return true, fileName
end
local saveResult = nil
local loadResult = nil
-- Автоматическая подгрузка цен при открытии окна
local lastLoadedDate = ""
local function tryAutoLoadForDate(date)
if lastLoadedDate ~= date then
local ok = loadItemsForDate(date)
-- Если файла нет, ничего не делаем
lastLoadedDate = date
end
end
local function drawWindow()
if not windowOpen.v then
if sampIsCursorActive() then
sampToggleCursor(false)
end
return
end
-- Автозагрузка цен за выбранную дату при открытии окна
tryAutoLoadForDate(selectedDate.v)
if centerWindowNextOpen then
local io = imgui.GetIO()
imgui.SetNextWindowPos(imgui.ImVec2(
(io.DisplaySize.x - 600) / 2,
(io.DisplaySize.y - 400) / 2
), imgui.Cond.Always)
centerWindowNextOpen = false
end
imgui.SetNextWindowSize(imgui.ImVec2(600, 400), imgui.Cond.FirstUseEver)
imgui.Begin("PriceTrackerRP - База цен на предметы", windowOpen)
imgui.Text("Автор скрипта: Vazelinovoe_Drislo")
imgui.Separator()
imgui.Text("Название предмета:")
imgui.InputText("##name", inputName)
imgui.Text("Цена покупки:")
imgui.InputText("##buyprice", inputBuyPrice)
imgui.Text("Цена продажи:")
imgui.InputText("##sellprice", inputSellPrice)
imgui.Text("Дата (ГГГГ-ММ-ДД):")
imgui.InputText("##date", selectedDate)
if imgui.Button("Добавить предмет") then
addItem()
end
imgui.SameLine()
if imgui.Button("Сохранить цены за дату") then
local ok, msg = saveItemsForDate(selectedDate.v)
if ok then
saveResult = 'Сохранено в файл:\n' .. msg
else
saveResult = 'Ошибка:\n' .. msg
end
end
if saveResult then
imgui.TextWrapped(saveResult)
end
imgui.Separator()
imgui.Text("Сохранённые цены:")
if #items == 0 then
imgui.Text("Нет данных.")
else
imgui.Columns(4, "items_columns", true)
imgui.Text("Название"); imgui.NextColumn()
imgui.Text("Цена покупки"); imgui.NextColumn()
imgui.Text("Цена продажи"); imgui.NextColumn()
imgui.Text("Дата"); imgui.NextColumn()
imgui.Separator()
for _, item in ipairs(items) do
imgui.Text(item.name); imgui.NextColumn()
imgui.Text(string.format("%.2f", item.buyPrice)); imgui.NextColumn()
imgui.Text(string.format("%.2f", item.sellPrice)); imgui.NextColumn()
imgui.Text(item.date); imgui.NextColumn()
end
imgui.Columns(1)
end
imgui.End()
end
function main()
if not isSampLoaded() or not isSampfuncsLoaded() then return end
while not isSampAvailable() do wait(100) end
sampRegisterChatCommand("pt", function(arg)
windowOpen.v = not windowOpen.v
if windowOpen.v then
centerWindowNextOpen = true
-- При открытии окна сразу пробуем автозагрузку
lastLoadedDate = "" -- сбрасываем, чтобы tryAutoLoadForDate сработал
end
end)
imgui.Process = true
imgui.OnDrawFrame = drawWindow
wait(-1)
end