## Educational => Twine => Topic started by: Chris on February 01, 2013, 02:41:05 PM

Title: Twine hack: random effects
Post by: Chris on February 01, 2013, 02:41:05 PM
Quote
So while messing in twine, I came across a place where I would want a random effect. Me still being relatively new to Twine, I have no idea if Twine is even capable of doing random events.

Say a player is drinking a potion. I want it to be able to give them a random amount of health or have a chance to poison them.

Is there even a way to do that?

Twine can do random events, but the process for doing so involves a bit of Javascript. In practice:

The first thing we need to do is set a random number from 0-2:
Code: [Select]
`<<set \$random = Math.floor(Math.random()*3)>><<print \$random>>`The reasons the syntax looks like this are long and cumbersome (and have a lot to do with Javascript), but just note that by replacing 3 with a different number, we will get that many different options (for example, if we use 10, we will get 10 numbers, 0-9).

And then apply a condition:
Code: [Select]
`<<if \$random == 0>>[[effect one]]<<endif>><<if \$random == 1>>[[effect two]]<<endif>><<if \$random == 2>>[[effect three]]<<endif>>`
This will check which random effect is applied.
Title: Re: Twine hack: random effects
Post by: Chris on February 01, 2013, 02:51:23 PM
Quote
Also, on another note. I was wondering if it was possible if after it picks one option for random to never pick that same option again.

This is a bit trickier - you might need Adventure Cow to do this, rather than Twine, but at the very least, we can simulate some of it. Let's go back to our original example:

Code: [Select]
`<<if \$random == 0>>[[effect one]]<<endif>><<if \$random == 1>>[[effect two]]<<endif>><<if \$random == 2>>[[effect three]]<<endif>>`
Here, we can nullify effects by marking them as "finished." Here's a sample for the page effect one.
Code: [Select]
`::effect one<<set \$effect_one_finished = true>>`
Now we need to hide this effect from showing up again, by changing the original code.

Code: [Select]
`<<if \$random == 0>>    <<if \$effect_one_finished>>    Effect one already happened.    <<else>>    [[effect one]]    <<endif>><<endif>><<if \$random == 1>>... need to change this[[effect two]]<<endif>><<if \$random == 2>>... need to change this[[effect three]]<<endif>>`
What just happened
First, there is a new variable, \$effect_one_finished, that we see if the effect one has happened already (on the page effect one). If \$random is 0 again, we'll check to see if the effect has already happened first (that's the if inside the other if).

Note that while this makes the effect stop happening more than once, it doesn't do what we probably want, which is to hide the used up effect and just select among the others. That's a problem you would likely need custom macros for.