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

What I'm saying is, when I test play, $TEST == false, and $DEBUG == false. There is no indication the editor has set any debug variables at all.
Here's a snippet I made based on Main class to help me get some debugging info that could make my life easier. I don't know if I really had to do this anyway. I hope you'll find it useful, if not, eh, well, it may be forgotten in the sands of time...

  1. begin
  2.   Graphics.freeze
  3.   $scene = Scene_Title.new
  4.   $scene.main while $scene != nil
  5.   Graphics.transition(30)
  6. #=begin
  7. rescue => error
  8.   a = Dir.getwd
  9.   aw = !FileTest.exists?(a+'/ErrorsLog.txt') ? 'w': 'a'
  10.   log = File.open(a+'/ErrorsLog.txt', aw)
  11.   time = Time.new
  12.   year = time.strftime('%Y')
  13.   month = time.strftime('%b')
  14.   day = time.strftime('%d')
  15.   hour = time.strftime('%H')
  16.   min = time.strftime('%M')
  17.   sec = time.strftime('%S')
  18.   logtime = "#{year} #{month} #{day} #{hour}:#{min}:#{sec}"
  19.   log.puts '---', logtime, 'Error! '+error, '---', error.backtrace.join("\n")
  20.   log.close
  21. #=end
  22. rescue Errno::ENOENT
  23.   filename = $!.message.sub("No such file or directory - ", "")
  24.   print "Unable to find file #{filename}."
  25. end
Expand to see the code.


I obviously included the #=begin and #=end just in case you feel like it should be commented out once it doesn't need to be debug anymore.

Edit:

OK, you could also paste this:

  1. begin
  2.   Graphics.freeze
  3.   $scene = Scene_Title.new
  4.   $scene.main while $scene != nil
  5.   Graphics.transition(30)
  6. rescue Exception => error
  7.   KyoLog.write(error)
  8. rescue Errno::ENOENT
  9.   filename = $!.message.sub("No such file or directory - ", "")
  10.   print "Unable to find file #{filename}."
  11. end
Expand to see the code.


But you'll need to paste this module above Main.

  1. class Game_Event;  attr_reader :map_id;  end
  2.  
  3. module KyoLog
  4.   CodeList = {
  5.     101 => 'Show Text',                  102 => 'Show Choices',
  6.     402 => 'When [**]',                  403 => 'When Cancel',
  7.     103 => 'Input Number',               104 => 'Xhange Text Options',
  8.     105 => 'Button Input Processing',    106 => 'Wait',
  9.     111 => 'Conditional Branch',         411 => 'Else',
  10.     112 => 'Loop',                       413 => 'Repeat Above',
  11.     113 => 'Break Loop',                 115 => 'Exit Event Processing',
  12.     116 => 'Erase Event',                117 => 'Call Common Event',
  13.     118 => 'Label',                      119 => 'Jump to Label',
  14.     121 => 'Control Switches',           122 => 'Control Variables',
  15.     123 => 'Control Self Switch',        124 => 'Control Timer',
  16.     125 => 'Change Gold',                126 => 'Change Items',
  17.     127 => 'Change Weapons',             128 => 'Change Armor',
  18.     129 => 'Change Party Member',        131 => 'Change Windowskin',
  19.     132 => 'Change Battle BGM',          133 => 'Change Battle End ME',
  20.     134 => 'Change Save Access',         135 => 'Change Menu Access',
  21.     136 => 'Change Encounter',           201 => 'Transfer Player',
  22.     202 => 'Set Event Location',         203 => 'Scroll Map',
  23.     204 => 'Change Map Settings',        205 => 'Change Fog Color Tone',
  24.     206 => 'Change Fog Opacity',         207 => 'Show Animation',
  25.     208 => 'Change Transparent Flag',    209 => 'Set Move Route',
  26.     210 => "Wait for Move's Completion", 221 => 'Prepare for Transition',
  27.     222 => 'Execute Transition',         223 => 'Change Screen Color Tone',
  28.     224 => 'Screen Flash',               225 => 'Screen Shake',
  29.     231 => 'Show Picture',               232 => 'Move Picture',
  30.     233 => 'Rotate Picture',             234 => 'Change Picture Color Tone',
  31.     235 => 'Erase Picture',              236 => 'Set Weather Effects',
  32.     241 => 'Play BGM',                   242 => 'Fade Out BGM0',
  33.     245 => 'Play BGS',                   246 => 'Fade Out BGS',
  34.     247 => 'Memorize BGM/BGS',           248 => 'Restore BGM/BGS',
  35.     249 => 'Play ME',                    250 => 'Play SE',
  36.     251 => 'Stop SE',                    301 => 'Battle Processing',
  37.     601 => 'If Win',                     602 => 'If Escape',
  38.     603 => 'If Lose',                    302 => 'Shop Processing',
  39.     303 => 'Name Input Processing',      311 => 'Change HP',
  40.     312 => 'Change SP',                  313 => 'Change State',
  41.     314 => 'Recover All',                315 => 'Change EXP',
  42.     316 => 'Change Level',               317 => 'Change Parameters',
  43.     318 => 'Change Skills',              319 => 'Change Equipment',
  44.     320 => 'Change Actor Name',          321 => 'Change Actor Class',
  45.     322 => 'Change Actor Graphic',       331 => 'Change Enemy HP',
  46.     332 => 'Change Enemy SP',            333 => 'Change Enemy State',
  47.     334 => 'Enemy Recover All',          335 => 'Enemy Appearance',
  48.     336 => 'Enemy Transform',            337 => 'Show Battle Animation',
  49.     338 => 'Deal Damage',                339 => 'Force Action',
  50.     340 => 'Abort Battle',               351 => 'Call Menu Screen',
  51.     352 => 'Call Save Screen',           353 => 'Game Over',
  52.     354 => 'Return to Title Screen',     355 => 'Script',
  53.     404 => 'Branch End - Choices',       604 => 'Branch End Battle Processing',
  54.     401 => '  Text Line',                  0 => '',
  55.   }
  56.   D, Line = Dir.getwd, '-----'
  57.   @aw = !FileTest.exists?(D+'/ErrorsLog.txt') ? 'w': 'a'
  58.   @e = []
  59.   time  = Time.new
  60.   year  = time.strftime('%Y')
  61.   month = time.strftime('%b')
  62.   day   = time.strftime('%d')
  63.   hour  = time.strftime('%H')
  64.   min   = time.strftime('%M')
  65.   sec   = time.strftime('%S')
  66.   @logtime = "#{year} #{month} #{day} #{hour}:#{min}:#{sec}"
  67.   def self.write(error, type='An error occurred!')
  68.     log = File.open(D+'/ErrorsLog.txt', @aw)
  69.     log.puts Line, @logtime, type, error
  70.     log.puts error.backtrace.join("\n"), Line
  71.     log.close
  72.   end
  73.  
  74.   def self.write_events_info
  75.     e  = File.open(D+'/Events.txt', @aw)
  76.     gp, gm = $game_player, $game_map.events
  77.     x, y   = $data_system.start_x, $data_system.start_y
  78.     e.puts Line, @logtime
  79.     e.puts "Player's Starting Position - X: #{x}, Y: #{y}"
  80.     e.puts "Player's Current Position  - X: #{gp.x}, Y: #{gp.y}"
  81.     e.puts 'Map Events Keys Size = ' + gm.keys.size.to_s
  82.     for n in 1..gm.size
  83.       @e.push "Map #{gm[n].map_id}, ID: #{gm[n].id},"+
  84.               "X: #{gm[n].x}, Y: #{gm[n].y}, Value: #{gm[n]}, "+
  85.               "Trigger: #{gm[n].trigger}\n\n Commands List:\n"
  86.       for m in 0...gm[n].list.size
  87.         c = gm[n].list[m].code;  l = CodeList[c]
  88.         com = c != 0 ? 'command_' : ' '
  89.         command = c != 0 ? "  #{com}#{c} - #{l}" : ''
  90.         @e.push command
  91.       end
  92.     end
  93.     e.puts "\n", @e.join("\n"), Line, Line
  94.     e.close
  95.     @e.clear
  96.   end
  97. end
Expand to see the code.


Here's a sample of the data stored in the ErrorsLog.txt log after exiting the program abruptly due to some (stupid) errors I committed while getting a script ready to be published.

Content Hidden Show
Quote:
---
2009 Apr 10 18:29:40
Error! undefined method `z=' for nil:NilClass
---
Section089:383:in `main'
Section093:10
---
2009 Apr 10 18:33:52
Error! undefined method `[]' for nil:NilClass
---
Section089:225:in `refresh'
Section089:239:in `update'
Section089:431:in `update'
Section089:403:in `processing'
Section089:400:in `loop'
Section089:405:in `processing'
Section089:394:in `main'
Section093:10


If the RPG Maker had included some debugging / error logging class this would have been easier, but it isn't something we couldn't handle, is it?

Edit...

I included another method that would log some basic info regarding the events present on a map...
Here's another good Backup Utility for RPG Maker. It's completely based on Ruby (and its C implementations obviously) but it still runs on both of the most recent versions of the maker.

First get FileUtils, it's quite useful, even on the RPG Maker XP or VX.

Download
(This script is free software.)

Paste is above Main.

Just include this simple wrap module above Main.

  1. module KyoBackup
  2.   time   = Time.new
  3.   year   = time.strftime('%Y')
  4.   month = time.strftime('%m')
  5.   day    = time.strftime('%d')
  6.   hour   = time.strftime('%H')
  7.   min    = time.strftime('%M')
  8.   sec    = time.strftime('%S')
  9.   @logtime = "#{year}#{month}#{day} #{hour}#{min}#{sec}"
  10.   Backup = 'Backup'
  11.   BUT = " #{@logtime}"
  12.   BN   = File.basename(Dir.getwd)
  13.   DN   = File.dirname(Dir.getwd)
  14.   S    = '/'
  15.   DEST = DN+S+Backup+S+BN+' '+BUT
  16.  
  17.   def self.project
  18.      FileUtils.mkdir(DN+S+Backup) if !File.exists?(DN+S+Backup)
  19.      FileUtils.cp_r(Dir.getwd, DEST)
  20.      print 'Backup ended successfully!'
  21.   end
  22. end
