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

SephirothSpawn wrote:
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.

...


Couldn't this be done simply with default values? Like so:

  1. MULTI_HASH = Proc.new { |hash, key| hash[key] = Hash.new(&MULTI_HASH) }
  2. @hash = Hash.new(&MULTI_HASH)
  3. @hash[0][2] = 4
  4. print @hash # {0=>{2=>4}}
Expand to see the code.


Haven't tested it, and it could be tricky since MULTI_HASH is recursive. It might be better done as a class with a recursive initializer (again, not tested):

  1. class Multi_Hash
  2.   def initialize(depth = 0, default = nil, &default_block)
  3.     if depth == 0
  4.       super(default, &default_block)
  5.     else
  6.       super do |hash, key|
  7.         hash[key] = Multi_Hash(depth - 1, default, &default_block)
  8.       end
  9.     end
  10.   end
  11.   def has_key?(*args)
  12.     return false if args.size == 0
  13.     return super(args[0]) if args.size == 1
  14.     return self[args.shift].has_key(*args)
  15.   end
  16. end
Expand to see the code.
I have created a snippet which reads the the configurations from the F1 menu and removes game pad support: (Keep going left/right? If this fixes the problem then garbage from a (non-existing?) game pad is the cause)

http://paste-bin.com/view/a84fb1d3 (XP)
http://paste-bin.com/view/5fa9f97f (VX)

Changes in the F1 menu are first added to the registry when the game is closed, so you cannot use the method for checking changes at runtime.

I hope that scripters of input modules will use this information to make their scripts even more awesome :3

*huggles*
Just remember that you can't automatically save Procs with Marshal.dump. (You'll need to write your own _dump method to include such feature.)
Here is a little script which you can use to check for transfer inconsistencies in your project: http://paste-bin.com/view/e5d0d0e3
Yes, I know it is ugly, but I am too lazy to make it pretty.

*hugs*
I made a new F12 reset script which keeps debug mode if on: http://paste-bin.com/view/0e59aa30
What about this?

