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

After seeing like 10 version of people and their Table classes, decided to simply this. Maybe I am just under thinking Tables, but I think people are over complicating them. So here is what I just came up with:
  1. class Table
  2.   Default = 0
  3.   attr_reader :default
  4.   def initialize(default = Default)
  5.     @data = {}
  6.     @data.default = default
  7.   end
  8.   def default=(default)
  9.     @data.default = default
  10.   end
  11.   def [](*args)
  12.     return @data[args]
  13.   end
  14.   def []=(*args)
  15.     v = args.pop
  16.     @data[args] = v
  17.   end
  18.   def each(&block)
  19.     @data.each(&block)
  20.   end
  21.   def each_value(&block)
  22.     @data.each_value(&block)
  23.   end
  24. end
Expand to see the code.


It doesn't do anything special at all. It's just a wrapper of the Hash instead of an array. Supports unlimited dimensions (actually, all it does create a bunch of keys).
Here there are some silly but still useful methods for Sprite and Scene_Base classes...

  1. class Sprite
  2.   def x_y(x, y); self.x, self.y = x, y; end
  3. end
Expand to see the code.


  1. def exit?
  2.     if Input.trigger?(Input::B) # If B button was pressed
  3.       $game_system.se_play($data_system.cancel_se) # Play cancel SE
  4.       $scene = Scene_Map.new # Switch to map screen
  5.       return
  6.     end
  7.   end
Expand to see the code.


Normally, Sprite class wouldn't allow you to define the x and y coordinates while initializing it, so you would need to do something like this...

@sprite = Sprite.new(viewport)# if needed, otherwise don't include viewport
@sprite.x, @sprite.y = 0, 0

...but the last line would be different if you include the method I posted above...

@sprite.x_y(0,0)

It'd be just easier to setup the coordinates.

The exit? method is just a simple way to include the Cancel button in any scene script in the main update method so now we don't need to include the same 4 lines in every single script but just a single method call to exit to Scene_Map.
I like it. However, I kinda prefer a mixin for any class with x & y.

  1. module Pos
  2.   def set_pos(x, y)
  3.     @x, @y = x, y
  4.   end
  5.   def pos
  6.     return @x, @y
  7.   end
  8. end
  9.  
  10. class Sprite
  11.   include Pos
  12. end
  13.  
  14. class Window
  15.   include Pos
  16. end
Expand to see the code.


I do like the exit update as well, however I suggest making it update_exit as methods with a ? typically only return true or false and do not have processing in them.
Right, or I could call it exit_scene_update or anything else. I forgot about the '?', I know I shouldn't have included that...

Well, then it'd also be a good idea to include this...

  1. module Pos
  2.   def active_visible=(boolean)
  3.     self.active, self.visible = boolean, boolean
  4.   end
  5. end
Expand to see the code.


Well, it could also be named w/o any = sign in between. That would be a good method to get rid of some inactive command menu for a while.
SephirothSpawn wrote:
After seeing like 10 version of people and their Table classes, decided to simply this. Maybe I am just under thinking Tables, but I think people are over complicating them. So here is what I just came up with:
  1. class Table
  2.   Default = 0
  3.   attr_reader :default
  4.   def initialize(default = Default)
  5.     @data = {}
  6.     @data.default = default
  7.   end
  8.   def default=(default)
  9.     @data.default = default
  10.   end
  11.   def [](*args)
  12.     return @data[args]
  13.   end
  14.   def []=(*args)
  15.     v = args.pop
  16.     @data[args] = v
  17.   end
  18.   def each(&block)
  19.     @data.each(&block)
  20.   end
  21.   def each_value(&block)
  22.     @data.each_value(&block)
  23.   end
  24. end
Expand to see the code.


It doesn't do anything special at all. It's just a wrapper of the Hash instead of an array. Supports unlimited dimensions (actually, all it does create a bunch of keys).


That's probably faster than all those complicated things, too, since Hash is actually faster than Array. What is missing, though, is a _dump and _load method that understands the Marshal serialization format of the built-in class. Those methods would be extremely useful for anybody trying to write an editor replacement.

Oh, and hi Seph.
Today I bring you 2 new (very similar) methods for the Array class.

  1. class Array
  2.   def next
  3.     @next = (@next.nil? or @next == self.size-1) ? 0 : @next+1
  4.     return self[@next]
  5.   end
  6.   alias :succ :next
  7.  
  8.   def previous
  9.     @prev = (@prev.nil? or @prev == 0) ? self.size-1 : @prev-1
  10.     return self[@prev]
  11.   end
  12.   alias :prev :previous
  13. end
Expand to see the code.


I know I configured it to create 2 separate instance variables, but you can use a single one instead, i.e. @pos instead of @next and @prev but it may work in a very different way than I'd expect.

Examples:

a = [1,4,9,7,5,2,4,8,9]
a.next #=> 1
a.next #=> 4
# a few extra lines in between
a.next #=> 9
a.next #=> 1
a.next #=> 4

The same would be valid for the "previous" method.

a.prev #=> 9
a.prev #=> 8
a.prev #=> 4
I really like that kyonides. Neat little idea to keep track of current index and provides a uniq way to pass through array objects.



Ok. While working on a Resolution System, I realized I had to redo the Graphics.transition effects process. So I made a little tool that transforms one bitmap into another (right now, just for sprites, but can be made a mixin pretty easily).

  1. class Bitmap
  2.   def dup
  3.     dummy = Bitmap.new(width, height)
  4.     dummy.blt(0, 0, self, self.rect)
  5.     return dummy
  6.   end
  7. end
  8.  
  9. class Sprite
  10.   alias_method :seph_spritetrans_update, :update
  11.   def update
  12.     if @transition != nil
  13.       @transition.update
  14.       @transition = nil if @transition.done?
  15.     end
  16.     seph_spritetrans_update
  17.   end
  18.   def transition(target_bitmap, transition_file = '001-Blind01',
  19.                  frames = 10, stretch = true)
  20.     self.bitmap = self.bitmap.dup
  21.     @transition = Sprite::Transition.new(self.bitmap, target_bitmap, transition_file, frames, stretch)
  22.   end
  23. end
  24.  
  25. class Sprite::Transition
  26.   def initialize(old_bitmap, target_bitmap, transition_file, frames, stretch)
  27.     @old_bitmap = old_bitmap
  28.     @target_bitmap = target_bitmap
  29.     bitmap = RPG::Cache.load_bitmap("Graphics/Transitions/", transition_file)
  30.     @tranisition_bitmap = Bitmap.new(@target_bitmap.width, @target_bitmap.height)
  31.     if stretch
  32.       @tranisition_bitmap.stretch_blt(@tranisition_bitmap.rect, bitmap, bitmap.rect)
  33.     else
  34.       @tranisition_bitmap.blt(0, 0, bitmap, bitmap.rect)
  35.     end
  36.     @frame = 0
  37.     @frames = frames
  38.     @dpf = 255.0 / @frames
  39.   end
  40.   def dist(color)
  41.     n = 0
  42.     n += color.red
  43.     n += color.green
  44.     n += color.blue
  45.     return (n / 3.0)
  46.   end
  47.   def update
  48.     @frame += 1
  49.     min_d = (@frame - 1) * @dpf
  50.     max_d = @frame * @dpf
  51.     for x in 0...@tranisition_bitmap.width
  52.       for y in 0...@tranisition_bitmap.height
  53.         d = dist(@tranisition_bitmap.get_pixel(x, y))
  54.         next unless d.between?(min_d, max_d)
  55.         @old_bitmap.set_pixel(x, y, @target_bitmap.get_pixel(x, y))
  56.       end
  57.     end
  58.   end
  59.   def done?
  60.     return @frame >= @frames
  61.   end
  62. end
Expand to see the code.


It is slow because it passes through each pixel for each time for each frame it undergoes the transition. I tried keeping a list of pixels to skip if they have been set (x/y coordinates) but that actually slowed it down significantly. The best thing I could do is add a min_d value, and only continue to pixel mods when it was between the min_d and max_d variables.

The algorithm I came up was pretty simple: each pixel is given a "d" value (why I choose name d, just because) from 0 to 255. The d is equal to

(red + green + blue) / 3.0

It finds the average rgb on a 0 to 255 scale

The original bitmap must be duplicated to prevent modifications to the bitmaps stored in RPG::Cache

It passes through each pixel on the transition bitmap and gets the d value. If the d value if set for the current frame (between last frame "d" and current frame "d", where frame "d" = 255.0 / @frames * frame), it gets the target bitmap pixel at same position and sets it on the old bitmap as the same position.


EDIT: If you want to see a sample:
  1. class Scene_Title
  2.   alias_method :seph_test_main,   :main
  3.   alias_method :seph_test_update, :update
  4.   def main
  5.     @test_sprite = Sprite.new
  6.     @test_sprite.z = 999
  7.     @test_sprite.bitmap = RPG::Cache.battler('085-Elemental03', 0)
  8.     seph_test_main
  9.     @test_sprite.dispose
  10.   end
  11.   def update
  12.     if Input.trigger?(Input::ALT)
  13.       target = RPG::Cache.battler('060-Aquatic02', 0)
  14.       @test_sprite.transition(target)
  15.     end
  16.     @test_sprite.update
  17.     seph_test_update
  18.   end
  19. end
