Сейчас 17:35:29 Пятница, 19 апреля, 2024 год
[ x ] Главная ⇒ Форум ⇐ RSS Файлы Cтатьи Картинки В о й т и   или   з а р е г и с т р и р о в а т ь с я


[ Новые сообщения · Участники · Правила форума · Поиск · RSS ]
  • Страница 1 из 1
  • 1
Модератор форума: PUVer, SirNikolas, Ty3uK  
Форум о Warcraft 3 » Раздел для картостроителей » Вопросы по картостроению » Вопрос по коду...
Вопрос по коду...
[DUОS]Дата: Пятница, 03 Декабря 2010, 20:56:58 | Сообщение # 1
Группа: Заблокированные
Сообщений: 6279
Награды: 9
Репутация: 1708
Блокировки:
Я сделал такую систему скрещивания. Можно ли сделать как-то проще?

udg_RuneItem[] - мгновенно юзающийся итем, продаётся в магазинах и лежит на земле.
udg_NormalItem[] - нормальный итем, лежит в инвентаре.
udg_ItemCost[] - стоимость итема (покупка и продажа).

Quote
Для каждого предмета свой номер, по которому можно получить из RuneItem NormalItem, а также ItemCost.

Задача была такая: Сделать систему, такую, чтобы предметы скрещивались с полным инвентарём и проверяли следующие условия:

1. Пуст (есть ли хоть один свободный слот) или полон инвентарь поднимающего предмет героя.
2. Если инвентарь пуст, тогда просто меняем RuneItem на NormalItem.
3. Если инвентарь героя полон, проверить:
- Есть ли рецепт для текущего предмета и куплены ли все компоненты для него (Покупаемый предмет должен быть последним компонентом). Если да, то не выводить ошибку и скомбинировать предметы в целевой рецепт.
- Имеет ли предмет заряды. Если да, то проверить, имеется ли среди предметов героя предмет такого же типа (имеется в виду проверка NormalItem[] == UnitItemInSlot(hero,slot)). Если да, то не выводить ошибку и сложить заряды одного предмета с зарядами другого.

Во всех остальных случаях вывести ошибку и вернуть деньги через переменную ItemCost[] (если предмет покупается).

Общие функции.

Code
function SimError takes player ForPlayer, string msg returns nothing
     local sound s = CreateSoundFromLabel("InterfaceError",false,false,false,10,10)
      
     if GetLocalPlayer() == ForPlayer then
         call ClearTextMessages()
         call DisplayTimedTextToPlayer(ForPlayer,.52,-1.,2.,"|cffffcc00"+msg+"|r")
         call StartSound(s)
         call KillSoundWhenDone(s)
     endif
      
     set s = null
endfunction

function GetUnitItemSlot takes unit hero, integer itemid returns integer
     local integer i = 0
     local item si
      
     loop
         exitwhen i > 5
         set si = UnitItemInSlot(hero,i)
         if GetItemTypeId(si) == itemid then
             set si = null
             return i
         endif
         set i = i + 1
     endloop
      
     set si = null
     return -1     
endfunction

function GetUnitItemOfType takes unit u, integer iid returns item
     local integer index = GetUnitItemSlot(u,iid)
      
     if index == -1 then
         return null
     else
         return UnitItemInSlot(u,index)
     endif
endfunction

function Recipe2 takes unit hero, integer id1, integer id2, integer tid returns nothing
     local integer slot1 = GetUnitItemSlot(hero,id1)
     local integer slot2 = GetUnitItemSlot(hero,id2)
      
     call RemoveItem(UnitItemInSlot(hero,slot1))
     call RemoveItem(UnitItemInSlot(hero,slot2))
      
     if IsUnitAlly(hero,Player(0)) then
         call DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Human\\HolyBolt\\HolyBoltSpecialArt.mdl",hero,"origin"))
     else
         call DestroyEffect(AddSpecialEffectTarget("Objects\\Spawnmodels\\Naga\\NagaDeath\\NagaDeath.mdl",hero,"origin"))
     endif
      
     call UnitAddItemById(hero,tid)
endfunction

function Recipe3 takes unit hero, integer id1, integer id2, integer id3, integer tid returns nothing
     local integer slot1 = GetUnitItemSlot(hero,id1)
     local integer slot2 = GetUnitItemSlot(hero,id2)
     local integer slot3 = GetUnitItemSlot(hero,id3)
      
     call RemoveItem(UnitItemInSlot(hero,slot1))
     call RemoveItem(UnitItemInSlot(hero,slot2))
     call RemoveItem(UnitItemInSlot(hero,slot3))
      
     if IsUnitAlly(hero,Player(0)) then
         call DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Human\\HolyBolt\\HolyBoltSpecialArt.mdl",hero,"origin"))
     else
         call DestroyEffect(AddSpecialEffectTarget("Objects\\Spawnmodels\\Naga\\NagaDeath\\NagaDeath.mdl",hero,"origin"))
     endif
      
     call UnitAddItemById(hero,tid)
endfunction

function Recipe4 takes unit hero, integer id1, integer id2, integer id3, integer id4, integer tid returns nothing
     local integer slot1 = GetUnitItemSlot(hero,id1)
     local integer slot2 = GetUnitItemSlot(hero,id2)
     local integer slot3 = GetUnitItemSlot(hero,id3)
     local integer slot4 = GetUnitItemSlot(hero,id4)
      
     call RemoveItem(UnitItemInSlot(hero,slot1))
     call RemoveItem(UnitItemInSlot(hero,slot2))
     call RemoveItem(UnitItemInSlot(hero,slot3))
     call RemoveItem(UnitItemInSlot(hero,slot4))
      
     if IsUnitAlly(hero,Player(0)) then
         call DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Human\\HolyBolt\\HolyBoltSpecialArt.mdl",hero,"origin"))
     else
         call DestroyEffect(AddSpecialEffectTarget("Objects\\Spawnmodels\\Naga\\NagaDeath\\NagaDeath.mdl",hero,"origin"))
     endif
      
     call UnitAddItemById(hero,tid)
endfunction

function Recipe5 takes unit hero, integer id1, integer id2, integer id3, integer id4, integer id5, integer tid returns nothing
     local integer slot1 = GetUnitItemSlot(hero,id1)
     local integer slot2 = GetUnitItemSlot(hero,id2)
     local integer slot3 = GetUnitItemSlot(hero,id3)
     local integer slot4 = GetUnitItemSlot(hero,id4)
     local integer slot5 = GetUnitItemSlot(hero,id5)
      
     call RemoveItem(UnitItemInSlot(hero,slot1))
     call RemoveItem(UnitItemInSlot(hero,slot2))
     call RemoveItem(UnitItemInSlot(hero,slot3))
     call RemoveItem(UnitItemInSlot(hero,slot4))
     call RemoveItem(UnitItemInSlot(hero,slot5))
      
     if IsUnitAlly(hero,Player(0)) then
         call DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Human\\HolyBolt\\HolyBoltSpecialArt.mdl",hero,"origin"))
     else
         call DestroyEffect(AddSpecialEffectTarget("Objects\\Spawnmodels\\Naga\\NagaDeath\\NagaDeath.mdl",hero,"origin"))
     endif
      
     call UnitAddItemById(hero,tid)
endfunction

