cookie clicker but bigger
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1121 lines
27 KiB

  1. "use strict";
  2. const belongings = {};
  3. const ownedUpgrades = {};
  4. const remainingUpgrades = [];
  5. let showOwnedUpgrades = false;
  6. const effects = {};
  7. const resources = {};
  8. let updateRate = 30;
  9. const currentProductivity = {};
  10. const contributions = {};
  11. let clickBonus = 0;
  12. let clickVictim = "micro";
  13. let lastTime = 0;
  14. let controlHeld = false;
  15. let shiftHeld = false;
  16. let mouseTarget = undefined;
  17. const activePowerups = [];
  18. function tickPowerups(delta) {
  19. const powerupList = document.querySelector("#powerup-list");
  20. let changed = false;
  21. // I love mutating arrays as I traverse them.
  22. for (let i = activePowerups.length - 1; i >= 0; i--) {
  23. activePowerups[i].lifetime -= delta;
  24. if (activePowerups[i].lifetime <= 0) {
  25. const entry = activePowerups[i];
  26. setTimeout(() => {
  27. powerupList.removeChild(entry.element);
  28. }, 1000);
  29. entry.element.classList.add("powerup-entry-done");
  30. activePowerups.splice(i, 1);
  31. changed = true;
  32. } else {
  33. const frac = (activePowerups[i].powerup.duration - activePowerups[i].lifetime) / (activePowerups[i].powerup.duration);
  34. activePowerups[i].element.style.setProperty("--progress", frac * 100 + "%")
  35. }
  36. }
  37. if (changed) {
  38. updateAll();
  39. }
  40. }
  41. function addPowerup(powerup) {
  42. const powerupList = document.querySelector("#powerup-list");
  43. const powerupEntry = document.createElement("div");
  44. powerupEntry.classList.add("powerup-entry");
  45. powerupEntry.innerText = powerup.name;
  46. powerupList.appendChild(powerupEntry);
  47. activePowerups.push({ powerup: powerup, lifetime: powerup.duration, element: powerupEntry });
  48. updateAll();
  49. }
  50. function applyGlobalProdBonus(cost) {
  51. for (let effect of effects["prod-all"]) {
  52. if (ownedUpgrades[effect.parent]) {
  53. cost = effect.apply(cost);
  54. }
  55. }
  56. return cost;
  57. }
  58. function calculateProductivity() {
  59. let productivity = makeCost();
  60. for (const [key, value] of Object.entries(belongings)) {
  61. const provided = productivityOf(key);
  62. productivity = addCost(productivity, provided);
  63. contributions[key] = provided;
  64. }
  65. return productivity;
  66. }
  67. // here's where upgrades will go :3
  68. function applyProductivityMultipliers(type, cost) {
  69. for (let effect of effects["prod"]) {
  70. if (ownedUpgrades[effect.parent] && effect.target == type) {
  71. cost = effect.apply(cost);
  72. }
  73. }
  74. for (let effect of effects["helper"]) {
  75. if (ownedUpgrades[effect.parent] && effect.helped == type) {
  76. cost = effect.apply(cost, belongings[effect.helper].count);
  77. }
  78. }
  79. return cost;
  80. }
  81. function productivityOf(type) {
  82. let baseProd = makeCost(buildings[type].prod);
  83. baseProd = applyProductivityMultipliers(type, baseProd);
  84. baseProd = applyGlobalProdBonus(baseProd);
  85. baseProd = scaleCost(baseProd, belongings[type].count);
  86. return baseProd;
  87. }
  88. function makeCost(source) {
  89. const empty = mapObject(resourceTypes, () => 0);
  90. return deepFreeze({...empty, ...source});
  91. }
  92. function addCost(cost1, cost2) {
  93. return deepFreeze(Object.keys(resourceTypes).reduce((o, k) => ({ ...o, [k]: cost1[k] + cost2[k]}), {}));
  94. }
  95. function scaleCost(cost, scale) {
  96. if (typeof(scale) != "number") console.log(scale)
  97. return deepFreeze(Object.keys(resourceTypes).reduce((o, k) => ({ ...o, [k]: cost[k] * scale}), {}));
  98. }
  99. function costOfBuilding(type, count = 1) {
  100. let total = makeCost();
  101. while (count > 0) {
  102. let baseCost = makeCost(buildings[type].cost);
  103. baseCost = scaleCost(baseCost, Math.pow(1.15, belongings[type].count + count - 1));
  104. total = addCost(total, baseCost);
  105. count--;
  106. }
  107. return mapObject(total, round);
  108. }
  109. function buildingCount() {
  110. if (controlHeld) {
  111. return 10;
  112. } else if (shiftHeld) {
  113. return 5;
  114. } else {
  115. return 1;
  116. }
  117. }
  118. function buyBuilding(type, e) {
  119. const count = buildingCount();
  120. let cost = costOfBuilding(type, count);
  121. if (canAfford(cost)) {
  122. spend(cost);
  123. belongings[type].count += count;
  124. }
  125. updateProductivity();
  126. updateClickBonus();
  127. }
  128. function updateAll() {
  129. updateProductivity();
  130. updateClickBonus();
  131. updateClickVictim();
  132. }
  133. // update stuff
  134. function updateDisplay() {
  135. let newTime = performance.now();
  136. let delta = newTime - lastTime;
  137. lastTime = newTime;
  138. addResources(delta);
  139. displayResources();
  140. displayBuildings();
  141. displayUpgrades(showOwnedUpgrades);
  142. tickPowerups(delta);
  143. setTimeout(updateDisplay, 1000 / updateRate);
  144. }
  145. function updateProductivity() {
  146. Object.assign(currentProductivity, calculateProductivity());
  147. activePowerups.forEach(entry => {
  148. const powerup = entry.powerup;
  149. const state = {
  150. ownedUpgrades: ownedUpgrades,
  151. resources: resources,
  152. currentProductivity: currentProductivity,
  153. belongings: belongings
  154. };
  155. powerup.effect(state);
  156. })
  157. }
  158. function addResources(delta) {
  159. for (const [resource, amount] of Object.entries(currentProductivity)) {
  160. resources[resource] += amount * delta / 1000;
  161. }
  162. }
  163. function displayResources() {
  164. document.title = "Gorge - " + round(resources.food) + " food";
  165. replaceChildren(document.querySelector("#resource-list"), renderResources());
  166. }
  167. function renderResources() {
  168. let list = [];
  169. for (const [key, value] of Object.entries(resources)) {
  170. let line1 = render(value, 3, 0) + " " + resourceTypes[key].name;
  171. let line2 = render(currentProductivity[key], 1, 1) + " " + resourceTypes[key].name + "/sec";
  172. list.push({ "text": line1, "class": "resource-quantity" });
  173. list.push({ "text": line2, "class": "resource-rate" });
  174. }
  175. return renderLines(list);
  176. }
  177. function displayBuildings() {
  178. const count = buildingCount();
  179. for (const [key, value] of Object.entries(belongings)) {
  180. if (!belongings[key].visible) {
  181. if (resources.food * 10 >= costOfBuilding(key).food) {
  182. unlockBuilding(key);
  183. } if (belongings[key].count > 0) {
  184. unlockBuilding(key);
  185. } else {
  186. continue;
  187. }
  188. belongings[key].visible = true;
  189. let button = cache.buildingButtons[key].button;
  190. button.classList.remove("hidden");
  191. }
  192. let button = cache.buildingButtons[key].button;
  193. let name = cache.buildingButtons[key].name;
  194. let cost = cache.buildingButtons[key].cost;
  195. const buildingCost = costOfBuilding(key, count);
  196. name.innerText = value.count + " " + (value.count == 1 ? buildings[key].name : buildings[key].plural);
  197. cost.innerText = render(buildingCost.food) + " food";
  198. if (canAfford(buildingCost) && button.classList.contains("building-button-disabled")) {
  199. button.classList.remove("building-button-disabled");
  200. cost.classList.add("building-button-cost-valid");
  201. } else if (!canAfford(buildingCost) && !button.classList.contains("building-button-disabled")) {
  202. button.classList.add("building-button-disabled");
  203. cost.classList.add("building-button-cost-invalid");
  204. }
  205. }
  206. }
  207. function canAfford(cost) {
  208. for (const [resource, amount] of Object.entries(cost)) {
  209. if (resources[resource] < amount) {
  210. return false;
  211. }
  212. }
  213. return true;
  214. }
  215. function spend(cost) {
  216. for (const [resource, amount] of Object.entries(cost)) {
  217. resources[resource] -= amount;
  218. }
  219. }
  220. function switchShowOwnedUpgrades() {
  221. if (showOwnedUpgrades) {
  222. document.querySelector("#upgrades").innerText = "Upgrades";
  223. } else {
  224. document.querySelector("#upgrades").innerText = "Owned Upgrades";
  225. }
  226. showOwnedUpgrades = !showOwnedUpgrades;
  227. }
  228. function displayUpgrades(owned) {
  229. if (owned) {
  230. Object.entries(ownedUpgrades).forEach(([key, val]) => {
  231. let button = cache.upgradeButtons[key];
  232. if (val) {
  233. button.classList.remove("hidden");
  234. } else {
  235. button.classList.add("hidden");
  236. }
  237. });
  238. }
  239. else {
  240. for (let id of remainingUpgrades) {
  241. let button = cache.upgradeButtons[id];
  242. let visible = states.upgrades[id].visible;
  243. let available = states.upgrades[id].available;
  244. if (ownedUpgrades[id] && visible !== false) {
  245. button.classList.add("hidden");
  246. states.upgrades[id].visible = false;
  247. continue;
  248. }
  249. if (upgradeReachable(id) && visible !== true) {
  250. button.classList.remove("hidden");
  251. states.upgrades[id].visible = true;
  252. } else if (!upgradeReachable(id) && visible !== false) {
  253. button.classList.add("hidden");
  254. states.upgrades[id].visible = false;
  255. }
  256. if (upgradeAvailable(id) && available !== true) {
  257. button.classList.remove("upgrade-button-inactive");
  258. states.upgrades[id].available = true;
  259. } else if (!upgradeAvailable(id) && available !== false) {
  260. button.classList.add("upgrade-button-inactive");
  261. states.upgrades[id].available = false;
  262. }
  263. }
  264. // we aren't trimming the list of upgrades now
  265. // because we need to switch between owned and unowned upgrades
  266. // - thus we need to be able to show or hide anything
  267. /*
  268. for (let i = remainingUpgrades.length-1; i >= 0; i--) {
  269. if (ownedUpgrades[remainingUpgrades[i]]) {
  270. remainingUpgrades.splice(i, 1);
  271. }
  272. }*/
  273. }
  274. }
  275. function updateClickBonus() {
  276. let bonus = 0;
  277. for (let effect of effects["click"]) {
  278. if (ownedUpgrades[effect.parent]) {
  279. bonus = effect.apply(bonus, currentProductivity["food"]);
  280. }
  281. }
  282. clickBonus = bonus;
  283. }
  284. function updateClickVictim() {
  285. for (let effect of effects["click-victim"]) {
  286. if (ownedUpgrades[effect.parent]) {
  287. clickVictim = effect.id;
  288. document.querySelector("#tasty-micro").innerText = "Eat " + buildings[effect.id].name;
  289. }
  290. }
  291. }
  292. function buyUpgrade(id, e) {
  293. if (ownedUpgrades[id]) {
  294. return;
  295. }
  296. let upgrade = upgrades[id];
  297. if (!upgradeAvailable(id)) {
  298. return;
  299. }
  300. spend(upgrade.cost);
  301. ownedUpgrades[id] = true;
  302. let text = "Bought " + upgrade.name + "!";
  303. clickPopup(text, "upgrade", [e.clientX, e.clientY]);
  304. updateProductivity();
  305. updateClickBonus();
  306. updateClickVictim();
  307. }
  308. function eatPrey() {
  309. const add = buildings[clickVictim]["prod"].food * 10 + clickBonus;
  310. resources.food += add;
  311. return add;
  312. }
  313. // setup stuff lol
  314. // we'll initialize the dict of buildings we can own
  315. function setup() {
  316. // create static data
  317. createTemplateUpgrades();
  318. // prepare dynamic stuff
  319. initializeData();
  320. createButtons();
  321. createDisplays();
  322. registerListeners();
  323. load();
  324. unlockAtStart();
  325. initializeCaches();
  326. initializeStates();
  327. updateAll();
  328. }
  329. const cache = {};
  330. function initializeCaches() {
  331. const buildingButtons = {};
  332. for (const [key, value] of Object.entries(belongings)) {
  333. let button = document.querySelector("#building-" + key);
  334. let name = document.querySelector("#building-" + key + " > .building-button-name");
  335. let cost = document.querySelector("#building-" + key + " > .building-button-cost");
  336. buildingButtons[key] = {
  337. button: button,
  338. name: name,
  339. cost: cost
  340. }
  341. }
  342. cache.buildingButtons = buildingButtons;
  343. const upgradeButtons = {};
  344. Object.keys(upgrades).forEach(key => {
  345. upgradeButtons[key] = document.querySelector("#upgrade-" + key);
  346. });
  347. cache.upgradeButtons = upgradeButtons;
  348. }
  349. const states = {};
  350. // we can keep track of some things, like whether
  351. // specific upgrades are currently visible. this
  352. // way, we don't have to set them visible every tick;
  353. // we can just check if they've been handled already
  354. function initializeStates() {
  355. const upgradeStates = {};
  356. Object.keys(upgrades).forEach(key => {
  357. upgradeStates[key] = {
  358. visible: undefined,
  359. available: undefined
  360. }
  361. });
  362. states.upgrades = upgradeStates;
  363. }
  364. function unlockAtStart() {
  365. unlockBuilding("micro");
  366. for (const [key, value] of Object.entries(belongings)) {
  367. if (belongings[key].visible) {
  368. unlockBuilding(key);
  369. }
  370. }
  371. }
  372. function unlockBuilding(id) {
  373. belongings[id].visible = true;
  374. document.querySelector("#building-" + id).classList.remove("hidden");
  375. }
  376. function initializeData() {
  377. for (const [key, value] of Object.entries(buildings)) {
  378. belongings[key] = {};
  379. belongings[key].count = 0;
  380. belongings[key].visible = false;
  381. contributions[key] = makeCost();
  382. }
  383. for (const [key, value] of Object.entries(resourceTypes)) {
  384. resources[key] = 0;
  385. currentProductivity[key] = 0;
  386. }
  387. for (const [id, upgrade] of Object.entries(upgrades)) {
  388. ownedUpgrades[id] = false;
  389. for (let effect of upgrade.effects) {
  390. if (effects[effect.type] === undefined) {
  391. effects[effect.type] = [];
  392. }
  393. // copy the data and add an entry for the upgrade id that owns the effect
  394. let newEffect = {};
  395. for (const [key, value] of Object.entries(effect)) {
  396. newEffect[key] = value;
  397. }
  398. newEffect.parent = id;
  399. // unfortunate name collision here
  400. // I'm using apply() to pass on any number of arguments to the
  401. // apply() function of the effect type
  402. newEffect.apply = function (...args) { return effect_types[effect.type].apply.apply(null, [effect].concat(args)); }
  403. effects[effect.type].push(newEffect);
  404. }
  405. }
  406. }
  407. function registerListeners() {
  408. document.querySelector("#tasty-micro").addEventListener("click", (e) => {
  409. const add = eatPrey();
  410. const text = "+" + round(add, 1) + " food";
  411. const gulp = "*glp*";
  412. clickPopup(text, "food", [e.clientX, e.clientY]);
  413. clickPopup(gulp, "gulp", [e.clientX, e.clientY]);
  414. });
  415. document.querySelector("#save").addEventListener("click", save);
  416. document.querySelector("#reset").addEventListener("click", reset);
  417. document.querySelector("#upgrades").addEventListener("click", switchShowOwnedUpgrades);
  418. document.addEventListener("keydown", e => {
  419. shiftHeld = e.shiftKey;
  420. controlHeld = e.ctrlKey;
  421. if (mouseTarget)
  422. mouseTarget.dispatchEvent(new Event("mousemove"));
  423. return true;
  424. });
  425. document.addEventListener("keyup", e => {
  426. shiftHeld = e.shiftKey;
  427. controlHeld = e.ctrlKey;
  428. if (mouseTarget)
  429. mouseTarget.dispatchEvent(new Event("mousemove"));
  430. return true;
  431. });
  432. }
  433. function createButtons() {
  434. createBuildings();
  435. createUpgrades();
  436. }
  437. function createBuildings() {
  438. let container = document.querySelector("#buildings-list");
  439. for (const [key, value] of Object.entries(buildings)) {
  440. let button = document.createElement("div");
  441. button.classList.add("building-button");
  442. button.classList.add("hidden");
  443. button.id = "building-" + key;
  444. let buttonName = document.createElement("div");
  445. buttonName.classList.add("building-button-name");
  446. let buttonCost = document.createElement("div");
  447. buttonCost.classList.add("building-button-cost");
  448. let buildingIcon = document.createElement("i");
  449. buildingIcon.classList.add("fas");
  450. buildingIcon.classList.add(value.icon);
  451. button.appendChild(buttonName);
  452. button.appendChild(buttonCost);
  453. button.appendChild(buildingIcon);
  454. button.addEventListener("mousemove", function (e) { mouseTarget = button; buildingTooltip(key, e); });
  455. button.addEventListener("mouseleave", function () { mouseTarget = undefined; buildingTooltipRemove(); });
  456. button.addEventListener("click", function (e) { buyBuilding(key, e); });
  457. button.addEventListener("click", function (e) { buildingTooltip(key, e); });
  458. container.appendChild(button);
  459. }
  460. }
  461. // do we have previous techs and at least one of each building?
  462. function upgradeReachable(id) {
  463. if (ownedUpgrades[id]) {
  464. return false;
  465. }
  466. if (upgrades[id].prereqs !== undefined) {
  467. for (const [type, reqs] of Object.entries(upgrades[id].prereqs)) {
  468. if (type == "buildings") {
  469. for (const [building, amount] of Object.entries(reqs)) {
  470. if (belongings[building].count == 0) {
  471. return false;
  472. }
  473. }
  474. }
  475. else if (type == "upgrades") {
  476. for (let upgrade of reqs) {
  477. if (!ownedUpgrades[upgrade]) {
  478. return false;
  479. }
  480. }
  481. }
  482. }
  483. }
  484. return true;
  485. }
  486. function upgradeAvailable(id) {
  487. if (!upgradeReachable(id)) {
  488. return false;
  489. }
  490. if (!canAfford(upgrades[id].cost)) {
  491. return false;
  492. }
  493. if (upgrades[id].prereqs !== undefined) {
  494. for (const [type, reqs] of Object.entries(upgrades[id].prereqs)) {
  495. if (type == "buildings") {
  496. for (const [building, amount] of Object.entries(upgrades[id].prereqs[type])) {
  497. if (belongings[building].count < amount) {
  498. return false;
  499. }
  500. }
  501. } else if (type == "productivity") {
  502. for (const [key, value] of Object.entries(reqs)) {
  503. if (currentProductivity[key] < value) {
  504. return false;
  505. }
  506. }
  507. }
  508. }
  509. }
  510. return true;
  511. }
  512. function createUpgrades() {
  513. let container = document.querySelector("#upgrades-list");
  514. for (const [key, value] of Object.entries(upgrades)) {
  515. remainingUpgrades.push(key);
  516. let button = document.createElement("div");
  517. button.classList.add("upgrade-button");
  518. button.classList.add("hidden");
  519. button.id = "upgrade-" + key;
  520. let buttonName = document.createElement("div");
  521. buttonName.classList.add("upgrade-button-name");
  522. buttonName.innerText = value.name;
  523. let upgradeIcon = document.createElement("i");
  524. upgradeIcon.classList.add("fas");
  525. upgradeIcon.classList.add(value.icon);
  526. button.appendChild(buttonName);
  527. button.appendChild(upgradeIcon);
  528. button.addEventListener("mouseenter", function (e) { mouseTarget = button; upgradeTooltip(key, e); });
  529. button.addEventListener("mousemove", function (e) { mouseTarget = button; upgradeTooltip(key, e); });
  530. button.addEventListener("mouseleave", function () { mouseTarget = undefined; upgradeTooltipRemove(); });
  531. button.addEventListener("click", function (e) { buyUpgrade(key, e); });
  532. container.appendChild(button);
  533. }
  534. }
  535. function createDisplays() {
  536. // nop
  537. }
  538. function renderLine(line) {
  539. let div = document.createElement("div");
  540. div.innerText = line.text;
  541. if (line.valid !== undefined) {
  542. if (line.valid) {
  543. div.classList.add("cost-met");
  544. } else {
  545. div.classList.add("cost-unmet");
  546. }
  547. }
  548. if (line.class !== undefined) {
  549. for (let entry of line.class.split(",")) {
  550. div.classList.add(entry);
  551. }
  552. }
  553. return div;
  554. }
  555. function renderLines(lines) {
  556. let divs = [];
  557. for (let line of lines) {
  558. divs.push(renderLine(line));
  559. }
  560. return divs;
  561. }
  562. function renderCost(cost) {
  563. let list = [];
  564. list.push({
  565. "text": "Cost:"
  566. });
  567. for (const [key, value] of Object.entries(cost)) {
  568. list.push({
  569. "text": render(value, 0) + " " + resourceTypes[key].name,
  570. "valid": resources[key] >= value
  571. });
  572. }
  573. return renderLines(list);
  574. }
  575. function renderPrereqs(prereqs) {
  576. let list = [];
  577. if (prereqs === undefined) {
  578. return renderLines(list);
  579. }
  580. list.push({
  581. "text": "Own:"
  582. });
  583. for (const [key, value] of Object.entries(prereqs)) {
  584. if (key == "buildings") {
  585. for (const [id, amount] of Object.entries(prereqs.buildings)) {
  586. list.push({
  587. "text": buildings[id].name + " x" + render(amount, 0),
  588. "valid": belongings[id].count >= amount
  589. });
  590. }
  591. } else if (key == "productivity") {
  592. for (const [id, amount] of Object.entries(prereqs.productivity)) {
  593. list.push({
  594. "text": render(amount, 0) + " " + resourceTypes[id].name + "/s",
  595. "valid": currentProductivity[id] >= amount
  596. });
  597. }
  598. }
  599. }
  600. return renderLines(list);
  601. }
  602. function renderEffects(effectList) {
  603. let list = [];
  604. for (let effect of effectList) {
  605. list.push({ "text": effect_types[effect.type].desc(effect) });
  606. }
  607. return renderLines(list);
  608. }
  609. function clickPopup(text, type, location) {
  610. const div = document.createElement("div");
  611. div.textContent = text;
  612. div.classList.add("click-popup-" + type);
  613. var direction;
  614. if (type == "food") {
  615. direction = -150;
  616. } else if (type == "gulp") {
  617. direction = -150;
  618. } else if (type == "upgrade") {
  619. direction = -50;
  620. } else if (type == "info") {
  621. direction = 0;
  622. }
  623. direction *= Math.random() * 0.5 + 1;
  624. direction = Math.round(direction) + "px"
  625. div.style.setProperty("--target", direction)
  626. div.style.left = location[0] + "px";
  627. div.style.top = location[1] + "px";
  628. const body = document.querySelector("body");
  629. body.appendChild(div);
  630. setTimeout(() => {
  631. body.removeChild(div);
  632. }, 2000);
  633. }
  634. function doNews() {
  635. const state = {
  636. ownedUpgrades: ownedUpgrades,
  637. resources: resources,
  638. currentProductivity: currentProductivity,
  639. belongings: belongings
  640. };
  641. let options = [];
  642. news.forEach(entry => {
  643. if (entry.condition(state)) {
  644. options = options.concat(entry.lines);
  645. }
  646. });
  647. const choice = Math.floor(Math.random() * options.length);
  648. showNews(options[choice](state));
  649. setTimeout(() => {
  650. doNews();
  651. }, 15000 + Math.random() * 2500);
  652. }
  653. function showNews(text) {
  654. const div = document.createElement("div");
  655. div.textContent = text;
  656. div.classList.add("news-text");
  657. const body = document.querySelector("body");
  658. body.appendChild(div);
  659. setTimeout(() => {
  660. body.removeChild(div);
  661. }, 10000);
  662. }
  663. function doPowerup() {
  664. const lifetime = 10000;
  665. const button = document.createElement("div");
  666. const left = Math.round(Math.random() * 50 + 25) + "%";
  667. const top = Math.round(Math.random() * 50 + 25) + "%";
  668. button.classList.add("powerup");
  669. button.style.setProperty("--lifetime", lifetime / 1000 + "s");
  670. button.style.setProperty("--leftpos", left);
  671. button.style.setProperty("--toppos", top);
  672. const body = document.querySelector("body");
  673. body.appendChild(button);
  674. const choices = [];
  675. Object.entries(powerups).forEach(([key, val]) => {
  676. choices.push(key);
  677. });
  678. const choice = Math.floor(Math.random() * choices.length);
  679. const powerup = powerups[choices[choice]];
  680. const icon = document.createElement("div");
  681. icon.classList.add("fas");
  682. icon.classList.add(powerup.icon);
  683. button.appendChild(icon);
  684. const remove = setTimeout(() => {
  685. body.removeChild(button);
  686. }, lifetime);
  687. let delay = 60000 + Math.random() * 30000;
  688. for (let effect of effects["powerup-freq"]) {
  689. if (ownedUpgrades[effect.parent]) {
  690. delay = effect.apply(delay);
  691. }
  692. }
  693. setTimeout(() => {
  694. doPowerup();
  695. }, delay);
  696. const state = {
  697. ownedUpgrades: ownedUpgrades,
  698. resources: resources,
  699. currentProductivity: currentProductivity,
  700. belongings: belongings
  701. };
  702. button.addEventListener("mousedown", e => {
  703. if (powerup.duration !== undefined) {
  704. addPowerup(powerup);
  705. } else {
  706. powerup.effect(state);
  707. }
  708. powerup.popup(powerup, e);
  709. button.classList.add("powerup-clicked");
  710. clearTimeout(remove);
  711. setTimeout(() => {
  712. body.removeChild(button);
  713. }, 500);
  714. });
  715. }
  716. function fillTooltip(type, field, content) {
  717. let item = document.querySelector("#" + type + "-tooltip-" + field);
  718. if (typeof (content) === "string") {
  719. item.innerText = content;
  720. } else {
  721. replaceChildren(item, content);
  722. }
  723. }
  724. function upgradeTooltip(id, event) {
  725. let tooltip = document.querySelector("#upgrade-tooltip");
  726. tooltip.style.setProperty("display", "inline-block");
  727. fillTooltip("upgrade", "name", upgrades[id].name);
  728. fillTooltip("upgrade", "desc", upgrades[id].desc);
  729. fillTooltip("upgrade", "effect", renderEffects(upgrades[id].effects));
  730. fillTooltip("upgrade", "cost", renderCost(upgrades[id].cost));
  731. fillTooltip("upgrade", "prereqs", renderPrereqs(upgrades[id].prereqs));
  732. let yOffset = tooltip.parentElement.getBoundingClientRect().y;
  733. let tooltipSize = tooltip.getBoundingClientRect().height;
  734. let yTrans = Math.round(event.clientY - yOffset);
  735. var body = document.body,
  736. html = document.documentElement;
  737. var height = Math.max(window.innerHeight);
  738. yTrans = Math.min(yTrans, height - tooltipSize - 150);
  739. tooltip.style.setProperty("transform", "translate(-220px, " + yTrans + "px)");
  740. }
  741. function upgradeTooltipRemove() {
  742. let tooltip = document.querySelector("#upgrade-tooltip");
  743. tooltip.style.setProperty("display", "none");
  744. }
  745. function prodSummary(id) {
  746. let list = [];
  747. list.push(
  748. { "text": "Each " + buildings[id].name + " produces " + contributions[id].food + " food/sec" }
  749. );
  750. list.push(
  751. { "text": "Your " + render(belongings[id].count) + " " + (belongings[id].count == 1 ? buildings[id].name + " is" : buildings[id].plural + " are") + " producing " + round(productivityOf(id).food, 1) + " food/sec" }
  752. );
  753. let percentage = round(100 * productivityOf(id).food / currentProductivity["food"], 2);
  754. if (isNaN(percentage)) {
  755. percentage = 0;
  756. }
  757. list.push(
  758. { "text": "(" + percentage + "% of all food)" }
  759. );
  760. return renderLines(list);
  761. }
  762. function buildingTooltip(id, event) {
  763. let tooltip = document.querySelector("#building-tooltip");
  764. tooltip.style.setProperty("display", "inline-block");
  765. const count = buildingCount();
  766. fillTooltip("building", "name", (count != 1 ? count + "x " : "") + buildings[id].name);
  767. fillTooltip("building", "desc", buildings[id].desc);
  768. fillTooltip("building", "cost", render(costOfBuilding(id, count).food) + " food");
  769. fillTooltip("building", "prod", prodSummary(id));
  770. let xPos = tooltip.parentElement.getBoundingClientRect().x - 450;
  771. // wow browsers are bad
  772. var body = document.body,
  773. html = document.documentElement;
  774. var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
  775. let yPos = Math.min(event.clientY, height - 200);
  776. tooltip.style.setProperty("transform", "translate(" + xPos + "px, " + yPos + "px)")
  777. }
  778. function buildingTooltipRemove() {
  779. let tooltip = document.querySelector("#building-tooltip");
  780. tooltip.style.setProperty("display", "none");
  781. }
  782. window.onload = function () {
  783. setup();
  784. lastTime = performance.now();
  785. doNews();
  786. doPowerup();
  787. setTimeout(updateDisplay, 1000 / updateRate);
  788. setTimeout(autosave, 60000);
  789. }
  790. function autosave() {
  791. saveGame();
  792. let x = window.innerWidth / 2;
  793. let y = window.innerHeight * 9 / 10;
  794. clickPopup("Autosaving...", "info", [x, y]);
  795. setTimeout(autosave, 60000);
  796. }
  797. function save(e) {
  798. saveGame();
  799. clickPopup("Saved!", "info", [e.clientX, e.clientY]);
  800. }
  801. function saveGame() {
  802. try {
  803. let storage = window.localStorage;
  804. storage.setItem("save-version", 1);
  805. storage.setItem("ownedUpgrades", JSON.stringify(ownedUpgrades));
  806. storage.setItem("resources", JSON.stringify(resources));
  807. storage.setItem("belongings", JSON.stringify(belongings));
  808. } catch (e) {
  809. clickPopup("Can't save - no access to local storage.", "info", [window.innerWidth / 2, window.innerHeight / 5]);
  810. }
  811. }
  812. function load() {
  813. try {
  814. let storage = window.localStorage;
  815. if (!storage.getItem("save-version")) {
  816. return;
  817. }
  818. let newOwnedUpgrades = JSON.parse(storage.getItem("ownedUpgrades"));
  819. for (const [key, value] of Object.entries(newOwnedUpgrades)) {
  820. ownedUpgrades[key] = value;
  821. }
  822. let newResources = JSON.parse(storage.getItem("resources"));
  823. for (const [key, value] of Object.entries(newResources)) {
  824. resources[key] = value;
  825. }
  826. let newBelongings = JSON.parse(storage.getItem("belongings"));
  827. for (const [key, value] of Object.entries(newBelongings)) {
  828. belongings[key] = value;
  829. }
  830. } catch (e) {
  831. clickPopup("Can't load - no access to local storage.", "info", [window.innerWidth / 2, window.innerHeight / 5]);
  832. }
  833. }
  834. function reset() {
  835. window.localStorage.clear();
  836. }