Как сделать это на gui.С переменными понятно,но как дальше?
Local integer i = случайное число от 1 до 3
Local integer h = случайное число от 1 до 3
Local integer j = 0
Local integer k = взять кол-во юнитов в области locations[h]
Local location p
If k < 1 then
Set p = GetRectCenter( locations[h] )
Call createUnitAtLoc( buildings[i], player(0), p )
Loop
Exitwhen j > 3
Call createUnitAtLoc( units[i], player(0), p )
Set j = j + 1
Endloop
Call removeLocation(p)
Set p = null
Endif

Sumert, хорошая идея

код

native UnitAlive takes unit id returns boolean

function CountAliveUnitsInGroupEnum takes nothing returns nothing
    if UnitAlive(GetEnumUnit()) then
        set bj_groupCountUnits = bj_groupCountUnits + 1
    endif
endfunction

function CreateUnitsForPlayer takes player p returns nothing
    local integer first = 1 //первый элемент массива
    local integer last = 3 //последний элемент
    local integer random = GetRandomInt(first, last) //случайное число от первого элемента до последнего, т.е. от 1 до 3

    local integer units_index = GetRandomInt(1, 3) //случайное число от 1 до 3

    local group g = CreateGroup() //создаем группу

    local integer i = random //счетчик цикла
    loop
        call GroupEnumUnitsInRect(g, udg_locations[i], null) //добавляем в группу всех юнитов из области
        set bj_groupCountUnits = 0 //обнуляем счетчик
        call ForGroup(g, function CountAliveUnitsInGroupEnum) // считаем юнитов в группе

        if bj_groupCountUnits == 0 then //проверяем сколько вышло
            call CreateUnit(p, udg_buildings[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 270.)

            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)

            exitwhen true
        else // если юнитов больше 0, тогда
            call GroupClear(g) // очищаем группу
        endif

        set i = i + 1
        if i > last then
            set i = first
        endif
        
        exitwhen i == random
    endloop

    //избавляемся от утечек
    call GroupClear(g)
    call DestroyGroup(g)
    set g = null
