Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sorting object by their properties?

Twine 2.0.11, Sugarcube 1.0.34

As a total code noob, I'm pretty sure I'm in out of my depth with this one, but I thought it wouldn't hurt to ask. Hopefully this makes sense.

In my game, NPCs are associated w/ objects that contain their stats. For instance, I use this for one NPC:
<<set $miko= {
  Name: "Miko",
  HPMax: 80,
  HPNow: 80,
  Wins: 0,
  Losses: 0,
}>>

As the game progresses, these stats change depending on the actions of the player.
Later in the game, I'd like to have story branches that respond to which NPC character has the most wins. Does anyone have any thoughts on the easiest way to do this?
For what its worth, I was looking into putting each relevant NPC's stat into an array and using some kind of sort or compare function. Something like this:
<<set $leaders = [["Miko",$miko.Wins], ["Elle",$elle.Wins], ["You",$player.Wins]]
<<print $leaders.sort(function(a,b){return a[1] - b[1];})>>

Anyone know if I'm barking up the right tree here? Any thoughts?

Comments

  • edited October 2016
    Your basic idea has merit.

    That said, you already have the objects, which include both the name and wins for each character. Adding tuples to your sorting array solely to have the name and wins is somewhat superfluous.

    Also, there's no reason I can think of to use a story variable here—doing so is wasteful as you're bloating the story history.

    I'd suggest using your objects and the setup object. For example:
    <<set
    	setup.leaders to [$miko, $elle, $player]
    		.sort(function (a, b) { return a.Wins - b.Wins; })
    >>
    
    That will sort the array ascending (lowest to highest) wins.


    If you wanted the sort to be descending (highest to lowest), simply reverse the order of the variables in the subtraction. For example:
    <<set
    	setup.leaders to [$miko, $elle, $player]
    		.sort(function (a, b) { return b.Wins - a.Wins; })
    >>
    


    Once that's done, you can do whatever you want to the array—map it all to a particular format, access only one member, etc. For example: (assume a descending sort)
    Leader: <<print setup.leaders[0].Name + " with " + setup.leaders[0].Wins + " wins!">>
    
    Board: <<print setup.leaders.map(function (who) { return who.Name + ": " + who.Wins; })>>
    
  • Fantastic, this is so helpful. Thank you! I have a lot to learn about using arrays, but this clarifies things for me.
Sign In or Register to comment.