Expand to see the code.


Just press Alt on the title screen.
That looks good, Seph. Have you tried the User32 mix-in module I made? Speaking of which, I've made some additions to it that make SetWindowLong that much more useful:

  1. #===============================================================================
  2. # ** User32
  3. #-------------------------------------------------------------------------------
  4. #    Wrapper for user32.dll functions. Use "include User32" to get the constants
  5. #===============================================================================
  6.  
  7. module User32
  8.   GSM                 = Win32API.new('user32', 'GetSystemMetrics', 'I', 'I')
  9.   SetWindowPos        = Win32API.new('user32', 'SetWindowPos', 'LLIIIII', 'I')
  10.   SetWindowLong       = Win32API.new('user32', 'SetWindowLong', 'LIL', 'L')
  11.   Keybd_Event         = Win32API.new('user32', 'keybd_event', 'LLLL', '')
  12.   FindWindow          = Win32API.new('user32', 'FindWindow', 'PP', 'L')
  13.   GetDesktopWindow    = Win32API.new('user32', 'GetDesktopWindow', '', 'L')
  14.   GetWindowInfo       = Win32API.new('user32', 'GetWindowInfo', 'LP', 'I')
  15.   SetForegroundWindow = Win32API.new('user32', 'SetForegroundWindow', 'L', 'L')
  16.   GetCursorPos        = Win32API.new('user32', 'GetCursorPos', 'P', 'I')
  17.   ShowCursor          = Win32API.new('user32', 'ShowCursor', 'L', 'L')
  18.   ScreenToClient      = Win32API.new('user32', 'ScreenToClient', 'LP', 'I')
  19.   GetKeyState         = Win32API.new('user32', 'GetKeyState', 'I', 'I')
  20.   GetAsyncKeyState    = Win32API.new('user32', 'GetAsyncKeyState', 'I', 'I')
  21.  
  22.   HWND = FindWindow.call('RGSS Player', Settings['Title'])
  23.  
  24.   # GSM constants. For more complete descriptions, see Microsoft's website:
  25.   # http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx
  26.   SM_CXSCREEN      = 0  # Width of the current master screen resolution
  27.   SM_CYSCREEN      = 1  # Height of the current master screen resolution
  28.  
  29.   SM_CXVSCROLL     = 2  # Width of a vertical scroll bar
  30.   SM_CYHSCROLL     = 3  # Height of a horizontal scroll bar
  31.  
  32.   SM_CYCAPTION     = 4  # Height of a caption area
  33.  
  34.   SM_CXBORDER      = 5  # Width of a window border
  35.   SM_CYBORDER      = 6  # Height of a window border
  36.  
  37.   SM_CXDLGFRAME    = 7
  38.   SM_CXFIXEDFRAME  = 7  # Width of non-resizable captioned window frame
  39.   SM_CYDLGFRAME    = 8
  40.   SM_CYFIXEDFRAME  = 8  # Height of non-resizable captioned window frame
  41.  
  42.   SM_CYVTHUMB      = 9  # Height of a thumb button on vertical scrollbars
  43.   SM_CXHTHUMB      = 10 # Width of a thumb button on horizontal scrollbars
  44.  
  45.   SM_CXICON        = 11 # Default width of an icon
  46.   SM_CYICON        = 12 # Default height of an icon
  47.  
  48.   SM_CXCURSOR      = 13 # Width of a cursor
  49.   SM_CYCURSOR      = 14 # Height of a cursor
  50.  
  51.   SM_CYMENU        = 15 # Height of a single-line menu bar
  52.  
  53.   SM_CXFULLSCREEN  = 16 # Width of client rect for a full-screen window
  54.   SM_CYFULLSCREEN  = 17 # Height of client rect for a full-screen window
  55.  
  56.   SM_CYKANJIWINDOW = 18 # Height of kanji window at bottom of screen, if there
  57.  
  58.   SM_MOUSEPRESENT  = 19 # Non-zero if mouse is present; 0 if not
  59.  
  60.   SM_CYVSCROLL     = 20 # Height of the arrow bitmap on vertical scrollbars
  61.   SM_CXHSCROLL     = 21 # Width of the arrow bitmap on horizontal scrollbars
  62.  
  63.   SM_DEBUG         = 22 # Non-zero if debug User.exe is installed; 0 if not
  64.   SM_SWAPBUTTON    = 23 # Non-zero if mouse button values are swapped
  65.  
  66.   SM_CXMIN         = 28 # Minimum width of a window
  67.   SM_CYMIN         = 29 # Minimum height of a window
  68.  
  69.   SM_CXSIZE        = 30 # Width of a button in a window caption or title bar
  70.   SM_CYSIZE        = 31 # Height of a button in a window caption or title bar
  71.  
  72.   SM_CXFRAME       = 32
  73.   SM_CXSIZEFRAME   = 32 # Width of the sizing border around a resizable window
  74.   SM_CYFRAME       = 33
  75.   SM_CYSIZEFRAME   = 33 # Height of the sizing border around a resizable window
  76.  
  77.   SM_CXMINTRACK    = 34 # Minimum "tracking" width of a window
  78.   SM_CYMINTRACK    = 35 # Minimum "tracking" height of a window
  79.  
  80.   SM_CXDOUBLECLK   = 36 # Width of rect which second click must be in for double
  81.   SM_CYDOUBLECLK   = 37 # Hght of rect which second click must be in for double
  82.  
  83.   SM_CXICONSPACING = 38 # Width of a grid cell for items in large icon view
  84.   SM_CYICONSPACING = 39 # Height of a grid cell for items in large icon view
  85.  
  86.   SM_MENUDROPALIGNMENT = 40 # 0 if drop-down menus are left-aligned...
  87.  
  88.   SM_PENWINDOWS    = 41 # Non-zero if Microsoft Windows for Pen computing
  89.                         #  extensions are installed; 0 if not
  90.  
  91.   SM_DBCSENABLED   = 42 # Non-zero if user32.dll supports DBCS; 0 if not
  92.  
  93.   SM_CMOUSEBUTTONS = 43 # Number of available mouse buttons, or 0 for no mouse
  94.  
  95.   SM_SECURE        = 44 # Always returns 0
  96.  
  97.   SM_CXEDGE        = 45 # Width of a 3-D style border
  98.   SM_CYEDGE        = 46 # Height of a 3-D style border
  99.  
  100.   SM_CXMINSPACING  = 47 # Width of a grid cell for minimized windows
  101.   SM_CYMINSPACING  = 48 # Height of a grid cell for minimized windows
  102.  
  103.   SM_CXSMICON      = 49 # Recommended width of a small icon
  104.   SM_CYSMICON      = 50 # Recommended height of a small icon
  105.  
  106.   SM_CYSMCAPTION   = 51 # Height of a small caption
  107.   SM_CXSMSIZE      = 52 # Width of small caption buttons
  108.   SM_CYSMSIZE      = 53 # Height of small caption buttons
  109.   SM_CXMENUSIZE    = 54 # Width of menu bar buttons
  110.   SM_CYMENUSIZE    = 55 # Height of menu bar buttons
  111.  
  112.   SM_ARRANGE       = 56 # Flags about how system the arranges minimized windows
  113.   SM_CXMINIMIZED   = 57 # Width of a minimized window
  114.   SM_CYMINIMIZED   = 58 # Height of a minimized window
  115.  
  116.   SM_CXMAXTRACK    = 59 # Default maximum width of resizable windows
  117.   SM_CYMAXTRACK    = 60 # Default maximum height of resizable windows
  118.   SM_CXMAXIMIZED   = 61 # Default width of maximized top-level window
  119.   SM_CYMAXIMIZED   = 62 # Default height of maximized top-level window
  120.  
  121.   SM_NETWORK       = 63 # The least significant bit is set if a network is
  122.                         #  present; otherwise, it is cleared
  123.  
  124.   SM_CLEANBOOT     = 67 # System boot type; 0:Normal, 1:Safe, 2:Safe w/network
  125.  
  126.   SM_CXDRAG        = 68
  127.   SM_CYDRAG        = 69 # Number of pixels mouse can move before initiating drag
  128.  
  129.   SM_SHOWSOUNDS    = 70 # Non-zero if user requires visible output; 0 if not
  130.  
  131.   SM_CXMENUCHECK   = 71 # Width of the default menu check-mark bitmap
  132.   SM_CYMENUCHECK   = 72 # Height of the default menu check-mark bitmap
  133.  
  134.   SM_SLOWMACHINE   = 73 # Non-zero if system has a slow processor; 0 if not
  135.                         #  No, seriously, that's what Microsoft said!
  136.  
  137.   SM_MIDEASTENABLED = 74 # Non-zero if system can use Hebrew, Arabic languages
  138.  
  139.   SM_MOUSEWHEELPRESENT = 75 # Nonzero mouse has vertical scroll wheel; 0 if not
  140.  
  141.   SM_XVIRTUALSCREEN    = 76 # Coordinates of the left side of the virtual screen
  142.   SM_YVIRTUALSCREEN    = 77 # Coordinates of the top of the virtual screen
  143.   SM_CXVIRTUALSCREEN   = 78 # Virtual width of all screens put together
  144.   SM_CYVIRTUALSCREEN   = 79 # Virtual height of all screen put together
  145.   SM_CMONITORS         = 80 # Numbers of display monitors on a desktop
  146.   SM_SAMEDISPLAYFORMAT = 81 # Non-zero if all screen use same color depth...
  147.  
  148.   # SetWindowPos constants
  149.   HWND_NOTOPMOST      = -2  # Make window not always on top (and bring to front)
  150.   HWND_TOPMOST        = -1  # Put window in front and make it always on top
  151.   HWND_TOP            = 0   # Put window in front of all non-topmost windows
  152.   HWND_BOTTOM         = 1   # Put window behind all other windows
  153.  
  154.   SWP_NOSIZE          = 0x0001 # Keep current size (ignores w and h)
  155.   SWP_NOMOVE          = 0x0002 # Keep current position (ignores X and Y)
  156.   SWP_NOZORDER        = 0x0004 # Keep current Z order (ignores hWndInsertAfter)
  157.   SWP_NOREDRAW        = 0x0008 # Does NOT redraw changes
  158.   SWP_NOACTIVATE      = 0x0010 # Does NOT automatically activate the window
  159.   SWP_FRAMECHANGED    = 0x0020 # Applies new frame styles set with SetWindowLong
  160.   SWP_SHOWWINDOW      = 0x0040 # Displays the window
  161.   SWP_HIDEWINDOW      = 0x0080 # Hides the window
  162.   SWP_NOCOPYBITS      = 0x0100 # Discards the entire contents of the client area
  163.   SWP_NOOWNERZORDER   = 0x0200 # Doesn't change the window display order
  164.   SWP_NOSENDCHANGING  = 0x0400 # Don't send WM_WINDOWPOSCHANGING
  165.   SWP_DEFERERASE      = 0x2000 # Prevents generation of the WM_SYNCPAINT message
  166.   SWP_ASYNCWINDOWPOS  = 0x4000 # Use if calling thread does not own the window
  167.  
  168.   # SetWindowLong constants
  169.   GWL_USERDATA        = -21 # Sets data reserved for use by the application
  170.   GWL_EXSTYLE         = -20 # Sets a new extended window style
  171.   GWL_STYLE           = -16 # Sets a new window style
  172.   GWL_ID              = -12 # Sets a new identifier of the window
  173.   GWL_HWNDPARENT      = -8  # Sets a new parent hWnd
  174.   GWL_HINSTANCE       = -6  # Sets a new application instance handle
  175.   GWL_WNDPROC         = -4  # Sets a new addr for the window calling procedure
  176.   # Only available when the hWnd parameter identifies a dialog box:
  177.   DWL_MSGRESULT       = 0   # Sets the return message of the dialog box proc
  178.   DWL_DLGPROC         = 4   # Sets the new address of the dialog box proc
  179.   DWL_USER            = 8   # Sets new extra information private to application
  180.  
  181.   # Window Styles (SetWindowLong(hWnd, GWL_STYLE, WS_*))
  182.   WS_OVERLAPPED       = 0x00000000 # Overlapped window has title and border
  183.   WS_TABSTOP          = 0x00010000 # Can receive focus from TAB key
  184.   WS_GROUP            = 0x00020000 # First control of group of controls
  185.   WS_MAXIMIZEBOX      = 0x00010000 # Has a mazimize button
  186.   WS_MINIMIZEBOX      = 0x00020000 # Has a minimize button
  187.   WS_THICKFRAME       = 0x00040000 # Has sizing border
  188.   WS_SYSMENU          = 0x00080000 # Has buttons on title bar (reqs WS_CAPTION)
  189.   WS_HSCROLL          = 0x00100000 # Has horizontal scroll bar
  190.   WS_VSCROLL          = 0x00200000 # Has vertical scroll bar
  191.   WS_DLGFRAME         = 0x00400000 # Dialog-style border. Cannot have title bar
  192.   WS_BORDER           = 0x00800000 # Thin border
  193.   WS_CAPTION          = 0x00C00000 # Has a title bar (implies WS_BORDER)
  194.   WS_MAXIMIZE         = 0x01000000 # Initially maximized
  195.   WS_CLIPCHILDREN     = 0x02000000 # Exclude area for children when drawing
  196.   WS_CLIPSIBLINGS     = 0x04000000 # Exclude sibling client rects when drawing
  197.   WS_DISABLED         = 0x08000000 # Initially disabled (no input)
  198.   WS_VISIBLE          = 0x10000000 # Initially visible
  199.   WS_MINIMIZE         = 0x20000000 # Initially minimized
  200.   WS_CHILD            = 0x40000000 # Child cannot have menu bar or WS_POPUP
  201.   WS_POPUP            = 0x80000000 # Popup window
  202.   # Window style aliases
  203.   WS_OVERLAPPEDWINDOW = WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_THICKFRAME|
  204.                         WS_MINIMIZEBOX|WS_MAXIMIZEBOX
  205.   WS_POPUPWINDOW      = WS_POPUP|WS_BORDER|WS_SYSMENU
  206.   WS_CHILDWINDOW      = WS_CHILD
  207.   WS_TILED            = WS_OVERLAPPED
  208.   WS_ICONIC           = WS_MINIMIZE
  209.   WS_SIZEBOX          = WS_THICKFRAME
  210.   WS_TILEDWINDOW      = WS_OVERLAPPEDWINDOW
  211. end
  212.  
