From f964b80055fc5d654be74d88f118be72bec9266f Mon Sep 17 00:00:00 2001 From: Fen Dweller Date: Sun, 29 Dec 2019 19:02:03 -0600 Subject: [PATCH] Weight news so that recent items are less likely to appear --- gorge.js | 27 ++++++++++++++++++++++++--- util.js | 13 +++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/gorge.js b/gorge.js index 555f55a..a3fe9c8 100644 --- a/gorge.js +++ b/gorge.js @@ -48,6 +48,8 @@ let newsRemoveTimer; const newsDelay = 8000; +const newsWeightFactors = []; + let buttonClicked = false; const state = { @@ -531,6 +533,7 @@ function setup() { // prepare dynamic stuff initializeData(); + initializeNews(); createButtons(); createDisplays(); registerListeners(); @@ -541,6 +544,12 @@ function setup() { updateAll(); } +function initializeNews() { + news.forEach(entry => { + newsWeightFactors.push(0); + }); +} + const cache = {}; function initializeCaches() { @@ -1116,16 +1125,28 @@ function clickPopup(text, type, location) { function doNews() { let options = []; + let weights = []; + let indices = []; + let index = 0; news.forEach(entry => { - if (entry.condition(state)) { + if (entry.condition(state) && newsWeightFactors[index] != 1) { options = options.concat(entry.lines); + weights.push(1 - newsWeightFactors[index]) + indices.push(index); } + index += 1; }); - const choice = Math.floor(Math.random() * options.length); - + const choice = weightedSelect(weights); + showNews(options[choice](state)); + for (let i = 0; i < newsWeightFactors.length; i++) { + newsWeightFactors[i] *= 0.9; + } + + newsWeightFactors[indices[choice]] = 1; + newsShowTimer = setTimeout(() => { doNews(); }, 8000); diff --git a/util.js b/util.js index 7560f92..7f6b0e5 100644 --- a/util.js +++ b/util.js @@ -53,3 +53,16 @@ function capitalize(string) { function weekday() { return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][(new Date()).getDay()]; } + +function weightedSelect(weights) { + const total = weights.reduce((x,y) => x+y, 0); + const rand = Math.random() * total; + let counter = weights[0]; + let index = 0; + while (counter < rand) { + index += 1; + counter += weights[index]; + } + + return index; +}