#============================================================================== # LonaCraft - 150_Mercs.rb (board M1 item 3, research # docs/RESEARCH_AWAY_RAIDS_MERCS.md section 3, owner decisions 2026-10-06). # A squad of hired mercenaries that guards one base: a captain and two # swords, hired from the Mercenary Guild's receptionist in the Noer tavern. # What it does: # * Contract: $game_system.lonacraft_data["mercs"] = {"until" => last date # unit, "base" => post base id or nil, "name" => the captain's name, # "down" => {role => date unit they are up again}, "hired", "warned"}. # Plain types, saved with the game. Price: "price_per_day" (1) x "coin" # (ItemCoin2, Large Copper Coin) a day for the squad, days from # "day_choices" (1 / 3 / 7 / 14), paid up front; paying again adds days. # R10: the contract price is ceil(days x price_per_day x the difficulty # level's "merc_price_mult") (Config/Bases.json "difficulty", 120_Raids.rb # diff): hard 1 / 3 / 7 / 14, hell 2 / 4 / 9 / 18, doom 2 / 5 / 11 / 21; # days paid stay as they are, an extension pays the price of today. # * The guild: Data/HCGframes/event/NoerTavernGuildEmpolyee.rb is redirected # to HCGframes/NoerTavernGuildEmpolyee.rb (Homes.redirect, the SELLERS # pattern of 100_Homes.rb), which runs the script that ran before # LonaCraft (RolePlayS's copy when RolePlayS is loaded first, else the # game's) unchanged. While it runs, a call_msg alias catches the "nothing # pending" menu (TagMapNoerTavernQuest:QuestBoard/other) and adds one line # (Homes.extend_menu, a runtime text key): "Hire mercenaries" or # "Mercenary contract (N days left)". The line is always choice 3 (hidden # options keep their index); picked, the hire / extend talk runs and the # choice is set to -1, so the script's own case does nothing. Quest # reports and the board are untouched. # * The squad: NPC/LonaCraftMercCaptain.json and NPC/LonaCraftMercenary.json # (the mod's own, into $data_npcs at load_mod_database; Npc_CompanionCharge # AI, Eyes_follower sensor, fraction 7). Runtime events built here # (sprites: mercenaries -char-M-REGULAR04 index 2 pattern 0, the # NFLwarrior look; captain -char-M-REGULAR01 index 3 pattern 2, the Elite # Warrior look). Init: set_npc, master = $game_player, drop list empty, # fraction_mode 2 (as setup_follower_summoned), not nappable. No companion # slot and no follower flag: the game's companion slots, assembly calls # and follower_goto never see them. Master = Lona, so 110_Bases.rb's build # rule (npcs_present?, hostile_near?) and the raid adoption skip them. # * Post (owner, 2026-10-06): chosen at hiring from the bases' names # (Bases.choose_base: newest first, at most 6; the most recently visited # when there are more); "Move post" from the captain picks again. The # squad is made at the chosen base's next setup. A post base that is gone # leaves the squad waiting at the guild for a new post (the receptionist # asks for one). # * Standing tiles (Change 2026-10-08, owner: "The mercenary hires need to # not block any doors. Easy fix is to prevent them from posting up against # any base wall."): a post is a free walkable tile at least POST_GAP (2) # tiles (4 directions) from every piece of the base (never on a door, the # tile outside or inside it, or a tile next to a wall or door) and off # the DOOR_LANE (3) tiles straight out of each door; the nearest such # tiles to the main door (the door nearest the StartPoint) by walking # distance, the outside first, then inside the walls. None (a tiny # clearing): the free tile farthest from the door, with a console line. # The same rule at every spawn (map setup) and again when the base's # pieces change (a post that breaks the rule is chosen again), so the # walk back after a fight ends on a clear tile. # * Every Game_Map#setup of the post base makes the members that are not # down (a nap removes them, not nappable, and makes them again). Idle (no # target), a small Game_Event#update_self_movement alias walks each back # to its post and faces out; with a target the game's AI fights. # * Hunting (Change 2026-10-08, owner: "change their AI logic to all attack # any enemies on the map ... Wildlife shouldn't count. Also, anything the # player attacks, the mercenaries become hostile to and help out."): every # CHECK_EVERY (30) frames each member with no target takes the nearest # foe: an NPC 110_Bases.rb counts_as_hostile? counts (the build rule: # attacking Lona's side now, or no animal and would attack Lona), or one # Lona hit on this map (Game_NonPlayerCharacter#set_last_attacker alias, # @last_attacker == $game_player; animals, traders and guards included, # Lona's own side never) until it dies or the map changes. Engaged through # the game's aggro: npc.set_aggro(foe, nil, ENGAGE_FRAMES) (the target, # alert 2, aggro frames; 281_Game_NonPlayerCharacter.rb:1256), topped up # each check, so sense_target keeps it out of sight (:459) and killer? # (:731) makes the game's AI walk to it (Npc_CompanionCharge # move_toward_TargetSmartAI) and use its killer skills (process_killer -> # set_killer_skill). Dead or gone: the next foe; none left: back to post. # No nearer in GIVE_UP_CHECKS (20) checks: that foe is skipped by that # member for SKIP_CHECKS (60). A member the game's AI already set on a # target of its own (a live raid) is left to it. Trace: "mercs: # engages (reason hostile|lona attacked)", "mercs: back to # post". # * Down, never dead: a member that dies is down for "down_days" (1); an # away raid that beats the squad puts all three down (140_AwayRaids.rb # knock_down). The captain down = no talk until he is back. # * The captain (action key): days left, add days (same prices), move post, # dismiss (no refund). The mercenaries send Lona to him. # * Date hook: one day before the end a popup; at the end the contract goes # with a popup and the squad leaves (deleted on the next map frame). # * Away raids (140_AwayRaids.rb): guard(rec, u) = squad power ("squad_power" # 220 x the share of members up) when posted at that base, else nil; # deterrence "deter" x 0.5 on the chance. Live raids: the captain calls # out when the raid warning shows (raid_warning, from 120_Raids.rb). # * Debug (Numpad . off a base map): hire the squad 3 days free. # * Nothing here runs without a contract: the hooks return at once when # lonacraft_data["mercs"] is empty (the guild menu line excepted). #============================================================================== module LonaCraft module Mercs TEXT = "LonaCraft:Mercs:" FILE = "Mercs" GUILD_SCRIPT = "Data/HCGframes/event/NoerTavernGuildEmpolyee.rb" GUILD_SCRIPTS = [GUILD_SCRIPT] # 98_SelfTest.rb redirect check GUILD_MENU_KEY = "TagMapNoerTavernQuest:QuestBoard/other" ROLES = ["L", "A", "B"] # captain, two mercenaries NPC_DATA = {"L" => "LonaCraftMercCaptain", "A" => "LonaCraftMercenary", "B" => "LonaCraftMercenary"} NPC_FILES = ["NPC/LonaCraftMercCaptain.json", "NPC/LonaCraftMercenary.json"] # role => [sheet, index, pattern] (docs/RESEARCH_AWAY_RAIDS_MERCS.md 3.4: L1 and M6) SPRITES = { "L" => ["-char-M-REGULAR01", 3, 2], "A" => ["-char-M-REGULAR04", 2, 0], "B" => ["-char-M-REGULAR04", 2, 0] } EVENT_PREFIX = "LonaCraftMerc" CHECK_EVERY = 30 DIRS = [[2, 0, 1], [4, -1, 0], [6, 1, 0], [8, 0, -1]] POST_GAP = 2 # 2026-10-08: a post is this far (4 directions) from every base piece DOOR_LANE = 3 # 2026-10-08: the tiles straight out of a door up to this far stay free ENGAGE_FRAMES = 300 # 2026-10-08: aggro frames a foe is held for (the game's @combatAggroTime base, 281:113) GIVE_UP_CHECKS = 20 # 2026-10-08: checks with no step nearer before a foe is left SKIP_CHECKS = 60 # 2026-10-08: checks a left foe is skipped by that member @tick = 0 @dist = {} # [map object id, x, y] => distance map to that post @leave = false # the contract ended: the squad leaves on the next map frame @engaged = {} # role => [foe event, reason, best distance, checks with no step nearer] @busy = {} # role => true: it hunted since it last stood at its post @skip = {} # role => {foe event => check number it is skipped until} @lona_hit = {} # foe event => true: NPCs Lona hit on this map @checks = 0 @piece_n = nil # [pieces, doors] of the post base at the last check (posts checked again on a change) def self.say(text) p "LonaCraft Mercs: #{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.cfg raids.cfg["mercs"] end def self.enabled? return false unless defined?(LonaCraft::Bases) && defined?(LonaCraft::Raids) bases.enabled? && cfg["enabled"] ? true : false end def self.now bases.date_now end def self.per_day defined?(Game_Date::DAY_LENGTH) ? Game_Date::DAY_LENGTH : 2 end def self.clean(label) label.to_s.gsub(/[,\[\]\r\n]/, "") end def self.wrapper_script(game_script) LonaCraft::Homes.wrapper_script(game_script) end #---------------------------------------------------------------------- # The contract #---------------------------------------------------------------------- def self.root return nil if $game_system.nil? || !$game_system.respond_to?(:lonacraft_data) $game_system.lonacraft_data end # the contract, or nil def self.record d = root return nil if d.nil? r = d["mercs"] return nil unless r.is_a?(Hash) && r["until"].is_a?(Integer) r["down"] = {} unless r["down"].is_a?(Hash) r end def self.hired? r = record !r.nil? && now <= r["until"] end def self.days_left r = record return 0 if r.nil? left = r["until"] - now return 0 if left < 0 [(left + per_day - 1) / per_day, 1].max end def self.coin $data_ItemName[cfg["coin"].to_s] end def self.coin_name c = coin c ? $game_text[c.name].to_s : cfg["coin"].to_s end def self.price_of(days) base = days.to_i * cfg["price_per_day"].to_i [(base * raids.diff("merc_price_mult").to_f - 1e-9).ceil, 0].max # R10, hard: base end def self.price_text(days) "#{price_of(days)} #{coin_name}" end def self.pick_name list = text("Names/list").split(",").map{|n| n.strip }.reject{|n| n.empty? || n.include?(":") } list.empty? ? "Brann" : list.sample end # Pays +days+: :ok (new contract), :extended, :no_coins, :off def self.pay(days, interp = nil) return :off unless enabled? days = days.to_i return :off if days < 1 d = root return :off if d.nil? cost = price_of(days) c = coin return :off if c.nil? return :no_coins if $game_party.item_number(c) < cost if interp && interp.respond_to?(:optain_lose_item) interp.optain_lose_item(c, cost) else $game_party.lose_item(c, cost) end add_days(days) end def self.add_days(days) r = record if r && now <= r["until"] r["until"] += days * per_day r["warned"] = false say("contract extended by #{days} days, until #{r["until"]}") return :extended end root["mercs"] = {"until" => now + days * per_day, "base" => nil, "name" => pick_name, "down" => {}, "hired" => now, "warned" => false} say("squad hired for #{days} days, captain #{root["mercs"]["name"]}, until #{root["mercs"]["until"]}") :ok end def self.end_contract(why) d = root return if d.nil? d.delete("mercs") @dist = {} @leave = true say("contract over (#{why})") end def self.notice(id, str) return unless defined?(LonaCraft::Homes) LonaCraft::Homes.notice(LonaCraft::RuntimeText.key(FILE, id, str)) end def self.with_name(str) r = record str.to_s.gsub("NAME", r ? r["name"].to_s : "") end # Game_Date hook: the warning one day before and the end def self.on_date_moved r = record return if r.nil? t = now r["down"].delete_if{|role, up| up.to_i <= t } if t > r["until"] notice("rt_ended", text("Notice/ended")) end_contract(:expired) return end if !r["warned"] && r["until"] - t < per_day r["warned"] = true notice("rt_one_day", text("Notice/one_day")) end rescue => e say("date hook error #{e.class} #{e.message}") end def self.down?(role, at = now) r = record return false if r.nil? r["down"][role].to_i > at end #---------------------------------------------------------------------- # Away raids (140_AwayRaids.rb) #---------------------------------------------------------------------- # the squad's power against an away raid on +rec+ at date unit +u+, or nil def self.guard(rec, u) return nil unless enabled? r = record return nil if r.nil? || r["base"].nil? || rec.nil? || r["base"].to_i != rec["id"].to_i return nil if u > r["until"] up = ROLES.count{|role| !down?(role, u) } return nil if up == 0 cfg["squad_power"].to_f * up / ROLES.size end def self.knock_down(rec, u) r = record return if r.nil? back = u + cfg["down_days"].to_i * per_day ROLES.each{|role| r["down"][role] = [r["down"][role].to_i, back].max } say("the squad at base #{rec["id"]} is down until #{back}") end def self.base_gone(rec) r = record return if r.nil? || r["base"].nil? || r["base"].to_i != rec["id"].to_i r["base"] = nil notice("rt_base_gone", text("Notice/base_gone").gsub("BASE", bases.name_of(rec))) end #---------------------------------------------------------------------- # The guild menu line (call_msg alias below) #---------------------------------------------------------------------- def self.guild_label if hired? clean(text("Guild/menu_contract").gsub("NUM", days_left.to_s)) else clean(text("Guild/menu_hire").gsub("PRICE", price_text(1))) end end # [runtime key, index of the added line] or nil def self.guild_menu return nil unless enabled? dialog = $game_text[GUILD_MENU_KEY].to_s labels = [guild_label] # R13: the maid line while Boss Mama is away (170_Maid.rb) maid = defined?(LonaCraft::Maid) && LonaCraft::Maid.guild_offer? ? clean(LonaCraft::Maid.menu_label) : nil labels << maid if maid got = LonaCraft::Homes.extend_menu(dialog, labels, nil) if got.nil? say("the guild menu text has no \\optB list, no line added") return nil end [LonaCraft::RuntimeText.key(FILE, "rt_guild_menu", got[0]), got[1], maid ? got[1] + 1 : nil] rescue => e say("guild menu error #{e.class} #{e.message}") nil end def self.day_labels cfg["day_choices"].map{|d| t = d.to_i == 1 ? text("Days/one") : text("Days/many").gsub("NUM", d.to_s) clean(t.gsub("PRICE", price_text(d))) } end #---------------------------------------------------------------------- # The squad on the map #---------------------------------------------------------------------- def self.member?(ev) return false if ev.nil? || (ev.respond_to?(:deleted?) && ev.deleted?) sd = ev.respond_to?(:summon_data) ? ev.summon_data : nil sd.is_a?(Hash) && !sd[:LonaCraftMerc].nil? end def self.live_members(map) out = {} return out if map.nil? map.events.values.each{|ev| next unless member?(ev) out[ev.summon_data[:LonaCraftMerc]] = ev } out end def self.dead?(ev) npc = ev.npc return true if npc.nil? return true if npc.action_state == :death npc.stat.get_stat("sta") <= 0 rescue false end def self.despawn(ev) ev.nappable = false if ev.respond_to?(:nappable=) ev.delete rescue => e say("despawn error #{e.class} #{e.message}") end # Game_Map#setup alias (after): the squad at its post base (+entered+ is false for a nap) def self.after_setup(map, entered) @dist = {} @engaged = {} @busy = {} @skip = {} @lona_hit = {} @piece_n = nil return if map.nil? || map.isOverMap r = record return if r.nil? || !enabled? rec = bases.record_for_map(map) return if rec.nil? if r["base"] && bases.record_by_id(r["base"]).nil? r["base"] = nil # the post base is gone (destroy-all, emptied) end return if r["base"].nil? || r["base"].to_i != rec["id"].to_i spawn_squad(map, rec) end # 2026-10-08: {[x, y] => true} tiles no member may post on: every base # piece and the tiles within POST_GAP - 1 of it (4 directions), and the # DOOR_LANE tiles straight out of each door def self.blocked_tiles(rec) out = {} r = POST_GAP - 1 bases.cells_of(bases.pieces_of(rec)).each{|c| (-r..r).each{|dx| w = r - dx.abs (-w..w).each{|dy| out[[c[0] + dx, c[1] + dy]] = true } } } raids.door_cells(rec).each{|d| DIRS.each{|dir, dx, dy| (1..DOOR_LANE).each{|k| out[[d[0] + dx * k, d[1] + dy * k]] = true } } } out end # {role => [x, y, facing]} (a 4th element true: the fallback tile) for # +roles+; +taken+ {[x, y] => true} tiles already posted. 2026-10-08: # free tiles clear of blocked_tiles, nearest the main door by walking # distance, the outside first, then inside the walls; none: the free # tile farthest from the door, with a console line. def self.post_tiles(map, rec, roles = ["A", "B", "L"], taken = {}) b = raids.play_bounds(map) reach = raids.flood_outside(map, rec, b) sm = map.storypoint_map sp = sm.is_a?(Hash) ? sm["StartPoint"] : nil start = sp.is_a?(Array) ? [sp[0].to_i, sp[1].to_i] : [$game_player.x, $game_player.y] blocked = blocked_tiles(rec) taken = taken.dup ok = lambda{|c| !blocked[c] && !taken[c] && raids.free_tile?(map, c[0], c[1]) } out = {} box = raids.base_box(rec) return out if box.nil? mx = (box[0] + box[2]) / 2.0 my = (box[1] + box[3]) / 2.0 # the main door and the tile outside it door = nil anchor = nil face = 2 raids.door_cells(rec).sort_by{|d| (d[0] - start[0]).abs + (d[1] - start[1]).abs }.each{|d| DIRS.each{|dir, dx, dy| c = [d[0] + dx, d[1] + dy] next unless reach[c] door = d anchor = c face = dir break } break if anchor } if anchor.nil? # no door with an outside: the outside tile next to the base nearest the StartPoint cands = reach.keys.select{|c| raids.box_dist(box, c[0], c[1]) == 1 } anchor = cands.min_by{|c| (c[0] - start[0]).abs + (c[1] - start[1]).abs } if anchor dx = anchor[0] - mx dy = anchor[1] - my face = dx.abs > dy.abs ? (dx < 0 ? 4 : 6) : (dy < 0 ? 8 : 2) end end ref = door || anchor || [mx.round, my.round] # the outside by walking distance from the door (ties: off the line # straight out of it first, then by y and x), then the inside by distance to it axis = lambda{|c| door && (door[0] == anchor[0] ? c[0] == door[0] : c[1] == door[1]) ? 1 : 0 } outside = anchor ? raids.bfs(map, [anchor], reach).sort_by{|c, n| [n, axis.call(c), c[1], c[0]] }.map{|c, n| c } : [] inside = nil roles.each{|role| c = outside.find{|o| ok.call(o) } if c.nil? inside ||= bases.inside_tiles(map, rec, raids.region_lists(map)).keys.sort_by{|o| (o[0] - ref[0]).abs + (o[1] - ref[1]).abs } c = inside.find{|o| ok.call(o) } end fell = false if c.nil? pool = (outside + inside).select{|o| !taken[o] && raids.free_tile?(map, o[0], o[1]) } c = pool.max_by{|o| (o[0] - ref[0]).abs + (o[1] - ref[1]).abs } fell = true say("no free tile #{POST_GAP} from the base pieces for #{role}: the farthest free tile from the door, #{c.inspect}") end next if c.nil? taken[c] = true out[role] = fell ? [c[0], c[1], face, true] : [c[0], c[1], face] } out end # 2026-10-08: a member whose post breaks the rule now (a piece built # next to it) gets a new one; the walk back goes there def self.repost(map, rec, members) blocked = blocked_tiles(rec) bad = [] taken = {} members.each{|role, ev| post = ev.summon_data[:LonaCraftMercPost] next unless post.is_a?(Array) if !post[3] && blocked[[post[0], post[1]]] bad << role else taken[[post[0], post[1]]] = true end } return if bad.empty? posts = post_tiles(map, rec, bad, taken) bad.each{|role| post = posts[role] members[role].summon_data[:LonaCraftMercPost] = post if post } say("posts chosen again for #{bad.join(", ")}: #{posts.inspect}") end def self.label(name) RPG::EventCommand.new(118, 0, [name]) end def self.build_event(role, x, y, face) sheet, index, pattern = SPRITES[role] ev = RPG::Event.new(x, y) ev.name = "#{EVENT_PREFIX}#{role}" page = RPG::Event::Page.new page.graphic.tile_id = 0 page.graphic.character_name = sheet page.graphic.character_index = index page.graphic.direction = face page.graphic.pattern = pattern page.move_type = 3 page.walk_anime = true page.step_anime = false page.direction_fix = false page.through = false page.priority_type = 1 page.trigger = 0 list = [] list << label("init") list << label("common") ["@nappable = false", "set_npc(#{NPC_DATA[role].inspect})", "@npc.stat.set_stat(\"arousal\", 0)", "@npc.stat.set_stat(\"mood\", 20)", "@npc.master = $game_player", "@npc.drop_list = []", "@npc.fraction_mode = 2"].each{|line| list << EvLib.NewEventCMD(line) } list << label("end_common") list << EvLib.NewEventCMD("lonacraft_merc_talk(#{role.inspect}) if respond_to?(:lonacraft_merc_talk)") list << RPG::EventCommand.new(0, 0, []) page.list = list ev.pages = [page] ev end def self.spawn_squad(map, rec) if NPC_DATA.values.uniq.any?{|n| $data_npcs.nil? || $data_npcs[n].nil? } say("NPC data missing (#{NPC_FILES.join(", ")}), no squad") return end have = live_members(map) need = ROLES.reject{|role| have[role] || down?(role) } return if need.empty? taken = {} have.each_value{|ev| post = ev.summon_data[:LonaCraftMercPost] taken[[post[0], post[1]]] = true if post.is_a?(Array) } posts = post_tiles(map, rec, ["A", "B", "L"].select{|role| need.include?(role) }, taken) made = [] need.each{|role| post = posts[role] next if post.nil? ev = build_event(role, post[0], post[1], post[2]) map.lonacraft_spawn_event(ev, {:LonaCraftMerc => role, :LonaCraftMercPost => post}) made << role } say("squad at base #{rec["id"]}: #{made.join(", ")} made, posts #{posts.inspect}") unless made.empty? rescue => e say("spawn error #{e.class} #{e.message} #{e.backtrace ? e.backtrace[0] : ""}") end # Scene_Map#update: deaths count as down; a squad with no contract or # off its post base leaves def self.update @tick += 1 return if @tick < CHECK_EVERY @tick = 0 r = record return if r.nil? && !@leave map = $game_map return if map.nil? || map.isOverMap members = live_members(map) if members.empty? @leave = false if r.nil? return end rec = bases.record_for_map(map) if r.nil? || rec.nil? || r["base"].nil? || r["base"].to_i != rec["id"].to_i members.each_value{|ev| despawn(ev) } @leave = false say("the squad leaves this map") return end t = now back = t + cfg["down_days"].to_i * per_day members.each{|role, ev| next unless dead?(ev) next if r["down"][role].to_i > t r["down"][role] = back say("#{role} is down until #{back}") } up = members.reject{|role, ev| dead?(ev) } n = [bases.pieces_of(rec).size, raids.door_cells(rec).size] if n != @piece_n @piece_n = n @dist = {} repost(map, rec, up) end engage(map, up) rescue => e say("update error #{e.class} #{e.message}") end #---------------------------------------------------------------------- # Hunting (2026-10-08) #---------------------------------------------------------------------- def self.trace(line) LonaCraft.trace(line) if LonaCraft.respond_to?(:trace_on?) && LonaCraft.trace_on? rescue nil end def self.member_name(role) r = record role == "L" && r ? "#{r["name"]} (captain)" : "mercenary #{role}" end def self.foe_label(ev) "#{ev.npc.npc_name} (event #{ev.id})" rescue "an NPC" end # +ev+ is alive on +map+ and not on Lona's side def self.foe_alive?(map, ev) return false if ev.nil? || (ev.respond_to?(:deleted?) && ev.deleted?) return false unless map.events[ev.id].equal?(ev) return false unless ev.respond_to?(:npc?) && ev.npc? npc = ev.npc return false if npc.nil? || npc.action_state == :death return false if npc.respond_to?(:npc_dead?) && npc.npc_dead? !bases.lona_side?(ev) rescue false end # Game_NonPlayerCharacter#set_last_attacker alias: Lona hit +npc+ def self.lona_hit(npc) return if record.nil? ev = npc.event return if ev.nil? || @lona_hit[ev] return if npc.is_object || npc.action_state == :death return if ev.instance_variable_get(:@missile) || bases::NOT_CREATURE_RACES.include?(npc.race.to_s) return if bases.lona_side?(ev) @lona_hit[ev] = true end # [[foe event, :hostile / :lona]] on +map+ def self.foes(map) @lona_hit.delete_if{|ev, v| !foe_alive?(map, ev) } out = [] map.events.values.each{|ev| next if ev.nil? if @lona_hit[ev] out << [ev, :lona] else hostile = begin bases.counts_as_hostile?(ev) rescue false end out << [ev, :hostile] if hostile end } out end def self.idle?(npc) npc.action_state.nil? || npc.action_state == :none end # every CHECK_EVERY frames, the members that are up def self.engage(map, members) @checks += 1 list = nil members.each{|role, ev| begin npc = ev.npc next if npc.nil? cur = @engaged[role] # a target the game's AI took itself (a live raid, a foe it saw): its own next if npc.target && !(cur && npc.target.equal?(cur[0])) list ||= foes(map) engage_one(role, ev, npc, list) rescue => e say("engage error #{role} #{e.class} #{e.message}") end } end def self.engage_one(role, ev, npc, list) cur = @engaged[role] cur = nil if cur && !list.any?{|f| f[0].equal?(cur[0]) } # dead, gone, or no foe now if cur d = (ev.x - cur[0].x).abs + (ev.y - cur[0].y).abs if d < cur[2] cur[2] = d cur[3] = 0 elsif d > 1 cur[3] += 1 end if cur[3] < GIVE_UP_CHECKS hold(npc, cur[0]) return end (@skip[role] ||= {})[cur[0]] = @checks + SKIP_CHECKS trace("mercs: #{member_name(role)} cannot reach #{foe_label(cur[0])}") npc.process_target_lost(false) if npc.target.equal?(cur[0]) && idle?(npc) end @engaged.delete(role) return if npc.target # still on it: the game's AI lets go of it itself sk = @skip[role] || {} sk.delete_if{|e, u| u <= @checks } pick = list.reject{|f| sk[f[0]] }.min_by{|f| (f[0].x - ev.x).abs + (f[0].y - ev.y).abs } if pick.nil? trace("mercs: #{member_name(role)} back to post") if @busy.delete(role) return end return unless idle?(npc) @engaged[role] = [pick[0], pick[1], (ev.x - pick[0].x).abs + (ev.y - pick[0].y).abs, 0] @busy[role] = true hold(npc, pick[0]) trace("mercs: #{member_name(role)} engages #{foe_label(pick[0])} (reason #{pick[1] == :lona ? "lona attacked" : "hostile"})") end # the game's aggro on +foe+ (281_Game_NonPlayerCharacter.rb:1256 # set_aggro: the target, alert 2, aggro frames), or its frames topped up def self.hold(npc, foe) return if foe.npc.nil? || foe.npc.user_redirect # set_aggro would aim at its user if npc.target.equal?(foe) npc.instance_variable_set(:@aggro_frame, ENGAGE_FRAMES) if npc.aggro_frame.to_i < ENGAGE_FRAMES elsif idle?(npc) npc.set_aggro(foe.npc, nil, ENGAGE_FRAMES) end end # Game_Event#update_self_movement alias: true = moved / held here def self.drive(ev) npc = ev.npc return false if npc.nil? return false unless npc.action_state.nil? || npc.action_state == :none return false unless npc.target.nil? post = ev.summon_data[:LonaCraftMercPost] return true unless post.is_a?(Array) if ev.x == post[0] && ev.y == post[1] ev.set_direction(post[2]) if ev.direction != post[2] return true end return true if ev.moving? dist = dist_to(post) d0 = dist ? dist[[ev.x, ev.y]] : nil if d0 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) return true } end ev.move_toward_xy(post[0], post[1]) if ev.respond_to?(:move_toward_xy) && rand(4) == 0 true rescue => e say("drive error #{e.class} #{e.message}") false end def self.dist_to(post) map = $game_map key = [map.object_id, post[0], post[1]] return @dist[key] if @dist.key?(key) rec = bases.record_for_map(map) closed = rec ? raids.door_closed_at(map, rec) : {} @dist[key] = raids.bfs(map, [[post[0], post[1]]], nil, raids.play_bounds(map), closed) rescue @dist[key] = nil end # 120_Raids.rb start_grace: the captain calls out def self.raid_warning(map) cap = live_members(map)["L"] return if cap.nil? || dead?(cap) key = LonaCraft::RuntimeText.key(FILE, "rt_warn", with_name(text("Raid/warn"))) map.popup(cap.id, key, 0, 0) end # Captain menu: "Move post" and "Dismiss" # the post goes to base +rec+ (the squad is made at its next setup) def self.post_at(rec) r = record return false if r.nil? || rec.nil? return false if r["base"].to_i == rec["id"].to_i r["base"] = rec["id"] live_members($game_map).each_value{|ev| despawn(ev) } say("post moved to base #{rec["id"]} (#{bases.name_of(rec)})") true end def self.post_name r = record rec = r && r["base"] ? bases.record_by_id(r["base"]) : nil rec ? bases.name_of(rec) : "" end def self.dismiss live_members($game_map).each_value{|ev| despawn(ev) } end_contract(:dismissed) end def self.debug_hire(days) res = add_days(days) if record["base"].nil? here = bases.record_for_map($game_map) pick = here || bases.pick_list.first record["base"] = pick["id"] if pick end bases.debug_say("LonaCraft debug squad #{res}, #{days_left} days, captain #{record["name"]}") end # NPC/*.json into $data_npcs (DataManager.load_mod_database alias below) def self.load_npcs NPC_FILES.each{|rel| path = LonaCraft.resource(rel) unless File.exist?(path) say("missing #{path}") next end npc = NonPlayerCharacter::Data_NPC.load_from_json(JSON.decode(File.read(path))) $data_npcs[npc.name] = npc } rescue => e say("NPC data error #{e.class} #{e.message}") end def self.install_redirect return if $mod_load_script.nil? || !defined?(LonaCraft::Homes) LonaCraft::Homes.redirect(GUILD_SCRIPT) rescue => e say("redirect error #{e.class} #{e.message}") end end end LonaCraft::Mercs.install_redirect #============================================================================== # DataManager: the squad's NPC data #============================================================================== module DataManager unless respond_to?(:load_mod_database_lonacraft_mercs) self.singleton_class.send(:alias_method, :load_mod_database_lonacraft_mercs, :load_mod_database) def self.load_mod_database load_mod_database_lonacraft_mercs LonaCraft::Mercs.load_npcs end end end #============================================================================== # Game_Date: contract warning and end (after 140_AwayRaids.rb's rolls) #============================================================================== class Game_Date [:shift, :addDays, :oneDayForward].each{|meth| old = "#{meth}_lonacraft_mercs".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::Mercs.on_date_moved if $game_date.equal?(self) rescue => e p "LonaCraft Mercs date hook error #{e.class} #{e.message}" end result } } end class Game_Map unless method_defined?(:setup_lonacraft_mercs) alias_method :setup_lonacraft_mercs, :setup def setup(map_id) before = @map_id_rec forced = @force_setup setup_lonacraft_mercs(map_id) begin LonaCraft::Mercs.after_setup(self, before != @map_id_rec || forced) rescue => e p "LonaCraft Mercs setup error #{e.class} #{e.message}" end end end end class Game_Event unless method_defined?(:lonacraft_mercs_self_movement) alias_method :lonacraft_mercs_self_movement, :update_self_movement def update_self_movement if @summon_data.is_a?(Hash) && @summon_data[:LonaCraftMerc] return if LonaCraft::Mercs.drive(self) end lonacraft_mercs_self_movement end end end # 2026-10-08: the NPCs Lona hits become the squad's foes class Game_NonPlayerCharacter if method_defined?(:set_last_attacker) && !method_defined?(:set_last_attacker_lonacraft_mercs) alias_method :set_last_attacker_lonacraft_mercs, :set_last_attacker def set_last_attacker(attacker) result = set_last_attacker_lonacraft_mercs(attacker) begin LonaCraft::Mercs.lona_hit(self) if !$game_player.nil? && @last_attacker.equal?($game_player) rescue => e p "LonaCraft Mercs hit hook error #{e.class} #{e.message}" end result end end end class Scene_Map unless method_defined?(:update_lonacraft_mercs) alias_method :update_lonacraft_mercs, :update def update update_lonacraft_mercs LonaCraft::Mercs.update end end end #============================================================================== # Game_Interpreter: the guild line, the hire talk, the captain #============================================================================== class Game_Interpreter # Run by HCGframes/NoerTavernGuildEmpolyee.rb in place of the game's script def lonacraft_merc_guild(game_script) @lonacraft_merc_guild = LonaCraft::Mercs.enabled? begin lonacraft_run_previous_script(game_script) ensure @lonacraft_merc_guild = nil end end # a message from a runtime text with an \optB list; the choice or -1 def lonacraft_merc_ask(id, text, options) m = LonaCraft::Mercs opts = options.map{|o| m.clean(o) }.join(",") call_msg(LonaCraft::RuntimeText.key(m::FILE, id, "#{text}\\optB[#{opts}]")) pick = $game_temp.choice $game_temp.choice = -1 pick.nil? ? -1 : pick end def lonacraft_merc_say(id, text) call_msg(LonaCraft::RuntimeText.key(LonaCraft::Mercs::FILE, id, text)) end # days picked (nil = none) from +ask+ (a text) and the day list def lonacraft_merc_pick_days(ask) m = LonaCraft::Mercs choices = m.cfg["day_choices"] pick = lonacraft_merc_ask("rt_days", ask, [m.text("Opt/cancel")] + m.day_labels) return nil if pick < 1 || pick > choices.size choices[pick - 1].to_i end # The guild line: hire (days, then the base), or the contract's state, # a new post when it has none, and more days def lonacraft_merc_guild_offer m = LonaCraft::Mercs b = LonaCraft::Bases price = m.price_text(1) if m.hired? if m.record["base"].nil? lonacraft_merc_say("rt_status", m.with_name(m.text("Guild/status_wait")).gsub("NUM", m.days_left.to_s)) rec = b.choose_base("LonaCraft:Mercs:Guild/ask_base") if rec && m.post_at(rec) lonacraft_merc_say("rt_posted", m.with_name(m.text("Guild/posted")).gsub("BASE", b.name_of(rec))) end else lonacraft_merc_say("rt_status", m.with_name(m.text("Guild/status")).gsub("NUM", m.days_left.to_s).gsub("BASE", m.post_name)) end else if b.pick_list.empty? call_msg("LonaCraft:Mercs:Guild/no_base") return end lonacraft_merc_say("rt_offer", m.text("Guild/offer").gsub("PRICE", price)) end days = lonacraft_merc_pick_days(m.text("Guild/ask_days").gsub("PRICE", price)) return if days.nil? rec = nil unless m.hired? rec = b.choose_base("LonaCraft:Mercs:Guild/ask_base") return if rec.nil? end case m.pay(days, self) when :no_coins call_msg("LonaCraft:Mercs:Guild/no_coins") when :ok m.post_at(rec) lonacraft_merc_say("rt_hired", m.with_name(m.text("Guild/hired")).gsub("BASE", b.name_of(rec))) when :extended lonacraft_merc_say("rt_extended", m.text("Guild/extended").gsub("NUM", days.to_s)) end end # The squad's action key def lonacraft_merc_talk(role) m = LonaCraft::Mercs r = m.record return if r.nil? if role != "L" lonacraft_merc_say("rt_merc", m.with_name(m.text("Talk/merc"))) cam_center(0) if respond_to?(:cam_center) return end pick = lonacraft_merc_ask("rt_captain", m.with_name(m.text("Talk/captain_menu")).gsub("NUM", m.days_left.to_s), [m.text("Talk/opt_status"), m.text("Talk/opt_add"), m.text("Talk/opt_move"), m.text("Talk/opt_dismiss"), m.text("Opt/cancel")]) case pick when 0 down = m::ROLES.count{|x| m.down?(x) } line = down == 0 ? m.text("Talk/status_ok") : m.text("Talk/status_down").gsub("NUM", down.to_s) lonacraft_merc_say("rt_status", m.with_name(line).gsub("NUM", m.days_left.to_s)) when 1 days = lonacraft_merc_pick_days(m.with_name(m.text("Talk/ask_days"))) unless days.nil? case m.pay(days, self) when :no_coins lonacraft_merc_say("rt_short", m.with_name(m.text("Talk/no_coins"))) when :ok, :extended lonacraft_merc_say("rt_extended", m.with_name(m.text("Talk/extended")).gsub("NUM", days.to_s)) end end when 2 rec = LonaCraft::Bases.choose_base("LonaCraft:Mercs:Talk/ask_post") if rec && m.post_at(rec) name = LonaCraft::Bases.name_of(rec) lonacraft_merc_say("rt_move", m.with_name(m.text("Talk/move")).gsub("BASE", name)) $game_map.popup(0, LonaCraft::RuntimeText.key(m::FILE, "rt_moving", m.text("Notice/moving").gsub("BASE", name)), 0, 0) end when 3 yes = lonacraft_merc_ask("rt_dismiss", m.with_name(m.text("Talk/dismiss_ask")), [m.text("Talk/opt_no"), m.text("Talk/opt_yes")]) if yes == 1 lonacraft_merc_say("rt_dismissed", m.with_name(m.text("Talk/dismissed"))) m.dismiss $game_map.popup(0, "LonaCraft:Mercs:Notice/dismissed", 0, 0) end end cam_center(0) if respond_to?(:cam_center) portrait_hide if respond_to?(:portrait_hide) $game_temp.choice = -1 end # The guild's "nothing pending" menu gets the mercenary line (choice 3) if method_defined?(:call_msg) && !method_defined?(:call_msg_lonacraft_mercs) alias_method :call_msg_lonacraft_mercs, :call_msg def call_msg(*args) return call_msg_lonacraft_mercs(*args) unless @lonacraft_merc_guild && args[0] == LonaCraft::Mercs::GUILD_MENU_KEY @lonacraft_merc_guild = nil menu = LonaCraft::Mercs.guild_menu return call_msg_lonacraft_mercs(*args) if menu.nil? new_args = args.dup new_args[0] = menu[0] result = call_msg_lonacraft_mercs(*new_args) if $game_temp.choice == menu[1] $game_temp.choice = -1 begin lonacraft_merc_guild_offer rescue => e p "LonaCraft Mercs guild error #{e.class} #{e.message}" end $game_temp.choice = -1 elsif menu[2] && $game_temp.choice == menu[2] $game_temp.choice = -1 begin lonacraft_maid_offer rescue => e p "LonaCraft Maid guild error #{e.class} #{e.message}" end $game_temp.choice = -1 end result end end end