endfunction
Загруженные файлы
`
ОЖИДАНИЕ РЕКЛАМЫ...

Показан только небольшой набор комментариев вокруг указанного. Перейти к актуальным.
6
Выбери custom scripts и копируй по одной строчке.
\\Ошибки
  1. Если я правильно понял, переменные locations и bildings - глобальные. Если так, то их надо писать "udg_locations" (без кавычек, конечно же).
  2. "local" пиши с маленькой буквы. "Local" не равно "local". Другими словами, у тебя выдаст ошибку и не запустится. Тоже самое относится к "call", "set", "if" и другим служебным словам. Пиши с маленькой буквы. Иначе везде выдаст ошибку. И внимательно посмотри, как пишутся стандартные функции. Ты пишешь "createUnitAtLoc", а правильно "CreateUnitAtLoc". Там, где маленькая буква, выдаст ошибку. Будь внимателен. (Для справки, правильно "RemoveLocation")
  3. По сути твоя переменная h имеет фиксированное значение и используется один раз. Можно её убрать и написать "set p = GetRectCenter( locations[GetRandomInt(1,3)] )". Это не ошибка, но так меньше строчек. Объявляют фиксированные переменные обычно тогда, когда она используется в коде несколько раз (твоя переменная i тому пример), а на один разок - слишком много чести.
  4. Последние две строчки поменяй местами. Могу тут ошибаться, но переменные, типо локации надо обнулять, даже если ты её ничему не присвоил.
25
я ему это с телефона писал, баловаться правописанием желания небыло.
мне кажется зайти на какой-нибудь sourceforge и посмотреть как правильно функции пишутся не тяжело.
Sumert:
переменные, типо локации надо обнулять, даже если ты её ничему не присвоил.
ты предлагаешь нулю присваивать нуль?
doctal, как советует Sumert, юзай "custom script" в GUI и вписывай туда мой код (каждую строку в новую функцию "custom scrip").
local integer i = GetRandomInt(1,3)
local integer h = GetRandomInt(1,3)
local integer j = 0
local location p
local group g = GetUnitsInRectAll( udg_locations[h] )
if (CountUnitsInGroup(g) < 1) then
set p = GetRectCenter( udg_locations[h] )
call CreateUnitAtLoc( Player(0), udg_buildings[i], p, 270 )
loop
exitwhen j > 3
call CreateUnitAtLoc( Player(0), udg_units[i], p, 270 )
set j = j + 1
endloop
call RemoveLocation(p)
set p = null
endif
call DestroyGroup(g)
set g = null
отвлекли, забыл пояснения дописать.
при создании юнитов впиши нужного игрока (для которого они создаются)
также я использовал переменные udg_locations, udg_buildings и udg_units - это твои массивы регионов, зданий и юнитов соответственно.
7
doctal:
Sergey105, у меня создаются войска в одной из 3х областей.Но если в этой области есть юнит,то в этой области ничего не создаётся.Так как переменная рандомное число,допустим 3,то юниты пытаются создаться в области 3(на которой юниты уже созданы),а я хочу что бы другие юниты создались либо в области 1,либо в области 2,а третие в той области что осталась.
поправил немного код
local integer first = 1 //первый элемент массива
local integer last = 3 //последний элемент
local integer h = GetRandomInt(first, last) //случайное число от первого элемента до последнего, т.е. от 1 до 3

local integer i = GetRandomInt(1, 3) //случайное число от 1 до 3

local group g = CreateGroup() //создаем группу

loop
	exitwhen last < first

	call GroupEnumUnitsInRect(g, locations[h], null) //добавляем в группу всех юнитов из области
    set bj_groupCountUnits = 0 //обнуляем счетчик
    call ForGroup(g, function CountUnitsInGroupEnum) // считаем юнитов в группе

	if bj_groupCountUnits == 0 then //проверяем сколько вышло
		call CreateUnit(Player(0), buildings[i], GetRectCenterX(locations[h]), GetRectCenterY(locations[h]), 270.)

		call CreateUnit(Player(0), units[i], GetRectCenterX(locations[h]), GetRectCenterY(locations[h]), 0.)
		call CreateUnit(Player(0), units[i], GetRectCenterX(locations[h]), GetRectCenterY(locations[h]), 0.)
		call CreateUnit(Player(0), units[i], GetRectCenterX(locations[h]), GetRectCenterY(locations[h]), 0.)
		call CreateUnit(Player(0), units[i], GetRectCenterX(locations[h]), GetRectCenterY(locations[h]), 0.)

		exitwhen true
	else // если юнитов больше 0, тогда
		call GroupClear(g) // очищаем группу
	endif

	set last = last - 1
endloop

//избавляемся от утечек
call GroupClear(g)
call DestroyGroup(g)
set g = null
21
Sergey105:
Я так и не понял что конкретно ты хочешь сделать ?
Короче он увидел спелл, не понимает jass и хочет тупо повторить, сие Творение на триггерах.
7
решил чутка размять пальцы и накатал пример
Код
function CreateUnitsForPlayer takes player p returns nothing
    local integer first = 1 //первый элемент массива
    local integer last = 3 //последний элемент
    local integer random = GetRandomInt(first, last) //случайное число от первого элемента до последнего, т.е. от 1 до 3

    local integer units_index = GetRandomInt(1, 3) //случайное число от 1 до 3

    local group g = CreateGroup() //создаем группу

    local integer i = random //счетчик цикла
    loop
        call GroupEnumUnitsInRect(g, udg_locations[i], null) //добавляем в группу всех юнитов из области
        set bj_groupCountUnits = 0 //обнуляем счетчик
        call ForGroup(g, function CountUnitsInGroupEnum) // считаем юнитов в группе

        if bj_groupCountUnits == 0 then //проверяем сколько вышло
            call CreateUnit(p, udg_buildings[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 270.)

            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)

            exitwhen true
        else // если юнитов больше 0, тогда
            call GroupClear(g) // очищаем группу
        endif

        set i = i + 1
        if i > last then
            set i = first
        endif
        
        exitwhen i == random
    endloop

    //избавляемся от утечек
    call GroupClear(g)
    call DestroyGroup(g)
    set g = null
endfunction
Как впихнуть код в карту
Для вызова функции используем custom script
call CreateUnitsForPlayer( <здесь должен быть нужный тебе игрок> )
где <здесь должен быть нужный тебе игрок> должна быть функция или переменная, например функция Player(0) - красный игрок, Player(1) - синий и т.д.
Ну и сама наработка

забыл написать, что нужно указать правильные значения вот тут
	local integer first = 1 //первый элемент массива
    local integer last = 3 //последний элемент
если первый элемент locations[1], значит first = 1, если locations[0], то first = 0, аналогично и с последним элементом. Пропускать элементы нельзя, например, locations[1], locations[2], locations[4], locations[5] - пропущен locations[3] элемент.
6
Ige, если уж писать код по-хорошему, надо учесть все, что хочет пользователь. А судя по тому, что хочет автор, надо добавить проверку, когда пикаешь юнитов в группу, что хотя бы один жив.
local integer first = 1 //первый элемент массива
    local integer last = 3 //последний элемент
    local integer random = GetRandomInt(first, last) //случайное число от первого элемента до последнего, т.е. от 1 до 3

    local integer units_index = GetRandomInt(1, 3) //случайное число от 1 до 3
    local integer UnitNumber=4
    local group G = CreateGroup() //создаем группу

    local integer i = random //счетчик цикла
    local unit Ufirst
    local boolean UnitDie=FALSE 
    loop
        call GroupEnumUnitsInRect(G, udg_locations[i], null) //добавляем в группу всех юнитов из области
        loop
             set Ufirst = FirstOfGroup(G)
             exitwhen Ufirst==null
             if GetWidgetLife( Ufirst ) > .405 then
                    set B=TRUE
             endif
             call GroupRemoveUnit(G, Ufirst)
       endloop
       If B==FALSE then 
            call CreateUnit(p, udg_buildings[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 270.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
       endif
       call GroupClear(G)
        set i = i + 1
        if i > last then
            set i = first
        endif
        exitwhen i == random
 endloop
7
Sumert, хорошая идея

код

native UnitAlive takes unit id returns boolean

function CountAliveUnitsInGroupEnum takes nothing returns nothing
    if UnitAlive(GetEnumUnit()) then
        set bj_groupCountUnits = bj_groupCountUnits + 1
    endif
endfunction

function CreateUnitsForPlayer takes player p returns nothing
    local integer first = 1 //первый элемент массива
    local integer last = 3 //последний элемент
    local integer random = GetRandomInt(first, last) //случайное число от первого элемента до последнего, т.е. от 1 до 3

    local integer units_index = GetRandomInt(1, 3) //случайное число от 1 до 3

    local group g = CreateGroup() //создаем группу

    local integer i = random //счетчик цикла
    loop
        call GroupEnumUnitsInRect(g, udg_locations[i], null) //добавляем в группу всех юнитов из области
        set bj_groupCountUnits = 0 //обнуляем счетчик
        call ForGroup(g, function CountAliveUnitsInGroupEnum) // считаем юнитов в группе

        if bj_groupCountUnits == 0 then //проверяем сколько вышло
            call CreateUnit(p, udg_buildings[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 270.)

            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)
            call CreateUnit(p, udg_units[units_index], GetRectCenterX(udg_locations[i]), GetRectCenterY(udg_locations[i]), 0.)

            exitwhen true
        else // если юнитов больше 0, тогда
            call GroupClear(g) // очищаем группу
        endif

        set i = i + 1
        if i > last then
            set i = first
        endif
        
        exitwhen i == random
    endloop

    //избавляемся от утечек
    call GroupClear(g)
    call DestroyGroup(g)
    set g = null
endfunction
Загруженные файлы
Принятый ответ
28
ну нифига себе вы настрочили
а я лишь на пару дней пропал
Ige, а нафига нативку добавлять?
есть же обычная проверка на хп
она намного быстрее и лучше чем эта нативка

автору
короче вопрос закрыт
на будущее
вопросы из разряда "как использовать функцию" или "как печатать на клавиатуре" не принимаются
Показан только небольшой набор комментариев вокруг указанного. Перейти к актуальным.
Чтобы оставить комментарий, пожалуйста, войдите на сайт.