Minimum and maximum stats settings

Twine Version: 2.3.16
Story Format: 2.36.1

I have set up a health stat and a fatigue stat, plus the usual strength, charisma etc stats.

<<set $Health to 100>>
<<set $Fatigue to 0>>

I have figured out how to regen fatigue when you sleep (thanks to How to allocate sleeping hours) @pbparjeter and @souppilouliouma

Tired? Get some sleep. How long do you want to sleep for?
<<link "1 hour">>
	<<minutes_incr 60>>
	<<goto "Room 23">>
	<<set $sleep_words to "one hour">>
	<<set $Fatigue to $Fatigue -= 5>>
	<<set $Health to $Health += 5>>


But what I need now is how to put a limit on how much and how little of a certain stat there can be.

For example, as I currently have it set up, I can sleep and restore fatigue even when my fatigue is back to zero. It continues into negative numbers, which makes no sense.

Also, I would like to have a maximum figure for most of these stats, usually on a scale of 0 to 100.

However, some stats like strength would start with a amximum of X, but be able to be increased through training etc, until it got to Y.

That may be two separate coding efforts, but I assume they would need to be included together so there is no clash of codes. Would I get an error or alert of that happened?

First, you will want to define a min and max in your StoryInit passage. You said you set up a fatigue stat already but make sure it is in your StoryInit passage. You set it to 0 but I am setting the default to 50 for demonstration purposes.

<<set $Fatigue to 50>>
<<set $Fatigue_max to 100>>
<<set $Fatigue_min to 0>>

You can change these at any time simply with a line of code elsewhere in the story, eg.

<<set $Fatigue_max to 120>>

Now define a widget in whichever passage(s) that you have tagged widget. This widget is very simple…it just sets the Fatigue variable back to the min and max whenever it goes over those limits.

<<widget "fatigue_change">>
<<set $Fatigue to $Fatigue += $args[0]>>
<<if $Fatigue gte $Fatigue_max>><<set $Fatigue to $Fatigue_max>>
  <<elseif $Fatigue lte $Fatigue_min>><<set $Fatigue to $Fatigue_min>>

Now in the link you originally posted (or wherever else you need it) change

<<set $Fatigue to $Fatigue -= 5>>


<<fatigue_change -5>>

Note the different way we are writing the number is to confirm to the way that we coded in the line 2 of the widget. Basically we are telling it to add -5 rather than subtract 5 now.

I don’t believe that anyone this will interfere with the order that Sugarcube executes code, but that is always a possibility.

1 Like

As always, it works perfectly. Thank you once again.

1 Like

You can use the Math.clamp() function to achieve the same outcome as the <<if>> and <<elseif>> macro calls in the fatigue_change widget.

The replacement widget code would looks something like the following…

<<widget "fatigue_change">>
    <<set $Fatigue to Math.clamp($Fatigue += $args[0], $Fatigue_min, $Fatigue_max)>>
1 Like