Battle rules
A rule changes how one fight plays. “No perks”, “the floor burns”, “the boss regenerates” and “every third hit does damage” are all rules. This guide shows the built-in rules, how to write your own in Lua, how to end a round on your own objective, and how to adjust difficulty at the moment a fight begins.
You need a fight to attach rules to. Battles and bosses builds one. Examples assume local sf2 = require("sf2").
Attach a rule
Section titled “Attach a rule”A rule is a table with a kind, written inline in a fight’s rules list:
local sf2 = require("sf2")
sf2.battles.register { id = "no_perks_duel", page = sf2.map.get("core:zones/zone_1"), title = "No Perks Duel", fights = { { opponents = { { fighter = "core:warrior-templates/default", level = 5 } }, rules = { { kind = "no_perks", target = "opponent" }, { kind = "ring_out", node = "root", axis = "X", min = -180, max = 180 }, }, } },}There is no function to call per rule. sf2.battles.register reads the list when the fight is created, and sf2.battles.patch accepts the same list on an existing fight. Items and perks a rule names must exist and belong to your mod or to a dependency. Unknown fields are errors that name the rule’s position, such as fights[1].rules[2].
Fields every rule shares
Section titled “Fields every rule shares”| Field | Default | Meaning |
|---|---|---|
kind |
Required | Which rule this is; see the next section. |
id |
Generated | A stable local ID. Leave it out unless something else must refer to the rule. |
target |
"all" |
Who the rule applies to: "player", "opponent" or "all". A few kinds ignore or restrict it; see the notes. |
mode |
"all" |
Which campaign mode: "normal", "eclipse" or "all". |
rounds |
Every round | List of round numbers, such as { 2, 3 }. |
phases |
Every phase | List of fight phases, such as { 2, 3 }. A round controller moves the fight between phases; see Split a fight into phases. Not on require_item, equip_item, avatar, name or recharge_magic_each_round. |
The built-in rule kinds
Section titled “The built-in rule kinds”Times given in frames are simulation frames, 60 per second. Fields marked ? are optional.
Restrictions and loadout
Section titled “Restrictions and loadout”kind |
Fields | What it does |
|---|---|---|
no_perks |
name? |
Disables perks for the target; name limits it to one perk name. |
require_item |
item, minimum_level? |
The player must have the item to enter. No target. |
equip_item |
item, minimum_level? |
Gives the target an item for this fight only. Not a permanent grant. |
no_button |
name |
Disables a combat button: "Punch", "Kick", "Ranged", "Magic" or "RaidCharge". Controls the player’s input, so use target = "player". |
attributes |
values |
Sets native attribute values, for example { WeaponDamage = 100 }. Unknown names do nothing. |
perk |
perk, aspect?, parameters? |
Applies a perk to the target. Must be a perk, not an enchantment. Settings work as in an opponent’s perk settings. |
recharge_magic_each_round |
None | Recharges magic every round. The target needs a usable magic item. |
resistance |
name, value |
The fight’s threshold for a resistance kept in the player’s save, such as "Resistance_2" (Ascension’s immunity). For every 500 points the player is short, the player’s hits do half the damage and the opponent’s twice as much. value is 0 to 100000. No target. Raise the saved value with a reward’s resistances. |
Controls and presentation
Section titled “Controls and presentation”kind |
Fields | What it does |
|---|---|---|
avatar |
name |
Replaces the portrait with an existing core portrait name. |
name |
name |
Replaces the displayed name. |
no_health_bar |
None | Hides health bars. Damage still counts. |
invert_joystick |
None | Reverses left and right for the player. Use target = "player". |
light_in_the_darkness |
radius, shape? |
Darkens the arena except for a spotlight that follows a fighter. radius is above 0 and at most 1 (about 0.2 is a small circle); shape runs from 0 (square) to 1 (circle, the default). Visual only. |
random_area |
image, icon?, width, fade_in, frames_on, fade_out, frames_off |
A band of the arena that appears at a random place, stays, fades and returns elsewhere. Pair it with a rule or perk that reacts to it. |
Arena and movement
Section titled “Arena and movement”kind |
Fields | What it does |
|---|---|---|
hot_ground |
frames, nodes, animations? |
Timed hot floor. nodes is 1 to 32 entries of { name, axis, min?, max? }. target must be "player" (default) or "opponent". |
ring_out |
node, axis, min, max |
Arena boundary on a body node (axis is "X" or "Y", min is below max). X bounds are measured from the stage centre for a native 1536-unit arena whose fighters reach ±608; on a stage where they can go further, both bounds move out by that extra reach so the zone keeps its distance from the walls. |
regeneration |
rate, frames_after_hit |
Regenerates health (positive rate, up to 1) or drains it (negative, down to -1) once frames_after_hit frames have passed since the last hit. |
no_animation |
name |
Disables one named animation for both fighters, such as "Jump". No target. |
remove_interval |
type |
Removes one interval class from the target: "Attack", "Block", "Invulnerable", "SelfUninterrupt", "Uninterrupt" or "Unstable". |
Combining rules
Section titled “Combining rules”kind |
Fields | What it does |
|---|---|---|
group |
rules, description? |
Applies up to 64 rules as one, with a single description in the fight’s rule list. With a description, rules may be empty: the group then only shows that text. Takes only rules, description, mode, rounds and id. |
random |
rules, refresh?, no_doubles? |
Picks one child at random. refresh is "each_fight" (default) or "each_round"; no_doubles avoids the same pick twice running. The game makes the pick, so a script cannot predict it. |
behavior |
behavior, parameters?, controls_outcome?, every_fight? |
Runs your Lua. See the next section. Cannot be placed inside group or random. |
rules = { { kind = "no_button", name = "Magic", target = "player" }, { kind = "group", description = sf2.text.register { id = "rules.cursed", language = "eng", value = "Cursed ground" }, rules = { { kind = "random_area", image = "ra_bleed", width = 500, fade_in = 60, frames_on = 180, fade_out = 60, frames_off = 240 }, { kind = "perk", perk = sf2.perks.get("core:perks/PERK_HERMITSTORM"), aspect = 100000 }, } }, { kind = "random", refresh = "each_round", no_doubles = true, rules = { { kind = "no_animation", name = "Jump" }, { kind = "no_health_bar" } } },}Write your own rule
Section titled “Write your own rule”When no built-in kind fits, write a behavior rule. A behavior is a table of Lua functions that the game calls at combat moments (a hit lands, a round begins, every tick). It is the same table you use for perks, so read Perks and enchantments for the full list, and Combat scripting for what a fighter handle can do.
This guardian only takes damage on every third hit:
local sf2 = require("sf2")
local guardian = { parameters = { every = 3 }, state = { lifetime = "round", fields = { hits = 0 } }, on_damage_resolving = function(self, fighter, event) if event.damage <= 0 then return end self.state.hits = self.state.hits + 1 if self.state.hits % self.params.every ~= 0 then fighter:scale_incoming_damage(0) end end,}
sf2.battles.register { id = "third_strike", page = sf2.map.get("core:zones/zone_1"), title = "Third Strike Trial", fights = { { rounds = 1, opponents = { { fighter = "core:warrior-templates/default", level = 5 } }, rules = { { kind = "behavior", behavior = guardian, parameters = { every = 3 }, target = "opponent" }, }, } },}How it behaves:
- A table written inline is registered for you. Pass the same table to another fight and it is reused.
parameterslets one behavior serve many fights: declare the names and defaults in the behavior, then override them per rule.stateis private to this rule and fighter, even when two rules share one behavior.lifetime = "round"resets it each round,"fight"keeps it across rounds. Usesf2.statefor progress that must outlive the fight.- Use
on_damage_resolvingto prevent or reduce damage that has not landed yet. Byon_damage_receivedthe hit is already done. - Filters apply to every callback: a rule limited to
rounds = { 2 }receives nothing in round one, so initialise its state inon_round_begin. - Rules run in list order, before the fighter’s perks. A failure in one rule does not stop the others, but changes it already made are not rolled back.
Two more options on a behavior rule:
every_fight = trueruns the rule in every offline fight while your mod is on, including other mods’ fights, without adding it to any list. It still honourstarget,modeandrounds. Keep its callbacks cheap, becauseon_tickthen runs everywhere. It does not run in Versus, the title screen’s sparring or the dojo.- To block a button on a condition, call
fighter:set_control_blockedfromon_round_beginof a player-targeted rule.
To add a rule to a core fight without replacing its own rules, patch with append_rules:
sf2.battles.patch { fight = "core:fights/zone_1/tournament/3", append_rules = { { kind = "behavior", behavior = guardian, parameters = { every = 2 }, target = "opponent" } },}This needs core in your manifest’s dependencies.
To change one detail of a core fight’s own rules instead, such as which animations count as off the ground on a hot floor, use edit_rules on sf2.battles.patch. It edits the game’s rules in place, so you do not have to restate them.
Remind the player on the pause screen
Section titled “Remind the player on the pause screen”The pause screen shows the fight’s rule text. When your behavior adds something the player should keep in mind, such as extra curses taken on before the fight, it can list it under that text with fighter:set_pause_notes: a few short lines, each with an optional picture. Set them in on_fight_begin, set them again when they change, and pass nil to remove them; they are gone by themselves once the fight ends.
local mark = sf2.assets.sprite("ui/curse") -- while the mod loads
-- In the behavior's on_fight_begin:fighter:set_pause_notes({ { text = "Curse of Ash: every hit you take burns.", icon = mark } })End a round on your own objective
Section titled “End a round on your own objective”Normally a round ends by knockout or timeout. A round controller is a behavior rule with controls_outcome = true. It is the only kind of rule allowed to call fighter:end_round("win") or "loss", which makes “survive ten seconds” or “land three hits” objectives possible.
local sf2 = require("sf2")
local survive = { state = { lifetime = "round", fields = { frames = 0 } }, on_tick = function(self, fighter, tick) self.state.frames = self.state.frames + tick.delta_frames if self.state.frames >= 600 then -- 10 seconds local accepted, reason = fighter:end_round("win") if not accepted then sf2.log.warn(reason) end end end,}
sf2.battles.patch { fight = "core:fights/zone_1/tournament/3", append_rules = { { kind = "behavior", behavior = survive, target = "player", controls_outcome = true }, },}The result always describes the player, even if called from the opponent’s callback. It is a normal round result, so rounds-to-win, rewards and saving all follow the usual path. A knockout, a timeout or a surrender still wins over your request.
Only one controller can apply to a fight in the same round and mode. Two overlapping controllers make the later mod fail to load, with an error naming both rules. Controllers with different mode or rounds filters can coexist. If several mods should cooperate, share one controller and pass data through saved state.
Split a fight into phases
Section titled “Split a fight into phases”A long boss fight can change as it goes on: once the boss falls below a mark, its wounds start to close, the lights go out, or kicks stop working. Each of these stages is a phase of the same round. The player keeps fighting; only the rules change.
Three pieces make it work:
- The round controller watches the fight and calls
fighter:set_phasewhen a stage is over. Every fight starts at 1, andfighter:snapshot().phasetells which phase is on. - Any rule can take
phases = { ... }. It is on only while the fight is in one of those phases, and switches on and off by itself when the phase changes. Agroupgives its phases to every rule inside it, so one group with adescriptionmakes a phase’s rule and its text. health_markson the boss draws dividers on its health bar, so the player sees where each stage ends (sf2.battles.register, under opponents).
This boss has 30 health bars split into three stages of 10, a rule and a text for each, and a 10% reward bonus for each stage cleared:
local sf2 = require("sf2")
local function text(id, value) return sf2.text.register { id = id, language = "eng", value = value }end
local SPLITS = { 20, 10 } -- boss health where the next stage begins
local seals = { state = { lifetime = "fight", fields = { cleared = 0 } }, on_tick = function(self, fighter, tick) local combat = fighter:snapshot() if not combat or not combat.opponent then return end local split = SPLITS[combat.phase] if split and combat.opponent.health <= split then fighter:set_phase(combat.phase + 1) self.state.cleared = self.state.cleared + 1 fighter:set_reward_bonus(0.1 * self.state.cleared) end end,}
sf2.battles.register { id = "warden", page = sf2.map.get("core:zones/zone_1"), title = "The Warden", fights = { { rounds = 1, round_time = 300, opponents = { { fighter = "core:warrior-templates/default", level = 30, health_bars = 30, visible_health_bars = 1, health_marks = { 10, 20 }, } }, rules = { { kind = "behavior", behavior = seals, target = "player", controls_outcome = true }, { kind = "group", phases = { 1 }, description = text("warden.first", "The Warden's wounds close"), rules = { { kind = "regeneration", rate = 0.002, frames_after_hit = 120, target = "opponent" } } }, { kind = "group", phases = { 2 }, description = text("warden.second", "The lights go out"), rules = { { kind = "light_in_the_darkness", radius = 0.25 } } }, { kind = "group", phases = { 3 }, description = text("warden.last", "No kicks"), rules = { { kind = "no_button", name = "Kick", target = "player" } } }, }, rewards = { [1] = { gems = 10 } }, } },}How it behaves:
- The phase changes at the end of the step in which the controller asks, without a round break. Rules leaving the phase stop at once: a hidden health bar comes back, the darkness lifts, a button returns. Rules entering it start fresh, as at the start of a round: a hot floor’s timer restarts, a random area picks a new place.
- To resume a boss at a later stage, call
fighter:set_phasefrom the controller’son_fight_begin: the round then starts in that phase. Set the boss’s health to match withfighter.opponent:change_health. - When the change gives the fight a different rule text, the new text appears as a banner over the fight and on the pause screen. Without a
description, nothing is shown, so a phase can also change quietly. - A perk rule out of phase stays on the fighter but cannot trigger, like
fighter:set_perk_disabled, and that also silences the same perk from the fighter’s own gear. Ano_perksrule in phase silences the perks it names the same way. Effects a perk already started run until they end. This works on the game’s own perks; a perk written in Lua keeps receiving its callbacks. - A
randomrule withphasesstill picks at the start of the round (or fight); the phase only switches the pick on and off. - A
behaviorrule withphasesreceives callbacks only during them; it gets no begin or end callback when the phase changes, so checksnapshot().phaseor keep your own state. - A behavior cannot sit inside a
group, so to give a behavior’s phase its text, add a group with the samephases, adescriptionandrules = {}. If the behavior leaves something on, such asfighter:set_controls_invertedor a meter, run it withoutphases, comparesnapshot().phaseitself, and undo the effect when the phase is over. - The controller itself takes no
phases: it is the rule that changes them. Rules that set up the fight before it starts (require_item,equip_item,avatar,name,recharge_magic_each_round) cannot have phases either, also not inside a group or random rule that has them. - The phase carries over into the next round. The reward bonus counts only if the player wins; see
fighter:set_reward_bonus.
Show a seal breaking
Section titled “Show a seal breaking”When a stage ends, the controller can mark the moment with fighter:play_seal_break. The fight holds still while a picture of your choice (a seal, a shield, a crest) cracks under three blows and shatters in the middle of the screen, then the fight goes on by itself. Call it beside set_phase, in the seals controller above:
local seal = sf2.assets.sprite("ui/seal") -- while the mod loads
-- In on_tick, where a stage ends:if split and combat.opponent.health <= split then fighter:set_phase(combat.phase + 1) fighter:play_seal_break(seal) -- about 2.4 seconds -- fighter:play_seal_break(seal, 1.5) would take 1.5 secondsendNo callback runs while it plays; the controller simply carries on at its next on_tick. The pieces are cut from your picture, so no extra art is needed, and nothing is drawn once it ends. To let the player drink elixirs or change gear between stages, open a Prepare screen next; see menus and settings.
To give the player a breather after the break, a behavior on the boss can hold his AI with fighter:set_ai_held and stop him being hurt with fighter:scale_incoming_damage until the next stage begins. The hold works whatever tactic the boss uses. To make curses and bleeds on him wait as well, instead of ticking down and hurting him while he rests, add fighter:set_perk_effects_frozen. To let the player’s hits and throws pass straight through him meanwhile, instead of landing for no damage, add fighter:set_invulnerable.
Adjust a fight as it starts
Section titled “Adjust a fight as it starts”sf2.battles.on_prepare lets a mod change each offline fight right before it begins, using ordinary Lua: look at the fight, decide, return a plan. It suits rules that depend on the player’s save, such as a difficulty chosen with a save option. For changes that are the same for everyone, patch the fight instead.
The handler runs for story, Survival, tournaments, challenges, bosses, mod modes and the Underworld. It runs for dojo sparring too, but only arrow_color is used there. It never runs for Versus, training, title-screen sparring or the Moveset Lab. A mod sets one handler.
local sf2 = require("sf2")
sf2.saves.option { id = "difficulty", title = "Choose your difficulty", default = "normal", choices = { { id = "normal", title = "Normal" }, { id = "brutal", title = "Brutal" } },}
sf2.battles.on_prepare(function(fight) if fight.underworld or fight.tutorial then return nil end if sf2.saves.get("difficulty") ~= "brutal" then return nil end if fight.preview then return { strength = 2 } end return { round_time = 60, strength = 2, minimum_ratio = 1.35, ai = { dodge = 1.5, chance_cap = 0.9 }, ai_add = { dodge = 0.3, block = 0.3 }, }end)The fight table describes the coming fight:
| Field | Meaning |
|---|---|
id |
The fight’s stable runtime ID. |
mode |
Fight kind: story, survival, tournament, challenge, boss, final, ascension, replayable, periodic, raid, tutorial, other or dojo. |
underworld, tutorial, endless |
True for Underworld fights, tutorial fights and untimed rounds. |
preview |
True when the map is only working out the difficulty bar. Return the same strength as for the real fight, and skip anything slow. |
score_victory |
True for a score victory: the round goes to whoever lands more hits, so its clock is part of the challenge. Leave its round_time short. |
round_time |
Seconds per round before your plan; 0 when untimed. |
ratio |
The difficulty-bar value before any plan: the last opponent’s rating divided by the player’s. |
enemies |
One entry per opponent: index, slots (equipped slots) and perks (qualified perk IDs). |
Return nil to leave the fight alone, or a plan with any of these fields:
| Field | Meaning |
|---|---|
round_time |
Seconds, 1 to 86400, or "endless". Untimed fights stay untimed. |
strength |
Multiplier on every opponent’s rating, 0.25 to 8. With strength = 2, opponents hit about 1.41 times as hard and take about 0.71 times the damage. |
minimum_ratio |
0 to 100. A floor for the difficulty bar; strength rises as needed to reach it. The bands start at 0 (Easy), 0.82, 1.3, 2.6 and 5.2 (Impossible). |
ai, ai_add |
Multipliers on, and amounts added to, the opponent’s own AI values: counter_attack, dodge, block, evade, quick_attack, table_attack, safe_attack, cautious_movement, dodge_missiles, dodge_magic, response_delay, enemy_response_delay, distance_error, frame_error. ai also takes chance_cap (0 to 1). |
enemies |
{ [index] = { perks = { perk handle, ... } } }: up to 8 perks added to that opponent for this fight, core perks or perks your mod registered. |
arrow_color |
"#RRGGBB" or "#RRGGBBAA" tint for the player’s ground arrow. A quick way to show the chosen difficulty. |
armored_against |
{ core perk handle, ... }, up to 32. Damage these perks of the player deal the opponents by draining their health (a negative regeneration) or by returning damage (a negative lifesteal) goes through the opponent’s body armour, like a weapon hit, instead of ignoring it. A perk also counts its enchantment variants (PERK_ITEM_SPECIAL_DAMAGE_RETURN covers its helm and armour versions). Against an opponent whose rating follows the player’s, armour changes nothing, so neither does this. |
For example, to make two armour-piercing perks respect the armour of every boss:
local PIERCING = { sf2.perks.get("core:perks/PERK_ROCK"), sf2.perks.get("core:perks/PERK_SKANDA_SET_KARMA") }
sf2.battles.on_prepare(function(fight) if fight.mode ~= "boss" then return nil end return { armored_against = PIERCING }end)When several mods set handlers their plans combine: strengths and AI multipliers multiply, additions add up, the highest minimum_ratio wins, and perk lists (including armored_against) are joined. Most opponents use the Standard fighting style, whose answers start each fight at zero and grow as the player repeats moves; ai_add gives them those answers from the first exchange.
Limits
Section titled “Limits”- A fight takes up to 100 rules (also after appending), and a
grouporrandomup to 64 children. - Every rule counts towards your mod’s 4096 registrations. A rule table you put in several fights is registered once and shared, so for a rule many fights use, build the table once and reuse it. Build a new table when a fight needs the rule different: changing a table after its first fight changes nothing.
- Replacing a fight’s rules with
rulesconflicts with every other change to that list. Preferappend_rules. - Rules run in offline fights only: not in Local or online Versus, training or the dojo, except
every_fightrules where noted above. - Custom HUD widgets and arbitrary win conditions beyond
controls_outcomeare not part of the rule API.
Where next
Section titled “Where next”- Combat scripting: every callback and fighter method.
- Sharing mods: how rules from different mods combine.
- Reference: callbacks for the exact arguments of each combat callback.