Current time: 23.03.2024, 12:42 Hello There, Guest! (LoginRegister)
Language: english | russian  

Post Reply 
Threaded Mode | Linear Mode
Школа ERM 2
» ERM 2.0 для ERA III
Author Message
SergOz Offline

Posts: 1285
Post: #196

daemon_n, будет сделано! 135
Я видел "Array" в changelog сразу как оно появилось и, бегло прочитав, понял что крутая штука, но всё не доберусь разобраться досконально. Видать ещё петух в жо не прижало сильно. Да и время...
Кстати, никто не знает: при помощи ERM можно растянуть время? Tease


Карта-мод "Война на Холсте"
02.07.2021 13:06
Find all posts by this user Quote this message in a reply
Berserker Offline
Administrators

Posts: 16449
Post: #197

Отряды совершают по два действия в ход.
Требования: Эра 3.8.5.
Не учитывается только мораль. Учитываются типы действий и тактическая фаза.



Скачать Герои 3 Эра и всё, что с ней связано / ERA 2.46f для старых модов
Поддержать проект
22.07.2021 23:26
Find all posts by this user Quote this message in a reply
Archer30 Offline
Moderators

Posts: 1098
Post: #198

A question of naming global vars (i^^ and s^^).

I notice that using the same name for global integer and string vars works in ERA, for example,
i^trainer_hero^ = 153
s^trainer_hero^ = Mutare Drake

Both work correctly in the game.
The question is, is this a good practice?


Latest ERA mods and scripts in development - My GitHub
15.10.2021 14:01
Find all posts by this user Quote this message in a reply
daemon_n Offline
Administrators

Posts: 4333
Post: #199

Archer30, assotiave wars - same as SN:W^trainer_hero^ (keeps int and string);


Image: widget.png?style=banner2

Новейший Heroes 3 Launcher
15.10.2021 14:26
Visit this user's website Find all posts by this user Quote this message in a reply
Berserker Offline
Administrators

Posts: 16449
Post: #200

Archer30, good question. Normally it's not good practice, because name of variable should reflect its contents and possibly type.

trainer_hero_id is better then trainer_hero, but without id the "id" is assumed.
trainer_hero_name is better then trainer_hero.


Скачать Герои 3 Эра и всё, что с ней связано / ERA 2.46f для старых модов
Поддержать проект
15.10.2021 18:55
Find all posts by this user Quote this message in a reply
Archer30 Offline
Moderators

Posts: 1098
Post: #201

Berserker, thanks for the good answer!


Latest ERA mods and scripts in development - My GitHub
15.10.2021 19:29
Find all posts by this user Quote this message in a reply
Archer30 Offline
Moderators

Posts: 1098
Post: #202

Hi! I'd like to have some feedback about preference in erm writing.

So daemon_n and I wrote different codes for the same feature - look for a hero with no owner/not in tavern and not on the map.

Here's daemon_n's:

And here's Archer30's:

My question is, which is prefered, in terms of efficiency and readableness, or any other criteria?
The main difference is the use of co vs if/en. I believe if/en is better in readableness. But is this true?
Any thought on the code is welcome, thanks! Ab


Latest ERA mods and scripts in development - My GitHub
(This post was last modified: 13.12.2021 05:42 by Archer30.)
04.12.2021 22:14
Find all posts by this user Quote this message in a reply
Berserker Offline
Administrators

Posts: 16449
Post: #203

Nice prograss in coding, guys. I'm really happy, that we have two more talanted programmers 132

The first rule in programming is "Premature optimization is evil".
The second one: "Optimize only after profiling".

Profiling is calling !!FU(GetTimeMsec), then repeating some function many times, then calling GetTimeMsec once again and display the difference.

In really important code places evaluating billions of times and in LuaJit/C++ language goto/continue could increase performance a bit, but the second version has better maintainability.
Maintainability is really important.

Generic rules are:

-) Prefer IF block over goto/continue/break if possible, unless it's "FAST EXIT" pattern like:

IF something THEN RETURN
IF something THEN RETURN
...
ok, main logics

...or unless it's really simple iteration with simple exit condition.

-) Loops without breaks can be extended without effort.
!!br&(hero)=(tavernHero); is simulation of WHILE (complex condition) DO, which is ok.

It's generic linear search pattern:

while (position is before end AND current item does not match) do
    increase position
end

if (position is < end) then
    something was found
else
    nothing was found
end

----------------------

In daemon_n's variant I would replace

    !!co|(x)>=0/(y)>=0/(z)>=0;
    !!br;

with

IF x < 0 OR x < 0 OR z < 0 THEN
    BREAK
END

Too many breaks/gotos/continue complicate the logics and increase mental efforts to undestand code flow.
It's also nice to separate commented lines with empty lines.

Code:
!!VR(heroAvailable:y):S(TRUE);
; Check if Hourglass of Asmodeus is enabled to decide whether include Xeron to the list
!!UN:P106/?(asmodeusOn:y)

