237 lines
8.6 KiB
JavaScript
237 lines
8.6 KiB
JavaScript
// Main game view. Static markup lives in index.html; this module binds the
|
|
// controls once, builds the generator/upgrade lists, and refreshes the numbers.
|
|
|
|
import { generatorQuote, isUnlocked, upgradeVisible } from '../engine/engine.js';
|
|
import { t } from '../services/i18n.js';
|
|
import { $, h, icon, refreshStaticIcons } from './dom.js';
|
|
|
|
const SLIDER_STEPS = 1000;
|
|
const TREND = { '-1': '▼', 1: '▲' }; // last move of the material price
|
|
|
|
function setText(node, text) {
|
|
if (node.textContent !== text) node.textContent = text;
|
|
}
|
|
|
|
/**
|
|
* @param actions callbacks into the game: make, buyMaterial, buyMarketing,
|
|
* buyGenerator(id, amount), buyUpgrade(id), setPrice(value)
|
|
*/
|
|
export function createView(actions) {
|
|
const el = {
|
|
units: $('#v-units'),
|
|
funds: $('#v-funds'),
|
|
material: $('#v-material'),
|
|
total: $('#v-total'),
|
|
rate: $('#v-rate'),
|
|
demand: $('#v-demand'),
|
|
income: $('#v-income'),
|
|
make: $('#make'),
|
|
makeYield: $('#make-yield'),
|
|
buyMaterial: $('#buy-material'),
|
|
buyMaterialInfo: $('#buy-material-info'),
|
|
buyMarketing: $('#buy-marketing'),
|
|
buyMarketingInfo: $('#buy-marketing-info'),
|
|
priceInput: $('#price-input'),
|
|
priceSlider: $('#price-slider'),
|
|
priceHint: $('#price-hint'),
|
|
generators: $('#generators'),
|
|
upgrades: $('#upgrades'),
|
|
upgradeCount: $('#upgrade-count'),
|
|
upgradesEmpty: $('#upgrades-empty'),
|
|
};
|
|
|
|
let ctx;
|
|
let fmt;
|
|
let buyAmount = 1;
|
|
let generatorRows = new Map();
|
|
let upgradeRows = new Map();
|
|
let upgradeSignature = null;
|
|
|
|
const money = (n) => t('theme.fmt.funds', { value: fmt.money(n) });
|
|
const perSecond = (n) => t('ui.perSecond', { value: fmt.number(n) });
|
|
|
|
// ---------------------------------------------------------------- controls
|
|
|
|
el.make.addEventListener('click', () => actions.make());
|
|
el.buyMaterial.addEventListener('click', () => actions.buyMaterial());
|
|
el.buyMarketing.addEventListener('click', () => actions.buyMarketing());
|
|
|
|
const priceFromSlider = () => {
|
|
const { minPrice, maxPrice } = ctx.rules.market;
|
|
return minPrice * (maxPrice / minPrice) ** (Number(el.priceSlider.value) / SLIDER_STEPS);
|
|
};
|
|
const sliderFromPrice = (price) => {
|
|
const { minPrice, maxPrice } = ctx.rules.market;
|
|
return (SLIDER_STEPS * Math.log(price / minPrice)) / Math.log(maxPrice / minPrice);
|
|
};
|
|
|
|
el.priceSlider.addEventListener('input', () => actions.setPrice(priceFromSlider()));
|
|
el.priceInput.addEventListener('change', () => actions.setPrice(Number(el.priceInput.value)));
|
|
$('#price-down').addEventListener('click', () => actions.nudgePrice(-ctx.rules.market.priceStep));
|
|
$('#price-up').addEventListener('click', () => actions.nudgePrice(ctx.rules.market.priceStep));
|
|
|
|
$('#buy-amount').addEventListener('change', (event) => {
|
|
const value = event.target.value;
|
|
buyAmount = value === 'max' ? 'max' : Number(value);
|
|
});
|
|
|
|
// ------------------------------------------------------------------- lists
|
|
|
|
function effectText(effect) {
|
|
const params = { value: fmt.number(effect.value) };
|
|
if (effect.target) params.target = t(`theme.gen.${effect.target}.name`);
|
|
if (effect.type === 'batch_discount') params.percent = fmt.number(Math.round((1 - effect.value) * 100));
|
|
return t(`effect.${effect.type}`, params);
|
|
}
|
|
|
|
function generatorRow(g) {
|
|
const owned = h('span', { class: 'badge' });
|
|
const rate = h('span');
|
|
const amount = h('span', { class: 'btn__label' });
|
|
const cost = h('small');
|
|
const buy = h(
|
|
'button',
|
|
{ class: 'btn btn--buy', type: 'button', onclick: () => actions.buyGenerator(g.id, buyAmount) },
|
|
amount,
|
|
cost,
|
|
);
|
|
const root = h(
|
|
'li',
|
|
{ class: 'card', hidden: true },
|
|
icon(`gen.${g.id}`),
|
|
h(
|
|
'div',
|
|
{ class: 'card__body' },
|
|
h('h3', { class: 'card__title' }, h('span', { text: t(`theme.gen.${g.id}.name`) }), owned),
|
|
h('p', { class: 'card__desc', text: t(`theme.gen.${g.id}.desc`) }),
|
|
h('p', { class: 'card__meta' }, rate),
|
|
),
|
|
buy,
|
|
);
|
|
el.generators.append(root);
|
|
return { root, owned, rate, amount, cost, buy };
|
|
}
|
|
|
|
function upgradeRow(u) {
|
|
const cost = h('small');
|
|
const root = h(
|
|
'li',
|
|
{ class: 'card' },
|
|
icon(`upg.${u.id}`),
|
|
h(
|
|
'div',
|
|
{ class: 'card__body' },
|
|
h('h3', { class: 'card__title', text: t(`theme.upg.${u.id}`) }),
|
|
h('p', { class: 'card__desc', text: effectText(u.effect) }),
|
|
),
|
|
h('button', { class: 'btn btn--buy', type: 'button', onclick: () => actions.buyUpgrade(u.id) }, cost),
|
|
);
|
|
return { root, cost, buy: root.lastElementChild, upgrade: u };
|
|
}
|
|
|
|
// ------------------------------------------------------------------ public
|
|
|
|
/** Call after the theme, language or game data changed. */
|
|
function rebuild(newCtx, formatter) {
|
|
ctx = newCtx;
|
|
fmt = formatter;
|
|
el.generators.replaceChildren();
|
|
el.upgrades.replaceChildren();
|
|
generatorRows = new Map(ctx.generators.map((g) => [g.id, generatorRow(g)]));
|
|
upgradeRows = new Map();
|
|
upgradeSignature = null;
|
|
el.priceInput.min = ctx.rules.market.minPrice;
|
|
el.priceInput.max = ctx.rules.market.maxPrice;
|
|
el.priceInput.step = ctx.rules.market.priceStep;
|
|
refreshStaticIcons();
|
|
}
|
|
|
|
function updateGenerators(state, d) {
|
|
for (const g of ctx.generators) {
|
|
const row = generatorRows.get(g.id);
|
|
const owned = state.generators[g.id];
|
|
const visible = owned > 0 || isUnlocked(state, g.unlock);
|
|
row.root.hidden = !visible;
|
|
if (!visible) continue;
|
|
|
|
let quote = generatorQuote(state, ctx, g.id, buyAmount);
|
|
if (quote.count <= 0) quote = generatorQuote(state, ctx, g.id, 1);
|
|
|
|
setText(row.owned, t('ui.owned', { count: fmt.number(owned) }));
|
|
setText(row.rate, t('ui.rateEach', { rate: fmt.number(d.perGenerator[g.id]) }));
|
|
setText(row.amount, t('ui.buyN', { count: fmt.number(quote.count) }));
|
|
setText(row.cost, money(quote.cost));
|
|
row.buy.disabled = state.funds < quote.cost;
|
|
}
|
|
}
|
|
|
|
function updateUpgrades(state) {
|
|
const visible = ctx.upgrades.filter((u) => upgradeVisible(state, u)).sort((a, b) => a.cost - b.cost);
|
|
const signature = visible.map((u) => u.id).join();
|
|
if (signature !== upgradeSignature) {
|
|
upgradeSignature = signature;
|
|
upgradeRows = new Map(visible.map((u) => [u.id, upgradeRow(u)]));
|
|
el.upgrades.replaceChildren(...[...upgradeRows.values()].map((row) => row.root));
|
|
el.upgradesEmpty.hidden = visible.length > 0;
|
|
}
|
|
for (const row of upgradeRows.values()) {
|
|
setText(row.cost, money(row.upgrade.cost));
|
|
row.buy.disabled = state.funds < row.upgrade.cost;
|
|
}
|
|
setText(
|
|
el.upgradeCount,
|
|
t('ui.upgradeCount', { owned: state.upgrades.length, total: ctx.upgrades.length }),
|
|
);
|
|
}
|
|
|
|
function updateMarket(state, d) {
|
|
const { fairPrice, minPrice } = ctx.rules.market;
|
|
if (document.activeElement !== el.priceInput) el.priceInput.value = state.price.toFixed(2);
|
|
if (document.activeElement !== el.priceSlider) {
|
|
el.priceSlider.value = Math.round(sliderFromPrice(Math.max(state.price, minPrice)));
|
|
}
|
|
const hintKey = state.price > fairPrice ? 'ui.hintHigh' : 'ui.hintFair';
|
|
setText(el.priceHint, t(hintKey, { fair: money(fairPrice), demand: fmt.number(d.demand) }));
|
|
|
|
const nextLevelMultiplier = ctx.rules.marketing.demandPerLevel ** (state.marketing + 1);
|
|
setText(
|
|
el.buyMarketingInfo,
|
|
t('ui.marketingInfo', {
|
|
level: state.marketing + 1,
|
|
multiplier: fmt.number(nextLevelMultiplier),
|
|
cost: money(d.marketingCost),
|
|
}),
|
|
);
|
|
el.buyMarketing.disabled = state.funds < d.marketingCost;
|
|
}
|
|
|
|
/** @param flow { income } smoothed funds per second */
|
|
function update(state, d, flow) {
|
|
setText(el.units, fmt.number(Math.floor(state.units)));
|
|
setText(el.funds, money(state.funds));
|
|
setText(el.material, fmt.number(Math.floor(state.material)));
|
|
setText(el.total, fmt.number(Math.floor(state.totalProduced)));
|
|
setText(el.rate, perSecond(d.rate));
|
|
setText(el.demand, perSecond(d.demand));
|
|
setText(el.income, t('ui.perSecond', { value: money(flow.income) }));
|
|
|
|
setText(el.makeYield, t('ui.makeYield', { amount: fmt.number(d.clickYield) }));
|
|
el.make.disabled = state.material < d.materialPerUnit;
|
|
setText(
|
|
el.buyMaterialInfo,
|
|
t('ui.batchInfo', {
|
|
amount: fmt.number(d.batchSize),
|
|
cost: money(d.batchCost),
|
|
trend: TREND[state.materialTrend] ?? '',
|
|
}),
|
|
);
|
|
el.buyMaterial.disabled = state.funds < d.batchCost;
|
|
|
|
updateMarket(state, d);
|
|
updateGenerators(state, d);
|
|
updateUpgrades(state);
|
|
}
|
|
|
|
return { rebuild, update };
|
|
}
|