Алгоритмы, Наработки и Способности
Способ реализации:
Lua
Тип:
Наработка

Как это работает

Благодаря тому, что в lua есть функциональное программирование, мы можем переопределить глобальные функции. Например:
function Location(x, y)
	return { x, y }
end
Заменив утечные функции на свои, можно избежать утечек и возможно немного ускорить выполнение кода.

Список функций

Функции возвращающие location
Игрок - Trigger Mouse Position
native BlzGetTriggerPlayerMousePosition takes nothing returns location
---@return table
function BlzGetTriggerPlayerMousePosition()
	return { BlzGetTriggerPlayerMouseX(), BlzGetTriggerPlayerMouseY() }
end
Center Of Region
function GetRectCenter takes rect whichRect returns location
    return Location(GetRectCenterX(whichRect), GetRectCenterY(whichRect))
endfunction
---@param whichRect rect
---@return table
function GetRectCenter(whichRect)
	return { GetRectCenterX(whichRect), GetRectCenterY(whichRect) }
end
Random Point In Region
function GetRandomLocInRect takes rect whichRect returns location
    return Location(GetRandomReal(GetRectMinX(whichRect), GetRectMaxX(whichRect)), GetRandomReal(GetRectMinY(whichRect), GetRectMaxY(whichRect)))
---@param whichRect rect
---@return table
function GetRandomLocInRect(whichRect)
	return { math.random(GetRectMinX(whichRect), GetRectMaxX(whichRect)), math.random(GetRectMinY(whichRect), GetRectMaxY(whichRect)) }
end
Point With Offset
function OffsetLocation takes location loc, real dx, real dy returns location
    return Location(GetLocationX(loc) + dx, GetLocationY(loc) + dy)
endfunction
---@param loc table
---@param dx real
---@param dy real
---@return table
function OffsetLocation(loc, dx, dy)
	return { loc[1] + dx, loc[2] + dy }
end
Point With Polar Offset
function PolarProjectionBJ takes location source, real dist, real angle returns location
    local real x = GetLocationX(source) + dist * Cos(angle * bj_DEGTORAD)
    local real y = GetLocationY(source) + dist * Sin(angle * bj_DEGTORAD)
    return Location(x, y)
endfunction
---@param source table
---@param dist real
---@param angle real
---@return table
function PolarProjectionBJ(source, dist, angle)
	angle = math.rad(angle)
	return { source[1] + dist * math.cos(angle), source[2] + dist * math.sin(angle) }
end
Камера - Target Of Camera Object
native CameraSetupGetDestPositionLoc takes camerasetup whichSetup returns location
---@param whichSetup camerasetup
---@return table
function CameraSetupGetDestPositionLoc(whichSetup)
	return { CameraSetupGetDestPositionX(whichSetup), CameraSetupGetDestPositionY(whichSetup) }
end
Камера - Source Of Current Camera
constant native GetCameraTargetPositionLoc  takes nothing returns location
---@return table
function GetCameraTargetPositionLoc()
	return { GetCameraTargetPositionX(), GetCameraTargetPositionY() }
end
Преобразование - Convert Coordinates To Point
native Location takes real x, real y returns location
---@param x real
---@param y real
---@return table
function Location(x, y)
	return { x, y }
end
Декорация - Position Of Destructible
function GetDestructableLoc takes destructable whichDestructable returns location
    return Location(GetDestructableX(whichDestructable), GetDestructableY(whichDestructable))
endfunction
---@param whichDestructable destructable
---@return table
function GetDestructableLoc(whichDestructable)
	return { GetDestructableX(whichDestructable), GetDestructableY(whichDestructable) }
end
Реакция на событие - Target Point Of Issued Order
constant native GetOrderPointLoc takes nothing returns location
---@return table
function GetOrderPointLoc()
	return { GetOrderPointX(), GetOrderPointY() }
end
Реакция на событие - Target Point Of Ability Being Cast
constant native GetSpellTargetLoc takes nothing returns location
---@return table
function GetSpellTargetLoc()
	return { GetSpellTargetX(), GetSpellTargetY() }
end
Предмет - Position Of Item
function GetItemLoc takes item whichItem returns location
    return Location(GetItemX(whichItem), GetItemY(whichItem))
endfunction
---@param whichItem item
---@return table
function GetItemLoc(whichItem)
	return { GetItemX(whichItem), GetItemY(whichItem) }
