├── .gitignore ├── .eslintignore ├── .prettierrc.js ├── kolmafia-polyfill.js ├── .vscode └── settings.json ├── src ├── resources │ ├── index.ts │ ├── cmc.ts │ ├── pantsgiving.ts │ ├── cleaver.ts │ ├── trainrealm.ts │ └── autumnaton.ts ├── value.ts ├── wanderer.ts ├── args.ts ├── lib.ts ├── index.ts ├── engine.ts ├── trickTreatTasks.ts ├── combat.ts ├── regularTasks.ts └── outfit.ts ├── babel.config.js ├── tsconfig.json ├── .eslintrc.js ├── package.json ├── .github └── workflows │ └── build.yml ├── documentation ├── faq.md └── scope.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | KoLmafia -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /KoLmafia/scripts/ 2 | /node_modules/ 3 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | printWidth: 100, 3 | }; 4 | -------------------------------------------------------------------------------- /kolmafia-polyfill.js: -------------------------------------------------------------------------------- 1 | const kolmafia = require("kolmafia"); 2 | export let console = { log: kolmafia.print }; 3 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.defaultFormatter": "esbenp.prettier-vscode", 3 | "editor.tabSize": 2, 4 | "editor.formatOnSave": true 5 | } 6 | -------------------------------------------------------------------------------- /src/resources/index.ts: -------------------------------------------------------------------------------- 1 | export { bestAutumnatonLocation } from "./autumnaton"; 2 | export { juneCleaverChoices, juneCleaverBonusEquip } from "./cleaver"; 3 | export { coldMedicineCabinet } from "./cmc"; 4 | export { getBestPantsgivingFood } from "./pantsgiving"; 5 | export { rotateTrainToOptimalCycle, willRotateTrainset } from "./trainrealm"; 6 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = function (api) { 2 | api.cache(true); 3 | return { 4 | presets: [ 5 | "@babel/preset-typescript", 6 | [ 7 | "@babel/preset-env", 8 | { 9 | targets: { rhino: "1.7.13" }, 10 | }, 11 | ], 12 | ], 13 | plugins: [ 14 | "@babel/plugin-proposal-class-properties", 15 | "@babel/plugin-proposal-object-rest-spread", 16 | ], 17 | }; 18 | }; 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "rootDir": "src", 4 | "noEmit": true, 5 | "allowUnreachableCode": false, 6 | "allowUnusedLabels": false, 7 | "declaration": false, 8 | "forceConsistentCasingInFileNames": true, 9 | "lib": ["esnext"], 10 | "module": "ESNext", 11 | "moduleResolution": "node", 12 | "noEmitOnError": true, 13 | "noFallthroughCasesInSwitch": true, 14 | "noImplicitReturns": true, 15 | "pretty": true, 16 | "strict": true, 17 | "target": "ESNext" 18 | }, 19 | "include": ["src/"], 20 | "isolatedModules": true /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 21 | } 22 | -------------------------------------------------------------------------------- /src/value.ts: -------------------------------------------------------------------------------- 1 | import { Item } from "kolmafia"; 2 | import { makeValue, ValueFunctions } from "garbo-lib"; 3 | 4 | import { $item } from "libram"; 5 | 6 | let _valueFunctions: ValueFunctions | undefined = undefined; 7 | function freecandyValueFunctions(): ValueFunctions { 8 | if (!_valueFunctions) { 9 | _valueFunctions = makeValue({ 10 | itemValues: new Map([[$item`fake hand`, 50000]]), 11 | }); 12 | } 13 | return _valueFunctions; 14 | } 15 | 16 | export function freecandyValue(item: Item, useHistorical = false): number { 17 | return freecandyValueFunctions().value(item, useHistorical); 18 | } 19 | 20 | export function freecandyAverageValue(...items: Item[]): number { 21 | return freecandyValueFunctions().averageValue(...items); 22 | } 23 | -------------------------------------------------------------------------------- /src/wanderer.ts: -------------------------------------------------------------------------------- 1 | import { WandererManager } from "garbo-lib"; 2 | import { getMonsters, myAdventures } from "kolmafia"; 3 | import { $location } from "libram"; 4 | import { freecandyValue } from "./value"; 5 | import args from "./args"; 6 | import { State } from "./lib"; 7 | 8 | let _wanderer: WandererManager | null = null; 9 | export function wanderer(): WandererManager { 10 | return (_wanderer ??= new WandererManager({ 11 | ascend: true, 12 | estimatedTurns: () => Math.min(myAdventures(), 5 * (args.blocks - State.blocks)), 13 | itemValue: freecandyValue, 14 | effectValue: () => 0, 15 | prioritizeCappingGuzzlr: false, 16 | plentifulMonsters: [...getMonsters($location`Trick-or-Treating`)], 17 | freeFightExtraValue: () => 0, 18 | })); 19 | } 20 | -------------------------------------------------------------------------------- /src/resources/cmc.ts: -------------------------------------------------------------------------------- 1 | import { descToItem, Item, runChoice, visitUrl } from "kolmafia"; 2 | import { freecandyValue } from "../value"; 3 | 4 | export function coldMedicineCabinet(): void { 5 | const options = visitUrl("campground.php?action=workshed"); 6 | let i = 0; 7 | let match; 8 | const regexp = /descitem\((\d+)\)/g; 9 | const itemChoices = new Map(); 10 | 11 | while ((match = regexp.exec(options)) !== null) { 12 | i++; 13 | const item = descToItem(match[1]); 14 | itemChoices.set(item, i); 15 | } 16 | 17 | const bestItem = Array.from(itemChoices.keys()) 18 | .map((i) => [i, freecandyValue(i)] as [Item, number]) 19 | .sort((a, b) => b[1] - a[1])[0][0]; 20 | const bestChoice = itemChoices.get(bestItem); 21 | if (bestChoice && bestChoice > 0) { 22 | visitUrl("campground.php?action=workshed"); 23 | runChoice(bestChoice); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/args.ts: -------------------------------------------------------------------------------- 1 | import { Args } from "grimoire-kolmafia"; 2 | import { myFamiliar } from "kolmafia"; 3 | 4 | const args = Args.create( 5 | "freecandydotexe", 6 | "A script that will not steal your identity but will do halloween for you", 7 | { 8 | blocks: Args.number({ 9 | help: "The number of blocks to run (defaults to infinite)", 10 | default: Infinity, 11 | }), 12 | treatOutfit: Args.string({ 13 | help: "The outfit to use when checking houses for trick-or-treating", 14 | setting: "freecandy_treatOutfit", 15 | default: "", 16 | }), 17 | trickOutfit: Args.string({ 18 | help: "A custom outfit to use when doing fights for trick-or-treating", 19 | setting: "freecandy_trickOutfit", 20 | default: "", 21 | }), 22 | familiar: Args.familiar({ 23 | help: "The familiar to use for combats", 24 | setting: "freecandy_familiar", 25 | default: myFamiliar(), 26 | }), 27 | }, 28 | { positionalArgs: ["blocks"] } 29 | ); 30 | 31 | export default args; 32 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | /* eslint env-node */ 2 | module.exports = { 3 | parser: "@typescript-eslint/parser", 4 | plugins: ["@typescript-eslint", "libram"], 5 | extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"], 6 | rules: { 7 | "block-scoped-var": "error", 8 | eqeqeq: "error", 9 | "no-var": "error", 10 | "prefer-const": "error", 11 | "eol-last": "error", 12 | "prefer-arrow-callback": "error", 13 | "no-trailing-spaces": "error", 14 | "prefer-template": "error", 15 | "sort-imports": [ 16 | "error", 17 | { 18 | ignoreCase: true, 19 | ignoreDeclarationSort: true, 20 | }, 21 | ], 22 | "node/no-unpublished-import": "off", 23 | "no-unused-vars": "off", 24 | "@typescript-eslint/no-unused-vars": "error", 25 | "libram/verify-constants": "error", 26 | }, 27 | parserOptions: { 28 | ecmaVersion: 2020, 29 | sourceType: "module", 30 | }, 31 | settings: { 32 | "import/parsers": { 33 | "@typescript-eslint/parser": [".ts", ".tsx"], 34 | }, 35 | "import/resolver": { 36 | typescript: { 37 | // always try to resolve types under `@types` directory even it doesn't contain any source code, like `@types/unist` 38 | alwaysTryTypes: true, 39 | }, 40 | }, 41 | }, 42 | }; 43 | -------------------------------------------------------------------------------- /src/lib.ts: -------------------------------------------------------------------------------- 1 | import { 2 | eat, 3 | fullnessLimit, 4 | myAdventures, 5 | myFullness, 6 | myHp, 7 | myMaxhp, 8 | myMaxmp, 9 | myMp, 10 | print, 11 | restoreHp, 12 | restoreMp, 13 | } from "kolmafia"; 14 | import { $item, get, have, SourceTerminal } from "libram"; 15 | import { isDarkMode } from "kolmafia"; 16 | import { StrictCombatTask } from "grimoire-kolmafia"; 17 | import { CandyStrategy } from "./combat"; 18 | 19 | export function safeRestore(): void { 20 | if (myHp() < myMaxhp() * 0.5) { 21 | restoreHp(myMaxhp() * 0.9); 22 | } 23 | const mpTarget = Math.min(myMaxmp(), 200); 24 | if (myMp() < mpTarget) { 25 | if ( 26 | (have($item`magical sausage`) || have($item`magical sausage casing`)) && 27 | get("_sausagesEaten") < 23 && 28 | myFullness() <= fullnessLimit() 29 | ) { 30 | eat($item`magical sausage`); 31 | } else restoreMp(mpTarget); 32 | } 33 | } 34 | 35 | export function printHighlight(message: string): void { 36 | const color = isDarkMode() ? "yellow" : "blue"; 37 | print(message, color); 38 | } 39 | 40 | export function printError(message: string): void { 41 | const color = "red"; 42 | print(message, color); 43 | } 44 | 45 | export type CandyTask = StrictCombatTask & { 46 | sobriety?: "sober" | "drunk"; 47 | }; 48 | 49 | export const State = { 50 | blocks: 0, 51 | }; 52 | 53 | export function shouldRedigitize(): boolean { 54 | if (!SourceTerminal.have()) return false; 55 | return ( 56 | myAdventures() * 1.1 < 57 | SourceTerminal.getDigitizeUsesRemaining() * 58 | (5 * 59 | (get("_sourceTerminalDigitizeMonsterCount") * 60 | (1 + get("_sourceTerminalDigitizeMonsterCount"))) - 61 | 3) 62 | ); 63 | } 64 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Args, getTasks, Quest } from "grimoire-kolmafia"; 2 | import args from "./args"; 3 | import { questStep, set } from "libram"; 4 | import { CandyTask, State } from "./lib"; 5 | import CandyEngine from "./engine"; 6 | import GLOBAL_TASKS from "./regularTasks"; 7 | import TRICK_TREAT_TASKS from "./trickTreatTasks"; 8 | import { myAdventures, print } from "kolmafia"; 9 | 10 | export default function main(argstring = ""): void { 11 | Args.fill(args, argstring); 12 | if (args.help) { 13 | Args.showHelp(args); 14 | return; 15 | } 16 | 17 | const nemesisStep = () => questStep("questG04Nemesis"); 18 | const doingNemesis = nemesisStep() >= 17 && nemesisStep() < 25; 19 | 20 | const noMoreAdventures = () => { 21 | if (myAdventures() <= 0) { 22 | print("Out of adventures! Stopping.", "red"); 23 | return true; 24 | } 25 | return false; 26 | }; 27 | 28 | const doneWithNemesis = () => { 29 | if (doingNemesis && nemesisStep() >= 25) { 30 | print("Fought the final nemesis wanderer! Stopping.", "red"); 31 | return true; 32 | } 33 | return false; 34 | }; 35 | 36 | const doneWithBlocks = () => { 37 | if (State.blocks >= args.blocks) { 38 | print(`Finished ${args.blocks} blocks!`, "red"); 39 | return true; 40 | } 41 | return false; 42 | }; 43 | 44 | // Allow re-running after losing a combat 45 | set("_lastCombatLost", false); 46 | 47 | const quest: Quest = { 48 | name: "hacking your system", 49 | completed: () => noMoreAdventures() || doneWithNemesis() || doneWithBlocks(), 50 | tasks: [...GLOBAL_TASKS, ...TRICK_TREAT_TASKS], 51 | }; 52 | 53 | const engine = new CandyEngine(getTasks([quest])); 54 | 55 | try { 56 | engine.run(); 57 | } finally { 58 | engine.destruct(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "freecandydotexe", 3 | "version": "1.0.0", 4 | "description": "A trick-or-treating script for the 2003 browser-based RPG Kingdom of Loathing.", 5 | "main": "KoLmafia/scripts/freecandydotexe/freecandy.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "build": "node build.mjs", 9 | "lint": "eslint src && prettier --check src", 10 | "lint:fix": "eslint src --fix && prettier --write src", 11 | "watch": "webpack --watch --progress" 12 | }, 13 | "devDependencies": { 14 | "@babel/cli": "^7.14.8", 15 | "@babel/compat-data": "^7.15.0", 16 | "@babel/core": "^7.15.0", 17 | "@babel/plugin-proposal-class-properties": "^7.18.6", 18 | "@babel/plugin-proposal-decorators": "^7.14.5", 19 | "@babel/plugin-proposal-object-rest-spread": "^7.14.7", 20 | "@babel/preset-env": "^7.15.0", 21 | "@babel/preset-typescript": "^7.15.0", 22 | "@typescript-eslint/eslint-plugin": "^5.5.0", 23 | "@typescript-eslint/parser": "^5.5.0", 24 | "babel-loader": "^8.2.2", 25 | "esbuild": "0.17.0", 26 | "esbuild-plugin-babel": "0.2.3", 27 | "eslint": "8.56.0", 28 | "eslint-config-prettier": "^8.3.0", 29 | "eslint-plugin-libram": "^0.4.5", 30 | "prettier": "^2.3.1", 31 | "typescript": "^4.5.2" 32 | }, 33 | "dependencies": { 34 | "core-js": "^3.16.4", 35 | "garbo-lib": "^1.0.0", 36 | "grimoire-kolmafia": "^0.3.23", 37 | "kolmafia": "^5.27651.0", 38 | "libram": "^0.8.27" 39 | }, 40 | "author": "loathers", 41 | "license": "ISC", 42 | "repository": { 43 | "type": "git", 44 | "url": "git+https://github.com/loathers/freecandydotexe.git" 45 | }, 46 | "keywords": [ 47 | "KoLMafia", 48 | "JS", 49 | "TS" 50 | ], 51 | "bugs": { 52 | "url": "https://github.com/loathers/freecandydotexe/issues" 53 | }, 54 | "homepage": "https://github.com/loathers/freecandydotexe#readme" 55 | } 56 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build & Lint 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | workflow_dispatch: 9 | 10 | env: 11 | node-version: "18" 12 | path: "KoLmafia" # The directory where your assets are generated, should match build.mjs 13 | 14 | jobs: 15 | test: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v3 19 | 20 | - name: Use Node.js ${{ env.node-version }} 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: ${{ env.node-version }} 24 | 25 | - name: Install Dependencies 26 | run: yarn install --immutable 27 | 28 | - name: Build 29 | run: yarn run build 30 | 31 | lint: 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v3 35 | 36 | - name: Use Node.js ${{ env.node-version }} 37 | uses: actions/setup-node@v3 38 | with: 39 | node-version: ${{ env.node-version }} 40 | 41 | - name: Install Dependencies 42 | run: yarn install --immutable 43 | 44 | - name: ESLint & Prettier 45 | run: yarn run lint 46 | 47 | push: 48 | runs-on: ubuntu-latest 49 | needs: [test, lint] 50 | if: github.ref == 'refs/heads/main' 51 | steps: 52 | - uses: actions/checkout@v3 53 | 54 | - name: Use Node.js ${{ env.node-version }} 55 | uses: actions/setup-node@v3 56 | with: 57 | node-version: ${{ env.node-version }} 58 | 59 | - name: Install Dependencies 60 | run: yarn install --immutable 61 | 62 | - name: Build 63 | run: yarn run build 64 | 65 | - name: Push to Release 66 | uses: s0/git-publish-subdir-action@develop 67 | env: 68 | REPO: self 69 | BRANCH: release 70 | FOLDER: ${{ env.path }} 71 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 72 | MESSAGE: "Build: ({sha}) {msg}" 73 | SKIP_EMPTY_COMMITS: true 74 | -------------------------------------------------------------------------------- /src/engine.ts: -------------------------------------------------------------------------------- 1 | import { Engine, Outfit } from "grimoire-kolmafia"; 2 | import { 3 | equip, 4 | inebrietyLimit, 5 | itemAmount, 6 | myInebriety, 7 | myMaxhp, 8 | myMaxmp, 9 | restoreHp, 10 | restoreMp, 11 | useFamiliar, 12 | visitUrl, 13 | xpath, 14 | } from "kolmafia"; 15 | import { CandyTask, printHighlight, State } from "./lib"; 16 | import { $familiar, $item, clamp, Session } from "libram"; 17 | import args from "./args"; 18 | 19 | export default class CandyEngine extends Engine { 20 | session: Session; 21 | aaBossFlag: number; 22 | 23 | constructor(tasks: CandyTask[]) { 24 | super(tasks); 25 | this.aaBossFlag = 26 | xpath( 27 | visitUrl("account.php?tab=combat"), 28 | `//*[@id="opt_flag_aabosses"]/label/input[@type='checkbox']@checked` 29 | )[0] === "checked" 30 | ? 1 31 | : 0; 32 | this.session = Session.current(); 33 | } 34 | 35 | destruct(): void { 36 | super.destruct(); 37 | visitUrl( 38 | `account.php?actions[]=flag_aabosses&flag_aabosses=${this.aaBossFlag}&action=Update`, 39 | true 40 | ); 41 | useFamiliar(args.familiar); 42 | 43 | printHighlight(`freecandy has run ${State.blocks} blocks, and produced the following items:`); 44 | for (const [item, quantity] of Session.current().diff(this.session).items) { 45 | printHighlight(` ${item}: ${quantity}`); 46 | } 47 | } 48 | 49 | available(task: CandyTask): boolean { 50 | const isDrunk = myInebriety() > inebrietyLimit(); 51 | const { sobriety } = task; 52 | if (isDrunk && sobriety === "sober") return false; 53 | if (!isDrunk && sobriety === "drunk") return false; 54 | return super.available(task); 55 | } 56 | 57 | dress(task: CandyTask, outfit: Outfit): void { 58 | super.dress(task, outfit); 59 | 60 | if (itemAmount($item`tiny stillsuit`)) { 61 | equip($familiar`Mosquito`, $item`tiny stillsuit`); 62 | } 63 | } 64 | 65 | prepare(task: CandyTask): void { 66 | super.prepare(task); 67 | 68 | if ("combat" in task) { 69 | const hpTarget = clamp(0.4 * myMaxhp(), 200, 2000); 70 | restoreHp(hpTarget); 71 | const mpTarget = Math.min(150, myMaxmp()); 72 | restoreMp(mpTarget); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/resources/pantsgiving.ts: -------------------------------------------------------------------------------- 1 | import { abort, isAccessible, Item, mallPrice, myLevel, runChoice, visitUrl } from "kolmafia"; 2 | import { $coinmaster, $item, get, have, maxBy } from "libram"; 3 | import { freecandyValue } from "../value"; 4 | 5 | type PantsgivingFood = { 6 | food: Item; 7 | costOverride?: () => number; 8 | canGet: () => boolean; 9 | }; 10 | const pantsgivingFoods: PantsgivingFood[] = [ 11 | { 12 | food: $item`glass of raw eggs`, 13 | costOverride: () => 0, 14 | canGet: () => have($item`glass of raw eggs`), 15 | }, 16 | { 17 | food: $item`Affirmation Cookie`, 18 | canGet: () => true, 19 | }, 20 | { 21 | food: $item`disco biscuit`, 22 | canGet: () => true, 23 | }, 24 | { 25 | food: $item`ice rice`, 26 | canGet: () => true, 27 | }, 28 | { 29 | food: $item`Tea, Earl Grey, Hot`, 30 | canGet: () => true, 31 | }, 32 | { 33 | food: $item`Dreadsylvanian stew`, 34 | costOverride: () => 35 | (10 / 20) * 36 | Math.max( 37 | freecandyValue($item`electric Kool-Aid`), 38 | freecandyValue($item`bottle of Bloodweiser`) 39 | ), 40 | canGet: () => 41 | have($item`Freddy Kruegerand`, 10) && 42 | isAccessible($coinmaster`The Terrified Eagle Inn`) && 43 | myLevel() >= 20, 44 | }, 45 | { 46 | food: $item`FantasyRealm turkey leg`, 47 | costOverride: () => 0, 48 | canGet: () => { 49 | if (!have($item`Rubee™`, 100)) return false; 50 | if (!get("_frToday") && !get("frAlways")) return false; 51 | if (have($item`FantasyRealm G. E. M.`)) return true; 52 | visitUrl("place.php?whichplace=realm_fantasy&action=fr_initcenter"); 53 | runChoice(1); 54 | return have($item`FantasyRealm G. E. M.`); 55 | }, 56 | }, 57 | ]; 58 | 59 | let bestPantsgivingFood: PantsgivingFood; 60 | export function getBestPantsgivingFood(): PantsgivingFood { 61 | if (!bestPantsgivingFood) { 62 | const options = pantsgivingFoods.filter(({ canGet }) => canGet()); 63 | if (!options.length) abort("No available pantsgiving foods--this should never happen!"); 64 | bestPantsgivingFood = maxBy( 65 | options, 66 | ({ food, costOverride }) => costOverride?.() ?? mallPrice(food), 67 | true 68 | ); 69 | } 70 | 71 | return bestPantsgivingFood; 72 | } 73 | -------------------------------------------------------------------------------- /documentation/faq.md: -------------------------------------------------------------------------------- 1 | # Free-quently Asked Questions 2 | 3 | ### Migrating from SVN to Git 4 | 5 | If you are having issues running the script, we would highly recommend converting from previous SVN installs to Git; having two versions of the same script is unsupported behavior that often leads to scope issues and areas where Mafia runs the older version of the script. Mafia support has been implemented for git in recent revisions, so freecandy users should update their mafia, remove the old SVN repo and convert to git. 6 | 7 | ``` 8 | svn delete Loathing-Associates-Scripting-Society-freecandydotexe-branches-release 9 | ``` 10 | 11 | Then install freecandy.exe as normal, in the core readme. 12 | 13 | ### Does freecandy.exe do X 14 | 15 | Maybe! We have a [whole other page](documentation/scope.md) dedicated to answering this, and the related question "should freecandy.exe do X." 16 | 17 | ### Why does freecandy.exe not support \[recent iotm\] when \[other, possibly related script\] does? 18 | 19 | There are two possible answers to this question, where "two" is actually however many things I end up writing here. The first is that we cannot frequently test freecandy.exe, because it can only be run on hallowe'en, so often times there will be experimental support for \[recent iotm\] that is not yet available on the release branch. The second is that a lot of things aren't actually particularly relevant to freecandy's stated goals; at the time of this writing, the Cursed Monkey's Paw is a fantastic iotm for meat farmers and ascenders, but does nothing for freecandy and its stated goals. The third (apparently two is three today) is that each person who works on freecandy has jobs, lovers, hopes, dreams, and hobbies, and writing code takes time, energy, focus, grit, and blood. That being said: PRs are welcome! 20 | 21 | ### Why is freecandy so finely honed for stasis & riftlet-like familiars, but not for others? 22 | 23 | Stasis and riftlet-like familiars are the only ones that require any particular special handling. The latter in particular involves doing a lot of weird math to optimize how much to value weight in constructing outfits. There are unfortunately few ways of eking value out of trick-or-treating monsters--they are free fights with low meat drop and inexpensive drops--so when we run other familiars (such as the Snapper, which is great!) we don't have a great way to fill up our outfit. Sorry! 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | greenbox logo 2 | 3 | **freecandy.exe** is a script meant to farm the recurring [Hallowe'en](https://kol.coldfront.net/thekolwiki/index.php/Halloween) holiday within the [Kingdom of Loathing](https://www.kingdomofloathing.com/). On Hallowe'en, players can derive high profits by visiting the infinitely recurring trick-or-treating blockss; this script aims to run your treat-filled Hallowe'en turns in the quickest way possible. 4 | 5 | To install, run the following command on an up-to-date KolMafia version: 6 | 7 | ``` 8 | git checkout loathers/freecandydotexe release 9 | ``` 10 | 11 | ## Running freecandy 12 | 13 | In its simplest form, running freecandy just requires running the following command in the mafia GCLI: 14 | 15 | ``` 16 | freecandy 10 17 | ``` 18 | 19 | Where "10" would be replaced by an integer telling the script how many blocks you would like to run while trick-or-treating. If you do not include a number after `freecandy`, the script will just run until you're out of adventures. This script will use the familiar you have equipped as your primary fight familiar; pick the familiar you want freecandy to use prior to the invocation of the script. 20 | 21 | ``` 22 | freecandy help 23 | ``` 24 | 25 | Will list additional options that you may run, the most notable of which is the `treatOutfit` argument (equivalent to the `freecandy_treatOutfit` mafia preference), which will tell freecandy to use a particular outfit to harvest candies from hallowe'en houses. If you leave this property blank (and fail to pass it as an argument), freecandy will make this decision on its own, but you are unlikely to like that decision because it will use mall data to decide, and many candies are laying fallow in the mall at high prices with low sale volume. Be warned! 26 | 27 | ## Documentation 28 | 29 | One important alert for all interested users: 30 | 31 | :warning: **FREECANDY.EXE WILL NOT DIET FOR YOU; IT WILL JUST USE ADVENTURES. FILL YOUR ORGANS!** :warning: 32 | 33 | For more details beyond this blisteringly important note: 34 | 35 | - For more information about what freecandy.exe does and does not do, [click here](documentation/scope.md). 36 | - To peruse frequently asked questions about freecandy, [click here](documentation/faq.md). 37 | 38 | To report bugs, please post issues on this GitHub repository. 39 | -------------------------------------------------------------------------------- /src/resources/cleaver.ts: -------------------------------------------------------------------------------- 1 | import { Item, myAdventures } from "kolmafia"; 2 | import { $item, get, JuneCleaver, maxBy, sum } from "libram"; 3 | import { freecandyValue } from "../value"; 4 | 5 | const juneCleaverChoiceValues = { 6 | 1467: { 7 | 1: 0, 8 | 2: 0, 9 | 3: 5 * get("valueOfAdventure"), 10 | }, 11 | 1468: { 1: 0, 2: 5, 3: 0 }, 12 | 1469: { 1: 0, 2: $item`Dad's brandy`, 3: 1500 }, 13 | 1470: { 1: 0, 2: $item`teacher's pen`, 3: 0 }, 14 | 1471: { 1: $item`savings bond`, 2: 250, 3: 0 }, 15 | 1472: { 16 | 1: $item`trampled ticket stub`, 17 | 2: $item`fire-roasted lake trout`, 18 | 3: 0, 19 | }, 20 | 1473: { 1: $item`gob of wet hair`, 2: 0, 3: 0 }, 21 | 1474: { 1: 0, 2: $item`guilty sprout`, 3: 0 }, 22 | 1475: { 1: $item`mother's necklace`, 2: 0, 3: 0 }, 23 | } as const; 24 | 25 | function valueJuneCleaverOption(result: Item | number): number { 26 | return result instanceof Item ? freecandyValue(result) : result; 27 | } 28 | 29 | function bestJuneCleaverOption(id: typeof JuneCleaver.choices[number]): 1 | 2 | 3 { 30 | const options = [1, 2, 3] as const; 31 | return maxBy(options, (option) => valueJuneCleaverOption(juneCleaverChoiceValues[id][option])); 32 | } 33 | 34 | let juneCleaverSkipChoices: typeof JuneCleaver.choices[number][] | null; 35 | 36 | function getJuneCleaverskipChoices(): typeof JuneCleaver.choices[number][] { 37 | if (JuneCleaver.skipsRemaining() > 0) { 38 | if (!juneCleaverSkipChoices) { 39 | juneCleaverSkipChoices = [...JuneCleaver.choices] 40 | .sort( 41 | (a, b) => 42 | valueJuneCleaverOption(juneCleaverChoiceValues[a][bestJuneCleaverOption(a)]) - 43 | valueJuneCleaverOption(juneCleaverChoiceValues[b][bestJuneCleaverOption(b)]) 44 | ) 45 | .splice(0, 3); 46 | } 47 | return [...juneCleaverSkipChoices]; 48 | } 49 | return []; 50 | } 51 | 52 | export const juneCleaverChoices = (): { [x in number]: number } => 53 | Object.fromEntries( 54 | JuneCleaver.choices.map((choice) => [ 55 | choice, 56 | getJuneCleaverskipChoices().includes(choice) ? 4 : bestJuneCleaverOption(choice), 57 | ]) 58 | ); 59 | 60 | let choiceAdventuresValue: number; 61 | export function juneCleaverBonusEquip(): Map { 62 | if (!JuneCleaver.have() || myAdventures() < get("_juneCleaverFightsLeft")) return new Map(); 63 | 64 | choiceAdventuresValue ??= 65 | sum([...JuneCleaver.choices], (choice) => 66 | valueJuneCleaverOption(juneCleaverChoiceValues[choice][bestJuneCleaverOption(choice)]) 67 | ) / JuneCleaver.choices.length; 68 | 69 | return new Map([[JuneCleaver.cleaver, choiceAdventuresValue / JuneCleaver.getInterval()]]); 70 | } 71 | -------------------------------------------------------------------------------- /src/trickTreatTasks.ts: -------------------------------------------------------------------------------- 1 | import { 2 | abort, 3 | handlingChoice, 4 | inMultiFight, 5 | lastChoice, 6 | myAdventures, 7 | runChoice, 8 | runCombat, 9 | visitUrl, 10 | } from "kolmafia"; 11 | import { treatOutfit, trickOutfit } from "./outfit"; 12 | import { CandyTask, State } from "./lib"; 13 | import { CandyStrategy } from "./combat"; 14 | const HOUSE_NUMBERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; 15 | 16 | let blockHtml = ""; 17 | let treated = false; 18 | let tricked: number[] = []; 19 | 20 | function getBlockHtml(): string { 21 | blockHtml ||= visitUrl("place.php?whichplace=town&action=town_trickortreat"); 22 | return blockHtml; 23 | } 24 | 25 | function refreshBlock(): void { 26 | blockHtml = visitUrl("place.php?whichplace=town&action=town_trickortreat"); 27 | } 28 | 29 | function resetBlock(): void { 30 | refreshBlock(); 31 | treated = false; 32 | tricked = []; 33 | State.blocks++; 34 | } 35 | 36 | function ensureInHalloween(): void { 37 | const onPage = handlingChoice() && lastChoice() === 804; 38 | if (!onPage) refreshBlock(); 39 | } 40 | 41 | const TRICK_TREAT_TASKS: CandyTask[] = [ 42 | { 43 | name: "Treat", 44 | ready: () => !treated, 45 | completed: () => !getBlockHtml().match(/whichhouse=\d*>[^>]*?house_l/), 46 | outfit: treatOutfit, 47 | prepare: ensureInHalloween, 48 | do: (): void => { 49 | // We do all treat houses in a row as one task for speed reasons 50 | for (const house of HOUSE_NUMBERS) { 51 | if (getBlockHtml().match(RegExp(`whichhouse=${house}>[^>]*?house_l`))) { 52 | tricked.push(house); 53 | visitUrl(`choice.php?whichchoice=804&option=3&whichhouse=${house}&pwd`); 54 | } else if (getBlockHtml().match(RegExp(`whichhouse=${house}>[^>]*?starhouse`))) { 55 | tricked.push(house); 56 | visitUrl(`choice.php?whichchoice=804&option=3&whichhouse=${house}&pwd`); 57 | runChoice(2); 58 | refreshBlock(); 59 | } 60 | } 61 | treated = true; 62 | }, 63 | }, 64 | { 65 | name: "Trick", 66 | ready: () => tricked.length < HOUSE_NUMBERS.length, 67 | completed: () => !getBlockHtml().match(/whichhouse=\d*>[^>]*?house_d/), 68 | prepare: ensureInHalloween, 69 | do: (): void => { 70 | // We return after doing one combat because combats change character-state enough we want to go through our non-hallowe'en tasks agaijn 71 | for (const house of HOUSE_NUMBERS) { 72 | if (tricked.includes(house)) continue; 73 | tricked.push(house); 74 | if (getBlockHtml().match(RegExp(`whichhouse=${house}>[^>]*?house_d`))) { 75 | visitUrl(`choice.php?whichchoice=804&option=3&whichhouse=${house}&pwd`); 76 | do { 77 | runCombat(); 78 | } while (inMultiFight()); 79 | return; 80 | } 81 | } 82 | if (tricked.length < HOUSE_NUMBERS.length) { 83 | abort("We thought there were unvisited trickable houses left, but alas! there are not!"); 84 | } 85 | }, 86 | outfit: trickOutfit, 87 | combat: new CandyStrategy(), 88 | }, 89 | { 90 | name: "Reset Block", 91 | ready: () => myAdventures() >= 5, 92 | completed: (): boolean => { 93 | refreshBlock(); 94 | return getBlockHtml().includes("whichhouse="); 95 | }, 96 | prepare: ensureInHalloween, 97 | do: (): void => { 98 | visitUrl("choice.php?whichchoice=804&pwd&option=1"); 99 | resetBlock(); 100 | if (!getBlockHtml().includes("whichhouse=")) 101 | abort("Something went awry when finding a new block!"); 102 | }, 103 | }, 104 | ]; 105 | 106 | export default TRICK_TREAT_TASKS; 107 | -------------------------------------------------------------------------------- /src/combat.ts: -------------------------------------------------------------------------------- 1 | import { 2 | $familiars, 3 | $item, 4 | $items, 5 | $location, 6 | $monster, 7 | $skill, 8 | $skills, 9 | Delayed, 10 | get, 11 | have, 12 | SourceTerminal, 13 | StrictMacro, 14 | } from "libram"; 15 | import { getMonsters, Item, Skill } from "kolmafia"; 16 | import { CombatStrategy } from "grimoire-kolmafia"; 17 | import { shouldRedigitize } from "./lib"; 18 | import args from "./args"; 19 | 20 | export class Macro extends StrictMacro { 21 | tryHaveSkill(skill: Skill | null): Macro { 22 | if (!skill) return this; 23 | return this.externalIf(have(skill), Macro.trySkill(skill)); 24 | } 25 | 26 | static tryHaveSkill(skill: Skill | null): Macro { 27 | return new Macro().tryHaveSkill(skill); 28 | } 29 | 30 | tryHaveItem(item: Item | null): Macro { 31 | if (!item) return this; 32 | return this.externalIf(have(item), Macro.tryItem(item)); 33 | } 34 | 35 | static tryHaveItem(item: Item | null): Macro { 36 | return new Macro().tryHaveItem(item); 37 | } 38 | 39 | try(actions: (Item | Skill)[]): Macro { 40 | return this.step( 41 | ...actions.map((action) => { 42 | if (action instanceof Item) { 43 | return Macro.tryHaveItem(action); 44 | } else return Macro.tryHaveSkill(action); 45 | }) 46 | ); 47 | } 48 | 49 | static try(actions: (Item | Skill)[]): Macro { 50 | return new Macro().try(actions); 51 | } 52 | 53 | stasisItem(): Macro { 54 | const spammableItem = 55 | $items`dictionary, facsimile dictionary, spices`.find((item) => have(item)) ?? 56 | $item`seal tooth`; 57 | return Macro.item(spammableItem); 58 | } 59 | 60 | static stasisItem(): Macro { 61 | return new Macro().stasisItem(); 62 | } 63 | 64 | kill(): Macro { 65 | return this.if_( 66 | "monstername *ghost", 67 | Macro.externalIf( 68 | have($skill`Silent Treatment`), 69 | Macro.skill($skill`Silent Treatment`) 70 | .attack() 71 | .repeat() 72 | ) 73 | .skill($skill`Saucegeyser`) 74 | .repeat() 75 | ) 76 | .attack() 77 | .repeat(); 78 | } 79 | 80 | static kill(): Macro { 81 | return new Macro().kill(); 82 | } 83 | 84 | stasis(): Macro { 85 | return this.try([ 86 | $skill`Curse of Weaksauce`, 87 | $skill`Micrometeorite`, 88 | $skill`Shadow Noodles`, 89 | $skill`Shell Up`, 90 | $item`Time-Spinner`, 91 | $item`little red book`, 92 | $item`nasty-smelling moss`, 93 | $item`HOA citation pad`, 94 | $item`Great Wolf's lice`, 95 | $item`Mayor Ghost's scissors`, 96 | $item`Rain-Doh indigo cup`, 97 | $item`porquoise-handled sixgun`, 98 | $skill`Summon Love Gnats`, 99 | $skill`Bowl Straight Up`, 100 | $skill`Sing Along`, 101 | ]) 102 | .externalIf(SourceTerminal.isCurrentSkill($skill`Extract`), Macro.skill($skill`Extract`)) 103 | .while_("!pastround 11", Macro.stasisItem()); 104 | } 105 | 106 | static stasis(): Macro { 107 | return new Macro().stasis(); 108 | } 109 | 110 | redigitize(): Macro { 111 | return this.externalIf(shouldRedigitize(), Macro.trySkill($skill`Digitize`)); 112 | } 113 | 114 | static redigitize(): Macro { 115 | return new Macro().redigitize(); 116 | } 117 | 118 | default(): Macro { 119 | return this.if_($monster`All-Hallow's Steve`, Macro.abort()) 120 | .externalIf( 121 | $familiars`Stocking Mimic, Ninja Pirate Zombie Robot, Comma Chameleon, Feather Boa Constrictor, Cocoabo`.includes( 122 | args.familiar 123 | ), 124 | Macro.stasis(), 125 | Macro.try([ 126 | ...$skills`Curse of Weaksauce, Micrometeorite, Sing Along, Bowl Straight Up`, 127 | ...$items`porquoise-handled sixgun, Rain-Doh indigo cup`, 128 | ]) 129 | .externalIf(SourceTerminal.isCurrentSkill($skill`Extract`), Macro.skill($skill`Extract`)) 130 | .externalIf( 131 | have($skill`Just the Facts`) && get("_circadianRhythmsRecalled"), 132 | Macro.if_( 133 | getMonsters($location`Trick-or-Treating`), 134 | Macro.trySkill($skill`Recall Facts: %phylum Circadian Rhythms`) 135 | ) 136 | ) 137 | ) 138 | .kill(); 139 | } 140 | 141 | static default(): Macro { 142 | return new Macro().default(); 143 | } 144 | } 145 | 146 | export class CandyStrategy extends CombatStrategy { 147 | constructor(macro: Delayed = () => Macro.default()) { 148 | super(); 149 | this.autoattack(macro).macro(macro); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/resources/trainrealm.ts: -------------------------------------------------------------------------------- 1 | import { $item, $items, arrayEquals, get, maxBy, sum, TrainSet } from "libram"; 2 | import { freecandyAverageValue } from "../value"; 3 | 4 | const TRAIN_CANDIES = [ 5 | $item`cotton candy bale`, 6 | $item`cotton candy cone`, 7 | $item`cotton candy pillow`, 8 | $item`cotton candy pinch`, 9 | $item`cotton candy plug`, 10 | $item`cotton candy skoshe`, 11 | $item`cotton candy smidgen`, 12 | $item`crazy little Turkish delight`, 13 | $item`Daffy Taffy`, 14 | $item`Elvish delight`, 15 | $item`explosion-flavored chewing gum`, 16 | $item`green candy heart`, 17 | $item`green gummi ingot`, 18 | $item`gummi canary`, 19 | $item`gummi salamander`, 20 | $item`gummi snake`, 21 | $item`Gummi-Gnauga`, 22 | $item`honey stick`, 23 | $item`honey-dipped locust`, 24 | $item`jabañero-flavored chewing gum`, 25 | $item`lavender candy heart`, 26 | $item`lime-and-chile-flavored chewing gum`, 27 | $item`marzipan skull`, 28 | $item`Mr. Mediocrebar`, 29 | $item`orange candy heart`, 30 | $item`pack of chewing gum`, 31 | $item`pickle-flavored chewing gum`, 32 | $item`Piddles`, 33 | $item`pile of candy`, 34 | $item`pink candy heart`, 35 | $item`pixellated candy heart`, 36 | $item`Polka Pop`, 37 | $item`red gummi ingot`, 38 | $item`Rock Pops`, 39 | $item`Senior Mints`, 40 | $item`Steal This Candy`, 41 | $item`Sugar Cog`, 42 | $item`sugar shard`, 43 | $item`tamarind-flavored chewing gum`, 44 | $item`Tasty Fun Good rice candy`, 45 | $item`white candy heart`, 46 | $item`white chocolate chips`, 47 | $item`Wint-O-Fresh mint`, 48 | $item`yellow candy heart`, 49 | $item`yellow gummi ingot`, 50 | $item`Yummy Tummy bean`, 51 | ]; 52 | 53 | let _candyFactoryValue: number; 54 | function candyFactoryValue(): number { 55 | return (_candyFactoryValue ??= freecandyAverageValue(...TRAIN_CANDIES)); 56 | } 57 | 58 | const GOOD_TRAIN_STATIONS = [ 59 | { piece: TrainSet.Station.GAIN_MEAT, value: () => 900 }, 60 | { 61 | // Some day this'll be better 62 | piece: TrainSet.Station.TRACKSIDE_DINER, 63 | value: () => freecandyAverageValue(...$items`bowl of cottage cheese, hot buttered roll, toast`), 64 | }, 65 | { piece: TrainSet.Station.CANDY_FACTORY, value: candyFactoryValue }, 66 | { 67 | piece: TrainSet.Station.GRAIN_SILO, 68 | value: () => 69 | 2 * 70 | freecandyAverageValue( 71 | ...$items`bottle of gin, bottle of vodka, bottle of whiskey, bottle of rum, bottle of tequila, boxed wine` 72 | ), 73 | }, 74 | { 75 | piece: TrainSet.Station.ORE_HOPPER, 76 | value: () => 77 | freecandyAverageValue( 78 | ...$items`linoleum ore, asbestos ore, chrome ore, teflon ore, vinyl ore, velcro ore, bubblewrap ore, cardboard ore, styrofoam ore` 79 | ), 80 | }, 81 | ]; 82 | 83 | let trainCycle: TrainSet.Cycle; 84 | function getBestCycle(): TrainSet.Cycle { 85 | if (!trainCycle) { 86 | const cycle = [ 87 | TrainSet.Station.COAL_HOPPER, 88 | ...GOOD_TRAIN_STATIONS.sort(({ value: a }, { value: b }) => b() - a()).map( 89 | ({ piece }) => piece 90 | ), 91 | TrainSet.Station.TOWER_FIZZY, 92 | TrainSet.Station.VIEWING_PLATFORM, 93 | ] as TrainSet.Cycle; 94 | trainCycle = cycle; 95 | } 96 | return [...trainCycle]; 97 | } 98 | 99 | function valueStation(station: TrainSet.Station): number { 100 | if (station === TrainSet.Station.COAL_HOPPER) { 101 | return valueStation(getBestCycle()[1]); 102 | } 103 | return GOOD_TRAIN_STATIONS.find(({ piece }) => piece === station)?.value() ?? 0; 104 | } 105 | 106 | function valueOffset(offset: number): number { 107 | const firstFortyTurns = 5 * sum(getBestCycle(), valueStation); 108 | const extraTurns = sum(getBestCycle().slice(0, offset - 1), valueStation); 109 | return (firstFortyTurns + extraTurns) / (40 + offset); 110 | } 111 | 112 | let bestOffset: number | null = null; 113 | function getBestOffset(): number { 114 | return (bestOffset ??= maxBy([2, 3, 4, 5, 6, 7, 8], valueOffset)); 115 | } 116 | 117 | function getPrioritizedStations(): TrainSet.Station[] { 118 | return getBestCycle().slice(0, getBestOffset() - 1); 119 | } 120 | 121 | function getRotatedCycle(): TrainSet.Cycle { 122 | const offset = get("trainsetPosition") % 8; 123 | const newPieces: TrainSet.Station[] = []; 124 | const defaultPieces = getBestCycle(); 125 | for (let i = 0; i < 8; i++) { 126 | const newPos = (i + offset) % 8; 127 | newPieces[newPos] = defaultPieces[i]; 128 | } 129 | return newPieces as TrainSet.Cycle; 130 | } 131 | 132 | export function rotateTrainToOptimalCycle(): boolean { 133 | return TrainSet.setConfiguration(getRotatedCycle()); 134 | } 135 | 136 | export function willRotateTrainset(): boolean { 137 | return ( 138 | TrainSet.canConfigure() && 139 | (!get("trainsetConfiguration") || 140 | (!getPrioritizedStations().includes(TrainSet.next()) && 141 | !arrayEquals(getRotatedCycle(), TrainSet.cycle()))) 142 | ); 143 | } 144 | -------------------------------------------------------------------------------- /documentation/scope.md: -------------------------------------------------------------------------------- 1 | # Outlining the Scope of freecandy.exe 2 | 3 | In this page, we're going to outline exactly what freecandy is meant to do. This is an evolving document that will ideally be updated as new features are implemented within freecandy. However, it is worth noting that while the developers (the Loathers admin team & the script's captain, [@horrible-little-slime]) are updating freecandy to provide light support to relevant new IOTMs, there is minimal appetite to considerably rework or revamp this script. 4 | 5 | As such, most large-scale changes that would impact this overall scope document would require pull requests from interested parties, likely folks outside of the core repository developers. Or, as the cool kids might say: we welcome PRs that would change this scope (so long as they do not impact the maintainability of this script), but it is very unlikely for scope change to come from us. 6 | 7 | With this addressed, let's outline things that this script does and does not do, starting with the things it does not do, as these are the things most often ignored by users who want to register bug reports. 8 | 9 | ## Out-of-Scope 10 | 11 | - **freecandy.exe will not steal your identity.** 12 | - **freecandy.exe will not fill your organs (stomach/liver/spleen).** 13 | - At least, it won't do it well. 14 | - There is one small and minor exception to this rule -- if you have pantsgiving, freecandy will wear it as part of its outfit optimizer and consume the new incremental fullness as it gets added to your stomach. 15 | - **freecandy.exe will not set up digitized monsters for you.** 16 | - As noted below, the script -will- fight them, if you've already digitized. But it isn't going to set them up for you. 17 | - **freecandy.exe will not complete the nemesis quest.** 18 | - As noted below, the script will stop if you reach the final wandering hitman, allowing you to manually progress the quest. But it will not do this for you. 19 | - **freecandy.exe will not take items from the clan stash for you.** 20 | - **freecandy.exe will not do beginning-of-the-day free fights, like garbage-collector does.** 21 | - **freecandy.com will not use a KoL Con 13 snowglobe.** 22 | - If you can think of a reasonable value to assign to it or the Can of Mixed Everything, please let us know! 23 | - **freecandy.exe will not cast or recast buffs.** 24 | - We would recommend you utilize mafia's [mood architecture](https://wiki.kolmafia.us/index.php/Mood) if you would like mafia to recast buffs while using freecandy. 25 | - **freecandy.exe will not work at all if you leave your items in Hagnks.** 26 | - **freecandy.exe will not work well (or possibly at all) if mafia has an incorrect image of your character-state, which can be caused by playing KoL outside of mafia, or by playing KoL in a different mafia installation.** 27 | 28 | ## In-Scope 29 | 30 | - **freecandy.exe will pick an outfit for you.** 31 | - When choosing this outfit, freecandy will defer to any outfit that you have personally selected through the use of the `freecandy_treatOutfit` preference. Simply put an outfit name in there to force this script to use that as part of your trick or treating outfit, provided you have the stats to use it. 32 | - It is important to note that this outfit **will be optimized** -- freecandy has an internal optimization engine that will attempt to maximize your profits in the fights it is allowed to do, and will select an equippable outfit accordingly. If you are using a stasis-like familiar (like the Stocking Mimic) or a turns-generating familiar (like the Reagnimatied Gnome), the outfit constructor will take that into account. 33 | - **freecandy.exe will use whatever familiar you invoke the script with (or whichever familiar is passed using the `familiar` argument) as your core "fights" familiar.** 34 | - If you have a trick-or-treating tot, freecandy will use the tot to double your candy gains from the noncombats, but will use whatever familiar you enter the script with on all of the weird free combats from each block. 35 | - **freecandy.exe will fight wanderers for you.** 36 | - This includes (but is not limited to): digitized wanderers, guaranteed kramcos, initial nemesis quest wanderers, parka YRs, and voting monsters. It will also re-digitize your digitized monster at appropriate intervals to ensure you max out your digitized wanderers. 37 | - It will also lovingly place each wanderer into a zone designed to maximize profit. If you have no such zone, it'll less-lovingly place them in the Haunted Kitchen. 38 | - **freecandy.exe will use one of the one-item outfits for its halloween combats.** 39 | - These include: invisible bag, witch hat, beholed bedsheet, wolfman mask, pumpkinhead mask, and the mummy costume. We would highly recommend purchasing one of these before running freecandy, although the script will try to equip you with the lowest-pain possible outfit you own instead, if needed. 40 | - It is willing to use certain two-item outfits, but it prefers not to. Because two items are worse than one. 41 | - **freecandy.exe will track its gains, and report them to you at the end of the day.** 42 | 43 | ## TL;DR 44 | 45 | This is not very long! Not reading it is the work of a madman, and failing to read this is grounds for me calling you a "silly goose" and ignoring you if you report a bug or issue. That being said, there is one big punchy summary I would like to leave you with: **freecandy.exe is designed to do run blocks and do tasks that a reasonable person would want to complete while running blocks; it is not designed to do tasks that might occur _before_ or _after_ running blocks**. That is the great running theme of this page; I wrote freecandy because I was tired of running tricktreat.ash (a great and venerable script to which freecandy owes a debt of blood) and constantly interrupting it to fight digitized monsters, or guaranteed kramcos, or a third example. It is not intended to be an all-day script for hallowe'en. 46 | -------------------------------------------------------------------------------- /src/resources/autumnaton.ts: -------------------------------------------------------------------------------- 1 | import { 2 | appearanceRates, 3 | availableAmount, 4 | getLocationMonsters, 5 | itemDropsArray, 6 | Location, 7 | myAdventures, 8 | toMonster, 9 | } from "kolmafia"; 10 | import { $items, AutumnAton, flat, get, maxBy, sum } from "libram"; 11 | import { freecandyAverageValue, freecandyValue } from "../value"; 12 | 13 | export function bestAutumnatonLocation(locations: Location[]): Location { 14 | return maxBy(mostValuableUpgrade(locations), averageAutumnatonValue); 15 | } 16 | 17 | function averageAutumnatonValue( 18 | location: Location, 19 | acuityOverride?: number, 20 | slotOverride?: number 21 | ): number { 22 | const badAttributes = ["LUCKY", "ULTRARARE", "BOSS"]; 23 | const rates = appearanceRates(location); 24 | const monsters = Object.keys(getLocationMonsters(location)) 25 | .map((m) => toMonster(m)) 26 | .filter((m) => !badAttributes.some((s) => m.attributes.includes(s)) && rates[m.name] > 0); 27 | 28 | if (monsters.length === 0) { 29 | return 0; 30 | } else { 31 | const maximumDrops = slotOverride ?? AutumnAton.zoneItems(); 32 | const acuityCutoff = 20 - (acuityOverride ?? AutumnAton.visualAcuity()) * 5; 33 | const validDrops = flat(monsters.map((m) => itemDropsArray(m))).map(({ rate, type, drop }) => ({ 34 | value: !["c", "0"].includes(type) ? freecandyValue(drop) : 0, 35 | preAcuityExpectation: ["c", "0", ""].includes(type) ? (2 * rate) / 100 : 0, 36 | postAcuityExpectation: 37 | rate >= acuityCutoff && ["c", "0", ""].includes(type) ? (8 * rate) / 100 : 0, 38 | })); 39 | const overallExpectedDropQuantity = sum( 40 | validDrops, 41 | ({ preAcuityExpectation, postAcuityExpectation }) => 42 | preAcuityExpectation + postAcuityExpectation 43 | ); 44 | const expectedCollectionValue = sum( 45 | validDrops, 46 | ({ value, preAcuityExpectation, postAcuityExpectation }) => { 47 | // This gives us the adjusted amount to fit within our total amount of available drop slots 48 | const adjustedDropAmount = 49 | (preAcuityExpectation + postAcuityExpectation) * 50 | Math.min(1, maximumDrops / overallExpectedDropQuantity); 51 | return adjustedDropAmount * value; 52 | } 53 | ); 54 | return seasonalItemValue(location) + expectedCollectionValue; 55 | } 56 | } 57 | 58 | function seasonalItemValue(location: Location, seasonalOverride?: number): number { 59 | // Find the value of the drops based on zone difficulty/type 60 | const autumnItems = $items`autumn leaf, AutumnFest ale, autumn breeze, autumn dollar, autumn years wisdom`; 61 | const avgValueOfRandomAutumnItem = freecandyAverageValue(...autumnItems); 62 | const autumnMeltables = $items`autumn debris shield, autumn leaf pendant, autumn sweater-weather sweater`; 63 | const autumnItem = AutumnAton.getUniques(location)?.item; 64 | const seasonalItemDrops = seasonalOverride ?? AutumnAton.seasonalItems(); 65 | if (autumnItem) { 66 | return ( 67 | (seasonalItemDrops > 1 ? avgValueOfRandomAutumnItem : 0) + 68 | (autumnMeltables.includes(autumnItem) 69 | ? // If we already have the meltable, then we get a random item, else value at 0 70 | availableAmount(autumnItem) > 0 71 | ? avgValueOfRandomAutumnItem 72 | : 0 73 | : freecandyValue(autumnItem)) 74 | ); 75 | } else { 76 | // If we're in a location without any uniques, we still get cowcatcher items 77 | return seasonalItemDrops > 1 ? avgValueOfRandomAutumnItem : 0; 78 | } 79 | } 80 | 81 | function expectedRemainingExpeditions(legs = AutumnAton.legs()): number { 82 | // Better estimate upgrade value if not ascending 83 | const availableAutumnatonTurns = myAdventures() - AutumnAton.turnsLeft(); 84 | const quests = get("_autumnatonQuests"); 85 | const legOffsetFactor = 11 * Math.max(quests - legs - 1, 0); 86 | return Math.floor( 87 | Math.sqrt(quests ** 2 + (2 * (availableAutumnatonTurns - legOffsetFactor)) / 11) 88 | ); 89 | } 90 | 91 | const profitRelevantUpgrades = [ 92 | "leftarm1", 93 | "leftleg1", 94 | "rightarm1", 95 | "rightleg1", 96 | "cowcatcher", 97 | "periscope", 98 | "radardish", 99 | ] as const; 100 | 101 | function profitFromExtraAcuity( 102 | bestLocationContainingUpgrade: Location, 103 | bestLocationWithInstalledUpgrade: Location 104 | ): number { 105 | return ( 106 | averageAutumnatonValue(bestLocationContainingUpgrade) + 107 | averageAutumnatonValue(bestLocationWithInstalledUpgrade) * 108 | Math.max(0, expectedRemainingExpeditions() - 1) 109 | ); 110 | } 111 | function profitFromExtraLeg( 112 | bestLocationContainingUpgrade: Location, 113 | bestLocationWithInstalledUpgrade: Location 114 | ): number { 115 | return ( 116 | averageAutumnatonValue(bestLocationContainingUpgrade) + 117 | averageAutumnatonValue(bestLocationWithInstalledUpgrade) * 118 | Math.max(0, expectedRemainingExpeditions(AutumnAton.legs() + 1) - 1) 119 | ); 120 | } 121 | function profitFromExtraArm( 122 | bestLocationContainingUpgrade: Location, 123 | bestLocationWithInstalledUpgrade: Location 124 | ): number { 125 | return ( 126 | averageAutumnatonValue(bestLocationContainingUpgrade) + 127 | averageAutumnatonValue(bestLocationWithInstalledUpgrade) * 128 | Math.max(0, expectedRemainingExpeditions() - 1) 129 | ); 130 | } 131 | function profitFromExtraAutumnItem( 132 | bestLocationContainingUpgrade: Location, 133 | bestLocationWithInstalledUpgrade: Location 134 | ): number { 135 | return ( 136 | averageAutumnatonValue(bestLocationContainingUpgrade) + 137 | (seasonalItemValue(bestLocationWithInstalledUpgrade) + 138 | averageAutumnatonValue(bestLocationWithInstalledUpgrade)) * 139 | Math.max(0, expectedRemainingExpeditions() - 1) 140 | ); 141 | } 142 | 143 | function makeUpgradeValuator(fullLocations: Location[], currentBestLocation: Location) { 144 | return function (upgrade: AutumnAton.Upgrade) { 145 | const upgradeLocations = fullLocations.filter( 146 | (location) => AutumnAton.getUniques(location)?.upgrade === upgrade 147 | ); 148 | 149 | if (!upgradeLocations.length) { 150 | return { upgrade, profit: 0 }; 151 | } 152 | 153 | const bestLocationContainingUpgrade = maxBy(upgradeLocations, averageAutumnatonValue); 154 | 155 | switch (upgrade) { 156 | case "periscope": 157 | case "radardish": { 158 | const bestLocationWithInstalledUpgrade = maxBy(fullLocations, (loc: Location) => 159 | averageAutumnatonValue(loc, AutumnAton.visualAcuity() + 1) 160 | ); 161 | return { 162 | upgrade, 163 | profit: profitFromExtraAcuity( 164 | bestLocationContainingUpgrade, 165 | bestLocationWithInstalledUpgrade 166 | ), 167 | }; 168 | } 169 | case "rightleg1": 170 | case "leftleg1": { 171 | return { 172 | upgrade, 173 | profit: profitFromExtraLeg(bestLocationContainingUpgrade, currentBestLocation), 174 | }; 175 | } 176 | case "rightarm1": 177 | case "leftarm1": { 178 | const bestLocationWithInstalledUpgrade = maxBy(fullLocations, (loc: Location) => 179 | averageAutumnatonValue(loc, undefined, AutumnAton.zoneItems() + 1) 180 | ); 181 | return { 182 | upgrade, 183 | profit: profitFromExtraArm( 184 | bestLocationContainingUpgrade, 185 | bestLocationWithInstalledUpgrade 186 | ), 187 | }; 188 | } 189 | case "cowcatcher": { 190 | return { 191 | upgrade, 192 | profit: profitFromExtraAutumnItem(bestLocationContainingUpgrade, currentBestLocation), 193 | }; 194 | } 195 | default: { 196 | return { upgrade, profit: 0 }; 197 | } 198 | } 199 | }; 200 | } 201 | 202 | function mostValuableUpgrade(fullLocations: Location[]): Location[] { 203 | const validLocations = fullLocations.filter((l) => l.parent !== "Clan Basement"); 204 | // This function shouldn't be getting called if we don't have an expedition left 205 | if (expectedRemainingExpeditions() < 1) { 206 | return validLocations; 207 | } 208 | const currentUpgrades = AutumnAton.currentUpgrades(); 209 | const acquirableUpgrades = profitRelevantUpgrades.filter( 210 | (upgrade) => !currentUpgrades.includes(upgrade) 211 | ); 212 | 213 | if (acquirableUpgrades.length === 0) { 214 | return validLocations; 215 | } 216 | 217 | const currentBestLocation = maxBy(validLocations, averageAutumnatonValue); 218 | const currentExpectedProfit = 219 | averageAutumnatonValue(currentBestLocation) * expectedRemainingExpeditions(); 220 | 221 | const upgradeValuations = acquirableUpgrades.map( 222 | makeUpgradeValuator(validLocations, currentBestLocation) 223 | ); 224 | 225 | const { upgrade: highestValueUpgrade, profit: profitFromBestUpgrade } = maxBy( 226 | upgradeValuations, 227 | "profit" 228 | ); 229 | 230 | if (profitFromBestUpgrade > currentExpectedProfit) { 231 | const upgradeLocations = validLocations.filter( 232 | (location) => AutumnAton.getUniques(location)?.upgrade === highestValueUpgrade 233 | ); 234 | return upgradeLocations; 235 | } else { 236 | return validLocations; 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/regularTasks.ts: -------------------------------------------------------------------------------- 1 | import { 2 | abort, 3 | adv1, 4 | cliExecute, 5 | eat, 6 | fullnessLimit, 7 | getWorkshed, 8 | inebrietyLimit, 9 | Item, 10 | Location, 11 | mallPrices, 12 | myClass, 13 | myFullness, 14 | myHp, 15 | myInebriety, 16 | retrieveItem, 17 | reverseNumberology, 18 | runChoice, 19 | sessionStorage, 20 | todayToString, 21 | totalTurnsPlayed, 22 | use, 23 | useSkill, 24 | visitUrl, 25 | } from "kolmafia"; 26 | import { 27 | $classes, 28 | $effect, 29 | $familiar, 30 | $item, 31 | $items, 32 | $location, 33 | $phylum, 34 | $skill, 35 | ActionSource, 36 | AutumnAton, 37 | Counter, 38 | ensureFreeRun, 39 | get, 40 | getKramcoWandererChance, 41 | have, 42 | JuneCleaver, 43 | questStep, 44 | set, 45 | Snapper, 46 | SourceTerminal, 47 | TrainSet, 48 | tryFindFreeRun, 49 | withProperty, 50 | } from "libram"; 51 | import { CandyTask, shouldRedigitize } from "./lib"; 52 | import { 53 | bestAutumnatonLocation, 54 | coldMedicineCabinet, 55 | getBestPantsgivingFood, 56 | juneCleaverChoices, 57 | rotateTrainToOptimalCycle, 58 | willRotateTrainset, 59 | } from "./resources"; 60 | import { combatOutfit, digitizeOutfit } from "./outfit"; 61 | import { Modes, Outfit } from "grimoire-kolmafia"; 62 | import { CandyStrategy, Macro } from "./combat"; 63 | import args from "./args"; 64 | import { wanderer } from "./wanderer"; 65 | import { DraggableFight, WanderDetails } from "garbo-lib"; 66 | 67 | const MARKET_QUESTS = [ 68 | { pref: "questM23Meatsmith", url: "shop.php?whichshop=meatsmith&action=talk" }, 69 | { pref: "questM24Doc", url: "shop.php?whichshop=doc&action=talk" }, 70 | { pref: "questM25Armorer", url: "shop.php?whichshop=armory&action=talk" }, 71 | ]; 72 | 73 | let _digitizeInitialized = true; 74 | 75 | function digitizeInitialized(): void { 76 | _digitizeInitialized = true; 77 | } 78 | 79 | let runSource: ActionSource | null = null; 80 | 81 | function getRunSource(): ActionSource { 82 | if (!runSource) { 83 | runSource = 84 | tryFindFreeRun() ?? 85 | ensureFreeRun({ 86 | requireUnlimited: () => true, 87 | noFamiliar: () => true, 88 | noRequirements: () => true, 89 | maximumCost: () => get("autoBuyPriceLimit") ?? 20000, 90 | }); 91 | } 92 | if (!runSource) abort("Unable to find free run with which to initialize digitize!"); 93 | return runSource; 94 | } 95 | 96 | function makeWandererTask( 97 | type: DraggableFight, 98 | drunkSafe: boolean, 99 | base: Omit & 100 | Partial<{ 101 | combat: CandyStrategy; 102 | do: () => Location; 103 | sobriety: "sober" | "drunk"; 104 | outfit: () => Outfit; 105 | }>, 106 | equip: Item[] = [], 107 | modes: Modes = {} 108 | ): CandyTask { 109 | const sobriety = drunkSafe ? undefined : "sober"; 110 | const options: WanderDetails = drunkSafe ? { wanderer: type, drunkSafe } : type; 111 | return { 112 | sobriety, 113 | do: () => wanderer().getTarget(options), 114 | choices: () => wanderer().getChoices(options), 115 | combat: new CandyStrategy(), 116 | outfit: () => combatOutfit({ equip: wanderer().getEquipment(options).concat(equip), modes }), 117 | ...base, 118 | }; 119 | } 120 | 121 | const GLOBAL_TASKS: CandyTask[] = [ 122 | { 123 | name: "Search the Mall", 124 | completed: () => sessionStorage.getItem("last mallprices") === todayToString(), 125 | do: (): void => { 126 | mallPrices("allitems"); 127 | sessionStorage.setItem("last mallprices", todayToString()); 128 | }, 129 | }, 130 | ...MARKET_QUESTS.map(({ pref, url }) => ({ 131 | name: `Start Quest: ${pref}`, 132 | completed: () => questStep(pref) > -1, 133 | do: (): void => { 134 | visitUrl(url); 135 | runChoice(1); 136 | }, 137 | })), 138 | { 139 | name: "Acquire Kgnee", 140 | ready: () => 141 | have($familiar`Reagnimated Gnome`) && 142 | !have($item`gnomish housemaid's kgnee`) && 143 | !get("_freecandy_checkedGnome", false), 144 | completed: () => get("_freecandy_checkedGnome", false), 145 | do: (): void => { 146 | visitUrl("arena.php"); 147 | runChoice(4); 148 | set("_freecandy_checkedGnome", true); 149 | }, 150 | outfit: { familiar: $familiar`Reagnimated Gnome` }, 151 | limit: { tries: 1 }, 152 | }, 153 | { 154 | name: "Ow!", 155 | completed: () => myHp() > 0, 156 | do: () => abort("Ow! I have 0 hp!"), 157 | }, 158 | { 159 | name: "Check combat lost", 160 | completed: () => !get("_lastCombatLost", false), 161 | do: () => abort("Lost in combat!"), 162 | }, 163 | { 164 | name: "Lick wounds", 165 | ready: () => have($skill`Tongue of the Walrus`), 166 | completed: () => !have($effect`Beaten Up`), 167 | do: () => useSkill($skill`Tongue of the Walrus`), 168 | }, 169 | { 170 | name: "Sweat Out some Booze", 171 | completed: () => get("_sweatOutSomeBoozeUsed") >= 3, 172 | ready: () => myInebriety() > 0 && get("sweat") >= 25, 173 | do: () => useSkill($skill`Sweat Out Some Booze`), 174 | outfit: { pants: $item`designer sweatpants` }, 175 | sobriety: "sober", 176 | }, 177 | { 178 | name: "Numberology", 179 | ready: () => Object.values(reverseNumberology()).includes(69), 180 | completed: () => get("_universeCalculated") >= get("skillLevel144"), 181 | do: () => cliExecute("numberology 69"), 182 | }, 183 | { 184 | name: "Magical Sausage", 185 | ready: () => 186 | $items`magical sausage, magical sausage casing`.some((i) => have(i)) && 187 | $items`Kramco Sausage-o-Matic™, replica Kramco Sausage-o-Matic™`.some((i) => have(i)), 188 | completed: () => get("_sausagesEaten") >= 23 || myFullness() > fullnessLimit(), 189 | do: () => eat($item`magical sausage`), 190 | }, 191 | { 192 | name: "License to Chill", 193 | ready: () => have($item`License to Chill`), 194 | completed: () => get("_licenseToChillUsed"), 195 | do: () => use($item`License to Chill`), 196 | }, 197 | { 198 | name: "Fill Pantsgiving Fullness", 199 | ready: () => 200 | !$classes`Vampyre, Grey Goo`.includes(myClass()) && myFullness() + 1 === fullnessLimit(), 201 | completed: () => myFullness() >= fullnessLimit(), 202 | do: (): void => { 203 | const { food } = getBestPantsgivingFood(); 204 | if (!get("_fudgeSporkUsed")) { 205 | retrieveItem($item`fudge spork`); 206 | eat($item`fudge spork`); 207 | } 208 | retrieveItem(food); 209 | eat(food); 210 | }, 211 | }, 212 | { 213 | name: "Autumn-Aton", 214 | completed: () => !AutumnAton.available(), 215 | do: (): void => { 216 | AutumnAton.sendTo(bestAutumnatonLocation); 217 | }, 218 | }, 219 | { 220 | name: "Cold Medicine Cabinet", 221 | ready: () => getWorkshed() === $item`cold medicine cabinet`, 222 | completed: () => 223 | get("_coldMedicineConsults") >= 5 || get("_nextColdMedicineConsult") > totalTurnsPlayed(), 224 | do: coldMedicineCabinet, 225 | }, 226 | { 227 | name: "Trainset", 228 | ready: () => TrainSet.installed(), 229 | completed: () => !willRotateTrainset(), 230 | do: rotateTrainToOptimalCycle, 231 | }, 232 | { 233 | name: "Tune Snapper", 234 | ready: () => args.familiar === $familiar`Red-Nosed Snapper`, 235 | completed: () => Snapper.getTrackedPhylum() === $phylum`dude`, 236 | do: () => Snapper.trackPhylum($phylum`dude`), 237 | }, 238 | { 239 | name: "June Cleaver", 240 | completed: () => !JuneCleaver.have() || !!get("_juneCleaverFightsLeft"), 241 | do: () => 242 | withProperty("recoveryScript", "", () => { 243 | const target = 244 | myInebriety() > inebrietyLimit() ? $location`Drunken Stupor` : $location`Noob Cave`; 245 | adv1(target, -1, ""); 246 | }), 247 | choices: juneCleaverChoices, 248 | outfit: { weapon: $item`June cleaver` }, 249 | combat: new CandyStrategy(Macro.abort()), 250 | }, 251 | { 252 | name: "Terminal Skills", 253 | ready: () => SourceTerminal.have(), 254 | completed: () => SourceTerminal.isCurrentSkill([$skill`Extract`, $skill`Duplicate`]), 255 | do: () => SourceTerminal.educate([$skill`Extract`, $skill`Duplicate`]), 256 | }, 257 | { 258 | name: "Proton Ghost", 259 | completed: () => get("questPAGhost") === "unstarted", 260 | ready: () => have($item`protonic accelerator pack`) && !!get("ghostLocation"), 261 | do: () => get("ghostLocation") ?? abort("Failed to find proper ghost location"), 262 | outfit: () => combatOutfit({ back: $item`protonic accelerator pack` }), 263 | combat: new CandyStrategy(() => 264 | Macro.trySkill($skill`Shoot Ghost`) 265 | .trySkill($skill`Shoot Ghost`) 266 | .trySkill($skill`Shoot Ghost`) 267 | .trySkill($skill`Trap Ghost`) 268 | ), 269 | }, 270 | makeWandererTask( 271 | "wanderer", 272 | true, 273 | { 274 | name: "Vote Wanderer", 275 | ready: () => 276 | have($item`"I Voted!" sticker`) && 277 | totalTurnsPlayed() % 11 === 1 && 278 | get("_voteFreeFights") < 3, 279 | completed: () => get("lastVoteMonsterTurn") === totalTurnsPlayed(), 280 | combat: new CandyStrategy(), 281 | }, 282 | $items`"I Voted!" sticker` 283 | ), 284 | makeWandererTask("wanderer", true, { 285 | name: "Digitize Wanderer", 286 | completed: () => Counter.get("Digitize") > 0, 287 | prepare: () => 288 | shouldRedigitize() && SourceTerminal.educate([$skill`Digitize`, $skill`Extract`]), 289 | post: () => get("_sourceTerminalDigitizeMonsterCount") || (_digitizeInitialized = false), 290 | outfit: digitizeOutfit, 291 | combat: new CandyStrategy(() => Macro.redigitize().default()), 292 | }), 293 | makeWandererTask( 294 | "wanderer", 295 | true, 296 | { 297 | name: "Void Monster", 298 | ready: () => have($item`cursed magnifying glass`) && get("cursedMagnifyingGlassCount") === 13, 299 | completed: () => get("_voidFreeFights") >= 5, 300 | }, 301 | $items`cursed magnifying glass` 302 | ), 303 | makeWandererTask( 304 | "wanderer", 305 | true, 306 | { 307 | name: "Kramco", 308 | ready: () => have($item`Kramco Sausage-o-Matic™`), 309 | completed: () => getKramcoWandererChance() < 1, 310 | post: digitizeInitialized, 311 | combat: new CandyStrategy(), 312 | }, 313 | $items`Kramco Sausage-o-Matic™` 314 | ), 315 | makeWandererTask("yellow ray", false, { 316 | name: "Yellow Ray: Fondeluge", 317 | ready: () => have($skill`Fondeluge`), 318 | completed: () => have($effect`Everything Looks Yellow`), 319 | sobriety: "sober", 320 | post: digitizeInitialized, 321 | combat: new CandyStrategy(() => 322 | Macro.tryHaveSkill($skill`Duplicate`) 323 | .trySkill($skill`Fondeluge`) 324 | .abort() 325 | ), 326 | }), 327 | makeWandererTask( 328 | "yellow ray", 329 | false, 330 | { 331 | name: "Yellow Ray: Jurassic Parka", 332 | ready: () => have($item`Jurassic Parka`) && have($skill`Torso Awareness`), 333 | completed: () => have($effect`Everything Looks Yellow`), 334 | sobriety: "sober", 335 | post: digitizeInitialized, 336 | combat: new CandyStrategy(() => 337 | Macro.tryHaveSkill($skill`Duplicate`) 338 | .trySkill($skill`Spit jurassic acid`) 339 | .abort() 340 | ), 341 | }, 342 | $items`Jurassic Parka`, 343 | { parka: "dilophosaur" } 344 | ), 345 | makeWandererTask("freefight", false, { 346 | name: "Free-for-All", 347 | ready: () => have($skill`Free-For-All`), 348 | completed: () => have($effect`Everything Looks Red`), 349 | sobriety: "sober", 350 | post: digitizeInitialized, 351 | combat: new CandyStrategy(Macro.skill($skill`Free-For-All`)), 352 | }), 353 | makeWandererTask("wanderer", true, { 354 | name: "Nemesis Assassin", 355 | completed: () => Counter.get("Nemesis Assassin window end") > 0, 356 | post: digitizeInitialized, 357 | }), 358 | { 359 | name: "Initialize Digitize", 360 | completed: () => _digitizeInitialized, 361 | do: (): Location => { 362 | getRunSource()?.prepare(); 363 | return wanderer().getTarget("backup"); 364 | }, 365 | choices: () => wanderer().getChoices("backup"), 366 | post: (): void => { 367 | digitizeInitialized(); 368 | runSource = null; 369 | }, 370 | outfit: (): Outfit => { 371 | const run = getRunSource(); 372 | const req = run?.constraints?.equipmentRequirements?.(); 373 | const familiar = run?.constraints?.familiar?.(); 374 | const outfit = new Outfit(); 375 | if (familiar) outfit.equip(familiar); 376 | if (req) { 377 | if (req.maximizeParameters) outfit.modifier = req.maximizeParameters; 378 | for (const item of req.maximizeOptions.forceEquip ?? []) { 379 | if (!outfit.equip(item)) abort(`Failed to equip item ${item} for free running`); 380 | } 381 | } 382 | return combatOutfit(outfit.spec()); 383 | }, 384 | combat: new CandyStrategy(() => Macro.step(getRunSource()?.macro ?? Macro.abort())), 385 | sobriety: "sober", 386 | }, 387 | ]; 388 | 389 | export default GLOBAL_TASKS; 390 | -------------------------------------------------------------------------------- /src/outfit.ts: -------------------------------------------------------------------------------- 1 | import { Outfit, OutfitSpec } from "grimoire-kolmafia"; 2 | import { 3 | abort, 4 | buy, 5 | canEquip, 6 | effectModifier, 7 | equippedItem, 8 | Familiar, 9 | fullnessLimit, 10 | getOutfits, 11 | haveEquipped, 12 | inebrietyLimit, 13 | Item, 14 | mallPrice, 15 | myAdventures, 16 | myEffects, 17 | myFullness, 18 | myInebriety, 19 | numericModifier, 20 | outfitPieces, 21 | outfitTreats, 22 | Slot, 23 | toEffect, 24 | toItem, 25 | toJson, 26 | toSlot, 27 | totalTurnsPlayed, 28 | userConfirm, 29 | } from "kolmafia"; 30 | import args from "./args"; 31 | import { 32 | $familiar, 33 | $familiars, 34 | $item, 35 | $items, 36 | $monster, 37 | $skill, 38 | $slot, 39 | $slots, 40 | BurningLeaves, 41 | clamp, 42 | CrownOfThrones, 43 | findLeprechaunMultiplier, 44 | get, 45 | getAverageAdventures, 46 | getFoldGroup, 47 | have, 48 | maxBy, 49 | SongBoom, 50 | sum, 51 | sumNumbers, 52 | } from "libram"; 53 | import { printError, printHighlight } from "./lib"; 54 | import { getBestPantsgivingFood, juneCleaverBonusEquip } from "./resources"; 55 | import { freecandyAverageValue, freecandyValue } from "./value"; 56 | 57 | function treatValue(outfit: string): number { 58 | return sum( 59 | Object.entries(outfitTreats(outfit)), 60 | ([candyName, probability]) => probability * freecandyValue(toItem(candyName)) 61 | ); 62 | } 63 | 64 | function dropsValueFunction(drops: Item[] | Map): number { 65 | return Array.isArray(drops) 66 | ? freecandyAverageValue(...drops) 67 | : sum([...drops.entries()], ([item, quantity]) => quantity * freecandyValue(item)) / 68 | sumNumbers([...drops.values()]); 69 | } 70 | 71 | function ensureBjorn(weightValue: number, meatValue = 0): CrownOfThrones.FamiliarRider { 72 | const key = `weight:${weightValue.toFixed(3)};meat:${meatValue}`; 73 | if (!CrownOfThrones.hasRiderMode(key)) { 74 | CrownOfThrones.createRiderMode(key, { 75 | dropsValueFunction, 76 | modifierValueFunction: CrownOfThrones.createModifierValueFunction( 77 | ["Familiar Weight", "Meat Drop"], 78 | { 79 | "Familiar Weight": (x) => weightValue * x, 80 | "Meat Drop": (x) => meatValue * x, 81 | } 82 | ), 83 | }); 84 | } 85 | 86 | const result = CrownOfThrones.pickRider(key); 87 | if (!result) abort("Failed to make sensible bjorn decision!"); 88 | 89 | return result; 90 | } 91 | 92 | export function getTreatOutfit(): string { 93 | if (!args.treatOutfit) { 94 | const availableOutfits = getOutfits().filter((name) => 95 | outfitPieces(name).every((piece) => canEquip(piece)) 96 | ); 97 | 98 | printError(`No treatOutfit given--doing some math to decide what to use`); 99 | 100 | if (!availableOutfits.length) { 101 | abort("You don't seem to actually have any outfits available, my friend!"); 102 | } 103 | 104 | args.treatOutfit = maxBy(availableOutfits, treatValue); 105 | printHighlight(`We have a winner! We'll be trick-or-treating with ${args.treatOutfit}.`); 106 | } 107 | 108 | return args.treatOutfit; 109 | } 110 | 111 | let _baseAdventureValue: number; 112 | function baseAdventureValue(): number { 113 | if (!_baseAdventureValue) { 114 | const outfitCandyValue = treatValue(getTreatOutfit()); 115 | const totOutfitCandyMultiplier = have($familiar`Trick-or-Treating Tot`) ? 1.6 : 1; 116 | const bowlValue = (1 / 5) * freecandyValue($item`huge bowl of candy`); 117 | const prunetsValue = have($familiar`Trick-or-Treating Tot`) 118 | ? 4 * 0.2 * freecandyValue($item`Prunets`) 119 | : 0; 120 | 121 | const outfitCandyTotal = 3 * outfitCandyValue * totOutfitCandyMultiplier; 122 | _baseAdventureValue = (1 / 5) * (outfitCandyTotal + bowlValue + prunetsValue); 123 | } 124 | return _baseAdventureValue; 125 | } 126 | 127 | function snowSuit() { 128 | if (!have($item`Snow Suit`) || get("_carrotNoseDrops") >= 3) return new Map([]); 129 | 130 | return new Map([[$item`Snow Suit`, freecandyValue($item`carrot nose`) / 10]]); 131 | } 132 | 133 | function mayflowerBouquet() { 134 | // +40% meat drop 12.5% of the time (effectively 5%) 135 | // Drops flowers 50% of the time, wiki says 5-10 a day. 136 | // Theorized that flower drop rate drops off but no info on wiki. 137 | // During testing I got 4 drops then the 5th took like 40 more adventures 138 | // so let's just assume rate drops by 11% with a min of 1% ¯\_(ツ)_/¯ 139 | 140 | if (!have($item`Mayflower bouquet`) || get("_mayflowerDrops") >= 10) 141 | return new Map([]); 142 | 143 | const averageFlowerValue = 144 | freecandyAverageValue( 145 | ...$items`tin magnolia, upsy daisy, lesser grodulated violet, half-orchid, begpwnia` 146 | ) * Math.max(0.01, 0.5 - get("_mayflowerDrops") * 0.11); 147 | return new Map([[$item`Mayflower bouquet`, averageFlowerValue]]); 148 | } 149 | 150 | function sweatpants() { 151 | if (!have($item`designer sweatpants`)) return new Map(); 152 | 153 | const needSweat = get("sweat") < 25 * (3 - get("_sweatOutSomeBoozeUsed")); 154 | 155 | if (!needSweat) return new Map(); 156 | 157 | const VOA = get("valueOfAdventure"); 158 | 159 | const bestPerfectDrink = maxBy( 160 | $items`perfect cosmopolitan, perfect negroni, perfect dark and stormy, perfect mimosa, perfect old-fashioned, perfect paloma`, 161 | mallPrice, 162 | true 163 | ); 164 | const perfectDrinkValuePerDrunk = 165 | (getAverageAdventures(bestPerfectDrink) * VOA - mallPrice(bestPerfectDrink)) / 3; 166 | const splendidMartiniValuePerDrunk = 167 | (getAverageAdventures($item`splendid martini`) + 2) * VOA - mallPrice($item`splendid martini`); 168 | 169 | const bonus = (Math.max(perfectDrinkValuePerDrunk, splendidMartiniValuePerDrunk) * 2) / 25; 170 | return new Map([[$item`designer sweatpants`, bonus]]); 171 | } 172 | 173 | function pantogram() { 174 | if (!have($item`pantogram pants`) || !get("_pantogramModifier").includes("Drops Items")) 175 | return new Map(); 176 | return new Map([[$item`pantogram pants`, 100]]); 177 | } 178 | 179 | let _sneegleebDropValue: number; 180 | function sneegleebDropValue(): number { 181 | return (_sneegleebDropValue ??= 182 | 0.13 * 183 | sum( 184 | Item.all().filter( 185 | (i) => i.tradeable && i.discardable && (i.inebriety || i.fullness || i.potion) 186 | ), 187 | (i) => clamp(freecandyValue(i), 0, 100_000) 188 | )); 189 | } 190 | 191 | function reallyEasyBonuses() { 192 | return new Map( 193 | ( 194 | [ 195 | [$item`lucky gold ring`, 400], 196 | [$item`Mr. Cheeng's spectacles`, 250], 197 | [$item`Mr. Screege's spectacles`, 180], 198 | [$item`KoL Con 13 snowglobe`, sneegleebDropValue()], 199 | [$item`can of mixed everything`, sneegleebDropValue() / 2], 200 | [$item`tiny stillsuit`, 69], 201 | ] as [Item, number][] 202 | ).filter(([item]) => have(item)) 203 | ); 204 | } 205 | 206 | function rakeLeaves(): Map { 207 | if (!BurningLeaves.have()) { 208 | return new Map(); 209 | } 210 | const rakeValue = freecandyValue($item`inflammable leaf`) * 1.5; 211 | return new Map([ 212 | [$item`rake`, rakeValue], 213 | [$item`tiny rake`, rakeValue], 214 | ]); 215 | } 216 | 217 | function easyBonuses() { 218 | return new Map([ 219 | ...reallyEasyBonuses(), 220 | ...juneCleaverBonusEquip(), 221 | ...snowSuit(), 222 | ...mayflowerBouquet(), 223 | ...sweatpants(), 224 | ...pantogram(), 225 | ...rakeLeaves(), 226 | ]); 227 | } 228 | 229 | let estimatedOutfitWeight: number; 230 | function getEstimatedOutfitWeight(): number { 231 | if (!estimatedOutfitWeight) { 232 | const bonuses = easyBonuses(); 233 | 234 | const freeAccessories = 3 - clamp([...easyBonuses().keys()].length, 0, 3); 235 | const openSlots = [ 236 | ...$slots`shirt, weapon, off-hand`, 237 | ...(have($item`Buddy Bjorn`) ? [] : $slots`back`), 238 | ...(bonuses.has($item`pantogram pants`) ? [] : $slots`pants`), 239 | ]; 240 | 241 | const viableItems = Item.all().filter( 242 | (item) => 243 | have(item) && 244 | (openSlots.includes(toSlot(item)) || (toSlot(item) === $slot`acc1` && freeAccessories > 0)) 245 | ); 246 | 247 | const nonAccessoryWeightEquips = openSlots.map((slot) => 248 | maxBy( 249 | viableItems.filter((item) => toSlot(item) === slot), 250 | (item) => numericModifier(item, "Familiar Weight") 251 | ) 252 | ); 253 | 254 | const accessoryWeightEquips = freeAccessories 255 | ? viableItems 256 | .filter((item) => toSlot(item) === $slot`acc1`) 257 | .sort( 258 | (a, b) => numericModifier(b, "Familiar Weight") - numericModifier(a, "Familiar Weight") 259 | ) 260 | .splice(0, freeAccessories) 261 | : []; 262 | 263 | estimatedOutfitWeight = 264 | sum([...accessoryWeightEquips, ...nonAccessoryWeightEquips], (item: Item) => 265 | numericModifier(item, "Familiar Weight") 266 | ) + 267 | (have($familiar`Temporal Riftlet`) ? 10 : 0) + 268 | (have($skill`Amphibian Sympathy`) ? 5 : 0); 269 | } 270 | 271 | return estimatedOutfitWeight; 272 | } 273 | 274 | let effectWeight: number; 275 | function getEffectWeight(): number { 276 | if (!effectWeight) { 277 | effectWeight = sum( 278 | Object.entries(myEffects()) 279 | .map(([name, duration]) => { 280 | return { 281 | effect: toEffect(name), 282 | duration: duration, 283 | }; 284 | }) 285 | .filter( 286 | ({ effect, duration }) => 287 | numericModifier(effect, "Familiar Weight") && duration >= myAdventures() 288 | ), 289 | ({ effect }) => numericModifier(effect, "Familiar Weight") 290 | ); 291 | } 292 | return effectWeight; 293 | } 294 | 295 | function overallAdventureValue(): number { 296 | const bonuses = easyBonuses(); 297 | const bjornChoice = ensureBjorn(0); 298 | const bjornValue = 299 | bjornChoice && (bjornChoice.dropPredicate?.() ?? true) 300 | ? bjornChoice.probability * 301 | (typeof bjornChoice.drops === "number" 302 | ? bjornChoice.drops 303 | : dropsValueFunction(bjornChoice.drops)) 304 | : 0; 305 | const itemAndMeatValue = 306 | sum(Slot.all(), (slot) => bonuses.get(equippedItem(slot)) ?? 0) + 307 | baseAdventureValue() + 308 | (haveEquipped($item`Buddy Bjorn`) || haveEquipped($item`Crown of Thrones`) ? bjornValue : 0); 309 | 310 | const stasisData = stasisFamiliars.get(args.familiar); 311 | if (stasisData) { 312 | return ( 313 | itemAndMeatValue + 314 | (20 + getEstimatedOutfitWeight() + getEffectWeight()) * 315 | stasisData.meatPerLb * 316 | clamp(stasisData.baseRate + actionRateBonus(), 0, 1) 317 | ); 318 | } else if (adventureFamiliars.includes(args.familiar)) { 319 | return (itemAndMeatValue * 1000) / (1000 - getEffectWeight() - getEstimatedOutfitWeight() - 20); 320 | } else return itemAndMeatValue; 321 | } 322 | 323 | function pantsgiving(): Map { 324 | if (!have($item`Pantsgiving`)) return new Map(); 325 | const count = get("_pantsgivingCount"); 326 | const turnArray = [5, 50, 500, 5000]; 327 | const index = 328 | myFullness() === fullnessLimit() 329 | ? get("_pantsgivingFullness") 330 | : turnArray.findIndex((x) => count < x); 331 | const turns = turnArray[index] ?? 50000; 332 | 333 | if (turns - count > myAdventures()) return new Map(); 334 | const { food, costOverride } = getBestPantsgivingFood(); 335 | const fullnessValue = 336 | overallAdventureValue() * (getAverageAdventures(food) + 1 + (get("_fudgeSporkUsed") ? 3 : 0)) - 337 | (costOverride?.() ?? mallPrice(food)) - 338 | mallPrice($item`Special Seasoning`) - 339 | (get("_fudgeSporkUsed") ? mallPrice($item`fudge spork`) : 0); 340 | const pantsgivingBonus = fullnessValue / (turns * 0.9); 341 | return new Map([[$item`Pantsgiving`, pantsgivingBonus]]); 342 | } 343 | 344 | function fullBonuses() { 345 | return new Map([...easyBonuses(), ...pantsgiving()]); 346 | } 347 | 348 | export function treatOutfit(): Outfit { 349 | const outfit = new Outfit(); 350 | const pieces = outfitPieces(getTreatOutfit()); 351 | for (const piece of pieces) { 352 | if (!outfit.equip(piece)) 353 | abort(`Could not equip all pieces of treat outfit: aborted on ${piece}`); 354 | } 355 | 356 | outfit.equip($familiar`Trick-or-Treating Tot`); 357 | return outfit; 358 | } 359 | 360 | const adventureFamiliars = $familiars`Temporal Riftlet, Reagnimated Gnome`; 361 | // https://www.desmos.com/calculator/y8iszw6rfk 362 | // Very basic linear approximation of the value of additional weight 363 | const MAGIC_NUMBER = 0.00123839009288; 364 | 365 | type stasisValue = { 366 | baseRate: number; 367 | meatPerLb: number; 368 | }; 369 | 370 | const stasisFamiliars = new Map([ 371 | [$familiar`Ninja Pirate Zombie Robot`, { baseRate: 1 / 2, meatPerLb: 14.52 }], 372 | [$familiar`Cocoabo`, { baseRate: 1 / 3, meatPerLb: 13.2 }], 373 | [$familiar`Stocking Mimic`, { baseRate: 1 / 3, meatPerLb: 13.2 }], 374 | [$familiar`Feather Boa Constrictor`, { baseRate: 1 / 3, meatPerLb: 27.5 }], 375 | ]); 376 | const actionRateBonus = () => 377 | numericModifier("Familiar Action Bonus") / 100 + 378 | ($items`short stack of pancakes, short stick of butter, short glass of water` 379 | .map((item) => effectModifier(item, "Effect")) 380 | .some((effect) => have(effect)) 381 | ? 1 382 | : 0); 383 | 384 | export function combatOutfit(base: OutfitSpec = {}): Outfit { 385 | const outfit = Outfit.from( 386 | base, 387 | new Error(`Failed to construct outfit from spec ${toJson(base)}`) 388 | ); 389 | outfit.equip(args.familiar); 390 | 391 | if (outfit.familiar === $familiar`Reagnimated Gnome`) { 392 | outfit.equip($item`gnomish housemaid's kgnee`); 393 | } 394 | 395 | if ( 396 | get("questPAGhost") === "unstarted" && 397 | get("nextParanormalActivity") <= totalTurnsPlayed() && 398 | myInebriety() <= inebrietyLimit() 399 | ) { 400 | outfit.equip($item`protonic accelerator pack`); 401 | } 402 | 403 | let weightValue = 0; 404 | if (!outfit.familiar) { 405 | abort( 406 | "It looks like we're about to go adventuring without a familiar, and that feels deeply wrong" 407 | ); 408 | } 409 | if (adventureFamiliars.includes(outfit.familiar)) { 410 | weightValue = Math.round(MAGIC_NUMBER * baseAdventureValue() * 100) / 100; 411 | } else { 412 | const stasisData = stasisFamiliars.get(outfit.familiar); 413 | if (stasisData) { 414 | const actionRate = stasisData.baseRate + actionRateBonus(); 415 | if ( 416 | actionRate < 1 && 417 | getFoldGroup($item`Loathing Legion helicopter`).some((foldable) => have(foldable)) 418 | ) { 419 | outfit.equip($item`Loathing Legion helicopter`); 420 | } 421 | const fullRate = clamp( 422 | actionRate + (outfit.haveEquipped($item`Loathing Legion helicopter`) ? 0.25 : 0), 423 | 0, 424 | 1 425 | ); 426 | weightValue = fullRate * stasisData.meatPerLb; 427 | } else if (SongBoom.song() === "Total Eclipse of Your Meat") { 428 | outfit.modifier.push("0.25 Meat Drop"); 429 | } else { 430 | outfit.modifier.push("0.01 Item Drop"); 431 | } 432 | } 433 | 434 | if (weightValue) { 435 | const rounded = Math.round(1000 * weightValue) / 1000; 436 | outfit.modifier.push(`${rounded} Familiar Weight`); 437 | } 438 | 439 | const bjornChoice = ensureBjorn(weightValue); 440 | if (have($item`Buddy Bjorn`)) { 441 | outfit.equip($item`Buddy Bjorn`); 442 | outfit.bjornify(bjornChoice.familiar); 443 | } else if (have($item`Crown of Thrones`)) { 444 | outfit.equip($item`Crown of Thrones`); 445 | outfit.enthrone(bjornChoice.familiar); 446 | } 447 | 448 | outfit.setBonuses(fullBonuses()); 449 | 450 | return outfit; 451 | } 452 | 453 | let askedAboutTwoPiece = false; 454 | const trickHats = $items`invisible bag, witch hat, beholed bedsheet, wolfman mask, pumpkinhead mask, mummy costume`; 455 | const twoPieces = ["Eldritch Equipage", "Bugbear Costume", "Filthy Hippy Disguise"]; 456 | export function trickOutfit(): Outfit { 457 | if (args.trickOutfit) { 458 | const outfit = new Outfit(); 459 | outfit.equip(args.familiar); 460 | for (const piece of outfitPieces(args.trickOutfit)) { 461 | if (!outfit.equip(piece)) { 462 | abort(`Failed to equip ${piece} from trick outfit ${args.trickOutfit}`); 463 | } 464 | } 465 | return outfit; 466 | } 467 | 468 | if (!trickHats.some((hat) => have(hat))) { 469 | buy(1, maxBy(trickHats, mallPrice, true)); 470 | } 471 | const trickHat = trickHats.find((i) => have(i)); 472 | if (!trickHat) { 473 | const twoPiece = twoPieces.find((outfit) => 474 | outfitPieces(outfit).every((i) => have(i) && canEquip(i)) 475 | ); 476 | if (!twoPiece) { 477 | abort("Unable to find a good 1-piece or 2-piece outfit for trick-or-treating"); 478 | } 479 | if ( 480 | !askedAboutTwoPiece && 481 | !userConfirm( 482 | "We don't have access to a one-piece outfit, but we did find a two-piece outfit. Is that alright?" 483 | ) 484 | ) { 485 | printError("We cannot create a good trick outfit, and must give up."); 486 | abort(); 487 | } else { 488 | askedAboutTwoPiece = true; 489 | } 490 | const outfit = new Outfit(); 491 | for (const piece of outfitPieces(twoPiece)) { 492 | if (!outfit.equip(piece)) abort(`Unable to equip ${piece} from ${twoPiece}!`); 493 | } 494 | return combatOutfit(outfit.spec()); 495 | } 496 | 497 | return combatOutfit({ hat: trickHat }); 498 | } 499 | 500 | export function digitizeOutfit(): Outfit { 501 | if (get("_sourceTerminalDigitizeMonster") === $monster`Knob Goblin Embezzler`) { 502 | const outfit = new Outfit(); 503 | const meatFamiliar = maxBy( 504 | Familiar.all().filter((f) => have(f)), 505 | findLeprechaunMultiplier 506 | ); 507 | outfit.equip(meatFamiliar); 508 | const baseMeat = 1000 + (SongBoom.song() === "Total Eclipse of Your Meat" ? 25 : 0); 509 | 510 | const leprechaunMultiplier = findLeprechaunMultiplier(meatFamiliar); 511 | const leprechaunCoefficient = 512 | (baseMeat / 100) * (2 * leprechaunMultiplier + Math.sqrt(leprechaunMultiplier)); 513 | 514 | const bjornChoice = ensureBjorn(leprechaunCoefficient, baseMeat / 100); 515 | if (have($item`Buddy Bjorn`)) { 516 | outfit.equip($item`Buddy Bjorn`); 517 | outfit.bjornify(bjornChoice.familiar); 518 | } else if (have($item`Crown of Thrones`)) { 519 | outfit.equip($item`Crown of Thrones`); 520 | outfit.enthrone(bjornChoice.familiar); 521 | } 522 | 523 | outfit.modifier.push(`${baseMeat / 100} Meat Drop`); 524 | outfit.modifier.push("0.72 Item Drop"); 525 | 526 | outfit.setBonuses(fullBonuses()); 527 | return outfit; 528 | } 529 | 530 | return combatOutfit(); 531 | } 532 | --------------------------------------------------------------------------------