function Recipe6 takes unit hero, integer id1, integer id2, integer id3, integer id4, integer id5, integer id6, integer tid returns nothing
     local integer slot1 = GetUnitItemSlot(hero,id1)
     local integer slot2 = GetUnitItemSlot(hero,id2)
     local integer slot3 = GetUnitItemSlot(hero,id3)
     local integer slot4 = GetUnitItemSlot(hero,id4)
     local integer slot5 = GetUnitItemSlot(hero,id5)
     local integer slot6 = GetUnitItemSlot(hero,id6)
      
     call RemoveItem(UnitItemInSlot(hero,slot1))
     call RemoveItem(UnitItemInSlot(hero,slot2))
     call RemoveItem(UnitItemInSlot(hero,slot3))
     call RemoveItem(UnitItemInSlot(hero,slot4))
     call RemoveItem(UnitItemInSlot(hero,slot5))
     call RemoveItem(UnitItemInSlot(hero,slot6))
      
     if IsUnitAlly(hero,Player(0)) then
         call DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Human\\HolyBolt\\HolyBoltSpecialArt.mdl",hero,"origin"))
     else
         call DestroyEffect(AddSpecialEffectTarget("Objects\\Spawnmodels\\Naga\\NagaDeath\\NagaDeath.mdl",hero,"origin"))
     endif
      
     call UnitAddItemById(hero,tid)
endfunction

function UnitHasEmptySlot takes unit u returns boolean
     local integer i = 0
     loop
         exitwhen i > 5
         if UnitItemInSlot(u,i) == null then
             return true
         endif
         set i = i + 1
     endloop
     return false
endfunction

function MakeRecipe takes unit u, integer iid returns item
     return null
endfunction

function RecipeExist takes integer iid returns boolean
     return false
endfunction

function Rune2Normal takes unit hero, item ri, boolean b returns item
     local integer i = 0
      
     loop
         exitwhen i > udg_TotalItems
         if GetItemTypeId(ri) == udg_RuneItem[i] then
          
             if UnitHasEmptySlot(hero) == false then
                  
                 if RecipeExist(udg_NormalItem[i]) then
                     return MakeRecipe(hero,udg_NormalItem[i])
                 elseif GetItemCharges(ri) > 0 and GetUnitItemSlot(hero,udg_NormalItem[i]) > -1 then
                     call SetItemCharges(ri,GetItemCharges(ri) + GetItemCharges(UnitItemInSlot(hero,GetUnitItemSlot(hero,udg_NormalItem[i]))))
                 else
                     call SimError(GetOwningPlayer(hero),"You can't pick this item up.")
                     call SetPlayerState(GetOwningPlayer(hero),PLAYER_STATE_RESOURCE_GOLD,GetPlayerState(GetOwningPlayer(hero),PLAYER_STATE_RESOURCE_GOLD) + udg_ItemCost[i])
                 endif
                  
             else    
                 return UnitAddItemById(hero,udg_NormalItem[i])
             endif
          
         endif
         set i = i + 1
     endloop
endfunction

function Normal2Rune takes item ni, real x, real y returns item
     local integer i = 0
     loop
         exitwhen i > udg_TotalItems
         if udg_NormalItem[i] == GetItemTypeId(ni) then
             return CreateItem(udg_RuneItem[i],x,y)     
         endif         
         set i = i + 1
     endloop
endfunction

function ItemIsRune takes integer itemid returns boolean
     local integer i = 0
     loop
         exitwhen i > udg_TotalItems
         if udg_RuneItem[i] == itemid then
             return true       
         endif         
         set i = i + 1
     endloop
     return false
endfunction

Триггер, ловящий покупку и подбор предметов.