end
Нейтральное здание - Way Gate Destination
function WaygateGetDestinationLocBJ takes unit waygate returns location
    return Location(WaygateGetDestinationX(waygate), WaygateGetDestinationY(waygate))
endfunction
---@param waygate unit
---@return table
function WaygateGetDestinationLocBJ(waygate)
	return { WaygateGetDestinationX(waygate), WaygateGetDestinationY(waygate) }
end
Игрок - Player Start Location
function GetPlayerStartLocationLoc takes player whichPlayer returns location
    return GetStartLocationLoc(GetPlayerStartLocation(whichPlayer))
endfunction
---@param whichPlayer player
---@return table
function GetPlayerStartLocationLoc(whichPlayer)
	return { GetPlayerStartLocationX(whichPlayer), GetPlayerStartLocationY(whichPlayer) }
end
Боевая единица - Position Of Unit
constant native GetUnitLoc takes unit whichUnit returns location
---@param whichUnit unit
---@return table
function GetUnitLoc(whichUnit)
	return { GetUnitX(whichUnit), GetUnitY(whichUnit) }
end
Боевая единица - Rally-Point As Point
constant native GetUnitRallyPoint takes unit whichUnit returns location
local GetUnitRallyPointOrigin = GetUnitRallyPoint

---@param whichUnit unit
---@return table
function GetUnitRallyPoint(whichUnit)
	local location = GetUnitRallyPointOrigin(whichUnit)
	local x, y     = GetLocationX(location), GetLocationY(location)
	RemoveLocation(location)
	return { x, y }
end
Боевая единица
Create Units Facing Angle
function CreateNUnitsAtLoc takes integer count, integer unitId, player whichPlayer, location loc, real face returns group
    call GroupClear(bj_lastCreatedGroup)
    loop
        set count = count - 1
        exitwhen count < 0
        call CreateUnitAtLocSaveLast(whichPlayer, unitId, loc, face)
        call GroupAddUnit(bj_lastCreatedGroup, bj_lastCreatedUnit)
    endloop
    return bj_lastCreatedGroup
endfunction
---@param count integer
---@param unitId integer
---@param whichPlayer player
---@param loc table
---@param face real
---@return group
function CreateNUnitsAtLoc(count, unitId, whichPlayer, loc, face)
	GroupClear(lastCreatedGroup)
	for i = 1, count do
		lastCreatedUnit = CreateUnit(whichPlayer, unitId, loc[1], loc[2], face)
		GroupAddUnit(lastCreatedGroup, lastCreatedUnit)
	end
	return lastCreatedGroup
end
Create Units Facing Point
function CreateNUnitsAtLocFacingLocBJ takes integer count, integer unitId, player whichPlayer, location loc, location lookAt returns group
    return CreateNUnitsAtLoc(count, unitId, whichPlayer, loc, AngleBetweenPoints(loc, lookAt))
endfunction
---@param count integer
---@param unitId integer
---@param whichPlayer player
---@param loc table
---@param lookAt table
---@return group
function CreateNUnitsAtLocFacingLocBJ(count, unitId, whichPlayer, loc, lookAt)
	GroupClear(lastCreatedGroup)
	local face = math.deg(math.atan(lookAt[2] - loc[2], lookAt[1] - loc[1]))
	for i = 1, count do
		lastCreatedUnit = CreateUnit(whichPlayer, unitId, loc[1], loc[2], face)
		GroupAddUnit(lastCreatedGroup, lastCreatedUnit)
	end
	return lastCreatedGroup
end
Create Corpse
function CreateCorpseLocBJ takes integer unitid, player whichPlayer, location loc returns unit
    set bj_lastCreatedUnit = CreateCorpse(whichPlayer, unitid, GetLocationX(loc), GetLocationY(loc), GetRandomReal(0, 360))
    return bj_lastCreatedUnit
endfunction
---@param unitid integer
---@param whichPlayer player
---@param loc table
---@return unit
function CreateCorpseLocBJ(unitid, whichPlayer, loc)
	lastCreatedUnit = CreateCorpse(whichPlayer, unitid, loc[1], loc[2], math.random(0, 359))
	return lastCreatedUnit
