[Ace] The .sort! command within BattleManager.make_action_orders (SOLVED)

Hey all!

So I'm currently looking at the BattleManager module in VX Ace and I've come across a version of the .sort! command that has a block with two variable designations (not sure if that's the right terminology sorry) within it.

You can see it in the last line here:

Ruby:
  #--------------------------------------------------------------------------
  # * Create Action Order
  #--------------------------------------------------------------------------
  def self.make_action_orders
    @action_battlers = []
    @action_battlers += $game_party.members unless @surprise
    @action_battlers += $game_troop.members unless @preemptive
    @action_battlers.each {|battler| battler.make_speed }
   
    @action_battlers.sort! {|a,b| b.speed - a.speed }        # <-- This line here
   
  end


So, after reading the section in the Help Window about this, I THINK I've got an understanding of it but that understanding also gives rise to more questions if it's true... so I figured I'd just hop on here and see if anyone could help clear this up for me 🙂.

=====================================================================================

The Questions
(These questions are treated as case questions, as I'm not entirely sure which case is actually true and they can't all be true, so if I'm right about one of the cases then please feel free to just answer that case's questions and ignore the others)

Is it the case that:
This line assigns both the designation "a" AND "b" to EACH item within the Array?
-
If that's the case, then is "b.speed - a.speed" the same as "battler speed - action speed" ?
If that's true, then how is it assigning b the value of battler speed and how is it assigning a the value of action speed?

-

Or is it the case that:
This line assigns designation "a" to the first item in the Array and then designation "b" to the second item in the Array?
Repeating this for items "3 and 4" and "5 and 6" and so on and so forth?
-
If that's the case, then is it determining action order based on the speed value the battler has - the speed value the next battler has and so on and so forth until each battler's speed has been compared to the others'?
-

Or is it the case that:
This line works completely differently to these two possible understandings of it and I've been looking at this all wrong?

--

Thanks for any help.
Sorry for the nooby questions, but we all gotta learn sometime right?
Both a and b are battlers meaning they can be either Actors or Enemies.

Plus how could they be different things? You wouldn't be able to compare and sort them because there wouldn't be a guarantee that the other thing had the speed method. So if it didn't crash right away is because they have the same method in common at least.

Keep in mind the @action_battlers array has a certain kind of members, sort only works on its current members, it won't assign any new ones on its own because sort and sort! can't do that.

Be careful, sort! is destructive by nature. If the original positions of its elements was the same as the final one, it will return nil instead of its original contents. In this specific case that was essentially unlikely so there it wasn't dangerous at all.
Both a and b are battlers meaning they can be either Actors or Enemies.
Plus how could they be different things? You wouldn't be able to compare and sort them because there wouldn't be a guarantee that the other thing had the speed method. So if it didn't crash right away is because they have the same method in common at least.
I get that they're both battlers and know already that that includes enemies AND allies (actors), the thing I was confused on is what the |a,b| block is doing.

Like, say you have an array of 4 battlers.
Is battler 1 then a and b?
Or is battler 1 a while battler 2 is b?

And then the minusing from eachother bit confused me because I was under the impression that if a and b are both battler 1, then they'd be the same value, but if they're for battler 1 and 2 respectively, then why is it written b.speed - a.speed? Wouldn't that lead to a bunch of "a"s left who have only been compared to "b"s but not to other "a"s (thus the array wouldn't get a proper sorting of every battler within itself)?

----

I had a thought after posting this, that maybe I've read the method wrong and it's not about how the actions play out in the turn phase, but is maybe about the input phase instead?

But I haven't come back to the method yet so I haven't had a chance to test that.

----

- Edit-
If it helps, here are my notes on this part of the BattleManager module's make_action_order method:
Ruby:
  #--------------------------------------------------------------------------
  # * Create Action Order
  #--------------------------------------------------------------------------
  def self.make_action_orders
    @action_battlers = []
      # Initially set up as one of the module's "member variables"
      # when set up it also was given the same value of empty array ( "= []" )
    @action_battlers += $game_party.members unless @surprise
      # add the amount of game_party members to the array unless surprised
    @action_battlers += $game_troop.members unless @preemptive
      # add the amount of game_troop members to the array unless preemptive
    @action_battlers.each {|battler| battler.make_speed }
      # for each battler in battlers, battler speed becomes = to action speed
      # (this is linked to the make_speed method)
      
    @action_battlers.sort! {|a,b| b.speed - a.speed }
      # somehow sorts the battlers actions by speed, update this later
      
  end