# XP or VX
exec = game_exe + ($DEBUG ? ' debug' : ' test')
Bad idea since it would cause debug mode to be enabled in VX whenever you press F12. (Maybe it won't be a problem for encrypted games RMVX games)
You are also forgetting a space.

Btw. notice that exec is a Kernel method just like system, but that I can make a local variable using the same name.

*hugs*
# XP or VX
exec = game_exe + ($DEBUG ? ' debug' : $TEST ? ' test' : '')

What space did I forget in any of these proposals?
Generally there's nothing wrong in trying to simplify code, but too many conditionals in one line can clutter code or make it hard to understand. Nonetheless both methods work.
My mistake about the spaces >_>

It looks like it will work just fine (I haven't checked)
It will complicate the snippet unnecessarily, but it is nice that you are trying to experiment with different structures :cute:

*hugs*
Hey guys: Here is a Tool Set script i finally made since i'm using it quite a lot, easier to have in one place !

Originally Made when I started Castlevania 3 years ago; I today compiled all in one place and improved the code I used a tiny bit.

Everything is explained in the Comments, I think you'll like it a lot !

  1. =begin
  2. #===============================================================================
  3. IDE Scripts
  4. by Trebor777
  5. v1.00
  6. 27/09/2010
  7. Set of methods to help working on scripts outside of RM:
  8. .Contain method to extract all the scripts
  9. .to load or require scripts
  10. .Create a console to override "p" dialog
  11. #===============================================================================
  12. =end
  13. #-------------------------------------------------------------------------------
  14. # Require a file, only once, return true if loaded properly
  15. #-------------------------------------------------------------------------------
  16. def require(dll)
  17.   $LOAD_PATH << "./"
  18.   p "Loading... #{dll}"
  19.   Kernel.send(:require,dll)
  20. end
  21. #-------------------------------------------------------------------------------
  22. # Load a file, like require, but can be called again if any change
  23. # return true if loaded properly
  24. #-------------------------------------------------------------------------------
  25. def load(dll)
  26.   $LOAD_PATH << "./"
  27.   p "Loading... #{dll}"
  28.   begin
  29.     Kernel.send(:load,dll)
  30.   rescue => error
  31.     send_error(error)
  32.   end
  33. end
  34. #-------------------------------------------------------------------------------
  35. # Will extract all the scripts in rb files ordered with 3digits, and their name:
  36. # 000_script_name.rb
  37. # TAKES an HASH as argument, allows more flexibility for the parameters,
  38. # and easier to read understand # inspired by ruby 1.9.1
  39. #
  40. # You can skip some scripts by providing an array containing the names of the
  41. # scripts to skip, like this:
  42. #                            extract_scripts({ :except => ["Main"] })
  43. # will extract all the scripts except "Main"
  44. #
  45. # You can provide the name of a folder to extract the script ( will extract at
  46. # the root of the folder if none provided:
  47. #                             extract_scripts({ :folder => "My_scriptfolder/" })
  48. #-------------------------------------------------------------------------------
  49. def extract_scripts(options={})
  50.   except = options[:except] || [] # Define Default Values
  51.   folder = options[:folder] || ""
  52.   id = 0 # Set file ID
  53.   $RGSS_SCRIPTS.each do |script|
  54.     name = script[1] # Extract Script Name
  55.     data = script[3] # Extract Code
  56.     next if except.include? name or name.empty? or data.empty? # Skip invalid values
  57.     filename = sprintf("%03d", id) + "_" + name # Generate base file name
  58.     p "Writing: #{filename}"
  59.     File.open(folder+filename+".rb", "wb") do |file|
  60.       file.write data #Write the code
  61.     end
  62.     id += 1 # Increment file ID
  63.   end
  64. end
  65. #-------------------------------------------------------------------------------
  66. # Load the all the scripts(rb files) from a specific folder, up to id "limit",
  67. # and skipping ids in skip
  68.  
  69. # TAKES an HASH as argument, allows more flexibility for the parameters,
  70. # and easier to read understand # inspired by ruby 1.9.1
  71.  
  72. # Example:
  73. # .Load all from folder in Data/scripts: load_scripts( {:folder => "Data/Scripts/" })
  74. # .Load all from root, but skip number 3 and 45: load_scripts({ :skip => [3,45] })
  75. # .Load all from root, up to script with number 62: load_script({ :limit => 62 })
  76. #-------------------------------------------------------------------------------
  77. def load_scripts(options={})
  78.   skip = options[:skip] || []
  79.   folder = options[:folder] || ""
  80.   begin
  81.     # Load the language selection 1st
  82.     Dir.foreach(folder) do |file|
  83.       file_id = file[0,3].to_i
  84.       break if file_id == options[:limit]
  85.       next if file == "." or file == ".." or File.extname(file) != ".rb" or skip.include?(file_id)
  86.       r = load (folder+"#{file}")
  87.       p "Loaded: #{r}"
  88.     end  
  89.   rescue => error
  90.     send_error(error)
  91.   end
  92. end
  93. #-------------------------------------------------------------------------------
  94. if $DEBUG or $TEST
  95.   #-----------------------------------------------------------------------------
  96.   def p(*args) # Output to Console
  97.     args.each { | arg | puts arg.inspect }
  98.   end
  99.   #-----------------------------------------------------------------------------
  100.   def handle
  101.     game="\0"*256
  102.     ini=Win32API.new('kernel32','GetPrivateProfileStringA','pppplp', 'l')
  103.     ini.call('Game','Title','',game,255,".\\Game.ini")
  104.     return Win32API.new('user32','FindWindowEx','llpp','l').call(0,0,nil,game.delete!("\0"))
  105.   end
  106.   #-----------------------------------------------------------------------------
  107.   # Create Console
  108.   #-----------------------------------------------------------------------------
  109.   Win32API.new("kernel32", "AllocConsole", "V", "L").call
  110.   $stdout.reopen("CONOUT$")
  111.   $stdin.reopen('CONIN$')
  112.   Win32API.new("user32", "SetForegroundWindow", "L", "L").call(handle)
  113.   #-----------------------------------------------------------------------------
  114.   # Print error on Console
  115.   #-----------------------------------------------------------------------------
  116.   def send_error(error)
  117.     puts "Error : " + error
  118.     #puts "At : ", caller
  119.     puts "TRACE : " + error.backtrace.join("\n")
  120.     puts " "
  121.     puts " Going to EXIT - Press Enter to Continue - "
  122.     gets if $DEBUG or $TEST
  123.   end
  124. end
Expand to see the code.



With this :) you can edit your code while testing the demo at the same time... :) if you use load_scripts, the edited scripts will be reloaded with F12 without problems, avoid losing time in closing demo, editing, saving, launch demo

Having a console to display your message, in a non blocking way(no dialogs freezing the game), helps a lot too ^^