end
Create Permanent Corpse
function CreatePermanentCorpseLocBJ takes integer style, integer unitid, player whichPlayer, location loc, real facing returns unit
    set bj_lastCreatedUnit = CreateCorpse(whichPlayer, unitid, GetLocationX(loc), GetLocationY(loc), facing)
    call SetUnitBlendTime(bj_lastCreatedUnit, 0)

    if (style == bj_CORPSETYPE_FLESH) then
        call SetUnitAnimation(bj_lastCreatedUnit, "decay flesh")
        call GroupAddUnit(bj_suspendDecayFleshGroup, bj_lastCreatedUnit)
    elseif (style == bj_CORPSETYPE_BONE) then
        call SetUnitAnimation(bj_lastCreatedUnit, "decay bone")
        call GroupAddUnit(bj_suspendDecayBoneGroup, bj_lastCreatedUnit)
    else
        // Unknown decay style - treat as skeletal.
        call SetUnitAnimation(bj_lastCreatedUnit, "decay bone")
        call GroupAddUnit(bj_suspendDecayBoneGroup, bj_lastCreatedUnit)
    endif

    call TimerStart(bj_delayedSuspendDecayTimer, 0.05, false, null)
    return bj_lastCreatedUnit
endfunction
---@param style integer
---@param unitid integer
---@param whichPlayer player
---@param loc table
---@param facing real
---@return unit
function CreatePermanentCorpseLocBJ(style, unitid, whichPlayer, loc, facing)
	lastCreatedUnit = CreateCorpse(whichPlayer, unitid, loc[1], loc[2], facing)
	SetUnitBlendTime(lastCreatedUnit, 0)
	
	if (style == bj_CORPSETYPE_FLESH) then
		SetUnitAnimation(lastCreatedUnit, 'decay flesh')
		GroupAddUnit(bj_suspendDecayFleshGroup, lastCreatedUnit)
	elseif (style == bj_CORPSETYPE_BONE) then
		SetUnitAnimation(lastCreatedUnit, 'decay bone')
		GroupAddUnit(bj_suspendDecayBoneGroup, lastCreatedUnit)
	else
		-- Unknown decay style - treat as skeletal.
		SetUnitAnimation(lastCreatedUnit, 'decay bone')
		GroupAddUnit(bj_suspendDecayBoneGroup, lastCreatedUnit)
	end
	
	TimerStart(bj_delayedSuspendDecayTimer, 0.05, false)
	return lastCreatedUnit
end

Установка

