--[[ В чем проблема? [code] Этот код под номером 1, получает только 2 ноды [code] А код…
- User
--[[
В чем проблема?
lua - Assistant
--[[
В чем проблема?
-- Код номер 1
local font = renderCreateFont('Tahoma', 10, 4)
local nodes = {}
local nodeCount = 255
local startNodeIndex = 1
local goalNodeIndex = 5
function main()
while not isSampAvailable() do
wait(0)
end
sampRegisterChatCommand('get_node_in_stream', function()
local fx, fy, fz = getCharCoordinates(PLAYER_PED)
nodes = {}
for i = 1, nodeCount do
local nx, ny, nz = getNthClosestCarNode(fx, fy, fz, i)
table.insert(nodes, {
x = nx,
y = ny,
z = nz
})
end
table.sort(nodes, function(a, b)
local distA = getDistanceBetweenCoords3d(fx, fy, fz, a.x, a.y, a.z)
local distB = getDistanceBetweenCoords3d(fx, fy, fz, b.x, b.y, b.z)
return distA < distB
end)
local start = nodes[startNodeIndex]
local goal = nodes[goalNodeIndex]
local path = AStar(start, goal, nodes)
if path then
lua_thread.create(function()
while true do
wait(0)
for i, node in ipairs(path) do
local result, sx, sy = convert3DCoordsToScreenEx(node.x, node.y, node.z)
if result and isPointOnScreen(node.x, node.y, node.z, 5) then renderFontDrawText(font, 'node #' .. i, sx, sy, 0xFFFFFFFF, 0x90000000) end
end
end
end)
else
print("Path not found")
end
end)
sampRegisterChatCommand('set_nodes', function(params)
local startIdx, goalIdx = params:match("(%d+)%s+(%d+)")
if startIdx and goalIdx then
startNodeIndex = tonumber(startIdx)
goalNodeIndex = tonumber(goalIdx)
print("Start node set to: " .. startNodeIndex)
print("Goal node set to: " .. goalNodeIndex)
else
print("Invalid input. Use: /set_nodes <start_index> <goal_index>")
end
end)
while true do
wait(0)
end
end
local function get_neighbors(node, nodes)
local neighbors = {}
for _, neighbor in ipairs(nodes) do
if neighbor ~= node then table.insert(neighbors, neighbor) end
end
return neighbors
end
local function reconstruct_path(cameFrom, current)
local total_path = {current}
while cameFrom[current] do
current = cameFrom[current]
table.insert(total_path, 1, current)
end
return total_path
end
function AStar(start, goal, nodes)
local closedSet = {}
local openSet = {start}
local cameFrom = {}
start.g = 0
start.h = getDistanceBetweenCoords3d(start.x, start.y, start.z, goal.x, goal.y, goal.z)
start.f = start.g + start.h
while #openSet > 0 do
table.sort(openSet, function(a, b) return a.f < b.f end)
local current = table.remove(openSet, 1)
if current == goal then return reconstruct_path(cameFrom, current) end
table.insert(closedSet, current)
for _, neighbor in ipairs(get_neighbors(current, nodes)) do
if not tableContains(closedSet, neighbor) then
local tentative_g_score = current.g + getDistanceBetweenCoords3d(current.x, current.y, current.z, neighbor.x, neighbor.y, neighbor.z)
if not tableContains(openSet, neighbor) or tentative_g_score < neighbor.g then
cameFrom[neighbor] = current
neighbor.g = tentative_g_score
neighbor.h = getDistanceBetweenCoords3d(neighbor.x, neighbor.y, neighbor.z, goal.x, goal.y, goal.z)
neighbor.f = neighbor.g + neighbor.h
if not tableContains(openSet, neighbor) then table.insert(openSet, neighbor) end
end
end
end
end
return false
end
function tableContains(tbl, element)
for _, value in pairs(tbl) do
if value == element then return true end
end
return false
end
Этот код под номером 1, получает только 2 ноды
-- Код номер 2
local font = renderCreateFont('Tahoma', 10, 4)
local nodes = {}
local nodeCount = 255
function main()
while not isSampAvailable() do
wait(0)
end
sampRegisterChatCommand('get_node_in_stream', function()
local fx, fy, fz = getCharCoordinates(PLAYER_PED)
nodes = {}
for i = 1, nodeCount do
local nx, ny, nz = getNthClosestCarNode(fx, fy, fz, i)
table.insert(nodes, {nx, ny, nz})
end
local sortedNodes = {}
local currentNode = {fx, fy, fz}
while #nodes > 0 do
local nearestIndex = 1
local nearestDistance = getDistanceBetweenCoords3d(currentNode[1], currentNode[2], currentNode[3], nodes[1][1], nodes[1][2], nodes[1][3])
for i = 2, #nodes do
local distance = getDistanceBetweenCoords3d(currentNode[1], currentNode[2], currentNode[3], nodes[i][1], nodes[i][2], nodes[i][3])
if distance < nearestDistance then
nearestIndex = i
nearestDistance = distance
end
end
table.insert(sortedNodes, nodes[nearestIndex])
currentNode = nodes[nearestIndex]
table.remove(nodes, nearestIndex)
end
nodes = sortedNodes
lua_thread.create(function()
while true do
wait(0)
for i = 1, #nodes do
local result, sx, sy = convert3DCoordsToScreenEx(nodes[i][1], nodes[i][2], nodes[i][3])
if result and isPointOnScreen(nodes[i][1], nodes[i][2], nodes[i][3], 5) then renderFontDrawText(font, 'node #' .. i, sx, sy, 0xFFFFFFFF, 0x90000000) end
end
end
end)
end)
while true do
wait(0)
end
end
А код номер 2, получает все доступные ноды. Как сделать чтобы код 1 тоже получал все ноды, а не только 2.]]
Проблема в вашем первом коде заключается в использовании алгоритма A* для поиска пути между двумя узлами. В результате, алгоритм находит лишь прямой путь от start до goal, что приводит к отображению только двух узлов. Если ваша цель — получить и отобразить все доступные узлы, использование A* не подходит.
Однако, если вы хотите сохранить функциональность A* и при этом получать больше узлов в пути, необходимо изменить способ выбора соседей в алгоритме. Вот как можно решить обе задачи:
Если ваша цель состоит просто в получении и отображении всех доступных узлов, вы можете модифицировать первый код, убрав часть с A* и следуя подходу второго кода. Вот пример модифицированного кода:
local font = renderCreateFont('Tahoma', 10, 4)
local nodes = {}
local nodeCount = 255
function main()
while not isSampAvailable() do
wait(0)
end
sampRegisterChatCommand('get_node_in_stream', function()
local fx, fy, fz = getCharCoordinates(PLAYER_PED)
nodes = {}
for i = 1, nodeCount do
local nx, ny, nz = getNthClosestCarNode(fx, fy, fz, i)
table.insert(nodes, {x = nx, y = ny, z = nz})
end
table.sort(nodes, function(a, b)
local distA = getDistanceBetweenCoords3d(fx, fy, fz, a.x, a.y, a.z)
local distB = getDistanceBetweenCoords3d(fx, fy, fz, b.x, b.y, b.z)
return distA < distB
end)
lua_thread.create(function()
while true do
wait(0)
for i, node in ipairs(nodes) do
local result, sx, sy = convert3DCoordsToScreenEx(node.x, node.y, node.z)
if result and isPointOnScreen(node.x, node.y, node.z, 5) then
renderFontDrawText(font, 'node #' .. i, sx, sy, 0xFFFFFFFF, 0x90000000)
end
end
end
end)
end)
sampRegisterChatCommand('set_nodes', function(params)
local startIdx, goalIdx = params:match("(%d+)%s+(%d+)")
if startIdx and goalIdx then
startNodeIndex = tonumber(startIdx)
goalNodeIndex = tonumber(goalIdx)
print("Start node set to: " .. startNodeIndex)
print("Goal node set to: " .. goalNodeIndex)
else
print("Invalid input. Use: /set_nodes <start_index> <goal_index>")
end
end)
while true do
wait(0)
end
end
Если вы хотите сохранить использование A* и получать более детальный путь с большим количеством узлов, необходимо изменить функцию get_neighbors, чтобы выбирать только близкие узлы вместо всех возможных. Это поможет алгоритму находить более реалистичные пути, проходящие через множество промежуточных узлов.
Вот модифицированный вариант вашего первого кода с улучшенной функцией соседей:
Ключевые изменения:
Функция get_neighbors: Теперь она выбирает только те узлы, которые находятся в пределах определенного расстояния от текущего узла (neighborDistanceThreshold). Это предотвращает прямое соединение с целью и заставляет A* проходить через промежуточные узлы.
Проверка достижения цели: Вместо сравнения таблиц (current == goal), используется сравнение координат узлов, чтобы корректно определить достижение цели.
Параметр neighborDistanceThreshold: Вам может понадобиться настроить это значение в зависимости от размера карты и плотности узлов, чтобы добиться желаемого поведения алгоритма.
Если ваша задача состоит в отображении всех узлов, рекомендуется использовать подход второго кода и убрать алгоритм A*. Если же вы хотите использовать A* для поиска пути с промежуточными узлами, необходимо корректно реализовать выбор соседей и проверку достижения цели, как показано в модифицированном первом коде.
Если после изменений всё ещё возникают проблемы, пожалуйста, предоставьте дополнительную информацию или ошибки, которые вы получаете, чтобы я мог помочь более детально.
Not yet included in a published release.
-- Код номер 1 с улучшенным A*
local font = renderCreateFont('Tahoma', 10, 4)
local nodes = {}
local nodeCount = 255
local startNodeIndex = 1
local goalNodeIndex = 5
local neighborDistanceThreshold = 50.0 -- настройте этот параметр в зависимости от вашей карты
function main()
while not isSampAvailable() do
wait(0)
end
sampRegisterChatCommand('get_node_in_stream', function()
local fx, fy, fz = getCharCoordinates(PLAYER_PED)
nodes = {}
for i = 1, nodeCount do
local nx, ny, nz = getNthClosestCarNode(fx, fy, fz, i)
table.insert(nodes, {
x = nx,
y = ny,
z = nz
})
end
table.sort(nodes, function(a, b)
local distA = getDistanceBetweenCoords3d(fx, fy, fz, a.x, a.y, a.z)
local distB = getDistanceBetweenCoords3d(fx, fy, fz, b.x, b.y, b.z)
return distA < distB
end)
local start = nodes[startNodeIndex]
local goal = nodes[goalNodeIndex]
local path = AStar(start, goal, nodes)
if path then
lua_thread.create(function()
while true do
wait(0)
for i, node in ipairs(path) do
local result, sx, sy = convert3DCoordsToScreenEx(node.x, node.y, node.z)
if result and isPointOnScreen(node.x, node.y, node.z, 5) then
renderFontDrawText(font, 'node #' .. i, sx, sy, 0xFFFFFFFF, 0x90000000)
end
end
end
end)
else
print("Path not found")
end
end)
sampRegisterChatCommand('set_nodes', function(params)
local startIdx, goalIdx = params:match("(%d+)%s+(%d+)")
if startIdx and goalIdx then
startNodeIndex = tonumber(startIdx)
goalNodeIndex = tonumber(goalIdx)
print("Start node set to: " .. startNodeIndex)
print("Goal node set to: " .. goalNodeIndex)
else
print("Invalid input. Use: /set_nodes <start_index> <goal_index>")
end
end)
while true do
wait(0)
end
end
local function get_neighbors(node, nodes)
local neighbors = {}
for _, neighbor in ipairs(nodes) do
if neighbor ~= node then
local distance = getDistanceBetweenCoords3d(node.x, node.y, node.z, neighbor.x, neighbor.y, neighbor.z)
if distance <= neighborDistanceThreshold then
table.insert(neighbors, neighbor)
end
end
end
return neighbors
end
local function reconstruct_path(cameFrom, current)
local total_path = {current}
while cameFrom[current] do
current = cameFrom[current]
table.insert(total_path, 1, current)
end
return total_path
end
function AStar(start, goal, nodes)
local closedSet = {}
local openSet = {start}
local cameFrom = {}
start.g = 0
start.h = getDistanceBetweenCoords3d(start.x, start.y, start.z, goal.x, goal.y, goal.z)
start.f = start.g + start.h
while #openSet > 0 do
table.sort(openSet, function(a, b) return a.f < b.f end)
local current = table.remove(openSet, 1)
if current.x == goal.x and current.y == goal.y and current.z == goal.z then
return reconstruct_path(cameFrom, current)
end
table.insert(closedSet, current)
for _, neighbor in ipairs(get_neighbors(current, nodes)) do
if not tableContains(closedSet, neighbor) then
local tentative_g_score = current.g + getDistanceBetweenCoords3d(current.x, current.y, current.z, neighbor.x, neighbor.y, neighbor.z)
if not tableContains(openSet, neighbor) or tentative_g_score < neighbor.g then
cameFrom[neighbor] = current
neighbor.g = tentative_g_score
neighbor.h = getDistanceBetweenCoords3d(neighbor.x, neighbor.y, neighbor.z, goal.x, goal.y, goal.z)
neighbor.f = neighbor.g + neighbor.h
if not tableContains(openSet, neighbor) then
table.insert(openSet, neighbor)
end
end
end
end
end
return false
end
function tableContains(tbl, element)
for _, value in pairs(tbl) do
if value == element then return true end
end
return false
end