Complete overhaul of code structure and relevant files (#639)

This commit is contained in:
Daniël van Noord
2021-03-14 00:41:14 +01:00
committed by GitHub
parent bb34bce9a5
commit 1bffb58782
163 changed files with 7369 additions and 10882 deletions

View File

@@ -0,0 +1,122 @@
/** General functions to format or beautify strings */
import { CMOptions } from '../../Config/VariablesAndData';
import { metric, shortScale, shortScaleAbbreviated } from '../../Data/Scales';
import { BackupFunctions } from '../../Main/VariablesAndData';
import {
ColorGreen, ColorOrange, ColorRed, ColorYellow,
} from '../VariablesAndData';
/**
* This function returns formats number based on the Scale setting
* @param {number} num Number to be beautified
* @param {any} floats Used in some scenario's by CM.Backup.Beautify (Game's original function)
* @param {number} forced Used to force (type 3) in certains cases
* @returns {string} Formatted number
*/
export function Beautify(num, floats, forced) {
const decimals = CMOptions.ScaleDecimals + 1;
if (num === Infinity) {
return 'Infinity';
} if (typeof num === 'undefined') {
return '0';
} if (CMOptions.Scale === 0) {
return BackupFunctions.Beautify(num, floats);
} if (Number.isFinite(num)) {
let answer = '';
if (num === 0) {
return num.toString();
} if (num > 0.001 && num < CMOptions.ScaleCutoff) {
answer = num.toFixed(2);
if (CMOptions.ScaleSeparator) answer = answer.toLocaleString('nl');
for (let i = 0; i < 3; i++) {
if (answer[answer.length - 1] === '0' || answer[answer.length - 1] === '.') answer = answer.slice(0, -1);
}
return answer;
} if (CMOptions.Scale === 4 && !forced || forced === 4) { // Scientific notation, 123456789 => 1.235E+8
answer = num.toExponential(decimals).toString().replace('e', 'E');
} else {
const exponential = num.toExponential().toString();
const AmountOfTenPowerThree = Math.floor(exponential.slice(exponential.indexOf('e') + 1) / 3);
answer = (num / Number(`1e${AmountOfTenPowerThree * 3}`)).toFixed(decimals);
// answer is now "xxx.xx" (e.g., 123456789 would be 123.46)
if (CMOptions.Scale === 1 && !forced || forced === 1) { // Metric scale, 123456789 => 123.457 M
if (num >= 0.01 && num < Number(`1e${metric.length * 3}`)) {
answer += ` ${metric[AmountOfTenPowerThree]}`;
} else answer = Beautify(num, 0, 4); // If number is too large or little, revert to scientific notation
} else if (CMOptions.Scale === 2 && !forced || forced === 2) { // Short scale, 123456789 => 123.457 M
if (num >= 0.01 && num < Number(`1e${shortScale.length * 3}`)) {
answer += ` ${shortScale[AmountOfTenPowerThree]}`;
} else answer = Beautify(num, 0, 4); // If number is too large or little, revert to scientific notation
} else if (CMOptions.Scale === 3 && !forced || forced === 3) { // Short scale, 123456789 => 123.457 M
if (num >= 0.01 && num < Number(`1e${shortScaleAbbreviated.length * 3}`)) {
answer += ` ${shortScaleAbbreviated[AmountOfTenPowerThree]}`;
} else answer = Beautify(num, 0, 4); // If number is too large or little, revert to scientific notation
} else if (CMOptions.Scale === 5 && !forced || forced === 5) { // Engineering notation, 123456789 => 123.457E+6
answer += `E${AmountOfTenPowerThree * 3}`;
}
}
if (answer === '') {
console.log(`Could not beautify number with CM.Disp.Beautify: ${num}`);
answer = BackupFunctions.Beautify(num, floats);
}
if (CMOptions.ScaleSeparator) answer = answer.replace('.', ',');
return answer;
}
console.log(`Could not beautify number with CM.Disp.Beautify: ${num}`);
return BackupFunctions.Beautify(num, floats);
}
/**
* This function returns time as a string depending on TimeFormat setting
* @param {number} time Time to be formatted
* @param {number} longFormat 1 or 0
* @returns {string} Formatted time
*/
export function FormatTime(time, longFormat) {
if (time === Infinity) return time;
time = Math.ceil(time);
const y = Math.floor(time / 31557600);
const d = Math.floor(time % 31557600 / 86400);
const h = Math.floor(time % 86400 / 3600);
const m = Math.floor(time % 3600 / 60);
const s = Math.floor(time % 60);
let str = '';
if (CMOptions.TimeFormat) {
if (time > 3155760000) return 'XX:XX:XX:XX:XX';
str += `${(y < 10 ? '0' : '') + y}:`;
str += `${(d < 10 ? '0' : '') + d}:`;
str += `${(h < 10 ? '0' : '') + h}:`;
str += `${(m < 10 ? '0' : '') + m}:`;
str += (s < 10 ? '0' : '') + s;
} else {
if (time > 777600000) return longFormat ? 'Over 9000 days!' : '>9000d';
str += (y > 0 ? `${y + (longFormat ? (y === 1 ? ' year' : ' years') : 'y')}, ` : '');
str += (d > 0 ? `${d + (longFormat ? (d === 1 ? ' day' : ' days') : 'd')}, ` : '');
if (str.length > 0 || h > 0) str += `${h + (longFormat ? (h === 1 ? ' hour' : ' hours') : 'h')}, `;
if (str.length > 0 || m > 0) str += `${m + (longFormat ? (m === 1 ? ' minute' : ' minutes') : 'm')}, `;
str += s + (longFormat ? (s === 1 ? ' second' : ' seconds') : 's');
}
return str;
}
/**
* This function returns the color to be used for time-strings
* @param {number} time Time to be coloured
* @returns {{string, string}} {text, color} Both the formatted time and color as strings in an array
*/
export function GetTimeColor(time) {
let color;
let text;
if (time <= 0) {
if (CMOptions.TimeFormat) text = '00:00:00:00:00';
else text = 'Done!';
color = ColorGreen;
} else {
text = FormatTime(time);
if (time > 300) color = ColorRed;
else if (time > 60) color = ColorOrange;
else color = ColorYellow;
}
return { text, color };
}

View File

@@ -0,0 +1,81 @@
import { CacheObjects1, CacheObjects10, CacheObjects100 } from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
import BuildingSell from '../../Sim/SimulationEvents/SellBuilding';
import { Beautify } from '../BeautifyAndFormatting/BeautifyFormatting';
import { Colors, LastTargetBuildings } from '../VariablesAndData';
/**
* Section: Functions related to right column of the screen (buildings/upgrades)
/**
* This function adjusts some things in the column of buildings.
* It colours them, helps display the correct sell-price and shuffles the order when CM.Options.SortBuildings is set
* The function is called by CM.Disp.Draw(), CM.Disp.UpdateColors() & CM.Disp.RefreshScale()
* And by changes in CM.Options.BuildColor, CM.Options.SortBuild & CM.Data.Config.BulkBuildColor
*/
export default function UpdateBuildings() {
let target = Game.buyBulk;
if (Game.buyMode === 1) {
LastTargetBuildings = target;
} else {
target = LastTargetBuildings;
}
if (target === 1) target = CacheObjects1;
else if (target === 10) target = CacheObjects10;
else if (target === 100) target = CacheObjects100;
if (Game.buyMode === 1) {
if (CMOptions.BuildColor === 1) {
for (const i of Object.keys(target)) {
l(`productPrice${Game.Objects[i].id}`).style.color = CMOptions.Colors[target[i].color];
}
} else {
for (const i of Object.keys(Game.Objects)) {
l(`productPrice${Game.Objects[i].id}`).style.removeProperty('color');
}
}
} else if (Game.buyMode === -1) {
for (const i of Object.keys(CacheObjects1)) {
const o = Game.Objects[i];
l(`productPrice${o.id}`).style.color = '';
/*
* Fix sell price displayed in the object in the store.
*
* The buildings sell price displayed by the game itself (without any mod) is incorrect.
* The following line of code fixes this issue, and can be safely removed when the game gets fixed.
*
* This issue is extensively detailed here: https://github.com/Aktanusa/CookieMonster/issues/359#issuecomment-735658262
*/
l(`productPrice${o.id}`).innerHTML = Beautify(BuildingSell(o, o.basePrice, o.amount, o.free, Game.buyBulk, 1));
}
}
// Build array of pointers, sort by pp, use array index (+2) as the grid row number
// (grid rows are 1-based indexing, and row 1 is the bulk buy/sell options)
// This regulates sorting of buildings
if (Game.buyMode === 1 && CMOptions.SortBuildings) {
const arr = Object.keys(target).map((k) => {
const o = target[k];
o.name = k;
o.id = Game.Objects[k].id;
return o;
});
arr.sort(function (a, b) { return (Colors.indexOf(a.color) > Colors.indexOf(b.color) ? 1 : (Colors.indexOf(a.color) < Colors.indexOf(b.color) ? -1 : (a.pp < b.pp) ? -1 : 0)); });
for (let x = 0; x < arr.length; x++) {
Game.Objects[arr[x].name].l.style.gridRow = `${x + 2}/${x + 2}`;
}
} else {
const arr = Object.keys(CacheObjects1).map((k) => {
const o = CacheObjects1[k];
o.name = k;
o.id = Game.Objects[k].id;
return o;
});
arr.sort((a, b) => a.id - b.id);
for (let x = 0; x < arr.length; x++) {
Game.Objects[arr[x].name].l.style.gridRow = `${x + 2}/${x + 2}`;
}
}
}

View File

@@ -0,0 +1,79 @@
import {
ColorBackPre, ColorBlue, ColorGray, ColorGreen, ColorOrange, ColorPurple, ColorRed, ColorTextPre, ColorYellow,
} from '../VariablesAndData';
/**
* This function creates the legend for the upgrade bar
* @returns {object} legend The legend-object to be added
*/
function CreateUpgradeBarLegend() {
const legend = document.createElement('div');
legend.style.minWidth = '330px';
legend.style.marginBottom = '4px';
const title = document.createElement('div');
title.className = 'name';
title.style.marginBottom = '4px';
title.textContent = 'Legend';
legend.appendChild(title);
const legendLine = function (color, text) {
const div = document.createElement('div');
div.style.verticalAlign = 'middle';
const span = document.createElement('span');
span.className = ColorBackPre + color;
span.style.display = 'inline-block';
span.style.height = '10px';
span.style.width = '10px';
span.style.marginRight = '4px';
div.appendChild(span);
div.appendChild(document.createTextNode(text));
return div;
};
legend.appendChild(legendLine(ColorBlue, 'Better than best PP building'));
legend.appendChild(legendLine(ColorGreen, 'Same as best PP building'));
legend.appendChild(legendLine(ColorYellow, 'Between best and worst PP buildings closer to best'));
legend.appendChild(legendLine(ColorOrange, 'Between best and worst PP buildings closer to worst'));
legend.appendChild(legendLine(ColorRed, 'Same as worst PP building'));
legend.appendChild(legendLine(ColorPurple, 'Worse than worst PP building'));
legend.appendChild(legendLine(ColorGray, 'Negative or infinity PP'));
return legend;
}
/**
* This function creates the upgrade bar above the upgrade-section in the right section of the screen
*/
export default function CreateUpgradeBar() {
const UpgradeBar = document.createElement('div');
UpgradeBar.id = 'CMUpgradeBar';
UpgradeBar.style.width = '100%';
UpgradeBar.style.backgroundColor = 'black';
UpgradeBar.style.textAlign = 'center';
UpgradeBar.style.fontWeight = 'bold';
UpgradeBar.style.display = 'none';
UpgradeBar.style.zIndex = '21';
UpgradeBar.onmouseout = function () { Game.tooltip.hide(); };
const placeholder = document.createElement('div');
placeholder.appendChild(CreateUpgradeBarLegend());
UpgradeBar.onmouseover = function () { Game.tooltip.draw(this, escape(placeholder.innerHTML), 'store'); };
const upgradeNumber = function (id, color) {
const span = document.createElement('span');
span.id = id;
span.className = ColorTextPre + color;
span.style.width = '14.28571428571429%';
span.style.display = 'inline-block';
span.textContent = '0';
return span;
};
UpgradeBar.appendChild(upgradeNumber('CMUpgradeBarBlue', ColorBlue));
UpgradeBar.appendChild(upgradeNumber('CMUpgradeBarGreen', ColorGreen));
UpgradeBar.appendChild(upgradeNumber('CMUpgradeBarYellow', ColorYellow));
UpgradeBar.appendChild(upgradeNumber('CMUpgradeBarOrange', ColorOrange));
UpgradeBar.appendChild(upgradeNumber('CMUpgradeBarRed', ColorRed));
UpgradeBar.appendChild(upgradeNumber('CMUpgradeBarPurple', ColorPurple));
UpgradeBar.appendChild(upgradeNumber('CMUpgradeBarGray', ColorGray));
l('upgrades').parentNode.insertBefore(UpgradeBar, l('upgrades').parentNode.childNodes[3]);
}

View File

@@ -0,0 +1,82 @@
import { CacheUpgrades } from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
import {
ColorBackPre, ColorBlue, ColorGray, ColorGreen, ColorOrange, ColorPurple, ColorRed, Colors, ColorYellow,
} from '../VariablesAndData';
/**
* This function adjusts some things in the upgrades section
* It colours them and shuffles the order when CM.Options.SortBuildings is set
* The function is called by CM.Disp.Draw(), CM.Disp.ToggleUpgradeBarAndColor & CM.Disp.RefreshScale()
* And by changes in CM.Options.SortUpgrades
*/
export default function UpdateUpgrades() {
// This counts the amount of upgrades for each pp group and updates the Upgrade Bar
if (CMOptions.UpBarColor > 0) {
let blue = 0;
let green = 0;
let yellow = 0;
let orange = 0;
let red = 0;
let purple = 0;
let gray = 0;
for (const i of Object.keys(Game.UpgradesInStore)) {
const me = Game.UpgradesInStore[i];
let addedColor = false;
for (let j = 0; j < l(`upgrade${i}`).childNodes.length; j++) {
if (l(`upgrade${i}`).childNodes[j].className.indexOf(ColorBackPre) !== -1) {
l(`upgrade${i}`).childNodes[j].className = ColorBackPre + CacheUpgrades[me.name].color;
addedColor = true;
break;
}
}
if (!addedColor) {
const div = document.createElement('div');
div.style.width = '10px';
div.style.height = '10px';
div.className = ColorBackPre + CacheUpgrades[me.name].color;
l(`upgrade${i}`).appendChild(div);
}
if (CacheUpgrades[me.name].color === ColorBlue) blue++;
else if (CacheUpgrades[me.name].color === ColorGreen) green++;
else if (CacheUpgrades[me.name].color === ColorYellow) yellow++;
else if (CacheUpgrades[me.name].color === ColorOrange) orange++;
else if (CacheUpgrades[me.name].color === ColorRed) red++;
else if (CacheUpgrades[me.name].color === ColorPurple) purple++;
else if (CacheUpgrades[me.name].color === ColorGray) gray++;
}
l('CMUpgradeBarBlue').textContent = blue;
l('CMUpgradeBarGreen').textContent = green;
l('CMUpgradeBarYellow').textContent = yellow;
l('CMUpgradeBarOrange').textContent = orange;
l('CMUpgradeBarRed').textContent = red;
l('CMUpgradeBarPurple').textContent = purple;
l('CMUpgradeBarGray').textContent = gray;
}
const arr = [];
// Build array of pointers, sort by pp, set flex positions
// This regulates sorting of upgrades
for (let x = 0; x < Game.UpgradesInStore.length; x++) {
const o = {};
o.name = Game.UpgradesInStore[x].name;
o.price = Game.UpgradesInStore[x].basePrice;
o.pp = CacheUpgrades[o.name].pp;
arr.push(o);
}
if (CMOptions.SortUpgrades) {
arr.sort(function (a, b) { return (Colors.indexOf(a.color) > Colors.indexOf(b.color) ? 1 : (Colors.indexOf(a.color) < Colors.indexOf(b.color) ? -1 : (a.pp < b.pp) ? -1 : 0)); });
} else {
arr.sort((a, b) => a.price - b.price);
}
const nameChecker = function (arr2, upgrade) {
return arr2.findIndex((e) => e.name === upgrade.name);
};
for (let x = 0; x < Game.UpgradesInStore.length; x++) {
l(`upgrade${x}`).style.order = nameChecker(arr, Game.UpgradesInStore[x]) + 1;
}
}

File diff suppressed because it is too large Load Diff

54
src/Disp/Dragon/Dragon.js Normal file
View File

@@ -0,0 +1,54 @@
/** Functions related to the Dragon */
import CacheDragonCost from '../../Cache/Dragon/Dragon';
import { CacheCostDragonUpgrade } from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
import CalculateChangeAura from '../../Sim/SimulationEvents/AuraChange';
import { Beautify, FormatTime } from '../BeautifyAndFormatting/BeautifyFormatting';
/**
* This functions adds the two extra lines about CPS and time to recover to the aura picker infoscreen
* @param {number} aura The number of the aura currently selected by the mouse/user
*/
export function AddAuraInfo(aura) {
if (CMOptions.DragonAuraInfo === 1) {
const [bonusCPS, priceOfChange] = CalculateChangeAura(aura);
const timeToRecover = FormatTime(priceOfChange / (bonusCPS + Game.cookiesPs));
const bonusCPSPercentage = Beautify(bonusCPS / Game.cookiesPs);
l('dragonAuraInfo').style.minHeight = '60px';
l('dragonAuraInfo').style.margin = '8px';
l('dragonAuraInfo').appendChild(document.createElement('div')).className = 'line';
const div = document.createElement('div');
div.style.minWidth = '200px';
div.style.textAlign = 'center';
div.textContent = `Picking this aura will change CPS by ${Beautify(bonusCPS)} (${bonusCPSPercentage}% of current CPS).`;
l('dragonAuraInfo').appendChild(div);
const div2 = document.createElement('div');
div2.style.minWidth = '200px';
div2.style.textAlign = 'center';
div2.textContent = `It will take ${timeToRecover} to recover the cost.`;
l('dragonAuraInfo').appendChild(div2);
}
}
/**
* This functions adds a tooltip to the level up button displaying the cost of rebuying all
* It is called by Game.ToggleSpecialMenu() after CM.Main.ReplaceNative()
*/
export function AddDragonLevelUpTooltip() {
// Check if it is the dragon popup that is on screen
if ((l('specialPopup').className.match(/onScreen/) && l('specialPopup').children[0].style.background.match(/dragon/)) !== null) {
for (let i = 0; i < l('specialPopup').childNodes.length; i++) {
if (l('specialPopup').childNodes[i].className === 'optionBox') {
l('specialPopup').children[i].onmouseover = function () {
CacheDragonCost();
Game.tooltip.dynamic = 1;
Game.tooltip.draw(l('specialPopup'), `<div style="min-width:200px;text-align:center;">${CacheCostDragonUpgrade}</div>`, 'this');
Game.tooltip.wobble();
};
l('specialPopup').children[i].onmouseout = function () { Game.tooltip.shouldHide = 1; };
}
}
}
}

45
src/Disp/Draw.js Normal file
View File

@@ -0,0 +1,45 @@
import { CMOptions } from '../Config/VariablesAndData';
import UpdateBuildings from './BuildingsUpgrades/Buildings';
import UpdateUpgrades from './BuildingsUpgrades/Upgrades';
import { UpdateBotBar } from './InfoBars/BottomBar';
import { UpdateTimerBar } from './InfoBars/TimerBar';
import RefreshMenu from './MenuSections/Refreshmenu';
import { UpdateTooltips } from './Tooltips/Tooltip';
import { CheckWrinklerTooltip, UpdateWrinklerTooltip } from './Tooltips/WrinklerTooltips';
/**
* This function handles all custom drawing for the Game.Draw() function.
* It is hooked on 'draw' by CM.RegisterHooks()
*/
export default function Draw() {
// Draw autosave timer in stats menu, this must be done here to make it count down correctly
if (
(Game.prefs.autosave && Game.drawT % 10 === 0) // with autosave ON and every 10 ticks
&& (Game.onMenu === 'stats' && CMOptions.Stats) // while being on the stats menu only
) {
const timer = document.getElementById('CMStatsAutosaveTimer');
if (timer) {
timer.innerText = Game.sayTime(Game.fps * 60 - (Game.T % (Game.fps * 60)), 4);
}
}
// Update colors
UpdateBuildings();
UpdateUpgrades();
// Redraw timers
UpdateTimerBar();
// Update Bottom Bar
UpdateBotBar();
// Update Tooltip
UpdateTooltips();
// Update Wrinkler Tooltip
CheckWrinklerTooltip();
UpdateWrinklerTooltip();
// Change menu refresh interval
RefreshMenu();
}

View File

@@ -0,0 +1,32 @@
/** Section: Functions related to the Golden Cookie Timers */
import { CMOptions } from '../../Config/VariablesAndData';
import { GCTimers } from '../VariablesAndData';
/**
* This function creates a new Golden Cookie Timer and appends it CM.Disp.GCTimers based on the id of the cookie
* @param {object} cookie A Golden Cookie object
*/
export default function CreateGCTimer(cookie) {
const GCTimer = document.createElement('div');
GCTimer.id = `GCTimer${cookie.id}`;
GCTimer.style.width = '96px';
GCTimer.style.height = '96px';
GCTimer.style.position = 'absolute';
GCTimer.style.zIndex = '10000000001';
GCTimer.style.textAlign = 'center';
GCTimer.style.lineHeight = '96px';
GCTimer.style.fontFamily = '"Kavoon", Georgia, serif';
GCTimer.style.fontSize = '35px';
GCTimer.style.cursor = 'pointer';
GCTimer.style.display = 'block';
if (CMOptions.GCTimer === 0) GCTimer.style.display = 'none';
GCTimer.style.left = cookie.l.style.left;
GCTimer.style.top = cookie.l.style.top;
GCTimer.onclick = function () { cookie.pop(); };
GCTimer.onmouseover = function () { cookie.l.style.filter = 'brightness(125%) drop-shadow(0px 0px 3px rgba(255,255,255,1))'; cookie.l.style.webkitFilter = 'brightness(125%) drop-shadow(0px 0px 3px rgba(255,255,255,1))'; };
GCTimer.onmouseout = function () { cookie.l.style.filter = ''; cookie.l.style.webkitFilter = ''; };
GCTimers[cookie.id] = GCTimer;
l('shimmers').appendChild(GCTimer);
}

View File

@@ -0,0 +1,15 @@
/**
* This function calculates the time it takes to reach a certain magic level
* @param {number} currentMagic The current magic level
* @param {number} maxMagic The user's max magic level
* @param {number} targetMagic The target magic level
* @returns {number} count / Game.fps The time it takes to reach targetMagic
*/
export default function CalculateGrimoireRefillTime(currentMagic, maxMagic, targetMagic) {
let count = 0;
while (currentMagic < targetMagic) {
currentMagic += Math.max(0.002, (currentMagic / Math.max(maxMagic, 100)) ** 0.5) * 0.002;
count++;
}
return count / Game.fps;
}

View File

@@ -0,0 +1,21 @@
import {
CacheAvgCps, CacheCurrWrinklerCount, CacheCurrWrinklerCPSMult, CacheWrinklersFattest,
} from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
/**
* This function returns the cps as either current or average CPS depending on CM.Options.CPSMode
* @returns {number} The average or current cps
*/
export default function GetCPS() {
if (CMOptions.CPSMode) {
return CacheAvgCps;
} if (CMOptions.CalcWrink === 0) {
return (Game.cookiesPs * (1 - Game.cpsSucked));
} if (CMOptions.CalcWrink === 1) {
return Game.cookiesPs * (CacheCurrWrinklerCPSMult + (1 - (CacheCurrWrinklerCount * 0.05)));
} if (CMOptions.CalcWrink === 2 && Game.wrinklers[CacheWrinklersFattest[1]].type === 1) {
return Game.cookiesPs * ((CacheCurrWrinklerCPSMult * 3 / CacheCurrWrinklerCount) + (1 - (CacheCurrWrinklerCount * 0.05)));
}
return Game.cookiesPs * ((CacheCurrWrinklerCPSMult / CacheCurrWrinklerCount) + (1 - (CacheCurrWrinklerCount * 0.05)));
}

View File

@@ -0,0 +1,24 @@
import {
ColorGray, ColorGreen, ColorOrange, ColorPurple, ColorRed, ColorYellow,
} from '../VariablesAndData';
/**
* This function returns Name and Color as object for sugar lump type that is given as input param.
* It is called by CM.Disp.UpdateTooltipSugarLump()
* @param {string} type Sugar Lump Type.
* @returns {{string}, {string}} text, color An array containing the text and display-color of the sugar lump
*/
export default function GetLumpColor(type) {
if (type === 0) {
return { text: 'Normal', color: ColorGray };
} if (type === 1) {
return { text: 'Bifurcated', color: ColorGreen };
} if (type === 2) {
return { text: 'Golden', color: ColorYellow };
} if (type === 3) {
return { text: 'Meaty', color: ColorOrange };
} if (type === 4) {
return { text: 'Caramelized', color: ColorPurple };
}
return { text: 'Unknown Sugar Lump', color: ColorRed };
}

View File

@@ -0,0 +1,16 @@
import { CacheWrinklersFattest, CacheWrinklersTotal } from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
/**
* This function returns the total amount stored in the Wrinkler Bank
* as calculated by CM.Cache.CacheWrinklers() if CM.Options.CalcWrink is set
* @returns {number} 0 or the amount of cookies stored (CM.Cache.WrinklersTotal)
*/
export default function GetWrinkConfigBank() {
if (CMOptions.CalcWrink === 1) {
return CacheWrinklersTotal;
} if (CMOptions.CalcWrink === 2) {
return CacheWrinklersFattest[0];
}
return 0;
}

View File

@@ -0,0 +1,11 @@
/**
* This function pops all normal wrinklers
* It is called by a click of the 'pop all' button created by CM.Disp.AddMenuStats()
*/
export default function PopAllNormalWrinklers() {
for (const i of Object.keys(Game.wrinklers)) {
if (Game.wrinklers[i].sucked > 0 && Game.wrinklers[i].type === 0) {
Game.wrinklers[i].hp = 0;
}
}
}

View File

@@ -0,0 +1,17 @@
import UpdateBuildings from '../BuildingsUpgrades/Buildings';
import UpdateUpgrades from '../BuildingsUpgrades/Upgrades';
import { UpdateBotBar } from '../InfoBars/BottomBar';
/**
* This function refreshes all numbers after a change in scale-setting
* It is therefore called by a changes in CM.Options.Scale, CM.Options.ScaleDecimals, CM.Options.ScaleSeparator and CM.Options.ScaleCutoff
*/
export default function RefreshScale() {
BeautifyAll();
Game.RefreshStore();
Game.RebuildUpgrades();
UpdateBotBar();
UpdateBuildings();
UpdateUpgrades();
}

View File

@@ -0,0 +1,20 @@
import { ToggleTimerBar } from '../../Config/SpecificToggles';
import ToggleBotBar from '../../Config/Toggles/ToggleBotBar';
import { CMOptions } from '../../Config/VariablesAndData';
import UpdateBackground from './UpdateBackground';
/**
* This function disables and shows the bars created by CookieMonster when the game is "ascending"
* It is called by CM.Disp.Draw()
*/
export default function UpdateAscendState() {
if (Game.OnAscend) {
l('game').style.bottom = '0px';
if (CMOptions.BotBar === 1) l('CMBotBar').style.display = 'none';
if (CMOptions.TimerBar === 1) l('CMTimerBar').style.display = 'none';
} else {
ToggleBotBar();
ToggleTimerBar();
}
UpdateBackground();
}

View File

@@ -0,0 +1,11 @@
/**
* This function sets the size of the background of the full game and the left column
* depending on whether certain abrs are activated
* It is called by CM.Disp.UpdateAscendState() and CM.Disp.UpdateBotTimerBarPosition()
*/
export default function UpdateBackground() {
Game.Background.canvas.width = Game.Background.canvas.parentNode.offsetWidth;
Game.Background.canvas.height = Game.Background.canvas.parentNode.offsetHeight;
Game.LeftBackground.canvas.width = Game.LeftBackground.canvas.parentNode.offsetWidth;
Game.LeftBackground.canvas.height = Game.LeftBackground.canvas.parentNode.offsetHeight;
}

View File

@@ -0,0 +1,24 @@
import { CMOptions } from '../../Config/VariablesAndData';
import UpdateBuildings from '../BuildingsUpgrades/Buildings';
import {
ColorBackPre, ColorBorderPre, Colors, ColorTextPre,
} from '../VariablesAndData';
/**
* This function changes/refreshes colours if the user has set new standard colours
* The function is therefore called by a change in CM.Options.Colors
*/
export default function UpdateColors() {
let str = '';
for (let i = 0; i < Colors.length; i++) {
str += `.${ColorTextPre}${Colors[i]} { color: ${CMOptions.Colors[Colors[i]]}; }\n`;
}
for (let i = 0; i < Colors.length; i++) {
str += `.${ColorBackPre}${Colors[i]} { background-color: ${CMOptions.Colors[Colors[i]]}; }\n`;
}
for (let i = 0; i < Colors.length; i++) {
str += `.${ColorBorderPre}${Colors[i]} { border: 1px solid ${CMOptions.Colors[Colors[i]]}; }\n`;
}
l('CMCSS').textContent = str;
UpdateBuildings(); // Class has been already set
}

View File

@@ -0,0 +1,88 @@
/** Functions related to the Bottom Bar */
import { CacheObjects1, CacheObjects10, CacheObjects100 } from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
import { VersionMajor, VersionMinor } from '../../Data/Moddata';
import { Beautify, GetTimeColor } from '../BeautifyAndFormatting/BeautifyFormatting';
import GetCPS from '../HelperFunctions/GetCPS';
import GetWrinkConfigBank from '../HelperFunctions/GetWrinkConfigBank';
import {
ColorBlue, ColorTextPre, ColorYellow, LastTargetBotBar,
} from '../VariablesAndData';
import { CreateBotBarBuildingColumn } from './CreateDOMElements';
/**
* This function creates the bottom bar and appends it to l('wrapper')
*/
export function CreateBotBar() {
const BotBar = document.createElement('div');
BotBar.id = 'CMBotBar';
BotBar.style.height = '69px';
BotBar.style.width = '100%';
BotBar.style.position = 'absolute';
BotBar.style.display = 'none';
BotBar.style.backgroundColor = '#262224';
BotBar.style.backgroundImage = 'linear-gradient(to bottom, #4d4548, #000000)';
BotBar.style.borderTop = '1px solid black';
BotBar.style.overflow = 'auto';
BotBar.style.textShadow = '-1px 0 black, 0 1px black, 1px 0 black, 0 -1px black';
const table = BotBar.appendChild(document.createElement('table'));
table.style.width = '100%';
table.style.textAlign = 'center';
table.style.whiteSpace = 'nowrap';
const tbody = table.appendChild(document.createElement('tbody'));
const firstCol = function (text, color) {
const td = document.createElement('td');
td.style.textAlign = 'right';
td.className = ColorTextPre + color;
td.textContent = text;
return td;
};
const type = tbody.appendChild(document.createElement('tr'));
type.style.fontWeight = 'bold';
type.appendChild(firstCol(`CM ${VersionMajor}.${VersionMinor}`, ColorYellow));
const bonus = tbody.appendChild(document.createElement('tr'));
bonus.appendChild(firstCol('Bonus Income', ColorBlue));
const pp = tbody.appendChild(document.createElement('tr'));
pp.appendChild(firstCol('Payback Period', ColorBlue));
const time = tbody.appendChild(document.createElement('tr'));
time.appendChild(firstCol('Time Left', ColorBlue));
l('wrapper').appendChild(BotBar);
for (const i of Object.keys(Game.Objects)) {
CreateBotBarBuildingColumn(i);
}
}
/**
* This function updates the bonus-, pp-, and time-rows in the the bottom bar
*/
export function UpdateBotBar() {
if (CMOptions.BotBar === 1 && CacheObjects1 && Game.buyMode === 1) {
let count = 0;
for (const i of Object.keys(CacheObjects1)) {
let target = Game.buyBulk;
if (Game.buyMode === 1) {
LastTargetBotBar = target;
} else {
target = LastTargetBotBar;
}
if (target === 1) target = CacheObjects1;
if (target === 10) target = CacheObjects10;
if (target === 100) target = CacheObjects100;
count++;
l('CMBotBar').firstChild.firstChild.childNodes[0].childNodes[count].childNodes[1].textContent = Game.Objects[i].amount;
l('CMBotBar').firstChild.firstChild.childNodes[1].childNodes[count].textContent = Beautify(target[i].bonus, 2);
l('CMBotBar').firstChild.firstChild.childNodes[2].childNodes[count].className = ColorTextPre + target[i].color;
l('CMBotBar').firstChild.firstChild.childNodes[2].childNodes[count].textContent = Beautify(target[i].pp, 2);
const timeColor = GetTimeColor((Game.Objects[i].bulkPrice - (Game.cookies + GetWrinkConfigBank())) / GetCPS());
l('CMBotBar').firstChild.firstChild.childNodes[3].childNodes[count].className = ColorTextPre + timeColor.color;
if (timeColor.text === 'Done!' && Game.cookies < Game.Objects[i].bulkPrice) {
l('CMBotBar').firstChild.firstChild.childNodes[3].childNodes[count].textContent = `${timeColor.text} (with Wrink)`;
} else l('CMBotBar').firstChild.firstChild.childNodes[3].childNodes[count].textContent = timeColor.text;
}
}
}

View File

@@ -0,0 +1,89 @@
/** Functions to create various DOM elements used by the Bars */
import { ColorBackPre, ColorBlue, ColorTextPre } from '../VariablesAndData';
/**
* This function creates an indivudual timer for the timer bar
* @param {string} id An id to identify the timer
* @param {string} name The title of the timer
* @param [{{string}, {string}}, ...] bars ([id, color]) The id and colours of individual parts of the timer
*/
export function CreateTimer(id, name, bars) {
const timerBar = document.createElement('div');
timerBar.id = id;
timerBar.style.height = '12px';
timerBar.style.margin = '0px 10px';
timerBar.style.position = 'relative';
const div = document.createElement('div');
div.style.width = '100%';
div.style.height = '10px';
div.style.margin = 'auto';
div.style.position = 'absolute';
div.style.left = '0px';
div.style.top = '0px';
div.style.right = '0px';
div.style.bottom = '0px';
const type = document.createElement('span');
type.style.display = 'inline-block';
type.style.textAlign = 'right';
type.style.fontSize = '10px';
type.style.width = '108px';
type.style.marginRight = '5px';
type.style.verticalAlign = 'text-top';
type.textContent = name;
div.appendChild(type);
for (let i = 0; i < bars.length; i++) {
const colorBar = document.createElement('span');
colorBar.id = bars[i].id;
colorBar.style.display = 'inline-block';
colorBar.style.height = '10px';
colorBar.style.verticalAlign = 'text-top';
colorBar.style.textAlign = 'center';
if (bars.length - 1 === i) {
colorBar.style.borderTopRightRadius = '10px';
colorBar.style.borderBottomRightRadius = '10px';
}
if (typeof bars[i].color !== 'undefined') {
colorBar.className = ColorBackPre + bars[i].color;
}
div.appendChild(colorBar);
}
const timer = document.createElement('span');
timer.id = `${id}Time`;
timer.style.marginLeft = '5px';
timer.style.verticalAlign = 'text-top';
div.appendChild(timer);
timerBar.appendChild(div);
return timerBar;
}
/**
* This function extends the bottom bar (created by CM.Disp.CreateBotBar) with a column for the given building.
* @param {string} buildingName Objectname to be added (e.g., "Cursor")
*/
export function CreateBotBarBuildingColumn(buildingName) {
if (l('CMBotBar') !== null) {
const type = l('CMBotBar').firstChild.firstChild.childNodes[0];
const bonus = l('CMBotBar').firstChild.firstChild.childNodes[1];
const pp = l('CMBotBar').firstChild.firstChild.childNodes[2];
const time = l('CMBotBar').firstChild.firstChild.childNodes[3];
const i = buildingName;
const header = type.appendChild(document.createElement('td'));
header.appendChild(document.createTextNode(`${i.indexOf(' ') !== -1 ? i.substring(0, i.indexOf(' ')) : i} (`));
const span = header.appendChild(document.createElement('span'));
span.className = ColorTextPre + ColorBlue;
header.appendChild(document.createTextNode(')'));
bonus.appendChild(document.createElement('td'));
pp.appendChild(document.createElement('td'));
time.appendChild(document.createElement('td'));
}
}

View File

@@ -0,0 +1,118 @@
/** Functions related to the Timer Bar */
import { UpdateBotTimerBarPosition } from '../../Config/SpecificToggles';
import { CMOptions } from '../../Config/VariablesAndData';
import {
BuffColors,
ColorBackPre, ColorGray, ColorOrange, ColorPurple, LastNumberOfTimers,
} from '../VariablesAndData';
import { CreateTimer } from './CreateDOMElements';
/**
* This function creates the TimerBar and appends it to l('wrapper')
*/
export function CreateTimerBar() {
const TimerBar = document.createElement('div');
TimerBar.id = 'CMTimerBar';
TimerBar.style.position = 'absolute';
TimerBar.style.display = 'none';
TimerBar.style.height = '0px';
TimerBar.style.fontSize = '10px';
TimerBar.style.fontWeight = 'bold';
TimerBar.style.backgroundColor = 'black';
// Create standard Golden Cookie bar
const CMTimerBarGC = CreateTimer('CMTimerBarGC',
'Next Cookie',
[{ id: 'CMTimerBarGCMinBar', color: ColorGray }, { id: 'CMTimerBarGCBar', color: ColorPurple }]);
TimerBar.appendChild(CMTimerBarGC);
// Create standard Reindeer bar
const CMTimerBarRen = CreateTimer('CMTimerBarRen',
'Next Reindeer',
[{ id: 'CMTimerBarRenMinBar', color: ColorGray }, { id: 'CMTimerBarRenBar', color: ColorOrange }]);
TimerBar.appendChild(CMTimerBarRen);
l('wrapper').appendChild(TimerBar);
}
/**
* This function updates indivudual timers in the timer bar
*/
export function UpdateTimerBar() {
if (CMOptions.TimerBar === 1) {
// label width: 113, timer width: 30, div margin: 20
const maxWidthTwoBar = l('CMTimerBar').offsetWidth - 163;
// label width: 113, div margin: 20, calculate timer width at runtime
const maxWidthOneBar = l('CMTimerBar').offsetWidth - 133;
let numberOfTimers = 0;
// Regulates visibility of Golden Cookie timer
if (Game.shimmerTypes.golden.spawned === 0 && !Game.Has('Golden switch [off]')) {
l('CMTimerBarGC').style.display = '';
l('CMTimerBarGCMinBar').style.width = `${Math.round(Math.max(0, Game.shimmerTypes.golden.minTime - Game.shimmerTypes.golden.time) * maxWidthTwoBar / Game.shimmerTypes.golden.maxTime)}px`;
if (CMOptions.TimerBarOverlay >= 1) l('CMTimerBarGCMinBar').textContent = Math.ceil((Game.shimmerTypes.golden.minTime - Game.shimmerTypes.golden.time) / Game.fps);
else l('CMTimerBarGCMinBar').textContent = '';
if (Game.shimmerTypes.golden.minTime === Game.shimmerTypes.golden.maxTime) {
l('CMTimerBarGCMinBar').style.borderTopRightRadius = '10px';
l('CMTimerBarGCMinBar').style.borderBottomRightRadius = '10px';
} else {
l('CMTimerBarGCMinBar').style.borderTopRightRadius = '';
l('CMTimerBarGCMinBar').style.borderBottomRightRadius = '';
}
l('CMTimerBarGCBar').style.width = `${Math.round(Math.min(Game.shimmerTypes.golden.maxTime - Game.shimmerTypes.golden.minTime, Game.shimmerTypes.golden.maxTime - Game.shimmerTypes.golden.time) * maxWidthTwoBar / Game.shimmerTypes.golden.maxTime)}px`;
if (CMOptions.TimerBarOverlay >= 1) l('CMTimerBarGCBar').textContent = Math.ceil(Math.min(Game.shimmerTypes.golden.maxTime - Game.shimmerTypes.golden.minTime, Game.shimmerTypes.golden.maxTime - Game.shimmerTypes.golden.time) / Game.fps);
else l('CMTimerBarGCBar').textContent = '';
l('CMTimerBarGCTime').textContent = Math.ceil((Game.shimmerTypes.golden.maxTime - Game.shimmerTypes.golden.time) / Game.fps);
numberOfTimers++;
} else l('CMTimerBarGC').style.display = 'none';
// Regulates visibility of Reindeer timer
if (Game.season === 'christmas' && Game.shimmerTypes.reindeer.spawned === 0) {
l('CMTimerBarRen').style.display = '';
l('CMTimerBarRenMinBar').style.width = `${Math.round(Math.max(0, Game.shimmerTypes.reindeer.minTime - Game.shimmerTypes.reindeer.time) * maxWidthTwoBar / Game.shimmerTypes.reindeer.maxTime)}px`;
if (CMOptions.TimerBarOverlay >= 1) l('CMTimerBarRenMinBar').textContent = Math.ceil((Game.shimmerTypes.reindeer.minTime - Game.shimmerTypes.reindeer.time) / Game.fps);
else l('CMTimerBarRenMinBar').textContent = '';
l('CMTimerBarRenBar').style.width = `${Math.round(Math.min(Game.shimmerTypes.reindeer.maxTime - Game.shimmerTypes.reindeer.minTime, Game.shimmerTypes.reindeer.maxTime - Game.shimmerTypes.reindeer.time) * maxWidthTwoBar / Game.shimmerTypes.reindeer.maxTime)}px`;
if (CMOptions.TimerBarOverlay >= 1) l('CMTimerBarRenBar').textContent = Math.ceil(Math.min(Game.shimmerTypes.reindeer.maxTime - Game.shimmerTypes.reindeer.minTime, Game.shimmerTypes.reindeer.maxTime - Game.shimmerTypes.reindeer.time) / Game.fps);
else l('CMTimerBarRenBar').textContent = '';
l('CMTimerBarRenTime').textContent = Math.ceil((Game.shimmerTypes.reindeer.maxTime - Game.shimmerTypes.reindeer.time) / Game.fps);
numberOfTimers++;
} else {
l('CMTimerBarRen').style.display = 'none';
}
// On every frame all buff-timers are deleted and re-created
const BuffTimerBars = {};
for (const i of Object.keys(Game.buffs)) {
if (Game.buffs[i]) {
const timer = CreateTimer(Game.buffs[i].name, Game.buffs[i].name, [{ id: `${Game.buffs[i].name}Bar` }]);
timer.style.display = '';
let classColor = '';
// Gives specific timers specific colors
if (typeof BuffColors[Game.buffs[i].name] !== 'undefined') {
classColor = BuffColors[Game.buffs[i].name];
} else classColor = ColorPurple;
timer.lastChild.children[1].className = ColorBackPre + classColor;
timer.lastChild.children[1].style.color = 'black';
if (CMOptions.TimerBarOverlay === 2) timer.lastChild.children[1].textContent = `${Math.round(100 * (Game.buffs[i].time / Game.buffs[i].maxTime))}%`;
else timer.lastChild.children[1].textContent = '';
timer.lastChild.children[1].style.width = `${Math.round(Game.buffs[i].time * (maxWidthOneBar - Math.ceil(Game.buffs[i].time / Game.fps).toString().length * 8) / Game.buffs[i].maxTime)}px`;
timer.lastChild.children[2].textContent = Math.ceil(Game.buffs[i].time / Game.fps);
numberOfTimers++;
BuffTimerBars[Game.buffs[i].name] = timer;
}
}
for (const i of Object.keys(BuffTimerBars)) {
l('CMTimerBar').appendChild(BuffTimerBars[i]);
}
if (numberOfTimers !== 0) {
l('CMTimerBar').style.height = `${numberOfTimers * 12 + 2}px`;
}
if (LastNumberOfTimers !== numberOfTimers) {
LastNumberOfTimers = numberOfTimers;
UpdateBotTimerBarPosition();
}
}
}

View File

@@ -0,0 +1,20 @@
import { CacheWrinklersFattest } from '../../Cache/VariablesAndData';
import PopAllNormalWrinklers from '../HelperFunctions/PopWrinklers';
/**
* This function creates two objects at the bottom of the left column that allowing popping of wrinklers
*/
export default function CreateWrinklerButtons() {
const popAllA = document.createElement('a');
popAllA.id = 'PopAllNormalWrinklerButton';
popAllA.textContent = 'Pop All Normal';
popAllA.className = 'option';
popAllA.onclick = function () { PopAllNormalWrinklers(); };
l('sectionLeftExtra').children[0].append(popAllA);
const popFattestA = document.createElement('a');
popFattestA.id = 'PopFattestWrinklerButton';
popFattestA.textContent = 'Pop Single Fattest';
popFattestA.className = 'option';
popFattestA.onclick = function () { if (CacheWrinklersFattest[1] !== null) Game.wrinklers[CacheWrinklersFattest[1]].hp = 0; };
l('sectionLeftExtra').children[0].append(popFattestA);
}

View File

@@ -0,0 +1,13 @@
import { DispCSS } from '../VariablesAndData';
/**
* This function creates a CSS style that stores certain standard CSS classes used by CookieMonster
*/
export default function CreateCssArea() {
DispCSS = document.createElement('style');
DispCSS.type = 'text/css';
DispCSS.id = 'CMCSS';
document.head.appendChild(DispCSS);
}

View File

@@ -0,0 +1,10 @@
/**
* This function updates the style of the building and upgrade sections to make these sortable
*/
export default function UpdateBuildingUpgradeStyle() {
l('products').style.display = 'grid';
l('storeBulk').style.gridRow = '1/1';
l('upgrades').style.display = 'flex';
l('upgrades').style['flex-wrap'] = 'wrap';
}

View File

@@ -0,0 +1,14 @@
/**
* This function creates a white square over the full screen and appends it to l('wrapper')
*/
export default function CreateWhiteScreen() {
const WhiteScreen = document.createElement('div');
WhiteScreen.id = 'CMWhiteScreen';
WhiteScreen.style.width = '100%';
WhiteScreen.style.height = '100%';
WhiteScreen.style.backgroundColor = 'white';
WhiteScreen.style.display = 'none';
WhiteScreen.style.zIndex = '9999999999';
WhiteScreen.style.position = 'absolute';
l('wrapper').appendChild(WhiteScreen);
}

View File

@@ -0,0 +1,25 @@
import { CMOptions } from '../../Config/VariablesAndData';
import AddMenuStats from './AddStatsPage';
import AddMenuInfo from './InfoPage';
import AddMenuPref from './SettingsPage';
/**
* This function adds the calll the functions to add extra info to the stats and options pages
*/
export default function AddMenu() {
const title = document.createElement('div');
title.className = 'title';
if (Game.onMenu === 'prefs') {
title.textContent = 'Cookie Monster Settings';
AddMenuPref(title);
} else if (Game.onMenu === 'stats') {
if (CMOptions.Stats) {
title.textContent = 'Cookie Monster Statistics';
AddMenuStats(title);
}
} else if (Game.onMenu === 'log') {
title.textContent = 'Cookie Monster '; // To create space between name and button
AddMenuInfo(title);
}
}

View File

@@ -0,0 +1,175 @@
/** Main function to create the sections of Cookie Monster on the Statistics page */
import { AddMissingUpgrades } from './CreateMissingUpgrades';
import * as CreateSections from './CreateStatsSections';
import * as CreateElements from './CreateDOMElements';
import * as GameData from '../../Data/Gamedata';
import { CMOptions } from '../../Config/VariablesAndData';
import {
CacheAverageClicks, CacheCentEgg, CacheLastChoEgg, CacheSeaSpec, CacheWrinklersFattest, CacheWrinklersNormal, CacheWrinklersTotal,
} from '../../Cache/VariablesAndData';
import PopAllNormalWrinklers from '../HelperFunctions/PopWrinklers';
import { ClickTimes, CookieTimes } from '../VariablesAndData';
import GetCPS from '../HelperFunctions/GetCPS';
import { Beautify } from '../BeautifyAndFormatting/BeautifyFormatting';
/**
* This function adds stats created by CookieMonster to the stats page
* It is called by CM.Disp.AddMenu
* @param {object} title On object that includes the title of the menu
*/
export default function AddMenuStats(title) {
const stats = document.createElement('div');
stats.className = 'subsection';
stats.appendChild(title);
stats.appendChild(CreateElements.StatsHeader('Lucky Cookies', 'Lucky'));
if (CMOptions.Header.Lucky) {
stats.appendChild(CreateSections.LuckySection());
}
stats.appendChild(CreateElements.StatsHeader('Chain Cookies', 'Chain'));
if (CMOptions.Header.Chain) {
stats.appendChild(CreateSections.ChainSection());
}
if (Game.Objects['Wizard tower'].minigameLoaded) {
stats.appendChild(CreateElements.StatsHeader('Spells', 'Spells'));
if (CMOptions.Header.Spells) {
stats.appendChild(CreateSections.SpellsSection());
}
}
if (Game.Objects.Farm.minigameLoaded) {
stats.appendChild(CreateElements.StatsHeader('Garden', 'Garden'));
if (CMOptions.Header.Garden) {
stats.appendChild(CreateSections.GardenSection());
}
}
stats.appendChild(CreateElements.StatsHeader('Prestige', 'Prestige'));
if (CMOptions.Header.Prestige) {
stats.appendChild(CreateSections.PrestigeSection());
}
if (Game.cpsSucked > 0) {
stats.appendChild(CreateElements.StatsHeader('Wrinklers', 'Wrink'));
if (CMOptions.Header.Wrink) {
const popAllFrag = document.createDocumentFragment();
popAllFrag.appendChild(document.createTextNode(`${Beautify(CacheWrinklersTotal)} / ${Beautify(CacheWrinklersNormal)} `));
const popAllA = document.createElement('a');
popAllA.textContent = 'Pop All Normal';
popAllA.className = 'option';
popAllA.onclick = function () { PopAllNormalWrinklers(); };
popAllFrag.appendChild(popAllA);
stats.appendChild(CreateElements.StatsListing('basic', 'Rewards of Popping (All/Normal)', popAllFrag));
const popFattestFrag = document.createDocumentFragment();
popFattestFrag.appendChild(document.createTextNode(`${Beautify(CacheWrinklersFattest[0])} `));
const popFattestA = document.createElement('a');
popFattestA.textContent = 'Pop Single Fattest';
popFattestA.className = 'option';
popFattestA.onclick = function () { if (CacheWrinklersFattest[1] !== null) Game.wrinklers[CacheWrinklersFattest[1]].hp = 0; };
popFattestFrag.appendChild(popFattestA);
stats.appendChild(CreateElements.StatsListing('basic', `Rewards of Popping Single Fattest Non-Shiny Wrinkler (id: ${CacheWrinklersFattest[1] !== null ? CacheWrinklersFattest[1] : 'None'})`, popFattestFrag));
}
}
let specDisp = false;
const missingHalloweenCookies = [];
for (const i of Object.keys(GameData.HalloCookies)) {
if (!Game.Has(GameData.HalloCookies[i])) {
missingHalloweenCookies.push(GameData.HalloCookies[i]);
specDisp = true;
}
}
const missingChristmasCookies = [];
for (const i of Object.keys(GameData.ChristCookies)) {
if (!Game.Has(GameData.ChristCookies[i])) {
missingChristmasCookies.push(GameData.ChristCookies[i]);
specDisp = true;
}
}
const missingValentineCookies = [];
for (const i of Object.keys(GameData.ValCookies)) {
if (!Game.Has(GameData.ValCookies[i])) {
missingValentineCookies.push(GameData.ValCookies[i]);
specDisp = true;
}
}
const missingNormalEggs = [];
for (const i of Object.keys(Game.eggDrops)) {
if (!Game.HasUnlocked(Game.eggDrops[i])) {
missingNormalEggs.push(Game.eggDrops[i]);
specDisp = true;
}
}
const missingRareEggs = [];
for (const i of Object.keys(Game.rareEggDrops)) {
if (!Game.HasUnlocked(Game.rareEggDrops[i])) {
missingRareEggs.push(Game.rareEggDrops[i]);
specDisp = true;
}
}
const missingPlantDrops = [];
for (const i of Object.keys(GameData.PlantDrops)) {
if (!Game.HasUnlocked(GameData.PlantDrops[i])) {
missingPlantDrops.push(GameData.PlantDrops[i]);
specDisp = true;
}
}
const choEgg = (Game.HasUnlocked('Chocolate egg') && !Game.Has('Chocolate egg'));
const centEgg = Game.Has('Century egg');
if (Game.season === 'christmas' || specDisp || choEgg || centEgg) {
stats.appendChild(CreateElements.StatsHeader('Season Specials', 'Sea'));
if (CMOptions.Header.Sea) {
if (missingHalloweenCookies.length !== 0) stats.appendChild(CreateElements.StatsListing('basic', 'Halloween Cookies Left to Buy', CreateElements.StatsMissDisp(missingHalloweenCookies)));
if (missingChristmasCookies.length !== 0) stats.appendChild(CreateElements.StatsListing('basic', 'Christmas Cookies Left to Buy', CreateElements.StatsMissDisp(missingChristmasCookies)));
if (missingValentineCookies.length !== 0) stats.appendChild(CreateElements.StatsListing('basic', 'Valentine Cookies Left to Buy', CreateElements.StatsMissDisp(missingValentineCookies)));
if (missingNormalEggs.length !== 0) stats.appendChild(CreateElements.StatsListing('basic', 'Normal Easter Eggs Left to Unlock', CreateElements.StatsMissDisp(missingNormalEggs)));
if (missingRareEggs.length !== 0) stats.appendChild(CreateElements.StatsListing('basic', 'Rare Easter Eggs Left to Unlock', CreateElements.StatsMissDisp(missingRareEggs)));
if (missingPlantDrops.length !== 0) stats.appendChild(CreateElements.StatsListing('basic', 'Rare Plant Drops Left to Unlock', CreateElements.StatsMissDisp(missingPlantDrops)));
if (Game.season === 'christmas') stats.appendChild(CreateElements.StatsListing('basic', 'Reindeer Reward', document.createTextNode(Beautify(CacheSeaSpec))));
if (choEgg) {
stats.appendChild(CreateElements.StatsListing('withTooltip', 'Chocolate Egg Cookies', document.createTextNode(Beautify(CacheLastChoEgg)), 'ChoEggTooltipPlaceholder'));
}
if (centEgg) {
stats.appendChild(CreateElements.StatsListing('basic', 'Century Egg Multiplier', document.createTextNode(`${Math.round((CacheCentEgg - 1) * 10000) / 100}%`)));
}
}
}
stats.appendChild(CreateElements.StatsHeader('Miscellaneous', 'Misc'));
if (CMOptions.Header.Misc) {
stats.appendChild(CreateElements.StatsListing('basic',
`Average Cookies Per Second (Past ${CookieTimes[CMOptions.AvgCPSHist] < 60 ? (`${CookieTimes[CMOptions.AvgCPSHist]} seconds`) : ((CookieTimes[CMOptions.AvgCPSHist] / 60) + (CMOptions.AvgCPSHist === 3 ? ' minute' : ' minutes'))})`,
document.createTextNode(Beautify(GetCPS(), 3))));
stats.appendChild(CreateElements.StatsListing('basic', `Average Cookie Clicks Per Second (Past ${ClickTimes[CMOptions.AvgClicksHist]}${CMOptions.AvgClicksHist === 0 ? ' second' : ' seconds'})`, document.createTextNode(Beautify(CacheAverageClicks, 1))));
if (Game.Has('Fortune cookies')) {
const fortunes = [];
for (const i of Object.keys(GameData.Fortunes)) {
if (!Game.Has(GameData.Fortunes[i])) {
fortunes.push(GameData.Fortunes[i]);
}
}
if (fortunes.length !== 0) stats.appendChild(CreateElements.StatsListing('basic', 'Fortune Upgrades Left to Buy', CreateElements.StatsMissDisp(fortunes)));
}
if (CMOptions.ShowMissedGC) {
stats.appendChild(CreateElements.StatsListing('basic', 'Missed Golden Cookies', document.createTextNode(Beautify(Game.missedGoldenClicks))));
}
if (Game.prefs.autosave) {
const timer = document.createElement('span');
timer.id = 'CMStatsAutosaveTimer';
timer.innerText = Game.sayTime(Game.fps * 60 - (Game.OnAscend ? 0 : (Game.T % (Game.fps * 60))), 4);
stats.appendChild(CreateElements.StatsListing('basic', 'Time till autosave', timer));
}
}
l('menu').insertBefore(stats, l('menu').childNodes[2]);
if (CMOptions.MissingUpgrades) {
AddMissingUpgrades();
}
}

View File

@@ -0,0 +1,121 @@
/** Section: Functions related to the creation of basic DOM elements page */
import { ToggleHeader } from '../../Config/ToggleSetting';
import { CMOptions } from '../../Config/VariablesAndData';
import { TooltipText } from '../VariablesAndData';
/**
* This function creates a header-object for the stats page
* It is called by CM.Disp.AddMenuStats()
* @param {string} config The name of the Config-group
* @param {string} text The to-be displayed name of the header
* @returns {object} div The header object
*/
export function StatsHeader(text, config) {
const div = document.createElement('div');
div.className = 'title';
div.style.padding = '0px 16px';
div.style.opacity = '0.7';
div.style.fontSize = '17px';
div.style.fontFamily = '"Kavoon", Georgia, serif';
div.appendChild(document.createTextNode(`${text} `));
const span = document.createElement('span');
span.style.cursor = 'pointer';
span.style.display = 'inline-block';
span.style.height = '14px';
span.style.width = '14px';
span.style.borderRadius = '7px';
span.style.textAlign = 'center';
span.style.backgroundColor = '#C0C0C0';
span.style.color = 'black';
span.style.fontSize = '13px';
span.style.verticalAlign = 'middle';
span.textContent = CMOptions.Header[config] ? '-' : '+';
span.onclick = function () { ToggleHeader(config); Game.UpdateMenu(); };
div.appendChild(span);
return div;
}
/**
* This function creates an stats-listing-object for the stats page
* It is called by CM.Disp.AddMenuStats()
* @param {string} type The type fo the listing
* @param {string} name The name of the option
* @param {object} text The text-object of the option
* @param {string} placeholder The id of the to-be displayed tooltip if applicable
* @returns {object} div The option object
*/
export function StatsListing(type, name, text, placeholder) {
const div = document.createElement('div');
div.className = 'listing';
const listingName = document.createElement('b');
listingName.textContent = name;
div.appendChild(listingName);
if (type === 'withTooltip') {
div.className = 'listing';
div.appendChild(document.createTextNode(' '));
const tooltip = document.createElement('span');
tooltip.onmouseout = function () { Game.tooltip.hide(); };
tooltip.onmouseover = function () { Game.tooltip.draw(this, escape(TooltipText[placeholder].innerHTML)); };
tooltip.style.cursor = 'default';
tooltip.style.display = 'inline-block';
tooltip.style.height = '10px';
tooltip.style.width = '10px';
tooltip.style.borderRadius = '5px';
tooltip.style.textAlign = 'center';
tooltip.style.backgroundColor = '#C0C0C0';
tooltip.style.color = 'black';
tooltip.style.fontSize = '9px';
tooltip.style.verticalAlign = 'bottom';
tooltip.textContent = '?';
div.appendChild(tooltip);
}
div.appendChild(document.createTextNode(': '));
div.appendChild(text);
return div;
}
/**
* This function creates a tooltip containing all missing holiday items contained in the list theMissDisp
* @param {list} theMissDisp A list of the missing holiday items
* @returns {object} frag The tooltip object
*/
export function StatsMissDisp(theMissDisp) {
const frag = document.createDocumentFragment();
frag.appendChild(document.createTextNode(`${theMissDisp.length} `));
const span = document.createElement('span');
span.onmouseout = function () { Game.tooltip.hide(); };
const placeholder = document.createElement('div');
const missing = document.createElement('div');
missing.style.minWidth = '140px';
missing.style.marginBottom = '4px';
const title = document.createElement('div');
title.className = 'name';
title.style.marginBottom = '4px';
title.style.textAlign = 'center';
title.textContent = 'Missing';
missing.appendChild(title);
for (const i of Object.keys(theMissDisp)) {
const div = document.createElement('div');
div.style.textAlign = 'center';
div.appendChild(document.createTextNode(theMissDisp[i]));
missing.appendChild(div);
}
placeholder.appendChild(missing);
span.onmouseover = function () { Game.tooltip.draw(this, escape(placeholder.innerHTML)); };
span.style.cursor = 'default';
span.style.display = 'inline-block';
span.style.height = '10px';
span.style.width = '10px';
span.style.borderRadius = '5px';
span.style.textAlign = 'center';
span.style.backgroundColor = '#C0C0C0';
span.style.color = 'black';
span.style.fontSize = '9px';
span.style.verticalAlign = 'bottom';
span.textContent = '?';
frag.appendChild(span);
return frag;
}

View File

@@ -0,0 +1,79 @@
/** Functions related to displaying the missing upgrades in the Statistics page */
import { CacheMissingUpgrades, CacheMissingUpgradesCookies, CacheMissingUpgradesPrestige } from '../../Cache/VariablesAndData';
/**
* This function creates the missing upgrades sections for prestige, normal and cookie upgrades
*/
export function AddMissingUpgrades() {
for (const menuSection of (l('menu').children)) {
if (menuSection.children[0]) {
if (menuSection.children[0].innerHTML === 'Prestige' && CacheMissingUpgradesPrestige) {
const prestigeUpgradesMissing = CacheMissingUpgradesPrestige.match(new RegExp('div', 'g') || []).length / 2;
const title = document.createElement('div');
title.id = 'CMMissingUpgradesPrestigeTitle';
title.className = 'listing';
const titlefrag = document.createElement('div');
titlefrag.innerHTML = `<b>Missing Prestige upgrades:</b> ${prestigeUpgradesMissing}/${Game.PrestigeUpgrades.length} (${Math.floor((prestigeUpgradesMissing / Game.PrestigeUpgrades.length) * 100)}%)`;
title.appendChild(titlefrag);
menuSection.appendChild(title);
const upgrades = document.createElement('div');
upgrades.className = 'listing crateBox';
upgrades.innerHTML = CacheMissingUpgradesPrestige;
menuSection.appendChild(upgrades);
} else if (menuSection.children[0].innerHTML === 'Upgrades') {
if (CacheMissingUpgrades) {
const normalUpgradesMissing = CacheMissingUpgrades.match(new RegExp('div', 'g') || []).length / 2;
const title = document.createElement('div');
title.id = 'CMMissingUpgradesTitle';
title.className = 'listing';
const titlefrag = document.createElement('div');
titlefrag.innerHTML = `<b>Missing normal upgrades:</b> ${normalUpgradesMissing}/${Game.UpgradesByPool[''].length + Game.UpgradesByPool.tech.length} (${Math.floor((normalUpgradesMissing / (Game.UpgradesByPool[''].length + Game.UpgradesByPool.tech.length)) * 100)}%)`;
title.appendChild(titlefrag);
menuSection.insertBefore(title, menuSection.childNodes[3]);
const upgrades = document.createElement('div');
upgrades.className = 'listing crateBox';
upgrades.innerHTML = CacheMissingUpgrades;
menuSection.insertBefore(upgrades, document.getElementById('CMMissingUpgradesTitle').nextSibling);
}
if (CacheMissingUpgradesCookies) {
const cookieUpgradesMissing = CacheMissingUpgradesCookies.match(new RegExp('div', 'g') || []).length / 2;
const title = document.createElement('div');
title.id = 'CMMissingUpgradesCookiesTitle';
title.className = 'listing';
const titlefrag = document.createElement('div');
titlefrag.innerHTML = `<b>Missing Cookie upgrades:</b> ${cookieUpgradesMissing}/${Game.UpgradesByPool.cookie.length} (${Math.floor((cookieUpgradesMissing / Game.UpgradesByPool.cookie.length) * 100)}%)`;
title.appendChild(titlefrag);
menuSection.appendChild(title);
const upgrades = document.createElement('div');
upgrades.className = 'listing crateBox';
upgrades.innerHTML = CacheMissingUpgradesCookies;
menuSection.appendChild(upgrades);
}
}
}
}
}
/**
* This function returns the "crates" (icons) for missing upgrades in the stats sections
* It returns a html string that gets appended to the respective CM.Cache.MissingUpgrades-variable by CM.Cache.CacheMissingUpgrades()
* @param {object} me The upgrade object
* @returns {string} ? The HTML string that creates the icon.
*/
export function crateMissing(me) {
let classes = 'crate upgrade missing';
if (me.pool === 'prestige') classes += ' heavenly';
let noFrame = 0;
if (!Game.prefs.crates) noFrame = 1;
if (noFrame) classes += ' noFrame';
let icon = me.icon;
if (me.iconFunction) icon = me.iconFunction();
const tooltip = `function() {return Game.crateTooltip(Game.UpgradesById[${me.id}], 'stats');}`;
return `<div class="${classes}"
${Game.getDynamicTooltip(tooltip, 'top', true)}
style = "${(`${icon[2] ? `background-image: url(${icon[2]});` : ''}background-position:${-icon[0] * 48}px ${-icon[1] * 48}px`)};">
</div>`;
}

View File

@@ -0,0 +1,349 @@
/** Functions to create the individual sections of the Statistics page */
import { MaxChainCookieReward } from '../../Cache/Stats/ChainCookies';
import {
CacheAvgCPSWithChoEgg,
CacheChainFrenzyMaxReward,
CacheChainFrenzyRequired,
CacheChainFrenzyRequiredNext,
CacheChainFrenzyWrathRequired,
CacheChainFrenzyWrathRequiredNext,
CacheChainMaxReward,
CacheChainRequired,
CacheChainRequiredNext,
CacheChainWrathMaxReward,
CacheChainWrathRequired,
CacheChainWrathRequiredNext,
CacheConjure,
CacheConjureReward,
CacheDragonsFortuneMultAdjustment,
CacheEdifice,
CacheEdificeBuilding,
CacheGoldenCookiesMult,
CacheHCPerSecond, CacheLastChoEgg, CacheLucky, CacheLuckyFrenzy, CacheLuckyReward, CacheLuckyRewardFrenzy, CacheLuckyWrathReward, CacheLuckyWrathRewardFrenzy, CacheNoGoldSwitchCookiesPS, CacheRealCookiesEarned, CacheWrathCookiesMult, CacheWrinklersTotal,
} from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
import ResetBonus from '../../Sim/SimulationEvents/ResetAscension';
import { Beautify, FormatTime } from '../BeautifyAndFormatting/BeautifyFormatting';
import GetCPS from '../HelperFunctions/GetCPS';
import GetWrinkConfigBank from '../HelperFunctions/GetWrinkConfigBank';
import { ColorGreen, ColorRed, ColorTextPre } from '../VariablesAndData';
import { StatsListing } from './CreateDOMElements';
/**
* This function creates the "Lucky" section of the stats page
* @returns {object} section The object contating the Lucky section
*/
export function LuckySection() {
// This sets which tooltip to display for certain stats
const goldCookTooltip = Game.auraMult('Dragon\'s Fortune') ? 'GoldCookDragonsFortuneTooltipPlaceholder' : 'GoldCookTooltipPlaceholder';
const section = document.createElement('div');
section.className = 'CMStatsLuckySection';
const luckyColor = ((Game.cookies + GetWrinkConfigBank()) < CacheLucky) ? ColorRed : ColorGreen;
const luckyTime = ((Game.cookies + GetWrinkConfigBank()) < CacheLucky) ? FormatTime((CacheLucky - (Game.cookies + GetWrinkConfigBank())) / GetCPS()) : '';
const luckyReqFrag = document.createDocumentFragment();
const luckyReqSpan = document.createElement('span');
luckyReqSpan.style.fontWeight = 'bold';
luckyReqSpan.className = ColorTextPre + luckyColor;
luckyReqSpan.textContent = Beautify(CacheLucky);
luckyReqFrag.appendChild(luckyReqSpan);
if (luckyTime !== '') {
const luckyReqSmall = document.createElement('small');
luckyReqSmall.textContent = ` (${luckyTime})`;
luckyReqFrag.appendChild(luckyReqSmall);
}
section.appendChild(StatsListing('withTooltip', '"Lucky!" Cookies Required', luckyReqFrag, goldCookTooltip));
const luckyColorFrenzy = ((Game.cookies + GetWrinkConfigBank()) < CacheLuckyFrenzy) ? ColorRed : ColorGreen;
const luckyTimeFrenzy = ((Game.cookies + GetWrinkConfigBank()) < CacheLuckyFrenzy) ? FormatTime((CacheLuckyFrenzy - (Game.cookies + GetWrinkConfigBank())) / GetCPS()) : '';
const luckyReqFrenFrag = document.createDocumentFragment();
const luckyReqFrenSpan = document.createElement('span');
luckyReqFrenSpan.style.fontWeight = 'bold';
luckyReqFrenSpan.className = ColorTextPre + luckyColorFrenzy;
luckyReqFrenSpan.textContent = Beautify(CacheLuckyFrenzy);
luckyReqFrenFrag.appendChild(luckyReqFrenSpan);
if (luckyTimeFrenzy !== '') {
const luckyReqFrenSmall = document.createElement('small');
luckyReqFrenSmall.textContent = ` (${luckyTimeFrenzy})`;
luckyReqFrenFrag.appendChild(luckyReqFrenSmall);
}
section.appendChild(StatsListing('withTooltip', '"Lucky!" Cookies Required (Frenzy)', luckyReqFrenFrag, goldCookTooltip));
const luckySplit = CacheLuckyReward !== CacheLuckyWrathReward;
const luckyRewardMaxSpan = document.createElement('span');
luckyRewardMaxSpan.style.fontWeight = 'bold';
luckyRewardMaxSpan.className = ColorTextPre + CacheLuckyReward;
luckyRewardMaxSpan.textContent = Beautify(CacheLuckyReward) + (luckySplit ? (` / ${Beautify(CacheLuckyWrathReward)}`) : '');
section.appendChild(StatsListing('withTooltip', `"Lucky!" Reward (MAX)${luckySplit ? ' (Golden / Wrath)' : ''}`, luckyRewardMaxSpan, goldCookTooltip));
const luckyRewardFrenzyMaxSpan = document.createElement('span');
luckyRewardFrenzyMaxSpan.style.fontWeight = 'bold';
luckyRewardFrenzyMaxSpan.className = ColorTextPre + luckyRewardFrenzyMaxSpan;
luckyRewardFrenzyMaxSpan.textContent = Beautify(CacheLuckyRewardFrenzy) + (luckySplit ? (` / ${Beautify(CacheLuckyWrathRewardFrenzy)}`) : '');
section.appendChild(StatsListing('withTooltip', `"Lucky!" Reward (MAX) (Frenzy)${luckySplit ? ' (Golden / Wrath)' : ''}`, luckyRewardFrenzyMaxSpan, goldCookTooltip));
const luckyCurBase = Math.min((Game.cookies + GetWrinkConfigBank()) * 0.15, CacheNoGoldSwitchCookiesPS * CacheDragonsFortuneMultAdjustment * 60 * 15) + 13;
const luckyCurSpan = document.createElement('span');
luckyCurSpan.style.fontWeight = 'bold';
luckyCurSpan.className = ColorTextPre + luckyCurSpan;
luckyCurSpan.textContent = Beautify(CacheGoldenCookiesMult * luckyCurBase) + (luckySplit ? (` / ${Beautify(CacheWrathCookiesMult * luckyCurBase)}`) : '');
section.appendChild(StatsListing('withTooltip', `"Lucky!" Reward (CUR)${luckySplit ? ' (Golden / Wrath)' : ''}`, luckyCurSpan, goldCookTooltip));
return section;
}
/**
* This function creates the "Chain" section of the stats page
* @returns {object} section The object contating the Chain section
*/
export function ChainSection() {
// This sets which tooltip to display for certain stats
const goldCookTooltip = Game.auraMult('Dragon\'s Fortune') ? 'GoldCookDragonsFortuneTooltipPlaceholder' : 'GoldCookTooltipPlaceholder';
const section = document.createElement('div');
section.className = 'CMStatsChainSection';
const chainColor = ((Game.cookies + GetWrinkConfigBank()) < CacheChainRequired) ? ColorRed : ColorGreen;
const chainTime = ((Game.cookies + GetWrinkConfigBank()) < CacheChainRequired) ? FormatTime((CacheChainRequired - (Game.cookies + GetWrinkConfigBank())) / GetCPS()) : '';
const chainReqFrag = document.createDocumentFragment();
const chainReqSpan = document.createElement('span');
chainReqSpan.style.fontWeight = 'bold';
chainReqSpan.className = ColorTextPre + chainColor;
chainReqSpan.textContent = Beautify(CacheChainRequired);
chainReqFrag.appendChild(chainReqSpan);
if (chainTime !== '') {
const chainReqSmall = document.createElement('small');
chainReqSmall.textContent = ` (${chainTime})`;
chainReqFrag.appendChild(chainReqSmall);
}
section.appendChild(StatsListing('withTooltip', '"Chain" Cookies Required', chainReqFrag, goldCookTooltip));
const chainWrathColor = ((Game.cookies + GetWrinkConfigBank()) < CacheChainWrathRequired) ? ColorRed : ColorGreen;
const chainWrathTime = ((Game.cookies + GetWrinkConfigBank()) < CacheChainWrathRequired) ? FormatTime((CacheChainWrathRequired - (Game.cookies + GetWrinkConfigBank())) / GetCPS()) : '';
const chainWrathReqFrag = document.createDocumentFragment();
const chainWrathReqSpan = document.createElement('span');
chainWrathReqSpan.style.fontWeight = 'bold';
chainWrathReqSpan.className = ColorTextPre + chainWrathColor;
chainWrathReqSpan.textContent = Beautify(CacheChainWrathRequired);
chainWrathReqFrag.appendChild(chainWrathReqSpan);
if (chainWrathTime !== '') {
const chainWrathReqSmall = document.createElement('small');
chainWrathReqSmall.textContent = ` (${chainWrathTime})`;
chainWrathReqFrag.appendChild(chainWrathReqSmall);
}
section.appendChild(StatsListing('withTooltip', '"Chain" Cookies Required (Wrath)', chainWrathReqFrag, goldCookTooltip));
const chainColorFrenzy = ((Game.cookies + GetWrinkConfigBank()) < CacheChainFrenzyRequired) ? ColorRed : ColorGreen;
const chainTimeFrenzy = ((Game.cookies + GetWrinkConfigBank()) < CacheChainFrenzyRequired) ? FormatTime((CacheChainFrenzyRequired - (Game.cookies + GetWrinkConfigBank())) / GetCPS()) : '';
const chainReqFrenFrag = document.createDocumentFragment();
const chainReqFrenSpan = document.createElement('span');
chainReqFrenSpan.style.fontWeight = 'bold';
chainReqFrenSpan.className = ColorTextPre + chainColorFrenzy;
chainReqFrenSpan.textContent = Beautify(CacheChainFrenzyRequired);
chainReqFrenFrag.appendChild(chainReqFrenSpan);
if (chainTimeFrenzy !== '') {
const chainReqFrenSmall = document.createElement('small');
chainReqFrenSmall.textContent = ` (${chainTimeFrenzy})`;
chainReqFrenFrag.appendChild(chainReqFrenSmall);
}
section.appendChild(StatsListing('withTooltip', '"Chain" Cookies Required (Frenzy)', chainReqFrenFrag, goldCookTooltip));
const chainWrathColorFrenzy = ((Game.cookies + GetWrinkConfigBank()) < CacheChainFrenzyWrathRequired) ? ColorRed : ColorGreen;
const chainWrathTimeFrenzy = ((Game.cookies + GetWrinkConfigBank()) < CacheChainFrenzyWrathRequired) ? FormatTime((CacheChainFrenzyWrathRequired - (Game.cookies + GetWrinkConfigBank())) / GetCPS()) : '';
const chainWrathReqFrenFrag = document.createDocumentFragment();
const chainWrathReqFrenSpan = document.createElement('span');
chainWrathReqFrenSpan.style.fontWeight = 'bold';
chainWrathReqFrenSpan.className = ColorTextPre + chainWrathColorFrenzy;
chainWrathReqFrenSpan.textContent = Beautify(CacheChainFrenzyWrathRequired);
chainWrathReqFrenFrag.appendChild(chainWrathReqFrenSpan);
if (chainWrathTimeFrenzy !== '') {
const chainWrathReqFrenSmall = document.createElement('small');
chainWrathReqFrenSmall.textContent = ` (${chainWrathTimeFrenzy})`;
chainWrathReqFrenFrag.appendChild(chainWrathReqFrenSmall);
}
section.appendChild(StatsListing('withTooltip', '"Chain" Cookies Required (Frenzy) (Wrath)', chainWrathReqFrenFrag, goldCookTooltip));
section.appendChild(StatsListing('withTooltip', '"Chain" Reward (MAX) (Golden / Wrath)', document.createTextNode(`${Beautify(CacheChainMaxReward[0])} / ${Beautify(CacheChainWrathMaxReward[0])}`), goldCookTooltip));
section.appendChild(StatsListing('withTooltip', '"Chain" Reward (MAX) (Frenzy) (Golden / Wrath)', document.createTextNode((`${Beautify(CacheChainFrenzyMaxReward[0])} / ${Beautify(CacheChainFrenzyMaxReward[0])}`)), goldCookTooltip));
const chainCurMax = Math.min(Game.cookiesPs * 60 * 60 * 6 * CacheDragonsFortuneMultAdjustment, Game.cookies * 0.5);
const chainCur = MaxChainCookieReward(7, chainCurMax, CacheGoldenCookiesMult)[0];
const chainCurWrath = MaxChainCookieReward(6, chainCurMax, CacheWrathCookiesMult)[0];
section.appendChild(StatsListing('withTooltip', '"Chain" Reward (CUR) (Golden / Wrath)', document.createTextNode((`${Beautify(chainCur)} / ${Beautify(chainCurWrath)}`)), goldCookTooltip));
section.appendChild(StatsListing('withTooltip', 'CPS Needed For Next Level (G / W)', document.createTextNode((`${Beautify(CacheChainRequiredNext)} / ${Beautify(CacheChainWrathRequiredNext)}`)), 'ChainNextLevelPlaceholder'));
section.appendChild(StatsListing('withTooltip', 'CPS Needed For Next Level (Frenzy) (G / W)', document.createTextNode((`${Beautify(CacheChainFrenzyRequiredNext)} / ${Beautify(CacheChainFrenzyWrathRequiredNext)}`)), 'ChainNextLevelPlaceholder'));
return section;
}
/**
* This function creates the "Spells" section of the stats page
* @returns {object} section The object contating the Spells section
*/
export function SpellsSection() {
const section = document.createElement('div');
section.className = 'CMStatsSpellsSection';
const conjureColor = ((Game.cookies + GetWrinkConfigBank()) < CacheConjure) ? ColorRed : ColorGreen;
const conjureTime = ((Game.cookies + GetWrinkConfigBank()) < CacheConjure) ? FormatTime((CacheConjure - (Game.cookies + GetWrinkConfigBank())) / GetCPS()) : '';
const conjureReqFrag = document.createDocumentFragment();
const conjureReqSpan = document.createElement('span');
conjureReqSpan.style.fontWeight = 'bold';
conjureReqSpan.className = ColorTextPre + conjureColor;
conjureReqSpan.textContent = Beautify(CacheConjure);
conjureReqFrag.appendChild(conjureReqSpan);
if (conjureTime !== '') {
const conjureReqSmall = document.createElement('small');
conjureReqSmall.textContent = ` (${conjureTime})`;
conjureReqFrag.appendChild(conjureReqSmall);
}
section.appendChild(StatsListing('withTooltip', '"Conjure Baked Goods" Cookies Required', conjureReqFrag, 'GoldCookTooltipPlaceholder'));
section.appendChild(StatsListing('withTooltip', '"Conjure Baked Goods" Reward (MAX)', document.createTextNode(Beautify(CacheConjureReward)), 'GoldCookTooltipPlaceholder'));
const conjureFrenzyColor = ((Game.cookies + GetWrinkConfigBank()) < CacheConjure * 7) ? ColorRed : ColorGreen;
const conjureFrenzyCur = Math.min((Game.cookies + GetWrinkConfigBank()) * 0.15, CacheNoGoldSwitchCookiesPS * 60 * 30);
const conjureFrenzyTime = ((Game.cookies + GetWrinkConfigBank()) < CacheConjure * 7) ? FormatTime((CacheConjure * 7 - (Game.cookies + GetWrinkConfigBank())) / GetCPS()) : '';
const conjureFrenzyReqFrag = document.createDocumentFragment();
const conjureFrenzyReqSpan = document.createElement('span');
conjureFrenzyReqSpan.style.fontWeight = 'bold';
conjureFrenzyReqSpan.className = ColorTextPre + conjureFrenzyColor;
conjureFrenzyReqSpan.textContent = Beautify(CacheConjure * 7);
conjureFrenzyReqFrag.appendChild(conjureFrenzyReqSpan);
if (conjureFrenzyTime !== '') {
const conjureFrenzyReqSmall = document.createElement('small');
conjureFrenzyReqSmall.textContent = ` (${conjureFrenzyTime})`;
conjureFrenzyReqFrag.appendChild(conjureFrenzyReqSmall);
}
section.appendChild(StatsListing('withTooltip', '"Conjure Baked Goods" Cookies Required (Frenzy)', conjureFrenzyReqFrag, 'GoldCookTooltipPlaceholder'));
section.appendChild(StatsListing('withTooltip', '"Conjure Baked Goods" Reward (MAX) (Frenzy)', document.createTextNode(Beautify(CacheConjureReward * 7)), 'GoldCookTooltipPlaceholder'));
section.appendChild(StatsListing('withTooltip', '"Conjure Baked Goods" Reward (CUR)', document.createTextNode(Beautify(conjureFrenzyCur)), 'GoldCookTooltipPlaceholder'));
if (CacheEdifice) {
section.appendChild(StatsListing('withTooltip', '"Spontaneous Edifice" Cookies Required (most expensive building)', document.createTextNode(`${Beautify(CacheEdifice)} (${CacheEdificeBuilding})`), 'GoldCookTooltipPlaceholder'));
}
return section;
}
/**
* This function creates the "Garden" section of the stats page
* @returns {object} section The object contating the Spells section
*/
export function GardenSection() {
const section = document.createElement('div');
section.className = 'CMStatsGardenSection';
const bakeberryColor = (Game.cookies < Game.cookiesPs * 60 * 30) ? ColorRed : ColorGreen;
const bakeberryFrag = document.createElement('span');
bakeberryFrag.style.fontWeight = 'bold';
bakeberryFrag.className = ColorTextPre + bakeberryColor;
bakeberryFrag.textContent = Beautify(Game.cookiesPs * 60 * 30);
section.appendChild(StatsListing('basic', 'Cookies required for max reward of Bakeberry: ', bakeberryFrag));
const chocorootColor = (Game.cookies < Game.cookiesPs * 60 * 3) ? ColorRed : ColorGreen;
const chocorootFrag = document.createElement('span');
chocorootFrag.style.fontWeight = 'bold';
chocorootFrag.className = ColorTextPre + chocorootColor;
chocorootFrag.textContent = Beautify(Game.cookiesPs * 60 * 3);
section.appendChild(StatsListing('basic', 'Cookies required for max reward of Chocoroot: ', chocorootFrag));
const queenbeetColor = (Game.cookies < Game.cookiesPs * 60 * 60) ? ColorRed : ColorGreen;
const queenbeetFrag = document.createElement('span');
queenbeetFrag.style.fontWeight = 'bold';
queenbeetFrag.className = ColorTextPre + queenbeetColor;
queenbeetFrag.textContent = Beautify(Game.cookiesPs * 60 * 60);
section.appendChild(StatsListing('basic', 'Cookies required for max reward of Queenbeet: ', queenbeetFrag));
const duketaterColor = (Game.cookies < Game.cookiesPs * 60 * 120) ? ColorRed : ColorGreen;
const duketaterFrag = document.createElement('span');
duketaterFrag.style.fontWeight = 'bold';
duketaterFrag.className = ColorTextPre + duketaterColor;
duketaterFrag.textContent = Beautify(Game.cookiesPs * 60 * 120);
section.appendChild(StatsListing('basic', 'Cookies required for max reward of Duketater: ', duketaterFrag));
return section;
}
/**
* This function creates the "Prestige" section of the stats page
* @returns {object} section The object contating the Prestige section
*/
export function PrestigeSection() {
const section = document.createElement('div');
section.className = 'CMStatsPrestigeSection';
const possiblePresMax = Math.floor(Game.HowMuchPrestige(CacheRealCookiesEarned
+ Game.cookiesReset + CacheWrinklersTotal
+ (Game.HasUnlocked('Chocolate egg') && !Game.Has('Chocolate egg') ? CacheLastChoEgg : 0)));
section.appendChild(StatsListing('withTooltip', 'Prestige Level (CUR / MAX)', document.createTextNode(`${Beautify(Game.prestige)} / ${Beautify(possiblePresMax)}`), 'PrestMaxTooltipPlaceholder'));
const neededCook = Game.HowManyCookiesReset(possiblePresMax + 1) - (CacheRealCookiesEarned + Game.cookiesReset + CacheWrinklersTotal + ((Game.HasUnlocked('Chocolate egg') && !Game.Has('Chocolate egg') ? CacheLastChoEgg : 0) ? CacheLastChoEgg : 0));
const cookiesNextFrag = document.createDocumentFragment();
cookiesNextFrag.appendChild(document.createTextNode(Beautify(neededCook)));
const cookiesNextSmall = document.createElement('small');
cookiesNextSmall.textContent = ` (${FormatTime(neededCook / CacheAvgCPSWithChoEgg, 1)})`;
cookiesNextFrag.appendChild(cookiesNextSmall);
section.appendChild(StatsListing('withTooltip', 'Cookies To Next Level', cookiesNextFrag, 'NextPrestTooltipPlaceholder'));
section.appendChild(StatsListing('withTooltip', 'Heavenly Chips (CUR / MAX)', document.createTextNode(`${Beautify(Game.heavenlyChips)} / ${Beautify((possiblePresMax - Game.prestige) + Game.heavenlyChips)}`), 'HeavenChipMaxTooltipPlaceholder'));
section.appendChild(StatsListing('basic', 'Heavenly Chips Per Second (last 5 seconds)', document.createTextNode(Beautify(CacheHCPerSecond, 2))));
const HCTarget = Number(CMOptions.HeavenlyChipsTarget);
if (!Number.isNaN(HCTarget)) {
const CookiesTillTarget = HCTarget - Math.floor(Game.HowMuchPrestige(Game.cookiesReset + Game.cookiesEarned));
if (CookiesTillTarget > 0) {
section.appendChild(StatsListing('basic', 'Heavenly Chips To Target Set In Settings (CUR)', document.createTextNode(Beautify(CookiesTillTarget))));
section.appendChild(StatsListing('basic', 'Time To Target (CUR, Current 5 Second Average)', document.createTextNode(FormatTime(CookiesTillTarget / CacheHCPerSecond))));
}
}
const resetBonus = ResetBonus(possiblePresMax);
const resetFrag = document.createDocumentFragment();
resetFrag.appendChild(document.createTextNode(Beautify(resetBonus)));
const increase = Math.round(resetBonus / Game.cookiesPs * 10000);
if (Number.isFinite(increase) && increase !== 0) {
const resetSmall = document.createElement('small');
resetSmall.textContent = ` (${increase / 100}% of income)`;
resetFrag.appendChild(resetSmall);
}
section.appendChild(StatsListing('withTooltip', 'Reset Bonus Income', resetFrag, 'ResetTooltipPlaceholder'));
const currentPrestige = Math.floor(Game.HowMuchPrestige(Game.cookiesReset));
const willHave = Math.floor(Game.HowMuchPrestige(Game.cookiesReset + Game.cookiesEarned));
const willGet = willHave - currentPrestige;
if (!Game.Has('Lucky digit')) {
let delta7 = 7 - (willHave % 10);
if (delta7 < 0) delta7 += 10;
const next7Reset = willGet + delta7;
const next7Total = willHave + delta7;
const frag7 = document.createDocumentFragment();
frag7.appendChild(document.createTextNode(`${next7Total.toLocaleString()} / ${next7Reset.toLocaleString()} (+${delta7})`));
section.appendChild(StatsListing('basic', 'Next "Lucky Digit" (total / reset)', frag7));
}
if (!Game.Has('Lucky number')) {
let delta777 = 777 - (willHave % 1000);
if (delta777 < 0) delta777 += 1000;
const next777Reset = willGet + delta777;
const next777Total = willHave + delta777;
const frag777 = document.createDocumentFragment();
frag777.appendChild(document.createTextNode(`${next777Total.toLocaleString()} / ${next777Reset.toLocaleString()} (+${delta777})`));
section.appendChild(StatsListing('basic', 'Next "Lucky Number" (total / reset)', frag777));
}
if (!Game.Has('Lucky payout')) {
let delta777777 = 777777 - (willHave % 1000000);
if (delta777777 < 0) delta777777 += 1000000;
const next777777Reset = willGet + delta777777;
const next777777Total = willHave + delta777777;
const frag777777 = document.createDocumentFragment();
frag777777.appendChild(document.createTextNode(`${next777777Total.toLocaleString()} / ${next777777Reset.toLocaleString()} (+${delta777777})`));
section.appendChild(StatsListing('basic', 'Next "Lucky Payout" (total / reset)', frag777777));
}
return section;
}

View File

@@ -0,0 +1,42 @@
/** Functions related to the Stats page */
import { ToggleHeader } from '../../Config/ToggleSetting';
import { CMOptions } from '../../Config/VariablesAndData';
import { LatestReleaseNotes, ModDescription } from '../../Data/Moddata';
/**
* This function adds stats created by CookieMonster to the stats page
* @param {object} title On object that includes the title of the menu
*/
export default function AddMenuInfo(title) {
const info = document.createElement('div');
info.className = 'subsection';
const span = document.createElement('span');
span.style.cursor = 'pointer';
span.style.display = 'inline-block';
span.style.height = '14px';
span.style.width = '14px';
span.style.borderRadius = '7px';
span.style.textAlign = 'center';
span.style.backgroundColor = '#C0C0C0';
span.style.color = 'black';
span.style.fontSize = '13px';
span.style.verticalAlign = 'middle';
span.textContent = CMOptions.Header.InfoTab ? '-' : '+';
span.onclick = function () { ToggleHeader('InfoTab'); Game.UpdateMenu(); };
title.appendChild(span);
info.appendChild(title);
if (CMOptions.Header.InfoTab) {
const description = document.createElement('div');
description.innerHTML = ModDescription;
info.appendChild(description);
const notes = document.createElement('div');
notes.innerHTML = LatestReleaseNotes;
info.appendChild(notes);
}
const menu = l('menu').children[1];
menu.insertBefore(info, menu.children[1]);
}

View File

@@ -0,0 +1,9 @@
import { CMOptions } from '../../Config/VariablesAndData';
/**
* This function refreshes the stats page, CM.Options.UpStats determines the rate at which that happens
* It is called by CM.Disp.Draw()
*/
export default function RefreshMenu() {
if (CMOptions.UpStats && Game.onMenu === 'stats' && (Game.drawT - 1) % (Game.fps * 5) !== 0 && (Game.drawT - 1) % Game.fps === 0) Game.UpdateMenu();
}

View File

@@ -0,0 +1,221 @@
/** Functions related to the Options/Preferences page */
import jscolor, * as JsColor from '@eastdesire/jscolor';
import { LoadConfig, SaveConfig } from '../../Config/SaveLoadReload/SaveLoadReloadSettings';
import {
ConfigPrefix, ToggleConfig, ToggleConfigVolume, ToggleHeader,
} from '../../Config/ToggleSetting';
import { CMOptions } from '../../Config/VariablesAndData';
import { ConfigGroups, ConfigGroupsNotification } from '../../Data/Sectionheaders';
import Config from '../../Data/SettingsData';
import ConfigDefault from '../../Data/SettingsDefault';
import RefreshScale from '../HelperFunctions/RefreshScale';
import UpdateColors from '../HelperFunctions/UpdateColors';
import { Colors } from '../VariablesAndData';
/**
* This function creates a header-object for the options page
* @param {string} config The name of the Config-group
* @param {string} text The to-be displayed name of the header
* @returns {object} div The header object
*/
function CreatePrefHeader(config, text) {
const div = document.createElement('div');
div.className = 'title';
div.style.opacity = '0.7';
div.style.fontSize = '17px';
div.appendChild(document.createTextNode(`${text} `));
const span = document.createElement('span'); // Creates the +/- button
span.style.cursor = 'pointer';
span.style.display = 'inline-block';
span.style.height = '14px';
span.style.width = '14px';
span.style.borderRadius = '7px';
span.style.textAlign = 'center';
span.style.backgroundColor = '#C0C0C0';
span.style.color = 'black';
span.style.fontSize = '13px';
span.style.verticalAlign = 'middle';
span.textContent = CMOptions.Header[config] ? '-' : '+';
span.onclick = function () { ToggleHeader(config); Game.UpdateMenu(); };
div.appendChild(span);
return div;
}
/**
* This function creates an option-object for the options page
* @param {string} config The name of the option
* @returns {object} div The option object
*/
function CreatePrefOption(config) {
const div = document.createElement('div');
div.className = 'listing';
if (Config[config].type === 'bool') {
const a = document.createElement('a');
if (Config[config].toggle && CMOptions[config] === 0) {
a.className = 'option off';
} else {
a.className = 'option';
}
a.id = ConfigPrefix + config;
a.onclick = function () { ToggleConfig(config); };
a.textContent = Config[config].label[CMOptions[config]];
div.appendChild(a);
const label = document.createElement('label');
label.textContent = Config[config].desc;
div.appendChild(label);
return div;
} if (Config[config].type === 'vol') {
const volume = document.createElement('div');
volume.className = 'sliderBox';
const title = document.createElement('div');
title.style.float = 'left';
title.innerHTML = Config[config].desc;
volume.appendChild(title);
const percent = document.createElement('div');
percent.id = `slider${config}right`;
percent.style.float = 'right';
percent.innerHTML = `${CMOptions[config]}%`;
volume.appendChild(percent);
const slider = document.createElement('input');
slider.className = 'slider';
slider.id = `slider${config}`;
slider.style.clear = 'both';
slider.type = 'range';
slider.min = '0';
slider.max = '100';
slider.step = '1';
slider.value = CMOptions[config];
slider.oninput = function () { ToggleConfigVolume(config); };
slider.onchange = function () { ToggleConfigVolume(config); };
volume.appendChild(slider);
div.appendChild(volume);
return div;
} if (Config[config].type === 'url') {
const span = document.createElement('span');
span.className = 'option';
span.textContent = `${Config[config].label} `;
div.appendChild(span);
const input = document.createElement('input');
input.id = ConfigPrefix + config;
input.className = 'option';
input.type = 'text';
input.readOnly = true;
input.setAttribute('value', CMOptions[config]);
input.style.width = '300px';
div.appendChild(input);
div.appendChild(document.createTextNode(' '));
const inputPrompt = document.createElement('input');
inputPrompt.id = `${ConfigPrefix + config}Prompt`;
inputPrompt.className = 'option';
inputPrompt.type = 'text';
inputPrompt.setAttribute('value', CMOptions[config]);
const a = document.createElement('a');
a.className = 'option';
a.onclick = function () {
Game.Prompt(inputPrompt.outerHTML, [['Save', function () { CMOptions[`${config}`] = l(`${ConfigPrefix}${config}Prompt`).value; SaveConfig(); Game.ClosePrompt(); Game.UpdateMenu(); }], 'Cancel']);
};
a.textContent = 'Edit';
div.appendChild(a);
const label = document.createElement('label');
label.textContent = Config[config].desc;
div.appendChild(label);
return div;
} if (Config[config].type === 'color') {
div.className = '';
for (let i = 0; i < Colors.length; i++) {
const innerDiv = document.createElement('div');
innerDiv.className = 'listing';
const input = document.createElement('input');
input.id = Colors[i];
input.style.width = '65px';
input.setAttribute('value', CMOptions.Colors[Colors[i]]);
innerDiv.appendChild(input);
const change = function () {
CMOptions.Colors[this.targetElement.id] = this.toHEXString();
UpdateColors();
SaveConfig();
Game.UpdateMenu();
};
new JsColor(input, { hash: true, position: 'right', onInput: change });
const label = document.createElement('label');
label.textContent = Config.Colors.desc[Colors[i]];
innerDiv.appendChild(label);
div.appendChild(innerDiv);
}
jscolor.init();
return div;
} if (Config[config].type === 'numscale') {
const span = document.createElement('span');
span.className = 'option';
span.textContent = `${Config[config].label} `;
div.appendChild(span);
const input = document.createElement('input');
input.id = ConfigPrefix + config;
input.className = 'option';
input.type = 'number';
input.value = (CMOptions[config]);
input.min = Config[config].min;
input.max = Config[config].max;
input.oninput = function () {
if (this.value > this.max) console.log('TEST');
CMOptions[config] = this.value;
SaveConfig();
RefreshScale();
};
div.appendChild(input);
div.appendChild(document.createTextNode(' '));
const label = document.createElement('label');
label.textContent = Config[config].desc;
div.appendChild(label);
return div;
}
return div;
}
/**
* This function adds the options/settings of CookieMonster to the options page
* It is called by CM.Disp.AddMenu
* @param {object} title On object that includes the title of the menu
*/
export default function AddMenuPref(title) {
const frag = document.createDocumentFragment();
frag.appendChild(title);
for (const group of Object.keys(ConfigGroups)) {
const groupObject = CreatePrefHeader(group, ConfigGroups[group]); // (group, display-name of group)
frag.appendChild(groupObject);
if (CMOptions.Header[group]) { // 0 is show, 1 is collapsed
// Make sub-sections of Notification section
if (group === 'Notification') {
for (const subGroup of Object.keys(ConfigGroupsNotification)) {
const subGroupObject = CreatePrefHeader(subGroup, ConfigGroupsNotification[subGroup]); // (group, display-name of group)
subGroupObject.style.fontSize = '15px';
subGroupObject.style.opacity = '0.5';
frag.appendChild(subGroupObject);
if (CMOptions.Header[subGroup]) {
for (const option in Config) {
if (Config[option].group === subGroup) frag.appendChild(CreatePrefOption(option));
}
}
}
} else {
for (const option of Object.keys(Config)) {
if (Config[option].group === group) frag.appendChild(CreatePrefOption(option));
}
}
}
}
const resDef = document.createElement('div');
resDef.className = 'listing';
const resDefBut = document.createElement('a');
resDefBut.className = 'option';
resDefBut.onclick = function () { LoadConfig(ConfigDefault); };
resDefBut.textContent = 'Restore Default';
resDef.appendChild(resDefBut);
frag.appendChild(resDef);
l('menu').childNodes[2].insertBefore(frag, l('menu').childNodes[2].childNodes[l('menu').childNodes[2].childNodes.length - 1]);
}

View File

@@ -0,0 +1,25 @@
import { CMOptions } from '../../Config/VariablesAndData';
import { isInitializing } from '../../InitSaveLoad/Variables';
/**
* This function creates a flash depending on configs. It is called by all functions
* that check game-events and which have settings for Flashes (e.g., Golden Cookies appearing, Magic meter being full)
* @param {number} mode Sets the intensity of the flash, used to recursively dim flash
* All calls of function have use mode === 3
* @param {string} config The setting in CM.Options that is checked before creating the flash
*/
export default function Flash(mode, config) {
// The arguments check makes the sound not play upon initialization of the mod
if ((CMOptions[config] === 1 && mode === 3 && isInitializing === false) || mode === 1) {
l('CMWhiteScreen').style.opacity = '0.5';
if (mode === 3) {
l('CMWhiteScreen').style.display = 'inline';
setTimeout(function () { Flash(2, config); }, 1000 / Game.fps);
} else {
setTimeout(function () { Flash(0, config); }, 1000 / Game.fps);
}
} else if (mode === 2) {
l('CMWhiteScreen').style.opacity = '1';
setTimeout(function () { Flash(1, config); }, 1000 / Game.fps);
} else if (mode === 0) l('CMWhiteScreen').style.display = 'none';
}

View File

@@ -0,0 +1,19 @@
/** Functions related to the flashes/sound/notifications */
import { CMOptions } from '../../Config/VariablesAndData';
import { isInitializing } from '../../InitSaveLoad/Variables';
/**
* This function creates a notifcation depending on configs. It is called by all functions
* that check game-events and which have settings for notifications (e.g., Golden Cookies appearing, Magic meter being full)
* @param {string} notifyConfig The setting in CM.Options that is checked before creating the notification
* @param {string} title The title of the to-be created notifications
* @param {string} message The text of the to-be created notifications
*/
export default function Notification(notifyConfig, title, message) {
// The arguments check makes the sound not play upon initialization of the mod
if (CMOptions[notifyConfig] === 1 && document.visibilityState === 'hidden' && isInitializing === false) {
const CookieIcon = 'https://orteil.dashnet.org/cookieclicker/favicon.ico';
new Notification(title, { body: message, badge: CookieIcon });
}
}

View File

@@ -0,0 +1,20 @@
import { CMOptions } from '../../Config/VariablesAndData';
import { isInitializing } from '../../InitSaveLoad/Variables';
/**
* This function plays a sound depending on configs. It is called by all functions
* that check game-events and which have settings for sound (e.g., Golden Cookies appearing, Magic meter being full)
* @param {variable} url A variable that gives the url for the sound (e.g., CM.Options.GCSoundURL)
* @param {string} sndConfig The setting in CM.Options that is checked before creating the sound
* @param {string} volConfig The setting in CM.Options that is checked to determine volume
*/
export default function PlaySound(url, sndConfig, volConfig) {
// The arguments check makes the sound not play upon initialization of the mod
if (CMOptions[sndConfig] === 1 && isInitializing === false) {
// eslint-disable-next-line new-cap
const sound = new realAudio(url);
if (CMOptions.GeneralSound) sound.volume = (CMOptions[volConfig] / 100) * (Game.volume / 100);
else sound.volume = (CMOptions[volConfig] / 100);
sound.play();
}
}

View File

@@ -0,0 +1,25 @@
import { CacheSpawnedGoldenShimmer } from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
import { LastGoldenCookieState } from '../../Main/VariablesAndData';
/**
* This function creates the Favicon, it is called by CM.Main.DelayInit()
*/
export function CreateFavicon() {
const Favicon = document.createElement('link');
Favicon.id = 'CMFavicon';
Favicon.rel = 'shortcut icon';
Favicon.href = 'https://orteil.dashnet.org/cookieclicker/favicon.ico';
document.getElementsByTagName('head')[0].appendChild(Favicon);
}
/**
* This function updates the Favicon depending on whether a Golden Cookie has spawned
* By relying on CM.Cache.spawnedGoldenShimmer it only changes for non-user spawned cookie
*/
export function UpdateFavicon() {
if (CMOptions.Favicon === 1 && LastGoldenCookieState > 0) {
if (CacheSpawnedGoldenShimmer.wrath) l('CMFavicon').href = 'https://aktanusa.github.io/CookieMonster/favicon/wrathCookie.ico';
else l('CMFavicon').href = 'https://aktanusa.github.io/CookieMonster/favicon/goldenCookie.ico';
} else l('CMFavicon').href = 'https://orteil.dashnet.org/cookieclicker/favicon.ico';
}

View File

@@ -0,0 +1,70 @@
/** Functions related to updating the tab in the browser's tab-bar */
import { CacheSeasonPopShimmer, CacheSpawnedGoldenShimmer } from '../../Cache/VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
import { LastSeasonPopupState, LastTickerFortuneState } from '../../Main/VariablesAndData';
import { Title } from '../VariablesAndData';
/**
* This function updates the tab title
* It is called on every loop by Game.Logic() which also sets CM.Disp.Title to Game.cookies
*/
export default function UpdateTitle() {
if (Game.OnAscend || CMOptions.Title === 0) {
document.title = Title;
} else if (CMOptions.Title === 1) {
let addFC = false;
let addSP = false;
let titleGC;
let titleFC;
let titleSP;
if (CacheSpawnedGoldenShimmer) {
if (CacheSpawnedGoldenShimmer.wrath) titleGC = `[W${Math.ceil(CacheSpawnedGoldenShimmer.life / Game.fps)}]`;
else titleGC = `[G${Math.ceil(CacheSpawnedGoldenShimmer.life / Game.fps)}]`;
} else if (!Game.Has('Golden switch [off]')) {
titleGC = `[${Number(l('CMTimerBarGCMinBar').textContent) < 0 ? '!' : ''}${Math.ceil((Game.shimmerTypes.golden.maxTime - Game.shimmerTypes.golden.time) / Game.fps)}]`;
} else titleGC = '[GS]';
if (LastTickerFortuneState) {
addFC = true;
titleFC = '[F]';
}
if (Game.season === 'christmas') {
addSP = true;
if (LastSeasonPopupState) titleSP = `[R${Math.ceil(CacheSeasonPopShimmer.life / Game.fps)}]`;
else {
titleSP = `[${Number(l('CMTimerBarRenMinBar').textContent) < 0 ? '!' : ''}${Math.ceil((Game.shimmerTypes.reindeer.maxTime - Game.shimmerTypes.reindeer.time) / Game.fps)}]`;
}
}
// Remove previous timers and add current cookies
let str = Title;
if (str.charAt(0) === '[') {
str = str.substring(str.lastIndexOf(']') + 1);
}
document.title = `${titleGC + (addFC ? titleFC : '') + (addSP ? titleSP : '')} ${str}`;
} else if (CMOptions.Title === 2) {
let str = '';
let spawn = false;
if (CacheSpawnedGoldenShimmer) {
spawn = true;
if (CacheSpawnedGoldenShimmer.wrath) str += `[W${Math.ceil(CacheSpawnedGoldenShimmer.life / Game.fps)}]`;
else str += `[G${Math.ceil(CacheSpawnedGoldenShimmer.life / Game.fps)}]`;
}
if (LastTickerFortuneState) {
spawn = true;
str += '[F]';
}
if (Game.season === 'christmas' && LastSeasonPopupState) {
str += `[R${Math.ceil(CacheSeasonPopShimmer.life / Game.fps)}]`;
spawn = true;
}
if (spawn) str += ' - ';
let title = 'Cookie Clicker';
if (Game.season === 'fools') title = 'Cookie Baker';
str += title;
document.title = str;
}
}

View File

@@ -0,0 +1,130 @@
import { CMOptions } from '../../Config/VariablesAndData';
import {
ColorTextPre, ColorBorderPre, ColorGray, ColorBlue, ColorRed, ColorYellow, ColorPurple, TooltipType,
} from '../VariablesAndData';
/** Creates various sections of tooltips */
/**
* This function creates a tooltipBox object which contains all CookieMonster added tooltip information.
* @returns {object} div An object containing the stylized box
*/
export function TooltipCreateTooltipBox() {
l('tooltip').firstChild.style.paddingBottom = '4px'; // Sets padding on base-tooltip
const tooltipBox = document.createElement('div');
tooltipBox.style.border = '1px solid';
tooltipBox.style.padding = '4px';
tooltipBox.style.margin = '0px -4px';
tooltipBox.id = 'CMTooltipBorder';
tooltipBox.className = ColorTextPre + ColorGray;
return tooltipBox;
}
/**
* This function creates a header object for tooltips.
* @param {string} text Title of header
* @returns {object} div An object containing the stylized header
*/
export function TooltipCreateHeader(text) {
const div = document.createElement('div');
div.style.fontWeight = 'bold';
div.id = `${text}Title`;
div.className = ColorTextPre + ColorBlue;
div.textContent = text;
return div;
}
/**
* This function creates the tooltip objectm for warnings
* The object is also removed by CM.Disp.UpdateTooltipWarnings() when type is 's' or 'g'
* @returns {object} TooltipWarn The Warnings-tooltip object
*/
export function TooltipCreateWarningSection() {
const TooltipWarn = document.createElement('div');
TooltipWarn.style.position = 'absolute';
TooltipWarn.style.display = 'block';
TooltipWarn.style.left = 'auto';
TooltipWarn.style.bottom = 'auto';
TooltipWarn.id = 'CMDispTooltipWarningParent';
const create = function (boxId, color, labelTextFront, labelTextBack, deficitId) {
const box = document.createElement('div');
box.id = boxId;
box.style.display = 'none';
box.style.transition = 'opacity 0.1s ease-out';
box.className = ColorBorderPre + color;
box.style.padding = '2px';
box.style.background = '#000 url(img/darkNoise.png)';
const labelDiv = document.createElement('div');
box.appendChild(labelDiv);
const labelSpan = document.createElement('span');
labelSpan.className = ColorTextPre + color;
labelSpan.style.fontWeight = 'bold';
labelSpan.textContent = labelTextFront;
labelDiv.appendChild(labelSpan);
labelDiv.appendChild(document.createTextNode(labelTextBack));
const deficitDiv = document.createElement('div');
box.appendChild(deficitDiv);
const deficitSpan = document.createElement('span');
deficitSpan.id = deficitId;
deficitDiv.appendChild(document.createTextNode('Deficit: '));
deficitDiv.appendChild(deficitSpan);
return box;
};
TooltipWarn.appendChild(create('CMDispTooltipWarnLucky', ColorRed, 'Warning: ', 'Purchase of this item will put you under the number of Cookies required for "Lucky!"', 'CMDispTooltipWarnLuckyText'));
TooltipWarn.firstChild.style.marginBottom = '4px';
TooltipWarn.appendChild(create('CMDispTooltipWarnLuckyFrenzy', ColorYellow, 'Warning: ', 'Purchase of this item will put you under the number of Cookies required for "Lucky!" (Frenzy)', 'CMDispTooltipWarnLuckyFrenzyText'));
TooltipWarn.lastChild.style.marginBottom = '4px';
TooltipWarn.appendChild(create('CMDispTooltipWarnConjure', ColorPurple, 'Warning: ', 'Purchase of this item will put you under the number of Cookies required for "Conjure Baked Goods"', 'CMDispTooltipWarnConjureText'));
TooltipWarn.lastChild.style.marginBottom = '4px';
TooltipWarn.appendChild(create('CMDispTooltipWarnConjureFrenzy', ColorPurple, 'Warning: ', 'Purchase of this item will put you under the number of Cookies required for "Conjure Baked Goods" (Frenzy)', 'CMDispTooltipWarnConjureFrenzyText'));
TooltipWarn.lastChild.style.marginBottom = '4px';
TooltipWarn.appendChild(create('CMDispTooltipWarnEdifice', ColorPurple, 'Warning: ', 'Purchase of this item will put you under the number of Cookies needed for "Spontaneous Edifice" to possibly give you your most expensive building"', 'CMDispTooltipWarnEdificeText'));
TooltipWarn.lastChild.style.marginBottom = '4px';
TooltipWarn.appendChild(create('CMDispTooltipWarnUser', ColorRed, 'Warning: ', `Purchase of this item will put you under the number of Cookies equal to ${CMOptions.ToolWarnUser} seconds of CPS`, 'CMDispTooltipWarnUserText'));
return TooltipWarn;
}
/**
* This function appends the sections for Bonus Income, PP and Time left (to achiev) to the tooltip-object
* The actual data is added by the Update-functions themselves
* @param {object} tooltip Object of a TooltipBox, normally created by a call to CM.Disp.TooltipCreateTooltipBox()
*/
export function TooltipCreateCalculationSection(tooltip) {
tooltip.appendChild(TooltipCreateHeader('Bonus Income'));
const income = document.createElement('div');
income.style.marginBottom = '4px';
income.style.color = 'white';
income.id = 'CMTooltipIncome';
tooltip.appendChild(income);
tooltip.appendChild(TooltipCreateHeader('Bonus Cookies per Click'));
tooltip.lastChild.style.display = 'none';
const click = document.createElement('div');
click.style.marginBottom = '4px';
click.style.color = 'white';
click.style.display = 'none';
click.id = 'CMTooltipCookiePerClick';
tooltip.appendChild(click);
tooltip.appendChild(TooltipCreateHeader('Payback Period'));
const pp = document.createElement('div');
pp.style.marginBottom = '4px';
pp.id = 'CMTooltipPP';
tooltip.appendChild(pp);
tooltip.appendChild(TooltipCreateHeader('Time Left'));
const time = document.createElement('div');
time.id = 'CMTooltipTime';
tooltip.appendChild(time);
if (TooltipType === 'b') {
tooltip.appendChild(TooltipCreateHeader('Production left till next achievement'));
tooltip.lastChild.id = 'CMTooltipProductionHeader'; // Assign a id in order to hid when no achiev's are left
const production = document.createElement('div');
production.id = 'CMTooltipProduction';
tooltip.appendChild(production);
}
}

View File

@@ -0,0 +1,19 @@
import { CMOptions } from '../../Config/VariablesAndData';
/**
* This function updates the location of the tooltip
* It is called by Game.tooltip.update() because of CM.Main.ReplaceNative()
*/
export default function UpdateTooltipLocation() {
if (Game.tooltip.origin === 'store') {
let warnOffset = 0;
if (CMOptions.ToolWarnLucky === 1 && CMOptions.ToolWarnPos === 1 && l('CMDispTooltipWarningParent') !== null) {
warnOffset = l('CMDispTooltipWarningParent').clientHeight - 4;
}
Game.tooltip.tta.style.top = `${Math.min(parseInt(Game.tooltip.tta.style.top, 10), (l('game').clientHeight + l('topBar').clientHeight) - Game.tooltip.tt.clientHeight - warnOffset - 46)}px`;
}
// Kept for future possible use if the code changes again
/* else if (!Game.onCrate && !Game.OnAscend && CM.Options.TimerBar === 1 && CM.Options.TimerBarPos === 0) {
Game.tooltip.tta.style.top = (parseInt(Game.tooltip.tta.style.top) + parseInt(CM.Disp.TimerBar.style.height)) + 'px';
} */
}

View File

@@ -0,0 +1,116 @@
/* eslint-disable no-unused-vars */
import * as UpdateTooltip from './UpdateTooltips';
import { TooltipCreateTooltipBox } from './CreateTooltip';
import { Beautify, GetTimeColor } from '../BeautifyAndFormatting/BeautifyFormatting';
import CopyData from '../../Sim/SimulationData/CopyData';
import { TooltipName, TooltipType } from '../VariablesAndData';
import { CMOptions } from '../../Config/VariablesAndData';
import BuildingGetPrice from '../../Sim/SimulationEvents/BuyBuilding';
/** All general functions related to creating and updating tooltips */
/**
* This function creates some very basic tooltips, (e.g., the tooltips in the stats page)
* The tooltips are created with CM.Disp[placeholder].appendChild(desc)
* @param {string} placeholder The name used to later refer and spawn the tooltip
* @param {string} text The text of the tooltip
* @param {string} minWidth The minimum width of the tooltip
*/
export function CreateSimpleTooltip(placeholder, text, minWidth) {
const Tooltip = document.createElement('div');
Tooltip.id = placeholder;
const desc = document.createElement('div');
desc.style.minWidth = minWidth;
desc.style.marginBottom = '4px';
const div = document.createElement('div');
div.style.textAlign = 'left';
div.textContent = text;
desc.appendChild(div);
Tooltip.appendChild(desc);
}
/**
* This function updates the sections of the tooltips created by CookieMonster
*/
export function UpdateTooltips() {
CopyData();
if (l('tooltipAnchor').style.display !== 'none' && l('CMTooltipArea')) {
l('CMTooltipArea').innerHTML = '';
const tooltipBox = TooltipCreateTooltipBox();
l('CMTooltipArea').appendChild(tooltipBox);
if (TooltipType === 'b') {
UpdateTooltip.Building();
} else if (TooltipType === 'u') {
UpdateTooltip.Upgrade();
} else if (TooltipType === 's') {
UpdateTooltip.SugarLump();
} else if (TooltipType === 'g') {
UpdateTooltip.Grimoire();
} else if (TooltipType === 'p') {
UpdateTooltip.GardenPlots();
} else if (TooltipType === 'ha') {
UpdateTooltip.HarvestAll();
}
UpdateTooltip.Warnings();
} else if (l('CMTooltipArea') === null) { // Remove warnings if its a basic tooltip
if (l('CMDispTooltipWarningParent') !== null) {
l('CMDispTooltipWarningParent').remove();
}
}
}
/**
* This function enhance the standard tooltips by creating and changing l('tooltip')
* The function is called by .onmouseover events that have replaced original code to use CM.Disp.Tooltip()
* @param {string} type Type of tooltip (b, u, s or g)
* @param {string} name Name of the object/item the tooltip relates to
* @returns {string} l('tooltip').innerHTML The HTML of the l('tooltip')-object
*/
export function CreateTooltip(type, name) {
if (type === 'b') { // Buildings
l('tooltip').innerHTML = Game.Objects[name].tooltip();
// Adds amortization info to the list of info per building
if (CMOptions.TooltipAmor === 1) {
const buildPrice = BuildingGetPrice(Game.Objects[name], Game.Objects[name].basePrice, 0, Game.Objects[name].free, Game.Objects[name].amount);
const amortizeAmount = buildPrice - Game.Objects[name].totalCookies;
if (amortizeAmount > 0) {
l('tooltip').innerHTML = l('tooltip').innerHTML
.split('so far</div>')
.join(`so far<br/>&bull; <b>${Beautify(amortizeAmount)}</b> ${Math.floor(amortizeAmount) === 1 ? 'cookie' : 'cookies'} left to amortize (${GetTimeColor((buildPrice - Game.Objects[name].totalCookies) / (Game.Objects[name].storedTotalCps * Game.globalCpsMult)).text})</div>`);
}
}
if (Game.buyMode === -1) {
/*
* Fix sell price displayed in the object tooltip.
*
* The buildings sell price displayed by the game itself (without any mod) is incorrect.
* The following line of code fixes this issue, and can be safely removed when the game gets fixed.
*
* This issue is extensively detailed here: https://github.com/Aktanusa/CookieMonster/issues/359#issuecomment-735658262
*/
l('tooltip').innerHTML = l('tooltip').innerHTML.split(Beautify(Game.Objects[name].bulkPrice)).join(Beautify((Game.Objects[name], Game.Objects[name].basePrice, Game.Objects[name].amount, Game.Objects[name].free, Game.buyBulk, 1)));
}
} else if (type === 'u') { // Upgrades
if (!Game.UpgradesInStore[name]) return '';
l('tooltip').innerHTML = Game.crateTooltip(Game.UpgradesInStore[name], 'store');
} else if (type === 's') l('tooltip').innerHTML = Game.lumpTooltip(); // Sugar Lumps
else if (type === 'g') l('tooltip').innerHTML = Game.Objects['Wizard tower'].minigame.spellTooltip(name)(); // Grimoire
else if (type === 'p') l('tooltip').innerHTML = Game.ObjectsById[2].minigame.tileTooltip(name[0], name[1])(); // Garden plots
else if (type === 'ha') l('tooltip').innerHTML = Game.ObjectsById[2].minigame.toolTooltip(1)(); // Harvest all button in garden
// Adds area for extra tooltip-sections
if ((type === 'b' && Game.buyMode === 1) || type === 'u' || type === 's' || type === 'g' || (type === 'p' && !Game.keys[16]) || type === 'ha') {
const area = document.createElement('div');
area.id = 'CMTooltipArea';
l('tooltip').appendChild(area);
}
// Sets global variables used by CM.Disp.UpdateTooltip()
TooltipType = type;
TooltipName = name;
UpdateTooltips();
return l('tooltip').innerHTML;
}

View File

@@ -0,0 +1,344 @@
import GetCPSBuffMult from '../../Cache/CPS/GetCPSBuffMult';
import {
CacheEdifice, CacheLastChoEgg, CacheLucky, CacheNoGoldSwitchCookiesPS, CacheObjects1, CacheObjects10, CacheObjects100, CacheUpgrades,
} from '../../Cache/VariablesAndData';
import ToggleToolWarnPos from '../../Config/Toggles/ToggleToolWarnPos';
import { CMOptions } from '../../Config/VariablesAndData';
import { SimObjects } from '../../Sim/VariablesAndData';
import { Beautify, FormatTime, GetTimeColor } from '../BeautifyAndFormatting/BeautifyFormatting';
import CalculateGrimoireRefillTime from '../HelperFunctions/CalculateGrimoireRefillTime';
import GetCPS from '../HelperFunctions/GetCPS';
import GetLumpColor from '../HelperFunctions/GetLumpColor';
import GetWrinkConfigBank from '../HelperFunctions/GetWrinkConfigBank';
import {
ColorTextPre, LastTargetTooltipBuilding, TooltipBonusIncome, TooltipBonusMouse, TooltipName, TooltipPrice, TooltipType,
} from '../VariablesAndData';
import * as Create from './CreateTooltip';
/** Functions that update specific types of tooltips */
/**
* This function adds extra info to the Building tooltips
*/
export function Building() {
if (CMOptions.TooltipBuildUpgrade === 1 && Game.buyMode === 1) {
const tooltipBox = l('CMTooltipBorder');
Create.TooltipCreateCalculationSection(tooltipBox);
let target;
if (Game.buyMode === 1) {
LastTargetTooltipBuilding = target;
} else {
target = LastTargetTooltipBuilding;
}
if (Game.buyBulk === 1) target = CacheObjects1;
else if (Game.buyBulk === 10) target = CacheObjects10;
else if (Game.buyBulk === 100) target = CacheObjects100;
TooltipPrice = Game.Objects[TooltipName].bulkPrice;
TooltipBonusIncome = target[TooltipName].bonus;
if (CMOptions.TooltipBuildUpgrade === 1 && Game.buyMode === 1) {
l('CMTooltipIncome').textContent = Beautify(TooltipBonusIncome, 2);
const increase = Math.round(TooltipBonusIncome / Game.cookiesPs * 10000);
if (Number.isFinite(increase) && increase !== 0) {
l('CMTooltipIncome').textContent += ` (${increase / 100}% of income)`;
}
l('CMTooltipBorder').className = ColorTextPre + target[TooltipName].color;
l('CMTooltipPP').textContent = Beautify(target[TooltipName].pp, 2);
l('CMTooltipPP').className = ColorTextPre + target[TooltipName].color;
const timeColor = GetTimeColor((TooltipPrice - (Game.cookies + GetWrinkConfigBank())) / GetCPS());
l('CMTooltipTime').textContent = timeColor.text;
if (timeColor.text === 'Done!' && Game.cookies < target[TooltipName].price) {
l('CMTooltipTime').textContent = `${timeColor.text} (with Wrink)`;
} else l('CMTooltipTime').textContent = timeColor.text;
l('CMTooltipTime').className = ColorTextPre + timeColor.color;
}
// Add "production left till next achievement"-bar
l('CMTooltipProductionHeader').style.display = 'none';
l('CMTooltipTime').style.marginBottom = '0px';
for (const i of Object.keys(Game.Objects[TooltipName].productionAchievs)) {
if (!Game.HasAchiev(Game.Objects[TooltipName].productionAchievs[i].achiev.name)) {
const nextProductionAchiev = Game.Objects[TooltipName].productionAchievs[i];
l('CMTooltipTime').style.marginBottom = '4px';
l('CMTooltipProductionHeader').style.display = '';
l('CMTooltipProduction').className = `ProdAchievement${TooltipName}`;
l('CMTooltipProduction').textContent = Beautify(nextProductionAchiev.pow - SimObjects[TooltipName].totalCookies, 15);
l('CMTooltipProduction').style.color = 'white';
break;
}
}
} else l('CMTooltipArea').style.display = 'none';
}
/**
* This function adds extra info to the Upgrade tooltips
*/
export function Upgrade() {
const tooltipBox = l('CMTooltipBorder');
Create.TooltipCreateCalculationSection(tooltipBox);
TooltipBonusIncome = CacheUpgrades[Game.UpgradesInStore[TooltipName].name].bonus;
TooltipPrice = Game.Upgrades[Game.UpgradesInStore[TooltipName].name].getPrice();
TooltipBonusMouse = CacheUpgrades[Game.UpgradesInStore[TooltipName].name].bonusMouse;
if (CMOptions.TooltipBuildUpgrade === 1) {
l('CMTooltipIncome').textContent = Beautify(TooltipBonusIncome, 2);
const increase = Math.round(TooltipBonusIncome / Game.cookiesPs * 10000);
// Don't display certain parts of tooltip if not applicable
if (l('CMTooltipIncome').textContent === '0' && (TooltipType === 'b' || TooltipType === 'u')) {
l('Bonus IncomeTitle').style.display = 'none';
l('CMTooltipIncome').style.display = 'none';
l('Payback PeriodTitle').style.display = 'none';
l('CMTooltipPP').style.display = 'none';
} else {
if (Number.isFinite(increase) && increase !== 0) {
l('CMTooltipIncome').textContent += ` (${increase / 100}% of income)`;
}
l('CMTooltipBorder').className = ColorTextPre + CacheUpgrades[Game.UpgradesInStore[TooltipName].name].color;
// If clicking power upgrade
if (TooltipBonusMouse) {
l('CMTooltipCookiePerClick').textContent = Beautify(TooltipBonusMouse);
l('CMTooltipCookiePerClick').style.display = 'block';
l('CMTooltipCookiePerClick').previousSibling.style.display = 'block';
}
// If only a clicking power upgrade change PP to click-based period
if (TooltipBonusIncome === 0 && TooltipBonusMouse) {
l('CMTooltipPP').textContent = `${Beautify(TooltipPrice / TooltipBonusMouse)} Clicks`;
l('CMTooltipPP').style.color = 'white';
} else {
l('CMTooltipPP').textContent = Beautify(CacheUpgrades[Game.UpgradesInStore[TooltipName].name].pp, 2);
l('CMTooltipPP').className = ColorTextPre + CacheUpgrades[Game.UpgradesInStore[TooltipName].name].color;
}
}
const timeColor = GetTimeColor((TooltipPrice - (Game.cookies + GetWrinkConfigBank())) / GetCPS());
l('CMTooltipTime').textContent = timeColor.text;
if (timeColor.text === 'Done!' && Game.cookies < Game.UpgradesInStore[TooltipName].getPrice()) {
l('CMTooltipTime').textContent = `${timeColor.text} (with Wrink)`;
} else l('CMTooltipTime').textContent = timeColor.text;
l('CMTooltipTime').className = ColorTextPre + timeColor.color;
// Add extra info to Chocolate egg tooltip
if (Game.UpgradesInStore[TooltipName].name === 'Chocolate egg') {
l('CMTooltipBorder').lastChild.style.marginBottom = '4px';
l('CMTooltipBorder').appendChild(Create.TooltipCreateHeader('Cookies to be gained (Currently/Max)'));
const chocolate = document.createElement('div');
chocolate.style.color = 'white';
chocolate.textContent = `${Beautify(Game.cookies * 0.05)} / ${Beautify(CacheLastChoEgg)}`;
l('CMTooltipBorder').appendChild(chocolate);
}
} else l('CMTooltipArea').style.display = 'none';
}
/**
* This function adds extra info to the Sugar Lump tooltip
* It adds to the additional information to l('CMTooltipArea')
*/
export function SugarLump() {
if (CMOptions.TooltipLump === 1) {
const tooltipBox = l('CMTooltipBorder');
tooltipBox.appendChild(Create.TooltipCreateHeader('Current Sugar Lump'));
const lumpType = document.createElement('div');
lumpType.id = 'CMTooltipTime';
tooltipBox.appendChild(lumpType);
const lumpColor = GetLumpColor(Game.lumpCurrentType);
lumpType.textContent = lumpColor.text;
lumpType.className = ColorTextPre + lumpColor.color;
} else l('CMTooltipArea').style.display = 'none';
}
/**
* This function adds extra info to the Grimoire tooltips
* It adds to the additional information to l('CMTooltipArea')
*/
export function Grimoire() {
const minigame = Game.Objects['Wizard tower'].minigame;
const spellCost = minigame.getSpellCost(minigame.spellsById[TooltipName]);
if (CMOptions.TooltipGrim === 1 && spellCost <= minigame.magicM) {
const tooltipBox = l('CMTooltipBorder');
// Time left till enough magic for spell
tooltipBox.appendChild(Create.TooltipCreateHeader('Time Left'));
const time = document.createElement('div');
time.id = 'CMTooltipTime';
tooltipBox.appendChild(time);
const timeColor = GetTimeColor(CalculateGrimoireRefillTime(minigame.magic, minigame.magicM, spellCost));
time.textContent = timeColor.text;
time.className = ColorTextPre + timeColor.color;
// Time left untill magic spent is recovered
if (spellCost <= minigame.magic) {
tooltipBox.appendChild(Create.TooltipCreateHeader('Recover Time'));
const recover = document.createElement('div');
recover.id = 'CMTooltipRecover';
tooltipBox.appendChild(recover);
const recoverColor = GetTimeColor(CalculateGrimoireRefillTime(Math.max(0, minigame.magic - spellCost), minigame.magicM, minigame.magic));
recover.textContent = recoverColor.text;
recover.className = ColorTextPre + recoverColor.color;
}
// Extra information on cookies gained when spell is Conjure Baked Goods (Name === 0)
if (TooltipName === '0') {
tooltipBox.appendChild(Create.TooltipCreateHeader('Cookies to be gained/lost'));
const conjure = document.createElement('div');
conjure.id = 'x';
tooltipBox.appendChild(conjure);
const reward = document.createElement('span');
reward.style.color = '#33FF00';
reward.textContent = Beautify(Math.min((Game.cookies + GetWrinkConfigBank()) * 0.15, CacheNoGoldSwitchCookiesPS * 60 * 30), 2);
conjure.appendChild(reward);
const seperator = document.createElement('span');
seperator.textContent = ' / ';
conjure.appendChild(seperator);
const loss = document.createElement('span');
loss.style.color = 'red';
loss.textContent = Beautify((CacheNoGoldSwitchCookiesPS * 60 * 15), 2);
conjure.appendChild(loss);
}
l('CMTooltipArea').appendChild(tooltipBox);
} else l('CMTooltipArea').style.display = 'none';
}
/**
* This function adds extra info to the Garden plots tooltips
* It adds to the additional information to l('CMTooltipArea')
*/
export function GardenPlots() {
const minigame = Game.Objects.Farm.minigame;
if (CMOptions.TooltipPlots && minigame.plot[TooltipName[1]][TooltipName[0]][0] !== 0) {
const mature = minigame.plot[TooltipName[1]][TooltipName[0]][1] > minigame.plantsById[minigame.plot[TooltipName[1]][TooltipName[0]][0] - 1].matureBase;
const plantName = minigame.plantsById[minigame.plot[TooltipName[1]][TooltipName[0]][0] - 1].name;
l('CMTooltipBorder').appendChild(Create.TooltipCreateHeader('Reward (Current / Maximum)'));
const reward = document.createElement('div');
reward.id = 'CMTooltipPlantReward';
l('CMTooltipBorder').appendChild(reward);
if (plantName === 'Bakeberry') {
l('CMTooltipPlantReward').textContent = `${mature ? Beautify(Math.min(Game.cookies * 0.03, Game.cookiesPs * 60 * 30)) : '0'} / ${Beautify(Game.cookiesPs * 60 * 30)}`;
} else if (plantName === 'Chocoroot' || plantName === 'White chocoroot') {
l('CMTooltipPlantReward').textContent = `${mature ? Beautify(Math.min(Game.cookies * 0.03, Game.cookiesPs * 60 * 3)) : '0'} / ${Beautify(Game.cookiesPs * 60 * 3)}`;
} else if (plantName === 'Queenbeet') {
l('CMTooltipPlantReward').textContent = `${mature ? Beautify(Math.min(Game.cookies * 0.04, Game.cookiesPs * 60 * 60)) : '0'} / ${Beautify(Game.cookiesPs * 60 * 60)}`;
} else if (plantName === 'Duketater') {
l('CMTooltipPlantReward').textContent = `${mature ? Beautify(Math.min(Game.cookies * 0.08, Game.cookiesPs * 60 * 120)) : '0'} / ${Beautify(Game.cookiesPs * 60 * 120)}`;
} else l('CMTooltipArea').style.display = 'none';
} else l('CMTooltipArea').style.display = 'none';
}
/**
* This function adds extra info to the Garden Harvest All tooltip
* It is called when the Harvest All tooltip is created or refreshed by CM.Disp.UpdateTooltip()
* It adds to the additional information to l('CMTooltipArea')
*/
export function HarvestAll() {
const minigame = Game.Objects.Farm.minigame;
if (CMOptions.TooltipLump) {
l('CMTooltipBorder').appendChild(Create.TooltipCreateHeader('Cookies gained from harvesting:'));
let totalGain = 0;
let mortal = 0;
if (Game.keys[16] && Game.keys[17]) mortal = 1;
for (let y = 0; y < 6; y++) {
for (let x = 0; x < 6; x++) {
if (minigame.plot[y][x][0] >= 1) {
const tile = minigame.plot[y][x];
const me = minigame.plantsById[tile[0] - 1];
const plantName = me.name;
let count = true;
if (mortal && me.immortal) count = false;
if (tile[1] < me.matureBase) count = false;
if (count && plantName === 'Bakeberry') {
totalGain += Math.min(Game.cookies * 0.03, Game.cookiesPs * 60 * 30);
} else if (count && plantName === 'Chocoroot' || plantName === 'White chocoroot') {
totalGain += Math.min(Game.cookies * 0.03, Game.cookiesPs * 60 * 3);
} else if (count && plantName === 'Queenbeet') {
totalGain += Math.min(Game.cookies * 0.04, Game.cookiesPs * 60 * 60);
} else if (count && plantName === 'Duketater') {
totalGain += Math.min(Game.cookies * 0.08, Game.cookiesPs * 60 * 120);
}
}
}
}
l('CMTooltipBorder').appendChild(document.createTextNode(Beautify(totalGain)));
} else l('CMTooltipArea').style.display = 'none';
}
/**
* This function updates the warnings section of the building and upgrade tooltips
* It is called by CM.Disp.UpdateTooltip()
*/
export function Warnings() {
if (TooltipType === 'b' || TooltipType === 'u') {
if (document.getElementById('CMDispTooltipWarningParent') === null) {
l('tooltipAnchor').appendChild(Create.TooltipCreateWarningSection());
ToggleToolWarnPos();
}
if (CMOptions.ToolWarnPos === 0) l('CMDispTooltipWarningParent').style.right = '0px';
else l('CMDispTooltipWarningParent').style.top = `${l('tooltip').offsetHeight}px`;
l('CMDispTooltipWarningParent').style.width = `${l('tooltip').offsetWidth - 6}px`;
const amount = (Game.cookies + GetWrinkConfigBank()) - TooltipPrice;
const bonusIncomeUsed = CMOptions.ToolWarnBon ? TooltipBonusIncome : 0;
let limitLucky = CacheLucky;
if (CMOptions.ToolWarnBon === 1) {
let bonusNoFren = TooltipBonusIncome;
bonusNoFren /= GetCPSBuffMult();
limitLucky += ((bonusNoFren * 60 * 15) / 0.15);
}
if (CMOptions.ToolWarnLucky === 1) {
if (amount < limitLucky && (TooltipType !== 'b' || Game.buyMode === 1)) {
l('CMDispTooltipWarnLucky').style.display = '';
l('CMDispTooltipWarnLuckyText').textContent = `${Beautify(limitLucky - amount)} (${FormatTime((limitLucky - amount) / (GetCPS() + bonusIncomeUsed))})`;
} else l('CMDispTooltipWarnLucky').style.display = 'none';
} else l('CMDispTooltipWarnLucky').style.display = 'none';
if (CMOptions.ToolWarnLuckyFrenzy === 1) {
const limitLuckyFrenzy = limitLucky * 7;
if (amount < limitLuckyFrenzy && (TooltipType !== 'b' || Game.buyMode === 1)) {
l('CMDispTooltipWarnLuckyFrenzy').style.display = '';
l('CMDispTooltipWarnLuckyFrenzyText').textContent = `${Beautify(limitLuckyFrenzy - amount)} (${FormatTime((limitLuckyFrenzy - amount) / (GetCPS() + bonusIncomeUsed))})`;
} else l('CMDispTooltipWarnLuckyFrenzy').style.display = 'none';
} else l('CMDispTooltipWarnLuckyFrenzy').style.display = 'none';
if (CMOptions.ToolWarnConjure === 1) {
const limitConjure = limitLucky * 2;
if ((amount < limitConjure) && (TooltipType !== 'b' || Game.buyMode === 1)) {
l('CMDispTooltipWarnConjure').style.display = '';
l('CMDispTooltipWarnConjureText').textContent = `${Beautify(limitConjure - amount)} (${FormatTime((limitConjure - amount) / (GetCPS() + bonusIncomeUsed))})`;
} else l('CMDispTooltipWarnConjure').style.display = 'none';
} else l('CMDispTooltipWarnConjure').style.display = 'none';
if (CMOptions.ToolWarnConjureFrenzy === 1) {
const limitConjureFrenzy = limitLucky * 2 * 7;
if ((amount < limitConjureFrenzy) && (TooltipType !== 'b' || Game.buyMode === 1)) {
l('CMDispTooltipWarnConjureFrenzy').style.display = '';
l('CMDispTooltipWarnConjureFrenzyText').textContent = `${Beautify(limitConjureFrenzy - amount)} (${FormatTime((limitConjureFrenzy - amount) / (GetCPS() + bonusIncomeUsed))})`;
} else l('CMDispTooltipWarnConjureFrenzy').style.display = 'none';
} else l('CMDispTooltipWarnConjureFrenzy').style.display = 'none';
if (CMOptions.ToolWarnEdifice === 1 && Game.Objects['Wizard tower'].minigameLoaded) {
if (CacheEdifice && amount < CacheEdifice && (TooltipType !== 'b' || Game.buyMode === 1)) {
l('CMDispTooltipWarnEdifice').style.display = '';
l('CMDispTooltipWarnEdificeText').textContent = `${Beautify(CacheEdifice - amount)} (${FormatTime((CacheEdifice - amount) / (GetCPS() + bonusIncomeUsed))})`;
} else l('CMDispTooltipWarnEdifice').style.display = 'none';
} else l('CMDispTooltipWarnEdifice').style.display = 'none';
if (CMOptions.ToolWarnUser > 0) {
if (amount < CMOptions.ToolWarnUser * GetCPS() && (TooltipType !== 'b' || Game.buyMode === 1)) {
l('CMDispTooltipWarnUser').style.display = '';
// Need to update tooltip text dynamically
l('CMDispTooltipWarnUser').children[0].textContent = `Purchase of this item will put you under the number of Cookies equal to ${CMOptions.ToolWarnUser} seconds of CPS`;
l('CMDispTooltipWarnUserText').textContent = `${Beautify(CMOptions.ToolWarnUser * GetCPS() - amount)} (${FormatTime((CMOptions.ToolWarnUser * GetCPS() - amount) / (GetCPS() + bonusIncomeUsed))})`;
} else l('CMDispTooltipWarnUser').style.display = 'none';
} else l('CMDispTooltipWarnUser').style.display = 'none';
} else if (l('CMDispTooltipWarningParent') !== null) {
l('CMDispTooltipWarningParent').remove();
}
}

View File

@@ -0,0 +1,63 @@
import { CMOptions } from '../../Config/VariablesAndData';
import { SimObjects } from '../../Sim/VariablesAndData';
import { Beautify } from '../BeautifyAndFormatting/BeautifyFormatting';
import { TooltipWrinkler, TooltipWrinklerArea, TooltipWrinklerBeingShown } from '../VariablesAndData';
/**
* This function checks and create a tooltip for the wrinklers
* It is called by CM.Disp.Draw()
* As wrinklers are not appended to the DOM we us a different system than for other tooltips
*/
export function CheckWrinklerTooltip() {
if (CMOptions.TooltipWrink === 1 && TooltipWrinklerArea === 1) { // Latter is set by CM.Main.AddWrinklerAreaDetect
let showingTooltip = false;
for (const i of Object.keys(Game.wrinklers)) {
const me = Game.wrinklers[i];
if (me.phase > 0 && me.selected) {
showingTooltip = true;
if (TooltipWrinklerBeingShown[i] === 0 || TooltipWrinklerBeingShown[i] === undefined) {
const placeholder = document.createElement('div');
const wrinkler = document.createElement('div');
wrinkler.style.minWidth = '120px';
wrinkler.style.marginBottom = '4px';
const div = document.createElement('div');
div.style.textAlign = 'center';
div.id = 'CMTooltipWrinkler';
wrinkler.appendChild(div);
placeholder.appendChild(wrinkler);
Game.tooltip.draw(this, escape(placeholder.innerHTML));
TooltipWrinkler = i;
TooltipWrinklerBeingShown[i] = 1;
} else break;
} else {
TooltipWrinklerBeingShown[i] = 0;
}
}
if (!showingTooltip) {
Game.tooltip.hide();
}
}
}
/**
* This function updates the amount to be displayed by the wrinkler tooltip created by CM.Disp.CheckWrinklerTooltip()
* It is called by CM.Disp.Draw()
* As wrinklers are not appended to the DOM we us a different system than for other tooltips
*/
export function UpdateWrinklerTooltip() {
if (CMOptions.TooltipWrink === 1 && l('CMTooltipWrinkler') !== null) {
let sucked = Game.wrinklers[TooltipWrinkler].sucked;
let toSuck = 1.1;
if (Game.Has('Sacrilegious corruption')) toSuck *= 1.05;
if (Game.wrinklers[TooltipWrinkler].type === 1) toSuck *= 3; // Shiny wrinklers
sucked *= toSuck;
if (Game.Has('Wrinklerspawn')) sucked *= 1.05;
if (SimObjects.Temple.minigameLoaded) {
const godLvl = Game.hasGod('scorn');
if (godLvl === 1) sucked *= 1.15;
else if (godLvl === 2) sucked *= 1.1;
else if (godLvl === 3) sucked *= 1.05;
}
l('CMTooltipWrinkler').textContent = Beautify(sucked);
}
}

View File

@@ -0,0 +1,101 @@
/* eslint-disable prefer-const */
/**
* Section: Variables used in Disp functions */
export let DispCSS;
/**
* These are variables used to create DOM object names and id (e.g., 'CMTextTooltip)
*/
export const ColorTextPre = 'CMText';
export const ColorBackPre = 'CMBack';
export const ColorBorderPre = 'CMBorder';
/**
* These are variables which can be set in the options by the user to standardize colours throughout CookieMonster
*/
export const ColorBlue = 'Blue';
export const ColorGreen = 'Green';
export const ColorYellow = 'Yellow';
export const ColorOrange = 'Orange';
export const ColorRed = 'Red';
export const ColorPurple = 'Purple';
export const ColorGray = 'Gray';
export const ColorPink = 'Pink';
export const ColorBrown = 'Brown';
export const Colors = [ColorGray, ColorBlue, ColorGreen, ColorYellow, ColorOrange, ColorRed, ColorPurple, ColorPink, ColorBrown];
/**
* This list is used to make some very basic tooltips.
* It is used by CM.Main.DelayInit() in the call of CM.Disp.CreateSimpleTooltip()
* @item {string} placeholder
* @item {string} text
* @item {string} minWidth
*/
export const TooltipText = [
['GoldCookTooltipPlaceholder', 'Calculated with Golden Switch off', '200px'],
['GoldCookDragonsFortuneTooltipPlaceholder', 'Calculated with Golden Switch off and at least one golden cookie on-screen', '240px'],
['PrestMaxTooltipPlaceholder', 'The MAX prestige is calculated with the cookies gained from popping all wrinklers with Skruuia god in Diamond slot, selling all stock market goods, selling all buildings with Earth Shatterer and Reality Bending auras, and buying Chocolate egg', '320px'],
['NextPrestTooltipPlaceholder', 'Calculated with cookies gained from wrinklers and Chocolate egg', '200px'],
['HeavenChipMaxTooltipPlaceholder', 'The MAX heavenly chips is calculated with the cookies gained from popping all wrinklers with Skruuia god in Diamond slot, selling all stock market goods, selling all buildings with Earth Shatterer and Reality Bending auras, and buying Chocolate egg', '330px'],
['ResetTooltipPlaceholder', 'The bonus income you would get from new prestige levels unlocked at 100% of its potential and from ascension achievements if you have the same buildings/upgrades after reset', '370px'],
['ChoEggTooltipPlaceholder', 'The amount of cookies you would get from popping all wrinklers with Skruuia god in Diamond slot, selling all stock market goods, selling all buildings with Earth Shatterer and Reality Bending auras, and then buying Chocolate egg', '300px'],
['ChainNextLevelPlaceholder', 'Cheated cookies might break this formula', '250px'],
];
/**
* These are variables used by the functions that create tooltips for wrinklers
* See CM.Disp.CheckWrinklerTooltip(), CM.Disp.UpdateWrinklerTooltip() and CM.Main.AddWrinklerAreaDetect()
*/
export let TooltipWrinklerArea = 0;
export let TooltipWrinkler = -1;
/**
* This array is used to store whether a Wrinkler tooltip is being shown or not
* [i] = 1 means tooltip is being shown, [i] = 0 means hidden
* It is used by CM.Disp.CheckWrinklerTooltip() and CM.Main.AddWrinklerAreaDetect()
*/
export let TooltipWrinklerBeingShown = [];
export let CMLastAscendState;
export let CMSayTime;
/**
* These are variables used to create various displays when the game is loaded on the "sell all" screen
*/
export let LastTargetBotBar = 1;
export let LastTargetBuildings = 1;
export let LastTargetTooltipBuilding = 1;
/**
* These arrays are used in the stats page to show
* average cookies per {CM.Disp.cookieTimes/CM.Disp.clickTimes} seconds
*/
export const CookieTimes = [10, 15, 30, 60, 300, 600, 900, 1800];
export const ClickTimes = [1, 5, 10, 15, 30];
/**
* This array is used to give certain timers specific colours
*/
export const BuffColors = {
Frenzy: ColorYellow, 'Dragon Harvest': ColorBrown, 'Elder frenzy': ColorGreen, Clot: ColorRed, 'Click frenzy': ColorBlue, Dragonflight: ColorPink,
};
/**
* This array is used to track GC timers
*/
export let GCTimers = {};
/**
* Used to store the number of cookies to be displayed in the tab-title
*/
export let Title = '';
export let TooltipPrice;
export let TooltipBonusIncome;
export let TooltipType;
export let TooltipName;
export let TooltipBonusMouse;
export let LastAscendState;
export let LastNumberOfTimers;

View File

@@ -1,34 +0,0 @@
/** General functions to format or beautify strings */
/**
* This function returns time as a string depending on TimeFormat setting
* @param {number} time Time to be formatted
* @param {number} longFormat 1 or 0
* @returns {string} Formatted time
*/
export default function FormatTime(time, longFormat) {
if (time === Infinity) return time;
time = Math.ceil(time);
const y = Math.floor(time / 31557600);
const d = Math.floor(time % 31557600 / 86400);
const h = Math.floor(time % 86400 / 3600);
const m = Math.floor(time % 3600 / 60);
const s = Math.floor(time % 60);
let str = '';
if (CM.Options.TimeFormat) {
if (time > 3155760000) return 'XX:XX:XX:XX:XX';
str += `${(y < 10 ? '0' : '') + y}:`;
str += `${(d < 10 ? '0' : '') + d}:`;
str += `${(h < 10 ? '0' : '') + h}:`;
str += `${(m < 10 ? '0' : '') + m}:`;
str += (s < 10 ? '0' : '') + s;
} else {
if (time > 777600000) return longFormat ? 'Over 9000 days!' : '>9000d';
str += (y > 0 ? `${y + (longFormat ? (y === 1 ? ' year' : ' years') : 'y')}, ` : '');
str += (d > 0 ? `${d + (longFormat ? (d === 1 ? ' day' : ' days') : 'd')}, ` : '');
if (str.length > 0 || h > 0) str += `${h + (longFormat ? (h === 1 ? ' hour' : ' hours') : 'h')}, `;
if (str.length > 0 || m > 0) str += `${m + (longFormat ? (m === 1 ? ' minute' : ' minutes') : 'm')}, `;
str += s + (longFormat ? (s === 1 ? ' second' : ' seconds') : 's');
}
return str;
}