[JASS]
как сделать 3 разных действия с одной периодичностью по таймеру?
Алгоритм:
запуск тригера - из чата
остановка тригера - тоже из чата
действие1 через 0.3 сек (итого 0,3)
действие2 через 0.3 сек (итого 0,6)
действие3 через 0.3 сек (итого 0,9)
действие1 через 0.3 сек (итого 1,2)
действие2 через 0.3 сек (итого 1,5)
действие3 через 0.3 сек (итого 1,8)
итд
набросал корявый код, нерабочий конечно:
globals
integer Go=0
integer N=0
endglobals

function Test_Act takes nothing returns nothing
local integer i=GetPlayerId(GetTriggerPlayer())
if ModuloInteger(N,3)==1 then
//0.3
call BJDebugMsg("111 "+I2S(i))
elseif ModuloInteger(N,3)==2 then
//0.6
call BJDebugMsg("222 "+I2S(i))
elseif ModuloInteger(N,3)==3 then
//0.9
call BJDebugMsg("333 "+I2S(i))
endif
set N=N+1
endfunction

function Test_Init takes nothing returns nothing
local integer i=GetPlayerId(GetTriggerPlayer())
local trigger t=CreateTrigger()
local timer time=CreateTimer()
If Go=0 then
set Go=1
call EnableTrigger(t)
else
set Go=0
call DisableTrigger(t)
call PauseTimer(time)
endif
//ver1
call TriggerRegisterTimerEventPeriodic(t, 0.3)
call TriggerAddAction(t, function Test_Act)
//ver2
call TimerStart(time, 0.3, true, function Test_Act)
endfunction

