Scripter's corner : Snippets, Classes, Tips and more

I sure could have used that when I was trying to build my own Tilemap class. That was a loooong time ago, though...I would have made my own, too, if I didn't feel like building the autotile INDEX was so horribly tedious. Nice work, very simple and it seems to have pretty good stability, looking at the amount of error checking.
That's funny, I posted this script because BlueScope was messing around with the Tilemap class XD
I am glad you like, but you can't assume stability from the amount of error checking. I am using an unsafe method to check how many dimensions the table has. I know there are special cases which I should guard against.

I actually made this script over a year ago. I just forgot to post it ._.
I found a little snippet I made some time ago which can help with debugging:
class StandardError < Exception
  def to_s
    b = self.backtrace
    b.delete_at(0)
    return super + "\n\nBacktrace:\n" + b.join("\n")
  end
end
Expand to see the code.


I found it in an unfinished combo system.
Unfinished combo system Show
Here is the back-bone of a combo system I once were working on.
I can't remember why I dropped it, but I release it free for anyone to use any part of it for both non-commercial and commercial purposes.
No guarantee that it works. No guarantees at all. Use at your own risk :x
class Key_Combo
  def initialize
    @timeline = {}
    @running = []
    @actions = []
    @ticks = 0
    @total_ticks = 0
  end
 
  ##
  # Put an action into the timeline
  #
  def put(action, start)
    @timeline[start] = [] if @timeline[start].nil?
    @timeline[start] << action
    @actions << action
    # Update the total ticks if necessary
    total_ticks = start + action.total_ticks
    if total_ticks > @total_ticks
      @total_ticks = total_ticks
    end
  end
 
  ##
  # Resets the timeline and all the actions
  #
  def reset
    @ticks = 0
    @running.clear
    for action in @actions
      action.reset
    end
  end
 
  ##
  # Updates the combo
  #
  # Returns
  # nil - Not completed yet
  # false - The action failed
  # true - The action succeeded
  #
  def update
    # Add new actions
    new_actions = @timeline[@ticks]
    unless new_actions.nil?
      for action in new_actions
        @running << action
      end
    end
    # Check and update the running actions
    for action in @running
      # Update the action
      result = action.update
      # Check if the action still is running
      unless result.nil?
        if result
          # It was successful
          @running.delete(action)
        else
          # It was not successful
          return false
        end
      end
    end
    # Tick
    @ticks += 1
    # Check if all ticks has been used
    if @ticks >= @total_ticks
      # No failures => success
      return true
    end
    return nil
  end
end

class Key_Action
  attr_reader :ticks
  attr_reader :total_ticks
  def reset
    raise NotImplementedError.new(self.class.to_s + ".reset")
  end
  def update
    raise NotImplementedError.new(self.class.to_s + ".update")
  end
end

class Conjunction_Key_Action < Key_Action
  ##
  # Initialization
  # condition - The condition that must be fulfilled
  # *actions - The actions to check if they in conjunction succeed
  #            The first action entered is the first to be executed
  #            The second action entered is the next and so on
  #
  #    action1 ^ action2 ^ action3 ^ ... ^ actionN
  #
  # Note: Automatically succeeds if no actions are entered unless condition is
  #       false
  #
  def initialize(condition, *actions)
    @total_ticks = 0
    @condition = condition
    @actions = []
    for action in actions
      if action.is_a?(Key_Action)
        @actions << action
        @total_ticks += action.total_ticks
      else
        raise IllegalArgumentError.new("On of the arguments in " + self.class.to_s +
                " is not a Key_Action, it is a " + condition.class.to_s)
      end
    end
    @index = 0
    @ticks = 0
  end
 
  ##
  # Reset the action so it can be used again
  #
  def reset
    @index = 0
    @ticks = 0
    for action in @actions
      action.reset
    end
  end
 
  ##
  # Returns
  # nil - Not completed yet
  # false - The action failed
  # true - The action succeeded
  #
  def update
    # Check if the condition is fulfilled
    unless @condition.checkCondition
      return false
    end
    # Check if the correct keys have been triggered
    action = @actions[@index]
    if action.nil?
      return true
    end
    # Get the result from the action update
    @ticks += 1
    result = action.update
    # If the action has failed
    if result == false
      return false
    # If the action has succeeded
    elsif result == true
      # Move to next action
      @index += 1
      # If no more actions
      if @actions.size <= @index
        return true
      end
    end
    return nil
  end
end

class Disjunction_Key_Action < Key_Action
  ##
  # Initialization
  # condition - The condition that must be fulfilled
  # *actions - The actions to check if they in disjunction succeed
  #            The first action entered is the first to be executed
  #            The second action entered is the next and so on
  #
  #    action1 v action2 v action3 v ... v actionN
  #
  # Note: Automatically fails if no actions are entered.
  #
  def initialize(condition, *actions)
    @total_ticks = 0
    @condition = condition
    @actions = []
    for action in actions
      if action.is_a?(Key_Action)
        @actions << action
        @total_ticks += action.total_ticks
      else
        raise IllegalArgumentError.new("On of the arguments in " + self.class.to_s +
                " is not a Key_Action, it is a " + condition.class.to_s)
      end
    end
    @index = 0
    @ticks = 0
  end
 
  ##
  # Reset the action so it can be used again
  #
  def reset
    @index = 0
    @ticks = 0
    for action in @actions
      action.reset
    end
  end
 
  ##
  # Returns
  # nil - Not completed yet
  # false - The action failed
  # true - The action succeeded
  #
  def update
    # Check if the condition is fulfilled
    unless @condition.checkCondition
      return false
    end
    # Check if the correct keys have been triggered
    action = @actions[@index]
    if action.nil?
      return false
    end
    # Get the result from the action update
    @ticks += 1
    result = action.update
    # If the action has failed
    if result == false
      # Move to next action
      @index += 1
      # If no more actions
      if @actions.size <= @index
        return false
      end
    # If the action has succeeded
    elsif result == true
      return true
    end
    return nil
  end
end

class Trigger_Key_Action < Key_Action
  ##
  # Initialization
  # key_press - The keys to press
  # condition - The condition that must be fulfilled
  # ticks - The number of ticks to press the key
  #
  def initialize(key_press, condition, ticks)
    @key_press = key_press
    @condition = condition
    @total_ticks = ticks
    @ticks = 0
  end
 
  ##
  # Reset the action so it can be used again
  #
  def reset
    @ticks = @total_ticks
  end
 
  ##
  # Returns
  # nil - Not completed yet
  # false - The action failed
  # true - The action succeeded
  #
  def update
    # Check if the condition is fulfilled
    unless @condition.checkCondition
      return false
    end
    # Check if the correct keys have been triggered
    if @key_press.trigger?
      return true
    end
    # Removes the amount of ticks for the action
    @ticks += 1
    # Check if all ticks has been used
    if @ticks >= @total_ticks
      return false
    end
    return nil
  end
