0 votes
by (130 points)

I'm quite new to Sugarcube and Twine in general and I'm currently working on my first proper project. It's a fantasy sports-based game in which the player generates random characters, makes a team and competes with other randomly generated teams.

Everything thus far has been fantastic and I'm really enjoying using Sugarcube, however the one thing that I haven't been able to figure out  is making a rankings table that will show: the name of a team, the points that each team has and for it to sort them based on the points total (highest to lowest).

I've tried creating an array that consists of things like <<set $scores to ["$team1score", "$team2score", "$team3score"... etc and then <<print $scores.sort()>> but the issue with that is that it doesn't always seem to display them in the correct order nor does that show the name of the team against it which is ideally something that I'd like for it to do. The only other way that I've thought of doing it would be through hundered of <<if>> statements in order to sort them all based on gt, gte, lt operators however that seems excessive and surely there must be an easier way.

Any help in this would be greatly appreciated.


1 Answer

+1 vote
by (159k points)

There are a number of ways you can solve your problem, the following solution is one of them.

1. You can a JavaScript Array to store all the information about your teams.

/* Initialise the Array used to store information about each team. */
<<set $teams to []>>

2. You can use a JavaScript Generic Object to store multiple facts about each team within the array.

/* Add the first team to the Array. */
<<run $teams.push({
	name: "Team 1",
	score: 10
/* Add the second team to the Array. */
<<run $teams.push({
	name: "Team 2",
	score: 13
/* Add the third team to the Array. */
<<run $teams.push({
	name: "Team 3",
	score: 7

3. You can use the JavaScript Array.sort() function to order the teams within the array based on each team's score value.

<<run $teams.sort(function (a, b) {
	return a.score - b.score;

4. You can use the range variation of the <<for>> macro to loop through each of the teams within the sorted array, so you can built a HTML table structure to display each team's information.

<<for _team range $teams>>
	<tr><td>_team.name</td><td style="text-align: right;">_team.score</td></tr>


by (130 points)
This is perfect, thank you!

It does exactly what I was hoping for it to do.