Expand to see the code.


Example usage (using the SetResolution dll by Selwyn which is defined as constant Set_Res):

  1.  def self.fullscreen
  2.     @default_size = size
  3.     SetWindowLong.call(HWND, GWL_STYLE, WS_VISIBLE|WS_CLIPSIBLINGS)
  4.     SetWindowPos.call(HWND, HWND_TOPMOST, 0, 0, @width, @height, SWP_SHOWWINDOW)
  5.     Set_Res.call(@width, @height, 4)
  6.     @fullscreen = true
  7.   end
  8.   def self.default
  9.     SetWindowLong.call(HWND, GWL_STYLE, WS_VISIBLE|WS_CLIPSIBLINGS|
  10.                                         WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX)
  11.     w = @width + (2 * GSM.call(SM_CXFIXEDFRAME))
  12.     h = @height + (2 * GSM.call(SM_CYFIXEDFRAME)) + GSM.call(SM_CYCAPTION)
  13.     x = (@default_size[0] - w) / 2
  14.     y = (@default_size[1] - h) / 2
  15.     SetWindowPos.call(HWND, HWND_TOP, x, y, w, h, SWP_SHOWWINDOW)
  16.     Set_Res.call(@default_size[0], @default_size[1], 0)
  17.     @fullscreen = false
  18.   end
  19.  
Expand to see the code.


But I'm here to add a feature to RGSS that was thankfully built into RGSS2: Sprite#viewport=. It was actually rather difficult, and the process of changing viewport is time-consuming (as it has to create a new sprite and copy all of the attributes over) but this solution should drop in with only minimal hit to resources:

  1. #===============================================================================
  2. # ** Sprite
  3. #-------------------------------------------------------------------------------
  4. #    In order to provide a viewport= method, this class has been heavily
  5. #    reworked as a "server" class which keeps a Sprite::Binding object which
  6. #    it calls methods on.
  7. #===============================================================================
  8.  
  9. class Sprite
  10.   #-----------------------------------------------------------------------------
  11.   # * Create a duplicate class Sprite::Binding
  12.   #-----------------------------------------------------------------------------
  13.   Binding = Sprite.dup
  14.   Attributes = [ 'bitmap', 'src_rect', 'visible', 'x', 'y', 'z', 'ox', 'oy',
  15.                  'zoom_x', 'zoom_y', 'angle', 'mirror', 'bush_depth', 'opacity',
  16.                  'blend_type', 'color', 'tone' ]
  17.   #-----------------------------------------------------------------------------
  18.   # * For each instance method, redefine the method to send to the binding
  19.   #-----------------------------------------------------------------------------
  20.   instance_methods(false).each do |symbol|
  21.     define_method(symbol) do |*args|
  22.       begin
  23.         @_binding.__send__(symbol, *args)
  24.       rescue Exception
  25.         # Remove from the backtrace the four entries pointing to this block
  26.         3.times { $!.backtrace.shift }
  27.         raise $!
  28.       end
  29.     end
  30.   end
  31.   #-----------------------------------------------------------------------------
  32.   # * Create the binding on initialization
  33.   #-----------------------------------------------------------------------------
  34.   def initialize(viewport = nil)
  35.     @_binding = Binding.new(viewport)
  36.   end
  37.   #-----------------------------------------------------------------------------
  38.   # * Set new viewport; dispose existing sprite and create new one with viewport
  39.   #-----------------------------------------------------------------------------
  40.   def viewport=(viewport)
  41.     # Skip if binding already uses this viewport
  42.     return @_binding.viewport if @_binding.viewport == viewport
  43.     old = @_binding                   # Cache old binding
  44.     @_binding = Binding.new(viewport) # Create a new sprite with this viewport
  45.     # Copy attributes over from the old binding
  46.     Attributes.each { |sym| @_binding.__send__(sym + '=', old.__send__(sym)) }
  47.     old.dispose                       # Dispose old binding
  48.     @_binding.viewport                # Return new viewport
  49.   end
  50. end
  51.  