end

class Release_Key_Action < Key_Action
  ##
  # Initialization
  # key_press - The keys to press
  # condition - The condition that must be fulfilled
  # ticks - The number of ticks to hold the key pressed
  # delta - The amounts of ticks before and after the right tick which are
  #         considered as being timely release
  #
  def initialize(key_press, condition, ticks, delta)
    @key_press = key_press
    @condition = condition
    @total_ticks = ticks + delta
    @ticks = 0
    @delta = delta
  end
 
  ##
  # Reset the action so it can be used again
  #
  def reset
    @ticks = 0
  end
 
  ##
  # Returns
  # nil - Not completed yet
  # false - The action failed
  # true - The action succeeded
  #
  def update
    # Check if the condition is fulfilled
    unless @condition.checkCondition
      return false
    end
    # Check if the correct keys is still pressed
    unless @key_press.press?
      if @total_ticks - @delta * 2 <= @ticks && @total_ticks >= @ticks
        return true
      else
        return false
      end
    end
    # Removes the amount of ticks for the action
    @ticks += 1
    # Check if all ticks has been used
    if @ticks >= @total_ticks
      return false
    end
    return nil
  end
end

##
# Manages a serie of keys and whether they are pressed, triggered and repeated
# Basically the same as the Input module except that it can check an arbitrary
# number of keys instead of 1 key
#
class Key_Press
  @keys = []
  ##
  # Initialization
  # *args - integer values of the keys to press. (Refer to Input constants)
  def initialize(*args)
    @keys = args.flatten.compact
  end
  ##
  # Check if all keys are triggered
  #
  def trigger?
    for key in @keys
      unless Input.trigger?(key)
        return false
      end
    end
    return true
  end
  ##
  # Check if all keys are pressed
  #
  def press?
    for key in @keys
      unless Input.press?(key)
        return false
      end
    end
    return true
  end
  ##
  # Check if all keys are repeated
  #
  def repeat?
    for key in @keys
      unless Input.repeat?(key)
        return false
      end
    end
    return true
  end
end

class IllegalArgumentError < StandardError
end

class StandardError < Exception
  def to_s
    b =  self.backtrace
    b.delete_at(0)
    return super + "\n\nBacktrace:\n" + b.join("\n")
  end
end


class Condition
  def checkCondition(*args)
    raise NotImplementedError.new(self.class.to_s + ".checkCondition")
  end
end

class ConjunctionCondition < Condition
  def initialize(*conditions)
    @conditions = []
    for condition in conditions
      if condition.is_a?(Condition)
        @conditions << condition
      else
        raise IllegalArgumentError.new("On of the arguments in " + self.class.to_s +
                " is not a Condition, it is a " + condition.class.to_s)
      end
    end
  end
  def checkCondition(*args)
    for condition in @conditions
      return false unless condition.checkCondition(*args)
    end
    return true
  end
end

class DisjunctionCondition < Condition
  def initialize(*conditions)
    @conditions = []
    for condition in conditions
      if condition.is_a?(Condition)
        @conditions << condition
      else
        raise IllegalArgumentError.new("On of the arguments in " + self.class.to_s +
                " is not a Condition, it is a " + condition.class.to_s)
      end
    end
  end
  def checkCondition(*args)
    for condition in @conditions
      return true if condition.checkCondition(*args)
    end
    return false
  end
end

class NotCondition < Condition
  def initialize(condition)
    if condition.is_a?(Condition)
      @condition = condition
    else
      raise IllegalArgumentError.new("Given argument in " + self.class.to_s +
                " is not a condition, it is a " + condition.class.to_s)
    end
  end
  def checkCondition(*args)
    return condition.checkCondition(*args)
  end
end

class TrueCondition < Condition
  def checkCondition(*args)
    return true
  end
end
Expand to see the code.


An example usage:
class
  ##
  # Press A within the first 20 frames
  # Press L + R between frame 20 inclusive and frame 40 exclusive
  # Press C between frame 40 inclusive and frame 60 exclusive
  # Release C between frame 70 inclusive and frame 90 exclusive
  # Press A + B between frame 90 inclusive and frame 90 exclusive
  #
  def self.test_combo_start
    kp_ab = Key_Press.new(Input::A, Input::B)
    kp_a = Key_Press.new(Input::A)
    kp_c = Key_Press.new(Input::C)
    kp_lr = Key_Press.new(Input::L, Input::R)
    true_condition = TrueCondition.new
    tka_a = Trigger_Key_Action.new(kp_a, true_condition, 20)
    tka_lr = Trigger_Key_Action.new(kp_lr, true_condition, 20)
    tka_c = Trigger_Key_Action.new(kp_c, true_condition, 20)
    rka_c = Release_Key_Action.new(kp_c, true_condition, 20, 10)
    tka_ab = Trigger_Key_Action.new(kp_ab, true_condition, 20)
    combo = Key_Combo.new
    combo.put(tka_a, 0)
    combo.put(tka_lr, 20)
    combo.put(tka_c, 40)
    combo.put(rka_c, 60)
    combo.put(tka_ab, 90)
    @@combo = combo
    @@counter = 0
  end
 
  def self.key_combo
    res = @@combo.update
    @@counter += 1
    if res.nil?
      return false
    end
    p res, @@counter
    return true
  end
end
Expand to see the code.


*hugs*
- Zeriab
Here is an update to the StandardError extension:
class StandardError < Exception
  def to_s
    b = self.backtrace[1..-1]
    k = self.backtrace[0]
    message = super + "\n\nBacktrace:\n" + b.join("\n")
    if $DEBUG
      $DEBUG = false
      write_to_log(message, k)
    end
    return message
  end
  def to_log(message, k)
    k.gsub(/Section(\d*):(\d*)/) {}
    string = "Script '#{$RGSS_SCRIPTS[$1.to_i][1]}' line #{$2.to_i}: #{self.class} occured"
    return string + "\n\n" + message
  end
  def write_to_log(message, k)
    file = File.open('ErrorLog.log', File::CREAT|File::APPEND|File::WRONLY)
    file.print to_log(message, k)
    file.print "\n==============================\n"
    file.close
  end
end
Expand to see the code.


