#============================================================================== # LonaCraft - 110_Bases.rb (board B1, design: docs/RESEARCH_BASE_BUILDING.md section 9) # What it does: # * A base is a world-map tile with buildings on it. The field map Lona gets # when she enters that tile is PINNED to it while at least one building # stands there: every later entry of that tile loads the same map. When the # last building goes, the record goes and the tile draws a random map again, # as the game does. The buildings (B2/B3, second part of this file): # Palisade Wall and Plank Floor as map tiles, Wooden Door as the game's # own door event; they call Bases.on_piece_placed / on_piece_removed. # Build mode and furniture in bases (board R7, third part of this file). # Wall and door HP, breaking and repair (board R4, last part; the raids # themselves are Scripts/120_Raids.rb). # A base ends when it has no piece AND no furniture (base_empty?). # * Pin: alias of change_map_enter_region (34_Functions_ChangeMap.rb:257-269), # the only reader of $data_region_maps; every entry runs through it (region # menu, encounters, the out-of-stamina nap on the world map). For the call # $data_region_maps[region] holds one map: the base's map, or one random # pick made here (the game's own .sample), so the entry knows its map. # * Pinned map: $data_mapinfos["LonaCraftBase_"] with the field map's file # and name and its own map number (MAP_ID_BASE + id), as Homes registers its # houses (100_Homes.rb:546-576). Game_Map#setup only reads .filename and .id # (31_Game_Map.rb:169-172). Numbers are turned back into keys on setup, and # the keys are registered again after a load (extract_save_contents). # The field map's BIOS still rolls resources and wildlife on every entry # (ReRollHalfEvents, 34_Functions_ChangeMap.rb:138), pinned or not. # * When the first building is placed on the map Lona entered, the live map # is re-keyed to the base's key and number, so a nap there (handleNap # calls setup(map_id_rec)) and pieces keyed by map number stay with it. # * Allowed tiles (allowed_tile?): a world map (isOverMap), a region id with # field maps, no map event on the tile (towns, caves, quests are points), # not inside Noer's walls (WALLED), not a SETTLEMENT_REGIONS region. A base # is only created after a plain entry: OverMapEvent_name was 0 (world-map # events, e.g. HCGframes/encounter/RefugeeCamp.rb:1, set it first). # * Marker: one event per base on its world map, "!World Map 02" (MARKER_SPRITE), # injected in setup_event_hack like the home doors (100_Homes.rb:1262-1304). # Its action key opens the tile's region menu, which an event on Lona's # tile would otherwise take (35_Game_Player.rb:604-620). # * System page: "Destroy all bases (N)" under Keybinding, with a yes/no # prompt like the hardcore one (194_menu_08_0_System.rb:408-440, 487-506). # Removes every record, no refund; furniture on base maps goes too. # * Debug (DEBUG = true): Numpad / on a field map adds a "debug" piece on # Lona's tile (the first one creates the base), or removes it when she # stands on one (the last one reverts the tile). Nothing is drawn. # * Save data (plain types, game system data, no save hook): # $game_system.lonacraft_data["bases"] = {"next_id", "list" => [record], # "maps" => {key => [map number, field map]}, "entry" => last region entry}. # record = {"id", "om" => [world map number, x, y], "region", "field", # "key", "map_no", "pieces" => {"x,y" => kind}, "made" => dateAmt, # "name" => the base's name, "visited" => entry counter, # "danger" => -1 Lower / 0 Normal / 1 Higher (R10; missing = Normal)}. # * Names (owner, 2026-10-06): every base is named on founding from its # land (NAME_KINDS: "Plains camp", "Forest camp", "Abandoned house", "Deep # Sewer"...), with the world-map tile added ("Plains camp 31-92") when # another base has that name. "Rename base" on the tile menu of the base's # world-map tile (the marker opens it) and on the Deep Sewer's ladders # opens a centred physical-keyboard editor, shaped like the online nickname # window, for at most NAME_MAX (48) letters; commas, brackets, colons, # backslashes and < > are dropped (the # \optB lists split on commas). API for other parts: name_of(rec), # choose_base(prompt_key) (a record or nil: newest first, at most 6 plus # Cancel; with more than 6, the 6 most recently visited). # * Danger (board R10, owner 2026-10-07): "Danger (Normal)" beside "Rename # base" on the same tile menu and on the Deep Sewer ladders. Picking it # steps the base's rec["danger"] Lower -> Normal -> Higher -> Lower, with a # popup; refused (buzzer, popup) while a live raid runs on that base. The # step's numbers are Config/Bases.json "difficulty" "base_danger" # (120_Raids.rb step). Owned houses and inn rooms have no Danger line # (never raided). # * API (for B2/B3): enabled?, record_for_tile(om_map, x, y), # record_for_map(map), base_at_map?(map), can_build_here?(map) (nil or a # reason symbol), on_piece_placed(map, x, y, kind), on_piece_removed(map, # x, y), allowed_tile?(x, y, om_map = nil), tile_reason(x, y, om_map = nil), # destroy_all!, count. # * Named maps (board R9, owner 2026-10-06): a map of the mod's own keyed by # its map name with a fixed map number (NAMED_MAPS; the Deep Sewer, # Scripts/130_Sewer.rb, registers it). One record for the whole map: # "om" nil, no marker, "kind" and "region" from NAMED_MAPS, made by the # first piece or furniture, gone with the last. The Deep Sewer is the only # map where building is allowed while NPCs are on it: refused while # $game_map.threat is on or a hostile NPC is within BUILD_ENEMY_RADIUS # tiles, and build mode closes by itself when that happens (sewer_watch). # A wall or door that would split the walkway graph is refused # (cuts_walkway?), the black ceiling never takes a piece, furniture only # goes on the platforms (not on the walkway regions), every # -point-StartPoint_ is kept clear like the StartPoint. # * Building and hostiles (owner 2026-10-08, replaces "no building while # any NPC is on the map"): "We should only block it for NPCs that would be # hostile to the player on site." hostiles_present? (npcs_present? is kept # as a wrapper) blocks build mode and single placement only for an NPC # that is hostile to Lona right now: alive, not an object / missile / # trap, not on Lona's side (lona_side?: her followers, master == # $game_player, the mercenaries, the maid), and either in combat with # Lona's side now (its target is Lona or one of hers, even an animal) or # not an animal (ANIMAL_RACES "Animal", "Dog", "Horse", "Others", or a # "Wild*" NPC such as WildGiantMice) and hostile by the game's own test # (would_attack_lona?: friendly?($game_player) false and check_ai_state # killer / fucker / assaulter, the test 35_Game_Player.rb:355 uses before # Lona may talk to an NPC). Companions, traders, hobos, quest NPCs, guards # that are not after her and wild animals that leave her alone never # block. Build mode closes by itself when one appears (build_watch, every # ENEMY_CHECK_FRAMES frames, popup Place/hostiles). The Deep Sewer keeps # its own rule (a hostile within BUILD_ENEMY_RADIUS, sewer_watch). #============================================================================== module LonaCraft module Bases ENABLED = true DEBUG = LonaCraft.debug? # Numpad / (see above); Config/LonaCraft.json "debug" (05_Config.rb), read at load DEBUG_KEY = :DIVIDE # Numpad / : free (95_Debug.rb uses 0 1 3 5 7 9 + - *, the game 2 4 6 8) TEXT = "LonaCraft:Bases:" KEY_PREFIX = "LonaCraftBase_" MAP_ID_BASE = 9200 # runtime map number of base = MAP_ID_BASE + id (Homes use 9001+) MARKER_PREFIX = "LonaCraftBaseMarker_" MARKER_SPRITE = ["!World Map 02", 4, 4, 0] # sheet, index, direction, pattern: a small fenced camp # Settlement regions of the world map (Text/ENG/OvermapEvents.txt:160-256): # 10 Slums, 12 Rudesind Slope, 18 Infected City Ruins, 20 Refugee Camp, # 21 Town of Noer, 22 Streets of Noer, 29/30 Fortress Ruins, # 31 Streets of Sybaris, 32 Alleys of Sybaris. SETTLEMENT_REGIONS = [10, 12, 18, 20, 21, 22, 29, 30, 31, 32] # Inside the walls of Noer on OvermapMain, [x1, y1, x2, y2] inclusive, read # off the wall art: the west quarter, the main town, the castle. WALLED = { "OvermapMain" => [[22, 94, 28, 103], [28, 95, 40, 103], [33, 92, 37, 96]] } # Named maps (R9): $data_mapinfos key => {"kind", "region"}. "region" picks # the raid scenario (120_Raids.rb: 90 = "sewer"). NAMED_MAPS = { "LonaCraftDeepSewer" => {"kind" => "sewer", "region" => 90} } # Deep Sewer build rule (R9): no building while a hostile NPC (alive, not # Lona's follower, not an object, the game's friendly? test false) is # within this many tiles of Lona (straight line), checked every # ENEMY_CHECK_FRAMES frames while build mode is open. BUILD_ENEMY_RADIUS = 8 ENEMY_CHECK_FRAMES = 15 # 2026-10-08: wild animals never block building unless in combat with # Lona's side (NPCdata races; "Wild*" names cover WildGiantMice, race # Abomination, and WildCrow) ANIMAL_RACES = ["Animal", "Dog", "Horse", "Others"] # no creature at all (projectiles, traps, dummies) NOT_CREATURE_RACES = ["Missile", "Bomb", "Mine", "SkillDummy", "AreaDot", "Overmap", "Johnson"] # Walkway graph of the sewer: the walkable tiles of these regions (1 the # tunnel mouths, 2 the walkways, bridges and the flooded basin, 3 the # homeless camp, 4 the goblin den, 5 the quest spawn tiles, # Maps/LonaCraftDeepSewer.rvdata2). The camp and the den count so that # no wall seals them or the walkway spur behind the den. WALKWAY_REGIONS = [1, 2, 3, 4, 5] @overmaps = {} # world map number => cached tile info of a world map not loaded now def self.enabled? ENABLED ? true : false end def self.text(key) $game_text["#{TEXT}#{key}"].to_s end #---------------------------------------------------------------------- # Save data ($game_system.lonacraft_data, 60_Skill.rb) #---------------------------------------------------------------------- def self.root return nil if $game_system.nil? || !$game_system.respond_to?(:lonacraft_data) d = $game_system.lonacraft_data b = d["bases"] unless b.is_a?(Hash) b = {} d["bases"] = b end b["next_id"] = 1 unless b["next_id"].is_a?(Integer) && b["next_id"] >= 1 b["list"] = [] unless b["list"].is_a?(Array) b["maps"] = {} unless b["maps"].is_a?(Hash) b end def self.list r = root r.nil? ? [] : r["list"] end def self.count list.size end def self.entry r = root return nil if r.nil? || !r["entry"].is_a?(Hash) r["entry"] end def self.record_by_id(id) return nil if id.nil? list.find{|rec| rec.is_a?(Hash) && rec["id"].to_i == id.to_i } end def self.record_for_tile(om_map, x, y) want = [om_map.to_i, x.to_i, y.to_i] list.find{|rec| rec.is_a?(Hash) && rec["om"].is_a?(Array) && rec["om"].map{|v| v.to_i } == want } end def self.records_on_overmap(om_map) list.select{|rec| rec.is_a?(Hash) && rec["om"].is_a?(Array) && rec["om"][0].to_i == om_map.to_i } end # The base of +map+ (the live Game_Map): its pinned key, or the map Lona # entered when that entry made a base. def self.record_for_map(map = $game_map) return nil if map.nil? || !enabled? key = map.map_id_rec rec = list.find{|r| r.is_a?(Hash) && r["key"] == key } return rec if rec e = entry return nil if e.nil? || e["base"].nil? || e["at"] != key record_by_id(e["base"]) end def self.base_at_map?(map = $game_map) record_for_map(map) ? true : false end #---------------------------------------------------------------------- # Named maps (R9) #---------------------------------------------------------------------- # the NAMED_MAPS row of +map+ (the live Game_Map), or nil def self.named_spec(map = $game_map) return nil if map.nil? key = map.map_id_rec return nil unless key.is_a?(String) NAMED_MAPS[key] end def self.named_map?(map = $game_map) !named_spec(map).nil? end def self.sewer_map?(map = $game_map) spec = named_spec(map) !spec.nil? && spec["kind"] == "sewer" end #---------------------------------------------------------------------- # Allowed tiles #---------------------------------------------------------------------- # Tile info of world map +om_map+: the live map when Lona is on it, else # its file (cached). nil when it is not a world map. def self.overmap_info(om_map) om_map = om_map.to_i if $game_map && $game_map.isOverMap && $game_map.map_id == om_map m = $game_map.instance_variable_get(:@map) return {:name => $game_map.name.to_s, :data => m.data, :events => m.events, :w => m.width, :h => m.height} end return @overmaps[om_map] if @overmaps.key?(om_map) info = nil mi = $data_mapinfos.nil? ? nil : $data_mapinfos[om_map] if mi m = load_data(mi.filename) if Note.get_data(m.note.to_s)["isOverMap"] == "true" info = {:name => mi.name.to_s, :data => m.data, :events => m.events, :w => m.width, :h => m.height} end end @overmaps[om_map] = info rescue => e p "LonaCraft Bases overmap read error #{e.class} #{e.message}" @overmaps[om_map] = nil end def self.walled?(name, x, y) (WALLED[name.to_s] || []).any?{|a, b, c, d| x >= a && x <= c && y >= b && y <= d } end # nil when a base may stand on world-map tile (x, y), else why not: # :disabled, :not_overmap, :no_region, :no_field, :settlement, :walled, :event def self.tile_reason(x, y, om_map = nil) return :disabled unless enabled? if om_map.nil? return :not_overmap unless $game_map && $game_map.isOverMap om_map = $game_map.map_id end info = overmap_info(om_map) return :not_overmap if info.nil? x = x.to_i y = y.to_i return :no_region if x < 0 || y < 0 || x >= info[:w] || y >= info[:h] region = info[:data][x, y, 3].to_i >> 8 return :no_region if region <= 0 maps = $data_region_maps.nil? ? nil : $data_region_maps[region] return :no_field unless maps.is_a?(Array) && !maps.empty? return :settlement if SETTLEMENT_REGIONS.include?(region) return :walled if walled?(info[:name], x, y) return :event if info[:events].values.any?{|ev| ev && ev.x == x && ev.y == y && !ev.name.to_s.start_with?(MARKER_PREFIX) } nil end def self.allowed_tile?(x, y, om_map = nil) tile_reason(x, y, om_map).nil? end # nil when a piece may be placed on +map+ (a base is there, or the map # is a plain entry of an allowed tile), else the reason symbol. def self.can_build_here?(map = $game_map) return :disabled unless enabled? return :map if map.nil? || map.isOverMap return nil if record_for_map(map) return nil if named_map?(map) # R9: the whole named map is one base e = entry return :not_field if e.nil? || e["at"] != map.map_id_rec return :event unless e["event"] == 0 || e["event"].nil? return :tile unless e["allowed"] nil end #---------------------------------------------------------------------- # Entering a tile (change_map_enter_region alias, below) #---------------------------------------------------------------------- # The map to load for this entry, or nil to leave the game alone. # Writes the entry note. def self.pick_for_entry(region) return nil unless enabled? return nil unless $game_map && $game_map.isOverMap return nil if $data_region_maps.nil? maps = $data_region_maps[region] return nil unless maps.is_a?(Array) && !maps.empty? r = root return nil if r.nil? om = $game_map.map_id x = $game_player.x y = $game_player.y rec = record_for_tile(om, x, y) pick = nil pick = rec["key"] if rec && ensure_registered(rec) pick = maps.sample if pick.nil? event = $story_stats["OverMapEvent_name"] event = event.to_i unless event.is_a?(String) r["entry"] = {"om" => [om, x, y], "region" => region.to_i, "event" => event, "to" => pick, "at" => pick, "base" => (pick == (rec && rec["key"]) ? rec["id"] : nil), "allowed" => allowed_tile?(x, y)} p "LonaCraft Bases: entry (#{x},#{y}) region #{region} -> #{pick.inspect}#{rec ? " (base #{rec["id"]})" : ""}" pick end #---------------------------------------------------------------------- # Runtime map numbers #---------------------------------------------------------------------- # A map number nothing else uses, from +want+ (as Homes.free_map_id). def self.free_map_id(want, key) used = {} $data_mapinfos.each{|k, v| next if v.nil? || k == key used[v.id] = true if v.respond_to?(:id) } want += 1 while used[want] want end # $data_mapinfos[key] for the field map +field+ under number +want+. # Returns the number used, or nil when the field map is unknown. def self.register(key, want, field) return nil if $data_mapinfos.nil? || key.nil? src = $data_mapinfos[field] if src.nil? p "LonaCraft Bases: field map #{field.inspect} of #{key} is unknown, not registered" return nil end want = want.to_i r = root info = $data_mapinfos[key] if info.is_a?(RPG::MapInfo) && info.id == want && info.filename == src.filename r["maps"][key] = [want, field] if r return want end no = free_map_id(want, key) info = RPG::MapInfo.new info.name = src.name info.filename = src.filename info.id = no $data_mapinfos[key] = info r["maps"][key] = [no, field] if r move_map_no(key, want, no) if no != want no rescue => e p "LonaCraft Bases register error #{e.class} #{e.message}" nil end # Another mod took the number: the record and its furniture follow. def self.move_map_no(key, from, to) p "LonaCraft Bases: #{key} moves from map #{from} to #{to} (number taken)" list.each{|rec| rec["map_no"] = to if rec["key"] == key } furniture_records.each{|f| f["map_id"] = to if f.is_a?(Hash) && f["map_id"].to_i == from } end def self.ensure_registered(rec) if NAMED_MAPS.key?(rec["key"].to_s) # R9: registered by its own script (130_Sewer.rb) info = $data_mapinfos.nil? ? nil : $data_mapinfos[rec["key"]] return false unless info.is_a?(RPG::MapInfo) move_map_no(rec["key"], rec["map_no"].to_i, info.id) if rec["map_no"].to_i != info.id rec["map_no"] = info.id return true end no = register(rec["key"], rec["map_no"] || (MAP_ID_BASE + rec["id"].to_i), rec["field"]) return false if no.nil? rec["map_no"] = no true end # After a load: every key a save may stand on. def self.register_all r = root return if r.nil? || !enabled? r["maps"].keys.each{|key| v = r["maps"][key] register(key, v[0], v[1]) if v.is_a?(Array) } list.each{|rec| ensure_registered(rec) } end # Game_Map#setup argument: a base map number becomes its key; a base # key is registered when missing. def self.setup_key(map_id) return map_id unless enabled? r = root return map_id if r.nil? || $data_mapinfos.nil? if map_id.is_a?(Integer) return map_id if $data_mapinfos[map_id] NAMED_MAPS.each_key{|key| # R9: a named map's number becomes its key info = $data_mapinfos[key] return key if info.is_a?(RPG::MapInfo) && info.id == map_id } r["maps"].each{|key, v| next unless v.is_a?(Array) && v[0].to_i == map_id return key if register(key, v[0], v[1]) } elsif map_id.is_a?(String) && map_id.start_with?(KEY_PREFIX) && $data_mapinfos[map_id].nil? v = r["maps"][map_id] register(map_id, v[0], v[1]) if v.is_a?(Array) end map_id end # Registry entries no base uses and Lona does not stand on. def self.prune_maps r = root return if r.nil? used = {} list.each{|rec| used[rec["key"]] = true } here = $game_map ? $game_map.map_id_rec : nil r["maps"].keys.each{|key| r["maps"].delete(key) unless used[key] || key == here } end # Game_Map#setup alias (after): the entry note ends on a world map. def self.after_setup(map) return unless enabled? unless map.isOverMap rec = record_for_map(map) return if rec.nil? mark_visited(rec) rebuild_tiles(map, true) # last point before the map is shown sync_doors(map, rec) # B3: doors back, closed (owner: closed after a nap) return end r = root return if r.nil? r.delete("entry") prune_maps refresh_marker_balloons(map) # M1: raided bases show "!" on the world map end #---------------------------------------------------------------------- # Pieces (B2/B3 call these) #---------------------------------------------------------------------- def self.piece_key(x, y) "#{x.to_i},#{y.to_i}" end # Records a piece at (x, y) on +map+; the first one creates the base. # Returns the record, or nil when no base may be made here. def self.on_piece_placed(map, x, y, kind = "piece") rec = record_for_map(map) if rec.nil? return nil unless can_build_here?(map).nil? rec = create_record(map) return nil if rec.nil? end rec["pieces"] = {} unless rec["pieces"].is_a?(Hash) rec["pieces"][piece_key(x, y)] = kind.to_s rec end # Forgets the piece at (x, y). Returns :reverted when it was the last # one (the record is gone), :removed, or nil (no base / no piece). def self.on_piece_removed(map, x, y) rec = record_for_map(map) return nil if rec.nil? || !rec["pieces"].is_a?(Hash) return nil if rec["pieces"].delete(piece_key(x, y)).nil? return :removed unless base_empty?(rec) # furniture counts too (R7 B5) remove_record(rec) :reverted end def self.create_record(map) spec = named_spec(map) return create_named_record(map, spec) if spec r = root e = entry return nil if r.nil? || e.nil? id = r["next_id"].to_i id += 1 while record_by_id(id) || r["maps"].key?("#{KEY_PREFIX}#{id}") key = "#{KEY_PREFIX}#{id}" field = e["to"] no = register(key, MAP_ID_BASE + id, field) return nil if no.nil? r["next_id"] = id + 1 rec = {"id" => id, "om" => e["om"].map{|v| v.to_i }, "region" => e["region"].to_i, "field" => field, "key" => key, "map_no" => no, "pieces" => {}, "made" => date_now} list << rec name_of(rec) # named on founding e["base"] = id rekey(map, rec) p "LonaCraft Bases: base #{id} on world map #{rec["om"].inspect} pins #{field.inspect} as #{key} (map #{no})" rec end # R9: the one record of a named map; its key and number are the map's own def self.create_named_record(map, spec) r = root return nil if r.nil? id = r["next_id"].to_i id += 1 while record_by_id(id) || r["maps"].key?("#{KEY_PREFIX}#{id}") r["next_id"] = id + 1 key = map.map_id_rec rec = {"id" => id, "om" => nil, "region" => spec["region"].to_i, "kind" => spec["kind"].to_s, "field" => nil, "key" => key, "map_no" => map.map_id.to_i, "pieces" => {}, "made" => date_now} list << rec name_of(rec) # named on founding p "LonaCraft Bases: base #{id} is the named map #{key} (map #{rec["map_no"]}), one record for the whole map" rec end # The live map takes the base's key and number, as if entered pinned. def self.rekey(map, rec) map.instance_variable_set(:@map_id_rec, rec["key"]) map.instance_variable_set(:@map_id, rec["map_no"]) e = entry e["at"] = rec["key"] if e end def self.remove_record(rec) list.delete(rec) e = entry e["base"] = nil if e && e["base"].to_i == rec["id"].to_i remove_live_markers($game_map, [rec]) if rec["om"].is_a?(Array) p "LonaCraft Bases: base #{rec["id"]} removed, world map tile #{rec["om"].inspect} is random again" else p "LonaCraft Bases: base #{rec["id"]} removed, nothing is built on #{rec["key"]} any more" end end def self.date_now $game_date ? $game_date.dateAmt.to_i : 0 rescue 0 end #---------------------------------------------------------------------- # Destroy all (System page) #---------------------------------------------------------------------- def self.furniture_records return [] if $game_system.nil? || !$game_system.respond_to?(:lonacraft_data) f = $game_system.lonacraft_data["furniture"] f.is_a?(Array) ? f : [] end # Removes exactly +recs+. Shared-online code uses this to remove only # camps owned by the local profile while retaining other players' camps. def self.destroy_records!(recs) r = root return 0 if r.nil? recs = Array(recs).select{|rec| rec.is_a?(Hash) && list.include?(rec) }.uniq return 0 if recs.empty? nos = recs.map{|rec| rec["map_no"].to_i } remove_live_markers($game_map, recs) here = record_for_map($game_map) clear_live($game_map, here) if here && recs.include?(here) && !$game_map.isOverMap gone = furniture_records.select{|f| f.is_a?(Hash) && nos.include?(f["map_id"].to_i) } gone.each{|f| return_furniture(f) } # R7: back to the inventory with chest contents recs.each{|rec| list.delete(rec) } e = entry e["base"] = nil if e && recs.any?{|rec| rec["id"].to_i == e["base"].to_i } prune_maps p "LonaCraft Bases: destroyed #{recs.size} bases and #{gone.size} furniture pieces" recs.size end # Every local base goes; built pieces are not refunded, furniture on base # maps goes back to the inventory with its chest contents (R7). def self.destroy_all! destroy_records!(list.dup) end #---------------------------------------------------------------------- # Markers on the world map #---------------------------------------------------------------------- def self.marker_name(rec) "#{MARKER_PREFIX}#{rec["id"]}" end # M1 (140_AwayRaids.rb): the away-raid reports Lona has not seen yet def self.report_for(rec) a = rec.is_a?(Hash) ? rec["away"] : nil list = a.is_a?(Hash) ? a["reports"] : nil return [] unless list.is_a?(Array) list.select{|r| r.is_a?(Hash) && !r["seen"] } end # M1: the quest "!" balloon (28, as the guild receptionist uses) on the # world-map marker of every base with an unseen report def self.refresh_marker_balloons(map = $game_map) return if map.nil? || !map.isOverMap records_on_overmap(map.map_id).each{|rec| ev = map.events.values.find{|e| e && e.respond_to?(:name) && e.name.to_s == marker_name(rec) } next if ev.nil? if report_for(rec).empty? ev.call_balloon(0) if ev.respond_to?(:call_balloon) else ev.call_balloon(28, -1) if ev.respond_to?(:call_balloon) end } rescue => e p "LonaCraft Bases marker balloon error #{e.class} #{e.message}" end def self.build_marker(rec) sheet, index, dir, pattern = MARKER_SPRITE ev = RPG::Event.new(rec["om"][1].to_i, rec["om"][2].to_i) ev.name = marker_name(rec) page = RPG::Event::Page.new page.graphic.tile_id = 0 page.graphic.character_name = sheet.to_s page.graphic.character_index = index.to_i page.graphic.direction = dir.to_i page.graphic.pattern = pattern.to_i page.move_type = 0 page.walk_anime = false page.step_anime = false page.direction_fix = true page.through = true page.priority_type = 0 page.trigger = 0 page.list = [ EvLib.NewEventCMD("lonacraft_base_marker if respond_to?(:lonacraft_base_marker)"), RPG::EventCommand.new(0, 0, []) ] ev.pages = [page] ev end # Deletes the markers of +recs+ from the live world map (and from its # loaded data, so a nap does not rebuild them). def self.remove_live_markers(map, recs) return if map.nil? || !map.isOverMap || recs.empty? names = recs.map{|rec| marker_name(rec) } data = map.instance_variable_get(:@map) return if data.nil? data.events.keys.each{|i| ev = data.events[i] next unless ev && names.include?(ev.name.to_s) data.events.delete(i) live = map.events[i] next if live.nil? live.nappable = false if live.respond_to?(:nappable=) live.delete } rescue => e p "LonaCraft Bases marker remove error #{e.class} #{e.message}" end #---------------------------------------------------------------------- # Debug key #---------------------------------------------------------------------- def self.debug_active? return false unless DEBUG && 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) begin $game_map.popup(0, text, 0, 0) rescue p text end p text end def self.debug_update return unless debug_active? pressed = begin Input.trigger?(DEBUG_KEY) rescue false end return unless pressed map = $game_map if map.isOverMap why = tile_reason($game_player.x, $game_player.y) rec = record_for_tile(map.map_id, $game_player.x, $game_player.y) return debug_say("LonaCraft debug bases #{count}; this tile #{rec ? "is base #{rec["id"]}" : (why ? "refused (#{why})" : "allowed")}") end x = $game_player.x y = $game_player.y rec = record_for_map(map) if rec && rec["pieces"].is_a?(Hash) && rec["pieces"][piece_key(x, y)] res = on_piece_removed(map, x, y) return debug_say(res == :reverted ? "LonaCraft debug last piece removed, base #{rec["id"]} gone, tile random again" : "LonaCraft debug piece removed (#{rec["pieces"].size} left)") end why = can_build_here?(map) return debug_say("LonaCraft debug no base here (#{why})") if why rec = on_piece_placed(map, x, y, "debug") return debug_say("LonaCraft debug could not make a base, see the console") if rec.nil? debug_say("LonaCraft debug base #{rec["id"]} piece #{rec["pieces"].size} at (#{x},#{y}), tile pinned") rescue => e p "LonaCraft Bases debug error #{e.class} #{e.message}" end end end #============================================================================== # Entering a world-map tile: the pin (34_Functions_ChangeMap.rb:257-269). #============================================================================== module GIM_ADDON if method_defined?(:change_map_enter_region) && !method_defined?(:lonacraft_bases_change_map_enter_region) alias_method :lonacraft_bases_change_map_enter_region, :change_map_enter_region def change_map_enter_region region = $game_player.region_id pick = nil begin pick = LonaCraft::Bases.pick_for_entry(region) rescue => e p "LonaCraft Bases entry error #{e.class} #{e.message}" pick = nil end return lonacraft_bases_change_map_enter_region if pick.nil? saved = $data_region_maps[region] $data_region_maps[region] = [pick] begin lonacraft_bases_change_map_enter_region ensure $data_region_maps[region] = saved end end end end #============================================================================== # Game_Map: base keys on setup, markers on the world map. #============================================================================== class Game_Map def lonacraft_inject_base_markers return unless LonaCraft::Bases.enabled? return unless Note.get_data(@map.note.to_s)["isOverMap"] == "true" bases = LonaCraft::Bases bases.records_on_overmap(@map_id).each{|rec| name = bases.marker_name(rec) next if @map.events.values.any?{|e| e && e.name == name } ev = bases.build_marker(rec) new_id = @map.events.keys.max new_id = new_id.nil? ? 1 : new_id + 1 ev.id = new_id @map.events[new_id] = ev @preload_EventHash[name] = ev if @preload_EventHash.is_a?(Hash) } end unless method_defined?(:setup_event_hack_lonacraft_bases) alias_method :setup_event_hack_lonacraft_bases, :setup_event_hack def setup_event_hack setup_event_hack_lonacraft_bases begin lonacraft_inject_base_markers rescue => e p "LonaCraft Bases marker error #{e.class} #{e.message}" end begin LonaCraft::Bases.rebuild_tiles(self) # B2: walls and floors into the fresh map data rescue => e p "LonaCraft Bases tile rebuild error #{e.class} #{e.message}" end end end unless method_defined?(:setup_lonacraft_bases) alias_method :setup_lonacraft_bases, :setup def setup(map_id) key = map_id begin key = LonaCraft::Bases.setup_key(map_id) rescue => e p "LonaCraft Bases setup key error #{e.class} #{e.message}" end setup_lonacraft_bases(key) begin LonaCraft::Bases.after_setup(self) rescue => e p "LonaCraft Bases after setup error #{e.class} #{e.message}" end end end end #============================================================================== # Game_Interpreter: the marker's command = the tile's region menu. #============================================================================== class Game_Interpreter def lonacraft_base_marker return unless $game_map.isOverMap region = $game_player.region_id $game_temp.reserve_region_event(region) if region > 0 end end #============================================================================== # DataManager: after a load, register the pinned maps the save knows. #============================================================================== module DataManager unless respond_to?(:extract_save_contents_lonacraft_bases) self.singleton_class.send(:alias_method, :extract_save_contents_lonacraft_bases, :extract_save_contents) def self.extract_save_contents(contents) extract_save_contents_lonacraft_bases(contents) begin LonaCraft::Bases.register_all # a save made on a base map before the 2026-10-06 fix may hold the map # without its walls; the load does not set the map up again LonaCraft::Bases.rebuild_tiles($game_map, true) if $game_map rescue => e p "LonaCraft Bases load error #{e.class} #{e.message}" end end end end #============================================================================== # Scene_Map: debug key. #============================================================================== class Scene_Map unless method_defined?(:update_lonacraft_bases) alias_method :update_lonacraft_bases, :update def update update_lonacraft_bases LonaCraft::Bases.debug_update if LonaCraft::Bases::DEBUG end end end #============================================================================== # Menu_System (194_menu_08_0_System.rb): "Destroy all bases (N)" + prompt. #============================================================================== class Menu_System LONACRAFT_BASES_ROW = 9 # rows 0-8 are the game's (hardcore .. keybinding) unless method_defined?(:create_sprites_lonacraft_bases) alias_method :create_sprites_lonacraft_bases, :create_sprites def create_sprites create_sprites_lonacraft_bases begin if LonaCraft::Bases.enabled? @commands << [lonacraft_create_bases_sprite, method(:lonacraft_bases_handler), method(:lonacraft_refresh_bases_opt)] end rescue => e p "LonaCraft Bases menu error #{e.class} #{e.message}" end end end def lonacraft_bases_label "#{LonaCraft::Bases.text("menu/destroy_all")} (#{LonaCraft::Bases.count})" end def lonacraft_create_bases_sprite mouse_row = @mouse_all_rects.length [uniform_text_sprite(198, BASE_LINE + UNIT_HEIGHT * LONACRAFT_BASES_ROW, 300, 30, lonacraft_bases_label, mouse_row)] end def lonacraft_refresh_bases_opt(sprites) spr = sprites[0] return if spr.nil? || spr.disposed? spr.bitmap.clear LonaCraft.apply_ui_font(spr.bitmap) spr.bitmap.draw_text(0, 0, spr.bitmap.width, spr.bitmap.height, lonacraft_bases_label) end def lonacraft_bases_handler return SndLib.sys_buzzer if LonaCraft::Bases.count <= 0 lonacraft_bases_prompt_show end def lonacraft_bases_prompt? !@lonacraft_bases_prompt.nil? && !@lonacraft_bases_prompt.disposed? && @lonacraft_bases_prompt.visible end def lonacraft_bases_prompt_show if @lonacraft_bases_prompt.nil? || @lonacraft_bases_prompt.disposed? @lonacraft_bases_prompt_back = Sprite.new @lonacraft_bases_prompt_back.bitmap = Cache.load_bitmap("Graphics/System/", "chat_window_black_area50") @lonacraft_bases_prompt_back.z = 1 + System_Settings::SCENE_Menu_Cursor_Z @lonacraft_bases_prompt = Sprite.new @lonacraft_bases_prompt.bitmap = Bitmap.new(Graphics.width, Graphics.height) @lonacraft_bases_prompt.z = @lonacraft_bases_prompt_back.z + 1 end bases = LonaCraft::Bases bmp = @lonacraft_bases_prompt.bitmap bmp.clear LonaCraft.apply_ui_font(bmp) bmp.font.size = 36 bmp.font.color.set(255, 100, 150, 255) bmp.draw_text(70, 50, 500, 44, bases.text("prompt/title"), 1) bmp.font.size = 20 bmp.font.color.set(*FONT_COLOR) bmp.draw_text(50, 99, 540, 36, bases.text("prompt/line1").gsub("NUM", bases.count.to_s), 1) bmp.draw_text(50, 119, 540, 36, bases.text("prompt/line2"), 1) bmp.font.size = 22 bmp.font.color = Color.new(0, 255, 0) bmp.draw_text(238, 158, 166, 42, InputUtils.getKeyAndTranslate(:C), 0) bmp.font.color = Color.new(255, 255, 0) bmp.draw_text(238, 158, 166, 42, InputUtils.getKeyAndTranslate(:B), 2) bmp.font.color = Color.new(255, 255, 255) bmp.font.size = 20 bmp.draw_text(238, 180, 166, 42, $game_text["DataInput:Key/Confirm"], 0) bmp.draw_text(238, 180, 166, 42, $game_text["DataInput:Key/Cancel"], 2) @lonacraft_bases_prompt_back.visible = @lonacraft_bases_prompt.visible = true end def lonacraft_bases_prompt_hide return if @lonacraft_bases_prompt.nil? || @lonacraft_bases_prompt.disposed? @lonacraft_bases_prompt_back.visible = @lonacraft_bases_prompt.visible = false end def lonacraft_bases_prompt_answer(yes) lonacraft_bases_prompt_hide if yes LonaCraft::Bases.destroy_all! SndLib.ppl_BooGroup(100) rescue SndLib.sys_ok else SndLib.sys_cancel end refresh end unless method_defined?(:update_input_lonacraft_bases) alias_method :update_input_lonacraft_bases, :update_input def update_input if lonacraft_bases_prompt? return if @cursor.moving? return lonacraft_bases_prompt_answer(true) if Input.trigger?(:C) || WolfPad.trigger?(:Z_LINK) return lonacraft_bases_prompt_answer(false) if Input.trigger?(:B) || WolfPad.trigger?(:X_LINK) return end update_input_lonacraft_bases end end unless method_defined?(:mouse_update_input_lonacraft_bases) alias_method :mouse_update_input_lonacraft_bases, :mouse_update_input def mouse_update_input if lonacraft_bases_prompt? return Mouse.ForceIdle if Input.MouseWheelForceIdle? return unless Mouse.enable? return lonacraft_bases_prompt_answer(true) if Input.trigger?(:MZ_LINK) return lonacraft_bases_prompt_answer(false) if Input.trigger?(:MX_LINK) return end mouse_update_input_lonacraft_bases end end unless method_defined?(:mouse_force_main_menu_pause_lonacraft_bases) alias_method :mouse_force_main_menu_pause_lonacraft_bases, :mouse_force_main_menu_pause def mouse_force_main_menu_pause return true if lonacraft_bases_prompt? mouse_force_main_menu_pause_lonacraft_bases end end unless method_defined?(:dispose_lonacraft_bases) alias_method :dispose_lonacraft_bases, :dispose def dispose [@lonacraft_bases_prompt, @lonacraft_bases_prompt_back].each{|spr| next if spr.nil? || spr.disposed? spr.bitmap.dispose if spr.bitmap && spr == @lonacraft_bases_prompt spr.dispose } dispose_lonacraft_bases end end end #============================================================================== # B2 / B3: building pieces (Palisade Wall, Plank Floor, Wooden Door). # Design: docs/RESEARCH_BASE_BUILDING.md sections 2-4, 9.6. # * Pieces live in the base record ("pieces" => {"x,y" => value}); value # letters: W wall, F floor, D door, S door turned sideways (in a wall that # runs up and down). A door may stand on a floor: "FD" / "FDS". No # furniture records are written for them. # * W1 Stone Wall (owner 2026-10-06): build code "S" (BUILD_ORDER, CODE_ITEM, # PIECE_ITEMS, PIECE_STATS "S" 1200 HP / armour 8), stored in the grid as # "B" (STONE_VALUE): "S" already marks a sideways door ("DS", "FDS") in # saved records. Stone and palisade do not join (each kind draws its own # edges). Bench-made only: build mode uses Stone Walls from the bag, never # raw stone (the recipe has no "hand" station). Repair 1 Stone Block = # +300 HP (REPAIR_STONE, PROPOSED). # * Walls are A4 TOP + FACE pairs (owner review 2026-10-06: the A3 block # walls looked flat next to the game's 3/4 view; WALL_A4, picked per A4 # sheet from the contact sheets scratchpad r11/contact_ts*.png). A wall # piece on (x, y) paints the TOP (47-shape, joins the same kind's tops in # 8 directions, section 2.3) on (x, y); where the tile south of a wall is # neither a wall nor a door, that tile shows the FACE (16-shape, joins the # same kind's faces left and right) on its layer 0. Faces are derived at # paint time (faces_of / face_at), never stored. Tops are walkable by the # tileset flags, so Game_Map#check_passage (and Furniture's # lonacraft_layer_pass?) refuse the tiles in @lonacraft_wall_block (every # wall top except a lintel over a front door, update_block); faces are # impassable by the flags (all 16 shapes checked in tiles_info). A north # wall takes two rows: top, then face. A gap in a wall running up and # down (a broken, taken down or never built piece with a wall or door # below it) gets no face: it is the map's own ground, walkable (fix # 2026-10-08, face_at; before, a side-wall breach showed the face of the # piece above and stayed solid). A rebuilt piece paints its top again. A front door goes in the FACE row # (wall above it, walked under: the lintel); a sideways door stands in a # wall running up and down; nowhere else (door_spot?). # * Floors are map TILES: the plank tile of the map's A5 sheet (FLOOR_TILE). # Walls, faces and floors are written into the map data (layer 0, layers # 1-2 cleared) at every setup (setup_event_hack, before the game builds its # region lists and events) and live when placed or taken down; the # neighbours are recomputed too. # * Live repaint (REDRAW): :table (shipped) swaps the map's Table for a copy # after writing, so the tilemap gets a new map_data object on its next # update (49_Spriteset_Map.rb:322-328) and redraws it all; :spriteset # rebuilds the spriteset as a nap does # (Game_Interpreter_Modifies_OM.rb:37-38); :none writes only. # * Doors are the game's own two-page door (NoerTavern WoodenDoorSide4, # doorEV_setup 29_Functions_417_Interpreter.rb:943-961): page 1 open # (through), page 2 closed, init block init_jump_page(2, tag) so it is # closed when built. Spawned as runtime events after every setup and closed # again after a nap. Closed: action key opens it. Open: action key asks # Close / Take down / Cancel. # * Taking down: action key facing a wall or floor piece asks Take down / # Cancel (Game_Player#check_action_event alias, only when nothing else # answered the key). The item comes back; the last piece ends the base (B1). # * Never on the exit ring (region 1, set_region_trigger(1) in every field # map), on -point-StartPoint or next to it, on a tile with an event, on # water, bush or a tile that is not passable; walls and doors not on Lona. # * The region lists of the game's spawns skip built tiles (setup_region_map # alias) unless a list would become empty. #============================================================================== module LonaCraft module Bases WALL_ITEM = "ItemLonaCraftPalisadeWall" FLOOR_ITEM = "ItemLonaCraftPlankFloor" DOOR_ITEM = "ItemLonaCraftWoodenDoor" STONE_ITEM = "ItemLonaCraftStoneWall" STONE_VALUE = "B" # grid value of a stone wall (W1); "S" is the sideways-door mark PIECE_ITEMS = {WALL_ITEM => "W", STONE_ITEM => "S", FLOOR_ITEM => "F", DOOR_ITEM => "D"} # The mod's wall sheets (owner review 3, 2026-10-06: every land type uses # exactly the two approved walls): tools/build_wall_sheets.py paints TileA4 # 97/105 (wood) and Outside_POOR_A4 80/88 (stone) into two top + face kind # pairs no map of that sheet uses (faces solid on every tileset of the sheet) # and writes Graphics/Tilesets/LonaCraft_.png + LonaCraft_walls.json. # A base map (a record, or the Deep Sewer, or a map where Lona starts to # build) gets a private copy of its RPG::Tileset whose A4 slot # (tileset_names[3]) is "../..//Graphics/Tilesets/LonaCraft_" # (Cache.tileset prepends Graphics/Tilesets/, 4_Cache.rb:71-73, the same # trick as the drop pictures); Spriteset_Map#update_tileset reloads when # $game_map.tileset changes (49_Spriteset_Map.rb:315-317). $data_tilesets # is never changed; only the sheet name is kept on the map (derived again # at every setup). WALL_SHEETS_JSON missing: WALL_A4 below (the game's own # art, the earlier per-sheet picks) is used instead. WALL_SHEETS_JSON = "Graphics/Tilesets/LonaCraft_walls.json" # A4 sheet => {"W" palisade, "S" stone} => [top kind, face kind] (owner reviews # 2026-10-06: the wood is TileA4 97/105, pale planks; the stone is # Outside_POOR_A4 80/88, plain grey blocks; every family takes the pair closest # to those two, picked by eye from scratchpad r11/zoom_wood.png / zoom_stone.png; # every face is solid in all 16 shapes). "least bad" = the sheet has nothing close: # TileA4 (plains, roads, Noer: 14, 23) 97/105 the wood 102/110 stone-frame top, wood face (least bad) # Outside_POOR_A4 (forest, mountain, swamp) 97/105 pale boards (least bad, no pale wood) 80/88 the stone # Inside_POOR_A4 (13) 96/104 pale planks 80/88 the stone art # macks_A4 (18) 97/105 pale wood frame (least bad, dark centre) 86/94 grey-green blocks # macks417_badland_A4 (17, 29, 39) 97/105 as macks_A4 119/127 grey frame, block face (least bad) # macks417_AbomTown_A4 (40) 118/126 pale top, plank face 103/111 grey cobble blocks # macks417_Tomb_A4 (the Deep Sewer, 8, 19) 97/105 as macks_A4 86/94 pale blocks, grey block face (a real pair) # Village&town Cliffs_And_Mines (shore, 4) 96/104 earth top, timber face (least bad) 84/92 grey cobble WALL_A4 = { "TileA4" => {"W" => [97, 105], "S" => [102, 110]}, "Outside_POOR_A4" => {"W" => [97, 105], "S" => [80, 88]}, "Inside_POOR_A4" => {"W" => [96, 104], "S" => [80, 88]}, "macks_A4" => {"W" => [97, 105], "S" => [86, 94]}, "macks417_badland_A4" => {"W" => [97, 105], "S" => [119, 127]}, "macks417_AbomTown_A4" => {"W" => [118, 126], "S" => [103, 111]}, "macks417_Tomb_A4" => {"W" => [97, 105], "S" => [86, 94]}, "Village&town-417EDITION_A4_Cliffs_And_Mines" => {"W" => [96, 104], "S" => [84, 92]} } # A5 sheet => plank floor tile id (chosen to stand apart from the walls: diagonal or crosswise planks) FLOOR_TILE = {"TileA5_exterior1" => 1600, "TileA5_exterior3" => 1600, "Outside_POOR_A5" => 1552, "macks_A5" => 1570, "Inside_POOR_A5" => 1552, "macks417_Tomb_A5" => 1570} EXIT_REGION = 1 # No building (pieces and furniture) within EDGE_GAP tiles of the exit ring # (region 1) or the map's border (owner 2026-10-06): 0 = the ring, 1 = the # outermost walkable band, 2 = the tiles against it. Checked on the 41 # field maps of the allowed regions (scratchpad r3/edge_check.py): region 1 # is the whole outer ring on the plains, roads, highway and Ork desert # maps, a few exit tiles at the path ends on forest, swamp and mountain # maps, and several desert / badland maps have walkable tiles on the map # border itself, so the border counts as well. EDGE_GAP = 2 REDRAW = :table # :table, :spriteset or :none (see above) REACH = 3 # the cursor stays within 3 tiles of Lona # [sheet, index, open [dir, pattern], closed [dir, pattern], closed terrain tag, # closed @forced_x, in-between frame [dir, pattern] or nil] # !Door4 index 0: direction 2 = the door face (closed front door), 4 = # half open, 6 / 8 = edge-on (open front door), pattern 0 = left leaf. DOOR_FRONT = ["!Door4", 0, [8, 0], [2, 0], 4, 0, nil] # NoerTavern events 54/55 # A door in a wall running up and down ("S", owner 2026-10-06): the # front door's frames reversed. Closed = the edge-on frame (moved 8 px # right so it sits on the wall line), open = the door face; opening and # closing show the half-open frame for a moment (lonacraft_base_door_turn). DOOR_SIDE = ["!Door4", 0, [2, 0], [8, 0], 4, 8, [4, 0]] # Sewer and tomb maps (owner 2026-10-06: "a metal grate door"): the iron # portcullis of !Door5 index 7 (scratchpad r3/grate_door_candidates.png): # direction 2 down (closed), 4 half up (between), 6 up (open). The game has # no edge-on gate, so the gate also stands face-on in a wall running up # and down. Same piece, item and two pages; only the picture changes. GRATE_FRONT = ["!Door5", 7, [6, 0], [2, 0], 4, 0, [4, 0]] GRATE_SIDE = ["!Door5", 7, [6, 0], [2, 0], 4, 0, [4, 0]] GRATE_A4_SHEETS = ["macks417_Tomb_A4"] # the sewer / tomb family DOOR_TURN_FRAMES = 6 # frames the half-open picture shows GHOST_OPACITY = 150 @tiles_info = {} # tileset id => {:wall, :floor} @originals = {} # map file => its Table as loaded (for taking pieces down) def self.text_key(key) "#{TEXT}#{key}" end # any wall, palisade or stone (doors, flood fills, raids, the sideways rule) def self.wall?(v) v.is_a?(String) && (v.include?("W") || v.include?(STONE_VALUE)) end def self.stone?(v) v.is_a?(String) && v.include?(STONE_VALUE) end # grid value for build code +code+ ("S" -> "B") def self.piece_value(code) code == "S" ? STONE_VALUE : code end def self.floor?(v) v.is_a?(String) && v.include?("F") end def self.door?(v) v.is_a?(String) && v.include?("D") end def self.pieces_of(rec) return {} if rec.nil? rec["pieces"] = {} unless rec["pieces"].is_a?(Hash) rec["pieces"] end def self.cells_of(pieces) pieces.keys.map{|k| k.split(",").map{|v| v.to_i } } end #---------------------------------------------------------------------- # Tiles of a map's tileset #---------------------------------------------------------------------- # {:wall => [top, face] or nil, :stone => [top, face] or nil, :floor => A5 id or nil} def self.tiles_info(map) id = map.instance_variable_get(:@tileset_id) return @tiles_info[id] if @tiles_info.key?(id) ts = $data_tilesets[id] || map.tileset # the game's tileset (its own sheet names) names = ts.tileset_names flags = ts.flags sheet = wall_sheet(names[3].to_s) pairs = sheet ? {"W" => sheet["wood"], "S" => sheet["stone"]} : (WALL_A4[names[3].to_s] || {}) ok = lambda{|kinds| next nil unless kinds.is_a?(Array) && kinds.size == 2 # the face must block in all 16 shapes; the top is made solid by check_passage next nil unless (0...16).all?{|sh| (flags[2048 + kinds[1] * 48 + sh] & 0x0F) == 0x0F } kinds } wall = ok.call(pairs["W"]) stone = ok.call(pairs["S"]) fs = floor_sheet(names[4].to_s) floors = fs ? fs["boards"] : [FLOOR_TILE[names[4].to_s]].compact floors = floors.select{|t| (flags[t] & 0x1F) == 0 } floors = [] unless fs.nil? || floors.size == 2 @tiles_info[id] = {:wall => wall, :stone => stone, :floor => floors[0], :floors => floors} rescue => e p "LonaCraft Bases tileset error #{e.class} #{e.message}" {:wall => nil, :stone => nil, :floor => nil} end # LonaCraft_walls.json, parsed once: {A4 sheet => {"file", "wood", "stone"}} def self.wall_sheets return @wall_sheets if @wall_sheets @wall_sheets = {} @floor_sheets = {} path = LonaCraft.resource(WALL_SHEETS_JSON) return @wall_sheets unless File.exist?(path) && defined?(LonaCraft::ConfigJSON) raw = LonaCraft::ConfigJSON.parse(File.open(path, "rb"){|f| f.read }) list = raw.is_a?(Hash) ? raw["sheets"] : nil return @wall_sheets unless list.is_a?(Hash) list.each{|name, e| next unless e.is_a?(Hash) && e["file"].is_a?(String) next unless [e["wood"], e["stone"]].all?{|k| k.is_a?(Array) && k.size == 2 && k.all?{|n| n.is_a?(Integer) } } next unless File.exist?(LonaCraft.resource("Graphics/Tilesets/#{e["file"]}.png")) @wall_sheets[name.to_s] = e } floors = raw.is_a?(Hash) ? raw["floors"] : nil (floors.is_a?(Hash) ? floors : {}).each{|name, e| next unless e.is_a?(Hash) && e["file"].is_a?(String) next unless e["boards"].is_a?(Array) && e["boards"].size == 2 && e["boards"].all?{|n| n.is_a?(Integer) } next unless File.exist?(LonaCraft.resource("Graphics/Tilesets/#{e["file"]}.png")) @floor_sheets[name.to_s] = e } p "LonaCraft Bases: #{@wall_sheets.size} wall sheets, #{@floor_sheets.size} floor sheets (#{WALL_SHEETS_JSON})" @wall_sheets rescue => e p "LonaCraft Bases wall sheet error #{e.class} #{e.message}" @floor_sheets = {} @wall_sheets = {} end def self.wall_sheet(a4) wall_sheets[a4.to_s] end # the A4 sheet name of +map+'s own tileset (not the private copy) def self.a4_sheet(map) ts = $data_tilesets[map.instance_variable_get(:@tileset_id)] || map.tileset ts.tileset_names[3].to_s rescue "" end # The map shows the mod's wall sheet from now on (a base, the sewer, a # first piece or its preview). Returns true when it does. def self.apply_wall_sheet(map) return false if map.nil? e = wall_sheet(a4_sheet(map)) f = floor_sheet(a5_sheet(map)) return false if e.nil? && f.nil? want = [e ? e["file"] : nil, f ? f["file"] : nil] map.instance_variable_set(:@lonacraft_wall_sheet, want) unless map.instance_variable_get(:@lonacraft_wall_sheet) == want true end # one private RPG::Tileset per game tileset and sheets (the same object every # call, so Spriteset_Map#update_tileset reloads only when it changes); # +files+ = [A4 file or nil, A5 file or nil] (a plain String: A4 only) def self.private_tileset(ts, files) files = [files, nil] unless files.is_a?(Array) @private_ts ||= {} key = [ts.id] + files t = @private_ts[key] return t if t && t.flags.equal?(ts.flags) t = ts.dup t.tileset_names = ts.tileset_names.dup t.tileset_names[3] = "../../#{LonaCraft.path}/Graphics/Tilesets/#{files[0]}" if files[0] t.tileset_names[4] = "../../#{LonaCraft.path}/Graphics/Tilesets/#{files[1]}" if files[1] @private_ts[key] = t end # the A5 sheet name of +map+'s own tileset (the floors) def self.a5_sheet(map) ts = $data_tilesets[map.instance_variable_get(:@tileset_id)] || map.tileset ts.tileset_names[4].to_s rescue "" end def self.floor_sheet(a5) wall_sheets # parses the JSON (walls and floors) @floor_sheets[a5.to_s] end # the shack's boards (Maps/NoerShack.rvdata2 rows 13-16): its two board # tiles in its own 6 x 4 pattern, repeated ("a" the first board, "b" the second) SHACK_PATTERN = ["abbbba", "abaaba", "bbaabb", "bbabab"] def self.floor_tile(info, x, y) f = info[:floors] return info[:floor] unless f.is_a?(Array) && f.size == 2 SHACK_PATTERN[y % 4][x % 6, 1] == "a" ? f[0] : f[1] end def self.code_ok_here?(map, code) info = tiles_info(map) case code when "W" then !info[:wall].nil? when "S" then !info[:stone].nil? when "F" then !info[:floor].nil? else true end end # The map file's own Table (cached), to put tiles back def self.original_data(map) mi = $data_mapinfos[map.map_id_rec] return nil if mi.nil? fn = mi.filename return @originals[fn] if @originals.key?(fn) @originals.clear if @originals.size > 4 @originals[fn] = load_data(fn).data rescue => e p "LonaCraft Bases map file error #{e.class} #{e.message}" nil end # a wall of the same kind (+stone+: stone, else palisade) at (x, y) def self.wall_at?(pieces, map, x, y, stone = false) return true unless map.valid?(x, y) # off the map counts as the same kind v = pieces[piece_key(x, y)] wall?(v) && stone?(v) == stone end # Section 2.3, ground type (47 shapes): +n+ .. +se+ = that neighbour is the same kind def self.ground_shape(n, s, w, e, nw, ne, sw, se) c = lambda{|a, b, d| a && b && !d } case [!w, !n, !e, !s] when [false, false, false, false] (c.call(n, w, nw) ? 1 : 0) | (c.call(n, e, ne) ? 2 : 0) | (c.call(s, e, se) ? 4 : 0) | (c.call(s, w, sw) ? 8 : 0) when [true, false, false, false] then 16 + (c.call(n, e, ne) ? 1 : 0) + (c.call(s, e, se) ? 2 : 0) when [false, true, false, false] then 20 + (c.call(s, e, se) ? 1 : 0) + (c.call(s, w, sw) ? 2 : 0) when [false, false, true, false] then 24 + (c.call(s, w, sw) ? 1 : 0) + (c.call(n, w, nw) ? 2 : 0) when [false, false, false, true] then 28 + (c.call(n, w, nw) ? 1 : 0) + (c.call(n, e, ne) ? 2 : 0) when [true, false, true, false] then 32 when [false, true, false, true] then 33 when [true, true, false, false] then 34 + (c.call(s, e, se) ? 1 : 0) when [false, true, true, false] then 36 + (c.call(s, w, sw) ? 1 : 0) when [false, false, true, true] then 38 + (c.call(n, w, nw) ? 1 : 0) when [true, false, false, true] then 40 + (c.call(n, e, ne) ? 1 : 0) when [true, true, true, false] then 42 when [true, true, false, true] then 43 when [true, false, true, true] then 44 when [false, true, true, true] then 45 else 46 end end # the TOP of a wall: joins the same kind's tops in 8 directions def self.top_shape(pieces, map, x, y, stone) f = lambda{|dx, dy| wall_at?(pieces, map, x + dx, y + dy, stone) } ground_shape(f.call(0, -1), f.call(0, 1), f.call(-1, 0), f.call(1, 0), f.call(-1, -1), f.call(1, -1), f.call(-1, 1), f.call(1, 1)) end # the FACE under a wall: joins the same kind's faces left and right, edge # drawn above (the top) and below (the ground); bits: left 1, top 2, right 4, bottom 8 def self.face_shape(pieces, map, x, y, stone) l = !map.valid?(x - 1, y) || face_at(pieces, map, x - 1, y) == stone r = !map.valid?(x + 1, y) || face_at(pieces, map, x + 1, y) == stone (l ? 0 : 1) | 2 | (r ? 0 : 4) | 8 end # the stone flag (true / false) of the face at (x, y), or nil when there is # none: the tile under a wall that is neither a wall nor a door, and not a # gap in a wall running up and down (fix 2026-10-08: a broken or taken # down piece with a wall or door below it showed the face of the piece # above, and faces are solid, so a breach in a side wall left no gap). # Two walls running left and right with one row between keep the face. def self.face_at(pieces, map, x, y) return nil unless map.valid?(x, y) && map.valid?(x, y - 1) up = pieces[piece_key(x, y - 1)] return nil unless wall?(up) here = pieces[piece_key(x, y)] return nil if wall?(here) || door?(here) down = pieces[piece_key(x, y + 1)] return nil if (wall?(down) || door?(down)) && !(runs_across?(pieces, x, y - 1) && runs_across?(pieces, x, y + 1)) stone?(up) end # the piece at (x, y) has a wall left or right of it (a wall running # left and right) def self.runs_across?(pieces, x, y) wall?(pieces[piece_key(x - 1, y)]) || wall?(pieces[piece_key(x + 1, y)]) end # {[x, y] => stone flag} of every face of +pieces+ def self.faces_of(pieces, map) out = {} pieces.each{|k, v| next unless wall?(v) x, y = k.split(",").map{|n| n.to_i } f = face_at(pieces, map, x, y + 1) out[[x, y + 1]] = f unless f.nil? } out end # a wall over a front door: walked under (the door's lintel) def self.lintel?(pieces, x, y) v = pieces[piece_key(x, y + 1)] wall?(pieces[piece_key(x, y)]) && door?(v) && !v.include?("S") end # the piece a tile belongs to: itself, or the wall above when it is a face def self.owner_tile(pieces, map, x, y) return [x, y] if pieces[piece_key(x, y)] return [x, y - 1] unless face_at(pieces, map, x, y).nil? [x, y] end # the tiles the piece at (x, y) covers on the map: itself and its face def self.footprint(pieces, map, x, y) out = [[x, y]] out << [x, y + 1] if wall?(pieces[piece_key(x, y)]) && !face_at(pieces, map, x, y + 1).nil? out end # every tile the record draws on: pieces and faces def self.all_cells(pieces, map) cells_of(pieces) + faces_of(pieces, map).keys end # Game_Map#check_passage alias table: the wall tops but the lintels, # {y * width + x => true}, nil when there is none def self.update_block(map, pieces) h = {} w = map.width pieces.each{|k, v| next unless wall?(v) x, y = k.split(",").map{|n| n.to_i } next if lintel?(pieces, x, y) h[y * w + x] = true } map.instance_variable_set(:@lonacraft_wall_block, h.empty? ? nil : h) end def self.wall_pair(info, stone) stone ? (info[:stone] || info[:wall]) : info[:wall] end # Writes the cells as +pieces+ says (tops, faces, floors, or the map file's own tiles) def self.paint(map, pieces, cells) apply_wall_sheet(map) if pieces.values.any?{|v| wall?(v) || floor?(v) } # the first piece or its preview info = tiles_info(map) data = map.data orig = nil cells.each{|x, y| next unless map.valid?(x, y) v = pieces[piece_key(x, y)] st = stone?(v) pair = wall?(v) ? wall_pair(info, st) : nil f = wall?(v) ? nil : face_at(pieces, map, x, y) fpair = f.nil? ? nil : wall_pair(info, f) if pair data[x, y, 0] = 2048 + pair[0] * 48 + top_shape(pieces, map, x, y, st) data[x, y, 1] = 0 data[x, y, 2] = 0 elsif fpair data[x, y, 0] = 2048 + fpair[1] * 48 + face_shape(pieces, map, x, y, f) data[x, y, 1] = 0 data[x, y, 2] = 0 elsif floor?(v) && info[:floor] data[x, y, 0] = floor_tile(info, x, y) data[x, y, 1] = 0 data[x, y, 2] = 0 else orig ||= original_data(map) next if orig.nil? 3.times{|z| data[x, y, z] = orig[x, y, z] } end } end # the tiles a change at (x, y) repaints: the tops around it (47-shape, 8 # directions) and the face row under them def self.around(x, y) out = [] (y - 1).upto(y + 2){|cy| (x - 1).upto(x + 1){|cx| out << [cx, cy] } } out end # Makes the shown tilemap pick up written tiles (REDRAW above) def self.repaint(map) case REDRAW when :table m = map.instance_variable_get(:@map) m.data = Marshal.load(Marshal.dump(m.data)) if m when :spriteset if SceneManager.scene_is?(Scene_Map) SceneManager.scene.dispose_spriteset SceneManager.scene.create_spriteset end end rescue => e p "LonaCraft Bases repaint error #{e.class} #{e.message}" end # setup_event_hack: the record's walls and floors into the fresh map data # Fix 2026-10-06 (walls gone on re-entry): Game_Map#isOverMap is the # PREVIOUS map's flag until setup_overmap runs (31_Game_Map.rb:285-287, # after setup_event_hack :193 and setup_events :205), so coming from # the world map the paint was skipped. The loaded map's own note decides. def self.loaded_overmap?(map) m = map.instance_variable_get(:@map) return false if m.nil? Note.get_data(m.note.to_s)["isOverMap"] == "true" end # Writes the record's walls and floors into the map data. Idempotent. # Runs in setup_event_hack (so the events and spawns built during the # setup see the walls) and again at the very end of Game_Map#setup # (after_setup, +final+), which also prints the console line. def self.rebuild_tiles(map, final = false) map.instance_variable_set(:@lonacraft_wall_block, nil) # a fresh map: no wall tops until painted map.instance_variable_set(:@lonacraft_wall_sheet, nil) # the game's sheet unless a base is here return unless enabled? return if loaded_overmap?(map) apply_wall_sheet(map) if named_map?(map) # the Deep Sewer always shows the mod's sheet rec = record_for_map(map) return if rec.nil? apply_wall_sheet(map) pieces = pieces_of(rec) paint(map, pieces, all_cells(pieces, map)) update_block(map, pieces) return unless final w = pieces.values.count{|v| wall?(v) } sw = pieces.values.count{|v| stone?(v) } f = pieces.values.count{|v| floor?(v) } d = pieces.values.count{|v| door?(v) } p "LonaCraft Bases: map #{map.map_id} painted #{w} walls (#{sw} stone), #{f} floors, #{d} doors from record #{rec["id"]}" info = tiles_info(map) names = ($data_tilesets[map.instance_variable_get(:@tileset_id)] || map.tileset).tileset_names p "LonaCraft Bases: #{w} walls skipped on map #{map.map_id}, no wall pair for A4 sheet #{names[3].inspect}" if w > 0 && info[:wall].nil? p "LonaCraft Bases: #{f} floors skipped on map #{map.map_id}, no plank tile for A5 sheet #{names[4].inspect}" if f > 0 && info[:floor].nil? end # setup_region_map alias (and refresh_spawn_lists after every build or # take-down): built tiles and the tiles inside the walls leave the # spawn lists. $game_map.region_map is what the game's spawns read: the # BIOS rolls (Map028 event 1), region_map_wildness_spawn and the # background groups (34_Functions_RegionMap.rb:361-1100, 1254-1460, # 1466+) and get_random_region (31_Game_Map.rb:1325-1328). A list that # would become empty takes the exit ring's tiles instead (region 1). def self.filter_region_map(map) rec = record_for_map(map) return if rec.nil? rm = map.instance_variable_get(:@region_map) return unless rm.is_a?(Array) built = {} pieces = pieces_of(rec) cells_of(pieces).each{|c| built[c] = true } faces_of(pieces, map).each_key{|c| built[c] = true } # the faces are solid too return if built.empty? inside = inside_tiles(map, rec, rm) drop = built.merge(inside) ring = outer_band(map) rm.each_with_index{|list, id| next if id == 0 || id == EXIT_REGION || !list.is_a?(Array) || list.empty? kept = list.reject{|c| drop[[c[0], c[1]]] } if kept.empty? rm[id] = ring.empty? ? list : ring.dup else rm[id] = kept end } p "LonaCraft Bases: #{inside.size} tiles inside the walls kept clear of spawns" end # passage of the map layers only (Furniture's Game_Map#lonacraft_layer_pass?, # 90_Furniture.rb): during setup the game's tile-event list still holds # the previous map's events, so Game_Map#passable? is not used here def self.layer_pass?(map, x, y, d) map.lonacraft_layer_pass?(x, y, 1 << (d / 2 - 1)) end # {[x, y] => distance} for every tile within EDGE_GAP of the exit ring # or the map border (grid distance, 4 directions), cached per loaded map def self.edge_zone(map) m = map.instance_variable_get(:@map) cache = map.instance_variable_get(:@lonacraft_edge_zone) return cache[1] if cache.is_a?(Array) && cache[0] == m.object_id zone = {} queue = [] w = map.width h = map.height (0...h).each{|y| (0...w).each{|x| next unless x == 0 || y == 0 || x == w - 1 || y == h - 1 || map.region_id(x, y) == EXIT_REGION zone[[x, y]] = 0 queue << [x, y] } } head = 0 while head < queue.size x, y = queue[head] head += 1 dist = zone[[x, y]] next if dist >= EDGE_GAP [[1, 0], [-1, 0], [0, 1], [0, -1]].each{|dx, dy| k = [x + dx, y + dy] next if k[0] < 0 || k[1] < 0 || k[0] >= w || k[1] >= h || zone.key?(k) zone[k] = dist + 1 queue << k } end map.instance_variable_set(:@lonacraft_edge_zone, [m.object_id, zone]) zone end # the outermost walkable band (distance 1): never built on, never inside def self.outer_band(map) edge_zone(map).select{|k, v| v == 1 && [2, 4, 6, 8].any?{|d| layer_pass?(map, k[0], k[1], d) } }.keys end def self.refresh_spawn_lists(map) map.send(:setup_region_map) rescue => e p "LonaCraft Bases spawn list error #{e.class} #{e.message}" end # {[x, y] => true} for walkable tiles the outside cannot reach: flood # fill over the tiles' passability (both ways, as a walker), door # pieces count as closed, seeded by the exit ring (region 1) and the # edge of the play area (the bounds of the region tiles). Only tiles # within the base's own bounds count, so pockets the game's map has by # itself are not reported. def self.inside_tiles(map, rec, rm) pieces = pieces_of(rec) cells = cells_of(pieces) return {} if cells.empty? xs = [] ys = [] rm.each_with_index{|list, id| next if id == 0 || !list.is_a?(Array) list.each{|c| xs << c[0]; ys << c[1] } } if xs.empty? ax0, ay0, ax1, ay1 = 0, 0, map.width - 1, map.height - 1 else ax0 = [xs.min - 1, 0].max ay0 = [ys.min - 1, 0].max ax1 = [xs.max + 1, map.width - 1].min ay1 = [ys.max + 1, map.height - 1].min end doors = {} cells.each{|c| doors[c] = true if door?(pieces[piece_key(c[0], c[1])]) } reached = {} queue = [] # seeds: walkable tiles on the play area's edge or next to the exit # ring (the ring itself is not walkable on the field maps: Map028's # 104 region-1 tiles are all impassable) (ay0..ay1).each{|y| (ax0..ax1).each{|x| next if doors[[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) == EXIT_REGION } next unless edge next unless [2, 4, 6, 8].any?{|d| 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 [[2, 0, 1], [4, -1, 0], [6, 1, 0], [8, 0, -1]].each{|d, dx, dy| nx = x + dx ny = y + dy next if nx < ax0 || nx > ax1 || ny < ay0 || ny > ay1 k = [nx, ny] next if reached[k] || doors[k] next unless layer_pass?(map, x, y, d) && layer_pass?(map, nx, ny, 10 - d) reached[k] = true queue << k } end bx0 = cells.map{|c| c[0] }.min bx1 = cells.map{|c| c[0] }.max by0 = cells.map{|c| c[1] }.min by1 = cells.map{|c| c[1] }.max named = named_map?(map) inside = {} (by0..by1).each{|y| (bx0..bx1).each{|x| k = [x, y] next if reached[k] || doors[k] || wall?(pieces[piece_key(x, y)]) next unless [2, 4, 6, 8].any?{|d| layer_pass?(map, x, y, d) } next if named && ceiling?(map, x, y) # R9: the sewer's black ceiling is passable by its flags inside[k] = true } } inside end #---------------------------------------------------------------------- # Placement rules #---------------------------------------------------------------------- # nil, or the text key / symbol why nothing may be built on +map+ now # Owner, 2026-10-06: no building while anyone else is on the map; # owner, 2026-10-08: only while an NPC that is hostile to Lona is # (header "Building and hostiles"). Kept as a wrapper. def self.npcs_present?(map) hostiles_present?(map) end # +ch+ (a character, an event or nil) is on Lona's side: Lona, her # followers and companions (npc.master == $game_player, # 281_Game_NonPlayerCharacter.rb:57), the mercenaries and the maid def self.lona_side?(ch) return false if ch.nil? return true if ch == $game_player return false unless ch.respond_to?(:npc?) && ch.npc? npc = ch.npc return false if npc.nil? return true if npc.respond_to?(:master) && npc.master == $game_player sd = ch.respond_to?(:summon_data) ? ch.summon_data : nil sd.is_a?(Hash) && (sd[:LonaCraftMerc] || sd[:LonaCraftMaid]) ? true : false rescue false end def self.animal?(npc) return true if ANIMAL_RACES.include?(npc.race.to_s) npc.npc_name.to_s.start_with?("Wild") rescue false end # the game's own test of whether the NPC on +ev+ would act against Lona: # not friendly?($game_player) (281_Game_NonPlayerCharacter.rb:1025) and # check_ai_state (:710-718, tri-state conditions, fated enemies) not # :none / :flee, as 35_Game_Player.rb:355 asks it with signal 65535 def self.would_attack_lona?(ev, npc) return false if npc.friendly?($game_player) sensor = begin ev.actor.sensors[0] rescue nil end st = npc.check_ai_state($game_player, 0, 65535, sensor) st == :killer || st == :fucker || st == :assaulter rescue false end # the first NPC on +map+ that blocks building, or nil def self.blocking_hostile(map) return nil if map.nil? || !map.respond_to?(:events) map.events.values.each{|ev| return ev if counts_as_hostile?(ev) } nil end # the build rule for one event (the loop of blocking_hostile; Change # 2026-10-08: also the mercenaries' target rule, 150_Mercs.rb foes): # an NPC creature, alive and up, not on Lona's side, that is attacking # her side now (any race), or is no animal and would attack Lona def self.counts_as_hostile?(ev) return false if ev.nil? return false if ev.respond_to?(:deleted?) && ev.deleted? return false unless ev.respond_to?(:npc?) && ev.npc? return false if ev.instance_variable_get(:@missile) npc = ev.npc return false if npc.nil? return false if npc.respond_to?(:is_object) && npc.is_object return false if NOT_CREATURE_RACES.include?(npc.race.to_s) return false if npc.action_state == :death return false if npc.respond_to?(:npc_dead?) && npc.npc_dead? return false if npc.respond_to?(:sta) && npc.sta.to_i <= 0 # down (fatigue, flee) return false if lona_side?(ev) return true if lona_side?(npc.target) && npc.ai_state != :flee # in combat with her side now return false if animal?(npc) would_attack_lona?(ev, npc) end def self.hostiles_present?(map) ev = blocking_hostile(map) if ev && DEBUG name = "#{ev.npc.npc_name} (event #{ev.id}, race #{ev.npc.race})" p "LonaCraft Bases: building refused, #{name} is hostile" if @last_blocker != name @last_blocker = name end @last_blocker = nil if ev.nil? !ev.nil? rescue => e p "LonaCraft Bases hostiles_present? error #{e.class} #{e.message}" false end # R9: a hostile NPC within +radius+ tiles of Lona (straight line): alive, # not an object, not Lona's follower, and the game's own test # npc.friendly?($game_player) (281_Game_NonPlayerCharacter.rb:1025) false def self.hostile_near?(map, radius = BUILD_ENEMY_RADIUS) return false if map.nil? || $game_player.nil? || !map.respond_to?(:events) px = $game_player.x py = $game_player.y r2 = radius * radius map.events.values.any?{|ev| next false if ev.nil? next false if ev.respond_to?(:deleted?) && ev.deleted? next false unless ev.respond_to?(:npc?) && ev.npc? dx = ev.x - px dy = ev.y - py next false if dx * dx + dy * dy > r2 npc = ev.npc next false if npc.nil? next false if npc.respond_to?(:is_object) && npc.is_object next false if npc.respond_to?(:action_state) && npc.action_state == :death next false if npc.respond_to?(:npc_dead?) && npc.npc_dead? next false if npc.respond_to?(:master) && npc.master == $game_player !npc.friendly?($game_player) } rescue => e p "LonaCraft Bases hostile_near? error #{e.class} #{e.message}" false end # R9: called every frame by build mode and by single placement on the # sewer (+state+ = [frame counter]). true = stop now: the buzzer and the # line are given here. def self.sewer_watch(map, state) state[0] += 1 why = nil if map.threat why = "threat" elsif state[0] >= ENEMY_CHECK_FRAMES state[0] = 0 why = "a hostile within #{BUILD_ENEMY_RADIUS} tiles" if hostile_near?(map) end return false if why.nil? SndLib.sys_buzzer map.popup(0, text_key("Place/enemy_near"), 0, 0) p "LonaCraft Bases: building on the sewer stopped, #{why}" true rescue => e p "LonaCraft Bases sewer watch error #{e.class} #{e.message}" false end # 2026-10-08: build mode and single placement on every map (+state+ = # [frame counter]): the Deep Sewer keeps sewer_watch; elsewhere it closes # when threat comes on or a hostile (hostiles_present?) shows up def self.build_watch(map, state) return sewer_watch(map, state) if sewer_map?(map) state[0] += 1 why = nil if map.threat why = "threat" elsif state[0] >= ENEMY_CHECK_FRAMES state[0] = 0 why = "a hostile on the map" if hostiles_present?(map) end return false if why.nil? SndLib.sys_buzzer map.popup(0, text_key(why == "threat" ? "Place/enemy_near" : "Place/hostiles"), 0, 0) p "LonaCraft Bases: building stopped, #{why}" true rescue => e p "LonaCraft Bases build watch error #{e.class} #{e.message}" false end # on or next to the map's StartPoint or any -point-StartPoint_ # (the sewer has one per entrance) def self.near_start?(map, x, y) sm = map.storypoint_map return false unless sm.is_a?(Hash) sm.any?{|name, sp| n = name.to_s next false unless n == "StartPoint" || n.start_with?("StartPoint_") sp.is_a?(Array) && (sp[0].to_i - x).abs + (sp[1].to_i - y).abs <= 1 } end # an A4 wall-top tile (rows 0, 2, 4 of the A4 sheet: the sewer's black # ceiling), passable by its flags inside a block, never walked on def self.ceiling?(map, x, y) v = map.data[x, y, 0].to_i return false if v < 2048 + 80 * 48 || v >= 8192 (((v - 2048) / 48 - 80) / 8).even? end # R9: true when a wall or door on (x, y) would split the sewer's walkway # graph: walkable tiles of WALKWAY_REGIONS without a wall or door piece, # joined by the map's passage both ways. +extra+: more tiles the piece # blocks (a new wall's face). Every walkway neighbour of the blocked # tiles must still reach the first one without them. def self.cuts_walkway?(map, x, y, pieces, extra = []) node = lambda{|tx, ty| next false unless map.valid?(tx, ty) next false unless WALKWAY_REGIONS.include?(map.region_id(tx, ty)) v = pieces[piece_key(tx, ty)] next false if wall?(v) || door?(v) [2, 4, 6, 8].any?{|d| layer_pass?(map, tx, ty, d) } } gone = ([[x, y]] + extra).select{|c| node.call(c[0], c[1]) } return false if gone.empty? out = {} ([[x, y]] + extra).each{|c| out[c] = true } steps = [[2, 0, 1], [4, -1, 0], [6, 1, 0], [8, 0, -1]] nb = [] gone.each{|gx, gy| steps.each{|d, dx, dy| nx = gx + dx ny = gy + dy next if out[[nx, ny]] next unless node.call(nx, ny) next unless layer_pass?(map, gx, gy, d) && layer_pass?(map, nx, ny, 10 - d) nb << [nx, ny] } } nb.uniq! return false if nb.size < 2 want = {} nb[1..-1].each{|c| want[c] = true } seen = {nb[0] => true} out.each_key{|c| seen[c] = true } queue = [nb[0]] head = 0 while head < queue.size && !want.empty? cx, cy = queue[head] head += 1 steps.each{|d, dx, dy| k = [cx + dx, cy + dy] next if seen[k] next unless node.call(k[0], k[1]) next unless layer_pass?(map, cx, cy, d) && layer_pass?(map, k[0], k[1], 10 - d) seen[k] = true want.delete(k) queue << k } end !want.empty? end def self.place_block_reason(map, code) return :threat if map.threat if sewer_map?(map) # R9: NPCs may be on the sewer, but not a hostile one close by return text_key("Place/enemy_near") if hostile_near?(map) else return text_key("Place/hostiles") if hostiles_present?(map) # 2026-10-08: hostile NPCs only end return text_key("Place/not_here") if map.isOverMap return text_key("Place/not_here") unless can_build_here?(map).nil? return text_key("Place/no_tiles") unless code_ok_here?(map, code) nil end # nil when +code+ may go on (x, y) with the record's +pieces+, else a popup key def self.tile_problem(map, code, x, y, pieces, ghost = nil) blocked = "QuickMsg:Lona/CannotPlaceHere#{rand(2)}" return blocked unless map.valid?(x, y) return text_key("Place/edge") if edge_zone(map)[[x, y]] return text_key("Place/start") if near_start?(map, x, y) v = pieces[piece_key(x, y)] if code == "D" return text_key("Place/taken") unless v.nil? || v == "F" else return text_key("Place/taken") unless v.nil? end return blocked if code != "F" && $game_player.x == x && $game_player.y == y return blocked if map.events_xy(x, y).any?{|ev| !ev.equal?(ghost) } return blocked if named_map?(map) && ceiling?(map, x, y) return text_key("Place/door_spot") if code == "D" && !door_spot?(pieces, map, x, y) # A4 walls: a new wall also shows its face on the tile below (two-row footprint) extra = [] if code == "W" || code == "S" fx = x fy = y + 1 fv = pieces[piece_key(fx, fy)] unless wall?(fv) || door?(fv) return text_key("Place/no_face") unless map.valid?(fx, fy) return text_key("Place/edge") if edge_zone(map)[[fx, fy]] return text_key("Place/start") if near_start?(map, fx, fy) return blocked if $game_player.x == fx && $game_player.y == fy return blocked if map.events_xy(fx, fy).any?{|ev| !ev.equal?(ghost) } return blocked if named_map?(map) && ceiling?(map, fx, fy) return text_key("Place/no_face") unless ground_ok?(map, pieces, fx, fy) extra << [fx, fy] end end return text_key("Place/walkway") if code != "F" && sewer_map?(map) && cuts_walkway?(map, x, y, pieces, extra) return nil if v == "F" # a door on a built floor return "QuickMsg:Lona/WrongPlace#{rand(2)}" unless ground_ok?(map, pieces, x, y) nil end # Grass carries the bush flag but is still usable ground. Wilderness camp # tiles need one walkable approach; sewer geometry keeps its stricter rule. # A tile showing one of our faces is judged by the map file's own tiles. def self.ground_ok?(map, pieces, x, y) return false if map.water_floor?(x, y) return false if named_map?(map) && map.bush?(x, y) if face_at(pieces, map, x, y).nil? directions = [2, 4, 6, 8] return named_map?(map) ? directions.all?{|d| map.passable?(x, y, d) } : directions.any?{|d| map.passable?(x, y, d) } end orig = original_data(map) return false if orig.nil? flags = map.tileset.flags tiles = [orig[x, y, 2], orig[x, y, 1], orig[x, y, 0]] return false if tiles.any?{|t| flags[t] & 0x100 != 0 } check = lambda{|bit| res = false tiles.each{|t| f = flags[t] next if f & 0x10 != 0 res = (f & bit == 0) break } res } bits = [1, 2, 4, 8] named_map?(map) ? bits.all?{|bit| check.call(bit) } : bits.any?{|bit| check.call(bit) } end # Where a door may stand (A4 walls): in the FACE row under a wall that runs # left and right (the front door, the wall above is its lintel), or inside a # wall running up and down (the sideways door). def self.door_spot?(pieces, map, x, y) w = lambda{|a, b| map.valid?(a, b) && wall?(pieces[piece_key(a, b)]) } return false if w.call(x, y) return true if w.call(x, y - 1) && w.call(x, y + 1) && !w.call(x - 1, y) && !w.call(x + 1, y) w.call(x, y - 1) && !w.call(x, y + 1) && (w.call(x - 1, y - 1) || w.call(x + 1, y - 1)) end # A door in a wall running up and down is turned sideways; a front door # stands in the face row (wall above, walls left or right of that wall) def self.door_side?(pieces, map, x, y) w = lambda{|a, b| map.valid?(a, b) && wall?(pieces[piece_key(a, b)]) } return false if w.call(x - 1, y) || w.call(x + 1, y) return true if w.call(x, y - 1) && w.call(x, y + 1) return false if w.call(x, y - 1) && (w.call(x - 1, y - 1) || w.call(x + 1, y - 1)) w.call(x, y - 1) || w.call(x, y + 1) # (older saves) the end of a wall running up and down end # Records the piece, writes its tiles / builds its door. Returns the record or nil. def self.place_piece(map, code, x, y) before = pieces_of(record_for_map(map)) old = before[piece_key(x, y)] value = piece_value(code) if code == "D" value = "D" value = "FD" if old == "F" value += "S" if door_side?(before, map, x, y) end rec = on_piece_placed(map, x, y, value) return nil if rec.nil? clear_hp(rec, x, y) # R4: a new piece stands at full HP pieces = pieces_of(rec) spawn_door(map, x, y, value) if code == "D" paint(map, pieces, around(x, y)) # a door clears the face under its lintel repaint(map) orient_doors_near(map, x, y) if code == "W" || code == "S" update_block(map, pieces) refresh_spawn_lists(map) rec end # Takes one part (:wall, :floor, :door) of the piece at (x, y) down. # Returns [item_name, reverted] or nil. def self.take_down(map, x, y, part) rec = record_for_map(map) return nil if rec.nil? pieces = pieces_of(rec) k = piece_key(x, y) v = pieces[k] newv = nil case part when :door return nil unless door?(v) remove_door_event(map, x, y) newv = floor?(v) ? "F" : nil item = DOOR_ITEM when :wall return nil unless wall?(v) item = stone?(v) ? STONE_ITEM : WALL_ITEM when :floor return nil unless floor?(v) && !door?(v) item = FLOOR_ITEM else return nil end reverted = false clear_hp(rec, x, y) # R4: its damage goes with it if newv pieces[k] = newv else reverted = (on_piece_removed(map, x, y) == :reverted) end paint(map, reverted ? {} : pieces, around(x, y)) repaint(map) orient_doors_near(map, x, y) if part == :wall && !reverted update_block(map, reverted ? {} : pieces) refresh_spawn_lists(map) [item, reverted] end # Destroy-all while Lona stands on a base map: tiles back, doors gone def self.clear_live(map, rec) pieces = pieces_of(rec) cells = cells_of(pieces) cells.each{|x, y| remove_door_event(map, x, y) if door?(pieces[piece_key(x, y)]) } paint(map, {}, all_cells(pieces, map)) # the faces go too repaint(map) update_block(map, {}) rescue => e p "LonaCraft Bases clear error #{e.class} #{e.message}" end #---------------------------------------------------------------------- # Doors (B3) #---------------------------------------------------------------------- def self.door_spec(value, map = $game_map) side = value.to_s.include?("S") return (side ? GRATE_SIDE : GRATE_FRONT) if grate_map?(map) side ? DOOR_SIDE : DOOR_FRONT end # the Deep Sewer and every map on the sewer / tomb A4 sheet use the iron gate def self.grate_map?(map) return false if map.nil? return true if sewer_map?(map) GRATE_A4_SHEETS.include?(a4_sheet(map)) rescue false end def self.door_page(sheet, index, g, through, list) page = RPG::Event::Page.new page.graphic.tile_id = 0 page.graphic.character_name = sheet page.graphic.character_index = index page.graphic.direction = g[0] page.graphic.pattern = g[1] page.move_type = 0 page.walk_anime = false page.step_anime = false page.direction_fix = true page.through = through page.priority_type = 1 page.trigger = 0 page.list = list + [RPG::EventCommand.new(0, 0, [])] page end def self.label(name) RPG::EventCommand.new(118, 0, [name]) end # The game's door, built at runtime (ghost: one closed page, no command) def self.build_door(x, y, value, ghost = false) sheet, index, open_g, closed_g, tag, shift, turn = door_spec(value) ev = RPG::Event.new(x, y) ev.name = ghost ? "LonaCraftBaseDoorGhost" : "LonaCraftBaseDoor_#{x}_#{y}" if ghost page = door_page(sheet, index, closed_g, true, []) page.priority_type = 2 ev.pages = [page] return ev end open_list = [label("init"), label("common"), EvLib.NewEventCMD("init_jump_page(2,#{tag})")] open_list << EvLib.NewEventCMD("@forced_x = #{shift}") if shift.to_i != 0 open_list << label("end_common") open_list << EvLib.NewEventCMD("lonacraft_base_door_menu(#{x},#{y}) if respond_to?(:lonacraft_base_door_menu)") closed_list = [ EvLib.NewEventCMD("lonacraft_base_door_open(#{x},#{y}) if respond_to?(:lonacraft_base_door_open)") ] ev.pages = [door_page(sheet, index, open_g, true, open_list), door_page(sheet, index, closed_g, false, closed_list)] ev end def self.door_event_at(map, x, y) k = piece_key(x, y) map.events.values.find{|e| e && !e.deleted? && e.summon_data.is_a?(Hash) && e.summon_data[:LonaCraftBaseDoor] == k } end def self.spawn_door(map, x, y, value) return if door_event_at(map, x, y) map.lonacraft_spawn_event(build_door(x, y, value), {:LonaCraftBaseDoor => piece_key(x, y)}) rescue => e p "LonaCraft Bases door error #{e.class} #{e.message}" end def self.remove_door_event(map, x, y) ev = door_event_at(map, x, y) return if ev.nil? ev.nappable = false if ev.respond_to?(:nappable=) ev.delete end # shows one frame of the door's sheet (direction_fix events keep it) def self.door_frame(ev, g) ev.instance_variable_set(:@direction, g[0].to_i) ev.instance_variable_set(:@pattern, g[1].to_i) end # back to its page's own picture def self.door_frame_reset(ev) pg = ev.instance_variable_get(:@page) return if pg.nil? door_frame(ev, [pg.graphic.direction, pg.graphic.pattern]) end # The door at (x, y) faces the way its wall runs now ("S" when the wall # runs up and down); a door whose way changed is built again. def self.orient_door(map, pieces, x, y) k = piece_key(x, y) v = pieces[k] return v unless door?(v) want = v.delete("S") want += "S" if door_side?(pieces, map, x, y) return v if want == v pieces[k] = want remove_door_event(map, x, y) spawn_door(map, x, y, want) want end def self.orient_doors_near(map, x, y) rec = record_for_map(map) return if rec.nil? pieces = pieces_of(rec) around(x, y).each{|cx, cy| orient_door(map, pieces, cx, cy) } end # After every setup: each door of the record stands, faces its wall, closed def self.sync_doors(map, rec) pieces = pieces_of(rec) pieces.keys.each{|k| next unless door?(pieces[k]) x, y = k.split(",").map{|n| n.to_i } v = orient_door(map, pieces, x, y) ev = door_event_at(map, x, y) if ev.nil? spawn_door(map, x, y, v) else spec = door_spec(v) ev.custom_page = 2 ev.set_event_terrain_tag(spec[4]) ev.forced_x = spec[5].to_i ev.refresh door_frame_reset(ev) end } rescue => e p "LonaCraft Bases door sync error #{e.class} #{e.message}" end #---------------------------------------------------------------------- # Items and the action key #---------------------------------------------------------------------- # Item use (player_item_usage_eval of the three items), as Furniture.use_item def self.use_item(actor, item) return if item.nil? $game_party.gain_item(item, 1) if item.consumable && !item.key_item? return if PIECE_ITEMS[item.item_name.to_s].nil? if $game_player.nil? || !actor.equal?($game_player.actor) || LonaCraft.vanilla_only_actor?(actor) SndLib.sys_buzzer return end # R7: the item opens build mode with its piece selected (BUILD_FROM_ITEM); # lonacraft_base_place is the one-at-a-time placement of B2/B3 if BUILD_FROM_ITEM $game_temp.loadEval("lonacraft_base_build_mode(#{PIECE_ITEMS[item.item_name.to_s].inspect})") else $game_temp.loadEval("lonacraft_base_place(#{item.item_name.to_s.inspect})") end rescue => e p "LonaCraft Bases use_item error #{e.class} #{e.message}" end def self.front_tile(player) x = player.x y = player.y case player.direction when 2 then y += 1 when 8 then y -= 1 when 4 then x -= 1 when 6 then x += 1 end [x, y] end # Game_Player#check_action_event alias: a wall or floor piece in front def self.action_on_piece(player) return false unless enabled? map = $game_map return false if map.nil? || map.isOverMap rec = record_for_map(map) return false if rec.nil? x, y = front_tile(player) pieces = pieces_of(rec) x, y = owner_tile(pieces, map, x, y) # facing a wall's face: its wall v = pieces[piece_key(x, y)] return false unless wall?(v) || (floor?(v) && !door?(v)) $game_temp.loadEval("lonacraft_base_piece_menu(#{x},#{y})") true end end end class Game_Map # A4 walls: their tops are walkable by the tileset flags; the base's wall # tops (Bases.update_block) refuse every direction. check_passage is what # passable? (walking, 31_Game_Map.rb:773-776), the NPCs' pathfinding # (202_pathfinding.rb:406-409, 465-468) and projectiles (efx_passable?) use. # the mod's wall sheet (Bases.apply_wall_sheet): a private tileset copy whose # A4 slot points at Graphics/Tilesets/LonaCraft_.png in the mod unless method_defined?(:tileset_lonacraft_bases) alias_method :tileset_lonacraft_bases, :tileset def tileset ts = tileset_lonacraft_bases file = @lonacraft_wall_sheet return ts if file.nil? || ts.nil? LonaCraft::Bases.private_tileset(ts, file) rescue tileset_lonacraft_bases end end unless method_defined?(:check_passage_lonacraft_bases) alias_method :check_passage_lonacraft_bases, :check_passage def check_passage(x, y, bit) b = @lonacraft_wall_block return false if b && b[y * width + x] check_passage_lonacraft_bases(x, y, bit) end end # ... and they count as tag 4 (sight, projectiles, Sensors.rb:161-171) also on # the tilesets whose A4 tops carry tag 0 (tileset 29 AbomMountain) unless method_defined?(:terrain_tag_lonacraft_bases) alias_method :terrain_tag_lonacraft_bases, :terrain_tag def terrain_tag(x, y) b = @lonacraft_wall_block return 4 if b && valid?(x, y) && b[y * width + x] terrain_tag_lonacraft_bases(x, y) end end unless method_defined?(:setup_region_map_lonacraft_bases) alias_method :setup_region_map_lonacraft_bases, :setup_region_map def setup_region_map setup_region_map_lonacraft_bases begin LonaCraft::Bases.filter_region_map(self) rescue => e p "LonaCraft Bases region error #{e.class} #{e.message}" end end end end class Game_Player unless method_defined?(:check_action_event_lonacraft_bases) alias_method :check_action_event_lonacraft_bases, :check_action_event def check_action_event(*args) result = check_action_event_lonacraft_bases(*args) return result if result begin return true if LonaCraft::Bases.action_on_piece(self) rescue => e p "LonaCraft Bases action error #{e.class} #{e.message}" end result end end end class Game_Interpreter # Run by the Load_Eval common event after a building item was used. def lonacraft_base_place(item_name) bases = LonaCraft::Bases item = $data_ItemName[item_name.to_s] code = bases::PIECE_ITEMS[item_name.to_s] return if item.nil? || code.nil? return unless $game_party.has_item?(item) map = $game_map reason = bases.place_block_reason(map, code) return lonacraft_base_refuse(reason) if reason x, y = bases.front_tile($game_player) unless map.valid?(x, y) x = $game_player.x y = $game_player.y end base_pieces = bases.pieces_of(bases.record_for_map(map)) ghost = nil shown = nil # cells painted as a preview show = lambda{|px, py| bases.paint(map, base_pieces, shown) if shown shown = nil if code == "D" ghost.moveto(px, py) if ghost else trial = base_pieces.merge(bases.piece_key(px, py) => bases.piece_value(code)) shown = bases.around(px, py) bases.paint(map, trial, shown) end bases.repaint(map) } if code == "D" ghost = map.lonacraft_spawn_event(bases.build_door(x, y, "D", true), {:LonaCraftBaseGhost => true}) ghost.nappable = false ghost.opacity = bases::GHOST_OPACITY end show.call(x, y) $game_map.popup(0, bases.text_key("Place/hint"), 0, 0) placed = false watch = [0] # R9 / 2026-10-08: stops when a hostile comes (close, on the sewer) begin wait(2) loop do wait(1) break if watch && bases.build_watch(map, watch) if Input.trigger?(:B) || WolfPad.trigger?(:X_LINK) SndLib.play_cursor break end if Input.trigger?(:C) || WolfPad.trigger?(:Z_LINK) # judge the tile without the preview on it bases.paint(map, base_pieces, shown) if shown problem = bases.place_block_reason(map, code) if problem lonacraft_base_refuse(problem) break end problem = bases.tile_problem(map, code, x, y, base_pieces, ghost) if problem.nil? placed = true break end if shown bases.paint(map, base_pieces.merge(bases.piece_key(x, y) => bases.piece_value(code)), shown) end SndLib.sys_buzzer $game_map.popup(0, problem, 0, 0) next end dx = 0 dy = 0 if Input.repeat?(:LEFT) dx = -1 elsif Input.repeat?(:RIGHT) dx = 1 elsif Input.repeat?(:UP) dy = -1 elsif Input.repeat?(:DOWN) dy = 1 end next if dx == 0 && dy == 0 nx = x + dx ny = y + dy next unless map.valid?(nx, ny) next if (nx - $game_player.x).abs > bases::REACH || (ny - $game_player.y).abs > bases::REACH x = nx y = ny show.call(x, y) SndLib.play_cursor end ensure bases.paint(map, base_pieces, shown) if shown if ghost && !ghost.deleted? ghost.delete end bases.repaint(map) end return unless placed return SndLib.sys_buzzer unless $game_party.has_item?(item) rec = bases.place_piece(map, code, x, y) return SndLib.sys_buzzer if rec.nil? optain_lose_item(item, 1) unless LonaCraft::Debug.free? # D2 god mode: placed for free SndLib.WoodenBuild(80) end def lonacraft_base_refuse(reason) SndLib.sys_buzzer if reason == :threat $game_map.popup(0, "QuickMsg:Lona/incombat#{rand(2)}", 0, 0) else call_msg(reason.to_s) eventPlayEnd end end def lonacraft_base_take_down(x, y, part) res = LonaCraft::Bases.take_down($game_map, x, y, part) return SndLib.sys_buzzer if res.nil? item = $data_ItemName[res[0]] SndLib.WoodenBuild optain_item(item, 1) if item $game_map.popup(0, LonaCraft::Bases.text_key("Piece/reverted"), 0, 0) if res[1] end # Action key facing a wall or floor piece def lonacraft_base_piece_menu(x, y) bases = LonaCraft::Bases v = bases.pieces_of(bases.record_for_map($game_map))[bases.piece_key(x, y)] part = bases.wall?(v) ? :wall : (bases.floor?(v) ? :floor : nil) return if part.nil? if $game_map.threat SndLib.sys_buzzer return $game_map.popup(0, "QuickMsg:Lona/incombat#{rand(2)}", 0, 0) end $game_portraits.lprt.hide if part == :wall # R4: the wall's HP in the text; a damaged wall offers Repair first hp = bases.hp_at(bases.record_for_map($game_map), x, y) hurt = hp && hp[0] < hp[1] st = bases.stone?(v) # W1: a stone wall has its own lines (Repair costs a Stone Block) menu = st ? (hurt ? "Piece/stone_menu_hurt" : "Piece/stone_menu") : (hurt ? "Piece/wall_menu_hurt" : "Piece/wall_menu") lonacraft_base_hp_msg(bases.text_key(menu), hp) pick = $game_temp.choice $game_temp.choice = -1 if hurt return eventPlayEnd if pick.nil? || pick < 0 if pick == 0 bases.repair_piece($game_map, x, y, self) return eventPlayEnd end pick -= 1 end case pick when 0 then lonacraft_base_take_down(x, y, part) when 1 then lonacraft_base_build_mode(st ? "S" : "W") end return eventPlayEnd end call_msg(bases.text_key("Piece/#{part}_menu")) pick = $game_temp.choice $game_temp.choice = -1 case pick when 0 then lonacraft_base_take_down(x, y, part) when 1 then lonacraft_base_build_mode(part == :wall ? "W" : "F") end eventPlayEnd end # R4: a menu text with HP_NOW / HP_MAX filled in (+hp+ = [now, max] or # nil). Same as call_msg: the message window replaces \T[key] by the text # first (53_Window_Base.rb:246-248), here the text is put in directly. def lonacraft_base_hp_msg(key, hp) text = $game_text[key].to_s text = text.gsub("HP_NOW", hp[0].to_s).gsub("HP_MAX", hp[1].to_s) if hp $game_message.background = 0 $game_message.position = 2 $game_message.add(text) $game_map.interpreter.wait_for_message end # Closed door, action key: opens it. The sideways door shows its # half-open frame first (the front door's frames played backwards). def lonacraft_base_door_open(x, y) bases = LonaCraft::Bases ev = bases.door_event_at($game_map, x, y) return if ev.nil? rec = bases.record_for_map($game_map) v = bases.pieces_of(rec)[bases.piece_key(x, y)] # R4: a damaged closed door asks Open / Repair / Cancel hp = bases.hp_at(rec, x, y) if hp && hp[0] < hp[1] $game_portraits.lprt.hide lonacraft_base_hp_msg(bases.text_key("Piece/door_closed_hurt"), hp) pick = $game_temp.choice $game_temp.choice = -1 if pick == 1 bases.repair_piece($game_map, x, y, self) return eventPlayEnd end return eventPlayEnd unless pick == 0 end spec = bases.door_spec(v) lonacraft_base_door_turn(ev, spec[6]) doorEV_setup(ev.id, 1, 0, "openDoor", [0, 0]) end # Closes the open door +ev+ (doorEV_setup refuses while someone stands in # the doorway; the picture then goes back to open) def lonacraft_base_door_close(ev, spec) lonacraft_base_door_turn(ev, spec[6]) doorEV_setup(ev.id, 2, spec[4], "closeDoor", [spec[5].to_i, 0]) LonaCraft::Bases.door_frame_reset(ev) if ev.through end def lonacraft_base_door_turn(ev, frame) return if frame.nil? LonaCraft::Bases.door_frame(ev, frame) wait(LonaCraft::Bases::DOOR_TURN_FRAMES) end # Action key on an open door: Close / Take down / Cancel def lonacraft_base_door_menu(x, y) bases = LonaCraft::Bases ev = bases.door_event_at($game_map, x, y) return if ev.nil? rec = bases.record_for_map($game_map) v = bases.pieces_of(rec)[bases.piece_key(x, y)] $game_portraits.lprt.hide # R4: HP in the text; a damaged door: Close / Repair / Take down / Cancel hp = bases.hp_at(rec, x, y) hurt = hp && hp[0] < hp[1] lonacraft_base_hp_msg(bases.text_key(hurt ? "Piece/door_menu_hurt" : "Piece/door_menu"), hp) pick = $game_temp.choice $game_temp.choice = -1 if hurt if pick == 1 bases.repair_piece($game_map, x, y, self) return eventPlayEnd end pick -= 1 if pick > 1 end case pick when 0 lonacraft_base_door_close(ev, bases.door_spec(v)) when 1 if $game_map.threat SndLib.sys_buzzer $game_map.popup(0, "QuickMsg:Lona/incombat#{rand(2)}", 0, 0) else lonacraft_base_take_down(x, y, :door) end end eventPlayEnd end end #============================================================================== # R7: build mode (B4') and furniture in bases (B5). # * Build mode: using a building item from the inventory (BUILD_FROM_ITEM), # or "Build mode" in a wall / floor piece's menu, opens it on the map with # that piece selected. A main-menu row was not added: the menu has no room # for an 11th row (rows 18 px apart, 20 px text, already squeezed to 17 px # for 10 rows to stay above the stats panel at y 207, 85_MenuCraft.rb # header, 170_menu_base.rb:284). # Keys (the game's input map, 3000_InputMenu.rb:20-62; skill and roster # keys do nothing while an event runs, 35_Game_Player.rb:1060-1061): # arrows move the cursor (BUILD_REACH tiles from Lona) # L / R previous / next piece (Page Up / Page Down, mouse wheel) # OK build here; hold OK while moving to build along a line # UI_DeleteItem take down the piece under the cursor (Space by default) # Cancel leave # A piece costs its recipe's inputs (LonaCraft::Recipes.find, so # Config/Recipes.json changes them), taken at once, no crafting step; a # ready-made piece in the inventory is used first. Taking down in build # mode gives the inputs back (the action-key take down gives the item). # The HUD (top right) shows the piece, its cost with what Lona holds, and # how many she can build now. # * Furniture: allowed wherever a base may be built (Furniture.base_map?, # 90_Furniture.rb). It stays in the furniture records, keyed by the base's # map number (the simpler way: no second copy in the grid); placing one # makes the base first (ensure_base). A base ends only when it has no piece # and no furniture (base_empty?), so a revert never strands furniture. # Destroy-all returns every furniture piece on base maps to the inventory # with its chest contents (return_furniture). Wall decorations hang on a # palisade wall tile whose tile below is not a wall (its visible face). #============================================================================== module LonaCraft module Bases BUILD_FROM_ITEM = true BUILD_ORDER = ["W", "S", "F", "D"] # L / R cycle: Palisade, Stone, Floor, Door CODE_ITEM = {"W" => WALL_ITEM, "S" => STONE_ITEM, "F" => FLOOR_ITEM, "D" => DOOR_ITEM} PART_CODE = {:wall => "W", :floor => "F", :door => "D"} BUILD_REACH = [9, 5] # cursor range in tiles from Lona (x, y): about one screen KEY_PREV = :L KEY_NEXT = :R KEY_TAKE = :UI_DeleteItem HUD_W = 250 HUD_H = 96 # Above the night darkness (KHAS_SHADOW_Z 1070) and the game's own HUD # viewport (MAP_HUD_Z 1120, 50_System_Settings.rb), else both are dimmed at night. HUD_Z = System_Settings::MAP_HUD_Z + 2 CURSOR_OK = Color.new(255, 255, 80, 230) CURSOR_BAD = Color.new(255, 60, 60, 230) #---------------------------------------------------------------------- # Furniture in bases (B5) #---------------------------------------------------------------------- def self.furniture_on(rec) return [] if rec.nil? no = rec["map_no"].to_i furniture_records.select{|f| f.is_a?(Hash) && f["map_id"].to_i == no } end def self.base_empty?(rec) pieces_of(rec).empty? && furniture_on(rec).empty? end # true on a field map where furniture may go (a base, or a tile where one may start) def self.furniture_map_ok?(map) return false unless enabled? return false if map.nil? || map.isOverMap can_build_here?(map).nil? end # the tile rules of the pieces that matter for furniture: not on the # exit ring, not on or next to the StartPoint def self.furniture_tile_ok?(map, x, y) return false unless furniture_map_ok?(map) return false unless map.valid?(x, y) return false if edge_zone(map)[[x, y]] return false if near_start?(map, x, y) if named_map?(map) return false if ceiling?(map, x, y) # R9: furniture on the platforms, never on the walkways return false if sewer_map?(map) && WALKWAY_REGIONS.include?(map.region_id(x, y)) end true end # the FACE of a wall (A4: the tile under a wall that is not a wall or a door) def self.wall_decoration_ok?(map, x, y) return false unless furniture_map_ok?(map) pieces = pieces_of(record_for_map(map)) !face_at(pieces, map, x, y).nil? end # The base of +map+, made now when there is none yet (furniture first) def self.ensure_base(map) rec = record_for_map(map) return rec if rec return nil unless can_build_here?(map).nil? create_record(map) end # After a furniture piece was picked up: true when that ended the base def self.after_furniture_removed(map) rec = record_for_map(map) return false if rec.nil? || !base_empty?(rec) remove_record(rec) true end # Destroy-all: the piece and its chest contents back to the inventory def self.return_furniture(f) item = $data_ItemName[f["item_name"].to_s] $game_party.gain_item(item, 1) if item box_id = f["box"].to_i fur = defined?(LonaCraft::Furniture) ? LonaCraft::Furniture : nil if fur && box_id >= fur::BOX_BASE && $game_boxes box = fur.box_contents(box_id) if box.is_a?(Hash) box.each{|key, count| next unless key.respond_to?(:item_name) && count.to_i > 0 obj = $data_ItemName[key.item_name] || key $game_party.gain_item(obj, count.to_i) } end $game_boxes.write_box(box_id, nil) end if fur && $game_map fur.remove($game_map, f["uid"]) # its live events too when Lona stands there else furniture_records.delete(f) end rescue => e p "LonaCraft Bases furniture return error #{e.class} #{e.message}" furniture_records.delete(f) end #---------------------------------------------------------------------- # Build mode costs (B4') #---------------------------------------------------------------------- def self.recipe_for(code) return nil unless defined?(LonaCraft::Recipes) LonaCraft::Recipes.find(CODE_ITEM[code]) end # {input item_name => count} or nil when the piece has no recipe def self.cost_of(code) r = recipe_for(code) r ? r.inputs : nil end def self.ready_made(code) item = $data_ItemName[CODE_ITEM[code]] item ? $game_party.item_number(item) : 0 end # how many the inputs held pay for def self.paid_by_materials(code) cost = cost_of(code) return 0 if cost.nil? || cost.empty? return 0 if bench_only?(code) # W1: made at the bench, built from the bag n = nil cost.each{|name, qty| q = qty.to_i next if q <= 0 k = LonaCraft::Recipes.input_count(name) / q n = k if n.nil? || k < n } n || 0 end # true when the piece's recipe cannot be made by hand (Stone Wall: Carpentry Bench only) def self.bench_only?(code) r = recipe_for(code) return false if r.nil? || !LonaCraft::Recipes.respond_to?(:at_station?) !LonaCraft::Recipes.at_station?(r, :hand) rescue false end GOD_COUNT = 999 # D2 god mode: what the HUD shows and the "short" check sees def self.can_build_count(code) return GOD_COUNT if LonaCraft::Debug.free? ready_made(code) + paid_by_materials(code) end # Takes one piece's price: a ready-made item first, else the inputs. # Returns :item, :materials, :free (D2 god mode, 95_Debug.rb) or nil. def self.pay(code, interp) return :free if LonaCraft::Debug.free? # D2 god mode: nothing taken item = $data_ItemName[CODE_ITEM[code]] if item && $game_party.item_number(item) > 0 interp.optain_lose_item(item, 1) return :item end return nil if paid_by_materials(code) <= 0 cost_of(code).each{|name, qty| if name == LonaCraft::FIBRE LonaCraft.pick_fibre(qty).each{|obj, amount| interp.optain_lose_item(obj, amount) } else obj = $data_ItemName[name] interp.optain_lose_item(obj, qty) if obj end } :materials end # Gives a piece's inputs back (any-plant inputs cannot be told apart: not refunded) def self.refund_materials(code, interp) cost = cost_of(code) if cost.nil? || bench_only?(code) # W1: a stone wall was built from the bag, it goes back to the bag item = $data_ItemName[CODE_ITEM[code]] interp.optain_item(item, 1) if item return end cost.each{|name, qty| next if name == LonaCraft::FIBRE obj = $data_ItemName[name] interp.optain_item(obj, qty) if obj } end # Takes down the top part at (x, y): door, then wall, then floor. # Returns [code, reverted] or nil. def self.take_down_top(map, x, y) pieces = pieces_of(record_for_map(map)) x, y = owner_tile(pieces, map, x, y) # the cursor on a face: its wall v = pieces[piece_key(x, y)] part = door?(v) ? :door : (wall?(v) ? :wall : (floor?(v) ? :floor : nil)) return nil if part.nil? code = (part == :wall && stone?(v)) ? "S" : PART_CODE[part] res = take_down(map, x, y, part) return nil if res.nil? [code, res[1]] end def self.cost_text(code) cost = cost_of(code) return text("Build/no_recipe") if cost.nil? line = cost.map{|name, qty| "#{qty} #{LonaCraft::Recipes.input_label(name)} (#{LonaCraft::Recipes.input_count(name)})" }.join(", ") bench_only?(code) ? "#{line}, #{text("Build/bench_only")}" : line end def self.key_name(sym) InputUtils.getKeyAndTranslate(sym).to_s rescue sym.to_s end def self.draw_hud(bmp, code) bmp.clear bmp.fill_rect(0, 0, bmp.width, bmp.height, Color.new(0, 0, 0, 160)) LonaCraft.apply_ui_font(bmp) bmp.font.size = 18 bmp.font.color.set(255, 255, 160, 255) item = $data_ItemName[CODE_ITEM[code]] name = item ? $game_text[item.name].to_s : code bmp.draw_text(6, 2, bmp.width - 12, 20, "#{text("Build/title")} #{name}") bmp.font.size = 15 n = can_build_count(code) bmp.font.color = n > 0 ? Color.new(220, 255, 220) : Color.new(255, 120, 120) bmp.draw_text(6, 24, bmp.width - 12, 18, "#{text("Build/cost")} #{cost_text(code)}") ready = ready_made(code) line = "#{text("Build/can")} #{n}" line += " (#{ready} #{text("Build/ready")})" if ready > 0 bmp.draw_text(6, 42, bmp.width - 12, 18, line) bmp.font.color = Color.new(200, 200, 200) bmp.font.size = 13 bmp.draw_text(6, 60, bmp.width - 12, 16, "#{key_name(KEY_PREV)}/#{key_name(KEY_NEXT)} #{text("Build/key_piece")} #{key_name(:C)} #{text("Build/key_build")}") bmp.draw_text(6, 76, bmp.width - 12, 16, "#{key_name(KEY_TAKE)} #{text("Build/key_take")} #{key_name(:B)} #{text("Build/key_leave")}") rescue => e p "LonaCraft Bases HUD error #{e.class} #{e.message}" end def self.cursor_bitmap(color) bmp = Bitmap.new(32, 32) bmp.fill_rect(0, 0, 32, 2, color) bmp.fill_rect(0, 30, 32, 2, color) bmp.fill_rect(0, 0, 2, 32, color) bmp.fill_rect(30, 0, 2, 32, color) bmp end end end class Game_Interpreter # Build mode (R7 B4'): place many pieces, paid from the inputs at once. def lonacraft_base_build_mode(code = "W") bases = LonaCraft::Bases map = $game_map code = "W" unless bases::BUILD_ORDER.include?(code) if LonaCraft.vanilla_only_actor?($game_player.actor) return SndLib.sys_buzzer end reason = bases.place_block_reason(map, "D") # the map's own checks (no tile table needed) return lonacraft_base_refuse(reason) if reason x, y = bases.front_tile($game_player) unless map.valid?(x, y) x = $game_player.x y = $game_player.y end hud = Sprite.new hud.bitmap = Bitmap.new(bases::HUD_W, bases::HUD_H) hud.x = Graphics.width - bases::HUD_W - 4 hud.y = 4 hud.z = bases::HUD_Z cur_ok = bases.cursor_bitmap(bases::CURSOR_OK) cur_bad = bases.cursor_bitmap(bases::CURSOR_BAD) cursor = Sprite.new cursor.bitmap = cur_ok cursor.z = bases::HUD_Z - 1 ghost = nil ghost_v = nil shown = nil problem = nil pieces = lambda{ bases.pieces_of(bases.record_for_map(map)) } judge = lambda{ r = bases.place_block_reason(map, code) r = bases.tile_problem(map, code, x, y, pieces.call, ghost) if r.nil? r = bases.text_key("Build/short") if r.nil? && bases.can_build_count(code) <= 0 r } show = lambda{ bases.paint(map, pieces.call, shown) if shown shown = nil problem = judge.call if code == "D" gv = bases.door_side?(pieces.call, map, x, y) ? "DS" : "D" if ghost && !ghost.deleted? && ghost_v != gv ghost.delete ghost = nil end if ghost.nil? || ghost.deleted? ghost = map.lonacraft_spawn_event(bases.build_door(x, y, gv, true), {:LonaCraftBaseGhost => true}) ghost.nappable = false ghost.opacity = bases::GHOST_OPACITY ghost.forced_x = bases.door_spec(gv)[5].to_i ghost_v = gv end ghost.moveto(x, y) else if ghost && !ghost.deleted? ghost.delete end ghost = nil cur = pieces.call if cur[bases.piece_key(x, y)].nil? && bases.code_ok_here?(map, code) shown = bases.around(x, y) bases.paint(map, cur.merge(bases.piece_key(x, y) => bases.piece_value(code)), shown) end end bases.repaint(map) cursor.bitmap = problem.nil? ? cur_ok : cur_bad bases.draw_hud(hud.bitmap, code) } build = lambda{|quiet| bases.paint(map, pieces.call, shown) if shown shown = nil # R4: OK on a damaged piece of the selected kind repairs it if !quiet && bases.repair_target?(map, code, x, y) bases.repair_piece(map, x, y, self) show.call next true end why = judge.call if why if why == :threat $game_map.popup(0, "QuickMsg:Lona/incombat#{rand(2)}", 0, 0) unless quiet elsif !quiet $game_map.popup(0, why.to_s, 0, 0) end SndLib.sys_buzzer unless quiet show.call next false end if ghost && !ghost.deleted? ghost.delete end ghost = nil rec = bases.place_piece(map, code, x, y) if rec.nil? SndLib.sys_buzzer show.call next false end bases.pay(code, self) SndLib.WoodenBuild(80) show.call true } place_cursor = lambda{ cursor.x = (map.adjust_x(x) * 32).round cursor.y = (map.adjust_y(y) * 32).round } $game_map.popup(0, bases.text_key("Build/hint"), 0, 0) show.call place_cursor.call watch = [0] # R9 / 2026-10-08: closes when threat comes on or a hostile comes (close, on the sewer) begin wait(2) loop do wait(1) place_cursor.call break if watch && bases.build_watch(map, watch) if Input.trigger?(:B) || WolfPad.trigger?(:X_LINK) SndLib.play_cursor break end if Input.trigger?(:C) || WolfPad.trigger?(:Z_LINK) build.call(false) next end if Input.trigger?(bases::KEY_TAKE) bases.paint(map, pieces.call, shown) if shown shown = nil if ghost && !ghost.deleted? ghost.delete end ghost = nil res = map.threat ? nil : bases.take_down_top(map, x, y) if res bases.refund_materials(res[0], self) SndLib.WoodenBuild $game_map.popup(0, bases.text_key("Piece/reverted"), 0, 0) if res[1] else SndLib.sys_buzzer end show.call next end step = 0 step = -1 if Input.trigger?(bases::KEY_PREV) step = 1 if Input.trigger?(bases::KEY_NEXT) if step != 0 i = bases::BUILD_ORDER.index(code) || 0 code = bases::BUILD_ORDER[(i + step) % bases::BUILD_ORDER.size] SndLib.play_cursor show.call next end dx = 0 dy = 0 if Input.repeat?(:LEFT) dx = -1 elsif Input.repeat?(:RIGHT) dx = 1 elsif Input.repeat?(:UP) dy = -1 elsif Input.repeat?(:DOWN) dy = 1 end next if dx == 0 && dy == 0 nx = x + dx ny = y + dy next unless map.valid?(nx, ny) next if (nx - $game_player.x).abs > bases::BUILD_REACH[0] || (ny - $game_player.y).abs > bases::BUILD_REACH[1] x = nx y = ny show.call place_cursor.call SndLib.play_cursor # hold OK while moving: build along the line (quietly skips bad tiles) build.call(true) if Input.press?(:C) end ensure bases.paint(map, pieces.call, shown) if shown if ghost && !ghost.deleted? ghost.delete end bases.repaint(map) [hud, cursor].each{|spr| next if spr.nil? || spr.disposed? spr.bitmap.dispose if spr == hud && spr.bitmap spr.dispose } cur_ok.dispose unless cur_ok.disposed? cur_bad.dispose unless cur_bad.disposed? end end end #============================================================================== # R4: piece HP, breaking, repair (docs/RESEARCH_RAIDS.md 3.4, 3.6, 4; owner # 2026-10-06). Raids themselves are Scripts/120_Raids.rb. # * HP lives in the base record: rec["hp"] = {"x,y" => hp} for DAMAGED pieces # only; a wall or door without an entry has full HP (plain integers, saved # with the record). Taking a piece down or building it again clears it. # * PIECE_STATS: max HP and armour per kind, W palisade 600 / 3, S stone # wall 1200 / 8 (W1), D door 300 / 3; # Config/Bases.json "pieces" changes them (set_config, 120_Raids.rb). # * break_piece: the piece goes as a take-down WITHOUT refund: out of the # record (a door on a floor leaves the floor), the door event deleted, the # tiles and the neighbours' shapes repainted, the spawn lists refreshed. It # never ends the base; 120_Raids.rb calls revert_if_empty when a raid ends. # * repair_piece: 1 Plank = +150 HP after 120 frames (REPAIR), refused while # the piece was hit in the last 180 frames (Raids.recently_hit?). From the # wall / door menus (action key, any side) and from build mode (OK on a # damaged piece of the selected kind). #============================================================================== module LonaCraft module Bases PIECE_STATS = { "W" => {"hp" => 600, "armour" => 3}, "S" => {"hp" => 1200, "armour" => 8}, # W1 stone wall (the research table's building wall, was "A4") "D" => {"hp" => 300, "armour" => 3}, "SD" => {"hp" => 600, "armour" => 6} # M1: a door set in stone walls (stone_set_door?) } REPAIR = {"item" => "ItemLonaCraftPlank", "hp" => 150, "frames" => 120, "blocked_after_hit_frames" => 180} # W1, PROPOSED: a stone wall is mended with a Stone Block, +300 HP (the rest as REPAIR) REPAIR_STONE = {"item" => "ItemLonaCraftStoneBlock", "hp" => 300} @piece_stats = nil @repair_cfg = nil def self.piece_stats @piece_stats || PIECE_STATS end def self.repair_cfg @repair_cfg || REPAIR end # 120_Raids.rb, after reading Config/Bases.json (already checked there) def self.set_config(stats, repair) @piece_stats = stats if stats.is_a?(Hash) @repair_cfg = repair if repair.is_a?(Hash) end # "D" for a door (also "FD", "FDS"), "S" for a stone wall, "W" for a palisade, nil for the rest def self.hp_kind(v) return "D" if door?(v) return "S" if stone?(v) return "W" if wall?(v) nil end # M1 (owner 2026-10-06): a door set in stone walls: a front door under a # Stone Wall, a sideways door with Stone Walls above and below, or (older # saves) a door in a wall line with Stone Walls left and right def self.stone_set_door?(pieces, x, y) v = pieces[piece_key(x, y)] return false unless door?(v) st = lambda{|a, b| stone?(pieces[piece_key(a, b)]) } return st.call(x, y - 1) && st.call(x, y + 1) if v.include?("S") st.call(x, y - 1) || (st.call(x - 1, y) && st.call(x + 1, y)) end # the stats kind of the piece at (x, y): "SD" (a door set in stone), "D", # "S", "W", or nil def self.piece_kind(pieces, x, y) v = pieces[piece_key(x, y)] return "SD" if door?(v) && stone_set_door?(pieces, x, y) && piece_stats["SD"].is_a?(Hash) hp_kind(v) end def self.max_hp_of(kind) s = piece_stats[kind] s.is_a?(Hash) ? [s["hp"].to_i, 1].max : 1 end def self.armour_of(kind) s = piece_stats[kind] s.is_a?(Hash) ? [s["armour"].to_i, 0].max : 0 end def self.hp_table(rec) rec["hp"] = {} unless rec["hp"].is_a?(Hash) rec["hp"] end # [hp, max] of the wall or door at (x, y), or nil (no such piece) def self.hp_at(rec, x, y) return nil if rec.nil? k = piece_key(x, y) kind = piece_kind(pieces_of(rec), x, y) return nil if kind.nil? max = max_hp_of(kind) t = rec["hp"] now = (t.is_a?(Hash) && t[k].is_a?(Integer)) ? [[t[k], 0].max, max].min : max [now, max] end def self.set_hp(rec, x, y, value) hp = hp_at(rec, x, y) return if hp.nil? t = hp_table(rec) k = piece_key(x, y) if value.to_i >= hp[1] t.delete(k) else t[k] = [value.to_i, 0].max end rec.delete("hp") if t.empty? end def self.clear_hp(rec, x, y) return if rec.nil? || !rec["hp"].is_a?(Hash) rec["hp"].delete(piece_key(x, y)) rec.delete("hp") if rec["hp"].empty? end # Takes +amount+ off the piece at (x, y); [hp, max], :broken, or nil def self.damage_piece(map, x, y, amount) rec = record_for_map(map) hp = hp_at(rec, x, y) return nil if hp.nil? now = hp[0] - amount.to_i if now <= 0 return break_piece(map, x, y) ? :broken : nil end set_hp(rec, x, y, now) [now, hp[1]] end # A wall or door at (x, y) goes with no refund. true when one went. def self.break_piece(map, x, y) rec = record_for_map(map) return false if rec.nil? pieces = pieces_of(rec) k = piece_key(x, y) v = pieces[k] return false unless door?(v) || wall?(v) cells = around(x, y) if door?(v) remove_door_event(map, x, y) # a front door takes its lintel (the wall above) with it, or that # wall's face would close the hole again (A4 walls) if !v.include?("S") && wall?(pieces[piece_key(x, y - 1)]) pieces.delete(piece_key(x, y - 1)) clear_hp(rec, x, y - 1) cells += around(x, y - 1) end if floor?(v) pieces[k] = "F" else pieces.delete(k) end else pieces.delete(k) end clear_hp(rec, x, y) paint(map, pieces, cells.uniq) # the top and its face go, the neighbours' shapes follow repaint(map) orient_doors_near(map, x, y) update_block(map, pieces) refresh_spawn_lists(map) p "LonaCraft Bases: #{v} at (#{x},#{y}) broken, base #{rec["id"]} keeps #{pieces.size} pieces" true rescue => e p "LonaCraft Bases break error #{e.class} #{e.message}" false end # After a raid: a base left with no piece and no furniture ends (B1 rule) def self.revert_if_empty(map) rec = record_for_map(map) return false if rec.nil? || !base_empty?(rec) remove_record(rec) true end def self.repair_blocked?(x, y) return false unless defined?(LonaCraft::Raids) LonaCraft::Raids.recently_hit?(x, y, repair_cfg["blocked_after_hit_frames"].to_i) end # build mode: OK on a damaged piece of the selected kind repairs it def self.repair_target?(map, code, x, y) rec = record_for_map(map) return false if rec.nil? x, y = owner_tile(pieces_of(rec), map, x, y) v = pieces_of(rec)[piece_key(x, y)] return false unless (code == "W" && wall?(v) && !stone?(v)) || (code == "S" && stone?(v)) || (code == "D" && door?(v)) hp = hp_at(rec, x, y) !hp.nil? && hp[0] < hp[1] end # Repairs the piece at (x, y) once; +interp+ is the running interpreter # (waits, takes the item). true when it was repaired. def self.repair_piece(map, x, y, interp) rec = record_for_map(map) hp = hp_at(rec, x, y) return false if hp.nil? cfg = repair_cfg stone = stone?(pieces_of(rec)[piece_key(x, y)]) cfg = cfg.merge(REPAIR_STONE) if stone if hp[0] >= hp[1] $game_map.popup(0, text_key("Repair/full"), 0, 0) return false end if repair_blocked?(x, y) SndLib.sys_buzzer $game_map.popup(0, text_key("Repair/being_hit"), 0, 0) return false end item = $data_ItemName[cfg["item"].to_s] free = LonaCraft::Debug.free? # D2 god mode: no Plank / Stone Block needed or taken if !free && (item.nil? || $game_party.item_number(item) <= 0) SndLib.sys_buzzer $game_map.popup(0, text_key(stone ? "Repair/no_stone" : "Repair/no_item"), 0, 0) return false end SndLib.WoodenBuild(70) interp.wait(cfg["frames"].to_i) if cfg["frames"].to_i > 0 if repair_blocked?(x, y) SndLib.sys_buzzer $game_map.popup(0, text_key("Repair/being_hit"), 0, 0) return false end hp = hp_at(record_for_map(map), x, y) # it may have broken meanwhile return false if hp.nil? || !record_for_map(map).equal?(rec) interp.optain_lose_item(item, 1) unless free || item.nil? now = [hp[0] + cfg["hp"].to_i, hp[1]].min set_hp(rec, x, y, now) SndLib.WoodenBuild(90) $game_map.popup(0, "#{text("Repair/done")} #{now} / #{hp[1]}", 0, 0) p "LonaCraft Bases: repaired (#{x},#{y}) to #{now}/#{hp[1]}" true rescue => e p "LonaCraft Bases repair error #{e.class} #{e.message}" false end end end #============================================================================== # Base names, the base picker and renaming (owner, 2026-10-06) #============================================================================== module LonaCraft # A text key filled at run time (names, lists): "LonaCraft::" # holds +str+ in $game_text until the language changes; the caller writes # it again before each use. Used by 110 / 140 / 150. module RuntimeText PART = "LonaCraft" def self.key(file, id, str) key = "#{PART}:#{file}:#{id}" return key if $game_text.nil? m = $game_text.instance_variable_get(:@map) return key unless m.is_a?(Hash) m[PART] = {} unless m[PART].is_a?(Hash) part = m[PART] unless part[file].is_a?(Hash) loaded = $game_text.load_file(PART, file) rescue nil part[file] = loaded.is_a?(Hash) ? loaded : {} end part[file][id] = str.to_s key rescue => e p "LonaCraft RuntimeText error #{e.class} #{e.message}" key end end module Bases NAME_MAX = 48 PICK_MAX = 6 NAME_DROP = /[,\[\]:\\<>\r\n\t]/ # world-map region => the land word of an automatic name (Text Bases.txt Name/) NAME_KINDS = { 1 => "plains", 2 => "shore", 27 => "shore", 3 => "mountain", 7 => "mountain", 4 => "forest", 5 => "forest", 6 => "forest", 8 => "swamp", 13 => "swamp", 15 => "swamp", 24 => "swamp", 25 => "swamp", 26 => "swamp", 11 => "road", 12 => "road", 17 => "road", 23 => "road", 14 => "desert", 19 => "desert", 16 => "blight", 28 => "blight", 9 => "house" } def self.clean_name(str) str.to_s.gsub(NAME_DROP, "").strip[0, NAME_MAX].to_s.strip end def self.auto_name(rec) key = rec["kind"].to_s == "sewer" ? "sewer" : (NAME_KINDS[rec["region"].to_i] || "camp") name = text("Name/#{key}") name = "Camp" if name.empty? || name.start_with?(TEXT) name = clean_name(name) taken = list.any?{|r| r.is_a?(Hash) && !r.equal?(rec) && r["name"].to_s == name } if taken tag = rec["om"].is_a?(Array) ? "#{rec["om"][1]}-#{rec["om"][2]}" : rec["id"].to_s name = "#{name} #{tag}" end name end # the base's name (made and saved on first use for older saves) def self.name_of(rec) return "" unless rec.is_a?(Hash) n = rec["name"] return n if n.is_a?(String) && !n.empty? rec["name"] = auto_name(rec) end # Local/offline records are always manageable. A shared record can only # be changed by the client whose authenticated nickname owns it; the # server repeats this check against profile_id before writing MySQL. def self.manageable?(rec) return false unless rec.is_a?(Hash) return true unless rec["lc_shared"] defined?(LonaCraft::OnlineSync) && LonaCraft::OnlineSync.respond_to?(:owns_camp?) && LonaCraft::OnlineSync.owns_camp?(rec) rescue false end def self.rename(rec, str) n = clean_name(str) return false if n.empty? || !manageable?(rec) return true if rec["name"].to_s == n rec["name"] = n if defined?(LonaCraft::OnlineSync) LonaCraft::OnlineSync.announce_metadata(rec) if LonaCraft::OnlineSync.respond_to?(:announce_metadata) LonaCraft::OnlineSync.update_tab_camp if LonaCraft::OnlineSync.respond_to?(:update_tab_camp) end p "LonaCraft Bases: base #{rec["id"]} is now #{n.inspect}" true end def self.mark_visited(rec) r = root return if r.nil? r["visit_seq"] = r["visit_seq"].to_i + 1 rec["visited"] = r["visit_seq"] end # the bases the picker offers: newest first, at most PICK_MAX; with more, # the PICK_MAX most recently visited def self.pick_list all = list.select{|r| r.is_a?(Hash) } return all.sort_by{|r| -r["id"].to_i } if all.size <= PICK_MAX all.sort_by{|r| [-r["visited"].to_i, -r["id"].to_i] }.first(PICK_MAX) end # Asks with the text of +prompt_key+ and the base names (\optB, Cancel # last); the record picked, or nil. Call from an event's interpreter. def self.choose_base(prompt_key) recs = pick_list return nil if recs.empty? labels = recs.map{|r| name_of(r).gsub(NAME_DROP, "") } + [text("Pick/cancel")] key = LonaCraft::RuntimeText.key("Bases", "rt_pick", "#{$game_text[prompt_key]}\\optB[#{labels.join(",")}]") $game_map.interpreter.call_msg(key) pick = $game_temp.choice $game_temp.choice = -1 return nil if pick.nil? || pick < 0 || pick >= recs.size recs[pick] rescue => e p "LonaCraft Bases picker error #{e.class} #{e.message}" nil end # +dialog_key+'s \optB menu with "Rename base (name)" and "Danger # (step)" added: [runtime key, index of the Rename line, index of the # Danger line] or nil def self.rename_menu(dialog_key, rec, id = "rt_rename_menu") return nil unless manageable?(rec) got = defined?(LonaCraft::Homes) ? LonaCraft::Homes.extend_menu($game_text[dialog_key].to_s, menu_labels(rec), nil) : nil return nil if got.nil? [LonaCraft::RuntimeText.key("Bases", id, got[0]), got[1], got[1] + 1] end # the two lines a base adds to a menu: Rename, Danger def self.menu_labels(rec) [text("Rename/opt").gsub("NAME", name_of(rec)).gsub(NAME_DROP, ""), danger_label(rec)] end #---------------------------------------------------------------------- # Danger (R10): the base's own step on top of the difficulty level #---------------------------------------------------------------------- DANGER_NEXT = {-1 => 0, 0 => 1, 1 => -1} def self.danger_of(rec) d = rec.is_a?(Hash) ? rec["danger"] : nil d.is_a?(Integer) && d >= -1 && d <= 1 ? d : 0 end def self.danger_key(d) {-1 => "lower", 0 => "normal", 1 => "higher"}[d] || "normal" end def self.danger_label(rec) text("Danger/opt").gsub("STEP", text("Danger/#{danger_key(danger_of(rec))}")).gsub(NAME_DROP, "") end # the next step for +rec+ (Lower -> Normal -> Higher -> Lower); refused # while a live raid runs on it. Returns the new step or nil. def self.cycle_danger(rec) return nil unless manageable?(rec) if defined?(LonaCraft::Raids) && LonaCraft::Raids.respond_to?(:busy_on?) && LonaCraft::Raids.busy_on?(rec) SndLib.sys_buzzer $game_map.popup(0, "#{TEXT}Danger/busy", 0, 0) p "LonaCraft Bases: base #{rec["id"]} danger not changed, a raid is on" return nil end d = DANGER_NEXT[danger_of(rec)] rec["danger"] = d if defined?(LonaCraft::OnlineSync) LonaCraft::OnlineSync.announce_metadata(rec) if LonaCraft::OnlineSync.respond_to?(:announce_metadata) LonaCraft::OnlineSync.update_tab_camp if LonaCraft::OnlineSync.respond_to?(:update_tab_camp) end $game_map.popup(0, "#{TEXT}Danger/now_#{danger_key(d)}", 0, 0) p "LonaCraft Bases: base #{rec["id"]} danger #{danger_key(d)}" d rescue => e p "LonaCraft Bases danger error #{e.class} #{e.message}" nil end # the base of Lona's world-map tile, or nil def self.record_at_player return nil if $game_map.nil? || !$game_map.isOverMap || $game_player.nil? record_for_tile($game_map.map_id, $game_player.x, $game_player.y) end # opens the name-entry screen for +rec+ (the scene sets the name on OK) def self.open_rename(rec) unless manageable?(rec) SndLib.sys_buzzer if defined?(SndLib) return false end SceneManager.call(Scene_LonaCraftBaseName) SceneManager.scene.prepare(rec["id"].to_i, NAME_MAX) true end end end #============================================================================== # The name-entry screen: a centred physical-keyboard editor with no on-screen # character grid. It behaves like the online nickname field. #============================================================================== # Compact physical-keyboard editor, intentionally shaped like the online # nickname window. The stock Window_NameInput grid uses fixed 360px geometry # and cannot represent a 48-character camp name without drifting off-screen. class Window_LonaCraftBaseNameEdit < Window_Base attr_reader :name def initialize(actor, max_char) @name = actor.name.to_s[0, max_char] @max_char = max_char @ok_handler = nil @cancel_handler = nil @last_input_frame = -1 @cursor_visible = nil wide = [(Graphics.width * 0.72).to_i, 480].max wide = [wide, Graphics.width - 80].min high = fitting_height(4) super((Graphics.width - wide) / 2, (Graphics.height - high) / 2, wide, high) self.z = 9999 NicknameInput.reset_text_input! if defined?(NicknameInput) && NicknameInput.respond_to?(:reset_text_input!) refresh activate end def set_handler(sym, callable) @ok_handler = callable if sym == :ok @cancel_handler = callable if sym == :cancel end def keyboard_text if defined?(NicknameInput) && NicknameInput.respond_to?(:typed_chars) return NicknameInput.typed_chars.to_s end Input.UTF8String.to_s rescue "" end def allowed_char?(ch) return false if ch.nil? || ch.empty? || ch =~ /[\x00-\x1f]/ ch !~ LonaCraft::Bases::NAME_DROP end def confirm_pressed? return NicknameInput.confirm_pressed? if defined?(NicknameInput) && NicknameInput.respond_to?(:confirm_pressed?) Input.trigger?(:C) || Input.trigger?(:RETURN) || Input.trigger?(:ENTER) rescue false end def cancel_pressed? return NicknameInput.cancel_pressed? if defined?(NicknameInput) && NicknameInput.respond_to?(:cancel_pressed?) Input.trigger?(:B) || Input.trigger?(:ESCAPE) rescue false end def update super return unless active frame = Graphics.frame_count rescue nil return if !frame.nil? && @last_input_frame == frame @last_input_frame = frame unless frame.nil? changed = false keyboard_text.each_char do |ch| break if @name.length >= @max_char next unless allowed_char?(ch) @name << ch changed = true end if Input.repeat?(:BACK) || Input.repeat?(:DELETE) unless @name.empty? @name = @name[0, @name.length - 1] changed = true end end cursor = ((Graphics.frame_count / 20) % 2 == 0 rescue true) if changed || cursor != @cursor_visible @cursor_visible = cursor refresh end if confirm_pressed? clean = LonaCraft::Bases.clean_name(@name) if clean.empty? SndLib.sys_buzzer if defined?(SndLib) else @name = clean SndLib.sys_ok if defined?(SndLib) deactivate @ok_handler.call if @ok_handler end elsif cancel_pressed? SndLib.sys_cancel if defined?(SndLib) && SndLib.respond_to?(:sys_cancel) deactivate @cancel_handler.call if @cancel_handler end end def refresh contents.clear LonaCraft.apply_ui_font(contents) change_color(system_color) draw_text(0, 0, contents_width, line_height, $game_text["LonaCraft:Bases:Rename/title"].to_s, 1) change_color(normal_color) cursor = @cursor_visible == false ? "" : "|" draw_text(16, line_height, contents_width - 32, line_height, @name + cursor, 1) change_color(system_color) draw_text(0, line_height * 2, contents_width, line_height, "Enter — сохранить Esc — отменить", 1) end end class Scene_LonaCraftBaseName < Scene_MenuBase NameHolder = Struct.new(:name) def prepare(base_id, max_char) @base_id = base_id @max_char = max_char end def start super rec = LonaCraft::Bases.record_by_id(@base_id) @holder = NameHolder.new(rec ? LonaCraft::Bases.name_of(rec) : "") @edit_window = Window_LonaCraftBaseNameEdit.new(@holder, @max_char || LonaCraft::Bases::NAME_MAX) @edit_window.set_handler(:ok, method(:on_input_ok)) @edit_window.set_handler(:cancel, method(:on_input_cancel)) end def on_input_ok rec = LonaCraft::Bases.record_by_id(@base_id) LonaCraft::Bases.rename(rec, @edit_window.name) if rec NicknameInput.reset_text_input! if defined?(NicknameInput) && NicknameInput.respond_to?(:reset_text_input!) return_scene end def on_input_cancel NicknameInput.reset_text_input! if defined?(NicknameInput) && NicknameInput.respond_to?(:reset_text_input!) return_scene end end #============================================================================== # Game_Interpreter: "Rename base" and "Danger" (R10) on the world-map tile # menu of a base (overmap_event_EnterMap, # Editables/33_Functions_OverMapEvents.rb:63-80, builds its \optB list in the # text it passes to call_msg) #============================================================================== class Game_Interpreter if method_defined?(:call_msg) && !method_defined?(:call_msg_lonacraft_bases) alias_method :call_msg_lonacraft_bases, :call_msg def call_msg(*args) msg = args[0] rec = nil if msg.is_a?(String) && msg =~ /\AOvermapEvents:World\/Region\d+\z/ && $game_map && $game_map.isOverMap rec = LonaCraft::Bases.record_at_player if rec original = $game_text[msg].to_s label = LonaCraft::Bases.name_of(rec).gsub(LonaCraft::Bases::NAME_DROP, '') title = original.sub(/\A(\\cg\[[^\]]+\])?[^\r\n]*/) do |line| graphic = line[/\A\\cg\[[^\]]+\]/].to_s graphic + label end new_args = args.dup new_args[0] = LonaCraft::RuntimeText.key('Bases', 'rt_camp_region', title) return call_msg_lonacraft_bases(*new_args) end end if msg.is_a?(String) && msg.include?("\\optB[") && $game_map && $game_map.isOverMap start = $game_text["OvermapEvents:World/Region_option_start"].to_s rec = LonaCraft::Bases.record_at_player if !start.empty? && msg.start_with?(start) end return call_msg_lonacraft_bases(*args) if rec.nil? return call_msg_lonacraft_bases(*args) unless LonaCraft::Bases.manageable?(rec) labels = LonaCraft::Bases.menu_labels(rec) access_option = rec['lc_shared'] && LonaCraft::OnlineSync.ready? labels << 'Доступ к лагерю' if access_option got = LonaCraft::Homes.extend_menu(msg, labels, nil) if defined?(LonaCraft::Homes) return call_msg_lonacraft_bases(*args) if got.nil? new_args = args.dup new_args[0] = got[0] result = call_msg_lonacraft_bases(*new_args) if $game_temp.choice == got[1] $game_temp.choice = -1 # the tile menu ends ("Cancel") LonaCraft::Bases.open_rename(rec) elsif $game_temp.choice == got[1] + 1 $game_temp.choice = -1 LonaCraft::Bases.cycle_danger(rec) # R10 elsif access_option && $game_temp.choice == got[1] + 2 $game_temp.choice = -1 lonacraft_base_access_menu(rec) if respond_to?(:lonacraft_base_access_menu) end result rescue => e p "LonaCraft Bases rename menu error #{e.class} #{e.message}" $game_temp.choice = -1 result end end end