Files
LonaRPG-Online-Games/ModScripts/99999999999_PlayerDocuments.rb
T
2026-10-29 21:59:06 +04:00

295 lines
12 KiB
Ruby

# encoding: UTF-8
# PlayerDocuments 1.0.1. Requires the shipped multiplayer and CorpseRecovery clients.
module MPPlayerDocuments
BASE = 'ItemPassportLona'
PREFIX = 'ItemPassportPlayer_'
class << self
attr_accessor :incoming, :legacy_owner, :merchant_key
def nick
value = WebSocket.local_nickname.to_s.strip
value.empty? ? 'Лона' : value
end
def base; $data_ItemName[BASE]; end
def owner(item)
return nil unless item
return nick if item.item_name == BASE
item.instance_variable_get(:@mp_document_owner)
end
def document?(item); !owner(item).nil?; end
def stable_name(who); PREFIX + who.to_s.encode('UTF-8').unpack1('H*'); end
def from_name(name)
return base if name == BASE
return nil unless name.to_s.match?(/\AItemPassportPlayer_(?:[0-9a-f]{2}){1,256}\z/)
who = [name.delete_prefix(PREFIX)].pack('H*').force_encoding('UTF-8')
return nil unless who.valid_encoding? && !who.match?(/[\x00-\x1f]/)
item_for(who)
end
def item_for(who)
who = who.to_s
return base if who == nick
name = stable_name(who)
found = $data_ItemName[name]
return found if found && $data_items[found.id].equal?(found)
item = base.dup
item.instance_variable_set(:@id, $data_items.length)
item.instance_variable_set(:@item_name, name)
item.instance_variable_set(:@name, "Документы #{who}")
item.instance_variable_set(:@mp_document_owner, who)
$data_items << item
$data_ItemName[name] = item
item
end
def ledger
$game_party.instance_variable_get(:@mp_document_merchants) ||
$game_party.instance_variable_set(:@mp_document_merchants, {})
end
def metadata
owners = {}
$game_party.items.each do |item|
who = owner(item)
owners[item.id.to_s] = who if who
end
{'version' => 1, 'owners' => owners, 'merchants' => ledger}
end
def with_snapshot(stats, fallback = nil)
previous, previous_owner = incoming, legacy_owner
data = stats.is_a?(Hash) ? stats['player_documents'] : nil
self.incoming = data.is_a?(Hash) && data['owners'].is_a?(Hash) ? data['owners'] : {}
self.legacy_owner = fallback
yield data
ensure
self.incoming, self.legacy_owner = previous, previous_owner
end
def sync
WebSocket.live_sync_mark_dirty if WebSocket.respond_to?(:live_sync_mark_dirty)
MPBankGuard.report if defined?(MPBankGuard) && MPBankGuard.ready?
end
def sell_gang(interpreter)
count = $game_party.item_number(BASE)
return if count <= 0
$game_party.lose_item(BASE, count)
interpreter.optain_item('ItemCoin3', 1)
row = (ledger['gang_boss'] ||= {'amount' => 0, 'coins' => 0})
row['amount'] += count
row['coins'] += 2
sync
end
def buy_gang(interpreter)
row = ledger['gang_boss']
return unless row && row['amount'].to_i > 0
cost = row['coins'].to_i
interpreter.call_msg("Выкупить свои документы за #{cost} золотых монет?\\optB[Нет,Выкупить]")
accepted = $game_temp.choice == 1
$game_temp.choice = -1
return unless accepted
if $game_party.item_number('ItemCoin3') < cost
interpreter.call_msg('Для выкупа документов не хватает золотых монет.')
return
end
$game_party.lose_item('ItemCoin3', cost)
$game_party.gain_item(BASE, row['amount'])
ledger.delete('gang_boss')
sync
interpreter.call_msg('Вот твои оригинальные документы. Забирай.')
end
end
module Party
def normalize_party_item(item)
if item.is_a?(String) && item.start_with?(PREFIX)
return MPPlayerDocuments.from_name(item)
end
who = item.instance_variable_get(:@mp_document_owner) if item.respond_to?(:item_name)
return MPPlayerDocuments.item_for(who) if who
super
end
# Foreign document runtime IDs can move after restarting/loading a save.
def mp_restore_documents
return if @mp_restoring_documents || !@mp_document_ids
@mp_restoring_documents = true
old = @mp_document_ids
moved = []
old.each do |id, who|
count = @items[id].to_i
item = MPPlayerDocuments.item_for(who)
moved << [id, item, count] if count > 0
end
moved.each { |id, _, _| @items.delete(id) }
@mp_document_ids = {}
moved.each do |_, item, count|
@items[item.id] = @items.fetch(item.id, 0) + count
@mp_document_ids[item.id] = MPPlayerDocuments.owner(item) unless item.item_name == BASE
end
ensure
@mp_restoring_documents = false
end
def items
mp_restore_documents
super
end
def item_number(item)
mp_restore_documents
super
end
def gain_item_core(item, amount = 1, include_equip = false)
mp_restore_documents
item = MPPlayerDocuments.from_name(item) || item if item.is_a?(String) && item.start_with?(PREFIX)
result = super(item, amount, include_equip)
actual = normalize_party_item(item)
if actual && actual.item_name != BASE && MPPlayerDocuments.document?(actual)
(@mp_document_ids ||= {})[actual.id] = MPPlayerDocuments.owner(actual)
end
result
end
end
module TextNames
def [](key, *args)
return MPPlayerDocuments.nick if key == 'menu:main_stats/name'
return "Документы #{MPPlayerDocuments.nick}" if key == 'DataItem:PassportLona/item_name'
return key if key.is_a?(String) && key.start_with?('Документы ')
super
end
end
# Validation runs before apply_bootstrap_state, while foreign passport IDs
# from a previous process do not exist in the current item database yet.
module BootstrapValidation
def validate_payload(state)
return super unless state.is_a?(Hash)
stats = payload_parts(state)['stats_json']
MPPlayerDocuments.with_snapshot(stats) { super(state) }
end
def data_item(kind, id)
if kind.to_s == 'item'
who = (MPPlayerDocuments.incoming || {})[id.to_s]
if who.is_a?(String) && !who.empty? && who.valid_encoding? && !who.match?(/[\x00-\x1f]/)
return MPPlayerDocuments.base
end
end
super
end
end
module Network
def _live_sync_collect_stats(actor)
super.merge('player_documents' => MPPlayerDocuments.metadata)
end
def _bootstrap_data_item_by_name(name)
MPPlayerDocuments.from_name(name) || super
end
def _bootstrap_gain_hash(kind, payload)
return super unless kind == 'item' && payload.is_a?(Hash)
remaining = payload.dup
payload.each do |id, qty|
who = (MPPlayerDocuments.incoming || {})[id.to_s]
if !who && id.to_i == MPPlayerDocuments.base.id
who = MPPlayerDocuments.legacy_owner || MPPlayerDocuments.nick
end
next unless who.is_a?(String) && !who.empty?
remaining.delete(id)
$game_party.gain_item(MPPlayerDocuments.item_for(who), qty.to_i) if qty.to_i > 0
end
super(kind, remaining)
end
def apply_bootstrap_state(state)
return super unless state.is_a?(Hash) && !state['server_spawn_only']
stats = state['stats_json'].is_a?(Hash) ? state['stats_json'] : bootstrap_decode_json_blob(state['stats_blob'])
MPPlayerDocuments.with_snapshot(stats) do |data|
# A corpse's merchant history never replaces a living player's history.
result = super(state)
if result && data.is_a?(Hash) && data['merchants'].is_a?(Hash)
$game_party.instance_variable_set(:@mp_document_merchants, data['merchants'])
end
result
end
end
end
module CorpseLoot
def consume_public_loot_packet(message)
return super unless public_loot_pending? && message.to_s.start_with?('bootstrap_state:')
parts = message.split(':', 21)
corpse = (@corpses || {})[@public_loot_pending_id.to_i]
fallback = corpse && corpse['nick']
stats = WebSocket.bootstrap_decode_json_blob(parts[16])
MPPlayerDocuments.with_snapshot(stats, fallback || 'Неизвестный игрок') { super(message) }
end
end
module Merchant
def manual_barters(trade_id)
previous = MPPlayerDocuments.merchant_key
MPPlayerDocuments.merchant_key = "#{trade_id}/#{@map_id}/#{get_character(0).id}"
MPPlayerDocuments.ledger.each_value do |rows|
next unless rows.is_a?(Array)
rows.each { |row| MPPlayerDocuments.item_for(row['owner']) }
end
$game_party.items # Remap saved inventory before barter takes its cancel snapshot.
super
ensure
MPPlayerDocuments.merchant_key = previous
end
end
module GangEvent
def load_script(path)
return super unless path == 'Data/HCGframes/event/NoerBackStreetGangBoss.rb'
script = File.binread(path).force_encoding('UTF-8')
menu = '\tcmd_sheet = tmpTarList'.gsub('\\t', "\t")
raise 'PlayerDocuments: gang menu changed' unless script.include?(menu)
script = script.sub(menu, "\ttmpTarList << ['Выкупить свои документы', 'buyOwnID'] if MPPlayerDocuments.ledger['gang_boss']\n" + menu)
marker = '\t\twhen "sellID"'.gsub('\\t', "\t")
raise 'PlayerDocuments: passport sale changed' unless script.include?(marker)
script = script.sub(marker, "\t\twhen \"buyOwnID\"\n\t\t\tMPPlayerDocuments.buy_gang(self)\n" + marker)
loss = 'optain_lose_item("ItemPassportLona",$game_party.item_number("ItemPassportLona"))'
payout = 'optain_item("ItemCoin3",1)'
raise 'PlayerDocuments: passport payout changed' unless script.include?(loss) && script.include?(payout)
script = script.sub(loss, 'MPPlayerDocuments.sell_gang(self)').sub(payout, '# Payout recorded by PlayerDocuments')
instance_eval(script, path)
end
end
module Trade
def prepare(*args)
super
@mp_merchant_key = MPPlayerDocuments.merchant_key
saved = MPPlayerDocuments.ledger[@mp_merchant_key]
return unless saved.is_a?(Array)
box = $game_boxes.box(@box_id)
box.keys.each { |item| box.delete(item) if MPPlayerDocuments.document?(item) }
saved.each do |row|
item = MPPlayerDocuments.item_for(row['owner'])
$game_boxes.setStoreWithPrice(@box_id, item, row['price'].to_i, row['amount'].to_i)
end
end
def move_item(val = nil)
item = @bag_window.active ? @bag_window.item : nil
document = item && MPPlayerDocuments.document?(item)
before = document ? $game_party.item_number(item) : 0
price = document ? item.get_sell_price : 0
result = super
if document && $game_party.item_number(item) < before
$game_boxes.setStoreItemPrice(item, price * 2)
refresh
end
result
end
def terminate
if !@resetToDefault && @mp_merchant_key
rows = []
$game_boxes.box(@box_id).each do |item, amount|
next unless amount.to_i > 0 && MPPlayerDocuments.document?(item)
rows << {'owner' => MPPlayerDocuments.owner(item), 'amount' => amount.to_i,
'price' => $game_boxes.getStoreItemPrice(item).to_i}
end
MPPlayerDocuments.ledger[@mp_merchant_key] = rows
end
super
end
end
end
Game_Party.prepend(MPPlayerDocuments::Party)
Text.prepend(MPPlayerDocuments::TextNames)
WebSocket.singleton_class.prepend(MPPlayerDocuments::Network)
MPStateInfra.singleton_class.prepend(MPPlayerDocuments::BootstrapValidation) if defined?(MPStateInfra)
MPCorpseRecovery.singleton_class.prepend(MPPlayerDocuments::CorpseLoot) if defined?(MPCorpseRecovery)
GIM_ADDON.prepend(MPPlayerDocuments::Merchant)
GIM_ADDON.prepend(MPPlayerDocuments::GangEvent)
Scene_TradeStorage.prepend(MPPlayerDocuments::Trade)