I can't tell you, it depends on where and when you ask the sort! method that question. 😛

Really, since they're temporary, they keep changing so what was 1 once might return later on as 5 or so. Usually sort methods might need to compare any of its elements more than once.

Let's do it ourselves.

Code:
array = [1,4,6,2]
array[1] - array[0]
#=> Returns 3
array[0], array[1] = array[1], array[0]
print array
#=>Returns [4,1,6,2]

Normally you'd use a comparison operator instead of a subtraction... so you'd usually find some > or < operator.
If you only run this test once, you won't end up with 6 at the beginning of your array so you keep running it till it finally ends up there.

In case you where thinking... but I've tested all four values already and 6 isn't the first element, yet.

Yeap, you're right so you got no other choice but running the test over and over again. 😛

EDIT

The input phase is over by the time the script calls make_action_orders.
It's a complex matter to explain, but let me try.

This line assigns both the designation "a" AND "b" to EACH item within the Array?
Not EACH item. Since 'sort' is comparing between the two. 'a' means one of the items in the array, and 'b' is the next item. Comparing the two items and sort based on that. How does that work internally is a mystery, however, you don't need to know that.

If that's the case, then is "b.speed - a.speed" the same as "battler speed - action speed" ?
No, it's both battler.speed

If that's true, then how is it assigning b the value of battler speed and how is it assigning a the value of action speed?
Well, both are battler.speed, so...

This line assigns designation "a" to the first item in the Array and then designation "b" to the second item in the Array?
Repeating this for items "3 and 4" and "5 and 6" and so on and so forth?
It may not necessarily in that sequence, it just comparing two items. Again, how that work is a mystery. But, what you need to know is if the result is more than 0 or less than 0, it will be sorted accordingly.

If that's the case, then is it determining action order based on the speed value the battler has - the speed value the next battler has and so on and so forth until each battler's speed has been compared to the others'?
Yes, it's essentially sorting the battler.

And then the minusing from eachother bit confused me because I was under the impression that if a and b are both battler 1, then they'd be the same value, but if they're for battler 1 and 2 respectively, then why is it written b.speed - a.speed? Wouldn't that lead to a bunch of "a"s left who have only been compared to "b"s but not to other "a"s (thus the array wouldn't get a proper sorting of every battler within itself)?
Let's put an example
Battler A has speed = 50
Battler B has speed = 100

B's speed - A's speed = 50
It's more than 0
B will be placed earlier in the array.

IF this was the case
Battler A has speed = 100
Battler B has speed = 50

B's speed - A's speed = -50
It's less than 0
B will be placed later in the array.
A will be placed earlier in the array.
It's a complex matter to explain, but let me try.


Not EACH item. Since 'sort' is comparing between the two. 'a' means one of the items in the array, and 'b' is the next item. Comparing the two items and sort based on that. How does that work internally is a mystery, however, you don't need to know that.


No, it's both battler.speed


Well, both are battler.speed, so...


It may not necessarily in that sequence, it just comparing two items. Again, how that work is a mystery. But, what you need to know is if the result is more than 0 or less than 0, it will be sorted accordingly.


Yes, it's essentially sorting the battler.

Rightio, so it's partially the second case I thought it could be but partially not as well then...

Let's put an example
Battler A has speed = 50
Battler B has speed = 100

B's speed - A's speed = 50
It's more than 0
B will be placed earlier in the array.

IF this was the case
Battler A has speed = 100
Battler B has speed = 50

B's speed - A's speed = -50
It's less than 0
B will be placed later in the array.
A will be placed earlier in the array.


So, let's say we have an array of 4 battlers.
We'll say they get added to the array as Battler 1, Battler 2, Battler 3 and Battler 4.

Does that little |a,b| block make it so:

Through the behind-the-scenes/invisible workings of RGSS3, each one of those Battlers has a turn being assigned "a" and compared to each of the other three Battlers while those ones are assigned "b".

So, Battler 1("a") is compared to Battler 2("b"), then compared to Battler 3("b") and then Battler 4("b")
Then, Battler 2("a") is compared to Battler 1("b") then compared to Battler 3("b") and then Battler 4("b")

And the same is then obviously done for Battler 3 as "a" and Battler 4 as "a".


So, by the end of it all, presumably each of them has been "a" once and "b" multiple times (to allow for the subtractions to happen).

Resulting in the "eventual" sorting of each of their orders within the Array by high to low speed?