HAve fun :thumb:
Well thanks a lot trebor. The p method override is a charm. But I don't understad how to edit the code live. can you be a little more especific.
Thanks in advance.
Well if you extract the scripts you want,
and then load them with the methods provided,

While you change your code on the extracted file, you can have the demo runnning :), and just F12 after you save the code, that reset the demo, and reload the extracted files :)
defining/redefining methods on a per object basis....???

Was sleeping and dreamed of rgss coding.... Any-who, in the dream I had an idea to create an "on_Mouse_Over event like thing for some buttons in my windows.

Warning: This spoiler contains dream code which is not to be actually used in an actual project Show
In my dream, my script looked something similar to (note, this is NOT actual code, but a mock-up):
  1. class My_Window < Window_Base
  2.   def initialize
  3.     super
  4.     @button = Sprite.new
  5.     @button.bitmap = Bitmap.new(button.png)
  6.   end
  7. end
Expand to see the code.


Well, instead of setting up an on_Mouse_Over in class Sprite, in my dream, I set an on_Mouse_Over on @button instead, like so:

  1. class My_Window < Window_Base
  2.   def initialize
  3.     super
  4.     @button = Sprite.new
  5.     @button.bitmap = Bitmap.new(button.png)
  6.     set_on_Mouse_Over
  7.   end
  8.  
  9.   def set_on_Mouse_Over
  10.     def @button.on_Mouse_Over
  11.       self.bitmap = Bitmap.new(button_active.png)
  12.     end
  13. end
Expand to see the code.


And lo and behold, if I call @button.on_Mouse_Over, it actually changes the graphic! in this way, I can custom define a method for each declared object seperately!


I may not have explained that very well, but I am still sort of half asleep... Weird how I come up with my best ideas in my sleep and they actually translate successfully to real life.

Another one you can actually insert into a project to test out. Real Code just insert it above main:

  1. class Foo
  2.   def bar
  3.     p "foobar"
  4.   end
  5. end
  6.  
  7. class Scene_Foo
  8.   def initialize
  9.     @foo = Foo.new
  10.     @foo2 = Foo.new
  11.     method_define
  12.   end
  13.  
  14.   def method_define
  15.     def @foo.barstool
  16.       p "Standing"
  17.     end
  18.     def @foo2.bar
  19.       p "drink please"
  20.     end
  21.   end
  22.  
  23.   def main
  24.     @foo.bar       # prints "foobar"
  25.     @foo.barstool  # prints "Standing"
  26.     @foo2.bar      # prints "drink please"
  27.     @foo2.barstool # Crashes with undefined method
  28.   end
  29. end
  30.  
  31. $scene = Scene_Foo.new
  32.  
  33. $scene.main
Expand to see the code.


This opens up a whole new world of possibilities....

Did anyone else know this was possible?

*runs off to get more ideas while sleeping*
Pretty cool, I didn't know that was possible. Usually I would do that by storing Proc objects, which are code blocks.

  1.  
  2. class Button
  3.   attr_accessor : on_mouse_over;
  4. end
  5.  
  6. class Window
  7.   def initialize
  8.     @button = Button.new
  9.     @button.on_mouse_over = Proc.new { |event_info|
  10.       p "hello"
  11.     }
  12.   end
  13.   def test
  14.     @button.on_mouse_over.call(nil)
  15.   end
  16. end
  17.  
  18. Window.new.test # Prints "hello"
  19.  
Expand to see the code.
What you have discovered is Ruby's singleton classes. What you have done with those few lines of code is to implicitly define a singleton class on the @button object and define a method on that class. Singleton classes are awesome, but you have to be careful with them. The only thing I can think of right now is that they can't be Marshal'ed, so you shouldn't use singleton classes in the game objects.

Did you know that you can initialize an object with a block? You could do something like this:

  1. class Button
  2.   def initialize(&block)
  3.     @block = block
  4.   end
  5.   def on_click
  6.     @block.call
  7.   end
  8. end
  9.  
  10. $button = Button.new { p "Button pressed" }
  11. $button.on_click
Expand to see the code.


When you prefix the last argument with &, that variable is a Proc object containing the passed block. This isn't the only way to use the block, of course, but it is the best way to store the block for later use.

One excellent thing you could do with this is have the button's event modify things in the scene, like so:

  1. class Scene_Test
  2.   # [...]
  3.   def main_window
  4.     # [...]
  5.     @command_window = Window_Command.new(160, s)
  6.     @command_window.visible = false
  7.     @command_window.active = false
  8.     @button = Button.new do
  9.       @command_window.active = true
  10.       @command_window.visible = true
  11.     end
  12.   end
  13.   # [...]
  14. end
