瀏覽代碼

Weight news so that recent items are less likely to appear

tags/v0.1.0
Fen Dweller 5 年之前
父節點
當前提交
f964b80055
沒有發現已知的金鑰在資料庫的簽署中 GPG Key ID: E80B35A6F11C3656
共有 2 個文件被更改,包括 37 次插入3 次删除
  1. +24
    -3
      gorge.js
  2. +13
    -0
      util.js

+ 24
- 3
gorge.js 查看文件

@@ -48,6 +48,8 @@ let newsRemoveTimer;


const newsDelay = 8000; const newsDelay = 8000;


const newsWeightFactors = [];

let buttonClicked = false; let buttonClicked = false;


const state = { const state = {
@@ -531,6 +533,7 @@ function setup() {
// prepare dynamic stuff // prepare dynamic stuff


initializeData(); initializeData();
initializeNews();
createButtons(); createButtons();
createDisplays(); createDisplays();
registerListeners(); registerListeners();
@@ -541,6 +544,12 @@ function setup() {
updateAll(); updateAll();
} }


function initializeNews() {
news.forEach(entry => {
newsWeightFactors.push(0);
});
}

const cache = {}; const cache = {};


function initializeCaches() { function initializeCaches() {
@@ -1116,16 +1125,28 @@ function clickPopup(text, type, location) {


function doNews() { function doNews() {
let options = []; let options = [];
let weights = [];
let indices = [];
let index = 0;
news.forEach(entry => { news.forEach(entry => {
if (entry.condition(state)) {
if (entry.condition(state) && newsWeightFactors[index] != 1) {
options = options.concat(entry.lines); 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)); showNews(options[choice](state));


for (let i = 0; i < newsWeightFactors.length; i++) {
newsWeightFactors[i] *= 0.9;
}

newsWeightFactors[indices[choice]] = 1;

newsShowTimer = setTimeout(() => { newsShowTimer = setTimeout(() => {
doNews(); doNews();
}, 8000); }, 8000);


+ 13
- 0
util.js 查看文件

@@ -53,3 +53,16 @@ function capitalize(string) {
function weekday() { function weekday() {
return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][(new Date()).getDay()]; 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;
}

Loading…
取消
儲存