Code
function Trig_Pick_Items_Timer takes nothing returns nothing
     local timer t = GetExpiredTimer()
     local item i = LoadItemHandle(udg_ItemHash,GetHandleId(t),0)
     local item di = CreateItem(GetItemTypeId(i),GetWidgetX(i),GetWidgetY(i)
      
     call SaveBoolean(udg_ItemHash,GetHandleId(di),1,true)
     call SaveInteger(udg_ItemHash,GetHandleId(di),2,LoadInteger(udg_ItemHash,GetHandleId(i),2))
      
     call FlushChildHashtable(udg_ItemHash,GetHandleId(t))
     call DestroyTimer(t)
      
     set i = null
     set t = null
endfunction

function Trig_Pick_Items_Actions takes nothing returns nothing
     local unit u
     local item i
     local item ni
     local real x
     local real y
     local timer t
      
     if GetTriggerEventId() == EVENT_PLAYER_UNIT_PICKUP_ITEM then
         set u = GetManipulatingUnit()
         set i = GetManipulatedItem()   
         set x = GetWidgetX(i)
         set y = GetWidgetY(i)
          
         call SetItemVisible(i,false)
          
         if LoadBoolean(udg_ItemHash,GetHandleId(i),0) == false or LoadBoolean(udg_ItemHash,GetHandleId(i),0) == null then  
          
             if UnitHasEmptySlot(u) == false and RecipeExist(GetItemTypeId(i)) then
                 call SaveBoolean(udg_ItemHash,GetHandleId(Rune2Normal(u,i,true)),0,false)
             elseif GetUnitItemSlot(u,GetItemTypeId(i)) > -1 then    
                 call Rune2Normal(u,i,false)   
             elseif UnitHasEmptySlot(u) == false and RecipeExist(GetItemTypeId(i)) == false then  
                 if LoadBoolean(udg_ItemHash,GetHandleId(i),1) then
                     set t = CreateTimer()
                     call SimError(GetOwningPlayer(u),"You can't pick this item up.")
                     call SaveItemHandle(udg_ItemHash,GetHandleId(t),0,i)
                     call TimerStart(t,.01,false,function Trig_Pick_Items_Timer)
                     set t = null
                 endif      
             else
                 set ni = Rune2Normal(u,i,false)
                 call SetItemCharges(ni,LoadInteger(udg_ItemHash,GetHandleId(i),2))
                 call SaveBoolean(udg_ItemHash,GetHandleId(ni),0,false)  
                 set ni = null
             endif
              
             call SaveBoolean(udg_ItemHash,GetHandleId(i),0,true)
         else
             call SaveBoolean(udg_ItemHash,GetHandleId(i),0,false)
         endif
      
     elseif GetTriggerEventId() == EVENT_PLAYER_UNIT_SELL_ITEM then
         set u = GetBuyingUnit()
         set i = GetSoldItem()
          
         call SetItemVisible(i,false)
          
         if LoadBoolean(udg_ItemHash,GetHandleId(i),0) == false or LoadBoolean(udg_ItemHash,GetHandleId(i),0) == null then
             call SaveBoolean(udg_ItemHash,GetHandleId(Rune2Normal(u,i,true)),1,false)
             call SaveBoolean(udg_ItemHash,GetHandleId(i),0,true)
         else
             call SaveBoolean(udg_ItemHash,GetHandleId(i),0,false)
         endif    
     endif
      
     set i = null
     set u = null
endfunction

//===========================================================================
function InitTrig_Pick_Items takes nothing returns nothing
     set gg_trg_Pick_Items = CreateTrigger()
     call TriggerRegisterAnyUnitEventBJ(gg_trg_Pick_Items,EVENT_PLAYER_UNIT_PICKUP_ITEM)
     call TriggerRegisterAnyUnitEventBJ(gg_trg_Pick_Items,EVENT_PLAYER_UNIT_SELL_ITEM)
     call TriggerAddAction(gg_trg_Pick_Items,function Trig_Pick_Items_Actions)
endfunction

Триггер, контролирующий дропы предметов.

Code
function Trig_Drop_Items_Conditions takes nothing returns boolean
     return ItemIsRune(GetItemTypeId(GetManipulatedItem())) == false
endfunction

function Trig_Drop_Items_Timer takes nothing returns nothing
     local timer t = GetExpiredTimer()
     local item i = LoadItemHandle(udg_ItemHash,GetHandleId(t),0)
     local integer ch = GetItemCharges(i)
     local item it
      
     call SetItemVisible(i,false)
     set it = Normal2Rune(i,GetWidgetX(i),GetWidgetY(i))
     call SaveInteger(udg_ItemHash,GetHandleId(it),2,ch)
     call SetItemCharges(it,ch)
     call SaveBoolean(udg_ItemHash,GetHandleId(it),1,true)

     call BJDebugMsg(I2S(GetItemCharges(it)))
      
     call RemoveItem(i)
      
     call FlushChildHashtable(udg_ItemHash,GetHandleId(t))
     call DestroyTimer(t)
      
     set it = null
     set i = null
     set t = null
endfunction

function Trig_Drop_Items_Actions takes nothing returns nothing
     local item i = GetManipulatedItem()
     local unit u = GetManipulatingUnit()
     local timer t = CreateTimer()
      
     call SaveItemHandle(udg_ItemHash,GetHandleId(t),0,i)
      
     call TimerStart(t,.01,false,function Trig_Drop_Items_Timer)

     set t = null
     set u = null
     set i = null
endfunction

//===========================================================================
function InitTrig_Drop_Items takes nothing returns nothing
     set gg_trg_Drop_Items = CreateTrigger()
     call TriggerRegisterAnyUnitEventBJ(gg_trg_Drop_Items,EVENT_PLAYER_UNIT_DROP_ITEM)
     call TriggerAddCondition(gg_trg_Drop_Items,Condition(function Trig_Drop_Items_Conditions))
     call TriggerAddAction(gg_trg_Drop_Items,function Trig_Drop_Items_Actions)
endfunction

P.S.: Проблема моего кода в том, что если у героя полный инвентарь, подбирается предмет с зарядами, но такой предмет уже есть у героя, предмет не поднимается и заряды не складываются.


НУ И ЧТО ТЕПЕРЬ?


Кликайте на дракошку ;)


