Wednesday, November 13, 2019

algorithm - Weighted random events with conditions


I'm building a system for distributing ingame events for a strategy game. The game is heavily driven by the events and each country/player should receive one or more per time unit.


The algorithm is similar to the "The Soft-coded Probabilities Solution" from this question: How do I create a weighted collection and then pick a random element from it?


The main differences are:



  1. I need conditions for if events can happen or not, like only triggers if unrest is above 2% or if you are at war etc. Maybe half the events will have conditions (but this may change over time as more are added while the algorithm probably won't).

  2. I need a mechanism to prevent the same event repeating for the same player in too short a time period. This applies to some events but not all.


It seems that no matter how I go about this I have to do either a lot of condition checking in advance to maintain my list(s) or a lot of iteration over events that are anyway not selectable. So is this algorithm still a good choice to build upon in this case or should I be looking elsewhere?



Answer




I recommend this plan:



  1. Check conditions, create a list of eligible events. Don't add event if it is the same as the one most recently shown to the user.

  2. Assign weights to each event. E.g. Event[0].weight = 5; Event[1].weight = 10;

  3. Get random number from 0 to N - 1, where N is the sum of all weights.

  4. Check if the random number is less than Event[0].weight. If so, choose that event. Else, subtract Event[0].weight from the random number. Then check Event[1].weight and so on.

  5. Once an event is selected, store it so the next time you pick one, you can keep it out of the list.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...