Files
LonaRPG-Online-Games/ModScripts/_Mods/LonaCraft/Scripts/140_AwayRaids.rb
T
2026-10-29 21:59:06 +04:00

1028 lines
38 KiB
Ruby

#==============================================================================
# LonaCraft - 140_AwayRaids.rb (board M1 item 2, research
# docs/RESEARCH_AWAY_RAIDS_MERCS.md section 2, owner decisions 2026-10-06).
# Raids on a base while Lona is somewhere else. No NPC is made: the raid is
# worked out on the base record and its map file and Lona reads the report.
# What it does:
# * Trigger: Game_Date#shift / addDays / oneDayForward aliases (after the
# game's, only for $game_date itself, as 100_Homes.rb's rent check). Every
# base keeps rec["away"]["t"], the last date unit handled; each NIGHT unit
# (dateAmt odd) since then gets one roll (at most "catchup_days" days), so
# one roll per base per game day at nightfall. The base Lona stands on is
# skipped (the live nap raid of 120_Raids.rb owns that night).
# * Skips: raids or "away" off; the first "grace_days" (1) after the base was
# founded (rec["made"]); "cooldown_days" (2) after an away raid; a base
# with no piece and no furniture.
# * Chance: "chance" (10) + min("value_bonus_cap" 10, value /
# "value_bonus_per" 10) percent, x "scenario_mult" (road / house / sewer
# 1.5), x the mercenaries' "deter" (0.5) when a squad is posted there and
# up (150_Mercs.rb). Group: Raids.pick_group of the base's scenario.
# * Party: AWAY_UNITS (the group's units in the 0-25 band of
# region_map_wildness_spawn, 34_Functions_RegionMap.rb:361-1115) plus the
# live extras (+1 EXTRA_UNIT per "extra_raider_per_value" of base value,
# at most "extra_raiders_max"); stats from $data_npcs (RolePlayS's
# overrides count). Breachers as live (120_Raids.rb role): race factor > 0,
# not ranged, atk >= "min_breach_atk". Looters: races in "looters".
# Power = sum of atk x health / 100.
# * Swing budget N = "swings" (24) x min("breacher_cap" 2, 1 +
# "per_extra_breacher" 0.15 x (the group's own breachers - 1)) x (1 +-
# "spread" 0.25) x (1 + WorldDifficulty x "difficulty_scale" 0.01); the
# extra raiders of a big base fight and loot but add no swings (owner,
# option A). One swing = one hit of
# the best breacher: max(1, atk - armour) x race factor, as the live siege.
# * Mercenaries posted at the base and up (150_Mercs.rb): squad power
# ("squad_power" 220 x the share of members up) x 0.8-1.2 against the
# party's power x 0.8-1.2. The squad wins: "repelled", nothing lost. The
# squad loses: every member is down for "down_days" (1) and the raid goes
# on with N x (1 - squad / party). Nobody is killed.
# * The outside-in simulation (no live map): the base's field map file
# ($data_mapinfos[rec["key"]], cached, 2 files) and its tileset flags;
# tile passage = Homes.layer_pass? (the layers, no events). The record's
# pieces on top, as 110_Bases.rb draws them: a door blocks, a wall top
# blocks but a lintel (a wall over a front door), the face under a wall
# (a tile that is neither wall nor door) blocks, a floor is open. Seeds =
# the walkable tiles on the edge of the play area (the bounds of the map's
# region tiles) or next to the exit ring (region 1), as Bases.inside_tiles.
# Owner's rule (2026-10-06): raiders come for what is INSIDE. Targets =
# storage with something in it (looters only) and other furniture while
# the smash cap is not reached. A base with no target is left alone (no
# fight, no damage, report "found nothing worth taking"). Walls and doors
# are broken ONLY on the way to a target: one breach per boundary, the
# cheapest piece on the path; walls that enclose nothing are never hit.
# Loop: (1) every furniture piece whose footprint is reached or next to a
# reached tile: a storage piece is looted (no swings), anything else is
# smashed at "smash" 0.25 ("smash_station" 0.10 for crafting stations;
# storage never), at most "smash_cap" (3) pieces a raid. (2) No target
# left: stop. (3) The rooms the outside does not reach are flooded into
# components; a room with a target, and every room that leads to one
# through more pieces, is worth a breach. Among the walls and doors next
# to the reached area that open such a room: the lowest cost
# ceil(hp left / damage), a door on a tie. (4) Cost <= N: N -= cost, the
# piece breaks (as Bases.break_piece, record only: a front door takes its
# lintel, a door on a floor leaves the floor), flood again. (5) Cost > N:
# the piece takes floor(N) x damage and the raid stops with what it has.
# The budget pays for breaches only. Stops too when the carry cap is full.
# * Loot: a chest's stacks by unit price, highest first, whole units until
# "loot_fraction" (0.5) of the chest's value or the carry cap
# ("carry_per_looter" 1500 x looters) is reached; a unit worth more than
# the carry left stays. Coins go first because they are worth most.
# * The record, the HP table, the chest boxes and the furniture list are
# edited; the next Game_Map#setup of the base draws it all. A base left
# with no piece and no furniture ends (Bases.remove_record), as live.
# * Reports: rec["away"]["reports"] (plain types, the last "reports_kept"):
# {"at", "group", "result" (repelled / breached / held), "mercs" (won /
# lost / nil), "broken" [[code, x, y]], "damaged" [[code, x, y, hp]],
# "taken" [[item_name, count]], "smashed" [item_name], "seen"}.
# * Telling Lona: the world-map marker of a base with an unseen report gets
# the quest "!" balloon (Bases.refresh_marker_balloons, at once when Lona
# is on the world map, and at every world-map setup); a popup when the
# date moved on the world map; on entering the base a popup and one
# message per unseen report (then "seen").
# * Debug (Numpad . off a base map, 120_Raids.rb): "away raid on base N now"
# and "hire the squad 3 days free" (150_Mercs.rb).
# * Nothing here runs without a base record: the date hook walks the base
# list (empty: nothing), the setup hook needs the base of the map.
# * Base names (Bases.name_of) in the reports and the world-map popups.
# * Difficulty (board R10, 120_Raids.rb diff / step, Config/Bases.json
# "difficulty"; "hard" changes nothing): the chance x "away_chance_mult"
# of the level x the base's Danger step (Lower 0.67, Higher 1.5);
# "grace_days" + "away_grace_days_add", "cooldown_days" +
# "away_cooldown_days_add" (0 at least); the swing budget N and the
# party's power against the mercenaries x "away_power_mult"; "smash" +
# "smash_add", "smash_station" + "smash_station_add" (0 to 1), "smash_cap"
# + "smash_cap_add", "loot_fraction" + "loot_add"; the party's extra
# raiders as live (Raids.extra_per_value / extras_max / max_raiders, the
# base's step included). Catch-up nights use the level of today's config.
# * Left during a raid (owner 2026-10-08: "If the player leaves the map,
# with a base, during a raid (any raid, night time event), then it needs
# to get treated like an away raid."). 120_Raids.rb leave_check (its
# Game_Map#setup alias, before the game's setup) calls left_raid! with
# the units still up: the party is made of THEM (race, atk, current
# health, ranged; the extra raiders the live raid added count as extras,
# so the swing budget is the group's own breachers', option A), not of
# AWAY_UNITS. The raid is worked out at once (date unit now), on the
# record as it stands: pieces keep the HP the siege left them and broken
# ones stay broken. Same rules as above: break only to reach a target,
# the smash cap, the loot share, the mercenaries, the maid, the level's
# away multipliers. The report gets "left" ("raid" / "hostile") and the
# line "Away/r_left"; the world-map smoke popup is queued. No double hit:
# rec["away"]["cool"] = now (the cooldown, as after any away raid) and
# rec["away"]["skip"] = that night's unit (now, or the next odd unit by
# day), which roll? refuses. Console and trace: "away: left-raid on
# <base>: <result>, broken N, damaged N, taken [...], smashed [...]".
#==============================================================================
module LonaCraft
module AwayRaids
TEXT = "LonaCraft:Raids:"
FILE = "Raids"
# group => [[unit, count], ...]: the 0-25 band of region_map_wildness_spawn
# (34_Functions_RegionMap.rb:361-1115, docs/RESEARCH_RAIDS.md 1.2)
AWAY_UNITS = {
"Orkind" => [["GoblinSpear", 4]],
"OrkindPlayGround" => [["GoblinSpear", 3], ["HobgoblinSpear", 2], ["OrcCommoner", 1]],
"Fishkind" => [["FishkindCharger", 2], ["FishkindCommoner", 2]],
"FishPPL" => [["DeeponeSpearGuard", 1], ["DeeponeBowGuard", 1], ["DeeponeWatcher", 1]],
"BanditMobs" => [["MobHumanRogueSpear", 3], ["MobHumanRogueScout", 2]],
"CommonMobs" => [["MobHumanCommoner", 3], ["MobMootCommoner", 1], ["MobHumanPickAxe", 1]],
"UndeadWalking" => [["UndeadCommoner", 3], ["UndeadSickle", 3], ["UndeadEliteWarrior", 1], ["UndeadEliteSpear", 1]],
"WolfGroup" => [["WildDireWolf", 2]],
"AbomManager" => [["AbomCreatureSpider", 2], ["AbomCreatureZombie", 2], ["AbomCreatureScorpion", 1]],
"AbomSpider" => [["AbomCreatureSpider", 5]],
"AbomBreedlingRaid" => [["AbomCreatureBreedling", 4]],
"SewerRats" => [["WildGiantMice", 5]]
}
# Raids::EXTRA_UNIT names that are EventLib templates, not $data_npcs entries
EXTRA_STATS = {"RandomGoblin" => "GoblinSpear", "RandomHobgoblin" => "HobgoblinSpear"}
DIRS = [[2, 0, 1], [4, -1, 0], [6, 1, 0], [8, 0, -1]]
REPORT_DELAY = 45 # frames after entering a base before its report shows
LIST_MAX = 6 # names per list in a report, then "and N more"
@maps = {} # map file => RPG::Map (2 kept)
@pending = nil # [base id, frames left]: the entry report
def self.say(text)
p "LonaCraft AwayRaids: #{text}"
end
def self.text_key(key)
"#{TEXT}#{key}"
end
def self.text(key)
$game_text[text_key(key)].to_s
end
def self.bases
LonaCraft::Bases
end
def self.raids
LonaCraft::Raids
end
def self.ac
raids.cfg["away"]
end
def self.rc
raids.rc
end
def self.enabled?
return false unless defined?(LonaCraft::Bases) && defined?(LonaCraft::Raids)
raids.enabled? && ac["enabled"] ? true : false
end
def self.per_day
defined?(Game_Date::DAY_LENGTH) ? Game_Date::DAY_LENGTH : 2
end
def self.notice(id, str)
return unless defined?(LonaCraft::Homes)
LonaCraft::Homes.notice(LonaCraft::RuntimeText.key(FILE, id, str))
end
def self.state(rec)
rec["away"] = {} unless rec["away"].is_a?(Hash)
rec["away"]
end
def self.mercs
defined?(LonaCraft::Mercs) ? LonaCraft::Mercs : nil
end
#----------------------------------------------------------------------
# The date hook
#----------------------------------------------------------------------
def self.on_date_moved
return unless enabled?
list = bases.list.select{|r| r.is_a?(Hash) }
return if list.empty?
now = bases.date_now
map = $game_map
here = (map && !map.isOverMap) ? map.map_id_rec : nil
hits = []
list.each{|rec|
st = state(rec)
last = st["t"].is_a?(Integer) ? st["t"] : now - 1
st["t"] = [last, now].max
next if here && rec["key"] == here
next if now <= last
first = [last + 1, now - ac["catchup_days"].to_i * per_day + 1].max
(first..now).each{|u|
next unless u.odd?
break unless bases.list.include?(rec)
next unless roll?(rec, u)
rep = raid!(rec, u)
hits << [rec, rep] if rep
}
}
return if hits.empty?
if map && map.isOverMap
hits.each{|rec, rep|
next unless bases.list.include?(rec)
notice("rt_smoke_#{rec["id"]}", text("Away/notice_smoke").gsub("BASE", bases.name_of(rec)))
}
bases.refresh_marker_balloons(map)
end
rescue => e
say("date hook error #{e.class} #{e.message}")
end
# true when base +rec+ is raided at night unit +u+
def self.roll?(rec, u)
st = state(rec)
per = per_day
made = rec["made"]
grace = [ac["grace_days"].to_i + raids.diff("away_grace_days_add").to_i, 0].max
return false if made.is_a?(Integer) && u < made + grace * per
return false if st["skip"].is_a?(Integer) && u <= st["skip"] # 2026-10-08: that night went to a left raid
cool = st["cool"]
cool_days = [ac["cooldown_days"].to_i + raids.diff("away_cooldown_days_add").to_i, 0].max
return false if cool.is_a?(Integer) && u < cool + cool_days * per
return false if bases.base_empty?(rec)
value = raids.base_value(rec)
per_value = ac["value_bonus_per"].to_f
bonus = per_value > 0 ? [value / per_value, ac["value_bonus_cap"].to_f].min : 0.0
pct = ac["chance"].to_f + bonus
scen = raids.scenario_for(rec)
mult = ac["scenario_mult"].is_a?(Hash) ? ac["scenario_mult"][scen] : nil
pct *= mult.to_f if mult
pct *= raids.diff("away_chance_mult").to_f * raids.step(rec, "away_chance_mult").to_f # R10
guard = mercs ? mercs.guard(rec, u) : nil
pct *= mercs.cfg["deter"].to_f if guard
hit = rand * 100.0 < pct
say("base #{rec["id"]} night #{u}: #{pct.round(1)} % (value #{value}, #{scen}, #{raids.diff_tag(rec)}#{guard ? ", guarded" : ""}) #{hit ? "RAID" : "quiet"}")
hit
end
#----------------------------------------------------------------------
# The party
#----------------------------------------------------------------------
def self.units_of(group, rec)
names = []
(AWAY_UNITS[group] || []).each{|n, c| c.to_i.times{ names << n } }
extra = [raids.base_value(rec) / raids.extra_per_value, raids.extras_max(rec)].min # R10 sizes
extra = [extra, raids.max_raiders - names.size].min
unit = raids::EXTRA_UNIT[group]
unit = EXTRA_STATS[unit] || unit
extra.times{ names << unit } if unit
names
end
def self.party(group, rec)
units = []
own = (AWAY_UNITS[group] || []).inject(0){|t, nc| t + nc[1].to_i }
units_of(group, rec).each_with_index{|n, i|
d = $data_npcs ? $data_npcs[n] : nil
next if d.nil?
units << {:name => n, :race => d.race.to_s, :atk => d.atk.to_i, :health => d.health.to_i,
:ranged => d.ranged ? true : false, :extra => i >= own}
}
party_of(units)
end
# the party of +units+ ({:name, :race, :atk, :health, :ranged, :extra});
# also the units a live raid left behind (left_raid!)
def self.party_of(units)
looters = ac["looters"].is_a?(Array) ? ac["looters"] : []
min_atk = rc["min_breach_atk"].to_i
breach = rc["breach"]
breachers = units.select{|u| breach[u[:race]].to_f > 0 && !u[:ranged] && u[:atk] >= min_atk }
# owner, 2026-10-06 (option A): the swing budget counts the group's own
# breachers only; the extra raiders a big base draws fight and loot
{:units => units, :breachers => breachers, :own_breachers => breachers.count{|u| !u[:extra] },
:looters => units.count{|u| looters.include?(u[:race]) },
:power => units.inject(0.0){|t, u| t + u[:atk] * u[:health] / 100.0 }}
end
# damage of the best breacher against +armour+, 0 when none
def self.damage(pt, armour)
best = 0
pt[:breachers].each{|u|
f = rc["breach"][u[:race]].to_f
d = [([u[:atk] - armour, 1].max * f).round, 1].max
best = d if d > best
}
best
end
def self.difficulty
v = $story_stats ? $story_stats["WorldDifficulty"].to_f : 0.0
v > 0 ? v : 0.0
rescue
0.0
end
def self.budget(pt)
b = pt[:own_breachers].to_i
f = [ac["breacher_cap"].to_f, 1.0 + ac["per_extra_breacher"].to_f * [b - 1, 0].max].min
s = ac["spread"].to_f
ac["swings"].to_f * f * (1.0 + (rand * 2.0 - 1.0) * s) * (1.0 + difficulty * ac["difficulty_scale"].to_f) *
raids.diff("away_power_mult").to_f # R10
end
# R10: the scaled smash chances, cap and loot share
def self.smash_cap
[ac["smash_cap"].to_i + raids.diff("smash_cap_add").to_i, 0].max
end
def self.smash_chance(station)
c = station ? ac["smash_station"].to_f + raids.diff("smash_station_add").to_f : ac["smash"].to_f + raids.diff("smash_add").to_f
[[c, 0.0].max, 1.0].min
end
def self.loot_fraction
[ac["loot_fraction"].to_f + raids.diff("loot_add").to_f, 0.0].max
end
#----------------------------------------------------------------------
# The map grid (map file + the record's pieces)
#----------------------------------------------------------------------
def self.map_file(rec)
info = $data_mapinfos ? $data_mapinfos[rec["key"]] : nil
if !info.is_a?(RPG::MapInfo) && bases.respond_to?(:ensure_registered)
bases.ensure_registered(rec)
info = $data_mapinfos[rec["key"]]
end
return nil unless info.is_a?(RPG::MapInfo)
fn = info.filename
return @maps[fn] if @maps.key?(fn)
@maps.clear if @maps.size >= 2
@maps[fn] = load_data(fn)
rescue => e
say("map file error #{e.class} #{e.message}")
nil
end
def self.grid(rec)
m = map_file(rec)
return nil if m.nil? || m.data.nil?
ts = $data_tilesets[m.tileset_id] || $data_tilesets[1]
return nil if ts.nil?
data = m.data
w = data.xsize
h = data.ysize
xs = []
ys = []
exits = {}
(0...h).each{|y|
(0...w).each{|x|
r = data[x, y, 3].to_i >> 8
next if r == 0
xs << x
ys << y
exits[[x, y]] = true if r == bases::EXIT_REGION
}
}
b = xs.empty? ? [0, 0, w - 1, h - 1] : [[xs.min - 1, 0].max, [ys.min - 1, 0].max, [xs.max + 1, w - 1].min, [ys.max + 1, h - 1].min]
{:data => data, :flags => ts.flags, :w => w, :h => h, :b => b, :exits => exits, :pieces => bases.pieces_of(rec)}
end
def self.pv(g, x, y)
g[:pieces][bases.piece_key(x, y)]
end
# a piece (or the face under a wall) stands on (x, y)
def self.blocked?(g, x, y)
v = pv(g, x, y)
return true if bases.door?(v)
return !bases.lintel?(g[:pieces], x, y) if bases.wall?(v)
y > 0 && bases.wall?(pv(g, x, y - 1))
end
def self.tile_pass?(g, x, y, d)
return false if x < 0 || y < 0 || x >= g[:w] || y >= g[:h]
return false if blocked?(g, x, y)
v = pv(g, x, y)
return true if bases.floor?(v) || bases.wall?(v) # a floor, or a lintel (walked under)
LonaCraft::Homes.layer_pass?(g[:data], g[:flags], g[:w], g[:h], x, y, d)
end
def self.walkable?(g, x, y)
[2, 4, 6, 8].any?{|d| tile_pass?(g, x, y, d) }
end
def self.flood(g)
ax0, ay0, ax1, ay1 = g[:b]
reached = {}
queue = []
(ay0..ay1).each{|y|
(ax0..ax1).each{|x|
edge = x == ax0 || x == ax1 || y == ay0 || y == ay1 ||
[[1, 0], [-1, 0], [0, 1], [0, -1]].any?{|dx, dy| g[:exits][[x + dx, y + dy]] }
next unless edge
next unless walkable?(g, x, y)
reached[[x, y]] = true
queue << [x, y]
}
}
head = 0
while head < queue.size
x, y = queue[head]
head += 1
DIRS.each{|d, dx, dy|
k = [x + dx, y + dy]
next if k[0] < ax0 || k[0] > ax1 || k[1] < ay0 || k[1] > ay1
next if reached[k]
next unless tile_pass?(g, x, y, d) && tile_pass?(g, k[0], k[1], 10 - d)
reached[k] = true
queue << k
}
end
reached
end
# the tiles a wall or door covers: itself, and a wall's face below
def self.piece_tiles(g, x, y)
out = [[x, y]]
v = pv(g, x, y)
if bases.wall?(v) && y + 1 < g[:h]
below = pv(g, x, y + 1)
out << [x, y + 1] unless bases.wall?(below) || bases.door?(below)
end
out
end
# {tile => component id} of the walkable tiles the outside does not reach
def self.components(g, reached)
ax0, ay0, ax1, ay1 = g[:b]
comp = {}
n = 0
(ay0..ay1).each{|y|
(ax0..ax1).each{|x|
k = [x, y]
next if reached[k] || comp[k] || !walkable?(g, x, y)
comp[k] = n
queue = [k]
head = 0
while head < queue.size
cx, cy = queue[head]
head += 1
DIRS.each{|d, dx, dy|
c = [cx + dx, cy + dy]
next if c[0] < ax0 || c[0] > ax1 || c[1] < ay0 || c[1] > ay1
next if reached[c] || comp[c]
next unless tile_pass?(g, cx, cy, d) && tile_pass?(g, c[0], c[1], 10 - d)
comp[c] = n
queue << c
}
end
n += 1
}
}
comp
end
# {[x, y] => room id} of the walkable tiles inside the walls of base
# +rec+, worked out from its map file and record (no live map needed);
# only tiles within the base's own bounds count, as Bases.inside_tiles.
# Used by 170_Maid.rb (wages, cooking, the bed rule).
def self.inside_rooms(rec)
g = grid(rec)
return {} if g.nil?
cells = bases.cells_of(g[:pieces])
return {} if cells.empty?
x0 = cells.map{|c| c[0] }.min
x1 = cells.map{|c| c[0] }.max
y0 = cells.map{|c| c[1] }.min
y1 = cells.map{|c| c[1] }.max + 1
comp = components(g, flood(g))
comp.select{|c, id| c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 }
rescue => e
say("inside rooms error #{e.class} #{e.message}")
{}
end
# [[cost, door first, x, y, hp, dmg], ...]: the walls and doors next to
# the reached area that lead (through further pieces, if need be) to a
# room holding a target (owner, 2026-10-06: walls are broken only to get
# at what is inside, one breach per boundary, the cheapest one)
def self.candidates(g, rec, reached, pt, target_tiles)
comp = components(g, reached)
valuable = {}
target_tiles.each{|c| valuable[comp[c]] = true if comp[c] }
return [] if valuable.empty?
links = []
g[:pieces].each{|k, v|
next unless bases.wall?(v) || bases.door?(v)
x, y = k.split(",").map{|n| n.to_i }
tiles = piece_tiles(g, x, y)
touch = false
ids = {}
tiles.each{|tx, ty|
DIRS.each{|d, dx, dy|
c = [tx + dx, ty + dy]
next if tiles.include?(c)
touch = true if reached[c]
ids[comp[c]] = true if comp[c]
}
}
links << [x, y, v, touch, ids.keys] unless ids.empty?
}
# rooms from which a target can be reached through more pieces
leads = valuable.dup
loop do
grown = false
links.each{|x, y, v, touch, ids|
next unless ids.any?{|i| leads[i] }
ids.each{|i|
next if leads[i]
leads[i] = true
grown = true
}
}
break unless grown
end
out = []
links.each{|x, y, v, touch, ids|
next unless touch && ids.any?{|i| leads[i] }
hp = bases.hp_at(rec, x, y)
next if hp.nil?
kind = bases.piece_kind(g[:pieces], x, y)
dmg = damage(pt, bases.armour_of(kind))
next if dmg <= 0
out << [(hp[0].to_f / dmg).ceil, bases.door?(v) ? 0 : 1, x, y, hp[0], dmg]
}
out
end
# the record-only break (Bases.break_piece without the live map)
def self.break_offline(rec, x, y)
pieces = bases.pieces_of(rec)
k = bases.piece_key(x, y)
v = pieces[k]
gone = [[v, x, y]]
if bases.door?(v)
up = bases.piece_key(x, y - 1)
if !v.include?("S") && bases.wall?(pieces[up])
gone << [pieces[up], x, y - 1]
pieces.delete(up)
bases.clear_hp(rec, x, y - 1)
end
if bases.floor?(v)
pieces[k] = "F"
else
pieces.delete(k)
end
else
pieces.delete(k)
end
bases.clear_hp(rec, x, y)
gone
end
#----------------------------------------------------------------------
# Furniture: loot and smash
#----------------------------------------------------------------------
def self.fur
defined?(LonaCraft::Furniture) ? LonaCraft::Furniture : nil
end
def self.touches?(tiles, reached)
tiles.any?{|tx, ty|
reached[[tx, ty]] || DIRS.any?{|d, dx, dy| reached[[tx + dx, ty + dy]] }
}
end
def self.price_of(obj)
obj.respond_to?(:price) ? obj.price.to_i : 0
rescue
0
end
def self.name_of(obj)
obj.respond_to?(:item_name) ? obj.item_name.to_s : nil
end
# takes from the chest of furniture record +f+; returns the value taken
def self.loot_box(f, room, taken)
box = fur.box_contents(f["box"].to_i)
return 0 unless box.is_a?(Hash)
stacks = box.select{|obj, n| n.to_i > 0 && price_of(obj) > 0 && name_of(obj) }.to_a
return 0 if stacks.empty?
value = stacks.inject(0){|t, (obj, n)| t + price_of(obj) * n.to_i }
target = value * loot_fraction
got = 0
stacks.sort_by{|obj, n| -price_of(obj) }.each{|obj, n|
price = price_of(obj)
take = 0
while take < n.to_i && got < target && price <= room - got
take += 1
got += price
end
next if take <= 0
$game_boxes.remove_item(obj, take, f["box"].to_i, false)
name = name_of(obj)
row = taken.find{|r| r[0] == name }
if row
row[1] += take
else
taken << [name, take]
end
}
got
end
#----------------------------------------------------------------------
# One raid
#----------------------------------------------------------------------
# Works out an away raid on +rec+ at date unit +u+; returns the report or
# nil. +pt+ / +left+: the party and the kind of a raid Lona left (left_raid!)
def self.raid!(rec, u, group = nil, pt = nil, left = nil)
scen = raids.scenario_for(rec)
group ||= raids.pick_group(scen)
return nil if group.nil?
pt ||= party(group, rec)
if pt[:units].empty?
say("base #{rec["id"]}: #{group} has no unit in $data_npcs, no raid")
return nil
end
st = state(rec)
st["cool"] = u
rep = {"at" => u, "group" => group.to_s, "result" => "held", "mercs" => nil,
"broken" => [], "damaged" => [], "taken" => [], "smashed" => [], "seen" => false}
rep["left"] = left.to_s if left # 2026-10-08: Lona left during the raid
unless fur && worth_raiding?(rec, pt)
rep["result"] = "nothing" # the owner's rule: no furniture, no chest = no damage
return file_report(rec, rep)
end
n = budget(pt)
scale = 1.0 + difficulty * ac["difficulty_scale"].to_f
guard = mercs ? mercs.guard(rec, u) : nil
if guard
sp = guard * (0.8 + rand * 0.4)
rp = pt[:power] * scale * raids.diff("away_power_mult").to_f * (0.8 + rand * 0.4) # R10
if sp >= rp
rep["result"] = "repelled"
rep["mercs"] = "won"
say("base #{rec["id"]}: the mercenaries (#{sp.round}) drove off #{group} (#{rp.round})")
return file_report(rec, rep)
end
rep["mercs"] = "lost"
mercs.knock_down(rec, u)
n *= 1.0 - sp / rp
say("base #{rec["id"]}: #{group} (#{rp.round}) beat the mercenaries (#{sp.round}), budget #{n.round(1)}")
end
simulate(rec, pt, n, rep)
rep["result"] = "breached" unless rep["broken"].empty?
file_report(rec, rep)
rescue => e
say("raid error #{e.class} #{e.message} #{e.backtrace ? e.backtrace[0] : ""}")
nil
end
# the furniture records worth breaking in for: storage with something in
# it (looters only), other pieces while the smash cap is not reached
def self.targets(rec, pt, done, smashed)
return [] unless fur
cap = smash_cap
bases.furniture_on(rec).select{|f|
next false if done[f["uid"].to_i]
kind = fur.kind_for(f["item_name"])
next false if kind.nil?
if kind[:storage]
pt[:looters] > 0 && !fur.box_empty?(f["box"].to_i)
else
smashed < cap
end
}
end
def self.target_tiles(f)
kind = fur.kind_for(f["item_name"])
out = []
fur.footprint(kind, f["x"].to_i, f["y"].to_i).each{|tx, ty|
out << [tx, ty]
DIRS.each{|d, dx, dy| out << [tx + dx, ty + dy] }
}
out
end
# true when the base holds anything worth a raid (the owner's rule: no
# furniture, no chest = nothing to take, the walls are left alone)
def self.worth_raiding?(rec, pt)
!targets(rec, pt, {}, 0).empty?
end
def self.simulate(rec, pt, n, rep)
g = grid(rec)
if g.nil?
say("base #{rec["id"]}: no map file, the raiders leave")
return
end
carry = ac["carry_per_looter"].to_i * pt[:looters]
cap = smash_cap
got = 0
done = {}
loop do
reached = flood(g)
# R13: raiders who reach the maid's room with blows left may kill her
if defined?(LonaCraft::Maid) && !rep["maid"] && n >= 1
res = LonaCraft::Maid.away_reached(rec, reached)
rep["maid"] = res if res
end
bases.furniture_on(rec).dup.each{|f|
uid = f["uid"].to_i
next if done[uid]
kind = fur.kind_for(f["item_name"])
next if kind.nil?
next unless touches?(fur.footprint(kind, f["x"].to_i, f["y"].to_i), reached)
done[uid] = true
if kind[:storage]
next if pt[:looters] <= 0 || got >= carry
got += loot_box(f, carry - got, rep["taken"])
else
next if rep["smashed"].size >= cap
chance = smash_chance(kind[:station])
next unless rand < chance
fur.records.delete(f)
rep["smashed"] << f["item_name"].to_s
end
}
break if pt[:looters] > 0 && carry > 0 && got >= carry
left = targets(rec, pt, done, rep["smashed"].size)
break if left.empty?
break if pt[:breachers].empty? || n < 1
tiles = []
left.each{|f| tiles.concat(target_tiles(f)) }
list = candidates(g, rec, reached, pt, tiles)
break if list.empty?
best = list.min_by{|c| [c[0], c[1], c[3], c[2]] }
cost, _, x, y, hp, dmg = best
if cost > n
rest = hp - n.floor * dmg
if rest < hp
bases.set_hp(rec, x, y, rest)
rep["damaged"] << [pv(g, x, y).to_s, x, y, rest]
end
break
end
n -= cost
rep["broken"].concat(break_offline(rec, x, y))
end
end
def self.file_report(rec, rep)
st = state(rec)
st["reports"] = [] unless st["reports"].is_a?(Array)
st["reports"] << rep
keep = [ac["reports_kept"].to_i, 1].max
st["reports"].shift while st["reports"].size > keep
say("base #{rec["id"]} raided by #{rep["group"]}: #{rep["result"]}, broken #{rep["broken"].size}, damaged #{rep["damaged"].size}, taken #{rep["taken"].inspect}, smashed #{rep["smashed"].inspect}")
if bases.base_empty?(rec)
name = bases.name_of(rec)
bases.remove_record(rec)
mercs.base_gone(rec) if mercs
notice("rt_gone_#{rec["id"]}", text("Away/notice_gone").gsub("BASE", name))
say("base #{rec["id"]} has nothing left and is gone")
end
rep
end
#----------------------------------------------------------------------
# Left during a raid (owner 2026-10-08, header; 120_Raids.rb handover)
#----------------------------------------------------------------------
# The live raid on +rec+ goes on as an away raid now, with +units+ (the
# raiders up when Lona left) of +group+; +what+ "raid" / "hostile".
def self.left_raid!(rec, group, units, what)
u = bases.date_now
st = state(rec)
st["t"] = [st["t"].is_a?(Integer) ? st["t"] : u, u].max
st["skip"] = u.odd? ? u : u + 1 # that night's roll is not made (no double hit)
pt = party_of(units)
say("base #{rec["id"]}: Lona left during the #{what == "hostile" ? "hostile siege" : "raid"}, #{group}: " +
"#{pt[:units].size} units, #{pt[:breachers].size} breachers (#{pt[:own_breachers]} own), " +
"#{pt[:looters]} looters, power #{pt[:power].round} (#{raids.diff_tag(rec)})")
name = bases.name_of(rec)
rep = raid!(rec, u, group, pt, what)
st["cool"] = u
line = "away: left-raid on #{name}: no report (no unit)"
if rep
maid = rep["maid"].is_a?(Array) ? ", maid #{rep["maid"][0]}" : ""
line = "away: left-raid on #{name}: #{rep["result"]}, broken #{rep["broken"].size}, damaged #{rep["damaged"].size}, " +
"taken #{rep["taken"].inspect}, smashed #{rep["smashed"].inspect}#{maid}"
end
say(line)
LonaCraft.trace(line) if LonaCraft.respond_to?(:trace_on?) && LonaCraft.trace_on?
if rep && bases.list.include?(rec)
notice("rt_smoke_#{rec["id"]}", text("Away/notice_smoke").gsub("BASE", name))
end
rep
rescue => e
say("left raid error #{e.class} #{e.message} #{e.backtrace ? e.backtrace[0] : ""}")
nil
end
#----------------------------------------------------------------------
# Report on entry
#----------------------------------------------------------------------
def self.after_setup(map)
@pending = nil
return if map.nil? || map.isOverMap || !enabled?
rec = bases.record_for_map(map)
return if rec.nil? || bases.report_for(rec).empty?
@pending = [rec["id"], REPORT_DELAY]
end
def self.update
return if @pending.nil?
return unless SceneManager.scene_is?(Scene_Map)
return if $game_map.nil? || $game_player.nil?
return if $game_message && $game_message.busy?
return if $game_map.interpreter && $game_map.interpreter.running?
@pending[1] -= 1
return if @pending[1] > 0
id = @pending[0]
@pending = nil
$game_temp.loadEval("lonacraft_away_reports(#{id.to_i})")
rescue => e
say("report error #{e.class} #{e.message}")
@pending = nil
end
def self.group_name(group)
t = text("Away/group/#{group}")
t.empty? || t.start_with?(TEXT) ? group.to_s : t
end
def self.piece_name(code)
key = if bases.door?(code)
"WoodenDoor"
elsif bases.stone?(code)
"StoneWall"
else
"PalisadeWall"
end
$game_text["LonaCraft:Bases:#{key}/item_name"].to_s
end
def self.item_label(name)
obj = $data_ItemName[name.to_s]
obj ? $game_text[obj.name].to_s : name.to_s
end
# "a x2, b, c x3" (at most LIST_MAX names, then "and N more")
def self.join_list(pairs)
shown = pairs.first(LIST_MAX).map{|label, n| n > 1 ? "#{label} x#{n}" : label }
rest = pairs.size - shown.size
shown << text("Away/r_more").gsub("NUM", rest.to_s) if rest > 0
shown.join(", ")
end
def self.count_pairs(names)
out = []
names.each{|label|
row = out.find{|r| r[0] == label }
if row
row[1] += 1
else
out << [label, 1]
end
}
out
end
# the message of one report: pages joined by "\f"
def self.report_text(rep, now, base_name = "")
who = group_name(rep["group"])
ago = now - rep["at"].to_i
pages = []
head = ago <= 1 ? text("Away/r_last_night") : text("Away/r_nights_ago").gsub("NUM", ((ago + 1) / per_day).to_s)
lines = [head.gsub("WHO", who).gsub("BASE", base_name.to_s)]
lines << text("Away/r_left") if rep["left"] # 2026-10-08: Lona left during the raid
case rep["result"]
when "repelled"
lines << text("Away/r_repelled")
when "nothing"
lines << text("Away/r_nothing")
else
lines << text("Away/r_mercs_lost") if rep["mercs"] == "lost"
lines << text("Away/r_held") if rep["broken"].empty?
end
pages << lines.join("\n")
if rep["maid"].is_a?(Array)
pages << text(rep["maid"][0] == "killed" ? "Away/r_maid_killed" : "Away/r_maid_hid").gsub("NAME", rep["maid"][1].to_s)
end
unless rep["result"] == "repelled" || rep["result"] == "nothing"
parts = []
broken = Array(rep["broken"]).map{|r| piece_name(r[0]) }
parts << text("Away/r_broken").gsub("LIST", join_list(count_pairs(broken))) unless broken.empty?
damaged = Array(rep["damaged"]).map{|r| piece_name(r[0]) }
parts << text("Away/r_damaged").gsub("LIST", join_list(count_pairs(damaged))) unless damaged.empty?
pages << parts.join("\n") unless parts.empty?
taken = Array(rep["taken"]).map{|name, n| [item_label(name), n.to_i] }
pages << text("Away/r_taken").gsub("LIST", join_list(taken)) unless taken.empty?
smashed = Array(rep["smashed"]).map{|name| item_label(name) }
pages << text("Away/r_smashed").gsub("LIST", join_list(count_pairs(smashed))) unless smashed.empty?
end
pages.join("\f")
end
#----------------------------------------------------------------------
# Debug (Numpad . off a base map, 120_Raids.rb)
#----------------------------------------------------------------------
def self.debug_raid(rec)
return say("debug: away raids are off") unless enabled?
rep = raid!(rec, bases.date_now)
bases.debug_say(rep ? "LonaCraft debug base #{rec["id"]}: #{rep["group"]}, #{rep["result"]}" : "LonaCraft debug no raid (no group)")
bases.refresh_marker_balloons($game_map) if $game_map && $game_map.isOverMap
end
end
end
#==============================================================================
# Game_Date: the away rolls ride on every date move (as 100_Homes.rb's rent)
#==============================================================================
class Game_Date
[:shift, :addDays, :oneDayForward].each{|meth|
old = "#{meth}_lonacraft_away".to_sym
next unless method_defined?(meth)
next if method_defined?(old)
alias_method old, meth
define_method(meth){|*args, **kwargs, &block|
result = kwargs.empty? ? send(old, *args, &block) : send(old, *args, **kwargs, &block)
begin
LonaCraft::AwayRaids.on_date_moved if $game_date.equal?(self)
rescue => e
p "LonaCraft AwayRaids date hook error #{e.class} #{e.message}"
end
result
}
}
end
#==============================================================================
# Game_Map: the entry report is armed after the base map is set up
#==============================================================================
class Game_Map
unless method_defined?(:setup_lonacraft_away)
alias_method :setup_lonacraft_away, :setup
def setup(map_id)
setup_lonacraft_away(map_id)
begin
LonaCraft::AwayRaids.after_setup(self)
rescue => e
p "LonaCraft AwayRaids setup error #{e.class} #{e.message}"
end
end
end
end
class Scene_Map
unless method_defined?(:update_lonacraft_away)
alias_method :update_lonacraft_away, :update
def update
update_lonacraft_away
LonaCraft::AwayRaids.update
end
end
end
#==============================================================================
# Game_Interpreter: the entry report and the debug menu
#==============================================================================
class Game_Interpreter
def lonacraft_away_reports(id)
away = LonaCraft::AwayRaids
rec = LonaCraft::Bases.record_by_id(id)
return if rec.nil?
list = LonaCraft::Bases.report_for(rec)
return if list.empty?
now = LonaCraft::Bases.date_now
$game_map.popup(0, "LonaCraft:Raids:Away/popup_entry", 0, 0)
list.each_with_index{|rep, i|
rep["seen"] = true
key = LonaCraft::RuntimeText.key(away::FILE, "rt_report_#{i}", away.report_text(rep, now, LonaCraft::Bases.name_of(rec)))
call_msg(key)
}
portrait_hide if respond_to?(:portrait_hide)
$game_temp.choice = -1
rescue => e
p "LonaCraft AwayRaids report window error #{e.class} #{e.message}"
end
def lonacraft_away_debug_menu
bases = LonaCraft::Bases
away = LonaCraft::AwayRaids
here = $game_map && !$game_map.isOverMap ? $game_map.map_id_rec : nil
recs = bases.list.select{|r| r.is_a?(Hash) && r["key"] != here }.first(8)
opts = recs.map{|r| "Away raid on base #{r["id"]} now" }
opts << "Hire the squad 3 days free" if defined?(LonaCraft::Mercs)
opts << "Hire a maid free" if defined?(LonaCraft::Maid)
opts << "Cancel"
lonacraft_raid_debug_choice("LonaCraft debug, away raids and mercenaries", opts)
pick = $game_temp.choice
$game_temp.choice = -1
eventPlayEnd
return if pick.nil? || pick < 0
if pick < recs.size
away.debug_raid(recs[pick])
elsif opts[pick] == "Hire the squad 3 days free"
LonaCraft::Mercs.debug_hire(3)
elsif opts[pick] == "Hire a maid free"
LonaCraft::Maid.debug_hire
end
end
end