Expand to see the code.


What that does is it copies the Sprite class into Sprite::Binding, then proceeds to rewrite all of the Sprite methods to redirect to a @_binding object created at initialization! It really does work, even with classes which extend the Sprite class. Just make sure you put that code at the top, before anything that makes a Sprite, or the Sprite created before this code will fail.
I like the User32 module. The only thing I do differently is rather than creating constants, I create methods instead that send api arguments and call arguments to a method within a parent API module that creates Win32API objects and lowers amount of API calls (and multiple constants sharing the same method.

  1. #==============================================================================
  2. # ** API
  3. #------------------------------------------------------------------------------
  4. # SephirothSpawn
  5. # 2010-03-12
  6. #------------------------------------------------------------------------------
  7. # * Library
  8. #
  9. # API:
  10. # ---------------------------------------------------------------------------
  11. # API.call
  12. # API.hwnd
  13. #==============================================================================
  14.  
  15. module API
  16.   #-------------------------------------------------------------------------
  17.   # * Create API Function List
  18.   #-------------------------------------------------------------------------
  19.   @functions = {}
  20.   #-------------------------------------------------------------------------
  21.   # * Name      : Call API Function
  22.   #   Version   : 1.0
  23.   #   Author    : SephirothSpawn
  24.   #   Call Info : API Arguments, Function Arguments
  25.   #
  26.   #   API.call(['dll', 'function', 'args', 'return'], function_args)
  27.   #-------------------------------------------------------------------------
  28.   def self.call(api_arguments, function_arguments)
  29.     # If key not found
  30.     unless @functions.has_key?(api_arguments)
  31.       @functions[api_arguments] = Win32API.new(*api_arguments)
  32.     end
  33.     # Call Function
  34.     @functions[api_arguments].call(*function_arguments)
  35.   end
  36.   #-------------------------------------------------------------------------
  37.   # * Name      : Handel
  38.   #   Version   : 1.0
  39.   #   Author    : SephirothSpawn
  40.   #   Call Info : Gets Game Handel
  41.   #-------------------------------------------------------------------------
  42.   def self.hwnd
  43.     # Return if already found
  44.     return @hwnd if @hwnd != nil
  45.     # Find Handel
  46.     hwnd = "\0" * 256
  47.     call_args = ['Game', 'Title', '', hwnd, 255, ".\\Game.ini"]
  48.     API::Kernel32.GetPrivateProfileString(*call_args)
  49.     hwnd.delete!("\0")
  50.     @hwnd = API::User32.FindWindow('RGSS Player', hwnd)
  51.   end
  52. end
Expand to see the code.


Essientialy, rather than have

User32::Method_Name.call(args)

API::User32.method_name(args)



But love all the neat little constants. I tried looking for them myself, but that was back when I really wasn't into API all that much.


Love the sprite#viewport= binding. I almost did that same thing as well without the binding aspect, but your way is hella sexy. Very nice.
I kind of like that idea for an API module. And you are wrapping that with individual functions like User32.SetWindowLong(args) and User32.FindWindow(args)? I guess you are since I see that in your hwnd function. I would still prefer to define HWND once as a constant, though.

I've gotten into the habit of using certain functions instead of others due to "performance" reasons, such as using object.nil? (presumably defined as def nil? ; false ; end in Object and overloaded in NilClass as def nil? ; true ; end) instead of object == nil (which presumably checks nil values first, but it's a much larger function that tends to get overloaded in other objects, some of which might have forgotten to check for nil values if they're particularly stupid). Another is to not use "return" on the last line of a function. It's stylistically consistent with most of the rest of the Ruby world, though I can only speculate as to whether it's faster or not.

I found this file that has a lot of Windows constants defined. There are a lot of constants in there I haven't added yet, because I haven't needed to use them yet. It's not like this is some kind of comprehensive User32 wrapper class that defines everything you might ever possibly need. It does the stuff that one might need to messing with the game window, the mouse, or the keyboard.
I feel special, and you should too! I've written a Table class which is designed specifically to replace the built-in Table class, right down to the ability to Marshal.load the data that came out of RMXP or anyplace else that only knew about the built-in class. I would like to thank my hex editor (0xED for Mac) for making this possible.

  1. #===============================================================================
  2. # ** Table
  3. #-------------------------------------------------------------------------------
  4. #    Rewrites the Table class. This is slower than RGSS but more portable.
  5. #===============================================================================
  6.  
  7. class Table < Hash
  8.   #-----------------------------------------------------------------------------
  9.   # * Initialize the table with variable length arguments
  10.   #-----------------------------------------------------------------------------
  11.   def initialize(*args)
  12.     super(0) # 0 is default value
  13.     @sizes = []
  14.     resize(*args)
  15.   end
  16.   #-----------------------------------------------------------------------------
  17.   # * Set the size of (and number of) the dimensions
  18.   #-----------------------------------------------------------------------------
  19.   def resize(*args)
  20.     args.pop while args.last == 0 # Remove 0 values from end of args
  21.     if args.include?(0)
  22.       raise ArgumentError, 'Size of part of a Table cannot be zero.'
  23.     end
  24.     self.clear unless @sizes.length == args.length
  25.     @sizes = args
  26.   end
  27.   #-----------------------------------------------------------------------------
  28.   # * Returns the size at a specific depth, or nil if out of range
  29.   #-----------------------------------------------------------------------------
  30.   def size(depth)
  31.     @sizes[depth]
  32.   end
  33.   def xsize ; @sizes[0] ; end
  34.   def ysize ; @sizes[1] ; end
  35.   def zsize ; @sizes[2] ; end
  36.   #-----------------------------------------------------------------------------
  37.   # * Clear hash (reset integer-only flag as well)
  38.   #-----------------------------------------------------------------------------
  39.   def clear
  40.     super
  41.     @ints_only = true
  42.   end
  43.   #-----------------------------------------------------------------------------
  44.   # * Retrieve data
  45.   #-----------------------------------------------------------------------------
  46.   def [](*args)
  47.     # Return nil if out of range
  48.     return nil unless check_indeces(args)
  49.     super(args) # Notice the variable arguments is passed as a single array
  50.   end
  51.   #-----------------------------------------------------------------------------
  52.   # * Set data
  53.   #-----------------------------------------------------------------------------
  54.   def []=(*args)
  55.     # Remove the last argument, which is what the data will be set to
  56.     operand = args.pop
  57.     # Set @ints_only flag
  58.     @ints_only &= operand.is_a? Integer
  59.     # Return nil if out of range
  60.     return nil unless check_indeces(args)
  61.     super(args, operand)
  62.   end
  63.   #-----------------------------------------------------------------------------
  64.   # * Check arguments for size and within range
  65.   #-----------------------------------------------------------------------------
  66.   def check_indeces(args)
  67.     # Prevent different number of arguments than at creation
  68.     if args.size != @sizes.size
  69.       raise ArgumentError, "Table has #{@sizes.size} dimensions, but " +
  70.                            "received #{args.size} arguments."
  71.     end
  72.     # Check if index is within range
  73.     args.each_with_index {|i, depth| return false if i < 0 or i > @sizes[depth]}
  74.     true
  75.   end
  76.   #-----------------------------------------------------------------------------
  77.   # * Dump to String (compatible with RGSS Table dump format for Integers)
  78.   #-----------------------------------------------------------------------------
  79.   def _dump(marshal_depth = -1)
  80.     integer_format = (@ints_only && @sizes.size <= 3)
  81.     # First, store information about the size
  82.     size_info = [@sizes.length, *@sizes]
  83.     size_info << 0x01 while size_info.length < 4
  84.     output = size_info.pack('I*')
  85.     # Then, store whether this is integer format or not
  86.     output += [integer_format ? 0xD2 : 0x00].pack('I')
  87.     if integer_format
  88.       # All values are integers, so store them as such
  89.       self.each { |int| output += [int].pack('s') }
  90.     else
  91.       # Copy self into a plain hash to dump
  92.       output += Marshal.dump(Hash.new.merge!(self), marshal_depth)
  93.     end
  94.     output
  95.   end
  96.   #-----------------------------------------------------------------------------
  97.   # * Load from String (compatible with RGSS Table dump format for Integers)
  98.   #-----------------------------------------------------------------------------
  99.   def self._load(data)
  100.     # Get depth of the Table
  101.     depth = data.slice!(0...4).unpack('I')[0]
  102.     # Get size of each dimension
  103.     sizes = data.slice!(0...[12, depth * 4].max).unpack('I*')[0...depth]
  104.     output = Table.new(*sizes)
  105.     # Non-integer format: load the rest as a plain Hash
  106.     if data.slice!(0...4).unpack('I')[0] == 0x00
  107.       return output.merge!(Marshal.load(data))
  108.     end
  109.     # Integer format: load each piece of data in the correct order
  110.     output.each_index { |*i| output[*i] = data.slice!(0...2).unpack('s')[0] }
  111.     return output
  112.   rescue RangeError
  113.     # Catches failed attempts to slice existing data due to out of range
  114.     raise RuntimeError, 'Load data for Table is not as long as specified. ' +
  115.                         'The file may be corrupted.'
  116.   end
  117.   #-----------------------------------------------------------------------------
  118.   # * Process through each element in order
  119.   #-----------------------------------------------------------------------------
  120.   def each
  121.     self.each_index { |*index| yield self[*index] }
  122.   end
  123.   #-----------------------------------------------------------------------------
  124.   # * Process through each element in order, with index
  125.   #-----------------------------------------------------------------------------
  126.   def each_with_index
  127.     self.each_index { |*index| yield self[*index], *index }
  128.   end
  129.   #-----------------------------------------------------------------------------
  130.   # * Process a block for each in range from 0...arg, permutated thru all args
  131.   #-----------------------------------------------------------------------------
  132.   def each_index(&block) ; Table.each_index(*@sizes.dup, &block) ; end
  133.   def self.each_index(*sizes, &block)
  134.     range = 0...sizes.shift
  135.     if sizes.empty?
  136.       range.each(&block)
  137.     else
  138.       range.each { |i| self.each_index(*sizes) { |*index| yield i, *index } }
  139.     end
  140.   end
  141. end
  142.  
Expand to see the code.


As a plus, it works as a table for non-integers as well, in which case its Marshal dumping and loading go back somewhat to normal in order to accommodate non-integers.

Note that in the _dump function, 0x01 and 0xD2 are inserted in the size section. These are values that were part of the result of Table's original dump function, though I could not discern their purpose besides filling space. 0x01 is just filler. I'm using the space where 0xD2 is to determine the load type, so all that's important is that that value is NOT 0x00.
Thanks Rey, this is going to help me out allot. I've spent hours searching for a way to do this, and here it is, perfect :thumb:
Nice rey. Beat me to it. I was going to work on the _dump and _load methods to what I posted above, but looks like you took care of it. :thumb:
Oh, so you're saying it would have gotten done anyway? I guess I've come to expect that certain things like that I have to do myself if I want them done, especially given that most of the best scripters aren't around anymore...
It's always better to do things yourself rather than waiting on someone. Its why I learned to script lol. And we still have a great community of talented scripters. :cheers:
I came up with some pretty cool method modifications for the Hash class that allows you to read and set multi-dimensioned hashes without the work it had before. It also allows you to use classes with [] and []= methods.

  1. class Hash
  2.   alias_method :seph_mdhash_elem, :[]
  3.   def [](*keys)
  4.     next_object = self
  5.     while keys.size > 0
  6.       key = keys.shift
  7.       if next_object.is_a?(Hash)
  8.         next_object = next_object.seph_mdhash_elem(key)
  9.       else
  10.         next_object = next_object[key]
  11.       end
  12.     end
  13.     return next_object
  14.   end
  15.   alias_method :seph_mdhash_setelem, :[]=
  16.   def []=(*args)
  17.     if args.size > 2
  18.       value = args.pop
  19.       keys = args.dup
  20.       next_object = self
  21.       while keys.size > 0
  22.         if keys.size == 1
  23.           if next_object.is_a?(Hash)
  24.             next_object.seph_mdhash_setelem(keys[0], value)
  25.           else
  26.             next_object[key] = value
  27.           end
  28.           break
  29.         end
  30.         key = keys.shift
  31.         next_object[key] = {} unless next_object.has_key?(key)
  32.         next_object = next_object[key]
  33.       end
  34.     else
  35.       seph_mdhash_setelem(*args)
  36.     end
  37.   end
  38.   alias_method :seph_mdhash_hk?, :has_key?
  39.   def has_key?(*keys)
  40.     current_hash = self
  41.     while keys.size > 0
  42.       key = keys.shift
  43.       if current_hash.seph_mdhash_hk?(key)
  44.         current_hash = current_hash[key]
  45.         next
  46.       end
  47.       return false
  48.     end
  49.     return true
  50.   end
  51. end
Expand to see the code.


# Reading m-d hashes
a = {1={2=>{3=>1, 4=>2}, 1=2}, 2=>{3 => 4}}

a -> {1={2=>{3=>1, 4=>2}, 1=2}, 2=>{3 => 4}}
a[1] -> {2=>{3=>1, 4=>2}, 1=2}
a[1, 2] -> {3=>1, 4=>2}
a[1, 2, 3] -> 1
a[1, 2, 4] -> 2
a[1, 1] -> 2
a[2] -> {3 => 4}
a[2][3] -> 4

# Setting m-d hashes (if dimension is not found, creates hash)

a = {}
a[1, 2] = 4
a[1, 3] = 2
a[2, 4] = 6

a -> {1 => {2 => 4, 3 => 2}, 2 => {4 => 6}}

# Checking if m-d has a key

a = {1 => {2 => 4, 3 => 2}, 2 => {4 => 6}}

a.has_key?(1, 2) -> true
a.has_key?(1, 4) -> false
a.has_key?(2) -> true
a.has_key?(2, 4) -> true
a.has_key?(2, 3) -> false


Why I haven't come up with this modification years ago when every script I created had m-d hashes for setup is beyond me, but oh well. No more

  1. if hash.has_key?(key)
  2.   if hash[key].has_key?(key2)
  3.     return hash[key][key2]
  4.   end
  5. end
  6.  
  7. # Now
  8. if has.has_key?(key, key2)
  9.   return hash[key, key2]
  10. end
Expand to see the code.
Seems to be useful.

BTW, here's a simple non GUI dice rolling script.

As a class...
  1. class QtyError < Exception
  2.   def to_s; 'Wrong number of dice, must be above 0' end
  3. end
  4.  
  5. class SidesError < Exception
  6.   def to_s; 'Wrong number of sides, must be above 3' end
  7. end
  8.  
  9. class Dice
  10.   def roll(qty, sides)
  11.     raise QtyError   if qty <= 0
  12.     raise SidesError if sides < 4
  13.     dice = []
  14.     qty.times {dice << (rand sides)+1}
  15.     return dice
  16.   end
  17. end
Expand to see the code.


Then you call it like this...

@dice = Dice.new # Returns #<Dice:0x85ee24c>
@dice.roll 2, 6 # Possibly returns [2, 5]

As a Module...
  1. class QtyError < Exception
  2.   def to_s; 'Wrong number of dice, must be above 0' end
  3. end
  4.  
  5. class SidesError < Exception
  6.   def to_s; 'Wrong number of sides, must be above 3' end
  7. end
  8.  
  9. module Dice
  10.   def self.roll(qty, sides)
  11.     raise QtyError   if qty <= 0
  12.     raise SidesError if sides < 4
  13.     dice = []
  14.     qty.times {dice << (rand sides)+1}
  15.     return dice
  16.   end
  17. end
Expand to see the code.


Then you call it like this...

Dice.roll 2, 6 # Possibly returns [2, 5]
Here's my second add-on for the Array class. It might look kinda repetitive, but you may chose to use just some of these method if you like.

Warning: include_one? method won't work in Ruby 1.8.1, the one included in RGSS 1 and 2. You'd need to create a one? method of your own.

  1. class Array
  2.   def include_all?(*args)
  3.     result = *args
  4.     return result.all? {|arg| self.include?(arg)}
  5.   end
  6.  
  7.   def include_one?(*args)
  8.     result = *args
  9.     return result.one? {|arg| self.include?(arg)}
  10.   end
  11.  
  12.   def include_some?(*args)
  13.     result = []
  14.     args.each {|arg| result << self.include?(arg)}
  15.     result.each {|arg| result.delete arg if !arg}
  16.     return result.size.between?(2,args.size-1)
  17.   end
  18. end
Expand to see the code.
I like the Dice roller. Perhaps a more general name for it could be used for generating random numbers vs. just dice rolls. It could serve more purposes than dice rolling.

--------------

While working on the mouse module, I decided to make a little Button class that basically uses proc objects to perform actions when the mouse if hovering over an area (or not hovering), when the mouse is clicked (left or right) over an object. Infinitely useful for games with Mouse as part of their system.

  1. class Mouse::Button
  2.   attr_accessor :active
  3.   attr_accessor :on_hover
  4.   attr_accessor :off_hover
  5.   attr_accessor :left_trigger
  6.   attr_accessor :right_trigger
  7.   def initialize(active = true)
  8.     @active = active
  9.     @on_hover = nil
  10.     @off_hover = nil
  11.     @left_trigger = nil
  12.     @right_trigger = nil
  13.     @hovering = false
  14.   end
  15.   def active=(active)
  16.     if @active != active
  17.       @active = active
  18.       self.hovering = false unless active
  19.     end
  20.   end
  21.   def self.hovering=(hovering)
  22.     if @hovering != hovering
  23.       @hovering = hovering
  24.       if hovering
  25.         @on_hover.call unless @on_hover == nil
  26.       else
  27.         @off_hover.call unless @off_hover == nil
  28.       end
  29.     end
  30.   end
  31.   def update
  32.     return unless self.active
  33.     self.hovering = hovering?
  34.     if @hovering
  35.       if Mouse.trigger?(0)
  36.         @left_trigger.call unless @left_trigger == nil
  37.       end
  38.       if Mouse.trigger?(1)
  39.         @right_trigger.call unless @right_trigger == nil
  40.       end
  41.     end
  42.   end
  43. end
  44.  
  45. class Mouse::Button::Rect < Mouse::Button
  46.   attr_accessor :rect
  47.   def initialize(rect, active = true)
  48.     @rect = rect
  49.     super(active)
  50.   end
  51.   def hovering?
  52.     return @rect.in_rect?(*Mouse.position)
  53.   end
  54. end
  55.  
  56. class Mouse::Button::Circ < Mouse::Button
  57.   attr_accessor :circ
  58.   def initialize(circ, active = true)
  59.     @circ = circ
  60.     super(active)
  61.   end
  62.   def hovering?
  63.     return @circ.in_circ?(*Mouse.position)
  64.   end
  65. end
  66.  
  67. class Mouse::Button::Bitmap < Mouse::Button::Rect
  68.   attr_accessor :x, :y, :bitmap
  69.   def initialize(x, y, bitmap, active = true)
  70.     @x, @y = x, y
  71.     @bitmap = bitmap
  72.     super(Rect.new(x, y, bitmap.width, bitmap.height), active)
  73.   end
  74.   def x=(x)
  75.     if @x != x
  76.       @x = x
  77.       @rect.set(@x, @rect.y, @rect.width, @rect.height)
  78.     end
  79.   end
  80.   def y=(y)
  81.     if @y != y
  82.       @y = y
  83.       @rect.set(@rect.x, @y, @rect.width, @rect.height)
  84.     end
  85.   end
  86.   def bitmap=(bitmap)
  87.     if @bitmap != bitmap
  88.       @bitmap = bitmap
  89.       @rect.set(@rect.x, @rect.y, @bitmap.width, @bitmap.height)
  90.     end
  91.   end
  92.   def hovering?(x, y)
  93.     return false unless super(x, y)
  94.     mx, my = *Mouse.position
  95.     return @bitmap.get_pixel(mx - @x, my - @y).alpha != 0
  96.   end
  97. end
Expand to see the code.

Required classes:
  1. class Circle
  2.   attr_accessor :center_x, :center_y, :radius
  3.   def initialize(cx, cy, rad)
  4.     @center_x = cx
  5.     @center_y = cy
  6.     @radius   = rad
  7.   end
  8.   def diameter
  9.     return @radius * 2
  10.   end
  11.   def dia ; return diameter ; end
  12.   def circumference
  13.     return Math::PI * dia
  14.   end
  15.   def circ ; return circumference ; end
  16.   def perimeter ; return circumference ; end
  17.   def per ; return circumference ; end
  18.   def area
  19.     return Math::PI * @radius ** 2
  20.   end
  21.   def in_circ?(x, y)
  22.     return Math.hypot((x - @x).abs, (y - @y).abs) < @radius
  23.   end
  24. end
  25.  
  26. class Rect
  27.   def in_rect?(x, y)
  28.     return x.between?(@x, @x + @width) && y.between?(@y + @height)
  29.   end
  30. end
Expand to see the code.


Right now you can create 3 types of buttons; Rectangle, Circle or Bitmap; which basically just define a region the mouse must be within. The first two are pretty straight forward and just use some geometry. The Bitmap button lets you set a bitmap object that it uses to check pixels. The mouse must be over a pixel with a alpha value over 0 to be considered hovering. Its also uses the Rect button as a parent to first check if the mouse is within the bitmaps area.

Testing them out now making a Sphere Break minigame.
SephirothSpawn wrote:
I like the Dice roller. Perhaps a more general name for it could be used for generating random numbers vs. just dice rolls. It could serve more purposes than dice rolling.

--------------

While working on the mouse module, I decided to make a little Button class that basically uses proc objects to perform actions when the mouse if hovering over an area (or not hovering), when the mouse is clicked (left or right) over an object. Infinitely useful for games with Mouse as part of their system.

  1. class Mouse::Button
  2.   attr_accessor :active
  3.   attr_accessor :on_hover
  4.   attr_accessor :off_hover
  5.   attr_accessor :left_trigger
  6.   attr_accessor :right_trigger
  7.   def initialize(active = true)
  8.     @active = active
  9.     @on_hover = nil
  10.     @off_hover = nil
  11.     @left_trigger = nil
  12.     @right_trigger = nil
  13.     @hovering = false
  14.   end
  15.   def active=(active)
  16.     if @active != active
  17.       @active = active
  18.       self.hovering = false unless active
  19.     end
  20.   end
  21.   def self.hovering=(hovering)
  22.     if @hovering != hovering
  23.       @hovering = hovering
  24.       if hovering
  25.         @on_hover.call unless @on_hover == nil
  26.       else
  27.         @off_hover.call unless @off_hover == nil
  28.       end
  29.     end
  30.   end
  31.   def update
  32.     return unless self.active
  33.     self.hovering = hovering?
  34.     if @hovering
  35.       if Mouse.trigger?(0)
  36.         @left_trigger.call unless @left_trigger == nil
  37.       end
  38.       if Mouse.trigger?(1)
  39.         @right_trigger.call unless @right_trigger == nil
  40.       end
  41.     end
  42.   end
  43. end
  44.  
  45. class Mouse::Button::Rect < Mouse::Button
  46.   attr_accessor :rect
  47.   def initialize(rect, active = true)
  48.     @rect = rect
  49.     super(active)
  50.   end
  51.   def hovering?
  52.     return @rect.in_rect?(*Mouse.position)
  53.   end
  54. end
  55.  
  56. class Mouse::Button::Circ < Mouse::Button
  57.   attr_accessor :circ
  58.   def initialize(circ, active = true)
  59.     @circ = circ
  60.     super(active)
  61.   end
  62.   def hovering?
  63.     return @circ.in_circ?(*Mouse.position)
  64.   end
  65. end
  66.  
  67. class Mouse::Button::Bitmap < Mouse::Button::Rect
  68.   attr_accessor :x, :y, :bitmap
  69.   def initialize(x, y, bitmap, active = true)
  70.     @x, @y = x, y
  71.     @bitmap = bitmap
  72.     super(Rect.new(x, y, bitmap.width, bitmap.height), active)
  73.   end
  74.   def x=(x)
  75.     if @x != x
  76.       @x = x
  77.       @rect.set(@x, @rect.y, @rect.width, @rect.height)
  78.     end
  79.   end
  80.   def y=(y)
  81.     if @y != y
  82.       @y = y
  83.       @rect.set(@rect.x, @y, @rect.width, @rect.height)
  84.     end
  85.   end
  86.   def bitmap=(bitmap)
  87.     if @bitmap != bitmap
  88.       @bitmap = bitmap
  89.       @rect.set(@rect.x, @rect.y, @bitmap.width, @bitmap.height)
  90.     end
  91.   end
  92.   def hovering?(x, y)
  93.     return false unless super(x, y)
  94.     mx, my = *Mouse.position
  95.     return @bitmap.get_pixel(mx - @x, my - @y).alpha != 0
  96.   end
  97. end
Expand to see the code.

Required classes:
  1. class Circle
  2.   attr_accessor :center_x, :center_y, :radius
  3.   def initialize(cx, cy, rad)
  4.     @center_x = cx
  5.     @center_y = cy
  6.     @radius   = rad
  7.   end
  8.   def diameter
  9.     return @radius * 2
  10.   end
  11.   def dia ; return diameter ; end
  12.   def circumference
  13.     return Math::PI * dia
  14.   end
  15.   def circ ; return circumference ; end
  16.   def perimeter ; return circumference ; end
  17.   def per ; return circumference ; end
  18.   def area
  19.     return Math::PI * @radius ** 2
  20.   end
  21.   def in_circ?(x, y)
  22.     return Math.hypot((x - @x).abs, (y - @y).abs) < @radius
  23.   end
  24. end
  25.  
  26. class Rect
  27.   def in_rect?(x, y)
  28.     return x.between?(@x, @x + @width) && y.between?(@y + @height)
  29.   end
  30. end
Expand to see the code.


Right now you can create 3 types of buttons; Rectangle, Circle or Bitmap; which basically just define a region the mouse must be within. The first two are pretty straight forward and just use some geometry. The Bitmap button lets you set a bitmap object that it uses to check pixels. The mouse must be over a pixel with a alpha value over 0 to be considered hovering. Its also uses the Rect button as a parent to first check if the mouse is within the bitmaps area.

Testing them out now making a Sphere Break minigame.


I think a better approach than subclassing for each type is creating an "area" attr that can be set to a Bitmap or to an object with method "inside?(x,y)". If the area is a bitmap, you treat it as a bitmap, otherwise just call the inside? method. That way you can change the button "type" anytime.
Not a bad idea, never thought of it.

  1. class Mouse::Button
  2.   attr_reader   :area
  3.   attr_reader   :bitmap
  4.   attr_reader   :active
  5.   attr_accessor :on_hover
  6.   attr_accessor :off_hover
  7.   attr_accessor :left_trigger
  8.   attr_accessor :right_trigger
  9.   def initialize(area, active = true, procs = {})
  10.     @area = area
  11.     @bitmap = nil
  12.     @active = active
  13.     instances = [@on_hover, @off_hover, @left_trigger, @right_trigger]
  14.     keys = ['on_hov', 'off_hov', 'l_trig', 'r_trig']
  15.     for i in 0...instances.size
  16.       instances[i] = procs.has_key?(keys[i]) ? procs[keys[i]] : nil
  17.     end
  18.     @hovering = false
  19.   end
  20.   def area=(area)
  21.     if @area != area
  22.       @area = area
  23.       if @bitmap != nil && @area.is_a?(Rect)
  24.         @area.set(@area.x, @area.y, @bitmap.width, @bitmap.height)
  25.       end
  26.     end
  27.     self.hovering = hovering?
  28.   end
  29.   def bitmap=(bitmap)
  30.     if @bitmap != bitmap
  31.       @bitmap = bitmap
  32.       unless @area.is_a?(Rect)
  33.         @area = Rect.new(0, 0, @bitmap.width, @bitmap.height)
  34.       else
  35.         @area.set(@area.x, @area.y, @bitmap.width, @bitmap.height)
  36.       end
  37.     end
  38.     self.hovering = hovering?
  39.   end
  40.   def active=(active)
  41.     if @active != active
  42.       @active = active
  43.       self.hovering = false unless active
  44.     end
  45.   end
  46.   def self.hovering=(hovering)
  47.     if @hovering != hovering
  48.       @hovering = hovering
  49.       if hovering
  50.         @on_hover.call unless @on_hover == nil
  51.       else
  52.         @off_hover.call unless @off_hover == nil
  53.       end
  54.     end
  55.   end
  56.   def hovering?
  57.     mx, my = *Mouse.position
  58.     if @area.respond_to(:inside?)
  59.       return false unless @area.inside?(mx, my)
  60.     end
  61.     if @bitmap != nil
  62.       if @area.respond_to?(:x) && @area.repond_to?(:y)
  63.         ax, ay = @area.x, @area.y
  64.       else
  65.         ax, ay = 0, 0
  66.       end
  67.       return false unless @bitmap.get_pixel(mx - ax, my - ay).alpha > 0
  68.     end
  69.     return true
  70.   end
  71.   def update
  72.     return unless self.active
  73.     self.hovering = hovering?
  74.     if @hovering
  75.       if Mouse.trigger?(0)
  76.         @left_trigger.call unless @left_trigger == nil
  77.       end
  78.       if Mouse.trigger?(1)
  79.         @right_trigger.call unless @right_trigger == nil
  80.       end
  81.     end
  82.   end
  83. end
Expand to see the code.


I like it.
Hope you won't mind, I remade that Button class, I think my version is easier to use.. you just set the "area" attribute with something that has and "inside?" method, or "x" and "y" methods and a "get_pixel" or "width" and "height", or even anything with a "bitmap" attr that can be used to get the pixels.
That is, the area could be a Sprite, a Bitmap with extra "x" and "y" methods, a Rect... or if you have another kind of shape that should use a specific algorithm, you just define the "inside?(x,y)" method for it.

  1.  
  2. #==============================================================================
  3. # ** Mouse::Button
  4. #------------------------------------------------------------------------------
  5. # Author: Gustavo Bicalho
  6. # Date: 2010-04-10
  7. # MACL Mouse Module Required
  8. #==============================================================================
  9.  
  10. class Mouse::Button
  11.   attr_accessor :area
  12.   attr_accessor :active
  13.  
  14.   attr_accessor :on_hover
  15.   attr_accessor :on_leave
  16.   attr_accessor :on_left_click
  17.   attr_accessor :on_right_click
  18.  
  19.   def initialize(area, active = true)
  20.     raise "area is #{area}" if !area
  21.     @area = area
  22.     @active = active
  23.     @hover = hover?
  24.   end
  25.  
  26.   def hover?
  27.     return false unless self.active
  28.     mx, my = *Mouse.position
  29.  
  30.     if @area.respond_to?(:inside?)
  31.       return @area.inside?(mx, my)
  32.     end
  33.  
  34.     if !(@area.respond_to?(:x) && @area.respond_to?(:y))
  35.       return false # Can't calculate position
  36.     end
  37.  
  38.     ax, ay = [email protected], [email protected] # relative mouse position
  39.  
  40.     bitmap = nil
  41.     if @area.respond_to?(:get_pixel)
  42.       bitmap = @area # ok, we'll use the get_pixel method of the area
  43.     elsif @area.respond_to?(:bitmap) && @area.bitmap.respond_to?(:get_pixel)
  44.       bitmap = @area.bitmap # we'll use the get_pixel of the bitmap of the area
  45.     end
  46.  
  47.     return bitmap.get_pixel(ax, ay).alpha > 0 if bitmap != nil
  48.    
  49.     # here we couldn't find any "get_pixel" method, so we try width and height
  50.     if @area.respond_to?(:width) && @area.respond_to?(:height)
  51.       return ax < @area.width && ay < @area.height
  52.     end
  53.    
  54.     # here, the area is completely useless. So we return false
  55.     return false
  56.   end
  57.  
  58.   def update
  59.     if !self.active
  60.       return if !@hover
  61.       @on_leave.call if @on_leave
  62.       @hover = false
  63.       return
  64.     end
  65.  
  66.     h = hover?
  67.    
  68.     # updates hovering status
  69.     if @hover != h
  70.       if @hover
  71.         @on_leave.call if @on_leave
  72.       else
  73.         @on_hover.call if @on_hover
  74.       end
  75.       @hover = h
  76.     end
  77.  
  78.     # checks clicks
  79.     if h
  80.       if Mouse.trigger?(0)
  81.         @on_left_click.call unless @on_left_click == nil
  82.       end
  83.       if Mouse.trigger?(1)
  84.         @on_right_click.call unless @on_right_click == nil
  85.       end
  86.     end
  87.   end
  88.  
  89. end
  90.  
Expand to see the code.


And here's a little test scene for it:
  1.  
  2. class Scene_Test
  3.  
  4.   def initialize
  5.   end
  6.  
  7.   def start_up
  8.     @b_normal = Bitmap.new("Graphics/btn.png")
  9.     @b_hover = Bitmap.new("Graphics/btn_hov.png")
  10.  
  11.     @sprite = Sprite.new
  12.     @sprite.x, @sprite.y = 40, 50
  13.     @sprite.bitmap = @b_normal
  14.    
  15.     @button = Mouse::Button.new(@sprite)
  16.     @button.on_hover = Proc.new { @sprite.bitmap = @b_hover }
  17.     @button.on_leave = Proc.new { @sprite.bitmap = @b_normal }
  18.     @button.on_left_click = Proc.new { $scene = nil }
  19.     @button.on_right_click = Proc.new {
  20.       @sprite.x, @sprite.y = rand(200)+100, rand(200)+100
  21.     }
  22.   end
  23.  
  24.   def clean_up
  25.     @b_normal.dispose
  26.     @b_hover.dispose
  27.     @sprite.dispose
  28.   end
  29.  
  30.   def update
  31.     Mouse.update
  32.     pos = Mouse.position
  33.     @button.update
  34.   end
  35.  
  36.   def main
  37.     start_up
  38.     Graphics.transition
  39.     loop do
  40.       Graphics.update
  41.       Input.update
  42.       update
  43.       break if $scene != self
  44.     end
  45.     Graphics.freeze
  46.     clean_up
  47.   end
  48.  
  49. end
  50.  
Expand to see the code.

Just put something that looks like a button at the Graphics dir with the name "btn.png" and another (different) one with the name "btn_hov.png" to see the hover effect. There's no cursor sprite so you can't test it properly in fullscreen, but hey, it's only an example :P

If you want to add this to the MACL or that HBGE project of yours, I'd be honored 😀

PS: would you review my RGSS Web Kit script, please? XD
Hmm... The only thing is that Bitmaps don't have a x or y instance, and that's only the thing.

The extra methods and differences I have are all control. If you turn a button off, you shouldn't still be hovering and it should call the off_hover method. Which called for the method for setting the hovering instance, to avoid that being in both the update and active= methods. I also kept the area and bitmap different for a speed thing. An extra instance, but relied more on the inside? method in the Rect class instead of checking the mouse position within the bitmaps area. This also allowed Buttons with a bitmap to have a :x and :y instance by having a Rect area property. Slight differences, but I'll work on taking the best of the two.

I am also working on making a Mixin for this, so you don't have to initialize button objects. But instead Sprites with include a button mixin (will have to also rely on the src_rect) but will work without having to create sprites and buttons.

And sure I will take a look over your web kit. Mind you I don't know tons about web-related Ruby, but I can look and do some research while I look over it. At the least I can do is go over your coding practices and formatting. I'll take a look tonight sometime.
SephirothSpawn wrote:
Hmm... The only thing is that Bitmaps don't have a x or y instance, and that's only the thing.

The extra methods and differences I have are all control. If you turn a button off, you shouldn't still be hovering and it should call the off_hover method. Which called for the method for setting the hovering instance, to avoid that being in both the update and active= methods. I also kept the area and bitmap different for a speed thing. An extra instance, but relied more on the inside? method in the Rect class instead of checking the mouse position within the bitmaps area. This also allowed Buttons with a bitmap to have a :x and :y instance by having a Rect area property. Slight differences, but I'll work on taking the best of the two.

I am also working on making a Mixin for this, so you don't have to initialize button objects. But instead Sprites with include a button mixin (will have to also rely on the src_rect) but will work without having to create sprites and buttons.

And sure I will take a look over your web kit. Mind you I don't know tons about web-related Ruby, but I can look and do some research while I look over it. At the least I can do is go over your coding practices and formatting. I'll take a look tonight sometime.


Well, anyone could add the x and y properties to Bitmaps, I thought someone could want to do that to avoid creating a Sprite =P But actually the main idea is to use Sprites.
And if you want a bitmap on the screen and have a button that reacts to an area of the bitmap (like <map> and <area> in html) you just put the bitmap on the screen using a Sprinte or whatever and use Rects (or classes implementing inside?(x,y), which by the way Rects don't) to define those areas. Of course, if you moved the Bitmap you'd need to move the areas together...

About running off_hover when deactivating the button, I just forgot that. Let's change the
  1.  
  2.   def update
  3.     return unless self.active
  4.     [...]
  5.  
Expand to see the code.

to
  1.  
  2.   def update
  3.     if !self.active
  4.       return if !@hover
  5.       @on_leave.call if @on_leave
  6.       @hover = false
  7.       return
  8.     end
  9.     [...]
  10.  
Expand to see the code.


And change the hover? method to return false whenever self.active is false.
I'll make those changes in my original post.

The mixin-button idea sounds a bit weird to me... maybe because I'm used to static languages =P
here are some snippets of code:

Testing whether any key is pressed:
  1. module Input
  2.   def self.all_keys?
  3.     self.update
  4.     self.constants.each{|i|return true if Input.trigger?(eval(i))}
  5.     return false
  6.   end
  7. end
Expand to see the code.

Quote:
loop{break if Input.all_keys?}


Opening the web browser:
  1. module Net
  2.   def self.openurl(url)
  3.     url='http://'<<url if url[0..6]!='http://'
  4.     Thread.new{system("explorer",url)}
  5.   end
  6. end
Expand to see the code.

Quote:
Net.openurl("http://www.hbgames.org")


Converting Array to Hash:
  1. class Array
  2.   def to_hash(val=nil)
  3.     return Hash[*self.collect{|v|[v,val]}.flatten]
  4.   end
  5. end
Expand to see the code.

val is the default value
Quote:
["key1","key2","key3"].to_hash(1)
=> {"key1"=> 1, "key2"=> 1, "key3"=> 1}


This one probably already exists.
  1. class Float<Numeric
  2.   alias :f_round :round unless $@
  3.   def round(r=0)
  4.     eval sprintf("%.#{r}f",self)
  5.   end
  6. end
Expand to see the code.

Quote:
3,14159265.round(3)
=>3,141
Well, what happens when Arrays have multiples of the same value? I think a .to_hash function should be with the indexes as keys, and objects as values. Otherwise some of the information will get lost. Additionally, you aren't just populating a Hash with multiple keys and same value.

  1.  
  2. class Array
  3.   def to_hash(include_nil = false)
  4.     hash = {}
  5.     for i in 0...size
  6.       hash[i] = self[i] if self[i] != nil || include_nil
  7.     end
  8.     return hash
  9.   end
  10. end
Expand to see the code.
Here I posted a few contributions.

  1. class Array
  2.   def which_is?(bool=true)
  3.     return 'No boolean argument provided' unless bool or !bool or bool.nil?
  4.     results = []
  5.     self.each {|v| results << self.index(v) if v == bool}
  6.     return results.empty? ? nil : results
  7.   end
  8. end
  9.  
  10. class Game_Switches
  11.   def [](switch_id)
  12.     if switch_id.is_a? Integer and switch_id <= 5000 and @data[switch_id] != nil
  13.       return @data[switch_id]
  14.     elsif switch_id.is_a? Range and switch_id.first.between?(1, 5000) and
  15.       switch_id.last.between?(1, 5000)
  16.       ary = []
  17.       switch_id.each {|id| ary << (@data[id].nil? ? false : @data[id]) }
  18.       return ary
  19.     end
  20.     return false
  21.   end
  22. end
Expand to see the code.


To test it, use...

$game_switches[2] = true
p $game_switches[1..5]
p $game_switches[1..5].include? true
p $game_switches[1..5].which_is? true

You should see 3 popup windows with the results to those commands.

[hr]

Just in case you need to check if a number or range has always 0 modulus if divided by one or more divisors, here's a script that might help you perform this tedious task in a timely manner. The output would be an array with all the numbers that comply with this if any.

OK, OK, I admit it, it's a weird scriptlet.

  1. module Math::Modulus
  2.   def mods mod, *args
  3.     results = {}
  4.     self.each do |n|
  5.       results[n] = []
  6.       args.each {|m| results[n] << true if n % m == mod}
  7.     end if self.is_a? Range
  8.     if self.is_a? Numeric
  9.       results[self] = []
  10.       args.each {|m| results[self] << true if self % m == mod}
  11.     end
  12.     results.delete_if {|k,v| v.size != args.size}
  13.     end_results, results = results.keys.sort, {}
  14.     return end_results
  15.   end
  16. end
  17.  
  18. class Numeric; include Math::Modulus end
  19.  
  20. class Range; include Math::Modulus end
Expand to see the code.


Script Call Examples:

(1..100).mods 0, 5, 7 #=> [35, 70] The only 2 numbers that leave no modulus behind.
70.mods 0, 5, 7 #=> [70]
60.mods 0, 5, 7 #=> []
A while ago I made a small extension to the Module class to allow quick writing of getter/setter methods for class variables. I used eval to create the method, so I rewrote the functions to not use eval.

  1. class Module
  2.   private
  3.   def class_accessor(*symbols)
  4.     class_reader *symbols
  5.     class_writer *symbols
  6.   end
  7.   def class_reader(*symbols)
  8.     symbols.each do |sym|
  9.       self.class.send(:define_method, sym) {class_variable_get("@@#{sym}")}
  10.     end
  11.     self
  12.   end
  13.   def class_writer(*symbols)
  14.     symbols.each do |sym|
  15.       self.class.send(:define_method, "#{sym}=") {|obj| class_variable_set("@@#{sym}", obj)}
  16.     end
  17.     self
  18.   end
  19.   def class_attr(symbol, writable=false)
  20.     class_reader symbol
  21.     class_writer symbol if writable
  22.   end
  23. end
Expand to see the code.
A small problem I noticed was that RMXP did not recognize terrain tags from events with tileset graphics. This may get in the way of some complicated event system, so I figured I might post this to help others out.

Starting on line 299 of Game_Map, I modified def terrain_tag to include event tile checks. Replace with the code below:

  1. class Game_Map
  2.  
  3.   def terrain_tag(x, y)
  4.     if @map_id != 0
  5.       for i in [2, 1, 0]
  6.         tile_id = data[x, y, i]
  7.         if tile_id == nil
  8.           return 0
  9.         elsif @terrain_tags[tile_id] > 0
  10.           for event in $game_map.events.values
  11.             if event.x == x and event.y == y and event.through == false and event.tile_id != nil and @terrain_tags[event.tile_id] > 0
  12.               return @terrain_tags[event.tile_id]
  13.             end
  14.           end
  15.           return @terrain_tags[tile_id]
  16.         end
  17.       end
  18.     end
  19.     return 0
  20.   end
  21.  
  22. end
Expand to see the code.


There may be errors with priority (I haven't delved deep into that area) but for general layered tiles it should work fine. Hope this helps, and feel free to comment on more efficient ways to rewrite, as it's probably not perfect.
Here's a little snippet to allow seperators in instances of Window_Command, effectively skipping the highlighting. Now I know that this could've been solved better, adjusting the index accordingly and all that, but for what it does compared to the amount of code it'd need, this is the better solution.

  1. class Window_Command < Window_Selectable
  2.   #--------------------------------------------------------------------------
  3.   def cursor_down(wrap = false)
  4.     if (@index < @item_max - @column_max) or (wrap and @column_max == 1)
  5.       skip = (@commands[@index+1] == '') ? 1 : 0
  6.       @index = (@index + skip + @column_max) % @item_max
  7.     end
  8.   end
  9.   #--------------------------------------------------------------------------
  10.   def cursor_up(wrap = false)
  11.     if (@index >= @column_max) or (wrap and @column_max == 1)
  12.       skip = (@commands[@index-1] == '') ? 1 : 0
  13.       @index = (@index - skip - @column_max + @item_max) % @item_max
  14.     end
  15.   end
  16.   #--------------------------------------------------------------------------
  17. end
Expand to see the code.


Done in RMVX - no idea if it'll work in RMXP. For use without any credit whatsoever, of course.

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