#============================================================================== # LonaCraft - 170_Maid.rb (board R13, research docs/RESEARCH_MAID.md, owner # decisions 2026-10-06: all 14 choices as recommended, except choice 12: she # needs a Bed or Bedroll inside the walls to take post). # A maid who keeps one post, a base or a house Lona owns (owner 2026-10-07: # "The maid should also be able to be sent to any houses you own, not just # bases."): she cooks the food left in its chests into the dark pot's dishes, # is paid a copper a day from a chest there, never fights, and is gone for # good when she dies. # What it does: # * Posts: a named base (Bases.pick_list), or a bought house of 100_Homes.rb # (a LOCATIONS row with its own map, not :mode :rent; today the Old Shack # and the Stone House; a rented inn room is never a post). Saved as "base" # (the base record id) or "home" (the location id), never both; Maid.post # gives [:base, record] or [:home, id]; a save with only "base" is as # before. In a house the whole house is inside the walls (as 160_Rest.rb # Rest.inside): every placed piece on the house's map counts for the bed # rule, the wages and the cooking. # * Hire: Boss Mama in the Noer tavern, a line "Hire a maid 5 Copper" in her # menu (Homes.add_menu_provider over the SELLERS wrapper of # NoerTavernWaifu.rb, 100_Homes.rb); while Boss Mama is away from the tavern # (her event's own init rule, Map059 ev69: UniqueCharUniqueTavernWaifu -1, # RecQuestCocona 14-20 or 25, or 4 before RecQuestCoconaAmt) the guild # receptionist offers the same line (150_Mercs.rb guild menu). The post is # picked by name (Maid.post_choices: the bases, then the owned houses); it # needs a Bed or Bedroll inside the walls, else Boss Mama says "There is # nowhere for her to sleep." (Hire/no_bed; Change 2026-10-08, owner: "We # are talking to Big Momma, not the maid she sends.") and nothing is # charged. # "hire_fee" 5 Copper Coins from Lona's purse (+ the difficulty level's # "maid_fee_add": hard 5, hell 7, doom 8; R10, Config/Bases.json # "difficulty"); a name, hair and face are drawn and saved. A hired maid # keeps her terms; her daily "pay" is never scaled. # * Wages: at every date move into day ("catchup_days" 14 at most), "pay" 1 # "coin" (ItemCoin1) from a chest or wardrobe inside the walls (the pantry # first); none: one more unpaid day; a paid day clears them. "grace_days" 3 # unpaid days: she leaves, with a popup. # * Cooking, the same morning, after the wages: with a Stove or Cooking Fire # inside the walls ("need_fire"; the fire stands in for the recipes' Wood), # up to "dishes_per_day" 2 dishes while fewer than "pantry_cap" 6 cooked # dishes are inside the walls. Recipes: $data_AlchemyRecipes (the dark pot) # whose output is one of the rest's plain dishes (160_Rest.rb DISHES: Meat # Salad, Good Soup, Smoked Meat, Meat Soup, Plant Soup, Dry Food); never # human or mystic meat, never FoodBad; MinStatReq checked against # "cook_skill" 10. Ingredients: items with pot_data in the chests inside # the walls, covered greedily (the item covering most of what is still # missing first, then the cheapest). Best = satiety of the dish (+ mood / 10) # minus the satiety of cooked dishes used up. Into the pantry: the chest # inside the walls nearest the fire. A popup on waking: " cooked ...". # The rest's chest meal (160_Rest.rb) eats these dishes. # * At the post: the runtime event (NPC/LonaCraftMaid.json, AI # Npc_LonaCraftMaid < Npc_RunAway, no skills, health 150; sheet # -char-F-REGULAR01 index 0 pattern 2, the game's unused "02Maid" look; the # saved hair and face are put back after every spawn), made after every # setup of the post's map (a base, or the house map, Homes.map_id_for). # She stands by the fire (else by a bed), wanders "wander" 3 tiles inside # her room; a hostile within "flee_radius" 6 tiles or a live raid (bases # only): she runs to the tile of her room farthest from its doors. In a # house her room is the floor (Homes.floor_tiles) minus the tiles on or # next to the -point-StartPoint / -point-ExitPoint (the stairs stay free), # and the hiding tile is the floor tile farthest from those points. # * Death: in a live raid (Game_NonPlayerCharacter#process_death alias) the # hire ends for good with a popup; rehire at Boss Mama. Away raids # (140_AwayRaids.rb): raiders who reach her room with blows left kill her # one time in two ("away_kill" 0.5, + the level's "maid_kill_add": hell # 0.6, doom 0.75), else she hid; both in the report. # Away raids never touch a house (towns are safe). # * Her menu: status (days paid, dishes cooked, the pantry, where she is), # Move (the bases and the owned houses, the same bed rule; her refusal is # her own line Talk/no_bed "There is nowhere for me to sleep there.", # 2026-10-08), Dismiss. # * Save: $game_system.lonacraft_data["maid"] (plain types; "base" or "home"). # * Nothing here runs without a hire (the Boss Mama line excepted). #============================================================================== module LonaCraft module Maid TEXT = "LonaCraft:Maid:" FILE = "Maid" NPC_NAME = "LonaCraftMaid" NPC_FILE = "NPC/LonaCraftMaid.json" SPRITE = ["-char-F-REGULAR01", 0, 2] # "02Maid" (CHSconfigs_NPC/-char-F-REGULAR01.json) # the "02Maid" part lists of that file (hair = head_equip, face = head) HAIRS = ["FregC_HeadEquip_human_GoldenWave.png", "FregC_HeadEquip_human_ShorGoldtWave.png", "FregC_HeadEquip_human_PoorSlaveLong.png", "FregC_HeadEquip_human_PoorSlaveShort.png", "FregC_HeadEquip_human_PurpleShort.png", "FregC_HeadEquip_human_FeiraGreen.png", "FregC_HeadEquip_human_EliseGoldHair.png", "FregC_HeadEquip_human_ElfArcher.png", "FregC_HeadEquip_HairMootRedMessy.png", "FregC_HeadEquip_human_ShortWhite.png", "FregC_HeadEquip_human_LongBrown.png", "FregC_HeadEquip_human_ShortRound.png", "FregC_HeadEquip_human_OldSlut.png"] FACES = ["FregC_head_human_NPC.png", "FregC_head_human_teller.png", "FregC_head_human_OldMama.png", "FregC_head_human_anonymous.png"] SELLER = "NoerTavernWaifu" FIRE_KINDS = ["Stove", "Campfire"] BED_KINDS = ["Bed", "BedDark", "BedBlue", "PottedPlant"] # PottedPlant = the Bedroll BAD_TAGS = ["HumanMeat", "MysticMeat", "HumanMysticMeat"] DISH_MOOD = {"ItemMeatSalad" => 40, "ItemSopGood" => 20, "ItemSopMeat" => 10, "ItemSopPlant" => 10} CHECK_EVERY = 30 DIRS = [[2, 0, 1], [4, -1, 0], [6, 1, 0], [8, 0, -1]] @tick = 0 @leave = false @flee = {} # event id => true while she hides @dist = {} # [map object id, x, y] => distance map over her room @rooms = {} # map object id => {tile => true} her room def self.say(text) p "LonaCraft Maid: #{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.fur LonaCraft::Furniture end def self.cfg raids.cfg["maid"] end def self.enabled? return false unless defined?(LonaCraft::Bases) && defined?(LonaCraft::Raids) && defined?(LonaCraft::Furniture) 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 #---------------------------------------------------------------------- # The hire record #---------------------------------------------------------------------- def self.root return nil if $game_system.nil? || !$game_system.respond_to?(:lonacraft_data) $game_system.lonacraft_data end def self.record d = root return nil if d.nil? r = d["maid"] r.is_a?(Hash) && r["name"].is_a?(String) ? r : nil end #---------------------------------------------------------------------- # Her post: a base or a house (2026-10-07) #---------------------------------------------------------------------- def self.homes defined?(LonaCraft::Homes) ? LonaCraft::Homes : nil end # true for location +id+ of 100_Homes.rb that can be a post: a bought # house with its own map, registered this session (never a rented room) def self.house?(id) h = homes return false if h.nil? || !h.enabled? || !id.is_a?(String) loc = h.location(id) !loc.nil? && !h.rent?(loc) && loc[:interior].is_a?(Array) && !h.map_id_for(id).nil? end # the houses Lona owns that can be posts (LOCATIONS order) def self.house_ids h = homes return [] if h.nil? || !h.enabled? h.owned_ids.select{|id| house?(id) } end # [:home, location id] / [:base, base id] as saved in +r+, or nil (no lookup) def self.post_ref(r) return nil unless r.is_a?(Hash) return [:home, r["home"]] if r["home"].is_a?(String) && !r["home"].empty? r["base"].nil? ? nil : [:base, r["base"].to_i] end # [:base, base record] / [:home, location id] of her post (or of +r+); # nil when it is gone (a base removed, a house not owned or not loaded) def self.post(r = record) ref = post_ref(r) return nil if ref.nil? return (house?(ref[1]) && homes.owned?(ref[1]) ? ref : nil) if ref[0] == :home rec = bases.record_by_id(ref[1]) rec ? [:base, rec] : nil end # writes post +pt+ into record +r+: "base" or "home", never both def self.set_post(r, pt) if pt[0] == :home r.delete("base") r["home"] = pt[1] else r.delete("home") r["base"] = pt[1]["id"] end end def self.same_post?(a, b) return false if a.nil? || b.nil? || a[0] != b[0] a[0] == :home ? a[1] == b[1] : a[1]["id"].to_i == b[1]["id"].to_i end def self.house_name(id) h = homes loc = h ? h.location(id) : nil loc ? h.text(loc[:name]) : id.to_s end # the post's name for texts ("-" for none) def self.post_name(pt) return "-" if pt.nil? pt[0] == :home ? house_name(pt[1]) : bases.name_of(pt[1]) end # a menu entry for +pt+ (as Bases.choose_base: no commas, brackets, # colons or backslashes) def self.post_label(pt) post_name(pt).gsub(bases::NAME_DROP, "") end # the hire and Move menus: the bases the picker offers (Bases.pick_list), # then the owned houses def self.post_choices bases.pick_list.map{|rc| [:base, rc] } + house_ids.map{|id| [:home, id] } end # true when +map+ (the live Game_Map) is the map of post +pt+ def self.here?(map, pt) return false if map.nil? || pt.nil? return homes.home_at_map?(map) == pt[1] if pt[0] == :home rec = bases.record_for_map(map) !rec.nil? && rec["id"].to_i == pt[1]["id"].to_i end def self.notice(id, str) return unless defined?(LonaCraft::Homes) LonaCraft::Homes.notice(LonaCraft::RuntimeText.key(FILE, id, str)) end def self.named(key) r = record text(key).gsub("NAME", r ? r["name"].to_s : "") 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 # R10: the hire fee of the difficulty level def self.fee [cfg["hire_fee"].to_i + raids.diff("maid_fee_add").to_i, 0].max end def self.fee_text "#{fee} #{coin_name}" end def self.pick_name list = text("Names/list").split(",").map{|n| n.strip }.reject{|n| n.empty? || n.include?(":") } list.empty? ? "Anna" : list.sample end # ends the hire; +how+ :left, :dismissed, :killed def self.end_hire(how) d = root r = record return if d.nil? || r.nil? d["maid_lost"] = {"name" => r["name"], "at" => now, "how" => how.to_s} d.delete("maid") @leave = true say("#{r["name"]} is gone (#{how})") end #---------------------------------------------------------------------- # Inside the walls, offline (140_AwayRaids.rb inside_rooms) #---------------------------------------------------------------------- def self.inside_of(rec) return {} if rec.nil? || !defined?(LonaCraft::AwayRaids) LonaCraft::AwayRaids.inside_rooms(rec) end # [[furniture record, kind], ...] of base +rec+ whose own tile is inside def self.inside_furniture(rec, rooms = nil) rooms ||= inside_of(rec) out = [] bases.furniture_on(rec).each{|f| k = fur.kind_for(f["item_name"]) next if k.nil? out << [f, k] if rooms[[f["x"].to_i, f["y"].to_i]] } out end # [[furniture record, kind], ...] of house +id+: every placed piece on its # map (the whole house is inside the walls, 160_Rest.rb Rest.inside) def self.house_furniture(id) h = homes no = h ? h.map_id_for(id) : nil return [] if no.nil? out = [] fur.records.each{|f| next unless f.is_a?(Hash) && f["map_id"].to_i == no.to_i k = fur.kind_for(f["item_name"]) out << [f, k] if k } out end # the furniture inside the walls of post +pt+ def self.post_furniture(pt) return [] if pt.nil? pt[0] == :home ? house_furniture(pt[1]) : inside_furniture(pt[1]) end def self.bed_inside?(pt) post_furniture(pt).any?{|f, k| BED_KINDS.include?(k[:key]) } end def self.fire_of(list) list.find{|f, k| FIRE_KINDS.include?(k[:key]) } end # storage pieces inside, the pantry first (the one nearest the fire) def self.chests_of(list) chests = list.select{|f, k| k[:storage] } fire = fire_of(list) return chests if fire.nil? fx = fire[0]["x"].to_i fy = fire[0]["y"].to_i chests.sort_by{|f, k| (f["x"].to_i - fx).abs + (f["y"].to_i - fy).abs } end def self.box_of(f, make = false) id = f["box"].to_i if id < fur::BOX_BASE return nil unless make id = fur.next_box_id f["box"] = id end $game_boxes.box(id) if make fur.box_contents(id).is_a?(Hash) ? id : (make ? id : nil) end #---------------------------------------------------------------------- # The date hook: wages, then cooking, once per day #---------------------------------------------------------------------- def self.on_date_moved r = record return if r.nil? || !enabled? t = now last = r["t"].is_a?(Integer) ? r["t"] : t r["t"] = [last, t].max return if t <= last first = [last + 1, t - cfg["catchup_days"].to_i * per_day + 1].max cooked = [] (first..t).each{|u| next unless u.even? break if record.nil? pt = post if pt.nil? r["base"] = nil unless r["home"] # a base gone; a house not loaded keeps its place break end list = post_furniture(pt) pay_day(r, list) break if record.nil? cooked.concat(cook_day(r, list)) } report_cooking(r, cooked) if record rescue => e say("date hook error #{e.class} #{e.message} #{e.backtrace ? e.backtrace[0] : ""}") end def self.pay_day(r, list) c = coin need = cfg["pay"].to_i paid = false if c && need > 0 chests_of(list).each{|f, k| id = box_of(f) next if id.nil? box = fur.box_contents(id) obj = box.keys.find{|o| o.respond_to?(:item_name) && o.item_name.to_s == c.item_name.to_s && box[o].to_i >= need } next if obj.nil? $game_boxes.remove_item(obj, need, id, false) paid = true break } else paid = true end if paid r["unpaid"] = 0 r["paid"] = r["paid"].to_i + 1 return end r["unpaid"] = r["unpaid"].to_i + 1 say("no wages today (#{r["unpaid"]} unpaid)") if r["unpaid"] >= cfg["grace_days"].to_i notice("rt_left", named("Notice/left").gsub("NUM", r["unpaid"].to_s)) end_hire(:left) else notice("rt_unpaid", named("Notice/unpaid")) end end #---------------------------------------------------------------------- # Cooking #---------------------------------------------------------------------- def self.rest defined?(LonaCraft::Rest) ? LonaCraft::Rest : nil end # the plain dishes (160_Rest.rb DISHES group :plain) she may cook def self.dish?(name) r = rest row = r ? r::DISHES[name.to_s] : nil !row.nil? && row[1] == :plain end def self.dish_sat(name) r = rest row = r ? r::DISHES[name.to_s] : nil row ? row[0].to_i : 0 end def self.dish_item(name) it = $data_ItemName[name.to_s] it = $data_items[rest::MEAT_SALAD_ID] if it.nil? && name.to_s == "ItemMeatSalad" && rest it end # [{:out, :req, :ban, :excl, :min}, ...] from the dark pot's table def self.recipes list = defined?($data_AlchemyRecipes) && $data_AlchemyRecipes.is_a?(Array) ? $data_AlchemyRecipes : [] out = [] list.each{|rc| next unless rc.is_a?(Hash) && rc["output"].is_a?(Hash) && rc["requirements"].is_a?(Hash) name = rc["output"].keys.first.to_s next unless dish?(name) && dish_item(name) req = rc["requirements"] next if req.keys.any?{|tag| BAD_TAGS.include?(tag.to_s) } cond = rc["conditions"].is_a?(Hash) ? rc["conditions"] : {} min = cond["MinStatReq"].is_a?(Hash) ? cond["MinStatReq"].values.map{|v| v.to_i }.max.to_i : 0 req2 = {} req.each{|tag, n| req2[tag.to_s] = n.to_i unless tag.to_s == "Wood" } # the fire burns out << {:out => name, :req => req2, :ban => (rc["bannedItem"].is_a?(Hash) ? rc["bannedItem"].keys.map{|k| k.to_s } : []), :excl => Array(cond["excludeIngredients"]).map{|k| k.to_s } + BAD_TAGS, :min => min} } out end def self.unit_name(obj) r = rest return "ItemMeatSalad" if r && obj.is_a?(RPG::Item) && obj.id == r::MEAT_SALAD_ID obj.respond_to?(:item_name) ? obj.item_name.to_s : "" end # one entry per unit: {:obj, :box, :tags, :price, :sat} def self.pool(list) units = [] chests_of(list).each{|f, k| id = box_of(f) next if id.nil? fur.box_contents(id).each{|obj, n| tags = obj.respond_to?(:pot_data) ? obj.pot_data : nil next unless tags.is_a?(Hash) && !tags.empty? next if tags.keys.any?{|tag| BAD_TAGS.include?(tag.to_s) } name = unit_name(obj) type = obj.respond_to?(:type) ? obj.type.to_s : "" next unless type == "Food" || name == "ItemOil" t2 = {} tags.each{|tag, v| t2[tag.to_s] = v.to_i } price = obj.respond_to?(:price) ? obj.price.to_i : 0 sat = dish?(name) ? dish_sat(name) : 0 n.to_i.times{ units << {:obj => obj, :box => id, :tags => t2, :price => price, :sat => sat, :name => name} } } } units end # the units that cover +rc+, or nil def self.cover(rc, units) missing = rc[:req].dup taken = [] left = units.reject{|u| u[:tags].keys.any?{|tag| rc[:ban].include?(tag) || rc[:excl].include?(tag) } } loop do break if missing.values.all?{|v| v <= 0 } best = nil best_key = nil left.each{|u| c = 0 missing.each{|tag, v| c += [u[:tags][tag].to_i, v].min if v > 0 } next if c <= 0 key = [c, -u[:price]] if best.nil? || (key <=> best_key) > 0 best = u best_key = key end } return nil if best.nil? taken << best left.delete_at(left.index{|u| u.equal?(best) }) best[:tags].each{|tag, v| missing[tag] -= v if missing.key?(tag) } end taken end # [recipe, units, score] of the best dish, or nil def self.best_dish(units) skill = cfg["cook_skill"].to_i best = nil recipes.each{|rc| next if rc[:min] > skill used = cover(rc, units) next if used.nil? score = dish_sat(rc[:out]) + DISH_MOOD[rc[:out]].to_i / 10.0 - used.inject(0){|s, u| s + u[:sat] } next if score <= 0 best = [rc, used, score] if best.nil? || score > best[2] } best end def self.cooked_inside(list) n = 0 chests_of(list).each{|f, k| id = box_of(f) next if id.nil? fur.box_contents(id).each{|obj, c| n += c.to_i if dish?(unit_name(obj)) } } n end # cooks this morning; returns the dish names made def self.cook_day(r, list) made = [] if fire_of(list).nil? && cfg["need_fire"] r["why"] = "no_fire" return made end pantry = chests_of(list).first if pantry.nil? r["why"] = "no_chest" return made end cfg["dishes_per_day"].to_i.times{ break if cooked_inside(list) >= cfg["pantry_cap"].to_i pick = best_dish(pool(list)) if pick.nil? r["why"] = "bare" if made.empty? break end rc, used, score = pick used.each{|u| $game_boxes.remove_item(u[:obj], 1, u[:box], false) } id = box_of(pantry[0], true) $game_boxes.add_item(dish_item(rc[:out]), 1, id, :force) made << rc[:out] r["cooked"] = r["cooked"].to_i + 1 r.delete("why") say("cooked #{rc[:out]} from #{used.map{|u| u[:name] }.join(", ")} (score #{score})") } made end def self.item_label(name) it = dish_item(name) it ? $game_text[it.name].to_s : name.to_s end def self.report_cooking(r, made) if made.empty? case r["why"] when "no_fire" then notice("rt_cook", named("Notice/no_fire")) when "bare" notice("rt_cook", named("Notice/bare")) unless r["bare_told"] r["bare_told"] = true end return end r.delete("bare_told") pairs = [] made.each{|n| row = pairs.find{|p| p[0] == n } if row row[1] += 1 else pairs << [n, 1] end } r["last"] = pairs txt = pairs.map{|n, c| c > 1 ? "#{item_label(n)} x#{c}" : item_label(n) }.join(", ") notice("rt_cook", named("Notice/cooked").gsub("LIST", txt)) end #---------------------------------------------------------------------- # Away raids (140_AwayRaids.rb simulate): raiders reached her room #---------------------------------------------------------------------- def self.away_tile(rec) ref = post_ref(record) return nil if ref.nil? || ref[0] != :base || ref[1] != rec["id"].to_i list = inside_furniture(rec) f = fire_of(list) || list.find{|ff, k| BED_KINDS.include?(k[:key]) } f ? [f[0]["x"].to_i, f[0]["y"].to_i] : nil end # ["killed" / "hid", name] once she is reached, else nil def self.away_reached(rec, reached) tile = away_tile(rec) return nil if tile.nil? x, y = tile hit = reached[[x, y]] || DIRS.any?{|d, dx, dy| reached[[x + dx, y + dy]] } return nil unless hit name = record["name"] if rand < cfg["away_kill"].to_f + raids.diff("maid_kill_add").to_f # R10 notice("rt_killed", named("Notice/killed")) end_hire(:killed) ["killed", name] else ["hid", name] end end #---------------------------------------------------------------------- # Boss Mama's line (and the guild's while she is away) #---------------------------------------------------------------------- def self.mama_away? s = $story_stats return false if s.nil? return true if s["UniqueCharUniqueTavernWaifu"].to_i == -1 q = s["RecQuestCocona"].to_i return true if q.between?(14, 20) || q == 25 q == 4 && $game_date && $game_date.dateAmt < s["RecQuestCoconaAmt"].to_i rescue false end def self.guild_offer? enabled? && mama_away? end def self.menu_label r = record r ? text("Menu/yours").gsub("NAME", r["name"].to_s) : text("Menu/hire").gsub("PRICE", fee_text) end def self.menu_entries return [] unless enabled? [[menu_label, lambda{|interp| interp.lonacraft_maid_offer }]] end def self.new_record(pt) r = {"name" => pick_name, "hired" => now, "t" => now, "unpaid" => 0, "paid" => 0, "cooked" => 0, "look" => {"head_equip" => HAIRS.sample, "head" => FACES.sample}} set_post(r, pt) r end # a new hire for post +pt+ ([:base, rec] / [:home, id]); :ok, :no_coins, :no_bed def self.hire(pt, interp) return :no_bed unless bed_inside?(pt) c = coin fee = self.fee return :no_coins if c.nil? || $game_party.item_number(c) < fee interp.optain_lose_item(c, fee) if fee > 0 root["maid"] = new_record(pt) say("#{record["name"]} hired for #{post_ref(record).inspect}") :ok end def self.move_to(pt) r = record return :no_bed unless bed_inside?(pt) return :same if same_post?(post, pt) set_post(r, pt) r.delete("why") live_members($game_map).each{|ev| despawn(ev) } :ok end def self.dismiss live_members($game_map).each{|ev| despawn(ev) } end_hire(:dismissed) end #---------------------------------------------------------------------- # The maid 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[:LonaCraftMaid] end def self.live_members(map) return [] if map.nil? map.events.values.select{|ev| member?(ev) } 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 def self.label(name) RPG::EventCommand.new(118, 0, [name]) end def self.build_event(x, y, face) sheet, index, pattern = SPRITE ev = RPG::Event.new(x, y) ev.name = "LonaCraftMaid" 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.direction_fix = false page.through = false page.priority_type = 1 page.trigger = 0 list = [label("init"), label("common")] ["@nappable = false", "set_npc(#{NPC_NAME.inspect})", "@npc.stat.set_stat(\"arousal\", 0)", "@npc.stat.set_stat(\"mood\", 50)", "@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_maid_talk if respond_to?(:lonacraft_maid_talk)") list << RPG::EventCommand.new(0, 0, []) page.list = list ev.pages = [page] ev end # her saved hair and face over the random parts (Charset_System.rb:121-130) def self.apply_look(ev) r = record look = r ? r["look"] : nil return unless look.is_a?(Hash) conf = ev.instance_variable_get(:@chs_configuration) return unless conf.is_a?(Hash) changed = false ["head_equip", "head"].each{|part| want = look[part] next unless want.is_a?(String) && conf.key?(part) && conf[part] != want conf[part] = want changed = true } ev.instance_variable_set(:@chs_need_update, true) if changed rescue => e say("look error #{e.class} #{e.message}") end # her room on the live map: the inside tiles joined to the fire (else a # bed, else the largest room); [room hash, anchor tile] or nil def self.live_room(map, rec) rm = map.instance_variable_get(:@region_map) ins = bases.inside_tiles(map, rec, rm.is_a?(Array) ? rm : []) return nil if ins.empty? list = bases.furniture_on(rec).map{|f| [f, fur.kind_for(f["item_name"])] }.select{|f, k| k && ins[[f["x"].to_i, f["y"].to_i]] } pick = fire_of(list) || list.find{|f, k| BED_KINDS.include?(k[:key]) } anchor = pick ? [pick[0]["x"].to_i, pick[0]["y"].to_i] : ins.keys.first room = {} raids.bfs(map, [anchor], ins).each_key{|c| room[c] = true } room[anchor] = true [room, anchor] end # the way out of house +id+ on the live map: its -point-ExitPoint and # -point-StartPoint (Game_Map#storypoint_map), else the entry tile def self.house_exits(map, id) out = [] sm = map.storypoint_map if sm.is_a?(Hash) ["ExitPoint", "StartPoint"].each{|n| sp = sm[n] out << [sp[0].to_i, sp[1].to_i] if sp.is_a?(Array) } end loc = homes.location(id) out << [loc[:interior][2].to_i, loc[:interior][3].to_i] if out.empty? && loc && loc[:interior].is_a?(Array) out.uniq end # her room in house +id+: the floor (Homes.floor_tiles) minus the tiles # on or next to the way out; the anchor is the fire, else a bed, else # the top-left floor tile. [room, anchor, way out, floor] or nil def self.house_room(map, id) floor = homes.floor_tiles(map, id) return nil if floor.nil? || floor.empty? exits = house_exits(map, id) room = {} floor.each_key{|c| room[c] = true unless exits.any?{|e| (e[0] - c[0]).abs + (e[1] - c[1]).abs <= 1 } } return nil if room.empty? list = house_furniture(id) pick = fire_of(list) || list.find{|f, k| BED_KINDS.include?(k[:key]) } anchor = pick ? [pick[0]["x"].to_i, pick[0]["y"].to_i] : room.keys.min_by{|c| [c[1], c[0]] } [room, anchor, exits, floor] end # her room on the live map of post +pt+: [room, anchor, door tiles, the # tiles the hiding distance is measured over], or nil def self.room_for(map, pt) return house_room(map, pt[1]) if pt[0] == :home rec = pt[1] got = live_room(map, rec) return nil if got.nil? room, anchor = got doors = [] bases.pieces_of(rec).each{|k, v| next unless bases.door?(v) x, y = k.split(",").map{|n| n.to_i } DIRS.each{|d, dx, dy| doors << [x + dx, y + dy] if room[[x + dx, y + dy]] } } [room, anchor, doors.uniq, room] end def self.after_setup(map) @dist = {} @rooms = {} @flee = {} return if map.nil? || map.isOverMap r = record return if r.nil? || !enabled? pt = post return unless here?(map, pt) return unless live_members(map).empty? if $data_npcs.nil? || $data_npcs[NPC_NAME].nil? say("NPC data missing (#{NPC_FILE}), no maid") return end got = room_for(map, pt) return say("no room inside the walls at #{post_ref(r).inspect}") if got.nil? room, anchor, doors, area = got ax, ay = anchor free = room.keys.select{|c| raids.free_tile?(map, c[0], c[1]) } return say("no free tile in her room") if free.empty? spot = free.min_by{|c| [(c[0] - ax).abs + (c[1] - ay).abs, c[1], c[0]] } src = doors.empty? ? [spot] : doors from_doors = raids.bfs(map, src, area) far = free.max_by{|c| [from_doors[c].to_i, -((c[0] - ax).abs + (c[1] - ay).abs)] } || spot face = ax == spot[0] ? (ay < spot[1] ? 8 : 2) : (ax < spot[0] ? 4 : 6) ev = map.lonacraft_spawn_event(build_event(spot[0], spot[1], face), {:LonaCraftMaid => true, :LonaCraftMaidPost => spot, :LonaCraftMaidFar => far}) @rooms[map.object_id] = room apply_look(ev) r["post"] = spot say("#{r["name"]} at #{post_ref(r).inspect}, post #{spot.inspect}, hiding tile #{far.inspect}, room #{room.size} tiles") rescue => e say("spawn error #{e.class} #{e.message} #{e.backtrace ? e.backtrace[0] : ""}") end def self.room_here @rooms[$game_map.object_id] || {} end def self.dist_to(tile) key = [$game_map.object_id, tile[0], tile[1]] return @dist[key] if @dist.key?(key) room = room_here @dist[key] = room.empty? ? nil : raids.bfs($game_map, [tile], room) end def self.step_to(ev, tile) dist = dist_to(tile) 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 } end ev.move_toward_xy(tile[0], tile[1]) if ev.respond_to?(:move_toward_xy) && rand(4) == 0 end def self.hostile_near?(ev) r2 = cfg["flee_radius"].to_i ** 2 $game_map.events.values.any?{|o| next false if o.nil? || o.equal?(ev) || (o.respond_to?(:deleted?) && o.deleted?) next false unless o.respond_to?(:npc?) && o.npc? npc = o.npc next false if npc.nil? || npc.master == $game_player next false if npc.respond_to?(:is_object) && npc.is_object next false if npc.action_state == :death dx = o.x - ev.x dy = o.y - ev.y next false if dx * dx + dy * dy > r2 !npc.friendly?($game_player) } rescue false end # Game_Event#update_self_movement alias: true = handled here def self.drive(ev) npc = ev.npc return false if npc.nil? return true unless npc.action_state.nil? || npc.action_state == :none return true if ev.moving? sd = ev.summon_data post = sd[:LonaCraftMaidPost] return true unless post.is_a?(Array) if @flee[ev.id] far = sd[:LonaCraftMaidFar] || post step_to(ev, far) unless ev.x == far[0] && ev.y == far[1] return true end off = (ev.x - post[0]).abs + (ev.y - post[1]).abs if off > cfg["wander"].to_i || !room_here[[ev.x, ev.y]] step_to(ev, post) elsif rand(150) == 0 d, dx, dy = DIRS.sample k = [ev.x + dx, ev.y + dy] ev.move_straight(d) if room_here[k] && (k[0] - post[0]).abs + (k[1] - post[1]).abs <= cfg["wander"].to_i && ev.passable?(ev.x, ev.y, d) end true rescue => e say("drive error #{e.class} #{e.message}") false end # Scene_Map#update: flee checks, her look, leaving 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 evs = live_members(map) if evs.empty? @leave = false if r.nil? return end pt = r ? post : nil unless here?(map, pt) evs.each{|ev| despawn(ev) } @leave = false return end if @rooms[map.object_id].nil? # after a load: her room again got = room_for(map, pt) @rooms[map.object_id] = got ? got[0] : {} end danger = pt[0] == :base && raids.active? # no live raids in a house evs.each{|ev| apply_look(ev) @flee[ev.id] = danger || hostile_near?(ev) } rescue => e say("update error #{e.class} #{e.message}") end # Game_NonPlayerCharacter#process_death alias: she is gone for good def self.on_death(npc) ev = npc.respond_to?(:event) ? npc.event : nil return unless member?(ev) && record notice("rt_killed", named("Notice/killed")) end_hire(:killed) rescue => e say("death error #{e.class} #{e.message}") end def self.load_npc path = LonaCraft.resource(NPC_FILE) return say("missing #{path}") unless File.exist?(path) 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 # for the house Lona stands in, else the base here, else the newest base def self.debug_hire h = homes id = h ? h.home_at_map?($game_map) : nil pt = house?(id) ? [:home, id] : nil if pt.nil? rec = bases.record_for_map($game_map) || bases.pick_list.first return bases.debug_say("LonaCraft debug no base") if rec.nil? pt = [:base, rec] end root["maid"] = new_record(pt) bases.debug_say("LonaCraft debug maid #{record["name"]} for #{post_name(pt)}") end end end #============================================================================== # The AI: runs from danger, never fights (Npc_RunAway, Editables/4003) #============================================================================== if defined?(Npc_RunAway) && !defined?(Npc_LonaCraftMaid) class Npc_LonaCraftMaid < Npc_RunAway def get_move_command nil # 170_Maid.rb drives her steps end def set_killer_skill(dist) nil end def set_assaulter_skill(dist) nil end end end if defined?(LonaCraft::Homes) LonaCraft::Homes.add_menu_provider(LonaCraft::Maid::SELLER){ LonaCraft::Maid.menu_entries } end module DataManager unless respond_to?(:load_mod_database_lonacraft_maid) self.singleton_class.send(:alias_method, :load_mod_database_lonacraft_maid, :load_mod_database) def self.load_mod_database load_mod_database_lonacraft_maid LonaCraft::Maid.load_npc end end end class Game_Date [:shift, :addDays, :oneDayForward].each{|meth| old = "#{meth}_lonacraft_maid".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::Maid.on_date_moved if $game_date.equal?(self) rescue => e p "LonaCraft Maid date hook error #{e.class} #{e.message}" end result } } end class Game_Map unless method_defined?(:setup_lonacraft_maid) alias_method :setup_lonacraft_maid, :setup def setup(map_id) setup_lonacraft_maid(map_id) begin LonaCraft::Maid.after_setup(self) rescue => e p "LonaCraft Maid setup error #{e.class} #{e.message}" end end end end class Game_Event unless method_defined?(:lonacraft_maid_self_movement) alias_method :lonacraft_maid_self_movement, :update_self_movement def update_self_movement if @summon_data.is_a?(Hash) && @summon_data[:LonaCraftMaid] return if LonaCraft::Maid.drive(self) end lonacraft_maid_self_movement end end end class Scene_Map unless method_defined?(:update_lonacraft_maid) alias_method :update_lonacraft_maid, :update def update update_lonacraft_maid LonaCraft::Maid.update end end end class Game_NonPlayerCharacter unless method_defined?(:process_death_lonacraft_maid) alias_method :process_death_lonacraft_maid, :process_death def process_death(*args) LonaCraft::Maid.on_death(self) if @action_state != :death && @event.respond_to?(:summon_data) && @event.summon_data.is_a?(Hash) && @event.summon_data[:LonaCraftMaid] process_death_lonacraft_maid(*args) end end end #============================================================================== # Game_Interpreter: the hire line, her menu #============================================================================== class Game_Interpreter def lonacraft_maid_say(id, text) call_msg(LonaCraft::RuntimeText.key(LonaCraft::Maid::FILE, id, text)) end def lonacraft_maid_ask(id, text, options) m = LonaCraft::Maid call_msg(LonaCraft::RuntimeText.key(m::FILE, id, "#{text}\\optB[#{options.map{|o| m.clean(o) }.join(",")}]")) pick = $game_temp.choice $game_temp.choice = -1 pick.nil? ? -1 : pick end # the bases, then the owned houses (Maid.post_choices), Cancel last; the # post picked ([:base, rec] / [:home, id]) or nil def lonacraft_maid_choose(id, prompt) m = LonaCraft::Maid posts = m.post_choices return nil if posts.empty? pick = lonacraft_maid_ask(id, prompt, posts.map{|pt| m.post_label(pt) } + [LonaCraft::Bases.text("Pick/cancel")]) pick >= 0 && pick < posts.size ? posts[pick] : nil end # Boss Mama's line (and the guild's while she is away) def lonacraft_maid_offer m = LonaCraft::Maid r = m.record if r lonacraft_maid_say("rt_status", m.named("Hire/status").gsub("BASE", m.post_name(m.post)).gsub("NUM", r["paid"].to_i.to_s).gsub("DISHES", r["cooked"].to_i.to_s)) return end if m.post_choices.empty? lonacraft_maid_say("rt_no_base", m.text("Hire/no_base")) return end lonacraft_maid_say("rt_offer", m.text("Hire/offer").gsub("PRICE", m.fee_text)) pt = lonacraft_maid_choose("rt_pick_post", m.text("Hire/ask_base")) return if pt.nil? case m.hire(pt, self) when :no_bed lonacraft_maid_say("rt_no_bed", m.text("Hire/no_bed")) when :no_coins lonacraft_maid_say("rt_no_coins", m.text("Hire/no_coins").gsub("PRICE", m.fee_text)) when :ok lonacraft_maid_say("rt_hired", m.named("Hire/done").gsub("BASE", m.post_name(pt))) end end # her action key def lonacraft_maid_talk m = LonaCraft::Maid r = m.record return if r.nil? pick = lonacraft_maid_ask("rt_menu", m.named("Talk/menu"), [m.text("Talk/opt_status"), m.text("Talk/opt_move"), m.text("Talk/opt_dismiss"), m.text("Opt/cancel")]) case pick when 0 pt = m.post pantry = pt ? m.cooked_inside(m.post_furniture(pt)) : 0 where = pt ? " " + m.text("Talk/where").gsub("BASE", m.post_name(pt)) : "" unpaid = r["unpaid"].to_i > 0 ? " " + m.text("Talk/unpaid").gsub("NUM", r["unpaid"].to_i.to_s) : "" lonacraft_maid_say("rt_status", m.named("Talk/status").gsub("NUM", r["paid"].to_i.to_s).gsub("DISHES", r["cooked"].to_i.to_s).gsub("PANTRY", pantry.to_s) + where + unpaid) when 1 pt = lonacraft_maid_choose("rt_pick_post", m.text("Talk/ask_base")) if pt case m.move_to(pt) when :no_bed then lonacraft_maid_say("rt_no_bed", m.named("Talk/no_bed")) # 2026-10-08: her own voice when :ok then lonacraft_maid_say("rt_moved", m.named("Talk/moved").gsub("BASE", m.post_name(pt))) end end when 2 if lonacraft_maid_ask("rt_dismiss", m.named("Talk/dismiss_ask"), [m.text("Talk/opt_no"), m.text("Talk/opt_yes")]) == 1 lonacraft_maid_say("rt_bye", m.named("Talk/dismissed")) m.dismiss end end cam_center(0) if respond_to?(:cam_center) portrait_hide if respond_to?(:portrait_hide) $game_temp.choice = -1 end end