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.
Scripter's corner : Snippets, Classes, Tips and more
RPG Maker ScriptsHere'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...
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:
But you'll need to paste this module above Main.
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.
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...
- begin
- Graphics.freeze
- $scene = Scene_Title.new
- $scene.main while $scene != nil
- Graphics.transition(30)
- #=begin
- rescue => error
- a = Dir.getwd
- aw = !FileTest.exists?(a+'/ErrorsLog.txt') ? 'w': 'a'
- log = File.open(a+'/ErrorsLog.txt', aw)
- time = Time.new
- year = time.strftime('%Y')
- month = time.strftime('%b')
- day = time.strftime('%d')
- hour = time.strftime('%H')
- min = time.strftime('%M')
- sec = time.strftime('%S')
- logtime = "#{year} #{month} #{day} #{hour}:#{min}:#{sec}"
- log.puts '---', logtime, 'Error! '+error, '---', error.backtrace.join("\n")
- log.close
- #=end
- rescue Errno::ENOENT
- filename = $!.message.sub("No such file or directory - ", "")
- print "Unable to find file #{filename}."
- 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:
- begin
- Graphics.freeze
- $scene = Scene_Title.new
- $scene.main while $scene != nil
- Graphics.transition(30)
- rescue Exception => error
- KyoLog.write(error)
- rescue Errno::ENOENT
- filename = $!.message.sub("No such file or directory - ", "")
- print "Unable to find file #{filename}."
- end
Expand to see the code.
But you'll need to paste this module above Main.
- class Game_Event; attr_reader :map_id; end
- module KyoLog
- CodeList = {
- 101 => 'Show Text', 102 => 'Show Choices',
- 402 => 'When [**]', 403 => 'When Cancel',
- 103 => 'Input Number', 104 => 'Xhange Text Options',
- 105 => 'Button Input Processing', 106 => 'Wait',
- 111 => 'Conditional Branch', 411 => 'Else',
- 112 => 'Loop', 413 => 'Repeat Above',
- 113 => 'Break Loop', 115 => 'Exit Event Processing',
- 116 => 'Erase Event', 117 => 'Call Common Event',
- 118 => 'Label', 119 => 'Jump to Label',
- 121 => 'Control Switches', 122 => 'Control Variables',
- 123 => 'Control Self Switch', 124 => 'Control Timer',
- 125 => 'Change Gold', 126 => 'Change Items',
- 127 => 'Change Weapons', 128 => 'Change Armor',
- 129 => 'Change Party Member', 131 => 'Change Windowskin',
- 132 => 'Change Battle BGM', 133 => 'Change Battle End ME',
- 134 => 'Change Save Access', 135 => 'Change Menu Access',
- 136 => 'Change Encounter', 201 => 'Transfer Player',
- 202 => 'Set Event Location', 203 => 'Scroll Map',
- 204 => 'Change Map Settings', 205 => 'Change Fog Color Tone',
- 206 => 'Change Fog Opacity', 207 => 'Show Animation',
- 208 => 'Change Transparent Flag', 209 => 'Set Move Route',
- 210 => "Wait for Move's Completion", 221 => 'Prepare for Transition',
- 222 => 'Execute Transition', 223 => 'Change Screen Color Tone',
- 224 => 'Screen Flash', 225 => 'Screen Shake',
- 231 => 'Show Picture', 232 => 'Move Picture',
- 233 => 'Rotate Picture', 234 => 'Change Picture Color Tone',
- 235 => 'Erase Picture', 236 => 'Set Weather Effects',
- 241 => 'Play BGM', 242 => 'Fade Out BGM0',
- 245 => 'Play BGS', 246 => 'Fade Out BGS',
- 247 => 'Memorize BGM/BGS', 248 => 'Restore BGM/BGS',
- 249 => 'Play ME', 250 => 'Play SE',
- 251 => 'Stop SE', 301 => 'Battle Processing',
- 601 => 'If Win', 602 => 'If Escape',
- 603 => 'If Lose', 302 => 'Shop Processing',
- 303 => 'Name Input Processing', 311 => 'Change HP',
- 312 => 'Change SP', 313 => 'Change State',
- 314 => 'Recover All', 315 => 'Change EXP',
- 316 => 'Change Level', 317 => 'Change Parameters',
- 318 => 'Change Skills', 319 => 'Change Equipment',
- 320 => 'Change Actor Name', 321 => 'Change Actor Class',
- 322 => 'Change Actor Graphic', 331 => 'Change Enemy HP',
- 332 => 'Change Enemy SP', 333 => 'Change Enemy State',
- 334 => 'Enemy Recover All', 335 => 'Enemy Appearance',
- 336 => 'Enemy Transform', 337 => 'Show Battle Animation',
- 338 => 'Deal Damage', 339 => 'Force Action',
- 340 => 'Abort Battle', 351 => 'Call Menu Screen',
- 352 => 'Call Save Screen', 353 => 'Game Over',
- 354 => 'Return to Title Screen', 355 => 'Script',
- 404 => 'Branch End - Choices', 604 => 'Branch End Battle Processing',
- 401 => ' Text Line', 0 => '',
- }
- D, Line = Dir.getwd, '-----'
- @aw = !FileTest.exists?(D+'/ErrorsLog.txt') ? 'w': 'a'
- @e = []
- time = Time.new
- year = time.strftime('%Y')
- month = time.strftime('%b')
- day = time.strftime('%d')
- hour = time.strftime('%H')
- min = time.strftime('%M')
- sec = time.strftime('%S')
- @logtime = "#{year} #{month} #{day} #{hour}:#{min}:#{sec}"
- def self.write(error, type='An error occurred!')
- log = File.open(D+'/ErrorsLog.txt', @aw)
- log.puts Line, @logtime, type, error
- log.puts error.backtrace.join("\n"), Line
- log.close
- end
- def self.write_events_info
- e = File.open(D+'/Events.txt', @aw)
- gp, gm = $game_player, $game_map.events
- x, y = $data_system.start_x, $data_system.start_y
- e.puts Line, @logtime
- e.puts "Player's Starting Position - X: #{x}, Y: #{y}"
- e.puts "Player's Current Position - X: #{gp.x}, Y: #{gp.y}"
- e.puts 'Map Events Keys Size = ' + gm.keys.size.to_s
- for n in 1..gm.size
- @e.push "Map #{gm[n].map_id}, ID: #{gm[n].id},"+
- "X: #{gm[n].x}, Y: #{gm[n].y}, Value: #{gm[n]}, "+
- "Trigger: #{gm[n].trigger}\n\n Commands List:\n"
- for m in 0...gm[n].list.size
- c = gm[n].list[m].code; l = CodeList[c]
- com = c != 0 ? 'command_' : ' '
- command = c != 0 ? " #{com}#{c} - #{l}" : ''
- @e.push command
- end
- end
- e.puts "\n", @e.join("\n"), Line, Line
- e.close
- @e.clear
- end
- 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
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.
...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.
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.
- module KyoBackup
- time = Time.new
- year = time.strftime('%Y')
- month = time.strftime('%m')
- day = time.strftime('%d')
- hour = time.strftime('%H')
- min = time.strftime('%M')
- sec = time.strftime('%S')
- @logtime = "#{year}#{month}#{day} #{hour}#{min}#{sec}"
- Backup = 'Backup'
- BUT = " #{@logtime}"
- BN = File.basename(Dir.getwd)
- DN = File.dirname(Dir.getwd)
- S = '/'
- DEST = DN+S+Backup+S+BN+' '+BUT
- def self.project
- FileUtils.mkdir(DN+S+Backup) if !File.exists?(DN+S+Backup)
- FileUtils.cp_r(Dir.getwd, DEST)
- print 'Backup ended successfully!'
- end
- 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
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.
This window will show the input number screen + text
and return the number.
new window_Input
- class Window_Input < Window_Message
- def initialize(text, digits)
- super()
- @var_id = 1
- start_input(text, digits)
- end
- def start_input(text, digits)
- @old_data = $game_variables[@var_id]
- $game_variables[@var_id] = 0
- $game_temp.message_text = text
- $game_temp.num_input_variable_id = @var_id
- $game_temp.num_input_digits_max = digits
- $game_temp.num_input_start = 1 # from_line
- end
- def finished?
- return @input_number_window.nil?
- end
- def get
- loop do
- # Update game screen
- Graphics.update
- # Update input information
- Input.update
- # Frame update
- update
- # Abort loop if screen is changed
- if @input_number_window.nil?
- break
- end
- end
- number = $game_variables[@var_id]
- $game_variables[@var_id] = @old_data
- return number
- end
- 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
2. version: without eval but with more evil
1. version: with eval
- class Module
- def akkr_reader(*args)
- args.each{ |sym| class_eval("def #{sym}; return @@#{sym}; end;") }
- end
- def akkr_writer(*args)
- args.each{ |sym| class_eval("def #(sym}=(value); return @@#{sym}=value; end;") }
- end
- def akkr_accessor(*args)
- akkr_reader(*args)
- akkr_writer(*args)
- end
- end
Expand to see the code.
2. version: without eval but with more evil
- class Module
- def akkr_reader(*args)
- args.each{ |sym| define_method(sym) { Object.instance_method(:class).bind(self).call.send(:class_variable_get,"@@#{sym}") } }
- end
- def akkr_writer(*args)
- args.each{ |sym| define_method("#{sym}=") { |value| Object.instance_method(:class).bind(self).call.send(:class_variable_set,"@@#{sym}",value) } }
- end
- def akkr_accessor(*args)
- akkr_reader(*args)
- akkr_writer(*args)
- end
- 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:
As it's a class variable, wouldn't be better to make a Class method instead?
Like so:
- class Foo
- @@foo = 2
- akkr_reader :foo
- # Do the same as just before.
- def foo
- @@foo
- end
- end
- d = Foo.new
- d.doo # => 2
Expand to see the code.
As it's a class variable, wouldn't be better to make a Class method instead?
if you would like to have class methods use:
PS: the second version need Ruby 1.8.3
- class << Foo
- akkr_reader :a
- end
- 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
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:
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. ;)
- a == 2 or a == 3 or a == "foo"
- => [2,3,"foo"].include? a
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
@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.
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
^_^
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.
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...
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:
- #===============================================================================
- # ** Graphics : Change Frame Rate
- #===============================================================================
- class << Graphics
- #-----------------------------------------------------------------------------
- # * Alias Listings
- #-----------------------------------------------------------------------------
- alias_method :chngframerate_graphics_update, :update
- #-----------------------------------------------------------------------------
- # * Update
- #-----------------------------------------------------------------------------
- def update
- chngframerate_graphics_update
- if Input.press?(Input::CTRL)
- if Input.trigger?(Input::F5)
- Graphics.frame_rate -= 10
- return
- elsif Input.trigger?(Input::F6)
- Graphics.frame_rate += 10
- return
- elsif Input.trigger?(Input::F7)
- Graphics.frame_rate = 40
- return
- end
- end
- end
- 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.
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)
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*
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.
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
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.
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.
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:
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.
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.
- - Overworld
- Town 1
- - Town 2
- Inn
- Mayor's House
- + 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.
- #===============================================================================
- # ** RPG::MapInfo
- #-------------------------------------------------------------------------------
- # Read many things from the name of a map
- #===============================================================================
- class RPG::MapInfo
- attr_accessor :id # This element did not exist before
- #-----------------------------------------------------------------------------
- # * Returns the parent MapInfo
- #-----------------------------------------------------------------------------
- def parent(data_hash = $data_mapinfos)
- return data_hash[self.parent_id]
- end
- #-----------------------------------------------------------------------------
- # * Returns a hash containing all sibling MapInfos
- #-----------------------------------------------------------------------------
- def siblings(data_hash = $data_mapinfos)
- output = {}
- each_sibling(data_hash) { |sibling| output[sibling.id] = sibling }
- return output
- end
- #-----------------------------------------------------------------------------
- # * Iterate through all sibling MapInfos
- #-----------------------------------------------------------------------------
- def each_sibling(data_hash = $data_mapinfos)
- data_hash.each_value do |mapinfo|
- yield mapinfo if self != mapinfo and self.parent_id == mapinfo.parent_id
- end
- end
- #-----------------------------------------------------------------------------
- # * Returns a hash containing all child MapInfos
- #-----------------------------------------------------------------------------
- def children(data_hash = $data_mapinfos)
- output = {}
- each_child(data_hash) { |child| output[child.id] = child }
- return output
- end
- #-----------------------------------------------------------------------------
- # * Iterate through all child MapInfos
- #-----------------------------------------------------------------------------
- def each_child(data_has = $data_mapinfos)
- data_hash.each_value { |mapinfo| yield mapinfo if id == mapinfo.parent_id }
- end
- #-----------------------------------------------------------------------------
- # * Name without any bracketed information
- #-----------------------------------------------------------------------------
- def name
- return @name.gsub(/\[[^\]]*\]/) {""}
- end
- #-----------------------------------------------------------------------------
- # * Name including bracketed information
- #-----------------------------------------------------------------------------
- def name!
- return @name
- end
- #-----------------------------------------------------------------------------
- # * Returns Integer from [#xx] where # is variable
- #-----------------------------------------------------------------------------
- def bracketed(definer)
- return nil unless @name =~ /\[#{definer}[ ]*([0-9]+)\]/i
- return $1.to_i
- end
- #=============================================================================
- # Example methods for getting data from map name
- #=============================================================================
- #-----------------------------------------------------------------------------
- # * Name contains [OV], meaning it's an overworld map
- #-----------------------------------------------------------------------------
- def overworld?
- return @name.include?("[OV]")
- end
- #-----------------------------------------------------------------------------
- # * Name contains [Loop-Map], meaning it's a looping map
- #-----------------------------------------------------------------------------
- def loop_map?
- return @name.include?("[Loop-Map]")
- end
- #-----------------------------------------------------------------------------
- # * Returns Slant, ex. [#40]
- #-----------------------------------------------------------------------------
- def slant
- return bracketed('#')
- end
- #-----------------------------------------------------------------------------
- # * Returns Encounter rate, ex. [encounter-rate: 50]
- #-----------------------------------------------------------------------------
- def level
- return bracketed('encounter-rate:')
- end
- end
- # Here we define the global data variable, and set the :id value for each one
- $data_mapinfos = load_data('Data/MapInfos.rxdata')
- $data_mapinfos.each { |key, mapinfo| mapinfo.id = key }
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.
- #===============================================================================
- # ** User32
- #-------------------------------------------------------------------------------
- # Wrapper for user32.dll functions. Use "include User32" to get the constants
- #===============================================================================
- module User32
- GSM = Win32API.new('user32', 'GetSystemMetrics', 'I', 'I')
- SetWindowLong = Win32API.new('user32', 'SetWindowLong', 'LIL', 'L')
- SetWindowPos = Win32API.new('user32', 'SetWindowPos', 'LLIIIII', 'I')
- Keybd_Event = Win32API.new('user32', 'keybd_event', 'LLLL', '')
- FindWindow = Win32API.new('user32', 'FindWindow', 'PP', 'L')
- SetForegroundWindow = Win32API.new('user32', 'SetForegroundWindow', 'L', 'L')
- GetCursorPos = Win32API.new('user32', 'GetCursorPos', 'P', 'I')
- ShowCursor = Win32API.new('user32', 'ShowCursor', 'L', 'L')
- ScreenToClient = Win32API.new('user32', 'ScreenToClient', 'LP', 'I')
- GetKeyState = Win32API.new('user32', 'GetKeyState', 'I', 'I')
- GetAsyncKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'I', 'I')
- HWND = FindWindow.call('RGSS Player', Settings["Title"])
- # GSM constants. For more complete descriptions, see Microsoft's website:
- # http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx
- SM_CXSCREEN = 0 # Width of the current master screen resolution
- SM_CYSCREEN = 1 # Height of the current master screen resolution
- SM_CXVSCROLL = 2 # Width of a vertical scroll bar
- SM_CYHSCROLL = 3 # Height of a horizontal scroll bar
- SM_CYCAPTION = 4 # Height of a caption area
- SM_CXBORDER = 5 # Width of a window border
- SM_CYBORDER = 6 # Height of a window border
- SM_CXDLGFRAME = 7
- SM_CXFIXEDFRAME = 7 # Width of non-resizable captioned window frame
- SM_CYDLGFRAME = 8
- SM_CYFIXEDFRAME = 8 # Height of non-resizable captioned window frame
- SM_CYVTHUMB = 9 # Height of a thumb button on vertical scrollbars
- SM_CXHTHUMB = 10 # Width of a thumb button on horizontal scrollbars
- SM_CXICON = 11 # Default width of an icon
- SM_CYICON = 12 # Default height of an icon
- SM_CXCURSOR = 13 # Width of a cursor
- SM_CYCURSOR = 14 # Height of a cursor
- SM_CYMENU = 15 # Height of a single-line menu bar
- SM_CXFULLSCREEN = 16 # Width of client rect for a full-screen window
- SM_CYFULLSCREEN = 17 # Height of client rect for a full-screen window
- SM_CYKANJIWINDOW = 18 # Height of kanji window at bottom of screen, if there
- SM_MOUSEPRESENT = 19 # Non-zero if mouse is present; 0 if not
- SM_CYVSCROLL = 20 # Height of the arrow bitmap on vertical scrollbars
- SM_CXHSCROLL = 21 # Width of the arrow bitmap on horizontal scrollbars
- SM_DEBUG = 22 # Non-zero if debug User.exe is installed; 0 if not
- SM_SWAPBUTTON = 23 # Non-zero if mouse button values are swapped
- SM_CXMIN = 28 # Minimum width of a window
- SM_CYMIN = 29 # Minimum height of a window
- SM_CXSIZE = 30 # Width of a button in a window caption or title bar
- SM_CYSIZE = 31 # Height of a button in a window caption or title bar
- SM_CXFRAME = 32
- SM_CXSIZEFRAME = 32 # Width of the sizing border around a resizable window
- SM_CYFRAME = 33
- SM_CYSIZEFRAME = 33 # Height of the sizing border around a resizable window
- SM_CXMINTRACK = 34 # Minimum "tracking" width of a window
- SM_CYMINTRACK = 35 # Minimum "tracking" height of a window
- SM_CXDOUBLECLK = 36 # Width of rect which second click must be in for double
- SM_CYDOUBLECLK = 37 # Hght of rect which second click must be in for double
- SM_CXICONSPACING = 38 # Width of a grid cell for items in large icon view
- SM_CYICONSPACING = 39 # Height of a grid cell for items in large icon view
- SM_MENUDROPALIGNMENT = 40 # 0 if drop-down menus are left-aligned...
- SM_PENWINDOWS = 41 # Non-zero if Microsoft Windows for Pen computing
- # extensions are installed; 0 if not
- SM_DBCSENABLED = 42 # Non-zero if user32.dll supports DBCS; 0 if not
- SM_CMOUSEBUTTONS = 43 # Number of available mouse buttons, or 0 for no mouse
- SM_SECURE = 44 # Always returns 0
- SM_CXEDGE = 45 # Width of a 3-D style border
- SM_CYEDGE = 46 # Height of a 3-D style border
- SM_CXMINSPACING = 47 # Width of a grid cell for minimized windows
- SM_CYMINSPACING = 48 # Height of a grid cell for minimized windows
- SM_CXSMICON = 49 # Recommended width of a small icon
- SM_CYSMICON = 50 # Recommended height of a small icon
- SM_CYSMCAPTION = 51 # Height of a small caption
- SM_CXSMSIZE = 52 # Width of small caption buttons
- SM_CYSMSIZE = 53 # Height of small caption buttons
- SM_CXMENUSIZE = 54 # Width of menu bar buttons
- SM_CYMENUSIZE = 55 # Height of menu bar buttons
- SM_ARRANGE = 56 # Flags about how system the arranges minimized windows
- SM_CXMINIMIZED = 57 # Width of a minimized window
- SM_CYMINIMIZED = 58 # Height of a minimized window
- SM_CXMAXTRACK = 59 # Default maximum width of resizable windows
- SM_CYMAXTRACK = 60 # Default maximum height of resizable windows
- SM_CXMAXIMIZED = 61 # Default width of maximized top-level window
- SM_CYMAXIMIZED = 62 # Default height of maximized top-level window
- SM_NETWORK = 63 # The least significant bit is set if a network is
- # present; otherwise, it is cleared
- SM_CLEANBOOT = 67 # System boot type; 0:Normal, 1:Safe, 2:Safe w/network
- SM_CXDRAG = 68
- SM_CYDRAG = 69 # Number of pixels mouse can move before initiating drag
- SM_SHOWSOUNDS = 70 # Non-zero if user requires visible output; 0 if not
- SM_CXMENUCHECK = 71 # Width of the default menu check-mark bitmap
- SM_CYMENUCHECK = 72 # Height of the default menu check-mark bitmap
- SM_SLOWMACHINE = 73 # Non-zero if system has a slow processor; 0 if not
- # No, seriously, that's what Microsoft said!
- SM_MIDEASTENABLED = 74 # Non-zero if system can use Hebrew, Arabic languages
- SM_MOUSEWHEELPRESENT = 75 # Nonzero mouse has vertical scroll wheel; 0 if not
- SM_XVIRTUALSCREEN = 76 # Coordinates of the left side of the virtual screen
- SM_YVIRTUALSCREEN = 77 # Coordinates of the top of the virtual screen
- SM_CXVIRTUALSCREEN = 78 # Virtual width of all screens put together
- SM_CYVIRTUALSCREEN = 79 # Virtual height of all screen put together
- SM_CMONITORS = 80 # Numbers of display monitors on a desktop
- SM_SAMEDISPLAYFORMAT = 81 # Non-zero if all screen use same color depth...
- # SetWindowPos constants
- HWND_NOTOPMOST = -2 # Make window not always on top (and bring to front)
- HWND_TOPMOST = -1 # Put window in front and make it always on top
- HWND_TOP = 0 # Put window in front of all non-topmost windows
- HWND_BOTTOM = 1 # Put window behind all other windows
- SWP_NOSIZE = 0x0001 # Keep current size (ignores w and h)
- SWP_NOMOVE = 0x0002 # Keep current position (ignores X and Y)
- SWP_NOZORDER = 0x0004 # Keep current Z order (ignores hWndInsertAfter)
- SWP_NOREDRAW = 0x0008 # Does NOT redraw changes
- SWP_NOACTIVATE = 0x0010 # Does NOT automatically activate the window
- SWP_FRAMECHANGED = 0x0020 # Applies new frame styles set with SetWindowLong
- SWP_SHOWWINDOW = 0x0040 # Displays the window
- SWP_HIDEWINDOW = 0x0080 # Hides the window
- SWP_NOCOPYBITS = 0x0100 # Discards the entire contents of the client area
- SWP_NOOWNERZORDER = 0x0200 # Doesn't change the window display order
- SWP_NOSENDCHANGING = 0x0400 # Don't send WM_WINDOWPOSCHANGING
- SWP_DEFERERASE = 0x2000 # Prevents generation of the WM_SYNCPAINT message
- SWP_ASYNCWINDOWPOS = 0x4000 # Use if calling thread does not own the window
- end
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.
EDIT: Added flash data, which is criminally easy with this approach.
- #===============================================================================
- # ** Tilemap
- #-------------------------------------------------------------------------------
- # rey meustrus and SephirothSpawn
- # Version 2.0
- # 2010-02-02
- # SDK : Version 2.0+, Parts I & II
- #-------------------------------------------------------------------------------
- # * Credits :
- #
- # Thanks to Trickster for conversion formula for Hexidecimal to rgb.
- # Thanks to trebor777 for helping with the priority bug from the 0.9 version.
- #-------------------------------------------------------------------------------
- # * Version History :
- #
- # Version 0.9 -------------------------------------------------- (??????????)
- # Version 1 ---------------------------------------------------- (2007-05-30)
- # Version 1.1 ------------------------------------------------- (2007-07-20)
- # - Update : Removed pointless block. Move RPG::Cache.autotile to MACL.
- # Version 1.11 ------------------------------------------------ (2007-07-31)
- # Version 2.0 ------------------------------------------------- (2010-02-02)
- #-------------------------------------------------------------------------------
- # * Description :
- #
- # This script was designed to re-write the default RGSS Hidden Tilemap class.
- # The script has many added features via read/write variables.
- #-------------------------------------------------------------------------------
- # * Instructions :
- #
- # Place The Script Below the SDK and Above Main.
- #-------------------------------------------------------------------------------
- # * Syntax :
- #
- # Get Autotile Tile Bitmap
- # - RPG::Cache.autotile_tile(autotile_filename, tile_id[, hue[, frame_id]])
- #
- # autotile_filename : Filename of autotile
- # tile_id : ID of tile (Found from RPG::Map.data)
- # hue (Optional) : Hue for tile
- # frame_id (Optional) : Frame of tile (for animated autotiles)
- #
- # * Tilemap Syntax
- #
- # - tile(tile_id) : Gets bitmap for tile_id
- # - tile(x, y, z) : Gets bitmap at coordinates using @map_data
- # - priority(tile_id) : Gets Z value for tile_id
- # - priority(x, y, z) : Gets Z value at coordinates
- #
- # Readable Attributes :
- # - viewport : Viewport used for sprites
- # - width : Total pixel width of the Tilemap
- # - height : Total pixel height of the Tilemap
- #
- # Readable/Writable Attributes :
- # - map_data : 3D Table of Tile ID Data
- # - flash_data : 3D Table of Tile Color Data
- # - priorities : 3D Table of Tile Priorities
- # - hue : Hue adjustment for all tiles
- # - ox, oy : Tilemap layer offsets
- # - zoom : Zoom value as fraction
- # - tilesize : Zoom value as size of individual tile (normal is 32.0)
- # - tileset_name : Name of Bitmap
- # - autotile_names : Array of Autotile Filenames
- # - visible : Tilemap Visible Flag
- # - static : Static Flag (no animated autotiles)
- # - is_a_plane : Behaves like a Plane (loops around edges)
- #===============================================================================
- #-------------------------------------------------------------------------------
- # SDK Log
- #-------------------------------------------------------------------------------
- SDK.log('Tilemap', 'rey meustrus and SephirothSpawn', 2.0, '2010-02-02')
- #===============================================================================
- # ** RPG::Cache
- #===============================================================================
- module RPG::Cache
- #-----------------------------------------------------------------------------
- # * Constants
- #-----------------------------------------------------------------------------
- Animated_Autotile_Frames = 16
- Empty_Bitmap = Bitmap.new(32, 32)
- Default_Rect = Rect.new(0, 0, 32, 32)
- Autotiles = [
- [[26, 27, 32, 33], [ 4, 27, 32, 33], [26, 5, 32, 33], [ 4, 5, 32, 33],
- [26, 27, 32, 11], [ 4, 27, 32, 11], [26, 5, 32, 11], [ 4, 5, 32, 11]],
- [[26, 27, 10, 33], [ 4, 27, 10, 33], [26, 5, 10, 33], [ 4, 5, 10, 33],
- [26, 27, 10, 11], [ 4, 27, 10, 11], [26, 5, 10, 11], [ 4, 5, 10, 11]],
- [[24, 25, 30, 31], [24, 5, 30, 31], [24, 25, 30, 11], [24, 5, 30, 11],
- [14, 15, 20, 21], [14, 15, 20, 11], [14, 15, 10, 21], [14, 15, 10, 11]],
- [[28, 29, 34, 35], [28, 29, 10, 35], [ 4, 29, 34, 35], [ 4, 29, 10, 35],
- [38, 39, 44, 45], [ 4, 39, 44, 45], [38, 5, 44, 45], [ 4, 5, 44, 45]],
- [[24, 29, 30, 35], [14, 15, 44, 45], [12, 13, 18, 19], [12, 13, 18, 11],
- [16, 17, 22, 23], [16, 17, 10, 23], [40, 41, 46, 47], [ 4, 41, 46, 47]],
- [[36, 37, 42, 43], [36, 5, 42, 43], [12, 17, 18, 23], [12, 13, 42, 43],
- [36, 41, 42, 47], [16, 17, 46, 47], [12, 17, 42, 47], [ 0, 1, 6, 7]]
- ]
- #-----------------------------------------------------------------------------
- # * Normal or Autotile Tile
- #-----------------------------------------------------------------------------
- def self.tile!(tileset_name, autotile_names, tile_id, hue = 0)
- return Empty_Bitmap if tile_id == 0
- return self.tile(tileset_name, tile_id, hue) if tile_id >= 384
- # After this point, we are an autorile
- filename = autotile_names[tile_id / 48 - 1]
- autotile = self.autotile(filename)
- # Reconfigure Tile ID
- tile_id %= 48
- # Creates Key
- key = [filename, tile_id, hue]
- # If Key Not Found
- if not @cache.has_key?(key) or @cache[key].disposed?
- # Creates Bitmap
- bitmap = Bitmap.new(autotile.width / 3, 32)
- # Collects Auto-Tile Tile Layout
- tiles = Autotiles[tile_id / 8][tile_id % 8]
- # Draws Auto-Tile Rects
- tiles.each_with_index do |tile_position, i|
- for frame_id in 0..(autotile.width / 96)
- src_rect = Rect.new(tile_position % 6 * 16 + frame_id * 96,
- tile_position / 6 * 16, 16, 16)
- bitmap.blt(i % 2 * 16 + frame_id * 32, i / 2 * 16, autotile, src_rect)
- end
- end
- # Saves Autotile to Cache
- @cache[key] = bitmap
- # Change Hue
- @cache[key].hue_change(hue)
- end
- @cache[key]
- end
- #-----------------------------------------------------------------------------
- # * Tile Rect
- #-----------------------------------------------------------------------------
- def self.tile_rect(tileset_name, autotile_names, tile_id)
- return Default_Rect if tile_id == 0 or tile_id >= 384
- autotile = self.autotile(filename = autotile_names[tile_id / 48 - 1])
- # Configures Animation Offset
- fc = (Graphics.frame_count/Animated_Autotile_Frames) % (autotile.width/96)
- @cache[fc] = Rect.new(fc * 32, 0, 32, 32) if not @cache.has_key?(fc)
- @cache[fc]
- end
- end
- #===============================================================================
- # ** Game_Character
- #-------------------------------------------------------------------------------
- # Remove $game_map.screen_y from Z processing so Tilemap doesn't have to
- # process Z value every time screen_y changes
- #===============================================================================
- class Game_Character
- #-----------------------------------------------------------------------------
- # * Get Screen Z-Coordinates
- # height : character height
- #-----------------------------------------------------------------------------
- def screen_z(height = 0)
- # If display flag on closest surface is ON
- if @always_on_top
- # 999, unconditional
- return 999
- end
- # Get screen coordinates from real coordinates and map display position
- z = (@real_y + 3) / 4 + 32
- # If tile
- if @tile_id > 0
- # Add tile priority * 32
- return z + $game_map.priorities[@tile_id] * 32
- # If character
- else
- # If height exceeds 32, then add 31
- return z + ((height > 32) ? 31 : 0)
- end
- end
- end
- #===============================================================================
- # ** Spriteset_Map
- #===============================================================================
- class Spriteset_Map
- #-----------------------------------------------------------------------------
- # * Alias Listings
- #-----------------------------------------------------------------------------
- alias_method :seph_tilemap_ssmap_inittm, :init_tilemap
- #-----------------------------------------------------------------------------
- # * Tilemap Initialization
- #-----------------------------------------------------------------------------
- def init_tilemap
- # Original Tilemap Initialization
- seph_tilemap_ssmap_inittm
- # Set Tilemap Settings
- @tilemap.tileset_name = $game_map.tileset_name
- @tilemap.autotile_names = $game_map.autotile_names
- end
- end
- #===============================================================================
- # ** Tilemap
- #===============================================================================
- class Tilemap
- #-----------------------------------------------------------------------------
- # * Tilemap Options
- #-----------------------------------------------------------------------------
- Viewport_Padding = 2 # Number of tiles beyond viewport to refresh
- Flash_Alpha = 64 # Alpha value of the color of flash data
- #-----------------------------------------------------------------------------
- # * Public Instance Variables
- #-----------------------------------------------------------------------------
- attr_reader :viewport # Viewport for all sprites
- attr_reader :map_data # 3D Table of Tile Settings
- attr_reader :flash_data # 3D Table of Sprite Flash Colors
- attr_reader :priorities # 3D Table of Tileset Priorities
- attr_reader :hue # Hue Adjustment Value
- attr_accessor :ox # Bitmap Offsets
- attr_accessor :oy # Bitmap Offsets
- attr_reader :zoom # Zoom Fraction
- attr_reader :tileset_name # Tileset Filename
- attr_reader :autotile_names # Array of Autotile Filenames
- attr_reader :visible # Tilemap Visibility
- attr_accessor :static # No Animated Autotiles
- attr_accessor :is_a_plane # Loops around edges
- attr_accessor :tileset # Deprecated
- attr_accessor :autotiles # Deprecated
- #-----------------------------------------------------------------------------
- # * Object Initialization
- #-----------------------------------------------------------------------------
- def initialize(viewport = nil)
- @viewport = viewport
- @map_data = nil
- @flash_data = nil
- @priorities = nil
- @hue = 0
- @ox = 0
- @oy = 0
- @zoom = 1.0
- @tileset_name = nil
- @autotile_names = []
- @visible = true
- @static = false
- @is_a_plane = false
- @sprites = {}
- @disposed = false
- @refresh_autotiles = true
- @autotiles = []
- end
- #-----------------------------------------------------------------------------
- # * Total pixel width
- #-----------------------------------------------------------------------------
- def width
- return 0 if @map_data.nil?
- @map_data.xsize * 32
- end
- #-----------------------------------------------------------------------------
- # * Total pixel height
- #-----------------------------------------------------------------------------
- def height
- return 0 if @map_data.nil?
- @map_data.ysize * 32
- end
- #-----------------------------------------------------------------------------
- # * Set Map Data
- #-----------------------------------------------------------------------------
- def map_data=(map_data)
- return if @map_data == map_data
- @map_data = map_data
- refresh
- end
- #-----------------------------------------------------------------------------
- # * Set Flash Data
- #-----------------------------------------------------------------------------
- def flash_data=(flash_data)
- return if @flash_data == flash_data
- @flash_data = flash_data
- @sprites.each do |key, sprite|
- if not flash_data.nil? and (hex = flash_data[*key]) != 0
- sprite.color.red = (hex / 256) * 16
- sprite.color.green = ((hex / 16) % 16) * 16
- sprite.color.blue = (hex % 16) * 16
- sprite.color.alpha = Flash_Alpha
- else
- sprite.color.alpha = 0
- end
- end
- Graphics.frame_reset
- end
- #-----------------------------------------------------------------------------
- # * Set Priorities
- #-----------------------------------------------------------------------------
- def priorities=(priorities)
- return if @priorities == priorities
- @priorities = priorities
- refresh
- end
- #-----------------------------------------------------------------------------
- # * Set Hue
- #-----------------------------------------------------------------------------
- def hue=(hue)
- return if @hue == hue
- @hue = hue
- refresh
- end
- #-----------------------------------------------------------------------------
- # * Set OX value
- #-----------------------------------------------------------------------------
- def ox=(ox)
- return if @ox == ox
- @ox = ox
- @sprites.each { |key, sprite| sprite.ox = ox }
- end
- #-----------------------------------------------------------------------------
- # * Set OX value
- #-----------------------------------------------------------------------------
- def oy=(oy)
- return if @oy == oy
- @oy = oy
- @sprites.each { |key, sprite| sprite.oy = oy }
- end
- #-----------------------------------------------------------------------------
- # * Get Tile Size
- #-----------------------------------------------------------------------------
- def tilesize
- (zoom * 32).to_i
- end
- #-----------------------------------------------------------------------------
- # * Set Tile Size
- #-----------------------------------------------------------------------------
- def tilesize=(tilesize)
- self.zoom = tilesize / 32.0
- end
- #-----------------------------------------------------------------------------
- # * Set Zoom Fraction
- #-----------------------------------------------------------------------------
- def zoom=(zoom)
- return if @zoom == zoom
- @zoom = zoom
- @sprites.each do |key, sprite|
- sprite.zoom_x = sprite.zoom_y = zoom
- sprite.x = key.at(0) * tilesize
- sprite.y = key.at(1) * tilesize
- end
- Graphics.frame_reset
- end
- #-----------------------------------------------------------------------------
- # * Set Visibility
- #-----------------------------------------------------------------------------
- def visible=(visible)
- return if @visible == visible
- @visible = visible
- @sprites.each_value { |sprite| sprite.visible = visible }
- end
- #-----------------------------------------------------------------------------
- # * Set Tileset Name
- #-----------------------------------------------------------------------------
- def tileset_name=(name)
- return if @tileset_name == name
- @tileset_name = name
- refresh
- end
- #-----------------------------------------------------------------------------
- # * Set Autotile Names
- #-----------------------------------------------------------------------------
- def autotile_names=(names)
- return if @autotile_names == names
- @autotile_names = names
- refresh
- end
- #-----------------------------------------------------------------------------
- # * Get bitmap at coordinates
- #-----------------------------------------------------------------------------
- def tile(*args)
- RPG::Cache.tile!(@tileset_name, @autotile_names, args_to_id(*args), @hue)
- end
- #-----------------------------------------------------------------------------
- # * Get bitmap rect at coordinates
- #-----------------------------------------------------------------------------
- def tile_rect(*args)
- RPG::Cache.tile_rect(@tileset_name, @autotile_names, args_to_id(*args))
- end
- #-----------------------------------------------------------------------------
- # * Get priority at coordinates
- #-----------------------------------------------------------------------------
- def priority(x, y, z)
- priority = @priorities[@map_data[x, y, z]]
- return 0 if priority == 0
- (y + priority) * 32 + 64
- end
- #-----------------------------------------------------------------------------
- # * Find tile_id from args
- #-----------------------------------------------------------------------------
- def args_to_id(*args)
- if args.size == 1
- return args[0]
- elsif args.size == 3
- return @map_data[*args]
- else
- raise ArgumentError, "Only one (tile_id) or three (x, y, z) args allowed"
- end
- end
- #-----------------------------------------------------------------------------
- # * Dispose
- #-----------------------------------------------------------------------------
- def dispose
- # Dispose Sprites
- @sprites.each_value { |sprite| sprite.dispose }
- # Set Disposed Flag to True
- @disposed = true
- end
- #-----------------------------------------------------------------------------
- # * Disposed?
- #-----------------------------------------------------------------------------
- def disposed?
- @disposed
- end
- #-----------------------------------------------------------------------------
- # * Frame Update
- #-----------------------------------------------------------------------------
- def update
- if @is_a_plane
- # Get Visible X Tiles
- x1 = @ox / 32 - Viewport_Padding
- x2 = @ox / 32 + @viewport.rect.width / tilesize + Viewport_Padding
- # Get Visible Y Tiles
- y1 = @oy / 32 - Viewport_Padding
- y2 = @oy / 32 + @viewport.rect.height / tilesize + Viewport_Padding
- # Wrapped values
- _x1 = x1 % @map_data.xsize
- _x2 = x2 % @map_data.xsize
- _y1 = y1 % @map_data.ysize
- _y2 = y2 % @map_data.ysize
- # Behave like a Plane
- tsize = tilesize
- each_visible_sprite do |x, y, z, sprite|
- if x > x2 and x >= _x1
- sprite.x = (x - @map_data.xsize) * tsize
- elsif x < x1 and x <= _x2
- sprite.x = (x + @map_data.xsize) * tsize
- else
- sprite.x = x * tsize
- end
- if y > y2 and y >= _y1
- sprite.y = (y - @map_data.ysize) * tsize
- elsif y < y1 and y <= _y2
- sprite.y = (y + @map_data.ysize) * tsize
- else
- sprite.y = y * tsize
- end
- end
- end
- # If Not Static and Autotile Reset Frame
- if Graphics.frame_count % RPG::Cache::Animated_Autotile_Frames == 0
- refresh_autotiles unless @static
- end
- end
- #-----------------------------------------------------------------------------
- # * Refresh
- #-----------------------------------------------------------------------------
- def refresh
- return if @map_data.nil? or @tileset_name.nil? or @autotile_names.size < 7
- @sprites.each_value { |sprite| sprite.dispose }
- @sprites.clear
- # Passes Through X Coordinates
- for x in 0...@map_data.xsize
- # Passes Through Z Coordinates
- for y in 0...@map_data.ysize
- # Passes Through Layers
- for z in 0...@map_data.zsize
- # Collects Tile ID
- id = @map_data[x, y, z]
- # Skip if 0 tile
- next if id == 0
- sprite = find_sprite(x, y, z)
- # Draw Tile
- sprite.bitmap = tile(id)
- sprite.src_rect = tile_rect(id)
- sprite.z = priority(x, y, z)
- end
- end
- end
- Graphics.frame_reset
- end
- #-----------------------------------------------------------------------------
- # * Refresh Auto-Tiles; only affects visible animated autotiles
- #-----------------------------------------------------------------------------
- def refresh_autotiles
- each_visible_sprite do |x, y, z, sprite|
- # Collects Tile ID
- id = @map_data[x, y, z]
- # Skip if 0 tile, or if not autotile
- next if id == 0 or id >= 384
- # Skip If Non-Animated Tile
- bitmap = RPG::Cache.autotile(@autotile_names[id / 48 - 1])
- next unless bitmap.width / 96 > 1
- # Draw Tile
- find_sprite(x, y, z).src_rect = tile_rect(id)
- end
- Graphics.frame_reset
- end
- #-----------------------------------------------------------------------------
- # * Find or create sprite at coordinates
- #-----------------------------------------------------------------------------
- def find_sprite(x, y, z, create = true)
- return @sprites[[x, y, z]] if @sprites.has_key?([x, y, z])
- return nil unless create
- sprite = Sprite.new(@viewport)
- sprite.visible = @visible
- sprite.x = x * tilesize
- sprite.y = y * tilesize
- sprite.ox = @ox
- sprite.oy = @oy
- sprite.zoom_x = sprite.zoom_y = @zoom
- @sprites[[x, y, z]] = sprite
- end
- #-----------------------------------------------------------------------------
- # * Dispose of sprite at coordinates
- #-----------------------------------------------------------------------------
- def dispose_sprite(x, y, z)
- return unless @sprites.has_key?([x, y, z])
- @sprites[[x, y, z]].dispose
- @sprites.delete([x, y, z])
- end
- #-----------------------------------------------------------------------------
- # * Iterate through visible sprites
- #-----------------------------------------------------------------------------
- def each_visible_sprite
- # Get Visible X Tiles
- x1 = (@ox / 32 - Viewport_Padding) % @map_data.xsize
- x2 = (@ox / 32 + @viewport.rect.width / tilesize + Viewport_Padding) %
- @map_data.xsize
- # Get Visible Y Tiles
- y1 = (@oy / 32 - Viewport_Padding) % @map_data.ysize
- y2 = (@oy / 32 + @viewport.rect.height / tilesize + Viewport_Padding) %
- @map_data.ysize
- @sprites.each do |key, sprite|
- send_sprite = true
- if x1 < x2
- send_sprite &= key.at(0).between?(x1, x2)
- else
- send_sprite &= key.at(0) > x1 || key.at(0) < x2
- end
- if y1 < y2
- send_sprite &= key.at(1).between?(y1, y2)
- else
- send_sprite &= key.at(1) > y1 || key.at(1) < y2
- end
- yield key.at(0), key.at(1), key.at(2), sprite if send_sprite
- end
- end
- end
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 !
how to swap variables without the use of a temporary variable? MAke use of parallel assignement !
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:
Just comment the __END__ when you want to test.
*hugs*
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:
- class Medal
- include Comparable
- attr_reader :titel, :time
- def initialize(titel, time)
- unless time.is_a?(Numeric)
- raise ArgumentError.new("Time must be a numeric")
- end
- @titel = titel
- @time = time
- end
- def <=>(medal)
- return time <=> medal.time
- end
- end
- __END__
- class TestError < StandardError; end
- bronze = Medal.new('Bronze', 180)
- bronze2 = Medal.new('Bronze', 180)
- bronze3 = Medal.new('Bronze3', 180)
- silver = Medal.new('Silver', 105)
- gold = Medal.new('Gold', 87.5)
- unless (bronze == bronze2)
- raise TestError.new("Medal.== does not compare #{bronze.inspect} " +
- "and #{bronze2.inspect} properly")
- end
- unless (bronze == bronze3)
- raise TestError.new("Medal.== does not ignore the title")
- end
- unless (silver <=> bronze) == -1
- raise TestError.new("Medal.<=> does not return -1 when its time is less" +
- " than the medal compared to")
- end
- unless (silver <=> gold) == 1
- raise TestError.new("Medal.<=> does not return 1 when its time is greater" +
- " than the medal compared to")
- end
- unless (bronze <=> gold) == 1
- raise TestError.new("Medal.<=> does not preserve transitivity.\n" +
- "I.e. <=> is highly problematic.")
- end
- 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.
Horray for filtering. :box:
- #==============================================================================
- # ** Equipment Optimzer
- #------------------------------------------------------------------------------
- # SephirothSpawn
- # Version 1.0
- # 2010-02-18
- #==============================================================================
- module EquipmentOptimzer
- #--------------------------------------------------------------------------
- # * Weapon Priorities
- #
- # Defines stat priorities looking for when passing through equipment
- #
- # Weapon_Priorities[actor_id] = [:stat_name, ...]
- #--------------------------------------------------------------------------
- Weapon_Priorities = {}
- Weapon_Priorities.default = [
- :atk, :str_plus, :pdef, :mdef, :dex_plus, :agi_plus, :int_plus
- ]
- #--------------------------------------------------------------------------
- # * Armor Priorities
- #
- # Defines stat priorities looking for when passing through equipment
- #
- # Armor_Priorities[actor_id] = [:stat_name, ...]
- #--------------------------------------------------------------------------
- Armor_Priorities = {}
- Armor_Priorities.default = [
- :pdef, :mdef, :eva, :dex_plus, :str_plus, :agi_plus, :int_plus
- ]
- #--------------------------------------------------------------------------
- # * Optimize Weapon
- #--------------------------------------------------------------------------
- def self.optimze_weapon(actor)
- # Return if actor cannot equip
- return if actor.equip_fix?(0)
- # Unequip current weapon
- actor.equip(0, 0)
- # Gather equippable weapons list
- weapons = []
- for weapon in $data_weapons
- next if weapon == nil
- next unless actor.equippable?(weapon)
- if $game_party.weapon_number(weapon.id) > 0
- weapons << weapon
- end
- end
- # Stop if no weapons found
- return if weapons.size == 0
- # Equip if only 1 weapon found
- if weapons.size == 1
- actor.equip_item(weapons[0])
- return
- end
- # Pass through priority list
- Weapon_Priorities[actor.id].each do |stat|
- # Get new list based off priority
- weapons = self.best_stat(weapons, stat)
- # Stop cycle if only 1 weapon found
- break if weapons.size == 1
- end
- # Equip Item
- actor.equip_item(weapons[0])
- end
- #--------------------------------------------------------------------------
- # * Optimize Armor
- #--------------------------------------------------------------------------
- def self.optimze_armor(actor, kind)
- # Return if actor cannot equip
- return if actor.equip_fix?(kind + 1)
- # Unequip current armor
- case kind
- when 0 ; actor.equip(1, 0)
- when 1 ; actor.equip(2, 0)
- when 2 ; actor.equip(3, 0)
- when 3 ; actor.equip(4, 0)
- end
- # Gather equippable armors list
- armors = []
- for armor in $data_armors
- next if armor == nil
- next if armor.kind != kind
- next unless actor.equippable?(armor)
- if $game_party.armor_number(armor.id) > 0
- armors << armor
- end
- end
- # Stop if no armors found
- return if armors.size == 0
- # Equip if only 1 armor found
- if armors.size == 1
- actor.equip_item(armors[0])
- return
- end
- # Pass through priority list
- Armor_Priorities[actor.id].each do |stat|
- # Get new list based off priority
- armors = self.best_stat(armors, stat)
- # Stop cycle if only 1 armor found
- break if armors.size == 1
- end
- # Equip Item
- actor.equip_item(armors[0])
- end
- #--------------------------------------------------------------------------
- # * Filter list by max result
- #--------------------------------------------------------------------------
- def self.best_stat(list, stat)
- # Get max value
- max = (list.collect {|x| x.send(stat)}).max
- # Start new list
- a = []
- # Add item to list if max == stat
- list.each {|x| a << x if x.send(stat) == max}
- # Return list
- return a
- end
- end
- #==============================================================================
- # ** Game_Actor
- #==============================================================================
- class Game_Actor
- #--------------------------------------------------------------------------
- # * Equip Item
- #--------------------------------------------------------------------------
- def equip_item(item)
- # Branch by item type
- case item
- when RPG::Weapon
- # Return if fixed
- return if equip_fix?(0)
- # Return unless equippable
- return unless equippable?(item)
- # Equip
- equip(0, item.id)
- when RPG::Armor
- # Return if fixed
- return if equip_fix?(item.kind + 1)
- # Return unless equippable
- return unless equippable?(item)
- # Equip
- equip(item.kind + 1, item.id)
- end
- end
- #--------------------------------------------------------------------------
- # * Optimize
- #
- # type: -1 (all), 0 (weapon), 1-4 (armors)
- #--------------------------------------------------------------------------
- def optimize(type = -1)
- # Branch by type
- case type
- when -1
- # Optimize weapon
- EquipmentOptimzer.optimze_weapon(self)
- # Optimize all armor
- for i in 0..3
- EquipmentOptimzer.optimze_armor(self, i)
- end
- when 0
- # Optimize weapon
- EquipmentOptimzer.optimze_weapon(self)
- else
- # Optimize armor
- EquipmentOptimzer.optimze_armor(self, type - 1)
- end
- end
- 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.
Script call:
Map.name(id) #=> Dark Castle
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.
- module Map
- NAME = load_data(Dir.glob('Data/MapInfos*').to_s)
- def self.name(map_id); NAME[map_id].name.sub(/@.*/, '') end
- 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.
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:
Just press alt when you are in the title screen. Works like a charm.
- #==============================================================================
- # ** AnimatedTextSprite
- #------------------------------------------------------------------------------
- # SephirothSpawn
- # Version 1.0
- # 2010-02-18
- #==============================================================================
- class AnimatedTextSprite < Sprite
- #--------------------------------------------------------------------------
- # * Object Initialization
- #--------------------------------------------------------------------------
- def initialize(width, height, viewport = nil)
- super(viewport)
- self.bitmap = Bitmap.new(width, height)
- @text, @speed = [], 6
- end
- #--------------------------------------------------------------------------
- # * Refresh
- #--------------------------------------------------------------------------
- def refresh(text, speed = @speed, max_height = true)
- # Clear bitmap
- self.bitmap.clear
- # Save speed
- @speed = [speed, 1].max
- # Start text lines
- @lines = [[]]
- # Start x counter
- x = 0
- # Start text array
- @text = [[]]
- # Space width
- space_width = self.bitmap.text_size(' ').width
- # Pass through each word
- for word in text.split(' ')
- # Gets word width
- width = self.bitmap.text_size(word).width
- # If word cannot fit in line
- if x + width > self.bitmap.width
- # If x is 0
- if x == 0
- # Add word to line anyways
- word.split('').each {|s| @text.last << s}
- @text << []
- next
- end
- # Set x to width
- x = width + space_width
- # Add word to new line
- @text << []
- word.split('').each {|s| @text.last << s}
- @text.last << ' '
- next
- end
- # Add width and word
- x += width + space_width
- word.split('').each {|s| @text.last << s}
- @text.last << ' '
- end
- # Save text position and update
- @text_x = 0
- @text_y = 0
- @text_h = self.bitmap.font.size + 2
- # Max bitmap height
- max_bitmap_height if max_height
- update
- end
- #--------------------------------------------------------------------------
- # * Maximize Bitmap Height
- #--------------------------------------------------------------------------
- def max_bitmap_height
- # Get current number of text lines
- lines = @text.size
- # Get min height
- height = lines * @text_h
- # Resize bitmap if neccessary
- if self.bitmap.height < height
- self.bitmap = Bitmap.new(self.bitmap.width, height)
- end
- end
- #--------------------------------------------------------------------------
- # * Frame Update
- #--------------------------------------------------------------------------
- def update
- # Return if text is empty
- return if @text.empty?
- # Return if not draw frame
- return unless Graphics.frame_count % @speed == 0
- # Get current line of text
- line = @text.first
- # If empty line
- if line.empty?
- # Remove curremt line
- @text.shift
- # Return if empty
- return if @text.empty?
- # Adjust text position
- @text_x = 0
- @text_y += @text_h
- end
- # Get next character
- t = @text.first.shift
- # Draw character
- w = self.bitmap.text_size(t).width
- self.bitmap.draw_text(@text_x, @text_y, w + 2, @text_h, t)
- @text_x += w
- end
- 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:
- $test = AnimatedTextSprite.new(320, 32)
- $test.z = 999
- class Scene_Title
- alias update2 update
- def update
- $test.update
- $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)
- update2
- end
- 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