Expand to see the code.
Rey, That is awesome. Thank you for explaining all of that. It makes much more sense now, really. And I will definitely be putting something like that to use. You see, I'm redoing the window class and rearranging the window-skin to use scroll bars instead of just displaying an arrow when the window can scroll, among other things. what you have shown me, i think will make some things a little easier on me.

Again, Thank you.
I don't think you can efficiently remove the arrows from the window class, but you can add a scroll bar. Scrolling is based on window.ox and window.oy . The arrows appear when the bitmap is larger than the window (minus the margin), so to remove them you'd either have to rewrite the Window class without arrows or intercept #contents so that the "real" contents are never too big and the pretend contents are written to the window. The first solution is pretty hard (though I have such a rewrite if you're interested), and the second solution would end up being really inefficient.
I'm already using Selwyn's rewrite and modifying it to work. so far so good, though I did have to make a few corrections as he made a few errors when he cut up the windowskin. I already got it to work, almost, just have to add actual mouse scrolling and a few other features to the windowskin similar to rmvx.
Here is something I've noticed more and more in the ruby world :) and it's really helpful and very flexible for coders and makes code easier to read as well!
Maybe some people already figured it:

So instead of using the classical way of using arguments.
  1.  
  2. def my_method(arg1= "this", arg2 = "that", etc... )
  3.   # do stuff with arg1
  4. end
  5.  
Expand to see the code.


here is a more flexible one, using hashes! Although it's mostly useful for the initialize method.

  1.  
  2. class Test_Arg
  3.   def initialize(options = {})
  4.     @a = options[:a] || "default_value"
  5.     @b = options[:whatever] || "b default"
  6.   end
  7. end
  8.  
  9. # Several example showing the flexibility it offers
  10. # this makes easier for people to identify what the parameter is as well
  11. a = TestArg.new
  12. b = TestArg.new(:a => "plop")
  13. c = TestArg.new(:whatever => "bebop")
  14. d = TestArg.new(:whatever => "abba", :a => "revolution")
  15.  
  16.  
Expand to see the code.