function Event takes nothing returns nothing
local string s=StringCase(GetEventPlayerChatString(),false)
if s=="-t" then
call Test_Init()
endif
endfunction
`
ОЖИДАНИЕ РЕКЛАМЫ...

Показан только небольшой набор комментариев вокруг указанного. Перейти к актуальным.
0
14
1 год назад
Отредактирован host_pi
0
Держи
работает
zinc to jass:
globals
string MyTimerLib___msg="-run"
integer MyTimerLib___i
integer array MyTimerLib___action
timer array MyTimerLib___ticker
boolean array MyTimerLib___running
hashtable MyTimerLib___ht=InitHashtable()
endglobals

function MyTimerLib___anon__1 takes nothing returns nothing
set MyTimerLib___i=LoadInteger(MyTimerLib___ht,GetHandleId(GetExpiredTimer()),0)
set MyTimerLib___action[MyTimerLib___i]=MyTimerLib___action[MyTimerLib___i]+1
call BJDebugMsg("Player: "+I2S(MyTimerLib___i)+", action: "+I2S(MyTimerLib___action[MyTimerLib___i]))
if(MyTimerLib___action[MyTimerLib___i]==2)then
set MyTimerLib___action[MyTimerLib___i]=-1
endif
endfunction

function MyTimerLib___anon__0 takes nothing returns nothing
set MyTimerLib___i=GetPlayerId(GetTriggerPlayer())
if(MyTimerLib___running[MyTimerLib___i])then
call PauseTimer(MyTimerLib___ticker[MyTimerLib___i])
set MyTimerLib___action[MyTimerLib___i]=-1
set MyTimerLib___running[MyTimerLib___i]=false
call BJDebugMsg("Player: "+I2S(MyTimerLib___i)+", stop")
return
endif
set MyTimerLib___running[MyTimerLib___i]=true
call TimerStart(MyTimerLib___ticker[MyTimerLib___i],.3,true,function MyTimerLib___anon__1)
endfunction

function MyTimerLib___onInit takes nothing returns nothing
local trigger t=CreateTrigger()
set MyTimerLib___i=0
loop
exitwhen(MyTimerLib___i>=bj_MAX_PLAYER_SLOTS)
if(GetPlayerController(Player(MyTimerLib___i))==MAP_CONTROL_USER and GetPlayerSlotState(Player(MyTimerLib___i))==PLAYER_SLOT_STATE_PLAYING)then
call TriggerRegisterPlayerChatEvent(t,Player(MyTimerLib___i),MyTimerLib___msg,false)
set MyTimerLib___action[MyTimerLib___i]=-1
set MyTimerLib___running[MyTimerLib___i]=false
set MyTimerLib___ticker[MyTimerLib___i]=CreateTimer()
call SaveInteger(MyTimerLib___ht,GetHandleId(MyTimerLib___ticker[MyTimerLib___i]),0,MyTimerLib___i)
endif
set MyTimerLib___i=MyTimerLib___i+1
endloop
call TriggerAddAction(t,function MyTimerLib___anon__0)
set t=null
endfunction

call ExecuteFunc("MyTimerLib___onInit")
т.е. на глобалках и таймерах подобный код не сделать с отдельным таймером для каждого плеера? (кроме как топорно отдельную функцию под отдельного плеера)
т.е. решить проблему передачи номера игрока внутрь таймера, что ты успешно проделал через HT
1
29
1 год назад
Отредактирован nazarpunk
1
т.е. на глобалках и таймерах подобный код не сделать с отдельным таймером для каждого плеера?
У меня код с отдельным таймером для каждого игрока какраз на глобалках. Можешь проверить через Multiwindow.
Вот здесь идёт получение номера игрока из ХТ. Игрока можно просто получить через Player(i).
Загруженные файлы
0
14
1 год назад
Отредактирован host_pi
0
Можешь проверить через Multiwindow.
проверил конечно
nazarpunk:
Вот здесь идёт получение номера игрока из ХТ.
имелись ввиду глобалки простые типа integer и string
в общем хештейбл я так понял это как словарь (еще и с древовидной child-parent структурой), из которого можно по нужной фразе вытянуть сохранённое значение
в данном случае тянется номер игрока по привязанному к нему id таймера. классное решение
1
29
1 год назад
1
имелись ввиду глобалки простые типа integer и string
Я только одну локалку использовал, всё остальное глобалки.
trigger t = CreateTrigger();
в общем хештейбл я так понял это как словарь
Это и есть хэш-таблица. Для простоты можешь относиться к ней как к к двумерному массиву с числовыми ключами.
ht[0][1] = somevalue;

данном случае тянется номер игрока по привязанному к нему id таймера. классное решение
Сохранение данных на хэндл это основа практически каждого MUI заклинания.
0
14
1 год назад
Отредактирован host_pi
0
накалякал вариант на тригере, таймерные тригеры у игроков также личные
по сути ничем не отличается по исполнению от таймера by nazarpunk
те же самые SaveInteger , LoadInteger
и ничего не оптимизировано, ничего не занулялось в конце функций
globals
integer PLAYERS=12
integer array GO
integer array N
trigger array tgo2
integer array tgo2_init
hashtable ht=InitHashtable()
endglobals

function GOO2_Actions takes nothing returns nothing
local integer i=LoadInteger(ht,GetHandleId(GetTriggeringTrigger()),0)
set N[i]=N[i]+1
if ModuloInteger(N[i],3)==1 then
call BJDebugMsg(I2S(N[i])+" Action 1: "+GetPlayerName(Player(i-1)))
elseif ModuloInteger(N[i],3)==2 then
call BJDebugMsg(I2S(N[i])+" Action 2: "+GetPlayerName(Player(i-1)))
elseif ModuloInteger(N[i],3)==0 then
call BJDebugMsg(I2S(N[i])+" Action 3: "+GetPlayerName(Player(i-1)))
//set N[i]=0
endif
endfunction

function GOO2 takes nothing returns nothing
local integer i=GetPlayerId(GetTriggerPlayer())+1
if tgo2_init[i]==0 then
set tgo2_init[i]=1
set tgo2[i]=CreateTrigger()
call SaveInteger(ht,GetHandleId(tgo2[i]),0,i)
call TriggerRegisterTimerEvent(tgo2[i], 1,true)
call TriggerAddAction(tgo2[i], function GOO2_Actions)
call DisableTrigger(tgo2[i])
endif
if GO[i]==0 then
set GO[i]=1
call EnableTrigger(tgo2[i])
else
set GO[i]=0
set N[i]=0
call DisableTrigger(tgo2[i])
call BJDebugMsg("STOP: "+GetPlayerName(Player(i-1)))
endif
endfunction

function Start takes nothing returns nothing
local string s=StringCase(GetEventPlayerChatString(),false)
elseif s=="-g2" then
call GOO2()
endif
endfunction

function Start_init takes nothing returns nothing
local trigger t=CreateTrigger()
local integer i=1
loop
exitwhen i>PLAYERS
call TriggerRegisterPlayerChatEvent(t,Player(i-1),"-",false)
set i=i+1
endloop
call TriggerAddAction(t,function Start)
endfunction

call Start_init()
1
13
1 год назад
Отредактирован Borodach
1
Я там описал смысл передачи, думал условия уже построиш для своей задачи.
Три варианта
Через цикл всем по таймеру
globals
    constant integer MAX_PLAYER = 12
    timer array TimerStartAction [MAX_PLAYER]
    integer array AnyAction[MAX_PLAYER]
endglobals

function StartAction takes nothing returns nothing
    local integer l = 0
    loop
        exitwhen l >= MAX_PLAYER
            if AnyAction[l] > 0 and AnyAction[l] < 4 then
                if AnyAction[l] == 1 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 1. Start this action by player #"+I2S(l+1))
                elseif AnyAction[l] == 2 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 2. Start this action by player #"+I2S(l+1))
                elseif AnyAction[l] == 3 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 3. Start this action by player #"+I2S(l+1))
                endif
                set AnyAction[l] = AnyAction[l] + 1
            else
                set AnyAction[l] = 0
                call PauseTimer(TimerStartAction[l])
            endif
        set l = l + 1
    endloop
endfunction

function EnterChatMessage takes nothing returns nothing
    local integer pId = GetPlayerId(GetTriggerPlayer())
    call TimerStart(TimerStartAction[pId], 0.3, true, function StartAction)
    set AnyAction[pId] = 1
endfunction

//===========================================================================
function InitTrig_Loop takes nothing returns nothing
    local integer i = 0
    set gg_trg_Loop = CreateTrigger()
    
    loop
        exitwhen i >= MAX_PLAYER
        call TriggerRegisterPlayerChatEvent( gg_trg_Loop, Player(i), "go", true )
        set TimerStartAction[i] = CreateTimer()
        set i = i + 1
    endloop
    call TriggerAddAction(gg_trg_Loop, function EnterChatMessage )
endfunction
Через цикл один таймер
globals
    constant integer MAX_PLAYER1 = 12
    timer TimerStartAction1 = CreateTimer()
    real array PlayerTimeExpiered[MAX_PLAYER1]
endglobals

function StartAction1 takes nothing returns nothing
    local integer l = 0
    loop
        exitwhen l >= MAX_PLAYER1
            if PlayerTimeExpiered[l] >= 0 and PlayerTimeExpiered[l] < 4 then
                if PlayerTimeExpiered[l] == 1 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 1. Start this action by player #"+I2S(l+1))
                elseif PlayerTimeExpiered[l] == 2 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 2. Start this action by player #"+I2S(l+1))
                elseif PlayerTimeExpiered[l] == 3 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 3. Start this action by player #"+I2S(l+1))
                endif
                set PlayerTimeExpiered[l] = PlayerTimeExpiered[l] + 1 //1 = one tick of timer = 0.3 sec
            endif
        set l = l + 1
    endloop
endfunction

function EnterChatMessage1 takes nothing returns nothing
    set PlayerTimeExpiered[GetPlayerId(GetTriggerPlayer())] = 0
endfunction

//===========================================================================
function InitTrig_StaticTimer takes nothing returns nothing
    local integer i = 0
    set gg_trg_StaticTimer = CreateTrigger()
    loop
        exitwhen i >= MAX_PLAYER1
        call TriggerRegisterPlayerChatEvent( gg_trg_StaticTimer, Player(i), "go", true )
        set PlayerTimeExpiered[i] = -1
        set i = i + 1
    endloop
    call TriggerAddAction(gg_trg_StaticTimer, function EnterChatMessage1 )
    
    call TimerStart( TimerStartAction1, 0.3, true, function StartAction1)
endfunction
Через хеш
globals
    constant integer MAX_PLAYER2 = 12
    timer array TimerStartAction2[MAX_PLAYER2]
    integer array ActionID[MAX_PLAYER2]
    hashtable htb = InitHashtable()
endglobals

function StartAction2 takes nothing returns nothing
    local integer l = 0
    local integer pId = LoadInteger(htb, GetHandleId(GetExpiredTimer()), StringHash("StartAction2"))

        if ActionID[pId] == 1 then
            call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 1. Start this action by player #"+I2S(l+1))
        elseif ActionID[pId] == 2 then
            call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 2. Start this action by player #"+I2S(l+1))
        elseif ActionID[pId] == 3 then
            call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 3. Start this action by player #"+I2S(l+1))
            call PauseTimer(GetExpiredTimer())
        endif
        set ActionID[pId] = ActionID[pId] + 1
        
endfunction

function EnterChatMessage2 takes nothing returns nothing
    local integer pId = GetPlayerId(GetTriggerPlayer())
    set ActionID[pId] = 1
    call SaveInteger(htb, GetHandleId(TimerStartAction2[pId]), StringHash("StartAction2"), pId)
    call TimerStart(TimerStartAction2[pId], 0.3, true, function StartAction2)
endfunction

//===========================================================================
function InitTrig_SaveHandle takes nothing returns nothing
    local integer i = 0
    set gg_trg_SaveHandle = CreateTrigger()
    loop
        exitwhen i >= MAX_PLAYER2
        call TriggerRegisterPlayerChatEvent( gg_trg_SaveHandle, Player(i), "go", true )
        set TimerStartAction2[i] = CreateTimer()
        set i = i + 1
    endloop
    call TriggerAddAction(gg_trg_SaveHandle, function EnterChatMessage2 )
endfunction
0
14
1 год назад
0
Три варианта


1й код - Через цикл всем по таймеру
кривокодие:
:3: syntax error
:3: Undefined type MAX_PLAYER
:4: syntax error
:4: Undefined type MAX_PLAYER
:37: Undeclared variable gg_trg_Loop
после починки кривокода видно, что каждый тикающий ускоряет тик всех остальных
это то, с чем я столкнулся в начале этого сообщения
для проверки этого феномена достаточно выставить таймер 5 секунд
и в 3 окнах одновременно отправить go
через 5 секунд у каждого будет по 3 тика, чего не может быть т.к. для трех тиков нужно 15 секунд


2й код - Через цикл один таймер
кривокодие:
:4: syntax error
:4: Undefined type MAX_PLAYER1
:32: Undeclared variable gg_trg_StaticTimer
после починки кривокода работает как и заявлено


3й код - Через хеш
кривокодие:
:3: syntax error
:3: Undefined type MAX_PLAYER2
:4: syntax error
:4: Undefined type MAX_PLAYER2
:34: Undeclared variable gg_trg_SaveHandle
+
надо заменить
I2S(l+1)
на
I2S(pId+1)
после починки кривокода работает как и заявлено
0
14
1 год назад
Отредактирован host_pi
0
я не понял
а чё, так можно было?
на тестах всё прекрасно работает для разных игроков с личным циклом
globals
integer PLAYERS=12
integer array GO
endglobals

function GOO3_Actions takes nothing returns nothing
local integer i=GetPlayerId(GetTriggerPlayer())+1
local integer j=1
loop
exitwhen j>10
if GO[i]==1 then
call BJDebugMsg("111 "+GetPlayerName(Player(i-1)))
call TriggerSleepAction(2)
endif
if GO[i]==1 then
call BJDebugMsg("222 "+GetPlayerName(Player(i-1)))
call TriggerSleepAction(2)
endif
if GO[i]==1 then
call BJDebugMsg("333 "+GetPlayerName(Player(i-1)))
call TriggerSleepAction(2)
endif
set j=j+1
endloop
endfunction

function GOO3 takes nothing returns nothing
local integer i=GetPlayerId(GetTriggerPlayer())+1
if GO[i]==0 then
set GO[i]=1
call GOO3_Actions()
else
set GO[i]=0
endif
endfunction

function Start takes nothing returns nothing
local string s=StringCase(GetEventPlayerChatString(),false)
if s=="-g3" then
call GOO3()
endif
endfunction

function Start_init takes nothing returns nothing
local trigger t=CreateTrigger()
local integer i=1
loop
exitwhen i>PLAYERS
call TriggerRegisterPlayerChatEvent(t,Player(i-1),"-",false)
set i=i+1
endloop
call TriggerAddAction(t,function Start)
endfunction

call Start_init()
и никакие глобалки не нужны
да ещё к тому же прекрасно можно передавать без ХТ переменные внутрь сна, чего нельзя было делать в таймерном и периодически-тригерном решениях
да ещё и логика кода супер простая
требую созвать консилиум по этому вопросу
1
13
1 год назад
Отредактирован Borodach
1
через 5 секунд у каждого будет по 3 тика, чего не может быть т.к. для трех тиков нужно 15 секунд
Не то условие добавил
Через цикл все з таймером
globals
    constant integer MAX_PLAYER = 12
    timer array TimerStartAction [MAX_PLAYER]
    integer array AnyAction[MAX_PLAYER]
endglobals

function StartAction takes nothing returns nothing
    local integer l = 0
    loop
        exitwhen l >= MAX_PLAYER
            if  TimerStartAction[l] == GetExpiredTimer() then
                if AnyAction[l] == 1 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 1. Start this action by player #"+I2S(l+1))
                elseif AnyAction[l] == 2 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 2. Start this action by player #"+I2S(l+1))
                elseif AnyAction[l] == 3 then
                    call DisplayTimedTextToPlayer(Player(l),0,0,20,"Start any action 3. Start this action by player #"+I2S(l+1))
                    set AnyAction[l] = 0
                    call PauseTimer(TimerStartAction[l])
                endif
                set AnyAction[l] = AnyAction[l] + 1
            endif
        set l = l + 1
    endloop
endfunction

function EnterChatMessage takes nothing returns nothing
    local integer pId = GetPlayerId(GetTriggerPlayer())
        call TimerStart(TimerStartAction[pId], 5, true, function StartAction)
        set AnyAction[pId] = 1
endfunction

//===========================================================================
function InitTrig_Loop takes nothing returns nothing
    local integer i = 0
    set gg_trg_Loop = CreateTrigger()
    
    loop
        exitwhen i >= MAX_PLAYER
        call TriggerRegisterPlayerChatEvent( gg_trg_Loop, Player(i), "go", true )
        set TimerStartAction[i] = CreateTimer()
        set i = i + 1
    endloop
    call TriggerAddAction(gg_trg_Loop, function EnterChatMessage )
endfunction
Нужен триггер с названием Loop или создать свой триггер
MAX_PLAYER - Просто константа, в JNGP Rebuild так можно, ошибок не будет
Через call TriggerSleepAction(2) можно, но для сети не рекомендуется. Почитаешь какие последствия могут быть. Для одного игрока тебе будет идеальный вариант
0
29
1 год назад
0
TriggerSleepAction в цикле. Да вы батенька гений.
0
14
1 год назад
Отредактирован host_pi
0
TriggerSleepAction в цикле. Да вы батенька гений.
ну так это можно считать полноценным решением? или тут есть какие-то подводные камни?
TriggerSleepAction(2) для сети не рекомендуется. Почитаешь какие последствия могут быть. Для одного игрока тебе будет идеальный вариант
требуется для сетевой игры конечно же. т.е. он не подходит для сетевой?
есть ссылки на статьи? пошёл погуглить
Не то условие добавил
Через цикл все з таймером
работает, у каждого свой таймер
Показан только небольшой набор комментариев вокруг указанного. Перейти к актуальным.
Чтобы оставить комментарий, пожалуйста, войдите на сайт.