From 132a16950d0fe7d993f74c1785066f088bcf9751 Mon Sep 17 00:00:00 2001 From: Maruno17 Date: Thu, 23 Dec 2021 00:27:17 +0000 Subject: [PATCH] Yet more Rubocopping --- .../001_Debugging/001_PBDebug.rb | 2 +- .../001_Technical/001_Debugging/003_Errors.rb | 2 +- .../001_Technical/002_Files/001_FileTests.rb | 2 +- .../001_Technical/002_Files/002_FileMixins.rb | 2 +- .../001_Technical/003_Intl_Messages.rb | 30 ++--- .../001_Technical/005_PluginManager.rb | 10 +- Data/Scripts/001_Technical/006_RPG_Sprite.rb | 30 ++--- .../003_Game processing/001_StartGame.rb | 2 +- .../003_Game processing/002_Scene_Map.rb | 12 +- .../003_Game processing/003_Interpreter.rb | 6 +- .../004_Interpreter_Commands.rb | 12 +- .../004_Game classes/001_Game_Screen.rb | 2 +- .../004_Game classes/002_Game_System.rb | 11 +- .../004_Game classes/003_Game_Picture.rb | 4 +- Data/Scripts/004_Game classes/004_Game_Map.rb | 8 +- .../005_Game_Map_Autoscroll.rb | 32 ++--- .../004_Game classes/006_Game_MapFactory.rb | 18 +-- .../004_Game classes/007_Game_Character.rb | 7 +- .../004_Game classes/008_Game_Event.rb | 24 ++-- .../004_Game classes/009_Game_Player.rb | 60 ++++----- .../004_Game classes/010_Game_CommonEvent.rb | 2 +- .../Scripts/005_Sprites/001_Sprite_Picture.rb | 6 +- Data/Scripts/005_Sprites/002_Sprite_Timer.rb | 2 +- .../005_Sprites/003_Sprite_Character.rb | 20 +-- .../005_Sprites/004_Sprite_Reflection.rb | 10 +- .../005_Sprites/005_Sprite_SurfBase.rb | 2 +- Data/Scripts/005_Sprites/007_Spriteset_Map.rb | 6 +- .../005_Sprites/009_Sprite_DynamicShadows.rb | 17 ++- .../Scripts/005_Sprites/010_ParticleEngine.rb | 14 +- .../005_Sprites/013_ScreenPosHelper.rb | 2 +- .../006_Map renderer/001_TilemapRenderer.rb | 2 +- .../006_Map renderer/004_TileDrawingHelper.rb | 4 +- .../007_Objects and windows/001_RPG_Cache.rb | 2 +- .../002_MessageConfig.rb | 18 +-- .../007_Objects and windows/003_Window.rb | 30 ++--- .../004_SpriteWindow.rb | 60 ++++----- .../005_SpriteWindow_text.rb | 12 +- .../006_SpriteWindow_pictures.rb | 12 +- .../007_SpriteWrapper.rb | 12 +- .../007_Objects and windows/009_Planes.rb | 4 +- .../007_Objects and windows/010_DrawText.rb | 16 +-- .../007_Objects and windows/011_Messages.rb | 68 +++++----- .../007_Objects and windows/012_TextEntry.rb | 10 +- Data/Scripts/008_Audio/001_Audio.rb | 6 +- Data/Scripts/008_Audio/002_Audio_Play.rb | 10 +- Data/Scripts/009_Scenes/001_Transitions.rb | 82 ++++++------ Data/Scripts/009_Scenes/002_EventScene.rb | 10 +- .../001_Hardcoded data/007_Evolution.rb | 5 +- .../010_Data/002_PBS data/001_MiscPBSData.rb | 12 +- .../Scripts/010_Data/002_PBS data/006_Item.rb | 2 +- .../010_Data/002_PBS data/013_Encounter.rb | 4 +- .../010_Data/002_PBS data/014_TrainerType.rb | 2 +- .../011_Battle/001_Battle/001_Battle.rb | 2 +- .../001_Battle/002_Battle_StartAndEnd.rb | 8 +- .../003_Battle_ExpAndMoveLearning.rb | 12 +- .../001_Battle/005_Battle_ActionSwitching.rb | 44 +++---- .../001_Battle/006_Battle_ActionUseItem.rb | 4 +- .../001_Battle/007_Battle_ActionRunning.rb | 30 ++--- .../001_Battle/010_Battle_AttackPhase.rb | 8 +- .../001_Battle/011_Battle_EndOfRoundPhase.rb | 13 +- .../002_Battler/001_Battle_Battler.rb | 18 +-- .../002_Battler/003_Battler_ChangeSelf.rb | 15 +-- .../002_Battler/004_Battler_Statuses.rb | 28 ++-- .../002_Battler/005_Battler_StatStages.rb | 24 ++-- .../002_Battler/006_Battler_AbilityAndItem.rb | 2 +- .../002_Battler/007_Battler_UseMove.rb | 84 ++++++------ .../009_Battler_UseMoveSuccessChecks.rb | 37 +++--- .../010_Battler_UseMoveTriggerEffects.rb | 86 +++++------- .../011_Battle/003_Move/001_Battle_Move.rb | 2 +- .../003_Move/003_Move_UsageCalculations.rb | 52 ++++---- .../003_Move/006_MoveEffects_BattlerStats.rb | 20 +-- .../003_Move/007_MoveEffects_BattlerOther.rb | 14 +- .../003_Move/009_MoveEffects_MultiHit.rb | 13 +- .../012_MoveEffects_ChangeMoveEffect.rb | 12 +- .../011_Battle/004_Scene/001_Battle_Scene.rb | 12 +- .../004_Scene/003_Scene_ChooseCommands.rb | 10 +- .../004_Scene/004_Scene_PlayAnimations.rb | 12 +- .../004_Scene/005_Battle_Scene_Menus.rb | 14 +- .../004_Scene/006_Battle_Scene_Objects.rb | 12 +- .../007_Battle_Scene_BaseAnimation.rb | 4 +- .../004_Scene/008_Battle_Scene_Animations.rb | 18 ++- Data/Scripts/011_Battle/005_AI/002_AI_Item.rb | 10 +- .../011_Battle/005_AI/003_AI_Switch.rb | 21 ++- Data/Scripts/011_Battle/005_AI/004_AI_Move.rb | 39 +++--- .../005_AI/005_AI_Move_EffectScores.rb | 124 +++++++++--------- .../005_AI/006_AI_Move_Utilities.rb | 119 ++++++----------- .../005_Battle_CatchAndStoreMixin.rb | 11 +- .../007_BattleAnimationPlayer.rb | 70 +++++----- .../008_Battle_AbilityEffects.rb | 4 +- .../009_Battle_ItemEffects.rb | 9 +- .../001_SafariBattle.rb | 2 +- .../003_BattlePalaceBattle.rb | 5 +- .../004_BattleArenaBattle.rb | 8 +- .../001_Overworld_Weather.rb | 55 ++++---- Data/Scripts/012_Overworld/001_Overworld.rb | 47 +++---- .../001_Overworld_BattleStarting.rb | 8 +- .../002_Overworld_BattleIntroAnim.rb | 10 +- .../003_Overworld_WildEncounters.rb | 22 ++-- .../012_Overworld/002_Overworld_Metadata.rb | 2 +- .../012_Overworld/003_Overworld_Time.rb | 6 +- .../012_Overworld/004_Overworld_FieldMoves.rb | 2 +- .../006_Overworld_BerryPlants.rb | 6 +- .../012_Overworld/007_Overworld_DayCare.rb | 17 ++- .../008_Overworld_RandomDungeons.rb | 8 +- Data/Scripts/013_Items/001_Item_Utilities.rb | 10 +- Data/Scripts/013_Items/002_Item_Effects.rb | 6 +- .../013_Items/003_Item_BattleEffects.rb | 24 ++-- Data/Scripts/013_Items/005_Item_PokeRadar.rb | 6 +- Data/Scripts/013_Items/007_Item_Sprites.rb | 8 +- .../001_Pokemon-related/001_FormHandlers.rb | 8 +- .../002_ShadowPokemon_Other.rb | 15 +-- .../003_Pokemon_Sprites.rb | 18 +-- .../001_Pokemon-related/004_PokemonStorage.rb | 8 +- Data/Scripts/014_Pokemon/001_Pokemon.rb | 4 +- .../015_Trainers and player/001_Trainer.rb | 6 +- .../002_Trainer_LoadAndNew.rb | 8 +- .../003_Trainer_Sprites.rb | 6 +- .../015_Trainers and player/004_Player.rb | 4 +- .../003_UI_EggHatching.rb | 28 ++-- .../006_UI_HallOfFame.rb | 34 ++--- .../001_Non-interactive UI/007_UI_Credits.rb | 2 +- Data/Scripts/016_UI/003_UI_Pokedex_Main.rb | 8 +- Data/Scripts/016_UI/004_UI_Pokedex_Entry.rb | 8 +- Data/Scripts/016_UI/005_UI_Party.rb | 27 ++-- Data/Scripts/016_UI/006_UI_Summary.rb | 34 ++--- Data/Scripts/016_UI/007_UI_Bag.rb | 28 ++-- Data/Scripts/016_UI/010_UI_Phone.rb | 20 +-- Data/Scripts/016_UI/013_UI_Load.rb | 2 +- Data/Scripts/016_UI/015_UI_Options.rb | 2 +- Data/Scripts/016_UI/016_UI_ReadyMenu.rb | 20 ++- Data/Scripts/016_UI/017_UI_PokemonStorage.rb | 79 ++++++----- Data/Scripts/016_UI/018_UI_ItemStorage.rb | 10 +- Data/Scripts/016_UI/020_UI_PokeMart.rb | 29 ++-- Data/Scripts/016_UI/022_UI_PurifyChamber.rb | 46 ++++--- Data/Scripts/016_UI/023_UI_MysteryGift.rb | 10 +- Data/Scripts/016_UI/024_UI_TextEntry.rb | 6 +- .../017_Minigames/002_Minigame_TripleTriad.rb | 45 +++---- .../017_Minigames/003_Minigame_SlotMachine.rb | 8 +- .../017_Minigames/004_Minigame_VoltorbFlip.rb | 22 ++-- .../017_Minigames/005_Minigame_Lottery.rb | 2 +- .../017_Minigames/006_Minigame_Mining.rb | 2 +- .../002_Challenge_Rulesets.rb | 8 +- .../003_Challenge_EntryRestrictions.rb | 2 +- .../002_BugContest.rb | 26 ++-- .../001_ChallengeGenerator_Data.rb | 8 +- .../002_ChallengeGenerator_Pokemon.rb | 26 ++-- .../004_ChallengeGenerator_BattleSim.rb | 22 ++-- Data/Scripts/019_Utilities/001_Utilities.rb | 64 +++++---- .../019_Utilities/002_Utilities_Pokemon.rb | 39 +++--- .../001_Editor screens/001_EditorScreens.rb | 60 ++++----- .../002_EditorScreens_TerrainTags.rb | 8 +- .../003_EditorScreens_MapConnections.rb | 6 +- .../004_EditorScreens_SpritePositioning.rb | 8 +- .../Scripts/020_Debug/001_Editor_Utilities.rb | 6 +- .../001_AnimEditor_SceneElements.rb | 69 +++++----- .../002_AnimEditor_ControlsButtons.rb | 24 ++-- .../003_AnimEditor_Interpolation.rb | 22 ++-- .../004_AnimEditor_ExportImport.rb | 4 +- .../005_AnimEditor_Functions.rb | 4 +- .../Scripts/020_Debug/002_Editor_DataTypes.rb | 4 +- .../003_Debug menus/002_Debug_MenuCommands.rb | 2 +- .../003_Debug_MenuExtraCode.rb | 44 +++---- .../005_Debug_PokemonCommands.rb | 10 +- .../007_Debug_BattleCommands.rb | 2 +- .../008_Debug_BattlerCommands.rb | 18 +-- .../009_Debug_BattleExtraCode.rb | 4 +- Data/Scripts/020_Debug/003_Editor_Listers.rb | 20 ++- Data/Scripts/021_Compiler/001_Compiler.rb | 22 ++-- .../021_Compiler/002_Compiler_CompilePBS.rb | 2 +- .../021_Compiler/003_Compiler_WritePBS.rb | 4 +- .../004_Compiler_MapsAndEvents.rb | 6 +- 171 files changed, 1455 insertions(+), 1647 deletions(-) diff --git a/Data/Scripts/001_Technical/001_Debugging/001_PBDebug.rb b/Data/Scripts/001_Technical/001_Debugging/001_PBDebug.rb index 36a6de9f6..81360266d 100644 --- a/Data/Scripts/001_Technical/001_Debugging/001_PBDebug.rb +++ b/Data/Scripts/001_Technical/001_Debugging/001_PBDebug.rb @@ -7,7 +7,7 @@ module PBDebug rescue PBDebug.log("") PBDebug.log("**Exception: #{$!.message}") - PBDebug.log("#{$!.backtrace.inspect}") + PBDebug.log($!.backtrace.inspect.to_s) PBDebug.log("") pbPrintException($!) # if $INTERNAL PBDebug.flush diff --git a/Data/Scripts/001_Technical/001_Debugging/003_Errors.rb b/Data/Scripts/001_Technical/001_Debugging/003_Errors.rb index 20b591686..eed3d98ee 100644 --- a/Data/Scripts/001_Technical/001_Debugging/003_Errors.rb +++ b/Data/Scripts/001_Technical/001_Debugging/003_Errors.rb @@ -37,7 +37,7 @@ def pbPrintException(e) message += "Exception: #{e.class}\r\n" message += "Message: " end - message += "#{emessage}" + message += emessage # show last 10/25 lines of backtrace if !e.is_a?(EventScriptError) message += "\r\n\r\nBacktrace:\r\n" diff --git a/Data/Scripts/001_Technical/002_Files/001_FileTests.rb b/Data/Scripts/001_Technical/002_Files/001_FileTests.rb index 973e9d9f6..92ff55426 100644 --- a/Data/Scripts/001_Technical/002_Files/001_FileTests.rb +++ b/Data/Scripts/001_Technical/002_Files/001_FileTests.rb @@ -378,7 +378,7 @@ class StringInput f = super yield f ensure - f.close if f + f&.close end else super diff --git a/Data/Scripts/001_Technical/002_Files/002_FileMixins.rb b/Data/Scripts/001_Technical/002_Files/002_FileMixins.rb index 522cb9ade..79f525993 100644 --- a/Data/Scripts/001_Technical/002_Files/002_FileMixins.rb +++ b/Data/Scripts/001_Technical/002_Files/002_FileMixins.rb @@ -137,7 +137,7 @@ class StringInput end def each_byte - while !eof? + until eof? yield getc end end diff --git a/Data/Scripts/001_Technical/003_Intl_Messages.rb b/Data/Scripts/001_Technical/003_Intl_Messages.rb index 6923aaf3b..22e052a66 100644 --- a/Data/Scripts/001_Technical/003_Intl_Messages.rb +++ b/Data/Scripts/001_Technical/003_Intl_Messages.rb @@ -69,7 +69,7 @@ def pbSetTextMessages neednewline = false end if list.code == 101 - lastitem += "#{list.parameters[0]}" + lastitem += list.parameters[0].to_s neednewline = true elsif list.code == 102 list.parameters[0].length.times do |k| @@ -78,7 +78,7 @@ def pbSetTextMessages neednewline = false elsif list.code == 401 lastitem += " " if lastitem != "" - lastitem += "#{list.parameters[0]}" + lastitem += list.parameters[0].to_s neednewline = true elsif list.code == 355 || list.code == 655 pbAddScriptTexts(items, list.parameters[0]) @@ -93,11 +93,9 @@ def pbSetTextMessages end end end - if neednewline - if lastitem != "" - items.push(lastitem) - lastitem = "" - end + if neednewline && lastitem != "" + items.push(lastitem) + lastitem = "" end end end @@ -140,7 +138,7 @@ def pbSetTextMessages neednewline = false end if list.code == 101 - lastitem += "#{list.parameters[0]}" + lastitem += list.parameters[0].to_s neednewline = true elsif list.code == 102 list.parameters[0].length.times do |k| @@ -149,7 +147,7 @@ def pbSetTextMessages neednewline = false elsif list.code == 401 lastitem += " " if lastitem != "" - lastitem += "#{list.parameters[0]}" + lastitem += list.parameters[0].to_s neednewline = true elsif list.code == 355 || list.code == 655 pbAddScriptTexts(items, list.parameters[0]) @@ -164,11 +162,9 @@ def pbSetTextMessages end end end - if neednewline - if lastitem != "" - items.push(lastitem) - lastitem = "" - end + if neednewline && lastitem != "" + items.push(lastitem) + lastitem = "" end end end @@ -210,7 +206,7 @@ def pbEachIntlSection(file) sectionname = $~[1] havesection = true else - if sectionname == nil + if sectionname.nil? raise _INTL("Expected a section at the beginning of the file (line {1})", lineno) end lastsection.push(line.gsub(/\s+$/, "")) @@ -739,7 +735,7 @@ def _INTL(*arg) end string = string.clone (1...arg.length).each do |i| - string.gsub!(/\{#{i}\}/, "#{arg[i]}") + string.gsub!(/\{#{i}\}/, arg[i].to_s) end return string end @@ -770,7 +766,7 @@ def _MAPINTL(mapid, *arg) string = MessageTypes.getFromMapHash(mapid, arg[0]) string = string.clone (1...arg.length).each do |i| - string.gsub!(/\{#{i}\}/, "#{arg[i]}") + string.gsub!(/\{#{i}\}/, arg[i].to_s) end return string end diff --git a/Data/Scripts/001_Technical/005_PluginManager.rb b/Data/Scripts/001_Technical/005_PluginManager.rb index 4b6287a9c..7accbf02a 100644 --- a/Data/Scripts/001_Technical/005_PluginManager.rb +++ b/Data/Scripts/001_Technical/005_PluginManager.rb @@ -319,10 +319,10 @@ module PluginManager value = [value] if value.is_a?(String) if value.is_a?(Array) value.each do |entry| - if !entry.is_a?(String) - self.error("Plugin '#{name}'s credits array contains a non-string value.") - else + if entry.is_a?(String) credits << entry + else + self.error("Plugin '#{name}'s credits array contains a non-string value.") end end else @@ -333,7 +333,7 @@ module PluginManager end end @@Plugins.values.each do |plugin| - if plugin[:incompatibilities] && plugin[:incompatibilities].include?(name) + if plugin[:incompatibilities]&.include?(name) self.error("Plugin '#{plugin[:name]}' is incompatible with '#{name}'. " + "They cannot both be used at the same time.") end @@ -475,7 +475,7 @@ module PluginManager print("#{message}\r\nThis exception was logged in #{errorlogline}.\r\nHold Ctrl when closing this message to copy it to the clipboard.") # Give a ~500ms coyote time to start holding Control t = System.delta - until (System.delta - t) >= 500000 + until (System.delta - t) >= 500_000 Input.update if Input.press?(Input::CTRL) Input.clipboard = message diff --git a/Data/Scripts/001_Technical/006_RPG_Sprite.rb b/Data/Scripts/001_Technical/006_RPG_Sprite.rb index bdccfd38d..40031e38d 100644 --- a/Data/Scripts/001_Technical/006_RPG_Sprite.rb +++ b/Data/Scripts/001_Technical/006_RPG_Sprite.rb @@ -6,13 +6,11 @@ class SpriteAnimation @sprite = sprite end - %w[ - x y ox oy viewport flash src_rect opacity tone - ].each_with_index do |s, _i| + ["x", "y", "ox", "oy", "viewport", "flash", "src_rect", "opacity", "tone"].each do |def_name| eval <<-__END__ - def #{s}(*arg) - @sprite.#{s}(*arg) + def #{def_name}(*arg) + @sprite.#{def_name}(*arg) end __END__ @@ -30,7 +28,7 @@ class SpriteAnimation def animation(animation, hit, height = 3) dispose_animation @_animation = animation - return if @_animation == nil + return if @_animation.nil? @_animation_hit = hit @_animation_height = height @_animation_duration = @_animation.frame_max @@ -66,7 +64,7 @@ class SpriteAnimation return if animation == @_loop_animation dispose_loop_animation @_loop_animation = animation - return if @_loop_animation == nil + return if @_loop_animation.nil? @_loop_animation_index = 0 fr = 20 if @_animation.name[/\[\s*(\d+?)\s*\]\s*$/] @@ -92,7 +90,7 @@ class SpriteAnimation end def dispose_animation - return if @_animation_sprites == nil + return if @_animation_sprites.nil? sprite = @_animation_sprites[0] if sprite != nil @@_reference_count[sprite.bitmap] -= 1 @@ -108,7 +106,7 @@ class SpriteAnimation end def dispose_loop_animation - return if @_loop_animation_sprites == nil + return if @_loop_animation_sprites.nil? sprite = @_loop_animation_sprites[0] if sprite != nil @@_reference_count[sprite.bitmap] -= 1 @@ -195,7 +193,7 @@ class SpriteAnimation 16.times do |i| sprite = sprites[i] pattern = cell_data[i, 0] - if sprite == nil || pattern == nil || pattern == -1 + if sprite.nil? || pattern.nil? || pattern == -1 sprite.visible = false if sprite != nil next end @@ -377,7 +375,7 @@ module RPG def pushAnimation(array, anim) array.length.times do |i| - next if array[i] && array[i].active? + next if array[i]&.active? array[i] = anim return end @@ -397,7 +395,7 @@ module RPG end def dispose_damage - return if @_damage_sprite == nil + return if @_damage_sprite.nil? @_damage_sprite.bitmap.dispose @_damage_sprite.dispose @_damage_sprite = nil @@ -406,14 +404,14 @@ module RPG def dispose_animation @animations.each do |a| - a.dispose_animation if a + a&.dispose_animation end @animations.clear end def dispose_loop_animation @loopAnimations.each do |a| - a.dispose_loop_animation if a + a&.dispose_loop_animation end @loopAnimations.clear end @@ -501,13 +499,13 @@ module RPG def update_animation @animations.each do |a| - a.update_animation if a && a.active? + a.update_animation if a&.active? end end def update_loop_animation @loopAnimations.each do |a| - a.update_loop_animation if a && a.active? + a.update_loop_animation if a&.active? end end diff --git a/Data/Scripts/003_Game processing/001_StartGame.rb b/Data/Scripts/003_Game processing/001_StartGame.rb index d9b2d6671..3c200c522 100644 --- a/Data/Scripts/003_Game processing/001_StartGame.rb +++ b/Data/Scripts/003_Game processing/001_StartGame.rb @@ -38,7 +38,7 @@ module Game # Called when starting a new game. Initializes global variables # and transfers the player into the map scene. def self.start_new - if $game_map && $game_map.events + if $game_map&.events $game_map.events.each_value { |event| event.clear_starting } end $game_temp.common_event_id = 0 if $game_temp diff --git a/Data/Scripts/003_Game processing/002_Scene_Map.rb b/Data/Scripts/003_Game processing/002_Scene_Map.rb index 9a0103191..ceafdadef 100644 --- a/Data/Scripts/003_Game processing/002_Scene_Map.rb +++ b/Data/Scripts/003_Game processing/002_Scene_Map.rb @@ -61,8 +61,8 @@ class Scene_Map pbBGMFade(0.8) end end - if playingBGS && map.autoplay_bgs - pbBGMFade(0.8) if playingBGS.name != map.bgs.name + if playingBGS && map.autoplay_bgs && playingBGS.name != map.bgs.name + pbBGMFade(0.8) end Graphics.frame_reset end @@ -145,12 +145,12 @@ class Scene_Map end keys = @spritesets.keys.clone keys.each do |i| - if !$map_factory.hasMap?(i) - @spritesets[i].dispose if @spritesets[i] + if $map_factory.hasMap?(i) + @spritesets[i].update + else + @spritesets[i]&.dispose @spritesets[i] = nil @spritesets.delete(i) - else - @spritesets[i].update end end @spritesetGlobal.update diff --git a/Data/Scripts/003_Game processing/003_Interpreter.rb b/Data/Scripts/003_Game processing/003_Interpreter.rb index 8b5aeb87d..a961b0f73 100644 --- a/Data/Scripts/003_Game processing/003_Interpreter.rb +++ b/Data/Scripts/003_Game processing/003_Interpreter.rb @@ -304,7 +304,7 @@ class Interpreter def pbEraseThisEvent if $game_map.events[@event_id] $game_map.events[@event_id].erase - $PokemonMap.addErasedEvent(@event_id) if $PokemonMap + $PokemonMap&.addErasedEvent(@event_id) end @index += 1 return true @@ -407,7 +407,7 @@ class Interpreter when 6 then event.move_right when 8 then event.move_up end - $PokemonMap.addMovedEvent(@event_id) if $PokemonMap + $PokemonMap&.addMovedEvent(@event_id) if old_x != event.x || old_y != event.y $game_player.lock loop do @@ -443,7 +443,7 @@ class Interpreter def pbTrainerEnd pbGlobalUnlock event = get_self - event.erase_route if event + event&.erase_route end def setPrice(item, buy_price = -1, sell_price = -1) diff --git a/Data/Scripts/003_Game processing/004_Interpreter_Commands.rb b/Data/Scripts/003_Game processing/004_Interpreter_Commands.rb index adb95b076..09baf51d9 100644 --- a/Data/Scripts/003_Game processing/004_Interpreter_Commands.rb +++ b/Data/Scripts/003_Game processing/004_Interpreter_Commands.rb @@ -414,8 +414,8 @@ class Interpreter #----------------------------------------------------------------------------- def command_116 if @event_id > 0 - $game_map.events[@event_id].erase if $game_map.events[@event_id] - $PokemonMap.addErasedEvent(@event_id) if $PokemonMap + $game_map.events[@event_id]&.erase + $PokemonMap&.addErasedEvent(@event_id) end @index += 1 return false @@ -512,10 +512,10 @@ class Interpreter next if $game_variables[i] == value $game_variables[i] = value when 1 # add - next if $game_variables[i] >= 99999999 + next if $game_variables[i] >= 99_999_999 $game_variables[i] += value when 2 # subtract - next if $game_variables[i] <= -99999999 + next if $game_variables[i] <= -99_999_999 $game_variables[i] -= value when 3 # multiply next if value == 1 @@ -527,8 +527,8 @@ class Interpreter next if [0, 1].include?(value) $game_variables[i] %= value end - $game_variables[i] = 99999999 if $game_variables[i] > 99999999 - $game_variables[i] = -99999999 if $game_variables[i] < -99999999 + $game_variables[i] = 99_999_999 if $game_variables[i] > 99_999_999 + $game_variables[i] = -99_999_999 if $game_variables[i] < -99_999_999 $game_map.need_refresh = true end return true diff --git a/Data/Scripts/004_Game classes/001_Game_Screen.rb b/Data/Scripts/004_Game classes/001_Game_Screen.rb index 72cb6b0ab..c7056ef97 100644 --- a/Data/Scripts/004_Game classes/001_Game_Screen.rb +++ b/Data/Scripts/004_Game classes/001_Game_Screen.rb @@ -142,7 +142,7 @@ end def pbToneChangeAll(tone, duration) $game_screen.start_tone_change(tone, duration * Graphics.frame_rate / 20) $game_screen.pictures.each do |picture| - picture.start_tone_change(tone, duration * Graphics.frame_rate / 20) if picture + picture&.start_tone_change(tone, duration * Graphics.frame_rate / 20) end end diff --git a/Data/Scripts/004_Game classes/002_Game_System.rb b/Data/Scripts/004_Game classes/002_Game_System.rb index 774f9c55c..6d2ba8fdf 100644 --- a/Data/Scripts/004_Game classes/002_Game_System.rb +++ b/Data/Scripts/004_Game classes/002_Game_System.rb @@ -61,11 +61,10 @@ class Game_System def bgm_play_internal(bgm, position) # :nodoc: @bgm_position = position if !@bgm_paused - @playing_bgm = (bgm == nil) ? nil : bgm.clone + @playing_bgm = bgm&.clone if bgm != nil && bgm.name != "" - if FileTest.audio_exist?("Audio/BGM/" + bgm.name) - bgm_play_internal2("Audio/BGM/" + bgm.name, - bgm.volume, bgm.pitch, @bgm_position) if !@defaultBGM + if !@defaultBGM && FileTest.audio_exist?("Audio/BGM/" + bgm.name) + bgm_play_internal2("Audio/BGM/" + bgm.name, bgm.volume, bgm.pitch, @bgm_position) end else @bgm_position = position if !@bgm_paused @@ -161,7 +160,7 @@ class Game_System ################################################################################ def bgs_play(bgs) - @playing_bgs = (bgs == nil) ? nil : bgs.clone + @playing_bgs = (bgs.nil?) ? nil : bgs.clone if bgs != nil && bgs.name != "" if FileTest.audio_exist?("Audio/BGS/" + bgs.name) vol = bgs.volume @@ -258,7 +257,7 @@ class Game_System ################################################################################ def windowskin_name - if @windowskin_name == nil + if @windowskin_name.nil? return $data_system.windowskin_name else return @windowskin_name diff --git a/Data/Scripts/004_Game classes/003_Game_Picture.rb b/Data/Scripts/004_Game classes/003_Game_Picture.rb index ef10a56de..d02d1950e 100644 --- a/Data/Scripts/004_Game classes/003_Game_Picture.rb +++ b/Data/Scripts/004_Game classes/003_Game_Picture.rb @@ -66,7 +66,7 @@ class Game_Picture @zoom_x = zoom_x.to_f @zoom_y = zoom_y.to_f @opacity = opacity.to_f - @blend_type = blend_type ? blend_type : 0 + @blend_type = blend_type || 0 @duration = 0 @target_x = @x @target_y = @y @@ -98,7 +98,7 @@ class Game_Picture @target_zoom_x = zoom_x.to_f @target_zoom_y = zoom_y.to_f @target_opacity = opacity.to_f - @blend_type = blend_type ? blend_type : 0 + @blend_type = blend_type || 0 end #----------------------------------------------------------------------------- # * Change Rotation Speed diff --git a/Data/Scripts/004_Game classes/004_Game_Map.rb b/Data/Scripts/004_Game classes/004_Game_Map.rb index bcffef5f0..c6e9b6af4 100644 --- a/Data/Scripts/004_Game classes/004_Game_Map.rb +++ b/Data/Scripts/004_Game classes/004_Game_Map.rb @@ -193,7 +193,7 @@ class Game_Map if self_event != nil && terrain.can_surf_freely [2, 1, 0].each do |j| facing_tile_id = data[newx, newy, j] - return false if facing_tile_id == nil + return false if facing_tile_id.nil? facing_terrain = GameData::TerrainTag.try_get(@terrain_tags[facing_tile_id]) if facing_terrain.id != :None && !facing_terrain.ignore_passability return facing_terrain.can_surf_freely @@ -207,7 +207,7 @@ class Game_Map # Can't walk onto ledges [2, 1, 0].each do |j| facing_tile_id = data[newx, newy, j] - return false if facing_tile_id == nil + return false if facing_tile_id.nil? facing_terrain = GameData::TerrainTag.try_get(@terrain_tags[facing_tile_id]) return false if facing_terrain.ledge break if facing_terrain.id != :None && !facing_terrain.ignore_passability @@ -326,7 +326,7 @@ class Game_Map max_x = (self.width - (Graphics.width.to_f / TILE_WIDTH)) * REAL_RES_X @display_x = [0, [@display_x, max_x].min].max end - $map_factory.setMapsInRange if $map_factory + $map_factory&.setMapsInRange end def display_y=(value) @@ -336,7 +336,7 @@ class Game_Map max_y = (self.height - (Graphics.height.to_f / TILE_HEIGHT)) * REAL_RES_Y @display_y = [0, [@display_y, max_y].min].max end - $map_factory.setMapsInRange if $map_factory + $map_factory&.setMapsInRange end def scroll_up(distance) diff --git a/Data/Scripts/004_Game classes/005_Game_Map_Autoscroll.rb b/Data/Scripts/004_Game classes/005_Game_Map_Autoscroll.rb index 3c1334fd3..bfa58138b 100644 --- a/Data/Scripts/004_Game classes/005_Game_Map_Autoscroll.rb +++ b/Data/Scripts/004_Game classes/005_Game_Map_Autoscroll.rb @@ -93,7 +93,22 @@ class Interpreter max_y = ($game_map.height - (Graphics.height.to_f / Game_Map::TILE_HEIGHT)) * 4 * Game_Map::TILE_HEIGHT count_x = ($game_map.display_x - [0, [(x * Game_Map::REAL_RES_X) - center_x, max_x].min].max) / Game_Map::REAL_RES_X count_y = ($game_map.display_y - [0, [(y * Game_Map::REAL_RES_Y) - center_y, max_y].min].max) / Game_Map::REAL_RES_Y - if !@diag + if @diag + @diag = false + dir = nil + if count_x != 0 && 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_y.abs : count_x.abs + else @diag = true dir = nil if count_x > 0 @@ -110,21 +125,6 @@ class Interpreter end end count = [count_x.abs, count_y.abs].min - else - @diag = false - dir = nil - if count_x != 0 && 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 diff --git a/Data/Scripts/004_Game classes/006_Game_MapFactory.rb b/Data/Scripts/004_Game classes/006_Game_MapFactory.rb index 273916d79..bf0a72af8 100644 --- a/Data/Scripts/004_Game classes/006_Game_MapFactory.rb +++ b/Data/Scripts/004_Game classes/006_Game_MapFactory.rb @@ -185,10 +185,10 @@ class PokemonMapFactory return false if !event.through && event.character_name != "" end # Check passability of player - if !thisEvent.is_a?(Game_Player) - if $game_map.map_id == mapID && $game_player.x == x && $game_player.y == y - return false if !$game_player.through && $game_player.character_name != "" - end + if !thisEvent.is_a?(Game_Player) && + $game_map.map_id == mapID && $game_player.x == x && $game_player.y == y && + !$game_player.through && $game_player.character_name != "" + return false end return true end @@ -201,8 +201,8 @@ class PokemonMapFactory return false if !map.valid?(x, y) return true if thisEvent.through if thisEvent == $game_player - if !($DEBUG && Input.press?(Input::CTRL)) - return false if !map.passableStrict?(x, y, 0, thisEvent) + if !($DEBUG && Input.press?(Input::CTRL)) && !map.passableStrict?(x, y, 0, thisEvent) + return false end elsif !map.passableStrict?(x, y, 0, thisEvent) return false @@ -289,12 +289,12 @@ class PokemonMapFactory # NOTE: Assumes the event is 1x1 tile in size. Only returns one tile. def getFacingTile(direction = nil, event = nil, steps = 1) - event = $game_player if event == nil + event = $game_player if event.nil? return [0, 0, 0] if !event x = event.x y = event.y id = event.map.map_id - direction = event.direction if direction == nil + direction = event.direction if direction.nil? return getFacingTileFromPos(id, x, y, direction, steps) end @@ -511,6 +511,6 @@ end def updateTilesets maps = $map_factory.maps maps.each do |map| - map.updateTileset if map + map&.updateTileset end end diff --git a/Data/Scripts/004_Game classes/007_Game_Character.rb b/Data/Scripts/004_Game classes/007_Game_Character.rb index 7d07e32da..757e9e934 100644 --- a/Data/Scripts/004_Game classes/007_Game_Character.rb +++ b/Data/Scripts/004_Game classes/007_Game_Character.rb @@ -244,8 +244,9 @@ class Game_Character next if self == event || !event.at_coordinate?(new_x, new_y) || event.through return false if self != $game_player || event.character_name != "" end - if $game_player.x == new_x && $game_player.y == new_y - return false if !$game_player.through && @character_name != "" + if $game_player.x == new_x && $game_player.y == new_y && + !$game_player.through && @character_name != "" + return false end return true end @@ -356,7 +357,7 @@ class Game_Character end def force_move_route(move_route) - if @original_move_route == nil + if @original_move_route.nil? @original_move_route = @move_route @original_move_route_index = @move_route_index end diff --git a/Data/Scripts/004_Game classes/008_Game_Event.rb b/Data/Scripts/004_Game classes/008_Game_Event.rb index b6a549c79..2858ff207 100644 --- a/Data/Scripts/004_Game classes/008_Game_Event.rb +++ b/Data/Scripts/004_Game classes/008_Game_Event.rb @@ -99,7 +99,7 @@ class Game_Event < Game_Character return $PokemonGlobal.eventvars[[@map_id, @event.id]].to_i end - def expired?(secs = 86400) + def expired?(secs = 86_400) ontime = self.variable time = pbGetTimeNow return ontime && (time.to_i > ontime + secs) @@ -109,8 +109,8 @@ class Game_Event < Game_Character ontime = self.variable.to_i return false if !ontime now = pbGetTimeNow - elapsed = (now.to_i - ontime) / 86400 - elapsed += 1 if (now.to_i - ontime) % 86400 > ((now.hour * 3600) + (now.min * 60) + now.sec) + elapsed = (now.to_i - ontime) / 86_400 + elapsed += 1 if (now.to_i - ontime) % 86_400 > ((now.hour * 3600) + (now.min * 60) + now.sec) return elapsed >= days end @@ -141,12 +141,12 @@ class Game_Event < Game_Character def pbCheckEventTriggerAfterTurning return if $game_system.map_interpreter.running? || @starting - if @event.name[/trainer\((\d+)\)/i] - distance = $~[1].to_i - if @trigger == 2 && pbEventCanReachPlayer?(self, $game_player, distance) - start if !jumping? && !over_trigger? - end - end + return if @trigger != 2 # Event touch + return if !@event.name[/trainer\((\d+)\)/i] + distance = $~[1].to_i + return if !pbEventCanReachPlayer?(self, $game_player, distance) + return if jumping? || over_trigger? + start end def check_event_trigger_touch(dir) @@ -170,8 +170,8 @@ class Game_Event < Game_Character def check_event_trigger_auto case @trigger when 2 # Event touch - if at_coordinate?($game_player.x, $game_player.y) - start if !jumping? && over_trigger? + if at_coordinate?($game_player.x, $game_player.y) && !jumping? && over_trigger? + start end when 3 # Autorun start @@ -197,7 +197,7 @@ class Game_Event < Game_Character return if new_page == @page @page = new_page clear_starting - if @page == nil + if @page.nil? @tile_id = 0 @character_name = "" @character_hue = 0 diff --git a/Data/Scripts/004_Game classes/009_Game_Player.rb b/Data/Scripts/004_Game classes/009_Game_Player.rb index 9224412a7..9984a5205 100644 --- a/Data/Scripts/004_Game classes/009_Game_Player.rb +++ b/Data/Scripts/004_Game classes/009_Game_Player.rb @@ -185,13 +185,12 @@ class Game_Player < Game_Character return result if checkIfRunning && $game_system.map_interpreter.running? # All event loops $game_map.events.values.each do |event| + next if !triggers.include?(event.trigger) next if !event.name[/trainer\((\d+)\)/i] distance = $~[1].to_i - # If event coordinates and triggers are consistent - if pbEventCanReachPlayer?(event, self, distance) && triggers.include?(event.trigger) - # If starting determinant is front event (other than jumping) - result.push(event) if !event.jumping? && !event.over_trigger? - end + next if !pbEventCanReachPlayer?(event, self, distance) + next if event.jumping? || event.over_trigger? + result.push(event) end return result end @@ -202,13 +201,12 @@ class Game_Player < Game_Character return result if checkIfRunning && $game_system.map_interpreter.running? # All event loops $game_map.events.values.each do |event| + next if !triggers.include?(event.trigger) next if !event.name[/counter\((\d+)\)/i] distance = $~[1].to_i - # If event coordinates and triggers are consistent - if pbEventFacesPlayer?(event, self, distance) && triggers.include?(event.trigger) - # If starting determinant is front event (other than jumping) - result.push(event) if !event.jumping? && !event.over_trigger? - end + next if !pbEventFacesPlayer?(event, self, distance) + next if event.jumping? || event.over_trigger? + result.push(event) end return result end @@ -355,32 +353,29 @@ class Game_Player < Game_Character return false if !$game_map.valid?(new_x, new_y) # All event loops $game_map.events.values.each do |event| + next if !triggers.include?(event.trigger) # If event coordinates and triggers are consistent next if !event.at_coordinate?(new_x, new_y) - next if !triggers.include?(event.trigger) # If starting determinant is front event (other than jumping) next if event.jumping? || event.over_trigger? event.start result = true 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 coordinates of 1 tile further away - new_x += (@direction == 6 ? 1 : @direction == 4 ? -1 : 0) - new_y += (@direction == 2 ? 1 : @direction == 8 ? -1 : 0) - return false if !$game_map.valid?(new_x, new_y) - # All event loops - $game_map.events.values.each do |event| - # If event coordinates and triggers are consistent - next if !event.at_coordinate?(new_x, new_y) - next if !triggers.include?(event.trigger) - # If starting determinant is front event (other than jumping) - next if event.jumping? || event.over_trigger? - event.start - result = true - end + if result == false && $game_map.counter?(new_x, new_y) + # Calculate coordinates of 1 tile further away + new_x += (@direction == 6 ? 1 : @direction == 4 ? -1 : 0) + new_y += (@direction == 2 ? 1 : @direction == 8 ? -1 : 0) + return false if !$game_map.valid?(new_x, new_y) + # All event loops + $game_map.events.values.each do |event| + next if !triggers.include?(event.trigger) + # If event coordinates and triggers are consistent + next if !event.at_coordinate?(new_x, new_y) + # If starting determinant is front event (other than jumping) + next if event.jumping? || event.over_trigger? + event.start + result = true end end return result @@ -559,11 +554,10 @@ end def pbGetPlayerCharset(charset, trainer = nil, force = false) trainer = $player if !trainer outfit = (trainer) ? trainer.outfit : 0 - if $game_player && $game_player.charsetData && !force - return nil if $game_player.charsetData[0] == trainer.character_ID && - $game_player.charsetData[1] == charset && - $game_player.charsetData[2] == outfit - end + return nil if !force && $game_player&.charsetData && + $game_player.charsetData[0] == trainer.character_ID && + $game_player.charsetData[1] == charset && + $game_player.charsetData[2] == outfit $game_player.charsetData = [trainer.character_ID, charset, outfit] if $game_player ret = charset if pbResolveBitmap("Graphics/Characters/" + ret + "_" + outfit.to_s) diff --git a/Data/Scripts/004_Game classes/010_Game_CommonEvent.rb b/Data/Scripts/004_Game classes/010_Game_CommonEvent.rb index e688c7701..ffd91eba6 100644 --- a/Data/Scripts/004_Game classes/010_Game_CommonEvent.rb +++ b/Data/Scripts/004_Game classes/010_Game_CommonEvent.rb @@ -56,7 +56,7 @@ class Game_CommonEvent def refresh # Create an interpreter for parallel process if necessary if self.trigger == 2 && switchIsOn?(self.switch_id) - if @interpreter == nil + if @interpreter.nil? @interpreter = Interpreter.new end else diff --git a/Data/Scripts/005_Sprites/001_Sprite_Picture.rb b/Data/Scripts/005_Sprites/001_Sprite_Picture.rb index 75614d84c..ee5be7c2d 100644 --- a/Data/Scripts/005_Sprites/001_Sprite_Picture.rb +++ b/Data/Scripts/005_Sprites/001_Sprite_Picture.rb @@ -7,11 +7,11 @@ class Sprite_Picture end def dispose - @sprite.dispose if @sprite + @sprite&.dispose end def update - @sprite.update if @sprite + @sprite&.update # If picture file name is different from current one if @picture_name != @picture.name # Remember file name to instance variables @@ -27,7 +27,7 @@ class Sprite_Picture if @picture_name == "" # Set sprite to invisible if @sprite - @sprite.dispose if @sprite + @sprite&.dispose @sprite = nil end return diff --git a/Data/Scripts/005_Sprites/002_Sprite_Timer.rb b/Data/Scripts/005_Sprites/002_Sprite_Timer.rb index 5022d55f0..74e01d297 100644 --- a/Data/Scripts/005_Sprites/002_Sprite_Timer.rb +++ b/Data/Scripts/005_Sprites/002_Sprite_Timer.rb @@ -7,7 +7,7 @@ class Sprite_Timer end def dispose - @timer.dispose if @timer + @timer&.dispose @timer = nil @disposed = true end diff --git a/Data/Scripts/005_Sprites/003_Sprite_Character.rb b/Data/Scripts/005_Sprites/003_Sprite_Character.rb index bc6f6b450..dadce49d9 100644 --- a/Data/Scripts/005_Sprites/003_Sprite_Character.rb +++ b/Data/Scripts/005_Sprites/003_Sprite_Character.rb @@ -8,7 +8,7 @@ class BushBitmap end def dispose - @bitmaps.each { |b| b.dispose if b } + @bitmaps.each { |b| b&.dispose } end def bitmap @@ -80,13 +80,13 @@ class Sprite_Character < RPG::Sprite end def dispose - @bushbitmap.dispose if @bushbitmap + @bushbitmap&.dispose @bushbitmap = nil - @charbitmap.dispose if @charbitmap + @charbitmap&.dispose @charbitmap = nil - @reflection.dispose if @reflection + @reflection&.dispose @reflection = nil - @surfbase.dispose if @surfbase + @surfbase&.dispose @surfbase = nil super end @@ -102,12 +102,12 @@ class Sprite_Character < RPG::Sprite @character_name = @character.character_name @character_hue = @character.character_hue @oldbushdepth = @character.bush_depth - @charbitmap.dispose if @charbitmap + @charbitmap&.dispose if @tile_id >= 384 @charbitmap = pbGetTileBitmap(@character.map.tileset_name, @tile_id, @character_hue, @character.width, @character.height) @charbitmapAnimated = false - @bushbitmap.dispose if @bushbitmap + @bushbitmap&.dispose @bushbitmap = nil @spriteoffset = false @cw = Game_Map::TILE_WIDTH * @character.width @@ -121,7 +121,7 @@ class Sprite_Character < RPG::Sprite ) RPG::Cache.retain('Graphics/Characters/', @character_name, @character_hue) if @character == $game_player @charbitmapAnimated = true - @bushbitmap.dispose if @bushbitmap + @bushbitmap&.dispose @bushbitmap = nil @spriteoffset = @character_name[/offset/i] @cw = @charbitmap.width / 4 @@ -163,7 +163,7 @@ class Sprite_Character < RPG::Sprite animation(animation, true) @character.animation_id = 0 end - @reflection.update if @reflection - @surfbase.update if @surfbase + @reflection&.update + @surfbase&.update end end diff --git a/Data/Scripts/005_Sprites/004_Sprite_Reflection.rb b/Data/Scripts/005_Sprites/004_Sprite_Reflection.rb index 55a46096d..fddce07d7 100644 --- a/Data/Scripts/005_Sprites/004_Sprite_Reflection.rb +++ b/Data/Scripts/005_Sprites/004_Sprite_Reflection.rb @@ -8,11 +8,9 @@ class Sprite_Reflection @event = event @height = 0 @fixedheight = false - if @event && @event != $game_player - if @event.name[/reflection\((\d+)\)/i] - @height = $~[1].to_i || 0 - @fixedheight = true - end + if @event != $game_player && @event&.name[/reflection\((\d+)\)/i] + @height = $~[1].to_i || 0 + @fixedheight = true end @viewport = viewport @disposed = false @@ -21,7 +19,7 @@ class Sprite_Reflection def dispose if !@disposed - @sprite.dispose if @sprite + @sprite&.dispose @sprite = nil @disposed = true end diff --git a/Data/Scripts/005_Sprites/005_Sprite_SurfBase.rb b/Data/Scripts/005_Sprites/005_Sprite_SurfBase.rb index f66e1bbc2..457111518 100644 --- a/Data/Scripts/005_Sprites/005_Sprite_SurfBase.rb +++ b/Data/Scripts/005_Sprites/005_Sprite_SurfBase.rb @@ -21,7 +21,7 @@ class Sprite_SurfBase def dispose return if @disposed - @sprite.dispose if @sprite + @sprite&.dispose @sprite = nil @surfbitmap.dispose @divebitmap.dispose diff --git a/Data/Scripts/005_Sprites/007_Spriteset_Map.rb b/Data/Scripts/005_Sprites/007_Spriteset_Map.rb index d14147ed9..9be78e3a9 100644 --- a/Data/Scripts/005_Sprites/007_Spriteset_Map.rb +++ b/Data/Scripts/005_Sprites/007_Spriteset_Map.rb @@ -122,10 +122,10 @@ class Spriteset_Map @character_sprites.each do |sprite| sprite.update end - if self.map != $game_map - @weather.fade_in(:None, 0, 20) - else + if self.map == $game_map @weather.fade_in($game_screen.weather_type, $game_screen.weather_max, $game_screen.weather_duration) + else + @weather.fade_in(:None, 0, 20) end @weather.ox = tmox @weather.oy = tmoy diff --git a/Data/Scripts/005_Sprites/009_Sprite_DynamicShadows.rb b/Data/Scripts/005_Sprites/009_Sprite_DynamicShadows.rb index 37f6edfb6..45761a647 100644 --- a/Data/Scripts/005_Sprites/009_Sprite_DynamicShadows.rb +++ b/Data/Scripts/005_Sprites/009_Sprite_DynamicShadows.rb @@ -19,7 +19,7 @@ class Sprite_Shadow < RPG::Sprite end def dispose - @chbitmap.dispose if @chbitmap + @chbitmap&.dispose super end @@ -35,7 +35,7 @@ class Sprite_Shadow < RPG::Sprite @tile_id = @character.tile_id @character_name = @character.character_name @character_hue = @character.character_hue - @chbitmap.dispose if @chbitmap + @chbitmap&.dispose if @tile_id >= 384 @chbitmap = pbGetTileBitmap(@character.map.tileset_name, @tile_id, @character.character_hue) @@ -89,7 +89,7 @@ class Sprite_Shadow < RPG::Sprite @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.opacity = @self_opacity * 13_000 / ((@distance * 370 / @distancemax) + 6000) self.angle = 57.3 * Math.atan2(@deltax, @deltay) @angle_trigo = self.angle + 90 @angle_trigo += 360 if @angle_trigo < 0 @@ -149,7 +149,7 @@ class Sprite_Character < RPG::Sprite end def clearShadows - @ombrelist.each { |s| s.dispose if s } + @ombrelist.each { |s| s&.dispose } @ombrelist.clear end @@ -185,9 +185,8 @@ class Spriteset_Map map = $game_map if !map map.events.keys.sort.each do |k| ev = map.events[k] - warn = true if (ev.list != nil && ev.list.length > 0 && - ev.list[0].code == 108 && - (ev.list[0].parameters == ["s"] || ev.list[0].parameters == ["o"])) + warn = true if ev.list != nil && ev.list.length > 0 && ev.list[0].code == 108 && + (ev.list[0].parameters == ["s"] || ev.list[0].parameters == ["o"]) params = XPML_read(map, "Shadow Source", ev, 4) @shadows.push([ev] + params) if params != nil end @@ -225,11 +224,11 @@ end #=================================================== def XPML_read(map, markup, event, max_param_number = 0) parameter_list = nil - return nil if !event || event.list == nil + return nil if !event || event.list.nil? event.list.size.times do |i| if event.list[i].code == 108 && event.list[i].parameters[0].downcase == "begin " + markup.downcase - parameter_list = [] if parameter_list == nil + parameter_list = [] if parameter_list.nil? ((i + 1)...event.list.size).each do |j| if event.list[j].code == 108 parts = event.list[j].parameters[0].split diff --git a/Data/Scripts/005_Sprites/010_ParticleEngine.rb b/Data/Scripts/005_Sprites/010_ParticleEngine.rb index 46598246c..2a7cc40ef 100644 --- a/Data/Scripts/005_Sprites/010_ParticleEngine.rb +++ b/Data/Scripts/005_Sprites/010_ParticleEngine.rb @@ -57,17 +57,17 @@ class Particle_Engine def realloc_effect(event, particle) type = pbEventCommentInput(event, 1, "Particle Engine Type") if type.nil? - particle.dispose if particle + particle&.dispose return nil end type = type[0].downcase cls = @effects[type] if cls.nil? - particle.dispose if particle + particle&.dispose return nil end if !particle || !particle.is_a?(cls) - particle.dispose if particle + particle&.dispose particle = cls.new(event, @viewport) end return particle @@ -93,7 +93,7 @@ class Particle_Engine particle = realloc_effect(event, particle) @effect[i] = particle end - particle.update if particle + particle&.update end end end @@ -135,7 +135,7 @@ class ParticleSprite end def dispose - @sprite.dispose if @sprite + @sprite&.dispose end def bitmap=(value) @@ -517,9 +517,9 @@ class Particle_Engine::Smokescreen < ParticleEffect_Event end multiple = 1.7 xgrav = @xgravity * multiple / @slowdown - xgrav = -xgrav if (rand(2) == 1) + xgrav = -xgrav if rand(2) == 1 ygrav = @ygravity * multiple / @slowdown - ygrav = -ygrav if (rand(2) == 1) + ygrav = -ygrav if rand(2) == 1 @particlex[i] += xgrav @particley[i] += ygrav @particlex[i] -= @__offsetx diff --git a/Data/Scripts/005_Sprites/013_ScreenPosHelper.rb b/Data/Scripts/005_Sprites/013_ScreenPosHelper.rb index e15424959..9ba1747de 100644 --- a/Data/Scripts/005_Sprites/013_ScreenPosHelper.rb +++ b/Data/Scripts/005_Sprites/013_ScreenPosHelper.rb @@ -29,7 +29,7 @@ module ScreenPosHelper end def self.pbScreenZ(ch, height = nil) - if height == nil + if height.nil? height = 0 if ch.tile_id > 0 height = 32 diff --git a/Data/Scripts/006_Map renderer/001_TilemapRenderer.rb b/Data/Scripts/006_Map renderer/001_TilemapRenderer.rb index 9965c82a4..5f8d5b2a3 100644 --- a/Data/Scripts/006_Map renderer/001_TilemapRenderer.rb +++ b/Data/Scripts/006_Map renderer/001_TilemapRenderer.rb @@ -171,7 +171,7 @@ class TilemapRenderer bitmap = @bitmaps[filename] @frame_counts[filename] = [bitmap.width / SOURCE_TILE_WIDTH, 1].max if bitmap.height > SOURCE_TILE_HEIGHT && @bitmap_wraps[filename] - @frame_counts[filename] /= 2 if @bitmap_wraps[filename] + @frame_counts[filename] /= 2 end end return @frame_counts[filename] diff --git a/Data/Scripts/006_Map renderer/004_TileDrawingHelper.rb b/Data/Scripts/006_Map renderer/004_TileDrawingHelper.rb index ac6c0674b..8373b2190 100644 --- a/Data/Scripts/006_Map renderer/004_TileDrawingHelper.rb +++ b/Data/Scripts/006_Map renderer/004_TileDrawingHelper.rb @@ -79,7 +79,7 @@ class TileDrawingHelper end def dispose - @tileset.dispose if @tileset + @tileset&.dispose @tileset = nil @autotiles.each_with_index do |autotile, i| autotile.dispose @@ -187,7 +187,7 @@ def bltMinimapAutotile(dstBitmap, x, y, srcBitmap, id) end def passable?(passages, tile_id) - return false if tile_id == nil + return false if tile_id.nil? passage = passages[tile_id] return (passage && passage < 15) end diff --git a/Data/Scripts/007_Objects and windows/001_RPG_Cache.rb b/Data/Scripts/007_Objects and windows/001_RPG_Cache.rb index 75785c0dd..ed1d473fc 100644 --- a/Data/Scripts/007_Objects and windows/001_RPG_Cache.rb +++ b/Data/Scripts/007_Objects and windows/001_RPG_Cache.rb @@ -27,7 +27,7 @@ module RPG def self.fromCache(i) return nil if !@cache.include?(i) obj = @cache[i] - return nil if obj && obj.disposed? + return nil if obj&.disposed? return obj end diff --git a/Data/Scripts/007_Objects and windows/002_MessageConfig.rb b/Data/Scripts/007_Objects and windows/002_MessageConfig.rb index b76c787a7..c5c1cd9b3 100644 --- a/Data/Scripts/007_Objects and windows/002_MessageConfig.rb +++ b/Data/Scripts/007_Objects and windows/002_MessageConfig.rb @@ -177,7 +177,7 @@ end def pbBottomLeftLines(window, lines, width = nil) window.x = 0 - window.width = width ? width : Graphics.width + window.width = width || Graphics.width window.height = (window.borderY rescue 32) + (lines * 32) window.y = Graphics.height - window.height end @@ -393,10 +393,10 @@ end def pbDoEnsureBitmap(bitmap, dwidth, dheight) if !bitmap || bitmap.disposed? || bitmap.width < dwidth || bitmap.height < dheight oldfont = (bitmap && !bitmap.disposed?) ? bitmap.font : nil - bitmap.dispose if bitmap + bitmap&.dispose bitmap = Bitmap.new([1, dwidth].max, [1, dheight].max) (oldfont) ? bitmap.font = oldfont : pbSetSystemFont(bitmap) - bitmap.font.shadow = false if bitmap.font && bitmap.font.respond_to?("shadow") + bitmap.font.shadow = false if bitmap.font&.respond_to?("shadow") end return bitmap end @@ -666,7 +666,7 @@ end def pbRestoreActivations(sprites, activeStatuses) return if !sprites || !activeStatuses activeStatuses.keys.each do |k| - if sprites[k] && sprites[k].is_a?(Window) && !pbDisposed?(sprites[k]) + if sprites[k].is_a?(Window) && !pbDisposed?(sprites[k]) sprites[k].active = activeStatuses[k] ? true : false end end @@ -689,7 +689,7 @@ def pbActivateWindow(sprites, key) return if !sprites activeStatuses = {} sprites.each do |i| - if i[1] && i[1].is_a?(Window) && !pbDisposed?(i[1]) + if i[1].is_a?(Window) && !pbDisposed?(i[1]) activeStatuses[i[0]] = i[1].active i[1].active = (i[0] == key) end @@ -717,7 +717,7 @@ end def addBackgroundPlane(sprites, planename, background, viewport = nil) sprites[planename] = AnimatedPlane.new(viewport) bitmapName = pbResolveBitmap("Graphics/Pictures/#{background}") - if bitmapName == nil + if bitmapName.nil? # Plane should exist in any case sprites[planename].bitmap = nil sprites[planename].visible = false @@ -739,7 +739,7 @@ end # _viewport_ is a viewport to place the background in. def addBackgroundOrColoredPlane(sprites, planename, background, color, viewport = nil) bitmapName = pbResolveBitmap("Graphics/Pictures/#{background}") - if bitmapName == nil + if bitmapName.nil? # Plane should exist in any case sprites[planename] = ColoredPlane.new(color, viewport) else @@ -773,7 +773,7 @@ if !defined?(_INTL) def _INTL(*args) string = args[0].clone (1...args.length).each do |i| - string.gsub!(/\{#{i}\}/, "#{args[i]}") + string.gsub!(/\{#{i}\}/, args[i].to_s) end return string end @@ -795,7 +795,7 @@ if !defined?(_MAPINTL) def _MAPINTL(*args) string = args[1].clone (2...args.length).each do |i| - string.gsub!(/\{#{i}\}/, "#{args[i + 1]}") + string.gsub!(/\{#{i}\}/, args[i + 1].to_s) end return string end diff --git a/Data/Scripts/007_Objects and windows/003_Window.rb b/Data/Scripts/007_Objects and windows/003_Window.rb index 16e67bb9c..1de8100fb 100644 --- a/Data/Scripts/007_Objects and windows/003_Window.rb +++ b/Data/Scripts/007_Objects and windows/003_Window.rb @@ -127,16 +127,16 @@ class Window def dispose if !self.disposed? @sprites.each do |i| - i[1].dispose if i[1] + i[1]&.dispose @sprites[i[0]] = nil end @sidebitmaps.each_with_index do |bitmap, i| - bitmap.dispose if bitmap + bitmap&.dispose @sidebitmaps[i] = nil end @blankcontents.dispose - @cursorbitmap.dispose if @cursorbitmap - @backbitmap.dispose if @backbitmap + @cursorbitmap&.dispose + @backbitmap&.dispose @sprites.clear @sidebitmaps.clear @_windowskin = nil @@ -191,7 +191,7 @@ class Window def windowskin=(value) @_windowskin = value - if value && value.is_a?(Bitmap) && !value.disposed? && value.width == 128 + if value.is_a?(Bitmap) && !value.disposed? && value.width == 128 @rpgvx = true else @rpgvx = false @@ -210,10 +210,10 @@ class Window end def cursor_rect=(value) - if !value - @cursor_rect.empty - else + if value @cursor_rect.set(value.x, value.y, value.width, value.height) + else + @cursor_rect.empty end end @@ -322,7 +322,7 @@ class Window def ensureBitmap(bitmap, dwidth, dheight) if !bitmap || bitmap.disposed? || bitmap.width < dwidth || bitmap.height < dheight - bitmap.dispose if bitmap + bitmap&.dispose bitmap = Bitmap.new([1, dwidth].max, [1, dheight].max) end return bitmap @@ -571,7 +571,12 @@ class Window @sprites["back"].src_rect.set(0, 0, 0, 0) end end - if @openness != 255 + if @openness == 255 + @spritekeys.each do |k| + sprite = @sprites[k] + sprite.zoom_y = 1.0 + end + else opn = @openness / 255.0 @spritekeys.each do |k| sprite = @sprites[k] @@ -580,11 +585,6 @@ class Window sprite.oy = 0 sprite.y = (@y + (@height / 2.0) + (@height * ratio * opn) - (@height / 2 * opn)).floor end - else - @spritekeys.each do |k| - sprite = @sprites[k] - sprite.zoom_y = 1.0 - end end i = 0 # Ensure Z order diff --git a/Data/Scripts/007_Objects and windows/004_SpriteWindow.rb b/Data/Scripts/007_Objects and windows/004_SpriteWindow.rb index 77e9b9d34..ebb28c414 100644 --- a/Data/Scripts/007_Objects and windows/004_SpriteWindow.rb +++ b/Data/Scripts/007_Objects and windows/004_SpriteWindow.rb @@ -113,16 +113,16 @@ class SpriteWindow < Window def dispose if !self.disposed? @sprites.each do |i| - i[1].dispose if i[1] + i[1]&.dispose @sprites[i[0]] = nil end @sidebitmaps.each_with_index do |bitmap, i| - bitmap.dispose if bitmap + bitmap&.dispose @sidebitmaps[i] = nil end @blankcontents.dispose - @cursorbitmap.dispose if @cursorbitmap - @backbitmap.dispose if @backbitmap + @cursorbitmap&.dispose + @backbitmap&.dispose @sprites.clear @sidebitmaps.clear @_windowskin = nil @@ -143,7 +143,7 @@ class SpriteWindow < Window def viewport=(value) @viewport = value @spritekeys.each do |i| - @sprites[i].dispose if @sprites[i] + @sprites[i]&.dispose if @sprites[i].is_a?(Sprite) @sprites[i] = Sprite.new(@viewport) else @@ -189,10 +189,10 @@ class SpriteWindow < Window end def cursor_rect=(value) - if !value - @cursor_rect.empty - else + if value @cursor_rect.set(value.x, value.y, value.width, value.height) + else + @cursor_rect.empty end end @@ -358,7 +358,7 @@ class SpriteWindow < Window @trim = [16, 16, 16, 16] end else - if value && value.is_a?(Bitmap) && !value.disposed? && value.width == 128 + if value.is_a?(Bitmap) && !value.disposed? && value.width == 128 @rpgvx = true else @rpgvx = false @@ -442,7 +442,7 @@ class SpriteWindow < Window def ensureBitmap(bitmap, dwidth, dheight) if !bitmap || bitmap.disposed? || bitmap.width < dwidth || bitmap.height < dheight - bitmap.dispose if bitmap + bitmap&.dispose bitmap = Bitmap.new([1, dwidth].max, [1, dheight].max) end return bitmap @@ -631,15 +631,13 @@ class SpriteWindow < Window end @sprites["contents"].x = @x + trimStartX @sprites["contents"].y = @y + trimStartY - if (@compat & CompatBits::ShowScrollArrows) > 0 && @skinformat == 0 - # Compatibility mode: Make scroll arrows visible - if @skinformat == 0 && @_windowskin && !@_windowskin.disposed? && - @contents && !@contents.disposed? - @sprites["scroll0"].visible = @visible && hascontents && @oy > 0 - @sprites["scroll1"].visible = @visible && hascontents && @ox > 0 - @sprites["scroll2"].visible = @visible && (@contents.width - @ox) > @width - trimWidth - @sprites["scroll3"].visible = @visible && (@contents.height - @oy) > @height - trimHeight - end + if (@compat & CompatBits::ShowScrollArrows) > 0 && @skinformat == 0 && + @_windowskin && !@_windowskin.disposed? && + @contents && !@contents.disposed? + @sprites["scroll0"].visible = @visible && hascontents && @oy > 0 + @sprites["scroll1"].visible = @visible && hascontents && @ox > 0 + @sprites["scroll2"].visible = @visible && (@contents.width - @ox) > @width - trimWidth + @sprites["scroll3"].visible = @visible && (@contents.height - @oy) > @height - trimHeight end if @_windowskin && !@_windowskin.disposed? borderX = startX + endX @@ -781,7 +779,13 @@ class SpriteWindow < Window @sprites["back"].src_rect.set(0, 0, 0, 0) end end - if @openness != 255 + if @openness == 255 + @spritekeys.each do |k| + sprite = @sprites[k] + sprite.zoom_x = 1.0 + sprite.zoom_y = 1.0 + end + else opn = @openness / 255.0 @spritekeys.each do |k| sprite = @sprites[k] @@ -791,12 +795,6 @@ class SpriteWindow < Window sprite.oy = 0 sprite.y = (@y + (@height / 2.0) + (@height * ratio * opn) - (@height / 2 * opn)).floor end - else - @spritekeys.each do |k| - sprite = @sprites[k] - sprite.zoom_x = 1.0 - sprite.zoom_y = 1.0 - end end i = 0 # Ensure Z order @@ -861,7 +859,7 @@ class SpriteWindow_Base < SpriteWindow end def setSkin(skin) # Filename of windowskin to apply. Supports XP, VX, and animated skins. - @customskin.dispose if @customskin + @customskin&.dispose @customskin = nil resolvedName = pbResolveBitmap(skin) return if nil_or_empty?(resolvedName) @@ -875,7 +873,7 @@ class SpriteWindow_Base < SpriteWindow end def setSystemFrame - @customskin.dispose if @customskin + @customskin&.dispose @customskin = nil __setWindowskin(@sysframe.bitmap) __resolveSystemFrame @@ -899,7 +897,7 @@ class SpriteWindow_Base < SpriteWindow if @curframe != MessageConfig.pbGetSystemFrame @curframe = MessageConfig.pbGetSystemFrame if @sysframe && !@customskin - @sysframe.dispose if @sysframe + @sysframe&.dispose @sysframe = AnimatedBitmap.new(@curframe) RPG::Cache.retain(@curframe) if @curframe && !@curframe.empty? @resolvedFrame = nil @@ -924,9 +922,9 @@ class SpriteWindow_Base < SpriteWindow end def dispose - self.contents.dispose if self.contents + self.contents&.dispose @sysframe.dispose - @customskin.dispose if @customskin + @customskin&.dispose super end end diff --git a/Data/Scripts/007_Objects and windows/005_SpriteWindow_text.rb b/Data/Scripts/007_Objects and windows/005_SpriteWindow_text.rb index 7e59891e4..3a0f14893 100644 --- a/Data/Scripts/007_Objects and windows/005_SpriteWindow_text.rb +++ b/Data/Scripts/007_Objects and windows/005_SpriteWindow_text.rb @@ -160,7 +160,7 @@ class Window_AdvancedTextPokemon < SpriteWindow_Base def dispose return if disposed? - @pausesprite.dispose if @pausesprite + @pausesprite&.dispose @pausesprite = nil super end @@ -490,10 +490,8 @@ class Window_AdvancedTextPokemon < SpriteWindow_Base drawSingleFormattedChar(self.contents, @fmtchars[i]) @lastDrawnChar = i end - if !self.letterbyletter - # all characters were drawn, reset old font - self.contents.font = @oldfont if @oldfont - end + # all characters were drawn, reset old font + self.contents.font = @oldfont if !self.letterbyletter && @oldfont if numchars > 0 && numchars != @numtextchars fch = @fmtchars[numchars - 1] if fch @@ -579,7 +577,7 @@ class Window_AdvancedTextPokemon < SpriteWindow_Base def update super - @pausesprite.update if @pausesprite && @pausesprite.visible + @pausesprite.update if @pausesprite&.visible if @waitcount > 0 @waitcount -= 1 return @@ -601,7 +599,7 @@ class Window_AdvancedTextPokemon < SpriteWindow_Base break if @textchars[@curchar] == "\n" || # newline @textchars[@curchar] == "\1" || # pause @textchars[@curchar] == "\2" || # letter-by-letter break - @textchars[@curchar] == nil + @textchars[@curchar].nil? end end end diff --git a/Data/Scripts/007_Objects and windows/006_SpriteWindow_pictures.rb b/Data/Scripts/007_Objects and windows/006_SpriteWindow_pictures.rb index 2d3920180..cf0f75a33 100644 --- a/Data/Scripts/007_Objects and windows/006_SpriteWindow_pictures.rb +++ b/Data/Scripts/007_Objects and windows/006_SpriteWindow_pictures.rb @@ -26,7 +26,7 @@ class IconWindow < SpriteWindow_Base end def clearBitmaps - @_iconbitmap.dispose if @_iconbitmap + @_iconbitmap&.dispose @_iconbitmap = nil self.contents = nil if !self.disposed? end @@ -40,13 +40,13 @@ class IconWindow < SpriteWindow_Base def setBitmap(file, hue = 0) clearBitmaps @name = file - return if file == nil - if file != "" + return if file.nil? + if file == "" + @_iconbitmap = nil + else @_iconbitmap = AnimatedBitmap.new(file, hue) # for compatibility self.contents = @_iconbitmap ? @_iconbitmap.bitmap : nil - else - @_iconbitmap = nil end end end @@ -84,7 +84,7 @@ class PictureWindow < SpriteWindow_Base end def clearBitmaps - @_iconbitmap.dispose if @_iconbitmap + @_iconbitmap&.dispose @_iconbitmap = nil self.contents = nil if !self.disposed? end diff --git a/Data/Scripts/007_Objects and windows/007_SpriteWrapper.rb b/Data/Scripts/007_Objects and windows/007_SpriteWrapper.rb index ffa426013..b1908c1f6 100644 --- a/Data/Scripts/007_Objects and windows/007_SpriteWrapper.rb +++ b/Data/Scripts/007_Objects and windows/007_SpriteWrapper.rb @@ -280,19 +280,19 @@ class IconSprite < SpriteWrapper oldrc = self.src_rect clearBitmaps @name = file - return if file == nil - if file != "" + return if file.nil? + if file == "" + @_iconbitmap = nil + else @_iconbitmap = AnimatedBitmap.new(file, hue) # for compatibility self.bitmap = @_iconbitmap ? @_iconbitmap.bitmap : nil self.src_rect = oldrc - else - @_iconbitmap = nil end end def clearBitmaps - @_iconbitmap.dispose if @_iconbitmap + @_iconbitmap&.dispose @_iconbitmap = nil self.bitmap = nil if !self.disposed? end @@ -336,7 +336,7 @@ class ChangelingSprite < SpriteWrapper end def addBitmap(key, path) - @bitmaps[key].dispose if @bitmaps[key] + @bitmaps[key]&.dispose @bitmaps[key] = AnimatedBitmap.new(path) end diff --git a/Data/Scripts/007_Objects and windows/009_Planes.rb b/Data/Scripts/007_Objects and windows/009_Planes.rb index b245e7f8e..76dc035d5 100644 --- a/Data/Scripts/007_Objects and windows/009_Planes.rb +++ b/Data/Scripts/007_Objects and windows/009_Planes.rb @@ -17,7 +17,7 @@ class ColoredPlane < Plane end def dispose - self.bitmap.dispose if self.bitmap + self.bitmap&.dispose super end @@ -59,7 +59,7 @@ class AnimatedPlane < Plane private def clear_bitmap - @bitmap.dispose if @bitmap + @bitmap&.dispose @bitmap = nil self.bitmap = nil if !self.disposed? end diff --git a/Data/Scripts/007_Objects and windows/010_DrawText.rb b/Data/Scripts/007_Objects and windows/010_DrawText.rb index 02518a726..577d75cce 100644 --- a/Data/Scripts/007_Objects and windows/010_DrawText.rb +++ b/Data/Scripts/007_Objects and windows/010_DrawText.rb @@ -174,7 +174,7 @@ def getFormattedTextFast(bitmap, xDst, yDst, widthDst, heightDst, text, lineheig characters = [] textchunks = [] textchunks.push(text) - text = textchunks.join("") + text = textchunks.join textchars = text.scan(/./m) lastword = [0, 0] # position of last word hadspace = false @@ -406,7 +406,7 @@ def getFormattedText(bitmap, xDst, yDst, widthDst, heightDst, text, lineheight = if controls.length == 0 ret = getFormattedTextFast(bitmap, xDst, yDst, widthDst, heightDst, text, lineheight, newlineBreaks, explicitBreaksOnly) - dummybitmap.dispose if dummybitmap + dummybitmap&.dispose return ret end x = y = 0 @@ -414,7 +414,7 @@ def getFormattedText(bitmap, xDst, yDst, widthDst, heightDst, text, lineheight = charactersInternal = [] # realtext = nil # realtextStart = "" -# if !explicitBreaksOnly && textchunks.join("").length == 0 +# if !explicitBreaksOnly && textchunks.join.length == 0 # # All commands occurred at the beginning of the text string # realtext = (newlineBreaks) ? text : text.gsub(/\n/, " ") # realtextStart = oldtext[0, oldtext.length - realtext.length] @@ -432,7 +432,7 @@ def getFormattedText(bitmap, xDst, yDst, widthDst, heightDst, text, lineheight = textlen += textchunks[i].scan(/./m).length control[2] = textlen end - text = textchunks.join("") + text = textchunks.join textchars = text.scan(/./m) colorstack = [] boldcount = 0 @@ -830,7 +830,7 @@ def getFormattedText(bitmap, xDst, yDst, widthDst, heightDst, text, lineheight = # Remove all characters with Y greater or equal to _yDst_+_heightDst_ characters.delete_if { |ch| ch[2] >= yDst + heightDst } if heightDst >= 0 bitmap.font = oldfont - dummybitmap.dispose if dummybitmap + dummybitmap&.dispose return characters end @@ -854,7 +854,7 @@ def getLineBrokenText(bitmap, value, width, dims) return ret if !bitmap || bitmap.disposed? || width <= 0 textmsg = value.clone ret.push(["", 0, 0, 0, bitmap.text_size("X").height, 0, 0, 0, 0]) - while ((c = textmsg.slice!(/\n|(\S*([ \r\t\f]?))/)) != nil) + while (c = textmsg.slice!(/\n|(\S*([ \r\t\f]?))/)) != nil break if c == "" length = c.scan(/./m).length ccheck = c @@ -1083,8 +1083,8 @@ def drawTextEx(bitmap, x, y, width, numlines, text, baseColor, shadowColor) end def drawFormattedTextEx(bitmap, x, y, width, text, baseColor = nil, shadowColor = nil, lineheight = 32) - base = !baseColor ? Color.new(12 * 8, 12 * 8, 12 * 8) : baseColor.clone - shadow = !shadowColor ? Color.new(26 * 8, 26 * 8, 25 * 8) : shadowColor.clone + base = baseColor ? baseColor.clone : Color.new(12 * 8, 12 * 8, 12 * 8) + shadow = shadowColor ? shadowColor.clone : Color.new(26 * 8, 26 * 8, 25 * 8) text = "" + text chars = getFormattedText(bitmap, x, y, width, -1, text, lineheight) drawFormattedChars(bitmap, chars) diff --git a/Data/Scripts/007_Objects and windows/011_Messages.rb b/Data/Scripts/007_Objects and windows/011_Messages.rb index 3bfa8ed69..b2929668b 100644 --- a/Data/Scripts/007_Objects and windows/011_Messages.rb +++ b/Data/Scripts/007_Objects and windows/011_Messages.rb @@ -7,15 +7,15 @@ end def pbMapInterpreterRunning? interp = pbMapInterpreter - return interp && interp.running? + return interp&.running? end def pbRefreshSceneMap - $scene.miniupdate if $scene && $scene.is_a?(Scene_Map) + $scene.miniupdate if $scene.is_a?(Scene_Map) end def pbUpdateSceneMap - $scene.miniupdate if $scene && $scene.is_a?(Scene_Map) && !pbIsFaded? + $scene.miniupdate if $scene.is_a?(Scene_Map) && !pbIsFaded? end #=============================================================================== @@ -26,7 +26,7 @@ def pbEventCommentInput(*args) list = args[0].list # List of commands for event or event page elements = args[1] # Number of elements trigger = args[2] # Trigger - return nil if list == nil + return nil if list.nil? return nil unless list.is_a?(Array) list.each do |item| next unless item.code == 108 || item.code == 408 @@ -186,7 +186,7 @@ def pbChooseNumber(msgwindow, params) Input.update pbUpdateSceneMap cmdwindow.update - msgwindow.update if msgwindow + msgwindow&.update yield if block_given? if Input.trigger?(Input::USE) ret = cmdwindow.number @@ -220,7 +220,7 @@ class FaceWindowVX < SpriteWindow_Base faceinfo = face.split(",") facefile = pbResolveBitmap("Graphics/Faces/" + faceinfo[0]) facefile = pbResolveBitmap("Graphics/Pictures/" + faceinfo[0]) if !facefile - self.contents.dispose if self.contents + self.contents&.dispose @faceIndex = faceinfo[1].to_i @facebitmaptmp = AnimatedBitmap.new(facefile) @facebitmap = BitmapWrapper.new(96, 96) @@ -240,7 +240,7 @@ class FaceWindowVX < SpriteWindow_Base def dispose @facebitmaptmp.dispose - @facebitmap.dispose if @facebitmap + @facebitmap&.dispose super end end @@ -374,10 +374,10 @@ end #=============================================================================== def pbCreateStatusWindow(viewport = nil) msgwindow = Window_AdvancedTextPokemon.new("") - if !viewport - msgwindow.z = 99999 - else + if viewport msgwindow.viewport = viewport + else + msgwindow.z = 99999 end msgwindow.visible = false msgwindow.letterbyletter = false @@ -389,10 +389,10 @@ end def pbCreateMessageWindow(viewport = nil, skin = nil) msgwindow = Window_AdvancedTextPokemon.new("") - if !viewport - msgwindow.z = 99999 - else + if viewport msgwindow.viewport = viewport + else + msgwindow.z = 99999 end msgwindow.visible = true msgwindow.letterbyletter = true @@ -447,10 +447,10 @@ def pbMessageDisplay(msgwindow, message, letterbyletter = true, commandProc = ni text.gsub!(/\\pm/i, _INTL("${1}", $player.money.to_s_formatted)) if $player text.gsub!(/\\n/i, "\n") text.gsub!(/\\\[([0-9a-f]{8,8})\]/i) { "" } - text.gsub!(/\\pg/i, "\\b") if $player && $player.male? - text.gsub!(/\\pg/i, "\\r") if $player && $player.female? - text.gsub!(/\\pog/i, "\\r") if $player && $player.male? - text.gsub!(/\\pog/i, "\\b") if $player && $player.female? + text.gsub!(/\\pg/i, "\\b") if $player&.male? + text.gsub!(/\\pg/i, "\\r") if $player&.female? + text.gsub!(/\\pog/i, "\\r") if $player&.male? + text.gsub!(/\\pog/i, "\\b") if $player&.female? text.gsub!(/\\pg/i, "") text.gsub!(/\\pog/i, "") text.gsub!(/\\b/i, "") @@ -517,7 +517,7 @@ def pbMessageDisplay(msgwindow, message, letterbyletter = true, commandProc = ni textlen += toUnformattedText(textchunks[i]).scan(/./m).length controls[i][2] = textlen end - text = textchunks.join("") + text = textchunks.join signWaitCount = 0 signWaitTime = Graphics.frame_rate / 2 haveSpecialClose = false @@ -534,10 +534,10 @@ def pbMessageDisplay(msgwindow, message, letterbyletter = true, commandProc = ni haveSpecialClose = true specialCloseSE = param when "f" - facewindow.dispose if facewindow + facewindow&.dispose facewindow = PictureWindow.new("Graphics/Pictures/#{param}") when "ff" - facewindow.dispose if facewindow + facewindow&.dispose facewindow = FaceWindowVX.new(param) when "ch" cmds = param.clone @@ -588,25 +588,25 @@ def pbMessageDisplay(msgwindow, message, letterbyletter = true, commandProc = ni param = controls[i][1] case control when "f" - facewindow.dispose if facewindow + facewindow&.dispose facewindow = PictureWindow.new("Graphics/Pictures/#{param}") pbPositionNearMsgWindow(facewindow, msgwindow, :left) facewindow.viewport = msgwindow.viewport facewindow.z = msgwindow.z when "ff" - facewindow.dispose if facewindow + facewindow&.dispose facewindow = FaceWindowVX.new(param) pbPositionNearMsgWindow(facewindow, msgwindow, :left) facewindow.viewport = msgwindow.viewport facewindow.z = msgwindow.z when "g" # Display gold window - goldwindow.dispose if goldwindow + goldwindow&.dispose goldwindow = pbDisplayGoldWindow(msgwindow) when "cn" # Display coins window - coinwindow.dispose if coinwindow + coinwindow&.dispose coinwindow = pbDisplayCoinsWindow(msgwindow, goldwindow) when "pt" # Display battle points window - battlepointswindow.dispose if battlepointswindow + battlepointswindow&.dispose battlepointswindow = pbDisplayBattlePointsWindow(msgwindow) when "wu" msgwindow.y = 0 @@ -650,7 +650,7 @@ def pbMessageDisplay(msgwindow, message, letterbyletter = true, commandProc = ni break if !letterbyletter Graphics.update Input.update - facewindow.update if facewindow + facewindow&.update if autoresume && msgwindow.waitcount == 0 msgwindow.resume if msgwindow.busy? break if !msgwindow.busy? @@ -677,11 +677,11 @@ def pbMessageDisplay(msgwindow, message, letterbyletter = true, commandProc = ni if commandProc ret = commandProc.call(msgwindow) end - msgback.dispose if msgback - goldwindow.dispose if goldwindow - coinwindow.dispose if coinwindow - battlepointswindow.dispose if battlepointswindow - facewindow.dispose if facewindow + msgback&.dispose + goldwindow&.dispose + coinwindow&.dispose + battlepointswindow&.dispose + facewindow&.dispose if haveSpecialClose pbSEPlay(pbStringToAudioFile(specialCloseSE)) atTop = (msgwindow.y == 0) @@ -752,7 +752,7 @@ def pbShowCommands(msgwindow, commands = nil, cmdIfCancel = 0, defaultCmd = 0) Graphics.update Input.update cmdwindow.update - msgwindow.update if msgwindow + msgwindow&.update yield if block_given? if Input.trigger?(Input::BACK) if cmdIfCancel > 0 @@ -832,7 +832,7 @@ def pbMessageWaitForInput(msgwindow, frames, showPause = false) frames.times do Graphics.update Input.update - msgwindow.update if msgwindow + msgwindow&.update pbUpdateSceneMap if Input.trigger?(Input::USE) || Input.trigger?(Input::BACK) break @@ -863,7 +863,7 @@ def pbFreeText(msgwindow, currenttext, passwordbox, maxlength, width = 240) break end window.update - msgwindow.update if msgwindow + msgwindow&.update yield if block_given? end Input.text_input = false diff --git a/Data/Scripts/007_Objects and windows/012_TextEntry.rb b/Data/Scripts/007_Objects and windows/012_TextEntry.rb index 24e29a1c2..07ece1cd7 100644 --- a/Data/Scripts/007_Objects and windows/012_TextEntry.rb +++ b/Data/Scripts/007_Objects and windows/012_TextEntry.rb @@ -23,7 +23,7 @@ class CharacterEntryHelper end def passwordChar=(value) - @passwordChar = value ? value : "" + @passwordChar = value || "" end def length @@ -192,7 +192,7 @@ class Window_TextEntry < SpriteWindow_Base @helper.cursor = 0 if @helper.cursor < 0 startpos = @helper.cursor fromcursor = 0 - while (startpos > 0) + while startpos > 0 c = (@helper.passwordChar != "") ? @helper.passwordChar : textscan[startpos - 1] fromcursor += bitmap.text_size(c).width break if fromcursor > width - 4 @@ -226,7 +226,7 @@ class Window_TextEntry_Keyboard < Window_TextEntry def update @frame += 1 @frame %= 20 - self.refresh if ((@frame % 10) == 0) + self.refresh if (@frame % 10) == 0 return if !self.active # Moving cursor if Input.triggerex?(:LEFT) || Input.repeatex?(:LEFT) @@ -460,7 +460,7 @@ class Window_MultilineTextEntry < SpriteWindow_Base def update @frame += 1 @frame %= 20 - self.refresh if ((@frame % 10) == 0) + self.refresh if (@frame % 10) == 0 return if !self.active # Moving cursor if Input.triggerex?(:UP) || Input.repeatex?(:UP) @@ -543,7 +543,7 @@ class Window_MultilineTextEntry < SpriteWindow_Base textheight = text[4] posToCursor = @cursorColumn - thiscolumn if posToCursor >= 0 - partialString = text[0].scan(/./m)[0, posToCursor].join("") + partialString = text[0].scan(/./m)[0, posToCursor].join cursorX += bitmap.text_size(partialString).width end break diff --git a/Data/Scripts/008_Audio/001_Audio.rb b/Data/Scripts/008_Audio/001_Audio.rb index a7d480341..e78018c73 100644 --- a/Data/Scripts/008_Audio/001_Audio.rb +++ b/Data/Scripts/008_Audio/001_Audio.rb @@ -138,7 +138,7 @@ def getPlayTime2(filename) loop do rstr = "" ateof = false - while !file.eof? + until file.eof? if (file.read(1)[0] rescue 0) == 0xFF begin rstr = file.read(3) @@ -152,14 +152,14 @@ def getPlayTime2(filename) if rstr[0] == 0xFB t = rstr[1] >> 4 next if [0, 15].include?(t) - freqs = [44100, 22050, 11025, 48000] + freqs = [44_100, 22_050, 11_025, 48_000] bitrates = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320] bitrate = bitrates[t] t = (rstr[1] >> 2) & 3 freq = freqs[t] t = (rstr[1] >> 1) & 1 filesize = FileTest.size(filename) - frameLength = ((144000 * bitrate) / freq) + t + frameLength = ((144_000 * bitrate) / freq) + t numFrames = filesize / (frameLength + 4) time = (numFrames * 1152.0 / freq) break diff --git a/Data/Scripts/008_Audio/002_Audio_Play.rb b/Data/Scripts/008_Audio/002_Audio_Play.rb index 5f9080fc4..d80c5c5d3 100644 --- a/Data/Scripts/008_Audio/002_Audio_Play.rb +++ b/Data/Scripts/008_Audio/002_Audio_Play.rb @@ -58,7 +58,7 @@ def pbBGMPlay(param, volume = nil, pitch = nil) return elsif (RPG.const_defined?(:BGM) rescue false) b = RPG::BGM.new(param.name, param.volume, param.pitch) - if b && b.respond_to?("play") + if b&.respond_to?("play") b.play return end @@ -108,7 +108,7 @@ def pbMEPlay(param, volume = nil, pitch = nil) return elsif (RPG.const_defined?(:ME) rescue false) b = RPG::ME.new(param.name, param.volume, param.pitch) - if b && b.respond_to?("play") + if b&.respond_to?("play") b.play return end @@ -125,7 +125,7 @@ def pbMEStop(timeInSeconds = 0.0) if $game_system && timeInSeconds > 0.0 && $game_system.respond_to?("me_fade") $game_system.me_fade(timeInSeconds) return - elsif $game_system && $game_system.respond_to?("me_stop") + elsif $game_system&.respond_to?("me_stop") $game_system.me_stop(nil) return elsif (RPG.const_defined?(:ME) rescue false) @@ -158,7 +158,7 @@ def pbBGSPlay(param, volume = nil, pitch = nil) return elsif (RPG.const_defined?(:BGS) rescue false) b = RPG::BGS.new(param.name, param.volume, param.pitch) - if b && b.respond_to?("play") + if b&.respond_to?("play") b.play return end @@ -209,7 +209,7 @@ def pbSEPlay(param, volume = nil, pitch = nil) end if (RPG.const_defined?(:SE) rescue false) b = RPG::SE.new(param.name, param.volume, param.pitch) - if b && b.respond_to?("play") + if b&.respond_to?("play") b.play return end diff --git a/Data/Scripts/009_Scenes/001_Transitions.rb b/Data/Scripts/009_Scenes/001_Transitions.rb index 0b91fd6ec..14bac461a 100644 --- a/Data/Scripts/009_Scenes/001_Transitions.rb +++ b/Data/Scripts/009_Scenes/001_Transitions.rb @@ -38,7 +38,7 @@ module Graphics def self.update update_KGC_SpecialTransition @@transition.update if @@transition && !@@transition.disposed? - @@transition = nil if @@transition && @@transition.disposed? + @@transition = nil if @@transition&.disposed? end def self.judge_special_transition(duration, filename) @@ -137,11 +137,11 @@ module Transitions def dispose return if disposed? dispose_all - @sprites.each { |s| s.dispose if s } + @sprites.each { |s| s&.dispose } @sprites.clear @overworld_sprite.dispose - @overworld_bitmap.dispose if @overworld_bitmap - @viewport.dispose if @viewport + @overworld_bitmap&.dispose + @viewport&.dispose @disposed = true end @@ -404,8 +404,8 @@ module Transitions end def dispose_all - @buffer_original.dispose if @buffer_original - @buffer_temp.dispose if @buffer_temp + @buffer_original&.dispose + @buffer_temp&.dispose end def update_anim @@ -628,13 +628,13 @@ module Transitions def dispose_all # Dispose sprites - @bubbles_sprite.dispose if @bubbles_sprite - @splash_sprite.dispose if @splash_sprite - @black_sprite.dispose if @black_sprite + @bubbles_sprite&.dispose + @splash_sprite&.dispose + @black_sprite&.dispose # Dispose bitmaps - @bubble_bitmap.dispose if @bubble_bitmap - @splash_bitmap.dispose if @splash_bitmap - @black_bitmap.dispose if @black_bitmap + @bubble_bitmap&.dispose + @splash_bitmap&.dispose + @black_bitmap&.dispose end def update_anim @@ -704,12 +704,12 @@ module Transitions def dispose_all # Dispose sprites if @ball_sprites - @ball_sprites.each { |s| s.dispose if s } + @ball_sprites.each { |s| s&.dispose } @ball_sprites.clear end # Dispose bitmaps - @black_bitmap.dispose if @black_bitmap - @ball_bitmap.dispose if @ball_bitmap + @black_bitmap&.dispose + @ball_bitmap&.dispose end def update_anim @@ -782,20 +782,20 @@ module Transitions def dispose_all # Dispose sprites if @overworld_sprites - @overworld_sprites.each { |s| s.dispose if s } + @overworld_sprites.each { |s| s&.dispose } @overworld_sprites.clear end if @black_sprites - @black_sprites.each { |s| s.dispose if s } + @black_sprites.each { |s| s&.dispose } @black_sprites.clear end if @ball_sprites - @ball_sprites.each { |s| s.dispose if s } + @ball_sprites.each { |s| s&.dispose } @ball_sprites.clear end # Dispose bitmaps - @black_bitmap.dispose if @black_bitmap - @ball_bitmap.dispose if @ball_bitmap + @black_bitmap&.dispose + @ball_bitmap&.dispose end def update_anim @@ -892,12 +892,12 @@ module Transitions def dispose_all # Dispose sprites if @ball_sprites - @ball_sprites.each { |s| s.dispose if s } + @ball_sprites.each { |s| s&.dispose } @ball_sprites.clear end # Dispose bitmaps - @black_bitmap.dispose if @black_bitmap - @ball_bitmap.dispose if @ball_bitmap + @black_bitmap&.dispose + @ball_bitmap&.dispose end def update_anim @@ -966,11 +966,11 @@ module Transitions def dispose_all # Dispose sprites - @ball_sprite.dispose if @ball_sprite + @ball_sprite&.dispose # Dispose bitmaps - @black_bitmap.dispose if @black_bitmap - @curve_bitmap.dispose if @curve_bitmap - @ball_bitmap.dispose if @ball_bitmap + @black_bitmap&.dispose + @curve_bitmap&.dispose + @ball_bitmap&.dispose end def update_anim @@ -1046,16 +1046,16 @@ module Transitions def dispose_all # Dispose sprites if @ball_sprites - @ball_sprites.each { |s| s.dispose if s } + @ball_sprites.each { |s| s&.dispose } @ball_sprites.clear end if @black_trail_sprites - @black_trail_sprites.each { |s| s.dispose if s } + @black_trail_sprites.each { |s| s&.dispose } @black_trail_sprites.clear end # Dispose bitmaps - @black_bitmap.dispose if @black_bitmap - @ball_bitmap.dispose if @ball_bitmap + @black_bitmap&.dispose + @ball_bitmap&.dispose end def update_anim @@ -1122,11 +1122,11 @@ module Transitions def dispose_all # Dispose sprites - @ball_sprite.dispose if @ball_sprite - @black_sprite.dispose if @black_sprite + @ball_sprite&.dispose + @black_sprite&.dispose # Dispose bitmaps - @black_bitmap.dispose if @black_bitmap - @ball_bitmap.dispose if @ball_bitmap + @black_bitmap&.dispose + @ball_bitmap&.dispose end def update_anim @@ -1194,14 +1194,14 @@ module Transitions def dispose_all # Dispose sprites - @ball_sprites.each { |s| s.dispose if s } + @ball_sprites.each { |s| s&.dispose } @ball_sprites.clear # Dispose bitmaps - @black_1_bitmap.dispose if @black_1_bitmap - @black_2_bitmap.dispose if @black_2_bitmap - @black_3_bitmap.dispose if @black_3_bitmap - @black_4_bitmap.dispose if @black_4_bitmap - @ball_bitmap.dispose if @ball_bitmap + @black_1_bitmap&.dispose + @black_2_bitmap&.dispose + @black_3_bitmap&.dispose + @black_4_bitmap&.dispose + @ball_bitmap&.dispose end def update_anim diff --git a/Data/Scripts/009_Scenes/002_EventScene.rb b/Data/Scripts/009_Scenes/002_EventScene.rb index 459ff2d7a..0aa75c87c 100644 --- a/Data/Scripts/009_Scenes/002_EventScene.rb +++ b/Data/Scripts/009_Scenes/002_EventScene.rb @@ -10,7 +10,7 @@ class PictureSprite < SpriteWrapper end def dispose - @pictureBitmap.dispose if @pictureBitmap + @pictureBitmap&.dispose super end @@ -22,7 +22,7 @@ class PictureSprite < SpriteWrapper def update super - @pictureBitmap.update if @pictureBitmap + @pictureBitmap&.update # If picture file name is different from current one if @customBitmap && @picture.name == "" self.bitmap = (@customBitmapIsBitmap) ? @customBitmap : @customBitmap.bitmap @@ -32,13 +32,13 @@ class PictureSprite < SpriteWrapper @hue = @picture.hue.to_i # If file name is not empty if @picture_name == "" - @pictureBitmap.dispose if @pictureBitmap + @pictureBitmap&.dispose @pictureBitmap = nil self.visible = false return end # Get picture graphic - @pictureBitmap.dispose if @pictureBitmap + @pictureBitmap&.dispose @pictureBitmap = AnimatedBitmap.new(@picture_name, @hue) self.bitmap = (@pictureBitmap) ? @pictureBitmap.bitmap : nil elsif @picture_name == "" @@ -175,7 +175,7 @@ class EventScene end def main - while !disposed? + until disposed? update end end diff --git a/Data/Scripts/010_Data/001_Hardcoded data/007_Evolution.rb b/Data/Scripts/010_Data/001_Hardcoded data/007_Evolution.rb index 531b3cd63..054787621 100644 --- a/Data/Scripts/010_Data/001_Hardcoded data/007_Evolution.rb +++ b/Data/Scripts/010_Data/001_Hardcoded data/007_Evolution.rb @@ -53,7 +53,7 @@ module GameData end def call_after_evolution(*args) - @after_evolution_proc.call(*args) if @after_evolution_proc + @after_evolution_proc&.call(*args) end end end @@ -500,8 +500,7 @@ GameData::Evolution.register({ :minimum_level => 1, # Needs any level up :level_up_proc => proc { |pkmn, parameter| map_metadata = $game_map.metadata - next map_metadata && map_metadata.town_map_position && - map_metadata.town_map_position[0] == parameter + next map_metadata&.town_map_position && map_metadata.town_map_position[0] == parameter } }) diff --git a/Data/Scripts/010_Data/002_PBS data/001_MiscPBSData.rb b/Data/Scripts/010_Data/002_PBS data/001_MiscPBSData.rb index 790924bed..3d37cfbe9 100644 --- a/Data/Scripts/010_Data/002_PBS data/001_MiscPBSData.rb +++ b/Data/Scripts/010_Data/002_PBS data/001_MiscPBSData.rb @@ -42,10 +42,8 @@ end #=============================================================================== def pbLoadPhoneData $game_temp = Game_Temp.new if !$game_temp - if !$game_temp.phone_messages_data - if pbRgssExists?("Data/phone.dat") - $game_temp.phone_messages_data = load_data("Data/phone.dat") - end + if !$game_temp.phone_messages_data && pbRgssExists?("Data/phone.dat") + $game_temp.phone_messages_data = load_data("Data/phone.dat") end return $game_temp.phone_messages_data end @@ -66,10 +64,8 @@ end #=============================================================================== def pbLoadBattleAnimations $game_temp = Game_Temp.new if !$game_temp - if !$game_temp.battle_animations_data - if pbRgssExists?("Data/PkmnAnimations.rxdata") - $game_temp.battle_animations_data = load_data("Data/PkmnAnimations.rxdata") - end + if !$game_temp.battle_animations_data && pbRgssExists?("Data/PkmnAnimations.rxdata") + $game_temp.battle_animations_data = load_data("Data/PkmnAnimations.rxdata") end return $game_temp.battle_animations_data end diff --git a/Data/Scripts/010_Data/002_PBS data/006_Item.rb b/Data/Scripts/010_Data/002_PBS data/006_Item.rb index e4e64c215..1af717dc1 100644 --- a/Data/Scripts/010_Data/002_PBS data/006_Item.rb +++ b/Data/Scripts/010_Data/002_PBS data/006_Item.rb @@ -188,7 +188,7 @@ module GameData :KYOGRE => [:BLUEORB], :GROUDON => [:REDORB] } - return combos[species] && combos[species].include?(@id) + return combos[species]&.include?(@id) end end end diff --git a/Data/Scripts/010_Data/002_PBS data/013_Encounter.rb b/Data/Scripts/010_Data/002_PBS data/013_Encounter.rb index dc17b34ca..157ba26e8 100644 --- a/Data/Scripts/010_Data/002_PBS data/013_Encounter.rb +++ b/Data/Scripts/010_Data/002_PBS data/013_Encounter.rb @@ -51,8 +51,8 @@ module GameData def self.each_of_version(version = 0) self.each do |data| yield data if data.version == version - if version > 0 - yield data if data.version == 0 && !self::DATA.has_key?([data.map, version]) + if version > 0 && data.version == 0 && !self::DATA.has_key?([data.map, version]) + yield data end end end diff --git a/Data/Scripts/010_Data/002_PBS data/014_TrainerType.rb b/Data/Scripts/010_Data/002_PBS data/014_TrainerType.rb index 37d81867e..16de68c47 100644 --- a/Data/Scripts/010_Data/002_PBS data/014_TrainerType.rb +++ b/Data/Scripts/010_Data/002_PBS data/014_TrainerType.rb @@ -48,7 +48,7 @@ module GameData def self.charset_filename_brief(tr_type) ret = self.charset_filename(tr_type) - ret.slice!("Graphics/Characters/") if ret + ret&.slice!("Graphics/Characters/") return ret end diff --git a/Data/Scripts/011_Battle/001_Battle/001_Battle.rb b/Data/Scripts/011_Battle/001_Battle/001_Battle.rb index 7f026fe71..f5970de8a 100644 --- a/Data/Scripts/011_Battle/001_Battle/001_Battle.rb +++ b/Data/Scripts/011_Battle/001_Battle/001_Battle.rb @@ -321,7 +321,7 @@ class Battle def pbAbleCount(idxBattler = 0) party = pbParty(idxBattler) count = 0 - party.each { |pkmn| count += 1 if pkmn && pkmn.able? } + party.each { |pkmn| count += 1 if pkmn&.able? } return count end diff --git a/Data/Scripts/011_Battle/001_Battle/002_Battle_StartAndEnd.rb b/Data/Scripts/011_Battle/001_Battle/002_Battle_StartAndEnd.rb index 6edd32014..a7fb8df81 100644 --- a/Data/Scripts/011_Battle/001_Battle/002_Battle_StartAndEnd.rb +++ b/Data/Scripts/011_Battle/001_Battle/002_Battle_StartAndEnd.rb @@ -465,11 +465,11 @@ class Battle end infected.each do |idxParty| strain = $player.party[idxParty].pokerusStrain - if idxParty > 0 && $player.party[idxParty - 1].pokerusStage == 0 - $player.party[idxParty - 1].givePokerus(strain) if rand(3) == 0 # 33% + if idxParty > 0 && $player.party[idxParty - 1].pokerusStage == 0 && rand(3) == 0 # 33% + $player.party[idxParty - 1].givePokerus(strain) end - if idxParty < $player.party.length - 1 && $player.party[idxParty + 1].pokerusStage == 0 - $player.party[idxParty + 1].givePokerus(strain) if rand(3) == 0 # 33% + if idxParty < $player.party.length - 1 && $player.party[idxParty + 1].pokerusStage == 0 && rand(3) == 0 # 33% + $player.party[idxParty + 1].givePokerus(strain) end end end diff --git a/Data/Scripts/011_Battle/001_Battle/003_Battle_ExpAndMoveLearning.rb b/Data/Scripts/011_Battle/001_Battle/003_Battle_ExpAndMoveLearning.rb index 53b1ac65e..2f4a37908 100644 --- a/Data/Scripts/011_Battle/001_Battle/003_Battle_ExpAndMoveLearning.rb +++ b/Data/Scripts/011_Battle/001_Battle/003_Battle_ExpAndMoveLearning.rb @@ -11,13 +11,13 @@ class Battle expAll = $player.has_exp_all || $bag.has?(:EXPALL) p1 = pbParty(0) @battlers.each do |b| - next unless b && b.opposes? # Can only gain Exp from fainted foes + next unless b&.opposes? # Can only gain Exp from fainted foes next if b.participants.length == 0 next unless b.fainted? || b.captured # Count the number of participants numPartic = 0 b.participants.each do |partic| - next unless p1[partic] && p1[partic].able? && pbIsOwner?(0, partic) + next unless p1[partic]&.able? && pbIsOwner?(0, partic) numPartic += 1 end # Find which Pokémon have an Exp Share @@ -199,7 +199,7 @@ class Battle if curLevel > newLevel # Gained all the Exp now, end the animation pkmn.calc_stats - battler.pbUpdate(false) if battler + battler&.pbUpdate(false) @scene.pbRefreshOne(battler.index) if battler break end @@ -211,11 +211,11 @@ class Battle oldSpAtk = pkmn.spatk oldSpDef = pkmn.spdef oldSpeed = pkmn.speed - if battler && battler.pokemon + if battler&.pokemon battler.pokemon.changeHappiness("levelup") end pkmn.calc_stats - battler.pbUpdate(false) if battler + battler&.pbUpdate(false) @scene.pbRefreshOne(battler.index) if battler pbDisplayPaused(_INTL("{1} grew to Lv. {2}!", pkmn.name, curLevel)) @scene.pbLevelUp(pkmn, battler, oldTotalHP, oldAttack, oldDefense, @@ -260,7 +260,7 @@ class Battle pbDisplayPaused(_INTL("1, 2, and... ... ... Ta-da!")) { pbSEPlay("Battle ball drop") } pbDisplayPaused(_INTL("{1} forgot how to use {2}. And...", pkmnName, oldMoveName)) pbDisplay(_INTL("{1} learned {2}!", pkmnName, moveName)) { pbSEPlay("Pkmn move learnt") } - battler.pbCheckFormOnMovesetChange if battler + battler&.pbCheckFormOnMovesetChange break elsif pbDisplayConfirm(_INTL("Give up on learning {1}?", moveName)) pbDisplay(_INTL("{1} did not learn {2}.", pkmnName, moveName)) diff --git a/Data/Scripts/011_Battle/001_Battle/005_Battle_ActionSwitching.rb b/Data/Scripts/011_Battle/001_Battle/005_Battle_ActionSwitching.rb index 117b70a2d..9d67f7f82 100644 --- a/Data/Scripts/011_Battle/001_Battle/005_Battle_ActionSwitching.rb +++ b/Data/Scripts/011_Battle/001_Battle/005_Battle_ActionSwitching.rb @@ -12,7 +12,7 @@ class Battle return false if idxParty >= party.length return false if !party[idxParty] if party[idxParty].egg? - partyScene.pbDisplay(_INTL("An Egg can't battle!")) if partyScene + partyScene&.pbDisplay(_INTL("An Egg can't battle!")) return false end if !pbIsOwner?(idxBattler, idxParty) @@ -24,11 +24,11 @@ class Battle return false end if party[idxParty].fainted? - partyScene.pbDisplay(_INTL("{1} has no energy left to battle!", party[idxParty].name)) if partyScene + partyScene&.pbDisplay(_INTL("{1} has no energy left to battle!", party[idxParty].name)) return false end if pbFindBattler(idxParty, idxBattler) - partyScene.pbDisplay(_INTL("{1} is already in battle!", party[idxParty].name)) if partyScene + partyScene&.pbDisplay(_INTL("{1} is already in battle!", party[idxParty].name)) return false end return true @@ -45,45 +45,43 @@ class Battle # Pokémon allSameSideBattlers(idxBattler).each do |b| next if choices[b.index][0] != :SwitchOut || choices[b.index][1] != idxParty - partyScene.pbDisplay(_INTL("{1} has already been selected.", - pbParty(idxBattler)[idxParty].name)) if partyScene + partyScene&.pbDisplay(_INTL("{1} has already been selected.", + pbParty(idxBattler)[idxParty].name)) return false end # Check whether battler can switch out battler = @battlers[idxBattler] return true if battler.fainted? # Ability/item effects that allow switching no matter what - if battler.abilityActive? - if Battle::AbilityEffects.triggerCertainSwitching(battler.ability, battler, self) - return true - end + if battler.abilityActive? && + Battle::AbilityEffects.triggerCertainSwitching(battler.ability, battler, self) + return true end - if battler.itemActive? - if Battle::ItemEffects.triggerCertainSwitching(battler.item, battler, self) - return true - end + if battler.itemActive? && + Battle::ItemEffects.triggerCertainSwitching(battler.item, battler, self) + return true end # Other certain switching effects return true if Settings::MORE_TYPE_EFFECTS && battler.pbHasType?(:GHOST) # Other certain trapping effects if battler.trappedInBattle? - partyScene.pbDisplay(_INTL("{1} can't be switched out!", battler.pbThis)) if partyScene + partyScene&.pbDisplay(_INTL("{1} can't be switched out!", battler.pbThis)) return false end # Trapping abilities/items allOtherSideBattlers(idxBattler).each do |b| next if !b.abilityActive? if Battle::AbilityEffects.triggerTrappingByTarget(b.ability, battler, b, self) - partyScene.pbDisplay(_INTL("{1}'s {2} prevents switching!", - b.pbThis, b.abilityName)) if partyScene + partyScene&.pbDisplay(_INTL("{1}'s {2} prevents switching!", + b.pbThis, b.abilityName)) return false end end allOtherSideBattlers(idxBattler).each do |b| next if !b.itemActive? if Battle::ItemEffects.triggerTrappingByTarget(b.item, battler, b, self) - partyScene.pbDisplay(_INTL("{1}'s {2} prevents switching!", - b.pbThis, b.itemName)) if partyScene + partyScene&.pbDisplay(_INTL("{1}'s {2} prevents switching!", + b.pbThis, b.itemName)) return false end end @@ -119,8 +117,8 @@ class Battle elsif !pbCanSwitch?(idxBattler, idxParty, partyScene) next false end - if shouldRegister - next false if idxParty < 0 || !pbRegisterSwitch(idxBattler, idxParty) + if shouldRegister && (idxParty < 0 || !pbRegisterSwitch(idxBattler, idxParty)) + next false end ret = idxParty next true @@ -187,10 +185,10 @@ class Battle switched.push(idxBattler) else # Player's Pokémon has fainted in a wild battle switch = false - if !pbDisplayConfirm(_INTL("Use next Pokémon?")) - switch = (pbRun(idxBattler, true) <= 0) - else + if pbDisplayConfirm(_INTL("Use next Pokémon?")) switch = true + else + switch = (pbRun(idxBattler, true) <= 0) end if switch idxPlayerPartyNew = pbGetReplacementPokemonIndex(idxBattler) # Owner chooses diff --git a/Data/Scripts/011_Battle/001_Battle/006_Battle_ActionUseItem.rb b/Data/Scripts/011_Battle/001_Battle/006_Battle_ActionUseItem.rb index e04963b88..3e43494ac 100644 --- a/Data/Scripts/011_Battle/001_Battle/006_Battle_ActionUseItem.rb +++ b/Data/Scripts/011_Battle/001_Battle/006_Battle_ActionUseItem.rb @@ -56,14 +56,14 @@ class Battle return if !item return if !GameData::Item.get(item).consumed_after_use? if pbOwnedByPlayer?(idxBattler) - if $bag && $bag.can_add?(item) + if $bag&.can_add?(item) $bag.add(item) else raise _INTL("Couldn't return unused item to Bag somehow.") end else items = pbGetOwnerItems(idxBattler) - items.push(item) if items + items&.push(item) end end diff --git a/Data/Scripts/011_Battle/001_Battle/007_Battle_ActionRunning.rb b/Data/Scripts/011_Battle/001_Battle/007_Battle_ActionRunning.rb index 4be5563df..61ad9863c 100644 --- a/Data/Scripts/011_Battle/001_Battle/007_Battle_ActionRunning.rb +++ b/Data/Scripts/011_Battle/001_Battle/007_Battle_ActionRunning.rb @@ -75,24 +75,22 @@ class Battle return 1 end # Abilities that guarantee escape - if battler.abilityActive? - if Battle::AbilityEffects.triggerCertainEscapeFromBattle(battler.ability, battler) - pbShowAbilitySplash(battler, true) - pbHideAbilitySplash(battler) - pbSEPlay("Battle flee") - pbDisplayPaused(_INTL("You got away safely!")) - @decision = 3 - return 1 - end + if battler.abilityActive? && + Battle::AbilityEffects.triggerCertainEscapeFromBattle(battler.ability, battler) + pbShowAbilitySplash(battler, true) + pbHideAbilitySplash(battler) + pbSEPlay("Battle flee") + pbDisplayPaused(_INTL("You got away safely!")) + @decision = 3 + return 1 end # Held items that guarantee escape - if battler.itemActive? - if Battle::ItemEffects.triggerCertainEscapeFromBattle(battler.item, battler) - pbSEPlay("Battle flee") - pbDisplayPaused(_INTL("{1} fled using its {2}!", battler.pbThis, battler.itemName)) - @decision = 3 - return 1 - end + if battler.itemActive? && + Battle::ItemEffects.triggerCertainEscapeFromBattle(battler.item, battler) + pbSEPlay("Battle flee") + pbDisplayPaused(_INTL("{1} fled using its {2}!", battler.pbThis, battler.itemName)) + @decision = 3 + return 1 end # Other certain trapping effects if battler.trappedInBattle? diff --git a/Data/Scripts/011_Battle/001_Battle/010_Battle_AttackPhase.rb b/Data/Scripts/011_Battle/001_Battle/010_Battle_AttackPhase.rb index 41a3f2981..27a265dfd 100644 --- a/Data/Scripts/011_Battle/001_Battle/010_Battle_AttackPhase.rb +++ b/Data/Scripts/011_Battle/001_Battle/010_Battle_AttackPhase.rb @@ -161,10 +161,10 @@ class Battle next if advance # Check for all done priority.each do |b| - if !b.fainted? && !b.movedThisRound? - advance = true if @choices[b.index][0] == :UseMove || @choices[b.index][0] == :Shift - end - break if advance + next if b.fainted? + next if b.movedThisRound? || ![:UseMove, :Shift].include?(@choices[b.index][0]) + advance = true + break end next if advance # All Pokémon have moved; end the loop diff --git a/Data/Scripts/011_Battle/001_Battle/011_Battle_EndOfRoundPhase.rb b/Data/Scripts/011_Battle/001_Battle/011_Battle_EndOfRoundPhase.rb index e36b8db0e..b4d04f5d6 100644 --- a/Data/Scripts/011_Battle/001_Battle/011_Battle_EndOfRoundPhase.rb +++ b/Data/Scripts/011_Battle/001_Battle/011_Battle_EndOfRoundPhase.rb @@ -223,7 +223,7 @@ class Battle if !moveUser # User isn't in battle, get it from the party party = pbParty(pos.effects[PBEffects::FutureSightUserIndex]) pkmn = party[pos.effects[PBEffects::FutureSightUserPartyIndex]] - if pkmn && pkmn.able? + if pkmn&.able? moveUser = Battler.new(self, pos.effects[PBEffects::FutureSightUserIndex]) moveUser.pbInitDummyPokemon(pkmn, pos.effects[PBEffects::FutureSightUserPartyIndex]) end @@ -504,12 +504,11 @@ class Battle b.pbItemHPHealCheck b.pbFaint if b.fainted? end - if perishSongUsers.length > 0 - # If all remaining Pokemon fainted by a Perish Song triggered by a single side - if (perishSongUsers.find_all { |idxBattler| opposes?(idxBattler) }.length == perishSongUsers.length) || - (perishSongUsers.find_all { |idxBattler| !opposes?(idxBattler) }.length == perishSongUsers.length) - pbJudgeCheckpoint(@battlers[perishSongUsers[0]]) - end + # Judge if all remaining Pokemon fainted by a Perish Song triggered by a single side + if perishSongUsers.length > 0 && + ((perishSongUsers.find_all { |idxBattler| opposes?(idxBattler) }.length == perishSongUsers.length) || + (perishSongUsers.find_all { |idxBattler| !opposes?(idxBattler) }.length == perishSongUsers.length)) + pbJudgeCheckpoint(@battlers[perishSongUsers[0]]) end # Check for end of battle if @decision > 0 diff --git a/Data/Scripts/011_Battle/002_Battler/001_Battle_Battler.rb b/Data/Scripts/011_Battle/002_Battler/001_Battle_Battler.rb index d2821caf9..dab483b94 100644 --- a/Data/Scripts/011_Battle/002_Battler/001_Battle_Battler.rb +++ b/Data/Scripts/011_Battle/002_Battler/001_Battle_Battler.rb @@ -136,17 +136,17 @@ class Battle::Battler #============================================================================= def hasMega? return false if @effects[PBEffects::Transform] - return @pokemon && @pokemon.hasMegaForm? + return @pokemon&.hasMegaForm? end - def mega?; return @pokemon && @pokemon.mega?; end + def mega?; return @pokemon&.mega?; end def hasPrimal? return false if @effects[PBEffects::Transform] - return @pokemon && @pokemon.hasPrimalForm? + return @pokemon&.hasPrimalForm? end - def primal?; return @pokemon && @pokemon.primal?; end + def primal?; return @pokemon&.primal?; end def shadowPokemon?; return false; end @@ -184,11 +184,11 @@ class Battle::Battler def shiny? return @effects[PBEffects::Illusion].shiny? if @effects[PBEffects::Illusion] - return @pokemon && @pokemon.shiny? + return @pokemon&.shiny? end def super_shiny? - return @pokemon && @pokemon.super_shiny? + return @pokemon&.super_shiny? end def owned? @@ -295,7 +295,7 @@ class Battle::Battler end def isSpecies?(species) - return @pokemon && @pokemon.isSpecies?(species) + return @pokemon&.isSpecies?(species) end # Returns the active types of this Pokémon. The array should not include the @@ -311,8 +311,8 @@ class Battle::Battler ret.push(:NORMAL) if ret.length == 0 end # Add the third type specially. - if withType3 && @effects[PBEffects::Type3] - ret.push(@effects[PBEffects::Type3]) if !ret.include?(@effects[PBEffects::Type3]) + if withType3 && @effects[PBEffects::Type3] && !ret.include?(@effects[PBEffects::Type3]) + ret.push(@effects[PBEffects::Type3]) end return ret end diff --git a/Data/Scripts/011_Battle/002_Battler/003_Battler_ChangeSelf.rb b/Data/Scripts/011_Battle/002_Battler/003_Battler_ChangeSelf.rb index cc163af5a..f20a2c42c 100644 --- a/Data/Scripts/011_Battle/002_Battler/003_Battler_ChangeSelf.rb +++ b/Data/Scripts/011_Battle/002_Battler/003_Battler_ChangeSelf.rb @@ -277,14 +277,13 @@ class Battle::Battler end end # Zygarde - Power Construct - if isSpecies?(:ZYGARDE) && self.ability == :POWERCONSTRUCT && endOfRound - if @hp <= @totalhp / 2 && @form < 2 # Turn into Complete Forme - newForm = @form + 2 - @battle.pbDisplay(_INTL("You sense the presence of many!")) - @battle.pbShowAbilitySplash(self, true) - @battle.pbHideAbilitySplash(self) - pbChangeForm(newForm, _INTL("{1} transformed into its Complete Forme!", pbThis)) - end + if isSpecies?(:ZYGARDE) && self.ability == :POWERCONSTRUCT && endOfRound && + @hp <= @totalhp / 2 && @form < 2 # Turn into Complete Forme + newForm = @form + 2 + @battle.pbDisplay(_INTL("You sense the presence of many!")) + @battle.pbShowAbilitySplash(self, true) + @battle.pbHideAbilitySplash(self) + pbChangeForm(newForm, _INTL("{1} transformed into its Complete Forme!", pbThis)) end # Morpeko - Hunger Switch if isSpecies?(:MORPEKO) && hasActiveAbility?(:HUNGERSWITCH) && endOfRound diff --git a/Data/Scripts/011_Battle/002_Battler/004_Battler_Statuses.rb b/Data/Scripts/011_Battle/002_Battler/004_Battler_Statuses.rb index 4c3b6a021..af40beffe 100644 --- a/Data/Scripts/011_Battle/002_Battler/004_Battler_Statuses.rb +++ b/Data/Scripts/011_Battle/002_Battler/004_Battler_Statuses.rb @@ -281,11 +281,11 @@ class Battle::Battler def pbCanSleepYawn? return false if self.status != :NONE - if affectedByTerrain? - return false if [:Electric, :Misty].include?(@battle.field.terrain) + if affectedByTerrain? && [:Electric, :Misty].include?(@battle.field.terrain) + return false end - if !hasActiveAbility?(:SOUNDPROOF) - return false if @battle.allBattlers.any? { |b| b.effects[PBEffects::Uproar] > 0 } + if !hasActiveAbility?(:SOUNDPROOF) && @battle.allBattlers.any? { |b| b.effects[PBEffects::Uproar] > 0 } + return false end if Battle::AbilityEffects.triggerStatusImmunityNonIgnorable(self.ability, self, :SLEEP) return false @@ -454,19 +454,17 @@ class Battle::Battler @battle.pbDisplay(_INTL("{1} surrounds itself with misty terrain!", pbThis(true))) if showMessages return false end - if selfInflicted || !@battle.moldBreaker - if hasActiveAbility?(:OWNTEMPO) - if showMessages - @battle.pbShowAbilitySplash(self) - if Battle::Scene::USE_ABILITY_SPLASH - @battle.pbDisplay(_INTL("{1} doesn't become confused!", pbThis)) - else - @battle.pbDisplay(_INTL("{1}'s {2} prevents confusion!", pbThis, abilityName)) - end - @battle.pbHideAbilitySplash(self) + if (selfInflicted || !@battle.moldBreaker) && hasActiveAbility?(:OWNTEMPO) + if showMessages + @battle.pbShowAbilitySplash(self) + if Battle::Scene::USE_ABILITY_SPLASH + @battle.pbDisplay(_INTL("{1} doesn't become confused!", pbThis)) + else + @battle.pbDisplay(_INTL("{1}'s {2} prevents confusion!", pbThis, abilityName)) end - return false + @battle.pbHideAbilitySplash(self) end + return false end if pbOwnSide.effects[PBEffects::Safeguard] > 0 && !selfInflicted && !(user && user.hasActiveAbility?(:INFILTRATOR)) diff --git a/Data/Scripts/011_Battle/002_Battler/005_Battler_StatStages.rb b/Data/Scripts/011_Battle/002_Battler/005_Battler_StatStages.rb index f1ee974a9..52719c498 100644 --- a/Data/Scripts/011_Battle/002_Battler/005_Battler_StatStages.rb +++ b/Data/Scripts/011_Battle/002_Battler/005_Battler_StatStages.rb @@ -118,7 +118,8 @@ class Battle::Battler return @stages[stat] <= -6 end - def pbCanLowerStatStage?(stat, user = nil, move = nil, showFailMsg = false, ignoreContrary = false, ignoreMirrorArmor = false) + def pbCanLowerStatStage?(stat, user = nil, move = nil, showFailMsg = false, + ignoreContrary = false, ignoreMirrorArmor = false) return false if fainted? if !@battle.moldBreaker # Contrary @@ -126,12 +127,14 @@ class Battle::Battler return pbCanRaiseStatStage?(stat, user, move, showFailMsg, true) end # Mirror Armor - if hasActiveAbility?(:MIRRORARMOR) && !ignoreMirrorArmor && user && user.index != @index - return true if !statStageAtMin?(stat) + if hasActiveAbility?(:MIRRORARMOR) && !ignoreMirrorArmor && + user && user.index != @index && !statStageAtMin?(stat) + return true end end if !user || user.index != @index # Not self-inflicted - if @effects[PBEffects::Substitute] > 0 && (ignoreMirrorArmor || !(move && move.ignoresSubstitute?(user))) + if @effects[PBEffects::Substitute] > 0 && + (ignoreMirrorArmor || !(move && move.ignoresSubstitute?(user))) @battle.pbDisplay(_INTL("{1} is protected by its substitute!", pbThis)) if showFailMsg return false end @@ -328,13 +331,12 @@ class Battle::Battler pbThis, user.pbThis(true), user.abilityName)) return false end - if abilityActive? - if Battle::AbilityEffects.triggerStatLossImmunity(self.ability, self, :ATTACK, @battle, false) || - Battle::AbilityEffects.triggerStatLossImmunityNonIgnorable(self.ability, self, :ATTACK, @battle, false) - @battle.pbDisplay(_INTL("{1}'s {2} prevented {3}'s {4} from working!", - pbThis, abilityName, user.pbThis(true), user.abilityName)) - return false - end + if abilityActive? && + (Battle::AbilityEffects.triggerStatLossImmunity(self.ability, self, :ATTACK, @battle, false) || + Battle::AbilityEffects.triggerStatLossImmunityNonIgnorable(self.ability, self, :ATTACK, @battle, false)) + @battle.pbDisplay(_INTL("{1}'s {2} prevented {3}'s {4} from working!", + pbThis, abilityName, user.pbThis(true), user.abilityName)) + return false end allAllies.each do |b| next if !b.abilityActive? diff --git a/Data/Scripts/011_Battle/002_Battler/006_Battler_AbilityAndItem.rb b/Data/Scripts/011_Battle/002_Battler/006_Battler_AbilityAndItem.rb index a04882f9a..db098f44a 100644 --- a/Data/Scripts/011_Battle/002_Battler/006_Battler_AbilityAndItem.rb +++ b/Data/Scripts/011_Battle/002_Battler/006_Battler_AbilityAndItem.rb @@ -378,7 +378,7 @@ class Battle::Battler def pbItemsOnUnnerveEnding @battle.pbPriority(true).each do |b| - b.pbHeldItemTriggerCheck if b.item && b.item.is_berry? + b.pbHeldItemTriggerCheck if b.item&.is_berry? end end diff --git a/Data/Scripts/011_Battle/002_Battler/007_Battler_UseMove.rb b/Data/Scripts/011_Battle/002_Battler/007_Battler_UseMove.rb index 874b853dc..096f08f91 100644 --- a/Data/Scripts/011_Battle/002_Battler/007_Battler_UseMove.rb +++ b/Data/Scripts/011_Battle/002_Battler/007_Battler_UseMove.rb @@ -175,12 +175,11 @@ class Battle::Battler elsif @effects[PBEffects::Encore] > 0 && choice[1] >= 0 && @battle.pbCanShowCommands?(@index) idxEncoredMove = pbEncoredMoveIndex - if idxEncoredMove >= 0 && @battle.pbCanChooseMove?(@index, idxEncoredMove, false) - if choice[1] != idxEncoredMove # Change move if battler was Encored mid-round - choice[1] = idxEncoredMove - choice[2] = @moves[idxEncoredMove] - choice[3] = -1 # No target chosen - end + if idxEncoredMove >= 0 && choice[1] != idxEncoredMove && + @battle.pbCanChooseMove?(@index, idxEncoredMove, false) # Change move if battler was Encored mid-round + choice[1] = idxEncoredMove + choice[2] = @moves[idxEncoredMove] + choice[3] = -1 # No target chosen end end # Labels the move being used as "move" @@ -203,19 +202,17 @@ class Battle::Battler move = choice[2] # In case disobedience changed the move to be used return if !move # if move was not chosen somehow # Subtract PP - if !specialUsage - if !pbReducePP(move) - @battle.pbDisplay(_INTL("{1} used {2}!", pbThis, move.name)) - @battle.pbDisplay(_INTL("But there was no PP left for the move!")) - @lastMoveUsed = nil - @lastMoveUsedType = nil - @lastRegularMoveUsed = nil - @lastRegularMoveTarget = -1 - @lastMoveFailed = true - pbCancelMoves - pbEndTurn(choice) - return - end + if !specialUsage && !pbReducePP(move) + @battle.pbDisplay(_INTL("{1} used {2}!", pbThis, move.name)) + @battle.pbDisplay(_INTL("But there was no PP left for the move!")) + @lastMoveUsed = nil + @lastMoveUsedType = nil + @lastRegularMoveUsed = nil + @lastRegularMoveTarget = -1 + @lastMoveFailed = true + pbCancelMoves + pbEndTurn(choice) + return end # Stance Change if isSpecies?(:AEGISLASH) && self.ability == :STANCECHANGE @@ -356,21 +353,21 @@ class Battle::Battler end end # Protean - if user.hasActiveAbility?([:LIBERO, :PROTEAN]) && !move.callsAnotherMove? && !move.snatched - if user.pbHasOtherType?(move.calcType) && !GameData::Type.get(move.calcType).pseudo_type - @battle.pbShowAbilitySplash(user) - user.pbChangeTypes(move.calcType) - typeName = GameData::Type.get(move.calcType).name - @battle.pbDisplay(_INTL("{1}'s type changed to {2}!", user.pbThis, typeName)) - @battle.pbHideAbilitySplash(user) - # NOTE: The GF games say that if Curse is used by a non-Ghost-type - # Pokémon which becomes Ghost-type because of Protean, it should - # target and curse itself. I think this is silly, so I'm making it - # choose a random opponent to curse instead. - if move.function == "CurseTargetOrLowerUserSpd1RaiseUserAtkDef1" && targets.length == 0 - choice[3] = -1 - targets = pbFindTargets(choice, move, user) - end + if user.hasActiveAbility?([:LIBERO, :PROTEAN]) && + !move.callsAnotherMove? && !move.snatched && + user.pbHasOtherType?(move.calcType) && !GameData::Type.get(move.calcType).pseudo_type + @battle.pbShowAbilitySplash(user) + user.pbChangeTypes(move.calcType) + typeName = GameData::Type.get(move.calcType).name + @battle.pbDisplay(_INTL("{1}'s type changed to {2}!", user.pbThis, typeName)) + @battle.pbHideAbilitySplash(user) + # NOTE: The GF games say that if Curse is used by a non-Ghost-type + # Pokémon which becomes Ghost-type because of Protean, it should + # target and curse itself. I think this is silly, so I'm making it + # choose a random opponent to curse instead. + if move.function == "CurseTargetOrLowerUserSpd1RaiseUserAtkDef1" && targets.length == 0 + choice[3] = -1 + targets = pbFindTargets(choice, move, user) end end #--------------------------------------------------------------------------- @@ -486,7 +483,7 @@ class Battle::Battler end pbProcessMoveHit(move, b, newTargets, 0, false) if success b.lastMoveFailed = true if !success - targets.each { |otherB| otherB.pbFaint if otherB && otherB.fainted? } + targets.each { |otherB| otherB.pbFaint if otherB&.fainted? } user.pbFaint if user.fainted? end # Magic Coat's bouncing back (move has no targets) @@ -502,14 +499,14 @@ class Battle::Battler success = pbProcessMoveHit(move, mc, [], 0, false) end mc.lastMoveFailed = true if !success - targets.each { |b| b.pbFaint if b && b.fainted? } + targets.each { |b| b.pbFaint if b&.fainted? } user.pbFaint if user.fainted? end end # Move-specific effects after all hits targets.each { |b| move.pbEffectAfterAllHits(user, b) } # Faint if 0 HP - targets.each { |b| b.pbFaint if b && b.fainted? } + targets.each { |b| b.pbFaint if b&.fainted? } user.pbFaint if user.fainted? # External/general effects after all hits. Eject Button, Shell Bell, etc. pbEffectsAfterMove(user, targets, move, realNumHits) @@ -707,7 +704,7 @@ class Battle::Battler @battle.pbPriority(true).each { |b| b.pbItemHPHealCheck } # Animate battlers fainting (checks all battlers rather than just targets # because Flame Burst's splash damage affects non-targets) - @battle.pbPriority(true).each { |b| b.pbFaint if b && b.fainted? } + @battle.pbPriority(true).each { |b| b.pbFaint if b&.fainted? } end @battle.pbJudgeCheckpoint(user, move) # Main effect (recoil/drain, etc.) @@ -716,7 +713,7 @@ class Battle::Battler move.pbEffectAgainstTarget(user, b) end move.pbEffectGeneral(user) - targets.each { |b| b.pbFaint if b && b.fainted? } + targets.each { |b| b.pbFaint if b&.fainted? } user.pbFaint if user.fainted? # Additional effect if !user.hasActiveAbility?(:SHEERFORCE) @@ -761,13 +758,12 @@ class Battle::Battler end end # Fainting - targets.each { |b| b.pbFaint if b && b.fainted? } + targets.each { |b| b.pbFaint if b&.fainted? } user.pbFaint if user.fainted? # Dragon Darts' second half of attack - if move.pbRepeatHit? && hitNum == 0 - if targets.any? { |b| !b.fainted? && !b.damageState.unaffected } - pbProcessMoveHit(move, user, all_targets, 1, skipAccuracyCheck) - end + if move.pbRepeatHit? && hitNum == 0 && + targets.any? { |b| !b.fainted? && !b.damageState.unaffected } + pbProcessMoveHit(move, user, all_targets, 1, skipAccuracyCheck) end return true end diff --git a/Data/Scripts/011_Battle/002_Battler/009_Battler_UseMoveSuccessChecks.rb b/Data/Scripts/011_Battle/002_Battler/009_Battler_UseMoveSuccessChecks.rb index 3b2494757..633e7c002 100644 --- a/Data/Scripts/011_Battle/002_Battler/009_Battler_UseMoveSuccessChecks.rb +++ b/Data/Scripts/011_Battle/002_Battler/009_Battler_UseMoveSuccessChecks.rb @@ -265,12 +265,10 @@ class Battle::Battler end end # Paralysis - if @status == :PARALYSIS - if @battle.pbRandom(100) < 25 - pbContinueStatus - @lastMoveFailed = true - return false - end + if @status == :PARALYSIS && @battle.pbRandom(100) < 25 + pbContinueStatus + @lastMoveFailed = true + return false end # Infatuation if @effects[PBEffects::Attract] >= 0 @@ -358,10 +356,9 @@ class Battle::Battler end target.damageState.protected = true @battle.successStates[user.index].protected = true - if move.pbContactMove?(user) && user.affectedByContactEffect? - if user.pbCanLowerStatStage?(:ATTACK, target) - user.pbLowerStatStage(:ATTACK, (Settings::MECHANICS_GENERATION >= 8) ? 1 : 2, target) - end + if move.pbContactMove?(user) && user.affectedByContactEffect? && + user.pbCanLowerStatStage?(:ATTACK, target) + user.pbLowerStatStage(:ATTACK, (Settings::MECHANICS_GENERATION >= 8) ? 1 : 2, target) end return false end @@ -389,8 +386,9 @@ class Battle::Battler end target.damageState.protected = true @battle.successStates[user.index].protected = true - if move.pbContactMove?(user) && user.affectedByContactEffect? - user.pbPoison(target) if user.pbCanPoison?(target, false) + if move.pbContactMove?(user) && user.affectedByContactEffect? && + user.pbCanPoison?(target, false) + user.pbPoison(target) end return false end @@ -402,10 +400,9 @@ class Battle::Battler end target.damageState.protected = true @battle.successStates[user.index].protected = true - if move.pbContactMove?(user) && user.affectedByContactEffect? - if user.pbCanLowerStatStage?(:DEFENSE, target) - user.pbLowerStatStage(:DEFENSE, 2, target) - end + if move.pbContactMove?(user) && user.affectedByContactEffect? && + user.pbCanLowerStatStage?(:DEFENSE, target) + user.pbLowerStatStage(:DEFENSE, 2, target) end return false end @@ -550,8 +547,8 @@ class Battle::Battler end end if target.effects[PBEffects::SkyDrop] >= 0 && - target.effects[PBEffects::SkyDrop] != user.index - miss = true if !move.hitsFlyingTargets? + target.effects[PBEffects::SkyDrop] != user.index && !move.hitsFlyingTargets? + miss = true end end target.damageState.invulnerable = true if miss @@ -572,9 +569,7 @@ class Battle::Battler def pbMissMessage(move, user, target) if target.damageState.affection_missed @battle.pbDisplay(_INTL("{1} avoided the move in time with your shout!", target.pbThis)) - elsif move.pbTarget(user).num_targets > 1 - @battle.pbDisplay(_INTL("{1} avoided the attack!", target.pbThis)) - elsif target.effects[PBEffects::TwoTurnAttack] + elsif move.pbTarget(user).num_targets > 1 || target.effects[PBEffects::TwoTurnAttack] @battle.pbDisplay(_INTL("{1} avoided the attack!", target.pbThis)) elsif !move.pbMissMessage(user, target) @battle.pbDisplay(_INTL("{1}'s attack missed!", user.pbThis)) diff --git a/Data/Scripts/011_Battle/002_Battler/010_Battler_UseMoveTriggerEffects.rb b/Data/Scripts/011_Battle/002_Battler/010_Battler_UseMoveTriggerEffects.rb index 751c53930..1ae15248b 100644 --- a/Data/Scripts/011_Battle/002_Battler/010_Battler_UseMoveTriggerEffects.rb +++ b/Data/Scripts/011_Battle/002_Battler/010_Battler_UseMoveTriggerEffects.rb @@ -45,27 +45,26 @@ class Battle::Battler end if target.opposes?(user) # Rage - if target.effects[PBEffects::Rage] && !target.fainted? - if target.pbCanRaiseStatStage?(:ATTACK, target) - @battle.pbDisplay(_INTL("{1}'s rage is building!", target.pbThis)) - target.pbRaiseStatStage(:ATTACK, 1, target) - end + if target.effects[PBEffects::Rage] && !target.fainted? && + target.pbCanRaiseStatStage?(:ATTACK, target) + @battle.pbDisplay(_INTL("{1}'s rage is building!", target.pbThis)) + target.pbRaiseStatStage(:ATTACK, 1, target) end # Beak Blast if target.effects[PBEffects::BeakBlast] PBDebug.log("[Lingering effect] #{target.pbThis}'s Beak Blast") - if move.pbContactMove?(user) && user.affectedByContactEffect? - target.pbBurn(user) if target.pbCanBurn?(user, false, self) + if move.pbContactMove?(user) && user.affectedByContactEffect? && + target.pbCanBurn?(user, false, self) + target.pbBurn(user) end end # Shell Trap (make the trapper move next if the trap was triggered) - if target.effects[PBEffects::ShellTrap] && - @battle.choices[target.index][0] == :UseMove && !target.movedThisRound? - if target.damageState.hpLost > 0 && !target.damageState.substitute && move.physicalMove? - target.tookPhysicalHit = true - target.effects[PBEffects::MoveNext] = true - target.effects[PBEffects::Quash] = 0 - end + if target.effects[PBEffects::ShellTrap] && move.physicalMove? && + @battle.choices[target.index][0] == :UseMove && !target.movedThisRound? && + target.damageState.hpLost > 0 && !target.damageState.substitute + target.tookPhysicalHit = true + target.effects[PBEffects::MoveNext] = true + target.effects[PBEffects::Quash] = 0 end # Grudge if target.effects[PBEffects::Grudge] && target.fainted? @@ -74,10 +73,9 @@ class Battle::Battler user.pbThis, move.name)) end # Destiny Bond (recording that it should apply) - if target.effects[PBEffects::DestinyBond] && target.fainted? - if user.effects[PBEffects::DestinyBondTarget] < 0 - user.effects[PBEffects::DestinyBondTarget] = target.index - end + if target.effects[PBEffects::DestinyBond] && target.fainted? && + user.effects[PBEffects::DestinyBondTarget] < 0 + user.effects[PBEffects::DestinyBondTarget] = target.index end end end @@ -114,10 +112,10 @@ class Battle::Battler if user.abilityActive? Battle::AbilityEffects.triggerOnEndOfUsingMove(user.ability, user, targets, move, @battle) end - # Greninja - Battle Bond if !user.fainted? && !user.effects[PBEffects::Transform] && - user.isSpecies?(:GRENINJA) && user.ability == :BATTLEBOND - if !@battle.pbAllFainted?(user.idxOpposingSide) && + !@battle.pbAllFainted?(user.idxOpposingSide) + # Greninja - Battle Bond + if user.isSpecies?(:GRENINJA) && user.ability == :BATTLEBOND && !@battle.battleBond[user.index & 1][user.pokemonIndex] numFainted = 0 targets.each { |b| numFainted += 1 if b.damageState.fainted } @@ -129,11 +127,8 @@ class Battle::Battler user.pbChangeForm(2, _INTL("{1} became Ash-Greninja!", user.pbThis)) end end - end - # Cramorant = Gulp Missile - if !user.fainted? && !user.effects[PBEffects::Transform] && - user.isSpecies?(:CRAMORANT) && user.ability == :GULPMISSILE && user.form == 0 - if !@battle.pbAllFainted?(user.idxOpposingSide) && + # Cramorant = Gulp Missile + if user.isSpecies?(:CRAMORANT) && user.ability == :GULPMISSILE && user.form == 0 && ((move.id == :SURF && numHits > 0) || (move.id == :DIVE && move.chargingTurn)) # NOTE: Intentionally no ability splash or message here. user.pbChangeForm((user.hp > user.totalhp / 2) ? 1 : 2, nil) @@ -181,16 +176,13 @@ class Battle::Battler def pbEffectsAfterMove2(user, targets, move, numHits, switched_battlers) # Target's held item (Eject Button, Red Card, Eject Pack) @battle.pbPriority(true).each do |b| - if targets.any? { |targetB| targetB.index == b.index } - if !b.damageState.unaffected && b.damageState.calcDamage > 0 && b.itemActive? - Battle::ItemEffects.triggerAfterMoveUseFromTarget(b.item, b, user, move, switched_battlers, @battle) - end + if targets.any? { |targetB| targetB.index == b.index } && + !b.damageState.unaffected && b.damageState.calcDamage > 0 && b.itemActive? + Battle::ItemEffects.triggerAfterMoveUseFromTarget(b.item, b, user, move, switched_battlers, @battle) end # Target's Eject Pack - if switched_battlers.empty? && b.index != user.index - if b.pbItemOnStatDropped(user) - switched_battlers.push(b.index) - end + if switched_battlers.empty? && b.index != user.index && b.pbItemOnStatDropped(user) + switched_battlers.push(b.index) end end # User's held item (Life Orb, Shell Bell, Throat Spray, Eject Pack) @@ -199,16 +191,14 @@ class Battle::Battler end # Target's ability (Berserk, Color Change, Emergency Exit, Pickpocket, Wimp Out) @battle.pbPriority(true).each do |b| - if targets.any? { |targetB| targetB.index == b.index } - if !b.damageState.unaffected && !switched_battlers.include?(b.index) && b.abilityActive? - Battle::AbilityEffects.triggerAfterMoveUseFromTarget(b.ability, b, user, move, switched_battlers, @battle) - end + if targets.any? { |targetB| targetB.index == b.index } && + !b.damageState.unaffected && !switched_battlers.include?(b.index) && b.abilityActive? + Battle::AbilityEffects.triggerAfterMoveUseFromTarget(b.ability, b, user, move, switched_battlers, @battle) end # Target's Emergency Exit, Wimp Out (including for Pokémon hurt by Flame Burst) - if switched_battlers.empty? && move.damagingMove? && b.index != user.index - if b.pbAbilitiesOnDamageTaken(user) - switched_battlers.push(b.index) - end + if switched_battlers.empty? && move.damagingMove? && + b.index != user.index && b.pbAbilitiesOnDamageTaken(user) + switched_battlers.push(b.index) end end end @@ -216,16 +206,12 @@ class Battle::Battler # Everything in this method is negated by Sheer Force. def pbEffectsAfterMove3(user, targets, move, numHits, switched_battlers) # User's held item that switches it out (Eject Pack) - if switched_battlers.empty? - if user.pbItemOnStatDropped(user) - switched_battlers.push(user.index) - end + if switched_battlers.empty? && user.pbItemOnStatDropped(user) + switched_battlers.push(user.index) end # User's ability (Emergency Exit, Wimp Out) - if switched_battlers.empty? && move.damagingMove? - if user.pbAbilitiesOnDamageTaken(user) - switched_battlers.push(user.index) - end + if switched_battlers.empty? && move.damagingMove? && user.pbAbilitiesOnDamageTaken(user) + switched_battlers.push(user.index) end end end diff --git a/Data/Scripts/011_Battle/003_Move/001_Battle_Move.rb b/Data/Scripts/011_Battle/003_Move/001_Battle_Move.rb index 967f9cf1d..fb70681ba 100644 --- a/Data/Scripts/011_Battle/003_Move/001_Battle_Move.rb +++ b/Data/Scripts/011_Battle/003_Move/001_Battle_Move.rb @@ -140,7 +140,7 @@ class Battle::Move def ignoresSubstitute?(user) # user is the Pokémon using this move if Settings::MECHANICS_GENERATION >= 6 return true if soundMove? - return true if user && user.hasActiveAbility?(:INFILTRATOR) + return true if user&.hasActiveAbility?(:INFILTRATOR) end return false end diff --git a/Data/Scripts/011_Battle/003_Move/003_Move_UsageCalculations.rb b/Data/Scripts/011_Battle/003_Move/003_Move_UsageCalculations.rb index e3e78db88..cccf79864 100644 --- a/Data/Scripts/011_Battle/003_Move/003_Move_UsageCalculations.rb +++ b/Data/Scripts/011_Battle/003_Move/003_Move_UsageCalculations.rb @@ -31,28 +31,29 @@ class Battle::Move #============================================================================= def pbCalcTypeModSingle(moveType, defType, user, target) ret = Effectiveness.calculate_one(moveType, defType) - # Ring Target - if target.hasActiveItem?(:RINGTARGET) - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if Effectiveness.ineffective_type?(moveType, defType) - end - # Foresight - if user.hasActiveAbility?(:SCRAPPY) || target.effects[PBEffects::Foresight] - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if defType == :GHOST && - Effectiveness.ineffective_type?(moveType, defType) - end - # Miracle Eye - if target.effects[PBEffects::MiracleEye] - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if defType == :DARK && - Effectiveness.ineffective_type?(moveType, defType) - end - # Delta Stream's weather - if target.effectiveWeather == :StrongWinds - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if defType == :FLYING && - Effectiveness.super_effective_type?(moveType, defType) + if Effectiveness.ineffective_type?(moveType, defType) + # Ring Target + if target.hasActiveItem?(:RINGTARGET) + ret = Effectiveness::NORMAL_EFFECTIVE_ONE + end + # Foresight + if (user.hasActiveAbility?(:SCRAPPY) || target.effects[PBEffects::Foresight]) && + defType == :GHOST + ret = Effectiveness::NORMAL_EFFECTIVE_ONE + end + # Miracle Eye + if target.effects[PBEffects::MiracleEye] && defType == :DARK + ret = Effectiveness::NORMAL_EFFECTIVE_ONE + end + elsif Effectiveness.super_effective_type?(moveType, defType) + # Delta Stream's weather + if target.effectiveWeather == :StrongWinds && defType == :FLYING + ret = Effectiveness::NORMAL_EFFECTIVE_ONE + end end # Grounded Flying-type Pokémon become susceptible to Ground moves - if !target.airborne? - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if defType == :FLYING && moveType == :GROUND + if !target.airborne? && defType == :FLYING && moveType == :GROUND + ret = Effectiveness::NORMAL_EFFECTIVE_ONE end return ret end @@ -493,9 +494,9 @@ class Battle::Move def pbAdditionalEffectChance(user, target, effectChance = 0) return 0 if target.hasActiveAbility?(:SHIELDDUST) && !@battle.moldBreaker ret = (effectChance > 0) ? effectChance : @addlEffect - if Settings::MECHANICS_GENERATION >= 6 || @function != "EffectDependsOnEnvironment" - ret *= 2 if user.hasActiveAbility?(:SERENEGRACE) || - user.pbOwnSide.effects[PBEffects::Rainbow] > 0 + if (Settings::MECHANICS_GENERATION >= 6 || @function != "EffectDependsOnEnvironment") && + (user.hasActiveAbility?(:SERENEGRACE) || user.pbOwnSide.effects[PBEffects::Rainbow] > 0) + ret *= 2 end ret = 100 if $DEBUG && Input.press?(Input::CTRL) return ret @@ -507,9 +508,8 @@ class Battle::Move return 0 if flinchingMove? return 0 if target.hasActiveAbility?(:SHIELDDUST) && !@battle.moldBreaker ret = 0 - if user.hasActiveAbility?(:STENCH, true) - ret = 10 - elsif user.hasActiveItem?([:KINGSROCK, :RAZORFANG], true) + if user.hasActiveAbility?(:STENCH, true) || + user.hasActiveItem?([:KINGSROCK, :RAZORFANG], true) ret = 10 end ret *= 2 if user.hasActiveAbility?(:SERENEGRACE) || diff --git a/Data/Scripts/011_Battle/003_Move/006_MoveEffects_BattlerStats.rb b/Data/Scripts/011_Battle/003_Move/006_MoveEffects_BattlerStats.rb index e9701371d..b9f937319 100644 --- a/Data/Scripts/011_Battle/003_Move/006_MoveEffects_BattlerStats.rb +++ b/Data/Scripts/011_Battle/003_Move/006_MoveEffects_BattlerStats.rb @@ -1427,9 +1427,7 @@ class Battle::Move::RaiseUserAndAlliesAtkDef1 < Battle::Move def pbEffectAgainstTarget(user, target) showAnim = true if target.pbCanRaiseStatStage?(:ATTACK, user, self) - if target.pbRaiseStatStage(:ATTACK, 1, user, showAnim) - showAnim = false - end + showAnim = false if target.pbRaiseStatStage(:ATTACK, 1, user, showAnim) end if target.pbCanRaiseStatStage?(:DEFENSE, user, self) target.pbRaiseStatStage(:DEFENSE, 1, user, showAnim) @@ -1477,9 +1475,7 @@ class Battle::Move::RaisePlusMinusUserAndAlliesAtkSpAtk1 < Battle::Move def pbEffectAgainstTarget(user, target) showAnim = true if target.pbCanRaiseStatStage?(:ATTACK, user, self) - if target.pbRaiseStatStage(:ATTACK, 1, user, showAnim) - showAnim = false - end + showAnim = false if target.pbRaiseStatStage(:ATTACK, 1, user, showAnim) end if target.pbCanRaiseStatStage?(:SPECIAL_ATTACK, user, self) target.pbRaiseStatStage(:SPECIAL_ATTACK, 1, user, showAnim) @@ -1532,9 +1528,7 @@ class Battle::Move::RaisePlusMinusUserAndAlliesDefSpDef1 < Battle::Move def pbEffectAgainstTarget(user, target) showAnim = true if target.pbCanRaiseStatStage?(:DEFENSE, user, self) - if target.pbRaiseStatStage(:DEFENSE, 1, user, showAnim) - showAnim = false - end + showAnim = false if target.pbRaiseStatStage(:DEFENSE, 1, user, showAnim) end if target.pbCanRaiseStatStage?(:SPECIAL_DEFENSE, user, self) target.pbRaiseStatStage(:SPECIAL_DEFENSE, 1, user, showAnim) @@ -1579,9 +1573,7 @@ class Battle::Move::RaiseGroundedGrassBattlersAtkSpAtk1 < Battle::Move def pbEffectAgainstTarget(user, target) showAnim = true if target.pbCanRaiseStatStage?(:ATTACK, user, self) - if target.pbRaiseStatStage(:ATTACK, 1, user, showAnim) - showAnim = false - end + showAnim = false if target.pbRaiseStatStage(:ATTACK, 1, user, showAnim) end if target.pbCanRaiseStatStage?(:SPECIAL_ATTACK, user, self) target.pbRaiseStatStage(:SPECIAL_ATTACK, 1, user, showAnim) @@ -1729,9 +1721,7 @@ class Battle::Move::UserStealTargetPositiveStatStages < Battle::Move GameData::Stat.each_battle do |s| next if target.stages[s.id] <= 0 if user.pbCanRaiseStatStage?(s.id, user, self) - if user.pbRaiseStatStage(s.id, target.stages[s.id], user, showAnim) - showAnim = false - end + showAnim = false if user.pbRaiseStatStage(s.id, target.stages[s.id], user, showAnim) end target.statsLoweredThisRound = true target.statsDropped = true diff --git a/Data/Scripts/011_Battle/003_Move/007_MoveEffects_BattlerOther.rb b/Data/Scripts/011_Battle/003_Move/007_MoveEffects_BattlerOther.rb index 63c6e78d6..ff0ce1ca9 100644 --- a/Data/Scripts/011_Battle/003_Move/007_MoveEffects_BattlerOther.rb +++ b/Data/Scripts/011_Battle/003_Move/007_MoveEffects_BattlerOther.rb @@ -209,8 +209,8 @@ class Battle::Move::ParalyzeFlinchTarget < Battle::Move return if target.damageState.substitute chance = pbAdditionalEffectChance(user, target, 10) return if chance == 0 - if @battle.pbRandom(100) < chance - target.pbParalyze(user) if target.pbCanParalyze?(user, false, self) + if target.pbCanParalyze?(user, false, self) && @battle.pbRandom(100) < chance + target.pbParalyze(user) end target.pbFlinch(user) if @battle.pbRandom(100) < chance end @@ -258,8 +258,8 @@ class Battle::Move::BurnFlinchTarget < Battle::Move return if target.damageState.substitute chance = pbAdditionalEffectChance(user, target, 10) return if chance == 0 - if @battle.pbRandom(100) < chance - target.pbBurn(user) if target.pbCanBurn?(user, false, self) + if target.pbCanBurn?(user, false, self) && @battle.pbRandom(100) < chance + target.pbBurn(user) end target.pbFlinch(user) if @battle.pbRandom(100) < chance end @@ -317,8 +317,8 @@ class Battle::Move::FreezeFlinchTarget < Battle::Move return if target.damageState.substitute chance = pbAdditionalEffectChance(user, target, 10) return if chance == 0 - if @battle.pbRandom(100) < chance - target.pbFreeze if target.pbCanFreeze?(user, false, self) + if target.pbCanFreeze?(user, false, self) && @battle.pbRandom(100) < chance + target.pbFreeze end target.pbFlinch(user) if @battle.pbRandom(100) < chance end @@ -429,7 +429,7 @@ class Battle::Move::CureUserPartyStatus < Battle::Move def pbMoveFailed?(user, targets) has_effect = @battle.allSameSideBattlers(user).any? { |b| b.status != :NONE } if !has_effect - has_effect = @battle.pbParty(user.index).any? { |pkmn| pkmn && pkmn.able? && pkmn.status != :NONE } + has_effect = @battle.pbParty(user.index).any? { |pkmn| pkmn&.able? && pkmn.status != :NONE } end if !has_effect @battle.pbDisplay(_INTL("But it failed!")) diff --git a/Data/Scripts/011_Battle/003_Move/009_MoveEffects_MultiHit.rb b/Data/Scripts/011_Battle/003_Move/009_MoveEffects_MultiHit.rb index 7080653e1..e2449dc37 100644 --- a/Data/Scripts/011_Battle/003_Move/009_MoveEffects_MultiHit.rb +++ b/Data/Scripts/011_Battle/003_Move/009_MoveEffects_MultiHit.rb @@ -221,13 +221,12 @@ end class Battle::Move::TwoTurnAttackOneTurnInSun < Battle::Move::TwoTurnMove def pbIsChargingTurn?(user) ret = super - if !user.effects[PBEffects::TwoTurnAttack] - if [:Sun, :HarshSun].include?(user.effectiveWeather) - @powerHerb = false - @chargingTurn = true - @damagingTurn = true - return false - end + if !user.effects[PBEffects::TwoTurnAttack] && + [:Sun, :HarshSun].include?(user.effectiveWeather) + @powerHerb = false + @chargingTurn = true + @damagingTurn = true + return false end return ret end diff --git a/Data/Scripts/011_Battle/003_Move/012_MoveEffects_ChangeMoveEffect.rb b/Data/Scripts/011_Battle/003_Move/012_MoveEffects_ChangeMoveEffect.rb index d593d52a8..01b89c8a4 100644 --- a/Data/Scripts/011_Battle/003_Move/012_MoveEffects_ChangeMoveEffect.rb +++ b/Data/Scripts/011_Battle/003_Move/012_MoveEffects_ChangeMoveEffect.rb @@ -175,9 +175,7 @@ class Battle::Move::CurseTargetOrLowerUserSpd1RaiseUserAtkDef1 < Battle::Move end showAnim = true if user.pbCanRaiseStatStage?(:ATTACK, user, self) - if user.pbRaiseStatStage(:ATTACK, 1, user, showAnim) - showAnim = false - end + showAnim = false if user.pbRaiseStatStage(:ATTACK, 1, user, showAnim) end if user.pbCanRaiseStatStage?(:DEFENSE, user, self) user.pbRaiseStatStage(:DEFENSE, 1, user, showAnim) @@ -562,9 +560,7 @@ class Battle::Move::PowerDependsOnUserStockpile < Battle::Move showAnim = true if user.effects[PBEffects::StockpileDef] > 0 && user.pbCanLowerStatStage?(:DEFENSE, user, self) - if user.pbLowerStatStage(:DEFENSE, user.effects[PBEffects::StockpileDef], user, showAnim) - showAnim = false - end + showAnim = false if user.pbLowerStatStage(:DEFENSE, user.effects[PBEffects::StockpileDef], user, showAnim) end if user.effects[PBEffects::StockpileSpDef] > 0 && user.pbCanLowerStatStage?(:SPECIAL_DEFENSE, user, self) @@ -611,11 +607,9 @@ class Battle::Move::HealUserDependingOnUserStockpile < Battle::Move @battle.pbDisplay(_INTL("{1}'s stockpiled effect wore off!", user.pbThis)) showAnim = true if user.effects[PBEffects::StockpileDef] > 0 && - user.pbCanLowerStatStage?(:DEFENSE, user, self) - if user.pbLowerStatStage(:DEFENSE, user.effects[PBEffects::StockpileDef], user, showAnim) + user.pbCanLowerStatStage?(:DEFENSE, user, self) && user.pbLowerStatStage(:DEFENSE, user.effects[PBEffects::StockpileDef], user, showAnim) showAnim = false end - end if user.effects[PBEffects::StockpileSpDef] > 0 && user.pbCanLowerStatStage?(:SPECIAL_DEFENSE, user, self) user.pbLowerStatStage(:SPECIAL_DEFENSE, user.effects[PBEffects::StockpileSpDef], user, showAnim) diff --git a/Data/Scripts/011_Battle/004_Scene/001_Battle_Scene.rb b/Data/Scripts/011_Battle/004_Scene/001_Battle_Scene.rb index 0bc791477..226eb5466 100644 --- a/Data/Scripts/011_Battle/004_Scene/001_Battle_Scene.rb +++ b/Data/Scripts/011_Battle/004_Scene/001_Battle_Scene.rb @@ -112,24 +112,24 @@ class Battle::Scene end def pbFrameUpdate(cw = nil) - cw.update if cw + cw&.update @battle.battlers.each_with_index do |b, i| next if !b - @sprites["dataBox_#{i}"].update(@frameCounter) if @sprites["dataBox_#{i}"] - @sprites["pokemon_#{i}"].update(@frameCounter) if @sprites["pokemon_#{i}"] - @sprites["shadow_#{i}"].update(@frameCounter) if @sprites["shadow_#{i}"] + @sprites["dataBox_#{i}"]&.update(@frameCounter) + @sprites["pokemon_#{i}"]&.update(@frameCounter) + @sprites["shadow_#{i}"]&.update(@frameCounter) end end def pbRefresh @battle.battlers.each_with_index do |b, i| next if !b - @sprites["dataBox_#{i}"].refresh if @sprites["dataBox_#{i}"] + @sprites["dataBox_#{i}"]&.refresh end end def pbRefreshOne(idxBattler) - @sprites["dataBox_#{idxBattler}"].refresh if @sprites["dataBox_#{idxBattler}"] + @sprites["dataBox_#{idxBattler}"]&.refresh end def pbRefreshEverything diff --git a/Data/Scripts/011_Battle/004_Scene/003_Scene_ChooseCommands.rb b/Data/Scripts/011_Battle/004_Scene/003_Scene_ChooseCommands.rb index 4a06e3cdc..19ab86127 100644 --- a/Data/Scripts/011_Battle/004_Scene/003_Scene_ChooseCommands.rb +++ b/Data/Scripts/011_Battle/004_Scene/003_Scene_ChooseCommands.rb @@ -70,7 +70,7 @@ class Battle::Scene cw = @sprites["fightWindow"] cw.battler = battler moveIndex = 0 - if battler.moves[@lastMove[idxBattler]] && battler.moves[@lastMove[idxBattler]].id + if battler.moves[@lastMove[idxBattler]]&.id moveIndex = @lastMove[idxBattler] end cw.shiftMode = (@battle.pbCanShift?(idxBattler)) ? 1 : 0 @@ -98,14 +98,14 @@ class Battle::Scene if Input.trigger?(Input::LEFT) cw.index -= 1 if (cw.index & 1) == 1 elsif Input.trigger?(Input::RIGHT) - if battler.moves[cw.index + 1] && battler.moves[cw.index + 1].id - cw.index += 1 if (cw.index & 1) == 0 + if battler.moves[cw.index + 1]&.id && (cw.index & 1) == 0 + cw.index += 1 end elsif Input.trigger?(Input::UP) cw.index -= 2 if (cw.index & 2) == 2 elsif Input.trigger?(Input::DOWN) - if battler.moves[cw.index + 2] && battler.moves[cw.index + 2].id - cw.index += 2 if (cw.index & 2) == 0 + if battler.moves[cw.index + 2]&.id && (cw.index & 2) == 0 + cw.index += 2 end end pbPlayCursorSE if cw.index != oldIndex diff --git a/Data/Scripts/011_Battle/004_Scene/004_Scene_PlayAnimations.rb b/Data/Scripts/011_Battle/004_Scene/004_Scene_PlayAnimations.rb index 6a6658ce5..9af5b7e15 100644 --- a/Data/Scripts/011_Battle/004_Scene/004_Scene_PlayAnimations.rb +++ b/Data/Scripts/011_Battle/004_Scene/004_Scene_PlayAnimations.rb @@ -137,8 +137,8 @@ class Battle::Scene a[2] = true if a[1].animDone? end pbUpdate - if !inPartyAnimation? - break if !sendOutAnims.any? { |a| !a[2] } + if !inPartyAnimation? && !sendOutAnims.any? { |a| !a[2] } + break end end fadeAnim.dispose @@ -165,7 +165,7 @@ class Battle::Scene # Recall animation recallAnim = Animation::BattlerRecall.new(@sprites, @viewport, idxBattler) loop do - recallAnim.update if recallAnim + recallAnim&.update pbUpdate break if recallAnim.animDone? end @@ -495,7 +495,7 @@ class Battle::Scene animID = pbFindMoveAnimation(moveID, user.index, hitNum) return if !animID anim = animID[0] - target = (targets && targets.is_a?(Array)) ? targets[0] : targets + target = (targets.is_a?(Array)) ? targets[0] : targets animations = pbLoadBattleAnimations return if !animations pbSaveShadows { @@ -510,7 +510,7 @@ class Battle::Scene # Plays a common animation. def pbCommonAnimation(animName, user = nil, target = nil) return if nil_or_empty?(animName) - target = target[0] if target && target.is_a?(Array) + target = target[0] if target.is_a?(Array) animations = pbLoadBattleAnimations return if !animations animations.each do |a| @@ -534,7 +534,7 @@ class Battle::Scene animPlayer = PBAnimationPlayerX.new(animation, user, target, self, oppMove) # Apply a transformation to the animation based on where the user and target # actually are. Get the centres of each sprite. - userHeight = (userSprite && userSprite.bitmap && !userSprite.bitmap.disposed?) ? userSprite.bitmap.height : 128 + userHeight = (userSprite&.bitmap && !userSprite.bitmap.disposed?) ? userSprite.bitmap.height : 128 if targetSprite targetHeight = (targetSprite.bitmap && !targetSprite.bitmap.disposed?) ? targetSprite.bitmap.height : 128 else diff --git a/Data/Scripts/011_Battle/004_Scene/005_Battle_Scene_Menus.rb b/Data/Scripts/011_Battle/004_Scene/005_Battle_Scene_Menus.rb index ea506053e..8008de645 100644 --- a/Data/Scripts/011_Battle/004_Scene/005_Battle_Scene_Menus.rb +++ b/Data/Scripts/011_Battle/004_Scene/005_Battle_Scene_Menus.rb @@ -161,7 +161,7 @@ class Battle::Scene::CommandMenu < Battle::Scene::MenuBase def dispose super - @buttonBitmap.dispose if @buttonBitmap + @buttonBitmap&.dispose end def z=(value) @@ -191,7 +191,7 @@ class Battle::Scene::CommandMenu < Battle::Scene::MenuBase def refresh @msgBox.refresh - @cmdWindow.refresh if @cmdWindow + @cmdWindow&.refresh refreshButtons end end @@ -310,10 +310,10 @@ class Battle::Scene::FightMenu < Battle::Scene::MenuBase def dispose super - @buttonBitmap.dispose if @buttonBitmap - @typeBitmap.dispose if @typeBitmap - @megaEvoBitmap.dispose if @megaEvoBitmap - @shiftBitmap.dispose if @shiftBitmap + @buttonBitmap&.dispose + @typeBitmap&.dispose + @megaEvoBitmap&.dispose + @shiftBitmap&.dispose end def z=(value) @@ -510,7 +510,7 @@ class Battle::Scene::TargetMenu < Battle::Scene::MenuBase def dispose super - @buttonBitmap.dispose if @buttonBitmap + @buttonBitmap&.dispose end def z=(value) diff --git a/Data/Scripts/011_Battle/004_Scene/006_Battle_Scene_Objects.rb b/Data/Scripts/011_Battle/004_Scene/006_Battle_Scene_Objects.rb index 8ea0fc87e..3c9cfa787 100644 --- a/Data/Scripts/011_Battle/004_Scene/006_Battle_Scene_Objects.rb +++ b/Data/Scripts/011_Battle/004_Scene/006_Battle_Scene_Objects.rb @@ -52,7 +52,7 @@ class Battle::Scene::PokemonDataBox < SpriteWrapper bgFilename = ["Graphics/Pictures/Battle/databox_thin", "Graphics/Pictures/Battle/databox_thin_foe"][@battler.index % 2] end - @databoxBitmap.dispose if @databoxBitmap + @databoxBitmap&.dispose @databoxBitmap = AnimatedBitmap.new(bgFilename) # Determine the co-ordinates of the data box and the left edge padding width if onPlayerSide @@ -500,7 +500,7 @@ class Battle::Scene::BattlerSprite < RPG::Sprite end def dispose - @_iconBitmap.dispose if @_iconBitmap + @_iconBitmap&.dispose @_iconBitmap = nil self.bitmap = nil if !self.disposed? super @@ -552,7 +552,7 @@ class Battle::Scene::BattlerSprite < RPG::Sprite def setPokemonBitmap(pkmn, back = false) @pkmn = pkmn - @_iconBitmap.dispose if @_iconBitmap + @_iconBitmap&.dispose @_iconBitmap = GameData::Species.sprite_bitmap_from_pokemon(@pkmn, back) self.bitmap = (@_iconBitmap) ? @_iconBitmap.bitmap : nil pbSetPosition @@ -563,7 +563,7 @@ class Battle::Scene::BattlerSprite < RPG::Sprite # recommendation is to create a PictureEx animation and push it into # the @battleAnimations array. def pbPlayIntroAnimation(pictureEx = nil) - @pkmn.play_cry if @pkmn + @pkmn&.play_cry end QUARTER_ANIM_PERIOD = Graphics.frame_rate * 3 / 20 @@ -617,7 +617,7 @@ class Battle::Scene::BattlerShadowSprite < RPG::Sprite end def dispose - @_iconBitmap.dispose if @_iconBitmap + @_iconBitmap&.dispose @_iconBitmap = nil self.bitmap = nil if !self.disposed? super @@ -647,7 +647,7 @@ class Battle::Scene::BattlerShadowSprite < RPG::Sprite def setPokemonBitmap(pkmn) @pkmn = pkmn - @_iconBitmap.dispose if @_iconBitmap + @_iconBitmap&.dispose @_iconBitmap = GameData::Species.shadow_bitmap_from_pokemon(@pkmn) self.bitmap = (@_iconBitmap) ? @_iconBitmap.bitmap : nil pbSetPosition diff --git a/Data/Scripts/011_Battle/004_Scene/007_Battle_Scene_BaseAnimation.rb b/Data/Scripts/011_Battle/004_Scene/007_Battle_Scene_BaseAnimation.rb index 587b2742f..3322ff64e 100644 --- a/Data/Scripts/011_Battle/004_Scene/007_Battle_Scene_BaseAnimation.rb +++ b/Data/Scripts/011_Battle/004_Scene/007_Battle_Scene_BaseAnimation.rb @@ -10,7 +10,7 @@ class Battle::Scene::Animation end def dispose - @tempSprites.each { |s| s.dispose if s } + @tempSprites.each { |s| s&.dispose } end def createProcesses; end @@ -47,7 +47,7 @@ class Battle::Scene::Animation def update return if @animDone - @tempSprites.each { |s| s.update if s } + @tempSprites.each { |s| s&.update } finished = true @pictureEx.each_with_index do |p, i| next if !p.running? diff --git a/Data/Scripts/011_Battle/004_Scene/008_Battle_Scene_Animations.rb b/Data/Scripts/011_Battle/004_Scene/008_Battle_Scene_Animations.rb index 98fc2e2d2..c7acd1985 100644 --- a/Data/Scripts/011_Battle/004_Scene/008_Battle_Scene_Animations.rb +++ b/Data/Scripts/011_Battle/004_Scene/008_Battle_Scene_Animations.rb @@ -140,9 +140,9 @@ class Battle::Scene::Animation::LineupAppear < Battle::Scene::Animation startsIndex = idxBall / ballsPerTrainer teamIndex = idxBall % ballsPerTrainer ret = @partyStarts[startsIndex] + teamIndex - if startsIndex < @partyStarts.length - 1 + if startsIndex < @partyStarts.length - 1 && ret >= @partyStarts[startsIndex + 1] # There is a later trainer, don't spill over into its team - return -1 if ret >= @partyStarts[startsIndex + 1] + return -1 end return ret end @@ -332,7 +332,7 @@ class Battle::Scene::Animation::PlayerFade < Battle::Scene::Animation end # Move and fade party bar/balls delay = 3 - if @sprites["partyBar_0"] && @sprites["partyBar_0"].visible + if @sprites["partyBar_0"]&.visible partyBar = addSprite(@sprites["partyBar_0"]) partyBar.moveDelta(delay, 16, -Graphics.width / 4, 0) if @fullAnim partyBar.moveOpacity(delay, 12, 0) @@ -377,7 +377,7 @@ class Battle::Scene::Animation::TrainerFade < Battle::Scene::Animation end # Move and fade party bar/balls delay = 3 - if @sprites["partyBar_1"] && @sprites["partyBar_1"].visible + if @sprites["partyBar_1"]&.visible partyBar = addSprite(@sprites["partyBar_1"]) partyBar.moveDelta(delay, 16, Graphics.width / 4, 0) if @fullAnim partyBar.moveOpacity(delay, 12, 0) @@ -722,12 +722,10 @@ class Battle::Scene::Animation::PokeballThrowCapture < Battle::Scene::Animation ball.setZ(0, batSprite.z + 1) @ballSpriteIndex = (@success) ? @tempSprites.length - 1 : -1 # Set up trainer sprite (only visible in Safari Zone battles) - if @showingTrainer && traSprite - if traSprite.bitmap.width >= traSprite.bitmap.height * 2 - trainer = addSprite(traSprite, PictureOrigin::Bottom) - # Trainer animation - ballStartX, ballStartY = trainerThrowingFrames(ball, trainer, traSprite) - end + if @showingTrainer && traSprite && traSprite.bitmap.width >= traSprite.bitmap.height * 2 + trainer = addSprite(traSprite, PictureOrigin::Bottom) + # Trainer animation + ballStartX, ballStartY = trainerThrowingFrames(ball, trainer, traSprite) end delay = ball.totalDuration # 0 or 7 # Poké Ball arc animation diff --git a/Data/Scripts/011_Battle/005_AI/002_AI_Item.rb b/Data/Scripts/011_Battle/005_AI/002_AI_Item.rb index 1990cbc48..32c79e246 100644 --- a/Data/Scripts/011_Battle/005_AI/002_AI_Item.rb +++ b/Data/Scripts/011_Battle/005_AI/002_AI_Item.rb @@ -115,12 +115,10 @@ class Battle::AI end end # Log Full Restores (HP healer and status curer) - if losthp > 0 || battler.status != :NONE - if fullRestoreItems.include?(i) - usableHPItems.push([i, (preferFullRestore) ? 3 : 7, 999]) - usableStatusItems.push([i, (preferFullRestore) ? 3 : 9]) - next - end + if fullRestoreItems.include?(i) && (losthp > 0 || battler.status != :NONE) + usableHPItems.push([i, (preferFullRestore) ? 3 : 7, 999]) + usableStatusItems.push([i, (preferFullRestore) ? 3 : 9]) + next end # Log single status-curing items if oneStatusItems.include?(i) diff --git a/Data/Scripts/011_Battle/005_AI/003_AI_Switch.rb b/Data/Scripts/011_Battle/005_AI/003_AI_Switch.rb index 8a855e667..49fd61c81 100644 --- a/Data/Scripts/011_Battle/005_AI/003_AI_Switch.rb +++ b/Data/Scripts/011_Battle/005_AI/003_AI_Switch.rb @@ -48,8 +48,8 @@ class Battle::AI skill >= PBTrainerAI.highSkill toxicHP = battler.totalhp / 16 nextToxicHP = toxicHP * (battler.effects[PBEffects::Toxic] + 1) - if battler.hp <= nextToxicHP && battler.hp > toxicHP * 2 - shouldSwitch = true if pbAIRandom(100) < 80 + if battler.hp <= nextToxicHP && battler.hp > toxicHP * 2 && pbAIRandom(100) < 80 + shouldSwitch = true end end # Pokémon is Encored into an unfavourable move @@ -62,8 +62,8 @@ class Battle::AI scoreSum += pbGetMoveScore(battler.moves[idxEncoredMove], battler, b, skill) scoreCount += 1 end - if scoreCount > 0 && scoreSum / scoreCount <= 20 - shouldSwitch = true if pbAIRandom(100) < 80 + if scoreCount > 0 && scoreSum / scoreCount <= 20 && pbAIRandom(100) < 80 + shouldSwitch = true end end end @@ -72,9 +72,9 @@ class Battle::AI if @battle.pbSideSize(battler.index + 1) == 1 && !battler.pbDirectOpposing.fainted? && skill >= PBTrainerAI.highSkill opp = battler.pbDirectOpposing - if opp.effects[PBEffects::HyperBeam] > 0 || - (opp.hasActiveAbility?(:TRUANT) && opp.effects[PBEffects::Truant]) - shouldSwitch = false if pbAIRandom(100) < 80 + if (opp.effects[PBEffects::HyperBeam] > 0 || + (opp.hasActiveAbility?(:TRUANT) && opp.effects[PBEffects::Truant])) && pbAIRandom(100) < 80 + shouldSwitch = false end end # Sudden Death rule - I'm not sure what this means @@ -103,9 +103,8 @@ class Battle::AI # Don't switch to this if too little HP if spikes > 0 spikesDmg = [8, 6, 4][spikes - 1] - if pkmn.hp <= pkmn.totalhp / spikesDmg - next if !pkmn.hasType?(:FLYING) && !pkmn.hasActiveAbility?(:LEVITATE) - end + next if pkmn.hp <= pkmn.totalhp / spikesDmg && + !pkmn.hasType?(:FLYING) && !pkmn.hasActiveAbility?(:LEVITATE) end end # moveType is the type of the target's last used move @@ -136,7 +135,7 @@ class Battle::AI end if @battle.pbRegisterSwitch(idxBattler, list[0]) PBDebug.log("[AI] #{battler.pbThis} (#{idxBattler}) will switch with " + - "#{@battle.pbParty(idxBattler)[list[0]].name}") + @battle.pbParty(idxBattler)[list[0]].name) return true end end diff --git a/Data/Scripts/011_Battle/005_AI/004_AI_Move.rb b/Data/Scripts/011_Battle/005_AI/004_AI_Move.rb index 1cffeab05..3021bb4f4 100644 --- a/Data/Scripts/011_Battle/005_AI/004_AI_Move.rb +++ b/Data/Scripts/011_Battle/005_AI/004_AI_Move.rb @@ -61,9 +61,9 @@ class Battle::AI # Decide whether all choices are bad, and if so, try switching instead if !wildBattler && skill >= PBTrainerAI.highSkill badMoves = false - if (maxScore <= 20 && user.turnCount > 2) || - (maxScore <= 40 && user.turnCount > 5) - badMoves = true if pbAIRandom(100) < 80 + if ((maxScore <= 20 && user.turnCount > 2) || + (maxScore <= 40 && user.turnCount > 5)) && pbAIRandom(100) < 80 + badMoves = true end if !badMoves && totalScore < 100 && user.turnCount > 1 badMoves = true @@ -160,13 +160,12 @@ class Battle::AI return 0 if score <= 0 if skill >= PBTrainerAI.mediumSkill # Prefer damaging moves if AI has no more Pokémon or AI is less clever - if @battle.pbAbleNonActiveCount(user.idxOwnSide) == 0 - if !(skill >= PBTrainerAI.highSkill && @battle.pbAbleNonActiveCount(target.idxOwnSide) > 0) - if move.statusMove? - score /= 1.5 - elsif target.hp <= target.totalhp / 2 - score *= 1.5 - end + if @battle.pbAbleNonActiveCount(user.idxOwnSide) == 0 && + !(skill >= PBTrainerAI.highSkill && @battle.pbAbleNonActiveCount(target.idxOwnSide) > 0) + if move.statusMove? + score /= 1.5 + elsif target.hp <= target.totalhp / 2 + score *= 1.5 end end # Don't prefer attacking the target if they'd be semi-invulnerable @@ -266,18 +265,16 @@ class Battle::AI end # Prefer flinching external effects (note that move effects which cause # flinching are dealt with in the function code part of score calculation) - if skill >= PBTrainerAI.mediumSkill && !move.flinchingMove? - if !target.hasActiveAbility?(:INNERFOCUS) && - !target.hasActiveAbility?(:SHIELDDUST) && - target.effects[PBEffects::Substitute] == 0 - canFlinch = false - if user.hasActiveItem?([:KINGSROCK, :RAZORFANG]) - canFlinch = true - elsif user.hasActiveAbility?(:STENCH) - canFlinch = true - end - realDamage *= 1.3 if canFlinch + if skill >= PBTrainerAI.mediumSkill && !move.flinchingMove? && + !target.hasActiveAbility?(:INNERFOCUS) && + !target.hasActiveAbility?(:SHIELDDUST) && + target.effects[PBEffects::Substitute] == 0 + canFlinch = false + if user.hasActiveItem?([:KINGSROCK, :RAZORFANG]) || + user.hasActiveAbility?(:STENCH) + canFlinch = true end + realDamage *= 1.3 if canFlinch end # Convert damage to percentage of target's remaining HP damagePercentage = realDamage * 100.0 / target.hp diff --git a/Data/Scripts/011_Battle/005_AI/005_AI_Move_EffectScores.rb b/Data/Scripts/011_Battle/005_AI/005_AI_Move_EffectScores.rb index f83b3df13..3e9a2bf4c 100644 --- a/Data/Scripts/011_Battle/005_AI/005_AI_Move_EffectScores.rb +++ b/Data/Scripts/011_Battle/005_AI/005_AI_Move_EffectScores.rb @@ -859,9 +859,7 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetAttack1" if move.statusMove? - if !target.pbCanLowerStatStage?(:ATTACK, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:ATTACK, user) score += target.stages[:ATTACK] * 20 if skill >= PBTrainerAI.mediumSkill hasPhysicalAttack = false @@ -876,6 +874,8 @@ class Battle::AI score -= 90 end end + else + score -= 90 end else score += 20 if target.stages[:ATTACK] > 0 @@ -892,10 +892,10 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetDefense1" if move.statusMove? - if !target.pbCanLowerStatStage?(:DEFENSE, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:DEFENSE, user) score += target.stages[:DEFENSE] * 20 + else + score -= 90 end elsif target.stages[:DEFENSE] > 0 score += 20 @@ -903,15 +903,15 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetSpeed1", "LowerTargetSpeed1WeakerInGrassyTerrain" if move.statusMove? - if !target.pbCanLowerStatStage?(:SPEED, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:SPEED, user) score += target.stages[:SPEED] * 10 if skill >= PBTrainerAI.highSkill aspeed = pbRoughStat(user, :SPEED, skill) ospeed = pbRoughStat(target, :SPEED, skill) score += 30 if aspeed < ospeed && aspeed * 2 > ospeed end + else + score -= 90 end elsif user.stages[:SPEED] > 0 score += 20 @@ -919,9 +919,7 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetSpAtk1" if move.statusMove? - if !target.pbCanLowerStatStage?(:SPECIAL_ATTACK, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:SPECIAL_ATTACK, user) score += user.stages[:SPECIAL_ATTACK] * 20 if skill >= PBTrainerAI.mediumSkill hasSpecicalAttack = false @@ -936,6 +934,8 @@ class Battle::AI score -= 90 end end + else + score -= 90 end else score += 20 if user.stages[:SPECIAL_ATTACK] > 0 @@ -952,10 +952,10 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetSpDef1" if move.statusMove? - if !target.pbCanLowerStatStage?(:SPECIAL_DEFENSE, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:SPECIAL_DEFENSE, user) score += target.stages[:SPECIAL_DEFENSE] * 20 + else + score -= 90 end elsif target.stages[:SPECIAL_DEFENSE] > 0 score += 20 @@ -963,10 +963,10 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetAccuracy1", "LowerTargetAccuracy2", "LowerTargetAccuracy3" if move.statusMove? - if !target.pbCanLowerStatStage?(:ACCURACY, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:ACCURACY, user) score += target.stages[:ACCURACY] * 10 + else + score -= 90 end elsif target.stages[:ACCURACY] > 0 score += 20 @@ -974,10 +974,10 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetEvasion1", "LowerTargetEvasion2", "LowerTargetEvasion3" if move.statusMove? - if !target.pbCanLowerStatStage?(:EVASION, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:EVASION, user) score += target.stages[:EVASION] * 10 + else + score -= 90 end elsif target.stages[:EVASION] > 0 score += 20 @@ -985,10 +985,10 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetEvasion1RemoveSideEffects" if move.statusMove? - if !target.pbCanLowerStatStage?(:EVASION, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:EVASION, user) score += target.stages[:EVASION] * 10 + else + score -= 90 end elsif target.stages[:EVASION] > 0 score += 20 @@ -1009,9 +1009,7 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetAttack2", "LowerTargetAttack3" if move.statusMove? - if !target.pbCanLowerStatStage?(:ATTACK, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:ATTACK, user) score += 40 if user.turnCount == 0 score += target.stages[:ATTACK] * 20 if skill >= PBTrainerAI.mediumSkill @@ -1027,6 +1025,8 @@ class Battle::AI score -= 90 end end + else + score -= 90 end else score += 10 if user.turnCount == 0 @@ -1044,11 +1044,11 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetDefense2", "LowerTargetDefense3" if move.statusMove? - if !target.pbCanLowerStatStage?(:DEFENSE, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:DEFENSE, user) score += 40 if user.turnCount == 0 score += target.stages[:DEFENSE] * 20 + else + score -= 90 end else score += 10 if user.turnCount == 0 @@ -1057,9 +1057,7 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetSpeed2", "LowerTargetSpeed3" if move.statusMove? - if !target.pbCanLowerStatStage?(:SPEED, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:SPEED, user) score += 20 if user.turnCount == 0 score += target.stages[:SPEED] * 20 if skill >= PBTrainerAI.highSkill @@ -1067,6 +1065,8 @@ class Battle::AI ospeed = pbRoughStat(target, :SPEED, skill) score += 30 if aspeed < ospeed && aspeed * 2 > ospeed end + else + score -= 90 end else score += 10 if user.turnCount == 0 @@ -1078,9 +1078,7 @@ class Battle::AI target.hasActiveAbility?(:OBLIVIOUS) score -= 90 elsif move.statusMove? - if !target.pbCanLowerStatStage?(:SPECIAL_ATTACK, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:SPECIAL_ATTACK, user) score += 40 if user.turnCount == 0 score += target.stages[:SPECIAL_ATTACK] * 20 if skill >= PBTrainerAI.mediumSkill @@ -1096,6 +1094,8 @@ class Battle::AI score -= 90 end end + else + score -= 90 end else score += 10 if user.turnCount == 0 @@ -1113,11 +1113,11 @@ class Battle::AI #--------------------------------------------------------------------------- when "LowerTargetSpDef2", "LowerTargetSpDef3" if move.statusMove? - if !target.pbCanLowerStatStage?(:SPECIAL_DEFENSE, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:SPECIAL_DEFENSE, user) score += 40 if user.turnCount == 0 score += target.stages[:SPECIAL_DEFENSE] * 20 + else + score -= 90 end else score += 10 if user.turnCount == 0 @@ -1323,9 +1323,7 @@ class Battle::AI end #--------------------------------------------------------------------------- when "SetUserTypesToUserMoveType" - if !user.canChangeType? - score -= 90 - else + if user.canChangeType? has_possible_type = false user.eachMoveWithIndex do |m, i| break if Settings::MECHANICS_GENERATION >= 6 && i > 0 @@ -1335,6 +1333,8 @@ class Battle::AI break end score -= 90 if !has_possible_type + else + score -= 90 end #--------------------------------------------------------------------------- when "SetUserTypesToResistLastAttack" @@ -1350,9 +1350,7 @@ class Battle::AI aType = m.pbCalcType(user) break end - if !aType - score -= 90 - else + if aType has_possible_type = false GameData::Type.each do |t| next if t.pseudo_type || user.pbHasType?(t.id) || @@ -1361,6 +1359,8 @@ class Battle::AI break end score -= 90 if !has_possible_type + else + score -= 90 end end #--------------------------------------------------------------------------- @@ -1793,9 +1793,7 @@ class Battle::AI if target.effects[PBEffects::Encore] > 0 score -= 90 elsif aspeed > ospeed - if !target.lastRegularMoveUsed - score -= 90 - else + if target.lastRegularMoveUsed moveData = GameData::Move.get(target.lastRegularMoveUsed) if moveData.category == 2 && # Status move [:User, :BothSides].include?(moveData.target) @@ -1805,6 +1803,8 @@ class Battle::AI Effectiveness.ineffective?(pbCalcTypeMod(moveData.type, target, user)) score += 60 end + else + score -= 90 end end #--------------------------------------------------------------------------- @@ -2056,9 +2056,7 @@ class Battle::AI end #--------------------------------------------------------------------------- when "SwitchOutUserPassOnEffects" - if !@battle.pbCanChooseNonActive?(user.index) - score -= 100 - else + if @battle.pbCanChooseNonActive?(user.index) score -= 40 if user.effects[PBEffects::Confusion] > 0 total = 0 GameData::Stat.each_battle { |s| total += user.stages[s.id] } @@ -2075,6 +2073,8 @@ class Battle::AI end score += 75 if !hasDamagingMove end + else + score -= 100 end #--------------------------------------------------------------------------- when "TrapTargetInBattle" @@ -2505,9 +2505,7 @@ class Battle::AI end #--------------------------------------------------------------------------- when "LowerTargetAttack1BypassSubstitute" - if !target.pbCanLowerStatStage?(:ATTACK, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:ATTACK, user) score += target.stages[:ATTACK] * 20 if skill >= PBTrainerAI.mediumSkill hasPhysicalAttack = false @@ -2522,6 +2520,8 @@ class Battle::AI score -= 90 end end + else + score -= 90 end #--------------------------------------------------------------------------- when "LowerTargetAtkSpAtk1" @@ -2537,11 +2537,11 @@ class Battle::AI end #--------------------------------------------------------------------------- when "LowerTargetSpAtk2", "LowerTargetSpAtk3" - if !target.pbCanLowerStatStage?(:SPECIAL_ATTACK, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:SPECIAL_ATTACK, user) score += 40 if user.turnCount == 0 score += target.stages[:SPECIAL_ATTACK] * 20 + else + score -= 90 end #--------------------------------------------------------------------------- when "RaiseGroundedGrassBattlersAtkSpAtk1" @@ -3005,7 +3005,7 @@ class Battle::AI end GameData::Stat.each_main_battle { |s| score += 10 if user.stages[s.id] <= 0 } if skill >= PBTrainerAI.mediumSkill - hasDamagingAttack = user.moves.any? { |m| next m && m.damagingMove? } + hasDamagingAttack = user.moves.any? { |m| next m&.damagingMove? } score += 20 if hasDamagingAttack end end @@ -3031,7 +3031,7 @@ class Battle::AI end GameData::Stat.each_main_battle { |s| score += 10 if user.stages[s.id] <= 0 } if skill >= PBTrainerAI.mediumSkill - hasDamagingAttack = user.moves.any? { |m| next m && m.damagingMove? } + hasDamagingAttack = user.moves.any? { |m| next m&.damagingMove? } score += 20 if hasDamagingAttack end end @@ -3064,11 +3064,11 @@ class Battle::AI end #--------------------------------------------------------------------------- when "LowerTargetDefense1DoublePowerInGravity" - if !target.pbCanLowerStatStage?(:DEFENSE, user) - score -= 90 - else + if target.pbCanLowerStatStage?(:DEFENSE, user) score += 20 score += target.stages[:DEFENSE] * 20 + else + score -= 90 end score += 30 if @battle.field.effects[PBEffects::Gravity] > 0 #--------------------------------------------------------------------------- diff --git a/Data/Scripts/011_Battle/005_AI/006_AI_Move_Utilities.rb b/Data/Scripts/011_Battle/005_AI/006_AI_Move_Utilities.rb index 938d827d0..ab6e64fe5 100644 --- a/Data/Scripts/011_Battle/005_AI/006_AI_Move_Utilities.rb +++ b/Data/Scripts/011_Battle/005_AI/006_AI_Move_Utilities.rb @@ -28,28 +28,29 @@ class Battle::AI #============================================================================= def pbCalcTypeModSingle(moveType, defType, user, target) ret = Effectiveness.calculate_one(moveType, defType) - # Ring Target - if target.hasActiveItem?(:RINGTARGET) - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if Effectiveness.ineffective_type?(moveType, defType) - end - # Foresight - if user.hasActiveAbility?(:SCRAPPY) || target.effects[PBEffects::Foresight] - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if defType == :GHOST && - Effectiveness.ineffective_type?(moveType, defType) - end - # Miracle Eye - if target.effects[PBEffects::MiracleEye] - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if defType == :DARK && - Effectiveness.ineffective_type?(moveType, defType) - end - # Delta Stream's weather - if target.effectiveWeather == :StrongWinds - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if defType == :FLYING && - Effectiveness.super_effective_type?(moveType, defType) + if Effectiveness.ineffective_type?(moveType, defType) + # Ring Target + if target.hasActiveItem?(:RINGTARGET) + ret = Effectiveness::NORMAL_EFFECTIVE_ONE + end + # Foresight + if (user.hasActiveAbility?(:SCRAPPY) || target.effects[PBEffects::Foresight]) && + defType == :GHOST + ret = Effectiveness::NORMAL_EFFECTIVE_ONE + end + # Miracle Eye + if target.effects[PBEffects::MiracleEye] && defType == :DARK + ret = Effectiveness::NORMAL_EFFECTIVE_ONE + end + elsif Effectiveness.super_effective_type?(moveType, defType) + # Delta Stream's weather + if target.effectiveWeather == :StrongWinds && defType == :FLYING + ret = Effectiveness::NORMAL_EFFECTIVE_ONE + end end # Grounded Flying-type Pokémon become susceptible to Ground moves - if !target.airborne? - ret = Effectiveness::NORMAL_EFFECTIVE_ONE if defType == :FLYING && moveType == :GROUND + if !target.airborne? && defType == :FLYING && moveType == :GROUND + ret = Effectiveness::NORMAL_EFFECTIVE_ONE end return ret end @@ -256,7 +257,7 @@ class Battle::AI when "HitOncePerUserTeamMember" # Beat Up mult = 0 @battle.eachInTeamFromBattlerIndex(user.index) do |pkmn, _i| - mult += 1 if pkmn && pkmn.able? && pkmn.status == :NONE + mult += 1 if pkmn&.able? && pkmn.status == :NONE end baseDmg *= mult when "TwoTurnAttackOneTurnInSun" # Solar Beam @@ -390,26 +391,20 @@ class Battle::AI ) end end - if skill >= PBTrainerAI.bestSkill && target.itemActive? - # NOTE: Type-weakening berries aren't suitable for checking at the start - # of the round. - if target.item && !target.item.is_berry? + if skill >= PBTrainerAI.bestSkill && target.itemActive? && (target.item && !target.item.is_berry?) Battle::ItemEffects.triggerDamageCalcFromTarget( target.item, user, target, move, multipliers, baseDmg, type ) end - end # Global abilities - if skill >= PBTrainerAI.mediumSkill - if (@battle.pbCheckGlobalAbility(:DARKAURA) && type == :DARK) || - (@battle.pbCheckGlobalAbility(:FAIRYAURA) && type == :FAIRY) + if skill >= PBTrainerAI.mediumSkill && ((@battle.pbCheckGlobalAbility(:DARKAURA) && type == :DARK) || + (@battle.pbCheckGlobalAbility(:FAIRYAURA) && type == :FAIRY)) if @battle.pbCheckGlobalAbility(:AURABREAK) multipliers[:base_damage_multiplier] *= 2 / 3.0 else multipliers[:base_damage_multiplier] *= 4 / 3.0 end end - end # Parental Bond if skill >= PBTrainerAI.mediumSkill && user.hasActiveAbility?(:PARENTALBOND) multipliers[:base_damage_multiplier] *= 1.25 @@ -418,11 +413,9 @@ class Battle::AI # TODO # Helping Hand - n/a # Charge - if skill >= PBTrainerAI.mediumSkill - if user.effects[PBEffects::Charge] > 0 && type == :ELECTRIC + if skill >= PBTrainerAI.mediumSkill && (user.effects[PBEffects::Charge] > 0 && type == :ELECTRIC) multipliers[:base_damage_multiplier] *= 2 end - end # Mud Sport and Water Sport if skill >= PBTrainerAI.mediumSkill if type == :ELECTRIC @@ -456,25 +449,17 @@ class Battle::AI end end # Badge multipliers - if skill >= PBTrainerAI.highSkill - if @battle.internalBattle - # Don't need to check the Atk/Sp Atk-boosting badges because the AI - # won't control the player's Pokémon. - if target.pbOwnedByPlayer? + if skill >= PBTrainerAI.highSkill && @battle.internalBattle && target.pbOwnedByPlayer? if move.physicalMove?(type) && @battle.pbPlayer.badge_count >= Settings::NUM_BADGES_BOOST_DEFENSE multipliers[:defense_multiplier] *= 1.1 elsif move.specialMove?(type) && @battle.pbPlayer.badge_count >= Settings::NUM_BADGES_BOOST_SPDEF multipliers[:defense_multiplier] *= 1.1 end end - end - end # Multi-targeting attacks - if skill >= PBTrainerAI.highSkill - if pbTargetsMultiple?(move, user) + if skill >= PBTrainerAI.highSkill && pbTargetsMultiple?(move, user) multipliers[:final_damage_multiplier] *= 0.75 end - end # Weather if skill >= PBTrainerAI.mediumSkill case user.effectiveWeather @@ -502,31 +487,26 @@ class Battle::AI # Critical hits - n/a # Random variance - n/a # STAB - if skill >= PBTrainerAI.mediumSkill - if type && user.pbHasType?(type) + if skill >= PBTrainerAI.mediumSkill && (type && user.pbHasType?(type)) if user.hasActiveAbility?(:ADAPTABILITY) multipliers[:final_damage_multiplier] *= 2 else multipliers[:final_damage_multiplier] *= 1.5 end end - end # Type effectiveness if skill >= PBTrainerAI.mediumSkill typemod = pbCalcTypeMod(type, user, target) multipliers[:final_damage_multiplier] *= typemod.to_f / Effectiveness::NORMAL_EFFECTIVE end # Burn - if skill >= PBTrainerAI.highSkill - if user.status == :BURN && move.physicalMove?(type) && + if skill >= PBTrainerAI.highSkill && (user.status == :BURN && move.physicalMove?(type) && !user.hasActiveAbility?(:GUTS) && - !(Settings::MECHANICS_GENERATION >= 6 && move.function == "DoublePowerIfUserPoisonedBurnedParalyzed") # Facade + !(Settings::MECHANICS_GENERATION >= 6 && move.function == "DoublePowerIfUserPoisonedBurnedParalyzed")) # Facade multipliers[:final_damage_multiplier] /= 2 end - end # Aurora Veil, Reflect, Light Screen - if skill >= PBTrainerAI.highSkill - if !move.ignoresReflect? && !user.hasActiveAbility?(:INFILTRATOR) + if skill >= PBTrainerAI.highSkill && (!move.ignoresReflect? && !user.hasActiveAbility?(:INFILTRATOR)) if target.pbOwnSide.effects[PBEffects::AuroraVeil] > 0 if @battle.pbSideBattlerCount(target) > 1 multipliers[:final_damage_multiplier] *= 2 / 3.0 @@ -547,13 +527,10 @@ class Battle::AI end end end - end # Minimize - if skill >= PBTrainerAI.highSkill - if target.effects[PBEffects::Minimize] && move.tramplesMinimize?(2) + if skill >= PBTrainerAI.highSkill && (target.effects[PBEffects::Minimize] && move.tramplesMinimize?(2)) multipliers[:final_damage_multiplier] *= 2 end - end # Move-specific base damage modifiers # TODO # Move-specific final damage modifiers @@ -572,20 +549,16 @@ class Battle::AI if c >= 0 && user.abilityActive? c = Battle::AbilityEffects.triggerCriticalCalcFromUser(user.ability, user, target, c) end - if skill >= PBTrainerAI.bestSkill - if c >= 0 && !moldBreaker && target.abilityActive? + if skill >= PBTrainerAI.bestSkill && (c >= 0 && !moldBreaker && target.abilityActive?) c = Battle::AbilityEffects.triggerCriticalCalcFromTarget(target.ability, user, target, c) end - end # Item effects that alter critical hit rate if c >= 0 && user.itemActive? c = Battle::ItemEffects.triggerCriticalCalcFromUser(user.item, user, target, c) end - if skill >= PBTrainerAI.bestSkill - if c >= 0 && target.itemActive? + if skill >= PBTrainerAI.bestSkill && (c >= 0 && target.itemActive?) c = Battle::ItemEffects.triggerCriticalCalcFromTarget(target.item, user, target, c) end - end # Other efffects c = -1 if target.pbOwnSide.effects[PBEffects::LuckyChant] > 0 if c >= 0 @@ -659,28 +632,22 @@ class Battle::AI ) end end - if skill >= PBTrainerAI.bestSkill - if target.abilityActive? && !moldBreaker + if skill >= PBTrainerAI.bestSkill && (target.abilityActive? && !moldBreaker) Battle::AbilityEffects.triggerAccuracyCalcFromTarget( target.ability, modifiers, user, target, move, type ) end - end # Item effects that alter accuracy calculation - if skill >= PBTrainerAI.mediumSkill - if user.itemActive? + if skill >= PBTrainerAI.mediumSkill && user.itemActive? Battle::ItemEffects.triggerAccuracyCalcFromUser( user.item, modifiers, user, target, move, type ) end - end - if skill >= PBTrainerAI.bestSkill - if target.itemActive? + if skill >= PBTrainerAI.bestSkill && target.itemActive? Battle::ItemEffects.triggerAccuracyCalcFromTarget( target.item, modifiers, user, target, move, type ) end - end # Other effects, inc. ones that set accuracy_multiplier or evasion_stage to specific values if skill >= PBTrainerAI.mediumSkill if @battle.field.effects[PBEffects::Gravity] > 0 @@ -699,15 +666,15 @@ class Battle::AI user.effects[PBEffects::LockOnPos] == target.index end if skill >= PBTrainerAI.highSkill - if move.function == "BadPoisonTarget" # Toxic - modifiers[:base_accuracy] = 0 if Settings::MORE_TYPE_EFFECTS && move.statusMove? && - user.pbHasType?(:POISON) + if move.function == "BadPoisonTarget" && (Settings::MORE_TYPE_EFFECTS && move.statusMove? && + user.pbHasType?(:POISON)) # Toxic + modifiers[:base_accuracy] = 0 end if ["OHKO", "OHKOIce", "OHKOHitsUndergroundTarget"].include?(move.function) modifiers[:base_accuracy] = move.accuracy + user.level - target.level modifiers[:accuracy_multiplier] = 0 if target.level > user.level - if skill >= PBTrainerAI.bestSkill - modifiers[:accuracy_multiplier] = 0 if target.hasActiveAbility?(:STURDY) + if skill >= PBTrainerAI.bestSkill && target.hasActiveAbility?(:STURDY) + modifiers[:accuracy_multiplier] = 0 end end end diff --git a/Data/Scripts/011_Battle/006_Other battle code/005_Battle_CatchAndStoreMixin.rb b/Data/Scripts/011_Battle/006_Other battle code/005_Battle_CatchAndStoreMixin.rb index 171d181e0..952f31c01 100644 --- a/Data/Scripts/011_Battle/006_Other battle code/005_Battle_CatchAndStoreMixin.rb +++ b/Data/Scripts/011_Battle/006_Other battle code/005_Battle_CatchAndStoreMixin.rb @@ -4,8 +4,9 @@ module Battle::CatchAndStoreMixin #============================================================================= def pbStorePokemon(pkmn) # Nickname the Pokémon (unless it's a Shadow Pokémon) - if !pkmn.shadowPokemon? && $PokemonSystem.givenicknames == 0 - if pbDisplayConfirm(_INTL("Would you like to give a nickname to {1}?", pkmn.name)) + if !pkmn.shadowPokemon? + if $PokemonSystem.givenicknames == 0 && + pbDisplayConfirm(_INTL("Would you like to give a nickname to {1}?", pkmn.name)) nickname = @scene.pbNameEntry(_INTL("{1}'s nickname?", pkmn.speciesName), pkmn) pkmn.name = nickname end @@ -166,7 +167,7 @@ module Battle::CatchAndStoreMixin # Definite capture, no need to perform randomness checks return 4 if x >= 255 || Battle::PokeBallEffects.isUnconditional?(ball, self, battler) # Second half of the shakes calculation - y = (65536 / ((255.0 / x)**0.1875)).floor + y = (65_536 / ((255.0 / x)**0.1875)).floor # Critical capture check if Settings::ENABLE_CRITICAL_CAPTURES dex_modifier = 0 @@ -187,7 +188,7 @@ module Battle::CatchAndStoreMixin # Calculate the number of shakes if c > 0 && pbRandom(256) < c @criticalCapture = true - return 4 if pbRandom(65536) < y + return 4 if pbRandom(65_536) < y return 0 end end @@ -195,7 +196,7 @@ module Battle::CatchAndStoreMixin numShakes = 0 4.times do |i| break if numShakes < i - numShakes += 1 if pbRandom(65536) < y + numShakes += 1 if pbRandom(65_536) < y end return numShakes end diff --git a/Data/Scripts/011_Battle/006_Other battle code/007_BattleAnimationPlayer.rb b/Data/Scripts/011_Battle/006_Other battle code/007_BattleAnimationPlayer.rb index e7485d0a2..bc198ad3b 100644 --- a/Data/Scripts/011_Battle/006_Other battle code/007_BattleAnimationPlayer.rb +++ b/Data/Scripts/011_Battle/006_Other battle code/007_BattleAnimationPlayer.rb @@ -494,7 +494,7 @@ class PBAnimation < Array when 0 # Play SE if i.name && i.name != "" pbSEPlay("Anim/" + i.name, i.volume, i.pitch) - elsif user && user.pokemon + elsif user&.pokemon name = GameData::Species.cry_filename_from_pokemon(user.pokemon) pbSEPlay(name, i.volume, i.pitch) if name end @@ -517,16 +517,16 @@ class PBAnimation < Array bgColor.opacity = i.opacity || 0 end when 2 # Move/recolour background graphic - if bgGraphic.bitmap != nil - oldbg[0] = bgGraphic.ox || 0 - oldbg[1] = bgGraphic.oy || 0 - oldbg[2] = bgGraphic.opacity || 0 - oldbg[3] = bgGraphic.color.clone || Color.new(0, 0, 0, 0) - else + if bgGraphic.bitmap.nil? oldbg[0] = 0 oldbg[1] = 0 oldbg[2] = bgColor.opacity || 0 oldbg[3] = bgColor.color.clone || Color.new(0, 0, 0, 0) + else + oldbg[0] = bgGraphic.ox || 0 + oldbg[1] = bgGraphic.oy || 0 + oldbg[2] = bgGraphic.opacity || 0 + oldbg[3] = bgGraphic.color.clone || Color.new(0, 0, 0, 0) end when 3 # Set foreground graphic (immediate) if i.name && i.name != "" @@ -543,16 +543,16 @@ class PBAnimation < Array foColor.opacity = i.opacity || 0 end when 4 # Move/recolour foreground graphic - if foGraphic.bitmap != nil - oldfo[0] = foGraphic.ox || 0 - oldfo[1] = foGraphic.oy || 0 - oldfo[2] = foGraphic.opacity || 0 - oldfo[3] = foGraphic.color.clone || Color.new(0, 0, 0, 0) - else + if foGraphic.bitmap.nil? oldfo[0] = 0 oldfo[1] = 0 oldfo[2] = foColor.opacity || 0 oldfo[3] = foColor.color.clone || Color.new(0, 0, 0, 0) + else + oldfo[0] = foGraphic.ox || 0 + oldfo[1] = foGraphic.oy || 0 + oldfo[2] = foGraphic.opacity || 0 + oldfo[3] = foGraphic.color.clone || Color.new(0, 0, 0, 0) end end end @@ -562,7 +562,14 @@ class PBAnimation < Array next if !i.duration || i.duration <= 0 next if frame < i.frame || frame > i.frame + i.duration fraction = (frame - i.frame).to_f / i.duration - if bgGraphic.bitmap != nil + if bgGraphic.bitmap.nil? + bgColor.opacity = oldbg[2] + ((i.opacity - oldbg[2]) * fraction) if i.opacity != nil + cr = (i.colorRed != nil) ? oldbg[3].red + ((i.colorRed - oldbg[3].red) * fraction) : oldbg[3].red + cg = (i.colorGreen != nil) ? oldbg[3].green + ((i.colorGreen - oldbg[3].green) * fraction) : oldbg[3].green + cb = (i.colorBlue != nil) ? oldbg[3].blue + ((i.colorBlue - oldbg[3].blue) * fraction) : oldbg[3].blue + ca = (i.colorAlpha != nil) ? oldbg[3].alpha + ((i.colorAlpha - oldbg[3].alpha) * fraction) : oldbg[3].alpha + bgColor.color = Color.new(cr, cg, cb, ca) + else bgGraphic.ox = oldbg[0] - ((i.bgX - oldbg[0]) * fraction) if i.bgX != nil bgGraphic.oy = oldbg[1] - ((i.bgY - oldbg[1]) * fraction) if i.bgY != nil bgGraphic.opacity = oldbg[2] + ((i.opacity - oldbg[2]) * fraction) if i.opacity != nil @@ -571,19 +578,19 @@ class PBAnimation < Array cb = (i.colorBlue != nil) ? oldbg[3].blue + ((i.colorBlue - oldbg[3].blue) * fraction) : oldbg[3].blue ca = (i.colorAlpha != nil) ? oldbg[3].alpha + ((i.colorAlpha - oldbg[3].alpha) * fraction) : oldbg[3].alpha bgGraphic.color = Color.new(cr, cg, cb, ca) - else - bgColor.opacity = oldbg[2] + ((i.opacity - oldbg[2]) * fraction) if i.opacity != nil - cr = (i.colorRed != nil) ? oldbg[3].red + ((i.colorRed - oldbg[3].red) * fraction) : oldbg[3].red - cg = (i.colorGreen != nil) ? oldbg[3].green + ((i.colorGreen - oldbg[3].green) * fraction) : oldbg[3].green - cb = (i.colorBlue != nil) ? oldbg[3].blue + ((i.colorBlue - oldbg[3].blue) * fraction) : oldbg[3].blue - ca = (i.colorAlpha != nil) ? oldbg[3].alpha + ((i.colorAlpha - oldbg[3].alpha) * fraction) : oldbg[3].alpha - bgColor.color = Color.new(cr, cg, cb, ca) end when 4 next if !i.duration || i.duration <= 0 next if frame < i.frame || frame > i.frame + i.duration fraction = (frame - i.frame).to_f / i.duration - if foGraphic.bitmap != nil + if foGraphic.bitmap.nil? + foColor.opacity = oldfo[2] + ((i.opacity - oldfo[2]) * fraction) if i.opacity != nil + cr = (i.colorRed != nil) ? oldfo[3].red + ((i.colorRed - oldfo[3].red) * fraction) : oldfo[3].red + cg = (i.colorGreen != nil) ? oldfo[3].green + ((i.colorGreen - oldfo[3].green) * fraction) : oldfo[3].green + cb = (i.colorBlue != nil) ? oldfo[3].blue + ((i.colorBlue - oldfo[3].blue) * fraction) : oldfo[3].blue + ca = (i.colorAlpha != nil) ? oldfo[3].alpha + ((i.colorAlpha - oldfo[3].alpha) * fraction) : oldfo[3].alpha + foColor.color = Color.new(cr, cg, cb, ca) + else foGraphic.ox = oldfo[0] - ((i.bgX - oldfo[0]) * fraction) if i.bgX != nil foGraphic.oy = oldfo[1] - ((i.bgY - oldfo[1]) * fraction) if i.bgY != nil foGraphic.opacity = oldfo[2] + ((i.opacity - oldfo[2]) * fraction) if i.opacity != nil @@ -592,13 +599,6 @@ class PBAnimation < Array cb = (i.colorBlue != nil) ? oldfo[3].blue + ((i.colorBlue - oldfo[3].blue) * fraction) : oldfo[3].blue ca = (i.colorAlpha != nil) ? oldfo[3].alpha + ((i.colorAlpha - oldfo[3].alpha) * fraction) : oldfo[3].alpha foGraphic.color = Color.new(cr, cg, cb, ca) - else - foColor.opacity = oldfo[2] + ((i.opacity - oldfo[2]) * fraction) if i.opacity != nil - cr = (i.colorRed != nil) ? oldfo[3].red + ((i.colorRed - oldfo[3].red) * fraction) : oldfo[3].red - cg = (i.colorGreen != nil) ? oldfo[3].green + ((i.colorGreen - oldfo[3].green) * fraction) : oldfo[3].green - cb = (i.colorBlue != nil) ? oldfo[3].blue + ((i.colorBlue - oldfo[3].blue) * fraction) : oldfo[3].blue - ca = (i.colorAlpha != nil) ? oldfo[3].alpha + ((i.colorAlpha - oldfo[3].alpha) * fraction) : oldfo[3].alpha - foColor.color = Color.new(cr, cg, cb, ca) end end end @@ -700,10 +700,10 @@ class PBAnimationPlayerX @user = (oppMove) ? target : user # Just used for playing user's cry @usersprite = (user) ? scene.sprites["pokemon_#{user.index}"] : nil @targetsprite = (target) ? scene.sprites["pokemon_#{target.index}"] : nil - @userbitmap = (@usersprite && @usersprite.bitmap) ? @usersprite.bitmap : nil # not to be disposed - @targetbitmap = (@targetsprite && @targetsprite.bitmap) ? @targetsprite.bitmap : nil # not to be disposed + @userbitmap = @usersprite&.bitmap # not to be disposed + @targetbitmap = @targetsprite&.bitmap # not to be disposed @scene = scene - @viewport = (scene) ? scene.viewport : nil + @viewport = scene&.viewport @inEditor = inEditor @looping = false @animbitmap = nil # Animation sheet graphic @@ -761,9 +761,9 @@ class PBAnimationPlayerX end def dispose - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose (2...MAX_SPRITES).each do |i| - @animsprites[i].dispose if @animsprites[i] + @animsprites[i]&.dispose end @bgGraphic.dispose @bgColor.dispose @@ -792,7 +792,7 @@ class PBAnimationPlayerX if animFrame >= @animation.length @frame = (@looping) ? 0 : -1 if @frame < 0 - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose @animbitmap = nil return end diff --git a/Data/Scripts/011_Battle/006_Other battle code/008_Battle_AbilityEffects.rb b/Data/Scripts/011_Battle/006_Other battle code/008_Battle_AbilityEffects.rb index b5a457fbc..11657517a 100644 --- a/Data/Scripts/011_Battle/006_Other battle code/008_Battle_AbilityEffects.rb +++ b/Data/Scripts/011_Battle/006_Other battle code/008_Battle_AbilityEffects.rb @@ -1179,8 +1179,8 @@ Battle::AbilityEffects::AccuracyCalcFromTarget.add(:UNAWARE, Battle::AbilityEffects::AccuracyCalcFromTarget.add(:WONDERSKIN, proc { |ability, mods, user, target, move, type| - if move.statusMove? && user.opposes?(target) - mods[:base_accuracy] = 50 if mods[:base_accuracy] > 50 + if move.statusMove? && user.opposes?(target) && mods[:base_accuracy] > 50 + mods[:base_accuracy] = 50 end } ) diff --git a/Data/Scripts/011_Battle/006_Other battle code/009_Battle_ItemEffects.rb b/Data/Scripts/011_Battle/006_Other battle code/009_Battle_ItemEffects.rb index 8507b1a91..7adad93b1 100644 --- a/Data/Scripts/011_Battle/006_Other battle code/009_Battle_ItemEffects.rb +++ b/Data/Scripts/011_Battle/006_Other battle code/009_Battle_ItemEffects.rb @@ -1421,11 +1421,10 @@ Battle::ItemEffects::OnBeingHit.add(:STICKYBARB, user.item = target.item target.item = nil target.effects[PBEffects::Unburden] = true if target.hasActiveAbility?(:UNBURDEN) - if battle.wildBattle? && !user.opposes? - if !user.initialItem && user.item == target.initialItem - user.setInitialItem(user.item) - target.setInitialItem(nil) - end + if battle.wildBattle? && !user.opposes? && + !user.initialItem && user.item == target.initialItem + user.setInitialItem(user.item) + target.setInitialItem(nil) end battle.pbDisplay(_INTL("{1}'s {2} was transferred to {3}!", target.pbThis, user.itemName, user.pbThis(true))) diff --git a/Data/Scripts/011_Battle/007_Other battle types/001_SafariBattle.rb b/Data/Scripts/011_Battle/007_Other battle types/001_SafariBattle.rb index cb0613d1f..043c4f3d4 100644 --- a/Data/Scripts/011_Battle/007_Other battle types/001_SafariBattle.rb +++ b/Data/Scripts/011_Battle/007_Other battle types/001_SafariBattle.rb @@ -26,7 +26,7 @@ class Battle::FakeBattler def super_shiny?; return @pokemon.super_shiny?; end def isSpecies?(check_species) - return @pokemon && @pokemon.isSpecies?(check_species) + return @pokemon&.isSpecies?(check_species) end def fainted?; return false; end diff --git a/Data/Scripts/011_Battle/007_Other battle types/003_BattlePalaceBattle.rb b/Data/Scripts/011_Battle/007_Other battle types/003_BattlePalaceBattle.rb index 20ca27378..dfd310ed5 100644 --- a/Data/Scripts/011_Battle/007_Other battle types/003_BattlePalaceBattle.rb +++ b/Data/Scripts/011_Battle/007_Other battle types/003_BattlePalaceBattle.rb @@ -87,8 +87,9 @@ class BattlePalaceBattle < Battle return false end # though incorrect, just for convenience (actually checks Torment later) - if thispkmn.effects[PBEffects::Torment] && thispkmn.lastMoveUsed - return false if thismove.id == thispkmn.lastMoveUsed + if thispkmn.effects[PBEffects::Torment] && + thispkmn.lastMoveUsed && thismove.id == thispkmn.lastMoveUsed + return false end return true end diff --git a/Data/Scripts/011_Battle/007_Other battle types/004_BattleArenaBattle.rb b/Data/Scripts/011_Battle/007_Other battle types/004_BattleArenaBattle.rb index 586834b65..82159ff48 100644 --- a/Data/Scripts/011_Battle/007_Other battle types/004_BattleArenaBattle.rb +++ b/Data/Scripts/011_Battle/007_Other battle types/004_BattleArenaBattle.rb @@ -53,9 +53,7 @@ class BattleArenaBattle < Battle end def pbCanSwitchLax?(idxBattler, _idxParty, partyScene = nil) - if partyScene - partyScene.pbDisplay(_INTL("{1} can't be switched out!", @battlers[idxBattler].pbThis)) - end + partyScene&.pbDisplay(_INTL("{1} can't be switched out!", @battlers[idxBattler].pbThis)) return false end @@ -366,8 +364,8 @@ class Battle::Scene ensure pbDisposeMessageWindow(msgwindow) dimmingvp.dispose - infowindow.contents.dispose if infowindow && infowindow.contents - infowindow.dispose if infowindow + infowindow&.contents&.dispose + infowindow&.dispose end end end diff --git a/Data/Scripts/012_Overworld/001_Overworld visuals/001_Overworld_Weather.rb b/Data/Scripts/012_Overworld/001_Overworld visuals/001_Overworld_Weather.rb index 13c85bb50..ec8f335c7 100644 --- a/Data/Scripts/012_Overworld/001_Overworld visuals/001_Overworld_Weather.rb +++ b/Data/Scripts/012_Overworld/001_Overworld visuals/001_Overworld_Weather.rb @@ -50,14 +50,14 @@ module RPG end def dispose - @sprites.each { |sprite| sprite.dispose if sprite } - @new_sprites.each { |sprite| sprite.dispose if sprite } - @tiles.each { |sprite| sprite.dispose if sprite } + @sprites.each { |sprite| sprite&.dispose } + @new_sprites.each { |sprite| sprite&.dispose } + @tiles.each { |sprite| sprite&.dispose } @viewport.dispose @weatherTypes.each_value do |weather| next if !weather - weather[1].each { |bitmap| bitmap.dispose if bitmap } - weather[2].each { |bitmap| bitmap.dispose if bitmap } + weather[1].each { |bitmap| bitmap&.dispose } + weather[2].each { |bitmap| bitmap&.dispose } end end @@ -83,7 +83,7 @@ module RPG @time_shift += 1 # No previous tiles to fade out first end @fading = true - @new_sprites.each { |sprite| sprite.dispose if sprite } + @new_sprites.each { |sprite| sprite&.dispose } @new_sprites.clear ensureSprites @new_sprites.each_with_index { |sprite, i| set_sprite_bitmap(sprite, i, @target_type) } @@ -456,25 +456,24 @@ module RPG @new_sprites.each_with_index { |sprite, i| sprite.visible = (i < @new_max) if sprite } end # End fading - if @fade_time >= ((@target_type == :None) ? FADE_OLD_PARTICLES_END : FADE_NEW_TILES_END) - @time_shift - if !@sprites.any? { |sprite| sprite.visible } - @type = @target_type - @max = @target_max - @target_type = nil - @target_max = nil - @old_max = nil - @new_max = nil - @old_tone = nil - @target_tone = nil - @fade_time = 0.0 - @time_shift = 0 - @sprites.each { |sprite| sprite.dispose if sprite } - @sprites = @new_sprites - @new_sprites = [] - @sprite_lifetimes = @new_sprite_lifetimes - @new_sprite_lifetimes = [] - @fading = false - end + if @fade_time >= ((@target_type == :None) ? FADE_OLD_PARTICLES_END : FADE_NEW_TILES_END) - @time_shift && + !@sprites.any? { |sprite| sprite.visible } + @type = @target_type + @max = @target_max + @target_type = nil + @target_max = nil + @old_max = nil + @new_max = nil + @old_tone = nil + @target_tone = nil + @fade_time = 0.0 + @time_shift = 0 + @sprites.each { |sprite| sprite&.dispose } + @sprites = @new_sprites + @new_sprites = [] + @sprite_lifetimes = @new_sprite_lifetimes + @new_sprite_lifetimes = [] + @fading = false end end @@ -501,7 +500,7 @@ module RPG update_sprite_position(@sprites[i], i, false) end elsif @sprites.length > 0 - @sprites.each { |sprite| sprite.dispose if sprite } + @sprites.each { |sprite| sprite&.dispose } @sprites.clear end # Update new weather particles (while fading in only) @@ -511,7 +510,7 @@ module RPG update_sprite_position(@new_sprites[i], i, true) end elsif @new_sprites.length > 0 - @new_sprites.each { |sprite| sprite.dispose if sprite } + @new_sprites.each { |sprite| sprite&.dispose } @new_sprites.clear end # Update weather tiles (sandstorm/blizzard tiled overlay) @@ -520,7 +519,7 @@ module RPG recalculate_tile_positions @tiles.each_with_index { |sprite, i| update_tile_position(sprite, i) } elsif @tiles.length > 0 - @tiles.each { |sprite| sprite.dispose if sprite } + @tiles.each { |sprite| sprite&.dispose } @tiles.clear end end diff --git a/Data/Scripts/012_Overworld/001_Overworld.rb b/Data/Scripts/012_Overworld/001_Overworld.rb index c6052e9f5..552746f98 100644 --- a/Data/Scripts/012_Overworld/001_Overworld.rb +++ b/Data/Scripts/012_Overworld/001_Overworld.rb @@ -47,23 +47,18 @@ def pbBatteryLow? end Events.onMapUpdate += proc { |_sender, _e| - if !$game_temp.warned_low_battery && pbBatteryLow? - if !$game_temp.in_menu && !$game_temp.in_battle && - !$game_player.move_route_forcing && !$game_temp.message_window_showing && - !pbMapInterpreterRunning? - if pbGetTimeNow.sec == 0 - pbMessage(_INTL("The game has detected that the battery is low. You should save soon to avoid losing your progress.")) - $game_temp.warned_low_battery = true - end - end + if !$game_temp.warned_low_battery && pbBatteryLow? && + !$game_temp.in_menu && !$game_temp.in_battle && !$game_player.move_route_forcing && + !$game_temp.message_window_showing && !pbMapInterpreterRunning? && + pbGetTimeNow.sec == 0 + pbMessage(_INTL("The game has detected that the battery is low. You should save soon to avoid losing your progress.")) + $game_temp.warned_low_battery = true end if $game_temp.cue_bgm_frame_delay $game_temp.cue_bgm_frame_delay -= 1 if $game_temp.cue_bgm_frame_delay <= 0 $game_temp.cue_bgm_frame_delay = nil - if $game_system.getPlayingBGM == nil - pbBGMPlay($game_temp.cue_bgm) - end + pbBGMPlay($game_temp.cue_bgm) if $game_system.getPlayingBGM.nil? end end } @@ -133,7 +128,7 @@ Events.onStepTakenFieldMovement += proc { |_sender, e| map = $map_factory.getMap(thistile[0]) [2, 1, 0].each do |i| tile_id = map.data[thistile[1], thistile[2], i] - next if tile_id == nil + next if tile_id.nil? next if GameData::TerrainTag.try_get(map.terrain_tags[tile_id]).id != :SootGrass if event == $game_player && $bag.has?(:SOOTSACK) old_soot = $player.soot @@ -229,7 +224,7 @@ Events.onMapChanging += proc { |_sender, e| map_infos = pbLoadMapInfos if $game_map.name == map_infos[new_map_ID].name new_map_metadata = GameData::MapMetadata.try_get(new_map_ID) - next if new_map_metadata && new_map_metadata.weather + next if new_map_metadata&.weather end $game_screen.weather(:None, 0, 0) } @@ -238,18 +233,18 @@ Events.onMapChanging += proc { |_sender, e| Events.onMapChange += proc { |_sender, e| old_map_ID = e[0] # previous map ID, is 0 if no map ID new_map_metadata = $game_map.metadata - if new_map_metadata && new_map_metadata.teleport_destination + if new_map_metadata&.teleport_destination $PokemonGlobal.healingSpot = new_map_metadata.teleport_destination end - $PokemonMap.clear if $PokemonMap - $PokemonEncounters.setup($game_map.map_id) if $PokemonEncounters + $PokemonMap&.clear + $PokemonEncounters&.setup($game_map.map_id) $PokemonGlobal.visitedMaps[$game_map.map_id] = true next if old_map_ID == 0 || old_map_ID == $game_map.map_id next if !new_map_metadata || !new_map_metadata.weather map_infos = pbLoadMapInfos if $game_map.name == map_infos[old_map_ID].name old_map_metadata = GameData::MapMetadata.try_get(old_map_ID) - next if old_map_metadata && old_map_metadata.weather + next if old_map_metadata&.weather end new_weather = new_map_metadata.weather $game_screen.weather(new_weather[0], 9, 0) if rand(100) < new_weather[1] @@ -262,14 +257,14 @@ Events.onMapSceneChange += proc { |_sender, e| # Update map trail if $game_map $PokemonGlobal.mapTrail = [] if !$PokemonGlobal.mapTrail - if $PokemonGlobal.mapTrail[0] != $game_map.map_id - $PokemonGlobal.mapTrail.pop if $PokemonGlobal.mapTrail.length >= 4 + if $PokemonGlobal.mapTrail[0] != $game_map.map_id && $PokemonGlobal.mapTrail.length >= 4 + $PokemonGlobal.mapTrail.pop end $PokemonGlobal.mapTrail = [$game_map.map_id] + $PokemonGlobal.mapTrail end # Display darkness circle on dark maps map_metadata = $game_map.metadata - if map_metadata && map_metadata.dark_map + if map_metadata&.dark_map $game_temp.darkness_sprite = DarknessSprite.new scene.spriteset.addUserSprite($game_temp.darkness_sprite) if $PokemonGlobal.flashUsed @@ -277,7 +272,7 @@ Events.onMapSceneChange += proc { |_sender, e| end else $PokemonGlobal.flashUsed = false - $game_temp.darkness_sprite.dispose if $game_temp.darkness_sprite + $game_temp.darkness_sprite&.dispose $game_temp.darkness_sprite = nil end # Show location signpost @@ -298,7 +293,7 @@ Events.onMapSceneChange += proc { |_sender, e| scene.spriteset.addUserSprite(LocationWindow.new($game_map.name)) if !nosignpost end # Force cycling/walking - if map_metadata && map_metadata.always_bicycle + if map_metadata&.always_bicycle pbMountBike elsif !pbCanUseBike?($game_map.map_id) pbDismountBike @@ -517,9 +512,7 @@ def pbMoveRoute(event, commands, waitComplete = false) end route.list.push(RPG::MoveCommand.new(PBMoveRoute::ThroughOff)) route.list.push(RPG::MoveCommand.new(0)) - if event - event.force_move_route(route) - end + event&.force_move_route(route) return route end @@ -610,7 +603,7 @@ def pbMoveTowardPlayer(event) pbUpdateSceneMap end end - $PokemonMap.addMovedEvent(event.id) if $PokemonMap + $PokemonMap&.addMovedEvent(event.id) end def pbJumpToward(dist = 1, playSound = false, cancelSurf = false) diff --git a/Data/Scripts/012_Overworld/002_Battle triggering/001_Overworld_BattleStarting.rb b/Data/Scripts/012_Overworld/002_Battle triggering/001_Overworld_BattleStarting.rb index 0a2edfe29..546ae1178 100644 --- a/Data/Scripts/012_Overworld/002_Battle triggering/001_Overworld_BattleStarting.rb +++ b/Data/Scripts/012_Overworld/002_Battle triggering/001_Overworld_BattleStarting.rb @@ -573,11 +573,9 @@ def pbAfterBattle(decision, canLose) pkmn.makeUnprimal end end - if [2, 5].include?(decision) # if loss or draw - if canLose - $player.party.each { |pkmn| pkmn.heal } - (Graphics.frame_rate / 4).times { Graphics.update } - end + if [2, 5].include?(decision) && canLose # if loss or draw + $player.party.each { |pkmn| pkmn.heal } + (Graphics.frame_rate / 4).times { Graphics.update } end Events.onEndBattle.trigger(nil, decision, canLose) $game_player.straighten diff --git a/Data/Scripts/012_Overworld/002_Battle triggering/002_Overworld_BattleIntroAnim.rb b/Data/Scripts/012_Overworld/002_Battle triggering/002_Overworld_BattleIntroAnim.rb index 5f443f843..aa07eadc8 100644 --- a/Data/Scripts/012_Overworld/002_Battle triggering/002_Overworld_BattleIntroAnim.rb +++ b/Data/Scripts/012_Overworld/002_Battle triggering/002_Overworld_BattleIntroAnim.rb @@ -32,11 +32,11 @@ end # Battle intro animation #=============================================================================== def pbSceneStandby - $scene.disposeSpritesets if $scene && $scene.is_a?(Scene_Map) + $scene.disposeSpritesets if $scene.is_a?(Scene_Map) RPG::Cache.clear Graphics.frame_reset yield - $scene.createSpritesets if $scene && $scene.is_a?(Scene_Map) + $scene.createSpritesets if $scene.is_a?(Scene_Map) end def pbBattleAnimation(bgm = nil, battletype = 0, foe = nil) @@ -46,7 +46,7 @@ def pbBattleAnimation(bgm = nil, battletype = 0, foe = nil) # Set up audio playingBGS = nil playingBGM = nil - if $game_system && $game_system.is_a?(Game_System) + if $game_system.is_a?(Game_System) playingBGS = $game_system.getPlayingBGS playingBGM = $game_system.getPlayingBGM $game_system.bgm_pause @@ -120,7 +120,7 @@ def pbBattleAnimation(bgm = nil, battletype = 0, foe = nil) end end # Take screenshot of game, for use in some animations - $game_temp.background_bitmap.dispose if $game_temp.background_bitmap + $game_temp.background_bitmap&.dispose $game_temp.background_bitmap = Graphics.snap_to_bitmap # Play main animation Graphics.freeze @@ -138,7 +138,7 @@ def pbBattleAnimation(bgm = nil, battletype = 0, foe = nil) yield if block_given? # After the battle pbPopFade - if $game_system && $game_system.is_a?(Game_System) + if $game_system.is_a?(Game_System) $game_system.bgm_resume(playingBGM) $game_system.bgs_resume(playingBGS) end diff --git a/Data/Scripts/012_Overworld/002_Battle triggering/003_Overworld_WildEncounters.rb b/Data/Scripts/012_Overworld/002_Battle triggering/003_Overworld_WildEncounters.rb index d70a0969d..02ce86a2e 100644 --- a/Data/Scripts/012_Overworld/002_Battle triggering/003_Overworld_WildEncounters.rb +++ b/Data/Scripts/012_Overworld/002_Battle triggering/003_Overworld_WildEncounters.rb @@ -281,25 +281,21 @@ class PokemonEncounters favored_type = nil case first_pkmn.ability_id when :FLASHFIRE - if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS - favored_type = :FIRE if GameData::Type.exists?(:FIRE) && rand(100) < 50 - end + favored_type = :FIRE if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS && + GameData::Type.exists?(:FIRE) && rand(100) < 50 when :HARVEST - if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS - favored_type = :GRASS if GameData::Type.exists?(:GRASS) && rand(100) < 50 - end + favored_type = :GRASS if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS && + GameData::Type.exists?(:GRASS) && rand(100) < 50 when :LIGHTNINGROD - if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS - favored_type = :ELECTRIC if GameData::Type.exists?(:ELECTRIC) && rand(100) < 50 - end + favored_type = :ELECTRIC if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS && + GameData::Type.exists?(:ELECTRIC) && rand(100) < 50 when :MAGNETPULL favored_type = :STEEL if GameData::Type.exists?(:STEEL) && rand(100) < 50 when :STATIC favored_type = :ELECTRIC if GameData::Type.exists?(:ELECTRIC) && rand(100) < 50 when :STORMDRAIN - if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS - favored_type = :WATER if GameData::Type.exists?(:WATER) && rand(100) < 50 - end + favored_type = :WATER if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS && + GameData::Type.exists?(:WATER) && rand(100) < 50 end if favored_type new_enc_list = [] @@ -433,7 +429,7 @@ def pbGenerateWildPokemon(species, level, isRoamer = false) end end # Give Pokérus - genwildpoke.givePokerus if rand(65536) < Settings::POKERUS_CHANCE + genwildpoke.givePokerus if rand(65_536) < Settings::POKERUS_CHANCE # Change wild Pokémon's gender/nature depending on the lead party Pokémon's # ability if first_pkmn diff --git a/Data/Scripts/012_Overworld/002_Overworld_Metadata.rb b/Data/Scripts/012_Overworld/002_Overworld_Metadata.rb index dc5600cfd..e1b4c1b49 100644 --- a/Data/Scripts/012_Overworld/002_Overworld_Metadata.rb +++ b/Data/Scripts/012_Overworld/002_Overworld_Metadata.rb @@ -156,7 +156,7 @@ class PokemonMapMetadata @erasedEvents.each do |i| if i[0][0] == $game_map.map_id && i[1] event = $game_map.events[i[0][1]] - event.erase if event + event&.erase end end @movedEvents.each do |i| diff --git a/Data/Scripts/012_Overworld/003_Overworld_Time.rb b/Data/Scripts/012_Overworld/003_Overworld_Time.rb index ab8e1926b..f5f0ead24 100644 --- a/Data/Scripts/012_Overworld/003_Overworld_Time.rb +++ b/Data/Scripts/012_Overworld/003_Overworld_Time.rb @@ -149,9 +149,9 @@ def moonphase(time = nil) # in UTC ] yy = time.year - ((12 - time.mon) / 10.0).floor j = (365.25 * (4712 + yy)).floor + ((((time.mon + 9) % 12) * 30.6) + 0.5).floor + time.day + 59 - j -= (((yy / 100.0) + 49).floor * 0.75).floor - 38 if j > 2299160 - j += (((time.hour * 60) + (time.min * 60)) + time.sec) / 86400.0 - v = (j - 2451550.1) / 29.530588853 + j -= (((yy / 100.0) + 49).floor * 0.75).floor - 38 if j > 2_299_160 + j += (((time.hour * 60) + (time.min * 60)) + time.sec) / 86_400.0 + v = (j - 2_451_550.1) / 29.530588853 v = ((v - v.floor) + (v < 0 ? 1 : 0)) ag = v * 29.53 transitions.length.times do |i| diff --git a/Data/Scripts/012_Overworld/004_Overworld_FieldMoves.rb b/Data/Scripts/012_Overworld/004_Overworld_FieldMoves.rb index f7339b0de..4cea205a2 100644 --- a/Data/Scripts/012_Overworld/004_Overworld_FieldMoves.rb +++ b/Data/Scripts/012_Overworld/004_Overworld_FieldMoves.rb @@ -245,7 +245,7 @@ def pbSmashEvent(event) PBMoveRoute::Wait, 2]) pbWait(Graphics.frame_rate * 4 / 10) event.erase - $PokemonMap.addErasedEvent(event.id) if $PokemonMap + $PokemonMap&.addErasedEvent(event.id) end diff --git a/Data/Scripts/012_Overworld/006_Overworld_BerryPlants.rb b/Data/Scripts/012_Overworld/006_Overworld_BerryPlants.rb index 6b2b010b0..ab6ebb39c 100644 --- a/Data/Scripts/012_Overworld/006_Overworld_BerryPlants.rb +++ b/Data/Scripts/012_Overworld/006_Overworld_BerryPlants.rb @@ -152,7 +152,7 @@ class BerryPlantData end end else - old_growth_stage = (done_replant) ? 0 : old_growth_stage + old_growth_stage = 0 if done_replant new_growth_stage = [@growth_stage, stages_growing + 1].min @watered_this_stage = false if new_growth_stage > old_growth_stage water if $game_screen && GameData::Weather.get($game_screen.weather_type).category == :Rain @@ -268,8 +268,8 @@ class BerryPlantSprite if berry_plant.new_mechanics && @old_stage != berry_plant.growth_stage && @old_stage > 0 && berry_plant.growth_stage <= GameData::BerryPlant::NUMBER_OF_GROWTH_STAGES + 1 spriteset = $scene.spriteset(@map.map_id) - spriteset.addUserAnimation(Settings::PLANT_SPARKLE_ANIMATION_ID, - @event.x, @event.y, false, 1) if spriteset + spriteset&.addUserAnimation(Settings::PLANT_SPARKLE_ANIMATION_ID, + @event.x, @event.y, false, 1) end end @old_stage = berry_plant.growth_stage diff --git a/Data/Scripts/012_Overworld/007_Overworld_DayCare.rb b/Data/Scripts/012_Overworld/007_Overworld_DayCare.rb index 760502c83..5588918a3 100644 --- a/Data/Scripts/012_Overworld/007_Overworld_DayCare.rb +++ b/Data/Scripts/012_Overworld/007_Overworld_DayCare.rb @@ -119,11 +119,10 @@ class DayCare end end # Learn Volt Tackle if a parent has a Light Ball and is in the Pichu family - if egg.species == :PICHU && GameData::Move.exists?(:VOLTTACKLE) - if (father[2] && father[0].hasItem?(:LIGHTBALL)) || - (mother[2] && mother[0].hasItem?(:LIGHTBALL)) - moves.push(:VOLTTACKLE) - end + if egg.species == :PICHU && GameData::Move.exists?(:VOLTTACKLE) && + ((father[2] && father[0].hasItem?(:LIGHTBALL)) || + (mother[2] && mother[0].hasItem?(:LIGHTBALL))) + moves.push(:VOLTTACKLE) end return moves end @@ -249,7 +248,7 @@ class DayCare end def set_pokerus(egg) - egg.givePokerus if rand(65536) < Settings::POKERUS_CHANCE + egg.givePokerus if rand(65_536) < Settings::POKERUS_CHANCE end end @@ -370,11 +369,11 @@ class DayCare pkmn2.moves.each { |m| known_moves2.push(m.id) if egg_moves1.include?(m.id) && !pkmn1.hasMove?(m.id) } end if !known_moves1.empty? - if !known_moves2.empty? + if known_moves2.empty? + pkmn2.learn_move(known_moves1[0]) + else learner = [[pkmn1, known_moves2[0]], [pkmn2, known_moves1[0]]].sample learner[0].learn_move(learner[1]) - else - pkmn2.learn_move(known_moves1[0]) end elsif !known_moves2.empty? pkmn1.learn_move(known_moves2[0]) diff --git a/Data/Scripts/012_Overworld/008_Overworld_RandomDungeons.rb b/Data/Scripts/012_Overworld/008_Overworld_RandomDungeons.rb index 75030772b..ef71d4860 100644 --- a/Data/Scripts/012_Overworld/008_Overworld_RandomDungeons.rb +++ b/Data/Scripts/012_Overworld/008_Overworld_RandomDungeons.rb @@ -412,11 +412,9 @@ module RandomDungeonGenerator when EdgeMasks::WEST cx -= 1 end - if cx >= 0 && cy >= 0 && cx < cellWidth && cy < cellHeight - if !getVisited(cx, cy) - clearEdgeNode(x, y, d) - recurseDepthFirst(cx, cy, depth + 1) - end + if cx >= 0 && cy >= 0 && cx < cellWidth && cy < cellHeight && !getVisited(cx, cy) + clearEdgeNode(x, y, d) + recurseDepthFirst(cx, cy, depth + 1) end end end diff --git a/Data/Scripts/013_Items/001_Item_Utilities.rb b/Data/Scripts/013_Items/001_Item_Utilities.rb index 6eec6c23d..07ffb79ba 100644 --- a/Data/Scripts/013_Items/001_Item_Utilities.rb +++ b/Data/Scripts/013_Items/001_Item_Utilities.rb @@ -212,7 +212,7 @@ def pbTopRightWindow(text, scene = nil) Graphics.update Input.update window.update - scene.pbUpdate if scene + scene&.pbUpdate break if Input.trigger?(Input::USE) end window.dispose @@ -702,7 +702,7 @@ def pbUseItem(bag, item, bagscene = nil) end end screen.pbEndScene - bagscene.pbRefresh if bagscene + bagscene&.pbRefresh } return (ret) ? 1 : 0 elsif useType == 2 # Item is usable from Bag @@ -845,12 +845,12 @@ def pbTakeItemFromPokemon(pkmn, scene) scene.pbDisplay(_INTL("The Bag is full. The Pokémon's item could not be removed.")) elsif pkmn.mail if scene.pbConfirm(_INTL("Save the removed mail in your PC?")) - if !pbMoveToMailbox(pkmn) - scene.pbDisplay(_INTL("Your PC's Mailbox is full.")) - else + if pbMoveToMailbox(pkmn) scene.pbDisplay(_INTL("The mail was saved in your PC.")) pkmn.item = nil ret = true + else + scene.pbDisplay(_INTL("Your PC's Mailbox is full.")) end elsif scene.pbConfirm(_INTL("If the mail is removed, its message will be lost. OK?")) $bag.add(pkmn.item) diff --git a/Data/Scripts/013_Items/002_Item_Effects.rb b/Data/Scripts/013_Items/002_Item_Effects.rb index 55d0ed95d..0d70f927a 100644 --- a/Data/Scripts/013_Items/002_Item_Effects.rb +++ b/Data/Scripts/013_Items/002_Item_Effects.rb @@ -281,9 +281,7 @@ ItemHandlers::UseInField.add(:SUPERROD, proc { |item| ItemHandlers::UseInField.add(:ITEMFINDER, proc { |item| $stats.itemfinder_count += 1 event = pbClosestHiddenItem - if !event - pbMessage(_INTL("... \\wt[10]... \\wt[10]... \\wt[10]...\\wt[10]Nope! There's no response.")) - else + if event offsetX = event.x - $game_player.x offsetY = event.y - $game_player.y if offsetX == 0 && offsetY == 0 # Standing on the item, spin around @@ -310,6 +308,8 @@ ItemHandlers::UseInField.add(:ITEMFINDER, proc { |item| pbMessage(_INTL("Huh? The {1}'s responding!\1", GameData::Item.get(item).name)) pbMessage(_INTL("There's an item buried around here!")) end + else + pbMessage(_INTL("... \\wt[10]... \\wt[10]... \\wt[10]...\\wt[10]Nope! There's no response.")) end next true }) diff --git a/Data/Scripts/013_Items/003_Item_BattleEffects.rb b/Data/Scripts/013_Items/003_Item_BattleEffects.rb index b885a0d00..d9066a1b3 100644 --- a/Data/Scripts/013_Items/003_Item_BattleEffects.rb +++ b/Data/Scripts/013_Items/003_Item_BattleEffects.rb @@ -79,7 +79,7 @@ ItemHandlers::CanUseInBattle.add(:AWAKENING, proc { |item, pokemon, battler, mov ItemHandlers::CanUseInBattle.copy(:AWAKENING, :CHESTOBERRY) ItemHandlers::CanUseInBattle.add(:BLUEFLUTE, proc { |item, pokemon, battler, move, firstAction, battle, scene, showMessages| - if battler && battler.hasActiveAbility?(:SOUNDPROOF) + if battler&.hasActiveAbility?(:SOUNDPROOF) scene.pbDisplay(_INTL("It won't have any effect.")) if showMessages next false end @@ -365,7 +365,7 @@ ItemHandlers::BattleUseOnPokemon.add(:SITRUSBERRY, proc { |item, pokemon, battle ItemHandlers::BattleUseOnPokemon.add(:AWAKENING, proc { |item, pokemon, battler, choices, scene| pokemon.heal_status - battler.pbCureStatus(false) if battler + battler&.pbCureStatus(false) name = (battler) ? battler.pbThis : pokemon.name scene.pbRefresh scene.pbDisplay(_INTL("{1} woke up.", name)) @@ -375,7 +375,7 @@ ItemHandlers::BattleUseOnPokemon.copy(:AWAKENING, :CHESTOBERRY, :BLUEFLUTE) ItemHandlers::BattleUseOnPokemon.add(:ANTIDOTE, proc { |item, pokemon, battler, choices, scene| pokemon.heal_status - battler.pbCureStatus(false) if battler + battler&.pbCureStatus(false) name = (battler) ? battler.pbThis : pokemon.name scene.pbRefresh scene.pbDisplay(_INTL("{1} was cured of its poisoning.", name)) @@ -385,7 +385,7 @@ ItemHandlers::BattleUseOnPokemon.copy(:ANTIDOTE, :PECHABERRY) ItemHandlers::BattleUseOnPokemon.add(:BURNHEAL, proc { |item, pokemon, battler, choices, scene| pokemon.heal_status - battler.pbCureStatus(false) if battler + battler&.pbCureStatus(false) name = (battler) ? battler.pbThis : pokemon.name scene.pbRefresh scene.pbDisplay(_INTL("{1}'s burn was healed.", name)) @@ -395,7 +395,7 @@ ItemHandlers::BattleUseOnPokemon.copy(:BURNHEAL, :RAWSTBERRY) ItemHandlers::BattleUseOnPokemon.add(:PARALYZEHEAL, proc { |item, pokemon, battler, choices, scene| pokemon.heal_status - battler.pbCureStatus(false) if battler + battler&.pbCureStatus(false) name = (battler) ? battler.pbThis : pokemon.name scene.pbRefresh scene.pbDisplay(_INTL("{1} was cured of paralysis.", name)) @@ -405,7 +405,7 @@ ItemHandlers::BattleUseOnPokemon.copy(:PARALYZEHEAL, :PARLYZHEAL, :CHERIBERRY) ItemHandlers::BattleUseOnPokemon.add(:ICEHEAL, proc { |item, pokemon, battler, choices, scene| pokemon.heal_status - battler.pbCureStatus(false) if battler + battler&.pbCureStatus(false) name = (battler) ? battler.pbThis : pokemon.name scene.pbRefresh scene.pbDisplay(_INTL("{1} was thawed out.", name)) @@ -415,8 +415,8 @@ ItemHandlers::BattleUseOnPokemon.copy(:ICEHEAL, :ASPEARBERRY) ItemHandlers::BattleUseOnPokemon.add(:FULLHEAL, proc { |item, pokemon, battler, choices, scene| pokemon.heal_status - battler.pbCureStatus(false) if battler - battler.pbCureConfusion if battler + battler&.pbCureStatus(false) + battler&.pbCureConfusion name = (battler) ? battler.pbThis : pokemon.name scene.pbRefresh scene.pbDisplay(_INTL("{1} became healthy.", name)) @@ -429,8 +429,8 @@ ItemHandlers::BattleUseOnPokemon.copy(:FULLHEAL, :RAGECANDYBAR) if Settings::RAG ItemHandlers::BattleUseOnPokemon.add(:FULLRESTORE, proc { |item, pokemon, battler, choices, scene| pokemon.heal_status - battler.pbCureStatus(false) if battler - battler.pbCureConfusion if battler + battler&.pbCureStatus(false) + battler&.pbCureConfusion name = (battler) ? battler.pbThis : pokemon.name if pokemon.hp < pokemon.totalhp pbBattleHPItem(pokemon, battler, pokemon.totalhp, scene) @@ -471,8 +471,8 @@ ItemHandlers::BattleUseOnPokemon.add(:ENERGYROOT, proc { |item, pokemon, battler ItemHandlers::BattleUseOnPokemon.add(:HEALPOWDER, proc { |item, pokemon, battler, choices, scene| pokemon.heal_status - battler.pbCureStatus(false) if battler - battler.pbCureConfusion if battler + battler&.pbCureStatus(false) + battler&.pbCureConfusion pokemon.changeHappiness("powder") name = (battler) ? battler.pbThis : pokemon.name scene.pbRefresh diff --git a/Data/Scripts/013_Items/005_Item_PokeRadar.rb b/Data/Scripts/013_Items/005_Item_PokeRadar.rb index 5e6f84e18..0cb9fc353 100644 --- a/Data/Scripts/013_Items/005_Item_PokeRadar.rb +++ b/Data/Scripts/013_Items/005_Item_PokeRadar.rb @@ -81,9 +81,9 @@ def pbPokeRadarHighlightGrass(showmessage = true) # Choose a rarity for the grass (0=normal, 1=rare, 2=shiny) s = (rand(100) < 25) ? 1 : 0 if $game_temp.poke_radar_data && $game_temp.poke_radar_data[2] > 0 - v = [(65536 / Settings::SHINY_POKEMON_CHANCE) - ([$game_temp.poke_radar_data[2], 40].min * 200), 200].max - v = (65536 / v.to_f).ceil - s = 2 if rand(65536) < v + v = [(65_536 / Settings::SHINY_POKEMON_CHANCE) - ([$game_temp.poke_radar_data[2], 40].min * 200), 200].max + v = (65_536 / v.to_f).ceil + s = 2 if rand(65_536) < v end grasses.push([x, y, i, s]) end diff --git a/Data/Scripts/013_Items/007_Item_Sprites.rb b/Data/Scripts/013_Items/007_Item_Sprites.rb index b38456b84..214d07865 100644 --- a/Data/Scripts/013_Items/007_Item_Sprites.rb +++ b/Data/Scripts/013_Items/007_Item_Sprites.rb @@ -22,7 +22,7 @@ class ItemIconSprite < SpriteWrapper end def dispose - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose super end @@ -70,7 +70,7 @@ class ItemIconSprite < SpriteWrapper def item=(value) return if @item == value && !@forceitemchange @item = value - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose @animbitmap = nil if @item || !@blankzero @animbitmap = AnimatedBitmap.new(GameData::Item.icon_filename(@item)) @@ -126,7 +126,7 @@ class HeldItemIconSprite < SpriteWrapper end def dispose - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose super end @@ -138,7 +138,7 @@ class HeldItemIconSprite < SpriteWrapper def item=(value) return if @item == value @item = value - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose @animbitmap = nil if @item @animbitmap = AnimatedBitmap.new(GameData::Item.held_icon_filename(@item)) diff --git a/Data/Scripts/014_Pokemon/001_Pokemon-related/001_FormHandlers.rb b/Data/Scripts/014_Pokemon/001_Pokemon-related/001_FormHandlers.rb index 4bc96b00b..936b7c5d4 100644 --- a/Data/Scripts/014_Pokemon/001_Pokemon-related/001_FormHandlers.rb +++ b/Data/Scripts/014_Pokemon/001_Pokemon-related/001_FormHandlers.rb @@ -334,11 +334,11 @@ MultipleForms.register(:KYUREM, { case form when 0 # Normal pkmn.moves.each do |move| - if [:ICEBURN, :FREEZESHOCK].include?(move.id) - move.id = :GLACIATE if GameData::Move.exists?(:GLACIATE) + if [:ICEBURN, :FREEZESHOCK].include?(move.id) && GameData::Move.exists?(:GLACIATE) + move.id = :GLACIATE end - if [:FUSIONFLARE, :FUSIONBOLT].include?(move.id) - move.id = :SCARYFACE if GameData::Move.exists?(:SCARYFACE) + if [:FUSIONFLARE, :FUSIONBOLT].include?(move.id) && GameData::Move.exists?(:SCARYFACE) + move.id = :SCARYFACE end end when 1 # White diff --git a/Data/Scripts/014_Pokemon/001_Pokemon-related/002_ShadowPokemon_Other.rb b/Data/Scripts/014_Pokemon/001_Pokemon-related/002_ShadowPokemon_Other.rb index 2d4486fb2..0f49bc970 100644 --- a/Data/Scripts/014_Pokemon/001_Pokemon-related/002_ShadowPokemon_Other.rb +++ b/Data/Scripts/014_Pokemon/001_Pokemon-related/002_ShadowPokemon_Other.rb @@ -50,12 +50,11 @@ def pbPurify(pkmn, scene) pkmn.exp = newexp end end - if $PokemonSystem.givenicknames == 0 - if scene.pbConfirm(_INTL("Would you like to give a nickname to {1}?", pkmn.speciesName)) - newname = pbEnterPokemonName(_INTL("{1}'s nickname?", pkmn.speciesName), - 0, Pokemon::MAX_NAME_SIZE, "", pkmn) - pkmn.name = newname - end + if $PokemonSystem.givenicknames == 0 && + scene.pbConfirm(_INTL("Would you like to give a nickname to {1}?", pkmn.speciesName)) + newname = pbEnterPokemonName(_INTL("{1}'s nickname?", pkmn.speciesName), + 0, Pokemon::MAX_NAME_SIZE, "", pkmn) + pkmn.name = newname end end @@ -201,13 +200,13 @@ class Battle::Battler def shadowPokemon? p = self.pokemon - return p && p.shadowPokemon? + return p&.shadowPokemon? end def inHyperMode? return false if fainted? p = self.pokemon - return p && p.hyper_mode + return p&.hyper_mode end def pbHyperMode diff --git a/Data/Scripts/014_Pokemon/001_Pokemon-related/003_Pokemon_Sprites.rb b/Data/Scripts/014_Pokemon/001_Pokemon-related/003_Pokemon_Sprites.rb index e07405506..45ebe66d3 100644 --- a/Data/Scripts/014_Pokemon/001_Pokemon-related/003_Pokemon_Sprites.rb +++ b/Data/Scripts/014_Pokemon/001_Pokemon-related/003_Pokemon_Sprites.rb @@ -8,14 +8,14 @@ class PokemonSprite < SpriteWrapper end def dispose - @_iconbitmap.dispose if @_iconbitmap + @_iconbitmap&.dispose @_iconbitmap = nil self.bitmap = nil if !self.disposed? super end def clearBitmap - @_iconbitmap.dispose if @_iconbitmap + @_iconbitmap&.dispose @_iconbitmap = nil self.bitmap = nil end @@ -47,7 +47,7 @@ class PokemonSprite < SpriteWrapper end def setPokemonBitmap(pokemon, back = false) - @_iconbitmap.dispose if @_iconbitmap + @_iconbitmap&.dispose @_iconbitmap = (pokemon) ? GameData::Species.sprite_bitmap_from_pokemon(pokemon, back) : nil self.bitmap = (@_iconbitmap) ? @_iconbitmap.bitmap : nil self.color = Color.new(0, 0, 0, 0) @@ -55,14 +55,14 @@ class PokemonSprite < SpriteWrapper end def setPokemonBitmapSpecies(pokemon, species, back = false) - @_iconbitmap.dispose if @_iconbitmap + @_iconbitmap&.dispose @_iconbitmap = (pokemon) ? GameData::Species.sprite_bitmap_from_pokemon(pokemon, back, species) : nil self.bitmap = (@_iconbitmap) ? @_iconbitmap.bitmap : nil changeOrigin end def setSpeciesBitmap(species, gender = 0, form = 0, shiny = false, shadow = false, back = false, egg = false) - @_iconbitmap.dispose if @_iconbitmap + @_iconbitmap&.dispose @_iconbitmap = GameData::Species.sprite_bitmap(species, form, gender, shiny, shadow, back, egg) self.bitmap = (@_iconbitmap) ? @_iconbitmap.bitmap : nil changeOrigin @@ -102,7 +102,7 @@ class PokemonIconSprite < SpriteWrapper end def dispose - @animBitmap.dispose if @animBitmap + @animBitmap&.dispose super end @@ -121,7 +121,7 @@ class PokemonIconSprite < SpriteWrapper def pokemon=(value) @pokemon = value - @animBitmap.dispose if @animBitmap + @animBitmap&.dispose @animBitmap = nil if !@pokemon self.bitmap = nil @@ -236,7 +236,7 @@ class PokemonSpeciesIconSprite < SpriteWrapper end def dispose - @animBitmap.dispose if @animBitmap + @animBitmap&.dispose super end @@ -307,7 +307,7 @@ class PokemonSpeciesIconSprite < SpriteWrapper end def refresh - @animBitmap.dispose if @animBitmap + @animBitmap&.dispose @animBitmap = nil bitmapFileName = GameData::Species.icon_filename(@species, @form, @gender, @shiny) return if !bitmapFileName diff --git a/Data/Scripts/014_Pokemon/001_Pokemon-related/004_PokemonStorage.rb b/Data/Scripts/014_Pokemon/001_Pokemon-related/004_PokemonStorage.rb index 3005390d0..df6b48497 100644 --- a/Data/Scripts/014_Pokemon/001_Pokemon-related/004_PokemonStorage.rb +++ b/Data/Scripts/014_Pokemon/001_Pokemon-related/004_PokemonStorage.rb @@ -153,7 +153,7 @@ class PokemonStorage end def [](x, y = nil) - if y == nil + if y.nil? return (x == -1) ? self.party : @boxes[x] else @boxes.each do |i| @@ -212,7 +212,7 @@ class PokemonStorage def pbMoveCaughtToBox(pkmn, box) maxPokemon(box).times do |i| - if self[box, i] == nil + if self[box, i].nil? if Settings::HEAL_STORED_POKEMON && box >= 0 old_ready_evo = pkmn.ready_to_evolve pkmn.heal @@ -232,14 +232,14 @@ class PokemonStorage pkmn.ready_to_evolve = old_ready_evo end maxPokemon(@currentBox).times do |i| - if self[@currentBox, i] == nil + if self[@currentBox, i].nil? self[@currentBox, i] = pkmn return @currentBox end end self.maxBoxes.times do |j| maxPokemon(j).times do |i| - if self[j, i] == nil + if self[j, i].nil? self[j, i] = pkmn @currentBox = j return @currentBox diff --git a/Data/Scripts/014_Pokemon/001_Pokemon.rb b/Data/Scripts/014_Pokemon/001_Pokemon.rb index d5c183692..d95ac2d78 100644 --- a/Data/Scripts/014_Pokemon/001_Pokemon.rb +++ b/Data/Scripts/014_Pokemon/001_Pokemon.rb @@ -157,7 +157,7 @@ class Pokemon @ability = nil MultipleForms.call("onSetForm", self, value, oldForm) calc_stats - $player.pokedex.register(self) if $player + $player&.pokedex&.register(self) end # The same as def form=, but yields to a given block in the middle so that a @@ -170,7 +170,7 @@ class Pokemon yield if block_given? MultipleForms.call("onSetForm", self, value, oldForm) calc_stats - $player.pokedex.register(self) if $player + $player&.pokedex&.register(self) end def form_simple=(value) diff --git a/Data/Scripts/015_Trainers and player/001_Trainer.rb b/Data/Scripts/015_Trainers and player/001_Trainer.rb index 3f7283e60..460caddb8 100644 --- a/Data/Scripts/015_Trainers and player/001_Trainer.rb +++ b/Data/Scripts/015_Trainers and player/001_Trainer.rb @@ -134,13 +134,13 @@ class Trainer # Returns true if there is a Pokémon of the given species in the trainer's # party. You may also specify a particular form it should be. def has_species?(species, form = -1) - return pokemon_party.any? { |p| p && p.isSpecies?(species) && (form < 0 || p.form == form) } + return pokemon_party.any? { |p| p&.isSpecies?(species) && (form < 0 || p.form == form) } end # Returns whether there is a fatefully met Pokémon of the given species in the # trainer's party. def has_fateful_species?(species) - return pokemon_party.any? { |p| p && p.isSpecies?(species) && p.obtain_method == 4 } + return pokemon_party.any? { |p| p&.isSpecies?(species) && p.obtain_method == 4 } end # Returns whether there is a Pokémon with the given type in the trainer's @@ -148,7 +148,7 @@ class Trainer def has_pokemon_of_type?(type) return false if !GameData::Type.exists?(type) type = GameData::Type.get(type).id - return pokemon_party.any? { |p| p && p.hasType?(type) } + return pokemon_party.any? { |p| p&.hasType?(type) } end # Checks whether any Pokémon in the party knows the given move, and returns diff --git a/Data/Scripts/015_Trainers and player/002_Trainer_LoadAndNew.rb b/Data/Scripts/015_Trainers and player/002_Trainer_LoadAndNew.rb index f305b23e0..3e1911c66 100644 --- a/Data/Scripts/015_Trainers and player/002_Trainer_LoadAndNew.rb +++ b/Data/Scripts/015_Trainers and player/002_Trainer_LoadAndNew.rb @@ -73,7 +73,7 @@ def pbTrainerTypeCheck(trainer_type) if pbConfirmMessage(_INTL("Add new trainer type {1}?", trainer_type.to_s)) pbTrainerTypeEditorNew(trainer_type.to_s) end - pbMapInterpreter.command_end if pbMapInterpreter + pbMapInterpreter&.command_end return false end @@ -113,10 +113,10 @@ def pbMissingTrainer(tr_type, tr_name, tr_version) raise _INTL("Can't find trainer ({1}, {2}, ID {3})", tr_type.to_s, tr_name, tr_version) end message = "" - if tr_version != 0 - message = _INTL("Add new trainer ({1}, {2}, ID {3})?", tr_type.to_s, tr_name, tr_version) - else + if tr_version == 0 message = _INTL("Add new trainer ({1}, {2})?", tr_type.to_s, tr_name) + else + message = _INTL("Add new trainer ({1}, {2}, ID {3})?", tr_type.to_s, tr_name, tr_version) end cmd = pbMessage(message, [_INTL("Yes"), _INTL("No")], 2) pbNewTrainer(tr_type, tr_name, tr_version) if cmd == 0 diff --git a/Data/Scripts/015_Trainers and player/003_Trainer_Sprites.rb b/Data/Scripts/015_Trainers and player/003_Trainer_Sprites.rb index 98b34878d..02e8ac2b5 100644 --- a/Data/Scripts/015_Trainers and player/003_Trainer_Sprites.rb +++ b/Data/Scripts/015_Trainers and player/003_Trainer_Sprites.rb @@ -12,7 +12,7 @@ class TrainerWalkingCharSprite < SpriteWrapper end def charset=(value) - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose @animbitmap = nil bitmapFileName = sprintf("Graphics/Characters/%s", value) @charset = pbResolveBitmap(bitmapFileName) @@ -26,7 +26,7 @@ class TrainerWalkingCharSprite < SpriteWrapper end def altcharset=(value) # Used for box icon in the naming screen - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose @animbitmap = nil @charset = pbResolveBitmap(value) if @charset @@ -43,7 +43,7 @@ class TrainerWalkingCharSprite < SpriteWrapper end def dispose - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose super end diff --git a/Data/Scripts/015_Trainers and player/004_Player.rb b/Data/Scripts/015_Trainers and player/004_Player.rb index cdedb0cba..b18396b34 100644 --- a/Data/Scripts/015_Trainers and player/004_Player.rb +++ b/Data/Scripts/015_Trainers and player/004_Player.rb @@ -38,13 +38,13 @@ class Player < Trainer def character_ID=(value) return if @character_ID == value @character_ID = value - $game_player.refresh_charset if $game_player + $game_player&.refresh_charset end def outfit=(value) return if @outfit == value @outfit = value - $game_player.refresh_charset if $game_player + $game_player&.refresh_charset end def trainer_type diff --git a/Data/Scripts/016_UI/001_Non-interactive UI/003_UI_EggHatching.rb b/Data/Scripts/016_UI/001_Non-interactive UI/003_UI_EggHatching.rb index ccb928e3c..256e3cf6b 100644 --- a/Data/Scripts/016_UI/001_Non-interactive UI/003_UI_EggHatching.rb +++ b/Data/Scripts/016_UI/001_Non-interactive UI/003_UI_EggHatching.rb @@ -103,15 +103,14 @@ class PokemonEggHatch_Scene pbMEPlay("Evolution success") @pokemon.name = nil pbMessage(_INTL("\\se[]{1} hatched from the Egg!\\wt[80]", @pokemon.name)) { update } - if $PokemonSystem.givenicknames == 0 - if pbConfirmMessage( - _INTL("Would you like to nickname the newly hatched {1}?", @pokemon.name) - ) { update } - nickname = pbEnterPokemonName(_INTL("{1}'s nickname?", @pokemon.name), - 0, Pokemon::MAX_NAME_SIZE, "", @pokemon, true) - @pokemon.name = nickname - @nicknamed = true - end + if $PokemonSystem.givenicknames == 0 && + pbConfirmMessage( + _INTL("Would you like to nickname the newly hatched {1}?", @pokemon.name) + ) { update } + nickname = pbEnterPokemonName(_INTL("{1}'s nickname?", @pokemon.name), + 0, Pokemon::MAX_NAME_SIZE, "", @pokemon, true) + @pokemon.name = nickname + @nicknamed = true end end @@ -209,12 +208,11 @@ def pbHatch(pokemon) pbMessage(_INTL("...\1")) pbMessage(_INTL("... .... .....\1")) pbMessage(_INTL("{1} hatched from the Egg!", speciesname)) - if $PokemonSystem.givenicknames == 0 - if pbConfirmMessage(_INTL("Would you like to nickname the newly hatched {1}?", speciesname)) - nickname = pbEnterPokemonName(_INTL("{1}'s nickname?", speciesname), - 0, Pokemon::MAX_NAME_SIZE, "", pokemon) - pokemon.name = nickname - end + if $PokemonSystem.givenicknames == 0 && + pbConfirmMessage(_INTL("Would you like to nickname the newly hatched {1}?", speciesname)) + nickname = pbEnterPokemonName(_INTL("{1}'s nickname?", speciesname), + 0, Pokemon::MAX_NAME_SIZE, "", pokemon) + pokemon.name = nickname end end end diff --git a/Data/Scripts/016_UI/001_Non-interactive UI/006_UI_HallOfFame.rb b/Data/Scripts/016_UI/001_Non-interactive UI/006_UI_HallOfFame.rb index d2e9d0dce..730e34f9b 100644 --- a/Data/Scripts/016_UI/001_Non-interactive UI/006_UI_HallOfFame.rb +++ b/Data/Scripts/016_UI/001_Non-interactive UI/006_UI_HallOfFame.rb @@ -138,21 +138,21 @@ class HallOfFame_Scene # Don't use odd numbers! def xpointformula(battlernumber) ret = 0 - if !SINGLEROW - ret = 32 + (160 * xpositionformula(battlernumber)) - else + if SINGLEROW ret = ((60 * (battlernumber / 2)) + 48) * (xpositionformula(battlernumber) - 1) ret += (Graphics.width / 2) - 56 + else + ret = 32 + (160 * xpositionformula(battlernumber)) end return ret end def ypointformula(battlernumber) ret = 0 - if !SINGLEROW - ret = 32 + (128 * ypositionformula(battlernumber) / 2) - else + if SINGLEROW ret = 96 - (8 * (battlernumber / 2)) + else + ret = 32 + (128 * ypositionformula(battlernumber) / 2) end return ret end @@ -160,20 +160,20 @@ class HallOfFame_Scene # Returns 0, 1 or 2 as the x/y column value def xpositionformula(battlernumber) ret = 0 - if !SINGLEROW - ret = (battlernumber / 3).even? ? (19 - battlernumber) % 3 : (19 + battlernumber) % 3 - else + if SINGLEROW ret = battlernumber % 2 * 2 + else + ret = (battlernumber / 3).even? ? (19 - battlernumber) % 3 : (19 + battlernumber) % 3 end return ret end def ypositionformula(battlernumber) ret = 0 - if !SINGLEROW - ret = (battlernumber / 3) % 2 * 2 - else + if SINGLEROW ret = 1 + else + ret = (battlernumber / 3) % 2 * 2 end return ret end @@ -244,12 +244,12 @@ class HallOfFame_Scene def createTrainerBattler @sprites["trainer"] = IconSprite.new(@viewport) @sprites["trainer"].setBitmap(GameData::TrainerType.front_sprite_filename($player.trainer_type)) - if !SINGLEROW - @sprites["trainer"].x = Graphics.width - 96 - @sprites["trainer"].y = 160 - else + if SINGLEROW @sprites["trainer"].x = Graphics.width / 2 @sprites["trainer"].y = 178 + else + @sprites["trainer"].x = Graphics.width - 96 + @sprites["trainer"].y = 160 end @sprites["trainer"].z = 9 @sprites["trainer"].ox = @sprites["trainer"].bitmap.width / 2 @@ -318,7 +318,7 @@ class HallOfFame_Scene [_INTL("IDNo.{1}", pokemon.egg? ? "?????" : idno), Graphics.width - 192, Graphics.height - 54, 2, BASECOLOR, SHADOWCOLOR] ] - if (hallNumber > -1) + if hallNumber > -1 textPositions.push([_INTL("Hall of Fame No."), (Graphics.width / 2) - 104, -6, 0, BASECOLOR, SHADOWCOLOR]) textPositions.push([hallNumber.to_s, (Graphics.width / 2) + 104, -6, 1, BASECOLOR, SHADOWCOLOR]) end diff --git a/Data/Scripts/016_UI/001_Non-interactive UI/007_UI_Credits.rb b/Data/Scripts/016_UI/001_Non-interactive UI/007_UI_Credits.rb index bb732ad1a..80985fc37 100644 --- a/Data/Scripts/016_UI/001_Non-interactive UI/007_UI_Credits.rb +++ b/Data/Scripts/016_UI/001_Non-interactive UI/007_UI_Credits.rb @@ -205,7 +205,7 @@ _END_ Graphics.transition(8, "fadetoblack") $game_temp.background_bitmap.dispose @background_sprite.dispose - @credit_sprites.each { |s| s.dispose if s } + @credit_sprites.each { |s| s&.dispose } text_viewport.dispose viewport.dispose $PokemonGlobal.creditsPlayed = true diff --git a/Data/Scripts/016_UI/003_UI_Pokedex_Main.rb b/Data/Scripts/016_UI/003_UI_Pokedex_Main.rb index 405b98a2f..9445f7485 100644 --- a/Data/Scripts/016_UI/003_UI_Pokedex_Main.rb +++ b/Data/Scripts/016_UI/003_UI_Pokedex_Main.rb @@ -517,8 +517,8 @@ class PokemonPokedex_Scene if System.user_language[3..4] == "US" # If the user is in the United States ht1 = (params[4] >= @heightCommands.length) ? 99 * 12 : (ht1 / 0.254).round ht2 = (params[5] < 0) ? 99 * 12 : (ht2 / 0.254).round - wt1 = (params[6] >= @weightCommands.length) ? 99990 : (wt1 / 0.254).round - wt2 = (params[7] < 0) ? 99990 : (wt2 / 0.254).round + wt1 = (params[6] >= @weightCommands.length) ? 99_990 : (wt1 / 0.254).round + wt2 = (params[7] < 0) ? 99_990 : (wt2 / 0.254).round textpos.push([sprintf("%d'%02d''", ht1 / 12, ht1 % 12), 166, 220, 2, base, shadow, 1]) textpos.push([sprintf("%d'%02d''", ht2 / 12, ht2 % 12), 294, 220, 2, base, shadow, 1]) textpos.push([sprintf("%.1f", wt1 / 10.0), 166, 272, 2, base, shadow, 1]) @@ -644,8 +644,8 @@ class PokemonPokedex_Scene wt2 = (sel[1] < 0) ? 9999 : (sel[1] >= @weightCommands.length) ? 0 : @weightCommands[sel[1]] hwoffset = false if System.user_language[3..4] == "US" # If the user is in the United States - wt1 = (sel[0] >= @weightCommands.length) ? 99990 : (wt1 / 0.254).round - wt2 = (sel[1] < 0) ? 99990 : (wt2 / 0.254).round + wt1 = (sel[0] >= @weightCommands.length) ? 99_990 : (wt1 / 0.254).round + wt2 = (sel[1] < 0) ? 99_990 : (wt2 / 0.254).round txt1 = sprintf("%.1f", wt1 / 10.0) txt2 = sprintf("%.1f", wt2 / 10.0) hwoffset = true diff --git a/Data/Scripts/016_UI/004_UI_Pokedex_Entry.rb b/Data/Scripts/016_UI/004_UI_Pokedex_Entry.rb index 6a9af665e..e4b93d975 100644 --- a/Data/Scripts/016_UI/004_UI_Pokedex_Entry.rb +++ b/Data/Scripts/016_UI/004_UI_Pokedex_Entry.rb @@ -130,17 +130,13 @@ class PokemonPokedexInfo_Scene @gender, @form = $player.pokedex.last_form_seen(@species) metrics_data = GameData::SpeciesMetrics.get_species_form(@species, @form) @sprites["infosprite"].setSpeciesBitmap(@species, @gender, @form) - if @sprites["formfront"] - @sprites["formfront"].setSpeciesBitmap(@species, @gender, @form) - end + @sprites["formfront"]&.setSpeciesBitmap(@species, @gender, @form) if @sprites["formback"] @sprites["formback"].setSpeciesBitmap(@species, @gender, @form, false, false, true) @sprites["formback"].y = 256 @sprites["formback"].y += metrics_data.back_sprite[1] * 2 end - if @sprites["formicon"] - @sprites["formicon"].pbSetParams(@species, @gender, @form) - end + @sprites["formicon"]&.pbSetParams(@species, @gender, @form) end def pbGetAvailableForms diff --git a/Data/Scripts/016_UI/005_UI_Party.rb b/Data/Scripts/016_UI/005_UI_Party.rb index 466d36781..7f9708ca1 100644 --- a/Data/Scripts/016_UI/005_UI_Party.rb +++ b/Data/Scripts/016_UI/005_UI_Party.rb @@ -347,12 +347,10 @@ class PokemonPartyPanel < SpriteWrapper @pkmnsprite.color = self.color @pkmnsprite.selected = self.selected end - if @helditemsprite && !@helditemsprite.disposed? - if @helditemsprite.visible - @helditemsprite.x = self.x + 62 - @helditemsprite.y = self.y + 48 - @helditemsprite.color = self.color - end + if @helditemsprite&.visible && !@helditemsprite.disposed? + @helditemsprite.x = self.x + 62 + @helditemsprite.y = self.y + 48 + @helditemsprite.color = self.color end if @overlaysprite && !@overlaysprite.disposed? @overlaysprite.x = self.x @@ -361,7 +359,7 @@ class PokemonPartyPanel < SpriteWrapper end if @refreshBitmap @refreshBitmap = false - @overlaysprite.bitmap.clear if @overlaysprite.bitmap + @overlaysprite.bitmap&.clear basecolor = Color.new(248, 248, 248) shadowcolor = Color.new(40, 40, 40) pbSetSystemFont(@overlaysprite.bitmap) @@ -1157,11 +1155,10 @@ class PokemonPartyScreen def pbPokemonScreen can_access_storage = false - if $player.has_box_link || $bag.has?(:POKEMONBOXLINK) - if !$game_switches[Settings::DISABLE_BOX_LINK_SWITCH] && - !$game_map.metadata&.has_flag?("DisableBoxLink") - can_access_storage = true - end + if ($player.has_box_link || $bag.has?(:POKEMONBOXLINK)) && + !$game_switches[Settings::DISABLE_BOX_LINK_SWITCH] && + !$game_map.metadata&.has_flag?("DisableBoxLink") + can_access_storage = true end @scene.pbStartScene(@party, (@party.length > 1) ? _INTL("Choose a Pokémon.") : _INTL("Choose Pokémon or cancel."), @@ -1317,10 +1314,8 @@ class PokemonPartyScreen item = @scene.pbChooseItem($bag) { @scene.pbSetHelpText((@party.length > 1) ? _INTL("Choose a Pokémon.") : _INTL("Choose Pokémon or cancel.")) } - if item - if pbGiveItemToPokemon(item, pkmn, self, pkmnid) - pbRefreshSingle(pkmnid) - end + if item && pbGiveItemToPokemon(item, pkmn, self, pkmnid) + pbRefreshSingle(pkmnid) end elsif cmdTakeItem >= 0 && command == cmdTakeItem # Take if pbTakeItemFromPokemon(pkmn, self) diff --git a/Data/Scripts/016_UI/006_UI_Summary.rb b/Data/Scripts/016_UI/006_UI_Summary.rb index 43938b747..72398b337 100644 --- a/Data/Scripts/016_UI/006_UI_Summary.rb +++ b/Data/Scripts/016_UI/006_UI_Summary.rb @@ -205,7 +205,7 @@ class PokemonSummary_Scene pbFadeOutAndHide(@sprites) { pbUpdate } pbDisposeSpriteHash(@sprites) @typebitmap.dispose - @markingbitmap.dispose if @markingbitmap + @markingbitmap&.dispose @viewport.dispose end @@ -519,7 +519,7 @@ class PokemonSummary_Scene # Write Egg Watch blurb memo += _INTL("\"The Egg Watch\"\n") eggstate = _INTL("It looks like this Egg will take a long time to hatch.") - eggstate = _INTL("What will hatch from this? It doesn't seem close to hatching.") if @pokemon.steps_to_hatch < 10200 + eggstate = _INTL("What will hatch from this? It doesn't seem close to hatching.") if @pokemon.steps_to_hatch < 10_200 eggstate = _INTL("It appears to move occasionally. It may be close to hatching.") if @pokemon.steps_to_hatch < 2550 eggstate = _INTL("Sounds can be heard coming from inside! It will hatch soon!") if @pokemon.steps_to_hatch < 1275 memo += sprintf("%s\n", eggstate) @@ -939,18 +939,18 @@ class PokemonSummary_Scene @sprites["movepresel"].visible = false switching = false elsif !@pokemon.shadowPokemon? - if !switching - @sprites["movepresel"].index = selmove - @sprites["movepresel"].visible = true - oldselmove = selmove - switching = true - else + if switching tmpmove = @pokemon.moves[oldselmove] @pokemon.moves[oldselmove] = @pokemon.moves[selmove] @pokemon.moves[selmove] = tmpmove @sprites["movepresel"].visible = false switching = false drawSelectedMove(nil, @pokemon.moves[selmove]) + else + @sprites["movepresel"].index = selmove + @sprites["movepresel"].visible = true + oldselmove = selmove + switching = true end end elsif Input.trigger?(Input::UP) @@ -1003,15 +1003,7 @@ class PokemonSummary_Scene @sprites["ribbonpresel"].visible = false switching = false elsif Input.trigger?(Input::USE) - if !switching - if @pokemon.ribbons[selribbon] - pbPlayDecisionSE - @sprites["ribbonpresel"].index = selribbon - (@ribbonOffset * 4) - oldselribbon = selribbon - @sprites["ribbonpresel"].visible = true - switching = true - end - else + if switching pbPlayDecisionSE tmpribbon = @pokemon.ribbons[oldselribbon] @pokemon.ribbons[oldselribbon] = @pokemon.ribbons[selribbon] @@ -1026,6 +1018,14 @@ class PokemonSummary_Scene @sprites["ribbonpresel"].visible = false switching = false drawSelectedRibbon(@pokemon.ribbons[selribbon]) + else + if @pokemon.ribbons[selribbon] + pbPlayDecisionSE + @sprites["ribbonpresel"].index = selribbon - (@ribbonOffset * 4) + oldselribbon = selribbon + @sprites["ribbonpresel"].visible = true + switching = true + end end elsif Input.trigger?(Input::UP) selribbon -= 4 diff --git a/Data/Scripts/016_UI/007_UI_Bag.rb b/Data/Scripts/016_UI/007_UI_Bag.rb index 9ed2beabc..3a5c6d8c0 100644 --- a/Data/Scripts/016_UI/007_UI_Bag.rb +++ b/Data/Scripts/016_UI/007_UI_Bag.rb @@ -148,13 +148,13 @@ class PokemonBag_Scene numfilledpockets = @bag.pockets.length - 1 if @choosing numfilledpockets = 0 - if @filterlist != nil + if @filterlist.nil? (1...@bag.pockets.length).each do |i| - numfilledpockets += 1 if @filterlist[i].length > 0 + numfilledpockets += 1 if @bag.pockets[i].length > 0 end else (1...@bag.pockets.length).each do |i| - numfilledpockets += 1 if @bag.pockets[i].length > 0 + numfilledpockets += 1 if @filterlist[i].length > 0 end end lastpocket = (resetpocket) ? 1 : @bag.last_viewed_pocket @@ -333,7 +333,7 @@ class PokemonBag_Scene def pbRefreshFilter @filterlist = nil return if !@choosing - return if @filterproc == nil + return if @filterproc.nil? @filterlist = [] (1...@bag.pockets.length).each do |i| @filterlist[i] = [] @@ -428,14 +428,12 @@ class PokemonBag_Scene # pbRefresh # end elsif Input.trigger?(Input::ACTION) # Start switching the selected item - if !@choosing - if thispocket.length > 1 && itemwindow.index < thispocket.length && - !Settings::BAG_POCKET_AUTO_SORT[itemwindow.pocket - 1] - itemwindow.sorting = true - swapinitialpos = itemwindow.index - pbPlayDecisionSE - pbRefresh - end + if !@choosing && thispocket.length > 1 && itemwindow.index < thispocket.length && + !Settings::BAG_POCKET_AUTO_SORT[itemwindow.pocket - 1] + itemwindow.sorting = true + swapinitialpos = itemwindow.index + pbPlayDecisionSE + pbRefresh end elsif Input.trigger?(Input::BACK) # Cancel the item screen pbPlayCloseMenuSE @@ -647,9 +645,7 @@ class PokemonBagScreen qty = @scene.pbChooseNumber(_INTL("How many do you want to deposit?"), qty) end if qty > 0 - if !storage.can_add?(item, qty) - pbDisplay(_INTL("There's no room to store items.")) - else + if storage.can_add?(item, qty) if !@bag.remove(item, qty) raise "Can't delete items from Bag" end @@ -660,6 +656,8 @@ class PokemonBagScreen dispqty = (itm.is_important?) ? 1 : qty itemname = (dispqty > 1) ? itm.name_plural : itm.name pbDisplay(_INTL("Deposited {1} {2}.", dispqty, itemname)) + else + pbDisplay(_INTL("There's no room to store items.")) end end end diff --git a/Data/Scripts/016_UI/010_UI_Phone.rb b/Data/Scripts/016_UI/010_UI_Phone.rb index 5dbae2e23..d027f3df6 100644 --- a/Data/Scripts/016_UI/010_UI_Phone.rb +++ b/Data/Scripts/016_UI/010_UI_Phone.rb @@ -82,17 +82,13 @@ class PokemonPhoneScene j = i + @sprites["list"].top_item next if j >= commands.length trainer = @trainers[j] - if trainer.length == 4 - if trainer[3] - @sprites["rematch[#{i}]"].setBitmap("Graphics/Pictures/phoneRematch") - end + if trainer.length == 4 && trainer[3] + @sprites["rematch[#{i}]"].setBitmap("Graphics/Pictures/phoneRematch") end end rematchcount = 0 @trainers.each do |trainer| - if trainer.length == 4 - rematchcount += 1 if trainer[3] - end + rematchcount += 1 if trainer.length == 4 && trainer[3] end infotext = _INTL("Registered
") infotext += _INTL(" {1}
", @sprites["list"].commands.length) @@ -125,10 +121,8 @@ class PokemonPhoneScene j = i + @sprites["list"].top_item next if j >= commands.length trainer = @trainers[j] - if trainer.length == 4 - if trainer[3] - @sprites["rematch[#{i}]"].setBitmap("Graphics/Pictures/phoneRematch") - end + if trainer.length == 4 && trainer[3] + @sprites["rematch[#{i}]"].setBitmap("Graphics/Pictures/phoneRematch") end end end @@ -137,9 +131,7 @@ class PokemonPhoneScene break elsif Input.trigger?(Input::USE) index = @sprites["list"].index - if index >= 0 - pbCallTrainer(@trainers[index][0], @trainers[index][1]) - end + pbCallTrainer(@trainers[index][0], @trainers[index][1]) if index >= 0 end end } diff --git a/Data/Scripts/016_UI/013_UI_Load.rb b/Data/Scripts/016_UI/013_UI_Load.rb index 5a87f988e..52c652396 100644 --- a/Data/Scripts/016_UI/013_UI_Load.rb +++ b/Data/Scripts/016_UI/013_UI_Load.rb @@ -54,7 +54,7 @@ class PokemonLoadPanel < SpriteWrapper end if @refreshBitmap @refreshBitmap = false - self.bitmap.clear if self.bitmap + self.bitmap&.clear if @isContinue self.bitmap.blt(0, 0, @bgbitmap.bitmap, Rect.new(0, (@selected) ? 111 * 2 : 0, @bgbitmap.width, 111 * 2)) else diff --git a/Data/Scripts/016_UI/015_UI_Options.rb b/Data/Scripts/016_UI/015_UI_Options.rb index 75c1db9ac..5ccc4182d 100644 --- a/Data/Scripts/016_UI/015_UI_Options.rb +++ b/Data/Scripts/016_UI/015_UI_Options.rb @@ -40,7 +40,7 @@ module PropertyMixin end def set(value) - @setProc.call(value) if @setProc + @setProc&.call(value) end end diff --git a/Data/Scripts/016_UI/016_UI_ReadyMenu.rb b/Data/Scripts/016_UI/016_UI_ReadyMenu.rb index afc272be6..2b9b3c78b 100644 --- a/Data/Scripts/016_UI/016_UI_ReadyMenu.rb +++ b/Data/Scripts/016_UI/016_UI_ReadyMenu.rb @@ -73,23 +73,21 @@ class ReadyMenuButton < SpriteWrapper textpos = [ [@command[1], textx, 16, 2, Color.new(248, 248, 248), Color.new(40, 40, 40), 1] ] - if !@command[2] - if !GameData::Item.get(@command[0]).is_important? - qty = $bag.quantity(@command[0]) - if qty > 99 - textpos.push([_INTL(">99"), 230, 16, 1, - Color.new(248, 248, 248), Color.new(40, 40, 40), 1]) - else - textpos.push([_INTL("x{1}", qty), 230, 16, 1, - Color.new(248, 248, 248), Color.new(40, 40, 40), 1]) - end + if !@command[2] && !GameData::Item.get(@command[0]).is_important? + qty = $bag.quantity(@command[0]) + if qty > 99 + textpos.push([_INTL(">99"), 230, 16, 1, + Color.new(248, 248, 248), Color.new(40, 40, 40), 1]) + else + textpos.push([_INTL("x{1}", qty), 230, 16, 1, + Color.new(248, 248, 248), Color.new(40, 40, 40), 1]) end end pbDrawTextPositions(self.bitmap, textpos) end def update - @icon.update if @icon + @icon&.update super end end diff --git a/Data/Scripts/016_UI/017_UI_PokemonStorage.rb b/Data/Scripts/016_UI/017_UI_PokemonStorage.rb index b702ad12a..fbd74f5a2 100644 --- a/Data/Scripts/016_UI/017_UI_PokemonStorage.rb +++ b/Data/Scripts/016_UI/017_UI_PokemonStorage.rb @@ -58,9 +58,9 @@ class MosaicPokemonSprite < PokemonSprite def dispose super - @mosaicbitmap.dispose if @mosaicbitmap + @mosaicbitmap&.dispose @mosaicbitmap = nil - @mosaicbitmap2.dispose if @mosaicbitmap2 + @mosaicbitmap2&.dispose @mosaicbitmap2 = nil end @@ -80,15 +80,15 @@ class MosaicPokemonSprite < PokemonSprite @inrefresh = true @oldbitmap = bitmap if @mosaic <= 0 || !@oldbitmap - @mosaicbitmap.dispose if @mosaicbitmap + @mosaicbitmap&.dispose @mosaicbitmap = nil - @mosaicbitmap2.dispose if @mosaicbitmap2 + @mosaicbitmap2&.dispose @mosaicbitmap2 = nil self.bitmap = @oldbitmap else newWidth = [(@oldbitmap.width / @mosaic), 1].max newHeight = [(@oldbitmap.height / @mosaic), 1].max - @mosaicbitmap2.dispose if @mosaicbitmap2 + @mosaicbitmap2&.dispose @mosaicbitmap = pbDoEnsureBitmap(@mosaicbitmap, newWidth, newHeight) @mosaicbitmap.clear @mosaicbitmap2 = pbDoEnsureBitmap(@mosaicbitmap2, @oldbitmap.width, @oldbitmap.height) @@ -145,12 +145,12 @@ class PokemonBoxArrow < SpriteWrapper def dispose @handsprite.dispose - @heldpkmn.dispose if @heldpkmn + @heldpkmn&.dispose super end def heldPokemon - @heldpkmn = nil if @heldpkmn && @heldpkmn.disposed? + @heldpkmn = nil if @heldpkmn&.disposed? @holding = false if !@heldpkmn return @heldpkmn end @@ -231,14 +231,14 @@ class PokemonBoxArrow < SpriteWrapper end def release - @heldpkmn.release if @heldpkmn + @heldpkmn&.release end def update @updating = true super heldpkmn = heldPokemon - heldpkmn.update if heldpkmn + heldpkmn&.update @handsprite.update @holding = false if !heldpkmn if @grabbingState > 0 @@ -314,7 +314,7 @@ class PokemonBoxSprite < SpriteWrapper def dispose if !disposed? PokemonBox::BOX_SIZE.times do |i| - @pokemonsprites[i].dispose if @pokemonsprites[i] + @pokemonsprites[i]&.dispose @pokemonsprites[i] = nil end @boxbitmap.dispose @@ -371,7 +371,7 @@ class PokemonBoxSprite < SpriteWrapper @bg = @boxnumber % PokemonStorage::BASICWALLPAPERQTY @storage[@boxnumber].background = @bg end - @boxbitmap.dispose if @boxbitmap + @boxbitmap&.dispose @boxbitmap = AnimatedBitmap.new("Graphics/Pictures/Storage/box_#{@bg}") end end @@ -466,7 +466,7 @@ class PokemonBoxPartySprite < SpriteWrapper def dispose Settings::MAX_PARTY_SIZE.times do |i| - @pokemonsprites[i].dispose if @pokemonsprites[i] + @pokemonsprites[i]&.dispose end @boxbitmap.dispose @contents.dispose @@ -539,8 +539,8 @@ class PokemonBoxPartySprite < SpriteWrapper xvalues.push(18 + (72 * (i % 2))) yvalues.push(2 + (16 * (i % 2)) + (64 * (i / 2))) end - @pokemonsprites.delete_if { |sprite| sprite && sprite.disposed? } - @pokemonsprites.each { |sprite| sprite.refresh if sprite } + @pokemonsprites.delete_if { |sprite| sprite&.disposed? } + @pokemonsprites.each { |sprite| sprite&.refresh } Settings::MAX_PARTY_SIZE.times do |j| sprite = @pokemonsprites[j] if sprite && !sprite.disposed? @@ -615,12 +615,12 @@ class PokemonStorageScene pbSetSystemFont(@sprites["markingoverlay"].bitmap) @sprites["arrow"] = PokemonBoxArrow.new(@arrowviewport) @sprites["arrow"].z += 1 - if command != 2 - pbSetArrow(@sprites["arrow"], @selection) - pbUpdateOverlay(@selection) - else + if command == 2 pbPartySetArrow(@sprites["arrow"], @selection) pbUpdateOverlay(@selection, @storage.party) + else + pbSetArrow(@sprites["arrow"], @selection) + pbUpdateOverlay(@selection) end pbSetMosaic(@selection) pbSEPlay("PC access") @@ -630,7 +630,7 @@ class PokemonStorageScene def pbCloseBox pbFadeOutAndHide(@sprites) pbDisposeSpriteHash(@sprites) - @markingbitmap.dispose if @markingbitmap + @markingbitmap&.dispose @boxviewport.dispose @boxsidesviewport.dispose @arrowviewport.dispose @@ -1043,24 +1043,21 @@ class PokemonStorageScene end def pbJumpToBox(newbox) - if @storage.currentBox != newbox - if newbox > @storage.currentBox - pbSwitchBoxToRight(newbox) - else - pbSwitchBoxToLeft(newbox) - end - @storage.currentBox = newbox + return if @storage.currentBox == newbox + if newbox > @storage.currentBox + pbSwitchBoxToRight(newbox) + else + pbSwitchBoxToLeft(newbox) end + @storage.currentBox = newbox end def pbSetMosaic(selection) - if !@screen.pbHeldPokemon - if @boxForMosaic != @storage.currentBox || @selectionForMosaic != selection - @sprites["pokemon"].mosaic = Graphics.frame_rate / 4 - @boxForMosaic = @storage.currentBox - @selectionForMosaic = selection - end - end + return if @screen.pbHeldPokemon + return if @boxForMosaic == @storage.currentBox && @selectionForMosaic == selection + @sprites["pokemon"].mosaic = Graphics.frame_rate / 4 + @boxForMosaic = @storage.currentBox + @selectionForMosaic = selection end def pbSetQuickSwap(value) @@ -1489,7 +1486,7 @@ class PokemonStorageScreen @scene.pbStartBox(self, command) loop do selected = @scene.pbSelectBox(@storage.party) - if selected == nil + if selected.nil? if pbHeldPokemon pbDisplay(_INTL("You're holding a Pokémon!")) next @@ -1569,7 +1566,7 @@ class PokemonStorageScreen @scene.pbStartBox(self, command) loop do selected = @scene.pbSelectBox(@storage.party) - if selected == nil + if selected.nil? next if pbConfirm(_INTL("Continue Box operations?")) break else @@ -1713,11 +1710,11 @@ class PokemonStorageScreen if pbAbleCount <= 1 && pbAble?(@storage[box, index]) && !heldpoke pbPlayBuzzerSE pbDisplay(_INTL("That's your last Pokémon!")) - elsif heldpoke && heldpoke.mail + elsif heldpoke&.mail pbDisplay(_INTL("Please remove the Mail.")) elsif !heldpoke && @storage[box, index].mail pbDisplay(_INTL("Please remove the Mail.")) - elsif heldpoke && heldpoke.cannot_store + elsif heldpoke&.cannot_store pbDisplay(_INTL("{1} refuses to go into storage!", heldpoke.name)) elsif !heldpoke && @storage[box, index].cannot_store pbDisplay(_INTL("{1} refuses to go into storage!", @storage[box, index].name)) @@ -1900,12 +1897,12 @@ class PokemonStorageScreen if pokemon.item itemname = pokemon.item.name if pbConfirm(_INTL("Take this {1}?", itemname)) - if !$bag.add(pokemon.item) - pbDisplay(_INTL("Can't store the {1}.", itemname)) - else + if $bag.add(pokemon.item) pbDisplay(_INTL("Took the {1}.", itemname)) pokemon.item = nil @scene.pbHardRefresh + else + pbDisplay(_INTL("Can't store the {1}.", itemname)) end end else @@ -1966,7 +1963,7 @@ class PokemonStorageScreen end next end - if selected == nil + if selected.nil? next if pbConfirm(_INTL("Continue Box operations?")) break elsif selected[0] == -4 # Box name diff --git a/Data/Scripts/016_UI/018_UI_ItemStorage.rb b/Data/Scripts/016_UI/018_UI_ItemStorage.rb index 813bb6e90..90a68dfd4 100644 --- a/Data/Scripts/016_UI/018_UI_ItemStorage.rb +++ b/Data/Scripts/016_UI/018_UI_ItemStorage.rb @@ -208,10 +208,8 @@ module UIHelper Graphics.update Input.update (block_given?) ? yield : cw.update - if !cw.busy? - if brief || (Input.trigger?(Input::USE) && cw.resume) - break - end + if !cw.busy? && (brief || (Input.trigger?(Input::USE) && cw.resume)) + break end end cw.visible = oldvisible @@ -336,7 +334,7 @@ module UIHelper oldvisible = helpwindow.visible helpwindow.visible = helptext ? true : false helpwindow.letterbyletter = false - helpwindow.text = helptext ? helptext : "" + helpwindow.text = helptext || "" cmdwindow = Window_CommandPokemon.new(commands) cmdwindow.index = initcmd begin @@ -361,7 +359,7 @@ module UIHelper end end ensure - cmdwindow.dispose if cmdwindow + cmdwindow&.dispose end helpwindow.visible = oldvisible return ret diff --git a/Data/Scripts/016_UI/020_UI_PokeMart.rb b/Data/Scripts/016_UI/020_UI_PokeMart.rb index 48f4c87d4..09b72167d 100644 --- a/Data/Scripts/016_UI/020_UI_PokeMart.rb +++ b/Data/Scripts/016_UI/020_UI_PokeMart.rb @@ -175,7 +175,7 @@ end class PokemonMart_Scene def update pbUpdateSpriteHash(@sprites) - @subscene.pbUpdate if @subscene + @subscene&.pbUpdate end def pbRefresh @@ -296,7 +296,7 @@ class PokemonMart_Scene end def pbEndSellScene - @subscene.pbEndScene if @subscene + @subscene&.pbEndScene pbDisposeSpriteHash(@sprites) if @viewport2 numFrames = Graphics.frame_rate * 4 / 10 @@ -582,14 +582,7 @@ class PokemonMartScreen break if !@adapter.addItem(item) added += 1 end - if added != quantity - added.times do - if !@adapter.removeItem(item) - raise _INTL("Failed to delete stored items") - end - end - pbDisplayPaused(_INTL("You have no more room in the Bag.")) - else + if added == quantity $stats.money_spent_at_marts += price $stats.mart_items_bought += quantity @adapter.setMoney(@adapter.getMoney - price) @@ -615,6 +608,13 @@ class PokemonMartScreen end end end + else + added.times do + if !@adapter.removeItem(item) + raise _INTL("Failed to delete stored items") + end + end + pbDisplayPaused(_INTL("You have no more room in the Bag.")) end end @scene.pbEndBuyScene @@ -652,7 +652,8 @@ class PokemonMartScreen qty.times do @adapter.removeItem(item) end - pbDisplayPaused(_INTL("Turned over the {1} and received ${2}.", itemname, price.to_s_formatted)) { pbSEPlay("Mart buy item") } + pbDisplayPaused(_INTL("Turned over the {1} and received ${2}.", + itemname, price.to_s_formatted)) { pbSEPlay("Mart buy item") } @scene.pbRefresh end @scene.pbHideMoney @@ -673,8 +674,7 @@ def pbPokemonMart(stock, speech = nil, cantsell = false) commands[cmdBuy = commands.length] = _INTL("Buy") commands[cmdSell = commands.length] = _INTL("Sell") if !cantsell commands[cmdQuit = commands.length] = _INTL("Quit") - cmd = pbMessage(speech ? speech : _INTL("Welcome! How may I serve you?"), - commands, cmdQuit + 1) + cmd = pbMessage(speech || _INTL("Welcome! How may I serve you?"), commands, cmdQuit + 1) loop do if cmdBuy >= 0 && cmd == cmdBuy scene = PokemonMart_Scene.new @@ -688,8 +688,7 @@ def pbPokemonMart(stock, speech = nil, cantsell = false) pbMessage(_INTL("Please come again!")) break end - cmd = pbMessage(_INTL("Is there anything else I can help you with?"), - commands, cmdQuit + 1) + cmd = pbMessage(_INTL("Is there anything else I can help you with?"), commands, cmdQuit + 1) end $game_temp.clear_mart_prices end diff --git a/Data/Scripts/016_UI/022_UI_PurifyChamber.rb b/Data/Scripts/016_UI/022_UI_PurifyChamber.rb index f0e0fc95a..1b22592ec 100644 --- a/Data/Scripts/016_UI/022_UI_PurifyChamber.rb +++ b/Data/Scripts/016_UI/022_UI_PurifyChamber.rb @@ -72,7 +72,7 @@ class PurifyChamberSet end def shadow=(value) - if value == nil || value.shadowPokemon? + if value.nil? || value.shadowPokemon? @shadow = value end end @@ -123,7 +123,7 @@ class PurifyChamberSet def insertAfter(index, value) return if self.length >= PurifyChamber::SETSIZE return if index < 0 || index >= PurifyChamber::SETSIZE - unless value && value.shadowPokemon? + unless value&.shadowPokemon? @list.insert(index + 1, value) @list.compact! @facing += 1 if @facing > index && value != nil @@ -133,7 +133,7 @@ class PurifyChamberSet def insertAt(index, value) return if index < 0 || index >= PurifyChamber::SETSIZE - unless value && value.shadowPokemon? + unless value&.shadowPokemon? @list[index] = value @list.compact! @facing = [[@facing, @list.length - 1].min, 0].max @@ -220,7 +220,7 @@ class PurifyChamber end def [](chamber, slot = nil) - if slot == nil + if slot.nil? return @sets[chamber] end return nil if chamber < 0 || chamber >= NUMSETS @@ -249,13 +249,11 @@ class PurifyChamber def update # called each step NUMSETS.times do |set| # If a shadow Pokemon and a regular Pokemon are on the same set - if @sets[set].shadow - if @sets[set].shadow.heart_gauge > 0 - flow = self.chamberFlow(set) - @sets[set].shadow.adjustHeart(-flow) - if isPurifiable?(set) - pbMessage(_INTL("Your {1} in the Purify Chamber is ready for purification!", @sets[set].shadow.name)) - end + if @sets[set].shadow && @sets[set].shadow.heart_gauge > 0 + flow = self.chamberFlow(set) + @sets[set].shadow.adjustHeart(-flow) + if isPurifiable?(set) + pbMessage(_INTL("Your {1} in the Purify Chamber is ready for purification!", @sets[set].shadow.name)) end end end @@ -363,7 +361,7 @@ class PurifyChamberScreen @scene.pbDisplay(_INTL("Can't place an egg there.")) return false end - if (position == 0) + if position == 0 if pkmn.shadowPokemon? # Remove from storage and place in set oldpkmn = PurifyChamberHelper.pbGetPokemon(@chamber, position) @@ -378,7 +376,7 @@ class PurifyChamberScreen @scene.pbDisplay(_INTL("Only a Shadow Pokémon can go there.")) return false end - elsif (position >= 1) + elsif position >= 1 if pkmn.shadowPokemon? @scene.pbDisplay(_INTL("Can't place a Shadow Pokémon there.")) return false @@ -454,12 +452,12 @@ class PurifyChamberScreen if choice == 0 if heldpkmn if pbPlace(heldpkmn, cmd[1]) # calls place or shift as appropriate - if !curpkmn + if curpkmn + heldpkmn = curpkmn # Pokemon was shifted + else pbOnPlace(heldpkmn) @scene.pbPositionHint(PurifyChamberHelper.adjustOnInsert(cmd[1])) heldpkmn = nil # Pokemon was placed - else - heldpkmn = curpkmn # Pokemon was shifted end end else @@ -498,14 +496,14 @@ class PurifyChamberScreen if pos newpkmn = $PokemonStorage[pos[0], pos[1]] if newpkmn - if (newpkmn.shadowPokemon?) != (curpkmn.shadowPokemon?) - @scene.pbDisplay(_INTL("That Pokémon can't be placed there.")) - else + if (newpkmn.shadowPokemon?) == (curpkmn.shadowPokemon?) @scene.pbReplace(cmd, pos) PurifyChamberHelper.pbSetPokemon(@chamber, cmd[1], newpkmn) $PokemonStorage[pos[0], pos[1]] = curpkmn @scene.pbRefresh pbOnPlace(curpkmn) + else + @scene.pbDisplay(_INTL("That Pokémon can't be placed there.")) end end end @@ -920,12 +918,12 @@ class PurifyChamberSetView < SpriteWrapper pos += 1 if button == Input::UP pos = nil if button == Input::RIGHT end - if pos != nil + if pos.nil? + @cursor = 0 + else pos -= (pos / points).floor * points # modulus pos *= 2 if @chamber.setCount(@set) == PurifyChamber::SETSIZE @cursor = pos + 1 - else - @cursor = 0 end end if @cursor != oldcursor @@ -1058,7 +1056,7 @@ class PurifyChamberSetView < SpriteWrapper def update super @__sprites.each do |sprite| - sprite.update if sprite + sprite&.update end @flows.each do |flow| flow.update @@ -1070,7 +1068,7 @@ class PurifyChamberSetView < SpriteWrapper def dispose @__sprites.each do |sprite| - sprite.dispose if sprite + sprite&.dispose end @flows.each do |flow| flow.dispose diff --git a/Data/Scripts/016_UI/023_UI_MysteryGift.rb b/Data/Scripts/016_UI/023_UI_MysteryGift.rb index b5c0554f7..434140398 100644 --- a/Data/Scripts/016_UI/023_UI_MysteryGift.rb +++ b/Data/Scripts/016_UI/023_UI_MysteryGift.rb @@ -42,7 +42,7 @@ def pbEditMysteryGift(type, item, id = 0, giftname = "") end elsif type > 0 # Item params = ChooseNumberParams.new - params.setRange(1, 99999) + params.setRange(1, 99_999) params.setDefaultValue(type) params.setCancelValue(0) loop do @@ -67,7 +67,7 @@ def pbEditMysteryGift(type, item, id = 0, giftname = "") idlist.push(i[0]) end params = ChooseNumberParams.new - params.setRange(0, 99999) + params.setRange(0, 99_999) params.setDefaultValue(id) params.setCancelValue(0) loop do @@ -99,9 +99,7 @@ end def pbCreateMysteryGift(type, item) gift = pbEditMysteryGift(type, item) - if !gift - pbMessage(_INTL("Didn't create a gift.")) - else + if gift begin if safeExists?("MysteryGiftMaster.txt") master = IO.read("MysteryGiftMaster.txt") @@ -116,6 +114,8 @@ def pbCreateMysteryGift(type, item) rescue pbMessage(_INTL("Couldn't save the gift to MysteryGiftMaster.txt.")) end + else + pbMessage(_INTL("Didn't create a gift.")) end end diff --git a/Data/Scripts/016_UI/024_UI_TextEntry.rb b/Data/Scripts/016_UI/024_UI_TextEntry.rb index 9da314417..8c5e9129d 100644 --- a/Data/Scripts/016_UI/024_UI_TextEntry.rb +++ b/Data/Scripts/016_UI/024_UI_TextEntry.rb @@ -193,7 +193,7 @@ class PokemonEntryScene end @sprites["helpwindow"].update @sprites["entry"].update - @sprites["subject"].update if @sprites["subject"] + @sprites["subject"]&.update end Input.update return ret @@ -207,7 +207,7 @@ class PokemonEntryScene @sprites["helpwindow"].update @sprites["entry"].update @sprites["entry2"].update - @sprites["subject"].update if @sprites["subject"] + @sprites["subject"]&.update if Input.trigger?(Input::USE) index = @sprites["entry2"].command if index == -3 # Confirm text @@ -741,7 +741,7 @@ class PokemonEntryScene2 def pbEndScene pbFadeOutAndHide(@sprites) { pbUpdate } @bitmaps.each do |bitmap| - bitmap.dispose if bitmap + bitmap&.dispose end @bitmaps.clear pbDisposeSpriteHash(@sprites) diff --git a/Data/Scripts/017_Minigames/002_Minigame_TripleTriad.rb b/Data/Scripts/017_Minigames/002_Minigame_TripleTriad.rb index 90a96667d..3615342da 100644 --- a/Data/Scripts/017_Minigames/002_Minigame_TripleTriad.rb +++ b/Data/Scripts/017_Minigames/002_Minigame_TripleTriad.rb @@ -67,7 +67,7 @@ class TriadCard ret *= (@north + @east + @south + @west) ret /= 10 # Ranges from 2 to 24,000 # Quantize prices to the next highest "unit" - if ret > 10000 + if ret > 10_000 ret = (1 + (ret / 1000)) * 1000 elsif ret > 5000 ret = (1 + (ret / 500)) * 500 @@ -280,7 +280,7 @@ class TriadScene pbUpdate command.update if command.index != index - preview.bitmap.dispose if preview.bitmap + preview.bitmap&.dispose if command.index < cardStorage.length item = cardStorage[command.index] preview.bitmap = TriadCard.new(item[0]).createBitmap(1) @@ -308,7 +308,7 @@ class TriadScene else pbPlayDecisionSE sprite = @sprites["player#{chosenCards.length}"] - sprite.bitmap.dispose if sprite.bitmap + sprite.bitmap&.dispose @cardBitmaps[chosenCards.length] = TriadCard.new(item[0]).createBitmap(1) sprite.bitmap = @cardBitmaps[chosenCards.length] chosenCards.push(item[0]) @@ -340,7 +340,7 @@ class TriadScene end end command.dispose - preview.bitmap.dispose if preview.bitmap + preview.bitmap&.dispose preview.dispose return chosenCards end @@ -525,7 +525,7 @@ class TriadScene sprite = @sprites["opponent#{@opponentCardIndexes[i]}"] if i == cardIndex @opponentCardBitmaps[@opponentCardIndexes[i]] = triadCard.createBitmap(2) - sprite.bitmap.dispose if sprite.bitmap + sprite.bitmap&.dispose sprite.bitmap = @opponentCardBitmaps[@opponentCardIndexes[i]] sprite.x = (Graphics.width / 2) - 118 + (position[0] * 78) sprite.y = 36 + (position[1] * 94) @@ -555,7 +555,7 @@ class TriadScene y = i / @battle.width if @boardSprites[i] owner = @battle.getOwner(x, y) - @boardSprites[i].bitmap.dispose if @boardSprites[i].bitmap + @boardSprites[i].bitmap&.dispose @boardSprites[i].bitmap = @boardCards[i].createBitmap(owner) end end @@ -653,7 +653,7 @@ class TriadScreen panels[2] = (@wrapAround ? 0 : @width - 1) if panels[2] > @width - 1 # right panels[5] = (@wrapAround ? @height - 1 : 0) if panels[5] < 0 # top panels[7] = (@wrapAround ? 0 : @height - 1) if panels[7] > @height - 1 # bottom - attacker = attackerParam != nil ? attackerParam : @board[(y * @width) + x] + attacker = attackerParam.nil? ? @board[(y * @width) + x] : attackerParam flips = [] return nil if attackerParam != nil && @board[(y * @width) + x].owner != 0 return nil if !attacker.card || attacker.owner == 0 @@ -678,7 +678,7 @@ class TriadScreen end if attack > defense || (attack == defense && @sameWins) flips.push([defenderX, defenderY]) - if attackerParam == nil + if attackerParam.nil? defender.owner = attacker.owner if @sameWins # Combo with the "sameWins" rule @@ -704,7 +704,7 @@ class TriadScreen raise _INTL("Minimum level must be 0 through 9.") if minLevel < 0 || minLevel > 9 raise _INTL("Maximum level must be 0 through 9.") if maxLevel < 0 || maxLevel > 9 raise _INTL("Maximum level shouldn't be less than the minimum level.") if maxLevel < minLevel - if rules && rules.is_a?(Array) && rules.length > 0 + if rules.is_a?(Array) && rules.length > 0 rules.each do |rule| @sameWins = true if rule == "samewins" @openHand = true if rule == "openhand" @@ -762,7 +762,7 @@ class TriadScreen cards = @scene.pbChooseTriadCard(@triadCards) end # Set the opponent's cards. - if oppdeck && oppdeck.is_a?(Array) && oppdeck.length == self.maxCards # Preset + if oppdeck.is_a?(Array) && oppdeck.length == self.maxCards # Preset opponentCards = [] oppdeck.each do |i| species_data = GameData::Species.try_get(i) @@ -812,7 +812,7 @@ class TriadScreen cardIndex = 0 if playerTurn # Player's turn - while !position + until position cardIndex = @scene.pbPlayerChooseCard(cards.length) triadCard = TriadCard.new(cards[cardIndex]) position = @scene.pbPlayerPlaceCard(cardIndex) @@ -1099,7 +1099,7 @@ def pbBuyTriads cmdwindow.update goldwindow.update if commands[cmdwindow.index][3] != olditem - preview.bitmap.dispose if preview.bitmap + preview.bitmap&.dispose preview.bitmap = TriadCard.new(commands[cmdwindow.index][3]).createBitmap(1) olditem = commands[cmdwindow.index][3] end @@ -1143,7 +1143,7 @@ def pbBuyTriads end cmdwindow.dispose goldwindow.dispose - preview.bitmap.dispose if preview.bitmap + preview.bitmap&.dispose preview.dispose Graphics.frame_reset # Scroll right before showing screen @@ -1182,7 +1182,7 @@ def pbSellTriads olditem = $PokemonGlobal.triads.get_item(cmdwindow.index) done = false Graphics.frame_reset - while !done + until done loop do Graphics.update Input.update @@ -1191,7 +1191,7 @@ def pbSellTriads goldwindow.update item = $PokemonGlobal.triads.get_item(cmdwindow.index) if olditem != item - preview.bitmap.dispose if preview.bitmap + preview.bitmap&.dispose if item preview.bitmap = TriadCard.new(item).createBitmap(1) end @@ -1249,7 +1249,7 @@ def pbSellTriads end cmdwindow.dispose goldwindow.dispose - preview.bitmap.dispose if preview.bitmap + preview.bitmap&.dispose preview.dispose Graphics.frame_reset # Scroll right before showing screen @@ -1276,28 +1276,23 @@ def pbTriadList sprite.z = 99999 done = false lastIndex = -1 - while !done + until done loop do Graphics.update Input.update cmdwindow.update if lastIndex != cmdwindow.index - sprite.bitmap.dispose if sprite.bitmap + sprite.bitmap&.dispose if cmdwindow.index < $PokemonGlobal.triads.length sprite.bitmap = TriadCard.new($PokemonGlobal.triads.get_item(cmdwindow.index)).createBitmap(1) end lastIndex = cmdwindow.index end - if Input.trigger?(Input::BACK) + if Input.trigger?(Input::BACK) || + (Input.trigger?(Input::USE) && cmdwindow.index >= $PokemonGlobal.triads.length) done = true break end - if Input.trigger?(Input::USE) - if cmdwindow.index >= $PokemonGlobal.triads.length - done = true - break - end - end end end cmdwindow.dispose diff --git a/Data/Scripts/017_Minigames/003_Minigame_SlotMachine.rb b/Data/Scripts/017_Minigames/003_Minigame_SlotMachine.rb index a8e3c7bf2..212f942df 100644 --- a/Data/Scripts/017_Minigames/003_Minigame_SlotMachine.rb +++ b/Data/Scripts/017_Minigames/003_Minigame_SlotMachine.rb @@ -180,7 +180,7 @@ class SlotMachineScene Graphics.update Input.update update - @sprites["window2"].bitmap.clear if @sprites["window2"].bitmap + @sprites["window2"].bitmap&.clear @sprites["window1"].setBitmap(sprintf("Graphics/Pictures/Slot Machine/win")) @sprites["window1"].src_rect.set(152 * ((frame / timePerFrame) % 4), 0, 152, 208) if bonus > 0 @@ -228,7 +228,7 @@ class SlotMachineScene Graphics.update Input.update update - @sprites["window2"].bitmap.clear if @sprites["window2"].bitmap + @sprites["window2"].bitmap&.clear @sprites["window1"].setBitmap(sprintf("Graphics/Pictures/Slot Machine/lose")) @sprites["window1"].src_rect.set(152 * ((frame / timePerFrame) % 2), 0, 152, 208) frame += 1 @@ -283,8 +283,8 @@ class SlotMachineScene Graphics.update Input.update update - @sprites["window1"].bitmap.clear if @sprites["window1"].bitmap - @sprites["window2"].bitmap.clear if @sprites["window2"].bitmap + @sprites["window1"].bitmap&.clear + @sprites["window2"].bitmap&.clear if @sprites["credit"].score == Settings::MAX_COINS pbMessage(_INTL("You've got {1} Coins.", Settings::MAX_COINS.to_s_formatted)) break diff --git a/Data/Scripts/017_Minigames/004_Minigame_VoltorbFlip.rb b/Data/Scripts/017_Minigames/004_Minigame_VoltorbFlip.rb index b041609a6..f70e97cc0 100644 --- a/Data/Scripts/017_Minigames/004_Minigame_VoltorbFlip.rb +++ b/Data/Scripts/017_Minigames/004_Minigame_VoltorbFlip.rb @@ -56,19 +56,15 @@ class VoltorbFlip # Randomize the values a little 25.times do |i| temp = squareValues[i] - if squareValues[i] > 1 - if rand(10) > 8 - total /= squareValues[i] - squareValues[i] -= 1 - total *= squareValues[i] - end + if squareValues[i] > 1 && rand(10) == 0 + total /= squareValues[i] + squareValues[i] -= 1 + total *= squareValues[i] end - if total < @levelRanges[@level - 1][0] - if squareValues[i] > 0 - total /= squareValues[i] - squareValues[i] = temp - total *= squareValues[i] - end + if total < @levelRanges[@level - 1][0] && squareValues[i] > 0 + total /= squareValues[i] + squareValues[i] = temp + total *= squareValues[i] end end # Populate @squares array @@ -263,7 +259,7 @@ class VoltorbFlip end end (@marks.length + 1).times do |i| - if @marks[i] == nil + if @marks[i].nil? @marks[i] = [@directory + "tiles", (@index[0] * 64) + 128, @index[1] * 64, 256, 0, 64, 64] elsif @marks[i][1] == (@index[0] * 64) + 128 && @marks[i][2] == @index[1] * 64 @marks.delete_at(i) diff --git a/Data/Scripts/017_Minigames/005_Minigame_Lottery.rb b/Data/Scripts/017_Minigames/005_Minigame_Lottery.rb index 647fb9338..79c7eef7a 100644 --- a/Data/Scripts/017_Minigames/005_Minigame_Lottery.rb +++ b/Data/Scripts/017_Minigames/005_Minigame_Lottery.rb @@ -6,7 +6,7 @@ def pbSetLotteryNumber(variable = 1) t = pbGetTimeNow hash = t.day + (t.month << 5) + (t.year << 9) srand(hash) # seed RNG with fixed value depending on date - lottery = rand(65536) # get a number + lottery = rand(65_536) # get a number srand # reseed RNG pbSet(variable, sprintf("%05d", lottery)) end diff --git a/Data/Scripts/017_Minigames/006_Minigame_Mining.rb b/Data/Scripts/017_Minigames/006_Minigame_Mining.rb index e78f91283..f897d012b 100644 --- a/Data/Scripts/017_Minigames/006_Minigame_Mining.rb +++ b/Data/Scripts/017_Minigames/006_Minigame_Mining.rb @@ -268,7 +268,7 @@ class MiningGameScene rnd -= ITEMS[i][1] if rnd < 0 if pbNoDuplicateItems(ITEMS[i][0]) - while !added + until added provx = rand(BOARD_WIDTH - ITEMS[i][4] + 1) provy = rand(BOARD_HEIGHT - ITEMS[i][5] + 1) if pbCheckOverlaps(false, provx, provy, ITEMS[i][4], ITEMS[i][5], ITEMS[i][6]) diff --git a/Data/Scripts/018_Alternate battle modes/002_Battle Frontier rules/002_Challenge_Rulesets.rb b/Data/Scripts/018_Alternate battle modes/002_Battle Frontier rules/002_Challenge_Rulesets.rb index 0622a17bb..2c038d47e 100644 --- a/Data/Scripts/018_Alternate battle modes/002_Battle Frontier rules/002_Challenge_Rulesets.rb +++ b/Data/Scripts/018_Alternate battle modes/002_Battle Frontier rules/002_Challenge_Rulesets.rb @@ -197,13 +197,13 @@ class PokemonRuleSet error.push(_INTL("{1} Pokémon are needed.", self.minLength)) if error && self.minLength > 1 return false elsif team.length > self.maxLength - error.push(_INTL("No more than {1} Pokémon may enter.", self.maxLength)) if error + error&.push(_INTL("No more than {1} Pokémon may enter.", self.maxLength)) return false end team.each do |pkmn| next if isPokemonValid?(pkmn) if pkmn - error.push(_INTL("{1} is not allowed.", pkmn.name)) if error + error&.push(_INTL("{1} is not allowed.", pkmn.name)) elsif error error.push(_INTL("This team is not allowed.")) end @@ -211,12 +211,12 @@ class PokemonRuleSet end @teamRules.each do |rule| next if rule.isValid?(team) - error.push(rule.errorMessage) if error + error&.push(rule.errorMessage) return false end @subsetRules.each do |rule| next if rule.isValid?(team) - error.push(rule.errorMessage) if error + error&.push(rule.errorMessage) return false end return true diff --git a/Data/Scripts/018_Alternate battle modes/002_Battle Frontier rules/003_Challenge_EntryRestrictions.rb b/Data/Scripts/018_Alternate battle modes/002_Battle Frontier rules/003_Challenge_EntryRestrictions.rb index 8c5e69214..a53c9d849 100644 --- a/Data/Scripts/018_Alternate battle modes/002_Battle Frontier rules/003_Challenge_EntryRestrictions.rb +++ b/Data/Scripts/018_Alternate battle modes/002_Battle Frontier rules/003_Challenge_EntryRestrictions.rb @@ -153,7 +153,7 @@ end #=============================================================================== class AblePokemonRestriction def isValid?(pkmn) - return pkmn && pkmn.able? + return pkmn&.able? end end diff --git a/Data/Scripts/018_Alternate battle modes/002_BugContest.rb b/Data/Scripts/018_Alternate battle modes/002_BugContest.rb index f19296d7f..e843f0286 100644 --- a/Data/Scripts/018_Alternate battle modes/002_BugContest.rb +++ b/Data/Scripts/018_Alternate battle modes/002_BugContest.rb @@ -24,7 +24,7 @@ class BugContestState def pbContestHeld? return false if !@lastContest timenow = pbGetTimeNow - return timenow.to_i - @lastContest < 86400 + return timenow.to_i - @lastContest < 86_400 end def expired? @@ -193,13 +193,13 @@ class BugContestState @otherparty.each do |poke| $player.party.push(poke) end - if !interrupted + if interrupted + @ended = false + else if @lastPokemon pbNicknameAndStore(@lastPokemon) end @ended = true - else - @ended = false end $stats.bug_contest_wins += 1 if place == 0 @lastPokemon = nil @@ -302,22 +302,18 @@ Events.onMapSceneChange += proc { |_sender, e| Events.onMapUpdate += proc { |_sender, _e| if !$game_player.move_route_forcing && !pbMapInterpreterRunning? && - !$game_temp.message_window_showing - if pbBugContestState.expired? - pbMessage(_INTL("ANNOUNCER: BEEEEEP!")) - pbMessage(_INTL("Time's up!")) - pbBugContestState.pbStartJudging - end + !$game_temp.message_window_showing && pbBugContestState.expired? + pbMessage(_INTL("ANNOUNCER: BEEEEEP!")) + pbMessage(_INTL("Time's up!")) + pbBugContestState.pbStartJudging end } Events.onMapChanging += proc { |_sender, e| newmapID = e[0] - if pbInBugContest? - if pbBugContestState.pbOffLimits?(newmapID) - # Clear bug contest if player flies/warps/teleports out of the contest - pbBugContestState.pbEnd(true) - end + if pbInBugContest? && pbBugContestState.pbOffLimits?(newmapID) + # Clear bug contest if player flies/warps/teleports out of the contest + pbBugContestState.pbEnd(true) end } diff --git a/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/001_ChallengeGenerator_Data.rb b/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/001_ChallengeGenerator_Data.rb index 1770a0bdb..4ed702394 100644 --- a/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/001_ChallengeGenerator_Data.rb +++ b/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/001_ChallengeGenerator_Data.rb @@ -293,10 +293,7 @@ def pbWriteCup(id, rules) end end cmd = 0 - if trlists.length != 0 - cmd = pbMessage(_INTL("Generate Pokémon teams for this challenge?"), - [_INTL("NO"), _INTL("YES, USE EXISTING"), _INTL("YES, USE NEW")], 1) - else + if trlists.length == 0 cmd = pbMessage(_INTL("Generate Pokémon teams for this challenge?"), [_INTL("YES"), _INTL("NO")], 2) case cmd @@ -305,6 +302,9 @@ def pbWriteCup(id, rules) when 1 cmd = 0 end + else + cmd = pbMessage(_INTL("Generate Pokémon teams for this challenge?"), + [_INTL("NO"), _INTL("YES, USE EXISTING"), _INTL("YES, USE NEW")], 1) end return if cmd == 0 # No case cmd diff --git a/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/002_ChallengeGenerator_Pokemon.rb b/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/002_ChallengeGenerator_Pokemon.rb index 2575cb55d..4c259c441 100644 --- a/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/002_ChallengeGenerator_Pokemon.rb +++ b/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/002_ChallengeGenerator_Pokemon.rb @@ -284,18 +284,20 @@ def pbRandomPokemonFromRule(rules, trainer) newmoves.push(m) if m && !newmoves.include?(m) end if (newmoves.include?(spitup) || newmoves.include?(swallow)) && - !newmoves.include?(stockpile) - next unless sketch + !newmoves.include?(stockpile) && !sketch + next end if (!newmoves.include?(spitup) && !newmoves.include?(swallow)) && - newmoves.include?(stockpile) - next unless sketch + newmoves.include?(stockpile) && !sketch + next end - if newmoves.include?(sleeptalk) && !newmoves.include?(rest) - next unless (sketch || !moves.include?(rest)) && rand(100) < 20 + if newmoves.include?(sleeptalk) && !newmoves.include?(rest) && + !((sketch || !moves.include?(rest)) && rand(100) < 20) + next end - if newmoves.include?(snore) && !newmoves.include?(rest) - next unless (sketch || !moves.include?(rest)) && rand(100) < 20 + if newmoves.include?(snore) && !newmoves.include?(rest) && + !((sketch || !moves.include?(rest)) && rand(100) < 20) + next end totalbasedamage = 0 hasPhysical = false @@ -310,13 +312,13 @@ def pbRandomPokemonFromRule(rules, trainer) hasSpecial = true if d.category == 1 end end - if !hasPhysical && ev.include?(:ATTACK) + if !hasPhysical && ev.include?(:ATTACK) && rand(100) < 80 # No physical attack, but emphasizes Attack - next if rand(100) < 80 + next end - if !hasSpecial && ev.include?(:SPECIAL_ATTACK) + if !hasSpecial && ev.include?(:SPECIAL_ATTACK) && rand(100) < 80 # No special attack, but emphasizes Special Attack - next if rand(100) < 80 + next end r = rand(10) next if r > 6 && totalbasedamage > 180 diff --git a/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/004_ChallengeGenerator_BattleSim.rb b/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/004_ChallengeGenerator_BattleSim.rb index 092ec62f8..3ed6ebbcd 100644 --- a/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/004_ChallengeGenerator_BattleSim.rb +++ b/Data/Scripts/018_Alternate battle modes/003_Battle Frontier generator/004_ChallengeGenerator_BattleSim.rb @@ -184,15 +184,15 @@ class PlayerRating # https://www.smogon.com/forums/threads/make-sense-of-your-shoddy-battle-rating.55764/ otherRating = 1500.0 otherDeviation = 350.0 - s = Math.sqrt(100000.0 + (@deviation * @deviation) + (otherDeviation * otherDeviation)) + s = Math.sqrt(100_000.0 + (@deviation * @deviation) + (otherDeviation * otherDeviation)) g = 10.0**((otherRating - @rating) * 0.79 / s) @estimatedRating = (1.0 / (1.0 + g)) * 100.0 # Percent chance that I win against opponent else # GLIXARE method rds = @deviation * @deviation - sqr = Math.sqrt(15.905694331435 * (rds + 221781.21786254)) + sqr = Math.sqrt(15.905694331435 * (rds + 221_781.21786254)) inner = (1500.0 - @rating) * Math::PI / sqr - @estimatedRating = ((10000.0 / (1.0 + (10.0**inner))) + 0.5) / 100.0 + @estimatedRating = ((10_000.0 / (1.0 + (10.0**inner))) + 0.5) / 100.0 end return @estimatedRating end @@ -296,7 +296,7 @@ class PlayerRating h2 += 0.5 * squVariance * e * (squDevplusVar - e) / (squD * d) x1 = x0 x0 -= h1 / h2 - break if ((x1 - x0).abs < 0.000001) + break if (x1 - x0).abs < 0.000001 } return Math.exp(x0 / 2.0) end @@ -373,13 +373,7 @@ end #=============================================================================== def pbRuledBattle(team1, team2, rule) decision = 0 - if rand(100) != 0 - party1 = [] - party2 = [] - team1.length.times { |i| party1.push(team1[i]) } - team2.length.times { |i| party2.push(team2[i]) } - decision = pbDecideWinner(party1, party2, team1.rating, team2.rating) - else + if rand(100) == 0 level = rule.ruleset.suggestedLevel t_type = GameData::TrainerType.keys.first trainer1 = NPCTrainer.new("PLAYER1", t_type) @@ -420,6 +414,12 @@ def pbRuledBattle(team1, team2, rule) p.heal p.item = items2[i] end + else + party1 = [] + party2 = [] + team1.length.times { |i| party1.push(team1[i]) } + team2.length.times { |i| party2.push(team2[i]) } + decision = pbDecideWinner(party1, party2, team1.rating, team2.rating) end case decision when 1 # Team 1 wins diff --git a/Data/Scripts/019_Utilities/001_Utilities.rb b/Data/Scripts/019_Utilities/001_Utilities.rb index 19bfb82f0..49dcfe189 100644 --- a/Data/Scripts/019_Utilities/001_Utilities.rb +++ b/Data/Scripts/019_Utilities/001_Utilities.rb @@ -130,45 +130,41 @@ end #=============================================================================== # Event utilities #=============================================================================== -def pbTimeEvent(variableNumber, secs = 86400) - if variableNumber && variableNumber >= 0 - if $game_variables - secs = 0 if secs < 0 - timenow = pbGetTimeNow - $game_variables[variableNumber] = [timenow.to_f, secs] - $game_map.refresh if $game_map - end - end +def pbTimeEvent(variableNumber, secs = 86_400) + return if !$game_variables + return if !variableNumber || variableNumber < 0 + secs = 0 if secs < 0 + timenow = pbGetTimeNow + $game_variables[variableNumber] = [timenow.to_f, secs] + $game_map&.refresh end def pbTimeEventDays(variableNumber, days = 0) - if variableNumber && variableNumber >= 0 - if $game_variables - days = 0 if days < 0 - timenow = pbGetTimeNow - time = timenow.to_f - expiry = (time % 86400.0) + (days * 86400.0) - $game_variables[variableNumber] = [time, expiry - time] - $game_map.refresh if $game_map - end - end + return if !$game_variables + return if !variableNumber || variableNumber < 0 + days = 0 if days < 0 + timenow = pbGetTimeNow + time = timenow.to_f + expiry = (time % 86_400.0) + (days * 86_400.0) + $game_variables[variableNumber] = [time, expiry - time] + $game_map&.refresh end def pbTimeEventValid(variableNumber) - retval = false - if variableNumber && variableNumber >= 0 && $game_variables - value = $game_variables[variableNumber] - if value.is_a?(Array) - timenow = pbGetTimeNow - retval = (timenow.to_f - value[0] > value[1]) # value[1] is age in seconds - retval = false if value[1] <= 0 # zero age - end - if !retval - $game_variables[variableNumber] = 0 - $game_map.refresh if $game_map - end + return false if !$game_variables + return false if !variableNumber || variableNumber < 0 + ret = false + value = $game_variables[variableNumber] + if value.is_a?(Array) + timenow = pbGetTimeNow + ret = (timenow.to_f - value[0] > value[1]) # value[1] is age in seconds + ret = false if value[1] <= 0 # zero age end - return retval + if !ret + $game_variables[variableNumber] = 0 + $game_map&.refresh + end + return ret end def pbExclaim(event, id = Settings::EXCLAMATION_ANIMATION_ID, tinting = false) @@ -184,7 +180,7 @@ def pbExclaim(event, id = Settings::EXCLAMATION_ANIMATION_ID, tinting = false) else sprite = $scene.spriteset.addUserAnimation(id, event.x, event.y, tinting, 2) end - while !sprite.disposed? + until sprite.disposed? Graphics.update Input.update pbUpdateSceneMap @@ -408,7 +404,7 @@ def pbMoveTutorAnnotations(move, movelist = nil) ret[i] = _INTL("LEARNED") else species = pkmn.species - if movelist && movelist.any? { |j| j == species } + if movelist&.any? { |j| j == species } # Checked data from movelist given in parameter ret[i] = _INTL("ABLE") elsif pkmn.compatible_with_move?(move) diff --git a/Data/Scripts/019_Utilities/002_Utilities_Pokemon.rb b/Data/Scripts/019_Utilities/002_Utilities_Pokemon.rb index 79f50e9bb..5306ee019 100644 --- a/Data/Scripts/019_Utilities/002_Utilities_Pokemon.rb +++ b/Data/Scripts/019_Utilities/002_Utilities_Pokemon.rb @@ -6,12 +6,11 @@ def pbBoxesFull? end def pbNickname(pkmn) + return if $PokemonSystem.givenicknames != 0 species_name = pkmn.speciesName - if $PokemonSystem.givenicknames == 0 - if pbConfirmMessage(_INTL("Would you like to give a nickname to {1}?", species_name)) - pkmn.name = pbEnterPokemonName(_INTL("{1}'s nickname?", species_name), - 0, Pokemon::MAX_NAME_SIZE, "", pkmn) - end + if pbConfirmMessage(_INTL("Would you like to give a nickname to {1}?", species_name)) + pkmn.name = pbEnterPokemonName(_INTL("{1}'s nickname?", species_name), + 0, Pokemon::MAX_NAME_SIZE, "", pkmn) end end @@ -210,22 +209,22 @@ def pbSize(pkmn) m = pkmn.personalID & 0xFF n = (pkmn.personalID >> 8) & 0xFF s = ((((ativ ^ dfiv) * hpiv) ^ m) * 256) + (((saiv ^ sdiv) * spiv) ^ n) - xyz = [1700, 1, 65510] + xyz = [1700, 1, 65_510] case s - when 0...10 then xyz = [ 290, 1, 0] - when 10...110 then xyz = [ 300, 1, 10] - when 110...310 then xyz = [ 400, 2, 110] - when 310...710 then xyz = [ 500, 4, 310] - when 710...2710 then xyz = [ 600, 20, 710] - when 2710...7710 then xyz = [ 700, 50, 2710] - when 7710...17710 then xyz = [ 800, 100, 7710] - when 17710...32710 then xyz = [ 900, 150, 17710] - when 32710...47710 then xyz = [1000, 150, 32710] - when 47710...57710 then xyz = [1100, 100, 47710] - when 57710...62710 then xyz = [1200, 50, 57710] - when 62710...64710 then xyz = [1300, 20, 62710] - when 64710...65210 then xyz = [1400, 5, 64710] - when 65210...65410 then xyz = [1500, 2, 65210] + when 0...10 then xyz = [ 290, 1, 0] + when 10...110 then xyz = [ 300, 1, 10] + when 110...310 then xyz = [ 400, 2, 110] + when 310...710 then xyz = [ 500, 4, 310] + when 710...2710 then xyz = [ 600, 20, 710] + when 2710...7710 then xyz = [ 700, 50, 2710] + when 7710...17_710 then xyz = [ 800, 100, 7710] + when 17_710...32_710 then xyz = [ 900, 150, 17_710] + when 32_710...47_710 then xyz = [1000, 150, 32_710] + when 47_710...57_710 then xyz = [1100, 100, 47_710] + when 57_710...62_710 then xyz = [1200, 50, 57_710] + when 62_710...64_710 then xyz = [1300, 20, 62_710] + when 64_710...65_210 then xyz = [1400, 5, 64_710] + when 65_210...65_410 then xyz = [1500, 2, 65_210] end return ((((s - xyz[2]) / xyz[1]) + xyz[0]).floor * baseheight / 10).floor end diff --git a/Data/Scripts/020_Debug/001_Editor screens/001_EditorScreens.rb b/Data/Scripts/020_Debug/001_Editor screens/001_EditorScreens.rb index c7589e28e..321d943c1 100644 --- a/Data/Scripts/020_Debug/001_Editor screens/001_EditorScreens.rb +++ b/Data/Scripts/020_Debug/001_Editor screens/001_EditorScreens.rb @@ -361,13 +361,11 @@ def pbTrainerTypeEditor if tr_type case button when Input::ACTION - if tr_type.is_a?(Symbol) - if pbConfirmMessageSerious("Delete this trainer type?") - GameData::TrainerType::DATA.delete(tr_type) - GameData::TrainerType.save - pbConvertTrainerData - pbMessage(_INTL("The Trainer type was deleted.")) - end + if tr_type.is_a?(Symbol) && pbConfirmMessageSerious("Delete this trainer type?") + GameData::TrainerType::DATA.delete(tr_type) + GameData::TrainerType.save + pbConvertTrainerData + pbMessage(_INTL("The Trainer type was deleted.")) end when Input::USE if tr_type.is_a?(Symbol) @@ -502,13 +500,11 @@ def pbTrainerBattleEditor if trainer_id case button when Input::ACTION - if trainer_id.is_a?(Array) - if pbConfirmMessageSerious("Delete this trainer battle?") - tr_data = GameData::Trainer::DATA[trainer_id] - GameData::Trainer::DATA.delete(trainer_id) - modified = true - pbMessage(_INTL("The Trainer battle was deleted.")) - end + if trainer_id.is_a?(Array) && pbConfirmMessageSerious("Delete this trainer battle?") + tr_data = GameData::Trainer::DATA[trainer_id] + GameData::Trainer::DATA.delete(trainer_id) + modified = true + pbMessage(_INTL("The Trainer battle was deleted.")) end when Input::USE if trainer_id.is_a?(Array) # Edit existing trainer @@ -874,8 +870,8 @@ def pbItemEditor [_INTL("Name"), ItemNameProperty, _INTL("Name of this item as displayed by the game.")], [_INTL("NamePlural"), ItemNameProperty, _INTL("Plural name of this item as displayed by the game.")], [_INTL("Pocket"), PocketProperty, _INTL("Pocket in the Bag where this item is stored.")], - [_INTL("Price"), LimitProperty.new(999999), _INTL("Purchase price of this item.")], - [_INTL("SellPrice"), LimitProperty.new(999999), _INTL("Sell price of this item. If blank, is half the purchase price.")], + [_INTL("Price"), LimitProperty.new(999_999), _INTL("Purchase price of this item.")], + [_INTL("SellPrice"), LimitProperty.new(999_999), _INTL("Sell price of this item. If blank, is half the purchase price.")], [_INTL("Description"), StringProperty, _INTL("Description of this item")], [_INTL("FieldUse"), EnumProperty.new(field_use_array), _INTL("How this item can be used outside of battle.")], [_INTL("BattleUse"), EnumProperty.new(battle_use_array), _INTL("How this item can be used within a battle.")], @@ -887,13 +883,11 @@ def pbItemEditor if item case button when Input::ACTION - if item.is_a?(Symbol) - if pbConfirmMessageSerious("Delete this item?") - GameData::Item::DATA.delete(item) - GameData::Item.save - Compiler.write_items - pbMessage(_INTL("The item was deleted.")) - end + if item.is_a?(Symbol) && pbConfirmMessageSerious("Delete this item?") + GameData::Item::DATA.delete(item) + GameData::Item.save + Compiler.write_items + pbMessage(_INTL("The item was deleted.")) end when Input::USE if item.is_a?(Symbol) @@ -974,7 +968,7 @@ def pbItemEditorNew(default_name) pocket = PocketProperty.set("", 0) return if pocket == 0 # Choose a price - price = LimitProperty.new(999999).set(_INTL("Purchase price"), -1) + price = LimitProperty.new(999_999).set(_INTL("Purchase price"), -1) return if price == -1 # Choose a description description = StringProperty.set(_INTL("Description"), "") @@ -1030,7 +1024,7 @@ def pbPokemonEditor [_INTL("WildItemRare"), GameDataPoolProperty.new(:Item), _INTL("Item(s) rarely held by wild Pokémon of this species.")], [_INTL("EggGroup 1"), GameDataProperty.new(:EggGroup), _INTL("Compatibility group (egg group) for breeding purposes.")], [_INTL("EggGroup 2"), GameDataProperty.new(:EggGroup), _INTL("Compatibility group (egg group) for breeding purposes.")], - [_INTL("HatchSteps"), LimitProperty.new(99999), _INTL("Number of steps until an egg of this species hatches.")], + [_INTL("HatchSteps"), LimitProperty.new(99_999), _INTL("Number of steps until an egg of this species hatches.")], [_INTL("Incense"), ItemProperty, _INTL("Item needed to be held by a parent to produce an egg of this species.")], [_INTL("Offspring"), GameDataPoolProperty.new(:Species), _INTL("All possible species that an egg can be when breeding for an egg of this species (if blank, the egg can only be this species).")], [_INTL("Evolutions"), EvolutionsProperty.new, _INTL("Evolution paths of this species.")], @@ -1039,20 +1033,18 @@ def pbPokemonEditor [_INTL("Color"), GameDataProperty.new(:BodyColor), _INTL("Pokémon's body color.")], [_INTL("Shape"), GameDataProperty.new(:BodyShape), _INTL("Body shape of this species.")], [_INTL("Habitat"), GameDataProperty.new(:Habitat), _INTL("The habitat of this species.")], - [_INTL("Generation"), LimitProperty.new(99999), _INTL("The number of the generation the Pokémon debuted in.")], + [_INTL("Generation"), LimitProperty.new(99_999), _INTL("The number of the generation the Pokémon debuted in.")], [_INTL("Flags"), StringListProperty, _INTL("Words/phrases that distinguish this species from others.")] ] pbListScreenBlock(_INTL("Pokémon species"), SpeciesLister.new(0, false)) { |button, species| if species case button when Input::ACTION - if species.is_a?(Symbol) - if pbConfirmMessageSerious("Delete this species?") - GameData::Species::DATA.delete(species) - GameData::Species.save - Compiler.write_pokemon - pbMessage(_INTL("The species was deleted.")) - end + if species.is_a?(Symbol) && pbConfirmMessageSerious("Delete this species?") + GameData::Species::DATA.delete(species) + GameData::Species.save + Compiler.write_pokemon + pbMessage(_INTL("The species was deleted.")) end when Input::USE if species.is_a?(Symbol) @@ -1259,7 +1251,7 @@ def pbRegionalDexEditor(dex) case pbMessage(_INTL("Save changes?"), [_INTL("Yes"), _INTL("No"), _INTL("Cancel")], 3) when 0 # Save all changes to Dex - dex.slice!(-1) while !dex[-1] + dex.slice!(-1) until dex[-1] ret = dex break when 1 # Just quit diff --git a/Data/Scripts/020_Debug/001_Editor screens/002_EditorScreens_TerrainTags.rb b/Data/Scripts/020_Debug/001_Editor screens/002_EditorScreens_TerrainTags.rb index 3b184b755..b903f0979 100644 --- a/Data/Scripts/020_Debug/001_Editor screens/002_EditorScreens_TerrainTags.rb +++ b/Data/Scripts/020_Debug/001_Editor screens/002_EditorScreens_TerrainTags.rb @@ -48,7 +48,7 @@ class PokemonTilesetScene def load_tileset(id) @tileset = @tilesets_data[id] - @tilehelper.dispose if @tilehelper + @tilehelper&.dispose @tilehelper = TileDrawingHelper.fromTileset(@tileset) @x = 0 @y = 0 @@ -88,7 +88,7 @@ class PokemonTilesetScene TILES_PER_ROW.times do |xx| tile_id = tile_ID_from_coordinates(xx, @top_y + yy) terr = @tileset.terrain_tags[tile_id] - textpos.push(["#{terr}", (xx * TILE_SIZE) + (TILE_SIZE / 2), (yy * TILE_SIZE) - 6, 2, TEXT_COLOR, TEXT_SHADOW_COLOR]) + textpos.push([terr.to_s, (xx * TILE_SIZE) + (TILE_SIZE / 2), (yy * TILE_SIZE) - 6, 2, TEXT_COLOR, TEXT_SHADOW_COLOR]) end end pbDrawTextPositions(@sprites["overlay"].bitmap, textpos) @@ -188,9 +188,9 @@ class PokemonTilesetScene ] case pbShowCommands(nil, commands, -1) when 0 - update_cursor_position(0, 99999) + update_cursor_position(0, 99_999) when 1 - update_cursor_position(0, -99999) + update_cursor_position(0, -99_999) when 2 choose_tileset end diff --git a/Data/Scripts/020_Debug/001_Editor screens/003_EditorScreens_MapConnections.rb b/Data/Scripts/020_Debug/001_Editor screens/003_EditorScreens_MapConnections.rb index 69347db71..5c84bc977 100644 --- a/Data/Scripts/020_Debug/001_Editor screens/003_EditorScreens_MapConnections.rb +++ b/Data/Scripts/020_Debug/001_Editor screens/003_EditorScreens_MapConnections.rb @@ -50,7 +50,7 @@ class SelectionSprite < Sprite end def dispose - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose @othersprite = nil @sprite.dispose end @@ -234,8 +234,8 @@ class MapScreenScene otherdims = MapFactoryHelper.getMapDims(i) x1 = (thissprite.x - othersprite.x) / 4 y1 = (thissprite.y - othersprite.y) / 4 - if (x1 == otherdims[0] || x1 == -thisdims[0] || - y1 == otherdims[1] || y1 == -thisdims[1]) + if x1 == otherdims[0] || x1 == -thisdims[0] || + y1 == otherdims[1] || y1 == -thisdims[1] ret.push(i) end end diff --git a/Data/Scripts/020_Debug/001_Editor screens/004_EditorScreens_SpritePositioning.rb b/Data/Scripts/020_Debug/001_Editor screens/004_EditorScreens_SpritePositioning.rb index b355c1cd9..cc636fc0f 100644 --- a/Data/Scripts/020_Debug/001_Editor screens/004_EditorScreens_SpritePositioning.rb +++ b/Data/Scripts/020_Debug/001_Editor screens/004_EditorScreens_SpritePositioning.rb @@ -21,11 +21,11 @@ def pbAutoPositionAll metrics = GameData::SpeciesMetrics.get_species_form(sp.species, sp.form) bitmap1 = GameData::Species.sprite_bitmap(sp.species, sp.form, nil, nil, nil, true) bitmap2 = GameData::Species.sprite_bitmap(sp.species, sp.form) - if bitmap1 && bitmap1.bitmap # Player's y + if bitmap1&.bitmap # Player's y metrics.back_sprite[0] = 0 metrics.back_sprite[1] = (bitmap1.height - (findBottom(bitmap1.bitmap) + 1)) / 2 end - if bitmap2 && bitmap2.bitmap # Foe's y + if bitmap2&.bitmap # Foe's y metrics.front_sprite[0] = 0 metrics.front_sprite[1] = (bitmap2.height - (findBottom(bitmap2.bitmap) + 1)) / 2 metrics.front_sprite[1] += 4 # Just because @@ -33,8 +33,8 @@ def pbAutoPositionAll metrics.front_sprite_altitude = 0 # Shouldn't be used metrics.shadow_x = 0 metrics.shadow_size = 2 - bitmap1.dispose if bitmap1 - bitmap2.dispose if bitmap2 + bitmap1&.dispose + bitmap2&.dispose end GameData::SpeciesMetrics.save Compiler.write_pokemon_metrics diff --git a/Data/Scripts/020_Debug/001_Editor_Utilities.rb b/Data/Scripts/020_Debug/001_Editor_Utilities.rb index 1d633cfad..adab28c9d 100644 --- a/Data/Scripts/020_Debug/001_Editor_Utilities.rb +++ b/Data/Scripts/020_Debug/001_Editor_Utilities.rb @@ -16,13 +16,13 @@ def pbSafeCopyFile(x, y, z = nil) filedata = nil if safeExists?(y) different = false - if FileTest.size(x) != FileTest.size(y) - different = true - else + if FileTest.size(x) == FileTest.size(y) filedata2 = "" File.open(x, "rb") { |f| filedata = f.read } File.open(y, "rb") { |f| filedata2 = f.read } different = true if filedata != filedata2 + else + different = true end if different safetocopy = pbConfirmMessage(_INTL("A different file named '{1}' already exists. Overwrite it?", y)) diff --git a/Data/Scripts/020_Debug/002_Animation editor/001_AnimEditor_SceneElements.rb b/Data/Scripts/020_Debug/002_Animation editor/001_AnimEditor_SceneElements.rb index 15cd762fd..b1e49a551 100644 --- a/Data/Scripts/020_Debug/002_Animation editor/001_AnimEditor_SceneElements.rb +++ b/Data/Scripts/020_Debug/002_Animation editor/001_AnimEditor_SceneElements.rb @@ -85,14 +85,14 @@ def pbSpriteHitTest(sprite, x, y, usealpha = true, wholecanvas = false) return false if sprite.bitmap.disposed? width = sprite.src_rect.width height = sprite.src_rect.height - if !wholecanvas + if wholecanvas + xwidth = 0 + xheight = 0 + else xwidth = width - 64 xheight = height - 64 width = 64 if width > 64 && !usealpha height = 64 if height > 64 && !usealpha - else - xwidth = 0 - xheight = 0 end width = sprite.bitmap.width if width > sprite.bitmap.width height = sprite.bitmap.height if height > sprite.bitmap.height @@ -125,7 +125,7 @@ def pbSpriteHitTest(sprite, x, y, usealpha = true, wholecanvas = false) bitmapX = sprite.src_rect.x + 192 - xmirror end color = sprite.bitmap.get_pixel(bitmapX, bitmapY) - return false if (color.alpha == 0) + return false if color.alpha == 0 end return true end @@ -478,7 +478,7 @@ class AnimationCanvas < Sprite def loadAnimation(anim) @animation = anim - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose if @animation.graphic == "" @animbitmap = nil else @@ -497,7 +497,7 @@ class AnimationCanvas < Sprite end def animbitmap=(value) - @animbitmap.dispose if @animbitmap + @animbitmap&.dispose @animbitmap = value (2...PBAnimation::MAX_SPRITES).each do |i| @celsprites[i].bitmap = @animbitmap if @celsprites[i] @@ -508,12 +508,12 @@ class AnimationCanvas < Sprite def dispose @user.dispose @target.dispose - @animbitmap.dispose if @animbitmap - @selectedbitmap.dispose if @selectedbitmap - @celbitmap.dispose if @celbitmap - self.bitmap.dispose if self.bitmap + @animbitmap&.dispose + @selectedbitmap&.dispose + @celbitmap&.dispose + self.bitmap&.dispose PBAnimation::MAX_SPRITES.times do |i| - @celsprites[i].dispose if @celsprites[i] + @celsprites[i]&.dispose end super end @@ -616,7 +616,9 @@ class AnimationCanvas < Sprite def setPreviousFrame(i) if @currentframe > 0 cel = @animation[@currentframe - 1][i] - if cel != nil + if cel.nil? + @lastframesprites[i].visible = false + else @lastframesprites[i].ox = 32 @lastframesprites[i].oy = 32 @lastframesprites[i].selected = false @@ -625,8 +627,6 @@ class AnimationCanvas < Sprite @lastframesprites[i].y = cel[AnimFrame::Y] + 64 @lastframesprites[i].visible = true @lastframesprites[i].repaint - else - @lastframesprites[i].visible = false end else @lastframesprites[i].visible = false @@ -799,31 +799,30 @@ class AnimationCanvas < Sprite def updateInput cel = currentCel mousepos = Mouse.getMousePos - if mousepos && pbSpriteHitTest(self, mousepos[0], mousepos[1], false, true) - if Input.trigger?(Input::MOUSELEFT) # Left mouse button - selectedcel = -1 - usealpha = (Input.press?(Input::ALT)) ? true : false - PBAnimation::MAX_SPRITES.times do |j| - if pbSpriteHitTest(@celsprites[j], mousepos[0], mousepos[1], usealpha, false) - selectedcel = j - end + if Input.trigger?(Input::MOUSELEFT) && mousepos && + pbSpriteHitTest(self, mousepos[0], mousepos[1], false, true) + selectedcel = -1 + usealpha = (Input.press?(Input::ALT)) ? true : false + PBAnimation::MAX_SPRITES.times do |j| + if pbSpriteHitTest(@celsprites[j], mousepos[0], mousepos[1], usealpha, false) + selectedcel = j end - if selectedcel < 0 - if @animbitmap && addSprite(mousepos[0] - BORDERSIZE, mousepos[1] - BORDERSIZE) - @selecting = true if !self.locked?(@currentcel) - @selectOffsetX = 0 - @selectOffsetY = 0 - cel = currentCel - invalidate - end - else - @currentcel = selectedcel + end + if selectedcel < 0 + if @animbitmap && addSprite(mousepos[0] - BORDERSIZE, mousepos[1] - BORDERSIZE) @selecting = true if !self.locked?(@currentcel) + @selectOffsetX = 0 + @selectOffsetY = 0 cel = currentCel - @selectOffsetX = cel[AnimFrame::X] - mousepos[0] + BORDERSIZE - @selectOffsetY = cel[AnimFrame::Y] - mousepos[1] + BORDERSIZE invalidate end + else + @currentcel = selectedcel + @selecting = true if !self.locked?(@currentcel) + cel = currentCel + @selectOffsetX = cel[AnimFrame::X] - mousepos[0] + BORDERSIZE + @selectOffsetY = cel[AnimFrame::Y] - mousepos[1] + BORDERSIZE + invalidate end end currentFrame = getCurrentFrame diff --git a/Data/Scripts/020_Debug/002_Animation editor/002_AnimEditor_ControlsButtons.rb b/Data/Scripts/020_Debug/002_Animation editor/002_AnimEditor_ControlsButtons.rb index ff5a61364..ad8d1b682 100644 --- a/Data/Scripts/020_Debug/002_Animation editor/002_AnimEditor_ControlsButtons.rb +++ b/Data/Scripts/020_Debug/002_Animation editor/002_AnimEditor_ControlsButtons.rb @@ -144,10 +144,10 @@ class Button < UIControl color = Color.new(120, 120, 120) bitmap.fill_rect(x + 1, y + 1, width - 2, height - 2, color) ret = Rect.new(x + 1, y + 1, width - 2, height - 2) - if !@captured - bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(0, 0, 0, 0)) - else + if @captured bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(120, 120, 120, 80)) + else + bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(0, 0, 0, 0)) end size = bitmap.text_size(self.label).width shadowtext(bitmap, x + 4, y, size, height, self.label, @disabled) @@ -196,10 +196,10 @@ class Checkbox < Button bitmap.fill_rect(x + 2, y + 2, self.width - 4, self.height - 4, Color.new(0, 0, 0, 0)) bitmap.fill_rect(x + 1, y + 1, width - 2, height - 2, color) ret = Rect.new(x + 1, y + 1, width - 2, height - 2) - if !@captured - bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(0, 0, 0, 0)) - else + if @captured bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(120, 120, 120, 80)) + else + bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(0, 0, 0, 0)) end if self.checked shadowtext(bitmap, x, y, 32, 32, "X", @disabled, 1) @@ -259,7 +259,7 @@ class TextField < UIControl @frame += 1 @frame %= 20 self.changed = false - self.invalidate if ((@frame % 10) == 0) + self.invalidate if (@frame % 10) == 0 # Moving cursor if Input.triggerex?(:LEFT) || Input.repeatex?(:LEFT) if @cursor > 0 @@ -302,10 +302,10 @@ class TextField < UIControl width -= size bitmap.fill_rect(x + 1, y + 1, width - 2, height - 2, color) ret = Rect.new(x + 1, y + 1, width - 2, height - 2) - if !@captured - bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(0, 0, 0, 0)) - else + if @captured bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(120, 120, 120, 80)) + else + bitmap.fill_rect(x + 2, y + 2, width - 4, height - 4, Color.new(0, 0, 0, 0)) end x += 4 textscan = self.text.scan(/./m) @@ -314,7 +314,7 @@ class TextField < UIControl @cursor = 0 if @cursor < 0 startpos = @cursor fromcursor = 0 - while (startpos > 0) + while startpos > 0 c = textscan[startpos - 1] fromcursor += bitmap.text_size(c).width break if fromcursor > width - 4 @@ -668,7 +668,7 @@ class TextSlider < UIControl def refresh bitmap = self.bitmap - if @maxoptionwidth == nil + if @maxoptionwidth.nil? @options.length.times do |i| w = self.bitmap.text_size(" " + @options[i] + " ").width @maxoptionwidth = w if !@maxoptionwidth || @maxoptionwidth < w diff --git a/Data/Scripts/020_Debug/002_Animation editor/003_AnimEditor_Interpolation.rb b/Data/Scripts/020_Debug/002_Animation editor/003_AnimEditor_Interpolation.rb index 2bc5b0061..39070d8af 100644 --- a/Data/Scripts/020_Debug/002_Animation editor/003_AnimEditor_Interpolation.rb +++ b/Data/Scripts/020_Debug/002_Animation editor/003_AnimEditor_Interpolation.rb @@ -166,15 +166,13 @@ class PointPath i = 0 @distances.each do |dist| curdist += dist - if dist > 0.0 - if curdist >= distForT - distT = 1.0 - ((curdist - distForT) / dist) - dx = @points[i + 1][0] - @points[i][0] - dy = @points[i + 1][1] - @points[i][1] - ret = [@points[i][0] + (dx * distT), - @points[i][1] + (dy * distT)] - break - end + if dist > 0.0 && curdist >= distForT + distT = 1.0 - ((curdist - distForT) / dist) + dx = @points[i + 1][0] - @points[i][0] + dy = @points[i + 1][1] - @points[i][1] + ret = [@points[i][0] + (dx * distT), + @points[i][1] + (dy * distT)] + break end i += 1 end @@ -295,8 +293,8 @@ def pbDefinePath(canvas) if Input.trigger?(Input::MOUSELEFT) 4.times do |j| next if !curve[j].hittest? - if [1, 2].include?(j) - next if !curve[0].visible || !curve[3].visible + if [1, 2].include?(j) && (!curve[0].visible || !curve[3].visible) + next end curve[j].visible = true 4.times do |k| @@ -381,7 +379,7 @@ def pbDefinePath(canvas) mousepos = Mouse.getMousePos(true) window.text = (mousepos) ? sprintf("(%d,%d)", mousepos[0], mousepos[1]) : "(??,??)" end - while !canceled + until canceled mousepos = Mouse.getMousePos(true) if mousepos && !pointpath.isEndPoint?(mousepos[0], mousepos[1]) pointpath.addPoint(mousepos[0], mousepos[1]) diff --git a/Data/Scripts/020_Debug/002_Animation editor/004_AnimEditor_ExportImport.rb b/Data/Scripts/020_Debug/002_Animation editor/004_AnimEditor_ExportImport.rb index 531506f0a..2692d6dcd 100644 --- a/Data/Scripts/020_Debug/002_Animation editor/004_AnimEditor_ExportImport.rb +++ b/Data/Scripts/020_Debug/002_Animation editor/004_AnimEditor_ExportImport.rb @@ -91,7 +91,7 @@ def pbConvertAnimToNewFormat(textdata) next if !textdata[i] PBAnimation::MAX_SPRITES.times do |j| next if !textdata[i][j] - needconverting = true if textdata[i][j][AnimFrame::FOCUS] == nil + needconverting = true if textdata[i][j][AnimFrame::FOCUS].nil? break if needconverting end break if needconverting @@ -101,7 +101,7 @@ def pbConvertAnimToNewFormat(textdata) next if !textdata[i] PBAnimation::MAX_SPRITES.times do |j| next if !textdata[i][j] - textdata[i][j][AnimFrame::PRIORITY] = 1 if textdata[i][j][AnimFrame::PRIORITY] == nil + textdata[i][j][AnimFrame::PRIORITY] = 1 if textdata[i][j][AnimFrame::PRIORITY].nil? case j when 0 # User battler textdata[i][j][AnimFrame::FOCUS] = 2 diff --git a/Data/Scripts/020_Debug/002_Animation editor/005_AnimEditor_Functions.rb b/Data/Scripts/020_Debug/002_Animation editor/005_AnimEditor_Functions.rb index 458b67353..5b8f1d649 100644 --- a/Data/Scripts/020_Debug/002_Animation editor/005_AnimEditor_Functions.rb +++ b/Data/Scripts/020_Debug/002_Animation editor/005_AnimEditor_Functions.rb @@ -707,7 +707,7 @@ def pbCopyFrames(canvas) dstvalue = sliderwin2.value(2) - 1 length = (endvalue - startvalue) + 1 if length > 0 # Ensure correct overlap handling - if (startvalue < dstvalue) + if startvalue < dstvalue startvalue += length dstvalue += length while length != 0 @@ -1187,5 +1187,5 @@ def pbAnimationEditor animationEditorMain(animation) Graphics.resize_screen(Settings::SCREEN_WIDTH, Settings::SCREEN_HEIGHT) pbSetResizeFactor($PokemonSystem.screensize) - $game_map.autoplay if $game_map + $game_map&.autoplay end diff --git a/Data/Scripts/020_Debug/002_Editor_DataTypes.rb b/Data/Scripts/020_Debug/002_Editor_DataTypes.rb index 05b828001..9799bbc39 100644 --- a/Data/Scripts/020_Debug/002_Editor_DataTypes.rb +++ b/Data/Scripts/020_Debug/002_Editor_DataTypes.rb @@ -829,7 +829,7 @@ end module MapProperty def self.set(settingname, oldsetting) - chosenmap = pbListScreen(settingname, MapLister.new(oldsetting ? oldsetting : 0)) + chosenmap = pbListScreen(settingname, MapLister.new(oldsetting || 0)) return (chosenmap > 0) ? chosenmap : oldsetting end @@ -1285,7 +1285,7 @@ class EvolutionsProperty ret = nil if ret.empty? else params = ChooseNumberParams.new - params.setRange(0, 65535) + params.setRange(0, 65_535) params.setDefaultValue(value) if value params.setCancelValue(-1) ret = pbMessageChooseNumber(_INTL("Choose a parameter."), params) diff --git a/Data/Scripts/020_Debug/003_Debug menus/002_Debug_MenuCommands.rb b/Data/Scripts/020_Debug/003_Debug menus/002_Debug_MenuCommands.rb index 38e7ffa94..dd568fca4 100644 --- a/Data/Scripts/020_Debug/003_Debug menus/002_Debug_MenuCommands.rb +++ b/Data/Scripts/020_Debug/003_Debug menus/002_Debug_MenuCommands.rb @@ -22,7 +22,7 @@ module DebugMenuCommands def self.hasFunction?(option, function) option_hash = @@commands[option] - return option_hash && option_hash.keys.include?(function) + return option_hash&.has_key?(function) end def self.getFunction(option, function) diff --git a/Data/Scripts/020_Debug/003_Debug menus/003_Debug_MenuExtraCode.rb b/Data/Scripts/020_Debug/003_Debug menus/003_Debug_MenuExtraCode.rb index eff5e0420..1644ba8c1 100644 --- a/Data/Scripts/020_Debug/003_Debug menus/003_Debug_MenuExtraCode.rb +++ b/Data/Scripts/020_Debug/003_Debug menus/003_Debug_MenuExtraCode.rb @@ -21,8 +21,8 @@ def pbWarpToMap next if !map.passableStrict?(x, y, 0, $game_player) blocked = false map.events.values.each do |event| - if event.at_coordinate?(x, y) && !event.through - blocked = true if event.character_name != "" + if event.at_coordinate?(x, y) && !event.through && event.character_name != "" + blocked = true end end next if blocked @@ -101,7 +101,7 @@ class SpriteWindow_DebugVariables < Window_DrawableCommand status = $game_variables[index + 1].to_s status = "\"__\"" if nil_or_empty?(status) end - name = '' if name == nil + name = '' if name.nil? id_text = sprintf("%04d:", index + 1) rect = drawCursor(index, rect) totalWidth = rect.width @@ -117,11 +117,11 @@ end def pbDebugSetVariable(id, diff) - $game_variables[id] = 0 if $game_variables[id] == nil + $game_variables[id] = 0 if $game_variables[id].nil? if $game_variables[id].is_a?(Numeric) pbPlayCursorSE - $game_variables[id] = [$game_variables[id] + diff, 99999999].min - $game_variables[id] = [$game_variables[id], -99999999].max + $game_variables[id] = [$game_variables[id] + diff, 99_999_999].min + $game_variables[id] = [$game_variables[id], -99_999_999].max $game_map.need_refresh = true end end @@ -135,8 +135,8 @@ def pbDebugVariableScreen(id) params.setMaxDigits(8) params.setNegativesAllowed(true) value = pbMessageChooseNumber(_INTL("Set variable {1}.", id), params) - $game_variables[id] = [value, 99999999].min - $game_variables[id] = [$game_variables[id], -99999999].max + $game_variables[id] = [value, 99_999_999].min + $game_variables[id] = [$game_variables[id], -99_999_999].max $game_map.need_refresh = true when String value = pbMessageFreeText(_INTL("Set variable {1}.", id), @@ -623,7 +623,7 @@ def pbImportAllAnimations Graphics.update audios = [] files = Dir.glob(folder + "/*.*") - %w[wav ogg mid wma].each { |ext| # mp3 + ["wav", "ogg", "mid", "wma"].each { |ext| # mp3 upext = ext.upcase audios.concat(files.find_all { |f| f[f.length - 3, 3] == ext }) audios.concat(files.find_all { |f| f[f.length - 3, 3] == upext }) @@ -632,7 +632,7 @@ def pbImportAllAnimations pbSafeCopyFile(audio, RTP.getAudioPath("Audio/SE/Anim/" + File.basename(audio)), "Audio/SE/Anim/" + File.basename(audio)) end images = [] - %w[png gif].each { |ext| # jpg jpeg bmp + ["png", "gif"].each { |ext| # jpg jpeg bmp upext = ext.upcase images.concat(files.find_all { |f| f[f.length - 3, 3] == ext }) images.concat(files.find_all { |f| f[f.length - 3, 3] == upext }) @@ -642,26 +642,24 @@ def pbImportAllAnimations end Dir.glob(folder + "/*.anm") { |f| textdata = loadBase64Anim(IO.read(f)) rescue nil - if textdata && textdata.is_a?(PBAnimation) + if textdata.is_a?(PBAnimation) index = pbAllocateAnimation(animations, textdata.name) missingFiles = [] textdata.name = File.basename(folder) if textdata.name == "" textdata.id = -1 # This is not an RPG Maker XP animation pbConvertAnimToNewFormat(textdata) - if textdata.graphic && textdata.graphic != "" - if !safeExists?(folder + "/" + textdata.graphic) && - !FileTest.image_exist?("Graphics/Animations/" + textdata.graphic) - textdata.graphic = "" - missingFiles.push(textdata.graphic) - end + if textdata.graphic && textdata.graphic != "" && + !safeExists?(folder + "/" + textdata.graphic) && + !FileTest.image_exist?("Graphics/Animations/" + textdata.graphic) + textdata.graphic = "" + missingFiles.push(textdata.graphic) end textdata.timing.each do |timing| - if timing.name && timing.name != "" - if !safeExists?(folder + "/" + timing.name) && - !FileTest.audio_exist?("Audio/SE/Anim/" + timing.name) - timing.name = "" - missingFiles.push(timing.name) - end + if timing.name && timing.name != "" && + !safeExists?(folder + "/" + timing.name) && + !FileTest.audio_exist?("Audio/SE/Anim/" + timing.name) + timing.name = "" + missingFiles.push(timing.name) end end animations[index] = textdata diff --git a/Data/Scripts/020_Debug/003_Debug menus/005_Debug_PokemonCommands.rb b/Data/Scripts/020_Debug/003_Debug menus/005_Debug_PokemonCommands.rb index 68c1ee109..1898dac4a 100644 --- a/Data/Scripts/020_Debug/003_Debug menus/005_Debug_PokemonCommands.rb +++ b/Data/Scripts/020_Debug/003_Debug menus/005_Debug_PokemonCommands.rb @@ -22,7 +22,7 @@ module PokemonDebugMenuCommands def self.hasFunction?(option, function) option_hash = @@commands[option] - return option_hash && option_hash.keys.include?(function) + return option_hash&.has_key?(function) end def self.getFunction(option, function) @@ -1029,7 +1029,7 @@ PokemonDebugMenuCommands.register("ownership", { pkmn.owner.id = $player.make_foreign_ID when 4 # Set foreign ID params = ChooseNumberParams.new - params.setRange(0, 65535) + params.setRange(0, 65_535) params.setDefaultValue(pkmn.owner.public_id) val = pbMessageChooseNumber( _INTL("Set the new ID (max. 65535)."), params @@ -1129,11 +1129,11 @@ PokemonDebugMenuCommands.register("shadow_pkmn", { break if cmd < 0 case cmd when 0 # Make Shadow - if !pkmn.shadowPokemon? + if pkmn.shadowPokemon? + screen.pbDisplay(_INTL("{1} is already a Shadow Pokémon.", pkmn.name)) + else pkmn.makeShadow screen.pbRefreshSingle(pkmnid) - else - screen.pbDisplay(_INTL("{1} is already a Shadow Pokémon.", pkmn.name)) end when 1 # Set heart gauge if pkmn.shadowPokemon? diff --git a/Data/Scripts/020_Debug/003_Debug menus/007_Debug_BattleCommands.rb b/Data/Scripts/020_Debug/003_Debug menus/007_Debug_BattleCommands.rb index df6437d34..e2fc41b9c 100644 --- a/Data/Scripts/020_Debug/003_Debug menus/007_Debug_BattleCommands.rb +++ b/Data/Scripts/020_Debug/003_Debug menus/007_Debug_BattleCommands.rb @@ -44,7 +44,7 @@ module BattleDebugMenuCommands def self.hasFunction?(option, function) option_hash = @@commands[option] - return option_hash && option_hash.keys.include?(function) + return option_hash&.has_key?(function) end def self.getFunction(option, function) diff --git a/Data/Scripts/020_Debug/003_Debug menus/008_Debug_BattlerCommands.rb b/Data/Scripts/020_Debug/003_Debug menus/008_Debug_BattlerCommands.rb index 0d8fc42e7..c7f6cca8a 100644 --- a/Data/Scripts/020_Debug/003_Debug menus/008_Debug_BattlerCommands.rb +++ b/Data/Scripts/020_Debug/003_Debug menus/008_Debug_BattlerCommands.rb @@ -32,7 +32,7 @@ module BattlePokemonDebugMenuCommands def self.hasFunction?(option, function) option_hash = @@commands[option] - return option_hash && option_hash.keys.include?(function) + return option_hash&.has_key?(function) end def self.getFunction(option, function) @@ -241,7 +241,7 @@ BattlePokemonDebugMenuCommands.register("set_level", { if level != pkmn.level pkmn.level = level pkmn.calc_stats - battler.pbUpdate if battler + battler&.pbUpdate end } }) @@ -315,7 +315,7 @@ BattlePokemonDebugMenuCommands.register("hidden_values", { if f != pkmn.ev[ev_id[cmd2]] pkmn.ev[ev_id[cmd2]] = f pkmn.calc_stats - battler.pbUpdate if battler + battler&.pbUpdate end else # (Max) Randomise all evTotalTarget = Pokemon::EV_LIMIT @@ -334,7 +334,7 @@ BattlePokemonDebugMenuCommands.register("hidden_values", { evTotalTarget -= addVal end pkmn.calc_stats - battler.pbUpdate if battler + battler&.pbUpdate end end when 1 # Set IVs @@ -365,12 +365,12 @@ BattlePokemonDebugMenuCommands.register("hidden_values", { if f != pkmn.iv[iv_id[cmd2]] pkmn.iv[iv_id[cmd2]] = f pkmn.calc_stats - battler.pbUpdate if battler + battler&.pbUpdate end else # Randomise all GameData::Stat.each_main { |s| pkmn.iv[s.id] = rand(Pokemon::IV_STAT_LIMIT + 1) } pkmn.calc_stats - battler.pbUpdate if battler + battler&.pbUpdate end end end @@ -467,7 +467,7 @@ BattlePokemonDebugMenuCommands.register("teach_move", { next end pkmn.learn_move(new_move) - battler.moves.push(Battle::Move.from_pokemon_move(self, pkmn.moves.last)) if battler + battler&.moves&.push(Battle::Move.from_pokemon_move(self, pkmn.moves.last)) pbMessage("\\ts[]" + _INTL("{1} learned {2}!", pkmn.name, move_name)) } }) @@ -492,7 +492,7 @@ BattlePokemonDebugMenuCommands.register("forget_move", { next if cmd < 0 old_move_name = pkmn.moves[move_indices[cmd]].name pkmn.forget_move_at_index(move_indices[cmd]) - battler.moves.delete_at(move_indices[cmd]) if battler + battler&.moves&.delete_at(move_indices[cmd]) pbMessage("\\ts[]" + _INTL("{1} forgot {2}.", pkmn.name, old_move_name)) } }) @@ -688,7 +688,7 @@ BattlePokemonDebugMenuCommands.register("set_nature", { elsif cmd == commands.length - 1 # Reset pkmn.nature = nil end - battler.pbUpdate if battler + battler&.pbUpdate end } }) diff --git a/Data/Scripts/020_Debug/003_Debug menus/009_Debug_BattleExtraCode.rb b/Data/Scripts/020_Debug/003_Debug menus/009_Debug_BattleExtraCode.rb index aa25118f1..b3b21c14e 100644 --- a/Data/Scripts/020_Debug/003_Debug menus/009_Debug_BattleExtraCode.rb +++ b/Data/Scripts/020_Debug/003_Debug menus/009_Debug_BattleExtraCode.rb @@ -119,7 +119,7 @@ module Battle::DebugVariables PBEffects::Unburden => { name: "Self lost its item (for Unburden)", default: false }, PBEffects::Uproar => { name: "Uproar number of rounds remaining", default: 0 }, PBEffects::WaterSport => { name: "Used Water Sport (Gen 5 and older)", default: false }, - PBEffects::WeightChange => { name: "Weight change +0.1*x kg", default: 0, min: -99999, max: 99999 }, + PBEffects::WeightChange => { name: "Weight change +0.1*x kg", default: 0, min: -99_999, max: 99_999 }, PBEffects::Yawn => { name: "Yawn rounds remaining until falling asleep", default: 0 } } @@ -421,7 +421,7 @@ class Battle::DebugSetEffects @window.refresh if update_input_for_integer(effect, variable_data[:default], variable_data) elsif variable_data[:default] == -1 @window.refresh if update_input_for_battler_index(effect, variable_data) - elsif variable_data[:default] == nil + elsif variable_data[:default].nil? case variable_data[:type] when :move @window.refresh if update_input_for_move(effect, variable_data) diff --git a/Data/Scripts/020_Debug/003_Editor_Listers.rb b/Data/Scripts/020_Debug/003_Editor_Listers.rb index 0d1a9a67a..f0dbf8123 100644 --- a/Data/Scripts/020_Debug/003_Editor_Listers.rb +++ b/Data/Scripts/020_Debug/003_Editor_Listers.rb @@ -132,7 +132,7 @@ class GraphicsLister end def dispose - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose @sprite.dispose end @@ -320,7 +320,7 @@ class MapLister end def dispose - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose @sprite.dispose end @@ -344,14 +344,12 @@ class MapLister end def value(index) - if @addGlobalOffset == 1 - return 0 if index == 0 - end + return 0 if @addGlobalOffset == 1 && index == 0 return (index < 0) ? -1 : @maps[index - @addGlobalOffset][0] end def refresh(index) - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose return if index < 0 return if index == 0 && @addGlobalOffset == 1 @sprite.bitmap = createMinimap(@maps[index - @addGlobalOffset][0]) @@ -426,7 +424,7 @@ class ItemLister end def dispose - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose @sprite.dispose end @@ -487,7 +485,7 @@ class TrainerTypeLister end def dispose - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose @sprite.dispose end @@ -529,7 +527,7 @@ class TrainerTypeLister end def refresh(index) - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose return if index < 0 begin if @ids[index].is_a?(Symbol) @@ -566,7 +564,7 @@ class TrainerBattleLister end def dispose - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose @sprite.dispose @pkmnList.dispose end @@ -629,7 +627,7 @@ class TrainerBattleLister def refresh(index) # Refresh trainer sprite - @sprite.bitmap.dispose if @sprite.bitmap + @sprite.bitmap&.dispose return if index < 0 begin if @ids[index].is_a?(Array) diff --git a/Data/Scripts/021_Compiler/001_Compiler.rb b/Data/Scripts/021_Compiler/001_Compiler.rb index f5c1744c0..55eb6ff55 100644 --- a/Data/Scripts/021_Compiler/001_Compiler.rb +++ b/Data/Scripts/021_Compiler/001_Compiler.rb @@ -39,10 +39,10 @@ module FileLineData def self.linereport if @section - if @key != nil - return _INTL("File {1}, section {2}, key {3}\r\n{4}\r\n\r\n", @file, @section, @key, @value) - else + if @key.nil? return _INTL("File {1}, section {2}\r\n{3}\r\n\r\n", @file, @section, @value) + else + return _INTL("File {1}, section {2}, key {3}\r\n{4}\r\n\r\n", @file, @section, @key, @value) end else return _INTL("File {1}, line {2}\r\n{3}\r\n\r\n", @file, @lineno, @linedata) @@ -79,7 +79,7 @@ module Compiler def csvQuote(str, always = false) return "" if nil_or_empty?(str) if always || str[/[,\"]/] # || str[/^\s/] || str[/\s$/] || str[/^#/] - str = str.gsub(/[\"]/, "\\\"") + str = str.gsub(/\"/, "\\\"") str = "\"#{str}\"" end return str @@ -110,7 +110,7 @@ module Compiler havesection = true lastsection = {} else - if sectionname == nil + if sectionname.nil? FileLineData.setLine(line, lineno) raise _INTL("Expected a section at the beginning of the file. This error may also occur if the file was not saved in UTF-8.\r\n{1}", FileLineData.linereport) end @@ -168,7 +168,7 @@ module Compiler lastsection = [] havesection = true else - if sectionname == nil + if sectionname.nil? raise _INTL("Expected a section at the beginning of the file (line {1}). Sections begin with '[name of section]'", lineno) end lastsection.push(line.gsub(/^\s+/, "").gsub(/\s+$/, "")) @@ -366,7 +366,7 @@ module Compiler return idx when Hash value = enumer[ret] - if value == nil + if value.nil? raise _INTL("Undefined value {1} (expected one of: {2})\r\n{3}", ret, enumer.keys.inspect, FileLineData.linereport) end return value @@ -597,10 +597,10 @@ module Compiler enumer = schema[2 + i] case enumer when Array - if enumer[value] != nil - file.write(enumer[value]) - else + if enumer[value].nil? file.write(value) + else + file.write(enumer[value]) end when Symbol, String mod = Object.const_get(enumer.to_sym) @@ -864,7 +864,7 @@ module Compiler compile_all(mustCompile) rescue Exception e = $! - raise e if "#{e.class}" == "Reset" || e.is_a?(Reset) || e.is_a?(SystemExit) + raise e if e.class.to_s == "Reset" || e.is_a?(Reset) || e.is_a?(SystemExit) pbPrintException(e) dataFiles.length.times do |i| begin diff --git a/Data/Scripts/021_Compiler/002_Compiler_CompilePBS.rb b/Data/Scripts/021_Compiler/002_Compiler_CompilePBS.rb index 7865ef465..72224f060 100644 --- a/Data/Scripts/021_Compiler/002_Compiler_CompilePBS.rb +++ b/Data/Scripts/021_Compiler/002_Compiler_CompilePBS.rb @@ -785,7 +785,7 @@ module Compiler raise _INTL("Species ID '{1}' is not defined in {2}.\r\n{3}", species_symbol, path, FileLineData.linereport) elsif form == 0 raise _INTL("A form cannot be defined with a form number of 0.\r\n{1}", FileLineData.linereport) - elsif used_forms[species_symbol] && used_forms[species_symbol].include?(form) + elsif used_forms[species_symbol]&.include?(form) raise _INTL("Form {1} for species ID {2} is defined twice.\r\n{3}", form, species_symbol, FileLineData.linereport) end used_forms[species_symbol] = [] if !used_forms[species_symbol] diff --git a/Data/Scripts/021_Compiler/003_Compiler_WritePBS.rb b/Data/Scripts/021_Compiler/003_Compiler_WritePBS.rb index 408f1e8cb..d2510383e 100644 --- a/Data/Scripts/021_Compiler/003_Compiler_WritePBS.rb +++ b/Data/Scripts/021_Compiler/003_Compiler_WritePBS.rb @@ -542,7 +542,7 @@ module Compiler current_family = nil list.each do |species| next if !species - if current_family && current_family.include?(species) + if current_family&.include?(species) f.write(",") if comma else current_family = GameData::Species.get(species).get_family_species @@ -739,7 +739,7 @@ module Compiler btTrainersRequiredTypes.keys.each do |key| schema = btTrainersRequiredTypes[key] record = bttrainers[i][schema[0]] - next if record == nil + next if record.nil? f.write(sprintf("%s = ", key)) case key when "Type" diff --git a/Data/Scripts/021_Compiler/004_Compiler_MapsAndEvents.rb b/Data/Scripts/021_Compiler/004_Compiler_MapsAndEvents.rb index f65f4f5ea..794d08786 100644 --- a/Data/Scripts/021_Compiler/004_Compiler_MapsAndEvents.rb +++ b/Data/Scripts/021_Compiler/004_Compiler_MapsAndEvents.rb @@ -134,7 +134,7 @@ module Compiler end def push_event(list, cmd, params = nil, indent = 0) - list.push(RPG::EventCommand.new(cmd, indent, params ? params : [])) + list.push(RPG::EventCommand.new(cmd, indent, params || [])) end def push_end(list) @@ -353,7 +353,7 @@ module Compiler priorities = getTilesetPriorities(map, mapID) [2, 1, 0].each do |i| tile_id = map.data[x, y, i] - return false if tile_id == nil + return false if tile_id.nil? passage = passages[tile_id] if !passage raise "The tile used on map #{mapID} at coordinates (#{x}, #{y}) on layer #{i + 1} doesn't exist in the tileset. " + @@ -371,7 +371,7 @@ module Compiler passages = getTilesetPassages(map, mapID) [2, 1, 0].each do |i| tile_id = map.data[x, y, i] - return false if tile_id == nil + return false if tile_id.nil? passage = passages[tile_id] if !passage raise "The tile used on map #{mapID} at coordinates (#{x}, #{y}) on layer #{i + 1} doesn't exist in the tileset. " +