Bem vindo, Visitante
Faça
Login
ou
Registre-se
por favor.
Ou forneça o usuario e senha para fazer o login rapido!
[-]
home
|
arquivo
|
envie o seu
|
quem somos
|
portal
|
Pokéstarter
Inicio
Scripts
Imagens
Outros
Insira este script em outros foruns!
Pokéstarter
[
Selecionar
] [
-
]
[CENTER][SIZE=4][B]Pokéstarter[/B][/SIZE] [I]por Peter 0.[/I][/CENTER] [SIZE=2][B][U]Informações[/U][/B][/SIZE] [LIST] [*] [b]Autor:[/b] Peter 0.[*] [b]Versão:[/b] 13.04.2007[*] [b]Categoria:[/b] Miscellaneous Systems[*] [b]Classe:[/b] RGSS[*] [b]Demo:[/b] [url=www.devmakers.org/../uploads/up_scripts/30-pokestarter.rar]Pokéstarter[/url] [*] [b]Tamanho:[/b] 9,85 MB[/LIST] [SIZE=2][B][U]Descrição[/U][/B][/SIZE] Starter Kit completo com todos os sistemas necessários para se fazer um jogo de Pokémon. Trata-se, provavelmente, do maior conjunto de scripts de todo o mundo maker. A demo vem com todos os sons e imagens dos 493 pokémons. Porém as habilidades e ataques da 4ª geração não existem nessa versão. [B][U][SIZE=2]Instruções de Uso[/SIZE][/U][/B] Aconselho que criem um novo projeto em cima da demo pois são muitos scripts e todos são essênciais assim como todos os arquivos contidos na mesma. [B][U][SIZE=2]Screenshots[/SIZE][/U][/B] [spoiler] [CENTER] [IMG]http://www.devmakers.org/uploads/up_scripts/5423e29f6323f02df3a478d060d2342c.jpg[/IMG] [IMG]http://www.devmakers.org/uploads/up_scripts/84e4980c82ba6c3c24c9f4558db29ace.jpg[/IMG] [/CENTER] [/spoiler] [B][U][SIZE=2]Script[/SIZE][/U][/B] [spoiler] [CODE] class SpriteAnimation @@_animations = [] @@_reference_count = {} def initialize(sprite) @sprite=sprite end %w[ x y ox oy viewport flash src_rect opacity ].each_with_index do |s, i| eval <<-__END__ def #{s}(*arg) @sprite.#{s}(*arg) end __END__ end def self.clear @@_animations.clear end def dispose dispose_animation dispose_loop_animation end def animation(animation, hit) dispose_animation @_animation = animation return if @_animation == nil @_animation_hit = hit @_animation_duration = @_animation.frame_max animation_name = @_animation.animation_name animation_hue = @_animation.animation_hue bitmap = RPG::Cache.animation(animation_name, animation_hue) if @@_reference_count.include?(bitmap) @@_reference_count[bitmap] += 1 else @@_reference_count[bitmap] = 1 end @_animation_sprites = [] if @_animation.position != 3 or not @@_animations.include?(animation) for i in 0..15 sprite = ::Sprite.new(self.viewport) sprite.bitmap = bitmap sprite.visible = false @_animation_sprites.push(sprite) end unless @@_animations.include?(animation) @@_animations.push(animation) end end update_animation end def loop_animation(animation) return if animation == @_loop_animation dispose_loop_animation @_loop_animation = animation return if @_loop_animation == nil @_loop_animation_index = 0 animation_name = @_loop_animation.animation_name animation_hue = @_loop_animation.animation_hue bitmap = RPG::Cache.animation(animation_name, animation_hue) if @@_reference_count.include?(bitmap) @@_reference_count[bitmap] += 1 else @@_reference_count[bitmap] = 1 end @_loop_animation_sprites = [] for i in 0..15 sprite = ::Sprite.new(self.viewport) sprite.bitmap = bitmap sprite.visible = false @_loop_animation_sprites.push(sprite) end update_loop_animation end def dispose_animation if @_animation_sprites != nil sprite = @_animation_sprites[0] if sprite != nil @@_reference_count[sprite.bitmap] -= 1 if @@_reference_count[sprite.bitmap] == 0 sprite.bitmap.dispose end end for sprite in @_animation_sprites sprite.dispose end @_animation_sprites = nil @_animation = nil end end def dispose_loop_animation if @_loop_animation_sprites != nil sprite = @_loop_animation_sprites[0] if sprite != nil @@_reference_count[sprite.bitmap] -= 1 if @@_reference_count[sprite.bitmap] == 0 sprite.bitmap.dispose end end for sprite in @_loop_animation_sprites sprite.dispose end @_loop_animation_sprites = nil @_loop_animation = nil end end def active? @_loop_animation_sprites != nil || @_animation_sprites != nil end def effect? @_animation_duration > 0 end def update if @_animation != nil and (Graphics.frame_count % 2 == 0) @_animation_duration -= 1 update_animation end if @_loop_animation != nil and (Graphics.frame_count % 2 == 0) update_loop_animation @_loop_animation_index += 1 @_loop_animation_index %= @_loop_animation.frame_max end end def update_animation if @_animation_duration > 0 frame_index = @_animation.frame_max - @_animation_duration cell_data = @_animation.frames[frame_index].cell_data position = @_animation.position animation_set_sprites(@_animation_sprites, cell_data, position) for timing in @_animation.timings if timing.frame == frame_index animation_process_timing(timing, @_animation_hit) end end else dispose_animation end end def update_loop_animation frame_index = @_loop_animation_index cell_data = @_loop_animation.frames[frame_index].cell_data position = @_loop_animation.position animation_set_sprites(@_loop_animation_sprites, cell_data, position) for timing in @_loop_animation.timings if timing.frame == frame_index animation_process_timing(timing, true) end end end def animation_set_sprites(sprites, cell_data, position) for i in 0..15 sprite = sprites[i] pattern = cell_data[i, 0] if sprite == nil or pattern == nil or pattern == -1 sprite.visible = false if sprite != nil next end sprite.visible = true sprite.src_rect.set(pattern % 5 * 192, pattern / 5 * 192, 192, 192) if position == 3 if self.viewport != nil sprite.x = self.viewport.rect.width / 2 sprite.y = self.viewport.rect.height - 160 else sprite.x = 320 sprite.y = 240 end else sprite.x = self.x - self.ox + self.src_rect.width / 2 sprite.y = self.y - self.oy + self.src_rect.height / 2 sprite.y -= self.src_rect.height / 4 if position == 0 sprite.y += self.src_rect.height / 4 if position == 2 end sprite.x += cell_data[i, 1] sprite.y += cell_data[i, 2] sprite.z = 2000 sprite.ox = 96 sprite.oy = 96 sprite.zoom_x = cell_data[i, 3] / 100.0 sprite.zoom_y = cell_data[i, 3] / 100.0 sprite.angle = cell_data[i, 4] sprite.mirror = (cell_data[i, 5] == 1) sprite.opacity = cell_data[i, 6] * self.opacity / 255.0 sprite.blend_type = cell_data[i, 7] end end def animation_process_timing(timing, hit) if (timing.condition == 0) or (timing.condition == 1 and hit == true) or (timing.condition == 2 and hit == false) if timing.se.name != "" se = timing.se Audio.se_play("Audio/SE/" + se.name, se.volume, se.pitch) end case timing.flash_scope when 1 self.flash(timing.flash_color, timing.flash_duration * 2) when 2 if self.viewport != nil self.viewport.flash(timing.flash_color, timing.flash_duration * 2) end when 3 self.flash(nil, timing.flash_duration * 2) end end end def x=(x) sx = x - self.x if sx != 0 if @_animation_sprites != nil for i in 0..15 @_animation_sprites[i].x += sx end end if @_loop_animation_sprites != nil for i in 0..15 @_loop_animation_sprites[i].x += sx end end end end def y=(y) sy = y - self.y if sy != 0 if @_animation_sprites != nil for i in 0..15 @_animation_sprites[i].y += sy end end if @_loop_animation_sprites != nil for i in 0..15 @_loop_animation_sprites[i].y += sy end end end end end module RPG class Sprite < ::Sprite def initialize(viewport = nil) super(viewport) @_whiten_duration = 0 @_appear_duration = 0 @_escape_duration = 0 @_collapse_duration = 0 @_damage_duration = 0 @_animation_duration = 0 @_blink = false @animations=[] @loopAnimations=[] end def dispose dispose_damage dispose_animation dispose_loop_animation super end def whiten self.blend_type = 0 self.color.set(255, 255, 255, 128) self.opacity = 255 @_whiten_duration = 16 @_appear_duration = 0 @_escape_duration = 0 @_collapse_duration = 0 end def appear self.blend_type = 0 self.color.set(0, 0, 0, 0) self.opacity = 0 @_appear_duration = 16 @_whiten_duration = 0 @_escape_duration = 0 @_collapse_duration = 0 end def escape self.blend_type = 0 self.color.set(0, 0, 0, 0) self.opacity = 255 @_escape_duration = 32 @_whiten_duration = 0 @_appear_duration = 0 @_collapse_duration = 0 end def collapse self.blend_type = 1 self.color.set(255, 64, 64, 255) self.opacity = 255 @_collapse_duration = 48 @_whiten_duration = 0 @_appear_duration = 0 @_escape_duration = 0 end def damage(value, critical) dispose_damage if value.is_a?(Numeric) damage_string = value.abs.to_s else damage_string = value.to_s end bitmap = Bitmap.new(160, 48) bitmap.font.name = "Arial Black" bitmap.font.size = 32 bitmap.font.color.set(0, 0, 0) bitmap.draw_text(-1, 12-1, 160, 36, damage_string, 1) bitmap.draw_text(+1, 12-1, 160, 36, damage_string, 1) bitmap.draw_text(-1, 12+1, 160, 36, damage_string, 1) bitmap.draw_text(+1, 12+1, 160, 36, damage_string, 1) if value.is_a?(Numeric) and value < 0 bitmap.font.color.set(176, 255, 144) else bitmap.font.color.set(255, 255, 255) end bitmap.draw_text(0, 12, 160, 36, damage_string, 1) if critical bitmap.font.size = 20 bitmap.font.color.set(0, 0, 0) bitmap.draw_text(-1, -1, 160, 20, "CRITICAL", 1) bitmap.draw_text(+1, -1, 160, 20, "CRITICAL", 1) bitmap.draw_text(-1, +1, 160, 20, "CRITICAL", 1) bitmap.draw_text(+1, +1, 160, 20, "CRITICAL", 1) bitmap.font.color.set(255, 255, 255) bitmap.draw_text(0, 0, 160, 20, "CRITICAL", 1) end @_damage_sprite = ::Sprite.new(self.viewport) @_damage_sprite.bitmap = bitmap @_damage_sprite.ox = 80 @_damage_sprite.oy = 20 @_damage_sprite.x = self.x @_damage_sprite.y = self.y - self.oy / 2 @_damage_sprite.z = 3000 @_damage_duration = 40 end def pushAnimation(array,anim) for i in 0...array.length if !array[i] || !array[i].active? array[i]=anim return end end array.push(anim) end def animation(animation, hit) anim=SpriteAnimation.new(self) anim.animation(animation,hit) pushAnimation(@animations,anim) end def loop_animation(animation) anim=SpriteAnimation.new(self) anim.loop_animation(animation) pushAnimation(@loopAnimations,anim) end def dispose_damage if @_damage_sprite != nil @_damage_sprite.bitmap.dispose @_damage_sprite.dispose @_damage_sprite = nil @_damage_duration = 0 end end def dispose_animation for a in @animations a.dispose_animation if a end @animations.clear end def dispose_loop_animation for a in @loopAnimations a.dispose_loop_animation if a end @loopAnimations.clear end def blink_on unless @_blink @_blink = true @_blink_count = 0 end end def blink_off if @_blink @_blink = false self.color.set(0, 0, 0, 0) end end def blink? @_blink end def effect? return true if @_whiten_duration > 0 or @_appear_duration > 0 or @_escape_duration > 0 or @_collapse_duration > 0 or @_damage_duration > 0 for a in @animations return true if a.effect? end return false end def update super if @_whiten_duration > 0 @_whiten_duration -= 1 self.color.alpha = 128 - (16 - @_whiten_duration) * 10 end if @_appear_duration > 0 @_appear_duration -= 1 self.opacity = (16 - @_appear_duration) * 16 end if @_escape_duration > 0 @_escape_duration -= 1 self.opacity = 256 - (32 - @_escape_duration) * 10 end if @_collapse_duration > 0 @_collapse_duration -= 1 self.opacity = 256 - (48 - @_collapse_duration) * 6 end if @_damage_duration > 0 @_damage_duration -= 1 case @_damage_duration when 38..39 @_damage_sprite.y -= 4 when 36..37 @_damage_sprite.y -= 2 when 34..35 @_damage_sprite.y += 2 when 28..33 @_damage_sprite.y += 4 end @_damage_sprite.opacity = 256 - (12 - @_damage_duration) * 32 if @_damage_duration == 0 dispose_damage end end for a in @animations a.update end for a in @loopAnimations a.update end if @_blink @_blink_count = (@_blink_count + 1) % 32 if @_blink_count < 16 alpha = (16 - @_blink_count) * 6 else alpha = (@_blink_count - 16) * 6 end self.color.set(255, 255, 255, alpha) end SpriteAnimation.clear end def update_animation for a in @animations a.update_animation if a && a.active? end end def update_loop_animation for a in @loopAnimations a.update_loop_animation if a && a.active? end end def x=(x) sx = x - self.x for a in @animations a.x=x if a end for a in @loopAnimations a.x=x if a end super end def y=(y) sy = y - self.y for a in @animations a.x=x if a end for a in @loopAnimations a.x=x if a end super end end end[/CODE] [CODE]#============================================================================== # ** Game_Temp #------------------------------------------------------------------------------ # This class handles temporary data that is not included with save data. # Refer to "$game_temp" for the instance of this class. #============================================================================== class Game_Temp #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_accessor :map_bgm # map music (for battle memory) attr_accessor :message_text # message text attr_accessor :message_proc # message callback (Proc) attr_accessor :choice_start # show choices: opening line attr_accessor :choice_max # show choices: number of items attr_accessor :choice_cancel_type # show choices: cancel attr_accessor :choice_proc # show choices: callback (Proc) attr_accessor :num_input_start # input number: opening line attr_accessor :num_input_variable_id # input number: variable ID attr_accessor :num_input_digits_max # input number: digit amount attr_accessor :message_window_showing # message window showing attr_accessor :common_event_id # common event ID attr_accessor :in_battle # in-battle flag attr_accessor :battle_calling # battle calling flag attr_accessor :battle_troop_id # battle troop ID attr_accessor :battle_can_escape # battle flag: escape possible attr_accessor :battle_can_lose # battle flag: losing possible attr_accessor :battle_proc # battle callback (Proc) attr_accessor :battle_turn # number of battle turns attr_accessor :battle_event_flags # battle event flags: completed attr_accessor :battle_abort # battle flag: interrupt attr_accessor :battle_main_phase # battle flag: main phase attr_accessor :battleback_name # battleback file name attr_accessor :forcing_battler # battler being forced into action attr_accessor :shop_calling # shop calling flag attr_accessor :shop_goods # list of shop goods attr_accessor :name_calling # name input: calling flag attr_accessor :name_actor_id # name input: actor ID attr_accessor :name_max_char # name input: max character count attr_accessor :menu_calling # menu calling flag attr_accessor :menu_beep # menu: play sound effect flag attr_accessor :save_calling # save calling flag attr_accessor :debug_calling # debug calling flag attr_accessor :player_transferring # player place movement flag attr_accessor :player_new_map_id # player destination: map ID attr_accessor :player_new_x # player destination: x-coordinate attr_accessor :player_new_y # player destination: y-coordinate attr_accessor :player_new_direction # player destination: direction attr_accessor :transition_processing # transition processing flag attr_accessor :transition_name # transition file name attr_accessor :gameover # game over flag attr_accessor :to_title # return to title screen flag attr_accessor :last_file_index # last save file no. attr_accessor :debug_top_row # debug screen: for saving conditions attr_accessor :debug_index # debug screen: for saving conditions #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize @map_bgm = nil @message_text = nil @message_proc = nil @choice_start = 99 @choice_max = 0 @choice_cancel_type = 0 @choice_proc = nil @num_input_start = 99 @num_input_variable_id = 0 @num_input_digits_max = 0 @message_window_showing = false @common_event_id = 0 @in_battle = false @battle_calling = false @battle_troop_id = 0 @battle_can_escape = false @battle_can_lose = false @battle_proc = nil @battle_turn = 0 @battle_event_flags = {} @battle_abort = false @battle_main_phase = false @battleback_name = '' @forcing_battler = nil @shop_calling = false @shop_id = 0 @name_calling = false @name_actor_id = 0 @name_max_char = 0 @menu_calling = false @menu_beep = false @save_calling = false @debug_calling = false @player_transferring = false @player_new_map_id = 0 @player_new_x = 0 @player_new_y = 0 @player_new_direction = 0 @transition_processing = false @transition_name = "" @gameover = false @to_title = false @last_file_index = 0 @debug_top_row = 0 @debug_index = 0 end end [/CODE] [CODE]#============================================================================== # ** Game_Switches #------------------------------------------------------------------------------ # This class handles switches. It's a wrapper for the built-in class "Array." # Refer to "$game_switches" for the instance of this class. #============================================================================== class Game_Switches #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize @data = [] end #-------------------------------------------------------------------------- # * Get Switch # switch_id : switch ID #-------------------------------------------------------------------------- def [](switch_id) if switch_id <= 5000 and @data[switch_id] != nil return @data[switch_id] else return false end end #-------------------------------------------------------------------------- # * Set Switch # switch_id : switch ID # value : ON (true) / OFF (false) #-------------------------------------------------------------------------- def []=(switch_id, value) if switch_id <= 5000 @data[switch_id] = value end end end [/CODE] [CODE]#============================================================================== # ** Game_Variables #------------------------------------------------------------------------------ # This class handles variables. It's a wrapper for the built-in class "Array." # Refer to "$game_variables" for the instance of this class. #============================================================================== class Game_Variables #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize @data = [] end #-------------------------------------------------------------------------- # * Get Variable # variable_id : variable ID #-------------------------------------------------------------------------- def [](variable_id) if variable_id <= 5000 and @data[variable_id] != nil return @data[variable_id] else return 0 end end #-------------------------------------------------------------------------- # * Set Variable # variable_id : variable ID # value : the variable's value #-------------------------------------------------------------------------- def []=(variable_id, value) if variable_id <= 5000 @data[variable_id] = value end end end [/CODE] [CODE]#============================================================================== # ** Game_SelfSwitches #------------------------------------------------------------------------------ # This class handles self switches. It's a wrapper for the built-in class # "Hash." Refer to "$game_self_switches" for the instance of this class. #============================================================================== class Game_SelfSwitches #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize @data = {} end #-------------------------------------------------------------------------- # * Get Self Switch # key : key #-------------------------------------------------------------------------- def [](key) return @data[key] == true ? true : false end #-------------------------------------------------------------------------- # * Set Self Switch # key : key # value : ON (true) / OFF (false) #-------------------------------------------------------------------------- def []=(key, value) @data[key] = value end end [/CODE] [CODE]#============================================================================== # ** Game_Screen #------------------------------------------------------------------------------ # This class handles screen maintenance data, such as change in color tone, # flashing, etc. Refer to "$game_screen" for the instance of this class. #============================================================================== class Game_Screen #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_reader :tone # color tone attr_reader :flash_color # flash color attr_reader :shake # shake positioning attr_reader :pictures # pictures attr_reader :weather_type # weather type attr_reader :weather_max # max number of weather sprites #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize @tone = Tone.new(0, 0, 0, 0) @tone_target = Tone.new(0, 0, 0, 0) @tone_duration = 0 @flash_color = Color.new(0, 0, 0, 0) @flash_duration = 0 @shake_power = 0 @shake_speed = 0 @shake_duration = 0 @shake_direction = 1 @shake = 0 @pictures = [nil] for i in 1..100 @pictures.push(Game_Picture.new(i)) end @weather_type = 0 @weather_max = 0.0 @weather_type_target = 0 @weather_max_target = 0.0 @weather_duration = 0 end #-------------------------------------------------------------------------- # * Start Changing Color Tone # tone : color tone # duration : time #-------------------------------------------------------------------------- def start_tone_change(tone, duration) @tone_target = tone.clone @tone_duration = duration if @tone_duration == 0 @tone = @tone_target.clone end end #-------------------------------------------------------------------------- # * Start Flashing # color : color # duration : time #-------------------------------------------------------------------------- def start_flash(color, duration) @flash_color = color.clone @flash_duration = duration end #-------------------------------------------------------------------------- # * Start Shaking # power : strength # speed : speed # duration : time #-------------------------------------------------------------------------- def start_shake(power, speed, duration) @shake_power = power @shake_speed = speed @shake_duration = duration end #-------------------------------------------------------------------------- # * Set Weather # type : type # power : strength # duration : time #-------------------------------------------------------------------------- def weather(type, power, duration) @weather_type_target = type if @weather_type_target != 0 @weather_type = @weather_type_target end if @weather_type_target == 0 @weather_max_target = 0.0 else @weather_max_target = (power + 1) * 4.0 end @weather_duration = duration if @weather_duration == 0 @weather_type = @weather_type_target @weather_max = @weather_max_target end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update if @tone_duration >= 1 d = @tone_duration @tone.red = (@tone.red * (d - 1) + @tone_target.red) / d @tone.green = (@tone.green * (d - 1) + @tone_target.green) / d @tone.blue = (@tone.blue * (d - 1) + @tone_target.blue) / d @tone.gray = (@tone.gray * (d - 1) + @tone_target.gray) / d @tone_duration -= 1 end if @flash_duration >= 1 d = @flash_duration @flash_color.alpha = @flash_color.alpha * (d - 1) / d @flash_duration -= 1 end if @shake_duration >= 1 or @shake != 0 delta = (@shake_power * @shake_speed * @shake_direction) / 10.0 if @shake_duration <= 1 and @shake * (@shake + delta) < 0 @shake = 0 else @shake += delta end if @shake > @shake_power * 2 @shake_direction = -1 end if @shake < - @shake_power * 2 @shake_direction = 1 end if @shake_duration >= 1 @shake_duration -= 1 end end if @weather_duration >= 1 d = @weather_duration @weather_max = (@weather_max * (d - 1) + @weather_max_target) / d @weather_duration -= 1 if @weather_duration == 0 @weather_type = @weather_type_target end end if $game_temp.in_battle for i in 51..100 @pictures[i].update end else for i in 1..50 @pictures[i].update end end end end [/CODE] [CODE]#============================================================================== # ** Game_Picture #------------------------------------------------------------------------------ # This class handles the picture. It's used within the Game_Screen class # ($game_screen). #============================================================================== class Game_Picture #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_reader :number # picture number attr_reader :name # file name attr_reader :origin # starting point attr_reader :x # x-coordinate attr_reader :y # y-coordinate attr_reader :zoom_x # x directional zoom rate attr_reader :zoom_y # y directional zoom rate attr_reader :opacity # opacity level attr_reader :blend_type # blend method attr_reader :tone # color tone attr_reader :angle # rotation angle #-------------------------------------------------------------------------- # * Object Initialization # number : picture number #-------------------------------------------------------------------------- def initialize(number) @number = number @name = "" @origin = 0 @x = 0.0 @y = 0.0 @zoom_x = 100.0 @zoom_y = 100.0 @opacity = 255.0 @blend_type = 1 @duration = 0 @target_x = @x @target_y = @y @target_zoom_x = @zoom_x @target_zoom_y = @zoom_y @target_opacity = @opacity @tone = Tone.new(0, 0, 0, 0) @tone_target = Tone.new(0, 0, 0, 0) @tone_duration = 0 @angle = 0 @rotate_speed = 0 end #-------------------------------------------------------------------------- # * Show Picture # name : file name # origin : starting point # x : x-coordinate # y : y-coordinate # zoom_x : x directional zoom rate # zoom_y : y directional zoom rate # opacity : opacity level # blend_type : blend method #-------------------------------------------------------------------------- def show(name, origin, x, y, zoom_x, zoom_y, opacity, blend_type) @name = name @origin = origin @x = x.to_f @y = y.to_f @zoom_x = zoom_x.to_f @zoom_y = zoom_y.to_f @opacity = opacity.to_f @blend_type = blend_type @duration = 0 @target_x = @x @target_y = @y @target_zoom_x = @zoom_x @target_zoom_y = @zoom_y @target_opacity = @opacity @tone = Tone.new(0, 0, 0, 0) @tone_target = Tone.new(0, 0, 0, 0) @tone_duration = 0 @angle = 0 @rotate_speed = 0 end #-------------------------------------------------------------------------- # * Move Picture # duration : time # origin : starting point # x : x-coordinate # y : y-coordinate # zoom_x : x directional zoom rate # zoom_y : y directional zoom rate # opacity : opacity level # blend_type : blend method #-------------------------------------------------------------------------- def move(duration, origin, x, y, zoom_x, zoom_y, opacity, blend_type) @duration = duration @origin = origin @target_x = x.to_f @target_y = y.to_f @target_zoom_x = zoom_x.to_f @target_zoom_y = zoom_y.to_f @target_opacity = opacity.to_f @blend_type = blend_type end #-------------------------------------------------------------------------- # * Change Rotation Speed # speed : rotation speed #-------------------------------------------------------------------------- def rotate(speed) @rotate_speed = speed end #-------------------------------------------------------------------------- # * Start Change of Color Tone # tone : color tone # duration : time #-------------------------------------------------------------------------- def start_tone_change(tone, duration) @tone_target = tone.clone @tone_duration = duration if @tone_duration == 0 @tone = @tone_target.clone end end #-------------------------------------------------------------------------- # * Erase Picture #-------------------------------------------------------------------------- def erase @name = "" end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update if @duration >= 1 d = @duration @x = (@x * (d - 1) + @target_x) / d @y = (@y * (d - 1) + @target_y) / d @zoom_x = (@zoom_x * (d - 1) + @target_zoom_x) / d @zoom_y = (@zoom_y * (d - 1) + @target_zoom_y) / d @opacity = (@opacity * (d - 1) + @target_opacity) / d @duration -= 1 end if @tone_duration >= 1 d = @tone_duration @tone.red = (@tone.red * (d - 1) + @tone_target.red) / d @tone.green = (@tone.green * (d - 1) + @tone_target.green) / d @tone.blue = (@tone.blue * (d - 1) + @tone_target.blue) / d @tone.gray = (@tone.gray * (d - 1) + @tone_target.gray) / d @tone_duration -= 1 end if @rotate_speed != 0 @angle += @rotate_speed / 2.0 while @angle < 0 @angle += 360 end @angle %= 360 end end end [/CODE] [CODE] class Game_Map attr_accessor :tileset_name attr_accessor :autotile_names attr_accessor :panorama_name attr_accessor :panorama_hue attr_accessor :fog_name attr_accessor :fog_hue attr_accessor :fog_opacity attr_accessor :fog_blend_type attr_accessor :fog_zoom attr_accessor :fog_sx attr_accessor :fog_sy attr_accessor :battleback_name attr_accessor :display_x attr_accessor :display_y attr_accessor :need_refresh attr_reader :passages attr_reader :priorities attr_reader :terrain_tags attr_reader :events attr_reader :fog_ox attr_reader :fog_oy attr_reader :fog_tone attr_reader :mapsInRange def initialize @map_id = 0 @display_x = 0 @display_y = 0 end def setup(map_id) @map_id = map_id @map = load_data(sprintf("Data/Map%03d.rxdata", @map_id)) tileset = $data_tilesets[@map.tileset_id] @tileset_name = tileset.tileset_name @autotile_names = tileset.autotile_names @panorama_name = tileset.panorama_name @panorama_hue = tileset.panorama_hue @fog_name = tileset.fog_name @fog_hue = tileset.fog_hue @fog_opacity = tileset.fog_opacity @fog_blend_type = tileset.fog_blend_type @fog_zoom = tileset.fog_zoom @fog_sx = tileset.fog_sx @fog_sy = tileset.fog_sy @battleback_name = tileset.battleback_name @passages = tileset.passages @priorities = tileset.priorities @terrain_tags = tileset.terrain_tags self.display_x = 0 self.display_y = 0 @need_refresh = false Events.onMapCreate.trigger(self,map_id, @map, tileset) @events = {} for i in @map.events.keys @events[i] = Game_Event.new(@map_id, @map.events[i],self) end @common_events = {} for i in 1...$data_common_events.size @common_events[i] = Game_CommonEvent.new(i) end @fog_ox = 0 @fog_oy = 0 @fog_tone = Tone.new(0, 0, 0, 0) @fog_tone_target = Tone.new(0, 0, 0, 0) @fog_tone_duration = 0 @fog_opacity_duration = 0 @fog_opacity_target = 0 @scroll_direction = 2 @scroll_rest = 0 @scroll_speed = 4 end def map_id return @map_id end def width return @map.width end def height return @map.height end def encounter_list return @map.encounter_list end def encounter_step return @map.encounter_step end #-------------------------------------------------------------------------- # ● マップデータの取得 #-------------------------------------------------------------------------- def data return @map.data end def autoplayAsCue if @map.autoplay_bgm # Checks whether the map has an autoplay BGM if (Time.now.hour<6||Time.now.hour>=20) && # Checks if it's night time - the values are editable FileTest.audio_exist?("Audio/BGM/"+ @map.bgm.name+ "n") # Checks whether a BGM file with the filename [normal BGM]n exists pbCueBGM( RPG::AudioFile.new(@map.bgm.name+"n", @map.bgm.volume,@map.bgm.pitch),1.0) # Plays it else pbCueBGM(@map.bgm,1.0) # Plays the normal BGM end end if @map.autoplay_bgs $game_system.bgs_play(@map.bgs) end end def autoplay if @map.autoplay_bgm # Checks whether the map has an autoplay BGM if (Time.now.hour<6||Time.now.hour>=20) && # Checks if it's night time - the values are editable FileTest.audio_exist?("Audio/BGM/"+ @map.bgm.name+ "n") # Checks whether a BGM file with the filename [normal BGM]n exists $game_system.bgm_play(@map.bgm.name+"n", @map.bgm.volume,@map.bgm.pitch) # Plays it else $game_system.bgm_play(@map.bgm) # Plays the normal BGM end end if @map.autoplay_bgs $game_system.bgs_play(@map.bgs) end end def refresh if @map_id > 0 for event in @events.values event.refresh end for common_event in @common_events.values common_event.refresh end end @need_refresh = false end def scroll_down(distance) @display_y = [@display_y + distance, (self.height - 15) * 128].min end def scroll_left(distance) @display_x = [@display_x - distance, 0].max end def scroll_right(distance) @display_x = [@display_x + distance, (self.width - 20) * 128].min end def scroll_up(distance) @display_y = [@display_y - distance, 0].max end def valid?(x, y) return (x >= 0 and x < width and y >= 0 and y < height) end def validLax?(x, y) return (x >=-10 and x <= width+10 and y >=-10 and y <= height+10) end def passable?(x, y, d, self_event = nil) return false if !valid?(x, y) bit = (1 << (d / 2 - 1)) & 0x0f for event in events.values if event.tile_id >= 0 and event != self_event and event.x == x and event.y == y and not event.through return false if @passages[event.tile_id] & bit != 0 return false if @passages[event.tile_id] & 0x0f == 0x0f return true if @priorities[event.tile_id] == 0 end end for i in [2, 1, 0] tile_id = data[x, y, i] if tile_id == nil return false # Make water tiles passable if player is surfing elsif pbIsPassableWaterTag?(@terrain_tags[tile_id]) && $PokemonGlobal.surfing return true elsif @passages[tile_id] & bit != 0 return false elsif @passages[tile_id] & 0x0f == 0x0f return false elsif @priorities[tile_id] == 0 return true end end return true end def passableStrict?(x, y, d, self_event = nil) return false if !valid?(x, y) for event in events.values if event.tile_id >= 0 and event != self_event and event.x == x and event.y == y and not event.through return false if @passages[event.tile_id] & 0x0f !=0 return true if @priorities[event.tile_id] == 0 end end for i in [2, 1, 0] tile_id = data[x, y, i] return false if tile_id == nil return false if @passages[tile_id] & 0x0f !=0 return true if @priorities[tile_id] == 0 end return true end def bush?(x, y) if @map_id != 0 for i in [2, 1, 0] tile_id = data[x, y, i] if tile_id == nil return false elsif @passages[tile_id] & 0x40 == 0x40 return true end end end return false end def counter?(x, y) if @map_id != 0 for i in [2, 1, 0] tile_id = data[x, y, i] if tile_id == nil return false elsif @passages[tile_id] && @passages[tile_id] & 0x80 == 0x80 return true end end end return false end def terrain_tag(x, y) if @map_id != 0 for i in [2, 1, 0] tile_id = data[x, y, i] if tile_id == nil return 0 elsif @terrain_tags[tile_id] && @terrain_tags[tile_id] > 0 return @terrain_tags[tile_id] end end end return 0 end def check_event(x, y) for event in self.events.values if event.x == x and event.y == y return event.id end end end def start_scroll(direction, distance, speed) @scroll_direction = direction @scroll_rest = distance * 128 @scroll_speed = speed end def scrolling? return @scroll_rest > 0 end def start_fog_tone_change(tone, duration) @fog_tone_target = tone.clone @fog_tone_duration = duration if @fog_tone_duration == 0 @fog_tone = @fog_tone_target.clone end end def start_fog_opacity_change(opacity, duration) @fog_opacity_target = opacity * 1.0 @fog_opacity_duration = duration if @fog_opacity_duration == 0 @fog_opacity = @fog_opacity_target end end def in_range?(object) return true if $PokemonSystem.tilemap==2 screne_x = display_x screne_x -= 256 screne_y = display_y screne_y -= 256 screne_width = display_x screne_width += Graphics.width*4+256 # 2816 screne_height = display_y screne_height += Graphics.height*4+256 # 2176 return false if object.real_x <= screne_x return false if object.real_x >= screne_width return false if object.real_y <= screne_y return false if object.real_y >= screne_height return true end def update if $MapFactory for i in $MapFactory.maps i.refresh if i.need_refresh end $MapFactory.setCurrentMap end if @scroll_rest > 0 distance = 2 ** @scroll_speed case @scroll_direction when 2 scroll_down(distance) when 4 scroll_left(distance) when 6 scroll_right(distance) when 8 scroll_up(distance) end @scroll_rest -= distance end for event in @events.values if in_range?(event) or event.trigger == 3 or event.trigger == 4 event.update end end for common_event in @common_events.values common_event.update end @fog_ox -= @fog_sx / 8.0 @fog_oy -= @fog_sy / 8.0 if @fog_tone_duration >= 1 d = @fog_tone_duration target = @fog_tone_target @fog_tone.red = (@fog_tone.red * (d - 1) + target.red) / d @fog_tone.green = (@fog_tone.green * (d - 1) + target.green) / d @fog_tone.blue = (@fog_tone.blue * (d - 1) + target.blue) / d @fog_tone.gray = (@fog_tone.gray * (d - 1) + target.gray) / d @fog_tone_duration -= 1 end if @fog_opacity_duration >= 1 d = @fog_opacity_duration @fog_opacity = (@fog_opacity * (d - 1) + @fog_opacity_target) / d @fog_opacity_duration -= 1 end end end class Game_Map def name return pbGetMessage(MessageTypes::MapNames,self.map_id) end end[/CODE] [CODE]#============================================================================== # ** Game_CommonEvent #------------------------------------------------------------------------------ # This class handles common events. It includes execution of parallel process # event. This class is used within the Game_Map class ($game_map). #============================================================================== class Game_CommonEvent #-------------------------------------------------------------------------- # * Object Initialization # common_event_id : common event ID #-------------------------------------------------------------------------- def initialize(common_event_id) @common_event_id = common_event_id @interpreter = nil refresh end #-------------------------------------------------------------------------- # * Get Name #-------------------------------------------------------------------------- def name return $data_common_events[@common_event_id].name end #-------------------------------------------------------------------------- # * Get Trigger #-------------------------------------------------------------------------- def trigger return $data_common_events[@common_event_id].trigger end #-------------------------------------------------------------------------- # * Get Condition Switch ID #-------------------------------------------------------------------------- def switch_id return $data_common_events[@common_event_id].switch_id end #-------------------------------------------------------------------------- # * Get List of Event Commands #-------------------------------------------------------------------------- def list return $data_common_events[@common_event_id].list end #-------------------------------------------------------------------------- # * Refresh #-------------------------------------------------------------------------- def refresh # Create an interpreter for parallel process if necessary if self.trigger == 2 and $game_switches[self.switch_id] == true if @interpreter == nil @interpreter = Interpreter.new end else @interpreter = nil end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update # If parallel process is valid if @interpreter != nil # If not running unless @interpreter.running? # Set up event @interpreter.setup(self.list, 0) end # Update interpreter @interpreter.update end end end [/CODE] [CODE] class Game_Character attr_reader :id attr_reader :x attr_reader :y attr_reader :real_x attr_reader :real_y attr_reader :tile_id attr_accessor :character_name attr_accessor :character_hue attr_reader :opacity attr_reader :blend_type attr_reader :direction attr_reader :pattern attr_reader :move_route_forcing attr_accessor :through attr_accessor :animation_id attr_accessor :transparent attr_reader :map attr_accessor :move_speed attr_accessor :walk_anime def map return @map ? @map : $game_map end def initialize(map=nil) @map=map @id = 0 @x = 0 @y = 0 @real_x = 0 @real_y = 0 @tile_id = 0 @character_name = "" @character_hue = 0 @opacity = 255 @blend_type = 0 @direction = 2 @pattern = 0 @move_route_forcing = false @through = false @animation_id = 0 @transparent = false @original_direction = 2 @original_pattern = 0 @move_type = 0 @move_speed = 4 @move_frequency = 6 @move_route = nil @move_route_index = 0 @original_move_route = nil @original_move_route_index = 0 @walk_anime = true @step_anime = false @direction_fix = false @always_on_top = false @anime_count = 0 @stop_count = 0 @jump_count = 0 @jump_peak = 0 @wait_count = 0 @locked = false @prelock_direction = 0 end def map return @map end def moving? return (@real_x != @x * 4 * Game_Map::TILEWIDTH or @real_y != @y * 4 * Game_Map::TILEHEIGHT) end def jumping? return @jump_count > 0 end def straighten if @walk_anime or @step_anime @pattern = 0 end @anime_count = 0 @prelock_direction = 0 end def force_move_route(move_route) if @original_move_route == nil @original_move_route = @move_route @original_move_route_index = @move_route_index end @move_route = move_route @move_route_index = 0 @move_route_forcing = true @prelock_direction = 0 @wait_count = 0 move_type_custom end def passableEx?(x, y, d, strict=false) new_x = x + (d == 6 ? 1 : d == 4 ? -1 : 0) new_y = y + (d == 2 ? 1 : d == 8 ? -1 : 0) return false unless self.map.valid?(new_x, new_y) return true if @through if strict return false unless self.map.passableStrict?(x, y, d, self) return false unless self.map.passableStrict?(new_x, new_y, 10 - d) else return false unless self.map.passable?(x, y, d, self) return false unless self.map.passable?(new_x, new_y, 10 - d) end for event in self.map.events.values if event.x == new_x and event.y == new_y unless event.through return false if self != $game_player || event.character_name != "" end end end if $game_player.x == new_x and $game_player.y == new_y unless $game_player.through return false if @character_name != "" end end return true end def passable?(x,y,d) return passableEx?(x,y,d,false) end def passableStrict?(x,y,d) return passableEx?(x,y,d,true) end def lock if @locked return end @prelock_direction = @direction turn_toward_player @locked = true end def lock? return @locked end def unlock unless @locked return end @locked = false unless @direction_fix if @prelock_direction != 0 @direction = @prelock_direction end end end def moveto(x, y) @x = x % self.map.width @y = y % self.map.height @real_x = @x * Game_Map.realResX @real_y = @y * Game_Map.realResY @prelock_direction = 0 end def screen_x return (@real_x - self.map.display_x + 3) / 4 + (Game_Map::TILEWIDTH/2) end def screen_y y = (@real_y - self.map.display_y + 3) / 4 + (Game_Map::TILEHEIGHT) if jumping? if @jump_count >= @jump_peak n = @jump_count - @jump_peak else n = @jump_peak - @jump_count end return y - (@jump_peak * @jump_peak - n * n) / 2 else return y end end def screen_z(height = 0) if @always_on_top return 999 end z = (@real_y - self.map.display_y + 3) / 4 + 32 if @tile_id > 0 return z + self.map.priorities[@tile_id] * 32 else # Add Z if height exceeds 32 return z + ((height > 32) ? 31 : 0) end end def bush_depth if @tile_id > 0 or @always_on_top return 0 end if @jump_count <= 0 and self.map.bush?(@x, @y) return 12 else return 0 end end def terrain_tag return self.map.terrain_tag(@x, @y) end end [/CODE] [CODE] class Game_Character def update if jumping? update_jump elsif moving? update_move else update_stop end if @anime_count > 18 - @move_speed * 2 if not @step_anime and @stop_count > 0 @pattern = @original_pattern else @pattern = (@pattern + 1) % 4 end @anime_count = 0 end if @wait_count > 0 @wait_count -= 1 return end if @move_route_forcing move_type_custom return end if @starting or lock? return end if @stop_count > (40 - @move_frequency * 2) * (6 - @move_frequency) case @move_type when 1 move_type_random when 2 move_type_toward_player when 3 move_type_custom end end end def update_jump @jump_count -= 1 @real_x = (@real_x * @jump_count + @x * Game_Map.realResX) / (@jump_count + 1) @real_y = (@real_y * @jump_count + @y * Game_Map.realResY) / (@jump_count + 1) end def update_move distance = 2 ** @move_speed realResX=Game_Map.realResX realResY=Game_Map.realResY if @y * realResY > @real_y @real_y = [@real_y + distance, @y * realResY].min end if @x * realResX < @real_x @real_x = [@real_x - distance, @x * realResX].max end if @x * realResX > @real_x @real_x = [@real_x + distance, @x * realResX].min end if @y * realResY < @real_y @real_y = [@real_y - distance, @y * realResY].max end if @walk_anime @anime_count += 1.5 elsif @step_anime @anime_count += 1 end end def update_stop if @step_anime @anime_count += 1 elsif @pattern != @original_pattern @anime_count += 1.5 end unless @starting or lock? @stop_count += 1 end end def move_type_random case rand(6) when 0..3 move_random when 4 move_forward when 5 @stop_count = 0 end end def move_type_toward_player sx = @x - $game_player.x sy = @y - $game_player.y abs_sx = sx > 0 ? sx : -sx abs_sy = sy > 0 ? sy : -sy if sx + sy >= 20 move_random return end case rand(6) when 0..3 move_toward_player when 4 move_random when 5 move_forward end end def move_type_custom if jumping? or moving? return end while @move_route_index < @move_route.list.size command = @move_route.list[@move_route_index] if command.code == 0 if @move_route.repeat @move_route_index = 0 end unless @move_route.repeat if @move_route_forcing and not @move_route.repeat @move_route_forcing = false @move_route = @original_move_route @move_route_index = @original_move_route_index @original_move_route = nil end @stop_count = 0 end return end if command.code <= 14 case command.code when 1 move_down when 2 move_left when 3 move_right when 4 move_up when 5 move_lower_left when 6 move_lower_right when 7 move_upper_left when 8 move_upper_right when 9 move_random when 10 move_toward_player when 11 move_away_from_player when 12 move_forward when 13 move_backward when 14 jump(command.parameters[0], command.parameters[1]) end if not @move_route.skippable and not moving? and not jumping? return end @move_route_index += 1 return end if command.code == 15 @wait_count = command.parameters[0] * 2 - 1 @move_route_index += 1 return end if command.code >= 16 and command.code <= 26 case command.code when 16 turn_down when 17 turn_left when 18 turn_right when 19 turn_up when 20 turn_right_90 when 21 turn_left_90 when 22 turn_180 when 23 turn_right_or_left_90 when 24 turn_random when 25 turn_toward_player when 26 turn_away_from_player end @move_route_index += 1 return end if command.code >= 27 case command.code when 27 $game_switches[command.parameters[0]] = true self.map.need_refresh = true when 28 $game_switches[command.parameters[0]] = false self.map.need_refresh = true when 29 @move_speed = command.parameters[0] when 30 @move_frequency = command.parameters[0] when 31 @walk_anime = true when 32 @walk_anime = false when 33 @step_anime = true when 34 @step_anime = false when 35 @direction_fix = true when 36 @direction_fix = false when 37 @through = true when 38 @through = false when 39 @always_on_top = true when 40 @always_on_top = false when 41 @tile_id = 0 @character_name = command.parameters[0] @character_hue = command.parameters[1] if @original_direction != command.parameters[2] @direction = command.parameters[2] @original_direction = @direction @prelock_direction = 0 end if @original_pattern != command.parameters[3] @pattern = command.parameters[3] @original_pattern = @pattern end when 42 @opacity = command.parameters[0] when 43 @blend_type = command.parameters[0] when 44 $game_system.se_play(command.parameters[0]) when 45 result = eval(command.parameters[0]) end @move_route_index += 1 end end end def increase_steps @stop_count = 0 end end [/CODE] [CODE] class Game_Character def move_down(turn_enabled = true) if turn_enabled turn_down end if passable?(@x, @y, 2) turn_down @y += 1 increase_steps else check_event_trigger_touch(@x, @y+1) end end def move_left(turn_enabled = true) if turn_enabled turn_left end if passable?(@x, @y, 4) turn_left @x -= 1 increase_steps else check_event_trigger_touch(@x-1, @y) end end def move_right(turn_enabled = true) if turn_enabled turn_right end if passable?(@x, @y, 6) turn_right @x += 1 increase_steps else check_event_trigger_touch(@x+1, @y) end end def move_up(turn_enabled = true) if turn_enabled turn_up end if passable?(@x, @y, 8) turn_up @y -= 1 increase_steps else check_event_trigger_touch(@x, @y-1) end end def move_lower_left unless @direction_fix @direction = (@direction == 6 ? 4 : @direction == 8 ? 2 : @direction) end if (passable?(@x, @y, 2) and passable?(@x, @y + 1, 4)) or (passable?(@x, @y, 4) and passable?(@x - 1, @y, 2)) @x -= 1 @y += 1 increase_steps end end def move_lower_right unless @direction_fix @direction = (@direction == 4 ? 6 : @direction == 8 ? 2 : @direction) end if (passable?(@x, @y, 2) and passable?(@x, @y + 1, 6)) or (passable?(@x, @y, 6) and passable?(@x + 1, @y, 2)) @x += 1 @y += 1 increase_steps end end def move_upper_left unless @direction_fix @direction = (@direction == 6 ? 4 : @direction == 2 ? 8 : @direction) end if (passable?(@x, @y, 8) and passable?(@x, @y - 1, 4)) or (passable?(@x, @y, 4) and passable?(@x - 1, @y, 8)) @x -= 1 @y -= 1 increase_steps end end def move_upper_right unless @direction_fix @direction = (@direction == 4 ? 6 : @direction == 2 ? 8 : @direction) end if (passable?(@x, @y, 8) and passable?(@x, @y - 1, 6)) or (passable?(@x, @y, 6) and passable?(@x + 1, @y, 8)) @x += 1 @y -= 1 increase_steps end end def move_random case rand(4) when 0 move_down(false) when 1 move_left(false) when 2 move_right(false) when 3 move_up(false) end end def move_toward_player sx = @x - $game_player.x sy = @y - $game_player.y if sx == 0 and sy == 0 return end abs_sx = sx.abs abs_sy = sy.abs if abs_sx == abs_sy rand(2) == 0 ? abs_sx += 1 : abs_sy += 1 end if abs_sx > abs_sy sx > 0 ? move_left : move_right if not moving? and sy != 0 sy > 0 ? move_up : move_down end else sy > 0 ? move_up : move_down if not moving? and sx != 0 sx > 0 ? move_left : move_right end end end def move_away_from_player sx = @x - $game_player.x sy = @y - $game_player.y if sx == 0 and sy == 0 return end abs_sx = sx.abs abs_sy = sy.abs if abs_sx == abs_sy rand(2) == 0 ? abs_sx += 1 : abs_sy += 1 end if abs_sx > abs_sy sx > 0 ? move_right : move_left if not moving? and sy != 0 sy > 0 ? move_down : move_up end else sy > 0 ? move_down : move_up if not moving? and sx != 0 sx > 0 ? move_right : move_left end end end def move_forward case @direction when 2 move_down(false) when 4 move_left(false) when 6 move_right(false) when 8 move_up(false) end end def move_backward last_direction_fix = @direction_fix @direction_fix = true case @direction when 2 move_up(false) when 4 move_right(false) when 6 move_left(false) when 8 move_down(false) end @direction_fix = last_direction_fix end def jump(x_plus, y_plus) if x_plus != 0 or y_plus != 0 if x_plus.abs > y_plus.abs x_plus < 0 ? turn_left : turn_right else y_plus < 0 ? turn_up : turn_down end end new_x = @x + x_plus new_y = @y + y_plus if (x_plus == 0 and y_plus == 0) or passable?(new_x, new_y, 0) straighten @x = new_x @y = new_y distance = x_plus * x_plus + y_plus * y_plus @jump_peak = 10 + distance - @move_speed @jump_peak = @jump_peak.floor @jump_count = @jump_peak * 2 @stop_count = 0 if self.is_a?(Game_Player) $PokemonTemp.dependentEvents.pbJumpDependentEvents end end end def turnGeneric(dir) unless @direction_fix oldDirection=@direction @direction=dir @stop_count=0 if dir!=oldDirection pbCheckEventTriggerAfterTurning end end end def turn_down; turnGeneric(2); end def turn_left; turnGeneric(4); end def turn_right; turnGeneric(6); end def turn_up; turnGeneric(8); end def turn_right_90 case @direction when 2 turn_left when 4 turn_up when 6 turn_down when 8 turn_right end end def turn_left_90 case @direction when 2 turn_right when 4 turn_down when 6 turn_up when 8 turn_left end end def turn_180 case @direction when 2 turn_up when 4 turn_right when 6 turn_left when 8 turn_down end end def turn_right_or_left_90 if rand(2) == 0 turn_right_90 else turn_left_90 end end def turn_random case rand(4) when 0 turn_up when 1 turn_right when 2 turn_left when 3 turn_down end end def turn_toward_player sx = @x - $game_player.x sy = @y - $game_player.y if sx == 0 and sy == 0 return end if sx.abs > sy.abs sx > 0 ? turn_left : turn_right else sy > 0 ? turn_up : turn_down end end def turn_away_from_player sx = @x - $game_player.x sy = @y - $game_player.y if sx == 0 and sy == 0 return end if sx.abs > sy.abs sx > 0 ? turn_right : turn_left else sy > 0 ? turn_down : turn_up end end end [/CODE] [CODE]class Game_Event < Game_Character attr_reader :trigger attr_reader :list attr_reader :starting attr_reader :keypress # Event triggered by a key press attr_reader :tempSwitches # Temporary self-switches attr_accessor :need_refresh def initialize(map_id, event, map=nil) super(map) @map_id = map_id @event = event @id = @event.id @erased = false @starting = false @keypress=false @need_refresh=false @route_erased=false @through = true @tempSwitches={} moveto(@event.x, @event.y) if map refresh end def map_id @map_id end def clear_starting @starting = false end def over_trigger? if @character_name != "" and not @through return false end unless self.map.passable?(@x, @y, 0) return false end return true end def start(keypress=false) if @list.size > 1 @starting = true @keypress=keypress end end def erase @erased = true refresh end def erase_route @route_erased=true refresh end def name return @event.name end def id return @event.id end def pbCheckEventTriggerAfterTurning if $game_system.map_interpreter.running? return end if @event.name[/^Trainer\\((\\d+)\\)$/] distance=$~[1].to_i if @trigger == 2 and pbEventCanReachPlayer?(self,$game_player,distance) if not jumping? and not over_trigger? start end end end end def tsOn?(c) return @tempSwitches && @tempSwitches[c]==true end def tsOff?(c) return !@tempSwitches || !@tempSwitches[c] end def setTempSwitchOn(c) @tempSwitches[c]=true refresh end def setTempSwitchOff(c) @tempSwitches[c]=false refresh end def variable return nil if !$PokemonGlobal.eventvars return $PokemonGlobal.eventvars[[@map_id,@event.id]] end def setVariable(variable) $PokemonGlobal.eventvars[[@map_id,@event.id]]=variable end def varAsInt return 0 if !$PokemonGlobal.eventvars return $PokemonGlobal.eventvars[[@map_id,@event.id]].to_i end def expired?(secs=86400) ontime=self.variable return ontime && (Time.now.to_i>ontime+secs) end def onEvent? return @map_id==$game_map.map_id && $game_player.x==self.x && $game_player.y==self.y end def isOff?(c) return !$game_self_switches[[@map_id,@event.id,c]] end def switchIsOn?(id) switchname=$data_system.switches[id] return false if !switchname if switchname[/^s\\:/] return eval($~.post_match) else return $game_switches[id] end end def refresh new_page = nil unless @erased for page in @event.pages.reverse c = page.condition if c.switch1_valid if !switchIsOn?(c.switch1_id) next end end if c.switch2_valid if !switchIsOn?(c.switch2_id) next end end if c.variable_valid if $game_variables[c.variable_id] < c.variable_value next end end if c.self_switch_valid key = [@map_id, @event.id, c.self_switch_ch] if $game_self_switches[key] != true next end end new_page = page break end end if new_page == @page return end @page = new_page clear_starting if @page == nil @tile_id = 0 @character_name = "" @character_hue = 0 @move_type = 0 @through = true @trigger = nil @list = nil @interpreter = nil return end @tile_id = @page.graphic.tile_id @character_name = @page.graphic.character_name @character_hue = @page.graphic.character_hue if @original_direction != @page.graphic.direction @direction = @page.graphic.direction @original_direction = @direction @prelock_direction = 0 end if @original_pattern != @page.graphic.pattern @pattern = @page.graphic.pattern @original_pattern = @pattern end @opacity = @page.graphic.opacity @blend_type = @page.graphic.blend_type @move_type = @page.move_type @move_speed = @page.move_speed * 1.25 @move_frequency = @page.move_frequency @move_route = @route_erased ? RPG::MoveRoute.new : @page.move_route @move_route_index = 0 @move_route_forcing = false @walk_anime = @page.walk_anime @step_anime = @page.step_anime @direction_fix = @page.direction_fix @through = @page.through @always_on_top = @page.always_on_top @trigger = @page.trigger @list = @page.list @interpreter = nil if @trigger == 4 @interpreter = Interpreter.new end check_event_trigger_auto end def check_event_trigger_touch(x, y) if $game_system.map_interpreter.running? return end return if @trigger!=2 return if x != $game_player.x || y != $game_player.y if not jumping? and not over_trigger? start end end def check_event_trigger_auto if @trigger == 2 and @x == $game_player.x and @y == $game_player.y if not jumping? and over_trigger? start end end if @trigger == 3 start end end def update last_moving=moving? super if !moving? && last_moving $game_player.pbCheckEventTriggerFromDistance([2]) end if @need_refresh @need_refresh=false refresh end check_event_trigger_auto if @interpreter != nil unless @interpreter.running? @interpreter.setup(@list, @event.id) end @interpreter.update end end end [/CODE] [CODE]#============================================================================== # ** Game_Player #------------------------------------------------------------------------------ # This class handles the player. Its functions include event starting # determinants and map scrolling. Refer to "$game_player" for the one # instance of this class. #============================================================================== def pbAddDependency(event) $PokemonTemp.dependentEvents.addEvent(event) end def pbRemoveDependency(event) $PokemonTemp.dependentEvents.removeEvent(event) end def pbAddDependency2(eventID, eventName, commonEvent) $PokemonTemp.dependentEvents.addEvent($game_map.events[eventID],eventName,commonEvent) end def pbRemoveDependency2(eventName) $PokemonTemp.dependentEvents.removeEventByName(eventName) end class Game_Player < Game_Character def map @map=nil return $game_map end #-------------------------------------------------------------------------- # * Invariables #-------------------------------------------------------------------------- def initialize(*arg) super(*arg) @lastdir=0 @lastdirframe=0 end def pbHasDependentEvents? return $PokemonGlobal.dependentEvents.length>0 end def move_down(turn_enabled = true) if turn_enabled turn_down end pbBridgeCheck(2) if passable?(@x, @y, 2) return if pbLedge(0,1) return if pbEndSurf(0,1) turn_down @y += 1 $PokemonTemp.dependentEvents.pbMoveDependentEvents increase_steps else if !check_event_trigger_touch(@x, @y+1) Audio.se_play("Audio/SE/bump.wav") end end end def move_left(turn_enabled = true) if turn_enabled turn_left end pbBridgeCheck(4) if passable?(@x, @y, 4) return if pbLedge(-1,0) return if pbEndSurf(-1,0) turn_left @x -= 1 $PokemonTemp.dependentEvents.pbMoveDependentEvents increase_steps else if !check_event_trigger_touch(@x-1, @y) Audio.se_play("Audio/SE/bump.wav") end end end def move_right(turn_enabled = true) if turn_enabled turn_right end pbBridgeCheck(6) if passable?(@x, @y, 6) return if pbLedge(1,0) return if pbEndSurf(1,0) turn_right @x += 1 $PokemonTemp.dependentEvents.pbMoveDependentEvents increase_steps else if !check_event_trigger_touch(@x+1, @y) Audio.se_play("Audio/SE/bump.wav") end end end def move_up(turn_enabled = true) if turn_enabled turn_up end pbBridgeCheck(8) if passable?(@x, @y, 8) return if pbLedge(0,-1) return if pbEndSurf(0,-1) turn_up @y -= 1 $PokemonTemp.dependentEvents.pbMoveDependentEvents increase_steps else if !check_event_trigger_touch(@x, @y-1) Audio.se_play("Audio/SE/bump.wav") end end end def pbTriggeredTrainerEvents(triggers,checkIfRunning=true) result = [] # If event is running if checkIfRunning && $game_system.map_interpreter.running? return result end # All event loops for event in $game_map.events.values next if !event.name[/^Trainer\\((\\d+)\\)$/] distance=$~[1].to_i # If event coordinates and triggers are consistent if pbEventCanReachPlayer?(event,self,distance) and triggers.include?(event.trigger) # If starting determinant is front event (other than jumping) if not event.jumping? and not event.over_trigger? result.push(event) end end end return result end def pbTriggeredCounterEvents(triggers,checkIfRunning=true) result = [] # If event is running if checkIfRunning && $game_system.map_interpreter.running? return result end # All event loops for event in $game_map.events.values next if !event.name[/^Counter\\((\\d+)\\)$/] distance=$~[1].to_i # If event coordinates and triggers are consistent if pbEventFacesPlayer?(event,self,distance) and triggers.include?(event.trigger) # If starting determinant is front event (other than jumping) if not event.jumping? and not event.over_trigger? result.push(event) end end end return result end def pbCheckEventTriggerAfterTurning end def pbCheckEventTriggerFromDistance(triggers) ret=pbTriggeredTrainerEvents(triggers) ret.concat(pbTriggeredCounterEvents(triggers)) return false if ret.length==0 for event in ret event.start end return true end def pbFacingEvent if $game_system.map_interpreter.running? return nil end new_x = @x + (@direction == 6 ? 1 : @direction == 4 ? -1 : 0) new_y = @y + (@direction == 2 ? 1 : @direction == 8 ? -1 : 0) for event in $game_map.events.values if event.x == new_x and event.y == new_y if not event.jumping? and not event.over_trigger? return event end end end if $game_map.counter?(new_x, new_y) new_x += (@direction == 6 ? 1 : @direction == 4 ? -1 : 0) new_y += (@direction == 2 ? 1 : @direction == 8 ? -1 : 0) for event in $game_map.events.values if event.x == new_x and event.y == new_y if not event.jumping? and not event.over_trigger? return event end end end end return nil end #-------------------------------------------------------------------------- # * Passable Determinants # x : x-coordinate # y : y-coordinate # d : direction (0,2,4,6,8) # * 0 = Determines if all directions are impassable (for jumping) #-------------------------------------------------------------------------- def passable?(x, y, d) # Get new coordinates new_x = x + (d == 6 ? 1 : d == 4 ? -1 : 0) new_y = y + (d == 2 ? 1 : d == 8 ? -1 : 0) # If coordinates are outside of map unless $game_map.validLax?(new_x, new_y) # Impassable return false end if !$game_map.valid?(new_x, new_y) return false if !$MapFactory return $MapFactory.isPassableFromEdge?(new_x, new_y) end # If debug mode is ON and ctrl key was pressed if $DEBUG and Input.press?(Input::CTRL) # Passable return true end super end #-------------------------------------------------------------------------- # * Set Map Display Position to Center of Screen #-------------------------------------------------------------------------- def center(x, y) center_x = (Graphics.width/2 - 16) * 4 # Center screen x-coordinate * 4 center_y = (Graphics.height/2 - 16) * 4 # Center screen y-coordinate * 4 max_x = ($game_map.width - Graphics.width/32.0) * 128 max_y = ($game_map.height - Graphics.height/32.0) * 128 $game_map.display_x = [0, [x * 128 - center_x, max_x].min].max $game_map.display_y = [0, [y * 128 - center_y, max_y].min].max end #-------------------------------------------------------------------------- # * Move to Designated Position # x : x-coordinate # y : y-coordinate #-------------------------------------------------------------------------- def moveto(x, y) super # Centering center(x, y) # Make encounter count make_encounter_count end #-------------------------------------------------------------------------- # * Increase Steps #-------------------------------------------------------------------------- def increase_steps super end #-------------------------------------------------------------------------- # * Get Encounter Count #-------------------------------------------------------------------------- def encounter_count return @encounter_count end #-------------------------------------------------------------------------- # * Make Encounter Count #-------------------------------------------------------------------------- def make_encounter_count # Image of two dice rolling if $game_map.map_id != 0 n = $game_map.encounter_step @encounter_count = rand(n) + rand(n) + 1 end end #-------------------------------------------------------------------------- # * Refresh #-------------------------------------------------------------------------- def refresh @opacity = 255 @blend_type = 0 end #-------------------------------------------------------------------------- # * Same Position Starting Determinant #-------------------------------------------------------------------------- def check_event_trigger_here(triggers,keypress=false) result = false # If event is running if $game_system.map_interpreter.running? return result end # All event loops for event in $game_map.events.values # If event coordinates and triggers are consistent if event.x == @x and event.y == @y and triggers.include?(event.trigger) # If starting determinant is same position event (other than jumping) if not event.jumping? and event.over_trigger? event.start(keypress) result = true end end end return result end #-------------------------------------------------------------------------- # * Front Envent Starting Determinant #-------------------------------------------------------------------------- def check_event_trigger_there(triggers,keypress=false) result = false # If event is running if $game_system.map_interpreter.running? return result end # Calculate front event coordinates new_x = @x + (@direction == 6 ? 1 : @direction == 4 ? -1 : 0) new_y = @y + (@direction == 2 ? 1 : @direction == 8 ? -1 : 0) # All event loops for event in $game_map.events.values # If event coordinates and triggers are consistent if event.x == new_x and event.y == new_y and triggers.include?(event.trigger) # If starting determinant is front event (other than jumping) if not event.jumping? and (keypress || !event.over_trigger?) event.start(keypress) result = true end end end # If fitting event is not found if result == false # If front tile is a counter if $game_map.counter?(new_x, new_y) # Calculate 1 tile inside coordinates new_x += (@direction == 6 ? 1 : @direction == 4 ? -1 : 0) new_y += (@direction == 2 ? 1 : @direction == 8 ? -1 : 0) # All event loops for event in $game_map.events.values # If event coordinates and triggers are consistent if event.x == new_x and event.y == new_y and triggers.include?(event.trigger) # If starting determinant is front event (other than jumping) if not event.jumping? and (keypress || !event.over_trigger?) event.start result = true end end end end end return result end #-------------------------------------------------------------------------- # * Touch Event Starting Determinant #-------------------------------------------------------------------------- def check_event_trigger_touch(x, y) result = false # If event is running if $game_system.map_interpreter.running? return result end # All event loops for event in $game_map.events.values if event.name[/^Trainer\\((\\d+)\\)$/] distance=$~[1].to_i next if !pbEventCanReachPlayer?(event,self,distance) end if event.name[/^Counter\\((\\d+)\\)$/] distance=$~[1].to_i next if !pbEventFacesPlayer?(event,self,distance) end # If event coordinates and triggers are consistent if event.x == x and event.y == y and [1,2].include?(event.trigger) # If starting determinant is front event (other than jumping) if not event.jumping? and not event.over_trigger? event.start result = true end end end return result end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update # Remember whether or not moving in local variables last_moving = moving? # If moving, event running, move route forcing, and message window # display are all not occurring dir=Input.dir4 unless moving? or $game_system.map_interpreter.running? or @move_route_forcing or $game_temp.message_window_showing or $PokemonTemp.miniupdate # Move player in the direction the directional button is being pressed if dir==@lastdir && Graphics.frame_count-@lastdirframe>2 case dir when 2 move_down when 4 move_left when 6 move_right when 8 move_up end elsif dir!=@lastdir case dir when 2 turn_down when 4 turn_left when 6 turn_right when 8 turn_up end end end $PokemonTemp.dependentEvents.updateDependentEvents if dir!=@lastdir @lastdirframe=Graphics.frame_count end @lastdir=dir # Remember coordinates in local variables last_real_x = @real_x last_real_y = @real_y super center_x = (Graphics.width/2 - 16) * 4 # Center screen x-coordinate * 4 center_y = (Graphics.height/2 - 16) * 4 # Center screen y-coordinate * 4 # If character moves down and is positioned lower than the center # of the screen if @real_y > last_real_y and @real_y - $game_map.display_y > center_y # Scroll map down $game_map.scroll_down(@real_y - last_real_y) end # If character moves left and is positioned more let on-screen than # center if @real_x < last_real_x and @real_x - $game_map.display_x < center_x # Scroll map left $game_map.scroll_left(last_real_x - @real_x) end # If character moves right and is positioned more right on-screen than # center if @real_x > last_real_x and @real_x - $game_map.display_x > center_x # Scroll map right $game_map.scroll_right(@real_x - last_real_x) end # If character moves up and is positioned higher than the center # of the screen if @real_y < last_real_y and @real_y - $game_map.display_y < center_y # Scroll map up $game_map.scroll_up(last_real_y - @real_y) end # If not moving unless moving? # If player was moving last time if last_moving $PokemonTemp.dependentEvents.pbTurnDependentEvents result = pbCheckEventTriggerFromDistance([2]) # Event determinant is via touch of same position event result |= check_event_trigger_here([1,2]) # If event which started does not exist Kernel.pbOnStepTaken(result) # *Added function call if result == false # Disregard if debug mode is ON and ctrl key was pressed unless $DEBUG and Input.press?(Input::CTRL) # Encounter countdown if @encounter_count > 0 @encounter_count -= 1 end end end end # If C button was pressed if Input.trigger?(Input::C) && !$PokemonTemp.miniupdate # Same position and front event determinant check_event_trigger_here([0],true) check_event_trigger_there([0,2],true) # *Modified to prevent unnecessary triggers end end end end [/CODE] [CODE]class Sprite_Character < RPG::Sprite attr_accessor :character def initialize(viewport, character = nil) super(viewport) @character = character update end def pbBushDepthBitmap(bitmap,depth) ret=Bitmap.new(bitmap.width,bitmap.height) charheight=ret.height/4 for i in 0...4 cy=charheight-depth-2 y=i*charheight ret.blt(0,y,bitmap, Rect.new(0,y,ret.width,cy)) if cy>=0 ret.blt(0,y+cy,bitmap, Rect.new(0,y+cy,ret.width,2),170) if cy>=0 ret.blt(0,y+cy+2,bitmap, Rect.new(0,y+cy+2,ret.width,2),85) if cy+2>=0 end return ret end def pbBushDepthTile(bitmap,depth) ret=Bitmap.new(bitmap.width,bitmap.height) charheight=ret.height cy=charheight-depth-2 y=charheight ret.blt(0,y,bitmap, Rect.new(0,y,ret.width,cy)) if cy>=0 ret.blt(0,y+cy,bitmap, Rect.new(0,y+cy,ret.width,2),170) if cy>=0 ret.blt(0,y+cy+2,bitmap, Rect.new(0,y+cy+2,ret.width,2),85) if cy+2>=0 return ret end def dispose @bushbitmap.dispose if @bushbitmap @bushbitmap=nil super end def update super if @tile_id != @character.tile_id or @character_name != @character.character_name or @character_hue != @character.character_hue @tile_id = @character.tile_id @character_name = @character.character_name @character_hue = @character.character_hue if @tile_id >= 384 @charbitmap.dispose if @charbitmap @charbitmap = RPG::Cache.tile(@character.map.tileset_name, @tile_id, @character.character_hue) @bushbitmap.dispose if @bushbitmap @bushbitmap=nil @cw = 32 # added @ch = 32 # added self.src_rect.set(0, 0, 32, 32) self.ox = Game_Map::TILEWIDTH/2 self.oy = Game_Map::TILEHEIGHT else @charbitmap.dispose if @charbitmap @charbitmap = RPG::Cache.character(@character.character_name, @character.character_hue) @bushbitmap.dispose if @bushbitmap @bushbitmap=nil @cw = @charbitmap.width / 4 @ch = @charbitmap.height / 4 self.ox = @cw / 2 self.oy = @ch end end if @character.bush_depth==0 self.bitmap=@charbitmap else if !@bushbitmap if @tile_id >= 384 @bushbitmap=pbBushDepthTile(@charbitmap,12) else @bushbitmap=pbBushDepthBitmap(@charbitmap,12) end end self.bitmap=@bushbitmap end self.visible = (not @character.transparent) if @tile_id == 0 sx = @character.pattern * @cw sy = (@character.direction - 2) / 2 * @ch self.src_rect.set(sx, sy, @cw, @ch) end if self.visible if $PokemonSystem.tilemap==0 || (@character.is_a?(Game_Event) && @character.name=="RegularTone") self.tone.set(0,0,0,0) else pbDayNightTint(self) end end self.x = @character.screen_x self.y = @character.screen_y self.z = @character.screen_z(@ch) self.opacity = @character.opacity self.blend_type = @character.blend_type # self.bush_depth = @character.bush_depth if @character.animation_id != 0 animation = $data_animations[@character.animation_id] animation(animation, true) @character.animation_id = 0 end end end [/CODE] [CODE]class Sprite_Picture def initialize(viewport, picture) @viewport = viewport @picture = picture @sprite = nil update end def dispose if @sprite @sprite.dispose end end def update @sprite.update if @sprite # If picture file name is different from current one if @picture_name != @picture.name # Remember file name to instance variables @picture_name = @picture.name # If file name is not empty if @picture_name != "" # Get picture graphic @sprite.dispose if @sprite @sprite=GifSprite.new("Graphics/Pictures/"+@picture_name,@viewport) end end # If file name is empty if @picture_name == "" # Set sprite to invisible if @sprite @sprite.dispose if @sprite @sprite=nil end return end # Set sprite to visible @sprite.visible = true # Set transfer starting point if @picture.origin == 0 @sprite.ox = 0 @sprite.oy = 0 else @sprite.ox = @sprite.bitmap.width / 2 @sprite.oy = @sprite.bitmap.height / 2 end # Set sprite coordinates @sprite.x = @picture.x @sprite.y = @picture.y @sprite.z = @picture.number # Set zoom rate, opacity level, and blend method @sprite.zoom_x = @picture.zoom_x / 100.0 @sprite.zoom_y = @picture.zoom_y / 100.0 @sprite.opacity = @picture.opacity @sprite.blend_type = @picture.blend_type # Set rotation angle and color tone @sprite.angle = @picture.angle @sprite.tone = @picture.tone end end [/CODE] [CODE]class Sprite_Timer def initialize @timer=nil @total_sec=nil @disposed=false end def dispose @timer.dispose if @timer @timer=nil @disposed=true end def disposed? @disposed end def update return if disposed? if $game_system.timer_working if !@timer @timer=Window_AdvancedTextPokemon.newWithSize("", Graphics.width-120,0,120,64) @timer.z=99998 end curtime=$game_system.timer / Graphics.frame_rate if curtime != @total_sec # Calculate total number of seconds @total_sec = curtime # Make a string for displaying the timer min = @total_sec / 60 sec = @total_sec % 60 @timer.text = _ISPRINTF("<ac>{1:02d}:{2:02d}", min, sec) end end end end[/CODE] [CODE]class Spriteset_Map attr_reader :map def initialize(map=nil) @map=map ? map : $game_map @viewport1 = Viewport.new(0, 0, Graphics.width,Graphics.height) @viewport1a = Viewport.new(0, 0, Graphics.width,Graphics.height) @viewport2 = Viewport.new(0, 0, Graphics.width,Graphics.height) @viewport3 = Viewport.new(0, 0, Graphics.width,Graphics.height) @viewport1a.z = 100 @viewport2.z = 200 @viewport3.z = 500 @tilemap = TilemapLoader.new(@viewport1) @tilemap.tileset = RPG::Cache.tileset(@map.tileset_name) for i in 0..6 autotile_name = @map.autotile_names[i] @tilemap.autotiles[i] = RPG::Cache.autotile(autotile_name) end @tilemap.map_data = @map.data @tilemap.priorities = @map.priorities @panorama = AnimatedPlane.new(@viewport1) @panorama.z = -1000 @fog = AnimatedPlane.new(@viewport1) @fog.z = 3000 @reflectedSprites=[] @character_sprites = [] for i in @map.events.keys.sort sprite = Sprite_Character.new(@viewport1, @map.events[i]) @character_sprites.push(sprite) @reflectedSprites.push(ReflectedSprite.new(sprite,@map.events[i],@viewport1)) end playersprite=Sprite_Character.new(@viewport1, $game_player) @reflectedSprites.push( ReflectedSprite.new(playersprite,$game_player,@viewport1) ) @character_sprites.push(playersprite) @weather = RPG::Weather.new(@viewport1a) @picture_sprites = [] for i in 1..50 @picture_sprites.push(Sprite_Picture.new(@viewport2, $game_screen.pictures[i])) end @timer_sprite = Sprite_Timer.new Kernel.pbOnSpritesetCreate(self,@viewport1) update end class ReflectedSprite def initialize(sprite,event,viewport=nil) @rsprite=sprite @sprite=nil @event=event @disposed=false @viewport=viewport update end def dispose if !@disposed @sprite.dispose if @sprite @sprite=nil @disposed=true end end def disposed? @disposed end def update return if disposed? currentY=@event.real_y.to_i/(4*Game_Map::TILEHEIGHT) limit=@rsprite.src_rect.height shouldShow=false # Clipping at Y i=0 while i<@rsprite.src_rect.height+Game_Map::TILEHEIGHT nextY=currentY+1+(i>>5) if @event.map.terrain_tag(@event.x,nextY)!=6 limit= ((nextY * (4*Game_Map::TILEHEIGHT))-@event.map.display_y+3).to_i/4 limit-=@rsprite.y break else shouldShow=true end i+=Game_Map::TILEHEIGHT end if limit>0 && shouldShow # Just-in-time creation of sprite if !@sprite @sprite=Sprite.new(@viewport) end else # Just-in-time disposal of sprite if @sprite @sprite.dispose @sprite=nil end return end if @sprite x=@rsprite.x-@rsprite.ox y=@rsprite.y-@rsprite.oy width=@rsprite.src_rect.width height=@rsprite.src_rect.height frame=(Graphics.frame_count%40)/10 if frame==1 @sprite.zoom_x=1.1 elsif frame==3 @sprite.zoom_x=0.9 else @sprite.zoom_x=1.0 end tileX=@event.map.display_x @sprite.x=x+width/2 @sprite.y=y+height+height/2 @sprite.ox=width/2 @sprite.oy=height/2 @sprite.angle=180 @sprite.z=@rsprite.z @sprite.mirror=true @sprite.bitmap=@rsprite.bitmap @sprite.tone=@rsprite.tone @sprite.opacity=@rsprite.opacity/2 @sprite.src_rect=@rsprite.src_rect currentY=@event.real_y.to_i/(4*Game_Map::TILEHEIGHT) if limit<@sprite.src_rect.height diff=@sprite.src_rect.height-limit @sprite.src_rect.y+=diff @sprite.src_rect.height=limit @sprite.y-=diff end end end end def dispose @tilemap.tileset.dispose for i in 0..6 @tilemap.autotiles[i].dispose end @tilemap.dispose @panorama.dispose @fog.dispose for sprite in @character_sprites sprite.dispose end for sprite in @reflectedSprites sprite.dispose end @weather.dispose for sprite in @picture_sprites sprite.dispose end @timer_sprite.dispose @viewport1.dispose @viewport2.dispose @viewport3.dispose @tilemap=nil @panorama=nil @fog=nil @character_sprites.clear @reflectedSprites.clear @weather=nil @picture_sprites.clear @viewport1=nil @viewport2=nil @viewport3=nil @timer_sprite=nil end def in_range?(object) return true if $PokemonSystem.tilemap==2 screne_x = @map.display_x screne_x -= 256 screne_y = @map.display_y screne_y -= 256 screne_width = @map.display_x screne_width += Graphics.width*4+256 # 2816 screne_height = @map.display_y screne_height += Graphics.height*4+256 # 2176 return false if object.real_x <= screne_x return false if object.real_x >= screne_width return false if object.real_y <= screne_y return false if object.real_y >= screne_height return true end def update if @panorama_name != @map.panorama_name or @panorama_hue != @map.panorama_hue @panorama_name = @map.panorama_name @panorama_hue = @map.panorama_hue if @panorama.bitmap != nil @panorama.setPanorama(nil) end if @panorama_name != "" @panorama.setPanorama(@panorama_name, @panorama_hue) end Graphics.frame_reset end if @fog_name != @map.fog_name or @fog_hue != @map.fog_hue @fog_name = @map.fog_name @fog_hue = @map.fog_hue if @fog.bitmap != nil @fog.setFog(nil) end if @fog_name != "" @fog.setFog(@fog_name, @fog_hue) end Graphics.frame_reset end tmox = @map.display_x.to_i / 4 tmoy = @map.display_y.to_i / 4 @tilemap.ox=tmox @tilemap.oy=tmoy if $PokemonSystem.tilemap!=2 @viewport1.rect.x=[-tmox,0].max @viewport1.rect.y=[-tmoy,0].max @viewport1.rect.width= [@tilemap.map_data.xsize*Game_Map::TILEWIDTH-tmox,Graphics.width].min @viewport1.rect.height= [@tilemap.map_data.ysize*Game_Map::TILEHEIGHT-tmoy,Graphics.height].min @viewport1.ox=[-tmox,0].max @viewport1.oy=[-tmoy,0].max else @viewport1.rect.set(0,0,Graphics.width,Graphics.height) @viewport1.ox=0 @viewport1.oy=0 end @viewport1.ox += $game_screen.shake @tilemap.update @panorama.ox = @map.display_x / 8 @panorama.oy = @map.display_y / 8 @fog.zoom_x = @map.fog_zoom / 100.0 @fog.zoom_y = @map.fog_zoom / 100.0 @fog.opacity = @map.fog_opacity @fog.blend_type = @map.fog_blend_type @fog.ox = @map.display_x / 4 + @map.fog_ox @fog.oy = @map.display_y / 4 + @map.fog_oy @fog.tone = @map.fog_tone @panorama.update @fog.update for sprite in @character_sprites if sprite.character.is_a?(Game_Event) if sprite.character.trigger == 3 || sprite.character.trigger == 4 || in_range?(sprite.character) sprite.update end else sprite.update end end for sprite in @reflectedSprites sprite.update end if self.map!=$game_map @weather.max-=2 if @weather.max>0 @weather.type = 0 if @weather.max==0 @weather.ox = 0 if @weather.max==0 @weather.oy = 0 if @weather.max==0 else @weather.type = $game_screen.weather_type @weather.max = $game_screen.weather_max @weather.ox = @map.display_x / 4 @weather.oy = @map.display_y / 4 end @weather.update for sprite in @picture_sprites sprite.update end @timer_sprite.update @viewport1.tone = $game_screen.tone @viewport1a.ox += $game_screen.shake @viewport3.color = $game_screen.flash_color @viewport1.update @viewport1a.update @viewport3.update end end [/CODE] [CODE]#============================================================================== # ** Interpreter #------------------------------------------------------------------------------ # This interpreter runs event commands. This class is used within the # Game_System class and the Game_Event class. #============================================================================== class Interpreter #-------------------------------------------------------------------------- # * Object Initialization # depth : nest depth # main : main flag #-------------------------------------------------------------------------- def initialize(depth = 0, main = false) @depth = depth @main = main # Depth goes up to level 100 if depth > 100 print("Common event call has exceeded maximum limit.") exit end # Clear inner situation of interpreter clear end def clear @map_id = 0 # map ID when starting up @event_id = 0 # event ID @message_waiting = false # waiting for message to end @move_route_waiting = false # waiting for move completion @button_input_variable_id = 0 # button input variable ID @wait_count = 0 # wait count @child_interpreter = nil # child interpreter @branch = {} # branch data end #-------------------------------------------------------------------------- # * Event Setup # list : list of event commands # event_id : event ID #-------------------------------------------------------------------------- def setup(list, event_id) # Clear inner situation of interpreter clear # Remember map ID @map_id = $game_map.map_id # Remember event ID @event_id = event_id # Remember list of event commands @list = list # Initialize index @index = 0 # Clear branch data hash @branch.clear end def running? return @list != nil end def setup_starting_event # Refresh map if necessary if $game_map.need_refresh $game_map.refresh end # If common event call is reserved if $game_temp.common_event_id > 0 # Set up event setup($data_common_events[$game_temp.common_event_id].list, 0) # Release reservation $game_temp.common_event_id = 0 return end # Loop (map events) for event in $game_map.events.values # If running event is found if event.starting # If not auto run if event.trigger < 3 # Clear starting flag event.clear_starting # Lock event.lock end # Set up event setup(event.list, event.id) return end end # Loop (common events) for common_event in $data_common_events.compact # If trigger is auto run, and condition switch is ON if common_event.trigger == 1 and $game_switches[common_event.switch_id] == true # Set up event setup(common_event.list, 0) return end end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update # Initialize loop count @loop_count = 0 # Loop loop do # Add 1 to loop count @loop_count += 1 # If 100 event commands ran if @loop_count > 100 # Call Graphics.update for freeze prevention Graphics.update @loop_count = 0 end # If map is different than event startup time if $game_map.map_id != @map_id # Change event ID to 0 @event_id = 0 end # If a child interpreter exists if @child_interpreter != nil # Update child interpreter @child_interpreter.update # If child interpreter is finished running unless @child_interpreter.running? # Delete child interpreter @child_interpreter = nil end # If child interpreter still exists if @child_interpreter != nil return end end # If waiting for message to end if @message_waiting return end # If waiting for move to end if @move_route_waiting # If player is forcing move route if $game_player.move_route_forcing return end # Loop (map events) for event in $game_map.events.values # If this event is forcing move route if event.move_route_forcing return end end # Clear move end waiting flag @move_route_waiting = false end # If waiting for button input if @button_input_variable_id > 0 # Run button input processing input_button return end # If waiting if @wait_count > 0 # Decrease wait count @wait_count -= 1 return end # If an action forcing battler exists if $game_temp.forcing_battler != nil return end # If a call flag is set for each type of screen if $game_temp.battle_calling or $game_temp.shop_calling or $game_temp.name_calling or $game_temp.menu_calling or $game_temp.save_calling or $game_temp.gameover return end # If list of event commands is empty if @list == nil # If main map event if @main # Set up starting event setup_starting_event end # If nothing was set up if @list == nil return end end # If return value is false when trying to execute event command if execute_command == false return end # Advance index @index += 1 end end #-------------------------------------------------------------------------- # * Button Input #-------------------------------------------------------------------------- def input_button # Determine pressed button n = 0 for i in 1..18 if Input.trigger?(i) n = i end end # If button was pressed if n > 0 # Change value of variables $game_variables[@button_input_variable_id] = n $game_map.need_refresh = true # End button input @button_input_variable_id = 0 end end #-------------------------------------------------------------------------- # * Setup Choices #-------------------------------------------------------------------------- def setup_choices(parameters) # Set choice item count to choice_max $game_temp.choice_max = parameters[0].size # Set choice to message_text for text in parameters[0] $game_temp.message_text += text + "\\n" end # Set cancel processing $game_temp.choice_cancel_type = parameters[1] # Set callback current_indent = @list[@index].indent $game_temp.choice_proc = Proc.new { |n| @branch[current_indent] = n } end def command_dummy return true end def pbExecuteScript(script) begin result = eval(script) return result rescue SyntaxError event=get_character(0) message=$!.message # Analyze script to make error message more helpful script.each_line {|line| line.gsub!(/\\s+$/,"") if line[/\\:\\:\\s*$/] message+="\\r\\n***Line '#{line}' can't begin with '::', try putting the next\\r\\nword on the same line, e.g.: 'PBSpecies::MEW'" end if line[/^\\s*\\(/] message+="\\r\\n***Line '#{line}' shouldn't begin with '(', try putting '(' at\\r\\nthe end of the last line" end } message+="\\r\\n***Full script:\\r\\n#{script}" s="" if event && $game_map mapname="???" mapname=$game_map.name rescue nil raise "Script error within event #{event.id}, map #{$game_map.map_id} (#{mapname}):\\r\\n#{message}\\r\\n" elsif $game_map mapname="???" mapname=$game_map.name rescue nil raise "Script error within map #{$game_map.map_id} (#{mapname}):\\r\\n#{message}\\r\\n" else raise "Script error in interpreter:\\r\\n#{message}\\r\\n" end return false rescue event=get_character(0) s="" for bt in $!.backtrace[0,10] s+=bt+"\\r\\n" end s.gsub!(/Section(\\d+)/){$RGSS_SCRIPTS[$1.to_i][1]} if event && $game_map mapname="???" mapname=$game_map.name rescue nil raise "Script error within event #{event.id}, map #{$game_map.map_id} (#{mapname}):\\r\\n#{$!.message}\\r\\n#{s}" elsif $game_map mapname="???" mapname=$game_map.name rescue nil raise "Script error within map #{$game_map.map_id} (#{mapname}):\\r\\n#{$!.message}\\r\\n#{s}" else raise "Script error in interpreter:\\r\\n#{$!.message}\\r\\n#{s}" end return false end end #-------------------------------------------------------------------------- # * Event Command Execution #-------------------------------------------------------------------------- def execute_command # If last to arrive for list of event commands if @index >= @list.size - 1 # End event command_end # Continue return true end # Make event command parameters available for reference via @parameters @parameters = @list[@index].parameters # Branch by command code case @list[@index].code when 101 # Show Text return command_101 when 102 # Show Choices return command_102 when 402 # When [**] return command_402 when 403 # When Cancel return command_403 when 103 # Input Number return command_103 when 104 # Change Text Options return command_104 when 105 # Button Input Processing return command_105 when 106 # Wait return command_106 when 111 # Conditional Branch return command_111 when 411 # Else return command_411 when 112 # Loop return command_112 when 413 # Repeat Above return command_413 when 113 # Break Loop return command_113 when 115 # Exit Event Processing return command_115 when 116 # Erase Event return command_116 when 117 # Call Common Event return command_117 when 118 # Label return command_118 when 119 # Jump to Label return command_119 when 121 # Control Switches return command_121 when 122 # Control Variables return command_122 when 123 # Control Self Switch return command_123 when 124 # Control Timer return command_124 when 125 # Change Gold return command_125 when 126 # Change Items return command_126 when 127 # Change Weapons return command_127 when 128 # Change Armor return command_128 when 129 # Change Party Member return command_129 when 131 # Change Windowskin return command_131 when 132 # Change Battle BGM return command_132 when 133 # Change Battle End ME return command_133 when 134 # Change Save Access return command_134 when 135 # Change Menu Access return command_135 when 136 # Change Encounter return command_136 when 201 # Transfer Player return command_201 when 202 # Set Event Location return command_202 when 203 # Scroll Map return command_203 when 204 # Change Map Settings return command_204 when 205 # Change Fog Color Tone return command_205 when 206 # Change Fog Opacity return command_206 when 207 # Show Animation return command_207 when 208 # Change Transparent Flag return command_208 when 209 # Set Move Route return command_209 when 210 # Wait for Move's Completion return command_210 when 221 # Prepare for Transition return command_221 when 222 # Execute Transition return command_222 when 223 # Change Screen Color Tone return command_223 when 224 # Screen Flash return command_224 when 225 # Screen Shake return command_225 when 231 # Show Picture return command_231 when 232 # Move Picture return command_232 when 233 # Rotate Picture return command_233 when 234 # Change Picture Color Tone return command_234 when 235 # Erase Picture return command_235 when 236 # Set Weather Effects return command_236 when 241 # Play BGM return command_241 when 242 # Fade Out BGM return command_242 when 245 # Play BGS return command_245 when 246 # Fade Out BGS return command_246 when 247 # Memorize BGM/BGS return command_247 when 248 # Restore BGM/BGS return command_248 when 249 # Play ME return command_249 when 250 # Play SE return command_250 when 251 # Stop SE return command_251 when 301 # Battle Processing return command_301 when 601 # If Win return command_601 when 602 # If Escape return command_602 when 603 # If Lose return command_603 when 302 # Shop Processing return command_302 when 303 # Name Input Processing return command_303 when 311 # Change HP return command_311 when 312 # Change SP return command_312 when 313 # Change State return command_313 when 314 # Recover All return command_314 when 315 # Change EXP return command_315 when 316 # Change Level return command_316 when 317 # Change Parameters return command_317 when 318 # Change Skills return command_318 when 319 # Change Equipment return command_319 when 320 # Change Actor Name return command_320 when 321 # Change Actor Class return command_321 when 322 # Change Actor Graphic return command_322 when 331 # Change Enemy HP return command_331 when 332 # Change Enemy SP return command_332 when 333 # Change Enemy State return command_333 when 334 # Enemy Recover All return command_334 when 335 # Enemy Appearance return command_335 when 336 # Enemy Transform return command_336 when 337 # Show Battle Animation return command_337 when 338 # Deal Damage return command_338 when 339 # Force Action return command_339 when 340 # Abort Battle return command_340 when 351 # Call Menu Screen return command_351 when 352 # Call Save Screen return command_352 when 353 # Game Over return command_353 when 354 # Return to Title Screen return command_354 when 355 # Script return command_355 else # Other return true end end def command_dummy return true end #-------------------------------------------------------------------------- # * End Event #-------------------------------------------------------------------------- def command_end # Clear list of event commands @list = nil # If main map event and event ID are valid if @main and @event_id > 0 # Unlock event $game_map.events[@event_id].unlock end end #-------------------------------------------------------------------------- # * Command Skip #-------------------------------------------------------------------------- def command_skip # Get indent indent = @list[@index].indent # Loop loop do # If next event command is at the same level as indent if @list[@index+1].indent == indent # Continue return true end # Advance index @index += 1 end end #-------------------------------------------------------------------------- # * Get Character # parameter : parameter #-------------------------------------------------------------------------- def get_character(parameter) # Branch by parameter case parameter when -1 # player return $game_player when 0 # this event events = $game_map.events return events == nil ? nil : events[@event_id] else # specific event events = $game_map.events return events == nil ? nil : events[parameter] end end #-------------------------------------------------------------------------- # * Calculate Operated Value # operation : operation # operand_type : operand type (0: invariable 1: variable) # operand : operand (number or variable ID) #-------------------------------------------------------------------------- def operate_value(operation, operand_type, operand) # Get operand if operand_type == 0 value = operand else value = $game_variables[operand] end # Reverse sign of integer if operation is [decrease] if operation == 1 value = -value end # Return value return value end #-------------------------------------------------------------------------- # * Show Text #-------------------------------------------------------------------------- def command_101 # If other text has been set to message_text if $game_temp.message_text != nil # End return false end # Set message end waiting flag and callback @message_waiting = true $game_temp.message_proc = Proc.new { @message_waiting = false } # Set message text on first line $game_temp.message_text = @list[@index].parameters[0] + "\\n" line_count = 1 # Loop loop do # If next event command text is on the second line or after if @list[@index+1].code == 401 # Add the second line or after to message_text $game_temp.message_text += @list[@index+1].parameters[0] + "\\n" line_count += 1 # If event command is not on the second line or after else # If next event command is show choices if @list[@index+1].code == 102 # If choices fit on screen if @list[@index+1].parameters[0].size <= 4 - line_count # Advance index @index += 1 # Choices setup $game_temp.choice_start = line_count setup_choices(@list[@index].parameters) end # If next event command is input number elsif @list[@index+1].code == 103 # If number input window fits on screen if line_count < 4 # Advance index @index += 1 # Number input setup $game_temp.num_input_start = line_count $game_temp.num_input_variable_id = @list[@index].parameters[0] $game_temp.num_input_digits_max = @list[@index].parameters[1] end end # Continue return true end # Advance index @index += 1 end end #-------------------------------------------------------------------------- # * Show Choices #-------------------------------------------------------------------------- def command_102 # If text has been set to message_text if $game_temp.message_text != nil # End return false end # Set message end waiting flag and callback @message_waiting = true $game_temp.message_proc = Proc.new { @message_waiting = false } # Choices setup $game_temp.message_text = "" $game_temp.choice_start = 0 setup_choices(@parameters) # Continue return true end #-------------------------------------------------------------------------- # * When [**] #-------------------------------------------------------------------------- def command_402 # If fitting choices are selected if @branch[@list[@index].indent] == @parameters[0] # Delete branch data @branch.delete(@list[@index].indent) # Continue return true end # If it doesn't meet the condition: command skip return command_skip end #-------------------------------------------------------------------------- # * When Cancel #-------------------------------------------------------------------------- def command_403 # If choices are cancelled if @branch[@list[@index].indent] == 4 # Delete branch data @branch.delete(@list[@index].indent) # Continue return true end # If it doen't meet the condition: command skip return command_skip end #-------------------------------------------------------------------------- # * Input Number #-------------------------------------------------------------------------- def command_103 # If text has been set to message_text if $game_temp.message_text != nil # End return false end # Set message end waiting flag and callback @message_waiting = true $game_temp.message_proc = Proc.new { @message_waiting = false } # Number input setup $game_temp.message_text = "" $game_temp.num_input_start = 0 $game_temp.num_input_variable_id = @parameters[0] $game_temp.num_input_digits_max = @parameters[1] # Continue return true end #-------------------------------------------------------------------------- # * Change Text Options #-------------------------------------------------------------------------- def command_104 # If message is showing if $game_temp.message_window_showing # End return false end # Change each option $game_system.message_position = @parameters[0] $game_system.message_frame = @parameters[1] # Continue return true end #-------------------------------------------------------------------------- # * Button Input Processing #-------------------------------------------------------------------------- def command_105 # Set variable ID for button input @button_input_variable_id = @parameters[0] # Advance index @index += 1 # End return false end #-------------------------------------------------------------------------- # * Wait #-------------------------------------------------------------------------- def command_106 # Set wait count @wait_count = @parameters[0] * 2 # Continue return true end #-------------------------------------------------------------------------- # * Conditional Branch #-------------------------------------------------------------------------- def command_111 # Initialize local variable: result result = false case @parameters[0] when 0 # switch result = ($game_switches[@parameters[1]] == (@parameters[2] == 0)) when 1 # variable value1 = $game_variables[@parameters[1]] if @parameters[2] == 0 value2 = @parameters[3] else value2 = $game_variables[@parameters[3]] end case @parameters[4] when 0 # value1 is equal to value2 result = (value1 == value2) when 1 # value1 is greater than or equal to value2 result = (value1 >= value2) when 2 # value1 is less than or equal to value2 result = (value1 <= value2) when 3 # value1 is greater than value2 result = (value1 > value2) when 4 # value1 is less than value2 result = (value1 < value2) when 5 # value1 is not equal to value2 result = (value1 != value2) end when 2 # self switch if @event_id > 0 key = [$game_map.map_id, @event_id, @parameters[1]] if @parameters[2] == 0 result = ($game_self_switches[key] == true) else result = ($game_self_switches[key] != true) end end when 3 # timer if $game_system.timer_working sec = $game_system.timer / Graphics.frame_rate if @parameters[2] == 0 result = (sec >= @parameters[1]) else result = (sec <= @parameters[1]) end end when 4, 5 # actor, enemy when 6 # character character = get_character(@parameters[1]) if character != nil result = (character.direction == @parameters[2]) end when 7 if @parameters[2] == 0 result = $Trainer && ($Trainer.money >= @parameters[1]) else result = $Trainer && ($Trainer.money <= @parameters[1]) end when 8, 9, 10 # item, weapon, armor when 11 # button result = (Input.press?(@parameters[1])) when 12 # script result = pbExecuteScript(@parameters[1]) end # Store determinant results in hash @branch[@list[@index].indent] = result # If determinant results are true if @branch[@list[@index].indent] == true # Delete branch data @branch.delete(@list[@index].indent) # Continue return true end # If it doesn't meet the conditions: command skip return command_skip end #-------------------------------------------------------------------------- # * Else #-------------------------------------------------------------------------- def command_411 # If determinant results are false if @branch[@list[@index].indent] == false # Delete branch data @branch.delete(@list[@index].indent) # Continue return true end # If it doesn't meet the conditions: command skip return command_skip end #-------------------------------------------------------------------------- # * Loop #-------------------------------------------------------------------------- def command_112 # Continue return true end #-------------------------------------------------------------------------- # * Repeat Above #-------------------------------------------------------------------------- def command_413 # Get indent indent = @list[@index].indent # Loop loop do # Return index @index -= 1 # If this event command is the same level as indent if @list[@index].indent == indent # Continue return true end end end #-------------------------------------------------------------------------- # * Break Loop #-------------------------------------------------------------------------- def command_113 # Get indent indent = @list[@index].indent # Copy index to temporary variables temp_index = @index # Loop loop do # Advance index temp_index += 1 # If a fitting loop was not found if temp_index >= @list.size-1 # Continue return true end # If this event command is [repeat above] and indent is shallow if @list[temp_index].code == 413 and @list[temp_index].indent < indent # Update index @index = temp_index # Continue return true end end end #-------------------------------------------------------------------------- # * Exit Event Processing #-------------------------------------------------------------------------- def command_115 # End event command_end # Continue return true end #-------------------------------------------------------------------------- # * Erase Event #-------------------------------------------------------------------------- def command_116 # If event ID is valid if @event_id > 0 # Erase event $game_map.events[@event_id].erase end # Advance index @index += 1 # End return false end #-------------------------------------------------------------------------- # * Call Common Event #-------------------------------------------------------------------------- def command_117 # Get common event common_event = $data_common_events[@parameters[0]] # If common event is valid if common_event != nil # Make child interpreter @child_interpreter = Interpreter.new(@depth + 1) @child_interpreter.setup(common_event.list, @event_id) end # Continue return true end #-------------------------------------------------------------------------- # * Label #-------------------------------------------------------------------------- def command_118 # Continue return true end #-------------------------------------------------------------------------- # * Jump to Label #-------------------------------------------------------------------------- def command_119 # Get label name label_name = @parameters[0] # Initialize temporary variables temp_index = 0 # Loop loop do # If a fitting label was not found if temp_index >= @list.size-1 # Continue return true end # If this event command is a designated label name if @list[temp_index].code == 118 and @list[temp_index].parameters[0] == label_name # Update index @index = temp_index # Continue return true end # Advance index temp_index += 1 end end #-------------------------------------------------------------------------- # * Control Switches #-------------------------------------------------------------------------- def command_121 # Loop for group control for i in @parameters[0] .. @parameters[1] # Change switch $game_switches[i] = (@parameters[2] == 0) end # Refresh map $game_map.need_refresh = true # Continue return true end #-------------------------------------------------------------------------- # * Control Variables #-------------------------------------------------------------------------- def command_122 # Initialize value value = 0 # Branch with operand case @parameters[3] when 0 # invariable value = @parameters[4] when 1 # variable value = $game_variables[@parameters[4]] when 2 # random number value = @parameters[4] + rand(@parameters[5] - @parameters[4] + 1) when 3, 4, 5 # item, actor, enemy when 6 # character character = get_character(@parameters[4]) if character != nil case @parameters[5] when 0 # x-coordinate value = character.x when 1 # y-coordinate value = character.y when 2 # direction value = character.direction when 3 # screen x-coordinate value = character.screen_x when 4 # screen y-coordinate value = character.screen_y when 5 # terrain tag value = character.terrain_tag end end when 7 # other case @parameters[4] when 0 # map ID value = $game_map.map_id when 1, 3 # number of party members, steps when 2 # gold value = $Trainer ? $Trainer.money : 0 when 4 # play time value = Graphics.frame_count / Graphics.frame_rate when 5 # timer value = $game_system.timer / Graphics.frame_rate when 6 # save count value = $game_system.save_count end end # Loop for group control for i in @parameters[0] .. @parameters[1] # Branch with control case @parameters[2] when 0 # substitute $game_variables[i] = value when 1 # add $game_variables[i] += value when 2 # subtract $game_variables[i] -= value when 3 # multiply $game_variables[i] *= value when 4 # divide if value != 0 $game_variables[i] /= value end when 5 # remainder if value != 0 $game_variables[i] %= value end end # Maximum limit check if $game_variables[i] > 99999999 $game_variables[i] = 99999999 end # Minimum limit check if $game_variables[i] < -99999999 $game_variables[i] = -99999999 end end # Refresh map $game_map.need_refresh = true # Continue return true end #-------------------------------------------------------------------------- # * Control Self Switch #-------------------------------------------------------------------------- def command_123 # If event ID is valid if @event_id > 0 # Make a self switch key key = [$game_map.map_id, @event_id, @parameters[0]] # Change self switches $game_self_switches[key] = (@parameters[1] == 0) end # Refresh map $game_map.need_refresh = true # Continue return true end #-------------------------------------------------------------------------- # * Control Timer #-------------------------------------------------------------------------- def command_124 # If started if @parameters[0] == 0 $game_system.timer = @parameters[1] * Graphics.frame_rate $game_system.timer_working = true end # If stopped if @parameters[0] == 1 $game_system.timer_working = false end # Continue return true end alias command_125 command_dummy # Change Gold alias command_126 command_dummy # Change Items alias command_127 command_dummy # Change Weapons alias command_128 command_dummy # Change Armor alias command_129 command_dummy # Change Party Member #-------------------------------------------------------------------------- # * Change Windowskin #-------------------------------------------------------------------------- def command_131 # Change windowskin file name $game_system.windowskin_name = @parameters[0] # Continue return true end #-------------------------------------------------------------------------- # * Change Battle BGM #-------------------------------------------------------------------------- def command_132 # Change battle BGM $game_system.battle_bgm = @parameters[0] # Continue return true end #-------------------------------------------------------------------------- # * Change Battle End ME #-------------------------------------------------------------------------- def command_133 # Change battle end ME $game_system.battle_end_me = @parameters[0] # Continue return true end #-------------------------------------------------------------------------- # * Change Save Access #-------------------------------------------------------------------------- def command_134 # Change save access flag $game_system.save_disabled = (@parameters[0] == 0) # Continue return true end #-------------------------------------------------------------------------- # * Change Menu Access #-------------------------------------------------------------------------- def command_135 # Change menu access flag $game_system.menu_disabled = (@parameters[0] == 0) # Continue return true end #-------------------------------------------------------------------------- # * Change Encounter #-------------------------------------------------------------------------- def command_136 # Change encounter flag $game_system.encounter_disabled = (@parameters[0] == 0) # Make encounter count $game_player.make_encounter_count # Continue return true end #-------------------------------------------------------------------------- # * Transfer Player #-------------------------------------------------------------------------- def command_201 # If in battle if $game_temp.in_battle # Continue return true end # If transferring player, showing message, or processing transition if $game_temp.player_transferring or $game_temp.message_window_showing or $game_temp.transition_processing # End return false end # Set transferring player flag $game_temp.player_transferring = true # If appointment method is [direct appointment] if @parameters[0] == 0 # Set player move destination $game_temp.player_new_map_id = @parameters[1] $game_temp.player_new_x = @parameters[2] $game_temp.player_new_y = @parameters[3] $game_temp.player_new_direction = @parameters[4] # If appointment method is [appoint with variables] else # Set player move destination $game_temp.player_new_map_id = $game_variables[@parameters[1]] $game_temp.player_new_x = $game_variables[@parameters[2]] $game_temp.player_new_y = $game_variables[@parameters[3]] $game_temp.player_new_direction = @parameters[4] end # Advance index @index += 1 # If fade is set if @parameters[5] == 0 # Prepare for transition Graphics.freeze # Set transition processing flag $game_temp.transition_processing = true $game_temp.transition_name = "" end # End return false end #-------------------------------------------------------------------------- # * Set Event Location #-------------------------------------------------------------------------- def command_202 # If in battle if $game_temp.in_battle # Continue return true end # Get character character = get_character(@parameters[0]) # If no character exists if character == nil # Continue return true end # If appointment method is [direct appointment] if @parameters[1] == 0 # Set character position character.moveto(@parameters[2], @parameters[3]) # If appointment method is [appoint with variables] elsif @parameters[1] == 1 # Set character position character.moveto($game_variables[@parameters[2]], $game_variables[@parameters[3]]) # If appointment method is [exchange with another event] else old_x = character.x old_y = character.y character2 = get_character(@parameters[2]) if character2 != nil character.moveto(character2.x, character2.y) character2.moveto(old_x, old_y) end end # Set character direction case @parameters[4] when 8 # up character.turn_up when 6 # right character.turn_right when 2 # down character.turn_down when 4 # left character.turn_left end # Continue return true end #-------------------------------------------------------------------------- # * Scroll Map #-------------------------------------------------------------------------- def command_203 # If in battle if $game_temp.in_battle # Continue return true end # If already scrolling if $game_map.scrolling? # End return false end # Start scroll $game_map.start_scroll(@parameters[0], @parameters[1], @parameters[2]) # Continue return true end #-------------------------------------------------------------------------- # * Change Map Settings #-------------------------------------------------------------------------- def command_204 case @parameters[0] when 0 # panorama $game_map.panorama_name = @parameters[1] $game_map.panorama_hue = @parameters[2] when 1 # fog $game_map.fog_name = @parameters[1] $game_map.fog_hue = @parameters[2] $game_map.fog_opacity = @parameters[3] $game_map.fog_blend_type = @parameters[4] $game_map.fog_zoom = @parameters[5] $game_map.fog_sx = @parameters[6] $game_map.fog_sy = @parameters[7] when 2 # battleback $game_map.battleback_name = @parameters[1] $game_temp.battleback_name = @parameters[1] end # Continue return true end #-------------------------------------------------------------------------- # * Change Fog Color Tone #-------------------------------------------------------------------------- def command_205 # Start color tone change $game_map.start_fog_tone_change(@parameters[0], @parameters[1] * 2) # Continue return true end #-------------------------------------------------------------------------- # * Change Fog Opacity #-------------------------------------------------------------------------- def command_206 # Start opacity level change $game_map.start_fog_opacity_change(@parameters[0], @parameters[1] * 2) # Continue return true end #-------------------------------------------------------------------------- # * Show Animation #-------------------------------------------------------------------------- def command_207 # Get character character = get_character(@parameters[0]) # If no character exists if character == nil # Continue return true end # Set animation ID character.animation_id = @parameters[1] # Continue return true end #-------------------------------------------------------------------------- # * Change Transparent Flag #-------------------------------------------------------------------------- def command_208 # Change player transparent flag $game_player.transparent = (@parameters[0] == 0) # Continue return true end #-------------------------------------------------------------------------- # * Set Move Route #-------------------------------------------------------------------------- def command_209 # Get character character = get_character(@parameters[0]) # If no character exists if character == nil # Continue return true end # Force move route character.force_move_route(@parameters[1]) # Continue return true end #-------------------------------------------------------------------------- # * Wait for Move's Completion #-------------------------------------------------------------------------- def command_210 # If not in battle unless $game_temp.in_battle # Set move route completion waiting flag @move_route_waiting = true end # Continue return true end #-------------------------------------------------------------------------- # * Prepare for Transition #-------------------------------------------------------------------------- def command_221 # If showing message window if $game_temp.message_window_showing # End return false end # Prepare for transition Graphics.freeze # Continue return true end #-------------------------------------------------------------------------- # * Execute Transition #-------------------------------------------------------------------------- def command_222 # If transition processing flag is already set if $game_temp.transition_processing # End return false end # Set transition processing flag $game_temp.transition_processing = true $game_temp.transition_name = @parameters[0] # Advance index @index += 1 # End return false end #-------------------------------------------------------------------------- # * Change Screen Color Tone #-------------------------------------------------------------------------- def command_223 # Start changing color tone $game_screen.start_tone_change(@parameters[0], @parameters[1] * 2) # Continue return true end #-------------------------------------------------------------------------- # * Screen Flash #-------------------------------------------------------------------------- def command_224 # Start flash $game_screen.start_flash(@parameters[0], @parameters[1] * 2) # Continue return true end #-------------------------------------------------------------------------- # * Screen Shake #-------------------------------------------------------------------------- def command_225 # Start shake $game_screen.start_shake(@parameters[0], @parameters[1], @parameters[2] * 2) # Continue return true end #-------------------------------------------------------------------------- # * Show Picture #-------------------------------------------------------------------------- def command_231 # Get picture number number = @parameters[0] + ($game_temp.in_battle ? 50 : 0) # If appointment method is [direct appointment] if @parameters[3] == 0 x = @parameters[4] y = @parameters[5] # If appointment method is [appoint with variables] else x = $game_variables[@parameters[4]] y = $game_variables[@parameters[5]] end # Show picture $game_screen.pictures[number].show(@parameters[1], @parameters[2], x, y, @parameters[6], @parameters[7], @parameters[8], @parameters[9]) # Continue return true end #-------------------------------------------------------------------------- # * Move Picture #-------------------------------------------------------------------------- def command_232 # Get picture number number = @parameters[0] + ($game_temp.in_battle ? 50 : 0) # If appointment method is [direct appointment] if @parameters[3] == 0 x = @parameters[4] y = @parameters[5] # If appointment method is [appoint with variables] else x = $game_variables[@parameters[4]] y = $game_variables[@parameters[5]] end # Move picture $game_screen.pictures[number].move(@parameters[1] * 2, @parameters[2], x, y, @parameters[6], @parameters[7], @parameters[8], @parameters[9]) # Continue return true end #-------------------------------------------------------------------------- # * Rotate Picture #-------------------------------------------------------------------------- def command_233 # Get picture number number = @parameters[0] + ($game_temp.in_battle ? 50 : 0) # Set rotation speed $game_screen.pictures[number].rotate(@parameters[1]) # Continue return true end #-------------------------------------------------------------------------- # * Change Picture Color Tone #-------------------------------------------------------------------------- def command_234 # Get picture number number = @parameters[0] + ($game_temp.in_battle ? 50 : 0) # Start changing color tone $game_screen.pictures[number].start_tone_change(@parameters[1], @parameters[2] * 2) # Continue return true end #-------------------------------------------------------------------------- # * Erase Picture #-------------------------------------------------------------------------- def command_235 # Get picture number number = @parameters[0] + ($game_temp.in_battle ? 50 : 0) # Erase picture $game_screen.pictures[number].erase # Continue return true end #-------------------------------------------------------------------------- # * Set Weather Effects #-------------------------------------------------------------------------- def command_236 # Set Weather Effects $game_screen.weather(@parameters[0], @parameters[1], @parameters[2]) # Continue return true end #-------------------------------------------------------------------------- # * Play BGM #-------------------------------------------------------------------------- def command_241 # Play BGM $game_system.bgm_play(@parameters[0]) # Continue return true end #-------------------------------------------------------------------------- # * Fade Out BGM #-------------------------------------------------------------------------- def command_242 # Fade out BGM $game_system.bgm_fade(@parameters[0]) # Continue return true end #-------------------------------------------------------------------------- # * Play BGS #-------------------------------------------------------------------------- def command_245 # Play BGS $game_system.bgs_play(@parameters[0]) # Continue return true end #-------------------------------------------------------------------------- # * Fade Out BGS #-------------------------------------------------------------------------- def command_246 # Fade out BGS $game_system.bgs_fade(@parameters[0]) # Continue return true end #-------------------------------------------------------------------------- # * Memorize BGM/BGS #-------------------------------------------------------------------------- def command_247 # Memorize BGM/BGS $game_system.bgm_memorize $game_system.bgs_memorize # Continue return true end #-------------------------------------------------------------------------- # * Restore BGM/BGS #-------------------------------------------------------------------------- def command_248 # Restore BGM/BGS $game_system.bgm_restore $game_system.bgs_restore # Continue return true end #-------------------------------------------------------------------------- # * Play ME #-------------------------------------------------------------------------- def command_249 # Play ME $game_system.me_play(@parameters[0]) # Continue return true end #-------------------------------------------------------------------------- # * Play SE #-------------------------------------------------------------------------- def command_250 # Play SE $game_system.se_play(@parameters[0]) # Continue return true end #-------------------------------------------------------------------------- # * Stop SE #-------------------------------------------------------------------------- def command_251 # Stop SE Audio.se_stop # Continue return true end def command_if(value) if @branch[@list[@index].indent] == value @branch.delete(@list[@index].indent) return true end return command_skip end alias command_301 command_dummy # Battle Processing def command_601; command_if(0); end # If Win def command_602; command_if(1); end # If Escape def command_603; command_if(2); end # If Lose alias command_302 command_dummy # Shop Processing alias command_303 command_dummy # Name Processing alias command_311 command_dummy # Change HP alias command_312 command_dummy # Change SP alias command_313 command_dummy # Change State alias command_314 command_dummy # Recover All alias command_315 command_dummy # Change EXP alias command_316 command_dummy # Change Level alias command_317 command_dummy # Change Parameters alias command_318 command_dummy # Change Skills alias command_319 command_dummy # Change Equipment alias command_320 command_dummy # Change Actor Name alias command_321 command_dummy # Change Actor Class alias command_322 command_dummy # Change Actor Graphic alias command_331 command_dummy # Change Enemy HP alias command_332 command_dummy # Change Enemy SP alias command_333 command_dummy # Change Enemy State alias command_334 command_dummy # Enemy Recover All alias command_335 command_dummy # Enemy Appearance alias command_336 command_dummy # Enemy Transform alias command_337 command_dummy # Show Battle Animation alias command_338 command_dummy # Deal Damage alias command_339 command_dummy # Force Action alias command_340 command_dummy # Abort Battle #-------------------------------------------------------------------------- # * Call Menu Screen #-------------------------------------------------------------------------- def command_351 # Set menu calling flag $game_temp.menu_calling = true # Advance index @index += 1 # End return false end #-------------------------------------------------------------------------- # * Call Save Screen #-------------------------------------------------------------------------- def command_352 # Set save calling flag $game_temp.save_calling = true # Advance index @index += 1 # End return false end #-------------------------------------------------------------------------- # * Game Over #-------------------------------------------------------------------------- def command_353 # Set game over flag $game_temp.gameover = true # End return false end #-------------------------------------------------------------------------- # * Return to Title Screen #-------------------------------------------------------------------------- def command_354 # Set return to title screen flag $game_temp.to_title = true # End return false end #-------------------------------------------------------------------------- # * Script #-------------------------------------------------------------------------- def command_355 script = @list[@index].parameters[0] + "\\n" loop do if @list[@index+1].code == 655 || @list[@index+1].code == 355 script += @list[@index+1].parameters[0] + "\\n" else break end @index += 1 end result = pbExecuteScript(script) return true end end[/CODE] [CODE]#============================================================================== # Splash Screen #============================================================================== # Sephiroth Spawn # 01.08.06 # Version 2 # Modified by Harshboy/Flameguru #-------------------------------------------------------------------------- # Call Using $scene = Scene_Intro.new([pics], splash_screen) #============================================================================== #============================================================================== # ** Scene_Intro #============================================================================== class Scene_Intro #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize(pics, splash = nil) @pics, @splash = pics, splash end def setTitle(sprite,title) @cache={} if !@cache if @currentTitle!=title sprite.setBitmap("Graphics/Titles/#{title}") @currentTitle=title end end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main # Loads Data System and Game System data_system = load_data("Data/System.rxdata") game_system = Game_System.new # Loads the Title.mid in Audio/BGM game_system.bgm_play(data_system.title_bgm) # Instance Variables @item, @speed, @o_speed, @phase = 0, 15, 20, 0 # Background Images @sprite = GifSprite.new setTitle(@sprite, @pics[@item]) @sprite.opacity = 5 # Start Logo @start = GifSprite.new setTitle(@start,"Start") @start.y, @start.z, @start.opacity = 250, 10, 0 # Execute transition Graphics.transition # Main loop while $scene == self # Update game screen Graphics.update # Update input information Input.update # Frame update @sprite.update case @phase when 0; intro_update # Into Updating when 1; splash_update # Splash Updating when 2; to_splash_update # From Intro To Splash Transition when 3; to_title_update # From Splash to Title Transtion when 4; toDeleteUpdate end end # Prepare for transition Graphics.freeze # Dispose of Sprites if @cache for i in @cache.values i.dispose end end @sprite.dispose @start.dispose end #-------------------------------------------------------------------------- # * Frame Update : Intro Images #-------------------------------------------------------------------------- def intro_update # If C is pressed if Input.trigger?(Input::C) && @speed>=0 @phase = @splash.nil? ? 3 : 2 end # Updates Sprite Opacity @sprite.opacity += @speed # Changes Direction @speed *= -1 if @sprite.opacity >= 255 # Change Sprite if @sprite.opacity <= 0 @item += 1 @speed *= -1 @item == @pics.size ? @phase = @splash.nil? ? 3 : 2 : setTitle(@sprite,@pics[@item]) end end #-------------------------------------------------------------------------- # * Frame Update : Splash Image #-------------------------------------------------------------------------- def splash_update # If C is pressed if Input.trigger?(Input::C) @phase = 3 end if Input.press?(Input::DOWN) && Input.press?(Input::CTRL) && Input.press?(Input::B) @phase=4 end # Loads Sprite Splash Bitmap setTitle(@sprite,@splash) # Updates Start Logo Opacity @start.opacity += @o_speed # Changes Direction @o_speed *= -1 if @start.opacity >= 255 || @start.opacity <= 0 # Updates Splash @sprite.opacity += @speed if @sprite.opacity < 255 end #-------------------------------------------------------------------------- # * Frame Update : Intro To Splash Transistion #-------------------------------------------------------------------------- def to_splash_update @sprite.opacity > 0 ? @sprite.opacity -= @speed : @phase = 1 end #-------------------------------------------------------------------------- # * Frame Update : Splash To Title Transistion #-------------------------------------------------------------------------- def to_title_update # Decrease Splash Opacity @sprite.opacity -= @speed if @sprite.opacity > 0 # Decresh Start Logo Opacity @start.opacity -= @speed if @start.opacity > 0 # Proceed to Title Screen if @sprite.opacity <= 0 && @start.opacity <= 0 Audio.bgm_stop sscene=PokemonLoadScene.new sscreen=PokemonLoad.new(sscene) sscreen.pbStartLoadScreen end end def toDeleteUpdate # Decrease Splash Opacity @sprite.opacity -= @speed if @sprite.opacity > 0 # Decresh Start Logo Opacity @start.opacity -= @speed if @start.opacity > 0 # Proceed to Title Screen if @sprite.opacity <= 0 && @start.opacity <= 0 Audio.bgm_stop sscene=PokemonLoadScene.new sscreen=PokemonLoad.new(sscene) sscreen.pbStartDeleteScreen end end end[/CODE] [CODE]=begin Modified Scene_Map class for Pokémon. =end class Scene_Map def spriteset for i in @spritesets.values return i if i.map==$game_map end return @spritesets.values[0] end def disposeSpritesets for i in @spritesets.keys if @spritesets[i] @spritesets[i].dispose @spritesets[i]=nil end end @spritesets.clear @spritesets={} end def createSpritesets @spritesets={} for map in $MapFactory.maps @spritesets[map.map_id]=Spriteset_Map.new(map) end $MapFactory.setSceneChanged(self,$PokemonTemp.mapChanged) $PokemonTemp.mapChanged=false updateSpritesets end def updateMaps for map in $MapFactory.maps map.update end $MapFactory.updateMaps if $PokemonTemp.mapChanged $PokemonTemp.mapChanged=false $MapFactory.setSceneChanged(self,true) end end def updateSpritesets @spritesets={} if !@spritesets keys=@spritesets.keys.clone for i in keys if !$MapFactory.hasMap?(i) @spritesets[i].dispose if @spritesets[i] @spritesets[i]=nil @spritesets.delete(i) else @spritesets[i].update end end for map in $MapFactory.maps if !@spritesets[map.map_id] @spritesets[map.map_id]=Spriteset_Map.new(map) end end Events.onMapUpdate.trigger(self) end def main createSpritesets Graphics.transition loop do Graphics.update Input.update update if $scene != self break end end Graphics.freeze disposeSpritesets if $game_temp.to_title Graphics.transition Graphics.freeze end end def miniupdate $PokemonTemp.miniupdate=true if $PokemonTemp loop do updateMaps $game_player.update $game_system.update $game_screen.update unless $game_temp.player_transferring break end transfer_player if $game_temp.transition_processing break end end updateSpritesets $PokemonTemp.miniupdate=false if $PokemonTemp end def update loop do updateMaps $game_system.map_interpreter.update $game_player.update $game_system.update $game_screen.update unless $game_temp.player_transferring break end transfer_player if $game_temp.transition_processing break end end updateSpritesets if $game_temp.to_title $scene = pbCallTitle return end if $game_temp.transition_processing $game_temp.transition_processing = false if $game_temp.transition_name == "" Graphics.transition(20) else Graphics.transition(40, "Graphics/Transitions/" + $game_temp.transition_name) end end if $game_temp.message_window_showing return end if Input.trigger?(Input::C) unless $game_system.map_interpreter.running? $PokemonTemp.hiddenMoveEventCalling=true end end if Input.trigger?(Input::B) unless $game_system.map_interpreter.running? or $game_system.menu_disabled $game_temp.menu_calling = true $game_temp.menu_beep = true end end if Input.trigger?(Input::F5) unless $game_system.map_interpreter.running? $PokemonTemp.keyItemCalling = true if $PokemonTemp end end if $DEBUG and Input.press?(Input::F9) $game_temp.debug_calling = true end unless $game_player.moving? if $game_temp.battle_calling call_battle elsif $game_temp.shop_calling call_shop elsif $game_temp.name_calling call_name elsif $game_temp.menu_calling call_menu elsif $game_temp.save_calling call_save elsif $game_temp.debug_calling call_debug elsif $PokemonTemp && $PokemonTemp.keyItemCalling $PokemonTemp.keyItemCalling=false $game_player.straighten Kernel.pbUseKeyItem elsif $PokemonTemp && $PokemonTemp.hiddenMoveEventCalling Kernel.pbHiddenMoveEvent end end end def call_name $game_temp.name_calling = false $game_player.straighten $game_map.update $scene = Scene_Name.new end def call_menu $game_temp.menu_calling = false $game_player.straighten $game_map.update sscene=PokemonMenu_Scene.new sscreen=PokemonMenu.new(sscene) sscreen.pbStartPokemonMenu end def call_debug $game_temp.debug_calling = false $game_system.se_play($data_system.decision_se) $game_player.straighten $scene = Scene_Debug.new end def autofade(mapid) playingBGM=$game_system.playing_bgm playingBGS=$game_system.playing_bgs return if !playingBGM && !playingBGS map=load_data(sprintf("Data/Map%03d.rxdata", mapid)) if playingBGM && map.autoplay_bgm if playingBGM.name!=map.bgm.name $game_system.bgm_fade(0.8) end end if playingBGS && map.autoplay_bgs if playingBGS.name!=map.bgs.name $game_system.bgs_fade(0.8) end end Graphics.frame_reset end def transfer_player(cancelVehicles=true) $game_temp.player_transferring = false Events.onMapTransferring.trigger( self,$game_temp.player_new_map_id,cancelVehicles) autofade($game_temp.player_new_map_id) if $game_map.map_id != $game_temp.player_new_map_id $MapFactory.setup($game_temp.player_new_map_id) end $game_player.moveto($game_temp.player_new_x, $game_temp.player_new_y) case $game_temp.player_new_direction when 2 $game_player.turn_down when 4 $game_player.turn_left when 6 $game_player.turn_right when 8 $game_player.turn_up end $game_player.straighten $game_map.update disposeSpritesets GC.start createSpritesets if $game_temp.transition_processing $game_temp.transition_processing = false Graphics.transition(20) end $game_map.autoplay Graphics.frame_reset Input.update end end[/CODE] [CODE]class Win32API @@RGSSWINDOW=nil @@GetCurrentThreadId=Win32API.new('kernel32','GetCurrentThreadId', '%w()','l') @@GetWindowThreadProcessId=Win32API.new('user32','GetWindowThreadProcessId', '%w(l p)','l') @@FindWindowEx=Win32API.new('user32','FindWindowEx', '%w(l l p p)','l') def Win32API.SetWindowText(text) hWnd = pbFindRgssWindow swp = Win32API.new('user32', 'SetWindowTextA', %(l, p), 'i') swp.call(hWnd, text) end # Added by Peter O. as a more reliable way to get the RGSS window def Win32API.pbFindRgssWindow return @@RGSSWINDOW if @@RGSSWINDOW processid=[0].pack('l') threadid=@@GetCurrentThreadId.call nextwindow=0 begin nextwindow=@@FindWindowEx.call(0,nextwindow,"RGSS Player",0) if nextwindow wndthreadid=@@GetWindowThreadProcessId.call(nextwindow,processid) if wndthreadid==threadid @@RGSSWINDOW=nextwindow return @@RGSSWINDOW end end end until nextwindow==0 raise "Can't find RGSS player window" return 0 end def Win32API.GetPrivateProfileString(section, key) val = "\\0"*256 gps = Win32API.new('kernel32', 'GetPrivateProfileString',%w(p p p p l p), 'l') gps.call(section, key, "", val, 256, ".\\\\Game.ini") val.delete!("\\0") return val end def Win32API.SetWindowPos(w, h) hWnd = pbFindRgssWindow windowrect=Win32API.GetWindowRect clientsize=Win32API.client_size xExtra=windowrect.width-clientsize[0] yExtra=windowrect.height-clientsize[1] swp = Win32API.new('user32', 'SetWindowPos', %(l, l, i, i, i, i, i), 'i') win = swp.call(hWnd, 0, windowrect.x, windowrect.y, w+xExtra,h+yExtra, 0) return win end def Win32API.client_size hWnd = pbFindRgssWindow rect = [0, 0, 0, 0].pack('l4') Win32API.new('user32', 'GetClientRect', %w(l p), 'i').call(hWnd, rect) width, height = rect.unpack('l4')[2..3] return width, height end def Win32API.GetWindowRect hWnd = pbFindRgssWindow rect = [0, 0, 0, 0].pack('l4') Win32API.new('user32', 'GetWindowRect', %w(l p), 'i').call(hWnd, rect) x,y,width, height = rect.unpack('l4') return Rect.new(x,y,width-x,height-y) end end [/CODE] [CODE] class Game_Map TILEWIDTH = 32 TILEHEIGHT = 32 def self.realResX return 4 * TILEWIDTH end def self.realResY return 4 * TILEHEIGHT end def display_x=(value) @display_x=value $MapFactory.setMapsInRange if $MapFactory end def display_y=(value) @display_y=value $MapFactory.setMapsInRange if $MapFactory end def start_scroll(direction, distance, speed) @scroll_direction = direction if direction==2 || direction==8 @scroll_rest = distance * Game_Map.realResY else @scroll_rest = distance * Game_Map.realResX end @scroll_speed = speed end def scroll_down(distance) self.display_y+=distance end def scroll_left(distance) self.display_x-=distance end def scroll_right(distance) self.display_x+=distance end def scroll_up(distance) self.display_y-=distance end end class Game_Player < Game_Character def center(x, y) center_x = (Graphics.width/2 - Game_Map::TILEWIDTH/2) * 4 # X coordinate in the center of the screen center_y = (Graphics.height/2 - Game_Map::TILEHEIGHT/2) * 4 # Y coordinate in the center of the screen max_x = ($game_map.width - Graphics.width*1.0/Game_Map::TILEWIDTH) * Game_Map.realResX max_y = ($game_map.height - Graphics.height*1.0/Game_Map::TILEHEIGHT) * Game_Map.realResY dispx=x * Game_Map.realResX - center_x dispy=y * Game_Map.realResY - center_y $game_map.display_x = dispx#[0, [dispx, max_x].min].max $game_map.display_y = dispy#[0, [dispy, max_y].min].max end end [/CODE] [CODE]########################################################### class Scene_Movie ########################################################### #Created by SoundSpawn ########################################################### #Fixed by Popper ########################################################### #Instruction # 1) Movies must in in a new folder called Movies in your directory # 2)If you call this script from and event (EG: Call Script: $scene = Scene_Movie.new("INTRO") ) # 3) Have fun playin movies with this script!!! ########################################################### def initialize(movie) @movie_name = Dir.getwd()+"\\\\Movies\\\\"+movie+".avi" main end def main @temp = Win32API.pbFindRgssWindow.to_s movie = Win32API.new('winmm','mciSendString','%w(p,p,l,l)','V') movie.call("open \\""+@movie_name+"\\" alias FILE style 1073741824 parent " + @temp.to_s,0,0,0) @message = Win32API.new('user32','SendMessage','%w(l,l,l,l)','V') @detector = Win32API.new('user32','GetSystemMetrics','%w(l)','L') @width = @detector.call(0) if @width == 640 #fullscreen Graphics.update sleep(0.1) Graphics.update sleep(0.1) Graphics.update sleep(0.1) #fullscreen end status = " " * 255 movie.call("play FILE",0,0,0) loop do sleep(0.1) @message.call(@temp.to_i,11,0,0) Graphics.update @message.call(@temp.to_i,11,1,0) Input.update movie.call("status FILE mode",status,255,0) true_status = status.unpack("aaaa") if true_status.to_s != "play" break end if Input.trigger?(Input::B) $scene = Scene_Map.new break end end $scene = Scene_Map.new end end[/CODE] [CODE]CREDITS_FONT = ["Calligraph421 BT", "Viner Hand ITC", "Arial", "Times New Roman"] CREDITS_SIZE = 24 CREDITS_OUTLINE = Color.new(0,0,127, 255) CREDITS_SHADOW = Color.new(0,0,0, 100) CREDITS_FILL = Color.new(255,255,255, 255) #============================================================================== # ¦ Scene_Credits #------------------------------------------------------------------------------ # Scrolls the credits you make below. Original Author unknown. Edited by # MiDas Mike so it doesn't play over the Title, but runs by calling the following: # $scene = Scene_Credits.new # New Edit 3/6/2007 11:14 PM by AvatarMonkeyKirby. # Ok, what I've done is changed the part of the script that was supposed to make # the credits automatically end so that way they actually end! Yes, they will # actually end when the credits are finished! So, that will make the people you # should give credit to now is: UNKOWN, MiDas Mike, and AvatarMonkeyKirby. # -sincerly yours, # Your Beloved # Oh yea, and I also added a line of code that fades out the BGM so it fades # sooner and smoother. #============================================================================== class Scene_Credits # This next piece of code is the credits. #Start Editing CREDIT=<<_END_ _END_ #Stop Editing def main #------------------------------- # Animated Background Setup #------------------------------- @sprite = Sprite.new #@sprite.bitmap = RPG::Cache.title($data_system.title_name) @backgroundList = ["Black"] #Edit this to the title screen(s) you wish to show in the background. They do repeat. @backgroundGameFrameCount = 0 # Number of game frames per background frame. @backgroundG_BFrameCount = 3.4 @sprite.bitmap = RPG::Cache.title(@backgroundList[0]) #------------------ # Credits txt Setup #------------------ credit_lines = CREDIT.split(/\\n/) credit_bitmap = Bitmap.new(640,32 * credit_lines.size) credit_lines.each_index do |i| line = credit_lines[i] credit_bitmap.font.name = CREDITS_FONT credit_bitmap.font.size = CREDITS_SIZE x = 0 credit_bitmap.font.color = CREDITS_OUTLINE credit_bitmap.draw_text(0 + 1,i * 32 + 1,640,32,line,1) credit_bitmap.draw_text(0 - 1,i * 32 + 1,640,32,line,1) credit_bitmap.draw_text(0 + 1,i * 32 - 1,640,32,line,1) credit_bitmap.draw_text(0 - 1,i * 32 - 1,640,32,line,1) credit_bitmap.font.color = CREDITS_SHADOW credit_bitmap.draw_text(0,i * 32 + 8,640,32,line,1) credit_bitmap.font.color = CREDITS_FILL credit_bitmap.draw_text(0,i * 32,640,32,line,1) end @credit_sprite = Sprite.new(Viewport.new(0,50,640,380)) @credit_sprite.bitmap = credit_bitmap @credit_sprite.z = 9998 @credit_sprite.oy = -430 #-430 @frame_index = 0 @last_flag = false #-------- # Setup #-------- #Stops all audio but background music. Audio.me_stop Audio.bgs_stop Audio.se_stop Graphics.transition loop do Graphics.update Input.update update if $scene != self break end end Graphics.freeze @sprite.dispose @credit_sprite.dispose end ##Checks if credits bitmap has reached it's ending point def last? if @frame_index > (@credit_sprite.bitmap.height + 500) $scene = Scene_Map.new Audio.bgm_fade(10000) #aprox 10 seconds return true end return false end #Check if the credits should be cancelled def cancel? if Input.trigger?(Input::C) $scene = Scene_Map.new return true end return false end def update @backgroundGameFrameCount = @backgroundGameFrameCount + 1 if @backgroundGameFrameCount >= @backgroundG_BFrameCount @backgroundGameFrameCount = 0 # Add current background frame to the end @backgroundList = @backgroundList << @backgroundList[0] # and drop it from the first position @backgroundList.delete_at(0) @sprite.bitmap = RPG::Cache.title(@backgroundList[0]) end return if cancel? return if last? @credit_sprite.oy += 1 #this is the speed that the text scrolls. 1 is default #The fastest I'd recomend is 5, after that it gets hard to read. @frame_index += 1 #This should fix the non-self-ending credits end end[/CODE] [CODE]#============================================================================== # - Scene_Pokegear #------------------------------------------------------------------------------ # Modified By Harshboy # Modified by Peter O. # Also Modified By OblivionMew #============================================================================== class Scene_Pokegear #-------------------------------------------------------------------------- # initialize #-------------------------------------------------------------------------- def initialize(menu_index = 0) @menu_index = menu_index end #-------------------------------------------------------------------------- # main #-------------------------------------------------------------------------- def main # Main Menu settings you can add or change these commands=[ _INTL("Map"), _INTL("Radio"), _INTL("Phone"), _INTL("Exit") ] @command_window = Window_CommandPokemon.new(commands,160) @command_window.index = @menu_index @command_window.x = (Graphics.width - @command_window.width) - 8 @command_window.y = 640 @card = GifSprite.new @card.setBitmap("Graphics/Pictures/Pokegearback") @card.x = 0 @card.y = 0 @map_icon = Sprite.new @map_icon.bitmap = RPG::Cache.picture("mapicon") @map_icon.x = 0 @map_icon.y = 57 @button_up = Sprite.new @button_up.bitmap = RPG::Cache.picture("buttonunp") @button_up.x = 320 @button_up.y = 80 @button_down = Sprite.new @button_down.bitmap = RPG::Cache.picture("buttonunp") @button_down.x = 320 @button_down.y = 165 @arr_icon=AnimatedSprite.create("Graphics/Pictures/selarr.png",8,1) @arr_icon.x = 60 @arr_icon.y = 57 @arr_icon.start @radio_icon = Sprite.new @radio_icon.bitmap = RPG::Cache.picture("radicon") @radio_icon.x = 0 @radio_icon.y = 109 @arr_icon.z=99999 @phone_icon = Sprite.new @phone_icon.bitmap = RPG::Cache.picture("phonicon") @phone_icon.x = 0 @phone_icon.y = 161 @exit_icon = Sprite.new @exit_icon.bitmap = RPG::Cache.picture("exicon") @exit_icon.x = 0 @exit_icon.y = 265 @trainer = Sprite.new @trainer.x = 360 @trainer.y = 80 @trainer.zoom_x = 1.0 @trainer.zoom_y = 1.0 @trainer.z = 99999 @trainer.bitmap = RPG::Cache.character( sprintf("trainer%03d.png",$Trainer.trainertype),0 ) @info = Window_UnformattedTextPokemon.new("") @info.height = Graphics.height / 4 + 16 @info.width = Graphics.width / 2 + 74 @info.x = 160 @info.y = Graphics.height - @info.height @info.z = 99999 @info.letterbyletter=false @target_window = Window_UnformattedTextPokemon.new("") @target_window.visible = false @target_window.active = false @target_window.letterbyletter=false Graphics.transition loop do Graphics.update Input.update update if $scene != self break end end @target_window.dispose Graphics.freeze @command_window.dispose @trainer.dispose @card.bitmap.dispose @info.dispose @arr_icon.dispose @map_icon.dispose @phone_icon.dispose @radio_icon.dispose @exit_icon.dispose @button_up.dispose @button_down.dispose end #-------------------------------------------------------------------------- # update the scene #-------------------------------------------------------------------------- def update @arr_icon.update @command_window.update @info.update if Input.press?(Input::UP) @button_up.bitmap = RPG::Cache.picture("buttonp") else @button_up.bitmap = RPG::Cache.picture("buttonunp") end if Input.press?(Input::DOWN) @button_down.bitmap = RPG::Cache.picture("buttonp") else @button_down.bitmap = RPG::Cache.picture("buttonunp") end case @command_window.index when 0 @map_icon.x = 32 @phone_icon.x = 0 @radio_icon.x = 0 @exit_icon.x = 0 @arr_icon.y=57 when 1 @map_icon.x = 0 @phone_icon.x = 0 @radio_icon.x = 32 @exit_icon.x = 0 @arr_icon.y=109 when 2 @map_icon.x = 0 @phone_icon.x = 32 @radio_icon.x = 0 @exit_icon.x = 0 @arr_icon.y=161 when 3 @map_icon.x = 0 @phone_icon.x = 0 @radio_icon.x = 0 @exit_icon.x = 32 @arr_icon.y=265 end #update command window and the info if it's active if @command_window.active update_command update_info return end end #-------------------------------------------------------------------------- # update the command window #-------------------------------------------------------------------------- def update_command if Input.trigger?(Input::B) $game_system.se_play($data_system.cancel_se) $scene = Scene_Map.new return end if Input.trigger?(Input::C) case @command_window.index when 0 $game_system.se_play($data_system.decision_se) pbFadeOutIn(99999) { scene=PokemonRegionMapScene.new screen=PokemonRegionMap.new(scene) screen.pbStartScreen } when 1 $game_system.se_play($data_system.decision_se) $scene = Scene_Jukebox.new when 2 $game_system.se_play($data_system.decision_se) pbFadeOutIn(99999) { PokemonPhoneScene.new.start } when 3 $game_system.se_play($data_system.decision_se) $scene = Scene_Map.new end return end end def update_info case @command_window.index when 0 @info.text=_INTL("A Map\\r\\nShows visited Places.") when 1 @info.text=_INTL("A Radio\\r\\nUsed to listen to Music.") when 2 @info.text=_INTL("A Phone\\r\\nUsed to call People.") when 3 @info.text=_INTL("Closes the PokeGear and returns to the game.") end end end[/CODE] [CODE]#------------------------------------------------------------------------------ # ** Scene_iPod # ** Created by xLeD (Scene_Jukebox) # ** Modified by Harshboy #------------------------------------------------------------------------------ # This class performs menu screen processing. #============================================================================== class Scene_Jukebox #-------------------------------------------------------------------------- # * Object Initialization # menu_index : command cursor's initial position #-------------------------------------------------------------------------- def initialize(menu_index = 0) @menu_index = menu_index end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main # Make song command window @spriteset = Spriteset_Map.new fadein = true # Makes the text window @Background = Sprite.new @Background.bitmap = RPG::Cache.picture("iPod") @Background.z += 255 @Background.opacity = 255 @choices=[ _INTL("March"), _INTL("Lullaby"), _INTL("Oak"), _INTL("Custom"), _INTL("Exit") ] @command_window = Window_CommandPokemon.new(@choices,160) @command_window.index = @menu_index @command_window.height=160 @command_window.width=176 @command_window.x = 150 @command_window.y = 130 @command_window.z=256 @command_window.opacity = 0 @custom=false # Execute transition Graphics.transition # Main loop loop do # Update game screen Graphics.update # Update input information Input.update # Frame update update # Abort loop if screen is changed if $scene != self break end end # Prepares for transition Graphics.freeze # Disposes the windows @command_window.dispose @spriteset.dispose @Background.dispose end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update # Update windows @command_window.update if @custom updateCustom else update_command end return end #-------------------------------------------------------------------------- # * Frame Update (when command window is active) #-------------------------------------------------------------------------- def updateCustom if Input.trigger?(Input::B) @command_window.commands=@choices @command_window.index=3 @custom=false return end if Input.trigger?(Input::C) $PokemonMap.whiteFluteUsed=false if $PokemonMap $PokemonMap.blackFluteUsed=false if $PokemonMap if @command_window.index==0 $game_system.setDefaultBGM(nil) else $game_system.setDefaultBGM( @command_window.commands[@command_window.index] ) end end end def update_command # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to map screen $scene = Scene_Pokegear.new return end # If C button was pressed if Input.trigger?(Input::C) # Branch by command window cursor position case @command_window.index when 0 $game_system.se_play($data_system.decision_se) $game_system.bgm_play(RPG::AudioFile.new("Radio - March", 100, 100)) $PokemonMap.whiteFluteUsed=true if $PokemonMap $PokemonMap.blackFluteUsed=false if $PokemonMap when 1 $game_system.se_play($data_system.decision_se) $game_system.bgm_play(RPG::AudioFile.new("Radio - Lullaby", 100, 100)) $PokemonMap.blackFluteUsed=true if $PokemonMap $PokemonMap.whiteFluteUsed=false if $PokemonMap when 2 $game_system.se_play($data_system.decision_se) $game_system.bgm_play(RPG::AudioFile.new("Radio - Oak", 100, 100)) $PokemonMap.whiteFluteUsed=false if $PokemonMap $PokemonMap.blackFluteUsed=false if $PokemonMap when 3 files=[_INTL("(Default)")] Dir.chdir("Audio/BGM/"){ Dir.glob("*.mp3"){|f| files.push(f) } Dir.glob("*.MP3"){|f| files.push(f) } Dir.glob("*.mid"){|f| files.push(f) } Dir.glob("*.MID"){|f| files.push(f) } } @command_window.commands=files @command_window.index=0 @custom=true when 4 $game_system.se_play($data_system.decision_se) $scene = Scene_Pokegear.new end return end end end[/CODE] [CODE]class Game_Player def fullPattern case self.direction when 2 return self.pattern when 4 return 4+self.pattern when 6 return 8+self.pattern when 8 return 12+self.pattern else return 0 end end def setDefaultCharName(chname,pattern) return if pattern<0||pattern>=16 @defaultCharacterName=chname @direction=[2,4,6,8][pattern/4] @pattern=pattern%4 end def pbCanRun? return Input.press?(Input::A) && $PokemonGlobal.runningShoes && ( pbGetMetadata($game_map.map_id,MetadataOutdoor) || ($PokemonEncounters && $PokemonEncounters.isCave?) ) end def character_name if !@defaultCharacterName @defaultCharacterName="" end if @defaultCharacterName!="" return @defaultCharacterName end if !$game_system.map_interpreter.running? && !moving? && !@move_route_forcing && $PokemonGlobal meta=pbGetMetadata(0,MetadataPlayerA+$PokemonGlobal.playerID) if $PokemonGlobal.playerID>=0 && meta && !$PokemonGlobal.bicycle && !$PokemonGlobal.diving && !$PokemonGlobal.surfing if meta[5] && meta[5]!="" && Input.dir4!=0 && pbCanRun? # Display running character sprite @character_name=meta[5] else # Display normal character sprite @character_name=meta[1] end end end return @character_name end alias update_old update def update if !$game_system.map_interpreter.running? && !moving? && !@move_route_forcing && $PokemonGlobal if $PokemonGlobal.bicycle @move_speed = 5.2 elsif pbCanRun? @move_speed = 4.8 else @move_speed = 3.8 end end update_old end end class Game_Character alias update_old2 update def update if self.is_a?(Game_Event) if @dependentEvents for i in 0...@dependentEvents.length if @dependentEvents[i][0]==$game_map.map_id && @dependentEvents[i][1]==self.id && @move_speed=$game_player.move_speed break end end end end update_old2 end end[/CODE] [CODE]#============================================================================== # ** Map Autoscroll #------------------------------------------------------------------------------ # Wachunga # Version 1.02 # 2005-12-18 #============================================================================== =begin This script supplements the built-in "Scroll Map" event command with the aim of simplifying cutscenes (and map scrolling in general). Whereas the normal event command requires a direction and number of tiles to scroll, Map Autoscroll scrolls the map to center on the tile whose x and y coordinates are given. FEATURES - automatic map scrolling to given x,y coordinate (or player) - destination is fixed, so it's possible to scroll to same place even if origin is variable (e.g. moving NPC) - variable speed (just like "Scroll Map" event command) - diagonal scrolling supported SETUP Instead of a "Scroll Map" event command, use the "Call Script" command and enter on the following on the first line: autoscroll(x,y) (replacing "x" and "y" with the x and y coordinates of the tile to scroll to) To specify a scroll speed other than the default (4), use: autoscroll(x,y,speed) (now also replacing "speed" with the scroll speed from 1-6) Diagonal scrolling happens automatically when the destination is diagonal relative to the starting point (i.e., not directly up, down, left or right). To scroll to the player, instead use the following: autoscroll_player(speed) Note: because of how the interpreter and the "Call Script" event command are setup, the call to autoscroll(...) can only be on the first line of the "Call Script" event command (and not flowing down to subsequent lines). For example, the following call may not work as expected: autoscroll($game_variables[1], $game_variables[2]) (since the long argument names require dropping down to a second line) A work-around is to setup new variables with shorter names in a preceding (separate) "Call Script" event command: @x = $game_variables[1] @y = $game_variables[2] and then use those as arguments: autoscroll(@x,@y) The renaming must be in a separate "Call Script" because otherwise the call to autoscroll(...) isn't on the first line. Originally requested by militantmilo80: http://www.rmxp.net/forums/index.php?showtopic=29519 =end class Interpreter SCROLL_SPEED_DEFAULT = 4 #-------------------------------------------------------------------------- # * Map Autoscroll to Coordinates # x : x coordinate to scroll to and center on # y : y coordinate to scroll to and center on # speed : (optional) scroll speed (from 1-6, default being 4) #-------------------------------------------------------------------------- def autoscroll(x,y,speed=SCROLL_SPEED_DEFAULT) if $game_map.scrolling? return false elsif not $game_map.valid?(x,y) print 'Map Autoscroll: given x,y is invalid' return command_skip elsif not (1..6).include?(speed) print 'Map Autoscroll: invalid speed (1-6 only)' return command_skip end center_x = (Graphics.width/2 - Game_Map::TILEWIDTH/2) * 4 # X coordinate in the center of the screen center_y = (Graphics.height/2 - Game_Map::TILEHEIGHT/2) * 4 # Y coordinate in the center of the screen max_x = ($game_map.width - Graphics.width*1.0/Game_Map::TILEWIDTH) * 4 * Game_Map::TILEWIDTH max_y = ($game_map.height - Graphics.height*1.0/Game_Map::TILEHEIGHT) * 4 * Game_Map::TILEHEIGHT count_x = ($game_map.display_x - [0,[x*Game_Map.realResX-center_x,max_x].min].max)/Game_Map.realResX count_y = ($game_map.display_y - [0,[y*Game_Map.realResY-center_y,max_y].min].max)/Game_Map.realResY if not @diag @diag = true dir = nil if count_x > 0 if count_y > 0 dir = 7 elsif count_y < 0 dir = 1 end elsif count_x < 0 if count_y > 0 dir = 9 elsif count_y < 0 dir = 3 end end count = [count_x.abs,count_y.abs].min else @diag = false dir = nil if count_x != 0 and count_y != 0 return false elsif count_x > 0 dir = 4 elsif count_x < 0 dir = 6 elsif count_y > 0 dir = 8 elsif count_y < 0 dir = 2 end count = count_x != 0 ? count_x.abs : count_y.abs end $game_map.start_scroll(dir, count, speed) if dir != nil if @diag return false else return true end end #-------------------------------------------------------------------------- # * Map Autoscroll (to Player) # speed : (optional) scroll speed (from 1-6, default being 4) #-------------------------------------------------------------------------- def autoscroll_player(speed=SCROLL_SPEED_DEFAULT) autoscroll($game_player.x,$game_player.y,speed) end end #------------------------------------------------------------------------------ class Game_Map def scroll_downright(distance) @display_x = [@display_x + distance, (self.width - Graphics.width*1.0/Game_Map::TILEWIDTH) * Game_Map.realResX].min @display_y = [@display_y + distance, (self.height - Graphics.height*1.0/Game_Map::TILEHEIGHT) * Game_Map.realResY].min end def scroll_downleft(distance) @display_x = [@display_x - distance, 0].max @display_y = [@display_y + distance, (self.height - Graphics.height*1.0/Game_Map::TILEHEIGHT) * Game_Map.realResY].min end def scroll_upright(distance) @display_x = [@display_x + distance, (self.width - Graphics.width*1.0/Game_Map::TILEWIDTH) * Game_Map.realResX].min @display_y = [@display_y - distance, 0].max end def scroll_upleft(distance) @display_x = [@display_x - distance, 0].max @display_y = [@display_y - distance, 0].max end def update_scrolling # If scrolling if @scroll_rest > 0 # Change from scroll speed to distance in map coordinates distance = 2 ** @scroll_speed # Execute scrolling case @scroll_direction #------------------------------------------------------------------------------ # Begin Map Autoscroll Edit #------------------------------------------------------------------------------ when 1 # down left scroll_downleft(distance) #------------------------------------------------------------------------------ # End Map Autoscroll Edit #------------------------------------------------------------------------------ when 2 # Down scroll_down(distance) #------------------------------------------------------------------------------ # Begin Map Autoscroll Edit #------------------------------------------------------------------------------ when 3 # down right scroll_downright(distance) #------------------------------------------------------------------------------ # End Map Autoscroll Edit #------------------------------------------------------------------------------ when 4 # Left scroll_left(distance) when 6 # Right scroll_right(distance) #------------------------------------------------------------------------------ # Begin Map Autoscroll Edit #------------------------------------------------------------------------------ when 7 # up left scroll_upleft(distance) #------------------------------------------------------------------------------ # End Map Autoscroll Edit #------------------------------------------------------------------------------ when 8 # Up scroll_up(distance) #------------------------------------------------------------------------------ # Begin Map Autoscroll Edit #------------------------------------------------------------------------------ when 9 # up right scroll_upright(distance) #------------------------------------------------------------------------------ # End Map Autoscroll Edit #------------------------------------------------------------------------------ end # Subtract distance scrolled @scroll_rest -= distance end end end[/CODE] [CODE]class Game_System attr_reader :map_interpreter # map event interpreter attr_reader :battle_interpreter # battle event interpreter attr_accessor :timer # timer attr_accessor :timer_working # timer working flag attr_accessor :save_disabled # save forbidden attr_accessor :menu_disabled # menu forbidden attr_accessor :encounter_disabled # encounter forbidden attr_accessor :message_position # text option: positioning attr_accessor :message_frame # text option: window frame attr_accessor :save_count # save count attr_accessor :magic_number # magic number attr_accessor :autoscroll_x_speed attr_accessor :autoscroll_y_speed attr_accessor :bgm_position def initialize @map_interpreter = Interpreter.new(0, true) @battle_interpreter = Interpreter.new(0, false) @timer = 0 @timer_working = false @save_disabled = false @menu_disabled = false @encounter_disabled = false @message_position = 2 @message_frame = 0 @save_count = 0 @magic_number = 0 @autoscroll_x_speed = 0 @autoscroll_y_speed = 0 end def audioBgmPlay(str,vol,pitch,position) Audio.bgm_play(str,vol,pitch,position) end def audioBgmFade(time) Audio.bgm_fade(time) end def audioBgmStop Audio.bgm_stop end def bgm_play_ex(bgm,volume,pitch,setplaying,position=0) if bgm.is_a?(String) bgm=RPG::AudioFile.new(bgm,volume,pitch) end if setplaying @playing_bgm = bgm==nil ? nil : bgm.clone end if bgm != nil and bgm.name != "" unless FileTest.audio_exist?("Audio/BGM/"+ bgm.name) if $DEBUG print "BGM File not found, game will continue playing.\\nFile : " + bgm.name end else audioBgmPlay("Audio/BGM/" + bgm.name, bgm.volume, bgm.pitch,position) if !@defaultBGM end else audioBgmStop if !@defaultBGM end if @defaultBGM audioBgmPlay("Audio/BGM/"+@defaultBGM.name, @defaultBGM.volume,@defaultBGM.pitch,position) end Graphics.frame_reset end def bgm_play(bgm,volume=100,pitch=100,position=0) bgm_play_ex(bgm,volume,pitch,true,position) end def bgm_pause; end def bgs_pause; end def bgm_resume(bgm,volume=100,pitch=100); end def bgs_resume(bgm,volume=100,pitch=100); end def bgm_stop @bgm_position=0 @playing_bgm = nil audioBgmStop if !@defaultBGM end def bgm_fade(time) @playing_bgm = nil audioBgmFade((time * 1000).floor) if !@defaultBGM end def getPlayingBGM return @playing_bgm ? @playing_bgm.clone : nil end def bgm_memorize @memorized_bgm = @playing_bgm end def bgm_restore bgm_play(@memorized_bgm) end def bgs_play(bgs,volume=100,pitch=100) if bgs.is_a?(String) bgs=RPG::AudioFile.new(bgs,volume,pitch) end @playing_bgs = bgs==nil ? nil : bgs.clone if bgs != nil and bgs.name != "" unless FileTest.audio_exist?("Audio/BGS/"+ bgs.name) if $DEBUG print "BGS File not found, game will continue playing. \\nFile : " + bgs.name end else Audio.bgs_play("Audio/BGS/" + bgs.name, bgs.volume, bgs.pitch) end else Audio.bgs_stop end Graphics.frame_reset end def bgs_fade(time) @playing_bgs = nil Audio.bgs_fade(time * 1000) end def bgs_stop @bgs_position=0 @playing_bgs = nil Audio.bgs_stop end def getPlayingBGS return @playing_bgs ? @playing_bgs.clone : nil end def bgs_memorize @memorized_bgs = @playing_bgs end def bgs_restore bgs_play(@memorized_bgs) end def setDefaultBGM(bgm,volume=100,pitch=100) if bgm.is_a?(String) bgm=RPG::AudioFile.new(bgm,volume,pitch) end if bgm != nil and bgm.name != "" @defaultBGM=bgm==nil ? nil : bgm.clone Audio.bgm_play("Audio/BGM/"+bgm.name) else @defaultBGM=nil self.bgm_play(@playing_bgm) end end def me_play(me) if me.is_a?(String) me=RPG::AudioFile.new(me) end if me != nil and me.name != "" unless FileTest.audio_exist?("Audio/ME/"+me.name) if $DEBUG print "ME File not found, game will continue playing. \\nFile : " + me.name end else Audio.me_play("Audio/ME/" + me.name, me.volume, me.pitch) end else Audio.me_stop end Graphics.frame_reset end def se_play(se) if se.is_a?(String) se=RPG::AudioFile.new(se) end if se != nil and se.name != "" unless FileTest.audio_exist?("Audio/SE/"+ se.name) if $DEBUG print "SE File not found, game will continue playing. \\nFile : " + se.name end else Audio.se_play("Audio/SE/" + se.name, se.volume, se.pitch) end end end def se_stop Audio.se_stop end def playing_bgm return @playing_bgm end def playing_bgs return @playing_bgs end def windowskin_name if @windowskin_name == nil return $data_system.windowskin_name else return @windowskin_name end end def windowskin_name=(windowskin_name) @windowskin_name = windowskin_name end def battle_bgm if @battle_bgm == nil return $data_system.battle_bgm else return @battle_bgm end end def battle_bgm=(battle_bgm) @battle_bgm = battle_bgm end def battle_end_me if @battle_end_me == nil return $data_system.battle_end_me else return @battle_end_me end end def battle_end_me=(battle_end_me) @battle_end_me = battle_end_me end def update if @timer_working and @timer > 0 @timer -= 1 end $game_temp.updateDayNightTone if pbCurrentEventCommentInput(1,"Cut Scene") && Input.trigger?(Input::F5) event=@map_interpreter.get_character(0) @map_interpreter.pbSetSelfSwitch(event.id,"A",true) @map_interpreter.command_end event.start end end end class Game_Temp def dayNightTone if !@dayNightTone @dayNightTone=Tone.new(0,0,0) @dayNightToneNeedUpdate=true end if @dayNightToneNeedUpdate pbSetDayNightTone(@dayNightTone) @dayNightToneNeedUpdate=false end return @dayNightTone end def updateDayNightTone @dayNightToneNeedUpdate=true end end [/CODE] [CODE]=begin A sprite whose sole purpose is to display an animation. This sprite can be displayed anywhere on the map and is disposed automatically when its animation is finished. =end class AnimationSprite < RPG::Sprite def initialize(animID,map,tileX,tileY,viewport=nil) super(viewport) @tileX=tileX @tileY=tileY self.bitmap=Bitmap.new(1,1) self.bitmap.clear @map=map self.x=((@tileX*Game_Map.realResX)-@map.display_x+3)/4+(Game_Map::TILEWIDTH/2) self.y=((@tileY*Game_Map.realResY)-@map.display_y+3)/4+(Game_Map::TILEHEIGHT) self.animation($data_animations[animID],true) end def dispose self.bitmap.dispose super end def update if !self.disposed? self.x=((@tileX*Game_Map.realResX)-@map.display_x+3)/4+(Game_Map::TILEWIDTH/2) self.y=((@tileY*Game_Map.realResY)-@map.display_y+3)/4+(Game_Map::TILEHEIGHT) super self.dispose if !self.effect? end end end =begin Modifying Spriteset_Map =end def pbDayNightTint(object) if !$scene.is_a?(Scene_Map) return else if $game_map && pbGetMetadata($game_map.map_id,1) tone=$game_temp.dayNightTone object.tone.set(tone.red,tone.green,tone.blue,tone.gray) else object.tone.set(0,0,0,0) end end end class Spriteset_Map alias _animationSprite_initialize initialize alias _animationSprite_update update alias _animationSprite_dispose dispose def initialize(map=nil) @usersprites=[] _animationSprite_initialize(map) end def addUserAnimation(animID,x,y) viewport=Viewport.new(0,0,Graphics.width,Graphics.height) viewport.z=99999 sprite=AnimationSprite.new(animID,$game_map,x,y,viewport) addUserSprite(sprite) return sprite end def addUserSprite(sprite) for i in 0...@usersprites.length if @usersprites[i]==nil || @usersprites[i].disposed? @usersprites[i]=sprite return end end @usersprites.push(sprite) end def dispose _animationSprite_dispose for i in 0...@usersprites.length @usersprites[i].dispose end @usersprites.clear end def update return if @tilemap.disposed? if $PokemonSystem.tilemap==0 if self.map==$game_map pbDayNightTint(@viewport3) else @viewport3.tone.set(0,0,0,0) end else pbDayNightTint(@tilemap) @viewport3.tone.set(0,0,0,0) end _animationSprite_update for i in 0...@usersprites.length @usersprites[i].update if !@usersprites[i].disposed? end end end [/CODE] [CODE]module Console attr_reader :bufferHandle GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 FILE_SHARE_READ = 0x00000001 FILE_SHARE_WRITE = 0x00000002 CONSOLE_TEXTMODE_BUFFER = 0x00000001 def Console::AllocConsole return @apiAllocConsole.call end def Console::CreateConsoleScreenBuffer(dwDesiredAccess,dwShareMode,dwFlags) return @apiCreateConsoleScreenBuffer.call(dwDesiredAccess,dwShareMode,nil,dwFlags,nil) end def Console::WriteConsole(lpBuffer) hFile = @bufferHandle return if !hFile return @apiWriteConsole.call(hFile,lpBuffer,lpBuffer.size,0,0) end def Console::ReadConsole(lpBuffer) hFile = @bufferHandle return @apiReadConsole.call(hFile,lpBuffer,lpBuffer.size,0,0) end def Console::SetConsoleActiveScreenBuffer(hScreenBuffer) return @apiSetConsoleActiveScreenBuffer.call(hScreenBuffer) end def Console::SetConsoleScreenBufferSize(hScreenBuffer,x,y) return @apiSetConsoleScreenBufferSize.call(hScreenBuffer,[x,y].pack("vv")) end def Console::SetConsoleTitle(title) return @apiSetConsoleTitle.call(title) end def self.setup_console unless $DEBUG return end @apiAllocConsole = Win32API.new("kernel32","AllocConsole","","l") @apiCreateConsoleScreenBuffer = Win32API.new("kernel32","CreateConsoleScreenBuffer","nnpnp","l") @apiSetConsoleActiveScreenBuffer = Win32API.new("kernel32","SetConsoleActiveScreenBuffer","l","s") @apiWriteConsole = Win32API.new("kernel32","WriteConsole","lpnnn","S") @apiReadConsole = Win32API.new("kernel32","ReadConsole","lpnnn","S") @apiSetConsoleScreenBufferSize = Win32API.new("kernel32","SetConsoleScreenBufferSize","lp","S") @apiSetConsoleTitle = Win32API.new("kernel32","SetConsoleTitle","p","s") access = (GENERIC_READ | GENERIC_WRITE) sharemode = (FILE_SHARE_READ | FILE_SHARE_WRITE) returnCode = AllocConsole() @bufferHandle = CreateConsoleScreenBuffer(access,sharemode,CONSOLE_TEXTMODE_BUFFER) f = File.open("Game.ini") lines = f.readlines() s = lines[3] len = s.size title = (s[6,len - 7]) SetConsoleScreenBufferSize(@bufferHandle,100,2000) SetConsoleTitle("Debug Console -- #{title}") echo "#{title} Output Window\\n" echo "-------------------------------\\n" echo "If you are seeing this window, you are running\\n" echo "#{title} in Debug Mode. This means\\n" echo "that you're either playing a Debug Version, or\\n" echo "you are playing from within RPG Maker XP.\\n" echo "\\n" echo "Closing this window will close the game. If \\n" echo "you want to get rid of this window, run the\\n" echo "program from the Shell, or download a Release\\n" echo "version.\\n" echo "\\n" echo "Gameplay will be paused while the console has\\n" echo "focus. To resume playing, switch to the Game\\n" echo "Window.\\n" echo "-------------------------------\\n" echo "Debug Output:\\n" echo "-------------------------------\\n\\n" SetConsoleActiveScreenBuffer(@bufferHandle) end def self.readInput length=20 buffer=0.chr*length eventsread=0.chr*4 done=false input="" while !done echo("waiting for input") begin @apiReadConsole.call(@bufferHandle,buffer,1,eventsread) rescue Hangup return end offset=0 events=eventsread.unpack("V") echo("got input [eventsread #{events}") for i in 0...events[0] keyevent=buffer[offset,20] keyevent=keyevent.unpack("vCvvvvV") if keyevent[0]==1 && keyevent[1]>0 input+=keyevent[4].chr if keyevent[4].chr=="\\n" done=true break end end offset+=20 end end return input end def self.readInput2 buffer=0.chr done=false input="" eventsread=0.chr*4 while !done if ReadConsole(buffer)==0 getlast = Win32API.new("kernel32","GetLastError","","n") echo(sprintf("failed (%d)\\r\\n",getlast.call())) break end offset=0 events=eventsread.unpack("V") if events[0]>0 echo("got input [eventsread #{events}][buffer #{buffer}]\\r\\n") key=buffer[0,events[0]] input+=key if key=="\\n" break end Graphics.update end end return input end def self.get_input echo self.readInput2 end end module Kernel def echo(string) unless $DEBUG return end Console::WriteConsole(string.is_a?(String) ? string : string.inspect) end def echoln(string) echo(string) echo("\\r\\n") end end[/CODE] [CODE] module Win32 #-------------------------------------------------------------------------- # ● Retrieves data from a pointer. #-------------------------------------------------------------------------- def copymem(len) buf = "\\0" * len Win32API.new("kernel32", "RtlMoveMemory", "ppl", "").call(buf, self, len) buf end end # Extends the numeric class. class Numeric include Win32 end # Extends the string class. class String include Win32 end #============================================================================== #End #============================================================================== #=============================================================================== # ** Module Winsock - Maps out the functions held in the Winsock DLL. #------------------------------------------------------------------------------- # Author Ruby # Version 1.8.1 #=============================================================================== #------------------------------------------------------------------------------- # Begin SDK Enabled Check #------------------------------------------------------------------------------- module Winsock DLL = "ws2_32" #-------------------------------------------------------------------------- # * Accept Connection #-------------------------------------------------------------------------- def self.accept(*args) Win32API.new(DLL, "accept", "ppl", "l").call(*args) end #-------------------------------------------------------------------------- # * Bind #-------------------------------------------------------------------------- def self.bind(*args) Win32API.new(DLL, "bind", "ppl", "l").call(*args) end #-------------------------------------------------------------------------- # * Close Socket #-------------------------------------------------------------------------- def self.closesocket(*args) Win32API.new(DLL, "closesocket", "p", "l").call(*args) end #-------------------------------------------------------------------------- # * Connect #-------------------------------------------------------------------------- def self.connect(*args) Win32API.new(DLL, "connect", "ppl", "l").call(*args) end #-------------------------------------------------------------------------- # * Get host (Using Adress) #-------------------------------------------------------------------------- def self.gethostbyaddr(*args) Win32API.new(DLL, "gethostbyaddr", "pll", "l").call(*args) end #-------------------------------------------------------------------------- # * Get host (Using Name) #-------------------------------------------------------------------------- def self.gethostbyname(*args) Win32API.new(DLL, "gethostbyname", "p", "l").call(*args) end #-------------------------------------------------------------------------- # * Get host's Name #-------------------------------------------------------------------------- def self.gethostname(*args) Win32API.new(DLL, "gethostname", "pl", "").call(*args) end #-------------------------------------------------------------------------- # * Get Server (Using Name) #-------------------------------------------------------------------------- def self.getservbyname(*args) Win32API.new(DLL, "getservbyname", "pp", "p").call(*args) end #-------------------------------------------------------------------------- # * Convert Host Long To Network Long #-------------------------------------------------------------------------- def self.htonl(*args) Win32API.new(DLL, "htonl", "l", "l").call(*args) end #-------------------------------------------------------------------------- # * Convert Host Short To Network Short #-------------------------------------------------------------------------- def self.htons(*args) Win32API.new(DLL, "htons", "l", "l").call(*args) end #-------------------------------------------------------------------------- # * Inet Adress #-------------------------------------------------------------------------- def self.inet_addr(*args) Win32API.new(DLL, "inet_addr", "p", "l").call(*args) end #-------------------------------------------------------------------------- # * Inet N To A #-------------------------------------------------------------------------- def self.inet_ntoa(*args) Win32API.new(DLL, "inet_ntoa", "l", "p").call(*args) end #-------------------------------------------------------------------------- # * Listen #-------------------------------------------------------------------------- def self.listen(*args) Win32API.new(DLL, "listen", "pl", "l").call(*args) end #-------------------------------------------------------------------------- # * Recieve #-------------------------------------------------------------------------- def self.recv(*args) Win32API.new(DLL, "recv", "ppll", "l").call(*args) end #-------------------------------------------------------------------------- # * Select #-------------------------------------------------------------------------- def self.select(*args) Win32API.new(DLL, "select", "lpppp", "l").call(*args) end #-------------------------------------------------------------------------- # * Send #-------------------------------------------------------------------------- def self.send(*args) Win32API.new(DLL, "send", "ppll", "l").call(*args) end #-------------------------------------------------------------------------- # * Set Socket Options #-------------------------------------------------------------------------- def self.setsockopt(*args) Win32API.new(DLL, "setsockopt", "pllpl", "l").call(*args) end #-------------------------------------------------------------------------- # * Shutdown #-------------------------------------------------------------------------- def self.shutdown(*args) Win32API.new(DLL, "shutdown", "pl", "l").call(*args) end #-------------------------------------------------------------------------- # * Socket #-------------------------------------------------------------------------- def self.socket(*args) Win32API.new(DLL, "socket", "lll", "l").call(*args) end #-------------------------------------------------------------------------- # * Get Last Error #-------------------------------------------------------------------------- def self.WSAGetLastError(*args) Win32API.new(DLL, "WSAGetLastError", "", "l").call(*args) end end #=============================================================================== # ** Socket - Creates and manages sockets. #------------------------------------------------------------------------------- # Author Ruby # Version 1.8.1 #=============================================================================== class Socket #-------------------------------------------------------------------------- # ● Constants #-------------------------------------------------------------------------- AF_UNSPEC = 0 AF_UNIX = 1 AF_INET = 2 AF_IPX = 6 AF_APPLETALK = 16 PF_UNSPEC = 0 PF_UNIX = 1 PF_INET = 2 PF_IPX = 6 PF_APPLETALK = 16 SOCK_STREAM = 1 SOCK_DGRAM = 2 SOCK_RAW = 3 SOCK_RDM = 4 SOCK_SEQPACKET = 5 IPPROTO_IP = 0 IPPROTO_ICMP = 1 IPPROTO_IGMP = 2 IPPROTO_GGP = 3 IPPROTO_TCP = 6 IPPROTO_PUP = 12 IPPROTO_UDP = 17 IPPROTO_IDP = 22 IPPROTO_ND = 77 IPPROTO_RAW = 255 IPPROTO_MAX = 256 SOL_SOCKET = 65535 SO_DEBUG = 1 SO_REUSEADDR = 4 SO_KEEPALIVE = 8 SO_DONTROUTE = 16 SO_BROADCAST = 32 SO_LINGER = 128 SO_OOBINLINE = 256 SO_RCVLOWAT = 4100 SO_SNDTIMEO = 4101 SO_RCVTIMEO = 4102 SO_ERROR = 4103 SO_TYPE = 4104 SO_SNDBUF = 4097 SO_RCVBUF = 4098 SO_SNDLOWAT = 4099 TCP_NODELAY = 1 MSG_OOB = 1 MSG_PEEK = 2 MSG_DONTROUTE = 4 IP_OPTIONS = 1 IP_DEFAULT_MULTICAST_LOOP = 1 IP_DEFAULT_MULTICAST_TTL = 1 IP_MULTICAST_IF = 2 IP_MULTICAST_TTL = 3 IP_MULTICAST_LOOP = 4 IP_ADD_MEMBERSHIP = 5 IP_DROP_MEMBERSHIP = 6 IP_TTL = 7 IP_TOS = 8 IP_MAX_MEMBERSHIPS = 20 EAI_ADDRFAMILY = 1 EAI_AGAIN = 2 EAI_BADFLAGS = 3 EAI_FAIL = 4 EAI_FAMILY = 5 EAI_MEMORY = 6 EAI_NODATA = 7 EAI_NONAME = 8 EAI_SERVICE = 9 EAI_SOCKTYPE = 10 EAI_SYSTEM = 11 EAI_BADHINTS = 12 EAI_PROTOCOL = 13 EAI_MAX = 14 AI_PASSIVE = 1 AI_CANONNAME = 2 AI_NUMERICHOST = 4 AI_MASK = 7 AI_ALL = 256 AI_V4MAPPED_CFG = 512 AI_ADDRCONFIG = 1024 AI_DEFAULT = 1536 AI_V4MAPPED = 2048 #-------------------------------------------------------------------------- # ● Returns the associated IP address for the given hostname. #-------------------------------------------------------------------------- def self.getaddress(host) gethostbyname(host)[3].unpack("C4").join(".") end #-------------------------------------------------------------------------- # ● Returns the associated IP address for the given hostname. #-------------------------------------------------------------------------- def self.getservice(serv) case serv when Numeric return serv when String return getservbyname(serv) else raise "Please use an integer or string for services." end end #-------------------------------------------------------------------------- # ● Returns information about the given hostname. #-------------------------------------------------------------------------- def self.gethostbyname(name) raise SocketError::ENOASSOCHOST if (ptr = Winsock.gethostbyname(name)) == 0 host = ptr.copymem(16).unpack("iissi") [host[0].copymem(64).split("\\0")[0], [], host[2], host[4].copymem(4).unpack("l")[0].copymem(4)] end #-------------------------------------------------------------------------- # ● Returns the user's hostname. #-------------------------------------------------------------------------- def self.gethostname buf = "\\0" * 256 Winsock.gethostname(buf, 256) buf.strip end #-------------------------------------------------------------------------- # ● Returns information about the given service. #-------------------------------------------------------------------------- def self.getservbyname(name) case name when /echo/i return 7 when /daytime/i return 13 when /ftp/i return 21 when /telnet/i return 23 when /smtp/i return 25 when /time/i return 37 when /http/i return 80 when /pop/i return 110 else Network.testing? != 0 ? (Network.testresult(true)) : (raise "Service not recognized.") return if Network.testing? == 2 end end #-------------------------------------------------------------------------- # ● Creates an INET-sockaddr struct. #-------------------------------------------------------------------------- def self.sockaddr_in(port, host) begin [AF_INET, getservice(port)].pack("sn") + gethostbyname(host)[3] + [].pack("x8") rescue Network.testing? != 0 ? (Network.testresult(true)): (nil) return if Network.testing? == 2 rescue Hangup Network.testing? != 0 ? (Network.testresult(true)): (nil) return if Network.testing? == 2 end end #-------------------------------------------------------------------------- # ● Creates a new socket and connects it to the given host and port. #-------------------------------------------------------------------------- def self.open(*args) socket = new(*args) if block_given? begin yield socket ensure socket.close end end nil end #-------------------------------------------------------------------------- # ● Creates a new socket. #-------------------------------------------------------------------------- def initialize(domain, type, protocol) SocketError.check if (@fd = Winsock.socket(domain, type, protocol)) == -1 @fd end #-------------------------------------------------------------------------- # ● Accepts incoming connections. #-------------------------------------------------------------------------- def accept(flags = 0) buf = "\\0" * 16 SocketError.check if Winsock.accept(@fd, buf, flags) == -1 buf end #-------------------------------------------------------------------------- # ● Binds a socket to the given sockaddr. #-------------------------------------------------------------------------- def bind(sockaddr) SocketError.check if (ret = Winsock.bind(@fd, sockaddr, sockaddr.size)) == -1 ret end #-------------------------------------------------------------------------- # ● Closes a socket. #-------------------------------------------------------------------------- def close SocketError.check if (ret = Winsock.closesocket(@fd)) == -1 ret end #-------------------------------------------------------------------------- # ● Connects a socket to the given sockaddr. #-------------------------------------------------------------------------- def connect(sockaddr) return if Network.testing? == 2 SocketError.check if (ret = Winsock.connect(@fd, sockaddr, sockaddr.size)) == -1 ret end #-------------------------------------------------------------------------- # ● Listens for incoming connections. #-------------------------------------------------------------------------- def listen(backlog) SocketError.check if (ret = Winsock.listen(@fd, backlog)) == -1 ret end #-------------------------------------------------------------------------- # ● Checks waiting data's status. #-------------------------------------------------------------------------- def select(timeout) SocketError.check if (ret = Winsock.select(1, [1, @fd].pack("ll"), 0, 0, [timeout, timeout * 1000000].pack("ll"))) == -1 ret end #-------------------------------------------------------------------------- # ● Checks if data is waiting. #-------------------------------------------------------------------------- def ready? not select(0) == 0 end #-------------------------------------------------------------------------- # ● Reads data from socket. #-------------------------------------------------------------------------- def read(len) buf = "\\0" * len Win32API.new("msvcrt", "_read", "lpl", "l").call(@fd, buf, len) buf end #-------------------------------------------------------------------------- # ● Returns received data. #-------------------------------------------------------------------------- def recv(len, flags = 0) retString="" remainLen=len while remainLen > 0 buf = "\\0" * remainLen retval=Winsock.recv(@fd, buf, buf.size, flags) SocketError.check if retval == -1 # Note: Return value may not equal requested length remainLen-=retval retString+=buf[0,retval] end return retString end #-------------------------------------------------------------------------- # ● Sends data to a host. #-------------------------------------------------------------------------- def send(data, flags = 0) SocketError.check if (ret = Winsock.send(@fd, data, data.size, flags)) == -1 ret end #-------------------------------------------------------------------------- # * Recieves file from a socket # size : file size # scene : update scene boolean #-------------------------------------------------------------------------- def recv_file(size,scene=false,file="") data = [] size.times do |i| if scene == true $scene.recv_update(size,i,file) if i%((size/1000)+1)== 0 else Graphics.update if i%1024 == 0 end data << recv(1) end return data end def recvTimeout if select(1000)==0 raise Hangup.new("Timeout") end return recv(1) end #-------------------------------------------------------------------------- # * Gets #-------------------------------------------------------------------------- def gets # Create buffer message = "" # Loop Until "end of line" while (char = recv(1)) != "\\n" message += char end # Return recieved data return message end #-------------------------------------------------------------------------- # ● Writes data to socket. #-------------------------------------------------------------------------- def write(data) Win32API.new("msvcrt", "_write", "lpl", "l").call(@fd, data, 1) end end #------------------------------------------------------------------------------- # End SDK Enabled Test #------------------------------------------------------------------------------- #=============================================================================== # ** TCPSocket - Creates and manages TCP sockets. #------------------------------------------------------------------------------- # Author Ruby # Version 1.8.1 #=============================================================================== #------------------------------------------------------------------------------- # Begin SDK Enabled Check #------------------------------------------------------------------------------- class TCPSocket < Socket #-------------------------------------------------------------------------- # ● Creates a new socket and connects it to the given host and port. #-------------------------------------------------------------------------- def self.open(*args) socket = new(*args) if block_given? begin yield socket ensure socket.close end end nil end #-------------------------------------------------------------------------- # ● Creates a new socket and connects it to the given host and port. #-------------------------------------------------------------------------- def initialize(host, port) super(AF_INET, SOCK_STREAM, IPPROTO_TCP) connect(Socket.sockaddr_in(port, host)) end end #============================================================================== # ■ SocketError #------------------------------------------------------------------------------ # Default exception class for sockets. #============================================================================== class SocketError < StandardError ENOASSOCHOST = "getaddrinfo: no address associated with hostname." def self.check errno = Winsock.WSAGetLastError if not Network.testing? == 1 raise Errno.const_get(Errno.constants.detect { |c| Errno.const_get(c).new.errno == errno }) else errno != 0 ? (Network.testresult(true)) : (Network.testresult(false)) end end end [/CODE] [CODE]# Particle Engine, Peter O., 2007-11-03 # Based on version 2 by Near Fantastica, 04.01.06 # In turn based on the Particle Engine designed by PinkMan class Particle_Engine #-------------------------------------------------------------------------- def initialize(viewport=nil,map=nil) @map=map ? map : $game_map @viewport = viewport @effect = [] @disposed=false @firsttime=true @effects={ # PinkMan's Effects "fire"=>Particle_Engine::Fire, "smoke"=>Particle_Engine::Smoke, "teleport"=>Particle_Engine::Teleport, "spirit"=>Particle_Engine::Spirit, "explosion"=>Particle_Engine::Explosion, "aura"=>Particle_Engine::Aura, # BlueScope's Effects "soot"=>Particle_Engine::Soot, "sootsmoke"=>Particle_Engine::SootSmoke, "rocket"=>Particle_Engine::Rocket, "fixteleport"=>Particle_Engine::FixedTeleport, "smokescreen"=>Particle_Engine::Smokescreen, "flare"=>Particle_Engine::Flare, "splash"=>Particle_Engine::Splash, # By Peter O. "starteleport"=>Particle_Engine::StarTeleport } end def add_effect(event) @effect[event.id]=pbParticleEffect(event) end def realloc_effect(event,particle) type = pbEventCommentInput(event, 1, "Particle Engine Type") if type.nil? particle.dispose if particle return nil end type=type[0].downcase cls=@effects[type] if cls.nil? particle.dispose if particle return nil end if !particle || !particle.is_a?(cls) particle.dispose if particle particle=cls.new(event,@viewport) end return particle end def pbParticleEffect(event) return realloc_effect(event,nil) end def remove_effect(event) return if @effect[event.id].nil? @effect[event.id].dispose @effect.delete_at(event.id) end def update if @firsttime @firsttime=false for event in @map.events.values remove_effect(event) add_effect(event) end end for i in 0...@effect.length particle=@effect[i] next if particle.nil? if particle.event.pe_refresh event=particle.event event.pe_refresh=false particle=realloc_effect(event,particle) @effect[i]=particle end particle.update if particle end end def disposed? return @disposed end def dispose return if disposed? for particle in @effect next if particle.nil? particle.dispose end @effect.clear @map=nil @disposed=true end end class ParticleEffect attr_accessor :x,:y,:z def initialize @x=0 @y=0 @z=0 end def update end def dispose end end class ParticleSprite attr_accessor :x,:y,:z,:opacity,:bitmap,:blend_type def initialize(viewport) @viewport=viewport @sprite=nil @x=0 @y=0 @z=0 @opacity=255 @bitmap=nil @blend_type=0 @minleft=0 @mintop=0 end def bitmap=(value) @bitmap=value if value @minleft=-value.width @mintop=-value.height else @minleft=0 @mintop=0 end end def dispose @sprite.dispose if @sprite end def update w=Graphics.width h=Graphics.height if !@sprite && @x>=@minleft && @y>=@mintop && @x<w && @y<h @sprite=Sprite.new(@viewport) elsif @sprite && (@x<@minleft || @y<@mintop || @x>=w || @y>=h) @sprite.dispose @sprite=nil end if @sprite @sprite.x=@x if @sprite.x!=@x @sprite.y=@y if @sprite.y!=@y @sprite.z=@z if @sprite.z!=@z @sprite.opacity=@opacity if @sprite.opacity!=@opacity @sprite.blend_type=@blend_type if @sprite.blend_type!=@blend_type @sprite.bitmap=@bitmap if @sprite.bitmap!=@bitmap end end end class ParticleEffect_Event < ParticleEffect attr_accessor :event def initialize(event,viewport=nil) @event=event @viewport=viewport @particles=[] @bitmaps={} end def setParameters(params) @randomhue,@leftright,@fade, @maxparticless,@hue,@slowdown, @ytop,@ybottom,@xleft,@xright, @xgravity,@ygravity,@xoffset,@yoffset, @opacityvar,@originalopacity=params end def loadBitmap(filename,hue) key=[filename,hue] bitmap=@bitmaps[key] if !bitmap || bitmap.disposed? bitmap=BitmapCache.fog(filename,hue) @bitmaps[key]=bitmap end return bitmap end def initParticles(filename,opacity,zOffset=0,blendtype=1) @particles = [] @particlex = [] @particley = [] @opacity = [] @startingx = self.x + @xoffset @startingy = self.y + @yoffset @screen_x = self.x @screen_y = self.y @real_x = @event.real_x @real_y = @event.real_y @filename=filename @zoffset=zOffset @bmwidth=32 @bmheight=32 for i in 0...@maxparticless @particlex[i]=-@xoffset @particley[i]=-@yoffset @particles[i] = ParticleSprite.new(@viewport) @particles[i].bitmap = loadBitmap(filename, @hue) if filename if i==0 && @particles[i].bitmap @bmwidth=@particles[i].bitmap.width @bmheight=@particles[i].bitmap.height end @particles[i].blend_type = blendtype @particles[i].y = @startingy @particles[i].x = @startingx @particles[i].z = self.z+zOffset @opacity[i] = rand(opacity/4) @particles[i].opacity = @opacity[i] @particles[i].update end end def x return ScreenPosHelper.pbScreenX(@event) end def y return ScreenPosHelper.pbScreenY(@event) end def z return ScreenPosHelper.pbScreenZ(@event) end def update if @viewport && (@viewport.rect.x >= Graphics.width || @viewport.rect.y >= Graphics.height) return end selfX=self.x selfY=self.y selfZ=self.z newRealX=@event.real_x newRealY=@event.real_y @startingx = selfX + @xoffset @startingy = selfY + @yoffset @__offsetx=(@real_x==newRealX) ? 0 : selfX-@screen_x @__offsety=(@real_y==newRealY) ? 0 : selfY-@screen_y @screen_x = selfX @screen_y = selfY @real_x = newRealX @real_y = newRealY if @opacityvar>0 && @viewport opac=(255.0/@opacityvar) minX=opac*(-@xgravity*1.0 / @slowdown).floor + @startingx maxX=opac*(@xgravity*1.0 / @slowdown).floor + @startingx minY=opac*(-@ygravity*1.0 / @slowdown).floor + @startingy maxY=@startingy minX-=@bmwidth minY-=@bmheight maxX+=@bmwidth maxY+=@bmheight if maxX<0 || maxY<0 || minX>=Graphics.width || minY>=Graphics.height echo "skipped" return end end particleZ=selfZ+@zoffset for i in 0...@maxparticless @particles[i].z = particleZ if @particles[i].y <= @ytop @particles[i].y = @startingy + @yoffset @particles[i].x = @startingx + @xoffset @particlex[i]=0.0 @particley[i]=0.0 end if @particles[i].x <= @xleft @particles[i].y = @startingy + @yoffset @particles[i].x = @startingx + @xoffset @particlex[i]=0.0 @particley[i]=0.0 end if @particles[i].y >= @ybottom @particles[i].y = @startingy + @yoffset @particles[i].x = @startingx + @xoffset @particlex[i]=0.0 @particley[i]=0.0 end if @particles[i].x >= @xright @particles[i].y = @startingy + @yoffset @particles[i].x = @startingx + @xoffset @particlex[i]=0.0 @particley[i]=0.0 end if @fade == 0 if @opacity[i] <= 0 @opacity[i] = @originalopacity @particles[i].y = @startingy + @yoffset @particles[i].x = @startingx + @xoffset @particlex[i]=0.0 @particley[i]=0.0 end else if @opacity[i] <= 0 @opacity[i] = 250 @particles[i].y = @startingy + @yoffset @particles[i].x = @startingx + @xoffset @particlex[i]=0.0 @particley[i]=0.0 end end calcParticlePos(i) if @randomhue == 1 if @hue >= 360 @hue = 0 end @hue = @hue + 0.5 @particles[i].bitmap = loadBitmap(@filename, @hue) if @filename end @opacity[i] = @opacity[i] - rand(@opacityvar) @particles[i].opacity = @opacity[i] @particles[i].update end end def calcParticlePos(i) @leftright = rand(2) if @leftright == 1 xo=(-@xgravity*1.0 / @slowdown) else xo=(@xgravity*1.0 / @slowdown) end yo=(-@ygravity*1.0 / @slowdown) @particlex[i]+=xo @particley[i]+=yo @particlex[i]-=@__offsetx @particley[i]-=@__offsety @particlex[i]=@particlex[i].floor @particley[i]=@particley[i].floor @particles[i].x=@particlex[i]+@startingx+@xoffset @particles[i].y=@particley[i]+@startingy+@yoffset end def dispose for particle in @particles particle.dispose end for bitmap in @bitmaps.values bitmap.dispose end @particles.clear @bitmaps.clear end end class Particle_Engine::Fire < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,1,20,40,0.5, -64,Graphics.height,-64,Graphics.width, 0.5,0.10,-5,-13,30,0]) initParticles("particle",250) end end class Particle_Engine::Smoke < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,0,80,20,0.5,-64, Graphics.height,-64,Graphics.width,0.5,0.10,-5,-15,5,80]) initParticles("smoke",250) end end class Particle_Engine::Teleport < ParticleEffect_Event def initialize(event,viewport) super setParameters([1,1,1,10,rand(360),1,-64, Graphics.height,-64,Graphics.width,0,3,-8,-15,20,0]) initParticles("wideportal",250) for i in 0...@maxparticless @particles[i].ox=16 @particles[i].oy=16 end end end class Particle_Engine::Spirit < ParticleEffect_Event def initialize(event,viewport) super setParameters([1,0,1,20,rand(360),0.5, -64,Graphics.height,-64,Graphics.width, 0.5,0.10,-5,-13,30,0]) initParticles("particle",250) end end class Particle_Engine::Explosion < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,1,20,0,0.5, -64,Graphics.height,-64,Graphics.width, 0.5,0.10,-5,-13,30,0]) initParticles("explosion",250) end end class Particle_Engine::Aura < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,1,20,0,1, -64,Graphics.height,-64,Graphics.width, 2,2,-5,-13,30,0]) initParticles("particle",250) end end class Particle_Engine::Soot < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,0,20,0,0.5, -64,Graphics.height,-64,Graphics.width, 0.5,0.10,-5,-15,5, 80]) initParticles("smoke",100,0,2) end end class Particle_Engine::SootSmoke < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,0,30,0,0.5, -64,Graphics.height,-64,Graphics.width, 0.5,0.10,-5,-15,5, 80]) initParticles("smoke",100,0) for i in 0...@maxparticless @particles[i].blend_type = rand(6) < 3 ? 1 : 2 end end end class Particle_Engine::Rocket < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,0,60,0,0.5, -64,Graphics.height,-64,Graphics.width, 0.5,0,-5,-15,5,80]) initParticles("smoke",100,-1) end end class Particle_Engine::FixedTeleport < ParticleEffect_Event def initialize(event,viewport) super setParameters([1,0,1,10,rand(360),1, -Graphics.height,Graphics.height,0,Graphics.width,0,3,-8,-15,20,0]) initParticles("wideportal",250) for i in 0...@maxparticless @particles[i].ox=16 @particles[i].oy=16 end end end # By Peter O. class Particle_Engine::StarTeleport < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,1,10,0,1, -Graphics.height,Graphics.height,0,Graphics.width,0,3,-8,-15,10,0]) initParticles("star",250) for i in 0...@maxparticless @particles[i].ox=48 @particles[i].oy=48 end end end class Particle_Engine::Smokescreen < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,0,450,0,0.2, -64,Graphics.height,-64,Graphics.width, 0.8,0.8,-5,-15,5,80]) initParticles(nil,100) for i in 0...@maxparticless rnd=rand(3) @opacity[i] = (rnd==0) ? 1 : 100 filename=(rnd==0) ? "explosionsmoke" : "smoke" @particles[i].bitmap = loadBitmap(filename, @hue) end end def calcParticlePos(i) if @randomhue==1 filename=(rand(3)==0) ? "explosionsmoke" : "smoke" @particles[i].bitmap = loadBitmap(filename, @hue) end multiple = 1.7 xgrav=(@xgravity*multiple/@slowdown) xgrav=-xgrav if (rand(2)==1) ygrav=(@ygravity*multiple/@slowdown) ygrav=-ygrav if (rand(2)==1) @particlex[i]+=xgrav @particley[i]+=ygrav @particlex[i]-=@__offsetx @particley[i]-=@__offsety @particlex[i]=@particlex[i].floor @particley[i]=@particley[i].floor @particles[i].x=@particlex[i]+@startingx+@xoffset @particles[i].y=@particley[i]+@startingy+@yoffset end end class Particle_Engine::Flare < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,1,30,10,1, -64,Graphics.height,-64,Graphics.width, 2,2,-5,-12,30,0]) initParticles("particle",255) end end class Particle_Engine::Splash < ParticleEffect_Event def initialize(event,viewport) super setParameters([0,0,1,30,255,1, -64,Graphics.height,-64,Graphics.width, 4,2,-5,-12,30,0]) initParticles("smoke",50) end def update super for i in 0...@maxparticless @particles[i].opacity=50 @particles[i].update end end end class Game_Event < Game_Character #-------------------------------------------------------------------------- attr_accessor :pe_refresh #-------------------------------------------------------------------------- alias nf_particles_game_map_initialize initialize alias nf_particles_game_map_refresh refresh #-------------------------------------------------------------------------- def initialize(map_id,event,map=nil) @pe_refresh=false begin nf_particles_game_map_initialize(map_id, event,map) rescue ArgumentError nf_particles_game_map_initialize(map_id, event) end end #-------------------------------------------------------------------------- def refresh nf_particles_game_map_refresh @pe_refresh=true end end [/CODE] [CODE] def bltMinimapAutotile(dstBitmap,x,y,srcBitmap,id) return if id>=48 || !srcBitmap || srcBitmap.disposed? anim=0 cxTile=3 cyTile=3 tiles = TileDrawingHelper::Autotiles[id>>3][id&7] src=Rect.new(0,0,0,0) for i in 0...4 tile_position = tiles[i] - 1 src.set( tile_position % 6 * cxTile + anim, tile_position / 6 * cyTile, cxTile, cyTile) dstBitmap.blt(i%2*cxTile+x,i/2*cyTile+y, srcBitmap, src) end end def passable?(passages,tile_id) return false if tile_id == nil return false if passages[tile_id] == nil return (passages[tile_id]<15) end def getPassabilityMinimap(mapid) map=load_data(sprintf("Data/Map%03d.rxdata",mapid)) tileset=$data_tilesets[map.tileset_id] minimap=Bitmap.new("Graphics/Pictures/minimap_tiles.png") ret=Bitmap.new(map.width*6,map.height*6) passtable=Table.new(map.width,map.height) passages=tileset.passages for i in 0...map.width for j in 0...map.height pass=true for z in [2,1,0] if !passable?(passages,map.data[i,j,z]) pass=false break end end passtable[i,j]=pass ? 1 : 0 end end neighbors=TileDrawingHelper::NeighborsToTiles for i in 0...map.width for j in 0...map.height if passtable[i,j]==0 nb=TileDrawingHelper.tableNeighbors(passtable,i,j) tile=neighbors[nb] bltMinimapAutotile(ret,i*6,j*6,minimap,tile) end end end minimap.dispose return ret end module ScreenPosHelper def self.pbScreenZoomX(ch) if $PokemonSystem.tilemap==2 return ((ch.screen_y - 16) - (Graphics.height / 2)) * (Draw_Tilemap::Pitch*1.0 / (Graphics.height * 25)) + 1 else return 1.0 end end def self.pbScreenZoomY(ch) if $PokemonSystem.tilemap==2 return ((ch.screen_y - 16) - (Graphics.height / 2)) * (Draw_Tilemap::Pitch*1.0 / (Graphics.height * 25)) + 1 else return 1.0 end end def self.pbScreenX(ch) ret=ch.screen_x if $PokemonSystem.tilemap==2 widthdiv2=(Graphics.width / 2) ret=widthdiv2+(ret-widthdiv2)*pbScreenZoomX(ch) end return ret end def self.pbScreenY(ch) ret=ch.screen_y if $PokemonSystem.tilemap==2 && Draw_Tilemap::Curve && Draw_Tilemap::Pitch != 0 zoomy=pbScreenZoomY(ch) oneMinusZoomY=1-zoomy ret += (8 * oneMinusZoomY * (oneMinusZoomY / (2 * ((Draw_Tilemap::Pitch*1.0 / 100) / (Graphics.height*1.0 / 16.0))) + 0.5)) end return ret end @heightcache={} def self.bmHeight(bm) h=@heightcache[bm] if !h bmap=RPG::Cache.character(bm,0) h=bmap.height @heightcache[bm]=h bmap.dispose end return h end def self.pbScreenZ(ch,height=nil) if height==nil height=0 if ch.tile_id > 0 height=32 elsif ch.character_name!="" height=bmHeight(ch.character_name)/4 end end ret=ch.screen_z(height) if $PokemonSystem.tilemap==2 ret-=(pbScreenZoomY(ch) < 0.5 ? 1000 : 0) end return ret end end ############################################### class Draw_Tilemap # This class controls a set of sprites, with different Z # values, arranged into horizontal bars StripSize = 16 Curve = true Pitch = 3 attr_accessor :tileset attr_accessor :map_data attr_accessor :flash_data attr_accessor :priorities attr_reader :autotiles attr_accessor :bitmaps attr_accessor :pitch attr_accessor :ox attr_accessor :oy attr_accessor :visible attr_reader :viewport attr_accessor :color attr_accessor :tone FlashOpacity=[100,90,80,70,80,90] #----------------------------------------------------------------------------- def initialize(viewport=nil) @tileset=nil @map_data=nil @priorities=nil @autotiles=[nil,nil,nil,nil,nil,nil,nil] @viewport=viewport @visible=true @helper=TileDrawingHelper.new(nil,@autotiles) @drawnstrips=[] @contentstrips=[] @disposed=false @bitmaps=[] @sprites=[] @ox=0 @oy=0 @tone=Tone.new(0,0,0,0) @color=Color.new(0,0,0,0) @flash_data=nil @numsprites=0 end def tileset=(value) @tileset=value @helper.tileset=value @doredraw=true end def map_data=(value) @map_data=value @doredraw=true end def flash_data=(value) @flash_data=value @doredraw=true end def priorities=(value) @priorities=value @doredraw=true end def redrawmap # Provide blank data in proper object form self.clear xsize=@map_data.xsize ysize=@map_data.ysize # Bitmaps used for each priority's drawing. Priorities 2-5 are combined. @bitmaps = [Bitmap.new(xsize*32, ysize*32+StripSize), Bitmap.new(xsize*32, ysize*32+StripSize), Bitmap.new(xsize*32, ysize*32+StripSize)] for i in @bitmaps i.clear end if @flash_data @bitmaps.push(Bitmap.new(xsize*32, ysize*32+StripSize)) end @drawnstrips.clear @contentstrips.clear # Generate blank sprites @sprites.clear @numsprites=ysize * (32 / StripSize) for i in 0...@map_data.zsize # For each layer @sprites.push([]) @contentstrips.push([]) end if @flash_data @sprites.push([]) @contentstrips.push([]) end end def update oyunchanged=false if !@flash_data.nil? && @sprites.length>0 flashindex=@sprites.length-1 for j in 0...@numsprites sprite=@sprites[flashindex][j] next if !sprite.is_a?(Sprite) sprite.opacity=FlashOpacity[(Graphics.frame_count/2) % 6] end end for s in @sprites for sprite in s next if !sprite.is_a?(Sprite) # sprite.tone=@tone # sprite.color=@color end end if @doredraw @drawnstrips=[] redrawmap @doredraw=false elsif @oldOx==@ox && @oldOy==@oy return elsif @oldOy==@oy oyunchanged=true end @oldOx=@ox @oldOy=@oy @pitch = Pitch minvalue=[0, ((Graphics.height / 2) - ((Graphics.height * 60) / @pitch) + @oy) / StripSize].max.to_i maxvalue=[@numsprites - 1,(@oy + Graphics.height) / StripSize].min.to_i return if minvalue>maxvalue for j in 0...@numsprites if j<minvalue || j>maxvalue for i in 0...@sprites.length sprite=@sprites[i][j] if sprite sprite.dispose if sprite.is_a?(Sprite) @sprites[i][j]=nil end end else drawStrip(j) end end vpy=@viewport.rect.y vpr=@viewport.rect.x+@viewport.rect.width vpb=@viewport.rect.y+@viewport.rect.height numsprites=0 for i in @sprites numsprites+=i.compact.length end for j in minvalue..maxvalue # For each strip within the visible screen, update OX/Y x=Graphics.width/2 sox=@ox+x y = (j * StripSize - @oy) zoom_x=1.0 zoom_y=1.0 unless @pitch == 0 # Apply X Zoom zoom_x = (y - Graphics.height*1.0 / 2) * (@pitch*1.0 / (Graphics.height * 25)) + 1 if Curve # Zoom Y values same as X, and compensate zoom_y = zoom_x yadd = StripSize*1.0 * (1 - zoom_y) * ((1 - zoom_y) / (2 * ((@pitch*1.0 / 100) / (Graphics.height*1.0 / (StripSize * 2)))) + 0.5) y+=yadd end end xstart=(x-sox*zoom_x) yend=(y+(StripSize*2)*zoom_y) if xstart>vpr || yend<=vpy for i in 0...@sprites.length sprite=@sprites[i][j] if sprite.is_a?(Sprite) sprite.dispose @sprites[i][j]=nil end end else for i in 0...@sprites.length sprite=@sprites[i][j] next if !sprite if sprite==true sprite=newSprite(i,j) @sprites[i][j]=sprite end sprite.visible=@visible sprite.x = x sprite.ox = sox sprite.y = y sprite.zoom_x = zoom_x sprite.zoom_y = zoom_y end end end end def clear for i in @bitmaps i.dispose end @bitmaps.clear for i in 0...@sprites.length for j in 0...@sprites[i].length @sprites[i][j].dispose if @sprites[i][j].is_a?(Sprite) end @sprites[i].clear end @sprites.clear end def dispose return if @disposed self.clear for i in 0...7 self.autotiles[i]=nil end @helper=nil @sprites=nil @bitmaps=nil @disposed = true end def disposed? return @disposed end def newSprite(i,j) sprite=Sprite.new(@viewport) sprite.bitmap=@bitmaps[i] sprite.src_rect.set(0, j * StripSize, @map_data.xsize * 32, StripSize * 2) sprite.x = Graphics.width / 2 sprite.y = -64 sprite.z = (i * 32) sprite.tone=@tone sprite.color=@color if i==@bitmaps.length-1 && !@flash_data.nil? sprite.blend_type=1 sprite.z=1 sprite.opacity=FlashOpacity[(Graphics.frame_count/2) % 6] end return sprite end def drawStrip(j) minY=(j*StripSize)/32 maxY=(j*StripSize+StripSize*2)/32 minY=0 if minY<0 minY=@map_data.ysize-1 if minY>@map_data.ysize-1 maxY=0 if maxY<0 maxY=@map_data.ysize-1 if maxY>@map_data.ysize-1 for y in minY..maxY if !@drawnstrips[y] for x in 0...@map_data.xsize draw_position(x, y) end @drawnstrips[y]=true end end for i in 0...@sprites.length # For each priority sprite=@sprites[i][j] if !sprite || (sprite!=true && sprite.disposed?) havecontent=false for y in minY..maxY havecontent=havecontent||@contentstrips[i][y] end sprite=(havecontent) ? true : nil @sprites[i][j]=sprite end end end def draw_position(x, y) for layer in 0...@map_data.zsize pos = @map_data[x, y, layer] priopos=@priorities[pos] priopos=0 if !priopos prio=(2<priopos) ? 2 : priopos @contentstrips[prio][y]=true if pos>0 @helper.bltTile(@bitmaps[prio],x*32,y*32,pos,0) end if !@flash_data.nil? lastlayer=@bitmaps.length-1 id=@flash_data[x,y,0] r=(id>>8)&15 g=(id>>4)&15 b=(id)&15 @contentstrips[lastlayer][y]=true color=Color.new(r*16,g*16,b*16) @bitmaps[lastlayer].fill_rect(x*32,y*32,32,32,color) end end end class Sprite_Character attr_accessor :character def initialize(viewport, character = nil) super(viewport) @character = character update end alias update_or :update def update update_or if $PokemonSystem.tilemap==2 self.zoom_y=ScreenPosHelper.pbScreenZoomY(@character) self.zoom_x=ScreenPosHelper.pbScreenZoomX(@character) self.x=ScreenPosHelper.pbScreenX(@character) self.y=ScreenPosHelper.pbScreenY(@character) self.z=ScreenPosHelper.pbScreenZ(@character,@ch) else self.zoom_x=1.0 self.zoom_y=1.0 end end end [/CODE] [CODE]def floodFillInternal(table,x,y,target,fillbits,points) w=table.xsize xLeft=x xRight=x yFromOrg=y xFromOrg=x curpos=yFromOrg*w+xFromOrg begin if !fillbits[curpos] points.push([xLeft,y]) end fillbits[curpos]=true curpos-=1 xLeft-=1 end while (xLeft>=0&& table[xLeft,y]==target&& !fillbits[curpos]) xLeft+=1 curpos=yFromOrg*w+xFromOrg begin if !fillbits[curpos] points.push([xRight,y]) end fillbits[curpos]=true curpos+=1 xRight+=1 end while(xRight<table.xsize&& table[xRight,y]==target&& !fillbits[curpos]) xRight-=1 curpos=yFromOrg-w+(xLeft) for i in xLeft..xRight above=(yFromOrg-1)*w+(i) below=(yFromOrg+1)*w+(i) if(y> 0 &&table[i,y-1]==target&&!fillbits[above]) ret=floodFillInternal(table,i,y-1,target,fillbits,points) end if(y<(table.ysize-1)&&table[i,y+1]==target&&!fillbits[below]) ret=floodFillInternal(table,i,y+1,target,fillbits,points) end end end N=0x01 NE=0x02 E=0x04 SE=0x08 S=0x10 SW=0x20 W=0x40 NW=0x80 BADNEIGHBORS=[ 0, SE, NW, NE, SW, S|SW, S|SE, N|NW, N|NE, W|SW, W|NW, E|NE, E|SE, S|SW|SE, N|NW|NE, W|NW|SW, E|NE|SE ] def isBadNeighbor?(neighbor) return true if BADNEIGHBORS.any?{|i| i==neighbor } return true if (neighbor&(S|W))==(0) && (neighbor&(SW))!=0 return true if (neighbor&(N|W))==(0) && (neighbor&(NW))!=0 return true if (neighbor&(S|E))==(0) && (neighbor&(SE))!=0 return true if (neighbor&(N|E))==(0) && (neighbor&(NE))!=0 return true if (neighbor&(NW|NE))==(0) && (neighbor&(N))!=0 return true if (neighbor&(SW|SE))==(0) && (neighbor&(S))!=0 return true if (neighbor&(NW|SW))==(0) && (neighbor&(W))!=0 return true if (neighbor&(NE|SE))==(0) && (neighbor&(E))!=0 end def pbTableMoveToNeighbor(table,pointtable,value) 1000.times do x=rand(table.xsize) y=rand(table.ysize) next if table[x,y]!=0 table[x,y]=value nb=TileDrawingHelper.tableNeighbors(table,x,y) if isBadNeighbor?(nb) table[x,y]=0 next end if nb==0 && rand(100)<50 table[x,y]=0 next end pointtable[x,y]=2 break end end def pbTablePlaceValue(table,value,minNumber,minbunch) return if minNumber<=0 # Phase 1: Place _minNumber_ points on the map 1000.times do 1000.times do x=rand(table.xsize-1) y=rand(table.ysize-1) placepos=[] if table[x,y]==0 table[x,y]=value placepos.push([x,y]) end if table[x+1,y]==0 table[x+1,y]=value placepos.push([x+1,y]) end if table[x,y+1]==0 table[x,y+1]=value placepos.push([x,y+1]) end if table[x+1,y+1]==0 table[x+1,y+1]=value placepos.push([x+1,y+1]) end placed=placepos.length for pp in placepos nb=TileDrawingHelper.tableNeighbors(table,pp[0],pp[1]) if isBadNeighbor?(nb) table[pp[0],pp[1]]=0 placed-=1 end end minNumber-=placed break end break if minNumber<=0 end # Phase 2: Move all bad points badpoints=0 begin badpoints=0 pointtable=Table.new(table.xsize,table.ysize) fillbits=[] # Find all bad points with flood filling if minbunch>0 table.xsize.times{|x| table.ysize.times{|y| next if table[x,y]!=value index=y*table.xsize+x if !fillbits[index] points=[] floodFillInternal(table,x,y,value,fillbits,points) isbad=(points.length<minbunch) havebadpoints=true if isbad badpoints+=points.length if isbad for p in points pointtable[p[0],p[1]]=isbad ? 1 : 2 end end } } end # Find all inappropriately placed points pointtable.xsize.times{|x| pointtable.ysize.times{|y| next if pointtable[x,y]==1 next if table[x,y]!=value nb=TileDrawingHelper.tableNeighbors(table,x,y) if isBadNeighbor?(nb) pointtable[x,y]=1 badpoints+=1 end if nb==(0xEF) # everything but South table[x,y+1]=value end if nb==(0xBF) # everything but West table[x-1,y]=value end if nb==(0xFB) # everything but East table[x+1,y]=value end if nb==(0xFE) # everything but North table[x,y-1]=value end } } if badpoints>0 # Move all bad points to new locations pointtable.xsize.times{|x| pointtable.ysize.times{|y| next if pointtable[x,y]!=1 # skip if not a bad point pointtable[x,y]=0 table[x,y]=0 pbTableMoveToNeighbor(table,pointtable,value) } } end end while badpoints>0 end def pbGenerateMap(id,width,height,generateMapParams) # Fill table with zeros table=Table.new(width,height) table.xsize.times{|x| table.ysize.times{|y| table[x,y]=0 } } # Place autotiles on the table for i in 0...7 count=generateMapParams[i*2] sticky=generateMapParams[i*2+1] pbTablePlaceValue(table,i+1,count,sticky) end # Create map and fill it with grass map=RPG::Map.new(width,height) map.data.xsize.times{|x| map.data.ysize.times{|y| map.data[x,y,0]=384 } } # Fill map with autotiles neighbors=TileDrawingHelper::NeighborsToTiles for i in 0...map.width for j in 0...map.height if table[i,j]!=0 nb=TileDrawingHelper.tableNeighbors(table,i,j) tile=neighbors[nb] map.data[i,j,1]=tile+48*table[i,j] end end end # Save map save_data(map,sprintf("Data/Map%03d.rxdata",id)) end =begin #Usage: pbGenerateMap( 24, # Map ID 30, # Map Width 30, # Map Height [ # Map Parameters # count, sticky 20,8, # Autotile 1 30,8, # Autotile 2 75,8, # Autotile 3 250,15, # Autotile 4 0,0, # Autotile 5 0,0, # Autotile 6 0,0 # Autotile 7 ] ) =end[/CODE] [CODE]class DungeonMap XBORDER=7 YBORDER=5 def initialize(width,height,blankValue) @map=Table.new( width+XBORDER+XBORDER, height+YBORDER+YBORDER ) for i in 0...@map.xsize for j in 0...@map.ysize @map[i,j]=blankValue end end end def width @map.xsize-XBORDER-XBORDER end def height @map.xsize-YBORDER-YBORDER end def map return @map end def draw(x,y,value) @map[x+XBORDER,y+YBORDER]=value end def get(x,y) @map[x+XBORDER,y+YBORDER] end def getRaw(x,y) @map[x,y] end end class RoomData attr_reader :x attr_reader :y attr_reader :width,:height alias top y alias left x def id return @room end def randomPos return [ @x+rand(@width), @y+rand(@height) ] end def right return @x+@width end def bottom return @y+@height end def initialize(room,x,y,width,height) @room=room @x=x @y=y @width=width @height=height end def draw(dungeon,value) for y in 0...self.height for x in 0...self.width xx=x+self.x yy=y+self.y dungeon.draw(xx,yy,value) end end end def createUnion(otherRoom) newX=[self.x,otherRoom.x].min newY=[self.y,otherRoom.y].min newRight=[self.right,otherRoom.right].max newBottom=[self.bottom,otherRoom.bottom].max return RoomData.new(self.id, newX,newY,newRight-newX,newBottom-newY) end def intersects?(otherRoom) newX=[self.x,otherRoom.x].max newY=[self.y,otherRoom.y].max newRight=[self.right,otherRoom.right].min newBottom=[self.bottom,otherRoom.bottom].min return (newX<newRight && newY<newBottom) end CLOSENESSFACTOR=2 def closeTo?(room) return false if !room if (self.bottom-room.top).abs<=CLOSENESSFACTOR return true end if (self.top-room.bottom).abs<=CLOSENESSFACTOR return true end if (self.right-room.left).abs<=CLOSENESSFACTOR return true end if (self.left-room.right).abs<=CLOSENESSFACTOR return true end return false end end def hasRoom?(rooms,room) return false if room<0 return rooms.any? {|item| item.id==room } end def getRoom(rooms,roomID) for room in rooms return room if room.id==roomID end return nil end def saferand(x) return 0 if x<=0 return rand(x) end def createCorridor(dungeon,startRoom,endRoom) moveDirection=(rand(2)==0) nowConnected=[] currentX=startRoom[0] currentY=startRoom[1] while currentX!=endRoom[0] || currentY!=endRoom[1] dx=endRoom[0]-currentX dy=endRoom[1]-currentY if (dx!=0 && moveDirection) currentX+=dx>0 ? 1 : -1 elsif dy!=0 currentY+=dy>0 ? 1 : -1 end if dungeon.get(currentX,currentY)==1 break end if rand(10)<3 moveDirection=!moveDirection end nowConnected.push([currentX,currentY]) end for point in nowConnected dungeon.draw(point[0],point[1],1) end end def generateDungeon(mapID) if false baselinesX=[0,0,28,18,14,11,9] baselinesY=[0,0,16,10,8] # min width, min height, min rooms, max rooms, startX, startY roomlayout=[ [2,2, 7,5, 4,4, 0,0], [3,2, 7,5, 4,6, 1,0], [3,3, 7,5, 6,9, 1,0], [4,3, 7,5, 8,11, 0,0], [4,4, 6,4, 7,12, 1,0], [5,4, 5,4, 6,12, 0,0], [6,4, 5,4, 7,12, 0,0] # prevent moving/growing here ] dungeonWidth=52 dungeonHeight=28 else baselinesX=[0,0,40,26,19,15,13] baselinesY=[0,0,21,14,10] # min width, min height, min rooms, max rooms, startX, startY roomlayout=[ [2,2, 16,7, 4,4, 0,0], [3,2, 12,7, 4,6, 1,0], [3,3, 12,7, 6,9, 1,0], [4,3, 12,7, 8,11, 0,0], [4,4, 10,6, 7,12, 1,0], [5,4, 9,6, 6,12, 0,0], [6,4, 9,6, 7,12, 0,0] # prevent moving/growing here ] dungeonWidth=78 dungeonHeight=42 end # TODO: Ensure no surpassing width/height for i in 0...baselinesX.length baselinesX[i]=baselinesX[i]*3/2 end for i in 0...baselinesY.length baselinesY[i]=baselinesY[i]*3/2 end for i in 0...roomlayout.length roomlayout[i][2]=roomlayout[i][2]*3/2 roomlayout[i][3]=roomlayout[i][3]*3/2 end dungeonWidth=dungeonWidth*3/2 dungeonHeight=dungeonHeight*3/2 dungeon=DungeonMap.new(dungeonWidth,dungeonHeight,2) layout=roomlayout[saferand(roomlayout.length)] numrooms=layout[4]+saferand(layout[5]-layout[4]+1) roomPositions=[] numRoomsX=layout[0] numRoomsY=layout[1] baselineX=baselinesX[numRoomsX] baselineY=baselinesY[numRoomsY] for y in 0...numRoomsY for x in 0...numRoomsX roomPositions.push([ roomPositions.length, layout[6]+(baselinesX[numRoomsX]*x), layout[7]+(baselinesY[numRoomsY]*y) ]) end end numrooms=roomPositions.length if numrooms>roomPositions.length roomPositions.sort!{|a,b| rand(3)-1 } rooms=[] for i in 0...numrooms room=roomPositions[i] roomX=room[1]+saferand(3) roomY=room[2]+saferand(3) roomWidth=layout[2]+saferand(baselineX-layout[2]-4) roomHeight=layout[3]+saferand(baselineY-layout[3]-2) roomRight=roomX+roomWidth roomBottom=roomY+roomHeight roomX=0 if roomX<0 roomY=0 if roomY<0 roomX-=roomRight-dungeon.width if roomRight>dungeon.width roomY-=roomBottom-dungeon.height if roomBottom>dungeon.height rooms.push(RoomData.new(room[0],roomX,roomY,roomWidth,roomHeight)) end ############ ## Combine rooms if necessary for i in 0...rooms.length next if !rooms[i] for j in i+1...rooms.length if rooms[i].closeTo?(rooms[j]) rooms[i]=rooms[i].createUnion(rooms[j]) rooms[j]=nil end end end rooms.compact! ############ ## Eliminate rooms within other rooms for i in 0...rooms.length next if !rooms[i] for j in i+1...rooms.length next if !rooms[j] || !rooms[i] # If the two rooms intersect if rooms[i].intersects?(rooms[j]) sizeI=rooms[i].width*rooms[i].height sizeJ=rooms[j].width*rooms[j].height # Eliminate the smaller of the two rooms if sizeI==sizeJ rooms[i]=nil rooms[j]=nil elsif sizeI<sizeJ rooms[i]=nil else rooms[j]=nil end end end end rooms.compact! ############ ## Create corridors firstRoom=rooms.delete_at(rand(rooms.length)) newRooms=[firstRoom] firstRoom.draw(dungeon,1) while rooms.length>0 startRoom=rooms[rand(rooms.length)] endRoom=newRooms[rand(newRooms.length)] createCorridor(dungeon, startRoom.randomPos, endRoom.randomPos ) rooms.delete(startRoom) newRooms.push(startRoom) startRoom.draw(dungeon,1) end ############ ## Fill map map=RPG::Map.new( dungeon.map.xsize, dungeon.map.ysize ) map.tileset_id=6 # Fill map with autotiles neighbors=TileDrawingHelper::NeighborsToTiles for i in 0...map.width for j in 0...map.height if dungeon.map[i,j]!=0 nb=TileDrawingHelper.tableNeighbors(dungeon.map,i,j) tile=neighbors[nb] map.data[i,j,1]=tile+48*dungeon.map[i,j] end end end save_data(map,sprintf("Data/Map%03d.rxdata",mapID)) end #generateDungeon(24)[/CODE] [CODE]#============================================================================== # Sprite_Shadow (Sprite_Ombre ) # Based on Genzai Kawakami's shadows, dynamisme&features by Rataime, extra features Boushy # Modified by Peter O. to be compatible with Pokémon Essentials #============================================================================== CATERPILLAR_COMPATIBLE = true SHADOW_WARN = true class Sprite_Shadow < RPG::Sprite attr_accessor :character def initialize(viewport, character = nil,params=[]) super(viewport) @source=params[0] @anglemin=0 @anglemin=params[1] if params.size>1 @anglemax=0 @anglemax=params[2] if params.size>2 @self_opacity=100 @self_opacity=params[4] if params.size>4 @distancemax=350 @distancemax=params[3] if params.size>3 @character = character update end def dispose self.bitmap.dispose if self.bitmap super end def update if !in_range?(@character, @source, @distancemax) self.opacity=0 return end super if @tile_id != @character.tile_id or @character_name != @character.character_name or @character_hue != @character.character_hue @tile_id = @character.tile_id @character_name = @character.character_name @character_hue = @character.character_hue if @tile_id >= 384 self.bitmap.dispose if self.bitmap self.bitmap = RPG::Cache.tile(@character.map.tileset_name, @tile_id, @character.character_hue) self.src_rect.set(0, 0, 32, 32) @ch=32 @cw=32 self.ox = 16 self.oy = 32 else self.bitmap.dispose if self.bitmap self.bitmap = RPG::Cache.character(@character.character_name, @character.character_hue) @cw = bitmap.width / 4 @ch = bitmap.height / 4 self.ox = @cw / 2 self.oy = @ch end end self.visible = (not @character.transparent) if @tile_id == 0 sx = @character.pattern * @cw sy = (@character.direction - 2) / 2 * @ch if self.angle>90 or angle<-90 if @character.direction== 6 sy = ( 4- 2) / 2 * @ch end if @character.direction== 4 sy = ( 6- 2) / 2 * @ch end if @character.direction== 2 sy = ( 8- 2) / 2 * @ch end if @character.direction== 8 sy = ( 2- 2) / 2 * @ch end end self.src_rect.set(sx, sy, @cw, @ch) end self.x = ScreenPosHelper.pbScreenX(@character) self.y = ScreenPosHelper.pbScreenY(@character)-5 self.z = ScreenPosHelper.pbScreenZ(@character,@ch)-1 self.zoom_x = ScreenPosHelper.pbScreenZoomX(@character) self.zoom_y = ScreenPosHelper.pbScreenZoomY(@character) self.blend_type = @character.blend_type self.bush_depth = @character.bush_depth if @character.animation_id != 0 animation = $data_animations[@character.animation_id] animation(animation, true) @character.animation_id = 0 end @deltax=ScreenPosHelper.pbScreenX(@source)-self.x @deltay=ScreenPosHelper.pbScreenY(@source)-self.y self.color = Color.new(0, 0, 0) @distance = ((@deltax ** 2) + (@deltay ** 2)) self.opacity = @self_opacity*13000/((@distance*370/@distancemax)+6000) self.angle = 57.3*Math.atan2(@deltax, @deltay ) @angle_trigo=self.angle+90 if @angle_trigo<0 @angle_trigo=360+@angle_trigo end if @anglemin !=0 or @anglemax !=0 if (@angle_trigo<@anglemin or @angle_trigo>@anglemax) and @anglemin<@anglemax self.opacity=0 return end if (@angle_trigo<@anglemin and @angle_trigo>@anglemax) and @anglemin>@anglemax self.opacity=0 return end end end def in_range?(element, object, range)# From Near's Anti Lag Script, edited elemScreenX=ScreenPosHelper.pbScreenX(element) objScreenX=ScreenPosHelper.pbScreenX(object) elemScreenY=ScreenPosHelper.pbScreenY(element) objScreenY=ScreenPosHelper.pbScreenY(object) x = (elemScreenX - objScreenX) * (elemScreenX - objScreenX) y = (elemScreenY - objScreenY) * (elemScreenY - objScreenY) r = x + y if r <= (range * range) return true else return false end end end #=================================================== # ? CLASS Sprite_Character edit #=================================================== class Sprite_Character < RPG::Sprite alias shadow_initialize initialize def initialize(viewport, character = nil) super(viewport) @ombrelist=[] @character = character shadow_initialize(viewport, @character) end def setShadows(map,shadows) if character.is_a?(Game_Event) and shadows.length>0 params = XPML_read(map,"Shadow",@character,4) if params!=nil for i in 0...shadows.size @ombrelist.push(Sprite_Shadow.new( viewport, @character,shadows[i] )) end end end if character.is_a?(Game_Player) and shadows.length>0 for i in 0...shadows.size @ombrelist.push(Sprite_Shadow.new( viewport, $game_player,shadows[i] )) end end update end alias shadow_update update def update shadow_update if @ombrelist.length>0 for i in 0...@ombrelist.size @ombrelist[i].update end end end end #=================================================== # ? CLASS Game_Event edit #=================================================== class Game_Event attr_accessor :id end #=================================================== # ? CLASS Spriteset_Map edit #=================================================== class Spriteset_Map attr_accessor :shadows alias shadow_initialize initialize def initialize(map=nil) @shadows=[] warn=false map=$game_map if !map for k in map.events.keys.sort warn=true if (map.events[k].list!=nil and map.events[k].list[0].code == 108 and (map.events[k].list[0].parameters == ["s"] or map.events[k].list[0].parameters == ["o"])) params = XPML_read(map,"Shadow Source",map.events[k],4) @shadows.push([map.events[k]]+params) if params!=nil end if warn == true and SHADOW_WARN p "Warning : At least one event on this map uses the obsolete way to add shadows" end shadow_initialize(map) for sprite in @character_sprites sprite.setShadows(map,@shadows) end end end #=================================================== # ? XPML Definition, by Rataime, using ideas from Near Fantastica # # Returns nil if the markup wasn't present at all, # returns [] if there wasn't any parameters, else # returns a parameters list with "int" converted as int # eg : # begin first # begin second # param1 1 # param2 two # begin third # anything 3 # # p XPML_read("first", event_id) -> [] # p XPML_read("second", event_id) -> [1,"two"] # p XPML_read("third", event_id) -> [3] # p XPML_read("forth", event_id) -> nil #=================================================== def XPML_read(map,markup,event,max_param_number=0) parameter_list = nil return nil if !event || event.list==nil for i in 0...event.list.size if event.list[i].code == 108 and event.list[i].parameters[0].downcase == "begin "+markup.downcase parameter_list = [] if parameter_list == nil for j in i+1...event.list.size if event.list[j].code == 108 parts = event.list[j].parameters[0].split if parts.size!=1 and parts[0].downcase!="begin" if parts[1].to_i!=0 or parts[1]=="0" parameter_list.push(parts[1].to_i) else parameter_list.push(parts[1]) end else return parameter_list end else return parameter_list end return parameter_list if max_param_number!=0 and j==i+max_param_number end end end return parameter_list end [/CODE] [CODE]class Thread def Thread.exclusive _old = Thread.critical begin Thread.critical = true return yield ensure Thread.critical = _old end end end class AudioContext attr_reader :context def initialize init = Win32API.new("audio.dll", "AudioContextInitialize", '', 'l') @context=init.call() end def dispose if @context!=0 init = Win32API.new("audio.dll", "AudioContextFree", 'l', '') init.call(context) @context=0 end end end ##################################### # Needed because RGSS doesn't call at_exit procs on exit # Exit is not called when game is reset (using F12) $AtExitProcs=[] if !$AtExitProcs def exit(code=0) for p in $AtExitProcs p.call end raise SystemExit.new(code) end def at_exit(&block) $AtExitProcs.push(Proc.new(&block)) end ##################################### module AudioState w32_LL = Win32API.new("kernel32.dll", "LoadLibrary", 'p', 'l') w32_FL = Win32API.new("kernel32.dll", "FreeLibrary", 'p', 'l') if FileTest.exist?("audio.dll") @handle = w32_LL.call("audio.dll") at_exit { w32_FL.call(@handle) } AudioContextIsActive=Win32API.new("audio.dll","AudioContextIsActive","l","l") AudioContextPlay=Win32API.new("audio.dll","AudioContextPlay","lpllll","") AudioContextStop=Win32API.new("audio.dll","AudioContextStop","l","") AudioContextFadeOut=Win32API.new("audio.dll","AudioContextFadeOut","ll","") AudioContextGetPosition=Win32API.new("audio.dll","AudioContextGetPosition","l","l") AudioContextFadeIn=Win32API.new("audio.dll","AudioContextFadeIn","ll","") AudioContextSetVolume=Win32API.new("audio.dll","AudioContextSetVolume","ll","") # AudioContextMute=Win32API.new("audio.dll","AudioContextMute","ll","") # AudioContextUnmute=Win32API.new("audio.dll","AudioContextUnmute","ll","") AudioContextSEPlay=Win32API.new("audio.dll","AudioContextSEPlay","lplll","") if !@MEContext @MEContext=AudioContext.new at_exit { @MEContext.dispose } end if !@BGMContext @BGMContext=AudioContext.new at_exit { @BGMContext.dispose } end if !@BGSContext @BGSContext=AudioContext.new at_exit { @BGSContext.dispose } end if !@SEContext @SEContext=AudioContext.new at_exit { @SEContext.dispose } end else AudioContextIsActive=nil AudioContextPlay=nil AudioContextStop=nil AudioContextFadeOut=nil AudioContextGetPosition=nil AudioContextFadeIn=nil AudioContextSetVolume=nil AudioContextSEPlay=nil end @channel=nil @bgm=nil @name="" @pitch=100 @bgmVolume=100.0 @meVolume=100.0 @bgsVolume=100.0 @seVolume=100.0 def self.setWaitingBGM(bgm,volume,pitch,position) @waitingBGM=[bgm,volume,pitch,position] end def self.bgmActive? return (AudioContextIsActive.call(@BGMContext.context)!=0) end def self.meActive? return (AudioContextIsActive.call(@MEContext.context)!=0) end def self.waitingBGM; @waitingBGM; end def self.context; @BGMContext.context; end def self.meContext; @MEContext.context; end def self.bgsContext; @BGSContext.context; end def self.seContext; @SEContext.context; end def self.system; @system; end def self.bgm; @bgm; end def self.name; @name; end def self.pitch; @pitch; end def self.volume; @volume; end def self.waitingBGM=(value); Thread.exclusive { @waitingBGM=value; } end def self.volume=(value); @volume=value; end def self.bgm=(value); @bgm=value; end def self.name=(value); @name=value; end def self.pitch=(value); @pitch=value; end end def Audio_bgm_playing? AudioState.channel!=nil end def Audio_bgm_name AudioState.name end def Audio_bgm_pitch AudioState.pitch end def Audio_bgm_play(name, volume, pitch, position = 0) volume=0 if !getPlayMusic() begin filename = canonicalize(rtpGetPath(name,[".mid",".mp3",".wma",".ogg",".wav",""])) if AudioState.meActive? AudioState.setWaitingBGM(filename,volume,pitch,position) return end AudioState::AudioContextPlay.call(AudioState.context,filename,volume,pitch,position,1) AudioState.name=filename AudioState.volume=volume AudioState.pitch=pitch rescue Hangup rescue p $!.message,$!.backtrace end end def Audio_me_play(name, volume, pitch, position = 0) volume=0 if !getPlayMusic() begin filename = canonicalize(rtpGetPath(name,[".mid",".mp3",".wma",".ogg",".wav",""])) if AudioState.bgmActive? bgmPosition=Kernel.Audio_bgm_get_position AudioState.setWaitingBGM( AudioState.name, AudioState.volume, AudioState.pitch, bgmPosition ) AudioState::AudioContextStop.call(AudioState.context) end AudioState::AudioContextPlay.call(AudioState.meContext,filename,volume,pitch,position,0) rescue p $!.message,$!.backtrace end end def Audio_me_fade(ms) AudioState::AudioContextFadeOut.call(AudioState.meContext,ms) end def Audio_me_stop() AudioState::AudioContextStop.call(AudioState.meContext) end def Audio_bgm_stop() begin AudioState::AudioContextStop.call(AudioState.context) AudioState.waitingBGM=nil AudioState.name = "" rescue p $!.message,$!.backtrace end end def Audio_bgm_get_position return AudioState::AudioContextGetPosition.call(AudioState.context) end def Audio_bgm_fade(ms) AudioState::AudioContextFadeOut.call(AudioState.context,ms.to_i) end def Audio_bgm_fadein(ms) AudioState::AudioContextFadeIn.call(AudioState.context,ms.to_i) end def Audio_bgm_get_volume return 0 if !AudioState.bgmActive? return AudioState.volume end def Audio_bgm_set_volume(volume) return if !AudioState.bgmActive? AudioState.volume = volume * 1.0 AudioState::AudioContextSetVolume.call(AudioState.context,volume.to_i) end def Audio_bgm_mute AudioState::AudioContextMute.call(AudioState.context,300) end def Audio_me_mute AudioState::AudioContextMute.call(AudioState.meContext,300) end def Audio_bgs_mute AudioState::AudioContextMute.call(AudioState.bgsContext,300) end def Audio_se_mute AudioState::AudioContextMute.call(AudioState.seContext,300) end def Audio_bgm_unmute AudioState::AudioContextUnmute.call(AudioState.context,300) end def Audio_me_unmute AudioState::AudioContextUnmute.call(AudioState.meContext,300) end def Audio_bgs_unmute AudioState::AudioContextUnmute.call(AudioState.bgsContext,300) end def Audio_se_unmute AudioState::AudioContextUnmute.call(AudioState.seContext,300) end def Audio_bgs_play(name, volume, pitch, position = 0) volume=0 if !getPlaySound() begin filename = canonicalize(rtpGetPath(name,[".mid",".mp3",".wma",".ogg",".wav",""])) AudioState::AudioContextPlay.call(AudioState.bgsContext,filename,volume,pitch,position,0) rescue p $!.message,$!.backtrace end end def Audio_bgs_fade(ms) AudioState::AudioContextFadeOut.call(AudioState.bgsContext,ms) end def Audio_bgs_stop() AudioState::AudioContextStop.call(AudioState.bgsContext) end def Audio_se_play(name, volume, pitch, position = 0) volume=0 if !getPlaySound() begin filename = canonicalize(rtpGetPath(name,[".mid",".mp3",".wma",".ogg",".wav",""])) AudioState::AudioContextSEPlay.call(AudioState.seContext,filename,volume,pitch,position) rescue p $!.message,$!.backtrace end end def Audio_se_stop() AudioState::AudioContextStop.call(AudioState.seContext) end #################################################### if FileTest.exist?("audio.dll") module Graphics if !defined?(audiomodule_update) class << self alias audiomodule_update update end end def self.update Audio.update audiomodule_update end end module Audio @@musicstate=nil @@soundstate=nil def self.update return if Graphics.frame_count%10!=0 =begin pm=getPlayMusic() ps=getPlaySound() if @@musicstate!=false && !pm @@musicstate=false Kernel.Audio_bgm_mute Kernel.Audio_me_mute elsif @@musicstate!=true && pm @@musicstate=true Kernel.Audio_bgm_unmute Kernel.Audio_me_unmute end if @@soundstate!=false && !ps @@soundstate=false Kernel.Audio_bgs_mute Kernel.Audio_se_mute elsif @@soundstate!=true && ps @@musicstate=true Kernel.Audio_bgs_unmute Kernel.Audio_se_unmute end =end if AudioState.waitingBGM && !AudioState.meActive? waitbgm=AudioState.waitingBGM AudioState.waitingBGM=nil bgm_play(waitbgm[0],waitbgm[1],waitbgm[2],waitbgm[3]) end end def self.bgm_play(name,volume=80,pitch=100,position=nil) begin if position==nil || position==0 Kernel.Audio_bgm_play(name,volume,pitch,0) else Kernel.Audio_bgm_play(name,volume,pitch,position) Kernel.Audio_bgm_fadein(500) end rescue Hangup bgm_play(name,volume,pitch,position) end end def self.bgm_fade(ms) Kernel.Audio_bgm_fade(ms) end def self.bgm_stop Kernel.Audio_bgm_stop() end def self.bgm_position ret=Kernel.Audio_bgm_get_position return ret end def self.me_play(name,volume=80,pitch=100) Kernel.Audio_me_play(name,volume,pitch,0) end def self.me_fade(ms) Kernel.Audio_me_fade(ms) end def self.me_stop Kernel.Audio_me_stop() end def self.bgs_play(name,volume=80,pitch=100) Kernel.Audio_bgs_play(name,volume,pitch,0) end def self.bgs_fade(ms) Kernel.Audio_bgs_fade(ms) end def self.bgs_stop Kernel.Audio_bgs_stop() end =begin def self.se_play(name,volume=80,pitch=100) Kernel.Audio_se_play(name,volume,pitch,0) end def self.se_stop Kernel.Audio_se_stop() end =end end class Game_System def bgm_pause(fadetime=0.0) pos=Audio.bgm_position if fadetime>0.0 bgm_fade(fadetime) end @bgm_position=pos end def bgs_pause(fadetime=0.0) if fadetime>0.0 bgs_fade(fadetime) else bgs_stop end end def bgm_unpause; @bgm_position=0; end def bgs_unpause; ; end def bgs_resume(bgm,volume=80,pitch=100); bgs_play(bgm,volume,pitch) end def bgm_resume(bgm,volume=80,pitch=100); bgm_play(bgm,volume,pitch,@bgm_position) @bgm_position=0 end def bgs_resume(bgm,volume=80,pitch=100); bgs_play(bgm,volume,pitch) end end ########### else ########### module Audio if !defined?(oldbgm_play) class << self alias oldbgm_play bgm_play end end def self.bgm_play(*arg) oldbgm_play(arg[0],arg[1]?arg[1]:80,arg[2]?arg[2]:100) end def self.bgm_position; 0; end end class Game_System def bgm_pause(fadetime=0.0) if fadetime>0.0 bgm_fade(fadetime) else bgm_stop end end def bgs_pause(fadetime=0.0) if fadetime>0.0 bgs_fade(fadetime) else bgs_stop end end def bgm_unpause; ; end def bgs_unpause; ; end def bgm_resume(*arg); bgm_play(*arg); end def bgs_resume(*arg); bgs_play(*arg); end end end [/CODE] [CODE]module Win32 class Registry module Constants HKEY_CLASSES_ROOT = 0x80000000 HKEY_CURRENT_USER = 0x80000001 HKEY_LOCAL_MACHINE = 0x80000002 HKEY_USERS = 0x80000003 HKEY_PERFORMANCE_DATA = 0x80000004 HKEY_PERFORMANCE_TEXT = 0x80000050 HKEY_PERFORMANCE_NLSTEXT = 0x80000060 HKEY_CURRENT_CONFIG = 0x80000005 HKEY_DYN_DATA = 0x80000006 REG_NONE = 0 REG_SZ = 1 REG_EXPAND_SZ = 2 REG_BINARY = 3 REG_DWORD = 4 REG_DWORD_LITTLE_ENDIAN = 4 REG_DWORD_BIG_ENDIAN = 5 REG_LINK = 6 REG_MULTI_SZ = 7 REG_RESOURCE_LIST = 8 REG_FULL_RESOURCE_DESCRIPTOR = 9 REG_RESOURCE_REQUIREMENTS_LIST = 10 REG_QWORD = 11 REG_QWORD_LITTLE_ENDIAN = 11 STANDARD_RIGHTS_READ = 0x00020000 STANDARD_RIGHTS_WRITE = 0x00020000 KEY_QUERY_VALUE = 0x0001 KEY_SET_VALUE = 0x0002 KEY_CREATE_SUB_KEY = 0x0004 KEY_ENUMERATE_SUB_KEYS = 0x0008 KEY_NOTIFY = 0x0010 KEY_CREATE_LINK = 0x0020 KEY_READ = STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY KEY_WRITE = STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY KEY_EXECUTE = KEY_READ KEY_ALL_ACCESS = KEY_READ | KEY_WRITE | KEY_CREATE_LINK REG_OPTION_RESERVED = 0x0000 REG_OPTION_NON_VOLATILE = 0x0000 REG_OPTION_VOLATILE = 0x0001 REG_OPTION_CREATE_LINK = 0x0002 REG_OPTION_BACKUP_RESTORE = 0x0004 REG_OPTION_OPEN_LINK = 0x0008 REG_LEGAL_OPTION = REG_OPTION_RESERVED | REG_OPTION_NON_VOLATILE | REG_OPTION_CREATE_LINK | REG_OPTION_BACKUP_RESTORE | REG_OPTION_OPEN_LINK REG_CREATED_NEW_KEY = 1 REG_OPENED_EXISTING_KEY = 2 REG_WHOLE_HIVE_VOLATILE = 0x0001 REG_REFRESH_HIVE = 0x0002 REG_NO_LAZY_FLUSH = 0x0004 REG_FORCE_RESTORE = 0x0008 MAX_KEY_LENGTH = 514 MAX_VALUE_LENGTH = 32768 end include Constants include Enumerable class Error < ::StandardError FormatMessageA=Win32API.new('kernel32.dll','FormatMessageA','LPLLPLP','L') def initialize(code) @code = code msg = "\\0" * 1024 len = FormatMessageA.call(0x1200, 0, code, 0, msg, 1024, 0) super msg[0, len].tr("\\r", '').chomp end attr_reader :code end class PredefinedKey < Registry def initialize(hkey, keyname) @hkey = hkey @parent = nil @keyname = keyname @disposition = REG_OPENED_EXISTING_KEY end def close raise Error.new(5) end def class Registry end Constants.constants.grep(/^HKEY_/) do |c| Registry.const_set c, new(Constants.const_get(c), c) end end module API [ %w/RegOpenKeyExA LPLLP L/, %w/RegCreateKeyExA LPLLLLPPP L/, %w/RegEnumValueA LLPPPPPP L/, %w/RegEnumKeyExA LLPPLLLP L/, %w/RegQueryValueExA LPLPPP L/, %w/RegSetValueExA LPLLPL L/, %w/RegFlushKey L L/, %w/RegCloseKey L L/, %w/RegQueryInfoKey LPPPPPPPPPPP L/, ].each do |fn| const_set fn[0].intern, Win32API.new('advapi32.dll', *fn) end module_function def check(result) raise Error, result, caller(2) if result != 0 end def packdw(dw) [dw].pack('V') end def unpackdw(dw) dw += [0].pack('V') dw.unpack('V')[0] end def packqw(qw) [ qw & 0xFFFFFFFF, qw >> 32 ].pack('VV') end def unpackqw(qw) qw = qw.unpack('VV') (qw[1] << 32) | qw[0] end def OpenKey(hkey, name, opt, desired) result = packdw(0) check RegOpenKeyExA.call(hkey, name, opt, desired, result) unpackdw(result) end def CreateKey(hkey, name, opt, desired) result = packdw(0) disp = packdw(0) check RegCreateKeyExA.call(hkey, name, 0, 0, opt, desired, 0, result, disp) [ unpackdw(result), unpackdw(disp) ] end def EnumValue(hkey, index) name = ' ' * Constants::MAX_KEY_LENGTH size = packdw(Constants::MAX_KEY_LENGTH) check RegEnumValueA.call(hkey, index, name, size, 0, 0, 0, 0) name[0, unpackdw(size)] end def EnumKey(hkey, index) name = ' ' * Constants::MAX_KEY_LENGTH size = packdw(Constants::MAX_KEY_LENGTH) wtime = ' ' * 8 check RegEnumKeyExA.call(hkey, index, name, size, 0, 0, 0, wtime) [ name[0, unpackdw(size)], unpackqw(wtime) ] end def QueryValue(hkey, name) type = packdw(0) size = packdw(0) check RegQueryValueExA.call(hkey, name, 0, type, 0, size) data = ' ' * unpackdw(size) check RegQueryValueExA.call(hkey, name, 0, type, data, size) [ unpackdw(type), data[0, unpackdw(size)] ] end def SetValue(hkey, name, type, data, size) check RegSetValueExA.call(hkey, name, 0, type, data, size) end def FlushKey(hkey) check RegFlushKey.call(hkey) end def CloseKey(hkey) check RegCloseKey.call(hkey) end def QueryInfoKey(hkey) subkeys = packdw(0) maxsubkeylen = packdw(0) values = packdw(0) maxvaluenamelen = packdw(0) maxvaluelen = packdw(0) secdescs = packdw(0) wtime = ' ' * 8 check RegQueryInfoKey.call(hkey, 0, 0, 0, subkeys, maxsubkeylen, 0, values, maxvaluenamelen, maxvaluelen, secdescs, wtime) [ unpackdw(subkeys), unpackdw(maxsubkeylen), unpackdw(values), unpackdw(maxvaluenamelen), unpackdw(maxvaluelen), unpackdw(secdescs), unpackqw(wtime) ] end end def self.expand_environ(str) str.gsub(/%([^%]+)%/) { ENV[$1] || $& } end @@type2name = { } %w[ REG_NONE REG_SZ REG_EXPAND_SZ REG_BINARY REG_DWORD REG_DWORD_BIG_ENDIAN REG_LINK REG_MULTI_SZ REG_RESOURCE_LIST REG_FULL_RESOURCE_DESCRIPTOR REG_RESOURCE_REQUIREMENTS_LIST REG_QWORD ].each do |type| @@type2name[Constants.const_get(type)] = type end def self.type2name(type) @@type2name[type] || type.to_s end def self.wtime2time(wtime) Time.at((wtime - 116444736000000000) / 10000000) end def self.time2wtime(time) time.to_i * 10000000 + 116444736000000000 end private_class_method :new def self.open(hkey, subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED) subkey = subkey.chomp('\\\\') begin newkey = API.OpenKey(hkey.hkey, subkey, opt, desired) rescue Error return nil end obj = new(newkey, hkey, subkey, REG_OPENED_EXISTING_KEY) if block_given? begin yield obj ensure obj.close end else obj end end def self.create(hkey, subkey, desired = KEY_ALL_ACCESS, opt = 0x0000) newkey, disp = API.CreateKey(hkey.hkey, subkey, opt, desired) obj = new(newkey, hkey, subkey, disp) if block_given? begin yield obj ensure obj.close end else obj end end @@final = proc { |hkey| proc { API.CloseKey(hkey[0]) if hkey[0] } } def initialize(hkey, parent, keyname, disposition) @hkey = hkey @parent = parent @keyname = keyname @disposition = disposition @hkeyfinal = [ hkey ] ObjectSpace.define_finalizer self, @@final.call(@hkeyfinal) end attr_reader :hkey, :parent, :keyname, :disposition def created? @disposition == REG_CREATED_NEW_KEY end def open? !@hkey.nil? end def name parent = self name = @keyname while parent = parent.parent name = parent.keyname + '\\\\' + name end name end def inspect "\\#<Win32::Registry key=#{name.inspect}>" end def _dump(depth) raise TypeError, "can't dump Win32::Registry" end def open(subkey, desired = KEY_READ, opt = REG_OPTION_RESERVED, &blk) self.class.open(self, subkey, desired, opt, &blk) end def create(subkey, desired = KEY_ALL_ACCESS, opt = REG_OPTION_RESERVED, &blk) self.class.create(self, subkey, desired, opt, &blk) end def close API.CloseKey(@hkey) @hkey = @parent = @keyname = nil @hkeyfinal[0] = nil end def each_value index = 0 while true begin subkey = API.EnumValue(@hkey, index) rescue Error break end begin type, data = read(subkey) rescue Error next end yield subkey, type, data index += 1 end index end alias each each_value def each_key index = 0 while true begin subkey, wtime = API.EnumKey(@hkey, index) rescue Error break end yield subkey, wtime index += 1 end index end def keys keys_ary = [] each_key { |key,| keys_ary << key } keys_ary end def read(name, *rtype) type, data = API.QueryValue(@hkey, name) unless rtype.empty? or rtype.include?(type) string = "Type mismatch (expect #{rtype.inspect} but #{type} present)" raise TypeError, string end case type when REG_SZ, REG_EXPAND_SZ [ type, data.chop ] when REG_MULTI_SZ [ type, data.split(/\\0/) ] when REG_BINARY [ type, data ] when REG_DWORD [ type, API.unpackdw(data) ] when REG_DWORD_BIG_ENDIAN [ type, data.unpack('N')[0] ] when REG_QWORD [ type, API.unpackqw(data) ] else raise TypeError, "Type #{type} is not supported." end end def [](name, *rtype) type, data = read(name, *rtype) case type when REG_SZ, REG_DWORD, REG_QWORD, REG_MULTI_SZ data when REG_EXPAND_SZ Registry.expand_environ(data) else raise TypeError, "Type #{type} is not supported." end end def read_s(name) read(name, REG_SZ)[1] end def read_s_expand(name) type, data = read(name, REG_SZ, REG_EXPAND_SZ) if type == REG_EXPAND_SZ Registry.expand_environ(data) else data end end def read_i(name) read(name, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD)[1] end def read_bin(name) read(name, REG_BINARY)[1] end def write(name, type, data) case type when REG_SZ, REG_EXPAND_SZ data = data.to_s + "\\0" when REG_MULTI_SZ data = data.to_a.join("\\0") + "\\0\\0" when REG_BINARY data = data.to_s when REG_DWORD data = API.packdw(data.to_i) when REG_DWORD_BIG_ENDIAN data = [data.to_i].pack('N') when REG_QWORD data = API.packqw(data.to_i) else raise TypeError, "Unsupported type #{type}" end API.SetValue(@hkey, name, type, data, data.length) end def []=(name, rtype, value = nil) if value write name, rtype, value else case value = rtype when Integer write name, REG_DWORD, value when String write name, REG_SZ, value when Array write name, REG_MULTI_SZ, value else raise TypeError, "Unexpected type #{value.class}" end end value end def write_s(name, value) write name, REG_SZ, value.to_s end def write_i(name, value) write name, REG_DWORD, value.to_i end def write_bin(name, value) write name, REG_BINARY, value.to_s end def flush API.FlushKey @hkey end def info API.QueryInfoKey(@hkey) end %w[ num_keys max_key_length num_values max_value_name_length max_value_length descriptor_length wtime ].each_with_index do |s, i| eval <<-__END__ def #{s} info[#{i}] end __END__ end end end def getExistingPath(file,extensions=[]) return file if FileTest.exist?(file) if extensions for ext in extensions fullfile=file+ext return fullfile if FileTest.exist?(fullfile) end end return nil end def rtpGetDirectory(key,rtpname) rtp=Win32API.GetPrivateProfileString("Game",rtpname) return nil if !rtp || rtp=="" begin path=key.read_s(rtp) if path && path!="" return path end return nil rescue return nil end end def rtpGetPathHelper(key,rtpname,file,extensions) path=rtpGetDirectory(key,rtpname) return path ? getExistingPath(path+"\\\\"+file,extensions) : nil end def chdirRTP(rtpname) Win32::Registry.open( Win32::Registry::HKEY_LOCAL_MACHINE,"SOFTWARE\\\\Enterbrain\\\\RGSS\\\\RTP"){|key| path=rtpGetDirectory(key,rtpname) if path && path!="" if block_given? Dir.chdir(path){ yield } else Dir.chdir(path) end end } end def rtpGetPath(file,extensions=[]) path=getExistingPath(file,extensions) if !path Win32::Registry.open( Win32::Registry::HKEY_LOCAL_MACHINE,"SOFTWARE\\\\Enterbrain\\\\RGSS\\\\RTP"){|key| path=rtpGetPathHelper(key,"RTP1",file,extensions) path=rtpGetPathHelper(key,"RTP2",file,extensions) if !path path=rtpGetPathHelper(key,"RTP3",file,extensions) if !path } end return path end def getPlayMusic begin ret=true Win32::Registry.open( Win32::Registry::HKEY_CURRENT_USER,"SOFTWARE\\\\Enterbrain\\\\RGSS"){|key| ret=(key["PlayMusic"] == 1) } return ret rescue return true end end def getPlaySound begin ret=true Win32::Registry.open( Win32::Registry::HKEY_CURRENT_USER,"SOFTWARE\\\\Enterbrain\\\\RGSS"){|key| ret=(key["PlaySound"] == 1) } return ret rescue p $!.message,$!.class.name return true end end def getButtonAssign begin Win32::Registry.open( Win32::Registry::HKEY_CURRENT_USER,"SOFTWARE\\\\Enterbrain\\\\RGSS"){|key| return key.read_bin("ButtonAssign") } rescue p $!.message,$!.class.name return nil end end module FileTest Image_ext = ['.bmp', '.png', '.jpg', '.jpeg'] Audio_ext = ['.mp3', '.mid', '.midi', '.ogg', '.wav', '.wma'] def self.audio_exist?(filename) return !rtpGetPath(filename,Audio_ext).nil? end def self.image_exist?(filename) return !rtpGetPath(filename,Image_ext).nil? end end[/CODE] [CODE]#31931740 # # stringio.rb # # Copyright (c) 1999-2003 Minero Aoki <aamine@loveruby.net> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # # Id: stringio.rb,v 1.10 2003/04/27 22:02:14 aamine Exp # class StringInput#:nodoc: include Enumerable class << self def new( str ) if block_given? begin f = super yield f ensure f.close if f end else super end end alias open new end def initialize( str ) @src = str @pos = 0 @closed = false @lineno = 0 end attr_reader :lineno def string @src end def inspect "#<#{self.class}:#{@closed ? 'closed' : 'open'},src=#{@src[0,30].inspect}>" end def close stream_check! @pos = nil @closed = true end def closed? @closed end def pos stream_check! [@pos, @src.size].min end alias tell pos def seek( offset, whence = IO::SEEK_SET ) stream_check! case whence when IO::SEEK_SET @pos = offset when IO::SEEK_CUR @pos += offset when IO::SEEK_END @pos = @src.size - offset else raise ArgumentError, "unknown seek flag: #{whence}" end @pos = 0 if @pos < 0 @pos = [@pos, @src.size + 1].min offset end def rewind stream_check! @pos = 0 end def eof? stream_check! @pos > @src.size end def each( &block ) stream_check! begin @src.each(&block) ensure @pos = 0 end end def gets stream_check! if idx = @src.index(?\\n, @pos) idx += 1 # "\\n".size line = @src[ @pos ... idx ] @pos = idx @pos += 1 if @pos == @src.size else line = @src[ @pos .. -1 ] @pos = @src.size + 1 end @lineno += 1 line end def getc stream_check! ch = @src[@pos] @pos += 1 @pos += 1 if @pos == @src.size ch end def read( len = nil ) stream_check! return read_all unless len str = @src[@pos, len] @pos += len @pos += 1 if @pos == @src.size str end alias sysread read def read_all stream_check! return nil if eof? rest = @src[@pos ... @src.size] @pos = @src.size + 1 rest end def stream_check! @closed and raise IOError, 'closed stream' end end class StringOutput#:nodoc: class << self def new( str = '' ) if block_given? begin f = super yield f ensure f.close if f end else super end end alias open new end def initialize( str = '' ) @dest = str @closed = false end def close @closed = true end def closed? @closed end def string @dest end alias value string alias to_str string def size @dest.size end alias pos size def inspect "#<#{self.class}:#{@dest ? 'open' : 'closed'},#{id}>" end def print( *args ) stream_check! raise ArgumentError, 'wrong # of argument (0 for >1)' if args.empty? args.each do |s| raise ArgumentError, 'nil not allowed' if s.nil? @dest << s.to_s end nil end def puts( *args ) stream_check! args.each do |str| @dest << (s = str.to_s) @dest << "\\n" unless s[-1] == ?\\n end @dest << "\\n" if args.empty? nil end def putc( ch ) stream_check! @dest << ch.chr nil end def printf( *args ) stream_check! @dest << sprintf(*args) nil end def write( str ) stream_check! s = str.to_s @dest << s s.size end alias syswrite write def <<( str ) stream_check! @dest << str.to_s self end private def stream_check! @closed and raise IOError, 'closed stream' end end [/CODE] [CODE]#---------------------------------------- # # Overriding Sprite, Viewport, and Plane to support resizing # By Peter O. # #---------------------------------------- module Graphics ## Nominal screen size @@width=480 @@height=320 ############## def self.width return @@width.to_i end def self.height return @@height.to_i end @@fadeoutvp=Viewport.new(0,0,640,480) @@fadeoutvp.z=0x3FFFFFFF @@fadeoutvp.color=Color.new(0,0,0,0) def self.brightness return (255-@@fadeoutvp.color.alpha) end def self.brightness=(value) value=0 if value<0 value=255 if value>255 @@fadeoutvp.color.alpha=255-value end def self.fadein(frames) return if frames<=0 curvalue=self.brightness count=(255-self.brightness) frames.times do |i| self.brightness=curvalue+(count*i/frames) self.update end end def self.wait(frames) return if frames<=0 frames.times do |i| self.update end end def self.fadeout(frames) return if frames<=0 curvalue=self.brightness count=self.brightness frames.times do |i| self.brightness=curvalue-(count*i/frames) self.update end end class << self begin x=@@haveresizescreen rescue NameError # If exception is caught, # the class variable wasn't defined yet if !method_defined?(:oldresizescreen) begin alias oldresizescreen resize_screen @@haveresizescreen=true rescue @@haveresizescreen=false end else @@haveresizescreen=false end end def haveresizescreen @@haveresizescreen end end def self.resize_screen(w,h) @@width=w @@height=h pbSetResizeFactor($ResizeFactor) end @@deletefailed=false def self.snap_to_bitmap if FileTest.exist?("./tempscreen.bmp") && @@deletefailed begin File.delete("./tempscreen.bmp") @@deletefailed=false rescue Errno::EACCES @@deletefailed=true return nil end end if FileTest.exist?("./rubyscreen.dll") takescreen=Win32API.new("rubyscreen.dll","TakeScreenshot","%w(p)","i") takescreen.call("./tempscreen.bmp") end bm=nil if FileTest.exist?("./tempscreen.bmp") bm=Bitmap.new("./tempscreen.bmp") begin File.delete("./tempscreen.bmp") @@deletefailed=false rescue Errno::EACCES @@deletefailed=true end end if bm && $ResizeOffsetX && $ResizeOffsetY && $ResizeOffsetX!=0 || $ResizeOffsetY!=0 tmpbitmap=Bitmap.new( Graphics.width*$ResizeFactor, Graphics.height*$ResizeFactor) tmpbitmap.blt(0,0,bm, Rect.new($ResizeOffsetX*$ResizeFactor, $ResizeOffsetY*$ResizeFactor, tmpbitmap.width,tmpbitmap.height)) bm.dispose bm=tmpbitmap end if bm && (bm.width<Graphics.width || bm.height<Graphics.height) newbitmap=Bitmap.new(Graphics.width,Graphics.height) newbitmap.stretch_blt(newbitmap.rect, bm,Rect.new(0,0,bm.width,bm.height)) bm.dispose bm=newbitmap end return bm end end $ResizeFactor=1.0 $ResizeFactorMul=100 $ResizeOffsetX=0 $ResizeOffsetY=0 def pbSetResizeFactor(factor) if $ResizeFactor!=factor $ResizeFactor=factor $ResizeFactorMul=(factor*100).to_i ObjectSpace.each_object(Sprite){|o| next if o.disposed? o.x=o.x o.y=o.y o.ox=o.ox o.oy=o.oy o.zoom_x=o.zoom_x o.zoom_y=o.zoom_y } ObjectSpace.each_object(Viewport){|o| begin o.rect=o.rect o.ox=o.ox o.oy=o.oy rescue RGSSError end } ObjectSpace.each_object(Plane){|o| next if o.disposed? o.zoom_x=o.zoom_x o.zoom_y=o.zoom_y } end if $ResizeBorder $ResizeBorder.refresh end begin if Graphics.haveresizescreen Graphics.oldresizescreen( (Graphics.width+$ResizeOffsetX*2)*factor, (Graphics.height+$ResizeOffsetY*2)*factor ) end Win32API.SetWindowPos( (Graphics.width+$ResizeOffsetX*2)*factor, (Graphics.height+$ResizeOffsetY*2)*factor ) rescue end end class Sprite unless @SpriteResizerMethodsAliased alias _initialize_SpriteResizer initialize alias _x_SpriteResizer x alias _y_SpriteResizer y alias _ox_SpriteResizer ox alias _oy_SpriteResizer oy alias _zoomx_SpriteResizer zoom_x alias _zoomy_SpriteResizer zoom_y alias _xeq_SpriteResizer x= alias _yeq_SpriteResizer y= alias _zoomxeq_SpriteResizer zoom_x= alias _zoomyeq_SpriteResizer zoom_y= alias _oxeq_SpriteResizer ox= alias _oyeq_SpriteResizer oy= alias _bushdeptheq_SpriteResizer bush_depth= @SpriteResizerMethodsAliased=true end def initialize(viewport=nil) _initialize_SpriteResizer(viewport) @resizedX=0 @resizedY=0 @resizedOx=0 @resizedOy=0 @resizedBushDepth=0 @resizedZoomX=1.0 @resizedZoomY=1.0 if $ResizeOffsetX!=0 && $ResizeOffsetY!=0 && !viewport _xeq_SpriteResizer($ResizeOffsetX*$ResizeFactorMul/100) _yeq_SpriteResizer($ResizeOffsetY*$ResizeFactorMul/100) end _zoomxeq_SpriteResizer(@resizedZoomX*$ResizeFactorMul/100) _zoomyeq_SpriteResizer(@resizedZoomY*$ResizeFactorMul/100) end def zoom_x return @resizedZoomX end def zoom_x=(val) value=val if $ResizeFactorMul!=100 value=(val.to_f*$ResizeFactorMul/100) if (value-0.50).abs<=0.001 value=0.50 end if (value-1.00).abs<=0.001 value=1.00 end end _zoomxeq_SpriteResizer(value) @resizedZoomX=val end def zoom_y return @resizedZoomY end def zoom_y=(val) value=val if $ResizeFactorMul!=100 value=(val.to_f*$ResizeFactorMul/100) if (value-0.50).abs<=0.001 value=0.50 end if (value-1.00).abs<=0.001 value=1.00 end end _zoomyeq_SpriteResizer(value) @resizedZoomY=val end def x return @resizedX end def x=(val) if $ResizeFactorMul!=100 offset=(self.viewport) ? 0 : $ResizeOffsetX value=((val.to_i+offset)*$ResizeFactorMul/100) _xeq_SpriteResizer(value.to_i) @resizedX=val.to_i elsif self.viewport _xeq_SpriteResizer(val) @resizedX=val else _xeq_SpriteResizer(val + $ResizeOffsetX) @resizedX=val end end def y return @resizedY end def bush_depth=(val) value=((val.to_i)*$ResizeFactorMul/100) _bushdeptheq_SpriteResizer(value.to_i) @resizedBushDepth=val.to_i end def bush_depth return @resizedBushDepth end def y=(val) if $ResizeFactorMul!=100 offset=(self.viewport) ? 0 : $ResizeOffsetY value=((val.to_i+offset)*$ResizeFactorMul/100) _yeq_SpriteResizer(value.to_i) @resizedY=val.to_i elsif self.viewport _yeq_SpriteResizer(val) @resizedY=val else _yeq_SpriteResizer(val + $ResizeOffsetY) @resizedY=val end end def ox=(val) if $ResizeFactor!=1.0 val=(val*$ResizeFactor).to_i val=(val/$ResizeFactor).to_i end @resizedOx=val _oxeq_SpriteResizer(val) end def oy=(val) if $ResizeFactor!=1.0 val=(val*$ResizeFactor).to_i val=(val/$ResizeFactor).to_i end @resizedOy=val _oyeq_SpriteResizer(val) end def ox return @resizedOx end def oy return @resizedOy end end class NotifiableRect < Rect def setNotifyProc(proc) @notifyProc=proc end def set(x,y,width,height) super @notifyProc.call(self) if @notifyProc end def x=(value) super @notifyProc.call(self) if @notifyProc end def y=(value) super @notifyProc.call(self) if @notifyProc end def width=(value) super @notifyProc.call(self) if @notifyProc end def height=(value) super @notifyProc.call(self) if @notifyProc end end class Viewport unless @SpriteResizerMethodsAliased alias _initialize_SpriteResizer initialize alias _rect_ViewportResizer rect alias _recteq_SpriteResizer rect= alias _oxeq_SpriteResizer ox= alias _oyeq_SpriteResizer oy= @SpriteResizerMethodsAliased=true end def initialize(*arg) args=arg.clone @oldrect=Rect.new(0,0,100,100) _initialize_SpriteResizer( @oldrect ) newRect=NotifiableRect.new(0,0,0,0) @resizedRectProc=Proc.new {|r| if $ResizeFactorMul==100 @oldrect.set( r.x.to_i+$ResizeOffsetX, r.y.to_i+$ResizeOffsetY, r.width.to_i, r.height.to_i ) self._recteq_SpriteResizer(@oldrect) else @oldrect.set( ((r.x+$ResizeOffsetX)*$ResizeFactorMul/100).to_i, ((r.y+$ResizeOffsetY)*$ResizeFactorMul/100).to_i, (r.width*$ResizeFactorMul/100).to_i, (r.height*$ResizeFactorMul/100).to_i ) self._recteq_SpriteResizer(@oldrect) end } newRect.setNotifyProc(@resizedRectProc) if arg.length==1 newRect.set( args[0].x,args[0].y,args[0].width,args[0].height) else newRect.set( args[0],args[1],args[2],args[3]) end @resizedRect=newRect @resizedOx=0 @resizedOy=0 end def ox return @resizedOx end def ox=(val) return if !val _oxeq_SpriteResizer((val*$ResizeFactorMul/100).to_i.to_f) @resizedOx=val end def oy return @resizedOy end def oy=(val) return if !val _oyeq_SpriteResizer((val*$ResizeFactorMul/100).to_i.to_f) @resizedOy=val end def rect return @resizedRect end def rect=(val) if val newRect=NotifiableRect.new(0,0,100,100) newRect.setNotifyProc(@resizedRectProc) newRect.set(val.x.to_i,val.y.to_i,val.width.to_i,val.height.to_i) @resizedRect=newRect end end end class Plane unless @SpriteResizerMethodsAliased alias _initialize_SpriteResizer initialize alias _zoomxeq_SpriteResizer zoom_x= alias _zoomyeq_SpriteResizer zoom_y= alias _oxeq_SpriteResizer ox= alias _oyeq_SpriteResizer oy= @SpriteResizerMethodsAliased=true end def initialize(viewport=nil) _initialize_SpriteResizer(viewport) @resizedZoomX=1.0 @resizedZoomY=1.0 @resizedOx=0 @resizedOy=0 _zoomxeq_SpriteResizer(@resizedZoomX*$ResizeFactorMul/100) _zoomyeq_SpriteResizer(@resizedZoomY*$ResizeFactorMul/100) end def ox return @resizedOx end def ox=(val) return if !val _oxeq_SpriteResizer(val*$ResizeFactorMul/100) @resizedOx=val end def oy return @resizedOy end def oy=(val) return if !val _oyeq_SpriteResizer(val*$ResizeFactorMul/100) @resizedOy=val end def zoom_x return @resizedZoomX end def zoom_x=(val) return if !val _zoomxeq_SpriteResizer(val*$ResizeFactorMul/100) @resizedZoomX=val end def zoom_y return @resizedZoomY end def zoom_y=(val) return if !val _zoomyeq_SpriteResizer(val*$ResizeFactorMul/100) @resizedZoomY=val end end ################### class ScreenBorder def initialize @maximumZ=500000 @bordername="" @sprite=Sprite.new @sprite.z=@maximumZ @defaultwidth=640 @defaultheight=480 @defaultbitmap=Bitmap.new(@defaultwidth,@defaultheight) refresh end def dispose @borderbitmap.dispose if @borderbitmap @defaultbitmap.dispose @sprite.dispose end def adjustZ(z) if z>=@maximumZ @maximumZ=z+1 @sprite.z=@maximumZ end end def bordername=(value) @bordername=value refresh end def refresh @sprite.x=-$ResizeOffsetX @sprite.y=-$ResizeOffsetY @sprite.visible=($ResizeOffsetX>0 && $ResizeOffsetY>0) @sprite.bitmap=nil if @sprite.visible if @bordername!=nil && @bordername!="" @borderbitmap.dispose if @borderbitmap @borderbitmap=RPG::Cache.picture(@bordername) @sprite.bitmap=@borderbitmap else @sprite.bitmap=@defaultbitmap end end @defaultbitmap.clear @defaultbitmap.fill_rect(0,0,@defaultwidth,$ResizeOffsetY,Color.new(0,0,0)) @defaultbitmap.fill_rect(0,0,$ResizeOffsetX,@defaultheight,Color.new(0,0,0)) @defaultbitmap.fill_rect(@defaultwidth-$ResizeOffsetX,0, $ResizeOffsetX,@defaultheight,Color.new(0,0,0)) @defaultbitmap.fill_rect(0,@defaultheight-$ResizeOffsetY, @defaultwidth,$ResizeOffsetY,Color.new(0,0,0)) end end $ResizeBorder=ScreenBorder.new def setScreenBorderName(border) if $ResizeBorder $ResizeBorder.bordername=border end end [/CODE] [CODE]class WindowCursorRect < Rect def initialize(window) @window=window @x=0 @y=0 @width=0 @height=0 end attr_reader :x,:y,:width,:height def empty needupdate=@x!=0 || @y!=0 || @width!=0 || @height!=0 if needupdate @x=0 @y=0 @width=0 @height=0 @window.width=@window.width end end def isEmpty? return @x==0 && @y==0 && @width==0 && @height==0 end def set(x,y,width,height) needupdate=@x!=x || @y!=y || @width!=width || @height!=height if needupdate @x=x @y=y @width=width @height=height @window.width=@window.width end end def height=(value) @height=value; @window.width=@window.width end def width=(value) @width=value; @window.width=@window.width end def x=(value) @x=value; @window.width=@window.width end def y=(value) @y=value; @window.width=@window.width end end class Window attr_reader :tone attr_reader :color attr_reader :blend_type attr_reader :contents_blend_type attr_reader :viewport attr_reader :contents attr_reader :ox attr_reader :oy attr_reader :x attr_reader :y attr_reader :z attr_reader :width attr_reader :active attr_reader :pause attr_reader :height attr_reader :opacity attr_reader :back_opacity attr_reader :contents_opacity attr_reader :visible attr_reader :cursor_rect attr_reader :openness attr_reader :stretch def windowskin @_windowskin end def initialize(viewport=nil) @sprites={} @spritekeys=[ "back", "corner0","side0","scroll0", "corner1","side1","scroll1", "corner2","side2","scroll2", "corner3","side3","scroll3", "cursor","contents","pause" ] @sidebitmaps=[nil,nil,nil,nil] @cursorbitmap=nil @bgbitmap=nil @viewport=viewport for i in @spritekeys @sprites[i]=Sprite.new(@viewport) end @disposed=false @tone=Tone.new(0,0,0) @color=Color.new(0,0,0,0) @blankcontents=Bitmap.new(1,1) # RGSS2 requires this @contents=@blankcontents @_windowskin=nil @rpgvx=false # Set to true to emulate RPGVX windows @x=0 @y=0 @width=0 @openness=255 @height=0 @ox=0 @oy=0 @z=0 @stretch=true @visible=true @active=true @blend_type=0 @contents_blend_type=0 @opacity=255 @back_opacity=255 @contents_opacity=255 @cursor_rect=WindowCursorRect.new(self) @cursorblink=0 @cursoropacity=255 @pause=false @pauseopacity=255 @pauseframe=0 privRefresh(true) end def dispose if !self.disposed? for i in @sprites i[1].dispose if i[1] @sprites[i[0]]=nil end for i in 0...@sidebitmaps.length @sidebitmaps[i].dispose if @sidebitmaps[i] @sidebitmaps[i]=nil end @blankcontents.dispose @cursorbitmap.dispose if @cursorbitmap @backbitmap.dispose if @backbitmap @sprites.clear @sidebitmaps.clear @_windowskin=nil @_contents=nil @disposed=true end end def openness=(value) @openness=value @openness=0 if @openness<0 @openness=255 if @openness>255 privRefresh end def stretch=(value) @stretch=value privRefresh(true) end def visible=(value) @visible=value privRefresh end def viewport=(value) @viewport=value for i in @spritekeys @sprites[i].dispose if @sprites[i].is_a?(Sprite) @sprites[i]=Sprite.new(@viewport) else @sprites[i]=nil end end privRefresh(true) end def z=(value) @z=value privRefresh end def disposed? return @disposed end def contents=(value) @contents=value privRefresh end def windowskin=(value) @_windowskin=value if value && value.is_a?(Bitmap) && !value.disposed? && value.width==128 @rpgvx=true else @rpgvx=false end privRefresh(true) end def ox=(value) @ox=value privRefresh end def active=(value) @active=value privRefresh(true) end def cursor_rect=(value) if !value @cursor_rect.empty else @cursor_rect.set(value.x,value.y,value.width,value.height) end end def oy=(value) @oy=value privRefresh end def width=(value) @width=value privRefresh(true) end def height=(value) @height=value privRefresh(true) end def pause=(value) @pause=value @pauseopacity=0 if !value privRefresh end def x=(value) @x=value privRefresh end def y=(value) @y=value privRefresh end def opacity=(value) @opacity=value @opacity=0 if @opacity<0 @opacity=255 if @opacity>255 privRefresh end def back_opacity=(value) @back_opacity=value @back_opacity=0 if @back_opacity<0 @back_opacity=255 if @back_opacity>255 privRefresh end def contents_opacity=(value) @contents_opacity=value @contents_opacity=0 if @contents_opacity<0 @contents_opacity=255 if @contents_opacity>255 privRefresh end def tone=(value) @tone=value privRefresh end def color=(value) @color=value privRefresh end def blend_type=(value) @blend_type=value privRefresh end def flash(color,duration) return if disposed? for i in @sprites i[1].flash(color,duration) end end def update return if disposed? mustchange=false if @active if @cursorblink==0 @cursoropacity-=8 @cursorblink=1 if @cursoropacity<=128 else @cursoropacity+=8 @cursorblink=0 if @cursoropacity>=255 end mustchange=true if !@cursor_rect.isEmpty? else mustchange=true if @cursoropacity!=128 @cursoropacity=128 end if @pause @pauseframe=(Graphics.frame_count / 8) % 4 @pauseopacity=[@pauseopacity+64,255].min mustchange=true end privRefresh if mustchange for i in @sprites i[1].update end end private def ensureBitmap(bitmap,dwidth,dheight) if !bitmap||bitmap.disposed?||bitmap.width<dwidth||bitmap.height<dheight bitmap.dispose if bitmap bitmap=Bitmap.new([1,dwidth].max,[1,dheight].max) end return bitmap end def tileBitmap(dstbitmap,dstrect,srcbitmap,srcrect) return if !srcbitmap || srcbitmap.disposed? left=dstrect.x top=dstrect.y y=0;loop do break unless y<dstrect.height x=0;loop do break unless x<dstrect.width dstbitmap.blt(x+left,y+top,srcbitmap,srcrect) x+=srcrect.width end y+=srcrect.height end end def privRefresh(changeBitmap=false) return if self.disposed? backopac=self.back_opacity*self.opacity/255 contopac=self.contents_opacity cursoropac=@cursoropacity*contopac/255 for i in 0...4 @sprites["corner#{i}"].bitmap=@_windowskin @sprites["scroll#{i}"].bitmap=@_windowskin end @sprites["pause"].bitmap=@_windowskin @sprites["contents"].bitmap=@contents if @_windowskin && !@_windowskin.disposed? for i in 0...4 @sprites["corner#{i}"].opacity=@opacity @sprites["corner#{i}"].tone=@tone @sprites["corner#{i}"].color=@color @sprites["corner#{i}"].blend_type=@blend_type @sprites["corner#{i}"].visible=@visible @sprites["side#{i}"].opacity=@opacity @sprites["side#{i}"].tone=@tone @sprites["side#{i}"].color=@color @sprites["side#{i}"].blend_type=@blend_type @sprites["side#{i}"].visible=@visible @sprites["scroll#{i}"].opacity=@opacity @sprites["scroll#{i}"].tone=@tone @sprites["scroll#{i}"].blend_type=@blend_type @sprites["scroll#{i}"].color=@color @sprites["scroll#{i}"].visible=@visible end for i in ["back","cursor","pause","contents"] @sprites[i].color=@color @sprites[i].tone=@tone @sprites[i].blend_type=@blend_type end @sprites["contents"].blend_type=@contents_blend_type @sprites["back"].opacity=backopac @sprites["contents"].opacity=contopac @sprites["cursor"].opacity=cursoropac @sprites["pause"].opacity=@pauseopacity @sprites["back"].visible=@visible @sprites["contents"].visible=@visible && @openness==255 @sprites["pause"].visible=@visible && @pause @sprites["cursor"].visible=@visible && @openness==255 hascontents=(@contents && !@contents.disposed?) @sprites["scroll0"].visible = @visible && hascontents && @oy > 0 @sprites["scroll1"].visible = @visible && hascontents && @ox > 0 @sprites["scroll2"].visible = @visible && hascontents && (@contents.width - @ox) > @width-32 @sprites["scroll3"].visible = @visible && hascontents && (@contents.height - @oy) > @height-32 else for i in 0...4 @sprites["corner#{i}"].visible=false @sprites["side#{i}"].visible=false @sprites["scroll#{i}"].visible=false end @sprites["contents"].visible=@visible && @openness==255 @sprites["contents"].color=@color @sprites["contents"].tone=@tone @sprites["contents"].blend_type=@contents_blend_type @sprites["contents"].opacity=contopac @sprites["back"].visible=false @sprites["pause"].visible=false @sprites["cursor"].visible=false end for i in @sprites i[1].z=@z end if @rpgvx @sprites["cursor"].z=@z#+1 # For Compatibility @sprites["contents"].z=@z#+2 # For Compatibility @sprites["pause"].z=@z#+2 # For Compatibility else @sprites["cursor"].z=@z+1 # For Compatibility @sprites["contents"].z=@z+2 # For Compatibility @sprites["pause"].z=@z+2 # For Compatibility end if @rpgvx trimX=64 trimY=0 backRect=Rect.new(0,0,64,64) blindsRect=Rect.new(0,64,64,64) else trimX=128 trimY=0 backRect=Rect.new(0,0,128,128) blindsRect=nil end @sprites["corner0"].src_rect.set(trimX,trimY+0,16,16); @sprites["corner1"].src_rect.set(trimX+48,trimY+0,16,16); @sprites["corner2"].src_rect.set(trimX,trimY+48,16,16); @sprites["corner3"].src_rect.set(trimX+48,trimY+48,16,16); @sprites["scroll0"].src_rect.set(trimX+24, trimY+16, 16, 8) # up @sprites["scroll3"].src_rect.set(trimX+24, trimY+40, 16, 8) # down @sprites["scroll1"].src_rect.set(trimX+16, trimY+24, 8, 16) # left @sprites["scroll2"].src_rect.set(trimX+40, trimY+24, 8, 16) # right cursorX=trimX cursorY=trimY+64 sideRects=[ Rect.new(trimX+16,trimY+0,32,16), Rect.new(trimX,trimY+16,16,32), Rect.new(trimX+48,trimY+16,16,32), Rect.new(trimX+16,trimY+48,32,16) ] if @width>32 && @height>32 @sprites["contents"].src_rect.set(@ox,@oy,@width-32,@height-32) else @sprites["contents"].src_rect.set(0,0,0,0) end pauseRects=[ trimX+32,trimY+64, trimX+48,trimY+64, trimX+32,trimY+80, trimX+48,trimY+80, ] pauseWidth=16 pauseHeight=16 @sprites["pause"].src_rect.set( pauseRects[@pauseframe*2], pauseRects[@pauseframe*2+1], pauseWidth,pauseHeight ) @sprites["pause"].x=@x+(@width/2)-(pauseWidth/2) @sprites["pause"].y=@y+@height-16 # 16 refers to skin margin @sprites["contents"].x=@x+16 @sprites["contents"].y=@y+16 @sprites["corner0"].x=@x @sprites["corner0"].y=@y @sprites["corner1"].x=@x+@width-16 @sprites["corner1"].y=@y @sprites["corner2"].x=@x @sprites["corner2"].y=@y+@height-16 @sprites["corner3"].x=@x+@width-16 @sprites["corner3"].y=@y+@height-16 @sprites["side0"].x=@x+16 @sprites["side0"].y=@y @sprites["side1"].x=@x @sprites["side1"].y=@y+16 @sprites["side2"].x=@x+@width-16 @sprites["side2"].y=@y+16 @sprites["side3"].x=@x+16 @sprites["side3"].y=@y+@height-16 @sprites["scroll0"].x = @x+@width / 2 - 8 @sprites["scroll0"].y = @y+8 @sprites["scroll1"].x = @x+8 @sprites["scroll1"].y = @y+@height / 2 - 8 @sprites["scroll2"].x = @x+@width - 16 @sprites["scroll2"].y = @y+@height / 2 - 8 @sprites["scroll3"].x = @x+@width / 2 - 8 @sprites["scroll3"].y = @y+@height - 16 @sprites["back"].x=@x+2 @sprites["back"].y=@y+2 @sprites["cursor"].x=@x+16+@cursor_rect.x @sprites["cursor"].y=@y+16+@cursor_rect.y if changeBitmap && @_windowskin && !@_windowskin.disposed? width=@cursor_rect.width height=@cursor_rect.height if width > 0 && height > 0 cursorrects=[ # sides Rect.new(cursorX+2, cursorY+0, 28, 2), Rect.new(cursorX+0, cursorY+2, 2, 28), Rect.new(cursorX+30, cursorY+2, 2, 28), Rect.new(cursorX+2, cursorY+30, 28, 2), # corners Rect.new(cursorX+0, cursorY+0, 2, 2), Rect.new(cursorX+30, cursorY+0, 2, 2), Rect.new(cursorX+0, cursorY+30, 2, 2), Rect.new(cursorX+30, cursorY+30, 2, 2), # back Rect.new(cursorX+2, cursorY+2, 28, 28) ] margin=2 fullmargin=4 @cursorbitmap = ensureBitmap(@cursorbitmap, width, height) @cursorbitmap.clear @sprites["cursor"].bitmap=@cursorbitmap @sprites["cursor"].src_rect.set(0,0,width,height) rect = Rect.new(margin,margin, width - fullmargin, height - fullmargin) @cursorbitmap.stretch_blt(rect, @_windowskin, cursorrects[8]) @cursorbitmap.blt(0, 0, @_windowskin, cursorrects[4])# top left @cursorbitmap.blt(width-margin, 0, @_windowskin, cursorrects[5]) # top right @cursorbitmap.blt(0, height-margin, @_windowskin, cursorrects[6]) # bottom right @cursorbitmap.blt(width-margin, height-margin, @_windowskin, cursorrects[7]) # bottom left rect = Rect.new(margin, 0, width - fullmargin, margin) @cursorbitmap.stretch_blt(rect, @_windowskin, cursorrects[0]) rect = Rect.new(0, margin, margin, height - fullmargin) @cursorbitmap.stretch_blt(rect, @_windowskin, cursorrects[1]) rect = Rect.new(width - margin, margin, margin, height - fullmargin) @cursorbitmap.stretch_blt(rect, @_windowskin, cursorrects[2]) rect = Rect.new(margin, height-margin, width - fullmargin, margin) @cursorbitmap.stretch_blt(rect, @_windowskin, cursorrects[3]) else @sprites["cursor"].visible=false @sprites["cursor"].src_rect.set(0,0,0,0) end for i in 0..3 dwidth=(i==0||i==3) ? @width-32 : 16 dheight=(i==0||i==3) ? 16 : @height-32 @sidebitmaps[i]=ensureBitmap(@sidebitmaps[i],dwidth,dheight) @sprites["side#{i}"].bitmap=@sidebitmaps[i] @sprites["side#{i}"].src_rect.set(0,0,dwidth,dheight) @sidebitmaps[i].clear if sideRects[i].width>0 && sideRects[i].height>0 @sidebitmaps[i].stretch_blt(@sprites["side#{i}"].src_rect, @_windowskin,sideRects[i]) end end backwidth=@width-4 backheight=@height-4 if backwidth>0 && backheight>0 @backbitmap=ensureBitmap(@backbitmap,backwidth,backheight) @sprites["back"].bitmap=@backbitmap @sprites["back"].src_rect.set(0,0,backwidth,backheight) @backbitmap.clear if @stretch @backbitmap.stretch_blt(@sprites["back"].src_rect,@_windowskin,backRect) else tileBitmap(@backbitmap,@sprites["back"].src_rect,@_windowskin,backRect) end if blindsRect tileBitmap(@backbitmap,@sprites["back"].src_rect,@_windowskin,blindsRect) end else @sprites["back"].visible=false @sprites["back"].src_rect.set(0,0,0,0) end end if @openness!=255 opn=@openness/255.0 for k in @spritekeys sprite=@sprites[k] ratio=(@height<=0) ? 0 : (sprite.y-@y)*1.0/@height sprite.zoom_y=opn sprite.oy=0 sprite.y=(@y+(@height/2.0)+(@height*ratio*opn)-(@height/2*opn)).floor end else for k in @spritekeys sprite=@sprites[k] sprite.zoom_y=1.0 end end i=0 # Ensure Z order for k in @spritekeys sprite=@sprites[k] y=sprite.y sprite.y=i sprite.oy=(sprite.zoom_y<=0) ? 0 : (i-y)/sprite.zoom_y end end end [/CODE] [CODE] class CustomTilemapAutotiles attr_accessor :changed def initialize @changed=true @tiles=[nil,nil,nil,nil,nil,nil,nil] end def []=(i,value) @tiles[i]=value @changed=true end def [](i) return @tiles[i] end end #Console::setup_console class CustomTilemapSprite < Sprite end class CustomTilemap Animated_Autotiles_Frames = 15 Autotiles = [ [ [27, 28, 33, 34], [ 5, 28, 33, 34], [27, 6, 33, 34], [ 5, 6, 33, 34], [27, 28, 33, 12], [ 5, 28, 33, 12], [27, 6, 33, 12], [ 5, 6, 33, 12] ], [ [27, 28, 11, 34], [ 5, 28, 11, 34], [27, 6, 11, 34], [ 5, 6, 11, 34], [27, 28, 11, 12], [ 5, 28, 11, 12], [27, 6, 11, 12], [ 5, 6, 11, 12] ], [ [25, 26, 31, 32], [25, 6, 31, 32], [25, 26, 31, 12], [25, 6, 31, 12], [15, 16, 21, 22], [15, 16, 21, 12], [15, 16, 11, 22], [15, 16, 11, 12] ], [ [29, 30, 35, 36], [29, 30, 11, 36], [ 5, 30, 35, 36], [ 5, 30, 11, 36], [39, 40, 45, 46], [ 5, 40, 45, 46], [39, 6, 45, 46], [ 5, 6, 45, 46] ], [ [25, 30, 31, 36], [15, 16, 45, 46], [13, 14, 19, 20], [13, 14, 19, 12], [17, 18, 23, 24], [17, 18, 11, 24], [41, 42, 47, 48], [ 5, 42, 47, 48] ], [ [37, 38, 43, 44], [37, 6, 43, 44], [13, 18, 19, 24], [13, 14, 43, 44], [37, 42, 43, 48], [17, 18, 47, 48], [13, 18, 43, 48], [ 1, 2, 7, 8] ] ] FlashOpacity=[100,90,80,70,80,90] attr_reader :tileset attr_reader :autotiles attr_reader :map_data attr_accessor :flash_data attr_accessor :priorities attr_reader :visible attr_accessor :ox attr_accessor :oy attr_reader :viewport attr_accessor :tone attr_accessor :color def graphicsHeight return @graphicsHeight end def graphicsWidth return @graphicsWidth end def initialize(viewport) @tileset = nil # Refers to Map Tileset Name @autotiles = CustomTilemapAutotiles.new @map_data = nil # Refers to 3D Array Of Tile Settings @flash_data = nil # Refers to 3D Array of Tile Flashdata @priorities = nil # Refers to Tileset Priorities @visible = true # Refers to Tileset Visibleness @ox = 0 # Bitmap Offsets @oy = 0 # bitmap Offsets @plane = false @haveGraphicsWH=Graphics.width!=nil rescue false if @haveGraphicsWH @graphicsWidth=Graphics.width @graphicsHeight=Graphics.height else @graphicsWidth=640 @graphicsHeight=480 end @tileWidth = Game_Map::TILEWIDTH rescue 32 @tileHeight = Game_Map::TILEHEIGHT rescue 32 @tileSrcWidth = 32 @tileSrcHeight = 32 @diffsizes=(@tileWidth!=@tileSrcWidth)||(@tileHeight!=@tileSrcHeight) @tone=Tone.new(0,0,0,0) @color=Color.new(0,0,0,0) @oldtone=Tone.new(0,0,0,0) @oldcolor=Color.new(0,0,0,0) @selfviewport=Viewport.new(0,0,graphicsWidth,graphicsHeight) @viewport=viewport ? viewport : @selfviewport @tiles=[] @autotileInfo=[] @regularTileInfo=[] @oldOx=0 @oldOy=0 @oldViewportOx=0 @oldViewportOy=0 @layer0=CustomTilemapSprite.new(viewport) @layer0.visible=true @nowshown=false @layer0.bitmap=Bitmap.new([graphicsWidth+320,1].max,[graphicsHeight+320,1].max) @flash=nil @layer0.ox=0 @layer0.oy=0 @oxLayer0=0 @oyLayer0=0 @oxFlash=0 @oyFlash=0 @layer0.z=0 @priotiles=[] @priotilesfast=[] @prioautotiles=[] @autosprites=[] @framecount=[0,0,0,0,0,0,0,0] @tilesetChanged=true @flashChanged=false @firsttime=true @disposed=false @usedsprites=false @layer0clip=true @firsttimeflash=true @fullyrefreshed=false @fullyrefreshedautos=false end def disposed? return @disposed end def flash_data=(value) @flash_data=value @flashChanged=true end def update if @haveGraphicsWH @graphicsWidth=Graphics.width @graphicsHeight=Graphics.height end if @oldtone!=@tone @layer0.tone=@tone @flash.tone=@tone if @flash for sprite in @autosprites sprite.tone=@tone if sprite.is_a?(Sprite) end for sprite in @tiles sprite.tone=@tone if sprite.is_a?(Sprite) end @oldtone=@tone.clone end if @oldcolor!=@color @layer0.color=@color @flash.color=@color if @flash for sprite in @autosprites sprite.color=@color if sprite.is_a?(Sprite) end for sprite in @tiles sprite.color=@color if sprite.is_a?(Sprite) end @oldcolor=@color.clone end if @autotiles.changed refresh_autotiles repaintAutotiles end if @flashChanged refresh_flash end if @tilesetChanged refresh_tileset end if @flash @flash.opacity=FlashOpacity[(Graphics.frame_count/2) % 6] end mustrefresh=!(@oldOx==@ox && @oldOy==@oy && !@tilesetChanged && !@autotiles.changed) if @viewport.ox!=@oldViewportOx || @viewport.oy!=@oldViewportOy mustrefresh=true @oldViewportOx=@viewport.ox @oldViewportOy=@viewport.oy end if mustrefresh refresh end if (Graphics.frame_count % Animated_Autotiles_Frames == 0) || @nowshown repaintAutotiles refresh(true) end @nowshown=false @autotiles.changed=false @tilesetChanged=false end def priorities=(value) @priorities=value @tilesetChanged=true end def tileset=(value) @tileset=value @tilesetChanged=true end def shown? return false if !@visible ysize=@map_data.ysize xsize=@map_data.xsize xStart=(@ox/@tileWidth)-1 xEnd=((@ox+@viewport.rect.width)/@tileWidth)+1 yStart=(@oy/@tileHeight)-1 yEnd=((@oy+@viewport.rect.height)/@tileHeight)+1 xStart=0 if xStart<0 xStart=xsize-1 if xStart>=xsize xEnd=0 if xEnd<0 xEnd=xsize-1 if xEnd>=xsize yStart=0 if yStart<0 yStart=ysize-1 if yStart>=ysize yEnd=0 if yEnd<0 yEnd=ysize-1 if yEnd>=ysize return (xStart<xEnd && yStart<yEnd) end def dispose return if disposed? @help.dispose if @help @help=nil i=0;len=@autotileInfo.length;while i<len if @autotileInfo[i] @autotileInfo[i].dispose @autotileInfo[i]=nil end i+=1 end i=0;len=@regularTileInfo.length;while i<len if @regularTileInfo[i] @regularTileInfo[i].dispose @regularTileInfo[i]=nil end i+=1 end i=0;len=@tiles.length;while i<len @tiles[i].dispose @tiles[i]=nil i+=2 end i=0;len=@autosprites.length;while i<len @autosprites[i].dispose @autosprites[i]=nil i+=2 end if @layer0 @layer0.bitmap.dispose if !@layer0.disposed? @layer0.bitmap=nil if !@layer0.disposed? @layer0.dispose @layer0=nil end if @flash @flash.bitmap.dispose if !@flash.disposed? @flash.bitmap=nil if !@flash.disposed? @flash.dispose @flash=nil end for i in 0...7 self.autotiles[i]=nil end @tiles.clear @autosprites.clear @autotileInfo.clear @regularTileInfo.clear @tilemap=nil @tileset=nil @priorities=nil @selfviewport.dispose @selfviewport=nil @disposed=true end def bltAutotile(bitmap,x,y,id,frame) return if frame<0 autotile=@autotiles[id/48-1] return if !autotile || autotile.disposed? if autotile.height==@tileSrcHeight anim=frame*@tileSrcWidth src_rect=Rect.new(anim,0,@tileSrcWidth,@tileSrcHeight) if @diffsizes bitmap.stretch_blt(Rect.new(x,y,@tileWidth,@tileHeight),autotile,src_rect) else bitmap.blt(x,y,autotile,src_rect) end else anim=frame*3*@tileSrcWidth id%=48 tiles = Autotiles[id>>3][id&7] src=Rect.new(0,0,0,0) halfTileWidth=@tileWidth>>1 halfTileHeight=@tileHeight>>1 halfTileSrcWidth=@tileSrcWidth>>1 halfTileSrcHeight=@tileSrcHeight>>1 for i in 0...4 tile_position = tiles[i] - 1 src.set( (tile_position % 6)*halfTileSrcWidth + anim, (tile_position / 6)*halfTileSrcHeight, halfTileSrcWidth, halfTileSrcHeight) if @diffsizes bitmap.stretch_blt( Rect.new(i%2*halfTileWidth+x,i/2*halfTileHeight+y,halfTileWidth,halfTileHeight), autotile,src) else bitmap.blt(i%2*halfTileWidth+x,i/2*halfTileHeight+y, autotile, src) end end end end def autotileNumFrames(id) autotile=@autotiles[id/48-1] return 0 if !autotile || autotile.disposed? frames=1 if autotile.height==@tileHeight frames=autotile.width/@tileWidth else frames=autotile.width/(3*@tileWidth) end return frames end def autotileFrame(id) autotile=@autotiles[id/48-1] return -1 if !autotile || autotile.disposed? frames=1 if autotile.height==@tileHeight frames=autotile.width/@tileWidth else frames=autotile.width/(3*@tileWidth) end return (Graphics.frame_count/Animated_Autotiles_Frames)%frames end def repaintAutotiles for i in 0...@autotileInfo.length next if !@autotileInfo[i] frame=autotileFrame(i) bltAutotile(@autotileInfo[i],0,0,i,frame) end end def getAutotile(sprite,id) frames=@framecount[id/48-1] if frames<=1 anim=0 else anim=(Graphics.frame_count/Animated_Autotiles_Frames)%frames end return if anim<0 bitmap=@autotileInfo[id] if !bitmap bitmap=Bitmap.new(@tileWidth,@tileHeight) bltAutotile(bitmap,0,0,id,anim) @autotileInfo[id]=bitmap end if sprite.bitmap!=bitmap sprite.bitmap=bitmap end end def getRegularTile(sprite,id) if !@diffsizes if sprite.bitmap!=@tileset sprite.bitmap=@tileset end sprite.src_rect.set(((id - 384)&7)*@tileSrcWidth,((id - 384)>>3)*@tileSrcHeight,@tileSrcWidth,@tileSrcHeight) else bitmap=@regularTileInfo[id] if !bitmap bitmap=Bitmap.new(@tileWidth,@tileHeight) rect=Rect.new(((id - 384)&7)*@tileSrcWidth,((id - 384)>>3)*@tileSrcHeight,@tileSrcWidth,@tileSrcHeight) bitmap.stretch_blt(Rect.new(0,0,@tileWidth,@tileHeight),@tileset,rect) @regularTileInfo[id]=bitmap end if sprite.bitmap!=bitmap sprite.bitmap=bitmap end end end def addTile(tiles,count,xpos,ypos,id) if id>=384 if count>=tiles.length sprite=CustomTilemapSprite.new(@viewport) tiles.push(sprite,0) else sprite=tiles[count] tiles[count+1]=0 end sprite.visible=@visible sprite.x=xpos sprite.y=ypos sprite.tone=@tone sprite.color=@color getRegularTile(sprite,id) spriteZ=(@priorities[id]==0||!@priorities[id]) ? 0 : ypos+@priorities[id]*32+32 sprite.z=spriteZ count+=2 else if count>=tiles.length sprite=CustomTilemapSprite.new(@viewport) tiles.push(sprite,1) else sprite=tiles[count] tiles[count+1]=1 end sprite.visible=@visible sprite.x=xpos sprite.y=ypos sprite.tone=@tone sprite.color=@color getAutotile(sprite,id) spriteZ=(@priorities[id]==0||!@priorities[id]) ? 0 : ypos+@priorities[id]*32+32 sprite.z=spriteZ count+=2 end return count end def refresh_tileset i=0;len=@regularTileInfo.length;while i<len if @regularTileInfo[i] @regularTileInfo[i].dispose @regularTileInfo[i]=nil end i+=1 end @regularTileInfo.clear @priotiles.clear ysize=@map_data.ysize xsize=@map_data.xsize zsize=@map_data.zsize if xsize>100 || ysize>100 @fullyrefreshed=false else for z in 0...zsize for y in 0...ysize for x in 0...xsize id = @map_data[x, y, z] next if id==0 || !@priorities[id] next if @priorities[id]==0 @priotiles.push([x,y,z,id]) end end end @fullyrefreshed=true end end def refresh_flash if @flash_data && !@flash @flash=CustomTilemapSprite.new(viewport) @flash.visible=true @flash.z=1 @flash.tone=tone @flash.color=color @flash.blend_type=1 @flash.bitmap=Bitmap.new([graphicsWidth*2,1].max,[graphicsHeight*2,1].max) @firsttimeflash=true elsif !@flash_data && @flash @flash.bitmap.dispose if @flash.bitmap @flash.dispose @flash=nil @firsttimeflash=false end end def refresh_autotiles i=0;len=@autotileInfo.length;while i<len if @autotileInfo[i] @autotileInfo[i].dispose @autotileInfo[i]=nil end i+=1 end i=0;len=@autosprites.length;while i<len if @autosprites[i] @autosprites[i].dispose @autosprites[i]=nil end i+=2 end @autosprites.clear @autotileInfo.clear @prioautotiles.clear @priorect=nil @priorectautos=nil hasanimated=false for i in 0...7 numframes=autotileNumFrames(48*(i+1)) hasanimated=true if numframes>=2 @framecount[i]=numframes end if hasanimated ysize=@map_data.ysize xsize=@map_data.xsize zsize=@map_data.zsize if xsize>100 || ysize>100 @fullyrefreshedautos=false else for y in 0...ysize for x in 0...xsize haveautotile=false for z in 0...zsize id = @map_data[x, y, z] next if id==0 || id>=384 || @priorities[id]!=0 || !@priorities[id] next if @framecount[id/48-1]<2 haveautotile=true break end @prioautotiles.push([x,y]) if haveautotile end end @fullyrefreshedautos=true end else @fullyrefreshedautos=true end end def map_data=(value) @map_data=value @tilesetChanged=true end def refreshFlashSprite return if !@flash || @flash_data.nil? ptX=@ox-@oxFlash ptY=@oy-@oyFlash if !@firsttimeflash && !@usedsprites && ptX>=0 && ptX+@viewport.rect.width<=@flash.bitmap.width && ptY>=0 && ptY+@viewport.rect.height<=@flash.bitmap.height @flash.ox=0 @flash.oy=0 @flash.src_rect.set(ptX.round,ptY.round, @viewport.rect.width,@viewport.rect.height) return end width=@flash.bitmap.width height=@flash.bitmap.height bitmap=@flash.bitmap ysize=@map_data.ysize xsize=@map_data.xsize zsize=@map_data.zsize @firsttimeflash=false @oxFlash=@ox-(width>>2) @oyFlash=@oy-(height>>2) @flash.ox=0 @flash.oy=0 @flash.src_rect.set(width>>2,height>>2, @viewport.rect.width,@viewport.rect.height) @flash.bitmap.clear @oxFlash=@oxFlash.floor @oyFlash=@oyFlash.floor xStart=(@oxFlash/@tileWidth) xStart=0 if xStart<0 yStart=(@oyFlash/@tileHeight) yStart=0 if yStart<0 xEnd=xStart+(width/@tileWidth)+1 yEnd=yStart+(height/@tileHeight)+1 xEnd=xsize if xEnd>=xsize yEnd=ysize if yEnd>=ysize if xStart<xEnd && yStart<yEnd yrange=yStart...yEnd xrange=xStart...xEnd tmpcolor=Color.new(0,0,0,0) for y in yrange ypos=(y*@tileHeight)-@oyFlash for x in xrange xpos=(x*@tileWidth)-@oxFlash id = @flash_data[x, y, 0] r=(id>>8)&15 g=(id>>4)&15 b=(id)&15 tmpcolor.set(r<<4,g<<4,b<<4) bitmap.fill_rect(xpos,ypos,@tileWidth,@tileHeight,tmpcolor) end end end end def refreshLayer0(autotiles=false) if autotiles return true if !shown? end ptX=@ox-@oxLayer0 ptY=@oy-@oyLayer0 if !autotiles && !@firsttime && !@usedsprites && ptX>=0 && ptX+@viewport.rect.width<=@layer0.bitmap.width && ptY>=0 && ptY+@viewport.rect.height<=@layer0.bitmap.height if @layer0clip @layer0.ox=0 @layer0.oy=0 @layer0.src_rect.set(ptX.round,ptY.round, @viewport.rect.width,@viewport.rect.height) else @layer0.ox=ptX.round @layer0.oy=ptY.round @layer0.src_rect.set(0,0,@layer0.bitmap.width,@layer0.bitmap.height) end return true end width=@layer0.bitmap.width height=@layer0.bitmap.height bitmap=@layer0.bitmap ysize=@map_data.ysize xsize=@map_data.xsize zsize=@map_data.zsize twidth=@tileWidth theight=@tileHeight mapdata=@map_data if autotiles return true if @fullyrefreshedautos && @prioautotiles.length==0 xStart=(@oxLayer0/twidth) xStart=0 if xStart<0 yStart=(@oyLayer0/theight) yStart=0 if yStart<0 xEnd=xStart+(width/twidth)+1 yEnd=yStart+(height/theight)+1 xEnd=xsize if xEnd>xsize yEnd=ysize if yEnd>ysize return true if xStart>=xEnd || yStart>=yEnd trans=Color.new(0,0,0,0) temprect=Rect.new(0,0,0,0) tilerect=Rect.new(0,0,twidth,theight) zrange=0...zsize overallcount=0 count=0 if !@fullyrefreshedautos for y in yStart..yEnd for x in xStart..xEnd haveautotile=false for z in zrange id = mapdata[x, y, z] next if !id || id<48 || id>=384 prioid=@priorities[id] next if prioid!=0 || !prioid fcount=@framecount[id/48-1] next if !fcount || fcount<2 if !haveautotile haveautotile=true overallcount+=1 xpos=(x*twidth)-@oxLayer0 ypos=(y*theight)-@oyLayer0 bitmap.fill_rect(xpos,ypos,twidth,theight,trans) if overallcount<=2000 break end end for z in zrange id = mapdata[x,y,z] next if !id || id<48 prioid=@priorities[id] next if prioid!=0 || !prioid if overallcount>2000 xpos=(x*twidth)-@oxLayer0 ypos=(y*theight)-@oyLayer0 count=addTile(@autosprites,count,xpos,ypos,id) next elsif id>=384 temprect.set(((id - 384)&7)*@tileSrcWidth,((id - 384)>>3)*@tileSrcHeight,@tileSrcWidth,@tileSrcHeight) xpos=(x*twidth)-@oxLayer0 ypos=(y*theight)-@oyLayer0 if @diffsizes bitmap.stretch_blt(Rect.new(xpos,ypos,twidth,theight),@tileset,temprect) else bitmap.blt(xpos,ypos,@tileset,temprect) end else tilebitmap=@autotileInfo[id] if !tilebitmap anim=autotileFrame(id) next if anim<0 tilebitmap=Bitmap.new(twidth,theight) bltAutotile(tilebitmap,0,0,id,anim) @autotileInfo[id]=tilebitmap end xpos=(x*twidth)-@oxLayer0 ypos=(y*theight)-@oyLayer0 bitmap.blt(xpos,ypos,tilebitmap,tilerect) end end end end Graphics.frame_reset else if !@priorect || !@priorectautos || @priorect[0]!=xStart || @priorect[1]!=yStart || @priorect[2]!=xEnd || @priorect[3]!=yEnd @priorectautos=@prioautotiles.find_all{|tile| x=tile[0] y=tile[1] # "next" means "return" here next !(x<xStart||x>xEnd||y<yStart||y>yEnd) } @priorect=[xStart,yStart,xEnd,yEnd] end # echoln ["autos",@priorect,@priorectautos.length,@prioautotiles.length] for tile in @priorectautos x=tile[0] y=tile[1] overallcount+=1 xpos=(x*twidth)-@oxLayer0 ypos=(y*theight)-@oyLayer0 bitmap.fill_rect(xpos,ypos,twidth,theight,trans) z=0 while z<zsize id = mapdata[x,y,z] z+=1 next if !id || id<48 prioid=@priorities[id] next if prioid!=0 || !prioid if id>=384 temprect.set(((id - 384)&7)*@tileSrcWidth,((id - 384)>>3)*@tileSrcHeight,@tileSrcWidth,@tileSrcHeight) if @diffsizes bitmap.stretch_blt(Rect.new(xpos,ypos,twidth,theight),@tileset,temprect) else bitmap.blt(xpos,ypos,@tileset,temprect) end else tilebitmap=@autotileInfo[id] if !tilebitmap anim=autotileFrame(id) next if anim<0 tilebitmap=Bitmap.new(twidth,theight) bltAutotile(tilebitmap,0,0,id,anim) @autotileInfo[id]=tilebitmap end bitmap.blt(xpos,ypos,tilebitmap,tilerect) end end end Graphics.frame_reset if overallcount>500 end @usedsprites=false return true end return false if @usedsprites @firsttime=false @oxLayer0=@ox-(width>>2) @oyLayer0=@oy-(height>>2) if @layer0clip @layer0.ox=0 @layer0.oy=0 @layer0.src_rect.set(width>>2,height>>2, @viewport.rect.width,@viewport.rect.height) else @layer0.ox=(width>>2) @layer0.oy=(height>>2) end @layer0.bitmap.clear @oxLayer0=@oxLayer0.floor @oyLayer0=@oyLayer0.floor xStart=(@oxLayer0/twidth) xStart=0 if xStart<0 yStart=(@oyLayer0/theight) yStart=0 if yStart<0 xEnd=xStart+(width/twidth)+1 yEnd=yStart+(height/theight)+1 xEnd=xsize if xEnd>=xsize yEnd=ysize if yEnd>=ysize if xStart<xEnd && yStart<yEnd tmprect=Rect.new(0,0,0,0) yrange=yStart...yEnd xrange=xStart...xEnd for z in 0...zsize for y in yrange ypos=(y*theight)-@oyLayer0 for x in xrange xpos=(x*twidth)-@oxLayer0 id = mapdata[x, y, z] next if id==0 || @priorities[id]!=0 || !@priorities[id] if id>=384 tmprect.set( ((id - 384)&7)*@tileSrcWidth,((id - 384)>>3)*@tileSrcHeight,@tileSrcWidth,@tileSrcHeight) if @diffsizes bitmap.stretch_blt(Rect.new(xpos,ypos,twidth,theight),@tileset,tmprect) else bitmap.blt(xpos,ypos,@tileset,tmprect) end else frames=@framecount[id/48-1] if frames<=1 frame=0 else frame=(Graphics.frame_count/Animated_Autotiles_Frames)%frames end bltAutotile(bitmap,xpos,ypos,id,frame) end end end end Graphics.frame_reset end return true end def getResizeFactor return $ResizeFactor ? $ResizeFactor : 1.0 end def ox=(val) rf=getResizeFactor if rf!=1.0 val=(val*rf).to_i val=(val/rf).to_i end wasshown=self.shown? @ox=val.floor @nowshown=(!wasshown && self.shown?) end def oy=(val) rf=getResizeFactor if rf!=1.0 val=(val*rf).to_i val=(val/rf).to_i end wasshown=self.shown? @oy=val.floor @nowshown=(!wasshown && self.shown?) end def visible=(val) wasshown=@visible @visible=val @nowshown=(!wasshown && val) end def refresh(autotiles=false) @oldOx=@ox @oldOy=@oy usesprites=false if @layer0 @layer0.visible=@visible usesprites=!refreshLayer0(autotiles) if autotiles && !usesprites return end else usesprites=true end refreshFlashSprite vpx=@viewport.rect.x vpy=@viewport.rect.y vpr=@viewport.rect.width+vpx vpb=@viewport.rect.height+vpy xsize=@map_data.xsize ysize=@map_data.ysize minX=(@ox/@tileWidth)-1 maxX=((@ox+@viewport.rect.width)/@tileWidth)+1 minY=(@oy/@tileHeight)-1 maxY=((@oy+@viewport.rect.height)/@tileHeight)+1 minX=0 if minX<0 minX=xsize-1 if minX>=xsize maxX=0 if maxX<0 maxX=xsize-1 if maxX>=xsize minY=0 if minY<0 minY=ysize-1 if minY>=ysize maxY=0 if maxY<0 maxY=ysize-1 if maxY>=ysize count=0 if minX<maxX && minY<maxY @usedsprites=usesprites || @usedsprites if @layer0 @layer0.visible=false if usesprites end if @fullyrefreshed if !@priotilesrect || !@priotilesfast || @priotilesrect[0]!=minX || @priotilesrect[1]!=minY || @priotilesrect[2]!=maxX || @priotilesrect[3]!=maxY @priotilesfast=@priotiles.find_all{|tile| x=tile[0] y=tile[1] # "next" means "return" here next !(x<minX||x>maxX||y<minY||y>maxY) } @priotilesrect=[minX,minY,maxX,maxY] end # echoln [minX,minY,maxX,maxY,@priotilesfast.length,@priotiles.length] for prio in @priotilesfast xpos=(prio[0]*@tileWidth)-@ox ypos=(prio[1]*@tileHeight)-@oy count=addTile(@tiles,count,xpos,ypos,prio[3]) end else if !@priotilesrect || !@priotilesfast || @priotilesrect[0]!=minX || @priotilesrect[1]!=minY || @priotilesrect[2]!=maxX || @priotilesrect[3]!=maxY @priotilesfast=[] for z in 0...@map_data.zsize for y in minY..maxY for x in minX..maxX id = @map_data[x, y, z] next if id==0 || !@priorities[id] next if @priorities[id]==0 @priotilesfast.push([x,y,z,id]) end end end @priotilesrect=[minX,minY,maxX,maxY] end for prio in @priotilesfast xpos=(prio[0]*@tileWidth)-@ox ypos=(prio[1]*@tileHeight)-@oy count=addTile(@tiles,count,xpos,ypos,prio[3]) end end end if count<@tiles.length bigchange=(count<=(@tiles.length*2/3)) && (@tiles.length*2/3)>25 j=count;len=@tiles.length;while j<len sprite=@tiles[j] @tiles[j+1]=-1 if bigchange sprite.dispose @tiles[j]=nil @tiles[j+1]=nil elsif !@tiles[j].disposed? sprite.visible=false if sprite.visible end j+=2 end @tiles.compact! if bigchange end end end class SynchronizedTilemapAutotilesInternal def initialize(oldat) @atdisposables=[[],[],[],[],[],[],[]] @atframes=[[],[],[],[],[],[],[]] @atframe=[-1,-1,-1,-1,-1,-1,-1] @autotiles=[] @oldat=oldat end def dispose for i in 0...7 for bitmap in @atdisposables[i] bitmap.dispose end @atdisposables[i].clear @atframes[i].clear end end def [](i) return @autotiles[i] end def []=(i,value) for frame in @atdisposables[i] frame.dispose end @atframe[i]=-1 @atframes[i].clear @atdisposables[i].clear if value && !value.disposed? if value.height==32 frames=value.width/32 for j in 0...frames @atdisposables[i][j]=Bitmap.new(32,32) @atdisposables[i][j].blt(0,0,value,Rect.new(j*32,0,32,32)) @atframes[i][j]=@atdisposables[i][j] end elsif value.height==128 frames=value.width/96 for j in 0...frames @atdisposables[i][j]=Bitmap.new(96,128) @atdisposables[i][j].blt(0,0,value,Rect.new(j*96,0,96,128)) @atframes[i][j]=@atdisposables[i][j] end else @atframes[i][0]=value end else @atframes[i][0]=value end @autotiles[i]=value sync end def sync frameused=[] for i in 0...7 frames=[1,@atframes[i].length].max frame=(Graphics.frame_count/15)%frames if frames>1 && @atframe[i]!=frame @oldat[i]=@atframes[i][frame] @atframe[i]=frame end end end end class SynchronizedTilemapAutotiles def initialize(autotiles) @autotiles=autotiles end def [](i) @autotiles[i] end def []=(i,value) @autotiles[i]=value end end class SynchronizedTilemap < Tilemap # This class derives from Tilemap just to synchronize # the tilemap animation. attr_accessor :numupdates def initialize(viewport=nil) super(viewport) @updating=true @autotiles=SynchronizedTilemapAutotilesInternal.new(self.autotiles) @autos=SynchronizedTilemapAutotiles.new(@autotiles) @updating=false end def dispose @autotiles.dispose super end def autotiles if @updating super else return @autos end end def update return if disposed? @autotiles.sync super end end [/CODE] [CODE] class TilemapLoader def initialize(viewport) @viewport=viewport @tilemap=nil @color=Color.new(0,0,0,0) @tone=Tone.new(0,0,0,0) updateClass end def updateClass case $PokemonSystem.tilemap when 1 setClass(CustomTilemap) when 2 setClass(Draw_Tilemap) else if Tilemap.method_defined?(:passages) setClass(CustomTilemap) else setClass($ResizeFactor==1.0 ? SynchronizedTilemap : CustomTilemap) end end end def setClass(cls) newtilemap=cls.new(@viewport) if @tilemap newtilemap.tileset=@tilemap.tileset newtilemap.map_data=@tilemap.map_data newtilemap.flash_data=@tilemap.flash_data newtilemap.priorities=@tilemap.priorities newtilemap.visible=@tilemap.visible newtilemap.ox=@tilemap.ox newtilemap.oy=@tilemap.oy for i in 0...7 newtilemap.autotiles[i]=@tilemap.autotiles[i] end @tilemap.dispose @tilemap=newtilemap newtilemap.update if cls!=SynchronizedTilemap else @tilemap=newtilemap end end def tone @tilemap.tone rescue @tone end def tone=(value) @tilemap.tone=value rescue nil end def disposed? @tilemap && @tilemap.disposed? end def dispose @tilemap.dispose end def update @tilemap.update end def viewport @tilemap.viewport end def autotiles @tilemap.autotiles end def tileset @tilemap.tileset end def tileset=(v) @tilemap.tileset=v end def map_data @tilemap.map_data end def map_data=(v) @tilemap.map_data=v end def flash_data @tilemap.flash_data end def flash_data=(v) @tilemap.flash_data=v end def priorities @tilemap.priorities end def priorities=(v) @tilemap.priorities=v end def visible @tilemap.visible end def visible=(v) @tilemap.visible=v end def ox @tilemap.ox end def ox=(v) @tilemap.ox=v end def oy @tilemap.oy end def oy=(v) @tilemap.oy=v end end [/CODE] [CODE]class TileDrawingHelper Autotiles = [ [ [27, 28, 33, 34], [ 5, 28, 33, 34], [27, 6, 33, 34], [ 5, 6, 33, 34], [27, 28, 33, 12], [ 5, 28, 33, 12], [27, 6, 33, 12], [ 5, 6, 33, 12] ], [ [27, 28, 11, 34], [ 5, 28, 11, 34], [27, 6, 11, 34], [ 5, 6, 11, 34], [27, 28, 11, 12], [ 5, 28, 11, 12], [27, 6, 11, 12], [ 5, 6, 11, 12] ], [ [25, 26, 31, 32], [25, 6, 31, 32], [25, 26, 31, 12], [25, 6, 31, 12], [15, 16, 21, 22], [15, 16, 21, 12], [15, 16, 11, 22], [15, 16, 11, 12] ], [ [29, 30, 35, 36], [29, 30, 11, 36], [ 5, 30, 35, 36], [ 5, 30, 11, 36], [39, 40, 45, 46], [ 5, 40, 45, 46], [39, 6, 45, 46], [ 5, 6, 45, 46] ], [ [25, 30, 31, 36], [15, 16, 45, 46], [13, 14, 19, 20], [13, 14, 19, 12], [17, 18, 23, 24], [17, 18, 11, 24], [41, 42, 47, 48], [ 5, 42, 47, 48] ], [ [37, 38, 43, 44], [37, 6, 43, 44], [13, 18, 19, 24], [13, 14, 43, 44], [37, 42, 43, 48], [17, 18, 47, 48], [13, 18, 43, 48], [ 1, 2, 7, 8] ] ] # converts neighbors returned from tableNeighbors to tile indexes NeighborsToTiles=[ 46, 44, 46, 44, 43, 41, 43, 40, 46, 44, 46, 44, 43, 41, 43, 40, 42, 32, 42, 32, 35, 19, 35, 18, 42, 32, 42, 32, 34, 17, 34, 16, 46, 44, 46, 44, 43, 41, 43, 40, 46, 44, 46, 44, 43, 41, 43, 40, 42, 32, 42, 32, 35, 19, 35, 18, 42, 32, 42, 32, 34, 17, 34, 16, 45, 39, 45, 39, 33, 31, 33, 29, 45, 39, 45, 39, 33, 31, 33, 29, 37, 27, 37, 27, 23, 15, 23, 13, 37, 27, 37, 27, 22, 11, 22, 9, 45, 39, 45, 39, 33, 31, 33, 29, 45, 39, 45, 39, 33, 31, 33, 29, 36, 26, 36, 26, 21, 7, 21, 5, 36, 26, 36, 26, 20, 3, 20, 1, 46, 44, 46, 44, 43, 41, 43, 40, 46, 44, 46, 44, 43, 41, 43, 40, 42, 32, 42, 32, 35, 19, 35, 18, 42, 32, 42, 32, 34, 17, 34, 16, 46, 44, 46, 44, 43, 41, 43, 40, 46, 44, 46, 44, 43, 41, 43, 40, 42, 32, 42, 32, 35, 19, 35, 18, 42, 32, 42, 32, 34, 17, 34, 16, 45, 38, 45, 38, 33, 30, 33, 28, 45, 38, 45, 38, 33, 30, 33, 28, 37, 25, 37, 25, 23, 14, 23, 12, 37, 25, 37, 25, 22, 10, 22, 8, 45, 38, 45, 38, 33, 30, 33, 28, 45, 38, 45, 38, 33, 30, 33, 28, 36, 24, 36, 24, 21, 6, 21, 4, 36, 24, 36, 24, 20, 2, 20, 0 ] def self.tableNeighbors(data,x,y) return 0 if x>=data.xsize || x<0 return 0 if y>=data.ysize || y<0 t=data[x,y] xp1=[x+1,data.xsize-1].min yp1=[y+1,data.ysize-1].min xm1=[x-1,0].max ym1=[y-1,0].max i=0 i|=0x01 if data[x ,ym1]==t # N i|=0x02 if data[xp1,ym1]==t # NE i|=0x04 if data[xp1,y ]==t # E i|=0x08 if data[xp1,yp1]==t # SE i|=0x10 if data[x ,yp1]==t # S i|=0x20 if data[xm1,yp1]==t # SW i|=0x40 if data[xm1,y ]==t # W i|=0x80 if data[xm1,ym1]==t # NW return i end attr_accessor :tileset attr_accessor :autotiles def initialize(tileset,autotiles) @tileset=tileset @autotiles=autotiles end def self.fromTileset(tileset) bmtileset=RPG::Cache.tileset(tileset.tileset_name) bmautotiles=[] for i in 0...7 bmautotiles.push(RPG::Cache.autotile(tileset.autotile_names[i])) end return self.new(bmtileset,bmautotiles) end def bltSmallAutotile(bitmap,x,y,cxTile,cyTile,id,frame) return if frame<0 || !@autotiles || id>=384 autotile=@autotiles[id/48-1] return if !autotile || autotile.disposed? cxTile=[cxTile/2,1].max cyTile=[cyTile/2,1].max if autotile.height==32 anim=frame*32 src_rect=Rect.new(anim,0,32,32) bitmap.stretch_blt(Rect.new(x,y,cxTile*2,cyTile*2),autotile,src_rect) else anim=frame*96 id%=48 tiles = TileDrawingHelper::Autotiles[id>>3][id&7] src=Rect.new(0,0,0,0) for i in 0...4 tile_position = tiles[i] - 1 src.set(tile_position % 6 * 16 + anim, tile_position / 6 * 16, 16, 16) bitmap.stretch_blt(Rect.new(i%2*cxTile+x,i/2*cyTile+y,cxTile,cyTile), autotile, src) end end end def bltSmallRegularTile(bitmap,x,y,cxTile,cyTile,id) return if !@tileset || id<384 || @tileset.disposed? rect=Rect.new((id - 384) % 8 * 32, (id - 384) / 8 * 32,32,32) bitmap.stretch_blt(Rect.new(x,y,cxTile,cyTile),@tileset,rect) end def bltSmallTile(bitmap,x,y,cxTile,cyTile,id,frame=0) if id>=384 bltSmallRegularTile(bitmap,x,y,cxTile,cyTile,id) elsif id>0 bltSmallAutotile(bitmap,x,y,cxTile,cyTile,id,frame) end end def bltAutotile(bitmap,x,y,id,frame) bltSmallAutotile(bitmap,x,y,32,32,id,frame) end def bltRegularTile(bitmap,x,y,id) bltSmallRegularTile(bitmap,x,y,32,32,id) end def bltTile(bitmap,x,y,id,frame=0) if id>=384 bltRegularTile(bitmap,x,y,id) elsif id>0 bltAutotile(bitmap,x,y,id,frame) end end end [/CODE] [CODE] module FileInputMixin def fgetb x=0 ret=0 each_byte do |i| ret=i break end return ret end def fgetw x=0 ret=0 each_byte do |i| ret|=(i<<x) x+=8 break if x==16 end return ret end def fgetdw x=0 ret=0 each_byte do |i| ret|=(i<<x) x+=8 break if x==32 end return ret end def fgetsb ret=fgetb if (ret&0x80)!=0 return ret-256 else return ret end end def xfgetb(offset) self.pos=offset return fgetb end def xfgetw(offset) self.pos=offset return fgetw end def xfgetdw(offset) self.pos=offset return fgetdw end def getOffset(index) self.binmode self.pos=0 offset=fgetdw>>3 return 0 if index>=offset self.pos=index*8 return fgetdw end def getLength(index) self.binmode self.pos=0 offset=fgetdw>>3 return 0 if index>=offset self.pos=index*8+4 return fgetdw end def readName(index) self.binmode self.pos=0 offset=fgetdw>>3 return "" if index>=offset self.pos=index<<3 offset=fgetdw length=fgetdw return "" if length==0 self.pos=offset return read(length) end end module FileOutputMixin def fputb(b) b=b&0xFF write(b.chr) end def fputw(w) 2.times do b=w&0xFF write(b.chr) w>>=8 end end def fputdw(w) 4.times do b=w&0xFF write(b.chr) w>>=8 end end end class File < IO =begin class << self alias debugopen open def open(f,m="r") debugopen("debug.txt","ab"){|file| file.write([f,m].inspect+"\\r\\n") } if block_given? debugopen(f,m) {|file| yield file } else return debugopen(f,m) end end end =end include FileInputMixin include FileOutputMixin end class StringInput include FileInputMixin def pos=(value) seek(value) end def each_byte while !eof? yield getc end end def binmode end end class StringOutput include FileOutputMixin end[/CODE] [CODE] def pbAddScriptTexts(items,script) script.scan(/(?:_I)\\s*\\(\\s*\\"((?:[^\\\\\\"]*\\\\\\"?)*[^\\"]*)\\"/){|s| string=s[0] string.gsub!(/\\\\\\"/,"\\"") string.gsub!(/\\\\\\\\/,"\\\\") items.push(string) } end def pbAddRgssScriptTexts(items,script) script.scan(/(?:_INTL|_ISPRINTF)\\s*\\(\\s*\\"((?:[^\\\\\\"]*\\\\\\"?)*[^\\"]*)\\"/){|s| string=s[0] string.gsub!(/\\\\r/,"\\r") string.gsub!(/\\\\n/,"\\n") string.gsub!(/\\\\1/,"\\1") string.gsub!(/\\\\\\"/,"\\"") string.gsub!(/\\\\\\\\/,"\\\\") items.push(string) } end def pbSetTextMessages Graphics.update begin mapinfos = load_data("Data/MapInfos.rxdata") t = Time.now.to_i messages=[] texts=[] for script in $RGSS_SCRIPTS if Time.now.to_i - t >= 5 t = Time.now.to_i Graphics.update end scr=Zlib::Inflate.inflate(script[2]) pbAddRgssScriptTexts(texts,scr) end mapnames=[] for id in mapinfos.keys mapnames[id]=mapinfos[id].name end MessageTypes.setMessages(MessageTypes::MapNames,mapnames) # Must add messages since this code is shared by game system # and editor MessageTypes.addMapMessagesAsHash(0,texts) for id in mapinfos.keys if Time.now.to_i - t >= 5 t = Time.now.to_i Graphics.update end filename=sprintf("Data/Map%03d.rxdata",id) next if !pbRgssExists?(filename) map = load_data(filename) items=[] choices=[] for event in map.events.values if Time.now.to_i - t >= 5 t = Time.now.to_i Graphics.update end begin for i in 0...event.pages.size neednewline=false lastitem="" for j in 0...event.pages[i].list.size list = event.pages[i].list[j] if neednewline && list.code!=401 if lastitem!="" lastitem.gsub!(/([^\\.\\!\\?])\\s\\s+/){|m| $1+" "} items.push(lastitem) lastitem="" end neednewline=false end if list.code == 101 lastitem+="#{list.parameters[0]}" neednewline=true elsif list.code == 102 for k in 0...list.parameters[0].length choices.push(list.parameters[0][k]) end neednewline=false elsif list.code == 401 lastitem+=" #{list.parameters[0]}" neednewline=true elsif list.code == 355 || list.code==655 pbAddScriptTexts(items,list.parameters[0]) elsif list.code == 111 && list.parameters[0]==12 pbAddScriptTexts(items,list.parameters[1]) elsif list.code==209 route=list.parameters[1] for k in 0...route.list.size if route.list[k].code==45 pbAddScriptTexts(items,route.list[k].parameters[0]) end end end end if neednewline if lastitem!="" items.push(lastitem) lastitem="" end end end end end if Time.now.to_i - t >= 5 t = Time.now.to_i Graphics.update end items|=[] choices|=[] items.concat(choices) MessageTypes.setMapMessagesAsHash(id,items) if Time.now.to_i - t >= 5 t = Time.now.to_i Graphics.update end end rescue Hangup end Graphics.update end def pbEachIntlSection(file) lineno=1 re=/^\\s*\\[\\s*([^\\]]+)\\s*\\]\\s*$/ havesection=false sectionname=nil lastsection=[] file.each_line {|line| if lineno==1&&line[0]==0xEF&&line[1]==0xBB&&line[2]==0xBF line=line[3,line.length-3] end if !line[/^\\#/] && !line[/^\\s*$/] if line[re] if havesection yield lastsection,sectionname end lastsection.clear sectionname=$~[1] havesection=true else if sectionname==nil raise _INTL("Expected a section at the beginning of the file (line {1})",lineno) end lastsection.push(line.gsub(/\\s+$/,"")) end end lineno+=1 if lineno%500==0 Graphics.update end } if havesection yield lastsection,sectionname end end def pbGetText(infile) begin file=File.open(infile,"rb") rescue raise _INTL("Can't find {1}",infile) end intldat=[] begin pbEachIntlSection(file){|section,name| index=name if section.length==0 next end if !name[/^([Mm][Aa][Pp])?(\\d+)$/] raise _INTL("Invalid section name {1}",name) end ismap=$~[1] && $~[1]!="" id=$~[2].to_i itemlength=0 if section[0][/^\\d+$/] intlhash=[] itemlength=3 if ismap raise _INTL("Section {1} can't be an ordered list (section was recognized as an ordered list because its first line is a number)",name) end if section.length%3!=0 raise _INTL("Section {1}'s line count is not divisible by 3 (section was recognized as an ordered list because its first line is a number)",name) end else intlhash=OrderedHash.new itemlength=2 if section.length%2!=0 raise _INTL("Section {1} has an odd number of entries (section was recognized as a hash because its first line is not a number)",name) end end i=0;loop do break unless i<section.length if itemlength==3 if !section[i][/^\\d+$/] raise _INTL("Expected a number in section {1}, got {2} instead",name,section[i]) end key=section[i].to_i i+=1 else key=MessageTypes.denormalizeValue(section[i]) end intlhash[key]=MessageTypes.denormalizeValue(section[i+1]) i+=2 end if ismap intldat[0]=[] if !intldat[0] intldat[0][id]=intlhash else intldat[id]=intlhash end } ensure file.close end return intldat end def pbCompileText outfile=File.open("intl.dat","wb") begin intldat=pbGetText("intl.txt") Marshal.dump(intldat,outfile) rescue raise ensure outfile.close end end class OrderedHash < Hash def initialize @keys=[] super end def keys return @keys.clone end def inspect str="{" for i in 0...@keys.length str+=", " if i>0 str+=@keys[i].inspect+"=>"+self[@keys[i]].inspect end str+="}" return str end alias :to_s :inspect def []=(key,value) oldvalue=self[key] if !oldvalue && value @keys.push(key) elsif !value @keys|=[] @keys-=[key] end return super(key,value) end def self._load(string) ret=self.new keysvalues=Marshal.load(string) keys=keysvalues[0] values=keysvalues[1] for i in 0...keys.length ret[keys[i]]=values[i] end return ret end def _dump(depth=100) values=[] for key in @keys values.push(self[key]) end return Marshal.dump([@keys,values]) end end class Messages def initialize(filename=nil,delayLoad=false) @messages=nil @filename=filename if @filename && !delayLoad loadMessageFile(@filename) end end def delayedLoad if @filename && !@messages loadMessageFile(@filename) @filename=nil end end def self.stringToKey(str) if str[/[\\r\\n\\t\\1]|^\\s+|\\s+$|\\s{2,}/] key=str.clone key.gsub!(/^\\s+/,"") key.gsub!(/\\s+$/,"") key.gsub!(/\\s{2,}/," ") return key end return str end def self.normalizeValue(value) if value[/[\\r\\n\\t\\x01]|^[\\[\\]]/] ret=value.clone ret.gsub!(/\\r/,"<<r>>") ret.gsub!(/\\n/,"<<n>>") ret.gsub!(/\\t/,"<<t>>") ret.gsub!(/\\[/,"<<[>>") ret.gsub!(/\\]/,"<<]>>") ret.gsub!(/\\x01/,"<<1>>") return ret end return value end def self.denormalizeValue(value) if value[/<<[rnt1\\[\\]]>>/] ret=value.clone ret.gsub!(/<<1>>/,"\\1") ret.gsub!(/<<r>>/,"\\r") ret.gsub!(/<<n>>/,"\\n") ret.gsub!(/<<\\[>>/,"[") ret.gsub!(/<<\\]>>/,"]") ret.gsub!(/<<t>>/,"\\t") return ret end return value end def self.writeObject(f,msgs,secname,origMessages=nil) return if !msgs if msgs.is_a?(Array) f.write("[#{secname}]\\r\\n") for j in 0...msgs.length next if msgs[j]==nil || msgs[j]=="" value=Messages.normalizeValue(msgs[j]) origValue="" if origMessages origValue=Messages.normalizeValue(origMessages.get(secname,j)) else origValue=Messages.normalizeValue(MessageTypes.get(secname,j)) end f.write("#{j}\\r\\n") f.write(origValue+"\\r\\n") f.write(value+"\\r\\n") end elsif msgs.is_a?(OrderedHash) f.write("[#{secname}]\\r\\n") keys=msgs.keys for key in keys next if msgs[key]==nil || msgs[key]=="" value=Messages.normalizeValue(msgs[key]) valkey=Messages.normalizeValue(key) # key is already serialized f.write(valkey+"\\r\\n") f.write(value+"\\r\\n") end end end def messages return @messages || [] end def extract(outfile) return if !@messages origMessages=Messages.new("Data/messages.dat") File.open(outfile,"wb"){|f| f.write(0xef.chr) f.write(0xbb.chr) f.write(0xbf.chr) f.write("# To localize this text for a particular language, please\\r\\n") f.write("# translate every second line of this file.\\r\\n") if @messages[0] for i in 0...@messages[0].length msgs=@messages[0][i] Messages.writeObject(f,msgs,"Map#{i}",origMessages) end end for i in 1...@messages.length msgs=@messages[i] Messages.writeObject(f,msgs,i,origMessages) end } end def setMessages(type,array) arr=[] @messages=[] if !@messages for i in 0...array.length arr[i]=(array[i]) ? array[i] : "" end @messages[type]=arr end def self.createHash(type,array) arr=OrderedHash.new for i in 0...array.length if array[i] key=Messages.stringToKey(array[i]) arr[key]=array[i] end end return arr end def self.addToHash(type,&