Comment

Comment by EarthLaunch

Why does weighted randomness seem so difficult for games? Are there any libraries that simplify this? I couldn't find any for JS.

So I created my own "algorithms" for things like randomly choosing which type of plants spawn in the world. It weighs them by the local frequency of each land-type. Eg if there's more swamp nearby, it's more likely to spawn cattails.

It's awful. Not intuitive. Weights have to be passed in ordered smallest to largest. Posting in hopes someone will correct my entire approach or point out an industry-standard way of doing these things.

  Utils.weightedRandom(percents, types)

  function weightedRandom(weight, outcomes){
    var randNumber = Math.floor(Math.random()*100)
    for(let i=0; i<weight.length; i++){
      if(randNumber<weight[i]){
        return outcomes[i]
      }
      else {
        randNumber -= weight[i]
      }
    }
  }
parent EarthLaunch 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton