cookie clicker but bigger
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1524 lines
37 KiB

  1. "use strict";
  2. const belongings = {};
  3. const stats = {};
  4. const macroDesc = {
  5. name: "Fen",
  6. species: "crux",
  7. proSubject: "he",
  8. proObject: "him",
  9. proPossessive: "his",
  10. }
  11. const ownedUpgrades = {};
  12. const remainingUpgrades = [];
  13. let showOwnedUpgrades = false;
  14. const effects = {};
  15. const resources = {};
  16. let updateRate = 60;
  17. const currentProductivity = {};
  18. const contributions = {};
  19. const clickPowers = {
  20. clickBonus: 0,
  21. clickMultiplier: 1,
  22. clickVictim: "micro",
  23. clickSeconds: 10
  24. }
  25. let clickBonus = 0;
  26. let clickVictim = "micro";
  27. let lastTime = 0;
  28. let controlHeld = false;
  29. let shiftHeld = false;
  30. let mouseTarget = undefined;
  31. let newsShowTimer;
  32. let newsRemoveTimer;
  33. const newsDelay = 8000;
  34. const newsWeightFactors = [];
  35. let buttonClicked = false;
  36. const state = {
  37. ownedUpgrades: ownedUpgrades,
  38. resources: resources,
  39. currentProductivity: currentProductivity,
  40. belongings: belongings,
  41. clickPowers: clickPowers,
  42. stats: stats
  43. };
  44. const numberModes = {
  45. words: {
  46. name: "Words",
  47. render: numberText,
  48. next: "smallWords"
  49. },
  50. smallWords: {
  51. name: "Small Words",
  52. render: numberTextSmall,
  53. next: "scientific"
  54. },
  55. scientific: {
  56. name: "Scientific",
  57. render: numberScientific,
  58. next: "full",
  59. },
  60. full: {
  61. name: "Full",
  62. render: numberFull,
  63. next: "words"
  64. }
  65. }
  66. deepFreeze(numberModes);
  67. let numberMode = numberModes["words"];
  68. const activePowerups = {};
  69. function tickPowerups(delta) {
  70. const powerupList = document.querySelector("#powerup-list");
  71. let changed = false;
  72. // I love mutating arrays as I traverse them.
  73. Object.entries(activePowerups).filter(x => x[1].life > 0).forEach(([key, data]) => {
  74. const newLife = data.life - delta;
  75. if (newLife <= 0) {
  76. setTimeout(() => {
  77. powerupList.removeChild(data.element);
  78. }, 1000);
  79. data.element.classList.add("powerup-entry-done");
  80. activePowerups[key].life = 0;
  81. changed = true;
  82. } else {
  83. data.life = newLife;
  84. const frac = (data.maxLife - data.life) / (data.maxLife);
  85. data.element.style.setProperty("--progress", frac * 100 + "%")
  86. }
  87. });
  88. if (changed) {
  89. updateAll();
  90. }
  91. }
  92. function addPowerup(key, powerup) {
  93. // powerup already exists
  94. if (activePowerups[key].life > 0) {
  95. activePowerups[key].life += powerup.duration;
  96. activePowerups[key].maxLife = activePowerups[key].life;
  97. } else {
  98. const powerupList = document.querySelector("#powerup-list");
  99. const powerupEntry = document.createElement("div");
  100. powerupEntry.classList.add("powerup-entry");
  101. const powerupIconHolder = document.createElement("div");
  102. powerupIconHolder.classList.add("powerup-entry-icon-holder");
  103. const powerupIcon = document.createElement("i");
  104. powerupIcon.classList.add("fas");
  105. powerupIcon.classList.add(powerup.icon);
  106. powerupIconHolder.appendChild(powerupIcon);
  107. powerupEntry.appendChild(powerupIconHolder);
  108. powerupList.appendChild(powerupEntry);
  109. activePowerups[key] = {powerup: powerup, life: powerup.duration, maxLife: powerup.duration, element: powerupEntry };
  110. powerupEntry.addEventListener("mousemove", function (e) { powerupTooltip(key, e); });
  111. powerupEntry.addEventListener("mouseleave", function () { powerupTooltipRemove(); });
  112. updateAll();
  113. }
  114. }
  115. function applyGlobalProdBonus(cost) {
  116. for (let effect of effects["prod-all"]) {
  117. if (ownedUpgrades[effect.parent]) {
  118. effect.apply(cost);
  119. }
  120. }
  121. }
  122. function calculateProductivity() {
  123. let productivity = makeCost();
  124. for (const [key, value] of Object.entries(belongings)) {
  125. const provided = productivityOf(key);
  126. productivity = addCost(productivity, provided);
  127. contributions[key] = provided;
  128. }
  129. return productivity;
  130. }
  131. // here's where upgrades will go :3
  132. function applyProductivityMultipliers(type, cost) {
  133. for (let effect of effects["prod"]) {
  134. if (ownedUpgrades[effect.parent] && effect.target == type) {
  135. effect.apply(cost);
  136. }
  137. }
  138. for (let effect of effects["helper"]) {
  139. if (ownedUpgrades[effect.parent] && effect.helped == type) {
  140. effect.apply(cost, belongings[effect.helper].count);
  141. }
  142. }
  143. }
  144. function productivityOf(type) {
  145. let baseProd = makeCost(buildings[type].prod);
  146. applyProductivityMultipliers(type, baseProd);
  147. applyGlobalProdBonus(baseProd);
  148. scaleCost(baseProd, belongings[type].count);
  149. return baseProd;
  150. }
  151. function makeCost(source) {
  152. const empty = mapObject(resourceTypes, () => 0);
  153. return {...empty, ...source};
  154. }
  155. function addCost(cost1, cost2) {
  156. return Object.keys(resourceTypes).reduce((o, k) => {o[k] += cost2[k]; return o;}, cost1);
  157. }
  158. function scaleCost(cost, scale) {
  159. return Object.keys(resourceTypes).reduce((o, k) => {o[k] *= scale; return o;}, cost);
  160. }
  161. function costOfBuilding(type, count = 1) {
  162. let total = makeCost();
  163. while (count > 0) {
  164. let baseCost = makeCost(buildings[type].cost);
  165. baseCost = scaleCost(baseCost, Math.pow(1.15, belongings[type].count + count - 1));
  166. total = addCost(total, baseCost);
  167. count--;
  168. }
  169. return mapObject(total, round);
  170. }
  171. function buildingCount() {
  172. if (controlHeld) {
  173. return 10;
  174. } else if (shiftHeld) {
  175. return 100;
  176. } else {
  177. return 1;
  178. }
  179. }
  180. function buyBuilding(type, e) {
  181. const count = buildingCount();
  182. let cost = costOfBuilding(type, count);
  183. if (canAfford(cost)) {
  184. spend(cost);
  185. belongings[type].count += count;
  186. }
  187. updateProductivity();
  188. }
  189. function updateAll() {
  190. updateProductivity();
  191. updateClickVictim();
  192. updateOptions();
  193. }
  194. function updateOptions() {
  195. cache.optionButtons.numbers.innerText = "Number mode: " + numberMode.name;
  196. }
  197. // update stuff
  198. function updateDisplay() {
  199. let newTime = performance.now();
  200. let delta = newTime - lastTime;
  201. lastTime = newTime;
  202. addResources(delta);
  203. displayResources();
  204. displayBuildings();
  205. displayUpgrades(showOwnedUpgrades);
  206. tickPowerups(delta);
  207. Object.keys(statTypes).forEach(key => {
  208. const value = document.querySelector("#stat-value-" + key);
  209. value.innerText = render(stats[key]);
  210. })
  211. stats.seconds += delta / 1000;
  212. setTimeout(updateDisplay, 1000 / updateRate);
  213. }
  214. function updateProductivity() {
  215. Object.assign(currentProductivity, calculateProductivity());
  216. // maybe this should go somewhere else - it also does clicking...
  217. updateClickPowers();
  218. Object.entries(activePowerups).forEach(([key, entry]) => {
  219. if (entry.life > 0) {
  220. const powerup = entry.powerup;
  221. powerup.effect(state);
  222. }
  223. });
  224. }
  225. function addResources(delta) {
  226. for (const [resource, amount] of Object.entries(currentProductivity)) {
  227. const gained = amount * delta / 1000;
  228. resources[resource] += gained;
  229. if (resource == "food")
  230. stats.food += gained;
  231. }
  232. }
  233. function displayResources() {
  234. document.title = "Gorge - " + round(resources.food) + " food";
  235. Object.keys(resources).forEach(key => {
  236. cache.resourceLabels[key].quantity.innerText = render(resources[key]) + " " + resourceTypes[key].name;
  237. if (resourceTypes[key].generated)
  238. cache.resourceLabels[key].rate.innerText = render(currentProductivity[key]) + " " + resourceTypes[key].name + "/sec";
  239. })
  240. }
  241. function displayBuildings() {
  242. const count = buildingCount();
  243. for (const [key, value] of Object.entries(belongings)) {
  244. let available = states.buildings[key].available;
  245. if (!belongings[key].visible) {
  246. if (resources.food * 10 >= costOfBuilding(key).food) {
  247. unlockBuilding(key);
  248. } if (belongings[key].count > 0) {
  249. unlockBuilding(key);
  250. } else {
  251. continue;
  252. }
  253. belongings[key].visible = true;
  254. let button = cache.buildingButtons[key].button;
  255. button.classList.remove("hidden");
  256. }
  257. let button = cache.buildingButtons[key].button;
  258. let name = cache.buildingButtons[key].name;
  259. let cost = cache.buildingButtons[key].cost;
  260. const buildingCost = costOfBuilding(key, count);
  261. const newName = value.count + " " + (value.count == 1 ? buildings[key].name : buildings[key].plural);
  262. if (newName != states.buildings[key].name) {
  263. name.innerText = newName;
  264. states.buildings[key].name = newName;
  265. }
  266. const newCost = render(buildingCost.food) + " food";
  267. if (newCost != states.buildings[key].cost) {
  268. cost.innerText = newCost;
  269. states.buildings[key].cost = newCost;
  270. }
  271. if (canAfford(buildingCost) && available !== true) {
  272. button.classList.remove("building-button-disabled");
  273. cost.classList.add("building-button-cost-valid");
  274. states.buildings[key].available = true;
  275. } else if (!canAfford(buildingCost) && available !== false) {
  276. button.classList.add("building-button-disabled");
  277. cost.classList.add("building-button-cost-invalid");
  278. states.buildings[key].available = false;
  279. }
  280. }
  281. }
  282. function canAfford(cost) {
  283. for (const [resource, amount] of Object.entries(cost)) {
  284. if (resources[resource] < amount) {
  285. return false;
  286. }
  287. }
  288. return true;
  289. }
  290. function spend(cost) {
  291. for (const [resource, amount] of Object.entries(cost)) {
  292. resources[resource] -= amount;
  293. }
  294. }
  295. function switchShowOwnedUpgrades() {
  296. initializeUpgradeStates();
  297. if (showOwnedUpgrades) {
  298. document.querySelector("#upgrades").innerText = "Upgrades";
  299. } else {
  300. document.querySelector("#upgrades").innerText = "Owned Upgrades";
  301. }
  302. showOwnedUpgrades = !showOwnedUpgrades;
  303. }
  304. function displayUpgrades(owned) {
  305. if (owned) {
  306. Object.entries(ownedUpgrades).forEach(([key, val]) => {
  307. let button = cache.upgradeButtons[key];
  308. if (val) {
  309. button.classList.remove("hidden");
  310. } else {
  311. button.classList.add("hidden");
  312. }
  313. });
  314. }
  315. else {
  316. for (let id of remainingUpgrades) {
  317. let button = cache.upgradeButtons[id];
  318. let visible = states.upgrades[id].visible;
  319. let available = states.upgrades[id].available;
  320. if (ownedUpgrades[id] && visible !== false) {
  321. button.classList.add("hidden");
  322. states.upgrades[id].visible = false;
  323. continue;
  324. }
  325. if (upgradeReachable(id) && visible !== true) {
  326. button.classList.remove("hidden");
  327. states.upgrades[id].visible = true;
  328. } else if (!upgradeReachable(id) && visible !== false) {
  329. button.classList.add("hidden");
  330. states.upgrades[id].visible = false;
  331. }
  332. if (upgradeAvailable(id) && available !== true) {
  333. button.classList.remove("upgrade-button-inactive");
  334. states.upgrades[id].available = true;
  335. } else if (!upgradeAvailable(id) && available !== false) {
  336. button.classList.add("upgrade-button-inactive");
  337. states.upgrades[id].available = false;
  338. }
  339. }
  340. // we aren't trimming the list of upgrades now
  341. // because we need to switch between owned and unowned upgrades
  342. // - thus we need to be able to show or hide anything
  343. /*
  344. for (let i = remainingUpgrades.length-1; i >= 0; i--) {
  345. if (ownedUpgrades[remainingUpgrades[i]]) {
  346. remainingUpgrades.splice(i, 1);
  347. }
  348. }*/
  349. }
  350. }
  351. function updateClickPowers() {
  352. let bonus = 0;
  353. clickPowers.clickMultiplier = 1;
  354. for (let effect of effects["click"]) {
  355. if (ownedUpgrades[effect.parent]) {
  356. bonus = effect.apply(bonus, currentProductivity["food"]);
  357. }
  358. }
  359. clickPowers.clickBonus = bonus;
  360. }
  361. function updateClickVictim() {
  362. const button = document.querySelector("#tasty-micro");
  363. button.classList.remove(...button.classList);
  364. for (let i=effects["click-victim"].length - 1; i >=0; i--) {
  365. const effect = effects["click-victim"][i];
  366. if (ownedUpgrades[effect.parent]) {
  367. clickPowers.clickVictim = effect.id;
  368. button.classList.add("fas")
  369. button.classList.add(buildings[effect.id].icon)
  370. return;
  371. }
  372. }
  373. clickPowers.clickVictim = "micro";
  374. button.classList.add("fas")
  375. button.classList.add(buildings.micro.icon)
  376. }
  377. function buyUpgrade(id, e) {
  378. if (ownedUpgrades[id]) {
  379. return;
  380. }
  381. let upgrade = upgrades[id];
  382. if (!upgradeAvailable(id)) {
  383. return;
  384. }
  385. spend(upgrade.cost);
  386. ownedUpgrades[id] = true;
  387. let text = "Bought " + upgrade.name + "!";
  388. clickPopup(text, "upgrade", [e.clientX, e.clientY]);
  389. updateProductivity();
  390. updateClickVictim();
  391. }
  392. function eatPrey() {
  393. const add = clickPowers.clickMultiplier * (buildings[clickPowers.clickVictim]["prod"].food * clickPowers.clickSeconds + clickPowers.clickBonus);
  394. resources.food += add;
  395. stats.foodClicked += add;
  396. return add;
  397. }
  398. // setup stuff lol
  399. // we'll initialize the dict of buildings we can own
  400. function setup() {
  401. // create static data
  402. createTemplateUpgrades();
  403. // prepare dynamic stuff
  404. initializeData();
  405. initializeNews();
  406. createButtons();
  407. createDisplays();
  408. registerListeners();
  409. load();
  410. unlockAtStart();
  411. initializeCaches();
  412. initializeStates();
  413. updateAll();
  414. }
  415. function initializeNews() {
  416. news.forEach(entry => {
  417. newsWeightFactors.push(0);
  418. });
  419. }
  420. const cache = {};
  421. function initializeCaches() {
  422. const buildingButtons = {};
  423. for (const [key, value] of Object.entries(belongings)) {
  424. let button = document.querySelector("#building-" + key);
  425. let name = document.querySelector("#building-" + key + " > .building-button-name");
  426. let cost = document.querySelector("#building-" + key + " > .building-button-cost");
  427. buildingButtons[key] = {
  428. button: button,
  429. name: name,
  430. cost: cost
  431. }
  432. }
  433. cache.buildingButtons = buildingButtons;
  434. const upgradeButtons = {};
  435. Object.keys(upgrades).forEach(key => {
  436. upgradeButtons[key] = document.querySelector("#upgrade-" + key);
  437. });
  438. cache.upgradeButtons = upgradeButtons;
  439. const resourceLabels = {};
  440. Object.keys(resourceTypes).forEach(key => {
  441. resourceLabels[key] = {
  442. quantity: document.querySelector("#resource-quantity-" + key),
  443. }
  444. if (resourceTypes[key].generated)
  445. resourceLabels[key].rate = document.querySelector("#resource-rate-" + key);
  446. });
  447. cache.resourceLabels = resourceLabels;
  448. const optionButtons = {};
  449. optionButtons.numbers = document.querySelector("#numbers");
  450. cache.optionButtons = optionButtons;
  451. }
  452. const states = {};
  453. // we can keep track of some things, like whether
  454. // specific upgrades are currently visible. this
  455. // way, we don't have to set them visible every tick;
  456. // we can just check if they've been handled already
  457. function initializeStates() {
  458. initializeBuildingStates();
  459. initializeUpgradeStates();
  460. }
  461. function initializeBuildingStates() {
  462. const buildingStates = {};
  463. Object.keys(buildings).forEach(key => {
  464. buildingStates[key] = {
  465. visible: undefined,
  466. available: undefined,
  467. name: undefined,
  468. cost: undefined
  469. }
  470. });
  471. states.buildings = buildingStates;
  472. }
  473. function initializeUpgradeStates() {
  474. const upgradeStates = {};
  475. Object.keys(upgrades).forEach(key => {
  476. upgradeStates[key] = {
  477. visible: undefined,
  478. available: undefined
  479. }
  480. });
  481. states.upgrades = upgradeStates;
  482. }
  483. function unlockAtStart() {
  484. unlockBuilding("micro");
  485. for (const [key, value] of Object.entries(belongings)) {
  486. if (belongings[key].visible) {
  487. unlockBuilding(key);
  488. }
  489. }
  490. }
  491. function unlockBuilding(id) {
  492. belongings[id].visible = true;
  493. document.querySelector("#building-" + id).classList.remove("hidden");
  494. }
  495. function initializeData() {
  496. for (const [key, value] of Object.entries(buildings)) {
  497. belongings[key] = {};
  498. belongings[key].count = 0;
  499. belongings[key].visible = false;
  500. contributions[key] = makeCost();
  501. }
  502. for (const [key, value] of Object.entries(resourceTypes)) {
  503. resources[key] = 0;
  504. currentProductivity[key] = 0;
  505. }
  506. for (const [id, upgrade] of Object.entries(upgrades)) {
  507. ownedUpgrades[id] = false;
  508. for (let effect of upgrade.effects) {
  509. if (effects[effect.type] === undefined) {
  510. effects[effect.type] = [];
  511. }
  512. // copy the data and add an entry for the upgrade id that owns the effect
  513. let newEffect = {};
  514. for (const [key, value] of Object.entries(effect)) {
  515. newEffect[key] = value;
  516. }
  517. newEffect.parent = id;
  518. // unfortunate name collision here
  519. // I'm using apply() to pass on any number of arguments to the
  520. // apply() function of the effect type
  521. newEffect.apply = function (...args) { return effect_types[effect.type].apply.apply(null, [effect].concat(args)); }
  522. effects[effect.type].push(newEffect);
  523. }
  524. }
  525. Object.keys(powerups).filter(x => powerups[x].duration !== undefined).forEach(key => activePowerups[key] = {
  526. life: 0
  527. });
  528. Object.entries(statTypes).forEach(([key, info]) => {
  529. stats[key] = 0;
  530. });
  531. }
  532. function handleButton(e) {
  533. const add = eatPrey();
  534. const text = "+" + render(round(add, 1), 3) + " food";
  535. const gulp = "*glp*";
  536. clickPopup(text, "food", [e.clientX, e.clientY]);
  537. clickPopup(gulp, "gulp", [e.clientX, e.clientY]);
  538. stats.clicks += 1;
  539. }
  540. function registerListeners() {
  541. document.addEventListener("mouseup", (e) => {
  542. if (buttonClicked) {
  543. buttonClicked = false;
  544. handleButton(e);
  545. return false;
  546. } else {
  547. return true;
  548. }
  549. });
  550. document.querySelector("#tasty-micro").addEventListener("mousedown", (e) => {
  551. buttonClicked = true;
  552. });
  553. document.querySelector("#save").addEventListener("click", save);
  554. document.querySelector("#reset").addEventListener("click", reset);
  555. document.querySelector("#numbers").addEventListener("click", cycleNumbers);
  556. document.querySelector("#stats").addEventListener("click", () => document.querySelector("#stats-modal").classList.add("modal-active"));
  557. document.querySelector("#options").addEventListener("click", openOptions);
  558. document.querySelector("#stats-exit").addEventListener("click", () => document.querySelector("#stats-modal").classList.remove("modal-active"));
  559. document.querySelector("#options-exit").addEventListener("click", closeOptions);
  560. document.querySelector("#upgrades").addEventListener("click", switchShowOwnedUpgrades);
  561. document.addEventListener("keydown", e => {
  562. shiftHeld = e.shiftKey;
  563. controlHeld = e.ctrlKey;
  564. if (mouseTarget)
  565. mouseTarget.dispatchEvent(new Event("mousemove"));
  566. return true;
  567. });
  568. document.addEventListener("keyup", e => {
  569. shiftHeld = e.shiftKey;
  570. controlHeld = e.ctrlKey;
  571. if (mouseTarget)
  572. mouseTarget.dispatchEvent(new Event("mousemove"));
  573. return true;
  574. });
  575. }
  576. function openOptions() {
  577. document.querySelector("#options-modal").classList.add("modal-active");
  578. Object.keys(options).forEach(key => {
  579. const input = document.querySelector("#option-value-" + key);
  580. input.value = options[key].get();
  581. });
  582. }
  583. function closeOptions() {
  584. document.querySelector("#options-modal").classList.remove("modal-active");
  585. Object.keys(options).forEach(key => {
  586. const input = document.querySelector("#option-value-" + key);
  587. options[key].set(input.value);
  588. });
  589. }
  590. function createButtons() {
  591. createBuildings();
  592. createUpgrades();
  593. }
  594. function createBuildings() {
  595. let container = document.querySelector("#buildings-list");
  596. for (const [key, value] of Object.entries(buildings)) {
  597. let button = document.createElement("div");
  598. button.classList.add("building-button");
  599. button.classList.add("hidden");
  600. button.id = "building-" + key;
  601. let buttonName = document.createElement("div");
  602. buttonName.classList.add("building-button-name");
  603. let buttonCost = document.createElement("div");
  604. buttonCost.classList.add("building-button-cost");
  605. let buildingIcon = document.createElement("i");
  606. buildingIcon.classList.add("fas");
  607. buildingIcon.classList.add(value.icon);
  608. button.appendChild(buttonName);
  609. button.appendChild(buttonCost);
  610. button.appendChild(buildingIcon);
  611. button.addEventListener("mousemove", function (e) { mouseTarget = button; buildingTooltip(key, e); });
  612. button.addEventListener("mouseleave", function () { mouseTarget = undefined; buildingTooltipRemove(); });
  613. button.addEventListener("click", function (e) { buyBuilding(key, e); });
  614. button.addEventListener("click", function (e) { buildingTooltip(key, e); });
  615. container.appendChild(button);
  616. }
  617. }
  618. // do we have previous techs and at least one of each building?
  619. function upgradeReachable(id) {
  620. if (ownedUpgrades[id]) {
  621. return false;
  622. }
  623. if (upgrades[id].prereqs !== undefined) {
  624. for (const [type, reqs] of Object.entries(upgrades[id].prereqs)) {
  625. if (type == "buildings") {
  626. for (const [building, amount] of Object.entries(reqs)) {
  627. if (belongings[building].count == 0) {
  628. return false;
  629. }
  630. }
  631. }
  632. else if (type == "upgrades") {
  633. for (let upgrade of reqs) {
  634. if (!ownedUpgrades[upgrade]) {
  635. return false;
  636. }
  637. }
  638. }
  639. else if (type == "resources") {
  640. for (const [resource, amount] of Object.entries(reqs)) {
  641. if (resources[resource] < amount) {
  642. return false;
  643. }
  644. };
  645. }
  646. else if (type == "stats") {
  647. for (const [stat, amount] of Object.entries(reqs)) {
  648. if (stats[stat] < amount) {
  649. return false;
  650. }
  651. };
  652. }
  653. }
  654. }
  655. return true;
  656. }
  657. function upgradeAvailable(id) {
  658. if (!upgradeReachable(id)) {
  659. return false;
  660. }
  661. if (!canAfford(upgrades[id].cost)) {
  662. return false;
  663. }
  664. if (upgrades[id].prereqs !== undefined) {
  665. for (const [type, reqs] of Object.entries(upgrades[id].prereqs)) {
  666. if (type == "buildings") {
  667. for (const [building, amount] of Object.entries(upgrades[id].prereqs[type])) {
  668. if (belongings[building].count < amount) {
  669. return false;
  670. }
  671. }
  672. } else if (type == "productivity") {
  673. for (const [key, value] of Object.entries(reqs)) {
  674. if (currentProductivity[key] < value) {
  675. return false;
  676. }
  677. }
  678. }
  679. }
  680. }
  681. return true;
  682. }
  683. function createUpgrades() {
  684. let container = document.querySelector("#upgrades-list");
  685. for (const [key, value] of Object.entries(upgrades)) {
  686. remainingUpgrades.push(key);
  687. let button = document.createElement("div");
  688. button.classList.add("upgrade-button");
  689. button.classList.add("hidden");
  690. button.id = "upgrade-" + key;
  691. const holder = document.createElement("div");
  692. holder.classList.add("upgrade-icon-holder");
  693. button.appendChild(holder);
  694. if (typeof(value.icon) == "object") {
  695. value.icon.forEach(icon => {
  696. let upgradeIcon = document.createElement("i");
  697. upgradeIcon.classList.add("fas");
  698. upgradeIcon.classList.add(icon.icon);
  699. upgradeIcon.style.color = icon.color;
  700. holder.appendChild(upgradeIcon);
  701. if (icon.transform) {
  702. upgradeIcon.style.transform = icon.transform;
  703. }
  704. })
  705. } else {
  706. let upgradeIcon = document.createElement("i");
  707. upgradeIcon.classList.add("fas");
  708. upgradeIcon.classList.add(value.icon);
  709. holder.appendChild(upgradeIcon);
  710. }
  711. button.addEventListener("mouseenter", function (e) { mouseTarget = button; upgradeTooltip(key, e); });
  712. button.addEventListener("mousemove", function (e) { mouseTarget = button; upgradeTooltip(key, e); });
  713. button.addEventListener("mouseleave", function () { mouseTarget = undefined; upgradeTooltipRemove(); });
  714. button.addEventListener("click", function (e) { buyUpgrade(key, e); });
  715. container.appendChild(button);
  716. }
  717. }
  718. function createDisplays() {
  719. const resourceList = document.querySelector("#resource-list");
  720. Object.keys(resourceTypes).forEach(key => {
  721. const quantity = document.createElement("div");
  722. quantity.classList.add("resource-quantity");
  723. quantity.id = "resource-quantity-" + key;
  724. resourceList.appendChild(quantity);
  725. if (resourceTypes[key].generated) {
  726. const rate = document.createElement("div");
  727. rate.classList.add("resource-rate");
  728. rate.id = "resource-rate-" + key;
  729. resourceList.appendChild(rate);
  730. }
  731. })
  732. const statHolder = document.querySelector("#stats-holder");
  733. Object.keys(statTypes).forEach(key => {
  734. const div = document.createElement("div");
  735. div.classList.add("stat-line");
  736. const name = document.createElement("div");
  737. name.classList.add("stat-name");
  738. const value = document.createElement("div");
  739. value.classList.add("stat-value");
  740. value.id = "stat-value-" + key;
  741. name.innerText = statTypes[key].name;
  742. value.innerText = stats[key];
  743. div.appendChild(name);
  744. div.appendChild(value);
  745. statHolder.append(div);
  746. });
  747. const optionHolder = document.querySelector("#options-holder");
  748. Object.keys(options).forEach(key => {
  749. const div = document.createElement("div");
  750. div.classList.add("option-line");
  751. const name = document.createElement("div");
  752. name.classList.add("option-name");
  753. const value = document.createElement("input");
  754. value.classList.add("option-value");
  755. value.id = "option-value-" + key;
  756. name.innerText = options[key].name;
  757. value.innerText = options[key].get();
  758. div.appendChild(name);
  759. div.appendChild(value);
  760. optionHolder.append(div);
  761. });
  762. }
  763. function renderLine(line) {
  764. let div = document.createElement("div");
  765. div.innerText = line.text;
  766. if (line.valid !== undefined) {
  767. if (line.valid) {
  768. div.classList.add("cost-met");
  769. } else {
  770. div.classList.add("cost-unmet");
  771. }
  772. }
  773. if (line.class !== undefined) {
  774. for (let entry of line.class.split(",")) {
  775. div.classList.add(entry);
  776. }
  777. }
  778. return div;
  779. }
  780. function renderLines(lines) {
  781. let divs = [];
  782. for (let line of lines) {
  783. divs.push(renderLine(line));
  784. }
  785. return divs;
  786. }
  787. function renderCost(cost) {
  788. let list = [];
  789. list.push({
  790. "text": "Cost:"
  791. });
  792. for (const [key, value] of Object.entries(cost)) {
  793. list.push({
  794. "text": render(value, 0) + " " + resourceTypes[key].name,
  795. "valid": resources[key] >= value
  796. });
  797. }
  798. return renderLines(list);
  799. }
  800. function renderPrereqs(prereqs) {
  801. let list = [];
  802. if (prereqs === undefined) {
  803. return renderLines(list);
  804. }
  805. list.push({
  806. "text": "Own:"
  807. });
  808. for (const [key, value] of Object.entries(prereqs)) {
  809. if (key == "buildings") {
  810. for (const [id, amount] of Object.entries(prereqs.buildings)) {
  811. list.push({
  812. "text": buildings[id].name + " x" + render(amount, 0),
  813. "valid": belongings[id].count >= amount
  814. });
  815. }
  816. } else if (key == "productivity") {
  817. for (const [id, amount] of Object.entries(prereqs.productivity)) {
  818. list.push({
  819. "text": render(amount, 0) + " " + resourceTypes[id].name + "/s",
  820. "valid": currentProductivity[id] >= amount
  821. });
  822. }
  823. }
  824. }
  825. return renderLines(list);
  826. }
  827. function renderEffects(effectList) {
  828. let list = [];
  829. for (let effect of effectList) {
  830. list.push({ "text": effect_types[effect.type].desc(effect) });
  831. }
  832. return renderLines(list);
  833. }
  834. function clickPopup(text, type, location) {
  835. const div = document.createElement("div");
  836. div.textContent = text;
  837. div.classList.add("click-popup-" + type);
  838. var direction;
  839. if (type == "food") {
  840. direction = -150;
  841. } else if (type == "gulp") {
  842. direction = -150;
  843. } else if (type == "upgrade") {
  844. direction = -50;
  845. } else if (type == "info") {
  846. direction = 0;
  847. }
  848. direction *= Math.random() * 0.5 + 1;
  849. direction = Math.round(direction) + "px"
  850. div.style.setProperty("--target", direction)
  851. div.style.left = location[0] + "px";
  852. div.style.top = location[1] + "px";
  853. const body = document.querySelector("body");
  854. body.appendChild(div);
  855. setTimeout(() => {
  856. body.removeChild(div);
  857. }, 2000);
  858. }
  859. function doNews() {
  860. let options = [];
  861. let weights = [];
  862. let indices = [];
  863. let index = 0;
  864. news.forEach(entry => {
  865. if (entry.condition(state) && newsWeightFactors[index] != 1) {
  866. options = options.concat(entry.lines);
  867. weights.push(1 - newsWeightFactors[index])
  868. indices.push(index);
  869. }
  870. index += 1;
  871. });
  872. const choice = weightedSelect(weights);
  873. showNews(options[choice](state));
  874. for (let i = 0; i < newsWeightFactors.length; i++) {
  875. newsWeightFactors[i] *= 0.9;
  876. }
  877. newsWeightFactors[indices[choice]] = 1;
  878. newsShowTimer = setTimeout(() => {
  879. doNews();
  880. }, 8000);
  881. }
  882. function showNews(text) {
  883. const div = document.createElement("div");
  884. div.innerHTML = text;
  885. div.classList.add("news-text");
  886. const body = document.querySelector("body");
  887. div.addEventListener("click", () => {
  888. clearTimeout(newsShowTimer);
  889. clearTimeout(newsRemoveTimer);
  890. div.classList.add("news-text-leaving");
  891. setTimeout(() => {
  892. body.removeChild(div);
  893. }, 1000);
  894. doNews();
  895. });
  896. body.appendChild(div);
  897. newsRemoveTimer = setTimeout(() => {
  898. div.classList.add("news-text-leaving");
  899. setTimeout(() => {
  900. body.removeChild(div);
  901. }, 1000);
  902. }, 8000);
  903. }
  904. function doPowerup() {
  905. const lifetime = 10000;
  906. const button = document.createElement("div");
  907. const left = Math.round(Math.random() * 50 + 25) + "%";
  908. const top = Math.round(Math.random() * 50 + 25) + "%";
  909. button.classList.add("powerup");
  910. button.style.setProperty("--lifetime", lifetime / 1000 + "s");
  911. button.style.setProperty("--leftpos", left);
  912. button.style.setProperty("--toppos", top);
  913. const body = document.querySelector("body");
  914. body.appendChild(button);
  915. const choices = [];
  916. Object.entries(powerups).forEach(([key, val]) => {
  917. if (val.prereqs(state))
  918. choices.push(key);
  919. });
  920. const choice = Math.floor(Math.random() * choices.length);
  921. const powerup = powerups[choices[choice]];
  922. const icon = document.createElement("div");
  923. icon.classList.add("fas");
  924. icon.classList.add(powerup.icon);
  925. button.appendChild(icon);
  926. const remove = setTimeout(() => {
  927. body.removeChild(button);
  928. }, lifetime);
  929. let delay = 60000 + Math.random() * 30000;
  930. for (let effect of effects["powerup-freq"]) {
  931. if (ownedUpgrades[effect.parent]) {
  932. delay = effect.apply(delay);
  933. }
  934. }
  935. setTimeout(() => {
  936. doPowerup();
  937. }, delay);
  938. button.addEventListener("mousedown", e => {
  939. if (powerup.duration !== undefined) {
  940. addPowerup(choices[choice], powerup);
  941. } else {
  942. powerup.effect(state);
  943. }
  944. powerup.popup(powerup, e);
  945. button.classList.add("powerup-clicked");
  946. resources.powerups += 1;
  947. clearTimeout(remove);
  948. stats.powerups += 1;
  949. setTimeout(() => {
  950. body.removeChild(button);
  951. }, 500);
  952. });
  953. }
  954. function fillTooltip(type, field, content) {
  955. let item = document.querySelector("#" + type + "-tooltip-" + field);
  956. if (typeof (content) === "string") {
  957. item.innerText = content;
  958. } else {
  959. replaceChildren(item, content);
  960. }
  961. }
  962. function upgradeTooltip(id, event) {
  963. let tooltip = document.querySelector("#upgrade-tooltip");
  964. tooltip.style.setProperty("display", "inline-block");
  965. fillTooltip("upgrade", "name", upgrades[id].name);
  966. fillTooltip("upgrade", "desc", upgrades[id].desc);
  967. fillTooltip("upgrade", "effect", renderEffects(upgrades[id].effects));
  968. fillTooltip("upgrade", "cost", renderCost(upgrades[id].cost));
  969. fillTooltip("upgrade", "prereqs", renderPrereqs(upgrades[id].prereqs));
  970. let yOffset = tooltip.parentElement.getBoundingClientRect().y;
  971. let tooltipSize = tooltip.getBoundingClientRect().height;
  972. let yTrans = Math.round(event.clientY - yOffset);
  973. var body = document.body,
  974. html = document.documentElement;
  975. var height = Math.max(window.innerHeight);
  976. yTrans = Math.min(yTrans, height - tooltipSize - 150);
  977. tooltip.style.setProperty("transform", "translate(-420px, " + yTrans + "px)");
  978. }
  979. function upgradeTooltipRemove() {
  980. let tooltip = document.querySelector("#upgrade-tooltip");
  981. tooltip.style.setProperty("display", "none");
  982. }
  983. function prodSummary(id) {
  984. let list = [];
  985. list.push(
  986. { "text": "Each " + buildings[id].name + " produces " + render(belongings[id].count == 0 ? 0 : contributions[id].food / belongings[id].count, 3) + " food/sec" }
  987. );
  988. list.push(
  989. { "text": "Your " + render(belongings[id].count) + " " + (belongings[id].count == 1 ? buildings[id].name + " is" : buildings[id].plural + " are") + " producing " + render(contributions[id].food, 3) + " food/sec" }
  990. );
  991. let percentage = round(100 * contributions[id].food / currentProductivity["food"], 2);
  992. if (isNaN(percentage)) {
  993. percentage = 0;
  994. }
  995. list.push(
  996. { "text": "(" + percentage + "% of all food)" }
  997. );
  998. return renderLines(list);
  999. }
  1000. function buildingTooltip(id, event) {
  1001. let tooltip = document.querySelector("#building-tooltip");
  1002. tooltip.style.setProperty("display", "inline-block");
  1003. const count = buildingCount();
  1004. fillTooltip("building", "name", (count != 1 ? count + "x " : "") + buildings[id].name);
  1005. fillTooltip("building", "desc", buildings[id].desc);
  1006. fillTooltip("building", "cost", render(costOfBuilding(id, count).food) + " food");
  1007. fillTooltip("building", "prod", prodSummary(id));
  1008. let xPos = tooltip.parentElement.getBoundingClientRect().x - 450;
  1009. // wow browsers are bad
  1010. var body = document.body,
  1011. html = document.documentElement;
  1012. var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
  1013. let yPos = Math.min(event.clientY, height - 200);
  1014. tooltip.style.setProperty("transform", "translate(" + xPos + "px, " + yPos + "px)")
  1015. }
  1016. function buildingTooltipRemove() {
  1017. let tooltip = document.querySelector("#building-tooltip");
  1018. tooltip.style.setProperty("display", "none");
  1019. }
  1020. function powerupTooltip(id, event) {
  1021. let tooltip = document.querySelector("#powerup-tooltip");
  1022. tooltip.style.setProperty("display", "inline-block");
  1023. fillTooltip("powerup", "name", powerups[id].name);
  1024. fillTooltip("powerup", "desc", powerups[id].description);
  1025. let xPos = tooltip.parentElement.getBoundingClientRect().x + 100;
  1026. // wow browsers are bad
  1027. var body = document.body,
  1028. html = document.documentElement;
  1029. var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
  1030. let yPos = Math.min(event.clientY - 100, height - 150);
  1031. tooltip.style.setProperty("transform", "translate(" + xPos + "px, " + yPos + "px)")
  1032. }
  1033. function powerupTooltipRemove() {
  1034. let tooltip = document.querySelector("#powerup-tooltip");
  1035. tooltip.style.setProperty("display", "none");
  1036. }
  1037. window.onload = function () {
  1038. setup();
  1039. lastTime = performance.now();
  1040. doNews();
  1041. doPowerup();
  1042. setTimeout(updateDisplay, 1000 / updateRate);
  1043. setTimeout(autosave, 60000);
  1044. }
  1045. window.onblur = function() {
  1046. controlHeld = false;
  1047. shiftHeld = false;
  1048. }
  1049. window.onfocus = function() {
  1050. window.dispatchEvent(new Event("keydown"))
  1051. }
  1052. function autosave() {
  1053. saveGame();
  1054. let x = window.innerWidth / 2;
  1055. let y = window.innerHeight * 9 / 10;
  1056. clickPopup("Autosaving...", "info", [x, y]);
  1057. setTimeout(autosave, 60000);
  1058. }
  1059. function save(e) {
  1060. saveGame();
  1061. clickPopup("Saved!", "info", [e.clientX, e.clientY]);
  1062. }
  1063. function saveGame() {
  1064. try {
  1065. let storage = window.localStorage;
  1066. const save = {}
  1067. save.version = migrations.length;
  1068. save.ownedUpgrades = ownedUpgrades;
  1069. save.resources = resources;
  1070. save.belongings = belongings;
  1071. save.stats = stats;
  1072. save.macroDesc = macroDesc;
  1073. storage.setItem("save", JSON.stringify(save));
  1074. } catch (e) {
  1075. clickPopup("Can't save - no access to local storage.", "info", [window.innerWidth / 2, window.innerHeight / 5]);
  1076. }
  1077. }
  1078. const migrations = [
  1079. // dummy migration, because there was no version 0
  1080. save => {
  1081. },
  1082. // introduce stats
  1083. save => {
  1084. save.stats = {}
  1085. },
  1086. // introduce macroDesc
  1087. save => {
  1088. save.macroDesc = {}
  1089. }
  1090. ]
  1091. function migrate(save) {
  1092. let version = save.version;
  1093. while (version != migrations.length) {
  1094. migrations[version](save);
  1095. version += 1;
  1096. }
  1097. save.version = version;
  1098. }
  1099. function load() {
  1100. try {
  1101. let storage = window.localStorage;
  1102. // migrate to everything in one
  1103. if (storage.getItem("save-version") !== null) {
  1104. const save = {};
  1105. save.ownedUpgrades = JSON.parse(storage.getItem("ownedUpgrades"));
  1106. save.resources = JSON.parse(storage.getItem("resources"));
  1107. save.belongings = JSON.parse(storage.getItem("belongings"));
  1108. save.version = 1;
  1109. storage.clear();
  1110. storage.setItem("save", JSON.stringify(save))
  1111. }
  1112. const save = JSON.parse(storage.getItem("save"));
  1113. if (save == null)
  1114. return;
  1115. migrate(save);
  1116. for (const [key, value] of Object.entries(save.ownedUpgrades)) {
  1117. ownedUpgrades[key] = value;
  1118. }
  1119. for (const [key, value] of Object.entries(save.resources)) {
  1120. resources[key] = value;
  1121. }
  1122. for (const [key, value] of Object.entries(save.belongings)) {
  1123. belongings[key] = value;
  1124. }
  1125. for (const [key, value] of Object.entries(save.stats)) {
  1126. stats[key] = value;
  1127. }
  1128. for (const [key, value] of Object.entries(save.macroDesc)) {
  1129. macroDesc[key] = value;
  1130. }
  1131. } catch (e) {
  1132. console.error(e);
  1133. clickPopup("Can't load - no access to local storage.", "info", [window.innerWidth / 2, window.innerHeight / 5]);
  1134. }
  1135. }
  1136. function reset() {
  1137. window.localStorage.clear();
  1138. }
  1139. function cycleNumbers() {
  1140. numberMode = numberModes[numberMode.next];
  1141. updateOptions();
  1142. }