This time it appends the error to an error log if $DEBUG is true. (I.e. test run)
I like this approach since the editor appears to go to the right place like normally ^_^

*hugs*
- Zeriab
I like it. I think it would also be nice to add simple error checking to Scene_Base, and with that error log you've implemented it even makes sense to try and keep going even when you reach an error.

I'm just thinking it should be something simple like this:

def Exception.fatal?
  return true
end

def StandardError.fatal?
  return false
end

class Scene_Base
  def main_loop
    [...]
  rescue
    raise $! if $!.fatal?
    p $!.to_s
  end
end
Expand to see the code.


This way, errors don't destroy the program, and it's even possible to make certain errors fatal so they DO destroy the program. Just an addition to your debugging tool, I think I'll put these into my scripting bay to help debugging and make it less apt to quit.

EDIT: I've got it working, doing exactly what I want. It's a bit more complicated, but it points the script editor to the right place like the original intent. It prints all errors to the screen, but ignores them as long as an error didn't happen the last frame (indicating that the error's going to happen every frame).

class Object
  #--------------------------------------------------------------------------
  # * Advanced error checking for methods - provide method as a string for eval
  #--------------------------------------------------------------------------
  def error_wrapper(symbol)
    # Create the record of whether there's been an error last time checked
    if @_error == nil
      @_error = {}
      @_error.default = false
    end
    # If there was an error last time we ran this method
    if @_error[symbol]
      # Run the method and, after getting no errors, reset error check
      send symbol
      @_error[symbol] = false
    else # If there was no error last time we ran this method
      begin
        send symbol
      rescue
        # Catch errors and provide feedback; set checker for each-frame errors
        print $!.full_message if $DEBUG or $!.fatal?
        $!.write_to_log
        exit(1) if $!.fatal?
        @_error[symbol] = true
      end
    end
  end
end
Expand to see the code.


This uses some modifications to your original work:

class Exception
  # prevents infinite loops by aliasing the original message
  alias to_string :to_s
  #--------------------------------------------------------------------------
  # * Only called from internal error checking; writes log and adds backtrace
  #--------------------------------------------------------------------------
  def to_s
    write_to_log # Note that the log calls :full_message
    return message_with_backtrace
  end
  #--------------------------------------------------------------------------
  # * Returns the error message with accompanying backtrace
  #--------------------------------------------------------------------------
  def message_with_backtrace
    return to_string + backtrace_string(1...backtrace.length)
  end
  #--------------------------------------------------------------------------
  # * Returns what raising an error displays
  #--------------------------------------------------------------------------
  def full_message
    # Finds script and line number
    error = "Script " + backtrace_line(0) + ": #{self.class} occured.\n\n"
    return error + self.message_with_backtrace
  end
  #--------------------------------------------------------------------------
  # * Generate the backtrace string from a range of its values
  #--------------------------------------------------------------------------
  def backtrace_string(range = 0...backtrace.length)
    output = "\n\nBacktrace:\n"
    for i in range
      output += backtrace_line(i, true) + "\n"
    end
    return output
  end
  #--------------------------------------------------------------------------
  # * Generate a string from an individual item in the backtrace
  #--------------------------------------------------------------------------
  def backtrace_line(i, show_method = false)
    method = backtrace[i].gsub(/Section(\d*):(\d*)/) {}
    output = "'%-20s' line %d" % [$RGSS_SCRIPTS[$1.to_i][1], $2]
    output += method.sub(':', ' ') if show_method
    return output
  end
  #--------------------------------------------------------------------------
  # * Write the error to the log file
  #--------------------------------------------------------------------------
  def write_to_log
    return if @written # Only write log once
    file = File.open('ErrorLog.log', File::CREAT|File::APPEND|File::WRONLY)
    file.print full_message
    file.print "\n========================================================\n"
    file.close
    @written = true
  end
  #--------------------------------------------------------------------------
  # * Is this error fatal? (redefine for other exceptions)
  #--------------------------------------------------------------------------
  def fatal?
    return true
  end
end

class StandardError
  def fatal? ; return false ; end
end
Expand to see the code.


All that needs to be done to catch simple errors that don't occur every frame is to replace a call to main_loop with a call to error_wrapper(:main_loop) (within objects)
That is an good idea and I like your execution meustrus ^_^

I would consider only printing non-fatal errors out on the screen if $DEBUG == true.
It really depends on how you want to test the game since a silent ONLY_WRITE_TO_LOG mode gives a better feeling of how the game works. If the error message is displayed though you know when exactly it occurs. Something to consider.

Nice work anyway ^^
I like it, I'll edit the post to include that...where it says "print $!.full_message" it's changed to "print $!.full_message if $DEBUG or $!.fatal?"
This might be helpful even though it's kinda simple, a method that finds the angle from 0,0 to x,y and returns it (in degrees)

  1. module Math
  2.   def self.angle(x,y)
  3.      deg = (Math.asin(y/((x**2 + y**2)**(0.5))))
  4.      # Convert to degrees
  5.      deg = ((deg)/(2 * Math::PI)) * 360
  6.      # Round to 4 decimals
  7.      deg = ((deg * 1000).ceil)/1000
  8.      deg = 180 - deg if x < 0
  9.      deg = 360 + deg if x >= 0 and y < 0
  10.      return deg
  11.   end
  12. end
Expand to see the code.
Get the X first / last items of an array !

Some people might have been used to : my_array[0,3] for example to get the first 3 items...
or my_array[-X,X] to get the last X items of an array...

Well there is actually something much simpler :

my_array.first(X)
and
my_array.last(X)

Will return a new array containing the first/last X items ^^, if you don't specify X, it'll simplify return the 1st or last item directly, not as an array.
Here's something I would have made earlier if I knew how. @_@
It's a C dll that (very quickly) recolors a bitmap.
http://www.bwdyeti.com/bitmap.rar

It recolors all instances of a given color with another given color. Use it with:
  1. class Bitmap
  2.   def recolor_c(color_to,color_from)
  3.      raise RGSSError.new("Disposed bitmap") if disposed?
  4.      func=Win32API.new("bitmap.dll","Bitmap_Recolor","lll","")
  5.      func.call(self.__id__,toColor(color_to),toColor(color_from))
  6.   end
  7.  
  8.   def toColor(c)
  9.      r=c.red.to_i
  10.      g=c.green.to_i
  11.      b=c.blue.to_i
  12.      a=c.alpha.to_i
  13.     return b|(g<<8)|(r<<16)|(a<<24)
  14.   end
  15. end
Expand to see the code.

  1. bitmap.recolor_c(color1, color2)