Сообщение отредактировал [DUОS] - Пятница, 03 Декабря 2010, 20:58:58
 

lawsonДата: Пятница, 03 Декабря 2010, 21:11:06 | Сообщение # 2
Группа: Проверенные
Сообщений: 3482
Награды: 0
Репутация: 974
Блокировки:
Функция герой поднимает предмет! если предмет являеться частью рецепта то получаешь то что состоит из этого рецепта.

Nic nie wiem bo mam chuj.
редактирую посты! ВСЕ!
 

[DUОS]Дата: Пятница, 03 Декабря 2010, 21:14:40 | Сообщение # 3
Группа: Заблокированные
Сообщений: 6279
Награды: 9
Репутация: 1708
Блокировки:
lawson,
Quote (|DUОS|)
Проблема моего кода в том, что если у героя полный инвентарь, подбирается предмет с зарядами, но такой предмет уже есть у героя, предмет не поднимается и заряды не складываются.

Я тут про заряды вообще-то о_О
И про упрощение.


НУ И ЧТО ТЕПЕРЬ?


Кликайте на дракошку ;)
 

oleg_best_olegДата: Пятница, 03 Декабря 2010, 22:38:50 | Сообщение # 4
Группа: Заблокированные
Сообщений: 1726
Награды: 0
Репутация: 654
Блокировки:
немного не по теме, но скинь триггер складывания зарядов
 

[DUОS]Дата: Пятница, 03 Декабря 2010, 23:12:53 | Сообщение # 5
Группа: Заблокированные
Сообщений: 6279
Награды: 9
Репутация: 1708
Блокировки:
oleg_best_oleg,
Всё есть в этом коде оО
Нормальное сложение стак с этим кодом, но код криво стак :о


НУ И ЧТО ТЕПЕРЬ?


Кликайте на дракошку ;)
 

EdiTTORRДата: Пятница, 03 Декабря 2010, 23:15:17 | Сообщение # 6
8 уровень
Группа: Проверенные
Сообщений: 585
Награды: 0
Репутация: 147
Блокировки:
[DUОS], почему сами триггеры не оптимизировал?

Местами здесь.
 