Просто скопируйте код в Нестандартный код карты.
Код
do
	-- Getters
	
	---@param locA table
	---@param locB table
	---@return real
	function AngleBetweenPoints(locA, locB)
		return math.deg(math.atan(locB[2] - locA[2], locB[1] - locA[1]))
	end
	
	---@param x real
	---@param y real
	---@return table
	function Location(x, y)
		return { x, y }
	end
	
	---@param whichRect rect
	---@return table
	function GetRectCenter(whichRect)
		return { GetRectCenterX(whichRect), GetRectCenterY(whichRect) }
	end
	
	---@return table
	function BlzGetTriggerPlayerMousePosition()
		return { BlzGetTriggerPlayerMouseX(), BlzGetTriggerPlayerMouseY() }
	end
	
	---@param whichRect rect
	---@return table
	function GetRandomLocInRect(whichRect)
		return { math.random(GetRectMinX(whichRect), GetRectMaxX(whichRect)), math.random(GetRectMinY(whichRect), GetRectMaxY(whichRect)) }
	end
	
	---@param loc table
	---@param dx real
	---@param dy real
	---@return table
	function OffsetLocation(loc, dx, dy)
		return { loc[1] + dx, loc[2] + dy }
	end
	
	---@param source table
	---@param dist real
	---@param angle real
	---@return table
	function PolarProjectionBJ(source, dist, angle)
		angle = math.rad(angle)
		return { source[1] + dist * math.cos(angle), source[2] + dist * math.sin(angle) }
	end
	
	---@param whichSetup camerasetup
	---@return table
	function CameraSetupGetDestPositionLoc(whichSetup)
		return { CameraSetupGetDestPositionX(whichSetup), CameraSetupGetDestPositionY(whichSetup) }
	end
	
	---@return table
	function GetCameraTargetPositionLoc()
		return { GetCameraTargetPositionX(), GetCameraTargetPositionY() }
	end
	
	---@param whichDestructable destructable
	---@return table
	function GetDestructableLoc(whichDestructable)
		return { GetDestructableX(whichDestructable), GetDestructableY(whichDestructable) }
	end
	
	---@return table
	function GetOrderPointLoc()
		return { GetOrderPointX(), GetOrderPointY() }
	end
	
	---@return table
	function GetSpellTargetLoc()
		return { GetSpellTargetX(), GetSpellTargetY() }
	end
	
	---@param whichItem item
	---@return table
	function GetItemLoc(whichItem)
		return { GetItemX(whichItem), GetItemY(whichItem) }
	end
	
	---@param whichPlayer player
	---@return table
	function GetPlayerStartLocationLoc(whichPlayer)
		return { GetPlayerStartLocationX(whichPlayer), GetPlayerStartLocationY(whichPlayer) }
	end
	
	---@param whichUnit unit
	---@return table
	function GetUnitLoc(whichUnit)
		return { GetUnitX(whichUnit), GetUnitY(whichUnit) }
	end
	
	local GetUnitRallyPointOrigin = GetUnitRallyPoint
	
	---@param whichUnit unit
	---@return table
	function GetUnitRallyPoint(whichUnit)
		local location = GetUnitRallyPointOrigin(whichUnit)
		local x, y     = GetLocationX(location), GetLocationY(location)
		RemoveLocation(location)
		return { x, y }
	end
	
	---@param waygate unit
	---@return table
	function WaygateGetDestinationLocBJ(waygate)
		return { WaygateGetDestinationX(waygate), WaygateGetDestinationY(waygate) }
	end
	
	-- Unit
	
	local lastCreatedUnit---@type unit
	local lastCreatedGroup = CreateGroup()
	
	---@param count integer
	---@param unitId integer
	---@param whichPlayer player
	---@param loc table
	---@param face real
	---@return group
	function CreateNUnitsAtLoc(count, unitId, whichPlayer, loc, face)
		GroupClear(lastCreatedGroup)
		for i = 1, count do
			lastCreatedUnit = CreateUnit(whichPlayer, unitId, loc[1], loc[2], face)
			GroupAddUnit(lastCreatedGroup, lastCreatedUnit)
		end
		return lastCreatedGroup
	end
	
	---@param count integer
	---@param unitId integer
	---@param whichPlayer player
	---@param loc table
	---@param lookAt table
	---@return group
	function CreateNUnitsAtLocFacingLocBJ(count, unitId, whichPlayer, loc, lookAt)
		GroupClear(lastCreatedGroup)
		local face = math.deg(math.atan(lookAt[2] - loc[2], lookAt[1] - loc[1]))
		for i = 1, count do
			lastCreatedUnit = CreateUnit(whichPlayer, unitId, loc[1], loc[2], face)
			GroupAddUnit(lastCreatedGroup, lastCreatedUnit)
		end
		return lastCreatedGroup
	end
	
	---@param unitid integer
	---@param whichPlayer player
	---@param loc table
	---@return unit
	function CreateCorpseLocBJ(unitid, whichPlayer, loc)
		lastCreatedUnit = CreateCorpse(whichPlayer, unitid, loc[1], loc[2], math.random(0, 359))
		return lastCreatedUnit
	end
	
	---@param style integer
	---@param unitid integer
	---@param whichPlayer player
	---@param loc table
	---@param facing real
	---@return unit
	function CreatePermanentCorpseLocBJ(style, unitid, whichPlayer, loc, facing)
		lastCreatedUnit = CreateCorpse(whichPlayer, unitid, loc[1], loc[2], facing)
		SetUnitBlendTime(lastCreatedUnit, 0)
		
		if (style == bj_CORPSETYPE_FLESH) then
			SetUnitAnimation(lastCreatedUnit, 'decay flesh')
			GroupAddUnit(bj_suspendDecayFleshGroup, lastCreatedUnit)
		elseif (style == bj_CORPSETYPE_BONE) then
			SetUnitAnimation(lastCreatedUnit, 'decay bone')
			GroupAddUnit(bj_suspendDecayBoneGroup, lastCreatedUnit)
		else
			-- Unknown decay style - treat as skeletal.
			SetUnitAnimation(lastCreatedUnit, 'decay bone')
			GroupAddUnit(bj_suspendDecayBoneGroup, lastCreatedUnit)
		end
		
		TimerStart(bj_delayedSuspendDecayTimer, 0.05, false)
		return lastCreatedUnit
	end