(I put "eventual" in speech marks as the computer still does this incredibly quickly so it's only eventual in terms of step order, rather than actual time-to-completion terms)
If you take a look at my "manual" method to sort an array filled with numbers, you'd notice soon that there's no other way to sort them if you don't pass through the whole array at least twice.

That's why we can't tell how many times the first battler was a or b during comparisons. That step takes place in the CRuby part of Ruby, which is the base of RGSS - any version.

It doesn't really matter when Eric was a or b, it just matters that Eric was compared against Damian or Ralph or the Ghost or the Undead soldier as many times as needed till sort finds out that they are ordered by speed. You can do it by ATK or MAT if you wanna. 😛 Really, you could do it.

I suspect you didn't get the following: a and b are just block variables. Still, I might be wrong and you may have noticed it some time ago.

Outside the sort block, they're invalid and an error would raise. Inside they're the array or hash elements. You could name them tori and wig, item1 and item2, etc. if you wanna. They will NEVER represent anything that doesn't belong to the array or hash.

sort block is different for an "each" one. If using each, you'd usually only need a single block variable to represent an element. That only changes if you're picking each of hash's key value pairs.
Through the behind-the-scenes/invisible workings of RGSS3, each one of those Battlers has a turn being assigned "a" and compared to each of the other three Battlers while those ones are assigned "b".
Yes

So, Battler 1("a") is compared to Battler 2("b"), then compared to Battler 3("b") and then Battler 4("b")
Then, Battler 2("a") is compared to Battler 1("b") then compared to Battler 3("b") and then Battler 4("b")
So, by the end of it all, presumably each of them has been "a" once and "b" multiple times (to allow for the subtractions to happen).
The actual inner working is a mystery. But presumably, that is what exactly happens.

Resulting in the "eventual" sorting of each of their orders within the Array by high to low speed?
Yes.

You could also try this
Go to https://repl.it/ and select Ruby and start your code.
Code:
array = [1,5,3,2,4,5,6,6,2,4,6]
p array.sort {|a,b| a - b}
p array.sort {|a,b| b - a}
And see what will happen.

I personally prefer to use <=> notation.
Code:
a = 10
b = 20
puts a <=> b
puts b <=> a
This is a direct comparison. a <=> b will print -1 because the former is smaller. And b <=> will produce 1 because the former is larger. You could use that in sorting.
Code:
array = [1,5,3,2,4,5,6,6,2,4,6]
p array.sort {|a,b| a <=> b}
p array.sort {|a,b| b <=> a}
And it will produce the same result.
The_Sarah said:
So, by the end of it all, presumably each of them has been "a" once and "b" multiple times (to allow for the subtractions to happen).
TheoAllen said:
The actual inner working is a mystery. But presumably, that is what exactly happens.

Well, take a look at this confusing piece of C code that provides the vital part of sorting an array for you.

Code:
RARRAY_PTR_USE(tmp, ptr, {
            ruby_qsort(ptr, len, sizeof(VALUE),
                       rb_block_given_p()?sort_1:sort_2, &data);

If you provide sort or sort! with a block like in make_actions_order, it will pick the mysterious first sort_1 function. It will later transfer the sorted elements to a temporary array. How many times? Well, the ruby_qsort function doesn't tell us about it. 😛

Yeah, TheoAllen mentioned something I have briefly stated a while ago. Using actual comparison operators like < or > or even the one he picked < = > without spaces, is the normal way to go.

Sort Possible Results
If I ever find the result is 0, both elements are "equal".
If -1, then the left variable is less than the right variable.
if it's 1 or greater, the right variable is greater than the left variable.

Their weird choice of a subtraction is supposed to do the same but not limited to -1, 0 and 1.
Again, it doesn't matter. What matter is if you supply them with -1, or 1, or 0 (means no change), the order will be changed based on that 😛

For fun, you could always do this.
Code:
array = [1,5,3,2,4,5,6,6,2,4,6]
p array.sort {|a,b| rand >= 0.5 ? -1 : 1}
For inefficient shuffle method 😛
How curious, I was telling her she could use external criteria to sort an array's element. Then I come back here to notice you used rand to get an random value as the way to determine their order. 😀

This thread is being closed, due to being solved. If for some reason you would like this thread re-opened, please report this post and leave a message why. Thank you.

Original thread: https://forums.rpgmakerweb.com/threads/ace-the-sort-command-within-battlemanager-make_action_orders-solved.125625/