[DUОS]Дата: Пятница, 03 Декабря 2010, 23:20:32 | Сообщение # 7
Группа: Заблокированные
Сообщений: 6279
Награды: 9
Репутация: 1708
Блокировки:
EdiTTORR,
Wow lol, разве нет? о.о


НУ И ЧТО ТЕПЕРЬ?


Кликайте на дракошку ;)
 

EdiTTORRДата: Пятница, 03 Декабря 2010, 23:26:03 | Сообщение # 8
8 уровень
Группа: Проверенные
Сообщений: 585
Награды: 0
Репутация: 147
Блокировки:
[DUОS], вроде не особо, лишние пробелы, генерированые приставки к функциям, стандартные иниты триггеров... :)

Местами здесь.
 

[DUОS]Дата: Пятница, 03 Декабря 2010, 23:35:12 | Сообщение # 9
Группа: Заблокированные
Сообщений: 6279
Награды: 9
Репутация: 1708
Блокировки:
EdiTTORR,
Ну, таким я обычно занимаюсь по готовности системы.


НУ И ЧТО ТЕПЕРЬ?


Кликайте на дракошку ;)
 

SirNikolasДата: Суббота, 04 Декабря 2010, 13:23:19 | Сообщение # 10
Группа: Модераторы
Сообщений: 6729
Награды: 1
Репутация: 1867
Блокировки:
Quote (|DUOS|)
Code
function MakeRecipe takes unit u, integer iid returns item   
     return null   
endfunction   

function RecipeExist takes integer iid returns boolean   
     return false   
endfunction
Это зачем?
Можно упростить функции Recipe1-5, введя дополнительный глобальный массив.
Code
function Recipe takes unit hero, integer count, integer tid returns item
     local integer i = 1
     loop
         exitwhen i > count
         call RemoveItem(UnitItemInSlot(hero, udg_Slot[i]))
         set i = i + 1
     endloop
     if IsUnitAlly(hero,Player(0)) then   
         call DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Human\\HolyBolt\\HolyBoltSpecialArt.mdl", hero, "origin"))   
     else   
         call DestroyEffect(AddSpecialEffectTarget("Objects\\Spawnmodels\\Naga\\NagaDeath\\NagaDeath.mdl", hero, "chest"))   
     endif         
     return UnitAddItemById(hero,tid)       
endfunction




Сообщение отредактировал SirNikolas - Суббота, 04 Декабря 2010, 17:29:36
 

[DUОS]Дата: Суббота, 04 Декабря 2010, 17:00:50 | Сообщение # 11
Группа: Заблокированные
Сообщений: 6279
Награды: 9
Репутация: 1708
Блокировки:
Quote (SirNikolas)
Это зачем?

Будущие рецептарные циклы)
Quote (SirNikolas)
function Recipe takes unit hero, integer count, integer tid returns item
local integer i = 1
loop
exitwhen i > count
call RemoveItem(UnitItemInSlot(hero, udg_Slot[i]))
endloop
if IsUnitAlly(hero,Player(0)) then
call DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Human\\HolyBolt\\HolyBoltSpecialArt.mdl", hero, "origin"))
else
call DestroyEffect(AddSpecialEffectTarget("Objects\\Spawnmodels\\Naga\\NagaDeath\\NagaDeath.mdl", hero, "chest"))
endif
return UnitAddItemById(hero,tid)
endfunction

А вот если слоты неизвестны? )
Идею понял, попробую развить.


НУ И ЧТО ТЕПЕРЬ?


Кликайте на дракошку ;)
 

Форум о Warcraft 3 » Раздел для картостроителей » Вопросы по картостроению » Вопрос по коду...
  • Страница 1 из 1
  • 1
Поиск:

Copyright © 2006 - 2024 Warcraft3FT.info При копировании материалов c сайта ставьте, пожалуйста, активную обратную ссылку на нас • Design by gReeB04ki ©
Хостинг от uCoz