Expand to see the code.


...and include this line in Main, just below "begin".

KyoBackup.project

And you'll see a pop up window telling you that it already backed up your project!!!

The directory path is the following:

If your projects are stored in...

C:/The full path to your current projects working directory/Name of your project

Then the Backup folder should be found here...

C:/The full path to your current projects working directory/Backup/Name of your project Date Time

NOTES:

On VX you might get some error message popping up regarding some file requirement (require 'etc').

There are about 3 lines that mention 'etc' or Etc., comment them out and it'll work smoothly for sure.
A window to add to your scene, which handles number input.
This window will show the input number screen + text
and return the number.

new window_Input
  1. class Window_Input < Window_Message
  2.  
  3.   def initialize(text, digits)
  4.      super()
  5.      @var_id = 1
  6.      start_input(text, digits)
  7.   end
  8.  
  9.   def start_input(text, digits)
  10.      @old_data = $game_variables[@var_id]
  11.      $game_variables[@var_id] = 0
  12.      $game_temp.message_text = text
  13.      $game_temp.num_input_variable_id = @var_id
  14.      $game_temp.num_input_digits_max = digits
  15.      $game_temp.num_input_start = 1   # from_line
  16.   end
  17.  
  18.   def finished?
  19.      return @input_number_window.nil?
  20.   end
  21.  
  22.   def get
  23.      loop do
  24.         # Update game screen
  25.         Graphics.update
  26.         # Update input information
  27.         Input.update
  28.         # Frame update
  29.         update
  30.         # Abort loop if screen is changed
  31.         if @input_number_window.nil?
  32.            break
  33.         end
  34.      end
  35.      number = $game_variables[@var_id]
  36.      $game_variables[@var_id] = @old_data
  37.      return number
  38.   end
  39.  
  40. end
Expand to see the code.

To use, add a window_input to your scene:

@window = Window_Input.new(text, digits)
@your_number = @window.get
@window.dispose
# no need to update/loop in the scene, just those lines above.
new: getter and setter for class_variables

1. version: with eval
  1.  
  2. class Module
  3.  
  4.  def akkr_reader(*args)
  5.   args.each{ |sym| class_eval("def #{sym}; return @@#{sym}; end;") }
  6.  end
  7.  
  8.  def akkr_writer(*args)
  9.   args.each{ |sym| class_eval("def #(sym}=(value); return @@#{sym}=value; end;") }
  10.  end
  11.  def akkr_accessor(*args)
  12.   akkr_reader(*args)
  13.   akkr_writer(*args)
  14.  end
  15. end
  16.  
Expand to see the code.


2. version: without eval but with more evil
  1. class Module
  2.  
  3.  def akkr_reader(*args)
  4.   args.each{ |sym| define_method(sym) { Object.instance_method(:class).bind(self).call.send(:class_variable_get,"@@#{sym}") } }
  5.  end
  6.  
  7.  def akkr_writer(*args)
  8.    args.each{ |sym| define_method("#{sym}=") { |value| Object.instance_method(:class).bind(self).call.send(:class_variable_set,"@@#{sym}",value) } }
  9.  end
  10.  def akkr_accessor(*args)
  11.   akkr_reader(*args)
  12.   akkr_writer(*args)
  13.  end
  14. end
Expand to see the code.
Shouldn't these new methods for Module class be private? AFAIK attr_reader and attr_writer or attr_accessor are already private in Module...
yes ... you could make it private if you like
Hanmac, you should have precised it was creating a method for instancied object of that class, to access the class variable.

Like so:

  1.  
  2. class Foo
  3.  
  4. @@foo = 2
  5.  
  6. akkr_reader :foo
  7.  
  8. # Do the same as just before.
  9. def foo
  10.  @@foo
  11. end
  12.  
  13. end
  14.  
  15.  
  16. d = Foo.new
  17. d.doo              # => 2
  18.  
Expand to see the code.


As it's a class variable, wouldn't be better to make a Class method instead?
  1.  
  2. Foo.foo  # => 2
  3.  
Expand to see the code.
if you would like to have class methods use:
  1. class << Foo
  2. akkr_reader :a
  3. end
  4.  
  5. Foo.a
Expand to see the code.


PS: the second version need Ruby 1.8.3
That's an interesting little snippet Hanmac ^^
I do not like the name, why is it called akkr_reader? Why not attr_class_reader or something other more intuitive and better self-documenting name? I believe the price for the shorter name is in this case not worth it.

Secondly I find it odd from a design perspective that instance methods have getters and setters which refer to the class variable. It would be more intuitive to have class methods instead. Of course the could be cases where having instance methods return a class variable rather than an instance variable is preferable.
It's not so much that you can create class methods, but more the conceptual meaning of the functionality you provide. Basically, I agree with Trebor777 or at least make its purpose clear in the documentation.

*hugs*
- Zeriab
attr_class_reader is really convoluted, class_reader is probably good enough. I would agree that having it as a class method is preferable,
Equivalent of a OR statement for the same variable:

  1.  
  2. a == 2 or a == 3 or a == "foo"
  3.  
  4. => [2,3,"foo"].include? a
  5.  
Expand to see the code.


Of course only applies for the same kind of condition ( == )
Can be useful to write shorter version if the variable or the values have long names. ;)
Nice find trebor :D