end
Так как функций очень много, список будет постепенно дополняться.
`
ОЖИДАНИЕ РЕКЛАМЫ...

Показан только небольшой набор комментариев вокруг указанного. Перейти к актуальным.
0
29
5 лет назад
Отредактирован nazarpunk
0
Может, благодаря тому, что в lua есть функциональное программирование?
Может и по этому))
Всё же ты часть нативок превращаешь в код, что выполняется на виртуальной машине.
Но и часть BJ будет переписана, надеюсь в итоге будет плюс.
Create Units Facing Point
А в чём тут разница?
Разница с чем?
Неверное название статьи. Не удаляем, а предотвращаем их создание.
Исправил.
Передачу nil потерял, не?
Если не передавать аргумент, то функция примет nil, незачем лишний раз писать.
0
28
5 лет назад
Отредактирован PT153
0
Разница с чем?
Ты просто переписал код на JASS2 на Lua, функции же идентичны по что. Нужно переделать AngleBetweenPoints(), а CreateNUnitsAtLocFacingLocBJ() не изменять, при вызове стандартной функции вызовется новая версия AngleBetweenPoints().
Если не передавать аргумент, то функция примет nil, незачем лишний раз писать.
Я так и думал.
Может и по этому))
То предложение странно звучит, JASS2 тоже ЯП, так-то. Но у JASS2 нет функциональщины (как и у многих других ЯП), а в Lua есть.
Но и часть BJ будет переписана, надеюсь в итоге будет плюс.
Я бы не стал пока так писать, потому что это лишь в теории. А для таких утверждений нужна практика.
0
29
5 лет назад
Отредактирован nazarpunk
0
Ты просто переписал код на JASS2 на Lua, функции же идентичны по что.
Копипастил всё подряд, потом уберу лишний вызов функции. PT153:
Нужно переделать AngleBetweenPoints()
Переделал уже
---@param locA table
---@param locB table
---@return real
function AngleBetweenPoints(locA, locB)
	return math.deg(math.atan(locB[2] - locA[2], locB[1] - locA[1]))
end
Я бы не стал пока так писать, потому что это лишь в теории. А для таких утверждений нужна практика.
Добавил волшебное слово "возможно"))
То предложение странно звучит, JASS2 тоже ЯП, так-то. Но у JASS2 нет функциональщины (как и у многих других ЯП), а в Lua есть.
Исправил.
0
28
5 лет назад
Отредактирован PT153
0
NazarPunk, очень хорошо. Как закончишь с локациями, сделай убивание тупых BJ, типа RemoveUnitBJ.
0
29
5 лет назад
0
Как закончишь с локациями, сделай убивание тупых BJ
Обязательно, одну уже переписал и заинлайнил функции, чтоб лишний раз не вызывать)
function CreateNUnitsAtLocFacingLocBJ(count, unitId, whichPlayer, loc, lookAt)
	GroupClear(lastCreatedGroup)
	local face = math.deg(math.atan(lookAt[2] - loc[2], lookAt[1] - loc[1]))
	for i = 1, count do
		lastCreatedUnit = CreateUnit(whichPlayer, unitId, loc[1], loc[2], face)
		GroupAddUnit(lastCreatedGroup, lastCreatedUnit)
	end
	return lastCreatedGroup
end
1
27
5 лет назад
1
Сколько можно годноту постить? Где бесполезные ресурсы?
0
24
5 лет назад
0
Красота! Работы здесь еще целая гора, конечно, до момента когда любой гуи код не будет ломаться при добавлении этой либы, но идея отличная.
1
29
5 лет назад
1
Работы здесь еще целая гора, конечно, до момента когда любой гуи код не будет ломаться при добавлении этой либы
В идеале конечно, насобирать базовых приёмов гуишников и тестить на них, но опыта промышленного тыкания менюшек у меня нет((
0
7
4 года назад
0
пытался вставить в гуй код выдал ошибкy endblock
0
29
4 года назад
0
пытался вставить в гуй код выдал ошибкy endblock
Ничего не смущает?
Загруженные файлы
0
7
4 года назад
0
NazarPunk:
пытался вставить в гуй код выдал ошибкy endblock
Ничего не смущает?
Загруженные файлы
Показан только небольшой набор комментариев вокруг указанного. Перейти к актуальным.
Чтобы оставить комментарий, пожалуйста, войдите на сайт.