repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/commands/devices_command_spec.rb
test/commands/devices_command_spec.rb
require 'helper' ADB_NO_DEVICES = <<-OUTPUT * daemon not running. starting it now on port 5037 * * daemon started successfully * List of devices attached OUTPUT ADB_DEVICES = <<-OUTPUT * daemon not running. starting it now on port 5037 * * daemon started successfully * List of devices attached 192.168.56.101:5555 device product:vbox86p model:Nexus_4___4_3___API_18___768x1280 device:vbox86p 005de387d71505d6 device usb:1D110000 product:occam model:Nexus_4 device:mako emulator-5554 device emulator-5556 offline OUTPUT class DevicesCommandSpec < CommandSpecBase before do @result = Object.new AdbCommand.any_instance.expects(:execute).returns(@result) end describe "when no devices were found" do before do @result.stubs(:output).returns(ADB_NO_DEVICES) end it "returns an empty device list" do command = silent DevicesCommand.new(@repl) command.execute.must_equal [] end end describe "when devices were found" do before do @result.stubs(:output).returns(ADB_DEVICES) end it "returns the list of devices, bar those that are offline" do command = silent DevicesCommand.new(@repl) devices = command.execute devices.map { |d| d.id }.must_equal [ "192.168.56.101:5555", "005de387d71505d6", "emulator-5554" ] end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/commands/command_spec_base.rb
test/commands/command_spec_base.rb
class Command attr_reader :shell_capture # capture system calls on all commands def `(cmd) capture_shell!(cmd) end def system(cmd) capture_shell!(cmd) end private def capture_shell!(cmd) @shell_capture = cmd # make sure $? is set Kernel::system("echo", "\\c") "mock output" end end class CommandSpecBase < MiniTest::Spec before do @repl = Replicant::REPL.new end def silent(command) def command.output(s) @output = s end def command.output_capture @output end command end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/commands/command_spec.rb
test/commands/command_spec.rb
require 'helper' class CommandSpec < CommandSpecBase class TestCommand < Command def run output "this is a test" end end describe "command loading" do it "loads the EnvCommand when command is '?'" do command = Command.load(@repl, "?") command.must_be_instance_of EnvCommand end it "loads the ListCommand when command is '!'" do command = Command.load(@repl, "!") command.must_be_instance_of ListCommand end it "returns nil if !-command cannot be resolved" do Command.load(@repl, "!unknown").must_be_nil end it "loads the AdbCommand for commands not starting in '!'" do command = Command.load(@repl, "shell ps") command.must_be_instance_of AdbCommand end describe "arguments" do it "injects the arguments for loaded command objects" do command = Command.load(@repl, "shell ps") command.args.must_equal "shell ps" end end end describe "command listing" do it "does not include the ListCommand" do Command.all.map{|c|c.class}.wont_include(ListCommand) end it "does not include the AdbCommand" do Command.all.map{|c|c.class}.wont_include(AdbCommand) end it "does not include the EnvCommand" do Command.all.map{|c|c.class}.wont_include(EnvCommand) end end describe "the command interface" do before do class ::TestCommand < Command; end @command = silent ::TestCommand.new(@repl) end it "allows resolving the command name via type inspection" do @command.name.must_equal "!test" end it "triggers the run method when calling 'execute'" do @command.expects(:run).once @command.execute end it "does not trigger the run method when arguments are invalid" do @command.expects(:valid_args?).returns(false) @command.expects(:run).never @command.execute end end describe "command options" do it "can silence console output" do command = TestCommand.new(@repl, nil, :silent => true) lambda { command.execute }.must_be_silent end end describe "arguments" do it "strips argument whitespace when creating command instance" do command = TestCommand.new(@repl, " ") command.args.must_equal "" end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/commands/device_command_spec.rb
test/commands/device_command_spec.rb
require 'helper' class DeviceCommandSpec < CommandSpecBase describe "given a valid list of devices" do before do @device1 = Device.new("1", "emulator-5554", "Emulator 1") @device2 = Device.new("2", "emulator-5556", "Emulator 2") DevicesCommand.any_instance.stubs(:execute).returns([@device1, @device2]) AdbCommand.any_instance.stubs(:command).returns("echo 'stub!'") end it "can select a device by index" do device = silent(DeviceCommand.new(@repl, "1")).execute device.must_equal @device1 device = silent(DeviceCommand.new(@repl, "2")).execute device.must_equal @device2 end it "updates the repl with the selected device" do device = silent(DeviceCommand.new(@repl, "1")).execute @repl.default_device.must_equal @device1 end it "can select a device by device id" do device = silent(DeviceCommand.new(@repl, "emulator-5554")).execute device.must_equal @device1 end it "does not return or update anything if selected device doesn't exist" do device = silent(DeviceCommand.new(@repl, "100")).execute device.must_be_nil @repl.default_device.must_be_nil end end describe "given an empty list of devices" do before do DevicesCommand.any_instance.stubs(:execute).returns([]) AdbCommand.any_instance.stubs(:command).returns("echo 'stub!'") end it "does not return or update anything if selected device doesn't exist" do device = silent(DeviceCommand.new(@repl, "emulator-bogus")).execute device.must_be_nil @repl.default_device.must_be_nil end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/commands/list_command_spec.rb
test/commands/list_command_spec.rb
require 'helper' class ListCommandSpec < CommandSpecBase describe "listing commands" do it "prints a list of available commands" do command = silent ListCommand.new(@repl) command.execute command.output_capture.must_match /^!\w+/ end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/commands/package_command_spec.rb
test/commands/package_command_spec.rb
require 'helper' class PackageCommandSpec < CommandSpecBase describe "with valid arguments" do it "accepts a package with one element" do command = silent PackageCommand.new(@repl, "myapp") command.execute @repl.default_package.must_equal "myapp" end it "accepts a package with two elements" do command = silent PackageCommand.new(@repl, "com.myapp") command.execute @repl.default_package.must_equal "com.myapp" end end describe "with invalid arguments" do it "refuses a package not starting with alphanumeric characters" do command = silent PackageCommand.new(@repl, "%myapp") command.expects(:run).never command.execute @repl.default_package.must_be_nil end it "refuses a package containing non-alphanumeric characters" do command = silent PackageCommand.new(@repl, "myapp.some$thing") command.expects(:run).never command.execute @repl.default_package.must_be_nil end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/commands/adb_command_spec.rb
test/commands/adb_command_spec.rb
require 'helper' class AdbCommandSpec < CommandSpecBase describe "a basic adb command" do before do @command = silent AdbCommand.new(@repl, "devices") @result = @command.execute end it "sends the command to adb" do @command.shell_capture.must_equal "adb devices 2>&1" end it "captures the process ID and exit code" do @result.code.must_equal $?.exitstatus @result.pid.must_equal $?.pid end it "prints its output to the REPL" do @command = AdbCommand.new(@repl, "devices") lambda { @command.execute }.must_output /mock output/ end end describe "with a default package set" do before do @repl.stubs(:default_package).returns("com.myapp") end it "does not set the default package if command is not package dependent" do command = silent AdbCommand.new(@repl, "devices") command.execute command.shell_capture.must_equal "adb devices 2>&1" end it "adds the default package if command is package dependent" do command = silent AdbCommand.new(@repl, "uninstall") command.execute command.shell_capture.must_equal "adb uninstall com.myapp 2>&1" end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant.rb
lib/replicant.rb
require 'active_support/core_ext/object/blank.rb' require 'active_support/core_ext/string/filters.rb' require 'active_support/core_ext/object/try.rb' require 'replicant/version' require 'replicant/styles' require 'replicant/process_muncher' require 'replicant/log_muncher' require 'replicant/commands' require 'replicant/device' require 'replicant/repl'
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/process_muncher.rb
lib/replicant/process_muncher.rb
class ProcessMuncher def initialize(repl) @repl = repl end def process_table result = AdbCommand.new(@repl, "shell ps", :silent => true).execute if result.code > 0 @signal_exit = true {} else processes = result.output # Parses something like: # u0_a27 1333 123 517564 18668 ffffffff b75a59eb S com.android.musicfx processes.lines.map do |pid_line| columns = pid_line.split [columns[1], columns[-1]] end.to_h end end def find_pid process_table.invert[@repl.default_package] end def scan_pid @last_pid = nil t = Thread.new do begin while @repl.default_package pid = find_pid t.exit if @signal_exit pid_changed = (pid && pid != @last_pid) || (pid.nil? && @last_pid) yield pid if block_given? && pid_changed @last_pid = pid sleep 2 end rescue Exception => e puts e.inspect puts e.backtrace.join("\n") raise e end end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/styles.rb
lib/replicant/styles.rb
module Styles CONSOLE_WIDTH = 70 STYLES = { # foreground text :black_fg => 30, :red_fg => 31, :green_fg => 32, :yellow_fg => 33, :blue_fg => 34, :magenta_fg => 35, :cyan_fg => 36, :white_fg => 37, # background :black_bg => 40, :red_bg => 41, :green_bg => 42, :yellow_bg => 43, :blue_bg => 44, :magenta_bg => 45, :cyan_bg => 46, :white_bg => 47, # text styles :bold => 1 } REPL_OUT = [:green_fg, :bold] def styled_text(text, *styles) create_style(*styles) + text + if block_given? then yield else end_style end end def create_style(*styles) "\e[#{STYLES.values_at(*styles).join(';')}m" end def end_style "\e[0m" end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/version.rb
lib/replicant/version.rb
module Replicant VERSION = "1.0.1" end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/repl.rb
lib/replicant/repl.rb
require 'find' require 'rexml/document' module Replicant class REPL Encoding.default_external = Encoding::UTF_8 Encoding.default_internal = Encoding::UTF_8 include Styles # for auto-complete via rlwrap; should probably go in Rakefile at some point ADB_COMMANDS = %w(devices connect disconnect push pull sync shell emu logcat forward jdwp install uninstall bugreport backup restore help version wait-for-device start-server kill-server get-state get-serialno get-devpath status-window remount reboot reboot-bootloader root usb tcpip ppp) attr_accessor :default_package attr_accessor :default_device def initialize end def run # must be the first thing to execute, since it wraps the script setup_rlwrap show_greeting if ARGV.any? { |arg| %w( -h --help -help help ).include?(arg) } show_help end # try to detect a default package to work with from an AndroidManifest # file somewhere close by if manifest_path = detect_android_manifest_path app_package = get_package_from_manifest(manifest_path) PackageCommand.new(self, app_package).execute end # try to pre-select a device, if any connected_devices = DevicesCommand.new(self, nil, :silent => true).execute if connected_devices.any? output "Found #{connected_devices.size} device(s)" DeviceCommand.new(self, "1").execute end # reset terminal colors on exit at_exit { puts end_style } loop do command_loop end end def command_loop print prompt begin command_line = $stdin.gets.chomp rescue NoMethodError, Interrupt exit end return if command_line.strip.empty? command = Command.load(self, command_line) if command command.execute puts styled_text("OK.", :white_fg, :bold) else output "No such command" end end def output(msg) puts styled_text(msg, *REPL_OUT) end def debug? ARGV.include?('--debug') end private def prompt prompt = ENV['REPL_PROMPT'] || begin pr = (default_device ? "#{default_device.short_name} " : "") << ">> " styled_text(pr, :white_fg, :bold) { create_style(*REPL_OUT) } end.lstrip end def show_greeting style = create_style(:white_fg, :bold) green = lambda { |text| styled_text(text, :green_fg) { style } } logo = <<-logo dP oo dP 88 88 88d888b. .d8888b. 88d888b. 88 dP .d8888b. .d8888b. 88d888b. d8888P 88' `88 88ooood8 88' `88 88 88 88' `"" 88' `88 88' `88 88 88 88. ... 88. .88 88 88 88. ... 88. .88 88 88 88 dP `88888P' 88Y888P' dP dP `88888P' `88888P8 dP dP dP 88 dP (c) 2013-2014 Matthias Kaeppler logo puts style + ("~" * Styles::CONSOLE_WIDTH) puts " v" + Replicant::VERSION puts green[logo] puts "" puts " Type '#{green['!']}' to see a list of commands, '#{green['?']}' for environment info." puts " Commands not starting in '#{green['!']}' are sent to adb verbatim." puts " Use #{green['Ctrl-D']} (i.e. EOF) to exit." puts ("~" * Styles::CONSOLE_WIDTH) + end_style end def show_help puts <<-help Usage: replicant [options] Options: --help Display this message --debug Display debug info Bug reports, suggestions, updates: http://github.com/mttkay/replicant/issues help exit end def setup_rlwrap if !ENV['__REPL_WRAPPED'] && system("which rlwrap > /dev/null 2> /dev/null") ENV['__REPL_WRAPPED'] = '0' # set up auto-completion commands completion_file = File.expand_path('~/.adb_completion') File.open(completion_file, 'w') { |file| file.write(ADB_COMMANDS.join(' ')) } # set up command history if File.exists?(history_dir = File.expand_path(ENV['REPL_HISTORY_DIR'] || "~/")) history_file = "#{history_dir}/.adb_history" end rlargs = "-c" # complete file names rlargs << " --break-chars=" # we don't want to break any of the commands rlargs << " -f #{completion_file}" if completion_file rlargs << " -H #{history_file}" if history_file exec "rlwrap #{rlargs} #$0 #{ARGV.join(' ')}" end end # best effort function to detect the manifest path. # checks for well known locations and falls back to a recursive search with # a maximum depth of 2 directory levels def detect_android_manifest_path manifest_file = 'AndroidManifest.xml' known_manifest_locations = %W(./#{manifest_file} ./src/main/#{manifest_file}) known_manifest_locations.find {|loc| File.exist?(loc)} || begin Find.find('.') do |path| Find.prune if path.start_with?('./.') || path.split('/').size > 3 if File.directory?(path) manifest_file_path = known_manifest_locations.map {|known_location| "#{path}/#{known_location}"}.find {|loc| File.exist?(loc)} return manifest_file_path if manifest_file_path and application_path?(path) end end end end def application_path?(path) if File.exists?("#{path}/project.properties") # old library project return IO.readlines("#{path}/project.properties").none? { |l| l =~ /android.library=true/ } elsif File.exists?("#{path}/build.gradle") return IO.readlines("#{path}/build.gradle").any { |l| l =~ /com.android.application/ } else true end end def get_package_from_manifest(manifest_path) manifest = REXML::Document.new(File.new(manifest_path)) manifest.root.attributes['package'] end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands.rb
lib/replicant/commands.rb
require_relative "commands/command" require_relative "commands/adb_command" require_relative "commands/clear_command" require_relative "commands/device_command" require_relative "commands/devices_command" require_relative "commands/env_command" require_relative "commands/list_command" require_relative "commands/package_command" require_relative "commands/reset_command" require_relative "commands/restart_command"
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/device.rb
lib/replicant/device.rb
class Device attr_reader :idx, :id, :name def initialize(idx, id, name) @idx = idx @id = id @name = name end def emulator? @id.start_with?('emulator-') end def physical_device? !emulator? end def short_name "#{@name[0..4]}[#{@idx}]" end def to_s "#{@id} [#{@name}]" end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/log_muncher.rb
lib/replicant/log_muncher.rb
class LogMuncher include Styles LOGFILE = "/tmp/replicant_device" TIMESTAMP_PATTERN = /^\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}/ PROCESS_PATTERN = /(\w){1}\/(.*)\(\s*([0-9]+)\):\s/ attr_accessor :current_pid def initialize(repl) @repl = repl @current_pid = nil end # Parses the device logs and reformats / recolors them def munch_logs logcat = "logcat -v time" i = IO.popen(AdbCommand.new(@repl, logcat).command) o = File.open(LOGFILE, 'wt') yield o if block_given? Thread.new do begin i.each_line do |line| log_line(o, line) end rescue Exception => e puts e.inspect puts e.backtrace.join("\n") raise e end end end private def log_line(o, line) transform_line(line).each do |seg| text = seg.first styles = seg.last o.print(create_style(*styles)) o.print(text) o.print(end_style) end o.flush end private def transform_line(line) segments = [] timestamp = line[TIMESTAMP_PATTERN] if timestamp # found proper log line process = PROCESS_PATTERN.match(line) pid = process[3] if @current_pid.nil? || @current_pid == pid segments << [" #{timestamp} ", [:white_bg, :bold]] # log level level = process[1] level_fg = case level when "D" then :yellow_fg when "E" then :red_fg else :white_fg end segments << [" #{level} ", [:black_bg, :bold] << level_fg] # log tag tag = process[2].strip segments << ["#{tag} ", [:black_bg, :cyan_fg, :bold]] # log remaining line remainder = [TIMESTAMP_PATTERN, PROCESS_PATTERN].reduce(line) { |l,r| l.gsub(r, '') }.strip segments << [" #{remainder}\n", [:white_fg]] elsif @repl.debug? segments << [" #{timestamp} ", [:black_fg]] segments << [" [muted]\n", [:black_fg]] end end segments end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/command.rb
lib/replicant/commands/command.rb
require 'stringio' class Command include Styles def self.inherited(subclass) @@subclasses ||= [] @@subclasses << subclass end def self.all (@@subclasses - [AdbCommand, ListCommand, EnvCommand]).map do |clazz| clazz.new(nil) end end def self.load(repl, command_line) if command_line == '!' # load command that lists available commands ListCommand.new(repl) elsif command_line == '?' EnvCommand.new(repl) elsif command_line.start_with?('!') # load custom command command_parts = command_line[1..-1].split command_name = command_parts.first command_args = command_parts[1..-1].join(' ') command_class = "#{command_name.capitalize}Command" begin clazz = Object.const_get(command_class) clazz.new(repl, command_args) rescue NameError => e nil end else # forward command to ADB AdbCommand.new(repl, command_line.strip) end end attr_reader :args def initialize(repl, args = nil, options = {}) @repl = repl @args = args.strip if args @options = options end def name "!#{self.class.name.gsub("Command", "").downcase}" end # subclasses override this to provide a description of their functionality def description "TODO: description missing" end # subclasses override this to provide a usage example def usage end def execute if valid_args? run else output "Invalid arguments. Ex.: #{usage}" end end private def valid_args? true end def output(message) @repl.output(message) unless @options[:silent] end def putsd(message) puts "[DEBUG] #{message}" if @repl.debug? end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/list_command.rb
lib/replicant/commands/list_command.rb
class ListCommand < Command def valid_args? args.blank? end def description "print a list of available commands" end def run command_list = Command.all.sort_by {|c| c.name}.map do |command| padding = 20 - command.name.length desc = "#{command.name} #{' ' * padding} -- #{command.description}" desc end output command_list.join("\n") end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/adb_command.rb
lib/replicant/commands/adb_command.rb
class AdbCommand < Command class Result attr_accessor :pid, :code, :output def to_s "result: pid=#{pid} code=#{code} output=#{output}" end end def run Result.new.tap do |result| cmd = "#{command}" putsd cmd if interactive? system cmd else result.output = `#{cmd}` output result.output end result.pid = $?.pid result.code = $?.exitstatus putsd "Command returned with exit status #{result.code}" end end def command adb = "adb" adb << " -s #{@repl.default_device.id}" if @repl.default_device adb << " #{args}" adb << " #{@repl.default_package}" if @repl.default_package && package_dependent? adb << " 2>&1" # redirect stderr to stdout so that we can silence it adb end private def interactive? args == "shell" || args.start_with?("logcat") end def package_dependent? ["uninstall"].include?(args) end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/restart_command.rb
lib/replicant/commands/restart_command.rb
class RestartCommand < Command def description "restart ADB" end def run # Faster than kill-server, and also catches ADB instances launched by # IntelliJ. Moreover, start-server after kill-server sometimes makes the # server fail to start up unless you sleep for a second or so `killall adb` AdbCommand.new(@repl, "start-server").execute end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/clear_command.rb
lib/replicant/commands/clear_command.rb
class ClearCommand < Command def description "clear application data" end # TODO: this is not a very good argument validator def valid_args? args.present? || @repl.default_package end def usage "#{name} [com.example.package|<empty>(when default package is set)]" end def run package = args.present? ? args : @repl.default_package # Clear app data - cache, SharedPreferences, Databases AdbCommand.new(@repl, "shell su -c \"rm -r /data/data/#{package}/*\"").execute # Force application stop to recreate shared preferences, databases with new launch AdbCommand.new(@repl, "shell am force-stop #{package}").execute end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/devices_command.rb
lib/replicant/commands/devices_command.rb
class DevicesCommand < Command def description "print a list of connected devices" end def run adb = AdbCommand.new(@repl, "devices -l", :silent => true) device_lines = adb.execute.output.lines.to_a.reject do |line| line.strip.empty? || line.include?("daemon") || line.include?("List of devices") end device_lines.reject! { |l| l =~ /offline/ } device_ids = device_lines.map { |l| /([\S]+)\s+device/.match(l)[1] } device_products = device_lines.map { |l| /product:([\S]+)/.match(l).try(:[], 1) } device_names = device_lines.zip(device_ids).map do |l, id| /model:([\S]+)/.match(l).try(:[], 1) || detect_device_name(id) end device_indices = (1..device_ids.size).to_a devices = device_indices.zip(device_ids, device_names, device_products).map do |idx, id, name, product| Device.new(idx, id, humanize_name(name, product)) end output "" output devices_string(devices) output "" devices end private def detect_device_name(id) if id.start_with?("emulator-") "Android emulator" else "Unknown device" end end def humanize_name(name_string, product) if product == "vbox86p" "Genymotion " + name_string.gsub(/___[\d_]+___/, "_") else name_string end.gsub('_', ' ').squish end def devices_string(devices) device_string = if devices.any? padding = devices.map { |d| d.name.length }.max devices.map { |d| "[#{d.idx}] #{d.name}#{' ' * (padding - d.name.length)} | #{d.id}" }.join("\n") else "No devices found" end end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/package_command.rb
lib/replicant/commands/package_command.rb
class PackageCommand < Command def description "set a default package to work with" end def usage "#{name} com.mydomain.mypackage" end def valid_args? args.present? && /^\w+(\.\w+)*$/ =~ args end def run output "Setting default package to #{args.inspect}" @repl.default_package = args end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/reset_command.rb
lib/replicant/commands/reset_command.rb
class ResetCommand < Command def description "clear current device and package" end def valid_args? args.blank? end def run @repl.default_device = nil @repl.default_package = nil end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/device_command.rb
lib/replicant/commands/device_command.rb
class DeviceCommand < Command @@threads = [] def initialize(repl, args = nil, options = {}) super @process_muncher = ProcessMuncher.new(repl) @log_muncher = LogMuncher.new(repl) end def description "set a default device to work with" end def usage "#{name} [<index>|<device_id>]" end def valid_args? args.present? && /\S+/ =~ args end def run default_device = if index? && (1..devices.size).include?(args.to_i) # user selected by index devices[args.to_i - 1] else # user selected by device ID devices.detect { |d| d.id == args } end if default_device @repl.default_device = default_device output "Default device set to #{default_device.name}" # kill any existing threads putsd "Found #{@@threads.size} zombie threads, killing..." unless @@threads.empty? @@threads.select! { |t| t.exit } @@threads << @log_muncher.munch_logs do |logfile| observe_pid_changes(logfile) end output "Logs are available at #{LogMuncher::LOGFILE}" else output "No such device" end default_device end private def index? /^\d+$/ =~ args end def devices @devices ||= DevicesCommand.new(@repl, nil, :silent => true).execute end def observe_pid_changes(logfile) @@threads << @process_muncher.scan_pid do |new_pid| @log_muncher.current_pid = new_pid if new_pid log_state_change!(logfile, "#{@repl.default_package} (pid = #{new_pid})") else log_state_change!(logfile, "<all>") end end end def log_message!(o, message) o.puts "*" * Styles::CONSOLE_WIDTH o.puts " #{message}" o.puts "*" * Styles::CONSOLE_WIDTH o.flush end def log_state_change!(o, change) msg = "Detected change in device or target package\n" msg << "-" * Styles::CONSOLE_WIDTH msg << "\n --> device = #{@repl.default_device.name}" msg << "\n --> process = #{change}" log_message!(o, msg) end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
mttkay/replicant
https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/lib/replicant/commands/env_command.rb
lib/replicant/commands/env_command.rb
class EnvCommand < Command def valid_args? args.blank? end def run env = "Package: #{@repl.default_package || 'Not set'}\n" env << "Device: " device = @repl.default_device env << if device "#{device.name} (#{device.id})" else 'Not set' end output env end end
ruby
MIT
9ff97d9f6909c2ceee95f30c60c4369c46a18569
2026-01-04T17:52:45.776762Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/db/migrate/0_create_amounts.rb
db/migrate/0_create_amounts.rb
# Copyright 2015-2021, Instacart class CreateAmounts < ActiveRecord::Migration def change create_table :amounts do |t| t.integer :amountable_id, null: false t.string :amountable_type, null: false t.string :name, null: false t.timestamps end add_monetize :amounts, :value add_index :amounts, [:amountable_id, :amountable_type] ActiveRecord::Base.connection.execute("CLUSTER amounts USING index_amounts_on_amountable_id_and_amountable_type") if is_pg? end def is_pg? ActiveRecord::Base.connection.instance_values["config"][:adapter].include?('postgresql') end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/spec/spec_helper.rb
spec/spec_helper.rb
# Copyright 2015-2021, Instacart ENV['RAILS_ENV'] = 'test' require 'rails' require 'money-rails' require 'active_record' require 'activerecord-import' require 'amountable' Dir['./spec/support/**/*.rb'].sort.each { |f| require f } MoneyRails::Hooks.init require 'amountable/amount' require 'database_cleaner' require 'db-query-matchers' Money.locale_backend = :i18n Money.default_currency = "USD" RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| DatabaseCleaner.cleaning do example.run end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/spec/support/database.rb
spec/support/database.rb
# Copyright 2015-2021, Instacart require "activerecord-import/base" db_name = ENV['DB'] || 'postgresql' spec_dir = Pathname.new(File.dirname(__FILE__)) / '..' database_yml = spec_dir.join('internal/config/database.yml') fail "Please create #{database_yml} first to configure your database. Take a look at: #{database_yml}.sample" unless File.exist?(database_yml) ActiveRecord::Migration.verbose = false ActiveRecord.try(:default_timezone=, :utc) || ActiveRecord::Base.default_timezone = :utc ActiveRecord::Base.configurations = YAML.load_file(database_yml) ActiveRecord::Base.logger = Logger.new(File.join(__dir__, '../debug.log')) ActiveRecord::Base.logger.level = ENV['CI'] ? ::Logger::ERROR : ::Logger::DEBUG configs = ActiveRecord::Base.configurations config = configs.try(:find_db_config, db_name) || configs[db_name] begin ActiveRecord::Base.establish_connection(db_name.to_sym) ActiveRecord::Base.connection rescue case db_name when /mysql/ ActiveRecord::Base.establish_connection(config.merge('database' => nil)) ActiveRecord::Base.connection.create_database(config['database'], {charset: 'utf8', collation: 'utf8_unicode_ci'}) when 'postgresql' ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public')) ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => 'utf8')) end ActiveRecord::Base.establish_connection(config) end def jsonb_available? true end require_relative '../internal/db/schema' Dir[spec_dir.join('internal/app/models/*.rb')].each { |file| require_relative file }
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/spec/amountable/amount_spec.rb
spec/amountable/amount_spec.rb
# Copyright 2015-2021, Instacart require 'spec_helper' describe Amountable::Amount do it 'should validate name presence' do subject.tap do |amount| expect(amount.valid?).to be false expect(amount.errors[:name]).not_to be nil end end it 'should validate name uniqueness' do Amountable::Amount.new(name: 'test', amountable_id: 1, amountable_type: 'Amountable').tap do |amount| expect(amount.valid?).to be true amount.save Amountable::Amount.new(name: 'test', amountable_id: 2, amountable_type: 'Amountable').tap do |other_amount| expect(other_amount.valid?).to be true other_amount.amountable_id = amount.amountable_id expect(other_amount.valid?).to be false expect(amount.errors[:name]).not_to be nil end end end it 'should have operations' do expect(Amountable::Amount.new(value: Money.new(1)) + Amountable::Amount.new(value: Money.new(2))).to eq(Money.new(3)) expect(Amountable::Amount.new(value: Money.new(1)) + 0.02).to eq(Money.new(3)) expect(Amountable::Amount.new(value: Money.new(2)) - Amountable::Amount.new(value: Money.new(1))).to eq(Money.new(1)) expect(Amountable::Amount.new(value: Money.new(2)) - 0.01).to eq(Money.new(1)) expect(Amountable::Amount.new(value: Money.new(2)) * 3).to eq(Money.new(6)) expect(Amountable::Amount.new(value: Money.new(6)) / 3).to eq(Money.new(2)) expect(Amountable::Amount.new(value: Money.new(2)).to_money).to eq(Money.new(2)) end it 'should not save if not persistable' do expect { subject.new(persistable: false).save }.to raise_exception(StandardError) end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/spec/amountable/nil_amount_spec.rb
spec/amountable/nil_amount_spec.rb
# Copyright 2015-2021, Instacart require 'spec_helper' describe Amountable::NilAmount do it 'should return 0' do expect(subject.value).to eq(Money.zero) end it 'should have nil amountable' do expect(subject.amountable).to be nil end it 'should have operations' do expect(subject + Amountable::Amount.new(value: Money.new(2))).to eq(Money.new(2)) expect(subject + 0.02).to eq(Money.new(2)) expect(subject - Amountable::Amount.new(value: Money.new(1))).to eq(Money.new(-1)) expect(subject - 0.01).to eq(Money.new(-1)) expect(subject * 3).to eq(Money.zero) expect(subject / 3).to eq(Money.zero) expect(subject.to_money).to eq(Money.zero) end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/spec/amountable/amountable_spec.rb
spec/amountable/amountable_spec.rb
# Copyright 2015-2021, Instacart require 'spec_helper' describe Amountable do context 'storage == :table' do it 'should' do order = Order.new expect { order.save }.not_to change { Amountable::Amount.count } %i(sub_total taxes total).each do |name| expect(order.send(name)).to eq(Money.zero) end order.sub_total = Money.new(100) expect(order.sub_total).to eq(Money.new(100)) expect(order.total).to eq(Money.new(100)) expect(order.all_amounts.size).to eq(1) order.all_amounts.first.tap do |amount| expect(amount.name).to eq('sub_total') expect(amount.value).to eq(Money.new(100)) expect(amount.new_record?).to be true expect { order.save }.to change { Amountable::Amount.count }.by(1) expect(amount.persisted?).to be true end expect do expect(order.update(sub_total: Money.new(200))) end.not_to change { Amountable::Amount.count } end describe 'name=' do let (:order) { Order.create } it 'should not persist Money.zero' do expect(order.sub_total = Money.zero).to eq(Money.zero) expect { order.save }.not_to change { Amountable::Amount.count } end it 'should not persist Money.zero if using ActiveRecord persistence' do expect { order.update(sub_total: Money.zero) }.not_to change { Amountable::Amount.count } end it 'should work with ActiveRecord#update' do expect { order.update(sub_total: Money.new(1)) }.to change { Amountable::Amount.count }.by(1) end it 'should destroy Amount if exist and assigning Money.zero' do order.update(sub_total: Money.new(1)) expect { order.sub_total = Money.zero }.to change { Amountable::Amount.count }.by(-1) expect(order.amounts.empty?).to be true end end it 'should insert amounts in bulk' do order = Order.create expect do order.update(sub_total: Money.new(100), taxes: Money.new(200)) end.to make_database_queries(count: 1, manipulative: true) end end if jsonb_available? context 'storage == :jsonb' do it 'should' do subscription = Subscription.new expect { subscription.save }.not_to change { Amountable::Amount.count } expect(subscription.amounts).to eq(Set.new) expect(subscription.attributes['amounts']).to be_nil %i(sub_total taxes total).each do |name| expect(subscription.send(name)).to eq(Money.zero) end subscription.sub_total = Money.new(100) expect(subscription.sub_total).to eq(Money.new(100)) expect(subscription.attributes['amounts']).to eq({'amounts' => {'sub_total' => {'cents' => 100, 'currency' => 'USD'}}, 'sets' => {'total' => {'cents' => 100, 'currency' => 'USD'}}}) expect(subscription.total).to eq(Money.new(100)) expect(subscription.amounts.size).to eq(1) subscription.amounts.first.tap do |amount| expect(amount.name).to eq('sub_total') expect(amount.value).to eq(Money.new(100)) expect(amount.new_record?).to be true expect { subscription.save }.not_to change { Amountable::Amount.count } expect(amount.persisted?).to be false end subscription.update(sub_total: Money.new(200)) expect(subscription.sub_total).to eq(Money.new(200)) expect(subscription.total).to eq(Money.new(200)) subscription.sub_total = Money.zero expect(subscription.sub_total).to eq(Money.zero) expect(subscription.total).to eq(Money.zero) expect(subscription.attributes['amounts']).to eq({'amounts' => {}, 'sets' => {}}) end end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/spec/internal/app/models/subscription.rb
spec/internal/app/models/subscription.rb
# Copyright 2015-2021, Instacart if jsonb_available? class Subscription < ActiveRecord::Base include Amountable act_as_amountable storage: :jsonb amount :sub_total, sets: [:total] amount :taxes, sets: [:total] end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/spec/internal/app/models/order.rb
spec/internal/app/models/order.rb
# Copyright 2015-2021, Instacart class Order < ActiveRecord::Base include Amountable act_as_amountable amount :sub_total, sets: [:total] amount :taxes, sets: [:total] end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/spec/internal/db/schema.rb
spec/internal/db/schema.rb
# Copyright 2015-2021, Instacart ActiveRecord::Schema.define do create_table "amounts", force: :cascade do |t| t.integer "amountable_id", null: false t.string "amountable_type", null: false t.datetime "created_at" t.string "name", null: false t.datetime "updated_at" t.integer "value_cents", default: 0, null: false t.string "value_currency", default: "USD", null: false end add_index "amounts", ["amountable_id", "amountable_type"], name: "index_amounts_on_amountable_id_and_amountable_type", using: :btree create_table "orders", force: :cascade do |t| t.datetime "created_at" t.datetime "updated_at" end if jsonb_available? create_table "subscriptions", force: :cascade do |t| t.datetime "created_at" t.datetime "updated_at" t.jsonb "amounts" end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/lib/amountable.rb
lib/amountable.rb
# Copyright 2015-2021, Instacart module Amountable extend ActiveSupport::Autoload autoload :Operations autoload :Amount autoload :VirtualAmount autoload :NilAmount autoload :VERSION autoload :TableMethods autoload :JsonbMethods class InvalidAmountName < StandardError; end class MissingColumn < StandardError; end ALLOWED_STORAGE = %i(table json).freeze def self.included(base) base.extend Amountable::ActAsMethod end module InstanceMethods def all_amounts @all_amounts ||= amounts.to_set end def find_amount(name) (@amounts_by_name ||= {})[name.to_sym] ||= amounts.to_set.find { |am| am.name == name.to_s } end def find_amounts(names) amounts.to_set.select { |am| names.include?(am.name.to_sym) } end def validate_amount_names amounts.each do |amount| errors.add(:amounts, "#{amount.name} is not an allowed amount name.") unless self.class.allowed_amount_name?(amount.name) end end def serializable_hash(opts = nil) opts ||= {} super(opts).tap do |base| unless opts[:except].to_a.include?(:amounts) amounts_json = (self.class.amount_names + self.class.amount_sets.keys).inject({}) do |mem, name| mem.merge!(name.to_s => send(name).to_f) unless opts[:except].to_a.include?(name.to_sym) mem end base.merge!(amounts_json) end end end end module ActAsMethod # Possible storage values: [:table, :jsonb] def act_as_amountable(options = {}) self.extend Amountable::ClassMethod class_attribute :amount_names class_attribute :amount_sets class_attribute :amounts_column_name class_attribute :storage self.amount_sets = Hash.new { |h, k| h[k] = Set.new } self.amount_names = Set.new self.amounts_column_name = 'amounts' self.storage = (options[:storage] || :table).to_sym case self.storage when :table has_many :amounts, class_name: 'Amountable::Amount', as: :amountable, dependent: :destroy, autosave: false include Amountable::TableMethods when :jsonb self.amounts_column_name = options[:column].to_s if options[:column] include Amountable::JsonbMethods else raise ArgumentError.new("Please specify a storage: #{ALLOWED_STORAGE}") end validate :validate_amount_names include Amountable::InstanceMethods end end module ClassMethod def amount_set(set_name, component) self.amount_sets[set_name.to_sym] << component.to_sym define_method set_name do get_set(set_name) end end def amount(name, options = {}) (self.amount_names ||= Set.new) << name define_method name do (find_amount(name) || Amountable::NilAmount.new).value end define_method "#{name}=" do |value| set_amount(name, value) end Array(options[:summable] || options[:summables] || options[:set] || options[:sets] || options[:amount_set] || options[:amount_sets]).each do |set| amount_set(set, name) end end def allowed_amount_name?(name) self.amount_names.include?(name.to_sym) end def where(opts, *rest) return super unless opts.is_a?(Hash) if self.storage == :jsonb where_json(opts, *rest) else super end end ruby2_keywords :where if Module.private_method_defined?(:ruby2_keywords) def where_json(opts, *rest) values = [] query = opts.inject([]) do |mem, (column, value)| column = column.to_sym if column.in?(self.amount_names) || column.in?(self.amount_sets.keys) mem << "#{self.pg_json_field_access(column, :cents)} = '%s'" mem << "#{self.pg_json_field_access(column, :currency)} = '%s'" values << value.to_money.fractional values << value.to_money.currency.iso_code opts.delete(column) end mem end query = [query.join(' AND ')] + values where(query, *rest).where(opts, *rest) end ruby2_keywords :where_json if Module.private_method_defined?(:ruby2_keywords) def pg_json_field_access(name, field = :cents) name = name.to_sym group = if name.in?(self.amount_names) 'amounts' elsif name.in?(self.amount_sets.keys) 'sets' end "#{self.amounts_column_name}::json#>'{#{group},#{name},#{field}}'" end end end ActiveSupport.on_load(:active_record) do include Amountable end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/lib/amountable/version.rb
lib/amountable/version.rb
# Copyright 2015-2021, Instacart module Amountable VERSION = '0.6.0' end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/lib/amountable/jsonb_methods.rb
lib/amountable/jsonb_methods.rb
# Copyright 2015-2021, Instacart module Amountable module JsonbMethods extend ActiveSupport::Autoload def amounts @_amounts ||= attribute(amounts_column_name).to_h['amounts'].to_h.map do |name, amount| Amountable::VirtualAmount.new(name: name, value_cents: amount['cents'], value_currency: amount['currency'], persistable: false, amountable: self) end.to_set end def set_amount(name, value) value = value.to_money initialize_column amounts_json = attribute(amounts_column_name) amounts_json['amounts'] ||= {} if value.zero? amounts_json['amounts'].delete(name.to_s) else amounts_json['amounts'][name.to_s] = {'cents' => value.fractional, 'currency' => value.currency.iso_code} end set_json(amounts_json) @_amounts = nil @amounts_by_name = nil refresh_sets value end def refresh_sets initialize_column amounts_json = attribute(amounts_column_name) amounts_json['sets'] = {} amount_sets.each do |name, amount_names| sum = find_amounts(amount_names).sum(Money.zero, &:value) next if sum.zero? amounts_json['sets'][name.to_s] = {'cents' => sum.fractional, 'currency' => sum.currency.iso_code} end set_json(amounts_json) end def get_set(name) value = attribute(amounts_column_name).to_h['sets'].to_h[name.to_s].to_h Money.new(value['cents'].to_i, value['currency']) end def set_json(json) send("#{amounts_column_name}=", json) end def initialize_column send("#{amounts_column_name}=", {}) if attribute(amounts_column_name).nil? end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/lib/amountable/operations.rb
lib/amountable/operations.rb
# Copyright 2015-2021, Instacart module Amountable module Operations def +(other_value) value + other_value.to_money end def -(other_value) value - other_value.to_money end def *(multiplier) value * multiplier end def /(divisor) value / divisor end def to_money value end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/lib/amountable/table_methods.rb
lib/amountable/table_methods.rb
# Copyright 2015-2021, Instacart module Amountable module TableMethods extend ActiveSupport::Autoload def set_amount(name, value) amount = find_amount(name) || amounts.build(name: name) amount.value = value.to_money if value.zero? amounts.delete(amount) all_amounts.delete(amount) @amounts_by_name.delete(name) amount.destroy if amount.persisted? else all_amounts << amount if amount.new_record? (@amounts_by_name ||= {})[name.to_sym] = amount end amount.value end def save(**args) ActiveRecord::Base.transaction do save_amounts if super end end def save!(**args) ActiveRecord::Base.transaction do save_amounts! if super end end def save_amounts(bang: false) amounts_to_insert = [] amounts.each do |amount| if amount.new_record? amount.amountable_id = self.id amounts_to_insert << amount else bang ? amount.save! : amount.save end end Amount.import(amounts_to_insert, timestamps: true, validate: false) amounts_to_insert.each do |amount| amount.instance_variable_set(:@new_record, false) end true end def save_amounts!; save_amounts(bang: true); end def get_set(name) find_amounts(self.amount_sets[name.to_sym]).sum(Money.zero, &:value) end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/lib/amountable/virtual_amount.rb
lib/amountable/virtual_amount.rb
# Copyright 2015-2021, Instacart module Amountable class VirtualAmount include ActiveModel::Model attr_accessor :amountable, :value_cents, :value_currency, :name, :persistable include Amountable::Operations validates :name, presence: true def value Money.new(value_cents, value_currency) end def value=(val) self.value_cents = value.fractional self.value_currency = value.currency.iso_code end def new_record? true end def persisted? false end def save raise StandardError.new("Can't persist amount to database") if persistable == false super end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/lib/amountable/nil_amount.rb
lib/amountable/nil_amount.rb
# Copyright 2015-2021, Instacart module Amountable class NilAmount include Amountable::Operations def value; Money.zero; end def amountable; nil; end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
instacart/amountable
https://github.com/instacart/amountable/blob/5e035e0dafb4bfdd0cc13385708bfe37be17d2a1/lib/amountable/amount.rb
lib/amountable/amount.rb
# Copyright 2015-2021, Instacart module Amountable class Amount < ActiveRecord::Base include Amountable::Operations belongs_to :amountable, polymorphic: true monetize :value_cents, with_model_currency: :value_currency validates :name, presence: true validates :name, uniqueness: {scope: [:amountable_id, :amountable_type]} attr_accessor :persistable def save raise StandardError.new("Can't persist amount to database") if persistable == false super end end end
ruby
ISC
5e035e0dafb4bfdd0cc13385708bfe37be17d2a1
2026-01-04T17:52:50.153955Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/test/simple_config_test.rb
test/simple_config_test.rb
require 'test_helper' class SimpleConfigConfigTest < Test::Unit::TestCase def setup @config = SimpleConfig::Config.new end def test_dup_creates_deep_clone new_config = cascaded_test_config.dup new_config.configure do group :test_group do set :inner_key, 'new_foo' end set :test, 'new_test' end assert_equal 'test-setting', cascaded_test_config.test assert_equal 'some other value', cascaded_test_config.test_group.inner_key assert_equal 'new_test', new_config.test assert_equal 'new_foo', new_config.test_group.inner_key end def test_should_be_able_to_set_config_values @config.set(:var_one, 'hello world') assert_equal 'hello world', @config.get(:var_one) end def test_should_be_able_to_access_settings_using_method_access @config.set(:foo, 'bar') assert_equal 'bar', @config.foo end def test_should_raise_NoMethodError_if_setting_does_not_exist_when_using_method_access assert_raises(NoMethodError) { @config.some_non_existent_variable } end def test_should_return_nil_if_setting_does_not_exist_when_using_get assert_nil @config.get(:some_non_existent_variable) end def test_unset_should_delete_config_values @config.set(:foo, 'bar') assert_equal('bar', @config.foo) @config.unset(:foo) assert_raises(NoMethodError) { @config.foo } end def test_unset_should_return_deleted_value @config.set(:foo, 'bar') assert_equal('bar', @config.unset(:foo)) end def test_exists_should_return_whether_variable_isset assert(!@config.exists?(:foo)) @config.set(:foo, 'bar') assert(@config.exists?(:foo)) @config.unset(:foo) assert(!@config.exists?(:foo)) end def test_exists_should_consider_empty_values_as_set [nil, 0, ''].each do |empty_value| @config.set(:foo, empty_value) assert_equal(empty_value, @config.get(:foo)) assert(@config.exists?(:foo)) end end def test_should_return_a_new_group_as_a_separate_config group = @config.group(:test) assert_instance_of(SimpleConfig::Config, group) assert_not_equal @config, group end def test_should_return_an_existing_group group = @config.group(:test) assert_equal group, @config.group(:test) end def test_should_configure_group_with_supplied_block_when_given group = @config.group(:test) do set :group_var, 'value' end assert_equal 'value', group.group_var end def test_should_respond_to_methods_for_settings_and_groups @config.group(:grp) { set :foo, 'bar' } assert(@config.respond_to?(:grp)) assert(@config.grp.respond_to?(:foo)) end def test_should_not_overwrite_existing_methods object_id = @config.object_id @config.set :object_id, 'object_id' assert_equal object_id, @config.object_id end def test_should_load_and_parse_external_config_as_ruby_in_context_of_config_instance File.stubs(:read).with('external_config.rb').returns(ruby_code = stub('ruby')) @config.expects(:instance_eval).with(ruby_code, 'external_config.rb') @config.load('external_config.rb') end def test_should_laod_and_parse_external_config_as_yaml_in_context_of_config_instance parser = stub('YAMLParser') SimpleConfig::YAMLParser.stubs(:parse_contents_of_file).with('external_config.yml').returns(parser) parser.expects(:parse_into).with(@config) @config.load('external_config.yml') end def test_should_load_and_parse_external_config_as_yaml_if_config_file_has_full_yaml_extension parser = stub('YAMLParser') SimpleConfig::YAMLParser.expects(:parse_contents_of_file).with('external_config.yaml').returns(parser) parser.stubs(:parse_into) @config.load('external_config.yaml') end def test_should_load_and_parse_external_config_if_file_exists_when_if_exists_is_true File.stubs(:read).with('external_config.rb').returns(ruby_code = stub('ruby')) @config.expects(:instance_eval).with(ruby_code, 'external_config.rb') File.stubs(:exist?).with('external_config.rb').returns(true) @config.load('external_config.rb', :if_exists? => true) end def test_should_not_load_and_parse_external_config_if_file_does_not_exist_when_if_exists_is_true @config.expects(:instance_eval).never File.stubs(:exist?).with('external_config.rb').returns(false) @config.load('external_config.rb', :if_exists? => true) end def test_should_respond_to_to_hash assert @config.respond_to? :to_hash end def test_should_create_hash_for_top_level @config = cascaded_test_config hash = { :test => "test-setting", :test_group => { :inner_key => "some other value", :object => { :key1 => "value1" } } } assert_equal hash, @config.to_hash end def test_should_create_hash_for_second_level @config = cascaded_test_config hash = { :inner_key => "some other value", :object => { :key1 => "value1" } } assert_equal hash, @config.test_group.to_hash end def test_should_be_able_to_redefine_settings @config = cascaded_test_config @config.set(:test, "new-test-setting") assert_equal "new-test-setting", @config.test end def test_config_merge_hash config = SimpleConfig::Config.new config.merge!(:example => {:foo => 'bar', :baz => 'qux'}, :test => 'foo') assert_equal 'foo', config.test assert_equal 'bar', config.example.foo assert_equal 'qux', config.example.baz end def test_config_merge_hash_non_destructive new_config = cascaded_test_config.merge(:test_group => {:inner_key => 'bar'}, :test => 'qux') assert_equal 'test-setting', cascaded_test_config.test assert_equal 'some other value', cascaded_test_config.test_group.inner_key assert_equal 'qux', new_config.test assert_equal 'bar', new_config.test_group.inner_key end private def cascaded_test_config SimpleConfig.for :simple_config_test do set :test, "test-setting" group :test_group do set :inner_key, "some other value" set :object, { :key1 => "value1" } end end end end
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/test/test_helper.rb
test/test_helper.rb
require 'rubygems' require 'test/unit' require 'mocha' $:.unshift File.expand_path('../../lib', __FILE__) require 'simple_config'
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/test/yaml_parser_test.rb
test/yaml_parser_test.rb
require 'test_helper' class YAMLParserTest < Test::Unit::TestCase include SimpleConfig def setup @config = Config.new end def test_parsing_of_a_single_variable parser = YAMLParser.new({'foo' => 'bar'}.to_yaml) parser.parse_into(@config) assert_equal 'bar', @config.foo end def test_parsing_of_multiple_variables parser = YAMLParser.new({'foo' => 'bar', 'baz' => 'qux'}.to_yaml) parser.parse_into(@config) assert_equal 'bar', @config.foo assert_equal 'qux', @config.baz end def test_parsing_of_a_group_with_one_variable parser = YAMLParser.new({'group1' => {'foo' => 'bar'}}.to_yaml) parser.parse_into(@config) assert_equal 'bar', @config.group1.foo end def test_parsing_of_a_group_with_two_variables parser = YAMLParser.new({'group1' => {'foo' => 'bar', 'baz' => 'qux'}}.to_yaml) parser.parse_into(@config) assert_equal 'bar', @config.group1.foo assert_equal 'qux', @config.group1.baz end def test_parsing_of_a_nested_group parser = YAMLParser.new({'group1' => {'group2' => {'foo' => 'bar'}}}.to_yaml) parser.parse_into(@config) assert_equal 'bar', @config.group1.group2.foo end end class YAMLParserFromContentsOfFile < Test::Unit::TestCase include SimpleConfig def test_should_initialize_new_parser_from_contents_of_given_file File.stubs(:read).with('config.yml').returns(yaml_data = stub('yaml data')) YAMLParser.expects(:new).with(yaml_data).returns(parser = stub('YAMLParser')) assert_equal parser, YAMLParser.parse_contents_of_file('config.yml') end end
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/test/simple_config_functional_test.rb
test/simple_config_functional_test.rb
require 'test_helper' require 'fileutils' class SimpleConfigFunctionalTest < Test::Unit::TestCase def test_simple_config_with_top_level_settings config = SimpleConfig.for(:my_test) do set :var_one, 'foo' set :var_two, 'bar' end assert_equal 'foo', config.var_one assert_equal 'bar', config.var_two end def test_config_with_groups config = SimpleConfig.for(:my_test) do group :test_group do set :var_one, 'foo' end end assert_equal 'foo', config.test_group.var_one end def test_config_with_top_level_settings_and_groups config = SimpleConfig.for(:my_test) do group :test_group do set :var_one, 'foo' end set :var_two, 'bar' end assert_equal 'foo', config.test_group.var_one assert_equal 'bar', config.var_two end def test_config_with_nested_groups config = SimpleConfig.for(:my_test) do group :test_group do group :inner_group do set :var_one, 'foo' end end end assert_equal 'foo', config.test_group.inner_group.var_one end def test_config_with_externally_loaded_ruby_config sample_file = File.join(File.dirname(__FILE__), *%w[example.rb]) File.open(sample_file, "w") do |io| io << %( set :foo, 'bar' ) end config = SimpleConfig.for(:my_test) do load sample_file end assert_equal 'bar', config.foo FileUtils.rm_f(sample_file) end def test_config_with_externally_loaded_yaml_config sample_file = File.join(File.dirname(__FILE__), *%w[example.yml]) File.open(sample_file, "w") do |io| io << %( example: foo: bar baz: qux test: foo ) end config = SimpleConfig.for(:my_test) do load sample_file end assert_equal 'foo', config.test assert_equal 'bar', config.example.foo assert_equal 'qux', config.example.baz FileUtils.rm_f(sample_file) end def test_config_with_optional_external_config assert_nothing_raised do SimpleConfig.for(:my_test) do load "non_existent_file", :if_exists? => true end end end end
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/templates/configuration.rb
templates/configuration.rb
SimpleConfig.for :application do # Set here your global configuration. # All settings can be overwritten later per-environment. load File.join(Rails.root.to_s, "config", "settings", "application.rb"), :if_exists? => true # Per Environment settings. # At startup only the file matching current environment will be loaded. # Settings stored here will overwrite settings with the same name stored in application.rb load File.join(Rails.root.to_s, "config", "settings", "#{Rails.env}.rb"), :if_exists? => true # Local settings. It is designed as a place for you to override variables # specific to your own development environment. # Make sure your version control system ignores this file otherwise # you risk checking in a file that will override values in production load File.join(Rails.root.to_s, "config", "settings", "local.rb"), :if_exists? => true end
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/lib/simple_config.rb
lib/simple_config.rb
require 'simple_config/version' require 'simple_config/railtie' if defined?(Rails) module SimpleConfig class << self def for(config_name, &block) default_manager.for(config_name, &block) end def default_manager @default_manager ||= Manager.new end end class Manager def initialize @configs = {} end def for(config_name, &block) config = (@configs[config_name] ||= Config.new) config.configure(&block) if block_given? config end end class Config def initialize @groups = {} @settings = {} end def dup self.class.new.tap do |duplicate| duplicate.merge!(to_hash) end end def configure(&block) instance_eval(&block) end def group(name, &block) group = (@groups[name] ||= Config.new) group.configure(&block) if block_given? define_accessor(name) { group } group end def set(key, value) unset(key) if set?(key) define_accessor(key) { value } @settings[key] = value end def get(key) @settings[key] end # Unsets any variable with given +key+ # and returns variable value if it exists, nil otherwise. # Any successive call to exists? :key will return false. # # exists? :bar # => false # # set :bar, 'foo' # exists? :bar # => true # # unset :bar # => 'foo' # exists? :bar # => false # # @param [Symbol] The key to unset. # @return The current value for +:key+. def unset(key) singleton_class.send(:remove_method, key) @settings.delete(key) end # Returns whether a variable with given +key+ is set. # # Please note that this method doesn't care about variable value. # A nil variable is considered as set. # # exists? :bar # => false # # set :bar, 'foo' # exists? :bar # => true # # set :bar, nil # exists? :bar # => true # # Use unset to completely remove a variable from the collection. # # set :bar, 'foo' # exists? :bar # => true # # unset :bar # exists? :bar # => false # # @param [Symbol] The key to check. # @return [Boolean] True if the key is set. def exists?(key) @settings.key?(key) end def set?(key) @settings.key?(key) end def to_hash hash = @settings.dup @groups.each do |key,group| hash[key] = group.to_hash end hash end def merge!(hash) hash.each do |key, value| if value.is_a?(Hash) group(key.to_sym).merge!(value) else set(key.to_sym, value) end end self end def merge(hash) dup.merge!(hash) end def load(external_config_file, options={}) options = {:if_exists? => false}.merge(options) if options[:if_exists?] return unless File.exist?(external_config_file) end case File.extname(external_config_file) when /rb/ instance_eval(File.read(external_config_file), external_config_file.to_s) when /yml|yaml/ YAMLParser.parse_contents_of_file(external_config_file).parse_into(self) end end private def define_accessor(name, &block) singleton_class.class_eval { define_method(name, &block) } if !respond_to?(name) || exists?(name) end def singleton_class class << self self end end end class YAMLParser def initialize(raw_yaml_data) require 'yaml' @data = YAML.load(raw_yaml_data) end def self.parse_contents_of_file(yaml_file) new(File.read(yaml_file)) end def parse_into(config) config.merge!(@data) end end end
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/lib/simpleconfig.rb
lib/simpleconfig.rb
require 'simple_config'
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/lib/simple_config/version.rb
lib/simple_config/version.rb
module SimpleConfig module Version MAJOR = 2 MINOR = 0 PATCH = 1 BUILD = nil STRING = [MAJOR, MINOR, PATCH, BUILD].compact.join(".") end VERSION = Version::STRING end
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
lukeredpath/simpleconfig
https://github.com/lukeredpath/simpleconfig/blob/397963648bc12be92cd887aedd82d3a901a9c7b8/lib/simple_config/railtie.rb
lib/simple_config/railtie.rb
require 'simple_config' require 'rails' module SimpleConfig class Railtie < ::Rails::Railtie rake_tasks do namespace :simpleconfig do desc "Initialize SimpleConfig configurations." task :setup do abort("Already found config/settings. Have you already run this task?.") if File.exist?("config/settings") mkdir("config/settings") mkdir("config/initializers") unless File.exist?("config/initializers") environments = Dir["config/environments/*.rb"].map { |f| File.basename(f, ".rb") } environments << "application" environments.each { |env| touch("config/settings/#{env}.rb") } cp( File.expand_path("../../../templates/configuration.rb", __FILE__), "config/initializers/configuration.rb" ) end end end end end
ruby
MIT
397963648bc12be92cd887aedd82d3a901a9c7b8
2026-01-04T17:52:54.553590Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/init.rb
init.rb
Dir[File.join(File.expand_path("../vendor", __FILE__), "*")].each do |vendor| $:.unshift File.join(vendor, "lib") end require "push/heroku/cisaurus/cisaurus" require "push/heroku/command/push"
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/progress/spec/progress_spec.rb
vendor/progress/spec/progress_spec.rb
require File.dirname(__FILE__) + '/spec_helper.rb' describe Progress do let(:count){ 165 } before :each do @io = StringIO.new Progress.instance_variable_set(:@io, @io) def Progress.time_to_print?; true; end end def io_pop @io.seek(0) s = @io.read @io.truncate(0) @io.seek(0) s end def io_pop_no_eta io_pop.sub(/ \(ETA: \d+.\)$/, '') end def verify_output_before_step(i, count) io_pop.should =~ /#{Regexp.quote(i == 0 ? '......' : '%5.1f' % (i / count.to_f * 100.0))}/ end def verify_output_after_stop io_pop.should =~ /100\.0.*\n$/ end describe 'direct usage' do describe 'procedural' do it "should show valid output when called as Progress.start" do Progress.start('Test', count) count.times do |i| verify_output_before_step(i, count) Progress.step end Progress.stop verify_output_after_stop end it "should show valid output when called as Progress" do Progress('Test', count) count.times do |i| verify_output_before_step(i, count) Progress.step end Progress.stop verify_output_after_stop end it "should show valid output when called without title" do Progress(count) count.times do |i| verify_output_before_step(i, count) Progress.step end Progress.stop verify_output_after_stop end end describe 'block' do it "should show valid output when called as Progress.start" do Progress.start('Test', count) do count.times do |i| verify_output_before_step(i, count) Progress.step end end verify_output_after_stop end it "should show valid output when called as Progress" do Progress('Test', count) do count.times do |i| verify_output_before_step(i, count) Progress.step end end verify_output_after_stop end it "should show valid output when called without title" do Progress(count) do count.times do |i| verify_output_before_step(i, count) Progress.step end end verify_output_after_stop end end end describe 'integrity' do it "should not raise errors on extra Progress.stop" do proc{ 10.times_with_progress('10') do Progress.start 'simple' do Progress.start 'procedural' Progress.stop Progress.stop end Progress.stop end Progress.stop }.should_not raise_error end it "should return result from block" do Progress.start('Test') do 'qwerty' end.should == 'qwerty' end it "should return result from step" do Progress.start do Progress.step{ 'qwerty' }.should == 'qwerty' end end it "should return result from set" do Progress.start do Progress.set(1){ 'qwerty' }.should == 'qwerty' end end it "should return result from nested block" do [1, 2, 3].with_progress('a').map do |a| [1, 2, 3].with_progress('b').map do |b| a * b end end.should == [[1, 2, 3], [2, 4, 6], [3, 6, 9]] end it "should kill progress on cycle break" do 2.times do catch(:lalala) do 2.times_with_progress('A') do |a| io_pop.should == "A: ......\n" 2.times_with_progress('B') do |b| io_pop.should == "A: ...... > B: ......\n" throw(:lalala) end end end io_pop.should == "A: ......\n\n" end end [[2, 200], [20, 20], [200, 2]].each do |_a, _b| it "should allow enclosed progress [#{_a}, #{_b}]" do _a.times_with_progress('A') do |a| io_pop_no_eta.should == "A: #{a == 0 ? '......' : '%5.1f%%'}\n" % [a / _a.to_f * 100.0] _b.times_with_progress('B') do |b| io_pop_no_eta.should == "A: #{a == 0 && b == 0 ? '......' : '%5.1f%%'} > B: #{b == 0 ? '......' : '%5.1f%%'}\n" % [(a + b / _b.to_f) / _a.to_f * 100.0, b / _b.to_f * 100.0] end io_pop_no_eta.should == "A: %5.1f%% > B: 100.0%%\n" % [(a + 1) / _a.to_f * 100.0] end io_pop.should == "A: 100.0%\nA: 100.0%\n\n" end it "should not overlap outer progress if inner exceeds [#{_a}, #{_b}]" do _a.times_with_progress('A') do |a| io_pop_no_eta.should == "A: #{a == 0 ? '......' : '%5.1f%%'}\n" % [a / _a.to_f * 100.0] Progress.start('B', _b) do (_b * 2).times do |b| io_pop_no_eta.should == "A: #{a == 0 && b == 0 ? '......' : '%5.1f%%'} > B: #{b == 0 ? '......' : '%5.1f%%'}\n" % [(a + [b / _b.to_f, 1].min) / _a.to_f * 100.0, b / _b.to_f * 100.0] Progress.step end end io_pop_no_eta.should == "A: %5.1f%% > B: 200.0%%\n" % [(a + 1) / _a.to_f * 100.0] end io_pop.should == "A: 100.0%\nA: 100.0%\n\n" end it "should allow step with block to validly count custom progresses [#{_a}, #{_b}]" do a_step = 99 Progress.start('A', _a * 100) do io_pop_no_eta.should == "A: ......\n" _a.times do |a| Progress.step(a_step) do _b.times_with_progress('B') do |b| io_pop_no_eta.should == "A: #{a == 0 && b == 0 ? '......' : '%5.1f%%'} > B: #{b == 0 ? '......' : '%5.1f%%'}\n" % [(a * a_step + b / _b.to_f * a_step) / (_a * 100).to_f * 100.0, b / _b.to_f * 100.0] end io_pop_no_eta.should == "A: %5.1f%% > B: 100.0%\n" % [(a + 1) * a_step.to_f / (100.0 * _a.to_f) * 100.0] end io_pop_no_eta.should == "A: %5.1f%%\n" % [(a + 1) * a_step.to_f / (100.0 * _a.to_f) * 100.0] end Progress.step _a end io_pop.should == "A: 100.0%\nA: 100.0%\n\n" end end end describe Enumerable do before :each do @a = 0...1000 end describe 'with_progress' do it "should not break each" do with, without = [], [] @a.with_progress.each{ |n| with << n } @a.each{ |n| without << n } with.should == without end it "should not break find" do @a.with_progress('Hello').find{ |n| n == 100 }.should == @a.find{ |n| n == 100 } @a.with_progress('Hello').find{ |n| n == 10000 }.should == @a.find{ |n| n == 10000 } default = proc{ 'default' } @a.with_progress('Hello').find(default){ |n| n == 10000 }.should == @a.find(default){ |n| n == 10000 } end it "should not break map" do @a.with_progress('Hello').map{ |n| n * n }.should == @a.map{ |n| n * n } end it "should not break grep" do @a.with_progress('Hello').grep(100).should == @a.grep(100) end it "should not break each_cons" do without_progress = [] @a.each_cons(3){ |values| without_progress << values } with_progress = [] @a.with_progress('Hello').each_cons(3){ |values| with_progress << values } without_progress.should == with_progress end describe "with_progress.with_progress" do it "should not change existing instance" do wp = @a.with_progress('hello') proc{ wp.with_progress('world') }.should_not change(wp, :title) end it "should create new instance with different title when called on WithProgress" do wp = @a.with_progress('hello') wp_wp = wp.with_progress('world') wp.title.should == 'hello' wp_wp.title.should == 'world' wp_wp.should_not == wp wp_wp.enumerable.should == wp.enumerable end end describe "calls to each" do class CallsToEach include Enumerable COUNT = 100 end def init_calls_to_each @enum = CallsToEach.new @objects = 10.times.to_a @enum.should_receive(:each).once{ |&block| @objects.each(&block) } end it "should call each only one time for object with length" do init_calls_to_each @enum.should_receive(:length).and_return(10) got = [] @enum.with_progress.each{ |o| got << o }.should == @enum got.should == @objects end it "should call each only one time for object without length" do init_calls_to_each got = [] @enum.with_progress.each{ |o| got << o }.should == @enum got.should == @objects end it "should call each only one time for String" do @objects = ('a'..'z').map{ |c| "#{c}\n" } str = @objects.join('') str.should_not_receive(:length) str.should_receive(:each).once{ |&block| @objects.each(&block) } got = [] str.with_progress.each{ |o| got << o }.should == str got.should == @objects end end end end describe Integer do describe 'with times_with_progress' do it "should not break times" do ii = 0 count.times_with_progress('Test') do |i| i.should == ii ii += 1 end end it "should show valid output for each_with_progress" do count.times_with_progress('Test') do |i| verify_output_before_step(i, count) end verify_output_after_stop end it "should show valid output for each_with_progress without title" do count.times_with_progress do |i| verify_output_before_step(i, count) end verify_output_after_stop end end end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/progress/spec/spec_helper.rb
vendor/progress/spec/spec_helper.rb
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'rspec' require 'progress'
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/progress/lib/progress.rb
vendor/progress/lib/progress.rb
require 'singleton' require 'thread' # ==== Procedural example # Progress.start('Test', 1000) # 1000.times do # Progress.step do # # do something # end # end # Progress.stop # ==== Block example # Progress.start('Test', 1000) do # 1000.times do # Progress.step do # # do something # end # end # end # ==== Step must not always be one # symbols = [] # Progress.start('Input 100 symbols', 100) do # while symbols.length < 100 # input = gets.scan(/\S/) # symbols += input # Progress.step input.length # end # end # ==== Enclosed block example # [1, 2, 3].each_with_progress('1 2 3') do |one_of_1_2_3| # 10.times_with_progress('10') do |one_of_10| # sleep(0.001) # end # end class Progress include Singleton attr_accessor :title, :current, :total, :note attr_reader :current_step def initialize(title, total) if title.is_a?(Numeric) && total.nil? title, total = nil, title elsif total.nil? total = 1 end @title = title @current = 0.0 @total = total == 0.0 ? 1.0 : Float(total) end def step_if_blank if current == 0.0 && total == 1.0 self.current = 1.0 end end def to_f(inner) inner = [inner, 1.0].min if current_step inner *= current_step end (current + inner) / total end def step(steps) @current_step = steps yield ensure @current_step = nil end class << self # start progress indication def start(title = nil, total = nil) if levels.empty? @started_at = Time.now @eta = nil @semaphore = Mutex.new start_beeper end levels << new(title, total) print_message true if block_given? begin yield ensure stop end end end # step current progress by `num / den` def step(num = 1, den = 1, &block) if levels.last set(levels.last.current + Float(num) / den, &block) elsif block block.call end end # set current progress to `value` def set(value, &block) if levels.last ret = if block levels.last.step(value - levels.last.current, &block) end if levels.last levels.last.current = Float(value) end print_message self.note = nil ret elsif block block.call end end # stop progress def stop if levels.last if levels.last.step_if_blank || levels.length == 1 print_message true set_title nil end levels.pop if levels.empty? stop_beeper io.puts end end end # check in block of showing progress def running? !levels.empty? end # set note def note=(s) if levels.last levels.last.note = s end end # output progress as lines (not trying to stay on line) # Progress.lines = true attr_writer :lines # force highlight # Progress.highlight = true attr_writer :highlight private def levels @levels ||= [] end def io @io || $stderr end def io_tty? io.tty? || ENV['PROGRESS_TTY'] end def lines? @lines.nil? ? !io_tty? : @lines end def highlight? @highlight.nil? ? io_tty? : @highlight end def time_to_print? if !@previous || @previous < Time.now - 0.3 @previous = Time.now true end end def eta(completed) now = Time.now if now > @started_at && completed > 0 current_eta = @started_at + (now - @started_at) / completed @eta = @eta ? @eta + (current_eta - @eta) * (1 + completed) * 0.5 : current_eta seconds = @eta - now if seconds > 0 left = case seconds when 0...60 '%.0fs' % seconds when 60...3600 '%.1fm' % (seconds / 60) when 3600...86400 '%.1fh' % (seconds / 3600) else '%.1fd' % (seconds / 86400) end eta_string = " (ETA: #{left})" end end end def set_title(title) if io_tty? io.print "\e]0;#{title}\a" end end def lock(force) if force ? @semaphore.lock : @semaphore.try_lock begin yield ensure @semaphore.unlock end end end def start_beeper @beeper = Thread.new do loop do sleep 10 print_message unless Thread.current[:skip] end end end def stop_beeper @beeper.kill @beeper = nil end def restart_beeper if @beeper @beeper[:skip] = true @beeper.run @beeper[:skip] = false end end def print_message(force = false) lock force do restart_beeper if force || time_to_print? inner = 0 parts, parts_cl = [], [] levels.reverse.each do |level| inner = current = level.to_f(inner) value = current.zero? ? '......' : "#{'%5.1f' % (current * 100.0)}%" title = level.title ? "#{level.title}: " : nil if !highlight? || value == '100.0%' parts << "#{title}#{value}" else parts << "#{title}\e[1m#{value}\e[0m" end parts_cl << "#{title}#{value}" end eta_string = eta(inner) message = "#{parts.reverse * ' > '}#{eta_string}" message_cl = "#{parts_cl.reverse * ' > '}#{eta_string}" if note = levels.last && levels.last.note message << " - #{note}" message_cl << " - #{note}" end if lines? io.puts message else io << message << "\e[K\r" end set_title message_cl end end end end end require 'progress/enumerable' require 'progress/integer' require 'progress/active_record' module Kernel def Progress(title = nil, total = nil, &block) Progress.start(title, total, &block) end private :Progress end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/progress/lib/progress/active_record.rb
vendor/progress/lib/progress/active_record.rb
require 'progress' if defined?(ActiveRecord::Base) module ActiveRecord module BatchesWithProgress # run `find_each` with progress def find_each_with_progress(options = {}) Progress.start(name.tableize, count(options)) do find_each do |model| Progress.step do yield model end end end end # run `find_in_batches` with progress def find_in_batches_with_progress(options = {}) Progress.start(name.tableize, count(options)) do find_in_batches do |batch| Progress.step batch.length do yield batch end end end end end class Base extend BatchesWithProgress end end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/progress/lib/progress/with_progress.rb
vendor/progress/lib/progress/with_progress.rb
require 'progress' class Progress class WithProgress include Enumerable attr_reader :enumerable, :title # initialize with object responding to each, title and optional length # if block is provided, it is passed to each def initialize(enumerable, title, length = nil, &block) @enumerable, @title, @length = enumerable, title, length each(&block) if block end # each object with progress def each enumerable, length = case when @length [@enumerable, @length] when !@enumerable.respond_to?(:length) || @enumerable.is_a?(String) || (defined?(StringIO) && @enumerable.is_a?(StringIO)) || (defined?(TempFile) && @enumerable.is_a?(TempFile)) elements = @enumerable.each.to_a [elements, elements.length] else [@enumerable, @enumerable.length] end Progress.start(@title, length) do enumerable.each do |object| Progress.step do yield object end end @enumerable end end # returns self but changes title def with_progress(title = nil, length = nil, &block) self.class.new(@enumerable, title, length || @length, &block) end end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/progress/lib/progress/enumerable.rb
vendor/progress/lib/progress/enumerable.rb
require 'enumerator' require 'progress/with_progress' module Enumerable # run any Enumerable method with progress # methods which don't necessarily go through all items (like find, any? or all?) will not show 100% # ==== Example # [1, 2, 3].with_progress('Numbers').each do |number| # # code # end # # [1, 2, 3].with_progress('Numbers').each_cons(2) do |numbers| # # code # end # # (0...100).with_progress('Numbers').select do |numbers| # # code # end # # (0...100).with_progress('Numbers').all? do |numbers| # # code # end def with_progress(title = nil, length = nil, &block) Progress::WithProgress.new(self, title, length, &block) end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/progress/lib/progress/integer.rb
vendor/progress/lib/progress/integer.rb
require 'progress' class Integer # run `times` with progress # 100.times_with_progress('Numbers') do |number| # # code # end def times_with_progress(title = nil) Progress.start(title, self) do times do |i| Progress.step do yield i end end end end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/anvil/lib/anvil.rb
vendor/anvil/lib/anvil.rb
require "anvil/version" module Anvil def self.agent @@agent ||= "anvil-cli/#{Anvil::VERSION}" end def self.append_agent(str) @@agent = self.agent + " " + str end def self.headers @headers ||= {} end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/anvil/lib/anvil/version.rb
vendor/anvil/lib/anvil/version.rb
module Anvil VERSION = "0.16.0" end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/anvil/lib/anvil/manifest.rb
vendor/anvil/lib/anvil/manifest.rb
require "anvil/builder" require "anvil/helpers" require "net/http" require "net/https" require "pathname" require "rest_client" require "find" class Anvil::Manifest include Anvil::Helpers PUSH_THREAD_COUNT = 40 attr_reader :cache_url attr_reader :dir attr_reader :manifest def initialize(dir=nil, options={}) @dir = dir @ignore = options[:ignore] || [] @manifest = @dir ? directory_manifest(@dir, :ignore => @ignore) : {} @cache_url = options[:cache] end def build(options={}) uri = URI.parse("#{anvil_host}/manifest/build") if uri.scheme == "https" proxy = https_proxy else proxy = http_proxy end if proxy proxy_uri = URI.parse(proxy) http = Net::HTTP.new(uri.host, uri.port, proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password) else http = Net::HTTP.new(uri.host, uri.port) end if uri.scheme == "https" http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end if uri.scheme == "https" http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end req = Net::HTTP::Post.new uri.request_uri env = options[:env] || {} req.initialize_http_header "User-Agent" => Anvil.agent req["User-Agent"] = Anvil.agent Anvil.headers.each do |name, val| next if name.to_s.strip == "" req[name] = val.to_s end req.set_form_data({ "buildpack" => options[:buildpack], "cache" => @cache_url, "env" => json_encode(options[:env] || {}), "keepalive" => "1", "manifest" => self.to_json, "type" => options[:type] }) slug_url = nil http.request(req) do |res| slug_url = res["x-slug-url"] @cache_url = res["x-cache-url"] begin res.read_body do |chunk| yield chunk.gsub("\000\000\000", "") end rescue EOFError puts raise Anvil::Builder::BuildError, "terminated unexpectedly" end code = if res["x-exit-code"].nil? manifest_id = Array(res["x-manifest-id"]).first Integer(String.new(anvil["/exit/#{manifest_id}"].get.to_s)) else res["x-exit-code"].first.to_i end raise Anvil::Builder::BuildError, "exited #{code}" unless code.zero? end slug_url end def save res = anvil["/manifest"].post(:manifest => self.to_json) res.headers[:location] end def manifest_by_hash(manifest) manifest.inject({}) do |ax, (name, file)| ax.update file["hash"] => file.merge("name" => name) end end def missing mbh = manifest_by_hash(@manifest) json_decode(anvil["/manifest/diff"].post(:manifest => self.to_json).to_s).inject({}) do |ax, hash| ax.update hash => mbh[hash] end end def upload(missing, &blk) upload_hashes missing, &blk missing.length end def to_json json_encode(@manifest) end def add(filename) @manifest[filename] = file_manifest(filename) end private def anvil RestClient.proxy = ENV["HTTP_PROXY"] @anvil ||= RestClient::Resource.new(anvil_host, :headers => anvil_headers) end def anvil_headers { "User-Agent" => Anvil.agent } end def anvil_host ENV["ANVIL_HOST"] || "https://api.anvilworks.org" end def directory_manifest(dir, options={}) root = Pathname.new(dir) ignore = (options[:ignore] || []) + [".anvil", ".git"] if File.exists?("#{dir}/.slugignore") File.read("#{dir}/.slugignore").split("\n").each do |match| Dir["#{dir}/**/#{match}"].each do |ignored_file| ignore.push Pathname.new(ignored_file).relative_path_from(root).to_s end end end manifest = {} Find.find(dir) do |path| relative = Pathname.new(path).relative_path_from(root).to_s if File.directory?(path) Find.prune if ignore.include?(relative) || ignore.include?(relative + "/") next end next if ignore.include?(relative) next if %w( . .. ).include?(File.basename(path)) next if File.pipe?(path) next if path =~ /\.swp$/ next unless path =~ /^[A-Za-z0-9\-\_\.\/\:\@]*$/ manifest[relative] = file_manifest(path) end manifest end def file_manifest(file) stat = File.stat(file) manifest = { "mtime" => stat.mtime.to_i, "mode" => "%o" % stat.mode, "size" => stat.size.to_s } if File.symlink?(file) manifest["link"] = File.readlink(file) else manifest["hash"] = calculate_hash(file) end manifest end def calculate_hash(filename) Digest::SHA2.hexdigest(File.open(filename, "rb").read) end def upload_file(filename, hash=nil) hash ||= calculate_hash(filename) anvil["/file/#{hash}"].post :data => File.new(filename, "rb") hash rescue RestClient::Forbidden => ex error "error uploading #{filename}: #{ex.http_body}" end def upload_hashes(hashes, &blk) mbh = manifest_by_hash(@manifest) filenames_by_hash = @manifest.inject({}) do |ax, (name, file_manifest)| ax.update file_manifest["hash"] => File.join(@dir.to_s, name) end bucket_hashes = hashes.inject({}) do |ax, hash| index = hash.hash % PUSH_THREAD_COUNT ax[index] ||= [] ax[index] << hash ax end threads = bucket_hashes.values.map do |hashes| Thread.new do hashes.each do |hash| upload_file filenames_by_hash[hash], hash blk.call mbh[hash] end end end threads.each(&:join) end def http_proxy proxy = ENV['HTTP_PROXY'] || ENV['http_proxy'] if proxy && !proxy.empty? unless /^[^:]+:\/\// =~ proxy proxy = "http://" + proxy end proxy else nil end end def https_proxy proxy = ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV["HTTP_PROXY"] || ENV["http_proxy"] if proxy && !proxy.empty? unless /^[^:]+:\/\// =~ proxy proxy = "https://" + proxy end proxy else nil end end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/anvil/lib/anvil/helpers.rb
vendor/anvil/lib/anvil/helpers.rb
require "anvil" require "anvil/okjson" module Anvil::Helpers def json_encode(obj) Anvil::OkJson.encode(obj) end def json_decode(str) Anvil::OkJson.decode(str) end def anvil_metadata_dir(root) dir = File.join(root, ".anvil") FileUtils.mkdir_p(dir) dir end def is_url?(string) URI.parse(string).scheme rescue nil end def read_anvil_metadata(root, name) return nil if is_url?(root) File.open(File.join(anvil_metadata_dir(root), name)).read.chomp rescue nil end def write_anvil_metadata(root, name, data) return if is_url?(root) File.open(File.join(anvil_metadata_dir(root), name), "w") do |file| file.puts data end end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/anvil/lib/anvil/cli.rb
vendor/anvil/lib/anvil/cli.rb
require "anvil" require "anvil/builder" require "anvil/engine" require "anvil/manifest" require "anvil/version" require "progress" require "thor" require "uri" class Anvil::CLI < Thor map ["-v", "--version"] => :version desc "build [SOURCE]", "Build an application" method_option :buildpack, :type => :string, :aliases => "-b", :desc => "Use a specific buildpack" method_option :pipeline, :type => :boolean, :aliases => "-p", :desc => "Pipe build output to stderr and put the slug url on stdout" method_option :type, :type => :string, :aliases => "-t", :desc => "Build a specific slug type (tgz, deb)" def build(source=nil) Anvil::Engine.build(source, options) rescue Anvil::Builder::BuildError => ex error "Build Error: #{ex.message}" end desc "version", "Display Anvil version" def version Anvil::Engine.version end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/anvil/lib/anvil/builder.rb
vendor/anvil/lib/anvil/builder.rb
require "anvil" require "anvil/helpers" require "net/http" require "net/https" require "rest_client" class Anvil::Builder include Anvil::Helpers class BuildError < StandardError; end attr_reader :source def initialize(source) @source = source end def build(options={}) uri = URI.parse("#{anvil_host}/build") if uri.scheme == "https" proxy = https_proxy else proxy = http_proxy end if proxy proxy_uri = URI.parse(proxy) http = Net::HTTP.new(uri.host, uri.port, proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password) else http = Net::HTTP.new(uri.host, uri.port) end if uri.scheme == "https" http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end req = Net::HTTP::Post.new uri.request_uri req.initialize_http_header "User-Agent" => Anvil.agent Anvil.headers.each do |name, val| next if name.to_s.strip == "" req.initialize_http_header name => val.to_s end req.set_form_data({ "buildpack" => options[:buildpack], "cache" => options[:cache], "env" => json_encode(options[:env] || {}), "source" => source, "type" => options[:type] }) slug_url = nil http.request(req) do |res| slug_url = res["x-slug-url"] begin res.read_body do |chunk| yield chunk end rescue EOFError puts raise BuildError, "terminated unexpectedly" end manifest_id = [res["x-manifest-id"]].flatten.first code = Integer(String.new(anvil["/exit/#{manifest_id}"].get.to_s)) raise BuildError, "exited #{code}" unless code.zero? end slug_url end private def anvil @anvil ||= RestClient::Resource.new(anvil_host, :headers => anvil_headers) end def anvil_headers { "User-Agent" => Anvil.agent } end def anvil_host ENV["ANVIL_HOST"] || "https://api.anvilworks.org" end def http_proxy proxy = ENV['HTTP_PROXY'] || ENV['http_proxy'] if proxy && !proxy.empty? unless /^[^:]+:\/\// =~ proxy proxy = "http://" + proxy end proxy else nil end end def https_proxy proxy = ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV["HTTP_PROXY"] || ENV["http_proxy"] if proxy && !proxy.empty? unless /^[^:]+:\/\// =~ proxy proxy = "https://" + proxy end proxy else nil end end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/anvil/lib/anvil/engine.rb
vendor/anvil/lib/anvil/engine.rb
require "anvil" require "anvil/builder" require "anvil/helpers" require "anvil/manifest" require "anvil/version" require "progress" require "thread" require "uri" class Anvil::Engine extend Anvil::Helpers def self.build(source, options={}) if options[:pipeline] old_stdout = $stdout.dup $stdout = $stderr end source ||= "." buildpack = options[:buildpack] || read_anvil_metadata(source, "buildpack") build_options = { :buildpack => prepare_buildpack(buildpack), :type => options[:type] || "tgz" } builder = if is_url?(source) Anvil::Builder.new(source) else manifest = Anvil::Manifest.new(File.expand_path(source), :cache => read_anvil_metadata(source, "cache"), :ignore => options[:ignore]) upload_missing manifest manifest end slug_url = builder.build(build_options) do |chunk| print chunk end unless is_url?(source) write_anvil_metadata source, "buildpack", buildpack write_anvil_metadata source, "cache", manifest.cache_url end old_stdout.puts slug_url if options[:pipeline] slug_url end def self.version puts Anvil::VERSION end def self.prepare_buildpack(buildpack) buildpack = buildpack.to_s if buildpack == "" buildpack elsif is_url?(buildpack) buildpack elsif buildpack =~ /\A\w+\/\w+\Z/ "http://codon-buildpacks.s3.amazonaws.com/buildpacks/#{buildpack}.tgz" elsif File.exists?(buildpack) && File.directory?(buildpack) manifest = Anvil::Manifest.new(buildpack) upload_missing manifest, "buildpack" manifest.save else raise Anvil::Builder::BuildError.new("unrecognized buildpack specification: #{buildpack}") end end def self.upload_missing(manifest, title="app") print "Checking for #{title} files to sync... " missing = manifest.missing puts "done, #{missing.length} files needed" return if missing.length.zero? queue = Queue.new total_size = missing.map { |hash, file| file["size"].to_i }.inject(&:+) display = Thread.new do Progress.start "Uploading", total_size while (msg = queue.pop).first != :done case msg.first when :step then Progress.step msg.last.to_i end end Progress.stop end if missing.length > 0 manifest.upload(missing.keys) do |file| queue << [:step, file["size"].to_i] end queue << [:done, nil] end display.join end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/vendor/anvil/lib/anvil/okjson.rb
vendor/anvil/lib/anvil/okjson.rb
# encoding: UTF-8 # # Copyright 2011, 2012 Keith Rarick # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # See https://github.com/kr/okjson for updates. require 'stringio' # Some parts adapted from # http://golang.org/src/pkg/json/decode.go and # http://golang.org/src/pkg/utf8/utf8.go module Anvil module OkJson extend self # Decodes a json document in string s and # returns the corresponding ruby value. # String s must be valid UTF-8. If you have # a string in some other encoding, convert # it first. # # String values in the resulting structure # will be UTF-8. def decode(s) ts = lex(s) v, ts = textparse(ts) if ts.length > 0 raise Error, 'trailing garbage' end v end # Parses a "json text" in the sense of RFC 4627. # Returns the parsed value and any trailing tokens. # Note: this is almost the same as valparse, # except that it does not accept atomic values. def textparse(ts) if ts.length < 0 raise Error, 'empty' end typ, _, val = ts[0] case typ when '{' then objparse(ts) when '[' then arrparse(ts) else raise Error, "unexpected #{val.inspect}" end end # Parses a "value" in the sense of RFC 4627. # Returns the parsed value and any trailing tokens. def valparse(ts) if ts.length < 0 raise Error, 'empty' end typ, _, val = ts[0] case typ when '{' then objparse(ts) when '[' then arrparse(ts) when :val,:str then [val, ts[1..-1]] else raise Error, "unexpected #{val.inspect}" end end # Parses an "object" in the sense of RFC 4627. # Returns the parsed value and any trailing tokens. def objparse(ts) ts = eat('{', ts) obj = {} if ts[0][0] == '}' return obj, ts[1..-1] end k, v, ts = pairparse(ts) obj[k] = v if ts[0][0] == '}' return obj, ts[1..-1] end loop do ts = eat(',', ts) k, v, ts = pairparse(ts) obj[k] = v if ts[0][0] == '}' return obj, ts[1..-1] end end end # Parses a "member" in the sense of RFC 4627. # Returns the parsed values and any trailing tokens. def pairparse(ts) (typ, _, k), ts = ts[0], ts[1..-1] if typ != :str raise Error, "unexpected #{k.inspect}" end ts = eat(':', ts) v, ts = valparse(ts) [k, v, ts] end # Parses an "array" in the sense of RFC 4627. # Returns the parsed value and any trailing tokens. def arrparse(ts) ts = eat('[', ts) arr = [] if ts[0][0] == ']' return arr, ts[1..-1] end v, ts = valparse(ts) arr << v if ts[0][0] == ']' return arr, ts[1..-1] end loop do ts = eat(',', ts) v, ts = valparse(ts) arr << v if ts[0][0] == ']' return arr, ts[1..-1] end end end def eat(typ, ts) if ts[0][0] != typ raise Error, "expected #{typ} (got #{ts[0].inspect})" end ts[1..-1] end # Scans s and returns a list of json tokens, # excluding white space (as defined in RFC 4627). def lex(s) ts = [] while s.length > 0 typ, lexeme, val = tok(s) if typ == nil raise Error, "invalid character at #{s[0,10].inspect}" end if typ != :space ts << [typ, lexeme, val] end s = s[lexeme.length..-1] end ts end # Scans the first token in s and # returns a 3-element list, or nil # if s does not begin with a valid token. # # The first list element is one of # '{', '}', ':', ',', '[', ']', # :val, :str, and :space. # # The second element is the lexeme. # # The third element is the value of the # token for :val and :str, otherwise # it is the lexeme. def tok(s) case s[0] when ?{ then ['{', s[0,1], s[0,1]] when ?} then ['}', s[0,1], s[0,1]] when ?: then [':', s[0,1], s[0,1]] when ?, then [',', s[0,1], s[0,1]] when ?[ then ['[', s[0,1], s[0,1]] when ?] then [']', s[0,1], s[0,1]] when ?n then nulltok(s) when ?t then truetok(s) when ?f then falsetok(s) when ?" then strtok(s) when Spc then [:space, s[0,1], s[0,1]] when ?\t then [:space, s[0,1], s[0,1]] when ?\n then [:space, s[0,1], s[0,1]] when ?\r then [:space, s[0,1], s[0,1]] else numtok(s) end end def nulltok(s); s[0,4] == 'null' ? [:val, 'null', nil] : [] end def truetok(s); s[0,4] == 'true' ? [:val, 'true', true] : [] end def falsetok(s); s[0,5] == 'false' ? [:val, 'false', false] : [] end def numtok(s) m = /-?([1-9][0-9]+|[0-9])([.][0-9]+)?([eE][+-]?[0-9]+)?/.match(s) if m && m.begin(0) == 0 if m[3] && !m[2] [:val, m[0], Integer(m[1])*(10**Integer(m[3][1..-1]))] elsif m[2] [:val, m[0], Float(m[0])] else [:val, m[0], Integer(m[0])] end else [] end end def strtok(s) m = /"([^"\\]|\\["\/\\bfnrt]|\\u[0-9a-fA-F]{4})*"/.match(s) if ! m raise Error, "invalid string literal at #{abbrev(s)}" end [:str, m[0], unquote(m[0])] end def abbrev(s) t = s[0,10] p = t['`'] t = t[0,p] if p t = t + '...' if t.length < s.length '`' + t + '`' end # Converts a quoted json string literal q into a UTF-8-encoded string. # The rules are different than for Ruby, so we cannot use eval. # Unquote will raise an error if q contains control characters. def unquote(q) q = q[1...-1] a = q.dup # allocate a big enough string rubydoesenc = false # In ruby >= 1.9, a[w] is a codepoint, not a byte. if a.class.method_defined?(:force_encoding) a.force_encoding('UTF-8') rubydoesenc = true end r, w = 0, 0 while r < q.length c = q[r] case true when c == ?\\ r += 1 if r >= q.length raise Error, "string literal ends with a \"\\\": \"#{q}\"" end case q[r] when ?",?\\,?/,?' a[w] = q[r] r += 1 w += 1 when ?b,?f,?n,?r,?t a[w] = Unesc[q[r]] r += 1 w += 1 when ?u r += 1 uchar = begin hexdec4(q[r,4]) rescue RuntimeError => e raise Error, "invalid escape sequence \\u#{q[r,4]}: #{e}" end r += 4 if surrogate? uchar if q.length >= r+6 uchar1 = hexdec4(q[r+2,4]) uchar = subst(uchar, uchar1) if uchar != Ucharerr # A valid pair; consume. r += 6 end end end if rubydoesenc a[w] = '' << uchar w += 1 else w += ucharenc(a, w, uchar) end else raise Error, "invalid escape char #{q[r]} in \"#{q}\"" end when c == ?", c < Spc raise Error, "invalid character in string literal \"#{q}\"" else # Copy anything else byte-for-byte. # Valid UTF-8 will remain valid UTF-8. # Invalid UTF-8 will remain invalid UTF-8. # In ruby >= 1.9, c is a codepoint, not a byte, # in which case this is still what we want. a[w] = c r += 1 w += 1 end end a[0,w] end # Encodes unicode character u as UTF-8 # bytes in string a at position i. # Returns the number of bytes written. def ucharenc(a, i, u) case true when u <= Uchar1max a[i] = (u & 0xff).chr 1 when u <= Uchar2max a[i+0] = (Utag2 | ((u>>6)&0xff)).chr a[i+1] = (Utagx | (u&Umaskx)).chr 2 when u <= Uchar3max a[i+0] = (Utag3 | ((u>>12)&0xff)).chr a[i+1] = (Utagx | ((u>>6)&Umaskx)).chr a[i+2] = (Utagx | (u&Umaskx)).chr 3 else a[i+0] = (Utag4 | ((u>>18)&0xff)).chr a[i+1] = (Utagx | ((u>>12)&Umaskx)).chr a[i+2] = (Utagx | ((u>>6)&Umaskx)).chr a[i+3] = (Utagx | (u&Umaskx)).chr 4 end end def hexdec4(s) if s.length != 4 raise Error, 'short' end (nibble(s[0])<<12) | (nibble(s[1])<<8) | (nibble(s[2])<<4) | nibble(s[3]) end def subst(u1, u2) if Usurr1 <= u1 && u1 < Usurr2 && Usurr2 <= u2 && u2 < Usurr3 return ((u1-Usurr1)<<10) | (u2-Usurr2) + Usurrself end return Ucharerr end def surrogate?(u) Usurr1 <= u && u < Usurr3 end def nibble(c) case true when ?0 <= c && c <= ?9 then c.ord - ?0.ord when ?a <= c && c <= ?z then c.ord - ?a.ord + 10 when ?A <= c && c <= ?Z then c.ord - ?A.ord + 10 else raise Error, "invalid hex code #{c}" end end # Encodes x into a json text. It may contain only # Array, Hash, String, Numeric, true, false, nil. # (Note, this list excludes Symbol.) # X itself must be an Array or a Hash. # No other value can be encoded, and an error will # be raised if x contains any other value, such as # Nan, Infinity, Symbol, and Proc, or if a Hash key # is not a String. # Strings contained in x must be valid UTF-8. def encode(x) case x when Hash then objenc(x) when Array then arrenc(x) else raise Error, 'root value must be an Array or a Hash' end end def valenc(x) case x when Hash then objenc(x) when Array then arrenc(x) when String then strenc(x) when Numeric then numenc(x) when true then "true" when false then "false" when nil then "null" else raise Error, "cannot encode #{x.class}: #{x.inspect}" end end def objenc(x) '{' + x.map{|k,v| keyenc(k) + ':' + valenc(v)}.join(',') + '}' end def arrenc(a) '[' + a.map{|x| valenc(x)}.join(',') + ']' end def keyenc(k) case k when String then strenc(k) else raise Error, "Hash key is not a string: #{k.inspect}" end end def strenc(s) t = StringIO.new t.putc(?") r = 0 # In ruby >= 1.9, s[r] is a codepoint, not a byte. rubydoesenc = s.class.method_defined?(:encoding) while r < s.length case s[r] when ?" then t.print('\\"') when ?\\ then t.print('\\\\') when ?\b then t.print('\\b') when ?\f then t.print('\\f') when ?\n then t.print('\\n') when ?\r then t.print('\\r') when ?\t then t.print('\\t') else c = s[r] case true when rubydoesenc begin c.ord # will raise an error if c is invalid UTF-8 t.write(c) rescue t.write(Ustrerr) end when Spc <= c && c <= ?~ t.putc(c) else n = ucharcopy(t, s, r) # ensure valid UTF-8 output r += n - 1 # r is incremented below end end r += 1 end t.putc(?") t.string end def numenc(x) if ((x.nan? || x.infinite?) rescue false) raise Error, "Numeric cannot be represented: #{x}" end "#{x}" end # Copies the valid UTF-8 bytes of a single character # from string s at position i to I/O object t, and # returns the number of bytes copied. # If no valid UTF-8 char exists at position i, # ucharcopy writes Ustrerr and returns 1. def ucharcopy(t, s, i) n = s.length - i raise Utf8Error if n < 1 c0 = s[i].ord # 1-byte, 7-bit sequence? if c0 < Utagx t.putc(c0) return 1 end raise Utf8Error if c0 < Utag2 # unexpected continuation byte? raise Utf8Error if n < 2 # need continuation byte c1 = s[i+1].ord raise Utf8Error if c1 < Utagx || Utag2 <= c1 # 2-byte, 11-bit sequence? if c0 < Utag3 raise Utf8Error if ((c0&Umask2)<<6 | (c1&Umaskx)) <= Uchar1max t.putc(c0) t.putc(c1) return 2 end # need second continuation byte raise Utf8Error if n < 3 c2 = s[i+2].ord raise Utf8Error if c2 < Utagx || Utag2 <= c2 # 3-byte, 16-bit sequence? if c0 < Utag4 u = (c0&Umask3)<<12 | (c1&Umaskx)<<6 | (c2&Umaskx) raise Utf8Error if u <= Uchar2max t.putc(c0) t.putc(c1) t.putc(c2) return 3 end # need third continuation byte raise Utf8Error if n < 4 c3 = s[i+3].ord raise Utf8Error if c3 < Utagx || Utag2 <= c3 # 4-byte, 21-bit sequence? if c0 < Utag5 u = (c0&Umask4)<<18 | (c1&Umaskx)<<12 | (c2&Umaskx)<<6 | (c3&Umaskx) raise Utf8Error if u <= Uchar3max t.putc(c0) t.putc(c1) t.putc(c2) t.putc(c3) return 4 end raise Utf8Error rescue Utf8Error t.write(Ustrerr) return 1 end class Utf8Error < ::StandardError end class Error < ::StandardError end Utagx = 0x80 # 1000 0000 Utag2 = 0xc0 # 1100 0000 Utag3 = 0xe0 # 1110 0000 Utag4 = 0xf0 # 1111 0000 Utag5 = 0xF8 # 1111 1000 Umaskx = 0x3f # 0011 1111 Umask2 = 0x1f # 0001 1111 Umask3 = 0x0f # 0000 1111 Umask4 = 0x07 # 0000 0111 Uchar1max = (1<<7) - 1 Uchar2max = (1<<11) - 1 Uchar3max = (1<<16) - 1 Ucharerr = 0xFFFD # unicode "replacement char" Ustrerr = "\xef\xbf\xbd" # unicode "replacement char" Usurrself = 0x10000 Usurr1 = 0xd800 Usurr2 = 0xdc00 Usurr3 = 0xe000 Spc = ' '[0] Unesc = {?b=>?\b, ?f=>?\f, ?n=>?\n, ?r=>?\r, ?t=>?\t} end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/lib/push/heroku/command/push.rb
lib/push/heroku/command/push.rb
require "anvil" require "anvil/engine" require "cgi" require "digest/sha2" require "heroku/command/base" require "net/https" require "pathname" require "progress" require "tmpdir" require "uri" # deploy code # class Heroku::Command::Push < Heroku::Command::Base # push [SOURCE] # # deploy code to heroku # # if SOURCE is a local directory, the contents of the directory will be built # if SOURCE is a git URL, the contents of the repo will be built # if SOURCE is a tarball URL, the contents of the tarball will be built # # SOURCE will default to "." # # -b, --buildpack URL # use a custom buildpack # def index source = shift_argument || "." validate_arguments! release_to = app # validate that we have an app user = api.post_login("", Heroku::Auth.password).body["email"] Anvil.append_agent "(heroku-push)" Anvil.headers["X-Heroku-User"] = user Anvil.headers["X-Heroku-App"] = release_to slug_url = Anvil::Engine.build source, :buildpack => options[:buildpack], :ignore => process_gitignore(source) action("Releasing to #{app}") do cisaurus = Cisaurus.new(Heroku::Auth.password) release = cisaurus.release(app, "Pushed by #{user}", slug_url) { print "." $stdout.flush } status release["release"] end rescue Anvil::Builder::BuildError => ex puts "ERROR: Build failed, #{ex.message}" exit 1 end private def is_url?(string) URI.parse(string).scheme rescue nil end def prepare_buildpack(buildpack) if buildpack == "" buildpack elsif is_url?(buildpack) buildpack elsif buildpack =~ /\A\w+\/\w+\Z/ "http://buildkits-dev.s3.amazonaws.com/buildpacks/#{buildpack}.tgz" elsif File.exists?(buildpack) && File.directory?(buildpack) print "Uploading buildpack... " manifest = Anvil::Manifest.new(buildpack) manifest.upload manifest.save puts "done" else error "unrecognized buildpack specification: #{buildpack}" end end def process_gitignore(source) return [] if is_url?(source) return [] unless File.exists?("#{source}/.git") Dir.chdir(source) do %x{ git ls-files --others -i --exclude-standard }.split("\n") end end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
ddollar/heroku-push
https://github.com/ddollar/heroku-push/blob/969cfedfaa28ee3774c4d6ff8528992eae597770/lib/push/heroku/cisaurus/cisaurus.rb
lib/push/heroku/cisaurus/cisaurus.rb
require "json" class Cisaurus CISAURUS_CLIENT_VERSION = "0.7-ALPHA" CISAURUS_HOST = ENV['CISAURUS_HOST'] || "cisaurus.heroku.com" def initialize(api_key, host = CISAURUS_HOST, api_version = "v1") protocol = (host.start_with? "localhost") ? "http" : "https" RestClient.proxy = case protocol when "http" http_proxy when "https" https_proxy end @base_url = "#{protocol}://:#{api_key}@#{host}" @ver_url = "#{@base_url}/#{api_version}" end def downstreams(app, depth=nil) JSON.parse RestClient.get pipeline_resource(app, "downstreams"), options(params :depth => depth) end def addDownstream(app, ds) RestClient.post pipeline_resource(app, "downstreams", ds), "", options end def removeDownstream(app, ds) RestClient.delete pipeline_resource(app, "downstreams", ds), options end def diff(app) JSON.parse RestClient.get pipeline_resource(app, "diff"), options end def promote(app, interval = 2) response = RestClient.post pipeline_resource(app, "promote"), "", options while response.code == 202 response = RestClient.get @base_url + response.headers[:location], options sleep(interval) yield end JSON.parse response end def release(app, description, slug_url, interval = 2) payload = {:description => description, :slug_url => slug_url} extras = {:content_type => :json, :accept => :json} response = RestClient.post app_resource(app, "release"), JSON.generate(payload), options(extras) while response.code == 202 response = RestClient.get @base_url + response.headers[:location], options(extras) sleep(interval) yield end JSON.parse response end private def app_resource(app, *extras) "#{@ver_url}/" + extras.unshift("apps/#{app}").join("/") end def http_proxy proxy = ENV['HTTP_PROXY'] || ENV['http_proxy'] if proxy && !proxy.empty? unless /^[^:]+:\/\// =~ proxy proxy = "http://" + proxy end proxy else nil end end def https_proxy proxy = ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV["HTTP_PROXY"] || ENV["http_proxy"] if proxy && !proxy.empty? unless /^[^:]+:\/\// =~ proxy proxy = "https://" + proxy end proxy else nil end end def pipeline_resource(app, *extras) app_resource(app, extras.unshift("pipeline").join("/")) end def params(tuples = {}) { :params => tuples.reject { |k,v| k.nil? || v.nil? } } end def options(extras = {}) { 'User-Agent' => "heroku-push-cli/#{CISAURUS_CLIENT_VERSION}", 'X-Ruby-Version' => RUBY_VERSION, 'X-Ruby-Platform' => RUBY_PLATFORM, 'X-Heroku-Host' => ENV['HEROKU_HOST'] || 'heroku.com' }.merge(extras) end end
ruby
MIT
969cfedfaa28ee3774c4d6ff8528992eae597770
2026-01-04T17:52:56.257680Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/yem__party_influenced_music_ported_to_ace_by_adon237.rb
yem__party_influenced_music_ported_to_ace_by_adon237.rb
#=============================================================================== # # Yanfly Engine Melody - Party Influenced Music # Last Date Updated: 2010.06.24 # Level: Normal # Ported to Ace by Adon237 # No matter how good an RPG's battle music is, players are going to get sick and # tired of listening to it for the zillionth time. This script won't rid RPG's # of that problem, but will hopefully stall the process by playing randomized # music dependent on who the player has in the active party at the start of any # normal battle. # #=============================================================================== # Updates # ----------------------------------------------------------------------------- # o 2010.06.24 - Started Script and Finished. #=============================================================================== # Instructions # ----------------------------------------------------------------------------- # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials but above ▼ Main. Remember to save. # # To use this script, modify the module down below to create the arrays of # music themes used by each actor. Depending on who is present in the battle, # a random piece of music will play gathered from the music pool. # # To force a theme to play, just set the battle theme to something else other # than the default battle theme. It will always choose the selected theme over # the random themes. Once the battle theme is changed back to the default battle # theme, then random battle themes will trigger once again. # #=============================================================================== $imported = {} if $imported == nil $imported["PartyInfluencedMusic"] = true module YEM module BATTLE_THEMES # This hash adjusts the random battle themes that may be played depending # on whether or not the party member is present in the battle when the music # loads up. Each array contains possible themes that may play for battle. # Actor 0 is the common pool. Inside of that array contains all of the # battle themes that can bebe played regardless of who's in the party. ACTOR_MUSIC ={ # ActorID 0 must exist. # ActorID => [BGM, BGM, BGM] 0 => [RPG::BGM.new("Battle1", 100, 100) ], # End Common 1 => [RPG::BGM.new("Battle2", 100, 100) ], # End Actor1 2 => [RPG::BGM.new("Town3", 100, 100) ], # End Actor2 3 => [RPG::BGM.new("Dungeon4", 100, 100) ], # End Actor3 } # Do not remove this. end # BATTLE_THEMES end # YEM #=============================================================================== # Editting anything past this point may potentially result in causing computer # damage, incontinence, explosion of user's head, coma, death, and/or halitosis. # Therefore, edit at your own risk. #=============================================================================== #=============================================================================== # Game_System #=============================================================================== class Game_System #-------------------------------------------------------------------------- # overwrite method: battle_bgm #-------------------------------------------------------------------------- def battle_bgm return @battle_bgm if @battle_bgm != nil former_in_battle = $game_party.in_battle $game_party.in_battle == true music_list = YEM::BATTLE_THEMES::ACTOR_MUSIC[0] for member in $game_party.battle_members next unless YEM::BATTLE_THEMES::ACTOR_MUSIC.include?(member.id) result = YEM::BATTLE_THEMES::ACTOR_MUSIC[member.id] if result.is_a?(Array) music_list |= result elsif result.is_a?(RPG::BGM) music_list.push(result) end end $game_party.in_battle == former_in_battle return music_list[rand(music_list.size)] end #-------------------------------------------------------------------------- # overwrite method: battle_bgm= #-------------------------------------------------------------------------- def battle_bgm=(battle_bgm) @battle_bgm = battle_bgm @battle_bgm = nil if @battle_bgm == $data_system.battle_bgm end end # Game_System #=============================================================================== # # END OF FILE # #===============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Instant_Cast.rb
Instant_Cast.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Instant Cast v1.03 # -- Last Updated: 2012.07.17 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-InstantCast"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.07.17 - Instant doesn't take up a turn if a characterh as additional # actions/can attack twice. # 2012.01.12 - Anti-crash methods implemented. # 2011.12.26 - Bug Fixed: If actor gets stunned while doing an instant cast, # the actor will not be reselected. # 2011.12.21 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # From the VX Yanfly Engines, instant cast properties have been a staple skill # and item property. Instant cast makes a return in RPG Maker VX Ace. There's # a few changes made with instant casts. # # 1) For actors with multiple actions, instants will only occur if the first # action is an instant. If the first action is not an instant the follow-up # actions contain an instant, the instant will be treated as normal. # # 2) Any actions added on by instants will automatically trigger immediately # after the instant finishes and will be treated as instants. This includes # Active Chain Skills triggering from an instant. # # 3) If an enemy uses an instant, the enemy will gain an additional skill to # use after using the said instant. This will apply whenever an enemy uses # an instant skill, even if it was after the enemy's first action. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/‘fÞ but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Skill Notetags - These notetags go in the skills notebox in the database. # ----------------------------------------------------------------------------- # <instant> # Causes the action to be an instant action. If an instant action is selected # first, then the action will be performed before the battle phase starts. If # placed behind a non-instant action, the would-be instant action will be # considered a normal action. If an enemy uses an instant action, no matter if # it was used first or after, the enemy gains an additional action. # # ----------------------------------------------------------------------------- # Item Notetags - These notetags go in the items notebox in the database. # ----------------------------------------------------------------------------- # <instant> # Causes the action to be an instant action. If an instant action is selected # first, then the action will be performed before the battle phase starts. If # placed behind a non-instant action, the would-be instant action will be # considered a normal action. If an enemy uses an instant action, no matter if # it was used first or after, the enemy gains an additional action. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script is compatible with Yanfly Engine Ace - Ace Battle Engine v1.00+. # Place this script under Ace Battle Engine in the script listing # #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module USABLEITEM INSTANT = /<(?:INSTANT|instant)>/i end # USABLEITEM end # REGEXP end # YEA #============================================================================== # ¡ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_instant load_database; end def self.load_database load_database_instant load_notetags_instant end #-------------------------------------------------------------------------- # new method: load_notetags_instant #-------------------------------------------------------------------------- def self.load_notetags_instant groups = [$data_skills, $data_items] for group in groups for obj in group next if obj.nil? obj.load_notetags_instant end end end end # DataManager #============================================================================== # ¡ RPG::UsableItem #============================================================================== class RPG::UsableItem < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :instant #-------------------------------------------------------------------------- # common cache: load_notetags_instant #-------------------------------------------------------------------------- def load_notetags_instant @instant = false #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::USABLEITEM::INSTANT @instant = true #--- end } # self.note.split #--- end end # RPG::UsableItem #============================================================================== # ¡ Game_Actor #============================================================================== class Game_Actor < Game_Battler #-------------------------------------------------------------------------- # new method: check_instant_action #-------------------------------------------------------------------------- def check_instant_action @backup_actions_instant = [] @actions.each { |action| next unless action if action.item.nil? @backup_actions_instant.push(action.dup) next end unless action.item.instant @backup_actions_instant.push(action.dup) action.clear end } end #-------------------------------------------------------------------------- # new method: restore_instant_action #-------------------------------------------------------------------------- def restore_instant_action @backup_actions_instant.each_index { |i| @actions[i] = @backup_actions_instant[i] } @backup_actions_instant.clear i = 0 @actions.each { |action| if action.item.nil?; break; end; i += 1 } @action_input_index = i end end # Game_Actor #============================================================================== # ¡ Game_Enemy #============================================================================== class Game_Enemy < Game_Battler #-------------------------------------------------------------------------- # new method: add_extra_action #-------------------------------------------------------------------------- def add_extra_action action_list = enemy.actions.select {|a| action_valid?(a) } return if action_list.empty? rating_max = action_list.collect {|a| a.rating }.max rating_zero = rating_max - 3 action_list.reject! {|a| a.rating <= rating_zero } action = Game_Action.new(self) action.set_enemy_action(select_enemy_action(action_list, rating_zero)) @actions.push(action) end end # Game_Enemy #============================================================================== # ¡ Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # alias method: next_command #-------------------------------------------------------------------------- alias scene_battle_next_command_instant next_command def next_command if instant_action? perform_instant_action else scene_battle_next_command_instant end end #-------------------------------------------------------------------------- # new method: instant_action? #-------------------------------------------------------------------------- def instant_action? return false if BattleManager.actor.nil? return false if BattleManager.actor.input.nil? action = BattleManager.actor.input.item return false if action.nil? return action.instant end #-------------------------------------------------------------------------- # new method: perform_instant_action #-------------------------------------------------------------------------- def perform_instant_action hide_instant_action_windows @subject = BattleManager.actor @subject.check_instant_action execute_action if @subject.current_action.valid? process_event loop do @subject.remove_current_action break if $game_troop.all_dead? break unless @subject.current_action @subject.current_action.prepare execute_action if @subject.current_action.valid? end process_action_end @subject.make_actions @subject.restore_instant_action @subject = nil show_instant_action_windows end #-------------------------------------------------------------------------- # new method: hide_instant_action_windows #-------------------------------------------------------------------------- def hide_instant_action_windows if $imported["YEA-BattleEngine"] @info_viewport.visible = true @status_aid_window.hide @status_window.show @actor_command_window.show end end #-------------------------------------------------------------------------- # new method: show_instant_action_windows #-------------------------------------------------------------------------- def show_instant_action_windows if $imported["YEA-BattleEngine"] @info_viewport.visible = true end start_actor_command_selection status_redraw_target(BattleManager.actor) next_command unless BattleManager.actor.inputable? end #-------------------------------------------------------------------------- # new method: status_redraw_target #-------------------------------------------------------------------------- def status_redraw_target(target) return unless target.actor? @status_window.draw_item($game_party.battle_members.index(target)) end #-------------------------------------------------------------------------- # alias method: execute_action #-------------------------------------------------------------------------- alias scene_battle_execute_action_instant execute_action def execute_action scene_battle_execute_action_instant enemy_add_actions end #-------------------------------------------------------------------------- # new method: enemy_add_actions #-------------------------------------------------------------------------- def enemy_add_actions return if @subject.actor? return if @subject.current_action.nil? return if @subject.current_action.item.nil? return unless @subject.current_action.item.instant @subject.add_extra_action end end # Scene_Battle #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Move_Restrict_Region.rb
Move_Restrict_Region.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Move Restrict Region v1.03 # -- Last Updated: 2012.01.03 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-MoveRestrictRegion"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.23.08 - Added Feature: <all restrict: x> # 2012.01.03 - Added Feature: <all restrict: x> # 2011.12.26 - Bug Fixed: Player Restricted Regions. # 2011.12.15 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Not everybody wants NPC's to travel all over the place. With this script, you # can set NPC's to be unable to move pass tiles marked by a specified Region. # Simply draw out the area you want to enclose NPC's in on and they'll be # unable to move past it unless they have Through on. Likewise, there are # regions that you can prevent the player from moving onto, too! # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Map Notetags - These notetags go in the map notebox in a map's properties. # ----------------------------------------------------------------------------- # <all restrict: x> # <all restrict: x, x> # Players and NPC's on the map will be unable to move past region x even if # they have the "through" flag set. The only thing that can go past is if the # player is using the debug through flag. Draw out the area you want to close # the player and NPC's in with the regions and both will be unable to move onto # any of those tiles marked by region x. If you want to have more regions # restrict NPC's, insert multiples of this tag. # # <npc restrict: x> # <npc restrict: x, x> # NPC's on that map will be unable to move past regions x unless they have a # "Through" flag on. Draw out the area you want to close NPC's in with the # regions and the NPC's will be unable to move onto any of those tiles marked # by region x. If you want to have more regions restrict NPC's, insert # multiples of this tag. # # <player restrict: x> # <player restrict: x, x> # Players will not be able to move on tiles marked by region x unless the # player has a "Through" flag on. Draw out the area you want to close the # player in with the regions and the player will be unable to move past any of # those tiles marked by region x. If you want to have more regions restrict the # player, insert multiples of this tag. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module MOVE_RESTRICT #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Default Completely Restricted Regions - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # If you want there to always be a region ID that will forbid both the # player and NPC's from passing through, insert that region ID into the # array below. This effect will completely block out both players and NPC's # even if they have the "through" flag. However, it does not block the # debug_through flag for players. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- DEFAULT_ALL = [61] #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Default Player Restricted Regions - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # If you want there to always be a region ID that will forbid the player # from passing through, insert that region ID into the array below. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- DEFAULT_PLAYER = [62] #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Default NPC Restricted Regions - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # If you want there to always be a region ID that will forbid NPC's from # passing through, insert that region ID into the array below. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- DEFAULT_NPC = [63] end # MOVE_RESTRICT end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module MAP ALL_RESTRICT = /<(?:ALL_RESTRICT|all restrict):[ ]*(\d+(?:\s*,\s*\d+)*)>/i NPC_RESTRICT = /<(?:NPC_RESTRICT|npc restrict):[ ]*(\d+(?:\s*,\s*\d+)*)>/i PLAYER_RESTRICT = /<(?:PLAYER_RESTRICT|player restrict):[ ]*(\d+(?:\s*,\s*\d+)*)>/i end # MAP end # REGEXP end # YEA #============================================================================== # ■ RPG::Map #============================================================================== class RPG::Map #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :all_restrict_regions attr_accessor :npc_restrict_regions attr_accessor :player_restrict_regions #-------------------------------------------------------------------------- # common cache: load_notetags_mrr #-------------------------------------------------------------------------- def load_notetags_mrr @all_restrict_regions = YEA::MOVE_RESTRICT::DEFAULT_ALL.clone @npc_restrict_regions = YEA::MOVE_RESTRICT::DEFAULT_NPC.clone @player_restrict_regions = YEA::MOVE_RESTRICT::DEFAULT_PLAYER.clone #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::MAP::ALL_RESTRICT $1.scan(/\d+/).each { |num| @all_restrict_regions.push(num.to_i) if num.to_i > 0 } when YEA::REGEXP::MAP::NPC_RESTRICT $1.scan(/\d+/).each { |num| @npc_restrict_regions.push(num.to_i) if num.to_i > 0 } when YEA::REGEXP::MAP::PLAYER_RESTRICT $1.scan(/\d+/).each { |num| @player_restrict_regions.push(num.to_i) if num.to_i > 0 } #--- end } # self.note.split #--- end end # RPG::Map #============================================================================== # ■ Game_Map #============================================================================== class Game_Map #-------------------------------------------------------------------------- # alias method: setup #-------------------------------------------------------------------------- alias game_map_setup_mrr setup def setup(map_id) game_map_setup_mrr(map_id) @map.load_notetags_mrr end #-------------------------------------------------------------------------- # new method: all_restrict_regions #-------------------------------------------------------------------------- def all_restrict_regions return @map.all_restrict_regions end #-------------------------------------------------------------------------- # new method: npc_restrict_regions #-------------------------------------------------------------------------- def npc_restrict_regions return @map.npc_restrict_regions end #-------------------------------------------------------------------------- # new method: player_restrict_regions #-------------------------------------------------------------------------- def player_restrict_regions return @map.player_restrict_regions end end # Game_Map #============================================================================== # ■ Game_CharacterBase #============================================================================== class Game_CharacterBase #-------------------------------------------------------------------------- # alias method: passable? #-------------------------------------------------------------------------- alias game_characterbase_passable_mrr passable? def passable?(x, y, d) return false if npc_region_forbid?(x, y, d) return false if player_region_forbid?(x, y, d) return game_characterbase_passable_mrr(x, y, d) end #-------------------------------------------------------------------------- # new method: npc_forbid? #-------------------------------------------------------------------------- def npc_region_forbid?(x, y, d) return false unless self.is_a?(Game_Event) region = 0 case d when 1; region = $game_map.region_id(x-1, y+1) when 2; region = $game_map.region_id(x+0, y+1) when 3; region = $game_map.region_id(x+1, y+1) when 4; region = $game_map.region_id(x-1, y+0) when 5; region = $game_map.region_id(x+0, y+0) when 6; region = $game_map.region_id(x+1, y+0) when 7; region = $game_map.region_id(x-1, y-1) when 8; region = $game_map.region_id(x+0, y-1) when 9; region = $game_map.region_id(x+1, y-1) end return true if $game_map.all_restrict_regions.include?(region) return false if @through return $game_map.npc_restrict_regions.include?(region) end #-------------------------------------------------------------------------- # new method: player_region_forbid? #-------------------------------------------------------------------------- def player_region_forbid?(x, y, d) return false unless self.is_a?(Game_Player) return false if debug_through? region = 0 case d when 1; region = $game_map.region_id(x-1, y+1) when 2; region = $game_map.region_id(x+0, y+1) when 3; region = $game_map.region_id(x+1, y+1) when 4; region = $game_map.region_id(x-1, y+0) when 5; region = $game_map.region_id(x+0, y+0) when 6; region = $game_map.region_id(x+1, y+0) when 7; region = $game_map.region_id(x-1, y-1) when 8; region = $game_map.region_id(x+0, y-1) when 9; region = $game_map.region_id(x+1, y-1) end return true if $game_map.all_restrict_regions.include?(region) return false if @through return $game_map.player_restrict_regions.include?(region) end end # Game_CharacterBase #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Class_System.rb
Class_System.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Class System v1.10 # -- Last Updated: 2012.01.29 # -- Level: Normal, Hard # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-ClassSystem"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.08.06 - Leveling issue if class level exceeds actor level. # 2012.01.29 - Visual Bug: Disabled classes now have faded icons. # 2012.01.08 - Compatibility Update: Learn Skill Engine # 2012.01.05 - Bug Fixed: Equipment no longer gets duplicated. # 2012.01.04 - Update: Autobattle will no longer use skills not available to # that class for specific actors. # 2012.01.02 - Efficiency Update. # 2011.12.26 - Added custom command functionality. # 2011.12.23 - Compatibility Update: Class Specifics. # 2011.12.22 - Compatibility Update: Ace Menu Engine. # 2011.12.20 - Compatibility Update: Class Unlock Level. # 2011.12.19 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script adds the ability for your player to freely change the classes of # actors outside of battle from a menu. When changing classes, this script # gives the option for the developer to choose whether or not classes have # their own levels (causing the actor's level to reset back to the class's # level) or to maintain the current level. In addition to providing the ability # to change classes, equipping a subclass is also doable, and the mechanics of # having a subclass can also be defined within this script. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Actor Notetags - These notetags go in the actors notebox in the database. # ----------------------------------------------------------------------------- # <unlocked classes: x> # <unlocked classes: x, x> # This will set the default classes as unlocked for the actor. This does not # override the default classes unlocked in the module, but instead, adds on # to the number of unlocked classes. # # ----------------------------------------------------------------------------- # Class Notetags - These notetags go in the class notebox in the database. # ----------------------------------------------------------------------------- # <icon: x> # Sets the icon representing the class to x. # # <help description> # string # string # </help description> # Sets the text used for the help window in the class scene. Multiple lines in # the notebox will be strung together. Use | for a line break. # # ----------------------------------------------------------------------------- # Script Calls - These commands are used with script calls. # ----------------------------------------------------------------------------- # $game_actors[x].unlock_class(y) # This allows actor x to unlock class y, making it available for switching in # and out in the Class scene. # # $game_actors[x].remove_class(y) # This causes actor x to remove class y from being able to switch to and from. # If the actor is currently class y, the class will not be removed. If the # actor's current subclass is y, the subclass will be unequipped. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module CLASS_SYSTEM #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - General Class Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # These are the general settings regarding the whole script. They control # various rules and regulations that this script undergoes. These settings # will also determine what a subclass can do for a player. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- CLASS_MENU_TEXT = "Class" # Text that appears in the Main Menu. MAINTAIN_LEVELS = false # Maintain through all classes. Default: false. DEFAULT_UNLOCKS = [ 1, 11, 21, 31] # Classes unlocked by default. # The display between a primary class and a subclass when written in a # window will appear as such. SUBCLASS_TEXT = "%s/%s" # This adjusts the stat rate inheritance for an actor if an actor has a # subclass equipped. If you want to disable this, set the rate to 0.0. SUBCLASS_STAT_RATE = 0.20 # This adds subclass skill types to the available skill types usable. SUBCLASS_SKILL_TYPES = true # This adds subclass weapons to equippable weapon types. SUBCLASS_WEAPON_TYPES = true # This adds subclass weapons to equippable armour types. SUBCLASS_ARMOUR_TYPES = true #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Class Scene Commands - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # These settings adjust how the class scene appears. Here, you can adjust # the command list and the order at which items appear. These are mostly # visual settings. Adjust them as you see fit. # # ------------------------------------------------------------------------- # :command Description # ------------------------------------------------------------------------- # :primary Allows the player to change the primary class. # :subclass Allows the player to change the subclass. # # :learn_skill Requires YEA - Learn Skill Engine # #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- COMMANDS =[ # The order at which the menu items are shown. # [ :command, "Display"], [ :primary, "Primary"], [:subclass, "Subclass"], [:learn_skill, "Custom"], # [ :custom1, "Custom1"], # [ :custom2, "Custom2"], ] # Do not remove this. #-------------------------------------------------------------------------- # - Status Class Commands - # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # For those who use scripts to that may produce unique effects for the # class menu, use this hash to manage the custom commands for the Class # Command Window. You can disable certain commands or prevent them from # appearing by using switches. If you don't wish to bind them to a switch, # set the proper switch to 0 for it to have no impact. #-------------------------------------------------------------------------- CUSTOM_CLASS_COMMANDS ={ # :command => [EnableSwitch, ShowSwitch, Handler Method, :custom1 => [ 0, 0, :command_name1], :custom2 => [ 0, 0, :command_name2], } # Do not remove this. # These settings adjust the colour displays for classes. CURRENT_CLASS_COLOUR = 17 # "Window" colour used for current class. SUBCLASS_COLOUR = 4 # "Window" colour used for subclass. # This adjusts the display for class levels if MAINTAIN_LEVELS is false. CLASS_LEVEL = "LV%s" # Text display for level. LEVEL_FONT_SIZE = 16 # Font size used for level. # This array sets the order of how classes are ordered in the class listing # window. Any class ID's unlisted will not be shown. CLASS_ORDER = [41..999, 1..40] # This adjusts the font size for the Parameters window. PARAM_FONT_SIZE = 20 #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Switch Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # These are the switches that govern whether or not certain menu items will # appear and/or will be enabled. By binding them to a Switch, you can just # set the Switch ON/OFF to show/hide or enable/disable a menu command. If # you do not wish to use this feature, set these commands to 0. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- SWITCH_SHOW_CLASS = 0 # Switch that shows Class in Main Menu. SWITCH_ENABLE_CLASS = 0 # Switch that enables Class in Main Menu. SWITCH_SHOW_PRIMARY = 0 # Switch that shows Subclass in Class Menu. SWITCH_ENABLE_PRIMARY = 0 # Switch that enables Subclass in Class Menu. SWITCH_SHOW_SUBCLASS = 0 # Switch that shows Subclass in Class Menu. SWITCH_ENABLE_SUBCLASS = 0 # Switch that enables Subclass in Class Menu. end # CLASS_SYSTEM end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module CLASS_SYSTEM module_function #-------------------------------------------------------------------------- # convert_integer_array #-------------------------------------------------------------------------- def convert_integer_array(array) result = [] array.each { |i| case i when Range; result |= i.to_a when Integer; result |= [i] end } return result end #-------------------------------------------------------------------------- # converted_contants #-------------------------------------------------------------------------- DEFAULT_UNLOCKS = convert_integer_array(DEFAULT_UNLOCKS) CLASS_ORDER = convert_integer_array(CLASS_ORDER) end # CLASS_SYSTEM module REGEXP module ACTOR UNLOCKED_CLASSES = /<(?:UNLOCKED_CLASSES|unlocked classes):[ ]*(\d+(?:\s*,\s*\d+)*)>/i end # ACTOR module CLASS ICON_INDEX = /<(?:ICON_INDEX|icon index|icon):[ ](\d+)>/i HELP_DESCRIPTION_ON = /<(?:HELP_DESCRIPTION|help description)>/i HELP_DESCRIPTION_OFF = /<\/(?:HELP_DESCRIPTION|help description)>/i end # CLASS end # REGEXP end # YEA #============================================================================== # ■ Switch #============================================================================== module Switch #-------------------------------------------------------------------------- # self.class_show #-------------------------------------------------------------------------- def self.class_show return true if YEA::CLASS_SYSTEM::SWITCH_SHOW_CLASS <= 0 return $game_switches[YEA::CLASS_SYSTEM::SWITCH_SHOW_CLASS] end #-------------------------------------------------------------------------- # self.class_enable #-------------------------------------------------------------------------- def self.class_enable return true if YEA::CLASS_SYSTEM::SWITCH_ENABLE_CLASS <= 0 return $game_switches[YEA::CLASS_SYSTEM::SWITCH_ENABLE_CLASS] end #-------------------------------------------------------------------------- # self.primary_show #-------------------------------------------------------------------------- def self.primary_show return true if YEA::CLASS_SYSTEM::SWITCH_SHOW_PRIMARY <= 0 return $game_switches[YEA::CLASS_SYSTEM::SWITCH_SHOW_PRIMARY] end #-------------------------------------------------------------------------- # self.primary_enable #-------------------------------------------------------------------------- def self.primary_enable return true if YEA::CLASS_SYSTEM::SWITCH_ENABLE_PRIMARY <= 0 return $game_switches[YEA::CLASS_SYSTEM::SWITCH_ENABLE_PRIMARY] end #-------------------------------------------------------------------------- # self.subclass_show #-------------------------------------------------------------------------- def self.subclass_show return true if YEA::CLASS_SYSTEM::SWITCH_SHOW_SUBCLASS <= 0 return $game_switches[YEA::CLASS_SYSTEM::SWITCH_SHOW_SUBCLASS] end #-------------------------------------------------------------------------- # self.subclass_enable #-------------------------------------------------------------------------- def self.subclass_enable return true if YEA::CLASS_SYSTEM::SWITCH_ENABLE_SUBCLASS <= 0 return $game_switches[YEA::CLASS_SYSTEM::SWITCH_ENABLE_SUBCLASS] end end # Switch #============================================================================== # ■ Numeric #============================================================================== class Numeric #-------------------------------------------------------------------------- # new method: group_digits #-------------------------------------------------------------------------- unless $imported["YEA-CoreEngine"] def group; return self.to_s; end end # $imported["YEA-CoreEngine"] end # Numeric #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_cs load_database; end def self.load_database load_database_cs load_notetags_cs end #-------------------------------------------------------------------------- # new method: load_notetags_cs #-------------------------------------------------------------------------- def self.load_notetags_cs groups = [$data_actors, $data_classes] for group in groups for obj in group next if obj.nil? obj.load_notetags_cs end end end end # DataManager #============================================================================== # ■ RPG::Actor #============================================================================== class RPG::Actor < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :unlocked_classes #-------------------------------------------------------------------------- # common cache: load_notetags_cs #-------------------------------------------------------------------------- def load_notetags_cs @unlocked_classes = [] #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::ACTOR::UNLOCKED_CLASSES $1.scan(/\d+/).each { |num| @unlocked_classes.push(num.to_i) if num.to_i > 0 } #--- end } # self.note.split #--- end end # RPG::Actor #============================================================================== # ■ RPG::Class #============================================================================== class RPG::Class < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :icon_index #-------------------------------------------------------------------------- # common cache: load_notetags_cs #-------------------------------------------------------------------------- def load_notetags_cs @icon_index = 0 @help_description_on = false #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::CLASS::ICON_INDEX @icon_index = $1.to_i #--- when YEA::REGEXP::CLASS::HELP_DESCRIPTION_ON @help_description_on = true when YEA::REGEXP::CLASS::HELP_DESCRIPTION_OFF @help_description_on = false #--- else @description += line.to_s if @help_description_on end } # self.note.split #--- @description.gsub!(/[|]/i) { "\n" } end end # RPG::Class #============================================================================== # ■ Game_Temp #============================================================================== class Game_Temp #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :scene_class_index attr_accessor :scene_class_oy end # Game_Temp #============================================================================== # ■ Game_Action #============================================================================== class Game_Action #-------------------------------------------------------------------------- # alias method: valid? #-------------------------------------------------------------------------- alias game_action_valid_cs valid? def valid? return false if check_auto_battle_class return game_action_valid_cs end #-------------------------------------------------------------------------- # new method: check_auto_battle_class #-------------------------------------------------------------------------- def check_auto_battle_class return false unless subject.actor? return false unless subject.auto_battle? return false if item.nil? return false if subject.added_skill_types.include?(item.stype_id) return false if item.id == subject.attack_skill_id return true end end # Game_Action #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :temp_flag #-------------------------------------------------------------------------- # alias method: added_skill_types #-------------------------------------------------------------------------- alias game_battlerbase_added_skill_types_cs added_skill_types def added_skill_types result = game_battlerbase_added_skill_types_cs result |= subclass_skill_types return result end #-------------------------------------------------------------------------- # new method: subclass_skill_types #-------------------------------------------------------------------------- def subclass_skill_types; return []; end #-------------------------------------------------------------------------- # alias method: equip_wtype_ok? #-------------------------------------------------------------------------- alias game_battlerbase_equip_wtype_ok_cs equip_wtype_ok? def equip_wtype_ok?(wtype_id) return true if subclass_equip_wtype?(wtype_id) return game_battlerbase_equip_wtype_ok_cs(wtype_id) end #-------------------------------------------------------------------------- # new method: subclass_equip_wtype? #-------------------------------------------------------------------------- def subclass_equip_wtype?(wtype_id); return false; end #-------------------------------------------------------------------------- # alias method: equip_atype_ok? #-------------------------------------------------------------------------- alias game_battlerbase_equip_atype_ok_cs equip_atype_ok? def equip_atype_ok?(atype_id) return true if subclass_equip_atype?(atype_id) return game_battlerbase_equip_atype_ok_cs(atype_id) end #-------------------------------------------------------------------------- # new method: subclass_equip_atype? #-------------------------------------------------------------------------- def subclass_equip_atype?(atype_id); return false; end end # Game_BattlerBase #============================================================================== # ■ Game_Actor #============================================================================== class Game_Actor < Game_Battler #-------------------------------------------------------------------------- # alias method: setup #-------------------------------------------------------------------------- alias game_actor_setup_cs setup def setup(actor_id) game_actor_setup_cs(actor_id) init_unlocked_classes init_subclass end #-------------------------------------------------------------------------- # new method: init_unlocked_classes #-------------------------------------------------------------------------- def init_unlocked_classes @unlocked_classes = actor.unlocked_classes.clone @unlocked_classes.push(@class_id) if !@unlocked_classes.include?(@class_id) @unlocked_classes.sort! end #-------------------------------------------------------------------------- # new method: init_subclass #-------------------------------------------------------------------------- def init_subclass @subclass_id = 0 end #-------------------------------------------------------------------------- # new method: unlocked_classes #-------------------------------------------------------------------------- def unlocked_classes init_unlocked_classes if @unlocked_classes.nil? return @unlocked_classes end #-------------------------------------------------------------------------- # new method: unlock_class #-------------------------------------------------------------------------- def unlock_class(class_id) init_unlocked_classes if @unlocked_classes.nil? return if @unlocked_classes.include?(class_id) @unlocked_classes.push(class_id) learn_class_skills(class_id) end #-------------------------------------------------------------------------- # new method: remove_class #-------------------------------------------------------------------------- def remove_class(class_id) init_unlocked_classes if @unlocked_classes.nil? return if class_id == @class_id @unlocked_classes.delete(class_id) @subclass_id = 0 if class_id == @subclass_id refresh end #-------------------------------------------------------------------------- # new method: subclass #-------------------------------------------------------------------------- def subclass init_subclass if @subclass_id.nil? return $data_classes[@subclass_id] end #-------------------------------------------------------------------------- # alias method: change_class #-------------------------------------------------------------------------- alias game_actor_change_class_cs change_class def change_class(class_id, keep_exp = false) @subclass_id = 0 if @subclass_id == class_id game_actor_change_class_cs(class_id, keep_exp) learn_class_skills(class_id) unlock_class(class_id) end #-------------------------------------------------------------------------- # new method: learn_class_skills #-------------------------------------------------------------------------- def learn_class_skills(class_id) return if class_id <= 0 return if $data_classes[class_id].nil? $data_classes[class_id].learnings.each do |learning| learn_skill(learning.skill_id) if learning.level == class_level(class_id) end end #-------------------------------------------------------------------------- # new method: change_subclass #-------------------------------------------------------------------------- def change_subclass(class_id) return if class_id == @class_id unlock_class(class_id) @subclass_id = @subclass_id == class_id ? 0 : class_id learn_class_skills(@subclass_id) refresh end #————————————————————————– # new method: class_level Edited by DisturbedInside #————————————————————————– def class_level(class_id) return @level if YEA::CLASS_SYSTEM::MAINTAIN_LEVELS temp_class = $data_classes[class_id] @exp[class_id] = 0 if @exp[class_id].nil? #declare a max level (using EXP) #If you can’t find it, go to the class database and select exp curve #then switch view to total at the top @exp[max_level] = 2547133 #This is the value to change. It declares a max level #You need to calculate how much exp for max level #Do it manually if using Yanfly-Adjusting Limits #To calculate max level exp if using Yanfly-adjusting limits is all math!! # Level 99 = 2547133 # to calculate past there…. have to add on multiples of 50744 # Level 110 = 3156061 # To go from 99 -> 110 have to add on 12 multiples of 50744. n = 1 loop do break if temp_class.exp_for_level(n+1) > @exp[class_id] n += 1 #add a restriction to “kick out” of loop if exp exceeds max level exp break if temp_class.exp_for_level(n+1) > @exp[max_level] end return n end #-------------------------------------------------------------------------- # new method: subclass_level #-------------------------------------------------------------------------- def subclass_level return 0 if @subclass_id == 0 return @level if YEA::CLASS_SYSTEM::MAINTAIN_LEVELS return class_level(@subclass_id) end #-------------------------------------------------------------------------- # alias method: param_base #-------------------------------------------------------------------------- alias game_actor_param_base_cs param_base def param_base(param_id) result = game_actor_param_base_cs(param_id) unless subclass.nil? subclass_rate = YEA::CLASS_SYSTEM::SUBCLASS_STAT_RATE slevel = subclass_level result += subclass.params[param_id, slevel] * subclass_rate end return result.to_i end #-------------------------------------------------------------------------- # new method: subclass_skill_types #-------------------------------------------------------------------------- def subclass_skill_types return [] unless YEA::CLASS_SYSTEM::SUBCLASS_SKILL_TYPES return [] if subclass.nil? array = [] for feature in subclass.features next unless feature.code == FEATURE_STYPE_ADD next if features_set(FEATURE_STYPE_ADD).include?(feature.data_id) array.push(feature.data_id) end return array end #-------------------------------------------------------------------------- # new method: subclass_equip_wtype? #-------------------------------------------------------------------------- def subclass_equip_wtype?(wtype_id) return false unless YEA::CLASS_SYSTEM::SUBCLASS_WEAPON_TYPES return false if subclass.nil? for feature in subclass.features next unless feature.code == FEATURE_EQUIP_WTYPE return true if wtype_id == feature.data_id end return super end #-------------------------------------------------------------------------- # new method: subclass_equip_atype? #-------------------------------------------------------------------------- def subclass_equip_atype?(atype_id) return false unless YEA::CLASS_SYSTEM::SUBCLASS_ARMOUR_TYPES return false if subclass.nil? for feature in subclass.features next unless feature.code == FEATURE_EQUIP_ATYPE return true if atype_id == feature.data_id end return super end #-------------------------------------------------------------------------- # alias method: release_unequippable_items #-------------------------------------------------------------------------- alias game_actor_release_unequippable_items_cs release_unequippable_items def release_unequippable_items(item_gain = true) item_gain = false if @temp_flag game_actor_release_unequippable_items_cs(item_gain) end end # Game_Actor #============================================================================== # ■ Game_Interpreter #============================================================================== class Game_Interpreter #-------------------------------------------------------------------------- # overwrite method: command_321 #-------------------------------------------------------------------------- def command_321 actor = $game_actors[@params[0]] if actor && $data_classes[@params[1]] maintain = YEA::CLASS_SYSTEM::MAINTAIN_LEVELS actor.change_class(@params[1], maintain) end end end # Game_Interpreter #============================================================================== # ■ Window_Base #============================================================================== class Window_Base < Window #-------------------------------------------------------------------------- # overwrite method: draw_actor_class #-------------------------------------------------------------------------- def draw_actor_class(actor, x, y, width = 112) change_color(normal_color) if actor.subclass.nil? text = actor.class.name else fmt = YEA::CLASS_SYSTEM::SUBCLASS_TEXT text = sprintf(fmt, actor.class.name, actor.subclass.name) end draw_text(x, y, width, line_height, text) end end # Window_Base #============================================================================== # ■ Window_MenuCommand #============================================================================== class Window_MenuCommand < Window_Command #-------------------------------------------------------------------------- # alias method: add_formation_command #-------------------------------------------------------------------------- alias window_menucommand_add_formation_command_cs add_formation_command def add_formation_command add_class_command unless $imported["YEA-AceMenuEngine"] window_menucommand_add_formation_command_cs end #-------------------------------------------------------------------------- # new method: add_class_command #-------------------------------------------------------------------------- def add_class_command return unless Switch.class_show text = YEA::CLASS_SYSTEM::CLASS_MENU_TEXT add_command(text, :class, Switch.class_enable) end end # Window_MenuCommand #============================================================================== # ■ Window_ClassCommand #============================================================================== class Window_ClassCommand < Window_Command #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize(x, y) super(x, y) @actor = nil end #-------------------------------------------------------------------------- # ● ウィンドウ幅の取得 #-------------------------------------------------------------------------- def window_width; return 160; end #-------------------------------------------------------------------------- # actor= #-------------------------------------------------------------------------- def actor=(actor) return if @actor == actor @actor = actor refresh end #-------------------------------------------------------------------------- # item_window= #-------------------------------------------------------------------------- def item_window=(window) @item_window = window end #-------------------------------------------------------------------------- # visible_line_number #-------------------------------------------------------------------------- def visible_line_number; return 4; end #-------------------------------------------------------------------------- # make_command_list #--------------------------------------------------------------------------
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
true
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Ace_Status_Menu.rb
Ace_Status_Menu.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Ace Status Menu v1.02 # -- Last Updated: 2011.12.26 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-StatusMenu"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.08.06 - Fix Sp Paramater TCR # 2011.12.26 - Compatibility Update: Rename Actor # 2011.12.23 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script changes the status screen completely to something the player can # interact with more and be able to view actor data with more clarity. The # player is able to view the general information for an actor (parameters and # experience), a parameters bar graph, the various hidden extra parameters # (named properties in the script), and a customizable biography for the actor. # Also with this script, biographies can be changed at any time using a script # call to add more of a personal touch to characters. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Script Calls - These commands are used with script calls. # ----------------------------------------------------------------------------- # $game_actors[x].description = string # Changes the biography description for actor x to that of the string. Use \n # to designate linebreaks in the string. If you wish to use text codes, write # them in the strings as \\n[2] or \\c[3] to make them work properly. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module STATUS #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Command Window Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # This section adjusts the commands that appear in the command window used # for the status screen. Rearrange the commands, add new ones, remove them # as you see fit. # # ------------------------------------------------------------------------- # :command Description # ------------------------------------------------------------------------- # :general Adds general page. # :parameters Adds parameters page. # :properties Adds properties page. # :biography Adds biography page. # # :rename Requires YEA - Rename Actor # :retitle Requires YEA - Retitle Actor # #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- COMMANDS =[ # The order at which the menu items are shown. # [ :command, "Display"], [ :general, "General"], [ :parameters, "Parameters"], [ :properties, "Properties"], # [ :custom1, "Skills"], # [ :custom2, "Equipment"], # [ :custom3, "Class"], [ :biography, "Biography"], [ :rename, "Rename"], # Requires YEA - Rename Actor [ :retitle, "Retitle"], # Requires YEA - Rename Actor ] # Do not remove this. #-------------------------------------------------------------------------- # - Status Custom Commands - # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # For those who use scripts to that may produce unique effects for the # status menu, use this hash to manage the custom commands for the Status # Command Window. You can disable certain commands or prevent them from # appearing by using switches. If you don't wish to bind them to a switch, # set the proper switch to 0 for it to have no impact. #-------------------------------------------------------------------------- CUSTOM_STATUS_COMMANDS ={ # :command => [EnableSwitch, ShowSwitch, Handler Method, Window Draw], :custom1 => [ 0, 0, :command_name1, :draw_custom1], :custom2 => [ 0, 0, :command_name2, :draw_custom2], :custom3 => [ 0, 0, :command_name3, :draw_custom3], } # Do not remove this. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - General Window Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # These settings adjust the way the general window visually appears. # Not many changes need to be done here other than vocab changes. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PARAMETERS_VOCAB = "Parameters" # Title used for Parameters. EXPERIENCE_VOCAB = "Experience" # Title used for Experience. NEXT_TOTAL_VOCAB = "Next %s Total EXP" # Label used for total experience. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Parameters Window Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # These settings adjust the way the parameters window visually appears. # Each of the stats have a non-window colour. Adjust them as you see fit. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PARAM_COLOUR ={ # ParamID => [:stat, Colour1, Colour2 ], 2 => [ :atk, Color.new(225, 100, 100), Color.new(240, 150, 150)], 3 => [ :def, Color.new(250, 150, 30), Color.new(250, 180, 100)], 4 => [ :mat, Color.new( 70, 140, 200), Color.new(135, 180, 230)], 5 => [ :mdf, Color.new(135, 130, 190), Color.new(170, 160, 220)], 6 => [ :agi, Color.new( 60, 180, 80), Color.new(120, 200, 120)], 7 => [ :luk, Color.new(255, 240, 100), Color.new(255, 250, 200)], } # Do not remove this. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Properties Window Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # These settings adjust the way the properties window visually appears. # The properties have abbreviations, but leaving them as such makes things # confusing (as it's sometimes hard to figure out what the abbreviations # mean). Change the way the appear, whether or not they appear, and what # order they will appear in. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PROPERTIES_FONT_SIZE = 16 # Font size used for properties. # These are the properties that appear in column 1. PROPERTIES_COLUMN1 =[ [:hit, "Hit Rate"], [:eva, "Evasion"], [:cri, "Critical Hit"], [:cev, "Critical Evade"], [:mev, "Magic Evasion"], [:mrf, "Magic Reflect"], [:cnt, "Counter Rate"], [:tgr, "Target Rate"], ] # Do not remove this. # These are the properties that appear in column 2. PROPERTIES_COLUMN2 =[ [:hrg, "HP Regen"], [:mrg, "MP Regen"], [:trg, "TP Regen"], [:rec, "Recovery"], [:grd, "Guard Rate"], [:pha, "Item Boost"], [:exr, "EXP Rate"], [:tcr, "TP Charge"], ] # Do not remove this. # These are the properties that appear in column 3. PROPERTIES_COLUMN3 =[ [:hcr, "HP Cost Rate"], # Requires YEA - Skill Cost Manager [:mcr, "MP Cost Rate"], [:tcr_y, "TP Cost Rate"], # Requires YEA - Skill Cost Manager [:cdr, "Cooldown Rate"], # Requires YEA - Skill Restrictions [:wur, "Warmup Rate"], # Requires YEA - Skill Restrictions [:pdr, "Physical Damage"], [:mdr, "Magical Damage"], [:fdr, "Floor Damage"], ] # Do not remove this. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Biography Window Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # These settings adjust the way the biography appears including the title # used at the top, the font size, and whatnot. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- BIOGRAPHY_NICKNAME_TEXT = "%s the %s" # How the nickname will appear. BIOGRAPHY_NICKNAME_SIZE = 32 # Size of the font used. end # STATUS end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== #============================================================================== # ■ Numeric #============================================================================== class Numeric #-------------------------------------------------------------------------- # new method: group_digits #-------------------------------------------------------------------------- unless $imported["YEA-CoreEngine"] def group; return self.to_s; end end # $imported["YEA-CoreEngine"] end # Numeric #============================================================================== # ■ Game_Temp #============================================================================== class Game_Temp #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :scene_status_index attr_accessor :scene_status_oy end # Game_Temp #============================================================================== # ■ Game_Actor #============================================================================== class Game_Actor < Game_Battler #-------------------------------------------------------------------------- # new method: description= #-------------------------------------------------------------------------- def description=(text) @description = text end #-------------------------------------------------------------------------- # overwrite method: description #-------------------------------------------------------------------------- def description return @description unless @description.nil? return actor.description end end # Game_Actor #============================================================================== # ■ Window_StatusCommand #============================================================================== class Window_StatusCommand < Window_Command #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :item_window #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize(dx, dy) super(dx, dy) @actor = nil end #-------------------------------------------------------------------------- # window_width #-------------------------------------------------------------------------- def window_width; return 160; end #-------------------------------------------------------------------------- # actor= #-------------------------------------------------------------------------- def actor=(actor) return if @actor == actor @actor = actor refresh end #-------------------------------------------------------------------------- # visible_line_number #-------------------------------------------------------------------------- def visible_line_number; return 4; end #-------------------------------------------------------------------------- # ok_enabled? #-------------------------------------------------------------------------- def ok_enabled? return handle?(current_symbol) end #-------------------------------------------------------------------------- # make_command_list #-------------------------------------------------------------------------- def make_command_list return unless @actor for command in YEA::STATUS::COMMANDS case command[0] #--- Default --- when :general, :parameters, :properties, :biography add_command(command[1], command[0]) #--- Yanfly Engine Ace --- when :rename next unless $imported["YEA-RenameActor"] add_command(command[1], command[0], @actor.rename_allow?) when :retitle next unless $imported["YEA-RenameActor"] add_command(command[1], command[0], @actor.retitle_allow?) #--- Custom Commands --- else process_custom_command(command) end end if !$game_temp.scene_status_index.nil? select($game_temp.scene_status_index) self.oy = $game_temp.scene_status_oy end $game_temp.scene_status_index = nil $game_temp.scene_status_oy = nil end #-------------------------------------------------------------------------- # process_ok #-------------------------------------------------------------------------- def process_ok $game_temp.scene_status_index = index $game_temp.scene_status_oy = self.oy super end #-------------------------------------------------------------------------- # process_custom_command #-------------------------------------------------------------------------- def process_custom_command(command) return unless YEA::STATUS::CUSTOM_STATUS_COMMANDS.include?(command[0]) show = YEA::STATUS::CUSTOM_STATUS_COMMANDS[command[0]][1] continue = show <= 0 ? true : $game_switches[show] return unless continue text = command[1] switch = YEA::STATUS::CUSTOM_STATUS_COMMANDS[command[0]][0] enabled = switch <= 0 ? true : $game_switches[switch] add_command(text, command[0], enabled) end #-------------------------------------------------------------------------- # update #-------------------------------------------------------------------------- def update super update_item_window end #-------------------------------------------------------------------------- # update_item_window #-------------------------------------------------------------------------- def update_item_window return if @item_window.nil? return if @current_index == current_symbol @current_index = current_symbol @item_window.refresh end #-------------------------------------------------------------------------- # item_window= #-------------------------------------------------------------------------- def item_window=(window) @item_window = window update end #-------------------------------------------------------------------------- # update_help #-------------------------------------------------------------------------- def update_help return if @actor.nil? @help_window.set_text(@actor.actor.description) end end # Window_StatusCommand #============================================================================== # ■ Window_StatusActor #============================================================================== class Window_StatusActor < Window_Base #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize(dx, dy) super(dx, dy, window_width, fitting_height(4)) @actor = nil end #-------------------------------------------------------------------------- # window_width #-------------------------------------------------------------------------- def window_width; return Graphics.width - 160; end #-------------------------------------------------------------------------- # actor= #-------------------------------------------------------------------------- def actor=(actor) return if @actor == actor @actor = actor refresh end #-------------------------------------------------------------------------- # refresh #-------------------------------------------------------------------------- def refresh contents.clear return unless @actor draw_actor_face(@actor, 0, 0) draw_actor_simple_status(@actor, 108, line_height / 2) end end # Window_StatusActor #============================================================================== # ■ Window_StatusItem #============================================================================== class Window_StatusItem < Window_Base #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize(dx, dy, command_window) super(dx, dy, Graphics.width, Graphics.height - dy) @command_window = command_window @actor = nil refresh end #-------------------------------------------------------------------------- # actor= #-------------------------------------------------------------------------- def actor=(actor) return if @actor == actor @actor = actor refresh end #-------------------------------------------------------------------------- # refresh #-------------------------------------------------------------------------- def refresh contents.clear reset_font_settings return unless @actor draw_window_contents end #-------------------------------------------------------------------------- # draw_window_contents #-------------------------------------------------------------------------- def draw_window_contents case @command_window.current_symbol when :general draw_actor_general when :parameters draw_parameter_graph when :properties draw_properties_list when :biography, :rename, :retitle draw_actor_biography else draw_custom end end #-------------------------------------------------------------------------- # draw_actor_general #-------------------------------------------------------------------------- def draw_actor_general change_color(system_color) text = YEA::STATUS::PARAMETERS_VOCAB draw_text(0, 0, contents.width/2, line_height, text, 1) text = YEA::STATUS::EXPERIENCE_VOCAB draw_text(contents.width/2, 0, contents.width/2, line_height, text, 1) draw_general_parameters draw_general_experience end #-------------------------------------------------------------------------- # draw_general_parameters #-------------------------------------------------------------------------- def draw_general_parameters dx = 24 dy = line_height / 2 draw_actor_level(dx, line_height*1+dy, contents.width/2 - 24) draw_actor_param(0, dx, line_height*2+dy, contents.width/2 - 24) draw_actor_param(1, dx, line_height*3+dy, contents.width/2 - 24) draw_actor_param(2, dx, line_height*4+dy, contents.width/4 - 12) draw_actor_param(4, dx, line_height*5+dy, contents.width/4 - 12) draw_actor_param(6, dx, line_height*6+dy, contents.width/4 - 12) dx += contents.width/4 - 12 draw_actor_param(3, dx, line_height*4+dy, contents.width/4 - 12) draw_actor_param(5, dx, line_height*5+dy, contents.width/4 - 12) draw_actor_param(7, dx, line_height*6+dy, contents.width/4 - 12) end #-------------------------------------------------------------------------- # draw_actor_level #-------------------------------------------------------------------------- def draw_actor_level(dx, dy, dw) colour = Color.new(0, 0, 0, translucent_alpha/2) rect = Rect.new(dx+1, dy+1, dw-2, line_height-2) contents.fill_rect(rect, colour) change_color(system_color) draw_text(dx+4, dy, dw-8, line_height, Vocab::level) change_color(normal_color) draw_text(dx+4, dy, dw-8, line_height, @actor.level.group, 2) end #-------------------------------------------------------------------------- # draw_actor_param #-------------------------------------------------------------------------- def draw_actor_param(param_id, dx, dy, dw) colour = Color.new(0, 0, 0, translucent_alpha/2) rect = Rect.new(dx+1, dy+1, dw-2, line_height-2) contents.fill_rect(rect, colour) change_color(system_color) draw_text(dx+4, dy, dw-8, line_height, Vocab::param(param_id)) change_color(normal_color) draw_text(dx+4, dy, dw-8, line_height, @actor.param(param_id).group, 2) end #-------------------------------------------------------------------------- # draw_general_experience #-------------------------------------------------------------------------- def draw_general_experience if @actor.max_level? s1 = @actor.exp.group s2 = "-------" s3 = "-------" else s1 = @actor.exp.group s2 = (@actor.next_level_exp - @actor.exp).group s3 = @actor.next_level_exp.group end s_next = sprintf(Vocab::ExpNext, Vocab::level) total_next_text = sprintf(YEA::STATUS::NEXT_TOTAL_VOCAB, Vocab::level) change_color(system_color) dx = contents.width/2 + 12 dy = line_height * 3 / 2 dw = contents.width/2 - 36 draw_text(dx, dy + line_height * 0, dw, line_height, Vocab::ExpTotal) draw_text(dx, dy + line_height * 2, dw, line_height, s_next) draw_text(dx, dy + line_height * 4, dw, line_height, total_next_text) change_color(normal_color) draw_text(dx, dy + line_height * 1, dw, line_height, s1, 2) draw_text(dx, dy + line_height * 3, dw, line_height, s2, 2) draw_text(dx, dy + line_height * 5, dw, line_height, s3, 2) end #-------------------------------------------------------------------------- # draw_parameter_graph #-------------------------------------------------------------------------- def draw_parameter_graph draw_parameter_title dy = line_height * 3/2 maximum = 1 minimum = @actor.param_max(2) for i in 2..7 maximum = [@actor.param(i), maximum].max minimum = [@actor.param(i), minimum].min end maximum += minimum * 0.33 unless maximum == minimum for i in 2..7 rate = calculate_rate(maximum, minimum, i) dy = line_height * i - line_height/2 draw_param_gauge(i, dy, rate) change_color(system_color) draw_text(28, dy, contents.width - 56, line_height, Vocab::param(i)) dw = (contents.width - 48) * rate - 8 change_color(normal_color) draw_text(28, dy, dw, line_height, @actor.param(i).group, 2) end end #-------------------------------------------------------------------------- # calculate_rate #-------------------------------------------------------------------------- def calculate_rate(maximum, minimum, param_id) return 1.0 if maximum == minimum rate = (@actor.param(param_id).to_f - minimum) / (maximum - minimum).to_f rate *= 0.67 rate += 0.33 return rate end #-------------------------------------------------------------------------- # draw_param_gauge #-------------------------------------------------------------------------- def draw_param_gauge(param_id, dy, rate) dw = contents.width - 48 colour1 = param_gauge1(param_id) colour2 = param_gauge2(param_id) draw_gauge(24, dy, dw, rate, colour1, colour2) end #-------------------------------------------------------------------------- # param_gauge1 #-------------------------------------------------------------------------- def param_gauge1(param_id) return YEA::STATUS::PARAM_COLOUR[param_id][1] end #-------------------------------------------------------------------------- # param_gauge2 #-------------------------------------------------------------------------- def param_gauge2(param_id) return YEA::STATUS::PARAM_COLOUR[param_id][2] end #-------------------------------------------------------------------------- # draw_parameter_title #-------------------------------------------------------------------------- def draw_parameter_title colour = Color.new(0, 0, 0, translucent_alpha/2) rect = Rect.new(0, 0, contents.width, contents.height) contents.fill_rect(rect, colour) change_color(system_color) text = YEA::STATUS::PARAMETERS_VOCAB draw_text(0, line_height/3, contents.width, line_height, text, 1) end #-------------------------------------------------------------------------- # draw_properties_list #-------------------------------------------------------------------------- def draw_properties_list contents.font.size = YEA::STATUS::PROPERTIES_FONT_SIZE draw_properties_column1 draw_properties_column2 draw_properties_column3 reset_font_settings end #-------------------------------------------------------------------------- # draw_properties_column1 #-------------------------------------------------------------------------- def draw_properties_column1 dx = 24 dw = (contents.width - 24) / 3 - 24 dy = 0 for property in YEA::STATUS::PROPERTIES_COLUMN1 dy = draw_property(property, dx, dy, dw) end end #-------------------------------------------------------------------------- # draw_properties_column2 #-------------------------------------------------------------------------- def draw_properties_column2 dx = 24 + (contents.width - 24) / 3 dw = (contents.width - 24) / 3 - 24 dy = 0 for property in YEA::STATUS::PROPERTIES_COLUMN2 dy = draw_property(property, dx, dy, dw) end end #-------------------------------------------------------------------------- # draw_properties_column3 #-------------------------------------------------------------------------- def draw_properties_column3 dx = 24 + (contents.width - 24) / 3 * 2 dw = (contents.width - 24) / 3 - 24 dy = 0 for property in YEA::STATUS::PROPERTIES_COLUMN3 dy = draw_property(property, dx, dy, dw) end end #-------------------------------------------------------------------------- # draw_property #-------------------------------------------------------------------------- def draw_property(property, dx, dy, dw) fmt = "%1.2f%%" case property[0] #--- when :hit value = sprintf(fmt, @actor.hit * 100) when :eva value = sprintf(fmt, @actor.eva * 100) when :cri value = sprintf(fmt, @actor.cri * 100) when :cev value = sprintf(fmt, @actor.cev * 100) when :mev value = sprintf(fmt, @actor.mev * 100) when :mrf value = sprintf(fmt, @actor.mrf * 100) when :cnt value = sprintf(fmt, @actor.cnt * 100) when :hrg value = sprintf(fmt, @actor.hrg * 100) when :mrg value = sprintf(fmt, @actor.mrg * 100) when :trg value = sprintf(fmt, @actor.trg * 100) when :tgr value = sprintf(fmt, @actor.tgr * 100) when :grd value = sprintf(fmt, @actor.grd * 100) when :rec value = sprintf(fmt, @actor.rec * 100) when :pha value = sprintf(fmt, @actor.pha * 100) when :mcr value = sprintf(fmt, @actor.mcr * 100) when :tcr value = sprintf(fmt, @actor.tcr * 100) when :pdr value = sprintf(fmt, @actor.pdr * 100) when :mdr value = sprintf(fmt, @actor.mdr * 100) when :fdr value = sprintf(fmt, @actor.fdr * 100) when :exr value = sprintf(fmt, @actor.exr * 100) when :hcr return dy unless $imported["YEA-SkillCostManager"] value = sprintf(fmt, @actor.hcr * 100) when :tcr_y return dy unless $imported["YEA-SkillCostManager"] value = sprintf(fmt, @actor.tcr_y * 100) when :gcr return dy unless $imported["YEA-SkillCostManager"] value = sprintf(fmt, @actor.gcr * 100) when :cdr return dy unless $imported["YEA-SkillRestrictions"] value = sprintf(fmt, @actor.cdr * 100) when :wur return dy unless $imported["YEA-SkillRestrictions"] value = sprintf(fmt, @actor.wur * 100) #--- else; return dy end colour = Color.new(0, 0, 0, translucent_alpha/2) rect = Rect.new(dx+1, dy+1, dw-2, line_height-2) contents.fill_rect(rect, colour) change_color(system_color) draw_text(dx+4, dy, dw-8, line_height, property[1], 0) change_color(normal_color) draw_text(dx+4, dy, dw-8, line_height, value, 2) return dy + line_height end #-------------------------------------------------------------------------- # draw_actor_biography #-------------------------------------------------------------------------- def draw_actor_biography fmt = YEA::STATUS::BIOGRAPHY_NICKNAME_TEXT text = sprintf(fmt, @actor.name, @actor.nickname) contents.font.size = YEA::STATUS::BIOGRAPHY_NICKNAME_SIZE draw_text(0, 0, contents.width, line_height*2, text, 1) reset_font_settings draw_text_ex(24, line_height*2, @actor.description) end #-------------------------------------------------------------------------- # draw_custom #-------------------------------------------------------------------------- def draw_custom current_symbol = @command_window.current_symbol return unless YEA::STATUS::CUSTOM_STATUS_COMMANDS.include?(current_symbol) method(YEA::STATUS::CUSTOM_STATUS_COMMANDS[current_symbol][3]).call end #-------------------------------------------------------------------------- # draw_custom1 #-------------------------------------------------------------------------- def draw_custom1 dx = 0; dy = 0 for skill in @actor.skills next if skill.nil? next unless @actor.added_skill_types.include?(skill.stype_id) draw_item_name(skill, dx, dy) dx = dx == contents.width / 2 + 16 ? 0 : contents.width / 2 + 16 dy += line_height if dx == 0 return if dy + line_height > contents.height end end #-------------------------------------------------------------------------- # draw_custom2 #-------------------------------------------------------------------------- def draw_custom2 dx = 4; dy = 0; slot_id = 0 for equip in @actor.equips change_color(system_color) text = Vocab.etype(@actor.equip_slots[slot_id]) draw_text(dx, dy, contents.width - dx, line_height, text) reset_font_settings draw_item_name(equip, dx+92, dy) unless equip.nil? slot_id += 1 dy += line_height break if dy + line_height > contents.height end dw = Graphics.width * 2 / 5 - 24 dx = contents.width - dw; dy = 0 param_id = 0 8.times do colour = Color.new(0, 0, 0, translucent_alpha/2) rect = Rect.new(dx+1, dy+1, dw - 2, line_height - 2) contents.fill_rect(rect, colour) size = $imported["YEA-AceEquipEngine"] ? YEA::EQUIP::STATUS_FONT_SIZE : 20 contents.font.size = size change_color(system_color) draw_text(dx+4, dy, dw, line_height, Vocab::param(param_id)) change_color(normal_color) dwa = (Graphics.width * 2 / 5 - 2) / 2 draw_text(dx, dy, dwa, line_height, @actor.param(param_id).group, 2) reset_font_settings change_color(system_color) draw_text(dx + dwa, dy, 22, line_height, "→", 1) param_id += 1 dy += line_height break if dy + line_height > contents.height end end #-------------------------------------------------------------------------- # draw_custom3 #-------------------------------------------------------------------------- def draw_custom3 return unless $imported["YEA-ClassSystem"] data = [] for class_id in YEA::CLASS_SYSTEM::CLASS_ORDER next if $data_classes[class_id].nil? item = $data_classes[class_id]
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
true
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Ace_Message_System.rb
Ace_Message_System.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Ace Message System v1.05 # -- Last Updated: 2012.01.13 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-MessageSystem"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.07.21 - Fixed REGEXP error at line 824 # 2012.01.13 - Bug Fixed: Negative tags didn't display other party members. # 2012.01.12 - Compatibility Update: Message Actor Codes # 2012.01.10 - Added Feature: \pic[x] text code. # 2012.01.04 - Bug Fixed: \ic tag was \ii. No longer the case. # - Added: Scroll Text window now uses message window font. # 2011.12.31 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # While RPG Maker VX Ace certainly improved the message system a whole lot, it # wouldn't hurt to add in a few more features, such as name windows, converting # textcodes to write out the icons and/or names of items, weapons, armours, and # more in quicker fashion. This script also gives the developer the ability to # adjust the size of the message window during the game, give it a separate # font, and to give the player a text fast-forward feature. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Message Window text Codes - These go inside of your message window. # ----------------------------------------------------------------------------- # Default: Effect: # \v[x] - Writes variable x's value. # \n[x] - Writes actor x's name. # \p[x] - Writes party member x's name. # \g - Writes gold currency name. # \c[x] - Changes the colour of the text to x. # \i[x] - Draws icon x at position of the text. # \{ - Makes text bigger by 8 points. # \} - Makes text smaller by 8 points. # \$ - Opens gold window. # \. - Waits 15 frames (quarter second). # \| - Waits 60 frames (a full second). # \! - Waits until key is pressed. # \> - Following text is instant. # \< - Following text is no longer instant. # \^ - Skips to the next message. # \\ - Writes a "\" in the window. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Wait: Effect: # \w[x] - Waits x frames (60 frames = 1 second). Message window only. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # NameWindow: Effect: # \n<x> - Creates a name box with x string. Left side. *Note # \nc<x> - Creates a name box with x string. Centered. *Note # \nr<x> - Creates a name box with x string. Right side. *Note # # *Note: Works for message window only. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Position: Effect: # \px[x] - Sets x position of text to x. # \py[x] - Sets y position of text to y. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Picture: Effect: # \pic[x] - Draws picture x from the Graphics\Pictures folder. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Outline: Effect: # \oc[x] - Sets outline colour to x. # \oo[x] - Sets outline opacity to x. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Font: Effect: # \fr - Resets all font changes. # \fz[x] - Changes font size to x. # \fn[x] - Changes font name to x. # \fb - Toggles font boldness. # \fi - Toggles font italic. # \fo - Toggles font outline. # \fs - Toggles font shadow. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Actor: Effect: # \af[x] - Shows face of actor x. *Note # \ac[x] - Writes out actor's class name. *Note # \as[x] - Writes out actor's subclass name. Req: Class System. *Note # \an[x] - Writes out actor's nickname. *Note # # *Note: If x is 0 or negative, it will show the respective # party member's face instead. # 0 - Party Leader # -1 - 1st non-leader member. # -2 - 2nd non-leader member. So on. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Names: Effect: # \nc[x] - Writes out class x's name. # \ni[x] - Writes out item x's name. # \nw[x] - Writes out weapon x's name. # \na[x] - Writes out armour x's name. # \ns[x] - Writes out skill x's name. # \nt[x] - Writes out state x's name. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Icon Names: Effect: # \ic[x] - Writes out class x's name including icon. * # \ii[x] - Writes out item x's name including icon. # \iw[x] - Writes out weapon x's name including icon. # \ia[x] - Writes out armour x's name including icon. # \is[x] - Writes out skill x's name including icon. # \it[x] - Writes out state x's name including icon. # # *Note: Requires YEA - Class System # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # And those are the text codes added with this script. Keep in mind that some # of these text codes only work for the Message Window. Otherwise, they'll work # for help descriptions, actor biographies, and others. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module MESSAGE #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - General Message Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # The following below will adjust the basic settings and that will affect # the majority of the script. Adjust them as you see fit. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # This button is the button used to make message windows instantly skip # forward. Hold down for the effect. Note that when held down, this will # speed up the messages, but still wait for the pauses. However, it will # automatically go to the next page when prompted. TEXT_SKIP = :A # Input::A is the shift button on keyboard. # This variable adjusts the number of visible rows shown in the message # window. If you do not wish to use this feature, set this constant to 0. # If the row value is 0 or below, it will automatically default to 4 rows. VARIABLE_ROWS = 21 # This variable adjusts the width of the message window shown. If you do # not wish to use this feature, set this constant to 0. If the width value # is 0 or below, it will automatically default to the screen width. VARIABLE_WIDTH = 22 # This is the amount of space that the message window will indent whenever # a face is used. Default: 112 FACE_INDENT_X = 112 #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Name Window Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # The name window is a window that appears outside of the main message # window box to display whatever text is placed inside of it like a name. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- NAME_WINDOW_X_BUFFER = -20 # Buffer x position of the name window. NAME_WINDOW_Y_BUFFER = 0 # Buffer y position of the name window. NAME_WINDOW_PADDING = 20 # Padding added to the horizontal position. NAME_WINDOW_OPACITY = 255 # Opacity of the name window. NAME_WINDOW_COLOUR = 6 # Text colour used by default for names. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Message Font Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Ace Message System separates the in-game system font form the message # font. Adjust the settings here for your fonts. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # This array constant determines the fonts used. If the first font does not # exist on the player's computer, the next font in question will be used # in place instead and so on. MESSAGE_WINDOW_FONT_NAME = ["Verdana", "Arial", "Courier New"] # These adjust the other settings regarding the way the game font appears # including the font size, whether or not the font is bolded by default, # italic by default, etc. MESSAGE_WINDOW_FONT_SIZE = 24 # Font size. MESSAGE_WINDOW_FONT_BOLD = false # Default bold? MESSAGE_WINDOW_FONT_ITALIC = false # Default italic? MESSAGE_WINDOW_FONT_OUTLINE = true # Default outline? MESSAGE_WINDOW_FONT_SHADOW = false # Default shadow? end # MESSAGE end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== #============================================================================== # ■ Variable #============================================================================== module Variable #-------------------------------------------------------------------------- # self.message_rows #-------------------------------------------------------------------------- def self.message_rows return 4 if YEA::MESSAGE::VARIABLE_ROWS <= 0 return 4 if $game_variables[YEA::MESSAGE::VARIABLE_ROWS] <= 0 return $game_variables[YEA::MESSAGE::VARIABLE_ROWS] end #-------------------------------------------------------------------------- # self.message_width #-------------------------------------------------------------------------- def self.message_width return Graphics.width if YEA::MESSAGE::VARIABLE_WIDTH <= 0 return Graphics.width if $game_variables[YEA::MESSAGE::VARIABLE_WIDTH] <= 0 return $game_variables[YEA::MESSAGE::VARIABLE_WIDTH] end end # Variable #============================================================================== # ■ Game_Interpreter #============================================================================== class Game_Interpreter #-------------------------------------------------------------------------- # overwrite method: command_101 #-------------------------------------------------------------------------- def command_101 wait_for_message $game_message.face_name = @params[0] $game_message.face_index = @params[1] $game_message.background = @params[2] $game_message.position = @params[3] while continue_message_string? @index += 1 if @list[@index].code == 401 $game_message.add(@list[@index].parameters[0]) end break if $game_message.texts.size >= Variable.message_rows end case next_event_code when 102 @index += 1 setup_choices(@list[@index].parameters) when 103 @index += 1 setup_num_input(@list[@index].parameters) when 104 @index += 1 setup_item_choice(@list[@index].parameters) end wait_for_message end #-------------------------------------------------------------------------- # new method: continue_message_string? #-------------------------------------------------------------------------- def continue_message_string? return true if next_event_code == 101 && Variable.message_rows > 4 return next_event_code == 401 end end # Game_Interpreter #============================================================================== # ■ Window_Base #============================================================================== class Window_Base < Window #-------------------------------------------------------------------------- # new method: setup_message_font #-------------------------------------------------------------------------- def setup_message_font @message_font = true change_color(normal_color) contents.font.out_color = Font.default_out_color contents.font.name = YEA::MESSAGE::MESSAGE_WINDOW_FONT_NAME contents.font.size = YEA::MESSAGE::MESSAGE_WINDOW_FONT_SIZE contents.font.bold = YEA::MESSAGE::MESSAGE_WINDOW_FONT_BOLD contents.font.italic = YEA::MESSAGE::MESSAGE_WINDOW_FONT_ITALIC contents.font.outline = YEA::MESSAGE::MESSAGE_WINDOW_FONT_OUTLINE contents.font.shadow = YEA::MESSAGE::MESSAGE_WINDOW_FONT_SHADOW end #-------------------------------------------------------------------------- # alias method: reset_font_settings #-------------------------------------------------------------------------- alias window_base_reset_font_settings_ams reset_font_settings def reset_font_settings if @message_font setup_message_font else window_base_reset_font_settings_ams contents.font.out_color = Font.default_out_color contents.font.outline = Font.default_outline contents.font.shadow = Font.default_shadow end end #-------------------------------------------------------------------------- # alias method: convert_escape_characters #-------------------------------------------------------------------------- alias window_base_convert_escape_characters_ams convert_escape_characters def convert_escape_characters(text) result = window_base_convert_escape_characters_ams(text) result = convert_ace_message_system_new_escape_characters(result) return result end #-------------------------------------------------------------------------- # new method: convert_ace_message_system_new_escape_characters #-------------------------------------------------------------------------- def convert_ace_message_system_new_escape_characters(result) #--- result.gsub!(/\eFR/i) { "\eAMSF[0]" } result.gsub!(/\eFB/i) { "\eAMSF[1]" } result.gsub!(/\eFI/i) { "\eAMSF[2]" } result.gsub!(/\eFO/i) { "\eAMSF[3]" } result.gsub!(/\eFS/i) { "\eAMSF[4]" } #--- result.gsub!(/\eAC\[([-+]?\d+)\]/i) { escape_actor_class_name($1.to_i) } result.gsub!(/\eAS\[([-+]?\d+)\]/i) { escape_actor_subclass_name($1.to_i) } result.gsub!(/\eAN\[([-+]?\d+)\]/i) { escape_actor_nickname($1.to_i) } #--- result.gsub!(/\eNC\[(\d+)\]/i) { $data_classes[$1.to_i].name } result.gsub!(/\eNI\[(\d+)\]/i) { $data_items[$1.to_i].name } result.gsub!(/\eNW\[(\d+)\]/i) { $data_weapons[$1.to_i].name } result.gsub!(/\eNA\[(\d+)\]/i) { $data_armors[$1.to_i].name } result.gsub!(/\eNS\[(\d+)\]/i) { $data_skills[$1.to_i].name } result.gsub!(/\eNT\[(\d+)\]/i) { $data_states[$1.to_i].name } #--- result.gsub!(/\eIC\[(\d+)\]/i) { escape_icon_item($1.to_i, :class) } result.gsub!(/\eII\[(\d+)\]/i) { escape_icon_item($1.to_i, :item) } result.gsub!(/\eIW\[(\d+)\]/i) { escape_icon_item($1.to_i, :weapon) } result.gsub!(/\eIA\[(\d+)\]/i) { escape_icon_item($1.to_i, :armour) } result.gsub!(/\eIS\[(\d+)\]/i) { escape_icon_item($1.to_i, :skill) } result.gsub!(/\eIT\[(\d+)\]/i) { escape_icon_item($1.to_i, :state) } #--- return result end #-------------------------------------------------------------------------- # new method: escape_actor_class_name #-------------------------------------------------------------------------- def escape_actor_class_name(actor_id) actor_id = $game_party.members[actor_id.abs].id if actor_id <= 0 actor = $game_actors[actor_id] return "" if actor.nil? return actor.class.name end #-------------------------------------------------------------------------- # new method: actor_subclass_name #-------------------------------------------------------------------------- def escape_actor_subclass_name(actor_id) return "" unless $imported["YEA-ClassSystem"] actor_id = $game_party.members[actor_id.abs].id if actor_id <= 0 actor = $game_actors[actor_id] return "" if actor.nil? return "" if actor.subclass.nil? return actor.subclass.name end #-------------------------------------------------------------------------- # new method: escape_actor_nickname #-------------------------------------------------------------------------- def escape_actor_nickname(actor_id) actor_id = $game_party.members[actor_id.abs].id if actor_id <= 0 actor = $game_actors[actor_id] return "" if actor.nil? return actor.nickname end #-------------------------------------------------------------------------- # new method: escape_icon_item #-------------------------------------------------------------------------- def escape_icon_item(data_id, type) case type when :class return "" unless $imported["YEA-ClassSystem"] icon = $data_classes[data_id].icon_index name = $data_items[data_id].name when :item icon = $data_items[data_id].icon_index name = $data_items[data_id].name when :weapon icon = $data_weapons[data_id].icon_index name = $data_weapons[data_id].name when :armour icon = $data_armors[data_id].icon_index name = $data_armors[data_id].name when :skill icon = $data_skills[data_id].icon_index name = $data_skills[data_id].name when :state icon = $data_states[data_id].icon_index name = $data_states[data_id].name else; return "" end text = "\eI[#{icon}]" + name return text end #-------------------------------------------------------------------------- # alias method: process_escape_character #-------------------------------------------------------------------------- alias window_base_process_escape_character_ams process_escape_character def process_escape_character(code, text, pos) case code.upcase #--- when 'FZ' contents.font.size = obtain_escape_param(text) when 'FN' text.sub!(/\[(.*?)\]/, "") font_name = $1.to_s font_name = Font.default_name if font_name.nil? contents.font.name = font_name.to_s #--- when 'OC' colour = text_color(obtain_escape_param(text)) contents.font.out_color = colour when 'OO' contents.font.out_color.alpha = obtain_escape_param(text) #--- when 'AMSF' case obtain_escape_param(text) when 0; reset_font_settings when 1; contents.font.bold = !contents.font.bold when 2; contents.font.italic = !contents.font.italic when 3; contents.font.outline = !contents.font.outline when 4; contents.font.shadow = !contents.font.shadow end #--- when 'PX' pos[:x] = obtain_escape_param(text) when 'PY' pos[:y] = obtain_escape_param(text) #--- when 'PIC' text.sub!(/\[(.*?)\]/, "") bmp = Cache.picture($1.to_s) rect = Rect.new(0, 0, bmp.width, bmp.height) contents.blt(pos[:x], pos[:y], bmp, rect) #--- else window_base_process_escape_character_ams(code, text, pos) end end end # Window_Base #============================================================================== # ■ Window_ChoiceList #============================================================================== class Window_ChoiceList < Window_Command #-------------------------------------------------------------------------- # alias method: initialize #-------------------------------------------------------------------------- alias window_choicelist_initialize_ams initialize def initialize(message_window) window_choicelist_initialize_ams(message_window) setup_message_font end end # Window_ChoiceList #============================================================================== # ■ Window_ScrollText #============================================================================== class Window_ScrollText < Window_Base #-------------------------------------------------------------------------- # alias method: initialize #-------------------------------------------------------------------------- alias window_scrolltext_initialize_ams initialize def initialize window_scrolltext_initialize_ams setup_message_font end end # Window_ScrollText #============================================================================== # ■ Window_NameMessage #============================================================================== class Window_NameMessage < Window_Base #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize(message_window) @message_window = message_window super(0, 0, Graphics.width, fitting_height(1)) self.opacity = YEA::MESSAGE::NAME_WINDOW_OPACITY self.z = @message_window.z + 1 self.openness = 0 setup_message_font @close_counter = 0 deactivate end #-------------------------------------------------------------------------- # update #-------------------------------------------------------------------------- def update super return if self.active return if self.openness == 0 return if @closing @close_counter -= 1 return if @close_counter > 0 close end #-------------------------------------------------------------------------- # start_close #-------------------------------------------------------------------------- def start_close @close_counter = 4 deactivate end #-------------------------------------------------------------------------- # force_close #-------------------------------------------------------------------------- def force_close @close_counter = 0 deactivate close end #-------------------------------------------------------------------------- # start #-------------------------------------------------------------------------- def start(text, x_position) @text = text.clone set_width create_contents set_x_position(x_position) set_y_position refresh activate open end #-------------------------------------------------------------------------- # set_width #-------------------------------------------------------------------------- def set_width text = @text.clone dw = standard_padding * 2 + text_size(text).width dw += YEA::MESSAGE::NAME_WINDOW_PADDING * 2 dw += calculate_size(text.slice!(0, 1), text) until text.empty? self.width = dw end #-------------------------------------------------------------------------- # calculate_size #-------------------------------------------------------------------------- def calculate_size(code, text) case code when "\e" return calculate_escape_code_width(obtain_escape_code(text), text) else return 0 end end #-------------------------------------------------------------------------- # calculate_escape_code_width #-------------------------------------------------------------------------- def calculate_escape_code_width(code, text) dw = -text_size("\e").width - text_size(code).width case code.upcase when 'C', 'OC', 'OO' dw += -text_size("[" + obtain_escape_param(text).to_s + "]").width return dw when 'I' dw += -text_size("[" + obtain_escape_param(text).to_s + "]").width dw += 24 return dw when '{' make_font_bigger when '}' make_font_smaller when 'FZ' contents.font.size = obtain_escape_param(text) when 'FN' text.sub!(/\[(.*?)\]/, "") font_name = $1.to_s font_name = Font.default_name if font_name.nil? contents.font.name = font_name.to_s when 'AMSF' case obtain_escape_param(text) when 0; reset_font_settings when 1; contents.font.bold = !contents.font.bold when 2; contents.font.italic = !contents.font.italic when 3; contents.font.outline = !contents.font.outline when 4; contents.font.shadow = !contents.font.shadow end else return dw end end #-------------------------------------------------------------------------- # set_y_position #-------------------------------------------------------------------------- def set_x_position(x_position) case x_position when 1 # Left self.x = @message_window.x self.x += YEA::MESSAGE::NAME_WINDOW_X_BUFFER when 2 # 3/10 self.x = @message_window.x self.x += @message_window.width * 3 / 10 self.x -= self.width / 2 when 3 # Center self.x = @message_window.x self.x += @message_window.width / 2 self.x -= self.width / 2 when 4 # 7/10 self.x = @message_window.x self.x += @message_window.width * 7 / 10 self.x -= self.width / 2 when 5 # Right self.x = @message_window.x + @message_window.width self.x -= self.width self.x -= YEA::MESSAGE::NAME_WINDOW_X_BUFFER end self.x = [[self.x, Graphics.width - self.width].min, 0].max end #-------------------------------------------------------------------------- # set_y_position #-------------------------------------------------------------------------- def set_y_position case $game_message.position when 0 self.y = @message_window.height self.y -= YEA::MESSAGE::NAME_WINDOW_Y_BUFFER else self.y = @message_window.y - self.height self.y += YEA::MESSAGE::NAME_WINDOW_Y_BUFFER end end #-------------------------------------------------------------------------- # refresh #-------------------------------------------------------------------------- def refresh contents.clear reset_font_settings @text = sprintf("\eC[%d]%s", YEA::MESSAGE::NAME_WINDOW_COLOUR, @text) draw_text_ex(YEA::MESSAGE::NAME_WINDOW_PADDING, 0, @text) end end # Window_NameMessage #============================================================================== # ■ Window_Message #============================================================================== class Window_Message < Window_Base #-------------------------------------------------------------------------- # alias method: initialize #-------------------------------------------------------------------------- alias window_message_initialize_ams initialize def initialize window_message_initialize_ams setup_message_font end #-------------------------------------------------------------------------- # overwrite method: window_width #-------------------------------------------------------------------------- def window_width return Variable.message_width end #-------------------------------------------------------------------------- # overwrite method: window_height #-------------------------------------------------------------------------- def window_height return fitting_height(Variable.message_rows) end #-------------------------------------------------------------------------- # alias method: create_all_windows #-------------------------------------------------------------------------- alias window_message_create_all_windows_ams create_all_windows def create_all_windows window_message_create_all_windows_ams @name_window = Window_NameMessage.new(self) end #-------------------------------------------------------------------------- # overwrite method: create_back_bitmap #-------------------------------------------------------------------------- def create_back_bitmap @back_bitmap = Bitmap.new(width, height) rect1 = Rect.new(0, 0, Graphics.width, 12) rect2 = Rect.new(0, 12, Graphics.width, fitting_height(4) - 24) rect3 = Rect.new(0, fitting_height(4) - 12, Graphics.width, 12) @back_bitmap.gradient_fill_rect(rect1, back_color2, back_color1, true) @back_bitmap.fill_rect(rect2, back_color1) @back_bitmap.gradient_fill_rect(rect3, back_color1, back_color2, true) end #-------------------------------------------------------------------------- # alias method: dispose_all_windows #-------------------------------------------------------------------------- alias window_message_dispose_all_windows_ams dispose_all_windows def dispose_all_windows window_message_dispose_all_windows_ams @name_window.dispose end #-------------------------------------------------------------------------- # alias method: update_all_windows #-------------------------------------------------------------------------- alias window_message_update_all_windows_ams update_all_windows def update_all_windows window_message_update_all_windows_ams @name_window.update @name_window.back_opacity = self.back_opacity @name_window.opacity = self.opacity end #-------------------------------------------------------------------------- # alias method: update_show_fast #-------------------------------------------------------------------------- alias window_message_update_show_fast_ams update_show_fast def update_show_fast @show_fast = true if Input.press?(YEA::MESSAGE::TEXT_SKIP) window_message_update_show_fast_ams end #-------------------------------------------------------------------------- # overwrite method: input_pause #-------------------------------------------------------------------------- def input_pause self.pause = true wait(10) Fiber.yield until Input.trigger?(:B) || Input.trigger?(:C) || Input.press?(YEA::MESSAGE::TEXT_SKIP) Input.update self.pause = false end #-------------------------------------------------------------------------- # overwrite method: convert_escape_characters #-------------------------------------------------------------------------- def convert_escape_characters(text) result = super(text.to_s.clone) result = namebox_escape_characters(result) result = message_escape_characters(result) return result end #-------------------------------------------------------------------------- # new method: namebox_escape_characters #-------------------------------------------------------------------------- def namebox_escape_characters(result) result.gsub!(/\eN\<(.+?)\>/i) { namewindow($1, 1) } result.gsub!(/\eN1\<(.+?)\>/i) { namewindow($1, 1) } result.gsub!(/\eN2\<(.+?)\>/i) { namewindow($1, 2) } result.gsub!(/\eNC\<(.+?)\>/i) { namewindow($1, 3) } result.gsub!(/\eN3\<(.+?)\>/i) { namewindow($1, 3) } result.gsub!(/\eN4\<(.+?)\>/i) { namewindow($1, 4) } result.gsub!(/\eN5\<(.+?)\>/i) { namewindow($1, 5) } result.gsub!(/\eNR\<(.+?)\>/i) { namewindow($1, 5) } return result end #-------------------------------------------------------------------------- # new method: namebox #-------------------------------------------------------------------------- def namewindow(text, position) @name_text = text @name_position = position return "" end #-------------------------------------------------------------------------- # new method: message_escape_characters #-------------------------------------------------------------------------- def message_escape_characters(result) result.gsub!(/\eAF\[(-?\d+)]/i) { change_face($1.to_i) } return result end #-------------------------------------------------------------------------- # new method: change_face
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
true
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Convert_Damage.rb
Convert_Damage.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Convert Damage v1.02 # -- Last Updated: 2012.01.23 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-ConvertDamage"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2013.02.17 - Bug fixes. # 2012.01.23 - Compatibility Update: Doppelganger # 2011.12.21 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script gives actors, classes, equipment, enemies, and states passive # convert damage HP/MP traits. By dealing physical or magical damage (dependant # on the type of attack), attackers may recover HP or MP depending on what # kinds of convert damage types they have. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Actor Notetags - These notetags go in the actors notebox in the database. # ----------------------------------------------------------------------------- # <convert hp physical: +x%> # <convert hp physical: -x%> # Converts any physical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert hp magical: +x%> # <convert hp magical: -x%> # Converts any magical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert mp physical: +x%> # <convert mp physical: -x%> # Converts any physical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <convert mp magical: +x%> # <convert mp magical: -x%> # Converts any magical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <anticonvert hp physical> # <anticonvert hp magical> # <anticonvert mp physical> # <anticonvert mp magical> # Prevents attackers from converting damage of those particular types. All # converted recovery effects of that type will be reduced to 0. # # ----------------------------------------------------------------------------- # Class Notetags - These notetags go in the class notebox in the database. # ----------------------------------------------------------------------------- # <convert hp physical: +x%> # <convert hp physical: -x%> # Converts any physical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert hp magical: +x%> # <convert hp magical: -x%> # Converts any magical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert mp physical: +x%> # <convert mp physical: -x%> # Converts any physical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <convert mp magical: +x%> # <convert mp magical: -x%> # Converts any magical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <anticonvert hp physical> # <anticonvert hp magical> # <anticonvert mp physical> # <anticonvert mp magical> # Prevents attackers from converting damage of those particular types. All # converted recovery effects of that type will be reduced to 0. # # ----------------------------------------------------------------------------- # Skill Notetags - These notetags go in the skills notebox in the database. # ----------------------------------------------------------------------------- # <no convert> # Prevents any kind of converted damage effects from being applied when this # skill is used. # # ----------------------------------------------------------------------------- # Item Notetags - These notetags go in the items notebox in the database. # ----------------------------------------------------------------------------- # <no convert> # Prevents any kind of converted damage effects from being applied when this # item is used. # # ----------------------------------------------------------------------------- # Weapon Notetags - These notetags go in the weapons notebox in the database. # ----------------------------------------------------------------------------- # <convert hp physical: +x%> # <convert hp physical: -x%> # Converts any physical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert hp magical: +x%> # <convert hp magical: -x%> # Converts any magical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert mp physical: +x%> # <convert mp physical: -x%> # Converts any physical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <convert mp magical: +x%> # <convert mp magical: -x%> # Converts any magical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <anticonvert hp physical> # <anticonvert hp magical> # <anticonvert mp physical> # <anticonvert mp magical> # Prevents attackers from converting damage of those particular types. All # converted recovery effects of that type will be reduced to 0. # # ----------------------------------------------------------------------------- # Armour Notetags - These notetags go in the armours notebox in the database. # ----------------------------------------------------------------------------- # <convert hp physical: +x%> # <convert hp physical: -x%> # Converts any physical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert hp magical: +x%> # <convert hp magical: -x%> # Converts any magical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert mp physical: +x%> # <convert mp physical: -x%> # Converts any physical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <convert mp magical: +x%> # <convert mp magical: -x%> # Converts any magical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <anticonvert hp physical> # <anticonvert hp magical> # <anticonvert mp physical> # <anticonvert mp magical> # Prevents attackers from converting damage of those particular types. All # converted recovery effects of that type will be reduced to 0. # # ----------------------------------------------------------------------------- # Enemy Notetags - These notetags go in the enemies notebox in the database. # ----------------------------------------------------------------------------- # <convert hp physical: +x%> # <convert hp physical: -x%> # Converts any physical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert hp magical: +x%> # <convert hp magical: -x%> # Converts any magical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert mp physical: +x%> # <convert mp physical: -x%> # Converts any physical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <convert mp magical: +x%> # <convert mp magical: -x%> # Converts any magical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <anticonvert hp physical> # <anticonvert hp magical> # <anticonvert mp physical> # <anticonvert mp magical> # Prevents attackers from converting damage of those particular types. All # converted recovery effects of that type will be reduced to 0. # # ----------------------------------------------------------------------------- # State Notetags - These notetags go in the states notebox in the database. # ----------------------------------------------------------------------------- # <convert hp physical: +x%> # <convert hp physical: -x%> # Converts any physical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert hp magical: +x%> # <convert hp magical: -x%> # Converts any magical damage dealt to recover HP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if HP # to be healed is 0 or below. # # <convert mp physical: +x%> # <convert mp physical: -x%> # Converts any physical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <convert mp magical: +x%> # <convert mp magical: -x%> # Converts any magical damage dealt to recover MP by x% of the damage dealt. # Bonus converted damage rates are additive. There will be no effects if MP # to be healed is 0 or below. # # <anticonvert hp physical> # <anticonvert hp magical> # <anticonvert mp physical> # <anticonvert mp magical> # Prevents attackers from converting damage of those particular types. All # converted recovery effects of that type will be reduced to 0. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # For maximum compatibility with Yanfly Engine Ace - Ace Battle Engine, place # this script under Ace Battle Engine. # #============================================================================== module YEA module CONVERT_DAMAGE #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Limit Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Adjust the maximum converted damage rate for dealing damage (so that an # attacker cannot gain huge amounts of recovery). #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- MAXIMUM_RATE = 1.0 # Maximum gain from dealing damage. end # CONVERT_DAMAGE end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module BASEITEM CONVERT_DMG = /<(?:CONVERT|convert)[ ](.*)[ ](.*):[ ]([\+\-]\d+)([%%])>/i ANTICONVERT = /<(?:ANTI_CONVERT|anti convert|anticonvert)[ ](.*)[ ](.*)>/i end # BASEITEM module USABLEITEM NO_CONVERT = /<(?:NO_CONVERT|no convert)>/i end # USABLEITEM end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_convertdmg load_database; end def self.load_database load_database_convertdmg load_notetags_convertdmg end #-------------------------------------------------------------------------- # new method: load_notetags_convertdmg #-------------------------------------------------------------------------- def self.load_notetags_convertdmg groups = [$data_actors, $data_classes, $data_weapons, $data_armors, $data_enemies, $data_states, $data_skills, $data_items] for group in groups for obj in group next if obj.nil? obj.load_notetags_convertdmg end end end end # DataManager #============================================================================== # ■ RPG::BaseItem #============================================================================== class RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :convert_dmg attr_accessor :anticonvert #-------------------------------------------------------------------------- # common cache: load_notetags_convertdmg #-------------------------------------------------------------------------- def load_notetags_convertdmg @convert_dmg ={ :hp_physical => 0.0, :hp_magical => 0.0, :mp_physical => 0.0, :mp_magical => 0.0, } # Do not remove this. @anticonvert = [] #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::BASEITEM::CONVERT_DMG case $1.upcase when "HP" case $2.upcase when "PHYSICAL"; type = :hp_physical when "MAGICAL"; type = :hp_magical else; next end when "MP" case $2.upcase when "PHYSICAL"; type = :mp_physical when "MAGICAL"; type = :mp_magical else; next end else; next end @convert_dmg[type] = $3.to_i * 0.01 #--- when YEA::REGEXP::BASEITEM::ANTICONVERT case $1.upcase when "HP" case $2.upcase when "PHYSICAL"; type = :hp_physical when "MAGICAL"; type = :hp_magical else; next end when "MP" case $2.upcase when "PHYSICAL"; type = :mp_physical when "MAGICAL"; type = :mp_magical else; next end else; next end @anticonvert.push(type) #--- end } # self.note.split #--- end end # RPG::BaseItem #============================================================================== # ■ RPG::UsableItem #============================================================================== class RPG::UsableItem < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :no_convert #-------------------------------------------------------------------------- # common cache: load_notetags_convertdmg #-------------------------------------------------------------------------- def load_notetags_convertdmg #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::USABLEITEM::NO_CONVERT @no_convert = true #--- end } # self.note.split #--- end end # RPG::UsableItem #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # new method: convert_dmg_rate #-------------------------------------------------------------------------- def convert_dmg_rate(type) n = 0.0 if actor? n += self.actor.convert_dmg[type] n += self.class.convert_dmg[type] for equip in equips next if equip.nil? n += equip.convert_dmg[type] end else n += self.enemy.convert_dmg[type] if $imported["YEA-Doppelganger"] && !self.class.nil? n += self.class.convert_dmg[type] end end for state in states next if state.nil? n += state.convert_dmg[type] end max_rate = YEA::CONVERT_DAMAGE::MAXIMUM_RATE return [[n, max_rate].min, -max_rate].max end #-------------------------------------------------------------------------- # new method: anti_convert? #-------------------------------------------------------------------------- def anti_convert?(type) if actor? return true if self.actor.anticonvert.include?(type) return true if self.class.anticonvert.include?(type) for equip in equips next if equip.nil? return true if equip.anticonvert.include?(type) end else return true if self.enemy.anticonvert.include?(type) end for state in states next if state.nil? return true if state.anticonvert.include?(type) end return false end end # Game_BattlerBase #============================================================================== # ■ Game_Battler #============================================================================== class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # alias method: execute_damage #-------------------------------------------------------------------------- alias game_battler_execute_damage_convertdmg execute_damage def execute_damage(user) apply_vampire_effects(user) game_battler_execute_damage_convertdmg(user) end #-------------------------------------------------------------------------- # new method: apply_vampire_effect #-------------------------------------------------------------------------- def apply_vampire_effects(user) return unless $game_party.in_battle return unless @result.hp_damage > 0 || @result.mp_damage > 0 return if user.current_action.nil? action = user.current_action.item return if action.no_convert apply_convert_physical_effect(user) if action.physical? apply_convert_magical_effect(user) if action.magical? end #-------------------------------------------------------------------------- # new method: apply_convert_physical_effect #-------------------------------------------------------------------------- def apply_convert_physical_effect(user) hp_rate = user.convert_dmg_rate(:hp_physical) hp_rate = 0 if anti_convert?(:hp_physical) hp_healed = (@result.hp_damage * hp_rate).to_i mp_rate = user.convert_dmg_rate(:mp_physical) mp_rate = 0 if anti_convert?(:mp_physical) mp_healed = (@result.mp_damage * mp_rate).to_i if hp_healed != 0 user.hp += hp_healed make_ace_battle_engine_convert_hp_popup(user, hp_healed) end if mp_healed != 0 user.mp += mp_healed make_ace_battle_engine_convert_mp_popup(user, mp_healed) end end #-------------------------------------------------------------------------- # new method: apply_convert_magical_effect #-------------------------------------------------------------------------- def apply_convert_magical_effect(user) hp_rate = user.convert_dmg_rate(:hp_magical) hp_rate = 0 if anti_convert?(:hp_magical) hp_healed = (@result.hp_damage * hp_rate).to_i mp_rate = user.convert_dmg_rate(:mp_magical) mp_rate = 0 if anti_convert?(:mp_magical) mp_healed = (@result.mp_damage * mp_rate).to_i if hp_healed != 0 user.hp += hp_healed make_ace_battle_engine_convert_hp_popup(user, hp_healed) end if mp_healed != 0 user.mp += mp_healed make_ace_battle_engine_convert_mp_popup(user, mp_healed) end end #-------------------------------------------------------------------------- # new method: make_ace_battle_engine_convert_hp_popup #-------------------------------------------------------------------------- def make_ace_battle_engine_convert_hp_popup(user, hp_healed) return unless $imported["YEA-BattleEngine"] setting = hp_healed > 0 ? :hp_heal : :hp_dmg rules = hp_healed > 0 ? "HP_HEAL" : "HP_DMG" value = hp_healed.abs text = sprintf(YEA::BATTLE::POPUP_SETTINGS[setting], value.group) user.create_popup(text, rules) end #-------------------------------------------------------------------------- # new method: make_ace_battle_engine_convert_mp_popup #-------------------------------------------------------------------------- def make_ace_battle_engine_convert_mp_popup(user, mp_healed) return unless $imported["YEA-BattleEngine"] setting = mp_healed > 0 ? :mp_heal : :mp_dmg rules = mp_healed > 0 ? "MP_HEAL" : "MP_DMG" value = mp_healed.abs text = sprintf(YEA::BATTLE::POPUP_SETTINGS[setting], value.group) user.create_popup(text, rules) end end # Game_Battler #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Skill_Cost_Manager.rb
Skill_Cost_Manager.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Skill Cost Manager v1.03 # -- Last Updated: 2012.01.23 # -- Level: Normal, Hard, Lunatic # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-SkillCostManager"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.08.06 - Restore SP-Paramater: TCR # 2012.01.23 - Compatibility Update: Doppelganger # 2011.12.11 - Started Script and Finished. # - Added max and min notetags. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script adds more functionality towards skill costs. Skills can now cost # HP, more MP, more TP, gold, and even have custom costs. The way the skill # costs are drawn in the display windows are changed to deliver more effective # and reliable information to the player. And if four skill costs aren't enough # to satisfy you, you can even make your own custom skill costs. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Actor Notetags - These notetags go in the actors notebox in the database. # ----------------------------------------------------------------------------- # <hp cost rate: x%> # Allows the actor to drop the HP cost of skills to x%. # # <tp cost rate: x%> # Allows the actor to drop the TP cost of skills to x%. # # <gold cost rate: x%> # Allows the actor to drop the Gold cost of skills to x%. # # ----------------------------------------------------------------------------- # Class Notetags - These notetags go in the class notebox in the database. # ----------------------------------------------------------------------------- # <hp cost rate: x%> # Allows the class to drop the HP cost of skills to x%. # # <tp cost rate: x%> # Allows the class to drop the TP cost of skills to x%. # # <gold cost rate: x%> # Allows the class to drop the Gold cost of skills to x%. # # ----------------------------------------------------------------------------- # Skill Notetags - These notetags go in the skills notebox in the database. # ----------------------------------------------------------------------------- # <hp cost: x> # Sets the skill's HP cost to x. This function did not exist by default in # RPG Maker VX Ace. # # <hp cost: x%> # Sets the HP cost to a percentage of the actor's MaxHP. If a normal HP cost is # present on the skill, too, then this value is added to the HP cost. # # <hp cost max: x> # <hp cost min: x> # Sets the maximum and minimum range of the HP Cost of the skill. If you do not # use this tag, there will be no maximum and/or minimum range. # # <mp cost: x> # Sets the skill's MP cost to x. Allows MP cost to exceed 9999, which is RPG # Maker VX Ace's database editor's maximum limit. # # <mp cost: x%> # Sets the MP cost to a percentage of the actor's MaxMP. If a normal MP cost is # present on the skill, too, then this value is added to the MP cost. # # <mp cost max: x> # <mp cost min: x> # Sets the maximum and minimum range of the MP Cost of the skill. If you do not # use this tag, there will be no maximum and/or minimum range. # # <tp cost: x> # Sets the skill's TP cost to x. Allows TP cost to exceed 100, which is RPG # Maker VX Ace's database editor's maximum limit. # # <tp cost: x%> # Sets the TP cost to a percentage of the actor's MaxTP. If a normal TP cost is # present on the skill, too, then this value is added to the TP cost. # # <tp cost max: x> # <tp cost min: x> # Sets the maximum and minimum range of the TP Cost of the skill. If you do not # use this tag, there will be no maximum and/or minimum range. # # <gold cost: x> # Sets the skill's gold cost to x. Enemies with skills that cost gold do not # use gold. If the player does not have enough gold, the skill can't be used. # # <gold cost: x%> # Sets the skill's gold cost equal to a percentage of the party's total gold. # If both a regular gold cost and a percentile gold cost is used, the total of # both values will be the skill's gold cost. # # <gold cost max: x> # <gold cost min: x> # Sets the maximum and minimum range of the Gold Cost of the skill. If you do # not use this tag, there will be no maximum and/or minimum range. # # --- Making Your Own Custom Costs --- # # <custom cost: string> # If you decide to have a custom cost for your game, insert this notetag to # change what displays in the skill menu visually. # # <custom cost colour: x> # This is the "Window" skin text colour used for the custom cost. By default, # it is text colour 0, which is the white colour. # # <custom cost size: x> # This is the text font size used for the custom cost in the display windows. # By default, it is font size 20. # # <custom cost icon: x> # If you wish to use an icon for your custom cost, replace x with the icon ID # you wish to show in display windows. By default, it is 0 (and not shown). # # <custom cost requirement> # string # string # </custom cost requirement> # Sets the custom cost requirement of the skill with an eval function using the # strings in between. The strings are a part of one line even if in the notebox # they are on separate lines. # # <custom cost perform> # string # string # </custom cost perform> # Sets how the custom cost payment is done with an eval function using the # strings in between. The strings are a part of one line even if in the notebox # they are on separate lines. # # ----------------------------------------------------------------------------- # Weapon Notetags - These notetags go in the weapons notebox in the database. # ----------------------------------------------------------------------------- # <hp cost rate: x%> # Allows the weapon to drop the HP cost of skills to x% when worn. # # <tp cost rate: x%> # Allows the weapon to drop the TP cost of skills to x% when worn. # # <gold cost rate: x%> # Allows the weapon to drop the Gold cost of skills to x% when worn. # # ----------------------------------------------------------------------------- # Armour Notetags - These notetags go in the armours notebox in the database. # ----------------------------------------------------------------------------- # <hp cost rate: x%> # Allows the armour to drop the HP cost of skills to x% when worn. # # <tp cost rate: x%> # Allows the armour to drop the TP cost of skills to x% when worn. # # <gold cost rate: x%> # Allows the armour to drop the TP cost of skills to x% when worn. # # ----------------------------------------------------------------------------- # Enemy Notetags - These notetags go in the enemies notebox in the database. # ----------------------------------------------------------------------------- # <hp cost rate: x%> # Allows the enemy to drop the HP cost of skills to x%. # # <tp cost rate: x%> # Allows the enemy to drop the TP cost of skills to x%. # # ----------------------------------------------------------------------------- # State Notetags - These notetags go in the states notebox in the database. # ----------------------------------------------------------------------------- # <hp cost rate: x%> # Allows the state to drop the HP cost of skills to x% when afflicted. # # <tp cost rate: x%> # Allows the state to drop the TP cost of skills to x% when afflicted. # # <gold cost rate: x%> # Allows the state to drop the Gold cost of skills to x% when afflicted. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module SKILL_COST #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - HP Cost Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # New to this script are HP costs. HP costs require the battler to have # sufficient HP before being able to use the skill. The text colour that's # used, the suffix, or whether or not to use an icon. If you do not wish # to use an icon, set the icon to 0. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- HP_COST_COLOUR = 21 # Colour used from "Window" skin. HP_COST_SIZE = 20 # Font size used for HP costs. HP_COST_SUFFIX = "%sHP" # Suffix used for HP costs. HP_COST_ICON = 0 # Icon used for HP costs. Set 0 to disable. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - MP Cost Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Here, you can change the settings for MP costs: the text colour that's # used, the suffix, or whether or not to use an icon. If you do not wish # to use an icon, set the icon to 0. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- MP_COST_COLOUR = 23 # Colour used from "Window" skin. Default: 23 MP_COST_SIZE = 20 # Font size used for MP costs. Default: 24 MP_COST_SUFFIX = "%sMP" # Suffix used for MP costs. No suffix default. MP_COST_ICON = 0 # Icon used for MP costs. Set 0 to disable. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - TP Cost Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Here, you can change the settings for TP costs: the text colour that's # used, the suffix, or whether or not to use an icon. If you do not wish # to use an icon, set the icon to 0. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- TP_COST_COLOUR = 2 # Colour used from "Window" skin. Default: 29 TP_COST_SIZE = 20 # Font size used for TP costs. Default: 24 TP_COST_SUFFIX = "%sTP" # Suffix used for TP costs. No suffix default. TP_COST_ICON = 0 # Icon used for TP costs. Set 0 to disable. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Gold Cost Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # New to this script are Gold costs. Gold costs require the party to have # enough gold before being able to use the skill. The text colour that's # used, the suffix, or whether or not to use an icon. If you do not wish # to use an icon, set the icon to 0. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- GOLD_COST_COLOUR = 6 # Colour used from "Window" skin. GOLD_COST_SIZE = 20 # Font size used for Gold costs. GOLD_COST_SUFFIX = "%sGold" # Suffix used for Gold costs. GOLD_COST_ICON = 0 # Icon used for Gold costs. Set 0 to disable. end # SKILL_COST end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module BASEITEM HP_COST_RATE = /<(?:HP_COST_RATE|hp cost rate):[ ](\d+)([%%])>/i TP_COST_RATE = /<(?:TP_COST_RATE|tp cost rate):[ ](\d+)([%%])>/i GOLD_COST_RATE = /<(?:GOLD_COST_RATE|gold cost rate):[ ](\d+)([%%])>/i end # BASEITEM module SKILL HP_COST_SET = /<(?:HP_COST|hp cost):[ ](\d+)>/i HP_COST_PER = /<(?:HP_COST|hp cost):[ ](\d+)([%%])>/i MP_COST_SET = /<(?:MP_COST|mp cost):[ ](\d+)>/i MP_COST_PER = /<(?:MP_COST|mp cost):[ ](\d+)([%%])>/i TP_COST_SET = /<(?:TP_COST|tp cost):[ ](\d+)>/i TP_COST_PER = /<(?:TP_COST|tp cost):[ ](\d+)([%%])>/i GOLD_COST_SET = /<(?:GOLD_COST|gold cost):[ ](\d+)>/i GOLD_COST_PER = /<(?:GOLD_COST|gold cost):[ ](\d+)([%%])>/i CUSTOM_COST_TEXT = /<(?:CUSTOM_COST|custom cost):[ ](.*)>/i CUSTOM_COST_COLOUR = /<(?:CUSTOM_COST_COLOUR|custom cost colour|custom cost color):[ ](\d+)>/i CUSTOM_COST_SIZE = /<(?:CUSTOM_COST_SIZE|custom cost size):[ ](\d+)>/i CUSTOM_COST_ICON = /<(?:CUSTOM_COST_ICON|custom cost icon):[ ](\d+)>/i CUSTOM_COST_REQUIREMENT_ON = /<(?:CUSTOM_COST_REQUIREMENT|custom cost requirement)>/i CUSTOM_COST_REQUIREMENT_OFF = /<\/(?:CUSTOM_COST_REQUIREMENT|custom cost requirement)>/i CUSTOM_COST_PERFORM_ON = /<(?:CUSTOM_COST_PERFORM|custom cost perform)>/i CUSTOM_COST_PERFORM_OFF = /<\/(?:CUSTOM_COST_PERFORM|custom cost perform)>/i HP_COST_MIN = /<(?:HP_COST_MIN|hp cost min):[ ](\d+)>/i HP_COST_MAX = /<(?:HP_COST_MIN|hp cost max):[ ](\d+)>/i MP_COST_MIN = /<(?:MP_COST_MIN|mp cost min):[ ](\d+)>/i MP_COST_MAX = /<(?:MP_COST_MIN|mp cost max):[ ](\d+)>/i TP_COST_MIN = /<(?:TP_COST_MIN|tp cost min):[ ](\d+)>/i TP_COST_MAX = /<(?:TP_COST_MIN|tp cost max):[ ](\d+)>/i GOLD_COST_MIN = /<(?:GOLD_COST_MIN|gold cost min):[ ](\d+)>/i GOLD_COST_MAX = /<(?:GOLD_COST_MIN|gold cost max):[ ](\d+)>/i end # SKILL end # REGEXP end # YEA #============================================================================== # ■ Icon #============================================================================== module Icon #-------------------------------------------------------------------------- # self.mp_cost #-------------------------------------------------------------------------- def self.mp_cost; return YEA::SKILL_COST::MP_COST_ICON; end #-------------------------------------------------------------------------- # self.tp_cost #-------------------------------------------------------------------------- def self.tp_cost; return YEA::SKILL_COST::TP_COST_ICON; end #-------------------------------------------------------------------------- # self.hp_cost #-------------------------------------------------------------------------- def self.hp_cost; return YEA::SKILL_COST::HP_COST_ICON; end #-------------------------------------------------------------------------- # self.gold_cost #-------------------------------------------------------------------------- def self.gold_cost; return YEA::SKILL_COST::GOLD_COST_ICON; end end # Icon #============================================================================== # ■ Numeric #============================================================================== class Numeric #-------------------------------------------------------------------------- # new method: group_digits #-------------------------------------------------------------------------- unless $imported["YEA-CoreEngine"] def group; return self.to_s; end end # $imported["YEA-CoreEngine"] end # Numeric #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_scm load_database; end def self.load_database load_database_scm load_notetags_scm end #-------------------------------------------------------------------------- # new method: load_notetags_scm #-------------------------------------------------------------------------- def self.load_notetags_scm groups = [$data_actors, $data_classes, $data_skills, $data_weapons, $data_armors, $data_enemies, $data_states] for group in groups for obj in group next if obj.nil? obj.load_notetags_scm end end end end # DataManager #============================================================================== # ■ RPG::BaseItem #============================================================================== class RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :tp_cost_rate attr_accessor :hp_cost_rate attr_accessor :gold_cost_rate #-------------------------------------------------------------------------- # common cache: load_notetags_scm #-------------------------------------------------------------------------- def load_notetags_scm @tp_cost_rate = 1.0 @hp_cost_rate = 1.0 @gold_cost_rate = 1.0 #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::BASEITEM::TP_COST_RATE @tp_cost_rate = $1.to_i * 0.01 when YEA::REGEXP::BASEITEM::HP_COST_RATE @hp_cost_rate = $1.to_i * 0.01 when YEA::REGEXP::BASEITEM::GOLD_COST_RATE @gold_cost_rate = $1.to_i * 0.01 #--- end } # self.note.split #--- end end # RPG::BaseItem #============================================================================== # ■ RPG::Skill #============================================================================== class RPG::Skill < RPG::UsableItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :hp_cost attr_accessor :hp_cost_percent attr_accessor :mp_cost_percent attr_accessor :tp_cost_percent attr_accessor :gold_cost attr_accessor :gold_cost_percent attr_accessor :hp_cost_min attr_accessor :hp_cost_max attr_accessor :mp_cost_min attr_accessor :mp_cost_max attr_accessor :tp_cost_min attr_accessor :tp_cost_max attr_accessor :gold_cost_min attr_accessor :gold_cost_max attr_accessor :use_custom_cost attr_accessor :custom_cost_text attr_accessor :custom_cost_colour attr_accessor :custom_cost_size attr_accessor :custom_cost_icon attr_accessor :custom_cost_requirement attr_accessor :custom_cost_perform #-------------------------------------------------------------------------- # common cache: load_notetags_scm #-------------------------------------------------------------------------- def load_notetags_scm @hp_cost = 0 @gold_cost = 0 @hp_cost_percent = 0.0 @mp_cost_percent = 0.0 @tp_cost_percent = 0.0 @gold_cost_percent = 0.0 @custom_cost_text = "0" @custom_cost_colour = 0 @custom_cost_size = 20 @custom_cost_icon = 0 @custom_cost_requirement = "" @custom_cost_perform = "" @use_custom_cost = false @custom_cost_req_on = false @custom_cost_per_on = false #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::SKILL::MP_COST_SET @mp_cost = $1.to_i when YEA::REGEXP::SKILL::MP_COST_PER @mp_cost_percent = $1.to_i * 0.01 when YEA::REGEXP::SKILL::TP_COST_SET @tp_cost = $1.to_i when YEA::REGEXP::SKILL::TP_COST_PER @tp_cost_percent = $1.to_i * 0.01 when YEA::REGEXP::SKILL::HP_COST_SET @hp_cost = $1.to_i when YEA::REGEXP::SKILL::HP_COST_PER @hp_cost_percent = $1.to_i * 0.01 when YEA::REGEXP::SKILL::GOLD_COST_SET @gold_cost = $1.to_i when YEA::REGEXP::SKILL::GOLD_COST_PER @gold_cost_percent = $1.to_i * 0.01 #--- when YEA::REGEXP::SKILL::HP_COST_MIN @hp_cost_min = $1.to_i when YEA::REGEXP::SKILL::HP_COST_MAX @hp_cost_max = $1.to_i when YEA::REGEXP::SKILL::MP_COST_MIN @mp_cost_min = $1.to_i when YEA::REGEXP::SKILL::MP_COST_MAX @mp_cost_max = $1.to_i when YEA::REGEXP::SKILL::TP_COST_MIN @tp_cost_min = $1.to_i when YEA::REGEXP::SKILL::TP_COST_MAX @tp_cost_max = $1.to_i when YEA::REGEXP::SKILL::GOLD_COST_MIN @gold_cost_min = $1.to_i when YEA::REGEXP::SKILL::GOLD_COST_MAX @gold_cost_max = $1.to_i #--- when YEA::REGEXP::SKILL::CUSTOM_COST_TEXT @custom_cost_text = $1.to_s when YEA::REGEXP::SKILL::CUSTOM_COST_COLOUR @custom_cost_colour = $1.to_i when YEA::REGEXP::SKILL::CUSTOM_COST_SIZE @custom_cost_size = $1.to_i when YEA::REGEXP::SKILL::CUSTOM_COST_ICON @custom_cost_icon = $1.to_i when YEA::REGEXP::SKILL::CUSTOM_COST_REQUIREMENT_ON @custom_cost_req_on = true @use_custom_cost = true when YEA::REGEXP::SKILL::CUSTOM_COST_REQUIREMENT_OFF @custom_cost_req_on = false @use_custom_cost = true when YEA::REGEXP::SKILL::CUSTOM_COST_PERFORM_ON @custom_cost_per_on = true @use_custom_cost = true when YEA::REGEXP::SKILL::CUSTOM_COST_PERFORM_OFF @custom_cost_per_on = false @use_custom_cost = true else @custom_cost_requirement += line.to_s if @custom_cost_req_on @custom_cost_perform += line.to_s if @custom_cost_per_on #--- end } # self.note.split #--- end end # RPG::Skill #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # alias method: skill_cost_payable? #-------------------------------------------------------------------------- alias game_battlerbase_skill_cost_payable_scm skill_cost_payable? def skill_cost_payable?(skill) return false if hp <= skill_hp_cost(skill) return false unless gold_cost_met?(skill) return false unless custom_cost_met?(skill) return game_battlerbase_skill_cost_payable_scm(skill) end #-------------------------------------------------------------------------- # new method: gold_cost_met? #-------------------------------------------------------------------------- def gold_cost_met?(skill) return true unless actor? return $game_party.gold >= skill_gold_cost(skill) end #-------------------------------------------------------------------------- # new method: custom_cost_met? #-------------------------------------------------------------------------- def custom_cost_met?(skill) return true unless skill.use_custom_cost return eval(skill.custom_cost_requirement) end #-------------------------------------------------------------------------- # alias method: pay_skill_cost #-------------------------------------------------------------------------- alias game_battlerbase_pay_skill_cost_scm pay_skill_cost def pay_skill_cost(skill) game_battlerbase_pay_skill_cost_scm(skill) self.hp -= skill_hp_cost(skill) $game_party.lose_gold(skill_gold_cost(skill)) if actor? pay_custom_cost(skill) end #-------------------------------------------------------------------------- # new method: pay_custom_cost #-------------------------------------------------------------------------- def pay_custom_cost(skill) return unless skill.use_custom_cost eval(skill.custom_cost_perform) end #-------------------------------------------------------------------------- # alias method: skill_mp_cost #-------------------------------------------------------------------------- alias game_battlerbase_skill_mp_cost_scm skill_mp_cost def skill_mp_cost(skill) n = game_battlerbase_skill_mp_cost_scm(skill) n += skill.mp_cost_percent * mmp * mcr n = [n.to_i, skill.mp_cost_max].min unless skill.mp_cost_max.nil? n = [n.to_i, skill.mp_cost_min].max unless skill.mp_cost_min.nil? return n.to_i end #-------------------------------------------------------------------------- # alias method: skill_tp_cost #-------------------------------------------------------------------------- alias game_battlerbase_skill_tp_cost_scm skill_tp_cost def skill_tp_cost(skill) n = game_battlerbase_skill_tp_cost_scm(skill) * tcr_y n += skill.tp_cost_percent * max_tp * tcr_y n = [n.to_i, skill.tp_cost_max].min unless skill.tp_cost_max.nil? n = [n.to_i, skill.tp_cost_min].max unless skill.tp_cost_min.nil? return n.to_i end #-------------------------------------------------------------------------- # new method: tcr_y #-------------------------------------------------------------------------- def tcr_y n = 1.0 if actor? n *= self.actor.tp_cost_rate n *= self.class.tp_cost_rate for equip in equips next if equip.nil? n *= equip.tp_cost_rate end else n *= self.enemy.tp_cost_rate if $imported["YEA-Doppelganger"] && !self.class.nil? n *= self.class.tp_cost_rate end end for state in states next if state.nil? n *= state.tp_cost_rate end return n end #-------------------------------------------------------------------------- # new method: skill_hp_cost #-------------------------------------------------------------------------- def skill_hp_cost(skill) n = skill.hp_cost * hcr n += skill.hp_cost_percent * mhp * hcr n = [n.to_i, skill.hp_cost_max].min unless skill.hp_cost_max.nil? n = [n.to_i, skill.hp_cost_min].max unless skill.hp_cost_min.nil? return n.to_i end #-------------------------------------------------------------------------- # new method: hcr #-------------------------------------------------------------------------- def hcr n = 1.0 if actor? n *= self.actor.hp_cost_rate n *= self.class.hp_cost_rate for equip in equips next if equip.nil? n *= equip.hp_cost_rate end else n *= self.enemy.hp_cost_rate if $imported["YEA-Doppelganger"] && !self.class.nil? n *= self.class.hp_cost_rate end end for state in states next if state.nil? n *= state.hp_cost_rate end return n end #-------------------------------------------------------------------------- # new method: skill_gold_cost #-------------------------------------------------------------------------- def skill_gold_cost(skill) n = skill.gold_cost * gcr n += skill.gold_cost_percent * $game_party.gold * gcr n = [n.to_i, skill.gold_cost_max].min unless skill.gold_cost_max.nil? n = [n.to_i, skill.gold_cost_min].max unless skill.gold_cost_min.nil? return n.to_i end #-------------------------------------------------------------------------- # new method: gcr #-------------------------------------------------------------------------- def gcr n = 1.0 n *= self.actor.gold_cost_rate n *= self.class.gold_cost_rate for equip in equips next if equip.nil? n *= equip.gold_cost_rate end for state in states next if state.nil? n *= state.gold_cost_rate end return n end end # Game_BattlerBase #============================================================================== # ■ Window_Base #============================================================================== class Window_Base < Window #-------------------------------------------------------------------------- # overwrite methods: cost_colours #-------------------------------------------------------------------------- def mp_cost_color; text_color(YEA::SKILL_COST::MP_COST_COLOUR); end; def tp_cost_color; text_color(YEA::SKILL_COST::TP_COST_COLOUR); end; def hp_cost_color; text_color(YEA::SKILL_COST::HP_COST_COLOUR); end; def gold_cost_color; text_color(YEA::SKILL_COST::GOLD_COST_COLOUR); end; end # Window_Base #============================================================================== # ■ Window_SkillList #============================================================================== class Window_SkillList < Window_Selectable #-------------------------------------------------------------------------- # overwrite method: draw_skill_cost #-------------------------------------------------------------------------- def draw_skill_cost(rect, skill) draw_tp_skill_cost(rect, skill) unless $imported["YEA-BattleEngine"] draw_mp_skill_cost(rect, skill) draw_tp_skill_cost(rect, skill) if $imported["YEA-BattleEngine"] draw_hp_skill_cost(rect, skill) draw_gold_skill_cost(rect, skill) draw_custom_skill_cost(rect, skill) end #-------------------------------------------------------------------------- # new method: draw_mp_skill_cost #-------------------------------------------------------------------------- def draw_mp_skill_cost(rect, skill) return unless @actor.skill_mp_cost(skill) > 0 change_color(mp_cost_color, enable?(skill)) #--- icon = Icon.mp_cost if icon > 0 draw_icon(icon, rect.x + rect.width-24, rect.y, enable?(skill)) rect.width -= 24 end #--- contents.font.size = YEA::SKILL_COST::MP_COST_SIZE cost = @actor.skill_mp_cost(skill) text = sprintf(YEA::SKILL_COST::MP_COST_SUFFIX, cost.group) draw_text(rect, text, 2) cx = text_size(text).width + 4 rect.width -= cx reset_font_settings end #-------------------------------------------------------------------------- # new method: draw_tp_skill_cost #-------------------------------------------------------------------------- def draw_tp_skill_cost(rect, skill) return unless @actor.skill_tp_cost(skill) > 0 change_color(tp_cost_color, enable?(skill)) #--- icon = Icon.tp_cost if icon > 0 draw_icon(icon, rect.x + rect.width-24, rect.y, enable?(skill)) rect.width -= 24 end #--- contents.font.size = YEA::SKILL_COST::TP_COST_SIZE cost = @actor.skill_tp_cost(skill) text = sprintf(YEA::SKILL_COST::TP_COST_SUFFIX, cost.group) draw_text(rect, text, 2) cx = text_size(text).width + 4 rect.width -= cx reset_font_settings end #-------------------------------------------------------------------------- # new method: draw_hp_skill_cost #-------------------------------------------------------------------------- def draw_hp_skill_cost(rect, skill) return unless @actor.skill_hp_cost(skill) > 0 change_color(hp_cost_color, enable?(skill)) #--- icon = Icon.hp_cost if icon > 0 draw_icon(icon, rect.x + rect.width-24, rect.y, enable?(skill)) rect.width -= 24 end #--- contents.font.size = YEA::SKILL_COST::HP_COST_SIZE cost = @actor.skill_hp_cost(skill) text = sprintf(YEA::SKILL_COST::HP_COST_SUFFIX, cost.group) draw_text(rect, text, 2) cx = text_size(text).width + 4 rect.width -= cx reset_font_settings end #-------------------------------------------------------------------------- # new method: draw_gold_skill_cost #-------------------------------------------------------------------------- def draw_gold_skill_cost(rect, skill) return unless @actor.skill_gold_cost(skill) > 0 change_color(gold_cost_color, enable?(skill)) #--- icon = Icon.gold_cost if icon > 0 draw_icon(icon, rect.x + rect.width-24, rect.y, enable?(skill)) rect.width -= 24 end #--- contents.font.size = YEA::SKILL_COST::GOLD_COST_SIZE cost = @actor.skill_gold_cost(skill) text = sprintf(YEA::SKILL_COST::GOLD_COST_SUFFIX, cost.group) draw_text(rect, text, 2) cx = text_size(text).width + 4 rect.width -= cx reset_font_settings end #-------------------------------------------------------------------------- # new method: draw_custom_skill_cost #-------------------------------------------------------------------------- def draw_custom_skill_cost(rect, skill) return unless skill.use_custom_cost
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
true
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LSP_Punishment.rb
Battle/LSP_Punishment.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic States Package - Punishment v1.01 # -- Last Updated: 2011.12.15 # -- Level: Lunatic # -- Requires: YEA - Lunatic States v1.00+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LSP-Punishment"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.31 - Bug Fixed: Error with battle popups not showing. # 2011.12.15 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic States Package Effects with punishment themed # effects. Included in it are effects that make battlers undead (take damage # whenever they are healed), make battlers whenever they execute physical or # magical attacks, make battlers take damage based on the original caster of # the state's stats, and an effect that heals the original caster of the state # whenever the battler takes HP or MP damage. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic States. Then, proceed to use the # proper effects notetags to apply the proper LSP Punishment item desired. # Look within the script for more instructions on how to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic States v1.00+ to work. It must be placed # under YEA - Lunatic States v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticStates"] class Game_BattlerBase #-------------------------------------------------------------------------- # ● Lunatic States Package Effects - Punishment # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These effects are centered around the theme of punishment. These effects # punish users for doing various aspects that may benefit them by harming # them in different ways. #-------------------------------------------------------------------------- alias lunatic_state_extension_lsp1 lunatic_state_extension def lunatic_state_extension(effect, state, user, state_origin, log_window) case effect.upcase #---------------------------------------------------------------------- # Punish Effect No.1: Undead HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with react effect. This causes any HP healing done to become # reversed and deal HP damage to the healed target. # # Recommended notetag: # <react effect: undead hp> #---------------------------------------------------------------------- when /UNDEAD HP/i return unless @result.hp_damage < 0 @result.hp_damage *= -1 @result.hp_drain *= -1 #---------------------------------------------------------------------- # Punish Effect No.2: Undead MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with react effect. This causes any MP healing done to become # reversed and deal MP damage to the healed target. # # Recommended notetag: # <react effect: undead mp> #---------------------------------------------------------------------- when /UNDEAD MP/i return unless @result.mp_damage < 0 @result.mp_damage *= -1 @result.mp_drain *= -1 #---------------------------------------------------------------------- # Punish Effect No.3: Physical Backfire # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with while effect. Whenever the affected battler uses a # physical attack, that battler will take HP damage equal to its own # stats after finishing the current action. Battler cannot die from # this effect. # # Recommended notetag: # <while effect: physical backfire stat x%> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. # Replace x with the stat multiplier to affect damage dealt. #---------------------------------------------------------------------- when /PHYSICAL BACKFIRE[ ](.*)[ ](\d+)([%%])/i return if user.current_action.nil? return unless user.current_action.item.physical? case $1.upcase when "MAXHP"; dmg = user.mhp when "MAXMP"; dmg = user.mmp when "ATK"; dmg = user.atk when "DEF"; dmg = user.def when "MAT"; dmg = user.mat when "MDF"; dmg = user.mdf when "AGI"; dmg = user.agi when "LUK"; dmg = user.luk else; return end dmg = (dmg * $2.to_i * 0.01).to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:hp_dmg], dmg.group) user.create_popup(text, "HP_DMG") end user.perform_damage_effect user.hp = [user.hp - dmg, 1].max #---------------------------------------------------------------------- # Punish Effect No.4: Magical Backfire # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with while effect. Whenever the affected battler uses a # magical attack, that battler will take HP damage equal to its own # stats after finishing the current action. Battler cannot die from # this effect. # # Recommended notetag: # <while effect: magical backfire stat x%> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. # Replace x with the stat multiplier to affect damage dealt. #---------------------------------------------------------------------- when /MAGICAL BACKFIRE[ ](.*)[ ](\d+)([%%])/i return if user.current_action.nil? return unless user.current_action.item.magical? case $1.upcase when "MAXHP"; dmg = user.mhp when "MAXMP"; dmg = user.mmp when "ATK"; dmg = user.atk when "DEF"; dmg = user.def when "MAT"; dmg = user.mat when "MDF"; dmg = user.mdf when "AGI"; dmg = user.agi when "LUK"; dmg = user.luk else; return end dmg = (dmg * $2.to_i * 0.01).to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:hp_dmg], dmg.group) user.create_popup(text, "HP_DMG") end user.perform_damage_effect user.hp = [user.hp - dmg, 1].max #---------------------------------------------------------------------- # Punish Effect No.5: Stat Slip Damage # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with close effect. At the end of the turn, the affected # battler will take HP slip damage based on the stat of the of one who # casted the status effect onto the battler. Battler cannot die from # this effect. # # Recommended notetag: # <close effect: stat slip damage x%> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. # Replace x with the stat multiplier to affect damage dealt. #---------------------------------------------------------------------- when /(.*)[ ]SLIP DAMAGE[ ](\d+)([%%])/i case $1.upcase when "MAXHP"; dmg = state_origin.mhp when "MAXMP"; dmg = state_origin.mmp when "ATK"; dmg = state_origin.atk when "DEF"; dmg = state_origin.def when "MAT"; dmg = state_origin.mat when "MDF"; dmg = state_origin.mdf when "AGI"; dmg = state_origin.agi when "LUK"; dmg = state_origin.luk else; return end dmg = (dmg * $2.to_i * 0.01).to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:hp_dmg], dmg.group) user.create_popup(text, "HP_DMG") end user.perform_damage_effect user.hp = [user.hp - dmg, 1].max #---------------------------------------------------------------------- # Punish Effect No.6: Stat Slip Heal # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with close effect. At the end of the turn, the affected # battler will heal HP based on the stat of the of one who casted the # status effect onto the battler. # # Recommended notetag: # <close effect: stat slip heal x%> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. # Replace x with the stat multiplier to affect damage dealt. #---------------------------------------------------------------------- when /(.*)[ ]SLIP HEAL[ ](\d+)([%%])/i case $1.upcase when "MAXHP"; dmg = state_origin.mhp when "MAXMP"; dmg = state_origin.mmp when "ATK"; dmg = state_origin.atk when "DEF"; dmg = state_origin.def when "MAT"; dmg = state_origin.mat when "MDF"; dmg = state_origin.mdf when "AGI"; dmg = state_origin.agi when "LUK"; dmg = state_origin.luk else; return end dmg = (dmg * $2.to_i * 0.01).to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:hp_heal], dmg.group) user.create_popup(text, "HP_HEAL") end user.perform_damage_effect user.hp += dmg #---------------------------------------------------------------------- # Punish Effect No.7: Drain HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with shock effect. Whenever user takes HP damage, the # original caster of the state will heal HP based on HP damage dealt. # # Recommended notetag: # <shock effect: drain hp x%> #---------------------------------------------------------------------- when /DRAIN HP[ ](\d+)([%%])/i return unless @result.hp_damage > 0 dmg = (@result.hp_damage * $1.to_i * 0.01).to_i if $imported["YEA-BattleEngine"] && dmg > 0 Sound.play_recovery text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:hp_heal], dmg.group) user.create_popup(text, "HP_HEAL") end state_origin.hp += dmg #---------------------------------------------------------------------- # Punish Effect No.8: Drain MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with shock effect. Whenever user takes MP damage, the # original caster of the state will heal MP based on MP damage dealt. # # Recommended notetag: # <shock effect: drain mp x%> #---------------------------------------------------------------------- when /DRAIN MP[ ](\d+)([%%])/i return unless @result.mp_damage > 0 dmg = (@result.mp_damage * $1.to_i * 0.01).to_i if $imported["YEA-BattleEngine"] && dmg > 0 Sound.play_recovery text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:mp_heal], dmg.group) user.create_popup(text, "MP_HEAL") end state_origin.mp += dmg #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else so = state_origin lw = log_window lunatic_state_extension_lsp1(effect, state, user, so, lw) end end end # Game_BattlerBase end # $imported["YEA-LunaticStates"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Lunatic_States.rb
Battle/Lunatic_States.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic States v1.02 # -- Last Updated: 2012.01.30 # -- Level: Lunatic # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LunaticStates"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.01.30 - Compatibility Update: Ace Battle Engine # 2011.12.19 - Fixed Death State stacking error. # 2011.12.15 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Lunatic mode effects have always been a core part of Yanfly Engine scripts. # They exist to provide more effects for those who want more power and control # for their items, skills, status effects, etc., but the users must be able to # add them in themselves. # # This script provides the base setup for state lunatic effects. These effects # will occur under certain conditions, which can include when a state is # applied, erased, leaves naturally, before taking damage, after taking damage, # at the start of a turn, while an action finishes, and at the end of a turn. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # ● Welcome to Lunatic Mode # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Lunatic States allow allow states to trigger various scripted functions # throughout certain set periods of times or when certain conditions # trigger. These effects can occur when a state is applied, when a state is # erased, when a state leaves naturally, before damage is taken, after # damage is taken, at the beginning of a turn, while the turn is occuring, # and at the closing of a turn. These effects are separated by these eight # different notetags. # # <apply effect: string> - Occurs when state is applied. # <erase effect: string> - Occurs when state is removed. # <leave effect: string> - Occurs when state timer hits 0. # <react effect: string> - Occurs before taking damage. # <shock effect: string> - Occurs after taking damage. # <begin effect: string> - Occurs at the start of each turn. # <while effect: string> - Occurs after performing an action. # <close effect: string> - Occurs at the end of a turn. # # If multiple tags of the same type are used in the same skill/item's # notebox, then the effects will occur in that order. Replace "string" in # the tags with the appropriate flag for the method below to search for. # Note that unlike the previous versions, these are all upcase. # # Should you choose to use multiple lunatic effects for a single state, you # may use these notetags in place of the ones shown above. # # <apply effect> <erase effect> <leave effect> # string string string # string string string # </apply effect> </erase effect> </leave effect> # # <react effect> <shock effect> # string string # string string # </react effect> </shock effect> # # <begin effect> <while effect> <close effect> # string string string # string string string # </begin effect> </while effect> </close effect> # # All of the string information in between those two notetags will be # stored the same way as the notetags shown before those. There is no # difference between using either. #-------------------------------------------------------------------------- def lunatic_state_effect(type, state, user) return unless SceneManager.scene_is?(Scene_Battle) return if state.nil? case type when :apply; effects = state.apply_effects when :erase; effects = state.erase_effects when :leave; effects = state.leave_effects when :react; effects = state.react_effects when :shock; effects = state.shock_effects when :begin; effects = state.begin_effects when :while; effects = state.while_effects when :close; effects = state.close_effects else; return end log_window = SceneManager.scene.log_window state_origin = state_origin?(state.id) for effect in effects case effect.upcase #---------------------------------------------------------------------- # Common Effect: Apply # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs whenever a state is refreshly added # to the battler's state pool. There is no need to modify this unless # you see fit. #---------------------------------------------------------------------- when /COMMON APPLY/i # No common apply effects added. #---------------------------------------------------------------------- # Common Effect: Erase # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs whenever a state is removed from # the battler's state pool. There is no need to modify this unless you # see fit. #---------------------------------------------------------------------- when /COMMON ERASE/i # No common erase effects added. #---------------------------------------------------------------------- # Common Effect: Leave # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs whenever a state's turns reach 0 # and leaves the battler's state pool. There is no need to modify this # unless you see fit. #---------------------------------------------------------------------- when /COMMON LEAVE/i # No common leave effects added. #---------------------------------------------------------------------- # Common Effect: React # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs right before the battler is about # to take damage. There is no need to modify this unless you see fit. #---------------------------------------------------------------------- when /COMMON REACT/i # No common react effects added. #---------------------------------------------------------------------- # Common Effect: Shock # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs right after the battler has taken # damage. There is no need to modify this unless you see fit. #---------------------------------------------------------------------- when /COMMON SHOCK/i # No common shock effects added. #---------------------------------------------------------------------- # Common Effect: Begin # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs at the start of the party's turn. # There is no need to modify this unless you see fit. #---------------------------------------------------------------------- when /COMMON BEGIN/i # No common begin effects added. #---------------------------------------------------------------------- # Common Effect: While # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs at the end of the battler's turn. # There is no need to modify this unless you see fit. #---------------------------------------------------------------------- when /COMMON WHILE/i # No common while effects added. #---------------------------------------------------------------------- # Common Effect: Close # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs at the end of the party's turn. # There is no need to modify this unless you see fit. #---------------------------------------------------------------------- when /COMMON CLOSE/i # No common close effects added. #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else lunatic_state_extension(effect, state, user, state_origin, log_window) end end # for effect in effects end # lunatic_object_effect end # Game_BattlerBase #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module STATE APPLY_EFFECT_STR = /<(?:APPLY_EFFECT|apply effect):[ ](.*)>/i APPLY_EFFECT_ON = /<(?:APPLY_EFFECT|apply effect)>/i APPLY_EFFECT_OFF = /<\/(?:APPLY_EFFECT|apply effect)>/i ERASE_EFFECT_STR = /<(?:ERASE_EFFECT|erase effect):[ ](.*)>/i ERASE_EFFECT_ON = /<(?:ERASE_EFFECT|erase effect)>/i ERASE_EFFECT_OFF = /<\/(?:ERASE_EFFECT|erase effect)>/i LEAVE_EFFECT_STR = /<(?:LEAVE_EFFECT|leave effect):[ ](.*)>/i LEAVE_EFFECT_ON = /<(?:LEAVE_EFFECT|leave effect)>/i LEAVE_EFFECT_OFF = /<\/(?:LEAVE_EFFECT|leave effect)>/i REACT_EFFECT_STR = /<(?:REACT_EFFECT|react effect):[ ](.*)>/i REACT_EFFECT_ON = /<(?:REACT_EFFECT|react effect)>/i REACT_EFFECT_OFF = /<\/(?:REACT_EFFECT|react effect)>/i SHOCK_EFFECT_STR = /<(?:SHOCK_EFFECT|shock effect):[ ](.*)>/i SHOCK_EFFECT_ON = /<(?:SHOCK_EFFECT|shock effect)>/i SHOCK_EFFECT_OFF = /<\/(?:SHOCK_EFFECT|shock effect)>/i BEGIN_EFFECT_STR = /<(?:BEGIN_EFFECT|begin effect):[ ](.*)>/i BEGIN_EFFECT_ON = /<(?:BEGIN_EFFECT|begin effect)>/i BEGIN_EFFECT_OFF = /<\/(?:BEGIN_EFFECT|begin effect)>/i WHILE_EFFECT_STR = /<(?:WHILE_EFFECT|while effect):[ ](.*)>/i WHILE_EFFECT_ON = /<(?:WHILE_EFFECT|while effect)>/i WHILE_EFFECT_OFF = /<\/(?:WHILE_EFFECT|while effect)>/i CLOSE_EFFECT_STR = /<(?:CLOSE_EFFECT|close effect):[ ](.*)>/i CLOSE_EFFECT_ON = /<(?:CLOSE_EFFECT|close effect)>/i CLOSE_EFFECT_OFF = /<\/(?:CLOSE_EFFECT|close effect)>/i end # STATE end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_lsta load_database; end def self.load_database load_database_lsta load_notetags_lsta end #-------------------------------------------------------------------------- # new method: load_notetags_lsta #-------------------------------------------------------------------------- def self.load_notetags_lsta for state in $data_states next if state.nil? state.load_notetags_lsta end end end # DataManager #============================================================================== # ■ RPG::State #============================================================================== class RPG::State < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :apply_effects attr_accessor :erase_effects attr_accessor :leave_effects attr_accessor :react_effects attr_accessor :shock_effects attr_accessor :begin_effects attr_accessor :while_effects attr_accessor :close_effects #-------------------------------------------------------------------------- # common cache: load_notetags_lsta #-------------------------------------------------------------------------- def load_notetags_lsta @apply_effects = ["COMMON APPLY"] @erase_effects = ["COMMON ERASE"] @leave_effects = ["COMMON LEAVE"] @react_effects = ["COMMON REACT"] @shock_effects = ["COMMON SHOCK"] @begin_effects = ["COMMON BEGIN"] @while_effects = ["COMMON WHILE"] @close_effects = ["COMMON CLOSE"] @apply_effects_on = false @erase_effects_on = false @leave_effects_on = false @react_effects_on = false @shock_effects_on = false @begin_effects_on = false @while_effects_on = false @close_effects_on = false #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::STATE::APPLY_EFFECT_STR @apply_effects.push($1.to_s) when YEA::REGEXP::STATE::ERASE_EFFECT_STR @erase_effects.push($1.to_s) when YEA::REGEXP::STATE::LEAVE_EFFECT_STR @leave_effects.push($1.to_s) when YEA::REGEXP::STATE::REACT_EFFECT_STR @react_effects.push($1.to_s) when YEA::REGEXP::STATE::SHOCK_EFFECT_STR @shock_effects.push($1.to_s) when YEA::REGEXP::STATE::BEGIN_EFFECT_STR @begin_effects.push($1.to_s) when YEA::REGEXP::STATE::WHILE_EFFECT_STR @while_effects.push($1.to_s) when YEA::REGEXP::STATE::CLOSE_EFFECT_STR @close_effects.push($1.to_s) #--- when YEA::REGEXP::STATE::APPLY_EFFECT_ON @apply_effects_on = true when YEA::REGEXP::STATE::ERASE_EFFECT_ON @erase_effects_on = true when YEA::REGEXP::STATE::LEAVE_EFFECT_ON @leave_effects_on = true when YEA::REGEXP::STATE::REACT_EFFECT_ON @react_effects_on = true when YEA::REGEXP::STATE::SHOCK_EFFECT_ON @shock_effects_on = true when YEA::REGEXP::STATE::BEGIN_EFFECT_ON @begin_effects_on = true when YEA::REGEXP::STATE::WHILE_EFFECT_ON @while_effects_on = true when YEA::REGEXP::STATE::CLOSE_EFFECT_ON @close_effects_on = true #--- when YEA::REGEXP::STATE::APPLY_EFFECT_OFF @apply_effects_on = false when YEA::REGEXP::STATE::ERASE_EFFECT_OFF @erase_effects_on = false when YEA::REGEXP::STATE::LEAVE_EFFECT_OFF @leave_effects_on = false when YEA::REGEXP::STATE::REACT_EFFECT_OFF @react_effects_on = false when YEA::REGEXP::STATE::SHOCK_EFFECT_OFF @shock_effects_on = false when YEA::REGEXP::STATE::BEGIN_EFFECT_OFF @begin_effects_on = false when YEA::REGEXP::STATE::WHILE_EFFECT_OFF @while_effects_on = false when YEA::REGEXP::STATE::CLOSE_EFFECT_OFF @close_effects_on = false #--- else @apply_effects.push(line.to_s) if @after_effects_on @erase_effects.push(line.to_s) if @erase_effects_on @leave_effects.push(line.to_s) if @leave_effects_on @react_effects.push(line.to_s) if @react_effects_on @shock_effects.push(line.to_s) if @shock_effects_on @begin_effects.push(line.to_s) if @begin_effects_on @while_effects.push(line.to_s) if @while_effects_on @close_effects.push(line.to_s) if @close_effects_on end } # self.note.split #--- end end # RPG::State #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # alias method: clear_states #-------------------------------------------------------------------------- alias game_battlerbase_clear_states_lsta clear_states def clear_states game_battlerbase_clear_states_lsta clear_state_origins end #-------------------------------------------------------------------------- # alias method: erase_state #-------------------------------------------------------------------------- alias game_battlerbase_erase_state_lsta erase_state def erase_state(state_id) lunatic_state_effect(:erase, $data_states[state_id], self) change_state_origin(:erase) game_battlerbase_erase_state_lsta(state_id) end #-------------------------------------------------------------------------- # new method: clear_state_origins #-------------------------------------------------------------------------- def clear_state_origins @state_origins = {} end #-------------------------------------------------------------------------- # new method: change_state_origin #-------------------------------------------------------------------------- def change_state_origin(state_id, type = :apply) return unless $game_party.in_battle return if state_id == death_state_id if :apply && SceneManager.scene_is?(Scene_Battle) subject = SceneManager.scene.subject clear_state_origins if @state_origins.nil? if subject.nil? @state_origins[state_id] = [:actor, self.id] if self.actor? @state_origins[state_id] = [:enemy, self.index] unless self.actor? elsif subject.actor? @state_origins[state_id] = [:actor, subject.id] else @state_origins[state_id] = [:enemy, subject.index] end else # :erase @state_origins[state_id] = nil end end #-------------------------------------------------------------------------- # new method: state_origin? #-------------------------------------------------------------------------- def state_origin?(state_id) return self unless $game_party.in_battle return self if @state_origins[state_id].nil? team = @state_origins[state_id][0] subject = @state_origins[state_id][1] if team == :actor return $game_actors[subject] else # :enemy return $game_troop.members[subject] end end end # Game_BattlerBase #============================================================================== # ■ Game_Battler #============================================================================== class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # alias method: on_battle_start #-------------------------------------------------------------------------- alias game_battler_on_battle_start_lsta on_battle_start def on_battle_start game_battler_on_battle_start_lsta clear_state_origins end #-------------------------------------------------------------------------- # alias method: on_battle_end #-------------------------------------------------------------------------- alias game_battler_on_battle_end_lsta on_battle_end def on_battle_end game_battler_on_battle_end_lsta clear_state_origins end #-------------------------------------------------------------------------- # alias method: add_new_state #-------------------------------------------------------------------------- alias game_battler_add_new_state_lsta add_new_state def add_new_state(state_id) change_state_origin(state_id, :apply) lunatic_state_effect(:apply, $data_states[state_id], self) game_battler_add_new_state_lsta(state_id) end #-------------------------------------------------------------------------- # alias method: remove_states_auto #-------------------------------------------------------------------------- alias game_battler_remove_states_auto_lsta remove_states_auto def remove_states_auto(timing) states.each do |state| if @state_turns[state.id] == 0 && state.auto_removal_timing == timing lunatic_state_effect(:leave, state, self) end end game_battler_remove_states_auto_lsta(timing) end #-------------------------------------------------------------------------- # alias method: execute_damage #-------------------------------------------------------------------------- alias game_battler_execute_damage_lsta execute_damage def execute_damage(user) for state in states; run_lunatic_states(:react); end game_battler_execute_damage_lsta(user) @result.restore_damage if $imported["YEA-BattleEngine"] for state in states; run_lunatic_states(:shock); end return unless $imported["YEA-BattleEngine"] @result.store_damage @result.clear_damage_values end #-------------------------------------------------------------------------- # new method: run_lunatic_states #-------------------------------------------------------------------------- def run_lunatic_states(type) for state in states; lunatic_state_effect(type, state, self); end end end # Game_Battler #============================================================================== # ■ Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :log_window attr_accessor :subject #-------------------------------------------------------------------------- # alias method: turn_start #-------------------------------------------------------------------------- alias scene_battle_turn_start_lsta turn_start def turn_start scene_battle_turn_start_lsta for member in all_battle_members; member.run_lunatic_states(:begin); end end #-------------------------------------------------------------------------- # alias method: turn_end #-------------------------------------------------------------------------- alias scene_battle_turn_end_lsta turn_end def turn_end for member in all_battle_members; member.run_lunatic_states(:close); end scene_battle_turn_end_lsta end #-------------------------------------------------------------------------- # alias method: execute_action #-------------------------------------------------------------------------- alias scene_battle_execute_action_lsta execute_action def execute_action scene_battle_execute_action_lsta @subject.run_lunatic_states(:while) end end # Scene_Battle #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # new method: lunatic_state_extension #-------------------------------------------------------------------------- def lunatic_state_extension(effect, state, user, state_origin, log_window) # Reserved for future Add-ons. end end # Game_BattlerBase #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LDP_Power.rb
Battle/LDP_Power.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Damage Package - Power v1.00 # -- Last Updated: 2011.12.21 # -- Level: Lunatic # -- Requires: YEA - Lunatic Damage v1.00+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LDP-Power"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.21 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic Damage Package with power themed formulas. # These formulas will increase the damage dealt depending on whether or not # the attacker or defender has high or low HP/MP. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic Damage. Then, proceed to use the # proper effects notetags to apply the proper LDP Power item desired. # Look within the script for more instructions on how to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic Damage v1.00+ to work. It must be placed # under YEA - Lunatic Damage v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticDamage"] class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # ● Lunatic Damage Package Effects - Power # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These effects are centered around the theme of dealing more damage by # various conditions, such as higher or lower HP/MP for the attacker or # defender. #-------------------------------------------------------------------------- alias lunatic_damage_extension_ldp2 lunatic_damage_extension def lunatic_damage_extension(formula, a, b, item, total_damage) user = a; value = 0 case formula.upcase #---------------------------------------------------------------------- # Power Damage Formula No.1: Attacker High HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates damage formula using the normal damage formula. Depending # on how high the attacker's HP is, the damage will increase by +x% or # decrease by -x% for every 1% HP the attacker has. # # Formula notetag: # <custom damage: attacker high hp +x%> # <custom damage: attacker high hp -x%> #---------------------------------------------------------------------- when /ATTACKER HIGH HP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) rate = (user.hp.to_f / user.mhp.to_f) * $1.to_i value *= 1.0 + rate #---------------------------------------------------------------------- # Power Damage Formula No.2: Attacker High MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates damage formula using the normal damage formula. Depending # on how high the attacker's MP is, the damage will increase by +x% or # decrease by -x% for every 1% MP the attacker has. # # Formula notetag: # <custom damage: attacker high mp +x%> # <custom damage: attacker high mp -x%> #---------------------------------------------------------------------- when /ATTACKER HIGH MP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) rate = (user.mp.to_f / [user.mmp, 1].max.to_f) * $1.to_i value *= 1.0 + rate #---------------------------------------------------------------------- # Power Damage Formula No.3: Attacker Low HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates damage formula using the normal damage formula. Depending # on how low the attacker's HP is, the damage will increase by +x% or # decrease by -x% for every 1% HP the attacker is missing. # # Formula notetag: # <custom damage: attacker low hp +x%> # <custom damage: attacker low hp -x%> #---------------------------------------------------------------------- when /ATTACKER LOW HP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) rate = (1.0 - (user.hp.to_f / user.mhp.to_f)) * $1.to_i value *= 1.0 + rate #---------------------------------------------------------------------- # Power Damage Formula No.4: Attacker Low MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates damage formula using the normal damage formula. Depending # on how low the attacker's MP is, the damage will increase by +x% or # decrease by -x% for every 1% MP the attacker is missing. # # Formula notetag: # <custom damage: attacker low mp +x%> # <custom damage: attacker low mp -x%> #---------------------------------------------------------------------- when /ATTACKER LOW MP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) rate = (1.0 - (user.mp.to_f / [user.mmp, 1].max.to_f)) * $1.to_i value *= 1.0 + rate #---------------------------------------------------------------------- # Power Damage Formula No.5: Defender High HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates damage formula using the normal damage formula. Depending # on how high the defender's HP is, the damage will increase by +x% or # decrease by -x% for every 1% HP the defender has. # # Formula notetag: # <custom damage: defender high hp +x%> # <custom damage: defender high hp -x%> #---------------------------------------------------------------------- when /DEFENDER HIGH HP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) rate = (self.hp.to_f / self.mhp.to_f) * $1.to_i value *= 1.0 + rate #---------------------------------------------------------------------- # Power Damage Formula No.6: Defender High MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates damage formula using the normal damage formula. Depending # on how high the defender's MP is, the damage will increase by +x% or # decrease by -x% for every 1% MP the defender has. # # Formula notetag: # <custom damage: defender high mp +x%> # <custom damage: defender high mp -x%> #---------------------------------------------------------------------- when /DEFENDER HIGH MP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) rate = (self.mp.to_f / [self.mmp, 1].max.to_f) * $1.to_i value *= 1.0 + rate #---------------------------------------------------------------------- # Power Damage Formula No.7: Defender Low HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates damage formula using the normal damage formula. Depending # on how low the defender's HP is, the damage will increase by +x% or # decrease by -x% for every 1% HP the defender is missing. # # Formula notetag: # <custom damage: defender low hp +x%> # <custom damage: defender low hp -x%> #---------------------------------------------------------------------- when /DEFENDER LOW HP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) rate = (1.0 - (user.hp.to_f / user.mhp.to_f)) * $1.to_i value *= 1.0 + rate #---------------------------------------------------------------------- # Power Damage Formula No.8: Defender Low MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates damage formula using the normal damage formula. Depending # on how low the defender's MP is, the damage will increase by +x% or # decrease by -x% for every 1% MP the defender is missing. # # Formula notetag: # <custom damage: defender low mp +x%> # <custom damage: defender low mp -x%> #---------------------------------------------------------------------- when /DEFENDER LOW MP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) rate = (1.0 - (user.mp.to_f / [user.mmp, 1].max.to_f)) * $1.to_i value *= 1.0 + rate else return lunatic_damage_extension_ldp2(formula, a, b, item, total_damage) end return value end end # Game_Battler end # $imported["YEA-LunaticDamage"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Element_Absorb.rb
Battle/Element_Absorb.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Element Absorb v1.01 # -- Last Updated: 2012.01.23 # -- Level: Normal, Hard # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-Element Absorb"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.01.23 - Compatibility Update: Doppelganger # 2011.12.14 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Absorbing elements have been taken out of RPG Maker VX Ace despite being a # possible feature in the past RPG Maker iterations. This script brings back # the ability to absorb elemental rates by applying them as traits for actors, # classes, weapons, armours, enemies, and states. # # If a target is inherently strong against the element absorbed, then more # will be absorbed. If the target is inherently weak to the element absorbed, # then less will be absorbed. The rate of which absorption takes effect is # dependent on the target's natural affinity to the element. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Actor Notetags - These notetags go in the actors notebox in the database. # ----------------------------------------------------------------------------- # <element absorb: x> # <element absorb: x, x> # Grants a trait to absorb element x and heal the battler. # # ----------------------------------------------------------------------------- # Class Notetags - These notetags go in the class notebox in the database. # ----------------------------------------------------------------------------- # <element absorb: x> # <element absorb: x, x> # Grants a trait to absorb element x and heal the battler. # # ----------------------------------------------------------------------------- # Weapons Notetags - These notetags go in the weapons notebox in the database. # ----------------------------------------------------------------------------- # <element absorb: x> # <element absorb: x, x> # Grants a trait to absorb element x and heal the battler. # # ----------------------------------------------------------------------------- # Armour Notetags - These notetags go in the armours notebox in the database. # ----------------------------------------------------------------------------- # <element absorb: x> # <element absorb: x, x> # Grants a trait to absorb element x and heal the battler. # # ----------------------------------------------------------------------------- # Enemy Notetags - These notetags go in the enemies notebox in the database. # ----------------------------------------------------------------------------- # <element absorb: x> # <element absorb: x, x> # Grants a trait to absorb element x and heal the battler. # # ----------------------------------------------------------------------------- # State Notetags - These notetags go in the states notebox in the database. # ----------------------------------------------------------------------------- # <element absorb: x> # <element absorb: x, x> # Grants a trait to absorb element x and heal the battler. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module ELEMENT_ABSORB #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Absorption Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Here, you can change how the game handles absorption when there are # multiple elements being calculated. If the following setting is set to # true, then the absorption takes priority. If false, then absorption is # ignored and the damage is calculated normally. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- MULTI_ELEMENT_ABSORB_PRIORITY = true end # ELEMENT_ABSORB end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module BASEITEM ELE_ABSORB = /<(?:ELEMENT_ABSORB|element absorb):[ ]*(\d+(?:\s*,\s*\d+)*)>/i end # BASEITEM end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_eabs load_database; end def self.load_database load_database_eabs load_notetags_eabs end #-------------------------------------------------------------------------- # new method: load_notetags_eabs #-------------------------------------------------------------------------- def self.load_notetags_eabs groups = [$data_actors, $data_classes, $data_weapons, $data_armors, $data_enemies, $data_states] for group in groups for obj in group next if obj.nil? obj.load_notetags_eabs end end end end # DataManager #============================================================================== # ■ RPG::BaseItem #============================================================================== class RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :element_absorb #-------------------------------------------------------------------------- # common cache: load_notetags_eabs #-------------------------------------------------------------------------- def load_notetags_eabs @element_absorb = [] #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::BASEITEM::ELE_ABSORB $1.scan(/\d+/).each { |num| @element_absorb.push(num.to_i) if num.to_i > 0 } #--- end } # self.note.split #--- end end # RPG::BaseItem #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # alias method: element_rate #-------------------------------------------------------------------------- alias game_battler_element_rate_eabs element_rate def element_rate(element_id) result = game_battler_element_rate_eabs(element_id) if element_absorb?(element_id) result = [result - 2.0, -0.01].min end return result end #-------------------------------------------------------------------------- # new method: element_absorb? #-------------------------------------------------------------------------- def element_absorb?(element_id) if actor? return true if self.actor.element_absorb.include?(element_id) return true if self.class.element_absorb.include?(element_id) for equip in equips next if equip.nil? return true if equip.element_absorb.include?(element_id) end else return true if self.enemy.element_absorb.include?(element_id) if $imported["YEA-Doppelganger"] && !self.class.nil? return true if self.class.element_absorb.include?(element_id) end end for state in states next if state.nil? return true if state.element_absorb.include?(element_id) end return false end end # Game_BattlerBase #============================================================================== # ■ Game_Battler #============================================================================== class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # alias method: elements_max_rate #-------------------------------------------------------------------------- alias game_battler_elements_max_rate_eabs elements_max_rate def elements_max_rate(elements) result = game_battler_elements_max_rate_eabs(elements) if YEA::ELEMENT_ABSORB::MULTI_ELEMENT_ABSORB_PRIORITY for element_id in elements next unless element_absorb?(element_id) result = [result - 2.0, -0.01].min return result end end return result end end # Game_Battler #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LOP_Recoil.rb
Battle/LOP_Recoil.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Objects Package - Recoil # -- Last Updated: 2012.01.14 # -- Level: Lunatic # -- Requires: YEA - Lunatic Objects v1.02+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LOP-Recoil"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.01.14 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic Objects Package Effects with recoil themed # effects. Upon attacking the target, the user of a skill/item can take damage # through either a set amount of a percentage of the damage dealt. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic Objects. Then, proceed to use the # proper before, prepare, during, or after effects notetags to apply the proper # LOP Recoil item desired. Look within the script for more instructions on how # to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic Objects v1.00+ to work. It must be placed # under YEA - Lunatic Objects v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticObjects"] class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # ● Lunatic Objects Package Effects - Recoil # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These effects are centered around the theme of recoil effects for skills # and items, such as dealing damage and to have a percentage of it return # back to the user or a set amount of damage returned back to the user. #-------------------------------------------------------------------------- alias lunatic_object_extension_lop3 lunatic_object_extension def lunatic_object_extension(effect, item, user, target, line_number) case effect.upcase #---------------------------------------------------------------------- # Recoil Effect No.1: Recoil Set HP Damage # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will return exactly x amount of HP damage to the user regardless # of how much damage the user has dealt to the target. The user can die # from this effect. # # Recommended notetag: # <during effect: recoil x hp damage> #---------------------------------------------------------------------- when /RECOIL[ ](\d+)[ ]HP DAMAGE/i dmg = $1.to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:hp_dmg], dmg.group) user.create_popup(text, "HP_DMG") end user.hp -= dmg text = sprintf("%s takes %s recoil damage!", user.name, dmg.group) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Recoil Effect No.2: Recoil Set MP Damage # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will return exactly x amount of MP damage to the user regardless # of how much damage the user has dealt to the target. # # Recommended notetag: # <during effect: recoil x mp damage> #---------------------------------------------------------------------- when /RECOIL[ ](\d+)[ ]MP DAMAGE/i dmg = $1.to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:mp_dmg], dmg.group) user.create_popup(text, "MP_DMG") end user.mp -= dmg vocab = Vocab::mp text = sprintf("%s loses %s %s from recoil!", user.name, dmg.group, vocab) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Recoil Effect No.3: Recoil Set TP Damage # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will return exactly x amount of TP damage to the user regardless # of how much damage the user has dealt to the target. # # Recommended notetag: # <during effect: recoil x tp damage> #---------------------------------------------------------------------- when /RECOIL[ ](\d+)[ ]TP DAMAGE/i dmg = $1.to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:tp_dmg], dmg.group) user.create_popup(text, "TP_DMG") end user.mp -= dmg vocab = Vocab::tp text = sprintf("%s loses %s %s from recoil!", user.name, dmg.group, vocab) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Recoil Effect No.4: Recoil Percent HP Damage # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will return a percentage of the damage dealt as HP damage to # the user. This will factor in both HP damage dealt to the target and # MP damage dealt to the target. The user can die from this effect. # # Recommended notetag: # <during effect: recoil x% hp damage> #---------------------------------------------------------------------- when /RECOIL[ ](\d+)([%%])[ ]HP DAMAGE/i dmg = ($1.to_i * 0.01 * target.result.hp_damage).to_i dmg += ($1.to_i * 0.01 * target.result.mp_damage).to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:hp_dmg], dmg.group) user.create_popup(text, "HP_DMG") end user.hp -= dmg text = sprintf("%s takes %s recoil damage!", user.name, dmg.group) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Recoil Effect No.5: Recoil Percent MP Damage # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will return a percentage of the damage dealt as MP damage to # the user. This will factor in both HP damage dealt to the target and # MP damage dealt to the target. # # Recommended notetag: # <during effect: recoil x% mp damage> #---------------------------------------------------------------------- when /RECOIL[ ](\d+)([%%])[ ]MP DAMAGE/i dmg = ($1.to_i * 0.01 * target.result.hp_damage).to_i dmg += ($1.to_i * 0.01 * target.result.mp_damage).to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:mp_dmg], dmg.group) user.create_popup(text, "MP_DMG") end user.mp -= dmg vocab = Vocab::mp text = sprintf("%s loses %s %s from recoil!", user.name, dmg.group, vocab) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Recoil Effect No.6: Recoil Percent TP Damage # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will return a percentage of the damage dealt as MP damage to # the user. This will factor in both HP damage dealt to the target and # MP damage dealt to the target. # # Recommended notetag: # <during effect: recoil x% tp damage> #---------------------------------------------------------------------- when /RECOIL[ ](\d+)([%%])[ ]TP DAMAGE/i dmg = ($1.to_i * 0.01 * target.result.hp_damage).to_i dmg += ($1.to_i * 0.01 * target.result.mp_damage).to_i if $imported["YEA-BattleEngine"] && dmg > 0 text = sprintf(YEA::BATTLE::POPUP_SETTINGS[:tp_dmg], dmg.group) user.create_popup(text, "TP_DMG") end user.mp -= dmg vocab = Vocab::tp text = sprintf("%s loses %s %s from recoil!", user.name, dmg.group, vocab) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else lunatic_object_extension_lop3(effect, item, user, target, line_number) end end # lunatic_object_extension end # Scene_Battle end # $imported["YEA-LunaticObjects"] #============================================================================== # ■ Numeric #============================================================================== class Numeric #-------------------------------------------------------------------------- # new method: group_digits #-------------------------------------------------------------------------- unless $imported["YEA-CoreEngine"] def group; return self.to_s; end end # $imported["YEA-CoreEngine"] end # Numeric #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LOP_Give&Take.rb
Battle/LOP_Give&Take.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Objects Package - Give & Take # -- Last Updated: 2011.12.27 # -- Level: Lunatic # -- Requires: YEA - Lunatic Objects v1.02+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LOP-Give&Take"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.27 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic Objects Package Effects with give & take themed # effects. With this script, the user and target will transfer states, buffs, # and debuffs from one another. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic Objects. Then, proceed to use the # proper before, prepare, during, or after effects notetags to apply the proper # LOP Give & Take item desired. Look within the script for more instructions on # how to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic Objects v1.00+ to work. It must be placed # under YEA - Lunatic Objects v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticObjects"] class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # ● Lunatic Objects Package Effects - Give & Take # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These effects are centered around the theme of giving and taking from a # target, be it an enemy or an ally. The user and target transfers states, # buffs, and debuffs to and from each other depending on the effect. #-------------------------------------------------------------------------- alias lunatic_object_extension_lop2 lunatic_object_extension def lunatic_object_extension(effect, item, user, target, line_number) case effect.upcase #---------------------------------------------------------------------- # Give & Take Effect No.1: Give State # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the user is inflicted with state x, it will transfer the state # over to the target. However, if the user is not inflicted with the # specific state, no transfers will occur. # # Recommended notetag: # <prepare effect: give state x> # <prepare effect: give state x, x> # - or - # <during effect: give state x> # <during effect: give state x, x> #---------------------------------------------------------------------- when /GIVE STATE[ ]*(\d+(?:\s*,\s*\d+)*)/i array = [] $1.scan(/\d+/).each { |num| array.push(num.to_i) if num.to_i > 0 } for i in array break if user == target next unless user.state?(i) user.remove_state(i) target.add_state(i) end #---------------------------------------------------------------------- # Give & Take Effect No.2: Take State # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the target is inflicted with state x, it will transfer the state # over to the user. However, if the target is not inflicted with the # specific state, no transfers will occur. # # Recommended notetag: # <prepare effect: take state x> # <prepare effect: take state x, x> # - or - # <during effect: take state x> # <during effect: take state x, x> #---------------------------------------------------------------------- when /TAKE STATE[ ]*(\d+(?:\s*,\s*\d+)*)/i array = [] $1.scan(/\d+/).each { |num| array.push(num.to_i) if num.to_i > 0 } for i in array break if user == target next unless target.state?(i) target.remove_state(i) user.add_state(i) end #---------------------------------------------------------------------- # Give & Take Effect No.3: Give Buff # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the user has stat x buffed, it will transfer the buff over to the # target. However, if the user does not have stat x buffed, no effects # will occur. # # Recommended notetag: # <prepare effect: give buff stat> # - or - # <during effect: give buff stat> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /GIVE BUFF[ ](.*)/i return if user == target case $1.upcase when "MAXHP"; param_id = 0 when "MAXMP"; param_id = 1 when "ATK"; param_id = 2 when "DEF"; param_id = 3 when "MAT"; param_id = 4 when "MDF"; param_id = 5 when "AGI"; param_id = 6 when "LUK"; param_id = 7 else; return end return unless user.buff?(param_id) user.add_debuff(param_id, 3) target.add_buff(param_id, 3) #---------------------------------------------------------------------- # Give & Take Effect No.4: Take Buff # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the target has stat x buffed, it will transfer the buff over to # the user. However, if the target does not have stat x buffed, no # effects will occur. # # Recommended notetag: # <prepare effect: take buff stat> # - or - # <during effect: take buff stat> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /TAKE BUFF[ ](.*)/i return if user == target case $1.upcase when "MAXHP"; param_id = 0 when "MAXMP"; param_id = 1 when "ATK"; param_id = 2 when "DEF"; param_id = 3 when "MAT"; param_id = 4 when "MDF"; param_id = 5 when "AGI"; param_id = 6 when "LUK"; param_id = 7 else; return end return unless target.buff?(param_id) target.add_debuff(param_id, 3) user.add_buff(param_id, 3) #---------------------------------------------------------------------- # Give & Take Effect No.5: Give Debuff # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the user has stat x debuffed, it will transfer the buff over to # the target. However, if the user does not have stat x debuffed, no # effects will occur. # # Recommended notetag: # <prepare effect: give debuff stat> # - or - # <during effect: give debuff stat> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /GIVE DEBUFF[ ](.*)/i return if user == target case $1.upcase when "MAXHP"; param_id = 0 when "MAXMP"; param_id = 1 when "ATK"; param_id = 2 when "DEF"; param_id = 3 when "MAT"; param_id = 4 when "MDF"; param_id = 5 when "AGI"; param_id = 6 when "LUK"; param_id = 7 else; return end return unless user.debuff?(param_id) user.add_buff(param_id, 3) target.add_debuff(param_id, 3) #---------------------------------------------------------------------- # Give & Take Effect No.6: Take Debuff # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the target has stat x debuffed, it will transfer the buff over to # the user. However, if the target does not have stat x debuffed, no # effects will occur. # # Recommended notetag: # <prepare effect: take buff stat> # - or - # <during effect: take buff stat> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /TAKE BUFF[ ](.*)/i return if user == target case $1.upcase when "MAXHP"; param_id = 0 when "MAXMP"; param_id = 1 when "ATK"; param_id = 2 when "DEF"; param_id = 3 when "MAT"; param_id = 4 when "MDF"; param_id = 5 when "AGI"; param_id = 6 when "LUK"; param_id = 7 else; return end return unless target.debuff?(param_id) target.add_buff(param_id, 3) user.add_debuff(param_id, 3) #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else lunatic_object_extension_lop2(effect, item, user, target, line_number) end end # lunatic_object_extension end # Scene_Battle end # $imported["YEA-LunaticObjects"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Element_Popups.rb
Battle/Element_Popups.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Battle Engine Add-On: Elemental Popups v1.00 # -- Last Updated: 2011.12.26 # -- Level: Normal # -- Requires: YEA - Ace Battle Engine v1.08+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-ElementalPopups"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.26 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script colour-coded element popups as they appear in battle for any kind # of HP damage dealt. This does not include healing popups, MP damage popups, # only HP damage dealt. Colour-coded element popups help the player quickly # identify what kind of damage is dealt and streamlines the delivery of battle # information to the audience. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # If you are using elements other than the default set of elements that came # with a default project of RPG Maker VX Ace, adjust the element colours in the # module below. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires Yanfly Engine Ace - Ace Battle Engine v1.08+ and the # script must be placed under Ace Battle Engine in the script listing. # #============================================================================== module YEA module ELEMENT_POPUPS #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Setting - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Description #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # This is the default font used for the popups. Adjust them accordingly # or even add new ones. DEFAULT = ["VL Gothic", "Verdana", "Arial", "Courier"] # The following are the various rules that govern the individual popup # types that will appear. Adjust them accordingly. Here is a list of what # each category does. # Zoom1 The zoom the popup starts at. Values over 2.0 may cause lag. # Zoom2 The zoom the popup goes to. Values over 2.0 may cause lag. # Sz The font size used for the popup text. # Bold Applying bold for the popup text. # Italic Applying italic for the popup text. # Red The red value of the popup text. # Grn The green value of the popup text. # Blu The blue value of the popup text. # Font The font used for the popup text. # # Note that if an element doesn't appear here, it'll use the DEFAULT # ruleset from Ace Battle Engine. COLOURS ={ # ElementID => [ Zoom1, Zoom2, Sz, Bold, Italic, Red, Grn, Blu, Font] 3 => [ 2.0, 1.0, 36, true, false, 240, 60, 60, DEFAULT], 4 => [ 2.0, 1.0, 36, true, false, 100, 200, 246, DEFAULT], 5 => [ 2.0, 1.0, 36, true, false, 255, 255, 160, DEFAULT], 6 => [ 2.0, 1.0, 36, true, false, 0, 115, 180, DEFAULT], 7 => [ 2.0, 1.0, 36, true, false, 240, 135, 80, DEFAULT], 8 => [ 2.0, 1.0, 36, true, false, 60, 180, 75, DEFAULT], 9 => [ 2.0, 1.0, 36, true, false, 175, 210, 255, DEFAULT], 10 => [ 2.0, 1.0, 36, true, false, 110, 80, 130, DEFAULT], } # Do not remove this. end # ELEMENT_POPUPS end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== if $imported["YEA-BattleEngine"] module YEA module BATTLE module_function #-------------------------------------------------------------------------- # add_element_popups #-------------------------------------------------------------------------- def add_element_popups(hash) for key in YEA::ELEMENT_POPUPS::COLOURS string = sprintf("ELEMENT_%d", key[0]) hash[string] = key[1] end return hash end #-------------------------------------------------------------------------- # converted_contants #-------------------------------------------------------------------------- POPUP_RULES = add_element_popups(POPUP_RULES) end # BATTLE end # YEA #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # alias method: create_popup #-------------------------------------------------------------------------- alias game_battlerbase_create_popup_elepop create_popup def create_popup(value, rules = "DEFAULT", flags = []) rules = @element_popup_tag if rules == "HP_DMG" && !@element_popup_tag.nil? game_battlerbase_create_popup_elepop(value, rules, flags) end end # Game_BattlerBase #============================================================================== # ■ Game_Battler #============================================================================== class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # alias method: item_apply #-------------------------------------------------------------------------- alias game_battler_item_apply_elepop item_apply def item_apply(user, item) @element_popup_tag = element_popup_tag?(user, item) game_battler_item_apply_elepop(user, item) @element_popup_tag = nil end #-------------------------------------------------------------------------- # new method: element_popup_tag? #-------------------------------------------------------------------------- def element_popup_tag?(user, item) return "HP_DMG" if item.nil? text = "ELEMENT_" if item.damage.element_id < 0 return "HP_DMG" if user.atk_elements.empty? rate = elements_max_rate(user.atk_elements) for i in user.atk_elements next unless element_rate(i) == rate text += i.to_s break end else text += item.damage.element_id.to_s end text = "HP_DMG" unless YEA::BATTLE::POPUP_RULES.include?(text) return text end end # Game_Battler end # $imported["YEA-BattleEngine"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Enemy_Death_Transform.rb
Battle/Enemy_Death_Transform.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Enemy Death Transform v1.01 # -- Last Updated: 2012.04.10 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-EnemyDeathTransform"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.04.10 - Randomizer bugfix thanks to Modern Algebra. # 2012.02.09 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script allows enemies to transform into another monster when they die. # Although this is easily evented, this script is made to save the tediousness # of applying that to every enemy and to allow the transforming sequence to be # a lot smoother. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Enemy Notetags - These notetags go in the enemy notebox in the database. # ----------------------------------------------------------------------------- # <death transform: x> # Sets the current enemy type to transform into enemy x upon death. # # <death transform rate: x%> # Sets the transform rate for the current enemy to be x%. If the previous tag # is not used, then this notetag has no effect. If this notetag isn't present, # the transform rate will be 100% by default. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module ENEMY DEATH_TRANSFORM = /<(?:DEATH_TRANSFORM|death transform):[ ](\d+)>/i DEATH_TRANSFORM_RATE = /<(?:DEATH_TRANSFORM_RATE|death transform rate):[ ](\d+)([%%])>/i end # ENEMY end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_edt load_database; end def self.load_database load_database_edt load_notetags_edt end #-------------------------------------------------------------------------- # new method: load_notetags_edt #-------------------------------------------------------------------------- def self.load_notetags_edt for obj in $data_enemies next if obj.nil? obj.load_notetags_edt end end end # DataManager #============================================================================== # ■ RPG::Enemy #============================================================================== class RPG::Enemy < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :death_transform attr_accessor :death_transform_rate #-------------------------------------------------------------------------- # common cache: load_notetags_edt #-------------------------------------------------------------------------- def load_notetags_edt @death_transform = 0 @death_transform_rate = 1.0 #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::ENEMY::DEATH_TRANSFORM @death_transform = $1.to_i when YEA::REGEXP::ENEMY::DEATH_TRANSFORM_RATE @death_transform_rate = $1.to_i * 0.01 end } # self.note.split #--- end end # RPG::Enemy #============================================================================== # ■ Game_Battler #============================================================================== class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # alias method: die #-------------------------------------------------------------------------- alias game_battler_die_edt die def die return death_transform if meet_death_transform_requirements? game_battler_die_edt end #-------------------------------------------------------------------------- # new method: meet_death_transform_requirements? #-------------------------------------------------------------------------- def meet_death_transform_requirements? return false unless enemy? return false unless enemy.death_transform > 0 return false if $data_enemies[enemy.death_transform].nil? return rand < enemy.death_transform_rate end #-------------------------------------------------------------------------- # new method: death_transform #-------------------------------------------------------------------------- def death_transform transform(enemy.death_transform) self.hp = mhp self.mp = mmp @sprite_effect_type = :whiten end end # Game_Battler #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LOP_Destruction.rb
Battle/LOP_Destruction.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Objects Package - Destruction # -- Last Updated: 2011.12.27 # -- Level: Lunatic # -- Requires: YEA - Lunatic Objects v1.00+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LOP-Destruction"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.27 - Tag changes for "Debuff" and "Buff". # 2011.12.14 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic Objects Package Effects with destruction themed # effects. These effects include things such as suicide effects, emptying MP, # emptying TP, and more. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic Objects. Then, proceed to use the # proper before, during, or after effects notetags to apply the proper LOP # Destruction item desired. Look within the script for more instructions on how # to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic Objects v1.00+ to work. It must be placed # under YEA - Lunatic Objects v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticObjects"] class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # ● Lunatic Objects Package Effects - Destruction # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These effects are centered around the theme of self destruction. These # effects will cause the user harm even if the user is targeting someone # other than the user itself. #-------------------------------------------------------------------------- alias lunatic_object_extension_lop1 lunatic_object_extension def lunatic_object_extension(effect, item, user, target, line_number) case effect.upcase #---------------------------------------------------------------------- # Destruction Effect No.1: Suicide # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with after effect. This causes the user to suicide (and # bring the user's HP down to 0) and adds a message saying that the # user has died. # # Recommended notetag: # <after effect: suicide> #---------------------------------------------------------------------- when /SUICIDE/i user.hp = 0 user.perform_collapse_effect status_redraw_target(target) text = sprintf("%s dies!", user.name) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Destruction Effect No.2: Empty MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with after effect. This causes the user's MP to hit zero # after performing the skill. # # Recommended notetag: # <after effect: empty mp> #---------------------------------------------------------------------- when /EMPTY MP/i user.mp = 0 text = sprintf("%s's MP empties out!", user.name) status_redraw_target(target) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Destruction Effect No.3: Empty TP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with after effect. This causes the user's TP to hit zero # after performing the skill. # # Recommended notetag: # <after effect: empty tp> #---------------------------------------------------------------------- when /EMPTY TP/i user.tp = 0 text = sprintf("%s's TP runs out!", user.name) status_redraw_target(target) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Destruction Effect No.4: Add State # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This can be used as either a before effect or after effect. This will # inflict the user with a status effect at the particular interval # during the usage of that skill such as poisoning oneself. # # Recommended notetag: # <before effect: add state x> # <after effect: add state x> #---------------------------------------------------------------------- when /ADD STATE[ ](\d+)/i state_id = $1.to_i target.add_state(state_id) return unless target.state?(state_id) status_redraw_target(target) state = $data_states[state_id] state_msg = target.actor? ? state.message1 : state.message2 return if state_msg.empty? text = target.name + state_msg @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Destruction Effect No.5: Remove State # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This can be used as either a before effect or after effect. This will # remove a state from the user at the particular interval during the # usage of that skill such as removing an elemental protection shield. # # Recommended notetag: # <before effect: remove state x> # <after effect: remove state x> #---------------------------------------------------------------------- when /REMOVE STATE[ ](\d+)/i state_id = $1.to_i return unless target.state?(state_id) target.remove_state(state_id) status_redraw_target(target) state = $data_states[state_id] state_msg = state.message4 return if state_msg.empty? text = target.name + state_msg @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Destruction Effect No.6: Debuff Stat # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This can be used as either a before effect or after effect. This will # cause the user's stat to drop during that interval in time. # # Recommended notetag: # <before effect: add debuff stat> # <after effect: add debuff stat> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /ADD DEBUFF[ ](.*)/i case $1.upcase when "MAXHP"; param_id = 0 when "MAXMP"; param_id = 1 when "ATK"; param_id = 2 when "DEF"; param_id = 3 when "MAT"; param_id = 4 when "MDF"; param_id = 5 when "AGI"; param_id = 6 when "LUK"; param_id = 7 else; return end target.add_debuff(param_id, 3) status_redraw_target(target) text = sprintf("%s's %s drops!", user.name, $1.upcase) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Destruction Effect No.7: Buff Stat # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This can be used as either a before effect or after effect. This will # cause the user's stat to rise during that interval in time. # # Recommended notetag: # <before effect: add buff stat> # <after effect: add buff stat> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /ADD BUFF[ ](.*)/i case $1.upcase when "MAXHP"; param_id = 0 when "MAXMP"; param_id = 1 when "ATK"; param_id = 2 when "DEF"; param_id = 3 when "MAT"; param_id = 4 when "MDF"; param_id = 5 when "AGI"; param_id = 6 when "LUK"; param_id = 7 else; return end target.add_buff(param_id, 3) status_redraw_target(target) text = sprintf("%s's %s rises!", user.name, $1.upcase) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Destruction Effect No.8: Clear States # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This can be used as either a before effect or after effect. This will # cause the user's states to clear completely. # # Recommended notetag: # <before effect: clear states> # <after effect: clear states> #---------------------------------------------------------------------- when /CLEAR STATES/i target.clear_states status_redraw_target(target) text = sprintf("%s removes all status effects!", user.name) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Destruction Effect No.9: Clear Buffs # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This can be used as either a before effect or after effect. This will # cause the user's buffs to clear completely. # # Recommended notetag: # <before effect: clear buffs> # <after effect: clear buffs> #---------------------------------------------------------------------- when /CLEAR BUFFS/i target.clear_buffs status_redraw_target(target) text = sprintf("%s loses all buffs!", user.name) @log_window.add_text(text) 3.times do @log_window.wait end @log_window.back_one #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else lunatic_object_extension_lop1(effect, item, user, target, line_number) end end # lunatic_object_extension end # Scene_Battle end # $imported["YEA-LunaticObjects"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LTP_Conditions.rb
Battle/LTP_Conditions.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Targets Package - Conditions v1.00 # -- Last Updated: 2012.01.02 # -- Level: Lunatic # -- Requires: YEA - Lunatic Targets v1.00+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LTP-Conditions"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.01.02 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic Targets Package Scopes with conditional themed # scopes. These scopes include targeting a group of units whose stats are above # or below a certain amount, current HP, MP, or TP is above or below a certain # percentage, whether or not they're affected by a specific state, or whether # or not they're affected by all of the specified states. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic Targets. Then, proceed to use the # proper effects notetags to apply the proper LTP Conditions item desired. # Look within the script for more instructions on how to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic Targets v1.00+ to work. It must be placed # under YEA - Lunatic Targets v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticTargets"] class Game_Action #-------------------------------------------------------------------------- # ● Lunatic Targets Package Scopes - Conditions # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These scopes are centered around the theme of conditions. These scopes # will select target from the targeted party based on various conditions # such as current percentage of HP, MP, TP, their stats above a certain # value, whether or not they're affected by specific states, or whether or # not they're affected by all of the specified states. #-------------------------------------------------------------------------- alias lunatic_targets_extension_ltp1 lunatic_targets_extension def lunatic_targets_extension(effect, user, smooth_target, targets) case effect.upcase #---------------------------------------------------------------------- # Condition Scope No.1: Current Stat Above # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets in the specified team whose current # HP, MP, or TP is x% or above x%. Targets will not be re-added if the # targets already exist within the current targeting scope. # # Recommended notetag: # <custom target: foes stat above x%> # <custom target: allies stat above x%> # <custom target: every stat above x%> # # Replace "stat" with HP, MP, or TP. # Replace x with the number percentage requirement. #---------------------------------------------------------------------- when /(.*)[ ](.*)[ ]ABOVE[ ](\d+)([%%])/i case $1.upcase when "FOE", "FOES", "ENEMY", "ENEMIES" group = opponents_unit.members when "EVERYBODY", "EVERYONE", "EVERY" group = opponents_unit.members + friends_unit.members else group = friends_unit.members end for member in group case $2.upcase when "HP" current = member.hp maximum = member.mhp when "MP" current = member.mp maximum = member.mmp else current = member.tp maximum = member.max_tp end next unless current >= $3.to_i * 0.01 * maximum targets |= [member] end #---------------------------------------------------------------------- # Condition Scope No.2: Current Stat Below # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets in the specified team whose current # HP, MP, or TP is x% or below x%. Targets will not be re-added if the # targets already exist within the current targeting scope. # # Recommended notetag: # <custom target: foes stat below x%> # <custom target: allies stat below x%> # <custom target: every stat below x%> # # Replace "stat" with HP, MP, or TP. # Replace x with the number percentage requirement. #---------------------------------------------------------------------- when /(.*)[ ](.*)[ ]BELOW[ ](\d+)([%%])/i case $1.upcase when "FOE", "FOES", "ENEMY", "ENEMIES" group = opponents_unit.members when "EVERYBODY", "EVERYONE", "EVERY" group = opponents_unit.members + friends_unit.members else group = friends_unit.members end for member in group case $2.upcase when "HP" current = member.hp maximum = member.mhp when "MP" current = member.mp maximum = member.mmp else current = member.tp maximum = member.max_tp end next unless current <= $3.to_i * 0.01 * maximum targets |= [member] end #---------------------------------------------------------------------- # Condition Scope No.3: Stat Above # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets in the specified team whose specified # stat is x or above x. Targets will not be re-added if the targets # already exist within the current targeting scope. # # Recommended notetag: # <custom target: foes stat above x> # <custom target: allies stat above x> # <custom target: every stat above x> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. # Replace x with the number requirement. #---------------------------------------------------------------------- when /(.*)[ ](.*)[ ]ABOVE[ ](\d+)/i case $1.upcase when "FOE", "FOES", "ENEMY", "ENEMIES" group = opponents_unit.members when "EVERYBODY", "EVERYONE", "EVERY" group = opponents_unit.members + friends_unit.members else group = friends_unit.members end case $2.upcase when "MAXHP"; stat = 0 when "MAXMP"; stat = 1 when "ATK"; stat = 2 when "DEF"; stat = 3 when "MAT"; stat = 4 when "MDF"; stat = 5 when "AGI"; stat = 6 when "LUK"; stat = 7 else; return targets end for member in group next unless member.param(stat) >= $3.to_i targets |= [member] end #---------------------------------------------------------------------- # Condition Scope No.4: Stat Below # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets in the specified team whose specified # stat is x or below x. Targets will not be re-added if the targets # already exist within the current targeting scope. # # Recommended notetag: # <custom target: foes stat below x> # <custom target: allies stat below x> # <custom target: every stat below x> # # Replace "stat" with MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, or LUK. # Replace x with the number requirement. #---------------------------------------------------------------------- when /(.*)[ ](.*)[ ]BELOW[ ](\d+)/i case $1.upcase when "FOE", "FOES", "ENEMY", "ENEMIES" group = opponents_unit.members when "EVERYBODY", "EVERYONE", "EVERY" group = opponents_unit.members + friends_unit.members else group = friends_unit.members end case $2.upcase when "MAXHP"; stat = 0 when "MAXMP"; stat = 1 when "ATK"; stat = 2 when "DEF"; stat = 3 when "MAT"; stat = 4 when "MDF"; stat = 5 when "AGI"; stat = 6 when "LUK"; stat = 7 else; return targets end for member in group next unless member.param(stat) <= $3.to_i targets |= [member] end #---------------------------------------------------------------------- # Condition Scope No.5: Any State # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets in the specified team who is afflicted # by any of the listed states. Targets will not be re-added if the targets # already exist within the current targeting scope. # # Recommended notetag: # <custom target: foes any state x> # <custom target: foes any state x, x> # <custom target: allies any state x> # <custom target: allies any state x, x> # <custom target: every any state x> # <custom target: every any state x, x> # # Replace x with the state's ID. #---------------------------------------------------------------------- when /(.*)[ ]ANY STATE[ ](\d+(?:\s*,\s*\d+)*)/i case $1.upcase when "FOE", "FOES", "ENEMY", "ENEMIES" group = opponents_unit.members when "EVERYBODY", "EVERYONE", "EVERY" group = opponents_unit.members + friends_unit.members else group = friends_unit.members end states = [] $2.scan(/\d+/).each { |num| states.push(num.to_i) if num.to_i > 0 } for member in group for state_id in states targets |= [member] if member.state?(state_id) end end #---------------------------------------------------------------------- # Condition Scope No.6: All States # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets in the specified team who is afflicted # by all of the listed states. Targets will not be re-added if the # targets already exist within the current targeting scope. # # Recommended notetag: # <custom target: foes all state x, x> # <custom target: allies all state x, x> # <custom target: every all state x, x> # # Replace x with the state's ID. #---------------------------------------------------------------------- when /(.*)[ ]ALL STATE[ ](\d+(?:\s*,\s*\d+)*)/i case $1.upcase when "FOE", "FOES", "ENEMY", "ENEMIES" group = opponents_unit.members when "EVERYBODY", "EVERYONE", "EVERY" group = opponents_unit.members + friends_unit.members else group = friends_unit.members end states = [] $2.scan(/\d+/).each { |num| states.push(num.to_i) if num.to_i > 0 } for member in group for state_id in states next if member.state?(state_id) group -= [member] end end targets |= group #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else st = smooth_target return lunatic_targets_extension_ltp1(effect, user, st, targets) end if $imported["YEA-BattleEngine"] targets.sort! { |a,b| a.screen_x <=> b.screen_x } end return targets end end # Game_BattlerBase end # $imported["YEA-LunaticTargets"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Combat_Log_Display.rb
Battle/Combat_Log_Display.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Combat Log Display v1.02 # -- Last Updated: 2012.01.24 # -- Level: Easy # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-CombatLogDisplay"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.01.24 - Bug Fixed: Confirm window crash with Battle Command List. # 2012.01.16 - Prevented subsequent line inserts. # 2011.12.10 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Sometimes text appears way too fast in the battle system or sometimes players # may miss what kind of information was delivered on-screen. For times like # that, being able to access the combat log would be important. The combat log # records all of the text that appears in the battle log window at the top. # The player can access the combat log display any time during action selection # phase. Sometimes, players can even review over the combat log to try and # figure out any kinds of patterns enemies may even have. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module COMBAT_LOG #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Combat Log Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Adjust the settings here to modify how the combat log works for your # game. You can change the command name and extra text that gets fitted # into the combat log over time. If you don't want specific text to appear, # just set the text to "" and nothing will show. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- COMMAND_NAME = "CombatLog" # Command list name. LINE_COLOUR = 0 # Line colour for separators. LINE_COLOUR_ALPHA = 48 # Opacity of the line colour. TEXT_BATTLE_START = "\\c[4]Battle Start!" # Battle start text. TEXT_TURN_NUMBER = "\\c[4]Turn Number: \\c[6]%d" # Turn number text. end # COMBAT_LOG end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== #============================================================================== # ■ Window_BattleLog #============================================================================== class Window_BattleLog < Window_Selectable #-------------------------------------------------------------------------- # new method: combatlog_window= #-------------------------------------------------------------------------- def combatlog_window=(window) @combatlog_window = window end #-------------------------------------------------------------------------- # new method: combatlog #-------------------------------------------------------------------------- def combatlog(text) return if @combatlog_window.nil? return if text == "" @combatlog_window.add_line(text) end #-------------------------------------------------------------------------- # alias method: add_text #-------------------------------------------------------------------------- alias window_battlelog_add_text_cld add_text def add_text(text) combatlog(text) window_battlelog_add_text_cld(text) end #-------------------------------------------------------------------------- # alias method: replace_text #-------------------------------------------------------------------------- alias window_battlelog_replace_text_cld replace_text def replace_text(text) combatlog(text) window_battlelog_replace_text_cld(text) end #-------------------------------------------------------------------------- # Start Ace Battle Engine Compatibility #-------------------------------------------------------------------------- if $imported["YEA-BattleEngine"] #-------------------------------------------------------------------------- # alias method: display_current_state #-------------------------------------------------------------------------- alias window_battlelog_display_current_state_cld display_current_state def display_current_state(subject) window_battlelog_display_current_state_cld(subject) return if YEA::BATTLE::MSG_CURRENT_STATE return if subject.most_important_state_text.empty? combatlog(subject.name + subject.most_important_state_text) end #-------------------------------------------------------------------------- # alias method: display_use_item #-------------------------------------------------------------------------- alias window_battlelog_display_use_item_cld display_use_item def display_use_item(subject, item) window_battlelog_display_use_item_cld(subject, item) return if YEA::BATTLE::MSG_CURRENT_ACTION if item.is_a?(RPG::Skill) combatlog(subject.name + item.message1) unless item.message2.empty? combatlog(item.message2) end else combatlog(sprintf(Vocab::UseItem, subject.name, item.name)) end end #-------------------------------------------------------------------------- # alias method: display_counter #-------------------------------------------------------------------------- alias window_battlelog_display_counter_cld display_counter def display_counter(target, item) window_battlelog_display_counter_cld(target, item) return if YEA::BATTLE::MSG_COUNTERATTACK combatlog(sprintf(Vocab::CounterAttack, target.name)) end #-------------------------------------------------------------------------- # alias method: display_reflection #-------------------------------------------------------------------------- alias window_battlelog_display_reflection_cld display_reflection def display_reflection(target, item) window_battlelog_display_reflection_cld(target, item) return if YEA::BATTLE::MSG_REFLECT_MAGIC combatlog(sprintf(Vocab::MagicReflection, target.name)) end #-------------------------------------------------------------------------- # alias method: display_substitute #-------------------------------------------------------------------------- alias window_battlelog_display_substitute_cld display_substitute def display_substitute(substitute, target) window_battlelog_display_substitute_cld(substitute, target) return if YEA::BATTLE::MSG_SUBSTITUTE_HIT combatlog(sprintf(Vocab::Substitute, substitute.name, target.name)) end #-------------------------------------------------------------------------- # alias method: display_failure #-------------------------------------------------------------------------- alias window_battlelog_display_failure_cld display_failure def display_failure(target, item) window_battlelog_display_failure_cld(target, item) return if YEA::BATTLE::MSG_FAILURE_HIT if target.result.hit? && !target.result.success combatlog(sprintf(Vocab::ActionFailure, target.name)) end end #-------------------------------------------------------------------------- # alias method: display_critical #-------------------------------------------------------------------------- alias window_battlelog_display_critical_cld display_critical def display_critical(target, item) window_battlelog_display_critical_cld(target, item) return if YEA::BATTLE::MSG_CRITICAL_HIT if target.result.critical text = target.actor? ? Vocab::CriticalToActor : Vocab::CriticalToEnemy combatlog(text) end end #-------------------------------------------------------------------------- # alias method: display_miss #-------------------------------------------------------------------------- alias window_battlelog_display_miss_cld display_miss def display_miss(target, item) window_battlelog_display_miss_cld(target, item) return if YEA::BATTLE::MSG_HIT_MISSED if !item || item.physical? fmt = target.actor? ? Vocab::ActorNoHit : Vocab::EnemyNoHit else fmt = Vocab::ActionFailure end combatlog(sprintf(fmt, target.name)) end #-------------------------------------------------------------------------- # alias method: display_evasion #-------------------------------------------------------------------------- alias window_battlelog_display_evasion_cld display_evasion def display_evasion(target, item) window_battlelog_display_evasion_cld(target, item) return if YEA::BATTLE::MSG_EVASION if !item || item.physical? fmt = Vocab::Evasion else fmt = Vocab::MagicEvasion end combatlog(sprintf(fmt, target.name)) end #-------------------------------------------------------------------------- # alias method: display_hp_damage #-------------------------------------------------------------------------- alias window_battlelog_display_hp_damage_cld display_hp_damage def display_hp_damage(target, item) window_battlelog_display_hp_damage_cld(target, item) return if YEA::BATTLE::MSG_HP_DAMAGE return if target.result.hp_damage == 0 && item && !item.damage.to_hp? combatlog(target.result.hp_damage_text) end #-------------------------------------------------------------------------- # alias method: display_mp_damage #-------------------------------------------------------------------------- alias window_battlelog_display_mp_damage_cld display_mp_damage def display_mp_damage(target, item) window_battlelog_display_mp_damage_cld(target, item) return if YEA::BATTLE::MSG_MP_DAMAGE combatlog(target.result.mp_damage_text) end #-------------------------------------------------------------------------- # alias method: display_tp_damage #-------------------------------------------------------------------------- alias window_battlelog_display_tp_damage_cld display_tp_damage def display_tp_damage(target, item) window_battlelog_display_tp_damage_cld(target, item) return if YEA::BATTLE::MSG_TP_DAMAGE combatlog(target.result.tp_damage_text) end #-------------------------------------------------------------------------- # alias method: display_added_states #-------------------------------------------------------------------------- alias window_battlelog_display_added_states_cld display_added_states def display_added_states(target) window_battlelog_display_added_states_cld(target) return if YEA::BATTLE::MSG_ADDED_STATES target.result.added_state_objects.each do |state| state_msg = target.actor? ? state.message1 : state.message2 next if state_msg.empty? combatlog(target.name + state_msg) end end #-------------------------------------------------------------------------- # alias method: display_removed_states #-------------------------------------------------------------------------- alias window_battlelog_display_removed_states_cld display_removed_states def display_removed_states(target) window_battlelog_display_removed_states_cld(target) return if YEA::BATTLE::MSG_REMOVED_STATES target.result.removed_state_objects.each do |state| next if state.message4.empty? combatlog(target.name + state.message4) end end #-------------------------------------------------------------------------- # alias method: display_buffs #-------------------------------------------------------------------------- alias window_battlelog_display_buffs_cld display_buffs def display_buffs(target, buffs, fmt) window_battlelog_display_buffs_cld(target, buffs, fmt) return if YEA::BATTLE::MSG_CHANGED_BUFFS buffs.each do |param_id| combatlog(sprintf(fmt, target.name, Vocab::param(param_id))) end end #-------------------------------------------------------------------------- # End Ace Battle Engine Compatibility #-------------------------------------------------------------------------- end # $imported["YEA-BattleEngine"] end # Window_BattleLog #============================================================================== # ■ Window_CombatLog #============================================================================== class Window_CombatLog < Window_Selectable #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize @data = [] super(0, 0, Graphics.width, Graphics.height-120) deactivate hide end #-------------------------------------------------------------------------- # add_line #-------------------------------------------------------------------------- def add_line(text) return if text == "-" && @data[@data.size - 1] == "-" @data.push(text) end #-------------------------------------------------------------------------- # refresh #-------------------------------------------------------------------------- def refresh create_contents draw_all_items end #-------------------------------------------------------------------------- # item_max #-------------------------------------------------------------------------- def item_max; return @data.size; end #-------------------------------------------------------------------------- # draw_item #-------------------------------------------------------------------------- def draw_item(index) text = @data[index] return if text.nil? rect = item_rect_for_text(index) if text == "-" draw_horz_line(rect.y) else draw_text_ex(rect.x, rect.y, text) end end #-------------------------------------------------------------------------- # draw_horz_line #-------------------------------------------------------------------------- def draw_horz_line(y) line_y = y + line_height / 2 - 1 contents.fill_rect(4, line_y, contents_width-8, 2, line_colour) end #-------------------------------------------------------------------------- # line_colour #-------------------------------------------------------------------------- def line_colour colour = text_color(YEA::COMBAT_LOG::LINE_COLOUR) colour.alpha = YEA::COMBAT_LOG::LINE_COLOUR_ALPHA return colour end #-------------------------------------------------------------------------- # show #-------------------------------------------------------------------------- def show super refresh activate select([item_max-1, 0].max) end #-------------------------------------------------------------------------- # hide #-------------------------------------------------------------------------- def hide deactivate super end end # Window_CombatLog #============================================================================== # ■ Window_PartyCommand #============================================================================== class Window_PartyCommand < Window_Command #-------------------------------------------------------------------------- # alias method: make_command_list #-------------------------------------------------------------------------- alias window_partycommand_make_command_list_cld make_command_list def make_command_list window_partycommand_make_command_list_cld return if $imported["YEA-BattleCommandList"] add_command(YEA::COMBAT_LOG::COMMAND_NAME, :combatlog) end end # Window_PartyCommand #============================================================================== # ■ Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # alias method: create_log_window #-------------------------------------------------------------------------- alias scene_battle_create_log_window_cld create_log_window def create_log_window scene_battle_create_log_window_cld create_combatlog_window end #-------------------------------------------------------------------------- # new method: create_combatlog_window #-------------------------------------------------------------------------- def create_combatlog_window @combatlog_window = Window_CombatLog.new @log_window.combatlog_window = @combatlog_window @combatlog_window.set_handler(:cancel, method(:close_combatlog)) @combatlog_window.add_line("-") @combatlog_window.add_line(YEA::COMBAT_LOG::TEXT_BATTLE_START) @combatlog_window.add_line("-") end #-------------------------------------------------------------------------- # new method: open_combatlog #-------------------------------------------------------------------------- def open_combatlog @combatlog_window.show end #-------------------------------------------------------------------------- # new method: close_combatlog #-------------------------------------------------------------------------- def close_combatlog @combatlog_window.hide if $imported["YEA-BattleCommandList"] if !@confirm_command_window.nil? && @confirm_command_window.visible @confirm_command_window.activate else @party_command_window.activate end else @party_command_window.activate end end #-------------------------------------------------------------------------- # alias method: create_party_command_window #-------------------------------------------------------------------------- alias create_party_command_window_cld create_party_command_window def create_party_command_window create_party_command_window_cld @party_command_window.set_handler(:combatlog, method(:open_combatlog)) end #-------------------------------------------------------------------------- # alias method: turn_start #-------------------------------------------------------------------------- alias scene_battle_turn_start_cld turn_start def turn_start scene_battle_turn_start_cld @combatlog_window.add_line("-") text = sprintf(YEA::COMBAT_LOG::TEXT_TURN_NUMBER, $game_troop.turn_count) @combatlog_window.add_line(text) @combatlog_window.add_line("-") end #-------------------------------------------------------------------------- # alias method: execute_action #-------------------------------------------------------------------------- alias scene_battle_execute_action_cld execute_action def execute_action @combatlog_window.add_line("-") scene_battle_execute_action_cld @combatlog_window.add_line("-") end #-------------------------------------------------------------------------- # alias method: turn_end #-------------------------------------------------------------------------- alias scene_battle_turn_end_cld turn_end def turn_end scene_battle_turn_end_cld @combatlog_window.add_line("-") end end # Scene_Battle #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LTP_Mathematics.rb
Battle/LTP_Mathematics.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Targets Package - Mathematics v1.00 # -- Last Updated: 2012.01.07 # -- Level: Lunatic # -- Requires: YEA - Lunatic Targets v1.00+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LTP-Mathematics"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.01.07 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic Targets Package Scopes with the theme of # selecting targets based on various math properties such as selecting odd # numbers, even numbers, numbers divisible by certain values, or prime numbers. # These targets are indiscriminant of allies or enemies unless specified. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic Targets. Then, proceed to use the # proper effects notetags to apply the proper LTP Mathematics item desired. # Look within the script for more instructions on how to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic Targets v1.00+ to work. It must be placed # under YEA - Lunatic Targets v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticTargets"] class Game_Action #-------------------------------------------------------------------------- # ● Lunatic Targets Package Scopes - Mathematics # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These scopes are centered around the theme of creating targets based on # various math such as stats divisible by a certain number, stats that are # odd or even, or stats that are prime. These targeting scopes are # indiscriminant of allies or enemies with the exception of levels and EXP. # Levels will be actors only unless Yanfly Engine Ace - Enemy Levels is # installed. EXP will be strictly actors only. #-------------------------------------------------------------------------- alias lunatic_targets_extension_ltp2 lunatic_targets_extension def lunatic_targets_extension(effect, user, smooth_target, targets) case effect.upcase #---------------------------------------------------------------------- # Mathematics Scope No.1: Divisible # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets from both groups of allies and enemies # whose specified stat is divisible by a certain number. Any battlers # who don't meet the requirements will not be affected by targeting. # # Recommended notetag: # <custom target: stat divisible x> # # Replace "stat" with MaxHP, MaxMP, HP, MP, TP, Level, EXP, ATK, DEF, # MAT, MDF, AGI, or LUK. # Replace x with the number to meet the conditions of. #---------------------------------------------------------------------- when /(.*)[ ]DIVISIBLE[ ](\d+)/i modifier = $2.to_i == 0 ? 1 : $2.to_i for member in $game_troop.alive_members + $game_party.alive_members case $1.upcase when "MAXHP", "MHP" next unless member.mhp % modifier == 0 when "MAXMP", "MMP", "MAXSP", "MSP" next unless member.mmp % modifier == 0 when "HP" next unless member.hp % modifier == 0 when "MP", "SP" next unless member.mp % modifier == 0 when "TP" next unless member.tp % modifier == 0 when "LEVEL" next if !$imported["YEA-EnemyLevels"] && !member.actor? next unless member.level % modifier == 0 when "EXP" next unless member.actor? next unless member.exp % modifier == 0 when "ATK" next unless member.atk % modifier == 0 when "DEF" next unless member.def % modifier == 0 when "MAT", "INT", "SPI" next unless member.mat % modifier == 0 when "MDF", "RES" next unless member.mdf % modifier == 0 when "AGI" next unless member.agi % modifier == 0 when "LUK" next unless member.luk % modifier == 0 else; next end targets |= [member] end #---------------------------------------------------------------------- # Mathematics Scope No.2: Even Number # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets from both groups of allies and enemies # whose specified stat is an even number. Any battlers who don't meet # the requirements will not be affected by targeting. # # Recommended notetag: # <custom target: stat even> # # Replace "stat" with MaxHP, MaxMP, HP, MP, TP, Level, EXP, ATK, DEF, # MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /(.*)[ ]EVEN/i modifier = 2 for member in $game_troop.alive_members + $game_party.alive_members case $1.upcase when "MAXHP", "MHP" next unless member.mhp % modifier == 0 when "MAXMP", "MMP", "MAXSP", "MSP" next unless member.mmp % modifier == 0 when "HP" next unless member.hp % modifier == 0 when "MP", "SP" next unless member.mp % modifier == 0 when "TP" next unless member.tp % modifier == 0 when "LEVEL" next if !$imported["YEA-EnemyLevels"] && !member.actor? next unless member.level % modifier == 0 when "EXP" next unless member.actor? next unless member.exp % modifier == 0 when "ATK" next unless member.atk % modifier == 0 when "DEF" next unless member.def % modifier == 0 when "MAT", "INT", "SPI" next unless member.mat % modifier == 0 when "MDF", "RES" next unless member.mdf % modifier == 0 when "AGI" next unless member.agi % modifier == 0 when "LUK" next unless member.luk % modifier == 0 else; next end targets |= [member] end #---------------------------------------------------------------------- # Mathematics Scope No.3: Odd Number # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets from both groups of allies and enemies # whose specified stat is an odd number. Any battlers who don't meet # the requirements will not be affected by targeting. # # Recommended notetag: # <custom target: stat odd> # # Replace "stat" with MaxHP, MaxMP, HP, MP, TP, Level, EXP, ATK, DEF, # MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /(.*)[ ]ODD/i modifier = 2 for member in $game_troop.alive_members + $game_party.alive_members case $1.upcase when "MAXHP", "MHP" next unless member.mhp % modifier != 0 when "MAXMP", "MMP", "MAXSP", "MSP" next unless member.mmp % modifier != 0 when "HP" next unless member.hp % modifier != 0 when "MP", "SP" next unless member.mp % modifier != 0 when "TP" next unless member.tp % modifier != 0 when "LEVEL" next if !$imported["YEA-EnemyLevels"] && !member.actor? next unless member.level % modifier != 0 when "EXP" next unless member.actor? next unless member.exp % modifier != 0 when "ATK" next unless member.atk % modifier != 0 when "DEF" next unless member.def % modifier != 0 when "MAT", "INT", "SPI" next unless member.mat % modifier != 0 when "MDF", "RES" next unless member.mdf % modifier != 0 when "AGI" next unless member.agi % modifier != 0 when "LUK" next unless member.luk % modifier != 0 else; next end targets |= [member] end #---------------------------------------------------------------------- # Mathematics Scope No.4: Prime Number # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This will select all targets from both groups of allies and enemies # whose specified stat is a prime number. Any battlers who don't meet # the requirements will not be affected by targeting. # # Recommended notetag: # <custom target: stat prime> # # Replace "stat" with MaxHP, MaxMP, HP, MP, TP, Level, EXP, ATK, DEF, # MAT, MDF, AGI, or LUK. #---------------------------------------------------------------------- when /(.*)[ ]ODD/i for member in $game_troop.alive_members + $game_party.alive_members case $1.upcase when "MAXHP", "MHP" next unless member.mhp.prime? when "MAXMP", "MMP", "MAXSP", "MSP" next unless member.mmp.prime? when "HP" next unless member.hp.prime? when "MP", "SP" next unless member.mp.prime? when "TP" next unless member.tp.prime? when "LEVEL" next if !$imported["YEA-EnemyLevels"] && !member.actor? next unless member.level.prime? when "EXP" next unless member.actor? next unless member.exp.prime? when "ATK" next unless member.atk.prime? when "DEF" next unless member.def.prime? when "MAT", "INT", "SPI" next unless member.mat.prime? when "MDF", "RES" next unless member.mdf.prime? when "AGI" next unless member.agi.prime? when "LUK" next unless member.luk.prime? else; next end targets |= [member] end #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else st = smooth_target return lunatic_targets_extension_ltp2(effect, user, st, targets) end if $imported["YEA-BattleEngine"] targets.sort! { |a,b| a.screen_x <=> b.screen_x } end return targets end end # Game_BattlerBase end # $imported["YEA-LunaticTargets"] #============================================================================== # ■ Numeric #============================================================================== class Numeric #-------------------------------------------------------------------------- # new method: prime? #-------------------------------------------------------------------------- def prime? n = self.abs return false if n < 2 2.upto(Math.sqrt(n).to_i) { |i| return false if n % i == 0 } return true end end # Numeric #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Cast_Animations.rb
Battle/Cast_Animations.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Cast Animations v1.00 # -- Last Updated: 2011.12.18 # -- Level: Easy, Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-CastAnimations"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.18 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Casting animations are actually great visual tools to help players recognize # and acknowledge which battler on the screen is currently taking an action. # The other thing is that casting animations also provide eye candy. This # script provides easy access to generate cast animations and to allow even # separate animations for each individual skill. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Skill Notetags - These notetags go in the skills notebox in the database. # ----------------------------------------------------------------------------- # <cast ani: x> # Sets the casting animation for this skill to be x. This animation will always # be played before this skill is used. If this tag isn't used, the default cast # animation will be the one set by the script's module. # # <no cast ani> # Sets the casting animation for this skill to be 0, making it so that no cast # animation will be played before this skill is used. # # ----------------------------------------------------------------------------- # Item Notetags - These notetags go in the items notebox in the database. # ----------------------------------------------------------------------------- # <cast ani: x> # Sets the casting animation for this item to be x. This animation will always # be played before this item is used. If this tag isn't used, the default cast # animation will be the one set by the script's module. # # <no cast ani> # Sets the casting animation for this item to be 0, making it so that no cast # animation will be played before this item is used. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module CAST_ANIMATIONS #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Default Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # These settings set the default casting animations for all skills that do # not use a unique casting animation. If you don't want any of the settings # below to have a cast animation, set it to 0 to disable it. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- NORMAL_ATTACK_ANI = 0 # Default animation for skill #1. DEFEND_ANIMATION = 0 # Default animation for skill #2. PHYSICAL_ANIMATION = 81 # Default animation for physical skills. MAGICAL_ANIMATION = 43 # Default animation for magical skills. ITEM_USE_ANIMATION = 0 # Default animation for using items. end # CAST_ANIMATIONS end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module USABLEITEM CAST_ANI = /<(?:CAST_ANI|cast ani|cast animation):[ ](\d+)>/i NO_CAST_ANI = /<(?:NO_CAST_ANI|no cast ani|no cast animation)>/i end # USABLEITEM end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_cani load_database; end def self.load_database load_database_cani load_notetags_cani end #-------------------------------------------------------------------------- # new method: load_notetags_cani #-------------------------------------------------------------------------- def self.load_notetags_cani groups = [$data_items, $data_skills] for group in groups for obj in group next if obj.nil? obj.load_notetags_cani end end end end # DataManager #============================================================================== # ■ RPG::UsableItem #============================================================================== class RPG::UsableItem < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variable #-------------------------------------------------------------------------- attr_accessor :cast_ani #-------------------------------------------------------------------------- # common cache: load_notetags_cani #-------------------------------------------------------------------------- def load_notetags_cani @cast_ani = 0 if self.is_a?(RPG::Skill) if @id == 1 @cast_ani = YEA::CAST_ANIMATIONS::NORMAL_ATTACK_ANI elsif @id == 2 @cast_ani = YEA::CAST_ANIMATIONS::DEFEND_ANIMATION elsif self.physical? @cast_ani = YEA::CAST_ANIMATIONS::PHYSICAL_ANIMATION elsif self.magical? @cast_ani = YEA::CAST_ANIMATIONS::MAGICAL_ANIMATION end else @cast_ani = YEA::CAST_ANIMATIONS::ITEM_USE_ANIMATION end #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::USABLEITEM::CAST_ANI @cast_ani = $1.to_i when YEA::REGEXP::USABLEITEM::NO_CAST_ANI @cast_ani = 0 #--- end } # self.note.split #--- end end # RPG::UsableItem #============================================================================== # ■ Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # alias method: use_item #-------------------------------------------------------------------------- alias scene_battle_use_item_cani use_item def use_item process_casting_animation unless $imported["YEA-BattleEngine"] scene_battle_use_item_cani end #-------------------------------------------------------------------------- # new method: process_casting_animation #-------------------------------------------------------------------------- def process_casting_animation item = @subject.current_action.item cast_ani = item.cast_ani return if cast_ani <= 0 show_animation([@subject], cast_ani) end end # Scene_Battle #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Death_Common_Event.rb
Battle/Death_Common_Event.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Death Common Events v1.01 # -- Last Updated: 2012.02.03 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-DeathCommonEvents"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.02.03 - New Feature: Wipe Out Event constant added. # 2012.01.24 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script causes the battle to run a common event upon a specific actor, # class, or enemy dying and running the collapsing effect. The common event # will run immediately upon death rather than waiting for the remainder of the # action to finish. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Actor Notetags - These notetags go in the actors notebox in the database. # ----------------------------------------------------------------------------- # <death event: x> # This causes the actor to run common event x upon death. The death event made # for the actor will take priority over the death event made for the class. # # ----------------------------------------------------------------------------- # Class Notetags - These notetags go in the class notebox in the database. # ----------------------------------------------------------------------------- # <death event: x> # This causes the class to run common event x upon death. The death event made # for the actor will take priority over the death event made for the class. # # ----------------------------------------------------------------------------- # Enemy Notetags - These notetags go in the enemies notebox in the database. # ----------------------------------------------------------------------------- # <death event: x> # This causes the enemy to run common event x upon death. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module DEATH_EVENTS #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Party Death Events - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # For those who would like a common event to run during battle when the # party wipes out, change the following constant below to the common event # ID to be used. If you do not wish to use an event for party wipes, set # the following constant to 0. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- WIPE_OUT_EVENT = 0 end # DEATH_EVENTS end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module BASEITEM DEATH_EVENT = /<(?:DEATH_EVENT|death event):[ ](\d+)>/i end # BASEITEM end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_dce load_database; end def self.load_database load_database_dce load_notetags_dce end #-------------------------------------------------------------------------- # new method: load_notetags_dce #-------------------------------------------------------------------------- def self.load_notetags_dce groups = [$data_actors, $data_classes, $data_enemies] for group in groups for obj in group next if obj.nil? obj.load_notetags_dce end end end end # DataManager #============================================================================== # ■ BattleManager #============================================================================== module BattleManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias process_defeat_dce process_defeat; end def self.process_defeat if SceneManager.scene_is?(Scene_Battle) SceneManager.scene.process_party_wipe_event end return unless $game_party.all_dead? process_defeat_dce end end # BattleManager #============================================================================== # ■ RPG::BaseItem #============================================================================== class RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :death_event_id #-------------------------------------------------------------------------- # common cache: load_notetags_dce #-------------------------------------------------------------------------- def load_notetags_dce @death_event_id = 0 #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::BASEITEM::DEATH_EVENT @death_event_id = $1.to_i #--- end } # self.note.split #--- end end # RPG::BaseItem #============================================================================== # ■ Game_Battler #============================================================================== class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # new method: death_event_id #-------------------------------------------------------------------------- def death_event_id return 0 end end # Game_Battler #============================================================================== # ■ Game_Actor #============================================================================== class Game_Actor < Game_Battler #-------------------------------------------------------------------------- # new method: death_event_id #-------------------------------------------------------------------------- def death_event_id return self.actor.death_event_id unless self.actor.death_event_id == 0 return self.class.death_event_id end #-------------------------------------------------------------------------- # alias method: perform_collapse_effect #-------------------------------------------------------------------------- alias game_actor_perform_collapse_effect_dce perform_collapse_effect def perform_collapse_effect game_actor_perform_collapse_effect_dce return unless SceneManager.scene_is?(Scene_Battle) SceneManager.scene.process_death_event(self) end end # Game_Actor #============================================================================== # ■ Game_Enemy #============================================================================== class Game_Enemy < Game_Battler #-------------------------------------------------------------------------- # new method: death_event_id #-------------------------------------------------------------------------- def death_event_id if $imported["YEA-Doppelganger"] && !self.class.nil? return self.class.death_event_id unless self.class.death_event_id == 0 end return self.enemy.death_event_id end #-------------------------------------------------------------------------- # alias method: perform_collapse_effect #-------------------------------------------------------------------------- alias game_enemy_perform_collapse_effect_dce perform_collapse_effect def perform_collapse_effect game_enemy_perform_collapse_effect_dce return unless SceneManager.scene_is?(Scene_Battle) SceneManager.scene.process_death_event(self) end end # Game_Enemy #============================================================================== # ■ Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # new method: process_death_event #-------------------------------------------------------------------------- def process_death_event(target) return unless target.dead? return if target.death_event_id == 0 $game_temp.reserve_common_event(target.death_event_id) process_death_common_event end #-------------------------------------------------------------------------- # new method: process_party_wipe_event #-------------------------------------------------------------------------- def process_party_wipe_event return unless $game_party.all_dead? return if YEA::DEATH_EVENTS::WIPE_OUT_EVENT <= 0 $game_temp.reserve_common_event(YEA::DEATH_EVENTS::WIPE_OUT_EVENT) process_death_common_event end #-------------------------------------------------------------------------- # new method: process_death_common_event #-------------------------------------------------------------------------- def process_death_common_event while !scene_changing? $game_troop.interpreter.update $game_troop.setup_battle_event wait_for_message wait_for_effect if $game_troop.all_dead? process_forced_action break unless $game_troop.interpreter.running? update_for_wait end end end # Scene_Battle #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Lunatic_Objects.rb
Battle/Lunatic_Objects.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Objects v1.02 # -- Last Updated: 2011.12.27 # -- Level: Lunatic # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LunaticObjects"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.27 - Added "Prepare" step. # - Moved Common Lunatic Object Effects to occur at the end of the # effects list per type. # 2011.12.15 - REGEXP Fix. # 2011.12.14 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Lunatic mode effects have always been a core part of Yanfly Engine scripts. # They exist to provide more effects for those who want more power and control # for their items, skills, status effects, etc., but the users must be able to # add them in themselves. # # This script provides the base setup for skill and item lunatic effects. # These lunatic object effects will give leeway to occur at certain times # during a skill or item's usage, which include before the object is used, # while (during) the object is used, and after the object is used. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # ● Welcome to Lunatic Mode # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Lunatic Object Effects allows skills and items allow users with scripting # knowledge to add in their own unique effects without need to edit the # base script. These effects occur at three different intervals and are # marked by three different tags. # # <before effect: string> # <prepare effect: string> # <during effect: string> # <after effect: string> # # Before effects occur before the skill cost or item consumption occurs, # but after the spell initiates. These are generally used for skill or item # preparations. # # Prepare effects occur as units are being targeted but before any HP damage # is dealt. Note that if a skill targets a unit multiple times, the prepare # effects will also run multiple times. # # During effects occur as units are being targeted and after HP damage # occurs but before moving onto the next target if done in a group. Note # that if a skill targets a unit multiple times, the during effects will # also run multiple times. # # After effects occur after the targets have all been hit. In general, this # will occur right before the skill or item's common event runs (if one was # scheduled to run). These are generally used for clean up purposes. # # If multiple tags of the same type are used in the same skill/item's # notebox, then the effects will occur in that order. Replace "string" in # the tags with the appropriate flag for the method below to search for. # Note that unlike the previous versions, these are all upcase. # # Should you choose to use multiple lunatic effects for a single skill or # item, you may use these notetags in place of the ones shown above. # # <before effect> <prepare effect> # string string # string string # </before effect> </prepare effect> # # <during effect> <after effect> # string string # string string # </during effect> </after effect> # # All of the string information in between those two notetags will be # stored the same way as the notetags shown before those. There is no # difference between using either. #-------------------------------------------------------------------------- def lunatic_object_effect(type, item, user, target) return if item.nil? case type when :before; effects = item.before_effects when :prepare; effects = item.prepare_effects when :during; effects = item.during_effects when :after; effects = item.after_effects else; return end line_number = @log_window.line_number for effect in effects case effect.upcase #---------------------------------------------------------------------- # Common Effect: Before # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs before every single skill or item # consumption even if you place it into the notebox or not. There is # no need to modify this unless you see fit. In a before effect, the # target is the user. #---------------------------------------------------------------------- when /COMMON BEFORE/i # No common before effects added. #---------------------------------------------------------------------- # Common Effect: During # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs during each targeting instance for # every single skill or item even if you place it into the notebox or # not. The prepare phase occurs before the action has takes place but # after the target has been selected. There is no need to modify this # unless you see fit. In a prepare effect, the target is the battler # being attacked. #---------------------------------------------------------------------- when /COMMON PREPARE/i # No common during effects added. #---------------------------------------------------------------------- # Common Effect: During # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs during each targeting instance for # every single skill or item even if you place it into the notebox or # not. The during phase occurs after the action has taken place but # before the next target is selected. There is no need to modify this # unless you see fit. In a during effect, the target is the battler # being attacked. #---------------------------------------------------------------------- when /COMMON DURING/i # No common during effects added. #---------------------------------------------------------------------- # Common Effect: After # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common effect that runs with every single skill or item # after targeting is over, but before common events begin even if you # place it into the notebox or not. There is no need to modify this # unless you see fit. In an after effect, the target is the user. #---------------------------------------------------------------------- when /COMMON AFTER/i # No common after effects added. #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else lunatic_object_extension(effect, item, user, target, line_number) end # effect.upcase end # for effect in effects end # lunatic_object_effect end # Scene_Battle #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module USABLEITEM BEFORE_EFFECT_STR = /<(?:BEFORE_EFFECT|before effect):[ ](.*)>/i BEFORE_EFFECT_ON = /<(?:BEFORE_EFFECT|before effect)>/i BEFORE_EFFECT_OFF = /<\/(?:BEFORE_EFFECT|before effect)>/i PREPARE_EFFECT_STR = /<(?:PREPARE_EFFECT|prepare effect):[ ](.*)>/i PREPARE_EFFECT_ON = /<(?:PREPARE_EFFECT|prepare effect)>/i PREPARE_EFFECT_OFF = /<\/(?:PREPARE_EFFECT|prepare effect)>/i DURING_EFFECT_STR = /<(?:DURING_EFFECT|during effect):[ ](.*)>/i DURING_EFFECT_ON = /<(?:DURING_EFFECT|during effect)>/i DURING_EFFECT_OFF = /<\/(?:DURING_EFFECT|during effect)>/i AFTER_EFFECT_STR = /<(?:AFTER_EFFECT|after effect):[ ](.*)>/i AFTER_EFFECT_ON = /<(?:AFTER_EFFECT|after effect)>/i AFTER_EFFECT_OFF = /<\/(?:AFTER_EFFECT|after effect)>/i end # USABLEITEM end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_lobj load_database; end def self.load_database load_database_lobj load_notetags_lobj end #-------------------------------------------------------------------------- # new method: load_notetags_lobj #-------------------------------------------------------------------------- def self.load_notetags_lobj groups = [$data_items, $data_skills] for group in groups for obj in group next if obj.nil? obj.load_notetags_lobj end end end end # DataManager #============================================================================== # ■ RPG::UsableItem #============================================================================== class RPG::UsableItem < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :before_effects attr_accessor :prepare_effects attr_accessor :during_effects attr_accessor :after_effects #-------------------------------------------------------------------------- # common cache: load_notetags_lobj #-------------------------------------------------------------------------- def load_notetags_lobj @before_effects = [] @prepare_effects = [] @during_effects = [] @after_effects = [] @before_effects_on = false @during_effects_on = false @after_effects_on = false #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::USABLEITEM::BEFORE_EFFECT_STR @before_effects.push($1.to_s) when YEA::REGEXP::USABLEITEM::PREPARE_EFFECT_STR @prepare_effects.push($1.to_s) when YEA::REGEXP::USABLEITEM::DURING_EFFECT_STR @during_effects.push($1.to_s) when YEA::REGEXP::USABLEITEM::AFTER_EFFECT_STR @after_effects.push($1.to_s) #--- when YEA::REGEXP::USABLEITEM::BEFORE_EFFECT_ON @before_effects_on = true when YEA::REGEXP::USABLEITEM::BEFORE_EFFECT_OFF @before_effects_on = false when YEA::REGEXP::USABLEITEM::PREPARE_EFFECT_ON @prepare_effects_on = true when YEA::REGEXP::USABLEITEM::PREPARE_EFFECT_OFF @prepare_effects_on = false when YEA::REGEXP::USABLEITEM::DURING_EFFECT_ON @during_effects_on = true when YEA::REGEXP::USABLEITEM::DURING_EFFECT_OFF @during_effects_on = false when YEA::REGEXP::USABLEITEM::AFTER_EFFECT_ON @after_effects_on = true when YEA::REGEXP::USABLEITEM::AFTER_EFFECT_OFF @after_effects_on = false #--- else @before_effects.push(line.to_s) if @before_effects_on @prepare_effects.push(line.to_s) if @prepare_effects_on @during_effects.push(line.to_s) if @during_effects_on @after_effects.push(line.to_s) if @after_effects_on end } # self.note.split #--- @before_effects.push("COMMON BEFORE") @prepare_effects.push("COMMON PREPARE") @during_effects.push("COMMON DURING") @after_effects.push("COMMON AFTER") end end # RPG::UsableItem #============================================================================== # ■ Game_Temp #============================================================================== class Game_Temp #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :lunatic_item attr_accessor :targets end # Game_Temp #============================================================================== # ■ Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # alias method: use_item #-------------------------------------------------------------------------- unless $imported["YEA-BattleEngine"] alias scene_battle_use_item_lobj use_item def use_item item = @subject.current_action.item lunatic_object_effect(:before, item, @subject, @subject) scene_battle_use_item_lobj lunatic_object_effect(:after, item, @subject, @subject) end #-------------------------------------------------------------------------- # alias method: apply_item_effects #-------------------------------------------------------------------------- alias scene_battle_apply_item_effects_lobj apply_item_effects def apply_item_effects(target, item) lunatic_object_effect(:prepare, item, @subject, target) scene_battle_apply_item_effects_lobj(target, item) lunatic_object_effect(:during, item, @subject, target) end end # $imported["YEA-BattleEngine"] #-------------------------------------------------------------------------- # new method: status_redraw_target #-------------------------------------------------------------------------- def status_redraw_target(target) return unless target.actor? @status_window.draw_item($game_party.battle_members.index(target)) end #-------------------------------------------------------------------------- # new method: lunatic_object_extension #-------------------------------------------------------------------------- def lunatic_object_extension(effect, item, user, target, line_number) # Reserved for future Add-ons. end end # Scene_Battle #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Lunatic_Parameters.rb
Battle/Lunatic_Parameters.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Parameters v1.01 # -- Last Updated: 2012.01.27 # -- Level: Lunatic # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LunaticParameters"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.01.27 - Bug Fixed: Wrong target during actions. # 2012.01.26 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Lunatic mode effects have always been a core part of Yanfly Engine scripts. # They exist to provide more effects for those who want more power and control # for their items, skills, status effects, etc., but the users must be able to # add them in themselves. # # Lunatic Parameters allows parameters to get custom temporary gains during # battle. These parameter bonuses are applied through custom lunatic traits # given to actors, classes, weapons, equips, enemies, and states. Once again, # keep in mind that these gains are applied only in battle. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # ● Welcome to Lunatic Mode # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Lunatic Parameters are applied similarly through a "traits" system. All # of the Lunatic Parameter tags applied from the actors, classes, weapons, # armours, enemies, and state notetags are compiled together using the # following notetag: # # <custom param: string> # # Replace param with one of the following: # MAXHP, MAXMP, ATK, DEF, MAT, MDF, AGI, LUK, or ALL # *Note: ALL only applies to ATK, DEF, MAT, MDF, AGI, and LUK # # These lunatic parameters are calculated and applied after all other # parameter calculations are made. This means, that lunatic parameter effects # are added on after the parameter base, parameter bonuses, parameter rates, # and parameter buffs are applied. # # Should you choose to use multiple lunatic traits for a single stat on one # item, you may use these notetags in place of the ones shown above. # # <custom param> # string # string # </custom param> # # All of the string information in between those two notetags will be # stored the same way as the notetags shown before those. There is no # difference between using either. #-------------------------------------------------------------------------- def lunatic_parameter(total, param_id, traits) target = current_target subject = current_subject base = total for trait in traits case trait #---------------------------------------------------------------------- # Common Effect: Common MaxHP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This trait is applied to MaxHP calculations regardless of whatever # other Lunatic Parameter traits were added. This trait is always # calculated last. #---------------------------------------------------------------------- when /COMMON MAXHP/i # No common MaxHP calculations made. #---------------------------------------------------------------------- # Common Effect: Common MaxMP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This trait is applied to MaxMP calculations regardless of whatever # other Lunatic Parameter traits were added. This trait is always # calculated last. #---------------------------------------------------------------------- when /COMMON MAXMP/i # No common MaxMP calculations made. #---------------------------------------------------------------------- # Common Effect: Common ATK # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This trait is applied to ATK calculations regardless of whatever # other Lunatic Parameter traits were added. This trait is always # calculated last. #---------------------------------------------------------------------- when /COMMON ATK/i # No common ATK calculations made. #---------------------------------------------------------------------- # Common Effect: Common DEF # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This trait is applied to DEF calculations regardless of whatever # other Lunatic Parameter traits were added. This trait is always # calculated last. #---------------------------------------------------------------------- when /COMMON DEF/i # No common DEF calculations made. #---------------------------------------------------------------------- # Common Effect: Common MAT # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This trait is applied to MAT calculations regardless of whatever # other Lunatic Parameter traits were added. This trait is always # calculated last. #---------------------------------------------------------------------- when /COMMON MAT/i # No common MAT calculations made. #---------------------------------------------------------------------- # Common Effect: Common MDF # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This trait is applied to MDF calculations regardless of whatever # other Lunatic Parameter traits were added. This trait is always # calculated last. #---------------------------------------------------------------------- when /COMMON MDF/i # No common MDF calculations made. #---------------------------------------------------------------------- # Common Effect: Common AGI # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This trait is applied to AGI calculations regardless of whatever # other Lunatic Parameter traits were added. This trait is always # calculated last. #---------------------------------------------------------------------- when /COMMON AGI/i # No common AGI calculations made. #---------------------------------------------------------------------- # Common Effect: Common LUK # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This trait is applied to LUK calculations regardless of whatever # other Lunatic Parameter traits were added. This trait is always # calculated last. #---------------------------------------------------------------------- when /COMMON LUK/i # No common LUK calculations made. #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else total = lunatic_param_extension(total, base, param_id, trait) end end return total end end # Game_BattlerBase #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module BASEITEM LUNATIC_STAT_STR = /<(?:CUSTOM|custom)[ ](.*):[ ](.*)>/i LUNATIC_STAT_ON = /<(?:CUSTOM|custom)[ ](.*)>/i LUNATIC_STAT_OFF = /<\/(?:CUSTOM|custom)[ ](.*)>/i end # BASEITEM end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_lpar load_database; end def self.load_database load_database_lpar load_notetags_lpar end #-------------------------------------------------------------------------- # new method: load_notetags_lpar #-------------------------------------------------------------------------- def self.load_notetags_lpar groups = [$data_actors, $data_classes, $data_weapons, $data_armors, $data_enemies, $data_states] for group in groups for obj in group next if obj.nil? obj.load_notetags_lpar end end end end # DataManager #============================================================================== # ■ RPG::BaseItem #============================================================================== class RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :custom_parameters #-------------------------------------------------------------------------- # common cache: load_notetags_lpar #-------------------------------------------------------------------------- def load_notetags_lpar @custom_parameters = { 0 => [], 1 => [], 2 => [], 3 => [], 4 => [], 5 => [], 6 => [], 7 => [] } @custom_parameter_on = false #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::BASEITEM::LUNATIC_STAT_STR case $1.upcase when "HP", "MAXHP", "MHP" param_id = 0 when "MP", "MAXMP", "MMP", "SP", "MAXSP", "MSP" param_id = 1 when "ATK" param_id = 2 when "DEF" param_id = 3 when "MAT", "INT", "SPI" param_id = 4 when "MDF", "RES" param_id = 5 when "AGI", "SPD" param_id = 6 when "LUK", "LUCK" param_id = 7 when "ALL" for i in 2...8 do @custom_parameters[i].push($2.to_s) end next else; next end @custom_parameters[param_id].push($2.to_s) #--- when YEA::REGEXP::BASEITEM::LUNATIC_STAT_ON case $1.upcase when "HP", "MAXHP", "MHP" param_id = 0 when "MP", "MAXMP", "MMP", "SP", "MAXSP", "MSP" param_id = 1 when "ATK" param_id = 2 when "DEF" param_id = 3 when "MAT", "INT", "SPI" param_id = 4 when "MDF", "RES" param_id = 5 when "AGI", "SPD" param_id = 6 when "LUK", "LUCK" param_id = 7 when "ALL" param_id = 8 else; next end @custom_parameter_on = param_id #--- when YEA::REGEXP::BASEITEM::LUNATIC_STAT_OFF @custom_parameter_on = false #--- else next unless @custom_parameter_on.is_a?(Integer) if @custom_parameter_on >= 8 for i in 2...8 do @custom_parameters[i].push(line.to_s) end next end @custom_parameters[@custom_parameter_on].push(line.to_s) end } # self.note.split #--- end end # RPG::BaseItem #============================================================================== # ■ Game_Temp #============================================================================== class Game_Temp #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :param_target attr_accessor :param_subject end # Game_Temp #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # alias method: param #-------------------------------------------------------------------------- alias game_battlerbase_param_lpar param def param(param_id) value = game_battlerbase_param_lpar(param_id) traits = lunatic_param_traits(param_id) value = lunatic_parameter(value, param_id, traits) return [[value, param_max(param_id)].min, param_min(param_id)].max.to_i end #-------------------------------------------------------------------------- # new method: lunatic_param_traits #-------------------------------------------------------------------------- def lunatic_param_traits(param_id) return [] unless $game_party.in_battle return [] if SceneManager.scene.is_a?(Scene_MenuBase) n = [] if actor? n += self.actor.custom_parameters[param_id] n += self.class.custom_parameters[param_id] for equip in equips next if equip.nil? n += equip.custom_parameters[param_id] end else n += self.enemy.custom_parameters[param_id] if $imported["YEA-Doppelganger"] && !self.class.nil? n += self.class.custom_parameters[param_id] end end for state in states next if state.nil? n += state.custom_parameters[param_id] end n.sort! case n when 0; n += ["COMMON MAXHP"] when 1; n += ["COMMON MAXMP"] when 2; n += ["COMMON ATK"] when 3; n += ["COMMON DEF"] when 4; n += ["COMMON MAT"] when 5; n += ["COMMON MDF"] when 6; n += ["COMMON AGI"] when 7; n += ["COMMON LUK"] end return n end #-------------------------------------------------------------------------- # new method: current_target #-------------------------------------------------------------------------- def current_target return nil unless $game_party.in_battle return nil if SceneManager.scene.is_a?(Scene_MenuBase) return nil unless $game_temp.param_subject == self return $game_temp.param_target end #-------------------------------------------------------------------------- # new method: current_subject #-------------------------------------------------------------------------- def current_subject return nil unless $game_party.in_battle return nil if SceneManager.scene.is_a?(Scene_MenuBase) return nil unless $game_temp.param_target == self return $game_temp.param_subject end #-------------------------------------------------------------------------- # new method: lunatic_param_extension #-------------------------------------------------------------------------- def lunatic_param_extension(total, base, param_id, trait) # Reserved for future Add-ons. return total end end # Game_BattlerBase #============================================================================== # ■ Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # alias method: invoke_item #-------------------------------------------------------------------------- alias scene_battle_invoke_item_lpar invoke_item def invoke_item(target, item) scene_battle_invoke_item_lpar(target, item) $game_temp.param_target = nil $game_temp.param_subject = nil end #-------------------------------------------------------------------------- # alias method: invoke_counter_attack #-------------------------------------------------------------------------- alias scene_battle_invoke_counter_attack_lpar invoke_counter_attack def invoke_counter_attack(target, item) $game_temp.param_target = @subject $game_temp.param_subject = target scene_battle_invoke_counter_attack_lpar(target, item) end #-------------------------------------------------------------------------- # alias method: invoke_magic_reflection #-------------------------------------------------------------------------- alias scene_battle_invoke_magic_reflection_lpar invoke_magic_reflection def invoke_magic_reflection(target, item) $game_temp.param_target = @subject $game_temp.param_subject = @subject scene_battle_invoke_magic_reflection_lpar(target, item) end #-------------------------------------------------------------------------- # alias method: apply_substitute #-------------------------------------------------------------------------- alias scene_battle_apply_substitute_lpar apply_substitute def apply_substitute(target, item) target = scene_battle_apply_substitute_lpar(target, item) $game_temp.param_target = target $game_temp.param_subject = @subject return target end end # Scene_Battle #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LDP_Critical.rb
Battle/LDP_Critical.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Damage Package - Critical v1.01 # -- Last Updated: 2012.02.12 # -- Level: Lunatic # -- Requires: YEA - Lunatic Damage v1.00+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LDP-Critical"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.02.12 - Bug Fixed: Typo between Critical Bonus and Critical Boost. # 2011.12.20 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic Damage Package with critical themed formulas. # Critical hits here can be triggered with various guarantees or increased # chances depending on circumstances. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic Damage. Then, proceed to use the # proper effects notetags to apply the proper LDP Critical item desired. # Look within the script for more instructions on how to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic Damage v1.00+ to work. It must be placed # under YEA - Lunatic Damage v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticDamage"] class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # ● Lunatic Damage Package Effects - Critical # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These effects are centered around the theme of dealing more damage by # actively triggering critical hits through various conditions (such as # low HP, low MP, how full the TP gauge is, and more). #-------------------------------------------------------------------------- alias lunatic_damage_extension_ldp1 lunatic_damage_extension def lunatic_damage_extension(formula, a, b, item, total_damage) user = a; value = 0 case formula.upcase #---------------------------------------------------------------------- # Critical Damage Formula No.1: Attacker HP Crisis # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the attacker strikes while his/her HP is under x%, then the attack # will cause a guaranteed critical hit using the normal damage formula. # # Formula notetag: # <custom damage: attacker hp crisis x%> #---------------------------------------------------------------------- when /ATTACKER HP CRISIS[ ](\d+)([%%])/i rate = $1.to_i * 0.01 @result.critical = true if user.hp <= user.mhp * rate value += item.damage.eval(user, self, $game_variables) #---------------------------------------------------------------------- # Critical Damage Formula No.2: Attacker MP Crisis # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the attacker strikes while his/her MP is under x%, then the attack # will cause a guaranteed critical hit using the normal damage formula. # # Formula notetag: # <custom damage: attacker mp crisis x%> #---------------------------------------------------------------------- when /ATTACKER MP CRISIS[ ](\d+)([%%])/i rate = $1.to_i * 0.01 @result.critical = true if user.mp <= user.mmp * rate value += item.damage.eval(user, self, $game_variables) #---------------------------------------------------------------------- # Critical Damage Formula No.3: Defender HP Crisis # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the attacker strikes while the defender's HP is under x%, then # the attack will cause a guaranteed critical hit using the normal # damage formula. # # Formula notetag: # <custom damage: defender hp crisis x%> #---------------------------------------------------------------------- when /DEFENDER HP CRISIS[ ](\d+)([%%])/i rate = $1.to_i * 0.01 @result.critical = true if self.hp <= self.mhp * rate value += item.damage.eval(user, self, $game_variables) #---------------------------------------------------------------------- # Critical Damage Formula No.4: Defender MP Crisis # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the attacker strikes while the defender's MP is under x%, then # the attack will cause a guaranteed critical hit using the normal # damage formula. # # Formula notetag: # <custom damage: defender mp crisis x%> #---------------------------------------------------------------------- when /DEFENDER MP CRISIS[ ](\d+)([%%])/i rate = $1.to_i * 0.01 @result.critical = true if self.mp <= self.mmp * rate value += item.damage.eval(user, self, $game_variables) #---------------------------------------------------------------------- # Critical Damage Formula No.5: High TP Critical # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This causes the attack's critical hit rate to be influenced by how # high the attacker's TP is (relative to the attacker's MaxTP). Then, # the attack will use the normal damage formula. # # Formula notetag: # <custom damage: high tp critical> #---------------------------------------------------------------------- when /HIGH TP CRITICAL/i rate = 1.0 * user.tp / user.max_tp @result.critical = (rand < rate) value += item.damage.eval(user, self, $game_variables) #---------------------------------------------------------------------- # Critical Damage Formula No.6: Low TP Critical # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This causes the attack's critical hit rate to be influenced by how # low the attacker's TP is (relative to the attacker's MaxTP). Then, # the attack will use the normal damage formula. # # Formula notetag: # <custom damage: low tp critical> #---------------------------------------------------------------------- when /LOW TP CRITICAL/i rate = 1.0 * (user.max_tp - user.tp) / user.max_tp @result.critical = (rand < rate) value += item.damage.eval(user, self, $game_variables) #---------------------------------------------------------------------- # Critical Damage Formula No.7: Critical Boost # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the attacker lands a critical hit, the damage dealt will have an # additional multiplier on top of the critical multiplier. Best used # with another damage formula. # # Formula notetag: # <custom damage: critical boost +x%> # <custom damage: critical boost -x%> #---------------------------------------------------------------------- when /CRITICAL BOOST[ ]([\+\-]\d+)([%%])/i rate = $1.to_i * 0.01 + 1.0 value = total_damage * rate if @result.critical #---------------------------------------------------------------------- # Critical Damage Formula No.8: Critical Bonus # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If the attacker lands a critical hit, the damage dealt will have an # additional bonus added on top of the critical multiplier. Best used # with another damage formula. # # Formula notetag: # <custom damage: critical bonus +x> # <custom damage: critical bonus -x> #---------------------------------------------------------------------- when /CRITICAL BONUS[ ]([\+\-]\d+)/i bonus = $1.to_i value += bonus if @result.critical else return lunatic_damage_extension_ldp1(formula, a, b, item, total_damage) end return value end end # Game_Battler end # $imported["YEA-LunaticDamage"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LSP_Protection.rb
Battle/LSP_Protection.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic States Package - Protection v1.00 # -- Last Updated: 2011.12.17 # -- Level: Lunatic # -- Requires: YEA - Lunatic States v1.00+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LSP-Protection"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.17 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic States Package Effects with protection themed # effects. These effects reduce damage based on various situations and # conditions, but they overall protect the user. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic States. Then, proceed to use the # proper effects notetags to apply the proper LSP Protection item desired. # Look within the script for more instructions on how to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic States v1.00+ to work. It must be placed # under YEA - Lunatic States v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticStates"] class Game_BattlerBase #-------------------------------------------------------------------------- # ● Lunatic States Package Effects - Protection # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These effects are centered around the theme of protection through mostly # damage reduction effects. #-------------------------------------------------------------------------- alias lunatic_state_extension_lsp2 lunatic_state_extension def lunatic_state_extension(effect, state, user, state_origin, log_window) case effect.upcase #---------------------------------------------------------------------- # Protection Effect No.1: Damage Cut # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with react effect. This causes any HP damage under the # marked MaxHP percentage to be nullified. # # Recommended notetag: # <react effect: damage cut x%> #---------------------------------------------------------------------- when /DAMAGE CUT[ ](\d+)([%%])/i return unless @result.hp_damage > 0 return unless self.mhp * $1.to_i * 0.01 >= @result.hp_damage @result.hp_damage = 0 return unless $imported["YEA-BattleEngine"] create_popup(state.name, "IMMU_ELE") #---------------------------------------------------------------------- # Protection Effect No.2: Damage Barrier # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with react effect. This causes any HP damage over the # marked MaxHP percentage to be nullified. # # Recommended notetag: # <react effect: damage barrier x%> #---------------------------------------------------------------------- when /DAMAGE BARRIER[ ](\d+)([%%])/i return unless @result.hp_damage > 0 return unless self.mhp * $1.to_i * 0.01 <= @result.hp_damage @result.hp_damage = 0 return unless $imported["YEA-BattleEngine"] create_popup(state.name, "IMMU_ELE") #---------------------------------------------------------------------- # Protection Effect No.3: Damage Shelter # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with react effect. This causes any HP damage over the # marked MaxHP percentage to be capped at the marked MaxHP percentage. # # Recommended notetag: # <react effect: damage shelter x%> #---------------------------------------------------------------------- when /DAMAGE SHELTER[ ](\d+)([%%])/i return unless @result.hp_damage > 0 return unless self.mhp * $1.to_i * 0.01 <= @result.hp_damage @result.hp_damage = (self.mhp * $1.to_i * 0.01).to_i return unless $imported["YEA-BattleEngine"] create_popup(state.name, "REST_ELE") #---------------------------------------------------------------------- # Protection Effect No.4: Damage Block # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with react effect. This causes any HP damage to decrease # (or increase if you use the + tag) by a set amount. Decreased damage # will not go under zero. # # Recommended notetag: # <react effect: damage block -x> # <react effect: damage block +x> #---------------------------------------------------------------------- when /DAMAGE BLOCK[ ]([\+\-]\d+)/i return unless @result.hp_damage > 0 @result.hp_damage = [@result.hp_damage + $1.to_i, 0].max #---------------------------------------------------------------------- # Protection Effect No.5: Heal Boost # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with react effect. This causes any HP healing done to be # increased (or decreased) by a multiplier. # # Recommended notetag: # <react effect: heal boost x%> #---------------------------------------------------------------------- when /HEAL BOOST[ ](\d+)([%%])/i return unless @result.hp_damage < 0 @result.hp_damage = (@result.hp_damage * $1.to_i * 0.01).to_i #---------------------------------------------------------------------- # Protection Effect No.6: Heal Bonus # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with react effect. This causes any HP healing done to be # increased (or decreased) by a set amount. Healing done cannot be # changed to damage. # # Recommended notetag: # <react effect: heal bonus +x> # <react effect: heal bonus -x> #---------------------------------------------------------------------- when /HEAL BONUS[ ]([\+\-]\d+)/i return unless @result.hp_damage < 0 @result.hp_damage = [@result.hp_damage - $1.to_i, 0].min #---------------------------------------------------------------------- # Protection Effect No.7: Persist # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Best used with remove effect. If the user receives damage that would # be lethal, there is a chance that the user will persist and live at # 1 HP left. # # Recommended notetag: # <react effect: persist x%> #---------------------------------------------------------------------- when /PERSIST[ ](\d+)([%%])/i return unless @result.hp_damage >= self.hp return if rand > $1.to_i * 0.01 @result.hp_damage = self.hp - 1 return unless $imported["YEA-BattleEngine"] create_popup(state.name, "WEAK_ELE") #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else so = state_origin lw = log_window lunatic_state_extension_lsp2(effect, state, user, so, lw) end end end # Game_BattlerBase end # $imported["YEA-LunaticStates"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/LDP_Gemini.rb
Battle/LDP_Gemini.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Damage Package - Gemini v1.00 # -- Last Updated: 2011.12.22 # -- Level: Lunatic # -- Requires: YEA - Lunatic Damage v1.00+ # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LDP-Gemini"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.22 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This is a script for Lunatic Damage Package with "Gemini" themed formulas. # This script causes damage to be dealt to both HP and MP with various formats # such as a percentage of the main damage dealt, set damage, a percentage of # one's MaxHP or MaxMP, or even custom formulas. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Install this script under YEA - Lunatic Damage. Then, proceed to use the # proper effects notetags to apply the proper LDP Gemini item desired. # Look within the script for more instructions on how to use each effect. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires YEA - Lunatic Damage v1.00+ to work. It must be placed # under YEA - Lunatic Damage v1.00+ in the script listing. # #============================================================================== if $imported["YEA-LunaticDamage"] class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # ● Lunatic Damage Package Effects - Gemini # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # These effects are centered around the theme of dealing damage to both # HP and MP through various means. #-------------------------------------------------------------------------- alias lunatic_damage_extension_ldp3 lunatic_damage_extension def lunatic_damage_extension(formula, a, b, item, total_damage) user = a; value = 0 case formula #---------------------------------------------------------------------- # Gemini Damage Formula No.1: Gemini MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates main damage formula using the normal damage formula. After # that, a percentage of damage dealt to HP will be dealt to MP. MP # damage will not be affected by elements, guarding, and/or other # damage modifiers. # # Formula notetag: # <custom damage: gemini mp x%> #---------------------------------------------------------------------- when /GEMINI MP[ ](\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) @result.mp_damage += ($1.to_i * 0.01 * value).to_i #---------------------------------------------------------------------- # Gemini Damage Formula No.2: Gemini HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates main damage formula using the normal damage formula. After # that, a percentage of damage dealt to MP will be dealt to HP. MP # damage will not be affected by elements, guarding, and/or other # damage modifiers. # # Formula notetag: # <custom damage: gemini hp x%> #---------------------------------------------------------------------- when /GEMINI HP[ ](\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) @result.hp_damage += ($1.to_i * 0.01 * value).to_i #---------------------------------------------------------------------- # Gemini Damage Formula No.3: Gemini Set MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates main damage formula using the normal damage formula. After # that, set damage will be dealt to MP. MP damage will not be affected # by elements, guarding, and/or other damage modifiers. # # Formula notetag: # <custom damage: gemini set mp +x> # <custom damage: gemini set mp -x> #---------------------------------------------------------------------- when /GEMINI SET MP[ ]([\+\-]\d+)/i value += item.damage.eval(user, self, $game_variables) @result.mp_damage += $1.to_i #---------------------------------------------------------------------- # Gemini Damage Formula No.4: Gemini Set HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates main damage formula using the normal damage formula. After # that, set damage will be dealt to HP. HP damage will not be affected # by elements, guarding, and/or other damage modifiers. # # Formula notetag: # <custom damage: gemini set hp +x> # <custom damage: gemini set hp -x> #---------------------------------------------------------------------- when /GEMINI SET HP[ ]([\+\-]\d+)/i value += item.damage.eval(user, self, $game_variables) @result.hp_damage += $1.to_i #---------------------------------------------------------------------- # Gemini Damage Formula No.5: Gemini Percent MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates main damage formula using the normal damage formula. After # that, a percentage of the defender's MP will be depleted. MP damage # will not be affected by elements, guarding, and/or other damage # modifiers. # # Formula notetag: # <custom damage: gemini per mp +x%> # <custom damage: gemini per mp -x%> #---------------------------------------------------------------------- when /GEMINI PER MP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) @result.mp_damage += ($1.to_i * 0.01 * self.mmp).to_i #---------------------------------------------------------------------- # Gemini Damage Formula No.6: Gemini Percent HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates main damage formula using the normal damage formula. After # that, a percentage of the defender's HP will be depleted. HP damage # will not be affected by elements, guarding, and/or other damage # modifiers. # # Formula notetag: # <custom damage: gemini per hp +x%> # <custom damage: gemini per hp -x%> #---------------------------------------------------------------------- when /GEMINI PER HP[ ]([\+\-]\d+)([%%])/i value += item.damage.eval(user, self, $game_variables) @result.hp_damage += ($1.to_i * 0.01 * self.mhp).to_i #---------------------------------------------------------------------- # Gemini Damage Formula No.7: Gemini Eval MP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates main damage formula using the normal damage formula. After # that, the damage dealt to MP will be calculated with another formula. # MP damage will not be affected by elements, guarding, and/or other # damage modifiers. # # Formula notetag: # <custom damage> # gemini eval mp: formula # </custom damage> #---------------------------------------------------------------------- when /GEMINI EVAL MP:[ ](.*)/i value += item.damage.eval(user, self, $game_variables) @result.mp_damage += (eval($1.to_s)).to_i #---------------------------------------------------------------------- # Gemini Damage Formula No.8: Gemini Eval HP # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Calculates main damage formula using the normal damage formula. After # that, the damage dealt to HP will be calculated with another formula. # MP damage will not be affected by elements, guarding, and/or other # damage modifiers. # # Formula notetag: # <custom damage> # gemini eval hp: formula # </custom damage> #---------------------------------------------------------------------- when /GEMINI EVAL HP:[ ](.*)/i value += item.damage.eval(user, self, $game_variables) @result.hp_damage += (eval($1.to_s)).to_i else return lunatic_damage_extension_ldp3(formula, a, b, item, total_damage) end return value end end # Game_Battler end # $imported["YEA-LunaticDamage"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Command_Autobattle.rb
Battle/Command_Autobattle.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Command Autobattle v1.01 # -- Last Updated: 2011.12.26 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-CommandAutobattle"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.26 - Bug Fixed: Autobattle cancelled after each battle. # 2011.12.12 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Anyone remember the Autobattle command from RPG Maker 2000? Well, now it's # back and you can choose to tack it onto the Party Command Window or the Actor # Command Window. When autobattle is selected, it will let the game determine # what action to use for the party and/or actors depending on the game's A.I. # # Furthermore, there is an option to have Autobattle continously remain in # effect if selected from the Party Command Window. When Autobattle is selected # in the Actor Command Window, it'll cause the game to automatically choose an # action for that actor instead. # # In addition to this, there exists the functionality of having all battle # members but the first member autobattle. This feature can be turned off. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # Adjust the settings in the module to your liking. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== module YEA module AUTOBATTLE #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Party Autobattle Command Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Adjust the command settings for Autobattle under the Party Command Window # here. If you decide to let Party Autobattle be continuous, it will keep # going until the player decides to cancel it with X. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ENABLE_PARTY_AUTOBATTLE = true # Enables autobattle in Party Window. PARTY_COMMAND_NAME = "Auto" # Text that appears for Autobattle. PARTY_SHOW_SWITCH = 0 # Switch used to show Autobattle. PARTY_ENABLE_SWITCH = 0 # Switch used to enable Autobattle. # Note: For both of the switches, if they are set to 0, then the feature # will not be used at all. The command will always be shown and/or the # command will always be enabled. # These settings adjust continous autobattle. If enabled, these settings # will be applied. Otherwise, they won't be. ENABLE_CONTINOUS = true # If true, autobattle is continous. DISABLE_MESSAGE = "Press Cancel to turn off Autobattle." #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Actor Autobattle Command Settings - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Adjust the command settings for Autobattle under the Actor Command Window # here. Actors do not have continous autobattle. Instead, they just simply # choose whatever action the game decides is most suitable for them. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ENABLE_ACTOR_AUTOBATTLE = true # Enables autobattle in Party Window. ACTOR_COMMAND_NAME = "Auto" # Text that appears for Autobattle. ACTOR_SHOW_SWITCH = 0 # Switch used to show Autobattle. ACTOR_ENABLE_SWITCH = 0 # Switch used to enable Autobattle. # Note: For both of the switches, if they are set to 0, then the feature # will not be used at all. The command will always be shown and/or the # command will always be enabled. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Secondary Members Autobattle - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # For those who only want to grant command control to the first actor in # battle, enable the setting below. All of the battle members who aren't # first in line will automatically choose their action for the turn. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ENABLE_SECONDARY_AUTOBATTLE = false end # AUTOBATTLE end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== #============================================================================== # ■ BattleManager #============================================================================== module BattleManager #-------------------------------------------------------------------------- # alias method: process_victory #-------------------------------------------------------------------------- class <<self; alias battlemanager_process_victory_cab process_victory; end def self.process_victory SceneManager.scene.close_disable_autobattle_window return battlemanager_process_victory_cab end #-------------------------------------------------------------------------- # alias method: process_abort #-------------------------------------------------------------------------- class <<self; alias battlemanager_process_abort_cab process_abort; end def self.process_abort SceneManager.scene.close_disable_autobattle_window return battlemanager_process_abort_cab end #-------------------------------------------------------------------------- # alias method: process_defeat #-------------------------------------------------------------------------- class <<self; alias battlemanager_process_defeat_cab process_defeat; end def self.process_defeat SceneManager.scene.close_disable_autobattle_window return battlemanager_process_defeat_cab end end # BattleManager #============================================================================== # ■ Game_Temp #============================================================================== class Game_Temp #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :continous_autobattle end # Game_Temp #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # alias method: auto_battle? #-------------------------------------------------------------------------- alias game_battlerbase_auto_battle_cab auto_battle? def auto_battle? return true if continuous_autobattle? return true if secondary_auto_battle? return game_battlerbase_auto_battle_cab end #-------------------------------------------------------------------------- # new method: continuous_autobattle? #-------------------------------------------------------------------------- def continuous_autobattle? return false unless actor? return $game_temp.continous_autobattle end #-------------------------------------------------------------------------- # new method: secondary_auto_battle? #-------------------------------------------------------------------------- def secondary_auto_battle? return false unless actor? return false if index == 0 return YEA::AUTOBATTLE::ENABLE_SECONDARY_AUTOBATTLE end end # Game_BattlerBase #============================================================================== # ■ Game_Unit #============================================================================== class Game_Unit #-------------------------------------------------------------------------- # alias method: make_actions #-------------------------------------------------------------------------- alias game_unit_make_actions_cab make_actions def make_actions game_unit_make_actions_cab refresh_autobattler_status_window end #-------------------------------------------------------------------------- # new method: refresh_autobattler_status_window #-------------------------------------------------------------------------- def refresh_autobattler_status_window return unless SceneManager.scene_is?(Scene_Battle) return unless self.is_a?(Game_Party) SceneManager.scene.refresh_autobattler_status_window end end # Game_Unit #============================================================================== # ■ Window_PartyCommand #============================================================================== class Window_PartyCommand < Window_Command #-------------------------------------------------------------------------- # alias method: make_command_list #-------------------------------------------------------------------------- alias window_partycommand_cab make_command_list def make_command_list window_partycommand_cab return if $imported["YEA-BattleCommandList"] add_autobattle_command if YEA::AUTOBATTLE::ENABLE_PARTY_AUTOBATTLE end #-------------------------------------------------------------------------- # new method: add_autobattle_command #-------------------------------------------------------------------------- def add_autobattle_command return unless show_autobattle? text = YEA::AUTOBATTLE::PARTY_COMMAND_NAME add_command(text, :autobattle, enable_autobattle?) end #-------------------------------------------------------------------------- # new method: show_autobattle? #-------------------------------------------------------------------------- def show_autobattle? return true if YEA::AUTOBATTLE::PARTY_SHOW_SWITCH <= 0 return $game_switches[YEA::AUTOBATTLE::PARTY_SHOW_SWITCH] end #-------------------------------------------------------------------------- # new method: enable_autobattle? #-------------------------------------------------------------------------- def enable_autobattle? return true if YEA::AUTOBATTLE::PARTY_ENABLE_SWITCH <= 0 return $game_switches[YEA::AUTOBATTLE::PARTY_ENABLE_SWITCH] end end # Window_PartyCommand #============================================================================== # ■ Window_ActorCommand #============================================================================== class Window_ActorCommand < Window_Command #-------------------------------------------------------------------------- # alias method: make_command_list #-------------------------------------------------------------------------- alias window_actorcommand_make_command_list_cab make_command_list def make_command_list return if @actor.nil? unless $imported["YEA-BattleCommandList"] add_autobattle_command if YEA::AUTOBATTLE::ENABLE_ACTOR_AUTOBATTLE end window_actorcommand_make_command_list_cab end #-------------------------------------------------------------------------- # new method: add_autobattle_command #-------------------------------------------------------------------------- def add_autobattle_command return unless show_autobattle? text = YEA::AUTOBATTLE::ACTOR_COMMAND_NAME add_command(text, :autobattle, enable_autobattle?) end #-------------------------------------------------------------------------- # new method: show_autobattle? #-------------------------------------------------------------------------- def show_autobattle? return true if YEA::AUTOBATTLE::ACTOR_SHOW_SWITCH <= 0 return $game_switches[YEA::AUTOBATTLE::ACTOR_SHOW_SWITCH] end #-------------------------------------------------------------------------- # new method: enable_autobattle? #-------------------------------------------------------------------------- def enable_autobattle? return true if YEA::AUTOBATTLE::ACTOR_ENABLE_SWITCH <= 0 return $game_switches[YEA::AUTOBATTLE::ACTOR_ENABLE_SWITCH] end end # Window_ActorCommand #============================================================================== # ■ Window_DisableAutobattle #============================================================================== class Window_DisableAutobattle < Window_Base #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize super(64, 0, Graphics.width - 128, fitting_height(1)) self.y = Graphics.height - fitting_height(1) + 12 self.opacity = 0 self.z = 1000 hide refresh end #-------------------------------------------------------------------------- # refresh #-------------------------------------------------------------------------- def refresh contents.clear draw_background(contents.rect) text = YEA::AUTOBATTLE::DISABLE_MESSAGE draw_text(contents.rect, text, 1) end #-------------------------------------------------------------------------- # draw_background #-------------------------------------------------------------------------- def draw_background(rect) temp_rect = rect.clone temp_rect.width /= 2 contents.gradient_fill_rect(temp_rect, back_color2, back_color1) temp_rect.x = temp_rect.width contents.gradient_fill_rect(temp_rect, back_color1, back_color2) end #-------------------------------------------------------------------------- # back_color1 #-------------------------------------------------------------------------- def back_color1; return Color.new(0, 0, 0, 192); end #-------------------------------------------------------------------------- # back_color2 #-------------------------------------------------------------------------- def back_color2; return Color.new(0, 0, 0, 0); end end # Window_DisableAutobattle #============================================================================== # ■ Scene_Battle #============================================================================== class Scene_Battle < Scene_Base #-------------------------------------------------------------------------- # alias method: create_all_windows #-------------------------------------------------------------------------- alias scene_battle_create_all_windows_cab create_all_windows def create_all_windows $game_temp.continous_autobattle = false scene_battle_create_all_windows_cab create_disable_autobattle_window end #-------------------------------------------------------------------------- # alias method: create_party_command_window #-------------------------------------------------------------------------- alias create_party_command_window_cab create_party_command_window def create_party_command_window create_party_command_window_cab @party_command_window.set_handler(:autobattle, method(:command_pautobattle)) end #-------------------------------------------------------------------------- # new method: command_pautobattle #-------------------------------------------------------------------------- def command_pautobattle for member in $game_party.battle_members next unless member.inputable? member.make_auto_battle_actions end $game_temp.continous_autobattle = YEA::AUTOBATTLE::ENABLE_CONTINOUS @disable_autobattle_window.show if $game_temp.continous_autobattle refresh_autobattler_status_window turn_start end #-------------------------------------------------------------------------- # new method: create_disable_autobattle_window #-------------------------------------------------------------------------- def create_disable_autobattle_window @disable_autobattle_window = Window_DisableAutobattle.new end #-------------------------------------------------------------------------- # alias method: update #-------------------------------------------------------------------------- alias scene_battle_update_cab update def update scene_battle_update_cab update_continous_autobattle_window end #-------------------------------------------------------------------------- # alias method: update_basic #-------------------------------------------------------------------------- alias scene_battle_update_basic_cab update_basic def update_basic scene_battle_update_basic_cab update_continous_autobattle_window end #-------------------------------------------------------------------------- # new method: update_continous_autobattle_window #-------------------------------------------------------------------------- def update_continous_autobattle_window return unless @disable_autobattle_window.visible opacity = $game_message.visible ? 0 : 255 @disable_autobattle_window.contents_opacity = opacity close_disable_autobattle_window if Input.press?(:B) end #-------------------------------------------------------------------------- # new method: close_disable_autobattle_window #-------------------------------------------------------------------------- def close_disable_autobattle_window Sound.play_cancel if Input.press?(:B) && @disable_autobattle_window.visible $game_temp.continous_autobattle = false @disable_autobattle_window.hide end #-------------------------------------------------------------------------- # alias method: create_actor_command_window #-------------------------------------------------------------------------- alias create_actor_command_window_cab create_actor_command_window def create_actor_command_window create_actor_command_window_cab @actor_command_window.set_handler(:autobattle, method(:command_aautobattle)) end #-------------------------------------------------------------------------- # new method: command_aautobattle #-------------------------------------------------------------------------- def command_aautobattle BattleManager.actor.make_auto_battle_actions next_command end #-------------------------------------------------------------------------- # new method: refresh_autobattler_status_window #-------------------------------------------------------------------------- def refresh_autobattler_status_window for member in $game_party.battle_members next unless member.auto_battle? @status_window.draw_item(member.index) end end end # Scene_Battle #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Extra_Drops.rb
Battle/Extra_Drops.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Extra Drops v1.01 # -- Last Updated: 2011.12.31 # -- Level: Normal # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-ExtraDrops"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2011.12.31 - Bug Fixed: Drop ratios now work properly. # 2011.12.17 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Enemies by default only drop three items maximum in RPG Maker VX Ace. The # drop rates are also limited to rates that can only be achieved through # denominator values. A drop rate of say, 75% cannot be achieved. This script # provides the ability to add more than just three drops and more control over # the drop rates, too. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Enemy Notetags - These notetags go in the enemies notebox in the database. # ----------------------------------------------------------------------------- # <drop Ix: y%> # <drop Wx: y%> # <drop Ax: y%> # Causes enemy to drop item, weapon, or armour (marked by I, W, or A) x at a # rate of y percent. Insert multiples of this tag to increase the number of # drops an enemy can possibly have. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module ENEMY DROP_PLUS = /<(?:DROP|drop)[ ]([IWA])(\d+):[ ](\d+)([%%])>/i end # ENEMY end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_edr load_database; end def self.load_database load_database_edr load_notetags_edr end #-------------------------------------------------------------------------- # new method: load_notetags_al #-------------------------------------------------------------------------- def self.load_notetags_edr for enemy in $data_enemies next if enemy.nil? enemy.load_notetags_edr end end end # DataManager #============================================================================== # ■ RPG::Enemy #============================================================================== class RPG::Enemy < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :extra_drops #-------------------------------------------------------------------------- # common cache: load_notetags_edr #-------------------------------------------------------------------------- def load_notetags_edr @extra_drops = [] #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::ENEMY::DROP_PLUS case $1.upcase when "I"; kind = 1 when "W"; kind = 2 when "A"; kind = 3 else; next end item = RPG::Enemy::DropItem.new item.kind = kind item.data_id = $2.to_i item.drop_rate = $3.to_i * 0.01 @extra_drops.push(item) end } # self.note.split #--- end end # RPG::Enemy #============================================================================== # ■ RPG::Enemy::DropItem #============================================================================== class RPG::Enemy::DropItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :drop_rate #-------------------------------------------------------------------------- # new method: drop_rate #-------------------------------------------------------------------------- def drop_rate return 0 if @drop_rate.nil? return @drop_rate end end # RPG::Enemy::DropItem #============================================================================== # ■ Game_Enemy #============================================================================== class Game_Enemy < Game_Battler #-------------------------------------------------------------------------- # alias method: make_drop_items #-------------------------------------------------------------------------- alias game_enemy_make_drop_items_edr make_drop_items def make_drop_items result = game_enemy_make_drop_items_edr result += make_extra_drops return result end #-------------------------------------------------------------------------- # new method: make_extra_drops #-------------------------------------------------------------------------- def make_extra_drops result = [] for drop in enemy.extra_drops next if rand > drop.drop_rate result.push(item_object(drop.kind, drop.data_id)) end return result end end # Game_Enemy #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Lunatic_Targets.rb
Battle/Lunatic_Targets.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Lunatic Targets v1.00 # -- Last Updated: 2012.01.02 # -- Level: Lunatic # -- Requires: n/a # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-LunaticTargets"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.01.02 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Lunatic mode effects have always been a core part of Yanfly Engine scripts. # They exist to provide more effects for those who want more power and control # for their items, skills, status effects, etc., but the users must be able to # add them in themselves. # # This script provides the base setup for state lunatic targeting. This script # lets you select a custom scope of targets that can be either dynmaic or a set # scope. This script will work with YEA - Target Manager as long as it's placed # above YEA - Target Manager. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script is compatible with Yanfly Engine Ace - Target Manager v1.01+. # Place this script above Yanfly Engine Ace - Target Manager v1.01+. # #============================================================================== class Game_Action #-------------------------------------------------------------------------- # ● Welcome to Lunatic Mode # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Lunatic Targets allow allow skills and items to select a custom set of # targets for their scope. To make use of a Lunatic Target scope, use the # following notetag: # # <custom target: string> # # If multiple tags of the same type are used in the same skill/item's # notebox, then the targets will be selected in that order. Replace "string" # in the tags with the appropriate flag for the method below to search for. # Note that unlike the previous versions, these are all upcase. # # Should you choose to use multiple lunatic target scopes for a single # object, you may use these notetags in place of the ones shown above. # # <custom target> # string # string # </custom target> # # All of the string information in between those two notetags will be # stored the same way as the notetags shown before those. There is no # difference between using either. #-------------------------------------------------------------------------- def lunatic_target(smooth_target) user = subject targets = [] for effect in item.custom_targets case effect.upcase #---------------------------------------------------------------------- # Common Before Target # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common scope that runs at the start of a targeting scope. # Any changes made here will affect the targeting of all skills/items. #---------------------------------------------------------------------- when /COMMON BEFORE TARGET/i # No common targeting effects applied. #---------------------------------------------------------------------- # Common After Target # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # This is a common scope that runs at the end of a targeting scope. # Any changes made here will affect the targeting of all skills/items. #---------------------------------------------------------------------- when /COMMON AFTER TARGET/i # No common targeting effects applied. #---------------------------------------------------------------------- # Default Targets # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If this tag is used, then the default targets will be added to the # total scope of targets. #---------------------------------------------------------------------- when /DEFAULT TARGET/i targets += default_target_set #---------------------------------------------------------------------- # Stop editting past this point. #---------------------------------------------------------------------- else targets = lunatic_targets_extension(effect, user, smooth_target, targets) end end return targets end end # Game_Action #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== module YEA module REGEXP module USABLEITEM CUSTOM_TARGET_STR = /<(?:CUSTOM_TARGET|custom target|custom targets):[ ](.*)>/i CUSTOM_TARGET_ON = /<(?:CUSTOM_TARGET|custom target|custom targets)>/i CUSTOM_TARGET_OFF = /<\/(?:CUSTOM_TARGET|custom target|custom targets)>/i end # USABLEITEM end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_ltar load_database; end def self.load_database load_database_ltar load_notetags_ltar end #-------------------------------------------------------------------------- # new method: load_notetags_ltar #-------------------------------------------------------------------------- def self.load_notetags_ltar groups = [$data_items, $data_skills] for group in groups for obj in group next if obj.nil? obj.load_notetags_ltar end end end end # DataManager #============================================================================== # ■ RPG::UsableItem #============================================================================== class RPG::UsableItem < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :custom_targets #-------------------------------------------------------------------------- # common cache: load_notetags_ltar #-------------------------------------------------------------------------- def load_notetags_ltar @custom_targets = ["COMMON BEFORE TARGET"] @custom_targets_on = false #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::USABLEITEM::CUSTOM_TARGET_STR @custom_targets.push($1.to_s) #--- when YEA::REGEXP::USABLEITEM::CUSTOM_TARGET_ON @custom_targets_on = true when YEA::REGEXP::USABLEITEM::CUSTOM_TARGET_OFF @custom_targets_on = false #--- else @custom_targets.push(line.to_s) if @custom_targets_on end } # self.note.split #--- @custom_targets.push("DEFAULT TARGET") if @custom_targets.size == 1 @custom_targets.push("COMMON AFTER TARGET") end end # RPG::UsableItem #============================================================================== # ■ Game_Action #============================================================================== class Game_Action #-------------------------------------------------------------------------- # alias method: make_targets #-------------------------------------------------------------------------- alias game_action_make_targets_ltar make_targets def make_targets group = item.for_friend? ? friends_unit : opponents_unit smooth_target = group.smooth_target(@target_index) return lunatic_target(smooth_target) end #-------------------------------------------------------------------------- # new method: default_target_set #-------------------------------------------------------------------------- def default_target_set return game_action_make_targets_ltar end #-------------------------------------------------------------------------- # new method: lunatic_targets_extension #-------------------------------------------------------------------------- def lunatic_targets_extension(effect, user, smooth_target, targets) # Reserved for future Add-ons. return targets end end # Game_Action #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false
Archeia/YEARepo
https://github.com/Archeia/YEARepo/blob/9549551db08e98cfddc46c1165c2807bc87eabd6/Battle/Enemy_HP_Bars.rb
Battle/Enemy_HP_Bars.rb
#============================================================================== # # ▼ Yanfly Engine Ace - Battle Engine Add-On: Enemy HP Bars v1.10 # -- Last Updated: 2012.02.10 # -- Level: Easy, Normal # -- Requires: YEA - Ace Battle Engine v1.00+. # #============================================================================== $imported = {} if $imported.nil? $imported["YEA-EnemyHPBars"] = true #============================================================================== # ▼ Updates # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # 2012.02.10 - Bug Fixed: AoE selection doesn't reveal hidden enemies. # 2012.02.01 - Bug Fixed: Back and front of gauge randomly don't appear. # 2012.01.11 - Efficiency update. # 2012.01.04 - Compatibility Update: Area of Effect # 2011.12.28 - Efficiency update. # - Bug Fixed: HP bars didn't disappear after a heal. # 2011.12.26 - Bug Fixed: HP bars were not depleting. # 2011.12.23 - Efficiency update. # 2011.12.10 - Bug Fixed: HP bars no longer appear when dead and an AoE skill # has been selected. # 2011.12.08 - New feature. Hide HP Bars until defeated once. # 2011.12.06 - Started Script and Finished. # #============================================================================== # ▼ Introduction # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script shows HP gauges on enemies as they're selected for targeting or # whenever they're damaged. The HP gauges will actually slide downward or # upward as the enemies take damage. # # Included in v1.01 is the option to require the player having slain an enemy # once before enemies of that type will show their HP gauge. # #============================================================================== # ▼ Instructions # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # To install this script, open up your script editor and copy/paste this script # to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save. # # ----------------------------------------------------------------------------- # Enemy Notetags - These notetags go in the enemy notebox in the database. # ----------------------------------------------------------------------------- # <back gauge: x> # Changes the colour of the enemy HP back gauge to x where x is the text colour # used from the "Window" skin image under Graphics\System. # # <hp gauge 1: x> # <hp gauge 2: x> # Changes the colour of the enemy HP HP gauge to x where x is the text colour # used from the "Window" skin image under Graphics\System. # # <hide gauge> # <show gauge> # Hides/shows HP gauge for enemies in battle. These gauges appear whenever the # enemy is targeted for battle or whenever the enemy takes HP damage. Note that # using the <show gauge> tag will bypass the requirement for needing to defeat # an enemy once if that setting is enabled. # #============================================================================== # ▼ Compatibility # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This script is made strictly for RPG Maker VX Ace. It is highly unlikely that # it will run with RPG Maker VX without adjusting. # # This script requires Yanfly Engine Ace - Ace Battle Engine v1.00+ and the # script must be placed under Ace Battle Engine in the script listing. # #============================================================================== module YEA module BATTLE #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # - Enemy HP Gauges - #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Adjust the settings for the enemy HP gauges. You can choose to show the # enemy HP gauges by default, the size of the gauge, the colour of the # gauge, and the back colour of the gauge. #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- SHOW_ENEMY_HP_GAUGE = true # Display Enemy HP Gauge? ANIMATE_HP_GAUGE = true # Animate the HP gauge? DEFEAT_ENEMIES_FIRST = false # Must defeat enemy first to show HP? ENEMY_GAUGE_WIDTH = 128 # How wide the enemy gauges are. ENEMY_GAUGE_HEIGHT = 12 # How tall the enemy gauges are. ENEMY_HP_GAUGE_COLOUR1 = 20 # Colour 1 for HP. ENEMY_HP_GAUGE_COLOUR2 = 21 # Colour 2 for HP. ENEMY_BACKGAUGE_COLOUR = 19 # Gauge Back colour. end # BATTLE end # YEA #============================================================================== # ▼ Editting anything past this point may potentially result in causing # computer damage, incontinence, explosion of user's head, coma, death, and/or # halitosis so edit at your own risk. #============================================================================== if $imported["YEA-BattleEngine"] module YEA module REGEXP module ENEMY HIDE_GAUGE = /<(?:HIDE_GAUGE|hide gauge)>/i SHOW_GAUGE = /<(?:SHOW_GAUGE|show gauge)>/i BACK_GAUGE = /<(?:BACK_GAUGE|back gauge):[ ]*(\d+)>/i HP_GAUGE_1 = /<(?:HP_GAUGE_1|hp gauge 1):[ ]*(\d+)>/i HP_GAUGE_2 = /<(?:HP_GAUGE_2|hp gauge 2):[ ]*(\d+)>/i end # ENEMY end # REGEXP end # YEA #============================================================================== # ■ DataManager #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method: load_database #-------------------------------------------------------------------------- class <<self; alias load_database_ehpb load_database; end def self.load_database load_database_ehpb load_notetags_ehpb end #-------------------------------------------------------------------------- # new method: load_notetags_ehpb #-------------------------------------------------------------------------- def self.load_notetags_ehpb groups = [$data_enemies] for group in groups for obj in group next if obj.nil? obj.load_notetags_ehpb end end end end # DataManager #============================================================================== # ■ RPG::Enemy #============================================================================== class RPG::Enemy < RPG::BaseItem #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :show_gauge attr_accessor :require_death_show_gauge attr_accessor :back_gauge_colour attr_accessor :hp_gauge_colour1 attr_accessor :hp_gauge_colour2 #-------------------------------------------------------------------------- # common cache: load_notetags_ehpb #-------------------------------------------------------------------------- def load_notetags_ehpb @show_gauge = YEA::BATTLE::SHOW_ENEMY_HP_GAUGE @require_death_show_gauge = YEA::BATTLE::DEFEAT_ENEMIES_FIRST @back_gauge_colour = YEA::BATTLE::ENEMY_BACKGAUGE_COLOUR @hp_gauge_colour1 = YEA::BATTLE::ENEMY_HP_GAUGE_COLOUR1 @hp_gauge_colour2 = YEA::BATTLE::ENEMY_HP_GAUGE_COLOUR2 #--- self.note.split(/[\r\n]+/).each { |line| case line #--- when YEA::REGEXP::ENEMY::HIDE_GAUGE @show_gauge = false when YEA::REGEXP::ENEMY::SHOW_GAUGE @show_gauge = true @require_death_show_gauge = false when YEA::REGEXP::ENEMY::BACK_GAUGE @back_gauge_colour = [$1.to_i, 31].min when YEA::REGEXP::ENEMY::HP_GAUGE_1 @hp_gauge_colour1 = [$1.to_i, 31].min when YEA::REGEXP::ENEMY::HP_GAUGE_2 @hp_gauge_colour2 = [$1.to_i, 31].min end } # self.note.split #--- end end # RPG::Enemy #============================================================================== # ■ Sprite_Battler #============================================================================== class Sprite_Battler < Sprite_Base #-------------------------------------------------------------------------- # alias method: initialize #-------------------------------------------------------------------------- alias sprite_battler_initialize_ehpb initialize def initialize(viewport, battler = nil) sprite_battler_initialize_ehpb(viewport, battler) create_enemy_gauges end #-------------------------------------------------------------------------- # alias method: dispose #-------------------------------------------------------------------------- alias sprite_battler_dispose_ehpb dispose def dispose sprite_battler_dispose_ehpb dispose_enemy_gauges end #-------------------------------------------------------------------------- # alias method: update #-------------------------------------------------------------------------- alias sprite_battler_update_ehpb update def update sprite_battler_update_ehpb update_enemy_gauges end #-------------------------------------------------------------------------- # new method: create_enemy_gauges #-------------------------------------------------------------------------- def create_enemy_gauges return if @battler.nil? return if @battler.actor? return unless @battler.enemy.show_gauge @back_gauge_viewport = Enemy_HP_Gauge_Viewport.new(@battler, self, :back) @hp_gauge_viewport = Enemy_HP_Gauge_Viewport.new(@battler, self, :hp) end #-------------------------------------------------------------------------- # new method: dispose_enemy_gauges #-------------------------------------------------------------------------- def dispose_enemy_gauges @back_gauge_viewport.dispose unless @back_gauge_viewport.nil? @hp_gauge_viewport.dispose unless @hp_gauge_viewport.nil? end #-------------------------------------------------------------------------- # new method: update_enemy_gauges #-------------------------------------------------------------------------- def update_enemy_gauges @back_gauge_viewport.update unless @back_gauge_viewport.nil? @hp_gauge_viewport.update unless @hp_gauge_viewport.nil? end #-------------------------------------------------------------------------- # new method: update_enemy_gauge_value #-------------------------------------------------------------------------- def update_enemy_gauge_value @back_gauge_viewport.new_hp_updates unless @back_gauge_viewport.nil? @hp_gauge_viewport.new_hp_updates unless @hp_gauge_viewport.nil? end end # Sprite_Battler #============================================================================== # ■ Game_BattlerBase #============================================================================== class Game_BattlerBase #-------------------------------------------------------------------------- # public instance variables #-------------------------------------------------------------------------- attr_accessor :hidden #-------------------------------------------------------------------------- # alias method: refresh #-------------------------------------------------------------------------- alias game_battlerbase_refresh_ehpb refresh def refresh game_battlerbase_refresh_ehpb return unless SceneManager.scene_is?(Scene_Battle) return if actor? sprite.update_enemy_gauge_value end end # Game_BattlerBase #============================================================================== # ■ Game_Battler #============================================================================== class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # alias method: die #-------------------------------------------------------------------------- alias game_battler_die_ehpb die def die game_battler_die_ehpb return if actor? $game_party.add_defeated_enemy(@enemy_id) end #-------------------------------------------------------------------------- # alias method: hp= #-------------------------------------------------------------------------- alias game_battlerbase_hpequals_ehpb hp= def hp=(value) game_battlerbase_hpequals_ehpb(value) return unless SceneManager.scene_is?(Scene_Battle) return if actor? return if value == 0 sprite.update_enemy_gauge_value end end # Game_Battler #============================================================================== # ■ Game_Party #============================================================================== class Game_Party < Game_Unit #-------------------------------------------------------------------------- # alias method: init_all_items #-------------------------------------------------------------------------- alias game_party_init_all_items_ehpb init_all_items def init_all_items game_party_init_all_items_ehpb @defeated_enemies = [] end #-------------------------------------------------------------------------- # new method: defeated_enemies #-------------------------------------------------------------------------- def defeated_enemies @defeated_enemies = [] if @defeated_enemies.nil? return @defeated_enemies end #-------------------------------------------------------------------------- # new method: add_defeated_enemy #-------------------------------------------------------------------------- def add_defeated_enemy(id) @defeated_enemies = [] if @defeated_enemies.nil? @defeated_enemies.push(id) unless @defeated_enemies.include?(id) end end # Game_Party #============================================================================== # ■ Enemy_HP_Gauge_Viewport #============================================================================== class Enemy_HP_Gauge_Viewport < Viewport #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize(battler, sprite, type) @battler = battler @base_sprite = sprite @type = type dw = YEA::BATTLE::ENEMY_GAUGE_WIDTH dw += 2 if @type == :back @start_width = dw dh = YEA::BATTLE::ENEMY_GAUGE_HEIGHT dh += 2 if @type == :back rect = Rect.new(0, 0, dw, dh) @current_hp = @battler.hp @current_mhp = @battler.mhp @target_gauge_width = target_gauge_width @gauge_rate = 1.0 setup_original_hide_gauge super(rect) self.z = 125 create_gauge_sprites self.visible = false update_position end #-------------------------------------------------------------------------- # dispose #-------------------------------------------------------------------------- def dispose @sprite.bitmap.dispose unless @sprite.bitmap.nil? @sprite.dispose super end #-------------------------------------------------------------------------- # update #-------------------------------------------------------------------------- def update super self.visible = gauge_visible? @sprite.ox += 4 if YEA::BATTLE::ANIMATE_HP_GAUGE update_position update_gauge @visible_counter -= 1 end #-------------------------------------------------------------------------- # setup_original_hide_gauge #-------------------------------------------------------------------------- def setup_original_hide_gauge @original_hide = @battler.enemy.require_death_show_gauge return unless @original_hide if YEA::BATTLE::DEFEAT_ENEMIES_FIRST enemy_id = @battler.enemy_id @original_hide = !$game_party.defeated_enemies.include?(enemy_id) end end #-------------------------------------------------------------------------- # create_gauge_sprites #-------------------------------------------------------------------------- def create_gauge_sprites @sprite = Plane.new(self) dw = self.rect.width * 2 @sprite.bitmap = Bitmap.new(dw, self.rect.height) case @type when :back colour1 = Colour.text_colour(@battler.enemy.back_gauge_colour) colour2 = Colour.text_colour(@battler.enemy.back_gauge_colour) when :hp colour1 = Colour.text_colour(@battler.enemy.hp_gauge_colour1) colour2 = Colour.text_colour(@battler.enemy.hp_gauge_colour2) end dx = 0 dy = 0 dw = self.rect.width dh = self.rect.height @gauge_width = target_gauge_width @sprite.bitmap.gradient_fill_rect(dx, dy, dw, dh, colour1, colour2) @sprite.bitmap.gradient_fill_rect(dw, dy, dw, dh, colour2, colour1) @visible_counter = 0 end #-------------------------------------------------------------------------- # update_visible #-------------------------------------------------------------------------- def gauge_visible? update_original_hide return false if @original_hide return false if case_original_hide? return true if @visible_counter > 0 return true if @gauge_width != @target_gauge_width if SceneManager.scene_is?(Scene_Battle) return false if SceneManager.scene.enemy_window.nil? unless @battler.dead? if SceneManager.scene.enemy_window.active return true if SceneManager.scene.enemy_window.enemy == @battler return true if SceneManager.scene.enemy_window.select_all? return true if highlight_aoe? end end end return false end #-------------------------------------------------------------------------- # highlight_aoe? #-------------------------------------------------------------------------- def highlight_aoe? return false unless $imported["YEA-AreaofEffect"] return false if @battler.enemy? && @battler.hidden return SceneManager.scene.enemy_window.hightlight_aoe?(@battler) end #-------------------------------------------------------------------------- # new_hp_updates #-------------------------------------------------------------------------- def new_hp_updates return if @current_hp == @battler.hp && @current_mhp == @battler.mhp @current_hp = @battler.hp @current_mhp = @battler.mhp return if @gauge_rate == target_gauge_rate @gauge_rate = target_gauge_rate @target_gauge_width = target_gauge_width @visible_counter = 60 end #-------------------------------------------------------------------------- # case_original_hide? #-------------------------------------------------------------------------- def case_original_hide? return false if !@battler.enemy.require_death_show_gauge if YEA::BATTLE::DEFEAT_ENEMIES_FIRST enemy_id = @battler.enemy_id return true unless $game_party.defeated_enemies.include?(enemy_id) end return false end #-------------------------------------------------------------------------- # update_original_hide #-------------------------------------------------------------------------- def update_original_hide return unless @original_hide return if @battler.dead? enemy_id = @battler.enemy_id @original_hide = false if $game_party.defeated_enemies.include?(enemy_id) end #-------------------------------------------------------------------------- # update_position #-------------------------------------------------------------------------- def update_position dx = @battler.screen_x - @start_width / 2 dy = @battler.screen_y self.rect.x = dx self.rect.y = dy dh = self.rect.height + 1 dh += 2 unless @type == :back dy = [@battler.screen_y, Graphics.height - dh - 120].min dy += 1 unless @type == :back self.rect.y = dy end #-------------------------------------------------------------------------- # update_gauge #-------------------------------------------------------------------------- def update_gauge return if @gauge_width == @target_gauge_width rate = 3 @target_gauge_width = target_gauge_width if @gauge_width > @target_gauge_width @gauge_width = [@gauge_width - rate, @target_gauge_width].max elsif @gauge_width < @target_gauge_width @gauge_width = [@gauge_width + rate, @target_gauge_width].min end @visible_counter = @gauge_width == 0 ? 10 : 60 return if @type == :back self.rect.width = @gauge_width end #-------------------------------------------------------------------------- # target_gauge_rate #-------------------------------------------------------------------------- def target_gauge_rate return @current_hp.to_f / @current_mhp.to_f end #-------------------------------------------------------------------------- # target_gauge_width #-------------------------------------------------------------------------- def target_gauge_width return [@current_hp * @start_width / @current_mhp, @start_width].min end end # Enemy_HP_Gauge_Viewport end # $imported["YEA-BattleEngine"] #============================================================================== # # ▼ End of File # #==============================================================================
ruby
MIT
9549551db08e98cfddc46c1165c2807bc87eabd6
2026-01-04T17:52:57.926095Z
false