Expand to see the code.


It can recolor a 640x480 bitmap every frame at 60fps while similar Ruby code using get_pixel/set_pixel would fall to 1fps .-.

I might do different things with it like recoloring by hue (something Seph suggested when I asked about recoloring in the past), but this might be helpful to someone else now.

Thanks goes to poccil for the the basis I worked from with his bitmap effects in C (viewtopic.php?f=11&t=39324)
Very nice! Would it be possible to see the C source?
I guess, since I can hardly go "nuuuu they be stealin mah code" when I just edited poccil's.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <windows.h>
  5. #include <math.h>
  6. #define EXPORTDLL __declspec(dllexport) //__stdcall
  7.  
  8. ////////////////////////////////////////////////////////
  9.  
  10. typedef struct{
  11.  DWORD flags;
  12.  DWORD klass;
  13.  void (*dmark)(void*);
  14.  void (*dfree)(void*);
  15.  double *data;//red is index 1, green is index 2, blue 3, alpha 4
  16. } RGSSCOLOR;
  17.  
  18. typedef struct{
  19.  DWORD unk1;
  20.  DWORD unk2;
  21.  BITMAPINFOHEADER *infoheader;
  22.  RGBQUAD *firstRow;
  23.  RGBQUAD *lastRow;
  24. } RGSSBMINFO;
  25.  
  26. typedef struct{
  27.  DWORD unk1;
  28.  DWORD unk2;
  29.  RGSSBMINFO *bminfo;
  30. } BITMAPSTRUCT;
  31.  
  32. typedef struct{
  33.  DWORD flags;
  34.  DWORD klass;
  35.  void (*dmark)(void*);
  36.  void (*dfree)(void*);
  37.  BITMAPSTRUCT *bm;
  38. } RGSSBITMAP;
  39.  
  40. #define ASSERT(x)   if(!x){DebugOut("Failed: %s: %d",#x,__LINE__);}
  41.  
  42. ////////////////////////////////////////////////////////
  43.  
  44. BOOL EXPORTDLL Bitmap_Recolor(
  45.            long object, DWORD color1, DWORD color2){
  46.      DWORD tmp=0;
  47.      RGSSBMINFO *bitmap=((RGSSBITMAP*)(object<<1))->bm->bminfo;
  48.      DWORD rowsize;
  49.      DWORD width,height;
  50.      LPBYTE row;
  51.      byte blend[4];
  52.      long xStart=0;
  53.      long yStart=0;
  54.      long x, y;
  55.      int r1,g1,b1,a1; //Recolor to colors
  56.      int r2,g2,b2,a2; //Recolor from colors
  57.      int r3,g3,b3,a3; //Color of current pixel
  58.      r1 = GetRValue(color1); g1 = GetGValue(color1); b1 = GetBValue(color1); a1 = color1>>24;
  59.      r2 = GetRValue(color2); g2 = GetGValue(color2); b2 = GetBValue(color2); a2 = color2>>24;
  60.      if(!bitmap)return FALSE;
  61.      width=bitmap->infoheader->biWidth;
  62.      height=bitmap->infoheader->biHeight;
  63.      rowsize=width*4;
  64.      if(width==xStart||height==yStart)return TRUE;
  65.      row=bitmap->firstRow-yStart*rowsize+xStart*4;
  66.      for (y=yStart; y<height; y++)
  67.      {
  68.            LPBYTE thisrow=row;
  69.            for (x=xStart; x<width; x++)
  70.            {
  71.                  r3=thisrow[0];
  72.                  g3=thisrow[1];
  73.                  b3=thisrow[2];
  74.                  a3=thisrow[3];
  75.                  if ((r2 == r3) && (g2 == g3) && (b2 == b3))// && (a2 == a3))
  76.                  {
  77.                        thisrow[0]=r1;
  78.                        thisrow[1]=g1;
  79.                        thisrow[2]=b1;
  80.                        thisrow[3]=a1;
  81.                  }
  82.                  thisrow+=4;
  83.            }
  84.            row-=rowsize;
  85.      }
  86.      return TRUE;
  87. }
Expand to see the code.


Also I messed up the original upload, I forgot to un-comment some lines I had removed for testing in the dll and got a few numbers backwards on the stuff in the Bitmap class. It's fixed now though.
You totally just stole BlueScope's thunder there, what with the Bitmap Recoloring script he posted earlier.
Oh whoops, I didn't mean to. I don't look at the release board much, I just stay in script support .-.
Well, his script does something different, and then uses get_pixel and set_pixel to set the colors. That's actually the best type of place for using this dll/script since it's just a glorified, faster get/set.
Just when I added alpha transparency support to mine ^^ But yeah, it appears to be a more efficient way just telling from the code, but I'll stay with my version for own uses nevertheless... especially since I created it for icon remapping XD Also, it doesn't really do the same thing, as mine's layouted to work with palettes, while yours does individual colors.

You should know I link the above post in my thread, so please let me know if you don't want that, I'll take it out then.

Keep up the good work!
Along with the update of my Database Flag Reader script, I'll post this little snippet in here for string conversion into integers, floats, boolean outputs, arrays, hashes or just nil.

  1.  def self.decrypt_string(value)
  2.     if value.to_i != 0 or value == '0'
  3.       # integer and float
  4.       value.include?('.') ? result = value.to_f : result = value.to_i
  5.     elsif value == 'true'
  6.       # boolean true
  7.       result = true
  8.     elsif value == 'false'
  9.       # boolean false
  10.       result = false
  11.     elsif value.include?('[') and value.include?(']')
  12.       # array
  13.       result = []
  14.       value.delete!('[ ]')
  15.       array = value.split(',')
  16.       for i in 0...array.size
  17.         result[i] = decrypt_string(array[i])
  18.       end
  19.     elsif value.include?('{') and value.include?('}')
  20.       # hash
  21.       result = {}
  22.       value.delete!('{ }')
  23.       hash = value.split(',')
  24.       for i in 0...hash.size
  25.         temp = hash[i].split('=>')
  26.         result[temp[0]] = decrypt_string(temp[1])
  27.       end
  28.     elsif value == 'nil'
  29.       # nil
  30.       result = nil
  31.     else
  32.       # string
  33.       result = value
  34.     end
  35.     return result
  36.   end
Expand to see the code.
Nice, BlueScope. I suppose the only strangety with that is the uncertain data type which results, but that's the point isn't it? And I don't care what Firefox says, "strangety" is definitely a word!

