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

2169 lines
80 KiB
Ruby

#==============================================================================
# LonaCraft - 120_Raids.rb (board R4, design: docs/RESEARCH_RAIDS.md; owner
# decisions 2026-10-06). Night raids on a base, with wall and door damage.
# What it does:
# * Trigger: a nap on a base map (Bases.record_for_map) keeps the game's own
# danger roll (region_map_wildness_nap_stats, 34_Functions_RegionMap.rb:237-246)
# and adds a base-value bonus to WildDangerous first: min(danger_cap,
# value x danger_per_value), value = walls + 2 x doors + 3 x furniture. The
# group list is the base's SCENARIO (7, by the record's world-map region,
# research 2.3) instead of the region list (:248-337). A roll that picked a
# raid group arms the raid. night_only: a raid rolled while napping at night
# keeps it night (Game_Map#nap alias takes back the one $game_date.shift,
# 70_Game_Map_DayNightAndOvermap.rb:13-14), so every raid comes at night.
# * Spawn: the game's BIOS spawns the group after the nap
# (region_map_wildness_spawn, :361-1115) on the outer spawn lists, which
# 110_Bases.rb already pruned of built and enclosed tiles. This file adopts
# the group (summon_data[:WildnessNapEvent] == the group, the tag the
# templates set, Map001 ev 384), moves each raider to a tile at least
# spawn_min_distance tiles from the base, door_bias of them on the side of
# the door nearest Lona, and adds +1 raider (the group's first unit,
# EXTRA_UNIT) per extra_raider_per_value of base value, up to
# extra_raiders_max; never more than max_raiders in all.
# * Warning: a popup and the group's spot sound; raiders hold their tiles for
# the scenario's grace (8 s, forest 5 s), +5 s when Lona has a dog companion
# (race "Dog", NPCdata/CompDoggy.json).
# * Siege driver (research 3.5): while Lona is enclosed (flood from the play
# area's edge with LIVE doors, an open door lets the flood through), each
# breacher gets a stand tile beside a wall or door between the outside and
# Lona's side, walks there over a distance map, faces the piece and swings:
# a forced launch_skill of its first melee skill (animation and sound only,
# the game's hit cannot pass a tag-4 tile, research 3.1) on a timer of
# swing_frames + rand(swing_rand); the damage is the mod's:
# max(1, atk - armour) x the race's breach factor, taken off the piece's HP
# (Bases.damage_piece). At 0 HP the piece breaks (Bases.break_piece) and
# the plan is made again; once Lona is not enclosed the game's own AI runs
# and each raider without a target is sent to look where Lona is
# (search_target_unit, 480_EventCharacterBatch.rb:880-902).
# Breacher = breach factor > 0, not ranged, atk >= min_breach_atk. Others
# mill outside (animals, commoners) or wait at range (ranged).
# * End: all raiders down (dead, or stamina <= 0, as check_enemy_survival?,
# 34_Functions_RegionMap.rb:1848-1866, which then runs too); give_up_frames
# of siege without any breach (they walk to the edge of the area and go);
# Lona leaves the map (any Game_Map#setup; past the warning, the raid
# goes on as an away raid, below). Drops are the raiders' own.
# A base left with no piece and no furniture ends after the raid.
# * Nap during a raid: refused at Game_Map#call_nap_event
# (31_Game_Map.rb:1305-1309), where Command_Nap.rb:9 and the bed / bedroll
# nap of Command_AreaNap.rb hand over to the map's NapEvent, and again in
# region_map_wildness_nap (the NapEvent's own command).
# * A raid in progress is runtime only: not saved. After a load there is no
# raid; the base record (with its HP table) is saved as always.
# * Config/Bases.json (user file, never written by the mod) changes the
# numbers; Config/Bases_defaults.json is written at the first use when its
# text changed. Strict reader LonaCraft::ConfigJSON (55_Recipes.rb); a bad
# file is not used, a bad entry is skipped, both with a console line.
# * Debug (DEBUG): Numpad . (DEBUG_KEY) on a base map opens a menu, scenario
# then group, and starts that raid at once (no roll, any time of day).
# * Console lines "LonaCraft Raids: ..." for every phase.
# * Nothing here runs on maps without a base: every hook first looks for a
# base record, a running raid or the raid tag on an event.
# * M1 (owner 2026-10-06): a door set in stone walls (the wall above it, or
# both walls of a sideways door, are Stone Walls) is the piece kind "SD",
# 600 HP / armour 6, here and in the away simulation (Bases.piece_kind).
# Config/Bases.json gets the "away" (Scripts/140_AwayRaids.rb) and "mercs"
# (Scripts/150_Mercs.rb) sections; Numpad . off a base map opens the
# away-raid / mercenary debug menu (140_AwayRaids.rb).
# * Deep Sewer (board R9, Scripts/130_Sewer.rb): the sewer is a tag map, so
# the game's danger roll does not run there (region_map_wildness_nap_stats
# needs OnRegionMap >= 1, 34_Functions_RegionMap.rb:1832, and
# enter_static_tag_map sets it to 0, 34_Functions_ChangeMap.rb:84). The
# sewer's own NapEvent rolls (35 % by day, 60 % at night), picks the group
# from the "sewer" scenario (region 90, the sewer record's region) and arms
# the raid with Raids.arm; its BIOS spawns the group on the tunnel mouths
# (region 1) after the nap. Two groups for it: "AbomBreedlingRaid" (the
# game's own case, :1077) and "SewerRats" (WildGiantMice, spawned by
# 130_Sewer.rb, tagged through the summon data).
# * Difficulty (board R10, docs/RESEARCH_DIFFICULTY.md, owner 2026-10-07):
# Config/Bases.json "difficulty" {"level": "hard" / "hell" / "doom", one
# table of knobs per level, "base_danger" {lower, higher}}. Independent of
# the game's own mode (owner: "Let's keep it from following the game mode,
# to give users customizability"). The level is read once, at config load
# (console "LonaCraft difficulty: Hell (Config/Bases.json)"); an unknown
# name falls back to hard. Every knob is an addition (_add) or a factor
# (_mult) at an existing read site; "hard" is all 0 / 1.0, today's
# numbers. diff(knob) reads the level's table, step(rec, knob) the base's
# own Danger (rec["danger"] -1 Lower / 0 Normal / 1 Higher, missing = 0,
# set on the world-map tile menu and the Deep Sewer ladders, 110_Bases.rb).
# Here: roll_add (+ the base's step) added to WildDangerous with the
# base-value bonus; danger_mult on danger_per_value and danger_cap;
# extra_per_value_add, extra_raiders_add (+ step), max_raiders_add;
# damage_mult on every swing; grace_mult on the warning (the dog's extra
# time is not scaled); give_up_mult on give_up_frames, fixed when the raid
# begins. The other knobs are read in 130_Sewer.rb, 140_AwayRaids.rb,
# 150_Mercs.rb, 160_Rest.rb and 170_Maid.rb.
# * Any hostile on a base map (owner bug report 2026-10-08: the game's own
# nap group ignored the base and a hostile that lost sight of Lona behind
# a shut door gave up). Before, only the raiders this file adopted and
# tagged (summon_data[:LonaCraftRaid]) were driven, and only while they had
# no target (drive / update_swings); the game's AI drops a target it cannot
# see (sense_target, 281_Game_NonPlayerCharacter.rb:456-463: the sight
# line ends on a tag-4 wall top or closed door, Sensors.rb:161-172, and
# after targetLock_HP (10 sensor ticks) process_target_lost :490-504).
# Now, every CHECK_EVERY frames on a base map (watch, Scene_Map alias),
# an NPC joins the siege when Lona is shut in, it stands outside, and
# either it targets Lona's side (Lona, her followers, the mercenaries,
# the maid: Bases.lona_side?) and that target is shut in too ("aggro"),
# or it is the game's own nap group of this map (summon_data
# [:WildnessNapEvent] == OnRegionMapSpawnRace) and would attack Lona by
# the game's own test (Bases.would_attack_lona?) ("nap group"). No running
# raid: a siege state of its own (why :hostile) starts at once (no
# warning, no extra raiders, no relocation); during a raid's siege phase
# they join the raid (r[:joined], never tagged: the tag only marks the
# mod's own raiders). Idle wanderers, non-hostile NPCs (traders, hobos,
# guards that are not after Lona) and anything while Lona is not shut in
# keep the game's AI. Same driver, same roles, same damage rules (armour,
# breach factor, difficulty damage_mult); a unit with a target is driven
# while its target is shut in, and keeps that target (Game_Event
# #update_npc_sensor alias: targetLock_HP refilled before the game's
# sensor tick, hold_target). The :hostile siege ends quietly (no popup,
# no check_enemy_survival?) when its units are down or Lona is no longer
# shut in; it gives up (walks off, deleted) as a raid does. The game's
# nap spawn on a base map that the mod did not arm is never doubled: its
# units join (after_spawn console line). Config raids "hostiles" (true).
# Trace (LonaCraft.trace, debug + trace on): "siege: <name> targets
# <piece> at (x,y), reason no path / breach" when a unit is taken over or
# re-targeted after a break, "siege: <name> released, reason ..." when
# it is let go (path open, down, gave up, raid over).
# * Leaving 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."). Hook: this file's Game_Map#setup
# alias, BEFORE the game's setup (31_Game_Map.rb:159), the one point every
# way off the map passes (map edge / exit menu, change_map_leave_region
# and change_map_leave_tag_map, 34_Functions_ChangeMap.rb:179, 271, a
# capture, a story transfer) while the raiders are still on the map. A
# setup of the same map (a nap, handleNap -> setup(map_id_rec), as the
# game's own nap test, 31_Game_Map.rb:165) is not a leave. Taken over:
# a raid in its warning, siege or assault phase (not while the group is
# collected or retreats) and every :hostile siege, with at least one unit
# up. The units up (name, race, atk, current health, ranged, extra:
# adopted after reserve_extras, r[:extra_ids]) go to
# AwayRaids.left_raid!, which works the raid out at once on the record
# as an away raid (140_AwayRaids.rb header). The live raid ends as
# :handed: no popup, no check_enemy_survival?, no revert_if_empty (as a
# :left end; the game's leave path clears its own nap race,
# change_map_story_stats_fix, 34_Functions_ChangeMap.rb:131), @armed
# cleared. Group: the raid's own; for a :hostile siege the units' nap
# tag (summon_data[:WildnessNapEvent]) most of them carry, else
# "Hostiles". Console and trace: "raid: Lona left during <raid|hostile
# siege> at <base>, N raiders, handing to away raid".
#==============================================================================
module LonaCraft
module Raids
TEXT = "LonaCraft:Raids:"
DEBUG = LonaCraft.debug? # Numpad . ; Config/LonaCraft.json "debug" (05_Config.rb), read at load
DEBUG_KEY = :DECIMAL # Numpad . : free (95_Debug.rb 0 1 3 5 7 9 + - *, 110_Bases.rb /, the game 2 4 6 8)
USER_FILE = "Config/Bases.json"
DEFAULTS_FILE = "Config/Bases_defaults.json"
ADOPT_FRAMES = 120 # frames to collect the spawned group (RandomGoblin summons in two steps)
EXTRA_ADOPT_FRAMES = 90
CHECK_EVERY = 30 # frames between the end / door / enclosure checks
HUNT_EVERY = 120 # frames between "go look where Lona is" in the assault
STUCK_FRAMES = 60 # a breacher blocked this long gives its stand tile up
DIRS = [[2, 0, 1], [4, -1, 0], [6, 1, 0], [8, 0, -1]]
# group => the unit added as an extra raider (the group's first unit in
# region_map_wildness_spawn, 34_Functions_RegionMap.rb:361-1115)
EXTRA_UNIT = {
"Orkind" => "RandomGoblin", "OrkindPlayGround" => "RandomHobgoblin",
"Fishkind" => "FishkindCharger", "FishPPL" => "DeeponeSpearGuard",
"BanditMobs" => "MobHumanRogueSpear", "CommonMobs" => "MobHumanCommoner",
"UndeadWalking" => "UndeadCommoner", "WolfGroup" => "WildDireWolf",
"AbomManager" => "AbomCreatureSpider", "AbomSpider" => "AbomCreatureSpider",
"AbomBreedlingRaid" => "AbomCreatureBreedling", "SewerRats" => "WildGiantMice"
}
GROUPS = EXTRA_UNIT.keys
SPOT_SOUND = {
"Orkind" => :sound_goblin_spot, "OrkindPlayGround" => :sound_OrcSpot,
"Fishkind" => :FishkindSmSpot, "FishPPL" => :FishkindSmSpot,
"BanditMobs" => :sound_MaleWarriorSpot, "CommonMobs" => :sound_MaleWarriorSpot,
"UndeadWalking" => :sound_ZombieSpot, "WolfGroup" => :dogSpot,
"AbomManager" => :BreedlingSpot, "AbomSpider" => :BreedlingSpot,
"AbomBreedlingRaid" => :BreedlingSpot, "SewerRats" => :ratSpot
}
SCENARIO_ORDER = ["field", "road", "forest", "shore", "swamp", "wasteland", "house", "sewer"]
DEFAULTS = {
"pieces" => {
"W" => {"hp" => 600, "armour" => 3},
"D" => {"hp" => 300, "armour" => 3},
"S" => {"hp" => 1200, "armour" => 8}, # W1 stone wall (was "A4", the building wall)
"SD" => {"hp" => 600, "armour" => 6} # M1: a door set in stone walls
},
"repair" => {"item" => "ItemLonaCraftPlank", "hp" => 150, "frames" => 120, "blocked_after_hit_frames" => 180},
"raids" => {
"enabled" => true,
"danger_per_value" => 0.1,
"danger_cap" => 10,
"night_only" => true,
"grace_frames" => 480,
"dog_extra_frames" => 300,
"give_up_frames" => 10800,
"retreat_frames" => 1200,
"swing_frames" => 60,
"swing_rand" => 30,
"spawn_min_distance" => 8,
"door_bias" => 0.5,
"extra_raider_per_value" => 30,
"extra_raiders_max" => 4,
"max_raiders" => 12,
"min_breach_atk" => 3,
"refuse_nap" => true,
"hostiles" => true, # 2026-10-08: any hostile that cannot reach Lona through the walls attacks them
"breach" => {"Orkind" => 1.5, "Goblin" => 1.0, "Human" => 1.0, "Fishkind" => 1.0, "Undead" => 0.75, "Abomination" => 1.25},
"scenarios" => {
"field" => {"regions" => [1], "groups" => {"Orkind" => 70, "BanditMobs" => 30, "UndeadWalking" => 20, "WolfGroup" => 20}, "grace_frames" => 480, "door_bias" => 0.5},
"road" => {"regions" => [11, 17, 23], "groups" => {"BanditMobs" => 60, "Orkind" => 20, "CommonMobs" => 20}, "grace_frames" => 480, "door_bias" => 0.7},
"forest" => {"regions" => [4, 5, 7], "groups" => {"Orkind" => 70, "BanditMobs" => 20, "UndeadWalking" => 30, "WolfGroup" => 40}, "grace_frames" => 300, "door_bias" => 0.5},
"shore" => {"regions" => [2, 27], "groups" => {"Orkind" => 50, "BanditMobs" => 40, "FishPPL" => 20}, "grace_frames" => 480, "door_bias" => 0.5},
"swamp" => {"regions" => [8, 13, 15, 24, 25, 26], "groups" => {"Fishkind" => 70, "Orkind" => 30, "UndeadWalking" => 20}, "grace_frames" => 480, "door_bias" => 0.5},
"wasteland" => {"regions" => [3, 6, 14, 16, 19, 28], "groups" => {"AbomManager" => 40, "AbomSpider" => 30, "Orkind" => 30}, "grace_frames" => 480, "door_bias" => 0.5},
"house" => {"regions" => [9], "groups" => {"BanditMobs" => 60, "CommonMobs" => 30, "Orkind" => 10}, "grace_frames" => 480, "door_bias" => 0.8},
"sewer" => {"regions" => [90], "groups" => {"CommonMobs" => 50, "AbomBreedlingRaid" => 30, "SewerRats" => 30, "UndeadWalking" => 10}, "grace_frames" => 300, "door_bias" => 0.5}
}
},
# M1 item 2, away raids (Scripts/140_AwayRaids.rb, docs/RESEARCH_AWAY_RAIDS_MERCS.md 2, 5)
"away" => {
"enabled" => true, "chance" => 10.0, "value_bonus_per" => 10.0, "value_bonus_cap" => 10.0,
"scenario_mult" => {"road" => 1.5, "house" => 1.5, "sewer" => 1.5},
"grace_days" => 1, "cooldown_days" => 2, "catchup_days" => 14,
"swings" => 24.0, "per_extra_breacher" => 0.15, "breacher_cap" => 2.0, "spread" => 0.25, "difficulty_scale" => 0.01,
"loot_fraction" => 0.5, "carry_per_looter" => 1500,
"smash" => 0.25, "smash_station" => 0.1, "smash_cap" => 3, "reports_kept" => 5,
"looters" => ["Human", "Moot", "Goblin", "Orkind", "Fishkind"]
},
# M1 item 3, mercenaries (Scripts/150_Mercs.rb, research 3)
"mercs" => {
"enabled" => true, "coin" => "ItemCoin2", "price_per_day" => 1, "day_choices" => [1, 3, 7, 14],
"squad_power" => 220.0, "deter" => 0.5, "down_days" => 1
},
# R12 / R14 rest tiers, the chest meal and the bath (Scripts/160_Rest.rb, docs/RESEARCH_REST.md 2.6)
"rest" => {
"enabled" => true, "ground_sta_mult" => 0.6, "ground_sta_cap_pct" => 80, "ground_health_mult" => 0.5,
"ground_mood" => 10, "ground_dirt" => 15, "ground_sick_chance" => 10, "ground_danger" => 10,
"bed_mood" => 10, "bed_roll_mult" => 0.75, "meal_sat" => 30,
"food_on_bedroll" => false, "bath_on_bedroll" => false, "mystery_dishes" => false, "human_dishes" => false
},
# R13 the maid (Scripts/170_Maid.rb, docs/RESEARCH_MAID.md 6)
"maid" => {
"enabled" => true, "hire_fee" => 5, "coin" => "ItemCoin1", "pay" => 1, "grace_days" => 3, "catchup_days" => 14,
"dishes_per_day" => 2, "pantry_cap" => 6, "cook_skill" => 10, "need_fire" => true,
"wander" => 3, "flee_radius" => 6, "away_kill" => 0.5
},
# R10 difficulty (docs/RESEARCH_DIFFICULTY.md section 4): "hard" is
# today's numbers (every _add 0, every _mult 1.0); "hell" and "doom"
# are the research's Harsh and Brutal columns
"difficulty" => {
"level" => "hard",
"hard" => {
"roll_add" => 0, "danger_mult" => 1.0, "extra_per_value_add" => 0, "extra_raiders_add" => 0,
"max_raiders_add" => 0, "damage_mult" => 1.0, "grace_mult" => 1.0, "give_up_mult" => 1.0,
"away_chance_mult" => 1.0, "away_grace_days_add" => 0, "away_cooldown_days_add" => 0,
"away_power_mult" => 1.0, "smash_add" => 0.0, "smash_station_add" => 0.0, "smash_cap_add" => 0,
"loot_add" => 0.0, "sewer_day_add" => 0, "sewer_night_add" => 0, "sewer_pop_mult" => 1.0,
"merc_price_mult" => 1.0, "maid_fee_add" => 0, "maid_kill_add" => 0.0,
"ground_danger_add" => 0, "ground_sick_add" => 0, "bed_roll_add" => 0.0
},
"hell" => {
"roll_add" => 4, "danger_mult" => 1.5, "extra_per_value_add" => -5, "extra_raiders_add" => 1,
"max_raiders_add" => 2, "damage_mult" => 1.25, "grace_mult" => 0.85, "give_up_mult" => 1.33,
"away_chance_mult" => 1.5, "away_grace_days_add" => 0, "away_cooldown_days_add" => 0,
"away_power_mult" => 1.25, "smash_add" => 0.05, "smash_station_add" => 0.02, "smash_cap_add" => 1,
"loot_add" => 0.1, "sewer_day_add" => 5, "sewer_night_add" => 10, "sewer_pop_mult" => 1.25,
"merc_price_mult" => 1.25, "maid_fee_add" => 2, "maid_kill_add" => 0.1,
"ground_danger_add" => 5, "ground_sick_add" => 5, "bed_roll_add" => 0.1
},
"doom" => {
"roll_add" => 8, "danger_mult" => 2.0, "extra_per_value_add" => -10, "extra_raiders_add" => 2,
"max_raiders_add" => 4, "damage_mult" => 1.5, "grace_mult" => 0.7, "give_up_mult" => 1.67,
"away_chance_mult" => 2.0, "away_grace_days_add" => 0, "away_cooldown_days_add" => -1,
"away_power_mult" => 1.5, "smash_add" => 0.15, "smash_station_add" => 0.05, "smash_cap_add" => 2,
"loot_add" => 0.25, "sewer_day_add" => 15, "sewer_night_add" => 20, "sewer_pop_mult" => 1.5,
"merc_price_mult" => 1.5, "maid_fee_add" => 3, "maid_kill_add" => 0.25,
"ground_danger_add" => 10, "ground_sick_add" => 10, "bed_roll_add" => 0.15
},
# the per-base Danger step (C4), on top of the level
"base_danger" => {
"lower" => {"roll_add" => -4, "away_chance_mult" => 0.67, "extra_raiders_add" => -1, "sewer_chance_add" => -10},
"higher" => {"roll_add" => 4, "away_chance_mult" => 1.5, "extra_raiders_add" => 1, "sewer_chance_add" => 10}
}
}
}
LEVELS = ["hard", "hell", "doom"]
LEVEL_NAMES = {"hard" => "Hard", "hell" => "Hell", "doom" => "Doom"}
DANGER_STEPS = {-1 => "lower", 0 => "normal", 1 => "higher"}
@cfg = nil
@raid = nil # the running raid (runtime only, never saved)
@armed = nil # a nap roll picked a raid group; consumed by the spawn
@debug_pending = nil
@hits = {} # "map key:x,y" => Graphics.frame_count of the last hit
@melee = {} # npc name => melee skill (or false)
@level = nil # R10: the difficulty level, set at config load
@watch_t = 0 # 2026-10-08: frame counter of the hostile watch
@reach_cache = nil # [signature, {[x, y] => true}] of outside_reach
# NPC races that are no creature (projectiles, traps, dummies)
NOT_UNITS = ["Missile", "Bomb", "Mine", "SkillDummy", "AreaDot", "Overmap", "Johnson"]
def self.say(text)
p "LonaCraft Raids: #{text}"
end
def self.text_key(key)
"#{TEXT}#{key}"
end
def self.bases
LonaCraft::Bases
end
#----------------------------------------------------------------------
# Config/Bases.json
#----------------------------------------------------------------------
def self.cfg
load_config if @cfg.nil?
@cfg
end
def self.rc
cfg["raids"]
end
def self.copy(obj)
Marshal.load(Marshal.dump(obj))
end
def self.load_config
@cfg = copy(DEFAULTS)
write_defaults
data = read_user
merge_user(data) if data.is_a?(Hash)
resolve_level
bases.set_config(@cfg["pieces"], @cfg["repair"])
p "LonaCraft Raids: config ready, palisade #{@cfg["pieces"]["W"]["hp"]} HP, stone #{@cfg["pieces"]["S"]["hp"]} HP, door #{@cfg["pieces"]["D"]["hp"]} HP, raids #{rc["enabled"] ? "on" : "off"}"
rescue => e
say("config error #{e.class} #{e.message}, defaults used")
@cfg = copy(DEFAULTS)
resolve_level
bases.set_config(@cfg["pieces"], @cfg["repair"])
end
def self.read_user
path = LonaCraft.resource(USER_FILE)
return nil unless File.exist?(path)
LonaCraft::ConfigJSON.parse(File.open(path, "rb"){|f| f.read })
rescue LonaCraft::ConfigJSON::Error => e
say("#{USER_FILE} not used, #{e.message}")
nil
rescue => e
say("#{USER_FILE} not used, #{e.class} #{e.message}")
nil
end
def self.skip(where, why)
say("#{USER_FILE} #{where} skipped, #{why}")
end
# a user value fits the default's type (numbers >= 0)
def self.value_ok?(default, v)
case default
when true, false then v == true || v == false
when Integer then v.is_a?(Integer) && v >= 0
when Float then v.is_a?(Numeric) && v >= 0
when String then v.is_a?(String) && !v.empty?
else false
end
end
def self.merge_flat(target, val, where)
unless val.is_a?(Hash)
skip(where, "not a {...} block")
return
end
val.each{|k, v|
if !target.key?(k) || target[k].is_a?(Hash) || target[k].is_a?(Array)
skip("#{where}/#{k}", "unknown key")
elsif !value_ok?(target[k], v)
skip("#{where}/#{k}", "bad value #{v.inspect}")
else
target[k] = target[k].is_a?(Float) ? v.to_f : v
end
}
end
def self.merge_user(data)
data.each{|sec, val|
case sec
when "pieces"
unless val.is_a?(Hash)
skip("pieces", "not a {...} block")
next
end
val.each{|kind, v|
if @cfg["pieces"][kind].nil?
skip("pieces/#{kind}", "unknown piece (W, S, D, SD)")
next
end
merge_flat(@cfg["pieces"][kind], v, "pieces/#{kind}")
@cfg["pieces"][kind]["hp"] = DEFAULTS["pieces"][kind]["hp"] if @cfg["pieces"][kind]["hp"] < 1
}
when "repair"
merge_flat(@cfg["repair"], val, "repair")
when "raids"
merge_raids(val)
when "away", "mercs"
merge_lists(sec, val)
when "rest", "maid"
merge_flat(@cfg[sec], val, sec)
when "difficulty"
merge_difficulty(val)
else
skip(sec.to_s, "unknown section (pieces, repair, raids, away, mercs, rest, maid, difficulty)")
end
}
r = rc
r["door_bias"] = 1.0 if r["door_bias"] > 1.0
r["max_raiders"] = 1 if r["max_raiders"] < 1
r["extra_raider_per_value"] = 1 if r["extra_raider_per_value"] < 1
end
# "away" / "mercs": flat numbers plus their few lists and tables
def self.merge_lists(sec, val)
unless val.is_a?(Hash)
skip(sec, "not a {...} block")
return
end
target = @cfg[sec]
flat = {}
val.each{|k, v|
case k
when "looters"
if v.is_a?(Array) && v.all?{|n| n.is_a?(String) }
target[k] = v
else
skip("#{sec}/#{k}", "needs a list of race names")
end
when "day_choices"
if v.is_a?(Array) && !v.empty? && v.all?{|n| n.is_a?(Integer) && n > 0 }
target[k] = v
else
skip("#{sec}/#{k}", "needs a list of day counts above 0")
end
when "scenario_mult"
if v.is_a?(Hash) && v.all?{|n, m| n.is_a?(String) && m.is_a?(Numeric) && m >= 0 }
target[k] = Hash[v.map{|n, m| [n, m.to_f] }]
else
skip("#{sec}/#{k}", "needs {scenario: multiplier}")
end
else
flat[k] = v
end
}
merge_flat(target, flat, sec) unless flat.empty?
end
# R10 "difficulty": "level" (a name), the three level tables and
# "base_danger" {lower, higher}; knobs are numbers, negative allowed for
# an _add, 0 or more for a _mult; whole numbers where the default is one
def self.merge_difficulty(val)
unless val.is_a?(Hash)
skip("difficulty", "not a {...} block")
return
end
dc = @cfg["difficulty"]
val.each{|k, v|
where = "difficulty/#{k}"
if k == "level"
if v.is_a?(String) && !v.strip.empty?
dc["level"] = v.strip.downcase # an unknown name: resolve_level falls back to hard
else
skip(where, "needs a level name (#{LEVELS.join(", ")})")
end
elsif LEVELS.include?(k)
merge_knobs(dc[k], v, where)
elsif k == "base_danger"
unless v.is_a?(Hash)
skip(where, "not a {...} block")
next
end
v.each{|st, t|
if dc["base_danger"][st].is_a?(Hash)
merge_knobs(dc["base_danger"][st], t, "#{where}/#{st}")
else
skip("#{where}/#{st}", "unknown step (lower, higher)")
end
}
else
skip(where, "unknown key (level, #{LEVELS.join(", ")}, base_danger)")
end
}
end
def self.merge_knobs(target, val, where)
unless val.is_a?(Hash)
skip(where, "not a {...} block")
return
end
val.each{|k, v|
d = target[k]
if d.nil?
skip("#{where}/#{k}", "unknown key")
elsif !v.is_a?(Numeric) || (d.is_a?(Integer) && !v.is_a?(Integer))
skip("#{where}/#{k}", "bad value #{v.inspect}")
elsif k.end_with?("_mult") && v < 0
skip("#{where}/#{k}", "bad value #{v.inspect} (a factor is 0 or more)")
else
target[k] = d.is_a?(Float) ? v.to_f : v
end
}
end
def self.merge_raids(val)
unless val.is_a?(Hash)
skip("raids", "not a {...} block")
return
end
flat = {}
val.each{|k, v|
case k
when "breach"
unless v.is_a?(Hash)
skip("raids/breach", "not a {...} block")
next
end
v.each{|race, f|
if f.is_a?(Numeric) && f >= 0
rc["breach"][race.to_s] = f.to_f
else
skip("raids/breach/#{race}", "bad value #{f.inspect}")
end
}
when "scenarios"
merge_scenarios(v)
else
flat[k] = v
end
}
merge_flat(rc, flat, "raids")
end
def self.merge_scenarios(val)
unless val.is_a?(Hash)
skip("raids/scenarios", "not a {...} block")
return
end
val.each{|name, sc|
where = "raids/scenarios/#{name}"
unless sc.is_a?(Hash)
skip(where, "not a {...} block")
next
end
cur = rc["scenarios"][name]
if cur.nil?
unless sc["regions"].is_a?(Array) && sc["groups"].is_a?(Hash)
skip(where, "a new scenario needs regions and groups")
next
end
cur = {"regions" => [], "groups" => {}, "grace_frames" => rc["grace_frames"], "door_bias" => rc["door_bias"]}
end
ok = true
out = copy(cur)
sc.each{|k, v|
case k
when "regions"
if v.is_a?(Array) && v.all?{|n| n.is_a?(Integer) && n > 0 }
out["regions"] = v
else
skip("#{where}/regions", "needs a list of region numbers")
ok = false
end
when "groups"
if v.is_a?(Hash) && v.all?{|g, w| GROUPS.include?(g) && w.is_a?(Integer) && w >= 0 }
out["groups"] = v
else
skip("#{where}/groups", "needs {group: weight}, groups #{GROUPS.join(" ")}")
ok = false
end
when "grace_frames"
if v.is_a?(Integer) && v >= 0
out[k] = v
else
skip("#{where}/#{k}", "bad value #{v.inspect}")
end
when "door_bias"
if v.is_a?(Numeric) && v >= 0 && v <= 1
out[k] = v.to_f
else
skip("#{where}/#{k}", "bad value #{v.inspect}")
end
else
skip("#{where}/#{k}", "unknown key")
end
}
rc["scenarios"][name] = out if ok || !rc["scenarios"][name].nil?
}
end
def self.json(v, ind = "")
case v
when Hash
return "{}" if v.empty?
inner = ind + " "
"{\n" + v.map{|k, x| "#{inner}#{k.to_s.inspect}: #{json(x, inner)}" }.join(",\n") + "\n#{ind}}"
when Array then "[" + v.map{|x| json(x, ind) }.join(", ") + "]"
when String then v.inspect
when nil then "null"
else v.to_s
end
end
def self.defaults_text
lines = []
lines << "// LonaCraft base and raid defaults (Scripts/120_Raids.rb), written by the game."
lines << "// Do not edit this file: copy the keys you want to change into Config/Bases.json"
lines << "// (only those keys, inside the same section). README \"Raids\" explains each key,"
lines << "// README \"Difficulty\" the \"difficulty\" section."
lines << json(DEFAULTS)
lines.join("\n") + "\n"
end
def self.write_defaults
text = defaults_text
text.force_encoding("ASCII-8BIT") if text.respond_to?(:force_encoding)
path = LonaCraft.resource(DEFAULTS_FILE)
old = File.exist?(path) ? File.open(path, "rb"){|f| f.read } : nil
return if old == text
dir = File.dirname(path)
Dir.mkdir(dir) unless File.directory?(dir)
File.open(path, "wb"){|f| f.write(text) }
say("wrote #{DEFAULTS_FILE}")
rescue => e
say("cannot write #{DEFAULTS_FILE}, #{e.class} #{e.message}")
end
#----------------------------------------------------------------------
# Difficulty (R10): the level, its knobs, the base's Danger step
#----------------------------------------------------------------------
# Sets @level from the config's "level" (once, at config load) and
# names it on the console; an unknown name falls back to hard
def self.resolve_level
want = @cfg["difficulty"]["level"].to_s
@level = LEVELS.include?(want) ? want : "hard"
say("difficulty level #{want.inspect} unknown (#{LEVELS.join(", ")}), hard used") unless LEVELS.include?(want)
p "LonaCraft difficulty: #{LEVEL_NAMES[@level]} (#{USER_FILE})"
rescue => e
@level = "hard"
say("difficulty error #{e.class} #{e.message}, hard used")
end
def self.level
cfg
@level || "hard"
end
def self.level_name
LEVEL_NAMES[level]
end
# the identity of a knob: 1.0 for a factor, 0 for an addition
def self.knob_identity(knob)
knob.to_s.end_with?("_mult") ? 1.0 : 0
end
# the level's value of +knob+
def self.diff(knob)
t = cfg["difficulty"][level]
v = t.is_a?(Hash) ? t[knob] : nil
v.is_a?(Numeric) ? v : knob_identity(knob)
end
# the base's Danger step: -1 Lower, 0 Normal (missing, old saves), 1 Higher
def self.danger_of(rec)
d = rec.is_a?(Hash) ? rec["danger"] : nil
d.is_a?(Integer) && d >= -1 && d <= 1 ? d : 0
end
# the base's Danger value of +knob+ (Normal: the identity)
def self.step(rec, knob)
name = DANGER_STEPS[danger_of(rec)]
t = cfg["difficulty"]["base_danger"][name]
v = t.is_a?(Hash) ? t[knob] : nil
v.is_a?(Numeric) ? v : knob_identity(knob)
end
# "Hell, danger higher" for console lines
def self.diff_tag(rec = nil)
d = rec ? danger_of(rec) : 0
d == 0 ? level_name : "#{level_name}, danger #{DANGER_STEPS[d]}"
end
# the scaled raid sizes (also the away party, 140_AwayRaids.rb)
def self.extra_per_value
[rc["extra_raider_per_value"].to_i + diff("extra_per_value_add").to_i, 1].max
end
def self.extras_max(rec)
[rc["extra_raiders_max"].to_i + diff("extra_raiders_add").to_i + step(rec, "extra_raiders_add").to_i, 0].max
end
def self.max_raiders
[rc["max_raiders"].to_i + diff("max_raiders_add").to_i, 1].max
end
# true while a live raid runs on base +rec+ (the Danger line is refused)
def self.busy_on?(rec)
!@raid.nil? && rec.is_a?(Hash) && @raid[:base] == rec["id"]
end
#----------------------------------------------------------------------
# Bases, scenarios, value
#----------------------------------------------------------------------
def self.enabled?
bases.enabled? && rc["enabled"] ? true : false
end
# the base record of the map Lona is on, or nil (never on a world map)
def self.base_here(map = $game_map)
return nil if map.nil? || map.isOverMap
bases.record_for_map(map)
end
def self.scenario_names
rc["scenarios"].keys.sort_by{|n| SCENARIO_ORDER.index(n) || 99 }
end
def self.scenario_for(rec)
region = rec["region"].to_i
name = scenario_names.find{|n| rc["scenarios"][n]["regions"].include?(region) }
name || (rc["scenarios"]["field"] ? "field" : scenario_names.first)
end
def self.groups_of(scen)
s = rc["scenarios"][scen]
return [] if s.nil?
s["groups"].select{|g, w| w.to_i > 0 }.keys
end
def self.pick_group(scen)
s = rc["scenarios"][scen]
return nil if s.nil?
list = s["groups"].select{|g, w| w.to_i > 0 }.to_a
total = list.inject(0){|t, gw| t + gw[1].to_i }
return nil if total <= 0
n = rand(total)
list.each{|g, w|
return g if n < w.to_i
n -= w.to_i
}
list.last[0]
end
def self.base_value(rec)
pieces = bases.pieces_of(rec)
w = pieces.values.count{|v| bases.wall?(v) }
d = pieces.values.count{|v| bases.door?(v) }
f = bases.furniture_on(rec).size
w + 2 * d + 3 * f
end
#----------------------------------------------------------------------
# The nap roll (GIM_ADDON aliases below)
#----------------------------------------------------------------------
# Before the game's roll: the base-value bonus. Returns the record or nil.
def self.before_roll
@armed = nil
return nil unless enabled?
rec = base_here
return nil if rec.nil?
value = base_value(rec)
dm = diff("danger_mult").to_f
bonus = [(value * rc["danger_per_value"].to_f * dm).floor, (rc["danger_cap"].to_i * dm).floor].min
$story_stats["WildDangerous"] += bonus if bonus > 0
# R10: the level's roll_add and the base's Danger step; a cut never
# takes WildDangerous below 0
add = diff("roll_add").to_i + step(rec, "roll_add").to_i
if add != 0
w = $story_stats["WildDangerous"]
$story_stats["WildDangerous"] = [w + add, [w, 0].min].max
end
extra = add == 0 ? "" : format(" %+d (%s)", add, diff_tag(rec))
say("nap on base #{rec["id"]}, value #{value}, danger +#{bonus}#{extra} -> #{$story_stats["WildDangerous"]}")
rec
end
# The game's group list for the roll on a base map: the scenario's
def self.race_list_here
return nil unless enabled?
rec = base_here
return nil if rec.nil?
scen = scenario_for(rec)
list = rc["scenarios"][scen]["groups"].select{|g, w| w.to_i > 0 }.map{|g, w| [w.to_i, g] }
return nil if list.empty?
list
end
def self.after_roll(rec)
race = $story_stats["OnRegionMapSpawnRace"]
unless GROUPS.include?(race)
say("no raid this nap (#{race.inspect})") if race == 0
say("the game's group #{race.inspect} comes instead of a raid") unless race == 0
return
end
@armed = {:key => $game_map.map_id_rec, :base => rec["id"], :race => race, :scen => scenario_for(rec),
:night => $game_date.night?, :fresh => true}
say("raid armed on base #{rec["id"]}: #{race} (#{@armed[:scen]}), #{@armed[:night] ? "napping at night" : "napping by day"}")
end
# R9: the Deep Sewer's own nap roll (130_Sewer.rb) picked +race+ on the base
# +rec+: arm the raid as after_roll does. Returns true when armed.
def self.arm(rec, race)
@armed = nil
return false unless enabled? && rec && GROUPS.include?(race)
@armed = {:key => $game_map.map_id_rec, :base => rec["id"], :race => race, :scen => scenario_for(rec),
:night => $game_date.night?, :fresh => true}
say("raid armed on base #{rec["id"]}: #{race} (#{@armed[:scen]}), #{@armed[:night] ? "napping at night" : "napping by day"}")
true
end
# Game_Map#nap alias (after the game's shift): a raid rolled at night keeps the night
def self.after_map_nap(map, init_from_event)
a = @armed
return if a.nil? || !a[:fresh]
a[:fresh] = false
return unless rc["night_only"] && a[:night] && $game_date.day?
$game_date.rshift
map.send(:set_light) unless init_from_event
say("woken in the same night")
rescue => e
say("night error #{e.class} #{e.message}")
end
# region_map_wildness_spawn alias (after): the game's group is on the map
def self.after_spawn(force)
map = $game_map
if @debug_pending
scen, race = @debug_pending
@debug_pending = nil
begin_raid(map, race, scen, :debug)
return
end
a = @armed
race = force ? force : $story_stats["OnRegionMapSpawnRace"]
if a.nil? || !map || map.map_id_rec != a[:key] || race != a[:race]
note_game_spawn(map, race)
return
end
@armed = nil
begin_raid(map, a[:race], a[:scen], :nap)
end
# 2026-10-08: the game's own spawn on a base map that the mod did not arm:
# no second group; its units join the siege (watch) while Lona is shut in
def self.note_game_spawn(map, race)
return if map.nil? || race.nil? || race == 0 || !hostiles_on?
rec = base_here(map)
return if rec.nil?
say("the game's own group #{race.inspect} came to base #{rec["id"]}: no second group, its units join the siege while Lona is shut in")
end
#----------------------------------------------------------------------
# Raid state
#----------------------------------------------------------------------
def self.busy?
!@raid.nil?
end
def self.active?
!@raid.nil?
end
def self.reset
say("raid state cleared (load)") if @raid || @armed
@raid = nil
@armed = nil
@debug_pending = nil
@hits = {}
@reach_cache = nil
end
def self.recently_hit?(x, y, frames)
return false if $game_map.nil?
t = @hits["#{$game_map.map_id_rec}:#{x.to_i},#{y.to_i}"]
!t.nil? && Graphics.frame_count - t < frames
end
# the state of a raid (+why+ :nap / :debug) or of a siege of hostiles (:hostile)
def self.new_state(map, rec, race, scen, why)
{
:id => Graphics.frame_count, :key => map.map_id_rec, :base => rec["id"], :race => race,
:scen => scen, :why => why, :phase => :adopt, :t => 0, :adopt_left => ADOPT_FRAMES,
:extras_done => false, :raiders => [], :placed_door => 0, :role => {}, :assign => {},
:reserved => {}, :walk => {}, :stuck => {}, :swing => {}, :blocked => {}, :siege_t => 0,
:breached => false, :grace => 0, :retreat_t => 0, :reach => nil, :door_sig => nil, :assign_budget => 2,
:give_up => (rc["give_up_frames"].to_i * diff("give_up_mult").to_f).round, # R10, kept for this raid
:joined => {}, :traced => {}, :rebreach => {}, # 2026-10-08: joined hostiles, trace bookkeeping
:extra_ids => {} # 2026-10-08: the extra raiders (reserve_extras), for a leave hand-over
}
end
def self.begin_raid(map, race, scen, why)
rec = base_here(map)
return say("no base here, raid dropped") if rec.nil?
scen = scenario_for(rec) if rc["scenarios"][scen].nil?
end_raid(:replaced) if @raid # a siege of hostiles gives way; they join again in the raid's siege phase
@raid = new_state(map, rec, race, scen, why)
say("raid begins on base #{rec["id"]}: #{race} (#{scen}, #{why}, #{diff_tag(rec)}), collecting the group")
end
def self.end_raid(why)
r = @raid
@raid = nil
return if r.nil?
map = $game_map
hostile = r[:why] == :hostile
r[:raiders].each{|ev| let_go(r, ev, "#{hostile ? "siege" : "raid"} over (#{why})") }
on_base = map && !map.isOverMap && map.map_id_rec == r[:key]
if on_base && why != :left && why != :replaced && why != :handed # :handed: the away raid has it (leave_check)
unless hostile # a siege of hostiles ends quietly; the game keeps its own bookkeeping
case why
when :cleared then $game_map.popup(0, text_key("Raid/over"), 0, 0)
when :gave_up then $game_map.popup(0, text_key("Raid/gave_up"), 0, 0)
end
begin
map.interpreter.check_enemy_survival? # the game's clear: WildDangerous -50 when none is left
rescue => e
say("survival check error #{e.class} #{e.message}")
end
end
bases.revert_if_empty(map)
end
say("#{hostile ? "siege of hostiles" : "raid"} over (#{why}) after #{r[:t]} frames, #{r[:breached] ? "a piece was broken" : "no breach"}")
end
def self.raider_alive?(ev)
return false if ev.nil? || ev.deleted? || ev.npc.nil?
return false if ev.npc.action_state == :death
ev.npc.stat.get_stat("sta") > 0
rescue
false
end
def self.mine?(ev, r = @raid)
return false if r.nil? || ev.nil?
sd = ev.summon_data
sd.is_a?(Hash) && sd[:LonaCraftRaid] == r[:id]
end
#----------------------------------------------------------------------
# Any hostile on a base map (2026-10-08, header). A unit = a raider of
# the mod's raid (tagged) or a hostile that joined (r[:joined], by id).
#----------------------------------------------------------------------
def self.hostiles_on?
enabled? && rc["hostiles"] ? true : false
end
def self.unit?(ev, r = @raid)
return false if r.nil? || ev.nil?
return true if r[:joined] && r[:joined][ev.id]
mine?(ev, r)
end
def self.trace(text)
LonaCraft.trace("siege: #{text}") if LonaCraft.respond_to?(:trace)
rescue
nil
end
# the game's own nap group of this map (its templates tag themselves,
# check_enemy_survival? 34_Functions_RegionMap.rb:1848-1866 counts them);
# never the sewer's own population (R9)
def self.nap_unit?(ev)
sd = ev.summon_data
return false unless sd.is_a?(Hash) && !sd[:LonaCraftSewerPop]
race = $story_stats["OnRegionMapSpawnRace"]
return false if race.nil? || race == 0
sd[:WildnessNapEvent] == race
rescue
false
end
# why the NPC on +ev+ joins the siege ("aggro", "nap group") or nil
def self.join_reason(ev)
return nil if ev.deleted? || !ev.respond_to?(:npc?) || !ev.npc?
return nil if ev.instance_variable_get(:@missile)
npc = ev.npc
return nil if npc.nil? || !raider_alive?(ev)
return nil if npc.respond_to?(:is_object) && npc.is_object
return nil if NOT_UNITS.include?(npc.race.to_s)
return nil if bases.lona_side?(ev)
return nil unless npc.action_state.nil? || npc.action_state == :none
return "aggro" if bases.lona_side?(npc.target) && npc.ai_state != :flee
return "nap group" if nap_unit?(ev) && bases.would_attack_lona?(ev, npc)
nil
rescue
nil
end
# {[x, y] => true}: the tiles the outside reaches (flood_outside), cached
# until a door opens or closes or a piece comes or goes
def self.outside_reach(map, rec)
pieces = bases.pieces_of(rec)
sig = [map.map_id_rec, door_signature(map, rec), pieces.size, pieces.keys.sort.join(";")]
c = @reach_cache
return c[1] if c && c[0] == sig
reach = flood_outside(map, rec, play_bounds(map))
@reach_cache = [sig, reach]
reach
end
# Scene_Map#update alias, every frame: every CHECK_EVERY frames on a base
# map, the hostiles that cannot reach Lona's side join the siege
def self.watch
@watch_t = (@watch_t || 0) + 1
return unless @watch_t % CHECK_EVERY == 0
return unless hostiles_on?
map = $game_map
return if map.nil? || map.isOverMap || $game_player.nil?
return if map.interpreter.running? || ($game_message && $game_message.busy?)
r = @raid
return if r && r[:phase] != :siege # adopt, grace, assault, retreat: the raid's own rules
rec = base_here(map)
return if rec.nil?
list = []
map.events.values.each{|ev|
next if ev.nil? || unit?(ev, r)
why = join_reason(ev)
list << [ev, why] if why
}
return if list.empty?
reach = outside_reach(map, rec)
return if reach[[$game_player.x, $game_player.y]] # Lona is not shut in: the game's own AI
list = list.select{|ev, why|
next false unless reach[[ev.x, ev.y]] # it stands outside
t = ev.npc.target
why != "aggro" || t.nil? || !reach[[t.x, t.y]] # and its target is shut in
}
return if list.empty?
r ||= begin_hostile(map, rec)
return if r.nil? || !r.equal?(@raid)
list.each{|ev, why| join(r, ev, why) }
rescue => e
say("watch error #{e.class} #{e.message}")
end
def self.begin_hostile(map, rec)
@raid = new_state(map, rec, nil, nil, :hostile)
r = @raid
r[:phase] = :siege
say("hostiles on base #{rec["id"]} cannot reach Lona: the siege driver takes them (#{diff_tag(rec)})")
replan(map, r)
@raid
end
def self.join(r, ev, why)
r[:joined][ev.id] = why
r[:raiders] << ev unless r[:raiders].include?(ev)
say("#{ev.npc.npc_name} (event #{ev.id}) joins the siege: #{why}")
end
def self.piece_name(rec, piece)
case bases.piece_kind(bases.pieces_of(rec), piece[0], piece[1])
when "D" then "door"
when "SD" then "door in stone"
when "S" then "stone wall"
when "W" then "palisade"
else "piece"
end
end
def self.nearest_cand(r, ev)
c = r[:cands]
return nil if c.nil? || c.empty?
c.keys.min_by{|pc| (pc[0] - ev.x).abs + (pc[1] - ev.y).abs }
end
# the take-over line (once per unit, again after a break re-targets it)
def self.note_take(r, ev, piece)
re = r[:rebreach].delete(ev.id)
return if r[:traced].key?(ev.id) && !re
piece ||= nearest_cand(r, ev)
return if piece.nil?
r[:traced][ev.id] = true
rec = base_here
joined = r[:joined][ev.id]
text = "#{ev.npc.npc_name} targets #{rec ? piece_name(rec, piece) : "piece"} at (#{piece[0]},#{piece[1]}), " +
"reason #{re ? "breach" : "no path"} (event #{ev.id}, #{joined ? "joined: #{joined}" : "raider"}, #{role(ev, r)})"
say("siege: #{text}")
trace(text)
rescue => e
say("trace error #{e.class} #{e.message}")
end
# the release line (only for a unit that had its take-over line)
def self.let_go(r, ev, why)
return if ev.nil? || !r[:traced].delete(ev.id)
name = begin
ev.npc.npc_name
rescue
"?"
end
text = "#{name} released, reason #{why} (event #{ev.id})"
say("siege: #{text}")
trace(text)
end
# Game_Event#update_npc_sensor alias (before the game's tick): a unit at
# work on the siege keeps its target while that target is shut in. The
# game drops a target it does not sense once targetLock_HP runs out
# (281_Game_NonPlayerCharacter.rb:456-463); it is refilled here.
def self.hold_target(ev)
r = @raid
return if r.nil? || r[:phase] != :siege || !unit?(ev, r)
npc = ev.npc
return if npc.nil?
t = npc.target
return unless bases.lona_side?(t)
return if t.respond_to?(:deleted?) && t.deleted?
return if t.actor.nil? || t.actor.action_state == :death
return if (r[:reach] || {})[[t.x, t.y]] # it can reach its target: the game's own rules
npc.targetLock_HP = 10 if npc.targetLock_HP.to_i < 10
rescue
nil
end
#----------------------------------------------------------------------
# Spawn placement
#----------------------------------------------------------------------
def self.region_lists(map)
rm = map.instance_variable_get(:@region_map)
rm.is_a?(Array) ? rm : []
end
def self.base_box(rec)
cells = bases.cells_of(bases.pieces_of(rec))
return nil if cells.empty?
[cells.map{|c| c[0] }.min, cells.map{|c| c[1] }.min, cells.map{|c| c[0] }.max, cells.map{|c| c[1] }.max]
end
def self.box_dist(box, x, y)
[box[0] - x, 0, x - box[2]].max + [box[1] - y, 0, y - box[3]].max
end
def self.door_cells(rec)
pieces = bases.pieces_of(rec)
pieces.keys.select{|k| bases.door?(pieces[k]) }.map{|k| k.split(",").map{|n| n.to_i } }
end
# [far tiles, far tiles on the door side] from the outer spawn lists
def self.spawn_tiles(map, r, rec)
return r[:spawn] if r[:spawn]
rm = region_lists(map)
ids = $story_stats["RegionMap_RegionOuta"]
ids = (2...rm.size).to_a unless ids.is_a?(Array) && !ids.empty?
tiles = []
ids.each{|i|
list = rm[i.to_i]
tiles.concat(list.map{|c| [c[0], c[1]] }) if list.is_a?(Array)
}
tiles.uniq!
box = base_box(rec) || [$game_player.x, $game_player.y, $game_player.x, $game_player.y]
min = rc["spawn_min_distance"].to_i
far = tiles.select{|c| box_dist(box, c[0], c[1]) >= min }
if far.size < 8
want = [8, tiles.size / 4].max
far = tiles.sort_by{|c| -box_dist(box, c[0], c[1]) }.first(want)
end
doors = door_cells(rec)
side = far
unless doors.empty?
px = $game_player.x
py = $game_player.y
door = doors.min_by{|d| (d[0] - px).abs + (d[1] - py).abs }
mx = (box[0] + box[2]) / 2.0
my = (box[1] + box[3]) / 2.0
vx = door[0] - mx
vy = door[1] - my
side = far.select{|c| (c[0] - mx) * vx + (c[1] - my) * vy > 0 }
side = far if side.empty?
end
say("spawn tiles: #{tiles.size} outer, #{far.size} at >= #{min} from the base, #{side.size} on the door side")
r[:spawn] = [far, side]
end
def self.free_tile?(map, x, y)
return false unless map.valid?(x, y)
return false if $game_player.x == x && $game_player.y == y
return false unless map.events_xy(x, y).empty?
[2, 4, 6, 8].any?{|d| bases.layer_pass?(map, x, y, d) }
end
def self.pick_spawn(map, r, rec, door_side)
far, side = spawn_tiles(map, r, rec)
pool = door_side ? side : far
20.times{
c = pool.sample
return c if c && free_tile?(map, c[0], c[1])
}
nil
end
def self.place_raider(map, r, rec, ev)
bias = (rc["scenarios"][r[:scen]] || {})["door_bias"] || rc["door_bias"]
door_side = r[:placed_door] < (r[:raiders].size * bias.to_f).round
c = pick_spawn(map, r, rec, door_side)
return if c.nil?
r[:placed_door] += 1 if door_side
ev.moveto(c[0], c[1])
end
def self.adopt_scan(map, r, rec)
max = max_raiders
map.events.values.each{|ev|
next if ev.nil? || ev.deleted? || !ev.respond_to?(:npc?) || !ev.npc?
sd = ev.summon_data
next unless sd.is_a?(Hash) && sd[:WildnessNapEvent] == r[:race] && !sd[:LonaCraftRaid]
next if sd[:LonaCraftSewerPop] # R9: the sewer's own hobos and goblins are never raiders
next if ev.npc.nil? || ev.npc.master == $game_player
if r[:raiders].size >= max
ev.nappable = false
ev.delete
say("raider over the cap of #{max} removed")
next
end
sd[:LonaCraftRaid] = r[:id]
r[:raiders] << ev
r[:extra_ids][ev.id] = true if r[:extras_done] # adopted after reserve_extras: an extra raider
place_raider(map, r, rec, ev)
}
end
def self.reserve_extras(map, r, rec)
r[:extras_done] = true
value = base_value(rec)
n = [value / extra_per_value, extras_max(rec)].min
n = [n, max_raiders - r[:raiders].size].min
unit = EXTRA_UNIT[r[:race]]
return 0 if n <= 0 || unit.nil?
$story_stats["OnRegionMapSpawnRace"] = r[:race] # the templates tag themselves with it
made = 0
n.times{
c = pick_spawn(map, r, rec, false)
next if c.nil?
# the tag also in the summon data: WildGiantMice (SewerRats) does not tag itself
map.reserve_summon_event(unit, c[0], c[1], -1, {:WildnessNapEvent => r[:race]})
made += 1
}
say("base value #{value}: #{made} extra #{unit}")
made
end
def self.dog_companion?(map)
map.npcs.any?{|ev| ev && !ev.deleted? && ev.npc && ev.npc.master == $game_player && ev.npc.race == "Dog" }
rescue
false
end
def self.start_grace(map, r)
r[:phase] = :grace
sc = rc["scenarios"][r[:scen]] || {}
r[:grace] = ((sc["grace_frames"] || rc["grace_frames"]).to_i * diff("grace_mult").to_f).round # R10
dog = dog_companion?(map)
r[:grace] += rc["dog_extra_frames"].to_i if dog
$game_map.popup(0, text_key(dog ? "Warn/raid_dog" : "Warn/raid"), 0, 0)
begin
LonaCraft::Mercs.raid_warning(map) if defined?(LonaCraft::Mercs) # M1: the captain calls out
rescue => e
say("mercenary warning error #{e.class} #{e.message}")
end
begin
SndLib.dogSpot(90) if dog
snd = SPOT_SOUND[r[:race]]
SndLib.send(snd, 90) if snd
rescue => e
say("sound error #{e.class} #{e.message}")
end
say("#{r[:raiders].size} raiders (#{r[:race]}) hold for #{r[:grace]} frames#{dog ? ", the dog heard them" : ""}")
end
#----------------------------------------------------------------------
# The siege plan
#----------------------------------------------------------------------
def self.play_bounds(map)
xs = []
ys = []
region_lists(map).each_with_index{|list, id|
next if id == 0 || !list.is_a?(Array)
list.each{|c| xs << c[0]; ys << c[1] }
}
return [0, 0, map.width - 1, map.height - 1] if xs.empty?
[[xs.min - 1, 0].max, [ys.min - 1, 0].max, [xs.max + 1, map.width - 1].min, [ys.max + 1, map.height - 1].min]
end
def self.door_closed_at(map, rec)
out = {}
door_cells(rec).each{|c|
ev = bases.door_event_at(map, c[0], c[1])
out[c] = true unless ev && ev.through
}
out
end
def self.door_signature(map, rec)
door_closed_at(map, rec).keys.sort.inspect
end
# {[x, y] => true}: tiles the outside reaches (live doors), as
# Bases.inside_tiles seeds it (play-area edge and the exit ring)
def self.flood_outside(map, rec, b)
closed = door_closed_at(map, rec)
reached = {}
queue = []
ax0, ay0, ax1, ay1 = b
(ay0..ay1).each{|y|
(ax0..ax1).each{|x|
next if closed[[x, y]]
edge = x == ax0 || x == ax1 || y == ay0 || y == ay1 ||
[[1, 0], [-1, 0], [0, 1], [0, -1]].any?{|dx, dy| map.region_id(x + dx, y + dy) == bases::EXIT_REGION }
next unless edge
next unless [2, 4, 6, 8].any?{|d| bases.layer_pass?(map, x, y, d) }
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] || closed[k]
next unless bases.layer_pass?(map, x, y, d) && bases.layer_pass?(map, k[0], k[1], 10 - d)
reached[k] = true
queue << k
}
end
reached
end
# distance map {[x, y] => steps} from +sources+ over +allowed+ tiles
# (+allowed+ nil: anywhere within +b+, closed doors excepted)
def self.bfs(map, sources, allowed, b = nil, closed = {})
dist = {}
queue = []
sources.each{|c|
next if dist.key?(c)
dist[c] = 0
queue << c
}
head = 0
while head < queue.size
x, y = queue[head]
head += 1
d0 = dist[[x, y]]
DIRS.each{|d, dx, dy|
k = [x + dx, y + dy]
next if dist.key?(k)
if allowed
next unless allowed[k]
else
next if k[0] < b[0] || k[0] > b[2] || k[1] < b[1] || k[1] > b[3] || closed[k]
end
next unless bases.layer_pass?(map, x, y, d) && bases.layer_pass?(map, k[0], k[1], 10 - d)
dist[k] = d0 + 1
queue << k
}
end
dist
end
# Makes the plan again (start, a break, a door opened or closed, Lona
# going in or out). Switches between :siege and :assault.
def self.replan(map, r)
rec = base_here(map)
return end_raid(:left) if rec.nil?
r[:assign] = {}
r[:reserved] = {}
r[:walk] = {}
r[:stuck] = {}
reach = outside_reach(map, rec)
r[:reach] = reach
r[:door_sig] = door_signature(map, rec)
lona = [$game_player.x, $game_player.y]
if reach[lona]
r[:raiders].each{|ev| let_go(r, ev, "path open") }
return end_raid(:path_open) if r[:why] == :hostile # hostiles siege only while Lona is shut in
r[:phase] = :assault unless r[:phase] == :retreat
r[:hunt_t] = 0
say("Lona is not shut in: the raiders go for her (assault)")
hunt(map, r)
return
end
r[:phase] = :siege unless r[:phase] == :retreat
# Lona's side: what she reaches without crossing a wall or a closed door
closed = door_closed_at(map, rec)
box = base_box(rec) || [lona[0], lona[1], lona[0], lona[1]]
ib = [[box[0] - 1, 0].max, [box[1] - 1, 0].max, [box[2] + 1, map.width - 1].min, [box[3] + 1, map.height - 1].min]
inner = bfs(map, [lona], nil, ib, closed)
pieces = bases.pieces_of(rec)
touching = {}
outer = {}
pieces.each{|k, v|
next unless bases.wall?(v) || bases.door?(v)
x, y = k.split(",").map{|n| n.to_i }
stands = []
near_lona = false
# A4 walls: a wall covers its top and its face (the tile below), so a
# raider stands beside the top or south / beside the face
fp = bases.respond_to?(:footprint) ? bases.footprint(pieces, map, x, y) : [[x, y]]
fp.each{|fx, fy|
DIRS.each{|d, dx, dy|
c = [fx + dx, fy + dy]
next if fp.include?(c)
stands << c if reach[c]
near_lona = true if inner.key?(c)
}
}
stands.uniq!
next if stands.empty?
(near_lona ? touching : outer)[[x, y]] = stands
}
r[:cands] = touching.empty? ? outer : touching
all = r[:cands].values.flatten(1).uniq
r[:approach] = bfs(map, all, reach)
say("siege plan: #{r[:cands].size} pieces to break, #{all.size} stand tiles, outside #{reach.size} tiles")
end
def self.hunt(map, r)
r[:raiders].each{|ev|
next unless raider_alive?(ev)
npc = ev.npc
next unless npc.target.nil? && (npc.action_state.nil? || npc.action_state == :none)
ev.search_target_unit($game_player, ev, 2) if ev.respond_to?(:search_target_unit)
}
end
def self.breach_factor(ev)
rc["breach"][ev.npc.race.to_s].to_f
rescue
0.0
end
def self.atk_of(ev)
ev.npc.atk.to_i
rescue
0
end
def self.role(ev, r)
return r[:role][ev.id] if r[:role][ev.id]
ranged = (ev.npc.ranged? rescue false)
role = if ranged
:ranged
elsif breach_factor(ev) > 0 && atk_of(ev) >= rc["min_breach_atk"].to_i
:breach
else
:mill
end
r[:role][ev.id] = role
end
def self.swing_damage(ev, armour)
f = breach_factor(ev)
return 0 if f <= 0
[([atk_of(ev) - armour, 1].max * f * diff("damage_mult").to_f).round, 1].max # R10 damage_mult
end
def self.mean_swing
rc["swing_frames"].to_i + rc["swing_rand"].to_i / 2.0
end
def self.next_swing
rc["swing_frames"].to_i + rand(rc["swing_rand"].to_i + 1)
end
def self.frames_per_tile(ev)
256.0 / (2 ** ev.move_speed.to_f)
rescue
16.0
end
# breacher +ev+ takes the free stand tile with the lowest walk + break time
def self.assign(map, r, ev)
rec = base_here(map)
return nil if rec.nil? || r[:cands].nil?
return nil if (r[:assign_budget] -= 1) < 0 # at most 2 a frame
from = bfs(map, [[ev.x, ev.y]], r[:reach])
pieces = bases.pieces_of(rec)
fpt = frames_per_tile(ev)
best = nil
r[:cands].each{|piece, stands|
kind = bases.piece_kind(pieces, piece[0], piece[1]) # M1: "SD" for a door set in stone
next if kind.nil?
hp = bases.hp_at(rec, piece[0], piece[1])
dmg = swing_damage(ev, bases.armour_of(kind))
next if dmg <= 0
break_frames = hp[0] / (dmg / mean_swing)
stands.each{|s|
next if r[:reserved][s] || (r[:blocked][s] && r[:blocked][s] > r[:t])
steps = from[s]
next if steps.nil?
cost = steps * fpt + break_frames
best = [cost, piece, s] if best.nil? || cost < best[0]
}
}
return nil if best.nil?
r[:assign][ev.id] = [best[1], best[2]]
r[:reserved][best[2]] = ev.id
r[:walk][best[2]] ||= bfs(map, [best[2]], r[:reach])
say("#{ev.npc.npc_name} goes for (#{best[1][0]},#{best[1][1]}) from stand (#{best[2][0]},#{best[2][1]}), about #{(best[0] / 60.0).round} s")
r[:assign][ev.id]
end
def self.release(r, ev, block_stand = false)
a = r[:assign].delete(ev.id)
return if a.nil?
r[:reserved].delete(a[1])
r[:blocked][a[1]] = r[:t] + 300 if block_stand
r[:swing].delete(ev.id)
end
def self.dir_to(from, to)
dx = to[0] - from[0]
dy = to[1] - from[1]
return (dx > 0 ? 6 : 4) if dx.abs > dy.abs
dy > 0 ? 2 : 8
end
# one step down the distance map; true when it moved or waits
def self.step_down(ev, dist, r)
d0 = dist[[ev.x, ev.y]]
if d0.nil? # off the map of this walk: wander, and count as stuck
ev.move_random if rand(30) == 0
r[:stuck][ev.id] = (r[:stuck][ev.id] || 0) + 1
return false
end
DIRS.each{|d, dx, dy|
k = [ev.x + dx, ev.y + dy]
next unless dist[k] && dist[k] == d0 - 1
next unless ev.passable?(ev.x, ev.y, d)
ev.move_straight(d)
r[:stuck][ev.id] = 0
return true
}
r[:stuck][ev.id] = (r[:stuck][ev.id] || 0) + 1
false
end
#----------------------------------------------------------------------
# Movement (Game_Event#update_self_movement alias, called while the
# event stands still). true = the raid moved it, skip the game's own.
#----------------------------------------------------------------------
def self.drive(ev)
r = @raid
return false if r.nil? || !unit?(ev, r)
npc = ev.npc
return false if npc.nil?
return false unless npc.action_state.nil? || npc.action_state == :none
t = npc.target
unless t.nil?
# 2026-10-08: a unit with a target is driven only in the siege and
# only while that target is shut in; else the game's AI
return false unless r[:phase] == :siege
if (r[:reach] || {})[[t.x, t.y]]
let_go(r, ev, "path open")
return false
end
end
case r[:phase]
when :adopt, :grace
true
when :siege
drive_siege(ev, r)
when :retreat
drive_retreat(ev, r)
else
false
end
rescue => e
say("drive error #{e.class} #{e.message}")
false
end
def self.drive_siege(ev, r)
map = $game_map
case role(ev, r)
when :breach
a = r[:assign][ev.id] || assign(map, r, ev)
note_take(r, ev, a ? a[0] : nil)
return approach(ev, r, 2) if a.nil?
piece, stand = a
if ev.x == stand[0] && ev.y == stand[1]
ev.set_direction(dir_to(stand, piece))
return true
end
step_down(ev, r[:walk][stand] || {}, r)
if (r[:stuck][ev.id] || 0) > STUCK_FRAMES
release(r, ev, true)
r[:stuck][ev.id] = 0
ev.move_random
end
true
when :ranged
note_take(r, ev, nil)
approach(ev, r, 5)
else
note_take(r, ev, nil)
approach(ev, r, 2)
end
end
# walk toward the stand tiles until +near+ steps away, then wait / mill
def self.approach(ev, r, near)
dist = r[:approach] || {}
d0 = dist[[ev.x, ev.y]]
if d0 && d0 > near
step_down(ev, dist, r)
elsif rand(90) == 0
ev.move_random
elsif rand(30) == 0
ev.turn_toward_character($game_player)
end
true
end
def self.drive_retreat(ev, r)
dist = r[:exit] || {}
d0 = dist[[ev.x, ev.y]]
return true if d0.nil? || d0 == 0 # removed by update
step_down(ev, dist, r)
true
end
def self.start_retreat(map, r)
r[:phase] = :retreat
r[:retreat_t] = 0
r[:raiders].each{|ev| let_go(r, ev, "gave up") }
r[:assign] = {}
r[:reserved] = {}
reach = r[:reach] || {}
exits = bases.outer_band(map).select{|c| reach[c] }
r[:exit] = exits.empty? ? {} : bfs(map, exits, reach)
say("no breach in #{r[:siege_t]} frames: the raiders give up (#{exits.size} exit tiles)")
end
#----------------------------------------------------------------------
# Swings
#----------------------------------------------------------------------
def self.melee_skill(ev)
name = ev.npc.npc_name
return @melee[name] if @melee.key?(name)
list = ev.npc.skills_killer || []
s = list.find{|k|
next false if k.nil?
next false if k.respond_to?(:is_projectile?) && k.is_projectile?
next false if k.respond_to?(:holding?) && k.holding?
next false if k.respond_to?(:blocking?) && k.blocking?
true
}
@melee[name] = s || false
rescue
@melee[name] = false
end
# the swing's picture and sound: a forced launch of the raider's melee
# skill, its cost given back (its hit cannot pass the tag-4 piece). The
# skill's user effect gets the piece's tile as its target, a FakeTarget
# as the game gives Lona's own skills (25_Game_Actor.rb:1542).
def self.animate_swing(ev, piece)
s = melee_skill(ev)
return unless s
npc = ev.npc
old = npc.instance_variable_get(:@target)
npc.instance_variable_set(:@target, Struct::FakeTarget.new(piece[0], piece[1]))
begin
if npc.launch_skill(s, true)
npc.process_skill_cost_reverse(s) if npc.respond_to?(:process_skill_cost_reverse)
end
ensure
npc.instance_variable_set(:@target, old)
end
rescue => e
say("swing animation error #{e.class} #{e.message}")
end
def self.vol(ev)
ev.report_distance_to_vol_close
rescue
80
end
def self.swing(map, r, rec, ev, piece)
x, y = piece
kind = bases.piece_kind(bases.pieces_of(rec), x, y)
if kind.nil?
release(r, ev)
return false
end
ev.set_direction(dir_to([ev.x, ev.y], piece))
animate_swing(ev, piece)
dmg = swing_damage(ev, bases.armour_of(kind))
@hits["#{r[:key]}:#{x},#{y}"] = Graphics.frame_count
res = bases.damage_piece(map, x, y, dmg)
begin
SndLib.sys_KnockDoor(vol(ev))
$game_damage_popups.add(dmg, x, y, ev.direction, 1)
rescue
end
if res == :broken
r[:breached] = true
begin
SndLib.stoneCollapsed(vol(ev))
rescue
end
$game_map.popup(0, text_key("Raid/breach"), 0, 0)
say("#{kind == "D" ? "door" : "wall"} at (#{x},#{y}) broken by #{ev.npc.npc_name} after #{r[:t]} frames")
r[:traced].each_key{|id| r[:rebreach][id] = true } # their next target line says "breach"
replan(map, r)
return true
end
if res.is_a?(Array)
first = !r[:first_hit]
r[:first_hit] = true
say("first hit: (#{x},#{y}) #{res[0]}/#{res[1]} HP by #{ev.npc.npc_name} (#{dmg} a swing)") if first
end
false
end
def self.update_swings(map, r)
rec = base_here(map)
return if rec.nil?
r[:assign].to_a.each{|id, a|
piece, stand = a
ev = map.events[id]
next unless raider_alive?(ev)
next unless ev.x == stand[0] && ev.y == stand[1] && !ev.moving?
npc = ev.npc
next unless npc.action_state.nil? || npc.action_state == :none
tg = npc.target
next if tg && (r[:reach] || {})[[tg.x, tg.y]] # it can reach its target: the game's AI
t = (r[:swing][id] || next_swing) - 1
if t > 0
r[:swing][id] = t
next
end
r[:swing][id] = next_swing
return if swing(map, r, rec, ev, piece) # the plan changed
}
end
#----------------------------------------------------------------------
# Each frame (Scene_Map#update alias, only while a raid runs)
#----------------------------------------------------------------------
def self.update
r = @raid
return if r.nil?
map = $game_map
return end_raid(:left) if map.nil? || map.isOverMap || map.map_id_rec != r[:key]
return if map.interpreter.running? || ($game_message && $game_message.busy?)
r[:t] += 1
r[:assign_budget] = 2
case r[:phase]
when :adopt
rec = base_here(map)
return end_raid(:left) if rec.nil?
adopt_scan(map, r, rec)
r[:adopt_left] -= 1
return if r[:adopt_left] > 0
return end_raid(:no_group) if r[:raiders].empty?
unless r[:extras_done]
r[:adopt_left] = EXTRA_ADOPT_FRAMES if reserve_extras(map, r, rec) > 0
return if r[:adopt_left] > 0
end
start_grace(map, r)
when :grace
r[:grace] -= 1
if r[:grace] <= 0
say("grace over, the raiders move in")
r[:phase] = :siege
replan(map, r)
end
when :siege, :assault
update_swings(map, r) if r[:phase] == :siege
return if @raid.nil?
if r[:phase] == :siege
r[:siege_t] += 1
if !r[:breached] && r[:siege_t] >= (r[:give_up] || rc["give_up_frames"]).to_i
start_retreat(map, r)
return
end
else
r[:hunt_t] = (r[:hunt_t] || 0) + 1
hunt(map, r) if r[:hunt_t] % HUNT_EVERY == 0
end
if r[:t] % CHECK_EVERY == 0
r[:raiders].each{|ev| let_go(r, ev, "down") unless raider_alive?(ev) }
return end_raid(:cleared) unless r[:raiders].any?{|ev| raider_alive?(ev) }
rec = base_here(map)
return end_raid(:left) if rec.nil?
lona_out = r[:reach] && r[:reach][[$game_player.x, $game_player.y]] ? true : false
if door_signature(map, rec) != r[:door_sig] || lona_out != (r[:phase] == :assault)
replan(map, r)
end
end
when :retreat
r[:retreat_t] += 1
gone = r[:retreat_t] >= rc["retreat_frames"].to_i
r[:raiders].each{|ev|
next unless raider_alive?(ev) # the downed stay where they fell
next unless gone || (r[:exit] || {})[[ev.x, ev.y]] == 0
ev.nappable = false
ev.delete
}
return end_raid(:gave_up) unless r[:raiders].any?{|ev| raider_alive?(ev) }
end
rescue => e
say("update error #{e.class} #{e.message} #{e.backtrace ? e.backtrace[0] : ""}")
end_raid(:error)
end
#----------------------------------------------------------------------
# Leaving during a raid (owner 2026-10-08, header): an away raid at once
#----------------------------------------------------------------------
LEAVE_PHASES = [:grace, :siege, :assault] # after the warning; not while collecting or retreating
# Game_Map#setup alias, BEFORE the game's setup of +map_id+: Lona leaves
# the map of the running raid (any other map) while its units are up
def self.leave_check(map, map_id)
r = @raid
return if r.nil? || map.nil? || !map.equal?($game_map) || map.isOverMap
return if map.map_id_rec != r[:key]
return if map_id == r[:key] || (map_id.is_a?(Integer) && map_id == map.map_id) # a nap: the same map
handover(map, r)
rescue => e
say("leave error #{e.class} #{e.message} #{e.backtrace ? e.backtrace[0] : ""}")
end
# the away code's unit of the raider on +ev+ (140_AwayRaids.rb party)
def self.leave_unit(ev, r)
npc = ev.npc
{:name => npc.npc_name.to_s, :race => npc.race.to_s, :atk => atk_of(ev), :health => npc.health.to_i,
:ranged => role(ev, r) == :ranged, :extra => r[:extra_ids][ev.id] ? true : false}
rescue
nil
end
# the raid's group; a :hostile siege: the nap tag most of its units carry
def self.leave_group(r, live)
return r[:race].to_s if r[:why] != :hostile && r[:race]
tags = Hash.new(0)
live.each{|ev|
sd = ev.summon_data
t = sd.is_a?(Hash) ? sd[:WildnessNapEvent] : nil
tags[t.to_s] += 1 if t && t != 0
}
tags.empty? ? "Hostiles" : tags.max_by{|t, n| n }[0]
end
def self.handover(map, r)
away = defined?(LonaCraft::AwayRaids) ? LonaCraft::AwayRaids : nil
rec = bases.record_by_id(r[:base])
hostile = r[:why] == :hostile
live = r[:raiders].select{|ev| raider_alive?(ev) }
unless rec && away && away.enabled? && LEAVE_PHASES.include?(r[:phase]) && !live.empty? # a :hostile siege is in :siege
say("Lona left during the #{r[:phase]} phase, #{live.size} up: no hand-over") # after_setup ends it (:left)
return
end
units = live.map{|ev| leave_unit(ev, r) }.compact
group = leave_group(r, live)
line = "raid: Lona left during #{hostile ? "hostile siege" : "raid"} at #{bases.name_of(rec)}, #{units.size} raiders, handing to away raid"
say(line)
LonaCraft.trace(line) if LonaCraft.respond_to?(:trace_on?) && LonaCraft.trace_on?
end_raid(:handed)
@armed = nil
@debug_pending = nil
away.left_raid!(rec, group, units, hostile ? "hostile" : "raid")
end
#----------------------------------------------------------------------
# Map change, load, nap refusal
#----------------------------------------------------------------------
# any Game_Map#setup ends a running raid: a map change, or a nap (refused
# while a raid runs, so only a forced one); begin_raid comes after the setup
def self.after_setup(map)
end_raid(:left) if @raid
@reach_cache = nil
@armed = nil if @armed && map.map_id_rec != @armed[:key]
end
def self.nap_refused?
!@raid.nil? && rc["refuse_nap"]
end
def self.refuse_nap
SndLib.sys_buzzer
$game_player.call_balloon(0)
$game_player.animation = nil
$game_map.popup(0, text_key("Nap/refused"), 0, 0)
say("nap refused, the raid (#{@raid[:phase]}) is still on")
rescue => e
say("nap refusal error #{e.class} #{e.message}")
end
#----------------------------------------------------------------------
# Debug: Numpad . on a base map
#----------------------------------------------------------------------
def self.debug_active?
return false unless DEBUG && bases.enabled?
return false unless SceneManager.scene_is?(Scene_Map)
return false if $game_map.nil? || $game_player.nil?
return false if $game_message && $game_message.busy?
return false if $game_map.interpreter && $game_map.interpreter.running?
true
end
def self.debug_say(text)
bases.debug_say(text)
end
def self.debug_update
pressed = begin
Input.trigger?(DEBUG_KEY)
rescue
false
end
return unless pressed && debug_active?
if base_here.nil?
# M1: off a base map, the away-raid / mercenary debug menu (140_AwayRaids.rb)
return $game_temp.loadEval("lonacraft_away_debug_menu") if defined?(LonaCraft::AwayRaids)
return debug_say("LonaCraft debug raids need a base map")
end
return debug_say("LonaCraft debug a raid is on (#{@raid[:phase]})") if @raid && @raid[:why] != :hostile
$game_temp.loadEval("lonacraft_raid_debug_menu")
rescue => e
say("debug error #{e.class} #{e.message}")
end
def self.debug_start(scen, race, interp)
map = $game_map
rec = base_here(map)
return debug_say("LonaCraft debug no base here") if rec.nil?
outa = $story_stats["RegionMap_RegionOuta"]
unless outa.is_a?(Array) && !outa.empty?
ids = []
region_lists(map).each_with_index{|l, i| ids << i if i > bases::EXIT_REGION && l.is_a?(Array) && !l.empty? }
$story_stats["RegionMap_RegionOuta"] = ids
end
$story_stats["OverMapEvent_saw"] = 0 unless $story_stats["OverMapEvent_saw"] == 1
$story_stats["OnRegionMapSpawnRace"] = race
@debug_pending = [scen, race]
say("debug raid: #{race} (#{scen}) on base #{rec["id"]}")
begin
interp.region_map_wildness_spawn(race)
rescue => e
say("debug spawn error #{e.class} #{e.message}, extra units only")
end
if @debug_pending # the spawn alias did not run (the group is then missing: the raid ends as :no_group)
@debug_pending = nil
begin_raid(map, race, scen, :debug)
end
end
end
end
#==============================================================================
# The nap roll and the group spawn (GIM_ADDON, 34_Functions_RegionMap.rb:51-1949)
#==============================================================================
module GIM_ADDON
if method_defined?(:region_map_wildness_nap_stats) && !method_defined?(:lonacraft_raids_nap_stats)
alias_method :lonacraft_raids_nap_stats, :region_map_wildness_nap_stats
def region_map_wildness_nap_stats
rec = nil
begin
rec = LonaCraft::Raids.before_roll
rescue => e
p "LonaCraft Raids roll error #{e.class} #{e.message}"
end
lonacraft_raids_nap_stats
begin
LonaCraft::Raids.after_roll(rec) if rec
rescue => e
p "LonaCraft Raids roll error #{e.class} #{e.message}"
end
end
end
if method_defined?(:region_map_wildness_nap_stats_create_race_list) && !method_defined?(:lonacraft_raids_race_list)
alias_method :lonacraft_raids_race_list, :region_map_wildness_nap_stats_create_race_list
def region_map_wildness_nap_stats_create_race_list
list = nil
begin
list = LonaCraft::Raids.race_list_here
rescue => e
p "LonaCraft Raids race list error #{e.class} #{e.message}"
end
list || lonacraft_raids_race_list
end
end
if method_defined?(:region_map_wildness_spawn) && !method_defined?(:lonacraft_raids_spawn)
alias_method :lonacraft_raids_spawn, :region_map_wildness_spawn
def region_map_wildness_spawn(tmpForceSpawn = false)
res = lonacraft_raids_spawn(tmpForceSpawn)
begin
LonaCraft::Raids.after_spawn(tmpForceSpawn)
rescue => e
p "LonaCraft Raids spawn error #{e.class} #{e.message}"
end
res
end
end
if method_defined?(:region_map_wildness_nap) && !method_defined?(:lonacraft_raids_wildness_nap)
alias_method :lonacraft_raids_wildness_nap, :region_map_wildness_nap
def region_map_wildness_nap(tmpForce = nil)
if !tmpForce && LonaCraft::Raids.nap_refused?
LonaCraft::Raids.refuse_nap
return
end
lonacraft_raids_wildness_nap(tmpForce)
end
end
end
#==============================================================================
# Game_Map: the night kept, the nap refused, map changes
#==============================================================================
class Game_Map
unless method_defined?(:lonacraft_raids_map_nap)
alias_method :lonacraft_raids_map_nap, :nap
def nap(initFromEvent = false)
lonacraft_raids_map_nap(initFromEvent)
LonaCraft::Raids.after_map_nap(self, initFromEvent)
end
end
unless method_defined?(:lonacraft_raids_call_nap_event)
alias_method :lonacraft_raids_call_nap_event, :call_nap_event
def call_nap_event
if LonaCraft::Raids.nap_refused?
LonaCraft::Raids.refuse_nap
return
end
lonacraft_raids_call_nap_event
end
end
unless method_defined?(:setup_lonacraft_raids)
alias_method :setup_lonacraft_raids, :setup
def setup(map_id)
LonaCraft::Raids.leave_check(self, map_id) # 2026-10-08: leaving during a raid, before the old map goes
setup_lonacraft_raids(map_id)
begin
LonaCraft::Raids.after_setup(self)
rescue => e
p "LonaCraft Raids setup error #{e.class} #{e.message}"
end
end
end
end
#==============================================================================
# Game_Event: the siege driver moves raiders while they stand still
#==============================================================================
class Game_Event
unless method_defined?(:lonacraft_raids_self_movement)
alias_method :lonacraft_raids_self_movement, :update_self_movement
def update_self_movement
# 2026-10-08: every unit of the siege (the mod's raiders and joined hostiles)
if LonaCraft::Raids.busy? && LonaCraft::Raids.unit?(self)
return if LonaCraft::Raids.drive(self)
end
lonacraft_raids_self_movement
end
end
# 2026-10-08: a unit at work on the siege keeps its target although the
# walls cut its sight (39_Game_Event.rb:698-707 -> sense_target)
if method_defined?(:update_npc_sensor) && !method_defined?(:lonacraft_raids_npc_sensor)
alias_method :lonacraft_raids_npc_sensor, :update_npc_sensor
def update_npc_sensor
LonaCraft::Raids.hold_target(self) if LonaCraft::Raids.busy?
lonacraft_raids_npc_sensor
end
end
end
#==============================================================================
# Scene_Map: the raid's frame and the debug key
#==============================================================================
class Scene_Map
unless method_defined?(:update_lonacraft_raids)
alias_method :update_lonacraft_raids, :update
def update
update_lonacraft_raids
LonaCraft::Raids.update if LonaCraft::Raids.busy?
LonaCraft::Raids.watch # 2026-10-08: hostiles that cannot reach Lona join the siege
LonaCraft::Raids.debug_update if LonaCraft::Raids::DEBUG
end
end
end
#==============================================================================
# DataManager: a raid is never saved; after a load there is none
#==============================================================================
module DataManager
unless respond_to?(:extract_save_contents_lonacraft_raids)
self.singleton_class.send(:alias_method, :extract_save_contents_lonacraft_raids, :extract_save_contents)
def self.extract_save_contents(contents)
extract_save_contents_lonacraft_raids(contents)
begin
LonaCraft::Raids.reset
LonaCraft::Raids.cfg # HP and repair numbers before any menu reads them
rescue => e
p "LonaCraft Raids load error #{e.class} #{e.message}"
end
end
end
end
#==============================================================================
# Game_Interpreter: the debug menu (Numpad . on a base map)
#==============================================================================
class Game_Interpreter
def lonacraft_raid_debug_choice(title, options)
$game_message.background = 0
$game_message.position = 2
$game_message.add("#{title}\\optB[#{options.join(",")}]")
$game_map.interpreter.wait_for_message
end
def lonacraft_raid_debug_menu
raids = LonaCraft::Raids
rec = raids.base_here
return eventPlayEnd if rec.nil?
names = raids.scenario_names
lonacraft_raid_debug_choice("LonaCraft debug raid. Scenario (this base is #{raids.scenario_for(rec)})", names + ["Cancel"])
pick = $game_temp.choice
$game_temp.choice = -1
return eventPlayEnd if pick.nil? || pick < 0 || pick >= names.size
scen = names[pick]
groups = raids.groups_of(scen)
lonacraft_raid_debug_choice("LonaCraft debug raid. Group for #{scen}", groups + ["Any", "Cancel"])
pick = $game_temp.choice
$game_temp.choice = -1
race = nil
race = groups[pick] if pick && pick >= 0 && pick < groups.size
race = raids.pick_group(scen) if pick == groups.size
eventPlayEnd
return if race.nil?
raids.debug_start(scen, race, self)
end
end
# Config/Bases.json at boot, so the piece HP and repair numbers are set
# before any menu reads them (and the defaults file is written)
begin
LonaCraft::Raids.cfg
rescue => e
p "LonaCraft Raids config error #{e.class} #{e.message}"
end