@meustrus:
I agree that name is convoluted, which I believe fits when its an object method. (Sorry about the late reply, I didn't notice your reply before ._.)

*hugs*
- Zeriab
I must share this, because I wrangled with a solution to this problem before just looking it up in the Ruby documentation. Sometimes the RMXP help file's scripting section is really lacking...

You can create a Hash with default values by calling Hash.new(default) or Hash.new {|hash, key| default}. Further documentation. Such functionality isn't available for Array, but I determined that it would be more trouble than it's worth to give it to Arrays; just use Hashes instead if you need default values.
The RMXP help file is generally lacking when it comes to the default ruby stuff.
It is a nice find with a default value constructor based on the key you have found. Something worth remembering

^_^
This ain't much but when I was working on a timer request just now I made it... I'll probably hold onto it for convenience sake.

  1. #===============================================================================
  2. # ** Graphics : Change Frame Rate
  3. #===============================================================================
  4.  
  5. class << Graphics
  6.   #-----------------------------------------------------------------------------
  7.   # * Alias Listings
  8.   #-----------------------------------------------------------------------------
  9.   alias_method :chngframerate_graphics_update,    :update
  10.   #-----------------------------------------------------------------------------
  11.   # * Update
  12.   #-----------------------------------------------------------------------------
  13.   def update
  14.     chngframerate_graphics_update
  15.     if Input.press?(Input::CTRL)
  16.       if Input.trigger?(Input::F5)
  17.         Graphics.frame_rate -= 10
  18.         return
  19.       elsif Input.trigger?(Input::F6)
  20.         Graphics.frame_rate += 10
  21.         return
  22.       elsif Input.trigger?(Input::F7)
  23.         Graphics.frame_rate = 40
  24.         return
  25.       end
  26.     end
  27.   end
  28. end
Expand to see the code.


What it does is allows you to change Graphics.frame_rate by holding CTRL and pressing F5 (decrease), F6 (increase) or F7 (reset to 40).

One thing that bugs me is Enterbrain decided to secure the Graphics.frame_rate value between 0 and 120, which I understand why but it sucks. I tried overwritting/aliasing the method to go beyond 120 just to see what it does but its something more than just doing @frame_rate = n, damn hidden internal methods!


Also, what I posted on the Milliseconds in Timer request...

Interesting find about changing Graphics.frame_rate Show
I learned something new upon testing your request. I wanted to actually test the accuracy of the milliseconds, so I changed Graphics.frame_rate from 40 to 20 to 10 to 1 to 0.1, etc you get the idea, just so I could see the actual milliseconds counting down. Keep in mind, I tested the timer set at 1:00 at all times...

Well, as I started changing Graphics.frame_rate, I noticed the lower it was the higher the timer was and visa versa. For instance, Graphics.frame_rate = 20 would make the timer 2:00 instead of 1:00, and Graphics.frame_rate = 80 would make the timer 0:30... that isn't right! Remember how I said I set the timer at 1:00?

RMXP's frame_rate is supposed to always be 40
RMVX's frame_rate is supposed to always be 60

Many anti-lag scripts I've seen change Graphics.frame_rate to try and speed up the game when it is lagging, which is okay and works sometimes but will affect the Timer and possibly Window_Playtime's time. The solution, you can do a CTRL+SHIFT+F and replace anything that references Graphics.frame_rate with 40 (or 60 for VX), and you won't have to worry about Graphics.frame_rate affecting timed-things.


Go ahead, run the default timer and use this snippet to change your frame rate, you'll see exactly what I'm talking about! The timer's time will jump all over the damn place! Window_Playtime doesn't appear to be effected much, but the Timer is! You might want to keep this in mind when timing things in your own scripts too :P

Use 40 (XP) or 60 (VX) instead of Graphics.frame_rate! Also, never use Time.now for anything outside of checking what the actual time is! If you use Time.now to count-down actual in-game timers, that is a big no-no!

Ask ImmuneEntitiy! He had a Skill Timer script, meaning you have to wait [x] ammount of frames to use certain skills again. What that meant is when a player clicks off-screen and deactivates the window, then comes back his skills are already filled and he can cheat! Its because its checking the *real time* that has lapsed, and not the game's *internal frame time*

Anyways, thats my submission and tip of the day! Enjoy! :thumb:
Actually the timer should be frame_rate independant, and decrease the timer by the time which passed between 2frames not by the number of frames.
Here is a project I have created while playing around.
It removes the comments and indention from Scripts.rxdata and Scripts.rvdata: http://webgel.net/bb/files/Remove_Comments.zip
(No guarantees that it doesn't alter the semantics of the scripts)
Holy cow Zeriab, nice one!!! I've got a whole buttload of scripts in my project so it made a good test, it appears that everything still works fine. For those of you who like to penny-pinch (sort to speak) on your HDD space my old script file was 477 KB and the new one was 224 KB so that a little more than halfed the space the Scripts.rxdata took up in the project.

I always figured something like this would shrink the filesize and that is simply amazing! Interesting how much memory in a file that indentation and comments take up. I haven't the time to test tonight, but I'd imagine that maybe it might make your game run just a little bit faster, (or at least start up a little faster, if it takes a second to load everything.) Running my project after I did that, it does seem to eliminated alot of those 'quick pause' moments, like when transitioning between scenes and such.

It would be silly as a scripter or general project developer to do this in mid-development, but I'd probably do this before posting a large scale project, just to save those few grams of file size lol. Not to mention, although people can crack your project and steal your work it'd be harder for them to 'understand' the scripts coding itself, since it makes it harder for a human mind to seperate and keep track of without comments/indents. =P

Next big thing is if you came up with a way to do this and then encrypt all that data, maybe even put every individual script into the one same section, that would really fry people's brains to try and decypher, especially with comments and indentation/excess whitespace removed!

Good job on this man, I was really impressed ! *Hugs*
That sort of thing is most commonly done with javascript, as normally a difference of 200kb, however large proportional to the data, is a pittance. I'm surprised it actually improves performance, though. I guess the Ruby interpreter just isn't the absolute greatest, unlike say the PHP interpreter which can compile scripts to machine code every time to improve speed (PHP 6 may have some sort of versioning system that can tell if it needs to recompile a script or not, to cache compilations and save more time?).

Will have to keep this in mind for the future.
And first now I realize that I released the encrypted version >_<
I did it to make it simpler for non-scripters to use. But this is the Scripter's corner so it was a mistake to upload that version here.
Here is an unencrypted version: http://webgel.net/bb/files/RemoveComments.rar
Note that only the Scripts.rxdata is included, so you'll have to provide the missing files if you want to upon it in the editor.
Feel free to mess around with it. ^^

Thanks for the nice comments Kain :cute:
I am happy to hear that it didn't mess anything up. My motivation to make it was indeed to see if you could increase the speed, both loading time, but also at runtime. I admit I didn't know whether it will have an effect other than speeding up the initial load time. (So my main focus was to remove parts which had no semantic significance)
I totally agree that you should only use it for the version you publish. It does decrease the value of the scripts due to the lack of comments.

Encrypting the data would be silly because one would have to decrypt the data again which requires modification of the DLL file.
Obfuscation is another matter, which I believe is what you actually mean.
With my other projects that I prioritize higher I won't have time to work on it for a very long time, but feel free to work on it.
You can see how I work with the library I include which makes everything loads easier.

@rey: There are no compilation of the scripts to any intermediary format. There are in version 1.9.x, but not in the version XP and VX uses. That is why this is interesting. More interesting is that the speed up seems to be actually noticeable.
I believe it's lexing, parsing and then interpreting, but I am not sure. Luckily the library means I don't have to understand how it works.

*hugs*
- Zeriab
Yeah the only thing performance-wise that was improved was going from Scene_A to Scene_B and all that; ie your menu opens quicker when you call it, with the code compressed, than it would without deleting comments and excess whitespace. My theory is that it takes a nanosecond more to skip past all our optional human-readable notes and spacing while initializing an object, but without all that extra baggage the object gets created and sent to its respectable variable quicker.

I doubt this would improve the FPS on your map or anything, especially if you have a laggy event or some script bogging your project down it'll still drag it down with or without compressing the code in this fashion. My speculation is, again, it just speeds up the 'initialize' of the object, nothing less nothing more.
After some recent experimentation, I've realized that I had an interesting tip for scripters. I've been playing around with the interpreter, and I realized that the event's "Call Script..." function actually behaves as though the script you were calling is a part of the interpreter class. Actually, to be more specific, your script is contained within the call script method in the Interpreter class. Now, this presents both opportunities and potential problems.

First off, lets list the opportunities. Since the call script function is interpreted as part of the interpreter, that means you can call any method in the Interpreter class. This means that, if you wanted to, you could call custom methods inserted into the class. You can even call methods already there, such as the one used to get the instance of any character or event on the current map.

Now, there are potential issues with this as well. For example, if you call any of the other interpreter commands, it will probably crash, because it tries to read the necessary data from the current event command, which is call script. When it tries that, it will fail. Guaranteed. Another point to be raised is that if you ever modify the @index variable, you can do one of several things. You can set the event into a loop, by putting the index at a point its already passed. You could also crash it by putting it to a point where there are no commands for it to process. Or, you could crash it by making it into a data type other than an integer.

All of this and probably more is possible with a little bit of creative thinking, and it's simple enough to actually do.
I've got some cool stuff for RPG::MapInfos. Mostly this is for traversing the data tree that you see in the editor, which might look like:

  1. - Overworld
  2.     Town 1
  3.   - Town 2
  4.       Inn
  5.       Mayor's House
  6.   + Town 3
Expand to see the code.


Now, you can find $data_mapinfos[map_id].parent to figure out that if you're in the Mayor's House, you're actually in Town 2, or you can iterate through each sibling ($data_mapinfos.each_sibling {|sibling| print sibling.name}), or find out how many children a map has (Town 2 has 2 children) with $data_mapinfos.children.size. There is also a bit of regular expression to read bracketed data and remove it from the name of the map when it is returned for, say, a location script.

  1. #===============================================================================
  2. # ** RPG::MapInfo
  3. #-------------------------------------------------------------------------------
  4. #    Read many things from the name of a map
  5. #===============================================================================
  6.  
  7. class RPG::MapInfo
  8.   attr_accessor :id # This element did not exist before
  9.   #-----------------------------------------------------------------------------
  10.   # * Returns the parent MapInfo
  11.   #-----------------------------------------------------------------------------
  12.   def parent(data_hash = $data_mapinfos)
  13.     return data_hash[self.parent_id]
  14.   end
  15.   #-----------------------------------------------------------------------------
  16.   # * Returns a hash containing all sibling MapInfos
  17.   #-----------------------------------------------------------------------------
  18.   def siblings(data_hash = $data_mapinfos)
  19.     output = {}
  20.     each_sibling(data_hash) { |sibling| output[sibling.id] = sibling }
  21.     return output
  22.   end
  23.   #-----------------------------------------------------------------------------
  24.   # * Iterate through all sibling MapInfos
  25.   #-----------------------------------------------------------------------------
  26.   def each_sibling(data_hash = $data_mapinfos)
  27.     data_hash.each_value do |mapinfo|
  28.       yield mapinfo if self != mapinfo and self.parent_id == mapinfo.parent_id
  29.     end
  30.   end
  31.   #-----------------------------------------------------------------------------
  32.   # * Returns a hash containing all child MapInfos
  33.   #-----------------------------------------------------------------------------
  34.   def children(data_hash = $data_mapinfos)
  35.     output = {}
  36.     each_child(data_hash) { |child| output[child.id] = child }
  37.     return output
  38.   end
  39.   #-----------------------------------------------------------------------------
  40.   # * Iterate through all child MapInfos
  41.   #-----------------------------------------------------------------------------
  42.   def each_child(data_has = $data_mapinfos)
  43.     data_hash.each_value { |mapinfo| yield mapinfo if id == mapinfo.parent_id }
  44.   end
  45.   #-----------------------------------------------------------------------------
  46.   # * Name without any bracketed information
  47.   #-----------------------------------------------------------------------------
  48.   def name
  49.     return @name.gsub(/\[[^\]]*\]/) {""}
  50.   end
  51.   #-----------------------------------------------------------------------------
  52.   # * Name including bracketed information
  53.   #-----------------------------------------------------------------------------
  54.   def name!
  55.     return @name
  56.   end
  57.   #-----------------------------------------------------------------------------
  58.   # * Returns Integer from [#xx] where # is variable
  59.   #-----------------------------------------------------------------------------
  60.   def bracketed(definer)
  61.     return nil unless @name =~ /\[#{definer}[ ]*([0-9]+)\]/i
  62.     return $1.to_i
  63.   end
  64.   #=============================================================================
  65.   # Example methods for getting data from map name
  66.   #=============================================================================
  67.   #-----------------------------------------------------------------------------
  68.   # * Name contains [OV], meaning it's an overworld map
  69.   #-----------------------------------------------------------------------------
  70.   def overworld?
  71.     return @name.include?("[OV]")
  72.   end
  73.   #-----------------------------------------------------------------------------
  74.   # * Name contains [Loop-Map], meaning it's a looping map
  75.   #-----------------------------------------------------------------------------
  76.   def loop_map?
  77.     return @name.include?("[Loop-Map]")
  78.   end
  79.   #-----------------------------------------------------------------------------
  80.   # * Returns Slant, ex. [#40]
  81.   #-----------------------------------------------------------------------------
  82.   def slant
  83.     return bracketed('#')
  84.   end
  85.   #-----------------------------------------------------------------------------
  86.   # * Returns Encounter rate, ex. [encounter-rate: 50]
  87.   #-----------------------------------------------------------------------------
  88.   def level
  89.     return bracketed('encounter-rate:')
  90.   end
  91. end
  92. # Here we define the global data variable, and set the :id value for each one
  93. $data_mapinfos = load_data('Data/MapInfos.rxdata')
  94. $data_mapinfos.each { |key, mapinfo| mapinfo.id = key }
  95.  
Expand to see the code.


Also, expanding on the GSM module, here is an entire User32 module. It definitely doesn't include all of the User32 functions, but it has all of the ones I was using for resolution changing, mouse input keyboard input, and part of a debug console window (making a console window is kernel32, but I wanted to bring the main window back to the front afterward and that's SetForegroundWindow in user32). It also conveniently defines HWND as User32::HWND. If you "include User32" in your class or module, you can do something like SetWindowPos.call(HWND, HWND_TOP, 0, 0, width, height, SWP_NOMOVE | SWP_SHOWWINDOW) in order to bring the window to the top and change its width and height, but not change its position, and show the window.

  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.   SetWindowLong       = Win32API.new('user32', 'SetWindowLong', 'LIL', 'L')
  10.   SetWindowPos        = Win32API.new('user32', 'SetWindowPos', 'LLIIIII', 'I')
  11.   Keybd_Event         = Win32API.new('user32', 'keybd_event', 'LLLL', '')
  12.   FindWindow          = Win32API.new('user32', 'FindWindow', 'PP', 'L')
  13.   SetForegroundWindow = Win32API.new('user32', 'SetForegroundWindow', 'L', 'L')
  14.   GetCursorPos        = Win32API.new('user32', 'GetCursorPos', 'P', 'I')
  15.   ShowCursor          = Win32API.new('user32', 'ShowCursor', 'L', 'L')
  16.   ScreenToClient      = Win32API.new('user32', 'ScreenToClient', 'LP', 'I')
  17.   GetKeyState         = Win32API.new('user32', 'GetKeyState', 'I', 'I')
  18.   GetAsyncKeyState    = Win32API.new('user32', 'GetAsyncKeyState', 'I', 'I')
  19.  
  20.   HWND = FindWindow.call('RGSS Player', Settings["Title"])
  21.  
  22.   # GSM constants. For more complete descriptions, see Microsoft's website:
  23.   # http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx
  24.   SM_CXSCREEN      = 0  # Width of the current master screen resolution
  25.   SM_CYSCREEN      = 1  # Height of the current master screen resolution
  26.  
  27.   SM_CXVSCROLL     = 2  # Width of a vertical scroll bar
  28.   SM_CYHSCROLL     = 3  # Height of a horizontal scroll bar
  29.  
  30.   SM_CYCAPTION     = 4  # Height of a caption area
  31.  
  32.   SM_CXBORDER      = 5  # Width of a window border
  33.   SM_CYBORDER      = 6  # Height of a window border
  34.  
  35.   SM_CXDLGFRAME    = 7
  36.   SM_CXFIXEDFRAME  = 7  # Width of non-resizable captioned window frame
  37.   SM_CYDLGFRAME    = 8
  38.   SM_CYFIXEDFRAME  = 8  # Height of non-resizable captioned window frame
  39.  
  40.   SM_CYVTHUMB      = 9  # Height of a thumb button on vertical scrollbars
  41.   SM_CXHTHUMB      = 10 # Width of a thumb button on horizontal scrollbars
  42.  
  43.   SM_CXICON        = 11 # Default width of an icon
  44.   SM_CYICON        = 12 # Default height of an icon
  45.  
  46.   SM_CXCURSOR      = 13 # Width of a cursor
  47.   SM_CYCURSOR      = 14 # Height of a cursor
  48.  
  49.   SM_CYMENU        = 15 # Height of a single-line menu bar
  50.  
  51.   SM_CXFULLSCREEN  = 16 # Width of client rect for a full-screen window
  52.   SM_CYFULLSCREEN  = 17 # Height of client rect for a full-screen window
  53.  
  54.   SM_CYKANJIWINDOW = 18 # Height of kanji window at bottom of screen, if there
  55.  
  56.   SM_MOUSEPRESENT  = 19 # Non-zero if mouse is present; 0 if not
  57.  
  58.   SM_CYVSCROLL     = 20 # Height of the arrow bitmap on vertical scrollbars
  59.   SM_CXHSCROLL     = 21 # Width of the arrow bitmap on horizontal scrollbars
  60.  
  61.   SM_DEBUG         = 22 # Non-zero if debug User.exe is installed; 0 if not
  62.   SM_SWAPBUTTON    = 23 # Non-zero if mouse button values are swapped
  63.  
  64.   SM_CXMIN         = 28 # Minimum width of a window
  65.   SM_CYMIN         = 29 # Minimum height of a window
  66.  
  67.   SM_CXSIZE        = 30 # Width of a button in a window caption or title bar
  68.   SM_CYSIZE        = 31 # Height of a button in a window caption or title bar
  69.  
  70.   SM_CXFRAME       = 32
  71.   SM_CXSIZEFRAME   = 32 # Width of the sizing border around a resizable window
  72.   SM_CYFRAME       = 33
  73.   SM_CYSIZEFRAME   = 33 # Height of the sizing border around a resizable window
  74.  
  75.   SM_CXMINTRACK    = 34 # Minimum "tracking" width of a window
  76.   SM_CYMINTRACK    = 35 # Minimum "tracking" height of a window
  77.  
  78.   SM_CXDOUBLECLK   = 36 # Width of rect which second click must be in for double
  79.   SM_CYDOUBLECLK   = 37 # Hght of rect which second click must be in for double
  80.  
  81.   SM_CXICONSPACING = 38 # Width of a grid cell for items in large icon view
  82.   SM_CYICONSPACING = 39 # Height of a grid cell for items in large icon view
  83.  
  84.   SM_MENUDROPALIGNMENT = 40 # 0 if drop-down menus are left-aligned...
  85.  
  86.   SM_PENWINDOWS    = 41 # Non-zero if Microsoft Windows for Pen computing
  87.                         #  extensions are installed; 0 if not
  88.  
  89.   SM_DBCSENABLED   = 42 # Non-zero if user32.dll supports DBCS; 0 if not
  90.  
  91.   SM_CMOUSEBUTTONS = 43 # Number of available mouse buttons, or 0 for no mouse
  92.  
  93.   SM_SECURE        = 44 # Always returns 0
  94.  
  95.   SM_CXEDGE        = 45 # Width of a 3-D style border
  96.   SM_CYEDGE        = 46 # Height of a 3-D style border
  97.  
  98.   SM_CXMINSPACING  = 47 # Width of a grid cell for minimized windows
  99.   SM_CYMINSPACING  = 48 # Height of a grid cell for minimized windows
  100.  
  101.   SM_CXSMICON      = 49 # Recommended width of a small icon
  102.   SM_CYSMICON      = 50 # Recommended height of a small icon
  103.  
  104.   SM_CYSMCAPTION   = 51 # Height of a small caption
  105.   SM_CXSMSIZE      = 52 # Width of small caption buttons
  106.   SM_CYSMSIZE      = 53 # Height of small caption buttons
  107.   SM_CXMENUSIZE    = 54 # Width of menu bar buttons
  108.   SM_CYMENUSIZE    = 55 # Height of menu bar buttons
  109.  
  110.   SM_ARRANGE       = 56 # Flags about how system the arranges minimized windows
  111.   SM_CXMINIMIZED   = 57 # Width of a minimized window
  112.   SM_CYMINIMIZED   = 58 # Height of a minimized window
  113.  
  114.   SM_CXMAXTRACK    = 59 # Default maximum width of resizable windows
  115.   SM_CYMAXTRACK    = 60 # Default maximum height of resizable windows
  116.   SM_CXMAXIMIZED   = 61 # Default width of maximized top-level window
  117.   SM_CYMAXIMIZED   = 62 # Default height of maximized top-level window
  118.  
  119.   SM_NETWORK       = 63 # The least significant bit is set if a network is
  120.                         #  present; otherwise, it is cleared
  121.  
  122.   SM_CLEANBOOT     = 67 # System boot type; 0:Normal, 1:Safe, 2:Safe w/network
  123.  
  124.   SM_CXDRAG        = 68
  125.   SM_CYDRAG        = 69 # Number of pixels mouse can move before initiating drag
  126.  
  127.   SM_SHOWSOUNDS    = 70 # Non-zero if user requires visible output; 0 if not
  128.  
  129.   SM_CXMENUCHECK   = 71 # Width of the default menu check-mark bitmap
  130.   SM_CYMENUCHECK   = 72 # Height of the default menu check-mark bitmap
  131.  
  132.   SM_SLOWMACHINE   = 73 # Non-zero if system has a slow processor; 0 if not
  133.                         #  No, seriously, that's what Microsoft said!
  134.  
  135.   SM_MIDEASTENABLED = 74 # Non-zero if system can use Hebrew, Arabic languages
  136.  
  137.   SM_MOUSEWHEELPRESENT = 75 # Nonzero mouse has vertical scroll wheel; 0 if not
  138.  
  139.   SM_XVIRTUALSCREEN    = 76 # Coordinates of the left side of the virtual screen
  140.   SM_YVIRTUALSCREEN    = 77 # Coordinates of the top of the virtual screen
  141.   SM_CXVIRTUALSCREEN   = 78 # Virtual width of all screens put together
  142.   SM_CYVIRTUALSCREEN   = 79 # Virtual height of all screen put together
  143.   SM_CMONITORS         = 80 # Numbers of display monitors on a desktop
  144.   SM_SAMEDISPLAYFORMAT = 81 # Non-zero if all screen use same color depth...
  145.  
  146.   # SetWindowPos constants
  147.   HWND_NOTOPMOST      = -2  # Make window not always on top (and bring to front)
  148.   HWND_TOPMOST        = -1  # Put window in front and make it always on top
  149.   HWND_TOP            = 0   # Put window in front of all non-topmost windows
  150.   HWND_BOTTOM         = 1   # Put window behind all other windows
  151.  
  152.   SWP_NOSIZE          = 0x0001 # Keep current size (ignores w and h)
  153.   SWP_NOMOVE          = 0x0002 # Keep current position (ignores X and Y)
  154.   SWP_NOZORDER        = 0x0004 # Keep current Z order (ignores hWndInsertAfter)
  155.   SWP_NOREDRAW        = 0x0008 # Does NOT redraw changes
  156.   SWP_NOACTIVATE      = 0x0010 # Does NOT automatically activate the window
  157.   SWP_FRAMECHANGED    = 0x0020 # Applies new frame styles set with SetWindowLong
  158.   SWP_SHOWWINDOW      = 0x0040 # Displays the window
  159.   SWP_HIDEWINDOW      = 0x0080 # Hides the window
  160.   SWP_NOCOPYBITS      = 0x0100 # Discards the entire contents of the client area
  161.   SWP_NOOWNERZORDER   = 0x0200 # Doesn't change the window display order
  162.   SWP_NOSENDCHANGING  = 0x0400 # Don't send WM_WINDOWPOSCHANGING
  163.   SWP_DEFERERASE      = 0x2000 # Prevents generation of the WM_SYNCPAINT message
  164.   SWP_ASYNCWINDOWPOS  = 0x4000 # Use if calling thread does not own the window
  165. end
  166.  
Expand to see the code.
I've been working on a new RMXP Tilemap script. It didn't work for what I needed it for (because it lags horribly when you zoom the whole thing out) and I haven't checked its speed against SephirothSpawn's original rewrite, but here it is. It does priorities correctly, unlike any rewrite before it, and it does this by making a Sprite for each 32x32 square. It also has animated autotiles. It is a Ruby equivalent to the built-in Tilemap class. The built-in is faster, of course, but can't zoom or have automatic Plane-like capabilities. Do with this what you will; it's probably best for educational purposes.

  1. #===============================================================================
  2. # ** Tilemap
  3. #-------------------------------------------------------------------------------
  4. # rey meustrus and SephirothSpawn
  5. # Version 2.0
  6. # 2010-02-02
  7. # SDK : Version 2.0+, Parts I & II
  8. #-------------------------------------------------------------------------------
  9. # * Credits :
  10. #
  11. #   Thanks to Trickster for conversion formula for Hexidecimal to rgb.
  12. #   Thanks to trebor777 for helping with the priority bug from the 0.9 version.
  13. #-------------------------------------------------------------------------------
  14. # * Version History :
  15. #
  16. #   Version 0.9 -------------------------------------------------- (??????????)
  17. #   Version 1 ---------------------------------------------------- (2007-05-30)
  18. #    Version 1.1 ------------------------------------------------- (2007-07-20)
  19. #     - Update : Removed pointless block. Move RPG::Cache.autotile to MACL.
  20. #    Version 1.11 ------------------------------------------------ (2007-07-31)
  21. #    Version 2.0 ------------------------------------------------- (2010-02-02)
  22. #-------------------------------------------------------------------------------
  23. # * Description :
  24. #
  25. #   This script was designed to re-write the default RGSS Hidden Tilemap class.
  26. #   The script has many added features via read/write variables.
  27. #-------------------------------------------------------------------------------
  28. # * Instructions :
  29. #
  30. #   Place The Script Below the SDK and Above Main.
  31. #-------------------------------------------------------------------------------
  32. # * Syntax :
  33. #
  34. #   Get Autotile Tile Bitmap
  35. #    - RPG::Cache.autotile_tile(autotile_filename, tile_id[, hue[, frame_id]])
  36. #
  37. #      autotile_filename   : Filename of autotile
  38. #      tile_id             : ID of tile (Found from RPG::Map.data)
  39. #      hue (Optional)      : Hue for tile
  40. #      frame_id (Optional) : Frame of tile (for animated autotiles)
  41. #
  42. # * Tilemap Syntax
  43. #
  44. #   - tile(tile_id)     : Gets bitmap for tile_id
  45. #   - tile(x, y, z)     : Gets bitmap at coordinates using @map_data
  46. #   - priority(tile_id) : Gets Z value for tile_id
  47. #   - priority(x, y, z) : Gets Z value at coordinates
  48. #
  49. #   Readable Attributes :
  50. #    - viewport         : Viewport used for sprites
  51. #    - width            : Total pixel width of the Tilemap
  52. #    - height           : Total pixel height of the Tilemap
  53. #
  54. #   Readable/Writable Attributes :
  55. #    - map_data         : 3D Table of Tile ID Data
  56. #    - flash_data       : 3D Table of Tile Color Data
  57. #    - priorities       : 3D Table of Tile Priorities
  58. #    - hue              : Hue adjustment for all tiles
  59. #    - ox, oy           : Tilemap layer offsets
  60. #    - zoom             : Zoom value as fraction
  61. #    - tilesize         : Zoom value as size of individual tile (normal is 32.0)
  62. #    - tileset_name     : Name of Bitmap
  63. #    - autotile_names   : Array of Autotile Filenames
  64. #    - visible          : Tilemap Visible Flag
  65. #    - static           : Static Flag (no animated autotiles)
  66. #    - is_a_plane       : Behaves like a Plane (loops around edges)
  67. #===============================================================================
  68.  
  69. #-------------------------------------------------------------------------------
  70. # SDK Log
  71. #-------------------------------------------------------------------------------
  72. SDK.log('Tilemap', 'rey meustrus and SephirothSpawn', 2.0, '2010-02-02')
  73.  
  74. #===============================================================================
  75. # ** RPG::Cache
  76. #===============================================================================
  77.  
  78. module RPG::Cache
  79.   #-----------------------------------------------------------------------------
  80.   # * Constants
  81.   #-----------------------------------------------------------------------------
  82.   Animated_Autotile_Frames = 16
  83.   Empty_Bitmap = Bitmap.new(32, 32)
  84.   Default_Rect = Rect.new(0, 0, 32, 32)
  85.   Autotiles = [
  86.     [[26, 27, 32, 33], [ 4, 27, 32, 33], [26,  5, 32, 33], [ 4,  5, 32, 33],
  87.      [26, 27, 32, 11], [ 4, 27, 32, 11], [26,  5, 32, 11], [ 4,  5, 32, 11]],
  88.     [[26, 27, 10, 33], [ 4, 27, 10, 33], [26,  5, 10, 33], [ 4,  5, 10, 33],
  89.      [26, 27, 10, 11], [ 4, 27, 10, 11], [26,  5, 10, 11], [ 4,  5, 10, 11]],
  90.     [[24, 25, 30, 31], [24,  5, 30, 31], [24, 25, 30, 11], [24,  5, 30, 11],
  91.      [14, 15, 20, 21], [14, 15, 20, 11], [14, 15, 10, 21], [14, 15, 10, 11]],
  92.     [[28, 29, 34, 35], [28, 29, 10, 35], [ 4, 29, 34, 35], [ 4, 29, 10, 35],
  93.      [38, 39, 44, 45], [ 4, 39, 44, 45], [38,  5, 44, 45], [ 4,  5, 44, 45]],
  94.     [[24, 29, 30, 35], [14, 15, 44, 45], [12, 13, 18, 19], [12, 13, 18, 11],
  95.      [16, 17, 22, 23], [16, 17, 10, 23], [40, 41, 46, 47], [ 4, 41, 46, 47]],
  96.     [[36, 37, 42, 43], [36,  5, 42, 43], [12, 17, 18, 23], [12, 13, 42, 43],
  97.      [36, 41, 42, 47], [16, 17, 46, 47], [12, 17, 42, 47], [ 0,  1,  6,  7]]
  98.   ]
  99.   #-----------------------------------------------------------------------------
  100.   # * Normal or Autotile Tile
  101.   #-----------------------------------------------------------------------------
  102.   def self.tile!(tileset_name, autotile_names, tile_id, hue = 0)
  103.     return Empty_Bitmap if tile_id == 0
  104.     return self.tile(tileset_name, tile_id, hue) if tile_id >= 384
  105.     # After this point, we are an autorile
  106.     filename = autotile_names[tile_id / 48 - 1]
  107.     autotile = self.autotile(filename)
  108.     # Reconfigure Tile ID
  109.     tile_id %= 48
  110.     # Creates Key
  111.     key = [filename, tile_id, hue]
  112.     # If Key Not Found
  113.     if not @cache.has_key?(key) or @cache[key].disposed?
  114.       # Creates Bitmap
  115.       bitmap = Bitmap.new(autotile.width / 3, 32)
  116.       # Collects Auto-Tile Tile Layout
  117.       tiles = Autotiles[tile_id / 8][tile_id % 8]
  118.       # Draws Auto-Tile Rects
  119.       tiles.each_with_index do |tile_position, i|
  120.         for frame_id in 0..(autotile.width / 96)
  121.           src_rect = Rect.new(tile_position % 6 * 16 + frame_id * 96,
  122.             tile_position / 6 * 16, 16, 16)
  123.           bitmap.blt(i % 2 * 16 + frame_id * 32, i / 2 * 16, autotile, src_rect)
  124.         end
  125.       end
  126.       # Saves Autotile to Cache
  127.       @cache[key] = bitmap
  128.       # Change Hue
  129.       @cache[key].hue_change(hue)
  130.     end
  131.     @cache[key]
  132.   end
  133.   #-----------------------------------------------------------------------------
  134.   # * Tile Rect
  135.   #-----------------------------------------------------------------------------
  136.   def self.tile_rect(tileset_name, autotile_names, tile_id)
  137.     return Default_Rect if tile_id == 0 or tile_id >= 384
  138.     autotile = self.autotile(filename = autotile_names[tile_id / 48 - 1])
  139.     # Configures Animation Offset
  140.     fc = (Graphics.frame_count/Animated_Autotile_Frames) % (autotile.width/96)
  141.     @cache[fc] = Rect.new(fc * 32, 0, 32, 32) if not @cache.has_key?(fc)
  142.     @cache[fc]
  143.   end
  144. end
  145.  
  146. #===============================================================================
  147. # ** Game_Character
  148. #-------------------------------------------------------------------------------
  149. #    Remove $game_map.screen_y from Z processing so Tilemap doesn't have to
  150. #    process Z value every time screen_y changes
  151. #===============================================================================
  152.  
  153. class Game_Character
  154.   #-----------------------------------------------------------------------------
  155.   # * Get Screen Z-Coordinates
  156.   #     height : character height
  157.   #-----------------------------------------------------------------------------
  158.   def screen_z(height = 0)
  159.     # If display flag on closest surface is ON
  160.     if @always_on_top
  161.       # 999, unconditional
  162.       return 999
  163.     end
  164.     # Get screen coordinates from real coordinates and map display position
  165.     z = (@real_y + 3) / 4 + 32
  166.     # If tile
  167.     if @tile_id > 0
  168.       # Add tile priority * 32
  169.       return z + $game_map.priorities[@tile_id] * 32
  170.     # If character
  171.     else
  172.       # If height exceeds 32, then add 31
  173.       return z + ((height > 32) ? 31 : 0)
  174.     end
  175.   end
  176. end
  177.  
  178. #===============================================================================
  179. # ** Spriteset_Map
  180. #===============================================================================
  181.  
  182. class Spriteset_Map
  183.   #-----------------------------------------------------------------------------
  184.   # * Alias Listings
  185.   #-----------------------------------------------------------------------------
  186.   alias_method :seph_tilemap_ssmap_inittm, :init_tilemap
  187.   #-----------------------------------------------------------------------------
  188.   # * Tilemap Initialization
  189.   #-----------------------------------------------------------------------------
  190.   def init_tilemap
  191.     # Original Tilemap Initialization
  192.     seph_tilemap_ssmap_inittm
  193.     # Set Tilemap Settings
  194.     @tilemap.tileset_name = $game_map.tileset_name
  195.     @tilemap.autotile_names = $game_map.autotile_names
  196.   end
  197. end
  198.  
  199. #===============================================================================
  200. # ** Tilemap
  201. #===============================================================================
  202.  
  203. class Tilemap
  204.   #-----------------------------------------------------------------------------
  205.   # * Tilemap Options
  206.   #-----------------------------------------------------------------------------
  207.   Viewport_Padding  = 2   # Number of tiles beyond viewport to refresh
  208.   Flash_Alpha       = 64  # Alpha value of the color of flash data
  209.   #-----------------------------------------------------------------------------
  210.   # * Public Instance Variables
  211.   #-----------------------------------------------------------------------------
  212.   attr_reader   :viewport       # Viewport for all sprites
  213.   attr_reader   :map_data       # 3D Table of Tile Settings
  214.   attr_reader   :flash_data     # 3D Table of Sprite Flash Colors
  215.   attr_reader   :priorities     # 3D Table of Tileset Priorities
  216.   attr_reader   :hue            # Hue Adjustment Value
  217.   attr_accessor :ox             # Bitmap Offsets      
  218.   attr_accessor :oy             # Bitmap Offsets      
  219.   attr_reader   :zoom           # Zoom Fraction        
  220.   attr_reader   :tileset_name   # Tileset Filename
  221.   attr_reader   :autotile_names # Array of Autotile Filenames
  222.   attr_reader   :visible        # Tilemap Visibility
  223.   attr_accessor :static         # No Animated Autotiles
  224.   attr_accessor :is_a_plane     # Loops around edges
  225.   attr_accessor :tileset        # Deprecated
  226.   attr_accessor :autotiles      # Deprecated
  227.   #-----------------------------------------------------------------------------
  228.   # * Object Initialization                            
  229.   #-----------------------------------------------------------------------------
  230.   def initialize(viewport = nil)                    
  231.     @viewport          = viewport
  232.     @map_data          = nil
  233.     @flash_data        = nil
  234.     @priorities        = nil
  235.     @hue               = 0
  236.     @ox                = 0
  237.     @oy                = 0
  238.     @zoom              = 1.0
  239.     @tileset_name      = nil
  240.     @autotile_names    = []
  241.     @visible           = true
  242.     @static            = false
  243.     @is_a_plane        = false
  244.     @sprites           = {}
  245.     @disposed          = false
  246.     @refresh_autotiles = true
  247.     @autotiles         = []
  248.   end
  249.   #-----------------------------------------------------------------------------
  250.   # * Total pixel width
  251.   #-----------------------------------------------------------------------------
  252.   def width
  253.     return 0 if @map_data.nil?
  254.     @map_data.xsize * 32
  255.   end
  256.   #-----------------------------------------------------------------------------
  257.   # * Total pixel height
  258.   #-----------------------------------------------------------------------------
  259.   def height
  260.     return 0 if @map_data.nil?
  261.     @map_data.ysize * 32
  262.   end
  263.   #-----------------------------------------------------------------------------
  264.   # * Set Map Data
  265.   #-----------------------------------------------------------------------------
  266.   def map_data=(map_data)
  267.     return if @map_data == map_data
  268.     @map_data = map_data
  269.     refresh
  270.   end
  271.   #-----------------------------------------------------------------------------
  272.   # * Set Flash Data
  273.   #-----------------------------------------------------------------------------
  274.   def flash_data=(flash_data)
  275.     return if @flash_data == flash_data
  276.     @flash_data = flash_data
  277.     @sprites.each do |key, sprite|
  278.       if not flash_data.nil? and (hex = flash_data[*key]) != 0
  279.         sprite.color.red   = (hex / 256) * 16
  280.         sprite.color.green = ((hex / 16) % 16) * 16
  281.         sprite.color.blue  = (hex % 16) * 16
  282.         sprite.color.alpha = Flash_Alpha
  283.       else
  284.         sprite.color.alpha = 0
  285.       end
  286.     end
  287.     Graphics.frame_reset
  288.   end
  289.   #-----------------------------------------------------------------------------
  290.   # * Set Priorities
  291.   #-----------------------------------------------------------------------------
  292.   def priorities=(priorities)
  293.     return if @priorities == priorities
  294.     @priorities = priorities
  295.     refresh
  296.   end
  297.   #-----------------------------------------------------------------------------
  298.   # * Set Hue
  299.   #-----------------------------------------------------------------------------
  300.   def hue=(hue)
  301.     return if @hue == hue
  302.     @hue = hue
  303.     refresh
  304.   end
  305.   #-----------------------------------------------------------------------------
  306.   # * Set OX value
  307.   #-----------------------------------------------------------------------------
  308.   def ox=(ox)
  309.     return if @ox == ox
  310.     @ox = ox
  311.     @sprites.each { |key, sprite| sprite.ox = ox }
  312.   end
  313.   #-----------------------------------------------------------------------------
  314.   # * Set OX value
  315.   #-----------------------------------------------------------------------------
  316.   def oy=(oy)
  317.     return if @oy == oy
  318.     @oy = oy
  319.     @sprites.each { |key, sprite| sprite.oy = oy }
  320.   end
  321.   #-----------------------------------------------------------------------------
  322.   # * Get Tile Size
  323.   #-----------------------------------------------------------------------------
  324.   def tilesize
  325.     (zoom * 32).to_i
  326.   end
  327.   #-----------------------------------------------------------------------------
  328.   # * Set Tile Size
  329.   #-----------------------------------------------------------------------------
  330.   def tilesize=(tilesize)
  331.     self.zoom = tilesize / 32.0
  332.   end
  333.   #-----------------------------------------------------------------------------
  334.   # * Set Zoom Fraction
  335.   #-----------------------------------------------------------------------------
  336.   def zoom=(zoom)
  337.     return if @zoom == zoom
  338.     @zoom = zoom
  339.     @sprites.each do |key, sprite|
  340.       sprite.zoom_x = sprite.zoom_y = zoom
  341.       sprite.x = key.at(0) * tilesize
  342.       sprite.y = key.at(1) * tilesize
  343.     end
  344.     Graphics.frame_reset
  345.   end
  346.   #-----------------------------------------------------------------------------
  347.   # * Set Visibility
  348.   #-----------------------------------------------------------------------------
  349.   def visible=(visible)
  350.     return if @visible == visible
  351.     @visible = visible
  352.     @sprites.each_value { |sprite| sprite.visible = visible }
  353.   end
  354.   #-----------------------------------------------------------------------------
  355.   # * Set Tileset Name
  356.   #-----------------------------------------------------------------------------
  357.   def tileset_name=(name)
  358.     return if @tileset_name == name
  359.     @tileset_name = name
  360.     refresh
  361.   end
  362.   #-----------------------------------------------------------------------------
  363.   # * Set Autotile Names
  364.   #-----------------------------------------------------------------------------
  365.   def autotile_names=(names)
  366.     return if @autotile_names == names
  367.     @autotile_names = names
  368.     refresh
  369.   end
  370.   #-----------------------------------------------------------------------------
  371.   # * Get bitmap at coordinates
  372.   #-----------------------------------------------------------------------------
  373.   def tile(*args)
  374.     RPG::Cache.tile!(@tileset_name, @autotile_names, args_to_id(*args), @hue)
  375.   end
  376.   #-----------------------------------------------------------------------------
  377.   # * Get bitmap rect at coordinates
  378.   #-----------------------------------------------------------------------------
  379.   def tile_rect(*args)
  380.     RPG::Cache.tile_rect(@tileset_name, @autotile_names, args_to_id(*args))
  381.   end
  382.   #-----------------------------------------------------------------------------
  383.   # * Get priority at coordinates
  384.   #-----------------------------------------------------------------------------
  385.   def priority(x, y, z)
  386.     priority = @priorities[@map_data[x, y, z]]
  387.     return 0 if priority == 0
  388.     (y + priority) * 32 + 64
  389.   end
  390.   #-----------------------------------------------------------------------------
  391.   # * Find tile_id from args
  392.   #-----------------------------------------------------------------------------
  393.   def args_to_id(*args)
  394.     if args.size == 1
  395.       return args[0]
  396.     elsif args.size == 3
  397.       return @map_data[*args]
  398.     else
  399.       raise ArgumentError, "Only one (tile_id) or three (x, y, z) args allowed"
  400.     end
  401.   end
  402.   #-----------------------------------------------------------------------------
  403.   # * Dispose
  404.   #-----------------------------------------------------------------------------
  405.   def dispose
  406.     # Dispose Sprites
  407.     @sprites.each_value { |sprite| sprite.dispose }
  408.     # Set Disposed Flag to True
  409.     @disposed = true
  410.   end
  411.   #-----------------------------------------------------------------------------
  412.   # * Disposed?
  413.   #-----------------------------------------------------------------------------
  414.   def disposed?
  415.     @disposed
  416.   end
  417.   #-----------------------------------------------------------------------------
  418.   # * Frame Update
  419.   #-----------------------------------------------------------------------------
  420.   def update
  421.     if @is_a_plane
  422.       # Get Visible X Tiles
  423.       x1 = @ox / 32 - Viewport_Padding
  424.       x2 = @ox / 32 + @viewport.rect.width / tilesize + Viewport_Padding
  425.       # Get Visible Y Tiles
  426.       y1 = @oy / 32 - Viewport_Padding
  427.       y2 = @oy / 32 + @viewport.rect.height / tilesize + Viewport_Padding
  428.       # Wrapped values
  429.       _x1 = x1 % @map_data.xsize
  430.       _x2 = x2 % @map_data.xsize
  431.       _y1 = y1 % @map_data.ysize
  432.       _y2 = y2 % @map_data.ysize
  433.       # Behave like a Plane
  434.       tsize = tilesize
  435.       each_visible_sprite do |x, y, z, sprite|
  436.         if x > x2 and x >= _x1
  437.           sprite.x = (x - @map_data.xsize) * tsize
  438.         elsif x < x1 and x <= _x2
  439.           sprite.x = (x + @map_data.xsize) * tsize
  440.         else
  441.           sprite.x = x * tsize
  442.         end
  443.         if y > y2 and y >= _y1
  444.           sprite.y = (y - @map_data.ysize) * tsize
  445.         elsif y < y1 and y <= _y2
  446.           sprite.y = (y + @map_data.ysize) * tsize
  447.         else
  448.           sprite.y = y * tsize
  449.         end
  450.       end
  451.     end
  452.     # If Not Static and Autotile Reset Frame
  453.     if Graphics.frame_count % RPG::Cache::Animated_Autotile_Frames == 0
  454.       refresh_autotiles unless @static
  455.     end
  456.   end
  457.   #-----------------------------------------------------------------------------
  458.   # * Refresh
  459.   #-----------------------------------------------------------------------------
  460.   def refresh
  461.     return if @map_data.nil? or @tileset_name.nil? or @autotile_names.size < 7
  462.     @sprites.each_value { |sprite| sprite.dispose }
  463.     @sprites.clear
  464.     # Passes Through X Coordinates
  465.     for x in 0...@map_data.xsize
  466.       # Passes Through Z Coordinates
  467.       for y in 0...@map_data.ysize
  468.         # Passes Through Layers
  469.         for z in 0...@map_data.zsize
  470.           # Collects Tile ID
  471.           id = @map_data[x, y, z]
  472.           # Skip if 0 tile
  473.           next if id == 0
  474.           sprite = find_sprite(x, y, z)
  475.           # Draw Tile
  476.           sprite.bitmap = tile(id)
  477.           sprite.src_rect = tile_rect(id)
  478.           sprite.z = priority(x, y, z)
  479.         end
  480.       end
  481.     end
  482.     Graphics.frame_reset
  483.   end  
  484.   #-----------------------------------------------------------------------------
  485.   # * Refresh Auto-Tiles; only affects visible animated autotiles
  486.   #-----------------------------------------------------------------------------
  487.   def refresh_autotiles
  488.     each_visible_sprite do |x, y, z, sprite|
  489.       # Collects Tile ID
  490.       id = @map_data[x, y, z]
  491.       # Skip if 0 tile, or if not autotile
  492.       next if id == 0 or id >= 384
  493.       # Skip If Non-Animated Tile
  494.       bitmap = RPG::Cache.autotile(@autotile_names[id / 48 - 1])
  495.       next unless bitmap.width / 96 > 1
  496.       # Draw Tile
  497.       find_sprite(x, y, z).src_rect = tile_rect(id)
  498.     end
  499.     Graphics.frame_reset
  500.   end    
  501.   #-----------------------------------------------------------------------------
  502.   # * Find or create sprite at coordinates
  503.   #-----------------------------------------------------------------------------
  504.   def find_sprite(x, y, z, create = true)
  505.     return @sprites[[x, y, z]] if @sprites.has_key?([x, y, z])
  506.     return nil unless create
  507.     sprite = Sprite.new(@viewport)
  508.     sprite.visible = @visible
  509.     sprite.x = x * tilesize
  510.     sprite.y = y * tilesize
  511.     sprite.ox = @ox
  512.     sprite.oy = @oy
  513.     sprite.zoom_x = sprite.zoom_y = @zoom
  514.     @sprites[[x, y, z]] = sprite
  515.   end
  516.   #-----------------------------------------------------------------------------
  517.   # * Dispose of sprite at coordinates
  518.   #-----------------------------------------------------------------------------
  519.   def dispose_sprite(x, y, z)
  520.     return unless @sprites.has_key?([x, y, z])
  521.     @sprites[[x, y, z]].dispose
  522.     @sprites.delete([x, y, z])
  523.   end
  524.   #-----------------------------------------------------------------------------
  525.   # * Iterate through visible sprites
  526.   #-----------------------------------------------------------------------------
  527.   def each_visible_sprite
  528.     # Get Visible X Tiles
  529.     x1 = (@ox / 32 - Viewport_Padding) % @map_data.xsize
  530.     x2 = (@ox / 32 + @viewport.rect.width / tilesize + Viewport_Padding) %
  531.          @map_data.xsize
  532.     # Get Visible Y Tiles
  533.     y1 = (@oy / 32 - Viewport_Padding) % @map_data.ysize
  534.     y2 = (@oy / 32 + @viewport.rect.height / tilesize + Viewport_Padding) %
  535.          @map_data.ysize
  536.     @sprites.each do |key, sprite|
  537.       send_sprite = true
  538.       if x1 < x2
  539.         send_sprite &= key.at(0).between?(x1, x2)
  540.       else
  541.         send_sprite &= key.at(0) > x1 || key.at(0) < x2
  542.       end
  543.       if y1 < y2
  544.         send_sprite &= key.at(1).between?(y1, y2)
  545.       else
  546.         send_sprite &= key.at(1) > y1 || key.at(1) < y2
  547.       end
  548.       yield key.at(0), key.at(1), key.at(2), sprite if send_sprite
  549.     end
  550.   end
  551. end
  552.  
Expand to see the code.


EDIT: Added flash data, which is criminally easy with this approach.
Stupid but useful...

how to swap variables without the use of a temporary variable? MAke use of parallel assignement !
  1.  
  2. x,y = y,x
  3.  
Expand to see the code.
It is definitely useful trebor ^^

I don't know how many of you know __END__.
The rest of that section will not be run. In fact I believe the parser will stop at __END__ and therefore won't even build the abstract syntax tree for what comes afterwards. (An effect is the lack of syntax checking)
This can be used for preventing the inclusion of test code except when you want to use it.

Here is a conceived example:
  1. class Medal
  2.   include Comparable
  3.   attr_reader :titel, :time
  4.   def initialize(titel, time)
  5.     unless time.is_a?(Numeric)
  6.       raise ArgumentError.new("Time must be a numeric")
  7.     end
  8.     @titel = titel
  9.     @time = time
  10.   end
  11.  
  12.   def <=>(medal)
  13.     return time <=> medal.time
  14.   end
  15. end
  16.  
  17. __END__
  18.  
  19. class TestError < StandardError; end
  20.  
  21. bronze = Medal.new('Bronze', 180)
  22. bronze2 = Medal.new('Bronze', 180)
  23. bronze3 = Medal.new('Bronze3', 180)
  24. silver = Medal.new('Silver', 105)
  25. gold = Medal.new('Gold', 87.5)
  26.  
  27. unless (bronze == bronze2)
  28.   raise TestError.new("Medal.== does not compare #{bronze.inspect} " +
  29.                       "and #{bronze2.inspect} properly")
  30. end
  31.  
  32. unless (bronze == bronze3)
  33.   raise TestError.new("Medal.== does not ignore the title")
  34. end
  35.  
  36. unless (silver <=> bronze) == -1
  37.   raise TestError.new("Medal.<=> does not return -1 when its time is less" +
  38.                       " than the medal compared to")
  39. end
  40.  
  41. unless (silver <=> gold) == 1
  42.   raise TestError.new("Medal.<=> does not return 1 when its time is greater" +
  43.                       " than the medal compared to")
  44. end
  45.  
  46. unless (bronze <=> gold) == 1
  47.   raise TestError.new("Medal.<=> does not preserve transitivity.\n" +
  48.                       "I.e. <=> is highly problematic.")
  49. end
  50.                    
  51. p 'Medal testing completed successfully'
Expand to see the code.


Just comment the __END__ when you want to test.

*hugs*
A neat little equipment optimizer. Can be customized for each actor, so aluxes may like weapons with atk, but hilda prefers int.

  1. #==============================================================================
  2. # ** Equipment Optimzer
  3. #------------------------------------------------------------------------------
  4. # SephirothSpawn
  5. # Version 1.0
  6. # 2010-02-18
  7. #==============================================================================
  8.  
  9. module EquipmentOptimzer
  10.   #--------------------------------------------------------------------------
  11.   # * Weapon Priorities
  12.   #
  13.   #     Defines stat priorities looking for when passing through equipment
  14.   #
  15.   #   Weapon_Priorities[actor_id] = [:stat_name, ...]
  16.   #--------------------------------------------------------------------------
  17.   Weapon_Priorities = {}
  18.   Weapon_Priorities.default = [
  19.     :atk, :str_plus, :pdef, :mdef, :dex_plus, :agi_plus, :int_plus
  20.   ]
  21.   #--------------------------------------------------------------------------
  22.   # * Armor Priorities
  23.   #
  24.   #     Defines stat priorities looking for when passing through equipment
  25.   #
  26.   #   Armor_Priorities[actor_id] = [:stat_name, ...]
  27.   #--------------------------------------------------------------------------
  28.   Armor_Priorities = {}
  29.   Armor_Priorities.default = [
  30.     :pdef, :mdef, :eva, :dex_plus, :str_plus, :agi_plus, :int_plus
  31.   ]
  32.   #--------------------------------------------------------------------------
  33.   # * Optimize Weapon
  34.   #--------------------------------------------------------------------------
  35.   def self.optimze_weapon(actor)
  36.     # Return if actor cannot equip
  37.     return if actor.equip_fix?(0)
  38.     # Unequip current weapon
  39.     actor.equip(0, 0)
  40.     # Gather equippable weapons list
  41.     weapons = []
  42.     for weapon in $data_weapons
  43.       next if weapon == nil
  44.       next unless actor.equippable?(weapon)
  45.       if $game_party.weapon_number(weapon.id) > 0
  46.         weapons << weapon
  47.       end
  48.     end
  49.     # Stop if no weapons found
  50.     return if weapons.size == 0
  51.     # Equip if only 1 weapon found
  52.     if weapons.size == 1
  53.       actor.equip_item(weapons[0])
  54.       return
  55.     end
  56.     # Pass through priority list
  57.     Weapon_Priorities[actor.id].each do |stat|
  58.       # Get new list based off priority
  59.       weapons = self.best_stat(weapons, stat)
  60.       # Stop cycle if only 1 weapon found
  61.       break if weapons.size == 1
  62.     end
  63.     # Equip Item
  64.     actor.equip_item(weapons[0])
  65.   end
  66.   #--------------------------------------------------------------------------
  67.   # * Optimize Armor
  68.   #--------------------------------------------------------------------------
  69.   def self.optimze_armor(actor, kind)
  70.     # Return if actor cannot equip
  71.     return if actor.equip_fix?(kind + 1)
  72.     # Unequip current armor
  73.     case kind
  74.     when 0 ; actor.equip(1, 0)
  75.     when 1 ; actor.equip(2, 0)
  76.     when 2 ; actor.equip(3, 0)
  77.     when 3 ; actor.equip(4, 0)
  78.     end
  79.     # Gather equippable armors list
  80.     armors = []
  81.     for armor in $data_armors
  82.       next if armor == nil
  83.       next if armor.kind != kind
  84.       next unless actor.equippable?(armor)
  85.       if $game_party.armor_number(armor.id) > 0
  86.         armors << armor
  87.       end
  88.     end
  89.     # Stop if no armors found
  90.     return if armors.size == 0
  91.     # Equip if only 1 armor found
  92.     if armors.size == 1
  93.       actor.equip_item(armors[0])
  94.       return
  95.     end
  96.     # Pass through priority list
  97.     Armor_Priorities[actor.id].each do |stat|
  98.       # Get new list based off priority
  99.       armors = self.best_stat(armors, stat)
  100.       # Stop cycle if only 1 armor found
  101.       break if armors.size == 1
  102.     end
  103.     # Equip Item
  104.     actor.equip_item(armors[0])
  105.   end
  106.   #--------------------------------------------------------------------------
  107.   # * Filter list by max result
  108.   #--------------------------------------------------------------------------
  109.   def self.best_stat(list, stat)
  110.     # Get max value
  111.     max = (list.collect {|x| x.send(stat)}).max
  112.     # Start new list
  113.     a = []
  114.     # Add item to list if max == stat
  115.     list.each {|x| a << x if x.send(stat) == max}
  116.     # Return list
  117.     return a
  118.   end
  119. end
  120.  
  121. #==============================================================================
  122. # ** Game_Actor
  123. #==============================================================================
  124.  
  125. class Game_Actor
  126.   #--------------------------------------------------------------------------
  127.   # * Equip Item
  128.   #--------------------------------------------------------------------------
  129.   def equip_item(item)
  130.     # Branch by item type
  131.     case item
  132.     when RPG::Weapon
  133.       # Return if fixed
  134.       return if equip_fix?(0)
  135.       # Return unless equippable
  136.       return unless equippable?(item)
  137.       # Equip
  138.       equip(0, item.id)
  139.     when RPG::Armor
  140.       # Return if fixed
  141.       return if equip_fix?(item.kind + 1)
  142.       # Return unless equippable
  143.       return unless equippable?(item)
  144.       # Equip
  145.       equip(item.kind + 1, item.id)
  146.     end
  147.   end
  148.   #--------------------------------------------------------------------------
  149.   # * Optimize
  150.   #
  151.   #   type: -1 (all), 0 (weapon), 1-4 (armors)
  152.   #--------------------------------------------------------------------------
  153.   def optimize(type = -1)
  154.     # Branch by type
  155.     case type
  156.     when -1
  157.       # Optimize weapon
  158.       EquipmentOptimzer.optimze_weapon(self)
  159.       # Optimize all armor
  160.       for i in 0..3
  161.         EquipmentOptimzer.optimze_armor(self, i)
  162.       end
  163.     when 0
  164.       # Optimize weapon
  165.       EquipmentOptimzer.optimze_weapon(self)
  166.     else
  167.       # Optimize armor
  168.       EquipmentOptimzer.optimze_armor(self, type - 1)
  169.     end
  170.   end
  171. end
Expand to see the code.


Horray for filtering. :box:
Nice one.

I bring you another scriptlet for map names. Since we already now that we should forget about using more $variables than the ones the Maker loads if possible, this solution might help you a lot. Actually it works for both, XP and VX.

  1. module Map
  2.   NAME = load_data(Dir.glob('Data/MapInfos*').to_s)
  3.  
  4.   def self.name(map_id); NAME[map_id].name.sub(/@.*/, '') end
  5. end
Expand to see the code.


Script call:

Map.name(id) #=> Dark Castle
Ok. Here's a little something I wanted to try out. Basically works like an animated message window, but made this into a single sprite class and made it pretty easy to use.

  1. #==============================================================================
  2. # ** AnimatedTextSprite
  3. #------------------------------------------------------------------------------
  4. # SephirothSpawn
  5. # Version 1.0
  6. # 2010-02-18
  7. #==============================================================================
  8.  
  9. class AnimatedTextSprite < Sprite
  10.   #--------------------------------------------------------------------------
  11.   # * Object Initialization
  12.   #--------------------------------------------------------------------------
  13.   def initialize(width, height, viewport = nil)
  14.     super(viewport)
  15.     self.bitmap = Bitmap.new(width, height)
  16.     @text, @speed = [], 6
  17.   end
  18.   #--------------------------------------------------------------------------
  19.   # * Refresh
  20.   #--------------------------------------------------------------------------
  21.   def refresh(text, speed = @speed, max_height = true)
  22.     # Clear bitmap
  23.     self.bitmap.clear
  24.     # Save speed
  25.     @speed = [speed, 1].max
  26.     # Start text lines
  27.     @lines = [[]]
  28.     # Start x counter
  29.     x = 0
  30.     # Start text array
  31.     @text = [[]]
  32.     # Space width
  33.     space_width = self.bitmap.text_size(' ').width
  34.     # Pass through each word
  35.     for word in text.split(' ')
  36.       # Gets word width
  37.       width = self.bitmap.text_size(word).width
  38.       # If word cannot fit in line
  39.       if x + width > self.bitmap.width
  40.         # If x is 0
  41.         if x == 0
  42.           # Add word to line anyways
  43.           word.split('').each {|s| @text.last << s}
  44.           @text << []
  45.           next
  46.         end
  47.         # Set x to width
  48.         x = width + space_width
  49.         # Add word to new line
  50.         @text << []
  51.         word.split('').each {|s| @text.last << s}
  52.         @text.last << ' '
  53.         next
  54.       end
  55.       # Add width and word
  56.       x += width + space_width
  57.       word.split('').each {|s| @text.last << s}
  58.       @text.last << ' '
  59.     end
  60.     # Save text position and update
  61.     @text_x = 0
  62.     @text_y = 0
  63.     @text_h = self.bitmap.font.size + 2
  64.     # Max bitmap height
  65.     max_bitmap_height if max_height
  66.     update
  67.   end
  68.   #--------------------------------------------------------------------------
  69.   # * Maximize Bitmap Height
  70.   #--------------------------------------------------------------------------
  71.   def max_bitmap_height
  72.     # Get current number of text lines
  73.     lines = @text.size
  74.     # Get min height
  75.     height = lines * @text_h
  76.     # Resize bitmap if neccessary
  77.     if self.bitmap.height < height
  78.       self.bitmap = Bitmap.new(self.bitmap.width, height)
  79.     end
  80.   end
  81.   #--------------------------------------------------------------------------
  82.   # * Frame Update
  83.   #--------------------------------------------------------------------------
  84.   def update
  85.     # Return if text is empty
  86.     return if @text.empty?
  87.     # Return if not draw frame
  88.     return unless Graphics.frame_count % @speed == 0
  89.     # Get current line of text
  90.     line = @text.first
  91.     # If empty line
  92.     if line.empty?
  93.       # Remove curremt line
  94.       @text.shift
  95.       # Return if empty
  96.       return if @text.empty?
  97.       # Adjust text position
  98.       @text_x = 0
  99.       @text_y += @text_h
  100.     end
  101.     # Get next character
  102.     t = @text.first.shift
  103.     # Draw character
  104.     w = self.bitmap.text_size(t).width
  105.     self.bitmap.draw_text(@text_x, @text_y, w + 2, @text_h, t)
  106.     @text_x += w
  107.   end
  108. end
Expand to see the code.


You create your sprite like always, and when you want to draw the animated text, just call
your_sprite.refresh(text, speed, resize)

text is just your long line of text. speed is just a simple Graphics.frame_count % speed == 0 test. Higher the speed, the slower the text. Resize is a checker I added that will resize the sprites height to make sure the text will be drawn on the bitmap.

If you want to test it:
  1. $test = AnimatedTextSprite.new(320, 32)
  2. $test.z = 999
  3.  
  4. class Scene_Title
  5.   alias update2 update
  6.   def update
  7.     $test.update
  8.     $test.refresh('This is about as long of line of text i could bare to type. just rambling here but whatever. i hope this works. blah blah blah.', rand(4) + 1) if Input.trigger?(Input::ALT)
  9.     update2
  10.   end
  11. end
Expand to see the code.


Just press alt when you are in the title screen. Works like a charm.

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