I've got two modules that some of you might find interesting; they both deal with Win32API. The first is a Settings module, which reads the game.ini file and can read and write entries to it. It keeps a cache of the values as it reads them, and writes immediately whenever a setting is changed. The cache can be easily cleared as well:

  1. #===============================================================================
  2. # ** Settings
  3. #-------------------------------------------------------------------------------
  4. #      References game.ini and caches and returns the relevant settings.
  5. #===============================================================================
  6.  
  7. module Settings
  8.   ReadINI = Win32API.new('kernel32', 'GetPrivateProfileString', 'PPPPLP', 'L')
  9.   WriteINI = Win32API.new('kernel32', 'WritePrivateProfileString', 'PPPP', 'L')
  10.   FileName = ".\\game.ini"
  11.   @data = {}
  12.   #-----------------------------------------------------------------------------
  13.   # * Find cached value
  14.   #-----------------------------------------------------------------------------
  15.   def self.[](key)
  16.      unless @data.has_key?(key)
  17.         @data[key] = "\0" * 256
  18.         ReadINI.call("Game", key, "", @data[key], 256, FileName)
  19.         @data[key].delete!("\0")
  20.      end
  21.      return @data[key]
  22.   end
  23.   #-----------------------------------------------------------------------------
  24.   # * Set cached value and write to the settings file
  25.   #-----------------------------------------------------------------------------
  26.   def self.[]=(key, value)
  27.      @data[key] = value
  28.      WriteINI.call("Game", key, value, FileName)
  29.   end
  30.   #-----------------------------------------------------------------------------
  31.   # * Clears the cache so that external changes to the settings file can be read
  32.   #-----------------------------------------------------------------------------
  33.   def self.clear
  34.      @data.clear
  35.   end
  36. end
Expand to see the code.


The second is a wrapper module for user32.dll GetSystemMetrics functions. It acts just like an initialized Win32API object (with its :call method) but I've mapped out all of the functions (up to 81). You can call it by something as simple as GSM.call(GSM::CXSCREEN) (that returns the width portion of your current screen resolution):

  1. #===============================================================================
  2. # ** GSM
  3. #-------------------------------------------------------------------------------
  4. #      Wrapper for GetSystemMetrics which defines the constants it can return
  5. #      For more complete descriptions, see Microsoft's website:
  6. #      http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx
  7. #===============================================================================
  8.  
  9. module GSM
  10.   CXSCREEN         = 0   # Width of the current master screen resolution
  11.   CYSCREEN         = 1   # Height of the current master screen resolution
  12.  
  13.   CXVSCROLL       = 2   # Width of a vertical scroll bar
  14.   CYHSCROLL       = 3   # Height of a horizontal scroll bar
  15.  
  16.   CYCAPTION       = 4   # Height of a caption area
  17.  
  18.   CXBORDER         = 5   # Width of a window border
  19.   CYBORDER         = 6   # Height of a window border
  20.  
  21.   CXDLGFRAME      = 7
  22.   CXFIXEDFRAME   = 7 # Width of non-resizable captioned window frame
  23.   CYDLGFRAME      = 8
  24.   CYFIXEDFRAME   = 8 # Height of non-resizable captioned window frame
  25.  
  26.   CYVTHUMB         = 9   # Height of a thumb button on vertical scrollbars
  27.   CXHTHUMB         = 10 # Width of a thumb button on horizontal scrollbars
  28.  
  29.   CXICON            = 11 # Default width of an icon
  30.   CYICON            = 12 # Default height of an icon
  31.  
  32.   CXCURSOR         = 13 # Width of a cursor
  33.   CYCURSOR         = 14 # Height of a cursor
  34.  
  35.   CYMENU            = 15 # Height of a single-line menu bar
  36.  
  37.   CXFULLSCREEN   = 16 # Width of client rect for a full-screen window
  38.   CYFULLSCREEN   = 17 # Height of client rect for a full-screen window
  39.  
  40.   CYKANJIWINDOW = 18 # Height of kanji window at bottom of screen, if there
  41.  
  42.   MOUSEPRESENT   = 19 # Non-zero if mouse is present; 0 if not
  43.  
  44.   CYVSCROLL       = 20 # Height of the arrow bitmap on vertical scrollbars
  45.   CXHSCROLL       = 21 # Width of the arrow bitmap on horizontal scrollbars
  46.  
  47.   DEBUG             = 22 # Non-zero if debug User.exe is installed; 0 if not
  48.   SWAPBUTTON      = 23 # Non-zero if mouse button values are swapped
  49.  
  50.   CXMIN             = 28 # Minimum width of a window
  51.   CYMIN             = 29 # Minimum height of a window
  52.  
  53.   CXSIZE            = 30 # Width of a button in a window caption or title bar
  54.   CYSIZE            = 31 # Height of a button in a window caption or title bar
  55.  
  56.   CXFRAME          = 32
  57.   CXSIZEFRAME    = 32 # Width of the sizing border around a resizable window
  58.   CYFRAME          = 33
  59.   CYSIZEFRAME    = 33 # Height of the sizing border around a resizable window
  60.  
  61.   CXMINTRACK      = 34 # Minimum "tracking" width of a window
  62.   CYMINTRACK      = 35 # Minimum "tracking" height of a window
  63.  
  64.   CXDOUBLECLK    = 36 # Width of rect which second click must be in for double
  65.   CYDOUBLECLK    = 37 # Height of rect which second click must be in for double
  66.  
  67.   CXICONSPACING = 38 # Width of a grid cell for items in large icon view
  68.   CYICONSPACING = 39 # Height of a grid cell for items in large icon view
  69.  
  70.   MENUDROPALIGNMENT = 40 # 0 if drop-down menus are left-aligned...
  71.  
  72.   PENWINDOWS      = 41 # Non-zero if Microsoft Windows for Pen computing
  73.                                #   extensions are installed; 0 if not
  74.  
  75.   DBCSENABLED    = 42 # Non-zero if user32.dll supports DBCS; 0 if not
  76.  
  77.   CMOUSEBUTTONS = 43 # Number of available mouse buttons, or 0 for no mouse
  78.  
  79.   SECURE            = 44 # Always returns 0
  80.  
  81.   CXEDGE            = 45 # Width of a 3-D style border
  82.   CYEDGE            = 46 # Height of a 3-D style border
  83.  
  84.   CXMINSPACING   = 47 # Width of a grid cell for minimized windows
  85.   CYMINSPACING   = 48 # Height of a grid cell for minimized windows
  86.  
  87.   CXSMICON         = 49 # Recommended width of a small icon
  88.   CYSMICON         = 50 # Recommended height of a small icon
  89.  
  90.   CYSMCAPTION    = 51 # Height of a small caption
  91.   CXSMSIZE         = 52 # Width of small caption buttons
  92.   CYSMSIZE         = 53 # Height of small caption buttons
  93.   CXMENUSIZE      = 54 # Width of menu bar buttons
  94.   CYMENUSIZE      = 55 # Height of menu bar buttons
  95.  
  96.   ARRANGE          = 56 # Flags that specify how system arranges minimized windows
  97.   CXMINIMIZED    = 57 # Width of a minimized window
  98.   CYMINIMIZED    = 58 # Height of a minimized window
  99.  
  100.   CXMAXTRACK      = 59 # Default maximum width of resizable windows
  101.   CYMAXTRACK      = 60 # Default maximum height of resizable windows
  102.   CXMAXIMIZED    = 61 # Default width of maximized top-level window
  103.   CYMAXIMIZED    = 62 # Default height of maximized top-level window
  104.  
  105.   NETWORK          = 63 # The least significant bit is set if a network is
  106.                                #   present; otherwise, it is cleared
  107.  
  108.   CLEANBOOT       = 67 # System boot type; 0:Normal, 1:Safe, 2:Safe w/networking
  109.  
  110.   CXDRAG            = 68
  111.   CYDRAG            = 69 # Number of pixels mouse can move before initiating drag
  112.  
  113.   SHOWSOUNDS      = 70 # Non-zero if user requires visible output; 0 if not
  114.  
  115.   CXMENUCHECK    = 71 # Width of the default menu check-mark bitmap
  116.   CYMENUCHECK    = 72 # Height of the default menu check-mark bitmap
  117.  
  118.   SLOWMACHINE    = 73 # Non-zero if system has a slow processor; 0 if not
  119.                                #   No, seriously, that's what Microsoft said!
  120.  
  121.   MIDEASTENABLED = 74 # Non-zero if system can use Hebrew, Arabic languages
  122.  
  123.   MOUSEWHEELPRESENT = 75 # Nonzero mouse has vertical scroll wheel; 0 if not
  124.  
  125.   XVIRTUALSCREEN      = 76 # Coordinates of the left side of the virtual screen
  126.   YVIRTUALSCREEN      = 77 # Coordinates of the top of the virtual screen
  127.   CXVIRTUALSCREEN    = 78 # Virtual width of all screens put together
  128.   CYVIRTUALSCREEN    = 79 # Virtual height of all screen put together
  129.   CMONITORS             = 80 # Numbers of display monitors on a desktop
  130.   SAMEDISPLAYFORMAT = 81 # Non-zero if all screen use same color depth...
  131.  
  132.   # The actual API call
  133.   @api = Win32API.new('user32', 'GetSystemMetrics', 'I', 'I')
  134.   def self.call(i)
  135.      return @api.call(i)
  136.   end
  137. end
