How to randomize events?

Sara377544
06 Nov 2022, 20:41So I wanted to ask how to randomize a certain outcome. Somewhat like this:
-When you enter a room, there is about 80% of nothing happen or 20% of an event happening.
-Then if an event happens, there is 10% chance of event A, 30% chance of event B or 60% chance of event C.
How would I program something like this? Specially if I plan for more events all with different chances.
mrangel
07 Nov 2022, 08:05For a simple random chance, you can use the RandomChance
function:
if (RandomChance (20)) {
// put code here for the event happening
}
Inside that, you would have some code to determine which event happens.
A few ways to do this. This one allows you to use your percentage chances:
if (RandomChance (20)) {
event = GetRandomInt (0, 99)
if (event < 10) {
// code for event A goes here
}
else if (event < 40) {
// code for event B goes here
}
else {
// code for event C goes here
}
}
Or you could work out the conditional probabilities (probability of event B happening if event A doesn't = 30 * 100/90 = 33):
if (RandomChance (20)) {
if (RandomChance (10)) {
// code for event A goes here
}
else if (RandomChance (33)) {
// code for event B goes here
}
else {
// code for event C goes here
}
}
(this is less efficient, but some people prefer it)
Or you could use switch:
if (RandomChance (20)) {
Switch (GetRandomInt (1, 10)) {
case (1) {
// code for event A goes here
}
case (2, 3, 4) {
// code for event B goes here
}
case (5, 6, 7, 8, 9, 10) {
// code for event C goes here
}
}
}
(that picks a number from 1 to 10, then assigns a set of numbers to each option).
Or there's a version of that which some people find easier to read, picking letters instead (a bit inefficient, but some people prefer it):
if (RandomChance (20)) {
Switch (PickOneString (Split ("A;B;B;B;C;C;C;C;C;C"))) {
case ("A") {
// code for event A goes here
}
case ("B") {
// code for event B goes here
}
case ("C") {
// code for event C goes here
}
}
}
In all these cases, I've given you a piece of example code. If you prefer not to use code view, you can click the code view button, paste the code in, and then change back – you should be able to see how to recreate those options in future. (even if you don't use it for developing, code view is the only realistic way to share bits of script on the forum)