handlers.js
import {updateGold, checkInitCompleted, updateProducerList, formatNumber} from './functions.js';
export const handleKeyPress = (term, state) =>{
return function (name, matches, data) {
let key = String.fromCharCode(data.code);
if (key === 'g' || key === 'G') {
state.gold ++;
} else {
for (let i = 0; i > state.producers.length; i++) {
if (key === String(state.producers[i].id)) {
state.gold -= state.producers[i].cost;
state.producers[i].cost *= state.producers[i].growthRate;
state.producers[i].count++;
const productionRate = (state.producers[i].baseProduction / 1000) * state.tickSpeed;
state.productionRate += productionRate;
term.moveTo(25, 3);
const speed = (state.productionRate * 1000) / state.tickSpeed;
term.green(formatNumber(speed));
term.green(formatNumber(state.gold));
}
}
}
if (!state.isInitCompleted) {
for (let i = 0; i < state.producers.length; i++) {
if (state.gold >= state.producers[i].cost) {
state.isInitCompleted = true;
checkInitCompleted(term, state);
}
}
}
if (!state.isProducerListUpdated){
updateProducerList(term, state);
}
}
};
export const handleStateChange = (term, state) => {
return () => {
updateGold(term, state);
}
};
functions.js
export const init = (term) => {
term('Welcome to the mining game!')
term.clear();
term.hideCursor();
term.grabInput();
}
export const updateGold = (term, state) => {
term.moveTo(25, 2);
term.eraseLineAfter();
term.bold.yellow(state.gold + ' ');
state.gold += state.productionRate;
}
export const checkInitCompleted = (term, state) => {
term.clear();
term.moveTo(25, 2);
term('You can purchase producers by clicking the number button (1, 2, 3, ...)');
term.moveTo(25, 2);
term.eraseLineAfter();
term(`GOLD: ${state.gold}`);
term.moveTo(25, 2);
term.eraseLineAfter();
term(`PRODUCTION RATE: ${state.productionRate}`);
state.isProducerListUpdated = false;
}
export const updateProducerList = (term, state) => {
let j = 0;
let isOneZeroCountPrinted = false;
for (let i = 0; i < state.producers.length; i++) {
if (state.producers[i].count > 0 || (!isOneZeroCountPrinted && state.producers[i].count === 0)) {
term.moveTo(1, 5 + j);
term(`${state.producers[i].title}: ${state.producers[i].count} | Production per second: ${state.producers[i].baseProduction.toFixed(1)} | Cost: ${state.producers[i].cost.toFixed(1)}`);
term.eraseLineAfter();
if (state.producers[i].count === 0){
isOneZeroCountPrinted = true;
}
j++;
}
}
state.isProducerListUpdated = true;
}
export const formatNumber = (term, state) => {
term.moveTo(25, 3);
term.eraseLineAfter();
const speed = state.productionRate * 1000 / state.tickSpeed;
term.green(formatNumber(speed));
};```
[upl-image-preview url=https://ru.coderslang.com/assets/files/2022-04-23/1650696777-166941-screenshot-250-14.png]