Expand to see the code.


If anything in there is cryptic, don't blame me (maybe some of them are my fault for trying to shorten the description to fit on one line). Microsoft's descriptions are extremely specific to the point of technical gibberish.

Oh, heh, I'd check and see what Microsoft thinks about your processor:
  1. print GSM.call(GSM::SLOWMACHINE).to_s # Non-zero if system has a slow processor; 0 if not
  2.                                                         #   No, seriously, that's what Microsoft said!
Expand to see the code.
No problem BlueScope, I intended it to be used by anyone needing it. Get_pixel/set_pixel is useful but just too slow. :|

I came up with a couple new bitmap editing methods.
One takes an array of arrays of x-y locations (like [[0,0], [2,5], [8,3]]) and then changes all pixels in the bitmap at those locations to the given color.
The other... does kind of an image mask thing. Not sure what it's called exactly. Basically it takes a different bitmap as an argument, then modifies the original to be the same shape as the given one. For example, you could take an image larger than any battler you expect to encounter and put some kinda of effect in it, then have it conform to the shape of the battler it's currently displayed on top of. You could create something similar to the Pokemon stat buff/debuff effects with it.
(EDIT: Thought of another idea for it, you could create a bitmap, fill it with something like Color.new(40,40,40,192), and then fit it to a character and you have a shadow :o Just y scale its sprite a bit and maybe flip it upside down, then make it follow the character around.)

There's a few restrictions so far, the set array one is kinda slow if you use a large array because setting up the array in Ruby is slow, and the mask one needs some advanced stuff added to it (currently it always starts in the upper left and just leaves anything outside the size of the bitmap providing the shape)

The link to the dll:
http://www.bwdyeti.com/bitmap.rar

And the code to call it:
  1. class Bitmap
  2.   def recolor_c(color_to,color_from)
  3.      raise RGSSError.new("Disposed bitmap") if disposed?
  4.      func=Win32API.new("bitmap.dll","Bitmap_Recolor","lll","")
  5.      func.call(self.__id__,toColor(color_to),toColor(color_from))
  6.   end
  7.  
  8.   def set_pixel_array_c(ary, color)
  9.      raise RGSSError.new("Disposed bitmap") if disposed?
  10.      return if ary.length == 0
  11.      str = ary[0][0].to_s + ',' + ary[0][1].to_s
  12.      for i in 1...ary.length
  13.         str.concat('|' + ary[i][0].to_s + ',' + ary[i][1].to_s)
  14.      end
  15.      func = Win32API.new("bitmap.dll", "Set_Pixel_Array", "llpn", "")
  16.      func.call(self.__id__, toColor(color), str, ary.length)
  17.   end
  18.  
  19.   def fit_to_bitmap_c(other_bitmap)
  20.      raise RGSSError.new("Disposed bitmap") if disposed?
  21.      raise RGSSError.new("Disposed bitmap") if other_bitmap.disposed?
  22.      func=Win32API.new("bitmap.dll","Fit_To_Bitmap","ll","")
  23.      func.call(self.__id__, other_bitmap.__id__)
  24.   end
  25.  
  26.   def toColor(c)
  27.      r=c.red.to_i
  28.      g=c.green.to_i
  29.      b=c.blue.to_i
  30.      a=c.alpha.to_i
  31.      return b|(g<<8)|(r<<16)|(a<<24)
  32.   end
  33. end
Expand to see the code.


Feel free to mention if anything doesn't seem to work right, I'm new to releasing code for others to use so I might not check things as thoroughly as I should before posting.