Hope it helps ! 😀
Yeah, definately will be helpful... reminds me of the way of using arrays to decide between multiple arguments, while obviously the purpose is different (still, the array will save you the few milliseconds of processing that hashes eat up... while it's probably not the best coding style).
  1. def example(*args)
  2.   if args.size == 2
  3.     args.each{ |argument| p argument }
  4.   else
  5.     p 'more or less than two arguments have been passed'
  6.   end
  7. end
Expand to see the code.

Just for completeness' sake ;)
Actually, I've heard that hashes are faster than arrays in Ruby. It sort of makes sense when you think of all the different access styles from the array[] method, and how arrays might have to recreate the entire array at O(n) to resize whenever a value is added, while a hash only needs to compute the hash at O(1).
Hm... well, can't say I tested it myself or anything, so I can't really say anything... might do some testing later (if I remember it :blank: )
More or less completely unrelated, I put a fancy little snippet together that allows to round any Float to the nearest number on a base you can choose yourself. For example, let's say you want to round to the half numbers, choose a base of 0.5 - for example, 4.345674.round_to_nearest(0.5) will return 4.5.
The other two methods are for rounding up or down, respective to the .ceil and .floor methods.

  1. class Float < Numeric
  2.  
  3.   def round_to_nearest(base = 1.0)
  4.     self - self % base + (self >= (self - self % base + base / 2.0) ? base : 0.0)
  5.   end
  6.  
  7.   def floor_to_nearest(base = 1.0)
  8.     self - self % base
  9.   end
  10.  
  11.   def ceil_to_nearest(base = 1.0)
  12.     self - self % base + base
  13.   end
  14.  
  15. end
Expand to see the code.

If you don't set a parameter, they will give you a equivalent to Float.round (or .ceil or .floor), however without the option to round to certain floating point digits. It should therefore be a tad faster than the original .round, however I wouldn't suggest using it as a replacement for the default for compatibility and readability reasons.

Hope this will be useful to someone.
I wonder if anyone besides me ever does the little things anymore... but hey, at least someone does ;o

This time I got a custom z-level script for events, originating on a request from Peri that vanished by the time I'm writing this. Well, here you go:
Initial version - use the one in ForeverZer0's next post instead Show
  1. class Game_Event < Game_Character
  2.   #--------------------------------------------------------------------------
  3.   attr_reader :event
  4.   #--------------------------------------------------------------------------
  5. end
  6.  
  7.  
  8. class Game_Character
  9.   #--------------------------------------------------------------------------
  10.   alias zleveladjust_screenz screen_z
  11.   def screen_z(height = 0)
  12.     if self.is_a?(Game_Event) && self.event.name[/z(\d{1,})/i] != nil && !@always_on_top
  13.       z = self.event.name[/z(\d{1,})/i].gsub(/z/, '').to_i
  14.       return z
  15.     end
  16.     zleveladjust_screenz(height = 0)
  17.   end
  18.   #--------------------------------------------------------------------------
  19. end
Expand to see the code.


By putting for example z50 in the event name, you will set a custom z-level of 50 for the event, with the default being 200. You can actually do al kind of weird combinations for the event name, for example "lshgishgpz567holjsdn", which will set the z-level to 567. This might be good or not, but it's the easiest and leat limiting way.

Another thing I should mention is that the 'Always on Top' flag will overwrite the custom z-level setting and set the event to the default 999. If you don't flag it, however, you can set values higher than that to make events appear even over events flagged as 'Always on Top'. That might not seem logical, and is only intended for special appliances - you should stick to values from 0 to 998 normally.
That's way more complicated than it need to be. You don't need to create an attr_reader in Game_Event, then have the actual code in Game_Character, and then use an "if" to make sure its a Game_Event again. You should just keep the whole thing in Game_Event. After that, your doing the same RegEx, which are hard on performance, twice in a row, and it is overly complicated. And on top of all of that, the "height=0" in the alias call is not going to work. The code should look something like this:

  1. class Game_Event < Game_Character
  2.  
  3.   alias zleveladjust_screenz screen_z
  4.   def screen_z(height = 0)
  5.     @event.name =~ /[Zz]([0-9]+)/
  6.     unless @always_on_top && $1 != nil
  7.       return $1.to_i
  8.     end
  9.     return zleveladjust_screenz(height)
  10.   end
  11. end
Expand to see the code.
Yeah, that's indeed a lot simpler... the height thing I totally overlooked (and I don't think it gave me an error in the past... well, don't really have anything to test it at all, so... :/ ), and to be honest, I totally confused the order of the classes and thought Game_Event was the superclass of Game_Character... >> Well, it was late, I suppose... >>"

Thanks for those hints there.
It's been awhile since I posted a script. So have a quickie.

  1. # avarisc's Tack (a.k.a. auto-alias)                             v1.0 - 7/31/14
  2. ################################################################################
  3. class Object
  4.     def tack_before(symbol, id) # requires code block
  5.         alias_method(("tack_before_" + symbol.to_s + "_" + id).to_sym, symbol) unless method_defined?(("tack_before_" + symbol.to_s  + "_" + id).to_sym)
  6.         send :define_method, symbol do
  7.             send ("tack_before_" + symbol.to_s + "_" + id).to_sym
  8.             yield
  9.         end
  10.     end
  11.     def tack_after(symbol, id) # requires code block
  12.         alias_method(("tack_after_" + symbol.to_s + "_" + id).to_sym, symbol) unless method_defined?(("tack_before_" + symbol.to_s  + "_" + id).to_sym)
  13.         send :define_method, symbol do
  14.       yield
  15.             send ("tack_after_" + symbol.to_s + "_" + id).to_sym
  16.         end
  17.     end
  18. end
Expand to see the code.


I get tired of juggling/managing aliases. I have my own alternatives in larger projects, but for tinkering in a clean sandbox, I always end up reimplementing it. This reduces alias tacking to 1 line.
Usage example:

  1.  
  2. # automatically call Map_Awesomizer.awesomize every time after spriteset map initializes
  3. class Spriteset_Map
  4.   tack_after :initialize, "my_awesome_script" do Map_Awesomizer.awesomize() end
  5. end
Expand to see the code.



If you don't get what this does, the miniscript allows the example to do exactly the same thing as this:

  1.  
  2. # automatically call Map_Awesomizer.awesomize every time after spriteset map initializes
  3. class Spriteset_Map
  4.   alias_method(:my_awesome_script_initialize, :initialize)
  5.   def initialize
  6.     my_awesome_script_initialize
  7.     Map_Awesomizer.awesomize
  8.   end
  9. end
  10.  
Expand to see the code.


Not the biggest change in the world. But if your code tends to squirm and tendril its way across all the various classes requiring a few dozen or more hooks, this will trim the code size significantly. And its faster.

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