=>
Code:
!!VR(heroAvailable:y):S(TRUE);

; Check if Hourglass of Asmodeus is enabled to decide whether include Xeron to the list
!!UN:P106/?(asmodeusOn:y)


Скачать Герои 3 Эра и всё, что с ней связано / ERA 2.46f для старых модов
Поддержать проект
05.12.2021 04:03
Find all posts by this user Quote this message in a reply
daemon_n Offline
Administrators

Posts: 4333
Post: #204

Berserker, спасибо за ревью)

P.S.: то есть сперва ты добавляешь re i/co/br, чтобы всё было как у людей, а теперь говоришь, что это плохо?96-copy
Признаться, я слегка в замешательстве102


Image: widget.png?style=banner2

Новейший Heroes 3 Launcher
05.12.2021 09:11
Visit this user's website Find all posts by this user Quote this message in a reply
wessonsm Offline

Posts: 779
Post: #205

daemon_n, циклы должны заканчиваться естественныы образом, а не через co/br.
Как ни крути, это костыль, а Берс не любит костылей.

А добавлено для некоторых исключительных случаев.
(This post was last modified: 05.12.2021 11:22 by wessonsm.)
05.12.2021 11:21
Find all posts by this user Quote this message in a reply
daemon_n Offline
Administrators

Posts: 4333
Post: #206

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


Image: widget.png?style=banner2

Новейший Heroes 3 Launcher
05.12.2021 11:30
Visit this user's website Find all posts by this user Quote this message in a reply
Berserker Offline
Administrators

Posts: 16449
Post: #207

daemon_n, ЕРМ не позволяет писать сложные условия в циклах. В других ЯП их писать можно, либо даже выделить условие в функцию.
Если условие не написать, то WHILE (...) DO эмулируется через

!!re ...

получить данные
!!br&...

!!co по возможности лучше заменить на

!!IF обратное условие THEN
    ...
END

Просто логика чище. И всегда можно добавить ELSE и дописать что-то после IF/ELSE, что на любом шаге цикла должно быть выполнено.
С Луа скриптами уже работаю, но сроки пока размыты.


Скачать Герои 3 Эра и всё, что с ней связано / ERA 2.46f для старых модов
Поддержать проект
05.12.2021 12:52
Find all posts by this user Quote this message in a reply
daemon_n Offline
Administrators

Posts: 4333
Post: #208

Berserker, в общем, вместо !!co ты предлагаешь охапку !!if/en, вложенных друг в друга?
Я без претензий - уточняю толькоYes


Image: widget.png?style=banner2

Новейший Heroes 3 Launcher
05.12.2021 12:54
Visit this user's website Find all posts by this user Quote this message in a reply
SergOz Offline

Posts: 1285
Post: #209

(05.12.2021 11:21)wessonsm Wrote:  циклы должны заканчиваться естественным образом, а не через co/br.
Как ни крути, это костыль, а Берс не любит костылей.
А добавлено для некоторых исключительных случаев.
(05.12.2021 12:54)daemon_n Wrote:  Berserker, в общем, вместо !!co ты предлагаешь охапку !!if/en, вложенных друг в друга?
Меня очень смутило определение !!co как костыль 113
Оправданным ли будет применение !!co в циклах !!re с большим количеством шагов и множеством последующих !!if ... !!en ?
Например, цикл по всем героям, с множеством проверок и, как следствие, множеством !!if& ... !!en, где сразу после !!re идёт проверка на присутствие героя на карте и последующем !!co, если его нет.

P.S. Всегда считал что !!co ускоряет действие циклов


Карта-мод "Война на Холсте"
(This post was last modified: 05.12.2021 13:21 by SergOz.)
05.12.2021 13:19
Find all posts by this user Quote this message in a reply
Berserker Offline
Administrators

Posts: 16449
Post: #210

daemon_n, как правило, да. Но есть два способа не давать коду вложенных проверок и циклов расти вглубь:

1) Вариант, который я использую, хотя кое-где в литературе и критикуется. Переменная-флаг вида result, isOk.

result = вычисляем условие

if result then
   ...
    result = вычисляем новое условие для продолжения
end

if result then
   ...
   result = вычисляем новое условие для продолжения
end

Так код сохраняет линейный вид.

Альтернатива — приём быстрого выхода/отсечения. Тут обычный break/continue

!!co&условие

!!co&условие

основная работа

Прыжки во внешние циклы можно аккуратно использовать, но это уже оптимизация. Читать тяжелее, дописывать код сложнее.

-----------------

Quote:P.S. Всегда считал что !!co ускоряет действие циклов
Это микрооптимизация.


Скачать Герои 3 Эра и всё, что с ней связано / ERA 2.46f для старых модов
Поддержать проект
05.12.2021 19:45
Find all posts by this user Quote this message in a reply
« Next Oldest | Next Newest »
Post Reply 


Forum Jump:

Powered by MyBB Copyright © 2002-2024 MyBB Group