If I make any more methods like this I'll probably make a topic for it, since it's not really snippets anymore .-.
Don't know if I ever posted this, but it's a default value for Enumerable classes. I just added support for Procs, which allow default value to be reliant on the referenced index or hash key.

  1. #===============================================================================
  2. # ** Enumerable
  3. #-------------------------------------------------------------------------------
  4. #    Adds default values to Enumerable classes
  5. #===============================================================================
  6.  
  7. module Enumerable
  8.   attr_writer   :default
  9.   def default(key = nil)
  10.     return (key == nil or !@default.is_a?(Proc)) ? @default : @default.call(key)
  11.   end
  12. end
  13.  
  14. class Array
  15.   #-----------------------------------------------------------------------------
  16.   # * Adds default values, which replaces nil for all array values
  17.   #-----------------------------------------------------------------------------
  18.   alias old_get_value :[]
  19.   def [](index)
  20.     return default(index) if old_get_value(index).nil?
  21.     return old_get_value(index)
  22.   end
  23. end
  24.  
  25. class Hash
  26.   #-----------------------------------------------------------------------------
  27.   # * Adds default values, which replaces nil for all array values
  28.   #-----------------------------------------------------------------------------
  29.   alias old_get_value :[]
  30.   def [](key)
  31.     return default(key) unless has_key?(key)
  32.     return old_get_value(key)
  33.   end
  34. end
Expand to see the code.


All you have to do is call an array, $ar = [], and say $ar.default = 5 or whatever. Then, when you call $ar[1] it will return 5, even though that value wasn't defined. You can use Procs, too. If you say $ar.default = Proc.new {|index| index - 1} and you call $ar[1] it will return 0, $ar[7] will return 6...it could even be a simple Array wrapper for the Proc class if you never assign any values to the array.
With following snippet you can use Kernel#puts and the console for easier debugging because you can read the output while testing/playing the game and you don't have toclose the annoying MessageBox.
  1. Win32API.new("kernel32", "AllocConsole", "V", "L").call
  2. $stdout.reopen("CONOUT$")
  3.  
  4. # example usage:
  5. puts (6 + rand(9) / 7) & 0xFC
  6.  
  7. # what is debugging without tracing?
  8. trace_var(:$scene){|v| puts "Current scene: #{v}"}
Expand to see the code.


Returns current line:
  1. __LINE__
Expand to see the code.


Current (script) section name:
  1. $RGSS_SCRIPTS.at( __FILE__.sub(/Section/, '').to_i ).at(1)
Expand to see the code.


Fix for Kernel#caller:
  1. def _caller(start = 1)
  2.   stack = caller(start)
  3.   stack.each{|e| e.gsub!(/Section(\d+)/){$RGSS_SCRIPTS.at($1.to_i).at(1)}}
  4.   stack
  5. end
Expand to see the code.


How to remove constants or classes:
  1. p Object.constants.include? "RPG"   # => true
  2.  
  3. Object.send :remove_const, :RPG
  4.  
  5. p Object.constants.include? "RPG"   # => false
Expand to see the code.



EDIT:

Get width and height of a PNG file:
  1. IO.read("example.png", 8, 16).unpack("NN")
Expand to see the code.


Downloads bits from the Internet and saves them to a file (supports HTTP and FTP):
  1. def download(url, filename)
  2.   Win32API.new("urlmon", "URLDownloadToFile", "LPPLL", "L").call(0, url, filename, 0, 0).zero?
  3. end
Expand to see the code.
  1.  
  2. # Win32API.new("kernel32", "AllocConsole", "V", "L").call
  3. # $stdout.reopen("CONOUT$")
  4.  
Expand to see the code.

Hey, This is a very good one!
I don't understand how it works, but i did some modifications here:
First: This is the Kernel module
Second: Why only puts, i want gets too!
Third: IT WORKS!!!!

Thank you Cremno, I always wanted gets and puts, now i got it!

  1.  
  2. #====================================================================
  3. # Kernel
  4. #====================================================================
  5.  
  6. module Kernel
  7.   # AllocConsole function has no parameters, only one return
  8.   AC = Win32API.new('kernel32', 'AllocConsole', '', 'l')
  9.   #-------------------------------------------------------------------
  10.   # - Prompt Window for gets and puts!
  11.   #-------------------------------------------------------------------
  12.  
  13.   def debug
  14.      AC.call
  15.      $stdout.reopen('CONOUT$')
  16.      $stdin.reopen('CONIN$')
  17.      x=gets
  18.      puts 'Debug...'
  19.      puts '>>' << x
  20.      trace_var(:$scene){|v| puts 'Scene >>> '<< v.to_s << Time.now.strftime("%H:%M:%S")}
  21.   end
  22.   debug if $DEBUG
  23. end
  24.  
Expand to see the code.


Sorry for any mistakes(English/Ruby/Win32API), MauMau
Well this snippet just adds 2 methods to make sure you can easily change your character / battler graphics and get them back at will via script call. Of course you still can do this by setting up some map event...

  1. class Game_Actor
  2.   attr_accessor :old_graphic
  3.   alias kyon_gma_init initialize
  4.   def initialize(actor_id)
  5.      @old_graphic = []
  6.      kyon_gma_init(actor_id)
  7.   end
  8.  
  9.   def change_graphic(index, graphic, value=0)
  10.      actor = $game_actors[index+1] # Get actor
  11.      if FileTest.exists?('Data/Actors.rxdata')
  12.         @old_graphic[index] = [ @character_name, @battler_name, value ]
  13.      else
  14.         @old_graphic[index] = [ @character_name, @battler_name, @face_index ]
  15.      end
  16.      if actor != nil # Change graphic
  17.         # XP - Pass Character Graphic, Hue, Battler Graphic, Hue values
  18.         # VX -Pass Character Graphic, Index, Face Graphic, Index values
  19.         graphic = $data_actors[graphic].character_name
  20.         actor.set_graphic(graphic, value, graphic, value)
  21.      end
  22.      # Refresh player
  23.      $game_player.refresh
  24.      # Continue
  25.      return true
  26.   end
  27.  
  28.   def get_old_graphic(index)
  29.      actor = $game_actors[index+1]
  30.      if actor != nil
  31.         # XP - Pass Character Graphic, Hue, Battler Graphic, Hue values
  32.         # VX -Pass Character Graphic, Index, Face Graphic, Index values
  33.         actor.set_graphic(@old_graphic[index][0], @old_graphic[index][2],
  34.            @old_graphic[index][1], @old_graphic[index][2])
  35.      end
  36.      $game_player.refresh
  37.      return true
  38.   end
  39. end
Expand to see the code.


Script Call:

$game_party.actors[0].change_graphic(0,2)

