##### CDI (crawl.dcss.io) RC ########################### # Plain options first, then font sizes/sound/keys, then the BRC Lua code at the bottom. # Lines starting with # are comments. # Contains code from BRC (Buehler RC, MIT): https://github.com/brianfaires/crawl-rc - see NOTICE in the repo. # This RC lives at https://github.com/LootAppraiser/dcss-rc ##### Pickup ##### # What autopickup grabs: gold, scrolls, potions, books, jewellery, wands, gems. # Armour/weapons are NOT auto-picked-up (you choose with g). autopickup = $?!+"/♦ pickup_thrown = true ##### Travel / Explore (vanilla offline defaults) ##### # Wait until HP and MP are both at 100% before moving on after resting rest_wait_percent = 100 # (Resting after explore is handled by the BRC fully-recover feature below.) # Half the vanilla 20 ms per step, and no travel trail. # explore_delay is left unset so explore uses travel_delay too. travel_delay = 10 rest_delay = 0 show_travel_trail = false # 0 = no bias towards walls/corners (vanilla) explore_wall_bias = 0 # Vanilla explore stops explore_stop = items,stairs,shops,altars,portals,branches,runed_doors,transporters explore_stop += greedy_pickup_smart,greedy_visited_item_stack ##### Safety ##### # (Low HP warning comes from the BRC misc-alerts feature below.) # Ask before casting a spell with a yellow-or-worse failure level fail_severity_to_confirm = 2 # Ask before using one-way hatches/shafts warn_hatches = true # Y/N prompts that matter need a capital Y (default, written out) easy_confirm = safe ##### Survival ##### # Hard --More-- so a panic keypress can't scroll past what just happened. Monster danger alerts are the BRC # alert-monsters feature below; these are the rest. Patterns follow gammafunk's long-used rc. # Lost control of your turns force_more_message += You are (paralysed|confused|blinded|mesmerised|petrified|slowing down) force_more_message += You suddenly lose the ability to move force_more_message += lose consciousness # An escape or action that did not work force_more_message += You miscast.*(Blink|Borgnjor|Door|Invisibility) force_more_message += You fail to use your ability force_more_message += You (can't|cannot) (read|drink|do) force_more_message += You cannot .* (while unable to breathe|in your current state) force_more_message += You don't have the energy to cast that spell force_more_message += You are unable to access your magic force_more_message += You are held in a net # Traps and level effects force_more_message += (blundered into a|invokes the power of) Zot force_more_message += enter a teleport trap force_more_message += Space (warps|bends).*around you # Uniques and Pandemonium lords: the "walk away from it" fights. (Capital letter after "You encounter".) force_more_message += monster_warning:You encounter (?-i:[A-Z]) # Buffs ending: stop travel as well as the --More--, flight ending over water or lava is the classic death force_more_message += (You are starting to lose your buoyancy|Your transformation is almost over) force_more_message += (You feel yourself slow down|You start to feel a little slower) runrest_stop_message += (You are starting to lose your buoyancy|Your transformation is almost over) runrest_stop_message += (You feel yourself slow down|You start to feel a little slower) runrest_stop_message += god:wrath finds you # Yellow background on "tough" monsters too (default is nasty and unusual only) tile_show_threat_levels = tough, nasty, unusual # Show the Zot light all game, not only when time is short always_show_zot = true ##### Items and skills ##### # Ask before reading/drinking an identified bad item autoinscribe += (bad|dangerous)_item.*scroll:!r autoinscribe += (bad|dangerous)_item.*potion:!q # Manual skill training from turn 1: auto-training spreads XP over skills you do not want default_manual_training = true ##### Autofight (Tab) ##### # Autofight refuses to act below this % HP (your original: 75) autofight_stop = 75 autofight_caught = true ##### Menus ##### # Inventory/pickup menus: equipped first, then artefacts, egos, then by name sort_menus = true:equipped,art,ego,basename,identified,qualname,>qty ##### Display / font sizes ##### # The font is the installed Terminus (TTF); see fontconfig/ and README. Keep sizes on a strike. tile_font_msg_size = 24 tile_font_stat_size = 24 tile_font_crt_size = 24 tile_font_tip_size = 24 tile_font_lbl_size = 24 tile_viewport_scale = 2 action_panel_scale = 150 ##### Sound (DWEM SoundSupport) ##### sounds_on = true sound_pack += https://sound-packs.nemelex.cards/DCSS-UST/v1.0.1.zip sound_pack += https://osp.nemelex.cards/build/latest.zip:["init.txt"] one_SDL_sound_channel = true sound_fade_time = 0.5 bgm_volume = 0 ##### Gold in the status panel (DWEM ConvenienceModule) ##### show_gold_status = true ##### Game recording (DWEM WTRec) ##### # Records each game in your browser and saves it when you return to the lobby. In chat: /wtrec list | download | delete. record_wtrec = true ##### Keys ##### # Ctrl-Tab: autofight without moving (note: browsers may grab Ctrl-Tab to switch tabs) bindkey = [\{-222}] CMD_AUTOFIGHT_NOMOVE # Ctrl-D: travel to the nearest down stairs and descend (= Ctrl-G then >) macros += M \{4} \{7}> # Ctrl-E (go up) comes from the go-up-macro feature below. ##### BRC (https://github.com/brianfaires/crawl-rc) - full build, only the parts we want ##### # Core files first (needed by every feature), then the features. # To drop a feature: delete its "##### lua/features/NAME.lua #####" block. # BRC picks features up automatically; nothing else needs editing. ##### lua/core/_header.lua ##### { BRC = {} BRC.Config = {} -- Specify a config by name, or "ask" to prompt at start of each new game BRC.Config.to_use = "Custom" } ##### your config ##### { -- Your BRC settings. Anything not listed here uses the feature's default. brc_config_custom = { BRC_CONFIG_NAME = "Custom", emojis = false, -- no emojis anywhere ["misc-alerts"] = { alert_low_hp_threshold = 35, -- warn when HP drops below this % of max (replaces native hp_warning) }, } -- brc_config_custom (do not remove this comment) } ##### lua/core/constants.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC core module -- @module BRC -- Constants and definitions used throughout BRC. --------------------------------------------------------------------------------------------------- ---- Cosmetic settings BRC.EMOJI = {} BRC.init_emojis = function() if BRC.Config.emojis then BRC.EMOJI.CAUTION = "⚠️" BRC.EMOJI.EXCLAMATION = "❗" BRC.EMOJI.EXCLAMATION_2 = "‼️" BRC.EMOJI.SUCCESS = "✅" else BRC.EMOJI.CAUTION = "!" BRC.EMOJI.EXCLAMATION = "!" BRC.EMOJI.EXCLAMATION_2 = "!!" BRC.EMOJI.SUCCESS = nil end end ---- Items ---- BRC.MISC_ITEMS = { "box of beasts", "condenser vane", "figurine of a ziggurat", "Gell's gravitambourine", "horn of Geryon", "lightning rod", "phantom mirror", "phial of floods", "sack of spiders", "tin of tremorstones", } -- BRC.MISC_ITEMS (do not remove this comment) BRC.MISSILES = { "poisoned dart", "atropa-tipped dart", "curare-tipped dart", "datura-tipped dart", "darts? of disjunction", "darts? of dispersal", " stone", "boomerang", "silver javelin", "javelin", "large rock", "throwing net", } -- BRC.MISSILES (do not remove this comment) -- Could be removed after https://github.com/crawl/crawl/issues/4606 is addressed BRC.SPELLBOOKS = { "parchment of", "book of", "Necronomicon", "Grand Grimoire", "tome of obsoleteness", "Everburning Encyclopedia", "Ozocubu's Autobiography", "Maxwell's Memoranda", "Young Poisoner's Handbook", "Fen Folio", "Inescapable Atlas", "There-And-Back Book", "Great Wizards, Vol. II", "Great Wizards, Vol. VII", "Trismegistus Codex", "the Unrestrained Analects", "Compendium of Siegecraft", "Codex of Conductivity", "Handbook of Applied Construction", "Treatise on Traps", "My Sojourn through Swampland", "Akashic Record", -- Include prefixes for randart books "Almanac", "Anthology", "Atlas", "Book", "Catalogue", "Codex", "Compendium", "Compilation", "Cyclopedia", "Directory", "Elucidation", "Encyclopedia", "Folio", "Grimoire", "Handbook", "Incunable", "Incunabulum", "Octavo", "Omnibus", "Papyrus", "Parchment", "Precepts", "Quarto", "Secrets", "Spellbook", "Tome", "Vellum", "Volume", } -- BRC.SPELLBOOKS (do not remove this comment) ---- Races ---- BRC.UNDEAD_RACES = { "Demonspawn", "Mummy", "Poltergeist", "Revenant" } BRC.NONLIVING_RACES = { "Djinni", "Gargoyle" } BRC.POIS_RES_RACES = { "Djinni", "Gargoyle", "Mummy", "Naga", "Poltergeist", "Revenant" } BRC.LITTLE_RACES = { "Spriggan" } BRC.SMALL_RACES = { "Kobold" } BRC.LARGE_RACES = { "Armataur", "Gale Centaur", "Naga", "Oni", "Troll" } ---- Skills ---- BRC.MAGIC_SCHOOLS = { air = "Air Magic", alchemy = "Alchemy", chemistry = "Alchemy", cold = "Ice Magic", conjuration = "Conjurations", death = "Necromancy", earth = "Earth Magic", fire = "Fire Magic", necromancy = "Necromancy", } -- BRC.MAGIC_SCHOOLS (do not remove this comment) BRC.TRAINING_SKILLS = { "Air Magic", "Alchemy", "Armour", "Axes", "Conjurations", "Dodging", "Earth Magic", "Evocations", "Fighting", "Fire Magic", "Forgecraft", "Hexes", "Ice Magic", "Invocations", "Long Blades", "Maces & Flails", "Necromancy", "Polearms", "Ranged Weapons", "Shapeshifting", "Shields", "Short Blades", "Spellcasting", "Staves", "Stealth", "Summonings", "Translocations", "Unarmed Combat", "Throwing", } -- BRC.TRAINING_SKILLS (do not remove this comment) BRC.WEAP_SCHOOLS = { "axes", "maces & flails", "polearms", "long blades", "short blades", "staves", "unarmed combat", "ranged weapons", } -- BRC.WEAP_SCHOOLS (do not remove this comment) ---- Branches ---- BRC.HELL_BRANCHES = { "Coc", "Dis", "Geh", "Hell", "Tar" } BRC.PORTAL_FEATURE_NAMES = { "Bailey", "Bazaar", "Desolation", "Gauntlet", "IceCv", "Necropolis", "Ossuary", "Sewer", "Trove", "Volcano", "Wizlab", "Zig", } -- BRC.PORTAL_FEATURE_NAMES (do not remove this comment) ---- Egos ---- BRC.RISKY_EGOS = { "antimagic", "chaos", "distort", "harm", "heavy", "Infuse", "Ponderous" } BRC.NON_ELEMENTAL_DMG_EGOS = { "distort", "heavy", "spect" } BRC.ADJECTIVE_EGOS = { -- Egos whose English modifier comes before item name antimagic = "antimagic", heavy = "heavy", spectralising = "spectral", vampirism = "vampiric" } -- BRC.ADJECTIVE_EGOS (do not remove this comment) ---- Artefact properties ---- BRC.ARTPROPS_BAD = { "Bane", "-Cast", "-Move", "-Tele", "^Contam", "^Drain", "^Fragile", "*Corrode", "*Noise", "*Rage", "*Silence", "*Slow", "*Tele", } -- BRC.ARTPROPS_BAD (do not remove this comment) BRC.ARTPROPS_EGO = { -- Corresponding ego rF = "fire resistance", rC = "cold resistance", rPois = "poison resistance", rN = "positive energy", rCorr = "corrosion resistance", Archmagi = "the Archmagi", Rampage = "rampaging", Will = "willpower", Air = "air", Earth = "earth", Fire = "fire", Ice = "ice", Necro = "death", Summ = "command", } -- BRC.ARTPROPS_EGO (do not remove this comment) ---- Other ---- BRC.KEYS = { ENTER = 13, ESC = 27, ["Cntl-T"] = 20, ["Cntl-E"] = 5, ["Cntl-5"] = crawl.is_webtiles() and -11 or -43 } -- BRC.KEYS (do not remove this comment) BRC.COL = { black = "0", blue = "1", green = "2", cyan = "3", red = "4", magenta = "5", brown = "6", lightgrey = "7", darkgrey = "8", lightblue = "9", lightgreen = "10", lightcyan = "11", lightred = "12", lightmagenta = "13", yellow = "14", white = "15", } -- BRC.COL (do not remove this comment) BRC.DMG_TYPE = { unbranded = 1, -- No brand plain = 2, -- Include brand dmg for non-elemental brands branded = 3, -- Include full brand dmg scoring = 4, -- Include boosts for non-damaging brands } -- BRC.DMG_TYPE (do not remove this comment) BRC.SIZE_PENALTY = { LITTLE = -2, SMALL = -1, NORMAL = 0, LARGE = 1, GIANT = 2 } BRC.BAD_DURATIONS = { "berserk", "blind", "confused", "corroded", "diminished spells", "marked", "magic-sapped", "short of breath", "sign of ruin", "slowed", "sluggish", "tree-form", "vertiginous", "vulnerable", "weakened", } -- BRC.BAD_DURATIONS (do not remove this comment) } ##### lua/util/util.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC utility module -- @module BRC.util -- General utility functions. --------------------------------------------------------------------------------------------------- BRC.util = {} --- Get the keycode for Cntl+char function BRC.util.cntl(c) if c >= '0' and c <= '9' or c >= 'a' and c <= 'z' then -- Idk why webtiles numeric keycodes are different than local tiles on Mac if crawl.is_webtiles() and c >= '0' and c <= '9' then return string.byte(c) - 64 end return string.byte(c) - 96 elseif c >= 'A' and c <= 'Z' then return string.byte(c) - 64 end BRC.mpr.error("Unsupported character sent to BRC.util.cntl: %s", c) return nil end --- Get key assigned to a crawl command (e.g. "CMD_EXPLORE") function BRC.util.get_cmd_key(cmd) local key = crawl.get_command(cmd) if not key or key == "NULL" then return nil end -- get_command returns things like "Uppercase Ctrl-S"; we just want 'S' local char_key = key:sub(-1) return key:contains("Ctrl") and BRC.util.cntl(char_key) or char_key end --- Tries sendkeys() first, fallback to do_commands() (which isn't always immediate) -- @param cmd (string) The command to execute like "CMD_EXPLORE" function BRC.util.do_cmd(cmd) local key = BRC.util.get_cmd_key(cmd) if key then crawl.sendkeys({ key }) crawl.flush_input() else crawl.do_commands({ cmd }) end end ---- Lua table helpers ---- --- Add or remove an item from a list function BRC.util.add_or_remove(list, item, add) if add then list[#list + 1] = item else util.remove(list, item) end end --- Sorts the keys of a dictionary/map: vars before tables, then alphabetically by key -- If a list is passed, will assume it's a list of global variable names function BRC.util.get_sorted_keys(map_or_list) local keys_vars = {} local keys_tables = {} if BRC.util.is_map(map_or_list) then for key, v in pairs(map_or_list) do table.insert(type(v) == "table" and keys_tables or keys_vars, key) end else for _, key in ipairs(map_or_list) do table.insert(type(_G[key]) == "table" and keys_tables or keys_vars, key) end end util.sort(keys_vars) util.sort(keys_tables) util.append(keys_vars, keys_tables) return keys_vars end function BRC.util.is_list(value) return value and type(value) == "table" and #value > 0 end function BRC.util.is_map(value) return value and type(value) == "table" and next(value) ~= nil and #value == 0 end --- Compare version (x.y) to crawl version. Return true if v1 <= crawl version. function BRC.util.version_is_valid(v1) local crawl_v = crawl.version("major") local cv_parts = { string.match(crawl_v, "([0-9]+)%.([0-9]+)" ) } local v1_parts = { string.match(v1, "([0-9]+)%.([0-9]+)" ) } return v1_parts[1] < cv_parts[1] or (v1_parts[1] == cv_parts[1] and v1_parts[2] <= cv_parts[2]) end } ##### lua/util/text.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC utility module -- @module BRC.txt -- Text and string functions. -- Creates string:contains() for all strings --------------------------------------------------------------------------------------------------- BRC.txt = {} ---- Text parsing ---- --- Search for text within a string, without Lua pattern matching. -- @return (bool) True if text is found, false otherwise. function BRC.txt.contains(self, text) return self:find(text, 1, true) ~= nil end --- Connect string:contains() to BRC.txt.contains() getmetatable("").__index.contains = BRC.txt.contains --- Parse the slot and item name from an item pickup message (e.g. "w - a +0 short sword") -- @return (string, int) The item name and slot index function BRC.txt.get_pickup_info(text) local cleaned = BRC.txt.clean(text) if cleaned:sub(2, 4) ~= " - " then return nil end return cleaned:sub(5, #cleaned), items.letter_to_index(cleaned:sub(1, 1)) end ---- Color functions - Usage: BRC.txt.white("Hello"), or BRC.txt["15"]("Hello") ---- for k, color in pairs(BRC.COL) do BRC.txt[k] = function(text) return string.format("<%s>%s", color, tostring(text), color) end BRC.txt[color] = BRC.txt[k] end ---- String manipulation ---- function BRC.txt.capitalize(s) if not s or s == "" then return s end return string.upper(string.sub(s, 1, 1)) .. string.lower(string.sub(s, 2)) end --- Remove newlines and tags from text function BRC.txt.clean(text) if type(text) ~= "string" then return text end return text:gsub("\n", ""):gsub("<[^>]*>", "") end function BRC.txt.wrap(text, wrapper, no_space) if not wrapper then return text end return table.concat({ wrapper, text, wrapper }, no_space and "" or " ") end ---- Conversion to string ---- function BRC.txt.int2char(num) return string.char(string.byte("a") + num) end function BRC.txt.serialize_chk_lua_save() local tokens = { BRC.txt.lightblue("\n---CHK_LUA_SAVE---") } for _, func in ipairs(chk_lua_save) do local result = func() if result and #result > 0 then tokens[#tokens + 1] = util.trim(result) end end return table.concat(tokens, "\n") end function BRC.txt.serialize_inventory() local tokens = { BRC.txt.lightcyan("\n---INVENTORY---\n") } for _, inv in ipairs(items.inventory()) do local base = inv.name("base") or "N/A" local cls = inv.class(true) or "N/A" local st = inv.subtype() or "N/A" tokens[#tokens + 1] = string.format("%s: (%s) Qual: %s", inv.slot, inv.quantity, inv.name()) tokens[#tokens + 1] = string.format(" Base: %s Class: %s, Subtype: %s\n", base, cls, st) end return table.concat(tokens) end ---- BRC.txt.tostr() local helper functions ---- local function limit_lines(str) if not str or str == "" then return str end if BRC.Config.dump.max_lines_per_table and BRC.Config.dump.max_lines_per_table > 0 then local lines = 1 str:gsub("\n", function() lines = lines + 1 end) if lines > BRC.Config.dump.max_lines_per_table then return string.format("{ %s lines... }", lines) end end return str end local function tostr_string(var, pretty) local s if var:contains("\n") then s = string.format("[[\n%s]]", var) else s = '"' .. var:gsub('"', "") .. '"' end if not pretty then return s end -- Replace > and < to display the color tags instead of colored text return s:gsub(">", "TempGT"):gsub("<", "TempLT"):gsub("TempGT", ""):gsub("TempLT", "") end local function tostr_list(var, pretty, indents) local tokens = {} for _, v in ipairs(var) do tokens[#tokens + 1] = limit_lines(BRC.txt.tostr(v, pretty, indents + 1)) end if #tokens < 4 and not util.exists(var, function(t) return type(t) == "table" end) then return "{ " .. table.concat(tokens, ", ") .. " }" else local INDENT = string.rep(" ", indents) local CHILD_INDENT = string.rep(" ", indents + 1) local LIST_SEP = ",\n" .. CHILD_INDENT return "{\n" .. CHILD_INDENT .. table.concat(tokens, LIST_SEP) .. "\n" .. INDENT .. "}" end end local function tostr_map(var, pretty, indents) local tokens = {} if pretty then local keys = BRC.util.get_sorted_keys(var) local contains_table = false for i = 1, #keys do local v = limit_lines(BRC.txt.tostr(var[keys[i]], true, indents + 1)) if v then if type(var[keys[i]]) == "table" then contains_table = true tokens[#tokens + 1] = string.format('["%s"] = %s', keys[i], v) else tokens[#tokens + 1] = string.format("%s = %s", keys[i], v) end end end if #tokens <= 2 and not contains_table then return "{ " .. table.concat(tokens, ", ") .. " }" end else for k, v in pairs(var) do local val_str = BRC.txt.tostr(v, pretty, indents + 1) if val_str then tokens[#tokens + 1] = '["' .. k .. '"] = ' .. val_str end end end local INDENT = string.rep(" ", indents) local CHILD_INDENT = string.rep(" ", indents + 1) local LIST_SEP = ",\n" .. CHILD_INDENT return "{\n" .. CHILD_INDENT .. table.concat(tokens, LIST_SEP) .. "\n" .. INDENT .. "}" end --- Serializes a variable to a string, for chk_lua_save or data dumps. -- @param pretty (optional bool) format for human readability -- @param _indents (optional int) Used internally to format multi-line tables function BRC.txt.tostr(var, pretty, _indents) local var_type = type(var) if var_type == "string" then return tostr_string(var, pretty) elseif var_type == "table" then _indents = _indents or 0 if BRC.util.is_list(var) then return tostr_list(var, pretty, _indents) elseif BRC.util.is_map(var) then return tostr_map(var, pretty, _indents) else return "{}" end end if BRC.Config.dump.omit_pointers and (var_type == "function" or var_type == "userdata") then return nil end return tostring(var) -- fallback to tostring() end } ##### lua/util/mpr.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC utility module -- @module BRC.mpr -- Wrappers around crawl.mpr for message printing : Colors, formatted messages, message queue, etc. --------------------------------------------------------------------------------------------------- BRC.mpr = {} BRC.mpr.brc_prefix = BRC.txt.darkgrey("[BRC] ") ---- mpr queue (displayed after all other messages for the turn) ---- local _mpr_queue = {} --- Queue a message to dispay at the end of ready() function BRC.mpr.que(msg, color, channel) BRC.mpr.que_optmore(false, msg, color, channel) end --- Queue msg w/ conditional force_more_message -- send with empty msg for a delayed force_more_message function BRC.mpr.que_optmore(show_more, msg, msg_color, channel) for _, q in ipairs(_mpr_queue) do if q.m == msg and q.ch == channel and q.more == show_more then return end end msg_color = msg_color or BRC.COL.lightgrey if not msg or #msg == 0 then msg = "" else msg = BRC.txt[msg_color](msg) end _mpr_queue[#_mpr_queue + 1] = { m = msg, ch = channel, more = show_more } end --- Display queued messages and clear the queue function BRC.mpr.consume_queue() local do_more = util.exists(_mpr_queue, function(q) return q.more end) -- stop_activity() can generate more autopickups, and thus more queue'd messages if do_more then you.stop_activity() end for _, msg in ipairs(_mpr_queue) do if msg.m and #msg.m > 0 then crawl.mpr(tostring(msg.m), msg.ch) crawl.flush_prev_message() end end _mpr_queue = {} if do_more then crawl.redraw_screen() crawl.more() end end ---- Color functions - Usage: BRC.mpr.white("Hello"), or BRC.mpr["15"]("Hello") ---- for k, color in pairs(BRC.COL) do BRC.mpr[k] = function(msg, channel) crawl.mpr(BRC.txt[color](msg), channel) crawl.flush_prev_message() end BRC.mpr[color] = BRC.mpr[k] end ---- Pre-formatted logging functions ---- local function log_message(message, context, msg_color) -- Avoid referencing BRC, to stay robust during startup msg_color = msg_color or "lightgrey" local msg = BRC.mpr.brc_prefix .. tostring(message) if context then msg = string.format("%s (%s)", msg, tostring(context)) end crawl.mpr(string.format("<%s>%s", msg_color, msg, msg_color)) crawl.flush_prev_message() end --- Primary function for displaying errors. Includes a force_more_message by default. -- @param context (optional) Additional context. No context if params are (string, bool). function BRC.mpr.error(message, context, skip_more) if type(context) == "boolean" and skip_more == nil then skip_more = context context = nil end -- Stop and clean up state before displaying the error BRC.opt.clear_single_turn_mutes() crawl.flush_input() you.stop_activity() log_message("(Error) " .. message, context, BRC.COL.lightred) if context then message = message .. " (" .. context .. ")" end print(message) if not skip_more then crawl.redraw_screen() crawl.more() end if BRC.Config.mpr.take_note_on_error then crawl.take_note("[BRC] (Error) " .. tostring(message)) end if BRC.Config.mpr.logs_to_stderr then crawl.stderr(BRC.mpr.brc_prefix .. "(Error) " .. message) end end function BRC.mpr.warning(message, context) log_message(message, context, BRC.COL.yellow) you.stop_activity() if BRC.Config.mpr.logs_to_stderr then crawl.stderr(BRC.mpr.brc_prefix .. "(Warning) " .. message) end end function BRC.mpr.info(message, context) log_message(message, context, BRC.COL.darkgrey) end function BRC.mpr.debug(message, context) if BRC.Config.mpr.show_debug_messages then log_message(message, context, BRC.COL.lightblue) end if BRC.Config.mpr.logs_to_stderr then crawl.stderr(BRC.mpr.brc_prefix .. "(Debug) " .. message) end end function BRC.mpr.okay(suffix) BRC.mpr.darkgrey("Okay, then." .. (suffix and " " .. suffix or "")) end --- Print a variable's stringified value function BRC.mpr.tostr(v) crawl.mpr(BRC.txt.tostr(v, true)) end ---- Messages with stop or force_more ---- --- Message plus stop travel/activity function BRC.mpr.stop(msg, color, channel) BRC.mpr[color or BRC.COL.lightgrey](msg, channel) you.stop_activity() end --- Message as a force_more_message function BRC.mpr.more(msg, color, channel) BRC.mpr[color or BRC.COL.lightgrey](msg, channel) you.stop_activity() crawl.redraw_screen() crawl.more() end --- Conditional force_more_message function BRC.mpr.optmore(show_more, msg, color, channel) if show_more then BRC.mpr.more(msg, color, channel) else BRC.mpr[color or BRC.COL.lightgrey](msg, channel) end end ---- Prompts for user input ---- --- Get a selection from the user, from a list of options function BRC.mpr.select(msg, options, color) if not (type(options) == "table" and #options > 0) then BRC.mpr.error("No options provided for BRC.mpr.select") return false end msg = msg .. ":\n" for i, option in ipairs(options) do msg = msg .. string.format("%s: %s\n", i, BRC.txt.white(option)) end BRC.mpr[color or BRC.COL.lightcyan](msg, "prompt") for _ = 1, 10 do local res = crawl.getch() if res then local num = res - string.byte("0") if num > 0 and num <= #options then return options[num] end end BRC.mpr.magenta("Invalid option, try again.") end BRC.mpr.lightmagenta("Fine then. Using option 1: " .. options[1]) return options[1] end --- Get a yes/no response function BRC.mpr.yesno(msg, color, capital_only) msg = string.format("%s (%s)", msg, capital_only and "Y/N" or "y/n") for i = 1, 10 do BRC.mpr[color or BRC.COL.lightgrey](msg, "prompt") local res = crawl.getch() if res and res >= 0 and res <= 255 then local c = string.char(res) if c == "Y" or c == "y" and not capital_only then return true end if c == "N" or c == "n" and not capital_only then return false end end if i == 1 and capital_only then msg = "[CAPS ONLY] " .. msg end end BRC.mpr.lightmagenta("Feels like a no.") return false end } ##### lua/util/item.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC utility module -- @module BRC.it -- Utilities for checking item types/attributes, and retrieving item-related information. --------------------------------------------------------------------------------------------------- BRC.it = {} function BRC.it.get_xy(name, radius) local r = radius or you.los() for dx = -r, r do for dy = -r, r do for _, fl in ipairs(items.get_items_at(dx, dy) or {}) do if fl.name() == name then return dx, dy end end end end end function BRC.it.get_staff_school(it) for k, v in pairs(BRC.MAGIC_SCHOOLS) do if it.subtype() == k then return v end end end function BRC.it.get_talisman_min_level(it) if it.name() == "protean talisman" then return 6 end -- Parse the item description local tokens = crawl.split(it.description, "\n") for _, v in ipairs(tokens) do if v:sub(1, 4) == "Min " then local start_pos = v:find("%d", 4) if start_pos then local end_pos = v:find("[^%d]", start_pos) return tonumber(v:sub(start_pos, end_pos - 1)) end end end BRC.mpr.error("Failed to find skill required for: " .. it.name()) return -1 end --- @return table All items whose slot is idx function BRC.it.all_inslot(idx) return util.filter(function(i) return i.slot == idx end, items.inventory()) end ---- Simple boolean checks ---- function BRC.it.is_amulet(it) return it and it.name("base") == "amulet" end function BRC.it.is_armour(it, include_orbs) return it and it.class(true) == "armour" and (include_orbs or not BRC.it.is_orb(it)) end function BRC.it.is_aux_armour(it) return BRC.it.is_armour(it) and not (BRC.it.is_body_armour(it) or BRC.it.is_shield(it)) end function BRC.it.is_body_armour(it) return it and it.subtype() == "body" end function BRC.it.is_jewellery(it) return it and it.class(true) == "jewellery" end function BRC.it.is_magic_staff(it) return it and it.class and it.class(true) == "magical staff" end function BRC.it.is_ring(it) return it and it.name("base") == "ring" end function BRC.it.is_scarf(it) return BRC.it.is_armour(it) and it.subtype() == "cloak" and it.name():contains("scarf") end function BRC.it.is_shield(it) return it and it.is_shield() end function BRC.it.is_talisman(it) return it and it.class(true) == "talisman" end function BRC.it.is_orb(it) return it and it.subtype() == "offhand" and not it.is_shield() end function BRC.it.is_polearm(it) return it and it.weap_skill:contains("Polearms") end } ##### lua/util/you.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC utility module -- @module BRC.you -- Utilities for checking character attributes and state --------------------------------------------------------------------------------------------------- BRC.you = {} --- Get mutation level, explicitly specifying crawl's optional params. -- @param innate_only boolean (optional) True to count only innate mutations, else count all. function BRC.you.mut_lvl(mutation, innate_only) return you.get_base_mutation_level(mutation, true, not innate_only, not innate_only) end ---- Boolean attributes ---- function BRC.you.by_slimy_wall() for x = -1, 1 do for y = -1, 1 do if view.feature_at(x, y) == "slimy_wall" then return true end end end return false end function BRC.you.free_offhand() if BRC.you.mut_lvl("missing a hand") > 0 then return true end return not items.equipped_at("offhand") end function BRC.you.have_shield() return BRC.it.is_shield(items.equipped_at("offhand")) end function BRC.you.in_hell(exclude_vestibule) local branch = you.branch() if exclude_vestibule and branch == "Hell" then return false end return util.contains(BRC.HELL_BRANCHES, branch) end function BRC.you.miasma_immune() if util.contains(BRC.UNDEAD_RACES, you.race()) then return true end if util.contains(BRC.NONLIVING_RACES, you.race()) then return true end return false end function BRC.you.mutation_immune() return util.contains(BRC.UNDEAD_RACES, you.race()) end function BRC.you.shapeshifting_skill() local skill = you.skill("Shapeshifting") local AMU = "amulet of wildshape" if util.exists(items.inventory(), function(i) return i.name("qual") == AMU end) then return skill + 5 end return skill end function BRC.you.size_penalty() if util.contains(BRC.LITTLE_RACES, you.race()) then return BRC.SIZE_PENALTY.LITTLE elseif util.contains(BRC.SMALL_RACES, you.race()) then return BRC.SIZE_PENALTY.SMALL elseif util.contains(BRC.LARGE_RACES, you.race()) then return BRC.SIZE_PENALTY.LARGE else return BRC.SIZE_PENALTY.NORMAL end end function BRC.you.unarmed_attack_delay() return 1 - you.skill("Unarmed Combat") / 54 end function BRC.you.zero_stat() return you.strength() <= 0 or you.dexterity() <= 0 or you.intelligence() <= 0 end ---- Equipment slot functions ---- --- The number of equipment slots available for the item (usually 1) function BRC.you.num_eq_slots(it) local player_race = you.race() if it.is_weapon then return player_race == "Coglin" and 2 or 1 end if BRC.it.is_aux_armour(it) then if player_race == "Formicid" then return it.subtype() == "gloves" and 2 or 1 end return player_race == "Poltergeist" and 6 or 1 end return 1 end --- Get all equipped items in the slot type for the item -- @return (table, int) - items, and num_slots (max size the list can be) -- This is usually a list of length 1, with num_slots==1 function BRC.you.equipped_at(it) local all_aux = {} local num_slots = BRC.you.num_eq_slots(it) local slot_name = it.is_weapon and "weapon" or BRC.it.is_body_armour(it) and "armour" or it.subtype() for i = 1, num_slots do local eq = items.equipped_at(slot_name, i) all_aux[#all_aux + 1] = eq end return all_aux, num_slots end ---- Skill attributes ---- function BRC.you.top_wpn_skill() local max_weap_skill = 0 local pref = nil for _, v in ipairs(BRC.WEAP_SCHOOLS) do if BRC.you.skill(v) > max_weap_skill then max_weap_skill = BRC.you.skill(v) pref = v end end return pref end --- Get the max skill for a comma-separated list of skills function BRC.you.skill(skill) if skill and not skill:contains(",") then return you.skill(skill) end local skills = crawl.split(skill, ",") local max = 0 for _, s in ipairs(skills) do if you.skill(s) > max then max = you.skill(s) end end return max end function BRC.you.skill_with(it) if BRC.it.is_magic_staff(it) then return math.max(BRC.you.skill(BRC.it.get_staff_school(it)), BRC.you.skill("Staves")) end if it.is_weapon then return BRC.you.skill(it.weap_skill) end if BRC.it.is_body_armour(it) then return BRC.you.skill("Armour") end if BRC.it.is_shield(it) then return BRC.you.skill("Shields") end if BRC.it.is_talisman(it) then return BRC.you.shapeshifting_skill() end return nil end } ##### lua/util/equipment.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC utility module -- @module BRC.eq -- This module contains 2 main types of functions: -- 1. Mirroring crawl calculations, like weapon damage, armour penalty, etc. -- 2. Design choices that aren't as generalizable as other util functions. -- Ex: Dragon scales are always considered branded, DPS calculation is an approximation, etc. -- Ex: is_risky(), is_useless_ego(), get_ego(), get_hands(), etc. --------------------------------------------------------------------------------------------------- BRC.eq = {} ---- Local functions (Mostly mirroring crawl calculations) ---- -- Last verified against: current crawl master branch (0.34-a0-786-ge5b59a6c5f) local function get_unadjusted_armour_pen(encumb) local pen = encumb - 2 * BRC.you.mut_lvl("sturdy frame") if pen > 0 then return pen end return 0 end local function get_adjusted_armour_pen(encumb, str) local base_pen = get_unadjusted_armour_pen(encumb) return 2 * base_pen * base_pen * (45 - you.skill("Armour")) / 45 / (5 * (str + 3)) end local function get_adjusted_dodge_bonus(encumb, str, dex) local size_factor = -2 * BRC.you.size_penalty() local dodge_bonus = 8 * (10 + you.skill("Dodging") * dex) / (20 - size_factor) / 10 local armour_dodge_penalty = get_unadjusted_armour_pen(encumb) - 3 if armour_dodge_penalty <= 0 then return dodge_bonus end if armour_dodge_penalty >= str then return dodge_bonus * str / (armour_dodge_penalty * 2) end return dodge_bonus - dodge_bonus * armour_dodge_penalty / (str * 2) end local function get_shield_penalty(sh) return 2 * sh.encumbrance * sh.encumbrance * (27 - you.skill("Shields")) / 27 / (25 + 5 * you.strength()) end local function get_branded_delay(delay, ego) if not ego then return delay end if ego == "speed" then return delay * 2 / 3 elseif ego == "heavy" then return delay * 1.5 end return delay end local function get_weap_min_delay(it) -- This is an abbreviated version of the actual calculation. -- Doesn't check brand or delay >=3, which are covered in get_weap_delay() if it.artefact and it.name("qual"):contains("woodcutter's axe") then return it.delay end local min_delay = math.floor(it.delay / 2) if it.weap_skill == "Short Blades" then return 5 end if it.is_ranged then local basename = it.name("base") local is_2h_ranged = basename:contains("crossbow") or basename:contains("arbalest") if is_2h_ranged then return math.max(min_delay, 10) end end return math.min(min_delay, 7) end local function get_slay_bonuses() local sum = 0 -- Slots can go as high as 18 afaict for i = 0, 20 do local inv = items.equipped_at(i) if inv then if BRC.it.is_ring(inv) then if inv.artefact then local name = inv.name() local idx = name:find("Slay", 1, true) if idx then local slay = tonumber(name:sub(idx + 5, idx + 5)) if slay == 1 then local next_digit = tonumber(name:sub(idx + 6, idx + 6)) if next_digit then slay = 10 + next_digit end end if name:sub(idx + 4, idx + 4) == "+" then sum = sum + slay else sum = sum - slay end end elseif BRC.eq.get_ego(inv) == "Slay" then sum = sum + inv.plus end elseif inv.artefact and (BRC.it.is_armour(inv, true) or BRC.it.is_amulet(inv)) then local slay = inv.artprops["Slay"] if slay then sum = sum + slay end end end end if you.race() == "Demonspawn" then sum = sum + 3 * BRC.you.mut_lvl("augmentation") sum = sum + BRC.you.mut_lvl("sharp scales") end return sum end --- Gets the updated stats after equipping an item -- @param stats (table) Keys are artefact properties, values are the current values -- If multiple equip slots available, assumes no item is removed. -- @return (table) New stats table with updated values (original table is not modified) local function get_stats_with_item(it, stats) local new_stats = util.copy_table(stats) local cur = items.equipped_at(it.equip_type) if not cur or it.equipped then return new_stats end if cur.artefact and BRC.you.num_eq_slots(it) == 1 then for k, _ in pairs(new_stats) do new_stats[k] = new_stats[k] - (cur.artprops[k] or 0) end end if it.artefact then for k, _ in pairs(new_stats) do new_stats[k] = new_stats[k] + (it.artprops[k] or 0) end end return new_stats end --- Get change in SH and EV when switching to shield local function get_delta_sh_ev(it) local it_sh = BRC.eq.get_sh(it) local it_ev = -get_shield_penalty(it) local cur = items.equipped_at(it.equip_type) if not cur or it.equipped then return it_sh, it_ev else return it_sh - BRC.eq.get_sh(cur), it_ev + get_shield_penalty(cur) end end --- Get change in AC and EV when switching to armour local function get_delta_ac_ev(it) local it_ac = BRC.eq.get_ac(it) local it_ev = BRC.eq.get_armour_ev(it) local cur = items.equipped_at(it.equip_type) if not cur or it.equipped or BRC.you.num_eq_slots(it) > 1 then return it_ac, it_ev else return it_ac - BRC.eq.get_ac(cur), it_ev - BRC.eq.get_armour_ev(cur) end end --- Calculate weapon damage using the brand bonuses in BRC.Config.BrandBonus -- @param dmg_type int Matches a damage type defined in BRC.DMG_TYPE: -- (1) unbranded: Only "heavy" is included -- (2) plain: Include non-elemental damaging brands -- (3) branded: Include all damaging brands -- (4) scoring: Include heuristics from 'subtle' brands local function get_dmg_with_brand_bonus(ego, base_dmg, it_plus, dmg_type) if not ego then return base_dmg + it_plus end -- Check if brand should apply based on damage type local should_apply = ( dmg_type == BRC.DMG_TYPE.unbranded and ego == "heavy" or dmg_type == BRC.DMG_TYPE.plain and util.contains(BRC.NON_ELEMENTAL_DMG_EGOS, ego) or dmg_type >= BRC.DMG_TYPE.branded and BRC.Config.BrandBonus[ego] or dmg_type == BRC.DMG_TYPE.scoring and BRC.Config.BrandBonus.subtle[ego] ) if should_apply then local bonus = BRC.Config.BrandBonus[ego] or BRC.Config.BrandBonus.subtle[ego] return bonus.factor * base_dmg + it_plus + bonus.offset else return base_dmg + it_plus end end ---- Stat formatting functions ---- --- Format damage values for consistent display width (4 characters) local function format_dmg(dmg) if dmg < 10 then return string.format("%.2f", dmg) end if dmg < 100 then return string.format("%.1f", dmg) end return string.format("%.0f ", dmg) end --- Format stat string for display or inscription local function format_stat(abbr, val, is_worn) local stat_str = string.format("%.1f", val) if val < 0 then return string.format("%s%s", abbr, stat_str) elseif is_worn then return string.format("%s:%s", abbr, stat_str) else return string.format("%s+%s", abbr, stat_str) end end --- Get armour stats as strings -- @return (string, string) AC or SH, and EV. If not worn, returns deltas from the worn item stats function BRC.eq.arm_stats(it) if not BRC.it.is_armour(it) then return "", "" end if BRC.it.is_shield(it) then local sh_delta, ev_delta = get_delta_sh_ev(it) local sh_str = format_stat("SH", sh_delta, it.equipped) local ev_str = format_stat("EV", ev_delta, it.equipped) return sh_str, ev_str else local ac_delta, ev_delta = get_delta_ac_ev(it) local ac_str = format_stat("AC", ac_delta, it.equipped) if not BRC.it.is_body_armour(it) then return ac_str end local ev_str = format_stat("EV", ev_delta, it.equipped) return ac_str, ev_str end end --- Get weapon stats as a string -- @return (string) DPS, damage, delay, and accuracy function BRC.eq.wpn_stats(it, dmg_type, skip_dps) if not it.is_weapon then return end if not dmg_type then -- Default to pulling from inscribe-stats config, if it exists. Else use plain. if f_inscribe_stats and f_inscribe_stats.Config then if type(f_inscribe_stats.Config.dmg_type) == "string" then dmg_type = BRC.DMG_TYPE[f_inscribe_stats.Config.dmg_type] else dmg_type = f_inscribe_stats.Config.dmg_type end else dmg_type = BRC.DMG_TYPE.plain end end local dmg = format_dmg(BRC.eq.get_avg_dmg(it, dmg_type)) local delay = BRC.eq.get_weap_delay(it) local delay_str = string.format("%.1f", delay) if delay < 1 then delay_str = string.format("%.2f", delay) delay_str = delay_str:sub(2, #delay_str) end local dps = format_dmg(dmg / delay) local acc = it.accuracy + (it.plus or 0) if acc >= 0 then acc = "+" .. acc end --TODO: This would be nice if it worked in all UIs --return string.format("DPS=%s (%s/%s) Ac%s", dps, dmg, delay_str, acc) if skip_dps then return string.format("Dmg=%s/%s A%s", dmg, delay_str, acc) end return string.format("DPS=%s (%s/%s) A%s", dps, dmg, delay_str, acc) end ---- Armour stats ---- function BRC.eq.get_ac(it) local it_plus = it.plus or 0 if it.artefact then local art_ac = it.artprops["AC"] if art_ac then it_plus = it_plus + art_ac end end local ac = it.ac * (1 + you.skill("Armour") / 22) + it_plus if not BRC.it.is_body_armour(it) then return ac end if BRC.you.mut_lvl("deformed body") + BRC.you.mut_lvl("pseudopods") > 0 then ac = ac * 0.6 end return ac end --- Compute an armour's impact on EV, including stat changes from wearing/removing artefacts function BRC.eq.get_armour_ev(it) local cur = { Str = you.strength(), Dex = you.dexterity(), EV = 0 } local worn = get_stats_with_item(it, cur) if worn.Str <= 0 then worn.Str = 1 end local bonus = get_adjusted_dodge_bonus(it.encumbrance, worn.Str, worn.Dex) if cur.Str <= 0 then cur.Str = 1 end local naked_bonus = get_adjusted_dodge_bonus(0, cur.Str, cur.Dex) return bonus - naked_bonus + worn.EV - get_adjusted_armour_pen(it.encumbrance, worn.Str) end function BRC.eq.get_sh(it) local stats = get_stats_with_item(it, { Dex = you.dexterity() }) local it_plus = it.plus or 0 local sh_skill = you.skill("Shields") local base_sh = it.ac * 2 local shield = base_sh * (50 + sh_skill * 5 / 2) shield = shield + 200 * it_plus shield = shield + 38 * (sh_skill + 3 + stats.Dex * (base_sh + 13) / 26) return shield / 200 end ---- Weapon stats ---- function BRC.eq.get_weap_delay(it) local delay = it.delay - BRC.you.skill(it.weap_skill) / 2 delay = math.max(delay, get_weap_min_delay(it)) delay = get_branded_delay(delay, BRC.eq.get_ego(it)) delay = math.max(delay, 3) local sh = items.equipped_at("offhand") if BRC.it.is_shield(sh) then delay = delay + get_shield_penalty(sh) end if it.is_ranged then local worn = items.equipped_at("armour") if worn then local str = you.strength() local cur = items.equipped_at("weapon") if cur and cur ~= it and cur.artefact then if it.artefact and it.artprops["Str"] then str = str + it.artprops["Str"] end if cur.artefact and cur.artprops["Str"] then str = str - cur.artprops["Str"] end end delay = delay + get_adjusted_armour_pen(worn.encumbrance, str) end end return delay / 10 end --- Get weapon damage (average), including stat/slay changes when swapping from current weapon. -- Aux attacks not included function BRC.eq.get_avg_dmg(it, dmg_type) dmg_type = dmg_type or BRC.DMG_TYPE.scoring local it_plus = (it.plus or 0) + get_slay_bonuses() local stats = { Str = you.strength(), Dex = you.dexterity(), Slay = it_plus } stats = get_stats_with_item(it, stats) local stat = (it.is_ranged or it.weap_skill:contains("Blades")) and stats.Dex or stats.Str local stat_mod = 0.75 + 0.025 * stat local skill_mod = (1 + BRC.you.skill(it.weap_skill) / 50) * (1 + you.skill("Fighting") / 60) local base_dmg = it.damage * stat_mod * skill_mod if BRC.it.is_magic_staff(it) then return base_dmg + stats.Slay + BRC.eq.get_staff_bonus_dmg(it, dmg_type) else return get_dmg_with_brand_bonus(BRC.eq.get_ego(it), base_dmg, stats.Slay, dmg_type) end end function BRC.eq.get_dps(it, dmg_type) if not dmg_type then dmg_type = BRC.DMG_TYPE.scoring end return BRC.eq.get_avg_dmg(it, dmg_type) / BRC.eq.get_weap_delay(it) end --- Calculate expected damage output from a staff -- @return (number) Damage * chance, (number) damage on proc, (number) chance to proc function BRC.eq.get_staff_bonus_dmg(it, dmg_type) local result = nil if dmg_type == BRC.DMG_TYPE.unbranded then result = 0 end if dmg_type == BRC.DMG_TYPE.plain then local basename = it.name("base") if basename ~= "staff of earth" and basename ~= "staff of conjuration" then result = 0 end end local spell_skill = BRC.you.skill(BRC.it.get_staff_school(it)) local evo_skill = you.skill("Evocations") local chance = (2 * evo_skill + spell_skill) / 30 if chance > 1 then chance = 1 end -- 0.75 is an acceptable approximation; most commonly 63/80 -- Varies by staff type in sometimes complex ways local dmg = 3 / 4 * (evo_skill / 2 + spell_skill) result = result or dmg * chance return result, dmg, chance end ---- Item properties ---- --- Get the ego of an item, with custom logic: -- Treat unusable egos as no ego. Always lowercase ego in return value. -- Include armours with innate effects (except steam dragon scales) -- Artefacts return their normal ego if they have one, else their name -- @param no_stat_only_egos (optional bool) Exclude egos that only affect speed/damage function BRC.eq.get_ego(it, no_stat_only_egos) local ego = it.ego(true) if ego then ego = ego:lower() if BRC.eq.is_useless_ego(ego) or (no_stat_only_egos and (ego == "speed" or ego == "heavy")) then return it.artefact and it.name() or nil end return ego end if BRC.it.is_body_armour(it) then local name = it.name("qual") local good_scales = name:contains("dragon scales") and not name:contains("steam") if name:contains("troll leather") or good_scales then return name end end return it.artefact and it.name() or nil end function BRC.eq.get_hands(it) if you.race() ~= "Formicid" then return it.hands end local st = it.subtype() if st == "giant club" or st == "giant spiked club" then return 2 end return 1 end function BRC.eq.is_risky(it) if it.artefact then for k, v in pairs(it.artprops) do if util.contains(BRC.ARTPROPS_BAD, k) or v < 0 then return true end end end local ego_name = BRC.eq.get_ego(it) return ego_name and util.contains(BRC.RISKY_EGOS, ego_name) end function BRC.eq.is_useless_ego(ego) if BRC.MAGIC_SCHOOLS[ego] then return BRC.Config.unskilled_egos_usable or you.skill(BRC.MAGIC_SCHOOLS[ego]) > 0 end local race = you.race() return ego == "holy" and util.contains(BRC.UNDEAD_RACES, race) or (ego == "rPois" or ego == "rpois" or ego == "poison resistance") and util.contains(BRC.POIS_RES_RACES, race) or ego == "pain" and you.skill("Necromancy") == 0 end } ##### lua/util/options.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC utility module -- @module BRC.opt -- Functions for setting crawl options and macros. --------------------------------------------------------------------------------------------------- BRC.opt = {} ---- Single turn mutes: Mute a message for the current turn only ---- local _single_turn_mutes = {} local _claimed_macro_keys = {} function BRC.opt.single_turn_mute(pattern) BRC.opt.message_mute(pattern, true) _single_turn_mutes[#_single_turn_mutes + 1] = pattern end function BRC.opt.clear_single_turn_mutes() util.foreach(_single_turn_mutes, function(m) BRC.opt.message_mute(m, false) end) _single_turn_mutes = {} end ---- crawl.setopt() wrappers ---- function BRC.opt.autopickup_exceptions(pattern, create) local op = create and "^=" or "-=" crawl.setopt(string.format("autopickup_exceptions %s %s", op, pattern)) end function BRC.opt.explore_stop(pattern, create) local op = create and "+=" or "-=" crawl.setopt(string.format("explore_stop %s %s", op, pattern)) end function BRC.opt.explore_stop_pickup_ignore(pattern, create) local op = create and "+=" or "-=" crawl.setopt(string.format("explore_stop_pickup_ignore %s %s", op, pattern)) end function BRC.opt.flash_screen_message(pattern, create) local op = create and "+=" or "-=" crawl.setopt(string.format("flash_screen_message %s %s", op, pattern)) end function BRC.opt.force_more_message(pattern, create) local op = create and "+=" or "-=" crawl.setopt(string.format("force_more_message %s %s", op, pattern)) end --- Bind a macro to a key. Function must be global and not a member of a module. -- If key is a number, it is converted to a keycode string. -- Passing an invalid function name will clear the macro for that key. function BRC.opt.macro(key, function_name, overwrite_existing) -- Format msg for debugging and keycode for crawl.setopt() local key_str = nil if type(key) == "number" then -- Try to convert to key name for better debug msg for k, v in pairs(BRC.KEYS) do if v == key then key_str = "<<< " .. k .. " >>" break end end -- Format keycode string for crawl.setopt() key = "\\{" .. key .. "}" if key_str == nil then key_str = "<<< \\" .. key .. " >>" end end -- The << >> formatting protects against crawl thinking '<' is a tag if key_str == nil then key_str = "<<< '" .. key .. "' >>" end if type(_G[function_name]) == "function" then if _claimed_macro_keys[key] and not overwrite_existing then BRC.mpr.debug("Macro key %s is already assigned to %s", key_str, _claimed_macro_keys[key]) return end crawl.setopt(string.format("macros += M %s ===%s", key, function_name)) _claimed_macro_keys[key] = function_name BRC.mpr.debug( string.format( "Assigned macro %s to key: %s", BRC.txt.magenta(function_name .. "()"), BRC.txt.lightred(key_str) ) ) else function_name = _claimed_macro_keys[key] if not function_name then crawl.mpr("no function name found for key: " .. key) return end crawl.setopt(string.format("macros += M %s %s", key, key)) _claimed_macro_keys[key] = nil BRC.mpr.debug( string.format( "Cleared macro %s from key: %s", BRC.txt.magenta(function_name .. "()"), BRC.txt.lightred(key_str) ) ) end end function BRC.opt.clear_macros() for key, _ in pairs(_claimed_macro_keys) do BRC.opt.macro(key, nil, true) end _claimed_macro_keys = {} end function BRC.opt.message_mute(pattern, create) local op = create and "^=" or "-=" crawl.setopt(string.format("message_colour %s mute:%s", op, pattern)) end function BRC.opt.runrest_ignore_message(pattern, create) local op = create and "+=" or "-=" crawl.setopt(string.format("runrest_ignore_message %s %s", op, pattern)) end function BRC.opt.runrest_ignore_monster(pattern, create) local op = create and "+=" or "-=" crawl.setopt(string.format("runrest_ignore_monster %s %s", op, pattern)) end function BRC.opt.runrest_stop_message(pattern, create) local op = create and "+=" or "-=" crawl.setopt(string.format("runrest_stop_message %s %s", op, pattern)) end } ##### lua/core/data.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC core feature: data-manager -- @module BRC.Data -- Provides functions and maintenance for persistent variables that survive game restarts. -- Handles backup/restore functionality and error handling. --------------------------------------------------------------------------------------------------- BRC.Data = {} BRC.Data.BRC_FEATURE_NAME = "data-manager" -- Included as a feature for Config override ---- Local constants ---- local RESTORE_TABLE = "_brc_persist_restore_table" local MAX_RESTORE_RETRIES = 5 -- Maximum number of retry prompts for data restoration ---- Local variables ---- -- Init tables in declaration, so persist() can be called before init() local _failures = {} local _persist_names = {} local _default_values = {} local pushed_restore_table_creation = false -- Set this on file load, not on init() local cur_location ---- Initialization ---- function BRC.Data.init() cur_location = you.where() if type(c_persist.BRC) ~= "table" then c_persist.BRC = {} end end ---- Local functions ---- local function is_usable_backup() if type(c_persist.BRC) ~= "table" or type(c_persist.BRC.Backup) ~= "table" or c_persist.BRC.Backup.backup_name ~= you.name() or c_persist.BRC.Backup.backup_race ~= you.race() or c_persist.BRC.Backup.backup_class ~= you.class() then return false end local turn_diff = you.turns() - c_persist.BRC.Backup.backup_turn if turn_diff == 0 then return true end for _ = 1, MAX_RESTORE_RETRIES do if BRC.mpr.yesno("Use backup from " .. turn_diff .. " turns ago?") then return true end if BRC.mpr.yesno("Are you sure? Data will reset to defaults.") then return false end end return true end local function try_restore(failed_vars) if not is_usable_backup() then BRC.mpr.error("Unable to restore from backup. Persistent data reset to defaults.", true) BRC.mpr.info("For detailed startup info, set BRC.Config.mpr.show_debug_messages=True.") return false end for _, name in ipairs(failed_vars) do _default_values[name] = nil -- Avoid re-init warnings _G[name] = BRC.Data.persist(name, c_persist.BRC.Backup[name]) end BRC.mpr.green(BRC.mpr.brc_prefix .. "Restored data from backup.") return true end ---- Public API ---- --- Creates a persistent global variable or table, that retains its value through restarts. -- @usage `var = BRC.Data.persist("var", value)` -- @warning After restarting, the variable/table will not exist until this is called. -- @return any The current value (whether default or persisted) function BRC.Data.persist(name, default_value) local t = type(default_value) if not util.contains({ "table", "string", "number", "boolean", "nil" }, t) then BRC.mpr.error(string.format("Cannot persist %s. Default value is of type %s", name, t)) return default_value end -- Keep default value for re-init if _default_values[name] then BRC.mpr.warning("Multiple calls to BRC.Data.persist(" .. name .. ", ...)") end if type(default_value) == "table" then -- Preserve the user's original table (may be in a config, etc) default_value = util.copy_table(default_value) _default_values[name] = util.copy_table(default_value) else _default_values[name] = default_value end -- Try to restore from persistent restore table if you.turns() == 0 then _G[name] = default_value elseif _G[RESTORE_TABLE] and _G[RESTORE_TABLE][name] ~= nil then _G[name] = _G[RESTORE_TABLE][name] _G[RESTORE_TABLE][name] = nil elseif default_value ~= nil and not util.contains(_failures, name) then -- avoid inf loop _G[name] = default_value _failures[#_failures + 1] = name BRC.mpr.debug(BRC.txt.red(name .. " failed to restore from chk_lua_save.")) end -- Create persistent restore table on next startup if not pushed_restore_table_creation then table.insert(chk_lua_save, function() return RESTORE_TABLE .. " = {}\n" end) pushed_restore_table_creation = true end -- Set up persist on next startup if not util.contains(_persist_names, name) then _persist_names[#_persist_names + 1] = name table.insert(chk_lua_save, function() if _G[name] == nil then return "" end return RESTORE_TABLE .. "." .. name .. " = " .. BRC.txt.tostr(_G[name]) .. "\n" end) end return _G[name] end function BRC.Data.serialize() local tokens = { BRC.txt.lightmagenta("\n---PERSISTENT VARIABLES---\n") } local sorted_keys = BRC.util.get_sorted_keys(_persist_names) for _, key in ipairs(sorted_keys) do tokens[#tokens + 1] = string.format("%s = %s\n", key, BRC.txt.tostr(_G[key], true)) end return table.concat(tokens) end function BRC.Data.reset() if _persist_names then for _, name in ipairs(_persist_names) do if type(_default_values[name]) == "table" then _G[name] = util.copy_table(_default_values[name]) else _G[name] = _default_values[name] end end end BRC.mpr.warning("Reset all persistent data to default values.") end --- @return boolean|nil true if no persist errors, false if failed restore, nil if handled errors function BRC.Data.handle_persist_errors() if #_failures == 0 then return true end local msg = "%s persistent variables did not restore: (%s)" BRC.mpr.error(msg:format(#_failures, table.concat(_failures, ", ")), true) for _ = 1, MAX_RESTORE_RETRIES do if BRC.mpr.yesno("Try restoring from backup?") then break end if BRC.mpr.yesno("Are you sure? Data will reset to defaults.") then return nil end end -- Whether restore works or not, we should reset _failures local failed_vars = _failures _failures = {} if try_restore(failed_vars) then return nil end return false end -- Backup and Restore from c_persist.BRC.Backup function BRC.Data.backup() if type(c_persist.BRC) ~= "table" then c_persist.BRC = {} end c_persist.BRC.Backup = {} c_persist.BRC.Backup.backup_name = you.name() c_persist.BRC.Backup.backup_race = you.race() c_persist.BRC.Backup.backup_class = you.class() c_persist.BRC.Backup.backup_turn = you.turns() for _, name in ipairs(_persist_names) do c_persist.BRC.Backup[name] = _G[name] end end ---- Crawl hook functions ---- function BRC.Data.ready() if you.where() ~= cur_location and not you.have_orb() then cur_location = you.where() BRC.Data.backup() end end } ##### lua/core/config.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC core module -- @module BRC.Configs -- Manages user-defined configs and feature config overrides. -- -- TL;DR: Each feature has its own config, with default values for every field. -- To change those values, define the same fields in a user-defined config. -- -- When a user-defined config is loaded, it inherits values from BRC.Configs.Default. -- If a user-defined config defines a field, that value is used. -- If not defined in the config, the value in BRC.Configs.Default is used. -- If not defined in either, the default value in the feature config is used. -- @warning BRC.Configs.Default defines all fields not in a feature config. Do not remove them. --------------------------------------------------------------------------------------------------- BRC.Configs = {} ---- Persistent variables ---- brc_full_persistant_config = BRC.Data.persist("brc_full_persistant_config", nil) brc_config_name = BRC.Data.persist("brc_config_name", nil) ---- BRC Default Config - Every user-defined config inherits these -- Define config fields that aren't feature-specific, and set their default values BRC.Configs.Default = util.copy_table(BRC.Config) -- Include values from BRC.Config in _header.lua BRC.Configs.Default.BRC_CONFIG_NAME = "Default" BRC.Configs.Default.emojis = true -- Include emojis in alerts -- Does "Armour of " have an ego when skill is 0? BRC.Configs.Default.unskilled_egos_usable = false BRC.Configs.Default.mpr = { show_debug_messages = false, logs_to_stderr = false, take_note_on_error = true, -- Note BRC errors in the character file for debugging with char dump } -- BRC.Configs.Default.mpr (do not remove this comment) BRC.Configs.Default.dump = { max_lines_per_table = 200, -- Avoid huge tables (alert_monsters.Config.Alerts) in debug dumps omit_pointers = true, -- Don't dump functions and userdata (they only show a hex address) } -- BRC.Configs.Default.dump (do not remove this comment) --- How weapon damage is calculated for inscriptions+pickup/alert: (factor * DMG + offset) BRC.Configs.Default.BrandBonus = { chaos = { factor = 1.15, offset = 2.0 }, -- Approximate weighted average distort = { factor = 1.0, offset = 6.0 }, drain = { factor = 1.25, offset = 2.0 }, elec = { factor = 1.0, offset = 4.5 }, -- 3.5 on avg; fudged up for AC pen entangle = { factor = 1.1, offset = 3 }, flame = { factor = 1.25, offset = 0 }, freeze = { factor = 1.25, offset = 0 }, heavy = { factor = 1.8, offset = 0 }, -- Speed is accounted for elsewhere pain = { factor = 1.0, offset = you.skill("Necromancy") / 2 }, spect = { factor = 1.7, offset = 0 }, -- Fudged down for increased incoming damage sunder = { factor = 1.2, offset = 0 }, valour = { factor = 1.15, offset = 0 }, venom = { factor = 1.0, offset = 5.0 }, -- 5 dmg per poisoning subtle = { -- Values to use for weapon "scores" (not damage) antimagic = { factor = 1.1, offset = 0 }, concuss = { factor = 1.2, offset = 0 }, devious = { factor = 1.1, offset = 0 }, holy = { factor = 1.15, offset = 0 }, penet = { factor = 1.3, offset = 0 }, protect = { factor = 1.15, offset = 0 }, reap = { factor = 1.3, offset = 0 }, rebuke = { factor = 1.2, offset = 0 }, vamp = { factor = 1.2, offset = 0 }, }, } -- BRC.Configs.Default.BrandBonus (do not remove this comment) ---- Local functions ---- local function is_config_module(p) return p and type(p) == "table" and p.BRC_CONFIG_NAME and type(p.BRC_CONFIG_NAME) == "string" and #p.BRC_CONFIG_NAME > 0 end local function find_config_modules() for _, c in pairs(_G) do if is_config_module(c) then BRC.Configs[c.BRC_CONFIG_NAME] = c end end end --- @param input_name string "ask" or a config name -- @return string The valid name of a config local function get_valid_config_name(input_name) if #BRC.Configs == 1 then return util.keys(BRC.Configs)[1] end if type(input_name) ~= "string" then BRC.mpr.warning("Non-string config name: " .. tostring(input_name)) else local config_name = input_name:lower() if config_name == "ask" then -- If game has started, restore from the previously saved config name if you.turns() > 0 and brc_config_name then return get_valid_config_name(brc_config_name) end else -- Find by name in BRC.Configs, or display warning for k, _ in pairs(BRC.Configs) do if config_name == k:lower() then return k end end BRC.mpr.warning("Could not load config: " .. tostring(input_name)) end end local config_names = util.keys(BRC.Configs) util.sort(config_names) return BRC.mpr.select("Select a config", config_names) end local function execute_config_init(config) if type(config) ~= "table" then return end if type(config.init) == "function" then config.init() end end --- Override values in dest, with values from source. Take care not to clear existing tables. -- Does not override "init" local function override_table(dest, source) if type(source) ~= "table" then return end for key, value in pairs(source) do if BRC.util.is_map(value) then if not dest[key] then dest[key] = {} end override_table(dest[key], value) else dest[key] = value end end end --- Warn about unknown keys in the user config that don't match any feature or core config key. -- Catches typos like ["pickup-alerts"] (plural) or misspelled option names. local function validate_config_keys() local feature_modules = BRC.get_all_feature_modules() -- Collect known core keys from BRC.Configs.Default local core_keys = {} for key, _ in pairs(BRC.Configs.Default) do core_keys[key] = true end -- Check each key in BRC.Config for key, value in pairs(BRC.Config) do -- Skip known core keys, init functions, and non-string keys if core_keys[key] or key == "init" or type(key) ~= "string" then -- luacheck: ignore 542 elseif feature_modules[key] then -- Known feature name — validate its top-level sub-keys against defaults local defaults = feature_modules[key].ConfigDefaults or feature_modules[key].Config if type(value) == "table" and type(defaults) == "table" then for sub_key, _ in pairs(value) do if sub_key ~= "disabled" and sub_key ~= "init" and defaults[sub_key] == nil then BRC.mpr.debug(string.format( "Unknown config key: %s.%s", BRC.txt.lightcyan(key), BRC.txt.yellow(sub_key) )) end end end elseif type(value) == "table" and key:find("-") then -- Looks like a feature name (contains hyphen) but no such module exists BRC.mpr.warning(string.format( "Unknown feature in config: %s (not registered — possible typo?)", BRC.txt.yellow(key) )) end end end ---- Public API ---- --- Main config loading entry point -- @param config_name string name of a config function BRC.init_config(config_name) find_config_modules() BRC.Config = util.copy_table(BRC.Configs.Default) local name = get_valid_config_name(config_name or BRC.Config.to_use) if BRC.Configs[brc_config_name] and (name ~= brc_config_name) and you.turns() > 0 then if not BRC.mpr.yesno(string.format( "Switch config from %s to %s?", BRC.txt.lightcyan(brc_config_name), BRC.txt.lightcyan(name) )) then name = brc_config_name end end override_table(BRC.Config, BRC.Configs[name]) execute_config_init(BRC.Config) for _ , value in pairs(BRC.get_registered_features()) do BRC.process_feature_config(value) end brc_config_name = name local m = BRC.mpr.brc_prefix .. "Using config: " .. BRC.txt.lightcyan(BRC.Config.BRC_CONFIG_NAME) BRC.mpr.white(m) BRC.init_emojis() -- Updates constant values based on BRC.Config.emojis -- validate_config_keys() runs from BRC.init() after register_all_features(); running here -- would warn on every hyphenated feature key because _features is still empty. end --- Exposed for testing; not part of public API. BRC._validate_config_keys = validate_config_keys --- Process a feature config: Load defaults, then override w BRC.Config function BRC.process_feature_config(feature) if type(feature.ConfigDefaults) == "table" then feature.Config = util.copy_table(feature.ConfigDefaults) else -- Save the defaults after default init(), so they can be used later w a diff config feature.Config = feature.Config or {} local preinit_defaults = util.copy_table(feature.Config) execute_config_init(feature.Config) feature.ConfigDefaults = util.copy_table(feature.Config) -- If init() is overridden, restore to the pre-init defaults and only apply the new init() if type(BRC.Config[feature.BRC_FEATURE_NAME].init) == "function" then feature.Config = util.copy_table(preinit_defaults) end end override_table(feature.Config, BRC.Config[feature.BRC_FEATURE_NAME]) execute_config_init(BRC.Config[feature.BRC_FEATURE_NAME]) end --- Stringify BRC.Config and each feature config, with headers -- @return table of strings, one for each config section (1 big string will overflow crawl.mpr()) function BRC.serialize_config() local tokens = {} tokens[#tokens + 1] = BRC.txt.lightcyan("\n---BRC Config---\n") .. BRC.txt.tostr(BRC.Config, true) local all_features = BRC.get_registered_features() local keys = util.keys(all_features) util.sort(keys) for i = 1, #keys do local name = keys[i] local feature = all_features[name] if feature.Config then local header = BRC.txt.cyan("\n\n---Feature Config: " .. name .. "---\n") tokens[#tokens + 1] = header .. BRC.txt.tostr(feature.Config, true) end end return tokens end ---- Initialize BRC.Config for debugging during startup + data.persist() calls ---- override_table(BRC.Config, BRC.Configs.Default) } ##### lua/core/hotkey.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC core feature: hotkey -- @module BRC.Hotkey -- Manages the BRC hotkey, and provides functions to add actions to it. -- Adding an action to the hotkey will prompt the user after performing any specified checks. -- If user accepts, the defined action is performed. (Equip, pick up, read, move to, etc) --------------------------------------------------------------------------------------------------- BRC.Hotkey = {} BRC.Hotkey.BRC_FEATURE_NAME = "hotkey" BRC.Hotkey.Config = { key = { keycode = BRC.KEYS.ENTER, name = "[Enter]" }, skip_keycode = BRC.KEYS.ESC, -- ESC keycode equip_hotkey = true, -- Offer to equip after picking up equipment wait_for_safety = true, -- Don't expire the hotkey with monsters in view explore_clears_queue = true, -- Clear the hotkey queue on explore newline_before_hotkey = true, -- Add a newline before the hotkey message move_to_feature = { -- Hotkey for "move to _" when you find these features enter_temple = "Temple", enter_lair = "Lair", altar_ecumenical = "faded altar", enter_bailey = "flagged portal", enter_bazaar = "bazaar", enter_desolation = "crumbling gateway", enter_gauntlet = "gauntlet", enter_ice_cave = "frozen archway", enter_necropolis = "phantasmal passage", enter_ossuary = "sand-covered staircase", enter_sewer = "glowing drain", enter_trove = "trove of treasure", enter_volcano = "dark tunnel", enter_wizlab = "magical portal", enter_ziggurat = "ziggurat", }, } -- BRC.Hotkey.Config (do not remove this comment) ---- Local constants ---- local WAYPOINT_MUTES = { "Assign waypoint to what number", "Existing waypoints", "Delete which waypoint", "\\(\\d\\) ", "All waypoints deleted", "You're already here!", "Okay\\, then\\.", "Unknown command", "Waypoint \\d (re-)?assigned", "Waypoints will disappear", } -- WAYPOINT_MUTES (do not remove this comment) ---- Local variables ---- local action_queue local cur_action local delay_expire local cur_floor ---- Initialization ---- function BRC.Hotkey.init() action_queue = {} cur_action = nil delay_expire = false cur_floor = you.where() BRC.opt.macro(BRC.Hotkey.Config.key.keycode, "macro_brc_hotkey") BRC.opt.macro(BRC.Hotkey.Config.skip_keycode, "macro_brc_skip_hotkey") end ---- Local functions ---- local function display_cur_message() if BRC.Hotkey.Config.wait_for_safety and not you.feel_safe() then return end local msg = string.format("[BRC] Press %s to %s.", BRC.Hotkey.Config.key.name, cur_action.msg) BRC.mpr.que(msg, BRC.COL.darkgrey) end local function load_next_action() if #action_queue == 0 then return end cur_action = table.remove(action_queue, 1) if cur_action.condition() then cur_action.turn = you.turns() + 1 display_cur_message() delay_expire = false else cur_action = nil load_next_action() end end local function expire_cur_action() if cur_action then cur_action.cleanup() end cur_action = nil load_next_action() end --- Get the highest available waypoint slot local function get_avail_waypoint() for i = 9, 0, -1 do if not travel.waypoint_delta(i) then return i end end BRC.mpr.debug("No available waypoint slots. Clearing them all.") util.foreach(WAYPOINT_MUTES, function(m) BRC.opt.single_turn_mute(m) end) crawl.sendkeys({ BRC.util.cntl("w"), "d", "*" }) crawl.flush_input() end ---- Macro function: On BRC hotkey press ---- function macro_brc_hotkey() if cur_action then cur_action.action() else BRC.mpr.info("Unknown command (no action assigned to hotkey).") end end function macro_brc_skip_hotkey() if cur_action and (you.feel_safe() or not BRC.Hotkey.Config.wait_for_safety) then expire_cur_action() if not cur_action then BRC.mpr.info("Hotkey cleared.") end else crawl.sendkeys({ BRC.Hotkey.Config.skip_keycode }) crawl.flush_input() end end ---- Public API ---- --- Assign an action to the BRC hotkey -- @param prefix string - The action (equip/pickup/read/etc) -- @param suffix string - Printed after the action. Usually an item name -- @param push_front boolean - Push the action to the front of the queue -- @param f_action function - The function to call when the hotkey is pressed -- @param f_condition (optional function) return bool - If the action is still valid -- @param f_cleanup (optional function) - Function to call after hotkey pressed or skipped -- @return nil function BRC.Hotkey.set(prefix, suffix, push_front, f_action, f_condition, f_cleanup) local act = { msg = BRC.txt.lightgreen(prefix) .. (suffix and (" " .. BRC.txt.white(suffix)) or ""), action = f_action, condition = f_condition or function() return true end, cleanup = f_cleanup or function() end, } -- act (do not remove this comment) if push_front then table.insert(action_queue, 1, act) else table.insert(action_queue, act) end end function BRC.Hotkey.equip(it, push_front) if not (it.is_weapon or BRC.it.is_armour(it, true) or BRC.it.is_jewellery(it)) then return end local name = it.name():gsub(" {.*}", "") local condition = function() local inv_items = util.filter(function(i) return i.name():gsub(" {.*}", "") == name end, items.inventory()) return util.exists(inv_items, function(i) return not i.equipped end) end local do_equip = function() local inv_items = util.filter(function(i) return i.name():gsub(" {.*}", "") == name end, items.inventory()) local already_eq = false for i = 1, #inv_items do if inv_items[i].equipped then already_eq = true else inv_items[i]:equip() return end end if already_eq then BRC.mpr.info("Already equipped.") else BRC.mpr.error("Could not find unequipped item '" .. name .. "' in inventory.") end end BRC.Hotkey.set("equip", it.name(), push_front, do_equip, condition) end --- Pick up an item by name (Must use name, since item goes stale when called from equip hotkey) function BRC.Hotkey.pickup(name, push_front) local condition = function() return util.exists(you.floor_items(), function(fl) return fl.name():contains(name) end) end local do_pickup = function() for _, fl in ipairs(you.floor_items()) do -- Check with contains() in case ID'ing it appends to the name if fl.name():contains(name) then items.pickup(fl) return end end BRC.mpr.info(name .. " isn't here!") end BRC.Hotkey.set("pickup", name, push_front, do_pickup, condition) end --- Set hotkey as 'move to ', if it's in LOS -- If target is a table, moves to that xy coordinate -- If target is a string, moves to that feature, otherwise searches for the item by name -- @param queue_pickup (optional boolean) - Queue pickup after moving to item (default true) local function set_waypoint_hotkey(name, push_front, target, queue_pickup) if util.contains(BRC.PORTAL_FEATURE_NAMES, you.branch()) then return -- Can't auto-travel end local x, y if type(target) == "table" then x, y = target.dx, target.dy elseif type(target) == "string" then local r = you.los() for dx = -r, r do for dy = -r, r do if view.feature_at(dx, dy):contains(target) then x, y = dx, dy break end end end else x, y = BRC.it.get_xy(name) end if x == nil then return BRC.mpr.debug(name .. " not found in LOS") end local waynum = get_avail_waypoint() if not waynum then return end util.foreach(WAYPOINT_MUTES, function(m) BRC.opt.single_turn_mute(m) end) travel.set_waypoint(waynum, x, y) local is_valid = function() local dx, dy = travel.waypoint_delta(waynum) return dx and not(dx == 0 and dy == 0) end local move_to_waypoint = function() if f_pickup_alert then f_pickup_alert.pause_alerts() end -- Don't interrupt hotkey travel with new alerts crawl.sendkeys({ BRC.util.get_cmd_key("CMD_INTERLEVEL_TRAVEL"), tostring(waynum) }) crawl.flush_input() end local clear_waypoint = function() local keys = { BRC.util.cntl("w"), "d", tostring(waynum) } -- If other waypoints exist, need to send ESC to exit the prompt for i = 0, 9 do if i ~= waynum and travel.waypoint_delta(i) then keys[#keys + 1] = BRC.KEYS.ESC end end util.foreach(WAYPOINT_MUTES, function(m) BRC.opt.single_turn_mute(m) end) crawl.sendkeys(keys) if not target and queue_pickup ~= false then BRC.Hotkey.pickup(name, true) end end BRC.Hotkey.set("move to", name, push_front, move_to_waypoint, is_valid, clear_waypoint) end function BRC.Hotkey.move_to_item(name, push_front, queue_pickup) set_waypoint_hotkey(name, push_front, nil, queue_pickup) end function BRC.Hotkey.move_to_feature(name, push_front, feature_name) set_waypoint_hotkey(name, push_front, feature_name, false) end function BRC.Hotkey.move_to_xy(name, push_front, x, y) set_waypoint_hotkey(name, push_front, {dx=x, dy=y}, false) end ---- Crawl hook functions ---- function BRC.Hotkey.c_assign_invletter(it) if BRC.Hotkey.Config.equip_hotkey then BRC.Hotkey.equip(it, true) end end function BRC.Hotkey.ch_start_running(kind) if BRC.Hotkey.Config.explore_clears_queue and kind:contains("explore") then action_queue = {} cur_action = nil end end function BRC.Hotkey.c_message(text, channel) if channel ~= "plain" then return end if type(BRC.Hotkey.Config.move_to_feature) ~= "table" then return end if not text:contains("Found") then return end for k, v in pairs(BRC.Hotkey.Config.move_to_feature) do if text:contains(v) then BRC.Hotkey.move_to_feature(v, true, k) end end for k, v in pairs(BRC.PORTAL_FEATURE_NAMES) do if text:contains(v) then BRC.Hotkey.move_to_feature(v, true, k) end end end function BRC.Hotkey.ready() if you.where() ~= cur_floor then -- Clear the queue when changing floors cur_floor = you.where() action_queue = {} cur_action = nil elseif cur_action == nil then load_next_action() elseif cur_action.turn > you.turns() then return elseif BRC.Hotkey.Config.wait_for_safety and not you.feel_safe() and cur_action.condition() then delay_expire = true elseif delay_expire and you.feel_safe() then delay_expire = false display_cur_message() else expire_cur_action() end end } ##### lua/core/brc.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC core module -- @module BRC -- @author buehler -- Serves as the central coordinator for all feature modules. -- Automatically loads any global module/table that defines `BRC_FEATURE_NAME` -- and manages the feature's lifecycle and hook dispatching. --------------------------------------------------------------------------------------------------- ---- Local constants ---- BRC.VERSION = "1.3.1" BRC.MIN_CRAWL_VERSION = "0.34" local HOOK_FUNCTIONS = { autopickup = "autopickup", c_answer_prompt = "c_answer_prompt", c_assign_invletter = "c_assign_invletter", c_message = "c_message", ch_start_running = "ch_start_running", init = "init", ready = "ready", multiready = "multiready", } -- HOOK_FUNCTIONS (do not remove this comment) ---- Local variables ---- local _features local _hooks local turn_count = -1 -- Do not reset this in init() ---- Local functions ---- local function char_dump(add_debug_info) if add_debug_info then crawl.take_note(BRC.dump(true, true)) BRC.mpr.info("Debug info added to character dump.") else BRC.mpr.info("No debug info added.") end BRC.util.do_cmd("CMD_CHARACTER_DUMP") end local function feature_is_disabled(f) local main = BRC.Config[f.BRC_FEATURE_NAME] if main and main.disabled == false then return false end -- catch override not yet applied return (f.Config and f.Config.disabled) or (main and main.disabled) end local function handle_feature_error(feature_name, hook_name, result) BRC.mpr.error(string.format("Failure in %s.%s", feature_name, hook_name), result, true) if BRC.mpr.yesno(string.format("Deactivate %s?", feature_name), BRC.COL.yellow) then BRC.unregister(feature_name) else BRC.mpr.okay() end end local function handle_core_error(hook_name, result, ...) local params = { hook_name } for i = 1, select("#", ...) do local param = select(i, ...) if param and type(param.name) == "function" then params[#params + 1] = "[" .. param.name() .. "]" else params[#params + 1] = BRC.txt.tostr(param, true) end end local msg = "BRC failure in safe_call_all_hooks(" .. table.concat(params, ", ") .. ")" BRC.mpr.error(msg, result, true) if BRC.mpr.yesno("Deactivate BRC." .. hook_name .. "?", BRC.COL.yellow) then _hooks[hook_name] = nil BRC.mpr.brown("Unregistered hook: " .. tostring(hook_name)) else BRC.mpr.okay("Returning nil to " .. hook_name .. ".") end end -- Hook management local function call_all_hooks(hook_name, ...) local last_return_value = nil local returning_feature = nil for i = #_hooks[hook_name], 1, -1 do local hook_info = _hooks[hook_name][i] if not feature_is_disabled(_features[hook_info.feature_name]) then if hook_name == HOOK_FUNCTIONS.init then BRC.mpr.debug(string.format("Initialize %s...", BRC.txt.lightcyan(hook_info.feature_name))) end local success, result = pcall(hook_info.func, ...) if not success then handle_feature_error(hook_info.feature_name, hook_name, result) elseif result ~= nil and last_return_value ~= result then -- Only track non-nil return values. This actually matters for autopickup if hook_name == HOOK_FUNCTIONS.autopickup then -- Unique case. One false will block autopickup. if result == false or last_return_value == nil then last_return_value = result returning_feature = hook_info.feature_name end else if last_return_value ~= nil then BRC.mpr.warning( string.format( "Return value mismatch in %s:\n (first) %s -> %s\n (final) %s -> %s", hook_name, returning_feature, BRC.txt.tostr(last_return_value, true), hook_info.feature_name, BRC.txt.tostr(result, true) ) ) end last_return_value = result returning_feature = hook_info.feature_name end end end end return last_return_value end --- Errors in this function won't show up in crawl, so it's kept simple and safe. local function safe_call_all_hooks(hook_name, ...) if not (_hooks and _hooks[hook_name] and #_hooks[hook_name] > 0) then return end local success, result = pcall(call_all_hooks, hook_name, ...) if success then return result end success, result = pcall(handle_core_error, hook_name, result, ...) if success then return end -- This is a serious error. Failed in the hook, and when we tried to report it. BRC.mpr.error("Failed to handle BRC core error!", result, true) if BRC.mpr.yesno("Dump char and deactivate BRC?", BRC.COL.yellow) then BRC.active = false BRC.mpr.brown("BRC deactivated.", "Error in hook: " .. tostring(hook_name)) pcall(char_dump, true) else BRC.mpr.okay() end end -- Register all features in the global namespace local function register_all_features() -- Find all feature modules local feature_names = {} for name, value in pairs(_G) do if BRC.is_feature_module(value) then feature_names[#feature_names + 1] = name end end -- Sort alphabetically (for reproducable behavior) util.sort(feature_names) -- Register features local loaded_count = 0 for _, name in ipairs(feature_names) do local success = BRC.register(_G[name]) if success then loaded_count = loaded_count + 1 elseif success == false then BRC.mpr.error("Failed to register feature: " .. name .. ". Aborting bulk registration.") return loaded_count end end return loaded_count end ---- Public API ---- function BRC.get_registered_features() return _features end function BRC.is_feature_module(f) return f and type(f) == "table" and f.BRC_FEATURE_NAME and type(f.BRC_FEATURE_NAME) == "string" and #f.BRC_FEATURE_NAME > 0 end --- Feature module tables for config validation: active registrations plus any module present in --- the environment but skipped by BRC.register (disabled-by-default) and tables nested under --- BRC (e.g. BRC.Data), which are not top-level globals. Different from get_registered_features(). function BRC.get_all_feature_modules() local modules = {} for name, mod in pairs(BRC.get_registered_features()) do modules[name] = mod end for _, value in pairs(_G) do if BRC.is_feature_module(value) then modules[value.BRC_FEATURE_NAME] = value end end if type(BRC) == "table" then for _, value in pairs(BRC) do if BRC.is_feature_module(value) then modules[value.BRC_FEATURE_NAME] = value end end end return modules end -- BRC.register(): Return true if success, false if error, nil if feature is disabled function BRC.register(f) if not BRC.is_feature_module(f) then BRC.mpr.error("Tried to register a non-feature module! Module contents:\n" .. BRC.txt.tostr(f)) return false elseif _features[f.BRC_FEATURE_NAME] then BRC.mpr.warning(BRC.txt.lightcyan(f.BRC_FEATURE_NAME) .. " already registered! Repeating...") BRC.unregister(f.BRC_FEATURE_NAME) end if feature_is_disabled(f) then BRC.mpr.debug(BRC.txt.lightcyan(f.BRC_FEATURE_NAME) .. " is disabled. Skipped registration.") return nil else if not BRC.Config[f.BRC_FEATURE_NAME] then BRC.Config[f.BRC_FEATURE_NAME] = {} end if not f.Config then f.Config = {} end end BRC.mpr.debug(string.format("Registering %s...", BRC.txt.lightcyan(f.BRC_FEATURE_NAME))) _features[f.BRC_FEATURE_NAME] = f -- Register hooks for _, hook_name in pairs(HOOK_FUNCTIONS) do if f[hook_name] then if not _hooks[hook_name] then _hooks[hook_name] = {} end table.insert(_hooks[hook_name], { feature_name = f.BRC_FEATURE_NAME, hook_name = hook_name, func = f[hook_name], }) end end BRC.process_feature_config(f) return true end function BRC.unregister(name) if not _features[name] then BRC.mpr.error(BRC.txt.yellow(name) .. " is not registered. Cannot unregister.") return false end _features[name] = nil local removed = {} for hook_name, hooks in pairs(_hooks) do for i = #hooks, 1, -1 do if hooks[i].feature_name == name then table.remove(hooks, i) removed[#removed + 1] = hook_name end end end BRC.mpr.info(string.format("Unregistered %s.", name)) BRC.mpr.debug(string.format("Unregistered %s hooks: (%s)", name, table.concat(removed, ", "))) return true end -- @param config_name (optional string) name of a config function BRC.reset(config_name) BRC.active = false BRC.Data.reset() BRC.opt.clear_macros() BRC.init(config_name) end -- @param config_name string name of a config function BRC.init(config_name) BRC.active = false _features = {} _hooks = {} if not BRC.util.version_is_valid(BRC.MIN_CRAWL_VERSION) then BRC.mpr.error(string.format( "BRC v%s requires crawl v%s or higher. You are running %s.", BRC.VERSION, BRC.txt.yellow(BRC.MIN_CRAWL_VERSION), BRC.txt.yellow(crawl.version("major")) )) if not BRC.mpr.yesno("Continue loading BRC anyway?", BRC.COL.yellow) then BRC.mpr.brown("BRC deactivated.") return false end end BRC.init_config(config_name) BRC.mpr.debug("Config loaded.") BRC.mpr.debug("Register core features...") BRC.register(BRC.Data) BRC.register(BRC.Hotkey) BRC.mpr.debug("Register features...") register_all_features() BRC._validate_config_keys() BRC.mpr.debug("Initialize features...") safe_call_all_hooks(HOOK_FUNCTIONS.init) local suffix = BRC.txt.blue(string.format(" (%s features)", #util.keys(_features))) BRC.mpr.debug("Add non-feature hooks...") add_autopickup_func(BRC.autopickup) BRC.opt.macro(BRC.util.get_cmd_key("CMD_CHARACTER_DUMP") or "#", "macro_brc_dump_character") BRC.mpr.debug("Verify persistent data reload...") local success = BRC.Data.handle_persist_errors() if success then BRC.Data.backup() -- Only backup after a clean startup local msg = string.format("Successfully initialized BRC v%s!%s", BRC.VERSION, suffix) BRC.mpr.lightgreen("\n" .. BRC.txt.wrap(msg, BRC.EMOJI.SUCCESS) .. "\n") else -- success == nil if errors were resolved, false if tried restore but failed if success == false and BRC.mpr.yesno("Deactivate BRC?" .. suffix, BRC.COL.yellow) then BRC.active = false BRC.mpr.lightred("\nBRC is off.\n") return false end BRC.mpr.magenta(string.format("\nInitialized BRC v%s with warnings!%s\n", BRC.VERSION, suffix)) end -- Avoid weird effects from autopickup before first turn BRC.active = you.turns() > 0 return true end --- Pull debug info. Print to mpr() and return as string -- @param skip_mpr (optional bool) Used in char_dump to just return the string function BRC.dump(verbose, skip_mpr) local tokens = {} tokens[#tokens + 1] = BRC.Data.serialize() if verbose then tokens[#tokens + 1] = BRC.txt.serialize_chk_lua_save() tokens[#tokens + 1] = BRC.txt.serialize_inventory() util.append(tokens, BRC.serialize_config()) end if not skip_mpr then for _, token in ipairs(tokens) do BRC.mpr.white(token) end end return table.concat(tokens, "\n") end ---- Macros ---- function macro_brc_dump_character() if not BRC.active then BRC.util.do_cmd("CMD_CHARACTER_DUMP") end char_dump(BRC.mpr.yesno("Add BRC debug info to character dump?", BRC.COL.lightcyan)) end ---- Crawl hooks ---- function BRC.autopickup(it, _) return safe_call_all_hooks(HOOK_FUNCTIONS.autopickup, it) end function BRC.c_answer_prompt(prompt) if not BRC.active then return end if not prompt then return end -- This fires from crawl, e.g. Shop purchase confirmation return safe_call_all_hooks(HOOK_FUNCTIONS.c_answer_prompt, prompt) end function BRC.c_assign_invletter(it) if not BRC.active then return end return safe_call_all_hooks(HOOK_FUNCTIONS.c_assign_invletter, it) end function BRC.c_message(text, channel) if not BRC.active then return end safe_call_all_hooks(HOOK_FUNCTIONS.c_message, text, channel) end function BRC.ch_start_running(kind) if not BRC.active then return end safe_call_all_hooks(HOOK_FUNCTIONS.ch_start_running, kind) end function BRC.ready() if you.turns() <= 1 then BRC.active = true end -- webtiles skips ready() on turn 0 if not BRC.active then return end BRC.opt.clear_single_turn_mutes() if you.turns() > turn_count then turn_count = you.turns() safe_call_all_hooks(HOOK_FUNCTIONS.ready) end safe_call_all_hooks(HOOK_FUNCTIONS.multiready) -- Always display messages, even if same turn BRC.mpr.consume_queue() crawl.redraw_screen() end } ##### lua/features/alert-monsters.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC feature module: alert-monsters -- @module f_alert_monsters -- @author gammafunk, buehler -- Dynamic force_more and flash_screen messages for monsters. -- Alerts are active/inactive based on player HP, XL, willpower, resistances, etc. -- -- @warning Never put a '}' on a line by itself. This breaks crawl's RC parser. --------------------------------------------------------------------------------------------------- f_alert_monsters = {} f_alert_monsters.BRC_FEATURE_NAME = "alert-monsters" f_alert_monsters.Config = { sensitivity = 1.0, -- 0 to disable all; at 2.0, alerts will fire at 1/2 HP pack_timeout = 10, -- turns to wait before repeating a pack alert. 0 to disable disable_alert_monsters_in_zigs = true, -- Disable dynamic force_mores in Ziggurats debug_alert_monsters = false, -- Get a message when alerts toggle off/on } -- f_alert_monsters.Config (do not remove this comment) --[[ Config.Alerts contains all alerts. Each table in it creates one alert, using the following fields: - `name` is for debugging. - `pattern` is a string or list of monster names, will alert when you encounter one. - `is_pack` (optional) indicates the alert is for a pack of monsters. Packs only fire once every few turns - as defined in Config.pack_timeout (default 15). - `flash_screen` (optional) alert will flash the screen instead of using force_more. - `cutoff` sets the point when the alert is active (usually how much HP you have) - `cond` defines HOW the character stats are compared against `cutoff` (HP/will/etc). Ex: `always` alerts are always on. `hp` alerts are active when you have < `cutoff` HP. `will` alerts are active when you have <= `cutoff` pips of willpower. `int` alerts are active when you have < `cutoff` Int. `xl` alerts are active when your XL is < `cutoff`. `elec` alerts are active when you have no rElec and < `cutoff` HP. `fire`, `cold`, etc active < `cutoff` HP with no resistance. Pips lower cutoff to 50/33/20% --]] f_alert_monsters.Config.Alerts = { { name = "always_fm", pattern = { -- High damage/speed "flayed ghost", "juggernaut", "orbs? of (entropy|fire|winter)", --Summoning "boundless tesseract", "demonspawn corrupter", "draconian stormcaller", "dryad", "guardian serpent", "halazid warlock", "shadow demon", "spriggan druid", "worldbinder", --Dangerous abilities "iron giant", "merfolk aquamancer", "nekomata", "shambling mangrove", "starflower", "torpor snail", "water nymph", "wretched star", "wyrmhole", --Dangerous clouds "apocalypse crab", "catoblepas", } }, { name = "always_flash", flash_screen = true, pattern = { -- Noteworthy abilities "air elemental", "elemental wellspring", "ghost crab", "ironbound convoker", "vault guardian", "vault warden", "wendigo", -- Displacement "deep elf knight", "swamp worm", -- Summoning "deep elf elementalist", -- Agony "death knight", "imperial myrmidon", "necromancer", } }, -- Early game Dungeon problems for chars with low hp. (adder defined below) { name = "30hp", cond = "hp", cutoff = 30, is_pack = true, pattern = { "hound", "gnoll" } }, { name = "mid_game_packs", cutoff = 90, is_pack = true, pattern = { "boggart", "dream sheep" } }, -- Monsters dangerous until a certain point { name = "xl_7", cond = "xl", cutoff = 6, is_pack = true, pattern = { "orc wizard" } }, { name = "xl_12", cond = "xl", cutoff = 12, pattern = { "hydra", "bloated husk" } }, -- Monsters that can hit for ~50% of hp from range with unbranded attacks { name = "40hp", cond = "hp", cutoff = 40, pattern = { "orc priest" } }, { name = "50hp", cond = "hp", cutoff = 50, pattern = { "manticore", "orc high priest" } }, { name = "60hp", cond = "hp", cutoff = 60, pattern = { "centaur(?! warrior)", "cyclops", "orc knight", "yaktaur(?! captain)" } }, { name = "70hp_melai", cond = "hp", cutoff = 70, is_pack = true, pattern = "meliai" }, { name = "80hp", cond = "hp", cutoff = 80, pattern = { "gargoyle" } }, { name = "90hp", cond = "hp", cutoff = 90, pattern = { "deep elf archer", "tengu conjurer" } }, { name = "110hp", cond = "hp", cutoff = 110, pattern = { "cacodemon", "centaur warrior", "deep elf high priest", "deep troll earth mage", "eye of devastation", "hellion", "stone giant", "sun moth", "yaktaur captain" } }, { name = "120hp", cond = "hp", cutoff = 120, pattern = { "magenta draconian", "thorn hunter", "quicksilver (dragon|elemental)" } }, { name = "160hp", cond = "hp", cutoff = 160, pattern = { "brimstone fiend", "deep elf sorcerer", "hell sentinel", "draconian (knight|scorcher)", "war gargoyle" } }, { name = "200hp", cond = "hp", cutoff = 200, pattern = { "(deep elf|draconian) annihilator", "iron (dragon|elemental)" } }, -- Monsters that can crowd-control you without sufficient willpower -- Cutoff ~10% for most spells; lower for more significant spells like banish { name = "willpower2", cond = "will", cutoff = 2, pattern = { "basilisk", "naga ritualist", "vampire(?! (bat|mage|mosquito))", "sphinx marauder" } }, { name = "willpower3", cond = "will", cutoff = 3, pattern = { "cacodemon", "death knight", "deep elf (demonologist|sorcerer|archer)", "draconian shifter", "fenstrider witch", "glowing orange brain", "guardian sphinx", "imperial myrmidon", "iron elemental", "occultist", "merfolk siren", "nagaraja", "ogre mage", "orc sorcerer", "satyr", "vampire knight", "vault sentinel" } }, { name = "willpower3_great_orb_of_eyes", cond = "will", cutoff = 3, is_pack = true, pattern = "great orb of eyes" }, { name = "willpower3_golden_eye", cond = "will", cutoff = 3, is_pack = true, pattern = "golden eye" }, { name = "willpower4", cond = "will", cutoff = 4, pattern = { "merfolk avatar", "tainted leviathan", "nargun" } }, -- Brain feed with low int { name = "brainfeed", cond = "int", cutoff = 6, pattern = { "glowing orange brain", "neqoxec" } }, -- Alert if no resist and HP below cutoff { name = "pois_30", cond = "pois", cutoff = 30, pattern = { "adder" } }, { name = "pois_80", cond = "pois", cutoff = 80, pattern = { "golden dragon", "green draconian", "swamp dragon" } }, { name = "pois_120", cond = "pois", cutoff = 120, pattern = { "fenstrider witch", "green death", "naga mage", "nagaraja" } }, { name = "pois_140", cond = "pois", cutoff = 140, pattern = { "tengu reaver" } }, { name = "elec_40", cond = "elec", cutoff = 40, is_pack = true, pattern = "electric eel" }, { name = "elec_80", cond = "elec", cutoff = 80, pattern = { "raiju", "shock serpent", "spark wasp" } }, { name = "elec_120", cond = "elec", cutoff = 120, pattern = { "black draconian", "blizzard demon", "deep elf zephyrmancer", "storm dragon", "tengu conjurer" } }, { name = "elec_140", cond = "elec", cutoff = 140, pattern = { "electric golem", "servants? of whisper", "spriggan air mage", "tengu reaver", "titan" } }, { name = "elec_140_pack", cond = "elec", cutoff = 140, is_pack = true, pattern = { "ball lightning" } }, { name = "corr_60", cond = "corr", cutoff = 60, pattern = { "acid dragon" } }, { name = "caustic_shrike", cond = "corr", cutoff = 120, is_pack = true, pattern = { "caustic shrike" } }, { name = "corr_140", cond = "corr", cutoff = 140, pattern = { "demonspawn corrupter", "entropy weaver", "moon troll", "tengu reaver" } }, { name = "fire_60_pack", cond = "fire", cutoff = 60, is_pack = true, pattern = { "hell hound", "lava snake", "lindwurm" } }, { name = "fire_60", cond = "fire", cutoff = 60, pattern = { "fire crab", "steam dragon" } }, { name = "fire_100", cond = "fire", cutoff = 100, pattern = { "deep elf pyromancer", "efreet", "smoke demon", "sun moth" } }, { name = "fire_120", cond = "fire", cutoff = 120, pattern = { "demonspawn blood saint", "hell hog", "hell knight", "molten gargoyle", "ogre mage", "orc sorcerer", "red draconian" } }, { name = "fire_140", cond = "fire", cutoff = 140, pattern = { "balrug" } }, { name = "fire_160", cond = "fire", cutoff = 160, pattern = { "fire dragon", "fire giant", "golden dragon", "ophan", "salamander tyrant", "tengu reaver", "will-o-the-wisp" } }, { name = "fire_240", cond = "fire", cutoff = 240, pattern = { "crystal (guardian|echidna)", "draconian scorcher", "hellephant" } }, { name = "cold_80", cond = "cold", cutoff = 80, pattern = { "rime drake" } }, { name = "cold_120", cond = "cold", cutoff = 120, pattern = { "blizzard demon", "bog body", "demonspawn blood saint", "ironbound frostheart", "white draconian" } }, { name = "shard_shrike", cond = "cold", cutoff = 120, is_pack = true, pattern = { "shard shrike" } }, { name = "cold_160", cond = "cold", cutoff = 160, pattern = { "draconian knight", "frost giant", "golden dragon", "ice dragon", "tengu reaver" } }, { name = "cold_180", cond = "cold", cutoff = 180, pattern = { "(? 1 then remove_patterns[#remove_patterns + 1] = v for _, m in ipairs(v.pattern) do local to_add = util.copy_table(v) to_add.name = (to_add.name or "") .. "_" .. m:gsub(" ", "_") to_add.pattern = m add_patterns[#add_patterns + 1] = to_add end end end util.append(C.Alerts, add_patterns) for _, v in ipairs(remove_patterns) do util.remove(C.Alerts, v) end -- Convert patterns to regex for _, v in ipairs(C.Alerts) do v.active_alert = false v.last_fm_turn = -1 if type(v.pattern) == "table" then v.pattern = table.concat(v.pattern, "|") end v.pattern = WARN_PREFIX .. v.pattern .. WARN_SUFFIX v.regex = crawl.regex(v.pattern:gsub("monster_warning:", "")) end end ---- Local functions ---- --- Check if player HP is below threshold, accounting for 0-3 pips of resistance. -- @return true if player HP is below threshold, and alert should be active. local function is_active_3pip(hp, dmg_threshold, resistance) -- Dmg taken is 1/1; 1/2; 1/3; 1/5 (for 0; 1; 2; 3 resistance) if resistance >= 3 then return hp < dmg_threshold / 5 end return hp < dmg_threshold / (resistance + 1) end --- Dispatch table for condition handler functions; checking if alerts should be active or not. -- Each handler takes (alert, stats) and returns true if the alert should be active. local CONDITION_HANDLERS = { xl = function(a, s) return s.xl < a.cutoff * C.sensitivity end, hp = function(a, s) return s.hp < a.cutoff * C.sensitivity end, int = function(a, s) return s.int < a.cutoff * C.sensitivity end, will = function(a, s) return s.will < a.cutoff * C.sensitivity end, mut = function(_, s) return s.rMut == 0 end, pois = function(a, s) return s.rPois == 0 and s.hp < a.cutoff * C.sensitivity end, elec = function(a, s) return s.rElec == 0 and s.hp < a.cutoff * C.sensitivity end, corr = function(a, s) return not s.rCorr and s.hp < a.cutoff * C.sensitivity end, fire = function(a, s) return is_active_3pip(s.hp, a.cutoff * C.sensitivity, s.rF) end, cold = function(a, s) return is_active_3pip(s.hp, a.cutoff * C.sensitivity, s.rC) end, drain = function(a, s) return is_active_3pip(s.hp, a.cutoff * C.sensitivity, s.rN) end, } -- CONDITION_HANDLERS (do not remove this comment) local function update_pack_mutes() -- Put pending mutes into effect for _, v in ipairs(patterns_to_mute) do if v.flash_screen then BRC.opt.flash_screen_message(v, false) else BRC.opt.force_more_message(v, false) end if C.debug_alert_monsters then BRC.mpr.blue("Muted pack: " .. v) end end patterns_to_mute = {} -- Remove expired mutes for _, v in ipairs(C.Alerts) do if v.is_pack and v.last_fm_turn ~= -1 and you.turns() >= v.last_fm_turn + C.pack_timeout then v.last_fm_turn = -1 v.active_alert = false -- Let the main logic decide if/when to reactivate it. if C.debug_alert_monsters then BRC.mpr.blue("Unmuted pack: " .. v.pattern) end end end end ---- Crawl hook functions ---- function f_alert_monsters.c_message(text, channel) if channel ~= "monster_warning" or not text:find("encounter") then return end if C.pack_timeout <= 0 then return end -- Identify when a mute should be turned on for _, v in ipairs(C.Alerts) do if v.is_pack and v.regex:matches(text) then if v.last_fm_turn == -1 then patterns_to_mute[#patterns_to_mute + 1] = v.pattern if C.debug_alert_monsters then BRC.mpr.blue("To mute: " .. v.pattern) end else if C.debug_alert_monsters then BRC.mpr.blue("Extending mute: " .. v.pattern) end end v.last_fm_turn = you.turns() end end end function f_alert_monsters.ready() local activated = {} local deactivated = {} -- Load all stats before loop. Most of them are used multiple times. local hp, _ = you.hp() if you.spirit_shield() > 0 then local mp, _ = you.mp() hp = hp + mp end -- Collect stats into a table for handlers local stats = { hp = hp, xl = you.xl(), int = you.intelligence(), will = you.willpower(), rMut = you.res_mutation(), rPois = you.res_poison(), rElec = you.res_shock(), rCorr = you.res_corr(), rF = you.res_fire(), rC = you.res_cold(), rN = you.res_draining(), } -- stats (do not remove this comment) for _, v in ipairs(C.Alerts) do local should_be_active = false if C.disable_alert_monsters_in_zigs and you.branch() == "Zig" then should_be_active = false elseif not v.cond then should_be_active = true else local handler = CONDITION_HANDLERS[v.cond] if handler then should_be_active = handler(v, stats) else BRC.mpr.error("Unknown condition in alert-monsters: " .. v.cond) end end if should_be_active ~= v.active_alert then v.active_alert = should_be_active if v.flash_screen then BRC.opt.flash_screen_message(v.pattern, should_be_active) else BRC.opt.force_more_message(v.pattern, should_be_active) end if C.debug_alert_monsters then if v.active_alert then activated[#activated + 1] = v.name or v.pattern else deactivated[#deactivated + 1] = v.name or v.pattern end end end end if C.debug_alert_monsters then if #activated > 0 then BRC.mpr.blue("Activating f_m: " .. table.concat(activated, ", ")) end if #deactivated > 0 then BRC.mpr.blue("Deactivating f_m: " .. table.concat(deactivated, ", ")) end end if C.pack_timeout > 0 then update_pack_mutes() end end } ##### lua/features/fully-recover.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC feature module: fully-recover -- @module f_fully_recover -- Rests until no negative duration statuses. Doesn't stop rest on each status expiration. -- @todo Can remove when crawl's explore_auto_rest_status setting reaches feature parity. --------------------------------------------------------------------------------------------------- f_fully_recover = {} f_fully_recover.BRC_FEATURE_NAME = "fully-recover" ---- Persistent variables ---- fr_bad_durations = BRC.Data.persist("fr_bad_durations", util.copy_table(BRC.BAD_DURATIONS)) ---- Local constants ---- local MAX_TURNS_TO_WAIT = 300 ---- Local variables ---- -- recovery_start_turn is a module field (not local) for test observability local M = f_fully_recover local explore_after_recovery ---- Initialization ---- function f_fully_recover.init() M.recovery_start_turn = nil explore_after_recovery = nil BRC.opt.macro(BRC.util.get_cmd_key("CMD_EXPLORE") or "o", "macro_brc_explore", true) BRC.opt.macro(BRC.util.get_cmd_key("CMD_REST") or "5", "macro_brc_rest") BRC.opt.runrest_ignore_message("recovery:.*", true) BRC.opt.runrest_ignore_message("duration:.*", true) BRC.opt.message_mute("^HP restored", true) BRC.opt.message_mute("Magic restored", true) end ---- Local functions ---- local function should_ignore_status(s) if s == "corroded" then return BRC.you.by_slimy_wall() or you.branch() == "Dis" elseif s == "slowed" then return BRC.you.zero_stat() end return false end local function fully_recovered() if you.contamination() > 0 then return false end local hp, mhp = you.hp() local mp, mmp = you.mp() if hp ~= mhp then return false end if mp ~= mmp then return false end local status = you.status() for _, s in ipairs(BRC.BAD_DURATIONS) do if status:find(s) and not should_ignore_status(s) then return false end end return true end local function remove_statuses_from_list() local status = you.status() local to_remove = {} for _, s in ipairs(fr_bad_durations) do if status:find(s) then table.insert(to_remove, s) end end for _, s in ipairs(to_remove) do util.remove(fr_bad_durations, s) BRC.mpr.error(" Removed: " .. s) end end --- If both CMD_EXPLORE macros are enabled, muted_explore is overridden. This function calls it. local function do_cmd_wrapper(cmd) if cmd == "CMD_EXPLORE" and macro_brc_muted_explore then macro_brc_muted_explore() else BRC.util.do_cmd(cmd) end end local function complete_recovery() local turns = you.turns() - M.recovery_start_turn M.recovery_start_turn = nil if turns > 0 then you.stop_activity() BRC.mpr.lightgreen(string.format("Fully recovered (%d turns)", turns)) if explore_after_recovery then do_cmd_wrapper("CMD_EXPLORE") end end end local function start_recovery(cmd) if BRC.active == false or f_fully_recover.Config.disabled or not you.feel_safe() then return do_cmd_wrapper(cmd) end if fully_recovered() then if M.recovery_start_turn ~= nil then complete_recovery() else do_cmd_wrapper(cmd) end else M.recovery_start_turn = you.turns() explore_after_recovery = cmd == "CMD_EXPLORE" do_cmd_wrapper("CMD_REST") end end ---- Macro function: Attach full recovery to auto-explore ---- function macro_brc_explore() start_recovery("CMD_EXPLORE") end ---- Macro function: Attach full recovery to auto-rest ---- function macro_brc_rest() start_recovery("CMD_REST") end ---- Crawl hook functions ---- function f_fully_recover.c_message(text, channel) if M.recovery_start_turn == nil then return end if channel == "plain" and ( text:contains("You start resting.") or text:contains("You start waiting.") or (f_announce_hp_mp and f_announce_hp_mp.msg_is_meter(text)) -- ignore announce-hp-mp messages ) then return end -- Always stop the current recovery, and ready() will re-evaluate with the updated player status -- For any non-duration/recovery message, abort the recovery entirely. you.stop_activity() if channel ~= "duration" and channel ~= "recovery" then M.recovery_start_turn = nil end end function f_fully_recover.ready() if M.recovery_start_turn == nil then return end if fully_recovered() then complete_recovery() elseif not you.feel_safe() then M.recovery_start_turn = nil you.stop_activity() elseif you.turns() - M.recovery_start_turn > MAX_TURNS_TO_WAIT then BRC.mpr.error("fully-recover timed out after " .. MAX_TURNS_TO_WAIT .. " turns.", true) BRC.mpr.error("fr_bad_durations:") remove_statuses_from_list() M.recovery_start_turn = nil you.stop_activity() else do_cmd_wrapper("CMD_REST") end end } ##### lua/features/go-up-macro.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC feature module: go-up-macro -- @module f_go_up_macro -- Handles orb run mechanics: HP-based monster ignore for cntl-E macro --------------------------------------------------------------------------------------------------- f_go_up_macro = {} f_go_up_macro.BRC_FEATURE_NAME = "go-up-macro" f_go_up_macro.Config = { go_up_macro_key = BRC.util.cntl("e"), -- Key for "go up closest stairs" macro ignore_mon_on_orb_run = true, -- Ignore monsters on orb run -- %HP thresholds for ignoring monsters during orb run (2-7 tiles away, depending on HP percent) orb_ignore_hp_min = 0.30, -- HP percent to stop ignoring monsters orb_ignore_hp_max = 0.70, -- HP percent to ignore monsters at min distance away (2 tiles) } -- f_go_up_macro.Config (do not remove this comment) ---- Local variables ---- local orb_ignore_distance ---- Local functions ---- local function set_orb_ignore_distance(distance) if orb_ignore_distance then BRC.opt.runrest_ignore_monster(".*:" .. orb_ignore_distance, false) orb_ignore_distance = nil end if distance then orb_ignore_distance = distance BRC.opt.runrest_ignore_monster(".*:" .. orb_ignore_distance, true) end end --- Get distance (2 - 7) to ignore monsters based on HP percent local function get_ignore_distance_from_hp() local hp, mhp = you.hp() local hp_pct = hp / mhp local min_pct = f_go_up_macro.Config.orb_ignore_hp_min local max_pct = f_go_up_macro.Config.orb_ignore_hp_max if hp_pct <= min_pct then return nil end if hp_pct >= max_pct then return 2 end -- Linear interpolation between min_pct and max_pct local ratio = (hp_pct - min_pct) / (max_pct - min_pct) return math.floor(2 + ratio * (you.los() - 2)) end ---- Initialization ---- function f_go_up_macro.init() BRC.opt.macro(f_go_up_macro.Config.go_up_macro_key, "macro_brc_go_up") end ---- Macro function ---- --- Go up the closest stairs (Cntl-E) function macro_brc_go_up() if BRC.active == false or f_go_up_macro.Config.disabled then return end if you.have_orb() and f_go_up_macro.Config.ignore_mon_on_orb_run then local distance = get_ignore_distance_from_hp() if distance ~= orb_ignore_distance then set_orb_ignore_distance(distance) end end -- Go up closest stairs; different macro for D:1 and portals local where = you.where() if where == "D:1" and you.have_orb() or where == "Temple" or util.contains(BRC.PORTAL_FEATURE_NAMES, you.branch()) or BRC.you.in_hell(true) then crawl.sendkeys({ "X", "<", "\r", BRC.KEYS.ESC, "<" }) -- {ESC, <} handles standing on stairs else crawl.sendkeys({ BRC.util.cntl("g"), "<" }) end crawl.flush_input() end } ##### lua/features/inscribe-stats.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC feature module: inscribe-stats -- @module f_inscribe_stats -- Inscribes and updates weapon DPS/dmg/delay, and armour AC/EV/SH, for items in inventory. -- For Coglin weapons, evaluates as if swapping out the primary weapon (for artefact stat changes) --------------------------------------------------------------------------------------------------- f_inscribe_stats = {} f_inscribe_stats.BRC_FEATURE_NAME = "inscribe-stats" f_inscribe_stats.Config = { inscribe_weapons = true, -- Inscribe weapon stats on pickup inscribe_armour = true, -- Inscribe armour stats on pickup dmg_type = BRC.DMG_TYPE.unbranded, -- unbranded, plain, branded, scoring skip_dps = false, -- Skip DPS in weapon inscriptions prefix_staff_dmg = true, -- Special prefix for magical staves } -- f_inscribe_stats.Config (do not remove this comment) ---- Local constants ---- local NUM_PATTERN = "[%+%-:]%d+[%.,%,]%d*" -- Matches numbers w/ decimal ---- Local variables ---- local C -- config alias ---- Initialization ---- function f_inscribe_stats.init() C = f_inscribe_stats.Config end ---- Local functions ---- local function inscribe_armour_stats(it) local abbr = BRC.it.is_shield(it) and "SH" or "AC" local ac_or_sh, ev = BRC.eq.arm_stats(it) local sign_change = false local new_insc if it.inscription:find(abbr .. NUM_PATTERN) then new_insc = it.inscription:gsub(abbr .. NUM_PATTERN, ac_or_sh) if not it.inscription:contains(ac_or_sh:sub(1, 3)) then sign_change = true end if ev and #ev > 0 then new_insc = new_insc:gsub("EV" .. NUM_PATTERN, ev) if not it.inscription:contains(ev:sub(1, 3)) then sign_change = true end end else new_insc = ac_or_sh if ev and #ev > 0 then new_insc = string.format("%s, %s", new_insc, ev) end if it.inscription and #it.inscription > 0 then new_insc = string.format("%s; %s", new_insc, it.inscription) end end it.inscribe(new_insc, false) -- If f_color_inscribe is enabled, update the color if sign_change and f_color_inscribe and f_color_inscribe.Config and not f_color_inscribe.Config.disabled and f_color_inscribe.colorize then f_color_inscribe.colorize(it) end end local function get_staff_dmg_str(it) local _, dmg, chance = BRC.eq.get_staff_bonus_dmg(it) if dmg == 0 or chance == 0 then return "(+0)" end if chance >= 1 then return string.format("(+%d)", math.floor(dmg)) end return string.format("(+%.0f|%.0f%%%%)", dmg, chance * 100) end --- Replace the old inscription with the current one, preserving prefix/suffix local function update_inscription(orig, cur) local first = orig:find(cur:sub(1, 4)) -- Handle format migration between DPS= and Dmg= modes (e.g. when skip_dps config changes) if not first then if cur:sub(1, 4) == "Dmg=" then first = orig:find("DPS=") elseif cur:sub(1, 4) == "DPS=" then first = orig:find("Dmg=") end end if not first then return cur .. "; " .. orig end local _, last = orig:find("A%+%d+") if not last then _, last = orig:find("A%-%d+") end if not last then BRC.mpr.error("Missing accuracy in inscription: " .. orig) return cur .. "; " .. orig end local prefix = orig:sub(1, first - 1) if #prefix > 0 and prefix:sub(-2) ~= "; " then prefix = prefix .. "; " end if prefix == "; " then prefix = "" end local suffix = util.trim(orig:sub(last+1)) if #suffix > 0 and suffix:sub(1, 1) ~= ";" then suffix = "; " .. suffix end if suffix == ";" then suffix = "" end return prefix .. cur .. suffix end local function inscribe_weapon_stats(it) local orig_inscr = it.inscription local dmg_type = C.dmg_type if type(dmg_type) == "string" then dmg_type = BRC.DMG_TYPE[dmg_type] end local dps_inscr = BRC.eq.wpn_stats(it, dmg_type, C.skip_dps) if C.prefix_staff_dmg and BRC.it.is_magic_staff(it) then local bonus_str = get_staff_dmg_str(it) dps_inscr = dps_inscr:gsub("/", bonus_str .. "/") -- Recuce weapon damage string from #.## -> # local dmg_index = dps_inscr:find("=%d+%.%d%d") if dmg_index then local dmg_str = dps_inscr:sub(dmg_index + 1, dmg_index + 4) local dmg_int = math.floor(tonumber(dmg_str)+0.5) dps_inscr = dps_inscr:gsub("=" .. dmg_str, "=" .. dmg_int) end end it.inscribe(update_inscription(orig_inscr, dps_inscr), false) end ---- Crawl hook functions ---- function f_inscribe_stats.do_stat_inscription(it) if C.inscribe_weapons and it.is_weapon then inscribe_weapon_stats(it) elseif C.inscribe_armour and BRC.it.is_armour(it) and not BRC.it.is_scarf(it) then inscribe_armour_stats(it) end end function f_inscribe_stats.ready() for _, inv in ipairs(items.inventory()) do f_inscribe_stats.do_stat_inscription(inv) end end } ##### lua/features/misc-alerts.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC feature module: misc-alerts -- @module f_misc_alerts -- @author gammafunk (save game w/ msg), buehler -- Various single-purpose alerts: save game w/ msg, low HP, faith amulet, spell level changes. --------------------------------------------------------------------------------------------------- f_misc_alerts = {} f_misc_alerts.BRC_FEATURE_NAME = "misc-alerts" f_misc_alerts.Config = { preferred_god = "", -- Stop on first altar with this text (Ex. "Wu Jian"); nil or "" disables force_more_on_pref_altar = true, -- Force more message on first altar for preferred god save_with_msg = true, -- Shift-S to save and leave yourself a message alert_low_hp_threshold = 35, -- % max HP to alert; 0 to disable alert_spell_level_changes = true, -- Alert when you gain additional spell levels alert_remove_faith = true, -- Reminder to remove amulet at max piety remove_faith_hotkey = true, -- Hotkey remove amulet } -- f_misc_alerts.Config (do not remove this comment) ---- Persistent variables ---- ma_alerted_max_piety = BRC.Data.persist("ma_alerted_max_piety", false) ma_saved_msg = BRC.Data.persist("ma_saved_msg", "") ma_found_altar = BRC.Data.persist("ma_found_altar", false) ---- Local constants ---- local REMOVE_FAITH_MSG = "6 star piety! Maybe ditch that amulet soon." local GOD_ALTAR_TEXT = "Found.*altar.*" ---- Local variables ---- local C -- config alias local below_hp_threshold local prev_spell_levels local removed_altar_alert ---- Initialization ---- function f_misc_alerts.init() C = f_misc_alerts.Config below_hp_threshold = false prev_spell_levels = you.spell_levels() removed_altar_alert = false if C.save_with_msg then BRC.opt.macro(BRC.util.get_cmd_key("CMD_SAVE_GAME") or "S", "macro_brc_save") if ma_saved_msg and #ma_saved_msg > 0 then BRC.mpr.white("MESSAGE: " .. ma_saved_msg) ma_saved_msg = "" end end if C.preferred_god and not ma_found_altar then if #C.preferred_god == 0 then ma_found_altar = true else GOD_ALTAR_TEXT = GOD_ALTAR_TEXT .. C.preferred_god BRC.opt.flash_screen_message(GOD_ALTAR_TEXT, true) BRC.opt.force_more_message(GOD_ALTAR_TEXT, C.force_more_on_pref_altar) end end end ---- Local functions ---- local function alert_low_hp() local hp, mhp = you.hp() if below_hp_threshold then below_hp_threshold = hp ~= mhp elseif hp <= mhp * C.alert_low_hp_threshold / 100 then below_hp_threshold = true local low_hp_msg = "Dropped below " .. C.alert_low_hp_threshold .. "% HP" BRC.mpr.que_optmore(true, BRC.txt.wrap(BRC.txt.magenta(low_hp_msg), BRC.EMOJI.EXCLAMATION)) end end local function alert_remove_faith() if not ma_alerted_max_piety and you.piety_rank() == 6 then local am = items.equipped_at("amulet") if am and am.subtype() == "amulet of faith" and not am.artefact then if you.god() == "Uskayaw" then return end BRC.mpr.more(REMOVE_FAITH_MSG, BRC.COL.lightcyan) ma_alerted_max_piety = true if C.remove_faith_hotkey and BRC.Hotkey then BRC.Hotkey.set("remove", "amulet of faith", false, function() items.equipped_at("amulet"):remove() end) end end end end local function alert_spell_level_changes() local new_spell_levels = you.spell_levels() if new_spell_levels > prev_spell_levels then local delta = new_spell_levels - prev_spell_levels local msg = string.format("Gained %s spell level%s", delta, delta > 1 and "s" or "") local suffix = string.format(" (%s available)", new_spell_levels) BRC.mpr.lightcyan(msg .. BRC.txt.cyan(suffix)) elseif new_spell_levels < prev_spell_levels then BRC.mpr.magenta(new_spell_levels .. " spell levels remaining") end prev_spell_levels = new_spell_levels end ---- Macro function: Save with message feature ---- function macro_brc_save() if BRC.active == false or f_misc_alerts.Config.disabled or not f_misc_alerts.Config.save_with_msg then return BRC.util.do_cmd("CMD_SAVE_GAME") end if not BRC.mpr.yesno("Save game and exit?", BRC.COL.lightcyan) then BRC.mpr.okay() return end BRC.mpr.white("Leave a message: ", "prompt") ma_saved_msg = crawl.c_input_line() BRC.util.do_cmd("CMD_SAVE_GAME_NOW") end ---- Crawl hook functions ---- function f_misc_alerts.c_message(text, _) if C.preferred_god and not ma_found_altar and text:find(GOD_ALTAR_TEXT) then ma_found_altar = true local feature_name = "altar_" .. (C.preferred_god:match("^%S+") or C.preferred_god):lower() BRC.Hotkey.move_to_feature("altar of " .. C.preferred_god, true, feature_name) end end function f_misc_alerts.ready() if C.alert_remove_faith then alert_remove_faith() end if C.alert_low_hp_threshold > 0 then alert_low_hp() end if C.alert_spell_level_changes then alert_spell_level_changes() end if ma_found_altar and not removed_altar_alert then removed_altar_alert = true BRC.opt.flash_screen_message(GOD_ALTAR_TEXT, false) BRC.opt.force_more_message(GOD_ALTAR_TEXT, false) end end } ##### lua/features/quiver-reminders.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC feature module: quiver-reminders -- @module f_quiver_reminders -- A handful of useful quiver-related reminders. (AKA things I often forget.) --------------------------------------------------------------------------------------------------- f_quiver_reminders = {} f_quiver_reminders.BRC_FEATURE_NAME = "quiver-reminders" f_quiver_reminders.Config = { confirm_consumables = true, warn_diff_missile_turns = 10, } -- f_quiver_reminders.Config (do not remove this comment) ---- Local variables ---- -- last_thrown/last_queued state is on module fields (not local) for test observability local M = f_quiver_reminders local C -- config alias ---- Initialization ---- function f_quiver_reminders.init() C = f_quiver_reminders.Config M.last_thrown = nil M.last_thrown_turn = -1 M.last_queued = nil M.last_queued_turn = -1 BRC.opt.macro(BRC.util.get_cmd_key("CMD_FIRE") or "f", "macro_brc_fire") end ---- Local functions ---- --- Generate a string that matches the "Throw: ()" format local function parse_name_from_item(it) local ego = it.ego() if not ego then return it.name("db") end return it.name("db") .. " (" .. ego .. ")" end local function quiver_missile_by_name(name) local slot = nil for _, inv in ipairs(items.inventory()) do if parse_name_from_item(inv) == name then slot = inv.slot break end end if not slot then BRC.mpr.error("Not found in inventory: " .. name) return end crawl.sendkeys(BRC.util.get_cmd_key("CMD_QUIVER_ITEM") .. "*(" .. BRC.txt.int2char(slot)) crawl.flush_input() end ---- Macro function: Fire from quiver ---- function macro_brc_fire() if BRC.active == false or f_quiver_reminders.Config.disabled then return BRC.util.do_cmd("CMD_FIRE") end local quivered = items.fired_item() if not quivered then return end if C.confirm_consumables then local cls = quivered.class(true) if cls == "potion" or cls == "scroll" then local action = cls == "potion" and "drink" or "read" local q = BRC.txt.lightgreen(quivered.name()) local msg = string.format("Really %s %s from quiver?", action, q) if not BRC.mpr.yesno(msg) then return BRC.mpr.okay() end end end local lt = M.last_thrown local ltt = M.last_thrown_turn if lt and (you.turns() - ltt <= C.warn_diff_missile_turns) then local eq_name = items.equipped_at("Weapon") and items.equipped_at("Weapon").name("qual") or nil local quiv_name = parse_name_from_item(quivered) if quiv_name ~= M.last_thrown and quiv_name ~= eq_name then local q = BRC.txt.lightgreen(quiv_name) if not BRC.mpr.yesno("Did you mean to throw " .. q .. "?") then local t = BRC.txt.lightgreen(M.last_thrown) if BRC.mpr.yesno("Quiver and throw " .. t .. " instead?") then quiver_missile_by_name(M.last_thrown) else return BRC.mpr.okay() end end end end BRC.util.do_cmd("CMD_FIRE") end ---- Crawl hook functions ---- function f_quiver_reminders.c_message(text, _) local cleaned = BRC.txt.clean(text) if cleaned:sub(1, 7) == "Throw: " then M.last_queued_turn = you.turns() -- Missile name is shown in message like: "Throw: 23 darts (curare)". Strip prefix. M.last_queued = cleaned:sub(8, #cleaned) -- Remove quantity and pluralization M.last_queued = M.last_queued:gsub("^%d+ ", "") if M.last_queued:sub(-1) == "s" then M.last_queued = M.last_queued:sub(1, -2) else M.last_queued = M.last_queued:gsub("s %(", " (") end elseif cleaned:sub(1, 10) == "You throw " then local lqt = M.last_queued_turn if you.turns() ~= lqt then BRC.mpr.error("quiver-remind turn changed: " .. lqt .. " -> " .. you.turns()) end M.last_thrown = M.last_queued M.last_thrown_turn = M.last_queued_turn end end } ##### lua/features/safe-stairs.lua ##### { --------------------------------------------------------------------------------------------------- -- BRC feature module: safe-stairs -- @module f_safe_stairs -- @author rypofalem (V:5 warning idea), buehler -- Prevent accidental stairs use and warn for Vaults:5 entry. --------------------------------------------------------------------------------------------------- f_safe_stairs = {} f_safe_stairs.BRC_FEATURE_NAME = "safe-stairs" f_safe_stairs.Config = { warn_backtracking = true, -- Warn if immediately taking stairs twice in a row warn_v5 = true, -- Prompt before entering Vaults:5 } -- f_safe_stairs.Config (do not remove this comment) ---- Persistent variables ---- ss_prev_location = BRC.Data.persist("ss_prev_location", you.where()) ss_v5_warned = BRC.Data.persist("ss_v5_warned", false) ---- Local variables ---- local C -- config alias local ss_cur_location ---- Initialization ---- function f_safe_stairs.init() C = f_safe_stairs.Config ss_cur_location = you.where() BRC.opt.macro(BRC.util.get_cmd_key("CMD_GO_DOWNSTAIRS") or ">", "macro_brc_downstairs") BRC.opt.macro(BRC.util.get_cmd_key("CMD_GO_UPSTAIRS") or "<", "macro_brc_upstairs") end ---- Local functions ---- local function check_new_location(cmd) local feature = view.feature_at(0, 0) if C.warn_backtracking and ss_prev_location ~= ss_cur_location then if cmd == "CMD_GO_DOWNSTAIRS" and (feature:contains("down") or feature:contains("shaft")) or cmd == "CMD_GO_UPSTAIRS" and feature:contains("up") then if not BRC.mpr.yesno("Really go right back?") then return BRC.mpr.okay() end end end if C.warn_v5 and not ss_v5_warned and ss_cur_location == "Vaults:4" and cmd == "CMD_GO_DOWNSTAIRS" and (feature:contains("down") or feature:contains("shaft")) then if not BRC.mpr.yesno("Really go to Vaults:5?") then return BRC.mpr.okay() end ss_v5_warned = true end BRC.util.do_cmd(cmd) end ---- Macro functions ---- function macro_brc_downstairs() if BRC.active == false or f_safe_stairs.Config.disabled then BRC.util.do_cmd("CMD_GO_DOWNSTAIRS") else check_new_location("CMD_GO_DOWNSTAIRS") end end function macro_brc_upstairs() if BRC.active == false or f_safe_stairs.Config.disabled then BRC.util.do_cmd("CMD_GO_UPSTAIRS") else check_new_location("CMD_GO_UPSTAIRS") end end ---- Crawl hook functions ---- function f_safe_stairs.ready() ss_prev_location = ss_cur_location ss_cur_location = you.where() end } ##### Lua hook functions (crawl calls these; they hand off to BRC) ##### { function c_message(text, channel) BRC.c_message(text, channel) end function c_answer_prompt(prompt) return BRC.c_answer_prompt(prompt) end function c_assign_invletter(it) return BRC.c_assign_invletter(it) end function ch_start_running(kind) BRC.ch_start_running(kind) end function ready() BRC.ready() end BRC.init() }