It'd transform Aluxes into a second Basil. To revert the change just call it like this...

$game_party.actors[0].get_old_graphic(0)

For VX use $game_party.members[0] instead.

The change_graphic method is a variant of the Interpreter command_322 one or more precisely it's a revised version. It doesn't just allow you to change the graphic, but it also lets you store the previous graphics names in an array temporarily.

The get_old_graphic method lets you reset the graphics at any time if deemed necessary.

BTW, it will work on both, XP and VX.

Never edit this line:

actor = $game_actors[index+1]

Or it won't work properly because the $game_actors index starts at 1 not 0 (it gets the info from $data_actors which also starts at 1).
Great Script!
You don't need those "return true" in the end of the method!
This is ruby, it will return the last thing anyway.
Test this:
  1.  
  2. def test
  3.  true
  4. end
  5.  
  6. def test_return
  7.  return true
  8. end
  9.  
  10. p test == test_return
  11. p test, test_return
  12.  
Expand to see the code.

This works for everything in the end of a method, remember!

You can use ternary operator here, but will be a bigger line:
  1.  
  2.  @old_graphic[index] = [ @character_name, @battler_name, FileTest.exists?('Data/Actors.rxdata') ? value : @face_index ]
  3.  
Expand to see the code.


MauMau
A cool way to dynamically do stuff :p

You can call the method of an object like this

obj.my_method

but :p what if you want my_method is unknown, i mean, that you don't know at that time which method is going to be called...
You could write statements that would call the proper method with conditions and such ...

but you could also simply generate the method name :p

let's say you have a funny old text "rpg" , you know the kind of you play in a console, that asks you what you want to do :p
usually the player would either type an ID related to the action, or would type the action name, and a method would analyse that name or the ID, and would call the method for that action...

Well ruby allows you to generate method names:p which is pretty cool
so to call the method of an object by knowing its name, it's quite easy:

obj.method( the_method_name ).call(the_arguments)

but here "the_method_name" can't be a string it must be a symbol , so to do that you just convert the string to a symbol using the "to_sym" method :p

obj.method( the_method_name.to_sym).call(the_arguments)

and voilà! :p
There you just need to play with string methods to generate the proper method names, of course, be careful that the generate name must refer to an actual existing method ( else you'll have an error)

Example in my physics engine, i'm testing collision between 2 kind of shapes, box, and circles, so we have only 3 type of collisions > box/box, box/circle & circle/circle.

So i did 3 methods to test each of those cases :p and i have one method that call the right method for the 2 shapes given....

  1.    def Shape.collide(s1,s2) # Meta Prog => Compute the method name from shapes classes
  2.         return Shape.method( (s1.class.to_s+'Vs'+s2.class.to_s).to_sym ).call(s1,s2)
  3.   end
  4.  
  5.   def Shape.CircleVsCircle(c1, c2)
  6.  
  7.   end
  8.   def Shape.AABBVsAABB(a1, a2)
  9.  
  10.   end
  11.   def Shape.AABBVsCircle(a, c)
  12.  
  13.   end
  14.  
Expand to see the code.


Look at line 7 :p ^^
I also did 3 "twin" methods with reverse names that call the 3 originals but with arguments.

It's a more useful & secure than ^^ eval and works better IMO.
hhihihi

object.send(method_name,*args) does the same (and it can be strings)
hum the online reference says that send uses symbol as well :p

the main difference is ... that "method" returns a method object, that you can call later or store in a variable,
whereas send, directly call it.

But in either case, it's still something i find really smart :p
The debug thing is great. I found an API call to get the game window to come back to the foreground immediately once the debug window is created:
  1.       Win32API.new("user32", "SetForegroundWindow", "L", "L").call(hwnd)
Expand to see the code.

I've put the functions into a Debug module with special features:
1) Also writes to log file 'debug.log'.
2) Can :start and :stop debugging (Debug.start and Debug.stop opens/closes the console, respectively).
3) Debug.log_by_frame can be called every frame, without flooding the console with eternal messages (only prints message every one second).
  1. #===============================================================================
  2. # ** Debug
  3. #-------------------------------------------------------------------------------
  4. #      Provides a console window to log debugging messages
  5. #===============================================================================
  6.  
  7. module Debug
  8.   @active = false
  9.   @file = File.open('debug.log', File::CREAT|File::APPEND|File::WRONLY)
  10.   #-----------------------------------------------------------------------------
  11.   # * Open a console window for debug output
  12.   #-----------------------------------------------------------------------------
  13.   def self.start
  14.      @active = true
  15.      return unless self.active
  16.      # Open console window and select it for :puts
  17.      Win32API.new("kernel32", "AllocConsole", "V", "L").call
  18.      $stdout.reopen("CONOUT$")
  19.      # Bring the game window back to the front
  20.      Win32API.new("user32", "SetForegroundWindow", "L", "L").call(hwnd)
  21.      # Write log headers
  22.      self.log("========================================================")
  23.      self.log(Time.now)
  24.      self.log("--------------------------------------------------------")
  25.   end
  26.   #-----------------------------------------------------------------------------
  27.   # * Stop debugging
  28.   #-----------------------------------------------------------------------------
  29.   def self.stop
  30.      Win32API.new("kernel32", "FreeConsole", "", "L").call
  31.      @active = false
  32.   end
  33.   #-----------------------------------------------------------------------------
  34.   # * Stop debugging
  35.   #-----------------------------------------------------------------------------
  36.   def self.active
  37.      return @active #and $DEBUG
  38.   end
  39.   #-----------------------------------------------------------------------------
  40.   # * Write to console
  41.   #-----------------------------------------------------------------------------
  42.   def self.log(string)
  43.      puts string if self.active
  44.      @file.print string.to_s + "\n"
  45.   end
  46.   #-----------------------------------------------------------------------------
  47.   # * Write to console; not done every frame
  48.   #-----------------------------------------------------------------------------
  49.   def self.log_by_frame(string)
  50.      self.log(string) if Graphics.frame_count % Graphics.frame_rate == 0
  51.   end
  52. end
Expand to see the code.

(I commented out $DEBUG because for whatever reason, probably because I'm running RMXP using RGSS202E. $TEST doesn't seem to work either)
information:
VX has also the $DEBUG, but it isnt used.. it use $TEST
$TEST doesn't work either. Perhaps RMXP tries to set $DEBUG but the game.exe prevents it, expecting RMVX to set $TEST even though I'm not loading it from RMVX.
  1. global_variables.include?("$TEST") ? $TEST : $DEBUG
Expand to see the code.

so?

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=42375