Advertisement
zc320139

PKMN Battle

Sep 13th, 2018
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 168.37 KB | None | 0 0
  1. # Results of battle:
  2. #    0 - Undecided or aborted
  3. #    1 - Player won
  4. #    2 - Player lost
  5. #    3 - Player or wild Pokémon ran from battle, or player forfeited the match
  6. #    4 - Wild Pokémon was caught
  7. #    5 - Draw
  8. ################################################################################
  9. # Placeholder battle peer.
  10. ################################################################################
  11. class PokeBattle_NullBattlePeer
  12.   def pbStorePokemon(player,pokemon)
  13.     if player.party.length<6
  14.       player.party[player.party.length]=pokemon
  15.     end
  16.     return -1
  17.   end
  18.  
  19.   def pbOnEnteringBattle(battle,pokemon)
  20.   end
  21.  
  22.   def pbGetStorageCreator()
  23.     return nil
  24.   end
  25.  
  26.   def pbCurrentBox()
  27.     return -1
  28.   end
  29.  
  30.   def pbBoxName(box)
  31.     return ""
  32.   end
  33. end
  34.  
  35.  
  36.  
  37. class PokeBattle_BattlePeer
  38.   def self.create
  39.     return PokeBattle_NullBattlePeer.new()
  40.   end
  41. end
  42.  
  43.  
  44.  
  45. ################################################################################
  46. # Success state (used for Battle Arena).
  47. ################################################################################
  48. class PokeBattle_SuccessState
  49.   attr_accessor :typemod
  50.   attr_accessor :useState    # 0 - not used, 1 - failed, 2 - succeeded
  51.   attr_accessor :protected
  52.   attr_accessor :skill
  53.  
  54.   def initialize
  55.     clear
  56.   end
  57.  
  58.   def clear
  59.     @typemod   = 4
  60.     @useState  = 0
  61.     @protected = false
  62.     @skill     = 0
  63.   end
  64.  
  65.   def updateSkill
  66.     if @useState==1 && !@protected
  67.       @skill-=2
  68.     elsif @useState==2
  69.       if @typemod>4
  70.         @skill+=2 # "Super effective"
  71.       elsif @typemod>=1 && @typemod<4
  72.         @skill-=1 # "Not very effective"
  73.       elsif @typemod==0
  74.         @skill-=2 # Ineffective
  75.       else
  76.         @skill+=1
  77.       end
  78.     end
  79.     @typemod=4
  80.     @useState=0
  81.     @protected=false
  82.   end
  83. end
  84.  
  85.  
  86.  
  87. ################################################################################
  88. # Catching and storing Pokémon.
  89. ################################################################################
  90. module PokeBattle_BattleCommon
  91.   def pbStorePokemon(pokemon)
  92.     if !(pokemon.isShadow? rescue false) && !pbInSafari?
  93.       if pbDisplayConfirmBW(_INTL("Would you like to give a nickname to {1}?",pokemon.name),
  94.         "YES", "NO",false)
  95.         species=PBSpecies.getName(pokemon.species)
  96.         nickname=@scene.pbNameEntry(_INTL("{1}'s nickname?",species),pokemon)
  97.         pokemon.name=nickname if nickname!=""
  98.       end
  99.     end
  100.     if pbBoxesFull?
  101.       Kernel.pbMessage(_INTL("There's no more room for Pokémon!\1"))
  102.       Kernel.pbMessage(_INTL("The Pokémon Boxes are full and can't accept any more!"))
  103.       return
  104.     end
  105.     pokemon.pbRecordFirstMoves
  106.     if $Trainer.party.length<6
  107.       $Trainer.party[$Trainer.party.length]=pokemon
  108.     else
  109.       oldcurbox=$PokemonStorage.currentBox
  110.       storedbox=$PokemonStorage.pbStoreCaught(pokemon)
  111.       curboxname=$PokemonStorage[oldcurbox].name
  112.       boxname=$PokemonStorage[storedbox].name
  113.       creator=nil
  114.       creator=Kernel.pbGetStorageCreator if $PokemonGlobal.seenStorageCreator
  115.       if storedbox!=oldcurbox
  116.         if creator
  117.           pbDisplayPaused(_INTL("Box \"{1}\" on {2}'s PC was full.\1",curboxname,creator))
  118.         else
  119.           pbDisplayPaused(_INTL("Box \"{1}\" on someone's PC was full.\1",curboxname))
  120.         end
  121.         pbDisplayPaused(_INTL("{1} was transferred to box \"{2}.\"",pokemon.name,boxname))
  122.       else
  123.         if creator
  124.           pbDisplayPaused(_INTL("{1} was transferred to {2}'s PC.\1",pokemon.name,creator))
  125.         else
  126.           pbDisplayPaused(_INTL("{1} was transferred to someone's PC.\1",pokemon.name))
  127.         end
  128.         pbDisplayPaused(_INTL("It was stored in box \"{1}.\"",boxname))
  129.       end
  130.     end
  131.   end
  132.  
  133.   def pbThrowPokeBall(idxPokemon,ball,rareness=nil,showplayer=false)
  134.     itemname=PBItems.getName(ball)
  135.     battler=nil
  136.     if pbIsOpposing?(idxPokemon)
  137.       battler=self.battlers[idxPokemon]
  138.     else
  139.       battler=self.battlers[idxPokemon].pbOppositeOpposing
  140.     end
  141.     if battler.isFainted?
  142.       battler=battler.pbPartner
  143.     end
  144.     pbDisplayBrief(_INTL("{1} threw one {2}!",self.pbPlayer.name,itemname))
  145.     if battler.isFainted?
  146.       pbDisplay(_INTL("But there was no target..."))
  147.       return
  148.     end
  149.    if @opponent && !pbIsSnagBall?(ball) && $game_switches[300]==true
  150.       @scene.pbThrowAndDeflect(ball,1)
  151.       pbDisplay(_INTL("What are you doing with my pokemon?!"))
  152.    elsif pbIsSnagBall?(ball) && $game_switches[300]==true || pbIsPokeBall?(ball)
  153.       pokemon=battler.pokemon
  154.       species=pokemon.species
  155.    if $DEBUG && Input.press?(Input::CTRL)
  156.       shakes=4
  157.   else
  158.       pbDisplay(_INTL("What are you doing with my pokemon?!")) if @opponent && pbIsSnagBall?(ball) && $game_switches[300]==true
  159.       $game_variables[300]+1  
  160.       if !rareness
  161.           dexdata=pbOpenDexData
  162.           pbDexDataOffset(dexdata,species,16)
  163.           rareness=dexdata.fgetb # Get rareness from dexdata file
  164.           dexdata.close
  165.         end
  166.         a=battler.totalhp
  167.         b=battler.hp
  168.         rareness=BallHandlers.modifyCatchRate(ball,rareness,self,battler)
  169.         x=(((a*3-b*2)*rareness)/(a*3)).floor
  170.         if battler.status==PBStatuses::SLEEP || battler.status==PBStatuses::FROZEN
  171.           x=(x*2.5).floor
  172.         elsif battler.status!=0
  173.           x=(x*1.5).floor
  174.         end
  175.         c=0
  176.         if $Trainer
  177.           if $Trainer.pokedexOwned>600
  178.             c=(x*2.5/6).floor
  179.           elsif $Trainer.pokedexOwned>450
  180.             c=(x*2/6).floor
  181.           elsif $Trainer.pokedexOwned>300
  182.             c=(x*1.5/6).floor
  183.           elsif $Trainer.pokedexOwned>150
  184.             c=(x*1/6).floor
  185.           elsif $Trainer.pokedexOwned>30
  186.             c=(x*0.5/6).floor
  187.           end
  188.         end
  189.         shakes=0; critical=false
  190.         if x>255 || BallHandlers.isUnconditional?(ball,self,battler)
  191.           shakes=4
  192.         else
  193.           x=1 if x<1
  194.           y = ( 65536 / ((255.0/x)**0.1875) ).floor
  195.           if USECRITICALCAPTURE && pbRandom(256)<c
  196.             critical=true
  197.             shakes=4 if pbRandom(65536)<y
  198.           else
  199.             shakes+=1 if pbRandom(65536)<y
  200.             shakes+=1 if pbRandom(65536)<y && shakes==1
  201.             shakes+=1 if pbRandom(65536)<y && shakes==2
  202.             shakes+=1 if pbRandom(65536)<y && shakes==3
  203.           end
  204.         end
  205.       end
  206.       PBDebug.log("[Threw Poké Ball] #{itemname}, #{shakes} shakes (4=capture)")
  207.       @scene.pbThrow(ball,(critical) ? 1 : shakes,critical,battler.index,showplayer)
  208.       case shakes
  209.       when 0
  210.         pbDisplay(_INTL("Oh no! The Pokémon broke free!"))
  211.         BallHandlers.onFailCatch(ball,self,battler)
  212.       when 1
  213.         pbDisplay(_INTL("Aww... It appeared to be caught!"))
  214.         BallHandlers.onFailCatch(ball,self,battler)
  215.       when 2
  216.         pbDisplay(_INTL("Aargh! Almost had it!"))
  217.         BallHandlers.onFailCatch(ball,self,battler)
  218.       when 3
  219.         pbDisplay(_INTL("Gah! It was so close, too!"))
  220.         BallHandlers.onFailCatch(ball,self,battler)
  221.       when 4
  222.         pbDisplayBrief(_INTL("Gotcha! {1} was caught!",pokemon.name))
  223.         @scene.pbThrowSuccess
  224.         if pbIsSnagBall?(ball) && @opponent
  225.           pbRemoveFromParty(battler.index,battler.pokemonIndex)
  226.           battler.pbReset
  227.           battler.participants=[]
  228.         else
  229.           @decision=4
  230.         end
  231.         if pbIsSnagBall?(ball)
  232.           pokemon.ot=self.pbPlayer.name
  233.           pokemon.trainerID=self.pbPlayer.id
  234.         end
  235.         BallHandlers.onCatch(ball,self,pokemon)
  236.         pokemon.ballused=pbGetBallType(ball)
  237.         pokemon.makeUnmega rescue nil
  238.         pokemon.makeUnprimal rescue nil
  239.         pokemon.pbRecordFirstMoves
  240.         if GAINEXPFORCAPTURE
  241.           battler.captured=true
  242.           pbGainEXP
  243.           battler.captured=false
  244.         end
  245.         if !self.pbPlayer.hasOwned?(species)
  246.           self.pbPlayer.setOwned(species)
  247.           if $Trainer.pokedex
  248.             pbDisplayPaused(_INTL("{1}'s data was added to the Pokédex.",pokemon.name))
  249.             @scene.pbShowPokedex(species)
  250.           end
  251.         end
  252.         @scene.pbHideCaptureBall
  253.         if pbIsSnagBall?(ball) && @opponent
  254.           pokemon.pbUpdateShadowMoves rescue nil
  255.           @snaggedpokemon.push(pokemon)
  256.         else
  257.           pbStorePokemon(pokemon)
  258.         end
  259.       end
  260.     end
  261.   end
  262. end
  263.  
  264.  
  265.  
  266. ################################################################################
  267. # Main battle class.
  268. ################################################################################
  269. class PokeBattle_Battle
  270.   attr_reader(:scene)             # Scene object for this battle
  271.   attr_accessor(:decision)        # Decision: 0=undecided; 1=win; 2=loss; 3=escaped; 4=caught
  272.   attr_accessor(:internalbattle)  # Internal battle flag
  273.   attr_accessor(:doublebattle)    # Double battle flag
  274.   attr_accessor(:cantescape)      # True if player can't escape
  275.   attr_accessor(:shiftStyle)      # Shift/Set "battle style" option
  276.   attr_accessor(:battlescene)     # "Battle scene" option
  277.   attr_accessor(:debug)           # Debug flag
  278.   attr_reader(:player)            # Player trainer
  279.   attr_reader(:opponent)          # Opponent trainer
  280.   attr_reader(:party1)            # Player's Pokémon party
  281.   attr_reader(:party2)            # Foe's Pokémon party
  282.   attr_reader(:partyorder)        # Order of Pokémon in the player's party
  283.   attr_accessor(:fullparty1)      # True if player's party's max size is 6 instead of 3
  284.   attr_accessor(:fullparty2)      # True if opponent's party's max size is 6 instead of 3
  285.   attr_reader(:battlers)          # Currently active Pokémon
  286.   attr_accessor(:items)           # Items held by opponents
  287.   attr_reader(:sides)             # Effects common to each side of a battle
  288.   attr_reader(:field)             # Effects common to the whole of a battle
  289.   attr_reader(:type)
  290.   attr_accessor(:environment)     # Battle surroundings
  291.   attr_accessor(:weather)         # Current weather, custom methods should use pbWeather instead
  292.   attr_accessor(:weatherduration) # Duration of current weather, or -1 if indefinite
  293.   attr_reader(:switching)         # True if during the switching phase of the round
  294.   attr_reader(:struggle)          # The Struggle move
  295.   attr_accessor(:choices)         # Choices made by each Pokémon this round
  296.   attr_reader(:successStates)     # Success states
  297.   attr_accessor(:lastMoveUsed)    # Last move used
  298.   attr_accessor(:lastMoveUser)    # Last move user
  299.   attr_accessor(:synchronize)     # Synchronize state
  300.   attr_accessor(:megaEvolution)   # Battle index of each trainer's Pokémon to Mega Evolve
  301.   attr_accessor(:amuletcoin)      # Whether Amulet Coin's effect applies
  302.   attr_accessor(:extramoney)      # Money gained in battle by using Pay Day
  303.   attr_accessor(:endspeech)       # Speech by opponent when player wins
  304.   attr_accessor(:endspeech2)      # Speech by opponent when player wins
  305.   attr_accessor(:endspeechwin)    # Speech by opponent when opponent wins
  306.   attr_accessor(:endspeechwin2)   # Speech by opponent when opponent wins
  307.   attr_accessor(:rules)
  308.   attr_reader(:turncount)
  309.   attr_accessor :controlPlayer
  310.   include PokeBattle_BattleCommon
  311.  
  312.   MAXPARTYSIZE = 6
  313.  
  314.   class BattleAbortedException < Exception; end
  315.  
  316.   def pbAbort
  317.     raise BattleAbortedException.new("Battle aborted")
  318.   end
  319.  
  320.   def pbDebugUpdate
  321.   end
  322.  
  323.   def pbRandom(x)
  324.     return rand(x)
  325.   end
  326.  
  327.   def pbAIRandom(x)
  328.     return rand(x)
  329.   end
  330.  
  331. ################################################################################
  332. # Initialise battle class.
  333. ################################################################################
  334.   def initialize(scene,p1,p2,player,opponent)
  335.     if p1.length==0
  336.       raise ArgumentError.new(_INTL("Party 1 has no Pokémon."))
  337.       return
  338.     end
  339.     if p2.length==0
  340.       raise ArgumentError.new(_INTL("Party 2 has no Pokémon."))
  341.       return
  342.     end
  343.     if p2.length>2 && !opponent
  344.       raise ArgumentError.new(_INTL("Wild battles with more than two Pokémon are not allowed."))
  345.       return
  346.     end
  347.     @scene           = scene
  348.     @decision        = 0
  349.     @internalbattle  = true
  350.     @doublebattle    = false
  351.     @cantescape      = false
  352.     @shiftStyle      = true
  353.     @battlescene     = true
  354.     @debug           = false
  355.     @debugupdate     = 0
  356.     if opponent && player.is_a?(Array) && player.length==0
  357.       player = player[0]
  358.     end
  359.     if opponent && opponent.is_a?(Array) && opponent.length==0
  360.       opponent = opponent[0]
  361.     end
  362.     @player          = player                # PokeBattle_Trainer object
  363.     @opponent        = opponent              # PokeBattle_Trainer object
  364.     @party1          = p1
  365.     @party2          = p2
  366.     @partyorder      = []
  367.     for i in 0...6; @partyorder.push(i); end
  368.     @fullparty1      = false
  369.     @fullparty2      = false
  370.     @battlers        = []
  371.     @items           = nil
  372.     @sides           = [PokeBattle_ActiveSide.new,   # Player's side
  373.                         PokeBattle_ActiveSide.new]   # Foe's side
  374.     @field           = PokeBattle_ActiveField.new    # Whole field (gravity/rooms)
  375.     @environment     = PBEnvironment::None   # e.g. Tall grass, cave, still water
  376.     @weather         = 0
  377.     @weatherduration = 0
  378.     @switching       = false
  379.     @choices         = [ [0,0,nil,-1],[0,0,nil,-1],[0,0,nil,-1],[0,0,nil,-1] ]
  380.     @successStates   = []
  381.     for i in 0...4
  382.       @successStates.push(PokeBattle_SuccessState.new)
  383.     end
  384.     @lastMoveUsed    = -1
  385.     @lastMoveUser    = -1
  386.     @synchronize     = [-1,-1,0]
  387.     @megaEvolution   = []
  388.     if @player.is_a?(Array)
  389.       @megaEvolution[0]=[-1]*@player.length
  390.     else
  391.       @megaEvolution[0]=[-1]
  392.     end
  393.     if @opponent.is_a?(Array)
  394.       @megaEvolution[1]=[-1]*@opponent.length
  395.     else
  396.       @megaEvolution[1]=[-1]
  397.     end
  398.     @amuletcoin      = false
  399.     @extramoney      = 0
  400.     @endspeech       = ""
  401.     @endspeech2      = ""
  402.     @endspeechwin    = ""
  403.     @endspeechwin2   = ""
  404.     @rules           = {}
  405.     @turncount       = 0
  406.     @peer            = PokeBattle_BattlePeer.create()
  407.     @priority        = []
  408.     @usepriority     = false
  409.     @snaggedpokemon  = []
  410.     @runCommand      = 0
  411.     if hasConst?(PBMoves,:STRUGGLE)
  412.       @struggle = PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:STRUGGLE)))
  413.     else
  414.       @struggle = PokeBattle_Struggle.new(self,nil)
  415.     end
  416.     @struggle.pp     = -1
  417.     for i in 0...4
  418.       battlers[i] = PokeBattle_Battler.new(self,i)
  419.     end
  420.     for i in @party1
  421.       next if !i
  422.       i.itemRecycle = 0
  423.       i.itemInitial = i.item
  424.     end
  425.     for i in @party2
  426.       next if !i
  427.       i.itemRecycle = 0
  428.       i.itemInitial = i.item
  429.     end
  430.   end
  431.  
  432. ################################################################################
  433. # Info about battle.
  434. ################################################################################
  435.   def pbDoubleBattleAllowed?
  436.     if !@fullparty1 && @party1.length>MAXPARTYSIZE
  437.       return false
  438.     end
  439.     if !@fullparty2 && @party2.length>MAXPARTYSIZE
  440.       return false
  441.     end
  442.     _opponent=@opponent
  443.     _player=@player
  444.     # Wild battle
  445.     if !_opponent
  446.       if @party2.length==1
  447.         return false
  448.       elsif @party2.length==2
  449.         return true
  450.       else
  451.         return false
  452.       end
  453.     # Trainer battle
  454.     else
  455.       if _opponent.is_a?(Array)
  456.         if _opponent.length==1
  457.           _opponent=_opponent[0]
  458.         elsif _opponent.length!=2
  459.           return false
  460.         end
  461.       end
  462.       _player=_player
  463.       if _player.is_a?(Array)
  464.         if _player.length==1
  465.           _player=_player[0]
  466.         elsif _player.length!=2
  467.           return false
  468.         end
  469.       end
  470.       if _opponent.is_a?(Array)
  471.         sendout1=pbFindNextUnfainted(@party2,0,pbSecondPartyBegin(1))
  472.         sendout2=pbFindNextUnfainted(@party2,pbSecondPartyBegin(1))
  473.         return false if sendout1<0 || sendout2<0
  474.       else
  475.         sendout1=pbFindNextUnfainted(@party2,0)
  476.         sendout2=pbFindNextUnfainted(@party2,sendout1+1)
  477.         return false if sendout1<0 || sendout2<0
  478.       end
  479.     end
  480.     if _player.is_a?(Array)
  481.       sendout1=pbFindNextUnfainted(@party1,0,pbSecondPartyBegin(0))
  482.       sendout2=pbFindNextUnfainted(@party1,pbSecondPartyBegin(0))
  483.       return false if sendout1<0 || sendout2<0
  484.     else
  485.       sendout1=pbFindNextUnfainted(@party1,0)
  486.       sendout2=pbFindNextUnfainted(@party1,sendout1+1)
  487.       return false if sendout1<0 || sendout2<0
  488.     end
  489.     return true
  490.   end
  491.  
  492.   def pbWeather  
  493.     for i in 0...4
  494.       if @battlers[i].hasWorkingAbility(:CLOUDNINE) ||
  495.          @battlers[i].hasWorkingAbility(:AIRLOCK)
  496.         return 0
  497.       end
  498.     end
  499.     return @weather
  500.   end
  501.  
  502. ################################################################################
  503. # Get battler info.
  504. ################################################################################
  505.   def pbIsOpposing?(index)
  506.     return (index%2)==1
  507.   end
  508.  
  509.   def pbOwnedByPlayer?(index)
  510.     return false if pbIsOpposing?(index)
  511.     if @player.is_a?(Array) #If has partner trainer, yet no curtrainer id
  512.       return false if index==2 && $PokemonSystem.multiplayer == 0
  513.     end
  514.     return true
  515.   end
  516.  
  517.   def pbIsDoubleBattler?(index)
  518.     return (index>=2)
  519.   end
  520.  
  521.   def pbThisEx(battlerindex,pokemonindex)
  522.     party=pbParty(battlerindex)
  523.     if pbIsOpposing?(battlerindex)
  524.       if @opponent
  525.         return _INTL("The foe {1}",party[pokemonindex].name)
  526.       else
  527.         return _INTL("The wild {1}",party[pokemonindex].name)
  528.       end
  529.     else
  530.       return _INTL("{1}",party[pokemonindex].name)
  531.     end
  532.   end
  533.  
  534. # Checks whether an item can be removed from a Pokémon.
  535.   def pbIsUnlosableItem(pkmn,item)
  536.     return true if pbIsMail?(item)
  537.     return false if pkmn.effects[PBEffects::Transform]
  538.     if isConst?(pkmn.ability,PBAbilities,:MULTITYPE)
  539.       plates=[:FISTPLATE,:SKYPLATE,:TOXICPLATE,:EARTHPLATE,:STONEPLATE,
  540.               :INSECTPLATE,:SPOOKYPLATE,:IRONPLATE,:FLAMEPLATE,:SPLASHPLATE,
  541.               :MEADOWPLATE,:ZAPPLATE,:MINDPLATE,:ICICLEPLATE,:DRACOPLATE,
  542.               :DREADPLATE,:PIXIEPLATE]
  543.       for i in plates
  544.         return true if isConst?(item,PBItems,i)
  545.       end
  546.     end
  547.     combos=[[:GIRATINA,:GRISEOUSORB],
  548.             [:GENESECT,:BURNDRIVE],
  549.             [:GENESECT,:CHILLDRIVE],
  550.             [:GENESECT,:DOUSEDRIVE],
  551.             [:GENESECT,:SHOCKDRIVE],
  552.             # Mega Stones
  553.             [:ABOMASNOW,:ABOMASITE],
  554.             [:ABSOL,:ABSOLITE],
  555.             [:AERODACTYL,:AERODACTYLITE],
  556.             [:AGGRON,:AGGRONITE],
  557.             [:ALAKAZAM,:ALAKAZITE],
  558.             [:ALTARIA,:ALTARIANITE],
  559.             [:AMPHAROS,:AMPHAROSITE],
  560.             [:AUDINO,:AUDINITE],
  561.             [:BANETTE,:BANETTITE],
  562.             [:BEEDRILL,:BEEDRILLITE],
  563.             [:BLASTOISE,:BLASTOISINITE],
  564.             [:BLAZIKEN,:BLAZIKENITE],
  565.             [:CAMPERUPT,:CAMERUPTITE],
  566.             [:CHARIZARD,:CHARIZARDITEX],
  567.             [:CHARIZARD,:CHARIZARDITEY],
  568.             [:DIANCIE,:DIANCITE],
  569.             [:GALLADE,:GALLADITE],
  570.             [:GARCHOMP,:GARCHOMPITE],
  571.             [:GARDEVOIR,:GARDEVOIRITE],
  572.             [:GENGAR,:GENGARITE],
  573.             [:GLALIE,:GLALITITE],
  574.             [:GYARADOS,:GYARADOSITE],
  575.             [:HERACROSS,:HERACRONITE],
  576.             [:HOUNDOOM,:HOUNDOOMINITE],
  577.             [:KANGASKHAN,:KANGASKHANITE],
  578.             [:LATIAS,:LATIASITE],
  579.             [:LATIOS,:LATIOSITE],
  580.             [:LOPUNNY,:LOPUNNITE],
  581.             [:LUCARIO,:LUCARIONITE],
  582.             [:MANECTRIC,:MANECTITE],
  583.             [:MAWILE,:MAWILITE],
  584.             [:MEDICHAM,:MEDICHAMITE],
  585.             [:METAGROSS,:METAGROSSITE],
  586.             [:MEWTWO,:MEWTWONITEX],
  587.             [:MEWTWO,:MEWTWONITEY],
  588.             [:PIDGEOT,:PIDGEOTITE],
  589.             [:PINSIR,:PINSIRITE],
  590.             [:SABLEYE,:SABLENITE],
  591.             [:SALAMENCE,:SALAMENCITE],
  592.             [:SCEPTILE,:SCEPTILITE],
  593.             [:SCIZOR,:SCIZORITE],
  594.             [:SHARPEDO,:SHARPEDONITE],
  595.             [:SLOWBRO,:SLOWBRONITE],
  596.             [:STEELIX,:STEELIXITE],
  597.             [:SWAMPERT,:SWAMPERTITE],
  598.             [:TYRANITAR,:TYRANITARITE],
  599.             [:VENUSAUR,:VENUSAURITE],
  600.             # Primal Reversion stones
  601.             [:KYOGRE,:BLUEORB],
  602.             [:GROUDON,:REDORB]
  603.            ]
  604.     for i in combos
  605.       if isConst?(pkmn.species,PBSpecies,i[0]) && isConst?(item,PBItems,i[1])
  606.         return true
  607.       end
  608.     end
  609.     return false
  610.   end
  611.  
  612.   def pbCheckGlobalAbility(a)
  613.     for i in 0...4 # in order from own first, opposing first, own second, opposing second
  614.       if @battlers[i].hasWorkingAbility(a)
  615.         return @battlers[i]
  616.       end
  617.     end
  618.     return nil
  619.   end
  620.  
  621. ################################################################################
  622. # Player-related info.
  623. ################################################################################
  624.   def pbPlayer
  625.     if @player.is_a?(Array)
  626.       return @player[0]
  627.     else
  628.       return @player
  629.     end
  630.   end
  631.  
  632.   def pbGetOwnerItems(battlerIndex)
  633.     return [] if !@items
  634.     if pbIsOpposing?(battlerIndex)
  635.       if @opponent.is_a?(Array)
  636.         return (battlerIndex==1) ? @items[0] : @items[1]
  637.       else
  638.         return @items
  639.       end
  640.     else
  641.       return []
  642.     end
  643.   end
  644.  
  645.   def pbSetSeen(pokemon)
  646.     if pokemon && @internalbattle
  647.       self.pbPlayer.seen[pokemon.species]=true
  648.       pbSeenForm(pokemon)
  649.     end
  650.   end
  651.  
  652.   def pbGetMegaRingName(battlerIndex)
  653.     if pbBelongsToPlayer?(battlerIndex)
  654.       rings=[:MEGARING,:MEGABRACELET,:MEGACUFF,:MEGACHARM]
  655.       for i in rings
  656.         next if !hasConst?(PBItems,i)
  657.         return PBItems.getName(i) if $PokemonBag.pbQuantity(i)>0
  658.       end
  659.     end
  660.     return _INTL("Mega Ring")
  661.   end
  662.  
  663.   def pbHasMegaRing(battlerIndex)
  664.     return true if !pbBelongsToPlayer?(battlerIndex)
  665.     rings=[:MEGARING,:MEGABRACELET,:MEGACUFF,:MEGACHARM]
  666.     for i in rings
  667.       next if !hasConst?(PBItems,i)
  668.       return true if $PokemonBag.pbQuantity(i)>0
  669.     end
  670.     return false
  671.   end
  672.  
  673.   def pbHasZRing(battlerIndex)
  674.     return true if !pbBelongsToPlayer?(battlerIndex)
  675.     rings=[:ZRING]
  676.     for i in rings
  677.       next if !hasConst?(PBItems,i)
  678.       return true if $PokemonBag.pbQuantity(i)>0
  679.     end
  680.     return false
  681.   end
  682.  
  683. =begin
  684.   def pbSetSeen(pokemon)
  685.     if pokemon && @internalbattle
  686.       self.pbPlayer.seen[pokemon.species]=true
  687.       pbSeenForm(pokemon)
  688.     end
  689.   end
  690. =end
  691. ################################################################################
  692. # Get party info, manipulate parties.
  693. ################################################################################
  694.   def pbPokemonCount(party)
  695.     count=0
  696.     for i in party
  697.       next if !i
  698.       count+=1 if i.hp>0 && !i.isEgg?
  699.     end
  700.     return count
  701.   end
  702.  
  703.   def pbAllFainted?(party)
  704.     pbPokemonCount(party)==0
  705.   end
  706.  
  707.   def pbMaxLevel(party)
  708.     lv=0
  709.     for i in party
  710.       next if !i
  711.       lv=i.level if lv<i.level
  712.     end
  713.     return lv
  714.   end
  715.  
  716.   def pbMaxLevelFromIndex(index)
  717.     party=pbParty(index)
  718.     owner=(pbIsOpposing?(index)) ? @opponent : @player
  719.     maxlevel=0
  720.     if owner.is_a?(Array)
  721.       start=0
  722.       limit=pbSecondPartyBegin(index)
  723.       start=limit if pbIsDoubleBattler?(index)
  724.       for i in start...start+limit
  725.         next if !party[i]
  726.         maxlevel=party[i].level if maxlevel<party[i].level
  727.       end
  728.     else
  729.       for i in party
  730.         next if !i
  731.         maxlevel=i.level if maxlevel<i.level
  732.       end
  733.     end
  734.     return maxlevel
  735.   end
  736.  
  737.   def pbParty(index)
  738.     return pbIsOpposing?(index) ? party2 : party1
  739.   end
  740.  
  741.   def pbPartyExact(index)
  742.     return party1 if index==0
  743.     return party1 if index==2 && !@player.is_a?(Array)
  744.     return party2 if index==1
  745.     return party2 if index==3 && !@opponent.is_a?(Array)
  746.     if index==2 && @player.is_a?(Array)
  747.       party = []
  748.       for i in 0...6; party.push(party1[6+i]); end
  749.     elsif index==3 && @opponent.is_a?(Array)
  750.       party = []
  751.       for i in 0...6; party.push(party2[6+i]); end
  752.     end
  753.     return party
  754.   end
  755.  
  756.   def pbController(index) #returns 0 if player 1, 1 if partner, etc.
  757.     ret = 0
  758.     if @player.is_a?(Array) && index==2 && $PokemonSystem.multiplayer == 1
  759.       ret = 1   #if partner trainer and co-op is turned on
  760.     end
  761.     return ret
  762.   end
  763.  
  764.   def SetInputPlayer(index)
  765.     # Single player is always P1
  766.       if $PokemonSystem.multiplayer == 0
  767.         $PokemonSystem.cur_player = 0
  768.       else  # Co-op controls are enabled
  769.         # Player 1:
  770.       if @player.is_a?(Array) && index==0
  771.         $PokemonSystem.cur_player = 0
  772.         # Player 2:
  773.       elsif @player.is_a?(Array) && index==2
  774.         $PokemonSystem.cur_player = 1
  775.       end
  776.       end
  777.     return
  778.   end
  779.  
  780.   def pbSecondPartyBegin(battlerIndex)
  781.     if pbIsOpposing?(battlerIndex)
  782.       return @fullparty2 ? 6 : 3
  783.     else
  784.       return @fullparty1 ? 6 : 3
  785.     end
  786.   end
  787.  
  788.   def pbFindNextUnfainted(party,start,finish=-1)
  789.     finish=party.length if finish<0
  790.     for i in start...finish
  791.       next if !party[i]
  792.       return i if party[i].hp>0 && !party[i].isEgg?
  793.     end
  794.     return -1
  795.   end
  796.  
  797.   def pbFindPlayerBattler(pkmnIndex)
  798.     battler=nil
  799.     for k in 0...4
  800.       if !pbIsOpposing?(k) && @battlers[k].pokemonIndex==pkmnIndex
  801.         battler=@battlers[k]
  802.         break
  803.       end
  804.     end
  805.     return battler
  806.   end
  807.  
  808.   def pbIsOwner?(battlerIndex,partyIndex)
  809.     secondParty=pbSecondPartyBegin(battlerIndex)
  810.     if !pbIsOpposing?(battlerIndex)
  811.       return true if !@player || !@player.is_a?(Array)
  812.       return (battlerIndex==0) ? partyIndex<secondParty : partyIndex>=secondParty
  813.     else
  814.       return true if !@opponent || !@opponent.is_a?(Array)
  815.       return (battlerIndex==1) ? partyIndex<secondParty : partyIndex>=secondParty
  816.     end
  817.   end
  818.  
  819.   def pbGetOwner(battlerIndex)
  820.     if pbIsOpposing?(battlerIndex)
  821.       if @opponent.is_a?(Array)
  822.         return (battlerIndex==1) ? @opponent[0] : @opponent[1]
  823.       else
  824.         return @opponent
  825.       end
  826.     else
  827.       if @player.is_a?(Array)
  828.         return (battlerIndex==0) ? @player[0] : @player[1]
  829.       else
  830.         return @player
  831.       end
  832.     end
  833.   end
  834.  
  835.   def pbGetOwnerPartner(battlerIndex)
  836.     if pbIsOpposing?(battlerIndex)
  837.       if @opponent.is_a?(Array)
  838.         return (battlerIndex==1) ? @opponent[1] : @opponent[0]
  839.       else
  840.         return @opponent
  841.       end
  842.     else
  843.       if @player.is_a?(Array)
  844.         return (battlerIndex==0) ? @player[1] : @player[0]
  845.       else
  846.         return @player
  847.       end
  848.     end
  849.   end
  850.  
  851.   def pbGetOwnerIndex(battlerIndex)
  852.     if pbIsOpposing?(battlerIndex)
  853.       return (@opponent.is_a?(Array)) ? ((battlerIndex==1) ? 0 : 1) : 0
  854.     else
  855.       return (@player.is_a?(Array)) ? ((battlerIndex==0) ? 0 : 1) : 0
  856.     end
  857.   end
  858.  
  859.   def pbBelongsToPlayer?(battlerIndex)
  860.     if @player.is_a?(Array) && @player.length>1
  861.       return battlerIndex==0
  862.     else
  863.       return (battlerIndex%2)==0
  864.     end
  865.     return false
  866.   end
  867.  
  868.   def pbPartyGetOwner(battlerIndex,partyIndex)
  869.     secondParty=pbSecondPartyBegin(battlerIndex)
  870.     if !pbIsOpposing?(battlerIndex)
  871.       return @player if !@player || !@player.is_a?(Array)
  872.       return (partyIndex<secondParty) ? @player[0] : @player[1]
  873.     else
  874.       return @opponent if !@opponent || !@opponent.is_a?(Array)
  875.       return (partyIndex<secondParty) ? @opponent[0] : @opponent[1]
  876.     end
  877.   end
  878.  
  879.   def pbAddToPlayerParty(pokemon)
  880.     party=pbParty(0)
  881.     for i in 0...party.length
  882.       party[i]=pokemon if pbIsOwner?(0,i) && !party[i]
  883.     end
  884.   end
  885.  
  886.   def pbRemoveFromParty(battlerIndex,partyIndex)
  887.     party=pbParty(battlerIndex)
  888.     side=(pbIsOpposing?(battlerIndex)) ? @opponent : @player
  889.     party[partyIndex]=nil
  890.     if !side || !side.is_a?(Array) # Wild or single opponent
  891.       party.compact!
  892.       for i in battlerIndex...party.length
  893.         for j in 0..3
  894.           next if !@battlers[j]
  895.           if pbGetOwner(j)==side && @battlers[j].pokemonIndex==i
  896.             @battlers[j].pokemonIndex-=1
  897.             break
  898.           end
  899.         end
  900.       end
  901.     else
  902.       if battlerIndex<pbSecondPartyBegin(battlerIndex)-1
  903.         for i in battlerIndex...pbSecondPartyBegin(battlerIndex)
  904.           if i>=pbSecondPartyBegin(battlerIndex)-1
  905.             party[i]=nil
  906.           else
  907.             party[i]=party[i+1]
  908.           end
  909.         end
  910.       else
  911.         for i in battlerIndex...party.length
  912.           if i>=party.length-1
  913.             party[i]=nil
  914.           else
  915.             party[i]=party[i+1]
  916.           end
  917.         end
  918.       end
  919.     end
  920.   end
  921.  
  922. ################################################################################
  923. # Check whether actions can be taken.
  924. ################################################################################
  925.   def pbCanShowCommands?(idxPokemon)
  926.     thispkmn=@battlers[idxPokemon]
  927.     return false if thispkmn.isFainted?
  928.     return false if thispkmn.effects[PBEffects::TwoTurnAttack]>0
  929.     return false if thispkmn.effects[PBEffects::HyperBeam]>0
  930.     return false if thispkmn.effects[PBEffects::Rollout]>0
  931.     return false if thispkmn.effects[PBEffects::Outrage]>0
  932.     return false if thispkmn.effects[PBEffects::Uproar]>0
  933.     return false if thispkmn.effects[PBEffects::Bide]>0
  934.     return true
  935.   end
  936.  
  937. ################################################################################
  938. # Attacking.
  939. ################################################################################
  940.   def pbCanShowFightMenu?(idxPokemon)
  941.     thispkmn=@battlers[idxPokemon]
  942.     if !pbCanShowCommands?(idxPokemon)
  943.       return false
  944.     end
  945.     # No moves that can be chosen
  946.     if !pbCanChooseMove?(idxPokemon,0,false) &&
  947.        !pbCanChooseMove?(idxPokemon,1,false) &&
  948.        !pbCanChooseMove?(idxPokemon,2,false) &&
  949.        !pbCanChooseMove?(idxPokemon,3,false)
  950.       return false
  951.     end
  952.     # Encore
  953.     return false if thispkmn.effects[PBEffects::Encore]>0
  954.     return true
  955.   end
  956.  
  957.   def pbCanChooseMove?(idxPokemon,idxMove,showMessages,sleeptalk=false)
  958.     thispkmn=@battlers[idxPokemon]
  959.     thismove=thispkmn.moves[idxMove]
  960.     opp1=thispkmn.pbOpposing1
  961.     opp2=thispkmn.pbOpposing2
  962.     if !thismove||thismove.id==0
  963.       return false
  964.     end
  965.     if thismove.pp<=0 && thismove.totalpp>0 && !sleeptalk
  966.       if showMessages
  967.         pbDisplayPaused(_INTL("There's no PP left for this move!"))
  968.       end
  969.       return false
  970.     end
  971.     if (thispkmn.hasWorkingItem(:FIRIUMZ)) ||
  972.        (thispkmn.hasWorkingItem(:WATERIUMZ)) ||
  973.        (thispkmn.hasWorkingItem(:GRASSIUMZ)) ||
  974.        (thispkmn.hasWorkingItem(:ELECTRIUMZ)) ||
  975.        (thispkmn.hasWorkingItem(:RAICHIUMZ)) ||
  976.        (thispkmn.hasWorkingItem(:PIKANIUMZ)) ||
  977.        (thispkmn.hasWorkingItem(:EEVEEIUMZ)) ||
  978.        (thispkmn.hasWorkingItem(:NORMALIUMZ)) ||
  979.        (thispkmn.hasWorkingItem(:ICIUMZ)) ||
  980.        (thispkmn.hasWorkingItem(:FIGHTINIUMZ)) ||
  981.        (thispkmn.hasWorkingItem(:SNORLIUMZ))
  982.       $game_switches[HASZSTONE]=true
  983.     else
  984.       $game_switches[HASZSTONE]=false
  985.     end
  986.     if thispkmn.effects[PBEffects::ChoiceBand]>=0 &&
  987.        (thispkmn.hasWorkingItem(:CHOICEBAND) ||
  988.        thispkmn.hasWorkingItem(:CHOICESPECS) ||
  989.        thispkmn.hasWorkingItem(:CHOICESCARF))
  990.       hasmove=false
  991.       for i in 0...4
  992.         if thispkmn.moves[i].id==thispkmn.effects[PBEffects::ChoiceBand]
  993.           hasmove=true
  994.           break
  995.         end
  996.       end
  997.       if hasmove && thismove.id!=thispkmn.effects[PBEffects::ChoiceBand]
  998.         if showMessages
  999.           pbDisplayPaused(_INTL("{1} allows the use of only {2}!",
  1000.              PBItems.getName(thispkmn.item),
  1001.              PBMoves.getName(thispkmn.effects[PBEffects::ChoiceBand])))
  1002.         end
  1003.         return false
  1004.       end
  1005.     end
  1006.     if opp1.effects[PBEffects::Imprison]
  1007.       if thismove.id==opp1.moves[0].id ||
  1008.          thismove.id==opp1.moves[1].id ||
  1009.          thismove.id==opp1.moves[2].id ||
  1010.          thismove.id==opp1.moves[3].id
  1011.         if showMessages
  1012.           pbDisplayPaused(_INTL("{1} can't use the sealed {2}!",thispkmn.pbThis,thismove.name))
  1013.         end
  1014.        #PBDebug.log("[CanChoose][#{opp1.pbThis} has: #{opp1.moves[0].name}, #{opp1.moves[1].name},#{opp1.moves[2].name},#{opp1.moves[3].name}]")
  1015.         return false
  1016.       end
  1017.     end
  1018.     if opp2.effects[PBEffects::Imprison]
  1019.       if thismove.id==opp2.moves[0].id ||
  1020.          thismove.id==opp2.moves[1].id ||
  1021.          thismove.id==opp2.moves[2].id ||
  1022.          thismove.id==opp2.moves[3].id
  1023.         if showMessages
  1024.           pbDisplayPaused(_INTL("{1} can't use the sealed {2}!",thispkmn.pbThis,thismove.name))
  1025.         end
  1026.         #PBDebug.log("[CanChoose][#{opp2.pbThis} has: #{opp2.moves[0].name}, #{opp2.moves[1].name},#{opp2.moves[2].name},#{opp2.moves[3].name}]")
  1027.         return false
  1028.       end
  1029.     end
  1030.     if thispkmn.effects[PBEffects::Taunt]>0 && thismove.basedamage==0
  1031.       if showMessages
  1032.         pbDisplayPaused(_INTL("{1} can't use {2} after the Taunt!",thispkmn.pbThis,thismove.name))
  1033.       end
  1034.       return false
  1035.     end
  1036.     if thispkmn.effects[PBEffects::Torment]
  1037.       if thismove.id==thispkmn.lastMoveUsed
  1038.         if showMessages
  1039.           pbDisplayPaused(_INTL("{1} can't use the same move in a row due to the torment!",thispkmn.pbThis))
  1040.         end
  1041.         return false
  1042.       end
  1043.     end
  1044.     if thismove.id==thispkmn.effects[PBEffects::DisableMove] && !sleeptalk
  1045.       if showMessages
  1046.         pbDisplayPaused(_INTL("{1}'s {2} is disabled!",thispkmn.pbThis,thismove.name))
  1047.       end
  1048.       return false
  1049.     end
  1050.     if thispkmn.effects[PBEffects::Encore]>0 && idxMove!=thispkmn.effects[PBEffects::EncoreIndex]
  1051.       return false
  1052.     end
  1053.     return true
  1054.   end
  1055.  
  1056.   def pbAutoChooseMove(idxPokemon,showMessages=true)
  1057.     thispkmn=@battlers[idxPokemon]
  1058.     if thispkmn.isFainted?
  1059.       @choices[idxPokemon][0]=0
  1060.       @choices[idxPokemon][1]=0
  1061.       @choices[idxPokemon][2]=nil
  1062.       return
  1063.     end
  1064.     if thispkmn.effects[PBEffects::Encore]>0 &&
  1065.        pbCanChooseMove?(idxPokemon,thispkmn.effects[PBEffects::EncoreIndex],false)
  1066.       PBDebug.log("[Auto choosing Encore move...]")
  1067.       @choices[idxPokemon][0]=1    # "Use move"
  1068.       @choices[idxPokemon][1]=thispkmn.effects[PBEffects::EncoreIndex] # Index of move
  1069.       @choices[idxPokemon][2]=thispkmn.moves[thispkmn.effects[PBEffects::EncoreIndex]]
  1070.       @choices[idxPokemon][3]=-1   # No target chosen yet
  1071.       if @doublebattle
  1072.         thismove=thispkmn.moves[thispkmn.effects[PBEffects::EncoreIndex]]
  1073.         target=thispkmn.pbTarget(thismove)
  1074.         if target==PBTargets::SingleNonUser
  1075.           target=@scene.pbChooseTarget(idxPokemon)
  1076.           pbRegisterTarget(idxPokemon,target) if target>=0
  1077.         elsif target==PBTargets::UserOrPartner
  1078.           target=@scene.pbChooseTarget(idxPokemon)
  1079.           pbRegisterTarget(idxPokemon,target) if target>=0 && (target&1)==(idxPokemon&1)
  1080.         end
  1081.       end
  1082.     else
  1083.       if !pbIsOpposing?(idxPokemon)
  1084.         pbDisplayPaused(_INTL("{1} has no moves left!",thispkmn.name)) if showMessages
  1085.       end
  1086.       @choices[idxPokemon][0]=1           # "Use move"
  1087.       @choices[idxPokemon][1]=-1          # Index of move to be used
  1088.       @choices[idxPokemon][2]=@struggle   # Use Struggle
  1089.       @choices[idxPokemon][3]=-1          # No target chosen yet
  1090.     end
  1091.   end
  1092.  
  1093.   def pbRegisterMove(idxPokemon,idxMove,showMessages=true)
  1094.     thispkmn=@battlers[idxPokemon]
  1095.     move=thispkmn.moves[idxMove]
  1096.     if $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:WATERIUMZ) && isConst?(move.type,PBTypes,:WATER)
  1097.       $game_variables[134]=100 if move.id == 551
  1098.       $game_variables[134]=185 if move.id == 536
  1099.       $game_variables[134]=175 if move.id == 538
  1100.       $game_variables[134]=120 if move.id == 546
  1101.       $game_variables[134]=160 if move.id == 543
  1102.       $game_variables[134]=100 if move.id == 552
  1103.       $game_variables[134]=100 if move.id == 554
  1104.       $game_variables[134]=180 if move.id == 540
  1105.       $game_variables[134]=120 if move.id == 547
  1106.       $game_variables[134]=100 if move.id == 553
  1107.       $game_variables[134]=160 if move.id == 541
  1108.       $game_variables[134]=200 if move.id == 534
  1109.       $game_variables[134]=200 if move.id == 535
  1110.       $game_variables[134]=175 if move.id == 537
  1111.       $game_variables[134]=120 if move.id == 548
  1112.       $game_variables[134]=120 if move.id == 545
  1113.       $game_variables[134]=175 if move.id == 539
  1114.       $game_variables[134]=100 if move.id == 550
  1115.       $game_variables[134]=160 if move.id == 542
  1116.       $game_variables[134]=160 if move.id == 549
  1117.       $game_variables[134]=140 if move.id == 544
  1118.       $game_variables[134]=185 if move.id == 612
  1119.       $game_variables[134]=100 if move.id == 609
  1120.       $game_variables[134]=185 if move.id == 617
  1121.       $game_variables[134]=160 if move.id == 656
  1122.       $game_variables[134]=175 if move.id == 692
  1123.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:HYDROVORTEX)))
  1124.       pbZMoveIOff
  1125.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:FIRIUMZ) && isConst?(move.type,PBTypes,:FIRE)
  1126.       $game_variables[134]=140 if move.id == 140
  1127.       $game_variables[134]=100 if move.id == 146
  1128.       $game_variables[134]=175 if move.id == 136
  1129.       $game_variables[134]=100 if move.id == 147
  1130.       $game_variables[134]=185 if move.id == 128
  1131.       $game_variables[134]=120 if move.id == 143
  1132.       $game_variables[134]=180 if move.id == 134
  1133.       $game_variables[134]=175 if move.id == 132
  1134.       $game_variables[134]=200 if move.id == 125
  1135.       $game_variables[134]=160 if move.id == 137
  1136.       $game_variables[134]=200 if move.id == 124
  1137.       $game_variables[134]=195 if move.id == 126
  1138.       $game_variables[134]=190 if move.id == 129
  1139.       $game_variables[134]=120 if move.id == 142
  1140.       $game_variables[134]=160 if move.id == 139
  1141.       $game_variables[134]=180 if move.id == 130
  1142.       $game_variables[134]=140 if move.id == 141
  1143.       $game_variables[134]=100 if move.id == 145
  1144.       $game_variables[134]=120 if move.id == 148
  1145.       $game_variables[134]=180 if move.id == 133
  1146.       $game_variables[134]=160 if move.id == 144
  1147.       $game_variables[134]=160 if move.id == 149
  1148.       $game_variables[134]=180 if move.id == 135
  1149.       $game_variables[134]=195 if move.id == 127
  1150.       $game_variables[134]=160 if move.id == 138
  1151.       $game_variables[134]=220 if move.id == 123
  1152.       $game_variables[134]=180 if move.id == 131
  1153.       $game_variables[134]=140 if move.id == 591
  1154.       $game_variables[134]=299 if move.id == 673
  1155.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:INFERNOOVERDRIVE)))
  1156.       pbZMoveIOff
  1157.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:GRASSIUMZ) && isConst?(move.type,PBTypes,:GRASS)
  1158.       $game_variables[134]=200 if move.id == 190
  1159.       $game_variables[134]=195 if move.id == 191
  1160.       $game_variables[134]=190 if move.id == 192
  1161.       $game_variables[134]=190 if move.id == 193
  1162.       $game_variables[134]=190 if move.id == 194
  1163.       $game_variables[134]=190 if move.id == 195
  1164.       $game_variables[134]=190 if move.id == 196
  1165.       $game_variables[134]=175 if move.id == 197
  1166.       $game_variables[134]=175 if move.id == 198
  1167.       $game_variables[134]=160 if move.id == 199
  1168.       $game_variables[134]=140 if move.id == 200
  1169.       $game_variables[134]=140 if move.id == 201
  1170.       $game_variables[134]=120 if move.id == 202
  1171.       $game_variables[134]=120 if move.id == 203
  1172.       $game_variables[134]=120 if move.id == 204
  1173.       $game_variables[134]=100 if move.id == 205
  1174.       $game_variables[134]=160 if move.id == 206
  1175.       $game_variables[134]=120 if move.id == 207
  1176.       $game_variables[134]=100 if move.id == 208
  1177.       $game_variables[134]=140 if move.id == 209
  1178.       $game_variables[134]=100 if move.id == 210
  1179.       $game_variables[134]=160 if move.id == 211
  1180.       $game_variables[134]=175 if move.id == 597
  1181.       $game_variables[134]=100 if move.id == 661
  1182.       $game_variables[134]=190 if move.id == 662
  1183.       $game_variables[134]=140 if move.id == 666
  1184.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:BLOOMDOOM)))
  1185.       pbZMoveIOff
  1186.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:ELECTRIUMZ) && isConst?(move.type,PBTypes,:ELECTRIC)
  1187.       $game_variables[134]=175 if move.id == 69
  1188.       $game_variables[134]=140 if move.id == 72
  1189.       $game_variables[134]=100 if move.id == 79
  1190.       $game_variables[134]=185 if move.id == 65
  1191.       $game_variables[134]=190 if move.id == 67
  1192.       $game_variables[134]=120 if move.id == 74
  1193.       $game_variables[134]=190 if move.id == 66
  1194.       $game_variables[134]=120 if move.id == 76
  1195.       $game_variables[134]=120 if move.id == 75
  1196.       $game_variables[134]=160 if move.id == 71
  1197.       $game_variables[134]=100 if move.id == 78
  1198.       $game_variables[134]=160 if move.id == 80
  1199.       $game_variables[134]=140 if move.id == 73
  1200.       $game_variables[134]=100 if move.id == 77
  1201.       $game_variables[134]=175 if move.id == 70
  1202.       $game_variables[134]=195 if move.id == 64
  1203.       $game_variables[134]=180 if move.id == 68
  1204.       $game_variables[134]=120 if move.id == 595
  1205.       $game_variables[134]=100 if move.id == 593
  1206.       $game_variables[134]=160 if move.id == 674
  1207.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:GIGAVOLTHAVOC)))
  1208.       pbZMoveIOff
  1209.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:RAICHIUMZ) && thispkmn.species==PBSpecies::RAICHU  && move.id == 69
  1210.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:STOKEDSPARKSURFER)))
  1211.       pbZMoveIOff
  1212.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:SNORLIUMZ) && thispkmn.species==PBSpecies::SNORLAX && move.id == 262
  1213.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:PULVERIZINGPANCAKE)))
  1214.       pbZMoveIOff
  1215.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:PIKANIUMZ) && thispkmn.species==PBSpecies::PIKACHU && move.id == 66
  1216.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:CATASTROPIKA)))
  1217.       pbZMoveIOff
  1218.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:EEVEEIUMZ) && thispkmn.species==PBSpecies::EEVEE && move.id == 264
  1219.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:EXTREMEEVOBOOST)))
  1220.       pbZMoveIOff
  1221.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:NORMALIUMZ) && isConst?(move.type,PBTypes,:NORMAL)
  1222.       $game_variables[134]=200 if move.id == 260
  1223.       $game_variables[134]=200 if move.id == 261
  1224.       $game_variables[134]=200 if move.id == 262
  1225.       $game_variables[134]=200 if move.id == 263
  1226.       $game_variables[134]=200 if move.id == 264
  1227.       $game_variables[134]=190 if move.id == 265
  1228.       $game_variables[134]=190 if move.id == 266
  1229.       $game_variables[134]=190 if move.id == 267
  1230.       $game_variables[134]=190 if move.id == 268
  1231.       $game_variables[134]=180 if move.id == 269
  1232.       $game_variables[134]=180 if move.id == 270
  1233.       $game_variables[134]=195 if move.id == 271
  1234.       $game_variables[134]=175 if move.id == 272
  1235.       $game_variables[134]=175 if move.id == 273
  1236.       $game_variables[134]=175 if move.id == 274
  1237.       $game_variables[134]=175 if move.id == 275
  1238.       $game_variables[134]=160 if move.id == 276
  1239.       $game_variables[134]=190 if move.id == 277
  1240.       $game_variables[134]=160 if move.id == 278
  1241.       $game_variables[134]=160 if move.id == 279
  1242.       $game_variables[134]=160 if move.id == 280
  1243.       $game_variables[134]=160 if move.id == 281
  1244.       $game_variables[134]=160 if move.id == 282
  1245.       $game_variables[134]=160 if move.id == 283
  1246.       $game_variables[134]=160 if move.id == 284
  1247.       $game_variables[134]=140 if move.id == 285
  1248.       $game_variables[134]=140 if move.id == 286
  1249.       $game_variables[134]=140 if move.id == 287
  1250.       $game_variables[134]=140 if move.id == 288
  1251.       $game_variables[134]=140 if move.id == 289
  1252.       $game_variables[134]=140 if move.id == 290
  1253.       $game_variables[134]=140 if move.id == 291
  1254.       $game_variables[134]=140 if move.id == 292
  1255.       $game_variables[134]=140 if move.id == 293
  1256.       $game_variables[134]=120 if move.id == 294
  1257.       $game_variables[134]=120 if move.id == 295
  1258.       $game_variables[134]=120 if move.id == 296
  1259.       $game_variables[134]=120 if move.id == 297
  1260.       $game_variables[134]=140 if move.id == 298
  1261.       $game_variables[134]=120 if move.id == 299
  1262.       $game_variables[134]=100 if move.id == 300
  1263.       $game_variables[134]=100 if move.id == 301
  1264.       $game_variables[134]=1   if move.id == 302
  1265.       $game_variables[134]=100 if move.id == 303
  1266.       $game_variables[134]=160 if move.id == 304
  1267.       $game_variables[134]=100 if move.id == 305
  1268.       $game_variables[134]=100 if move.id == 306
  1269.       $game_variables[134]=100 if move.id == 307
  1270.       $game_variables[134]=100 if move.id == 308
  1271.       $game_variables[134]=100 if move.id == 309
  1272.       $game_variables[134]=100 if move.id == 310
  1273.       $game_variables[134]=100 if move.id == 311
  1274.       $game_variables[134]=100 if move.id == 312
  1275.       $game_variables[134]=140 if move.id == 313
  1276.       $game_variables[134]=100 if move.id == 314
  1277.       $game_variables[134]=140 if move.id == 315
  1278.       $game_variables[134]=100 if move.id == 316
  1279.       $game_variables[134]=100 if move.id == 317
  1280.       $game_variables[134]=100 if move.id == 318
  1281.       $game_variables[134]=100 if move.id == 319
  1282.       $game_variables[134]=100 if move.id == 320
  1283.       $game_variables[134]=100 if move.id == 321
  1284.       $game_variables[134]=100 if move.id == 322
  1285.       $game_variables[134]=100 if move.id == 323
  1286.       $game_variables[134]=100 if move.id == 324
  1287.       $game_variables[134]=100 if move.id == 325
  1288.       $game_variables[134]=100 if move.id == 326
  1289.       $game_variables[134]=100 if move.id == 327
  1290.       $game_variables[134]=190 if move.id == 328
  1291.       $game_variables[134]=160 if move.id == 329
  1292.       $game_variables[134]=160 if move.id == 330
  1293.       $game_variables[134]=160 if move.id == 331
  1294.       $game_variables[134]=180 if move.id == 332
  1295.       $game_variables[134]=120 if move.id == 333
  1296.       $game_variables[134]=180 if move.id == 334
  1297.       $game_variables[134]=160 if move.id == 335
  1298.       $game_variables[134]=100 if move.id == 336
  1299.       $game_variables[134]=160 if move.id == 337
  1300.       $game_variables[134]=100 if move.id == 338
  1301.       $game_variables[134]=100 if move.id == 339
  1302.       $game_variables[134]=100 if move.id == 340
  1303.       $game_variables[134]=160 if move.id == 341
  1304.       $game_variables[134]=100 if move.id == 342
  1305.       $game_variables[134]=200 if move.id == 563 #Boom Burst
  1306.       $game_variables[134]=100 if move.id == 620 #Hold-Back
  1307.       $game_variables[134]=185 if move.id == 672 #Multi-Attack
  1308.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:BREAKNECKBLITZ)))
  1309.       pbZMoveIOff
  1310.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:ICIUMZ) && isConst?(move.type,PBTypes,:ICE)
  1311.       $game_variables[134]=200 if move.id == 240
  1312.       $game_variables[134]=200 if move.id == 241
  1313.       $game_variables[134]=185 if move.id == 242
  1314.       $game_variables[134]=175 if move.id == 243
  1315.       $game_variables[134]=160 if move.id == 244
  1316.       $game_variables[134]=140 if move.id == 245
  1317.       $game_variables[134]=120 if move.id == 246
  1318.       $game_variables[134]=120 if move.id == 247
  1319.       $game_variables[134]=120 if move.id == 248
  1320.       $game_variables[134]=120 if move.id == 249
  1321.       $game_variables[134]=100 if move.id == 250
  1322.       $game_variables[134]=120 if move.id == 251
  1323.       $game_variables[134]=100 if move.id == 252
  1324.       $game_variables[134]=100 if move.id == 253
  1325.       $game_variables[134]=100 if move.id == 254
  1326.       $game_variables[134]=140 if move.id == 255
  1327.       $game_variables[134]=180 if move.id == 256
  1328.       $game_variables[134]=140 if move.id == 579 #Freeze-Dry
  1329.       $game_variables[134]=180 if move.id == 653 #Ice Hammer
  1330.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:SUBZEROSLAMMER)))
  1331.       pbZMoveIOff
  1332.     elsif $game_switches[NO_Z_MOVE]==true && thispkmn.hasWorkingItem(:FIGHTINIUMZ) && isConst?(move.type,PBTypes,:FIGHTING)
  1333.       $game_variables[134]=200 if move.id == 84
  1334.       $game_variables[134]=200 if move.id == 85
  1335.       $game_variables[134]=200 if move.id == 86
  1336.       $game_variables[134]=200 if move.id == 87
  1337.       $game_variables[134]=200 if move.id == 88
  1338.       $game_variables[134]=200 if move.id == 89
  1339.       $game_variables[134]=200 if move.id == 90
  1340.       $game_variables[134]=200 if move.id == 91
  1341.       $game_variables[134]=200 if move.id == 92
  1342.       $game_variables[134]=200 if move.id == 93
  1343.       $game_variables[134]=200 if move.id == 94
  1344.       $game_variables[134]=200 if move.id == 95
  1345.       $game_variables[134]=200 if move.id == 96
  1346.       $game_variables[134]=200 if move.id == 97
  1347.       $game_variables[134]=200 if move.id == 98
  1348.       $game_variables[134]=200 if move.id == 99
  1349.       $game_variables[134]=200 if move.id == 100
  1350.       $game_variables[134]=200 if move.id == 101
  1351.       $game_variables[134]=200 if move.id == 102
  1352.       $game_variables[134]=200 if move.id == 103
  1353.       $game_variables[134]=200 if move.id == 104
  1354.       $game_variables[134]=200 if move.id == 105
  1355.       $game_variables[134]=200 if move.id == 106
  1356.       $game_variables[134]=200 if move.id == 107
  1357.       $game_variables[134]=200 if move.id == 108
  1358.       $game_variables[134]=200 if move.id == 109
  1359.       $game_variables[134]=200 if move.id == 110
  1360.       $game_variables[134]=200 if move.id == 111
  1361.       $game_variables[134]=200 if move.id == 112
  1362.       $game_variables[134]=200 if move.id == 113
  1363.       $game_variables[134]=200 if move.id == 114
  1364.       $game_variables[134]=200 if move.id == 115
  1365.       $game_variables[134]=200 if move.id == 116
  1366.       $game_variables[134]=200 if move.id == 117
  1367.       $game_variables[134]=200 if move.id == 118
  1368.       $game_variables[134]=200 if move.id == 119
  1369.       thismove=PokeBattle_Move.pbFromPBMove(self,PBMove.new(getConst(PBMoves,:ALLOUTPUMMELING)))
  1370.       pbZMoveIOff  
  1371.     else
  1372.       thismove=thispkmn.moves[idxMove]
  1373.     end
  1374.     #thismove=thispkmn.moves[idxMove]
  1375.     return false if !pbCanChooseMove?(idxPokemon,idxMove,showMessages)
  1376.     @choices[idxPokemon][0]=1         # "Use move"
  1377.     @choices[idxPokemon][1]=idxMove   # Index of move to be used
  1378.     @choices[idxPokemon][2]=thismove  # PokeBattle_Move object of the move
  1379.     @choices[idxPokemon][3]=-1        # No target chosen yet
  1380.     return true
  1381.   end
  1382.  
  1383.   def pbZMoveIOff
  1384.     $game_switches[NO_Z_MOVE]=false
  1385.     $game_switches[NO_Z_MOVEM]=true
  1386.   end
  1387.  
  1388.   def pbChoseMove?(i,move)
  1389.     return false if @battlers[i].isFainted?
  1390.     if @choices[i][0]==1 && @choices[i][1]>=0
  1391.       choice=@choices[i][1]
  1392.       return isConst?(@battlers[i].moves[choice].id,PBMoves,move)
  1393.     end
  1394.     return false
  1395.   end
  1396.  
  1397.   def pbChoseMoveFunctionCode?(i,code)
  1398.     return false if @battlers[i].isFainted?
  1399.     if @choices[i][0]==1 && @choices[i][1]>=0
  1400.       choice=@choices[i][1]
  1401.       return @battlers[i].moves[choice].function==code
  1402.     end
  1403.     return false
  1404.   end
  1405.  
  1406.   def pbRegisterTarget(idxPokemon,idxTarget)
  1407.     @choices[idxPokemon][3]=idxTarget   # Set target of move
  1408.     return true
  1409.   end
  1410.  
  1411.   def pbPriorityOld(ignorequickclaw=false)
  1412.     if @usepriority
  1413.       # use stored priority if round isn't over yet
  1414.       return @priority
  1415.     end
  1416.     speeds=[]
  1417.     quickclaw=[]
  1418.     priorities=[]
  1419.     temp=[]
  1420.     @priority.clear
  1421.     maxpri=0
  1422.     minpri=0
  1423.     # Calculate each Pokémon's speed
  1424.     for i in 0...4
  1425.       speeds[i]=@battlers[i].pbSpeed
  1426.       quickclaw[i]=@battlers[i].hasWorkingItem(:QUICKCLAW)
  1427.       quickclaw[i]=false if @choices[i][0]!=1
  1428.       quickclaw[i]=false if !(pbRandom(100)<20)
  1429.       quickclaw[i]=false if ignorequickclaw
  1430.     end
  1431.     # Find the maximum and minimum priority
  1432.     for i in 0...4
  1433.       # For this function, switching and using items
  1434.       # is the same as using a move with a priority of 0
  1435.       pri=0
  1436.       if @choices[i][0]==1 # Is a move
  1437.         thismove=@choices[i][2]
  1438.         pri=@choices[i][2].priority
  1439.         pri+=3 if @battlers[i].hasWorkingAbility(:TRIAGE) &&
  1440.                   @choices[i][2].isTriageBoosted?
  1441.         pri+=1 if @battlers[i].hasWorkingAbility(:GALEWINGS) &&
  1442.                   isConst?(@choices[i][2].type,PBTypes,:FLYING)
  1443.         pri+=1 if @battlers[i].hasWorkingAbility(:PRANKSTER) && @choices[i][2].basedamage==0 # Is status move
  1444.       end
  1445.       priorities[i]=pri
  1446.       if i==0
  1447.         maxpri=pri
  1448.         minpri=pri
  1449.       else
  1450.         maxpri=pri if maxpri<pri
  1451.         minpri=pri if minpri>pri
  1452.       end
  1453.     end
  1454.     # Find and order all moves with the same priority
  1455.     curpri=maxpri
  1456.     loop do
  1457.       temp.clear
  1458.       for j in 0...4
  1459.         if priorities[j]==curpri
  1460.           temp[temp.length]=j
  1461.         end
  1462.       end
  1463.       # Sort by speed
  1464.       if temp.length==1
  1465.         @priority[@priority.length]=@battlers[temp[0]]
  1466.       else
  1467.         n=temp.length
  1468.         for m in 0..n-2
  1469.           for i in 1..n-1
  1470.             if quickclaw[temp[i]]
  1471.               cmp=(quickclaw[temp[i-1]]) ? 0 : -1 #Rank higher if without Quick Claw, or equal if with it
  1472.             elsif quickclaw[temp[i-1]]
  1473.               cmp=1 # Rank lower
  1474.             elsif speeds[temp[i]]!=speeds[temp[i-1]]
  1475.               cmp=(speeds[temp[i]]>speeds[temp[i-1]]) ? -1 : 1 #Rank higher to higher-speed battler
  1476.             else
  1477.               cmp=0
  1478.             end
  1479.             if cmp<0
  1480.               # put higher-speed Pokémon first
  1481.               swaptmp=temp[i]
  1482.               temp[i]=temp[i-1]
  1483.               temp[i-1]=swaptmp
  1484.             elsif cmp==0
  1485.               # swap at random if speeds are equal
  1486.               if pbRandom(2)==0
  1487.                 swaptmp=temp[i]
  1488.                 temp[i]=temp[i-1]
  1489.                 temp[i-1]=swaptmp
  1490.               end
  1491.             end
  1492.           end
  1493.         end
  1494.         #Now add the temp array to priority
  1495.         for i in temp
  1496.           @priority[@priority.length]=@battlers[i]
  1497.         end
  1498.       end
  1499.       curpri-=1
  1500.       break unless curpri>=minpri
  1501.     end
  1502.  
  1503. =begin
  1504.     prioind=[
  1505.        @priority[0].index,
  1506.        @priority[1].index,
  1507.        @priority[2] ? @priority[2].index : -1,
  1508.        @priority[3] ? @priority[3].index : -1
  1509.     ]
  1510.     print("#{speeds.inspect} #{prioind.inspect}")
  1511. =end
  1512.  
  1513.     @usepriority=true
  1514.     d="   Priority: #{@priority[0].index}"
  1515.     d+=", #{@priority[1].index}" if @priority[1]
  1516.     d+=", #{@priority[2].index}" if @priority[2]
  1517.     d+=", #{@priority[3].index}" if @priority[3]
  1518.     PBDebug.log(d)
  1519.     return @priority
  1520.   end
  1521.  
  1522.   def pbPriority(ignorequickclaw=false)
  1523.     if @usepriority
  1524.       # use stored priority if round isn't over yet
  1525.       return @priority
  1526.     end
  1527.     speeds=[]
  1528.     quickclaw=[]
  1529.     priorities=[]
  1530.     temp=[]
  1531.     @priority.clear
  1532.     maxpri=0
  1533.     minpri=0
  1534.     # Calculate each Pokémon's speed
  1535.     speeds[0]=@battlers[0].pbSpeed
  1536.     speeds[1]=@battlers[1].pbSpeed
  1537.     speeds[2]=@battlers[2].pbSpeed
  1538.     speeds[3]=@battlers[3].pbSpeed
  1539.     quickclaw[0]=isConst?(@battlers[0].item,PBItems,:QUICKCLAW)
  1540.     quickclaw[1]=isConst?(@battlers[1].item,PBItems,:QUICKCLAW)
  1541.     quickclaw[2]=isConst?(@battlers[2].item,PBItems,:QUICKCLAW)
  1542.     quickclaw[3]=isConst?(@battlers[3].item,PBItems,:QUICKCLAW)
  1543.     quickclaw[0]=false if ignorequickclaw
  1544.     quickclaw[1]=false if ignorequickclaw
  1545.     quickclaw[2]=false if ignorequickclaw
  1546.     quickclaw[3]=false if ignorequickclaw
  1547.     # Find the maximum and minimum priority
  1548.     for i in 0..3
  1549.       # For this function, switching and using items
  1550.       # is the same as using a move with a priority of 0
  1551.       pri=(@choices[i][0]!=1)?0:@choices[i][2].priority
  1552.       priorities[i]=pri
  1553.       if i==0
  1554.         maxpri=pri
  1555.         minpri=pri
  1556.       else
  1557.         maxpri=pri if maxpri<pri
  1558.         minpri=pri if minpri>pri
  1559.       end
  1560.     end
  1561.     # Find and order all moves with the same priority
  1562.     curpri=maxpri
  1563.     loop do
  1564.       temp.clear
  1565.       for j in 0..3
  1566.         if priorities[j]==curpri
  1567.           temp[temp.length]=j
  1568.         end
  1569.       end
  1570.       # Sort by speed
  1571.       if temp.length==1
  1572.         @priority[@priority.length]=@battlers[temp[0]]
  1573.       else
  1574.         n=temp.length
  1575.         usequickclaw=(pbRandom(5)==0)
  1576.         for m in 0..n-2
  1577.           for i in m+1..n-1
  1578.             if quickclaw[temp[i]] && usequickclaw
  1579.               cmp=(quickclaw[temp[i-1]]) ? 0 : -1 #Rank higher if without Quick Claw, or equal if with it
  1580.             elsif quickclaw[temp[i-1]] && usequickclaw
  1581.               cmp=1 # Rank lower
  1582.             elsif speeds[temp[i]]!=speeds[temp[i-1]]
  1583.               cmp=(speeds[temp[i]]>speeds[temp[i-1]]) ? -1 : 1 #Rank higher to higher-speed battler
  1584.             else
  1585.               cmp=0
  1586.             end
  1587.             if cmp<0
  1588.               # put higher-speed Pokémon first
  1589.               swaptmp=temp[i]
  1590.               temp[i]=temp[i-1]
  1591.               temp[i-1]=swaptmp
  1592.             elsif cmp==0
  1593.               # swap at random if speeds are equal
  1594.               if pbRandom(2)==0
  1595.                 swaptmp=temp[i]
  1596.                 temp[i]=temp[i-1]
  1597.                 temp[i-1]=swaptmp
  1598.               end
  1599.             end
  1600.           end
  1601.         end
  1602.         #Now add the temp array to priority
  1603.         for i in temp
  1604.           @priority[@priority.length]=@battlers[i]
  1605.         end
  1606.       end
  1607.       curpri-=1
  1608.       break unless curpri>=minpri
  1609.     end
  1610.      
  1611. =begin
  1612.     prioind=[
  1613.        @priority[0].index,
  1614.        @priority[1].index,
  1615.        @priority[2] ? @priority[2].index : -1,
  1616.        @priority[3] ? @priority[3].index : -1
  1617.     ]
  1618.     print("#{speeds.inspect} #{prioind.inspect}")
  1619. =end
  1620.  
  1621.     @usepriority=true
  1622.     return @priority
  1623.   end
  1624.  
  1625. ################################################################################
  1626. # Switching Pokémon.
  1627. ################################################################################
  1628.   def pbCanSwitchLax?(idxPokemon,pkmnidxTo,showMessages)
  1629.     if pkmnidxTo>=0
  1630.       party=pbParty(idxPokemon)
  1631.       if pkmnidxTo>=party.length
  1632.         return false
  1633.       end
  1634.       if !party[pkmnidxTo]
  1635.         return false
  1636.       end
  1637.       if party[pkmnidxTo].isEgg?
  1638.         pbDisplayPaused(_INTL("An Egg can't battle!")) if showMessages
  1639.         return false
  1640.       end
  1641.       if !pbIsOwner?(idxPokemon,pkmnidxTo)
  1642.         owner=pbPartyGetOwner(idxPokemon,pkmnidxTo)
  1643.         pbDisplayPaused(_INTL("You can't switch {1}'s Pokémon with one of yours!",owner.name)) if showMessages
  1644.         return false
  1645.       end
  1646.       if party[pkmnidxTo].hp<=0
  1647.         pbDisplayPaused(_INTL("{1} has no energy left to battle!",party[pkmnidxTo].name)) if showMessages
  1648.         return false
  1649.       end  
  1650.       if @battlers[idxPokemon].pokemonIndex==pkmnidxTo ||
  1651.          @battlers[idxPokemon].pbPartner.pokemonIndex==pkmnidxTo
  1652.         pbDisplayPaused(_INTL("{1} is already in battle!",party[pkmnidxTo].name)) if showMessages
  1653.         return false
  1654.       end
  1655.     end
  1656.     return true
  1657.   end
  1658.  
  1659.   def pbCanSwitch?(idxPokemon,pkmnidxTo,showMessages)
  1660.     thispkmn=@battlers[idxPokemon]
  1661.     # Multi-Turn Attacks/Mean Look
  1662.     if !pbCanSwitchLax?(idxPokemon,pkmnidxTo,showMessages)
  1663.       return false
  1664.     end
  1665.     isOpposing=pbIsOpposing?(idxPokemon)
  1666.     party=pbParty(idxPokemon)
  1667.     for i in 0...4
  1668.       next if isOpposing!=pbIsOpposing?(i)
  1669.       if choices[i][0]==2 && choices[i][1]==pkmnidxTo
  1670.         pbDisplayPaused(_INTL("{1} has already been selected.",party[pkmnidxTo].name)) if showMessages
  1671.         return false
  1672.       end
  1673.     end
  1674.     if thispkmn.hasWorkingItem(:SHEDSHELL)
  1675.       return true
  1676.     end
  1677.     if thispkmn.effects[PBEffects::MultiTurn]>0 ||
  1678.        thispkmn.effects[PBEffects::MeanLook]>=0
  1679.       pbDisplayPaused(_INTL("{1} can't be switched out!",thispkmn.pbThis)) if showMessages
  1680.       return false
  1681.     end
  1682.     # Ingrain
  1683.     if thispkmn.effects[PBEffects::Ingrain]
  1684.       pbDisplayPaused(_INTL("{1} can't be switched out!",thispkmn.pbThis)) if showMessages
  1685.       return false
  1686.     end
  1687.     opp1=thispkmn.pbOpposing1
  1688.     opp2=thispkmn.pbOpposing2
  1689.     opp=nil
  1690.     if thispkmn.pbHasType?(:STEEL)
  1691.       opp=opp1 if opp1.hasWorkingAbility(:MAGNETPULL)
  1692.       opp=opp2 if opp2.hasWorkingAbility(:MAGNETPULL)
  1693.     end
  1694.     if !thispkmn.isAirborne?
  1695.       opp=opp1 if opp1.hasWorkingAbility(:ARENATRAP)
  1696.       opp=opp2 if opp2.hasWorkingAbility(:ARENATRAP)
  1697.     end
  1698.     if !thispkmn.hasWorkingAbility(:SHADOWTAG)
  1699.       opp=opp1 if opp1.hasWorkingAbility(:SHADOWTAG)
  1700.       opp=opp2 if opp2.hasWorkingAbility(:SHADOWTAG)
  1701.     end
  1702.     if opp
  1703.       abilityname=PBAbilities.getName(opp.ability)
  1704.       pbDisplayPaused(_INTL("{1}'s {2} prevents switching!",opp.pbThis,abilityname)) if showMessages
  1705.       return false
  1706.     end
  1707.     return true
  1708.   end
  1709.  
  1710.   def pbRegisterSwitch(idxPokemon,idxOther)
  1711.     return false if !pbCanSwitch?(idxPokemon,idxOther,false)
  1712.     @choices[idxPokemon][0]=2          # "Switch Pokémon"
  1713.     @choices[idxPokemon][1]=idxOther   # Index of other Pokémon to switch with
  1714.     @choices[idxPokemon][2]=nil
  1715.     side=(pbIsOpposing?(idxPokemon)) ? 1 : 0
  1716.     owner=pbGetOwnerIndex(idxPokemon)
  1717.     if @megaEvolution[side][owner]==idxPokemon
  1718.       @megaEvolution[side][owner]=-1
  1719.     end
  1720.     return true
  1721.   end
  1722.  
  1723.   def pbCanChooseNonActive?(index)
  1724.     party=pbParty(index)
  1725.     for i in 0..party.length-1
  1726.       return true if pbCanSwitchLax?(index,i,false)
  1727.     end
  1728.     return false
  1729.   end
  1730.  
  1731.   def pbSwitch(favorDraws=false)
  1732.     if !favorDraws
  1733.       return if @decision>0
  1734.       pbJudge()
  1735.       return if @decision>0
  1736.     else
  1737.       return if @decision==5
  1738.       pbJudge()
  1739.       return if @decision>0
  1740.     end
  1741.     firstbattlerhp=@battlers[0].hp
  1742.     switched=[]
  1743.     for index in 0...4
  1744.       next if !@doublebattle && pbIsDoubleBattler?(index)
  1745.       next if @battlers[index] && !@battlers[index].isFainted?
  1746.       next if !pbCanChooseNonActive?(index)
  1747.       if !pbOwnedByPlayer?(index)
  1748.         if !pbIsOpposing?(index) || (@opponent && pbIsOpposing?(index))
  1749.           newenemy=pbSwitchInBetween(index,false,false)
  1750.           if isConst?(@party2[newenemy].ability,PBAbilities,:ILLUSION) #ILLUSION
  1751.             party3=@party2.find_all {|item| item && !item.egg? && item.hp>0 }
  1752.             if party3[@party2.length-1] != @party2[newenemy]
  1753.               illusionpoke = party3[party3.length-1]
  1754.             end
  1755.           end #ILLUSION          
  1756.           opponent=pbGetOwner(index)
  1757.           if !@doublebattle && firstbattlerhp>0 && @shiftStyle && @opponent &&
  1758.               @internalbattle && pbCanChooseNonActive?(0) && pbIsOpposing?(index) &&
  1759.               @battlers[0].effects[PBEffects::Outrage]==0
  1760.             pbDisplayPaused(_INTL("{1} is about to send in {2}.",opponent.fullname,newname)) #ILLUSION
  1761.             if pbDisplayConfirmBW(_INTL("Will you switch your Pokémon?",self.pbPlayer.name),
  1762.               "SWITCH POKÉMON", "KEEP BATTLING")
  1763.               newpoke=pbSwitchPlayer(0,true,true)
  1764.               if newpoke>=0
  1765.                 pbDisplayBrief(_INTL("{1}, that's enough!  Come back!",@battlers[0].name))
  1766.                 pbRecallAndReplace(0,newpoke)
  1767.                 switched.push(0)
  1768.               end
  1769.             end
  1770.           end
  1771.           pbRecallAndReplace(index,newenemy)
  1772.           switched.push(index)
  1773.         end
  1774.       elsif @opponent
  1775.         newpoke=pbSwitchInBetween(index,true,false)
  1776.         pbRecallAndReplace(index,newpoke)
  1777.         switched.push(index)
  1778.       else
  1779.         switch=false
  1780.         if !pbDisplayConfirm(_INTL("Use next Pokémon?"))
  1781.           switch=(pbRun(index,true)<=0)
  1782.         else
  1783.           switch=true
  1784.         end
  1785.         if switch
  1786.           newpoke=pbSwitchInBetween(index,true,false)
  1787.           pbRecallAndReplace(index,newpoke)
  1788.           switched.push(index)
  1789.         end
  1790.       end
  1791.     end
  1792.     if switched.length>0
  1793.       priority=pbPriority
  1794.       for i in priority
  1795.         i.pbAbilitiesOnSwitchIn(true) if switched.include?(i.index)
  1796.       end
  1797.     end
  1798.   end
  1799.  
  1800.   def pbSendOut(index,pokemon)
  1801.     pbSetSeen(pokemon)
  1802.     @peer.pbOnEnteringBattle(self,pokemon)
  1803.     if pbIsOpposing?(index)
  1804.       @scene.pbTrainerSendOut(index,pokemon)
  1805.       # Last Pokemon script; credits to venom12 and HelioAU
  1806.       if pbPokemonCount(@party2)==1
  1807.         # Define any trainers that you want to activate this script below
  1808.         if isConst?(@opponent.trainertype,PBTrainers,:CHAMPION_3) or isConst?(@opponent.trainertype,PBTrainers,:CHAMPION_4) or isConst?(@opponent.trainertype,PBTrainers,:LEADER_Cheren) or isConst?(@opponent.trainertype,PBTrainers,:LEADER_Burgh) or isConst?(@opponent.trainertype,PBTrainers,:LEADER_4) or isConst?(@opponent.trainertype,PBTrainers,:LEADER_Clay) or isConst?(@opponent.trainertype,PBTrainers,:LEADER_Elesa) or isConst?(@opponent.trainertype,PBTrainers,:LEADER_Skyla) or isConst?(@opponent.trainertype,PBTrainers,:POKEMONTRAINER_Colress) or isConst?(@opponent.trainertype,PBTrainers,:LEADER_Drayden) or isConst?(@opponent.trainertype,PBTrainers,:RIVAL3) or isConst?(@opponent.trainertype,PBTrainers,:LEADER_Marlon)
  1809.           @scene.pbShowOpponent(0)
  1810.           # For each defined trainer, add the BELOW section for them
  1811.           if isConst?(@opponent.trainertype,PBTrainers,:CHAMPION_3)
  1812.             pbBGMPlay("LastPkMnGym",100,100)
  1813.             pbDisplayPaused(_INTL("Show me your true power!"))
  1814.           end
  1815.           if isConst?(@opponent.trainertype,PBTrainers,:CHAMPION_4)
  1816.             pbBGMPlay("LastPkMnGym",100,100)
  1817.             pbDisplayPaused(_INTL("Show me your true power!"))
  1818.           end
  1819.           if isConst?(@opponent.trainertype,PBTrainers,:LEADER_Cheren)
  1820.             pbBGMPlay("LastPkMnGym",100,100)
  1821.             pbDisplayPaused(_INTL("That's it. Show me what you got!"))
  1822.           end
  1823.           if isConst?(@opponent.trainertype,PBTrainers,:LEADER_Burgh)
  1824.             pbBGMPlay("LastPkMnGym",100,100)
  1825.             pbDisplayPaused(_INTL("This is getting tricky."))
  1826.           end
  1827.           if isConst?(@opponent.trainertype,PBTrainers,:Sabrina)
  1828.             pbBGMPlay("LastPkMnGym",100,100)
  1829.             pbDisplayPaused(_INTL("Your energy level is rising!"))
  1830.           end
  1831.           if isConst?(@opponent.trainertype,PBTrainers,:LEADER_Clay)
  1832.             pbBGMPlay("LastPkMnGym",100,100)
  1833.             pbDisplayPaused(_INTL("Your battle style is rock solid!"))
  1834.           end
  1835.           if isConst?(@opponent.trainertype,PBTrainers,:LEADER_Elesa)
  1836.             pbBGMPlay("LastPkMnGym",100,100)
  1837.             pbDisplayPaused(_INTL("Get ready to be shocked by this next move!"))
  1838.           end
  1839.           if isConst?(@opponent.trainertype,PBTrainers,:LEADER_Skyla)
  1840.             pbBGMPlay("LastPkMnGym",100,100)
  1841.             pbDisplayPaused(_INTL("Your about to get blown away!"))
  1842.           end
  1843.           if isConst?(@opponent.trainertype,PBTrainers,:RIVAL3)
  1844.             pbDisplayPaused(_INTL("My Fighting Spirit is at its max!"))
  1845.           end
  1846.           if isConst?(@opponent.trainertype,PBTrainers,:LEADER_Marlon)
  1847.             pbBGMPlay("LastPkMnGym",100,100)
  1848.             pbDisplayPaused(_INTL("Oh come on, You didn't have to rain on my parade."))
  1849.             Graphics.update
  1850.           end
  1851.           if $game_switches[131]
  1852.             if isConst?(@opponent.trainertype,PBTrainers,:LEADER_Skyla)
  1853.               pbBGMPlay("LastPkMnGym",100,100)
  1854.               pbDisplayPaused(_INTL("Show me all your strength!"))
  1855.             end
  1856.           end
  1857.           if isConst?(@opponent.trainertype,PBTrainers,:POKEMONTRAINER_Colress)
  1858.             pbDisplayPaused(_INTL("Your battle skills are quite impressive."))
  1859.           end
  1860.           # For each defined trainer, add the ABOVE section for them
  1861.           @scene.pbHideOpponent
  1862.         end
  1863.       end
  1864.     else
  1865.       @scene.pbSendOut(index,pokemon)
  1866.     end
  1867.     @scene.pbResetMoveIndex(index)
  1868.     # Primal Reversion
  1869.     pbPrimalReversion(index)    
  1870.   end
  1871.  
  1872.   def pbReplace(index,newpoke,batonpass=false)
  1873.     party=pbParty(index)
  1874.     if pbOwnedByPlayer?(index)
  1875.       # Reorder the party for this battle
  1876.       bpo=-1; bpn=-1
  1877.       for i in 0...6
  1878.         bpo=i if @partyorder[i]==@battlers[index].pokemonIndex
  1879.         bpn=i if @partyorder[i]==newpoke
  1880.       end
  1881.       poke1=@partyorder[bpo]
  1882.       @partyorder[bpo]=@partyorder[bpn]
  1883.       @partyorder[bpn]=poke1
  1884.       @battlers[index].pbInitialize(party[newpoke],newpoke,batonpass)
  1885.       pbSendOut(index,party[newpoke])
  1886.     else
  1887.       @battlers[index].pbInitialize(party[newpoke],newpoke,batonpass)
  1888.       pbSetSeen(party[newpoke])
  1889.       if pbIsOpposing?(index)
  1890.         pbSendOut(index,party[newpoke])
  1891.       else
  1892.         pbSendOut(index,party[newpoke])
  1893.       end
  1894.     end
  1895.   end    
  1896.  
  1897.   def pbRecallAndReplace(index,newpoke,batonpass=false,moldbreaker=false)
  1898.     @battlers[index].pbResetForm
  1899.     if !@battlers[index].isFainted?
  1900.       @scene.pbRecall(index)
  1901.     end
  1902.     pbMessagesOnReplace(index,newpoke)
  1903.     pbReplace(index,newpoke,batonpass)
  1904.     return pbOnActiveOne(@battlers[index],false,moldbreaker)
  1905.   end
  1906.  
  1907.   def pbMessagesOnReplace(index,newpoke)
  1908.     party=pbParty(index)
  1909.     if pbOwnedByPlayer?(index)
  1910. #     if !party[newpoke]
  1911. #       p [index,newpoke,party[newpoke],pbAllFainted?(party)]
  1912. #       PBDebug.log([index,newpoke,party[newpoke],"pbMOR"].inspect)
  1913. #       for i in 0...party.length
  1914. #         PBDebug.log([i,party[i].hp].inspect)
  1915. #       end
  1916. #       raise BattleAbortedException.new
  1917. #     end
  1918.       if isConst?(party[newpoke].ability,PBAbilities,:ILLUSION) #ILLUSION
  1919.         party2=party.find_all {|item| item && !item.egg? && item.hp>0 }
  1920.         if party2[party.length-1] != party[newpoke]
  1921.           illusionpoke = party[party.length-1]
  1922.         end
  1923.       end #ILLUSION
  1924.       newname = illusionpoke != nil ? illusionpoke.name : party[newpoke].name
  1925.       opposing=@battlers[index].pbOppositeOpposing
  1926.       if opposing.hp<=0 || opposing.hp==opposing.totalhp
  1927.         pbDisplayBrief(_INTL("Go! {1}!",newname))
  1928.       elsif opposing.hp>=(opposing.totalhp/2)
  1929.         pbDisplayBrief(_INTL("Do it! {1}!",newname))
  1930.       elsif opposing.hp>=(opposing.totalhp/4)
  1931.         pbDisplayBrief(_INTL("Go for it, {1}!",newname))
  1932.       else
  1933.         pbDisplayBrief(_INTL("Your foe's weak!\nGet 'em, {1}!",newname))
  1934.       end
  1935.       PBDebug.log("[Player sent out #{party[newpoke].name}]")
  1936.     else
  1937. #     if !party[newpoke]
  1938. #       p [index,newpoke,party[newpoke],pbAllFainted?(party)]
  1939. #       PBDebug.log([index,newpoke,party[newpoke],"pbMOR"].inspect)
  1940. #       for i in 0...party.length
  1941. #         PBDebug.log([i,party[i].hp].inspect)
  1942. #       end
  1943. #       raise BattleAbortedException.new
  1944. #     end
  1945.       if isConst?(party[newpoke].ability,PBAbilities,:ILLUSION) #ILLUSION
  1946.         party2=party.find_all {|item| item && !item.egg? && item.hp>0 }
  1947.         if party2[party.length-1] != party[newpoke]
  1948.           illusionpoke = party[party.length-1]
  1949.         end
  1950.       end #ILLUSION
  1951.       newname = illusionpoke != nil ? illusionpoke.name : party[newpoke].name #ILLUSION
  1952.       owner=pbGetOwner(index)
  1953.       pbDisplayBrief(_INTL("{1} sent\r\nout {2}!",owner.fullname,newname)) #ILLUSION
  1954.       PBDebug.log("[Opponent sent out #{party[newpoke].name}]")
  1955.     end
  1956.   end
  1957.  
  1958.   def pbSwitchInBetween(index,lax,cancancel)
  1959.     if !pbOwnedByPlayer?(index)
  1960.       return @scene.pbChooseNewEnemy(index,pbParty(index))
  1961.     else
  1962.       SetInputPlayer(index)
  1963.       SetInputPlayer(0)
  1964.       return pbSwitchPlayer(index,lax,cancancel)
  1965.     end
  1966.   end
  1967.  
  1968.   def pbSwitchPlayer(index,lax,cancancel)
  1969.     if @debug
  1970.       return @scene.pbChooseNewEnemy(index,pbParty(index))
  1971.     else
  1972.       return @scene.pbSwitch(index,lax,cancancel)
  1973.     end
  1974.   end
  1975.  
  1976. ################################################################################
  1977. # Using an item.
  1978. ################################################################################
  1979. # Uses an item on a Pokémon in the player's party.
  1980.   def pbUseItemOnPokemon(item,pkmnIndex,userPkmn,scene)
  1981.     pokemon=@party1[pkmnIndex]
  1982.     battler=nil
  1983.     name=pbGetOwner(userPkmn.index).fullname
  1984.     name=pbGetOwner(userPkmn.index).name if pbBelongsToPlayer?(userPkmn.index)
  1985.     pbDisplayBrief(_INTL("{1} used the\r\n{2}.",name,PBItems.getName(item)))
  1986.     PBDebug.log("[Player used #{PBItems.getName(item)}]")
  1987.     ret=false
  1988.     if pokemon.isEgg?
  1989.       pbDisplay(_INTL("But it had no effect!"))
  1990.     else
  1991.       for i in 0...4
  1992.         if !pbIsOpposing?(i) && @battlers[i].pokemonIndex==pkmnIndex
  1993.           battler=@battlers[i]
  1994.         end
  1995.       end
  1996.       ret=ItemHandlers.triggerBattleUseOnPokemon(item,pokemon,battler,scene)
  1997.     end
  1998.     if !ret && pbBelongsToPlayer?(userPkmn.index)
  1999.       if $PokemonBag.pbCanStore?(item)
  2000.         $PokemonBag.pbStoreItem(item)
  2001.       else
  2002.         raise _INTL("Couldn't return unused item to Bag somehow.")
  2003.       end
  2004.     end
  2005.     return ret
  2006.   end
  2007.  
  2008. # Uses an item on an active Pokémon.
  2009.   def pbUseItemOnBattler(item,index,userPkmn,scene)
  2010.     PBDebug.log("[Player used #{PBItems.getName(item)}]")
  2011.     ret=ItemHandlers.triggerBattleUseOnBattler(item,@battlers[index],scene)
  2012.     if !ret && pbBelongsToPlayer?(userPkmn.index)
  2013.       if $PokemonBag.pbCanStore?(item)
  2014.         $PokemonBag.pbStoreItem(item)
  2015.       else
  2016.         raise _INTL("Couldn't return unused item to Bag somehow.")
  2017.       end
  2018.     end
  2019.     return ret
  2020.   end
  2021.  
  2022.   def pbRegisterItem(idxPokemon,idxItem,idxTarget=nil)
  2023.     if ItemHandlers.hasUseInBattle(idxItem)
  2024.       if idxPokemon==0 # Player's first Pokémon
  2025.         if ItemHandlers.triggerBattleUseOnBattler(idxItem,@battlers[idxPokemon],self)
  2026.           ItemHandlers.triggerUseInBattle(idxItem,@battlers[idxPokemon],self)
  2027.           if @doublebattle
  2028.             @choices[idxPokemon+2][0]=3         # "Use an item"
  2029.             @choices[idxPokemon+2][1]=idxItem   # ID of item to be used
  2030.             @choices[idxPokemon+2][2]=idxTarget # Index of Pokémon to use item on
  2031.           end
  2032.         else
  2033.           if $PokemonBag.pbCanStore?(idxItem)
  2034.             $PokemonBag.pbStoreItem(idxItem)
  2035.           else
  2036.             raise _INTL("Couldn't return unusable item to Bag somehow.")
  2037.           end
  2038.           return false
  2039.         end
  2040.       else
  2041.       end
  2042.     end
  2043.     @choices[idxPokemon][0]=3         # "Use an item"
  2044.     @choices[idxPokemon][1]=idxItem   # ID of item to be used
  2045.     @choices[idxPokemon][2]=idxTarget # Index of Pokémon to use item on
  2046.     side=(pbIsOpposing?(idxPokemon)) ? 1 : 0
  2047.     owner=pbGetOwnerIndex(idxPokemon)
  2048.     if @megaEvolution[side][owner]==idxPokemon
  2049.       @megaEvolution[side][owner]=-1
  2050.     end
  2051.     return true
  2052.   end
  2053.  
  2054.   def pbEnemyUseItem(item,battler)
  2055.     return 0 if !@internalbattle
  2056.     items=pbGetOwnerItems(battler.index)
  2057.     return if !items
  2058.     opponent=pbGetOwner(battler.index)
  2059.     for i in 0...items.length
  2060.       if items[i]==item
  2061.         items.delete_at(i)
  2062.         break
  2063.       end
  2064.     end
  2065.     itemname=PBItems.getName(item)
  2066.     pbDisplayBrief(_INTL("{1} used the\r\n{2}!",opponent.fullname,itemname))
  2067.     PBDebug.log("[Opponent used #{itemname}]")
  2068.     if isConst?(item,PBItems,:POTION)
  2069.       battler.pbRecoverHP(20,true)
  2070.       pbDisplay(_INTL("{1}'s HP was restored.",battler.pbThis))
  2071.     elsif isConst?(item,PBItems,:SUPERPOTION)
  2072.       battler.pbRecoverHP(50,true)
  2073.       pbDisplay(_INTL("{1}'s HP was restored.",battler.pbThis))
  2074.     elsif isConst?(item,PBItems,:HYPERPOTION)
  2075.       battler.pbRecoverHP(200,true)
  2076.       pbDisplay(_INTL("{1}'s HP was restored.",battler.pbThis))
  2077.     elsif isConst?(item,PBItems,:MAXPOTION)
  2078.       battler.pbRecoverHP(battler.totalhp-battler.hp,true)
  2079.       pbDisplay(_INTL("{1}'s HP was restored.",battler.pbThis))
  2080.     elsif isConst?(item,PBItems,:FULLRESTORE)
  2081.       fullhp=(battler.hp==battler.totalhp)
  2082.       battler.pbRecoverHP(battler.totalhp-battler.hp,true)
  2083.       battler.status=0; battler.statusCount=0
  2084.       battler.effects[PBEffects::Confusion]=0
  2085.       if fullhp
  2086.         pbDisplay(_INTL("{1} became healthy!",battler.pbThis))
  2087.       else
  2088.         pbDisplay(_INTL("{1}'s HP was restored.",battler.pbThis))
  2089.       end
  2090.     elsif isConst?(item,PBItems,:FULLHEAL)
  2091.       battler.status=0; battler.statusCount=0
  2092.       battler.effects[PBEffects::Confusion]=0
  2093.       pbDisplay(_INTL("{1} became healthy!",battler.pbThis))
  2094.     elsif isConst?(item,PBItems,:XATTACK)
  2095.       if battler.pbCanIncreaseStatStage?(PBStats::ATTACK)
  2096.         battler.pbIncreaseStat(PBStats::ATTACK,1,true)
  2097.       end
  2098.     elsif isConst?(item,PBItems,:XDEFEND)
  2099.       if battler.pbCanIncreaseStatStage?(PBStats::DEFENSE)
  2100.         battler.pbIncreaseStat(PBStats::DEFENSE,1,true)
  2101.       end
  2102.     elsif isConst?(item,PBItems,:XSPEED)
  2103.       if battler.pbCanIncreaseStatStage?(PBStats::SPEED)
  2104.         battler.pbIncreaseStat(PBStats::SPEED,1,true)
  2105.       end
  2106.     elsif isConst?(item,PBItems,:XSPECIAL)
  2107.       if battler.pbCanIncreaseStatStage?(PBStats::SPATK)
  2108.         battler.pbIncreaseStat(PBStats::SPATK,1,true)
  2109.       end
  2110.     elsif isConst?(item,PBItems,:XSPDEF)
  2111.       if battler.pbCanIncreaseStatStage?(PBStats::SPDEF)
  2112.         battler.pbIncreaseStat(PBStats::SPDEF,1,true)
  2113.       end
  2114.     elsif isConst?(item,PBItems,:XACCURACY)
  2115.       if battler.pbCanIncreaseStatStage?(PBStats::ACCURACY)
  2116.         battler.pbIncreaseStat(PBStats::ACCURACY,1,true)
  2117.       end
  2118.     end
  2119.   end
  2120.  
  2121. ################################################################################
  2122. # Fleeing from battle.
  2123. ################################################################################
  2124.   def pbCanRun?(idxPokemon)
  2125.     return false if @opponent
  2126.     thispkmn=@battlers[idxPokemon]
  2127.     return true if thispkmn.hasWorkingItem(:SMOKEBALL)
  2128.     return true if thispkmn.hasWorkingAbility(:RUNAWAY)
  2129.     return pbCanSwitch?(idxPokemon,-1,false)
  2130.   end
  2131.  
  2132.   def pbRun(idxPokemon,duringBattle=false)
  2133.     thispkmn=@battlers[idxPokemon]
  2134.     if pbIsOpposing?(idxPokemon)
  2135.       return 0 if @opponent
  2136.       @choices[i][0]=5 # run
  2137.       @choices[i][1]=0
  2138.       @choices[i][2]=nil
  2139.       return -1
  2140.     end
  2141.     if @opponent
  2142.       if $DEBUG && Input.press?(Input::CTRL)
  2143.         if pbDisplayConfirm(_INTL("Treat this battle as a win?"))
  2144.           @decision=1
  2145.           return 1
  2146.         elsif pbDisplayConfirm(_INTL("Treat this battle as a loss?"))
  2147.           @decision=2
  2148.           return 1
  2149.         end
  2150.       elsif @internalbattle
  2151.         pbDisplayPaused(_INTL("No!  There's no running from a Trainer battle!"))
  2152.       elsif pbDisplayConfirm(_INTL("Would you like to forfeit the match and quit now?"))
  2153.         pbDisplay(_INTL("{1} forfeited the match!",self.pbPlayer.name))
  2154.         @decision=3
  2155.         return 1
  2156.       end
  2157.       return 0
  2158.     end
  2159.     if $DEBUG && Input.press?(Input::CTRL)
  2160.       pbDisplayPaused(_INTL("Got away safely!"))
  2161.       @decision=3
  2162.       return 1
  2163.     end
  2164.     if @cantescape
  2165.       pbDisplayPaused(_INTL("Can't escape!"))
  2166.       return 0
  2167.     end
  2168.     if thispkmn.hasWorkingItem(:SMOKEBALL)
  2169.       if duringBattle
  2170.         pbDisplayPaused(_INTL("Got away safely!"))
  2171.       else
  2172.         pbDisplayPaused(_INTL("{1} fled using its {2}!",thispkmn.pbThis,PBItems.getName(thispkmn.item)))
  2173.       end
  2174.       @decision=3
  2175.       return 1
  2176.     end
  2177.     if thispkmn.hasWorkingAbility(:RUNAWAY)
  2178.       if duringBattle
  2179.         pbDisplayPaused(_INTL("Got away safely!"))
  2180.       else
  2181.         pbDisplayPaused(_INTL("{1} fled using Run Away!",thispkmn.pbThis))
  2182.       end
  2183.       @decision=3
  2184.       return 1
  2185.     end
  2186.     if !duringBattle && !pbCanSwitch?(idxPokemon,-1,false) # TODO: Use real messages
  2187.       pbDisplayPaused(_INTL("Can't escape!"))
  2188.       return 0
  2189.     end
  2190.     # Note: not pbSpeed, because using unmodified Speed
  2191.     speedPlayer=@battlers[idxPokemon].speed
  2192.     opposing=@battlers[idxPokemon].pbOppositeOpposing
  2193.     opposing=opposing.pbPartner if opposing.isFainted?
  2194.     if !opposing.isFainted?
  2195.       speedEnemy=opposing.speed
  2196.       if speedPlayer>speedEnemy
  2197.         rate=256
  2198.       else
  2199.         speedEnemy=1 if speedEnemy<=0
  2200.         rate=speedPlayer*128/speedEnemy
  2201.         rate+=@runCommand*30
  2202.         rate&=0xFF
  2203.       end
  2204.     else
  2205.       rate=256
  2206.     end
  2207.     ret=1
  2208.     if pbAIRandom(256)<rate
  2209.       pbDisplayPaused(_INTL("Got away safely!"))
  2210.       @decision=3
  2211.     else
  2212.       pbDisplayPaused(_INTL("Can't escape!"))
  2213.       ret=-1
  2214.     end
  2215.     @runCommand+=1 if !duringBattle
  2216.     return ret
  2217.   end
  2218.  
  2219. ################################################################################
  2220. # Mega Evolve battler.
  2221. ################################################################################
  2222.  
  2223.   def pbCanMegaEvolve?(index)
  2224.     return false if $game_switches[NO_MEGA_EVOLUTION]
  2225.     return false if !@battlers[index].hasMega?
  2226.     return false if pbIsOpposing?(index) && !@opponent
  2227.     return true if $DEBUG && Input.press?(Input::CTRL)
  2228.     return false if !pbHasMegaRing(index)
  2229.     side=(pbIsOpposing?(index)) ? 1 : 0
  2230.     owner=pbGetOwnerIndex(index)
  2231.     return false if @megaEvolution[side][owner]!=-1
  2232.     return false if @battlers[index].effects[PBEffects::SkyDrop]
  2233.     return true
  2234.   end
  2235.  
  2236.   def pbRegisterMegaEvolution(index)
  2237.     side=(pbIsOpposing?(index)) ? 1 : 0
  2238.     owner=pbGetOwnerIndex(index)
  2239.     @megaEvolution[side][owner]=index
  2240.   end
  2241.  
  2242.   def pbMegaEvolve(index)
  2243.     return if !@battlers[index] || !@battlers[index].pokemon
  2244.     return if !(@battlers[index].hasMega? rescue false)
  2245.     return if (@battlers[index].isMega? rescue true)
  2246.     ownername=pbGetOwner(index).fullname
  2247.     ownername=pbGetOwner(index).name if pbBelongsToPlayer?(index)
  2248.     case (@battlers[index].pokemon.megaMessage rescue 0)
  2249.     when 1 # Rayquaza
  2250.       pbDisplay(_INTL("{1}'s fervent wish has reached {2}!",ownername,@battlers[index].pbThis))
  2251.     else
  2252.       pbDisplay(_INTL("{1}'s {2} is reacting to {3}'s Mega Ring!",  
  2253.        @battlers[index].pbThis,
  2254.        PBItems.getName(@battlers[index].item),
  2255.        ownername))    
  2256.     end
  2257.     pbCommonAnimation("MegaEvolution",@battlers[index],nil)
  2258.     @battlers[index].pokemon.makeMega
  2259.     @battlers[index].form=@battlers[index].pokemon.form
  2260.     @battlers[index].pbUpdate(true)
  2261.     @scene.pbChangePokemon(@battlers[index],@battlers[index].pokemon)
  2262.     pbCommonAnimation("MegaEvolution2",@battlers[index],nil)
  2263.     meganame=(@battlers[index].pokemon.megaName rescue nil)
  2264.     if !meganame || meganame==""
  2265.       meganame=_INTL("Mega {1}",PBSpecies.getName(@battlers[index].pokemon.species))
  2266.     end
  2267.     pbDisplay(_INTL("{1} has Mega Evolved into {2}!",@battlers[index].pbThis,meganame))
  2268.     PBDebug.log("[Mega Evolution] #{@battlers[index].pbThis} Mega Evolved")
  2269.     side=(pbIsOpposing?(index)) ? 1 : 0
  2270.     owner=pbGetOwnerIndex(index)
  2271.     @megaEvolution[side][owner]=-2
  2272.   end
  2273.  
  2274. ################################################################################
  2275. # Primal Evolve battler.
  2276. ################################################################################
  2277.  
  2278.   def pbPrimalReversion(index)
  2279.     return if !@battlers[index] || !@battlers[index].pokemon
  2280.     return if !(@battlers[index].hasPrimal? rescue false)
  2281.     return if (@battlers[index].isPrimal? rescue true)
  2282.     if isConst?(@battlers[index].pokemon.species,PBSpecies,:KYOGRE)
  2283.       pbCommonAnimation("PrimalReversionK",@battlers[index],nil)
  2284.     elsif isConst?(@battlers[index].pokemon.species,PBSpecies,:GROUDON)
  2285.       pbCommonAnimation("PrimalReversion",@battlers[index],nil)
  2286.     end
  2287.     @battlers[index].pokemon.makePrimal
  2288.     @battlers[index].form=@battlers[index].pokemon.form
  2289.     @battlers[index].pbUpdate(true)
  2290.     @scene.pbChangePokemon(@battlers[index],@battlers[index].pokemon)
  2291.     pbDisplay(_INTL("{1}'s Primal Reversion!\nIt reverted to its Primal Form!",@battlers[index].pbThis))
  2292.     PBDebug.log("[Primal Reversion] #{@battlers[index].pbThis} Primal Reverted")
  2293.   end
  2294.  
  2295.  
  2296. ################################################################################
  2297. # Call battler.
  2298. ################################################################################
  2299.   def pbCall(index)
  2300.     owner=pbGetOwner(index)
  2301.     pbDisplay(_INTL("{1} called {2}!",owner.name,@battlers[index].name))
  2302.     pbDisplay(_INTL("{1}!",@battlers[index].name))
  2303.     PBDebug.log("[#{owner.name} called to #{@battlers[index].pbThis(true)}]")
  2304.     if @battlers[index].isShadow?
  2305.       if @battlers[index].inHyperMode?
  2306.         @battlers[index].pokemon.hypermode=false
  2307.         @battlers[index].pokemon.adjustHeart(-300)
  2308.         pbDisplay(_INTL("{1} came to its senses from the Trainer's call!",@battlers[index].pbThis))
  2309.       else
  2310.         pbDisplay(_INTL("But nothing happened!"))
  2311.       end
  2312.     elsif @battlers[index].status!=PBStatuses::SLEEP &&
  2313.           @battlers[index].pbCanIncreaseStatStage?(PBStats::ACCURACY)
  2314.       @battlers[index].pbIncreaseStat(PBStats::ACCURACY,1,true)
  2315.     else
  2316.       pbDisplay(_INTL("But nothing happened!"))
  2317.     end
  2318.   end
  2319.  
  2320. ################################################################################
  2321. # Gaining Experience.
  2322. ################################################################################
  2323.   def pbGainEXP
  2324.     return if !@internalbattle
  2325.     successbegin=true
  2326.     for i in 0...4 # Not ordered by priority
  2327.       if !@doublebattle && pbIsDoubleBattler?(i)
  2328.         @battlers[i].participants=[]
  2329.         next
  2330.       end
  2331.       if pbIsOpposing?(i) && @battlers[i].participants.length>0 &&
  2332.          (@battlers[i].isFainted? || @battlers[i].captured)
  2333.         haveexpall=(hasConst?(PBItems,:EXPALL) && $PokemonBag.pbQuantity(:EXPALL)>0)
  2334.         # First count the number of participants
  2335.         partic=0
  2336.         expshare=0
  2337.         for j in @battlers[i].participants
  2338.           next if !@party1[j] #|| !pbIsOwner?(0,j)
  2339.           partic+=1 if @party1[j].hp>0 && !@party1[j].isEgg?
  2340.         end
  2341.         if !haveexpall
  2342.           for j in 0...@party1.length
  2343.             next if !@party1[j] #|| !pbIsOwner?(0,j)
  2344.             expshare+=1 if @party1[j].hp>0 && !@party1[j].isEgg? &&
  2345.                            (isConst?(@party1[j].item,PBItems,:EXPSHARE) ||
  2346.                            isConst?(@party1[j].itemInitial,PBItems,:EXPSHARE))
  2347.           end
  2348.         end
  2349.         # Now calculate EXP for the participants
  2350.         if partic>0 || expshare>0 || haveexpall
  2351.           if !@opponent && successbegin && pbAllFainted?(@party2)
  2352.             @scene.pbWildBattleSuccess
  2353.             successbegin=false
  2354.           end
  2355.           for j in 0...@party1.length
  2356.             next if !@party1[j] #|| !pbIsOwner?(0,j)
  2357.             next if @party1[j].hp<=0 || @party1[j].isEgg?
  2358.             haveexpshare=(isConst?(@party1[j].item,PBItems,:EXPSHARE) ||
  2359.                           isConst?(@party1[j].itemInitial,PBItems,:EXPSHARE))
  2360.             next if !haveexpshare && !@battlers[i].participants.include?(j)
  2361.             pbGainExpOne(j,@battlers[i],partic,expshare,haveexpall)
  2362.           end
  2363.           if haveexpall
  2364.             showmessage=true
  2365.             for j in 0...@party1.length
  2366.               next if !@party1[j] #|| !pbIsOwner?(0,j)
  2367.               next if @party1[j].hp<=0 || @party1[j].isEgg?
  2368.               next if isConst?(@party1[j].item,PBItems,:EXPSHARE) ||
  2369.                       isConst?(@party1[j].itemInitial,PBItems,:EXPSHARE)
  2370.               next if @battlers[i].participants.include?(j)
  2371.               pbDisplayPaused(_INTL("The rest of your team gained Exp. Points thanks to the {1}!",
  2372.                  PBItems.getName(getConst(PBItems,:EXPALL)))) if showmessage
  2373.               showmessage=false
  2374.               pbGainExpOne(j,@battlers[i],partic,expshare,haveexpall,false)
  2375.             end
  2376.           end
  2377.         end
  2378.         # Now clear the participants array
  2379.         @battlers[i].participants=[]
  2380.       end
  2381.     end
  2382.   end
  2383.  
  2384.   def pbGainExpOne(index,defeated,partic,expshare,haveexpall,showmessages=true)
  2385.     thispoke=@party1[index]
  2386.     # Original species, not current species
  2387.     level=defeated.level
  2388.     baseexp=defeated.pokemon.baseExp
  2389.     evyield=defeated.pokemon.evYield
  2390.     # Gain effort value points, using RS effort values
  2391.     totalev=0
  2392.     for k in 0...6
  2393.       totalev+=thispoke.ev[k]
  2394.     end
  2395.     for k in 0...6
  2396.       evgain=evyield[k]
  2397.       evgain*=8 if isConst?(thispoke.item,PBItems,:MACHOBRACE) ||
  2398.                    isConst?(thispoke.itemInitial,PBItems,:MACHOBRACE)
  2399.       case k
  2400.       when PBStats::HP
  2401.         evgain+=4 if isConst?(thispoke.item,PBItems,:POWERWEIGHT) ||
  2402.                      isConst?(thispoke.itemInitial,PBItems,:POWERWEIGHT)
  2403.       when PBStats::ATTACK
  2404.         evgain+=4 if isConst?(thispoke.item,PBItems,:POWERBRACER) ||
  2405.                      isConst?(thispoke.itemInitial,PBItems,:POWERBRACER)
  2406.       when PBStats::DEFENSE
  2407.         evgain+=4 if isConst?(thispoke.item,PBItems,:POWERBELT) ||
  2408.                      isConst?(thispoke.itemInitial,PBItems,:POWERBELT)
  2409.       when PBStats::SPATK
  2410.         evgain+=4 if isConst?(thispoke.item,PBItems,:POWERLENS) ||
  2411.                      isConst?(thispoke.itemInitial,PBItems,:POWERLENS)
  2412.       when PBStats::SPDEF
  2413.         evgain+=4 if isConst?(thispoke.item,PBItems,:POWERBAND) ||
  2414.                      isConst?(thispoke.itemInitial,PBItems,:POWERBAND)
  2415.       when PBStats::SPEED
  2416.         evgain+=4 if isConst?(thispoke.item,PBItems,:POWERANKLET) ||
  2417.                      isConst?(thispoke.itemInitial,PBItems,:POWERANKLET)
  2418.       end
  2419.       evgain*=2 if thispoke.pokerusStage>=1 # Infected or cured
  2420.       if evgain>0
  2421.         # Can't exceed overall limit
  2422.         evgain-=totalev+evgain-PokeBattle_Pokemon::EVLIMIT if totalev+evgain>PokeBattle_Pokemon::EVLIMIT
  2423.         # Can't exceed stat limit
  2424.         evgain-=thispoke.ev[k]+evgain-PokeBattle_Pokemon::EVSTATLIMIT if thispoke.ev[k]+evgain>PokeBattle_Pokemon::EVSTATLIMIT
  2425.         # Add EV gain
  2426.         thispoke.ev[k]+=evgain
  2427.         if thispoke.ev[k]>PokeBattle_Pokemon::EVSTATLIMIT
  2428.           print "Single-stat EV limit #{PokeBattle_Pokemon::EVSTATLIMIT} exceeded.\r\nStat: #{k}  EV gain: #{evgain}  EVs: #{thispoke.ev.inspect}"
  2429.           thispoke.ev[k]=PokeBattle_Pokemon::EVSTATLIMIT
  2430.         end
  2431.         totalev+=evgain
  2432.         if totalev>PokeBattle_Pokemon::EVLIMIT
  2433.           print "EV limit #{PokeBattle_Pokemon::EVLIMIT} exceeded.\r\nTotal EVs: #{totalev} EV gain: #{evgain}  EVs: #{thispoke.ev.inspect}"
  2434.         end
  2435.       end
  2436.     end
  2437.     # Gain experience
  2438.     ispartic=0
  2439.     ispartic=1 if defeated.participants.include?(index)
  2440.     haveexpshare=(isConst?(thispoke.item,PBItems,:EXPSHARE) ||
  2441.                   isConst?(thispoke.itemInitial,PBItems,:EXPSHARE)) ? 1 : 0
  2442.     exp=0
  2443.     if expshare>0
  2444.       if partic==0 # No participants, all Exp goes to Exp Share holders
  2445.         exp=(level*baseexp).floor
  2446.         exp=(exp/(NOSPLITEXP ? 1 : expshare)).floor*haveexpshare
  2447.       else
  2448.         if NOSPLITEXP
  2449.           exp=(level*baseexp).floor*ispartic
  2450.           exp=(level*baseexp/2).floor*haveexpshare if ispartic==0
  2451.         else
  2452.           exp=(level*baseexp/2).floor
  2453.           exp=(exp/partic).floor*ispartic + (exp/expshare).floor*haveexpshare
  2454.         end
  2455.       end
  2456.     elsif ispartic==1
  2457.       exp=(level*baseexp/(NOSPLITEXP ? 1 : partic)).floor
  2458.     elsif haveexpall
  2459.       exp=(level*baseexp/2).floor
  2460.     end
  2461.     return if exp<=0
  2462.     exp=(exp*6/5).floor if @opponent
  2463.     if USESCALEDEXPFORMULA
  2464.       exp=(exp/5).floor
  2465.       leveladjust=(2*level+10.0)/(level+thispoke.level+10.0)
  2466.       leveladjust=leveladjust**5
  2467.       leveladjust=Math.sqrt(leveladjust)
  2468.       exp=(exp*leveladjust).floor
  2469.       exp+=1 if ispartic>0 || haveexpshare>0
  2470.     else
  2471.       exp=(exp/7).floor
  2472.     end
  2473.     isOutsider=(thispoke.trainerID!=self.pbPlayer.id ||
  2474.                (thispoke.language!=0 && thispoke.language!=self.pbPlayer.language))
  2475.     if isOutsider
  2476.       exp=(exp*1.25).floor
  2477.     else
  2478.         exp=(exp*2/2).floor
  2479.     end
  2480.     exp=(exp*3/2).floor if isConst?(thispoke.item,PBItems,:LUCKYEGG) ||
  2481.                            isConst?(thispoke.itemInitial,PBItems,:LUCKYEGG)
  2482.     if @doublebattle
  2483.     exp=(exp*4/2).floor
  2484.     end
  2485.     exp=(exp*4/2).floor if thispoke.level <= 20
  2486.     exp=(exp*2).floor if thispoke.level <= 30
  2487.     exp=(exp*1.75).floor if thispoke.level >= 31
  2488.     exp=(exp*1.25).floor if thispoke.level >= 40
  2489.     exp=(exp*1/4).floor if thispoke.level >= 50
  2490.     growthrate=thispoke.growthrate
  2491.     newexp=PBExperience.pbAddExperience(thispoke.exp,exp,growthrate)
  2492.     exp=newexp-thispoke.exp
  2493.     if exp>0
  2494.       if showmessages
  2495.         if isOutsider
  2496.           pbDisplayPaused(_INTL("{1} gained {2} Exp. Points!",thispoke.name,exp))
  2497.         else
  2498.           pbDisplayPaused(_INTL("{1} gained {2} Exp. Points!",thispoke.name,exp))
  2499.         end
  2500.       end
  2501.       newlevel=PBExperience.pbGetLevelFromExperience(newexp,growthrate)
  2502.       tempexp=0
  2503.       curlevel=thispoke.level
  2504.       if newlevel<curlevel
  2505.         debuginfo="#{thispoke.name}: #{thispoke.level}/#{newlevel} | #{thispoke.exp}/#{newexp} | gain: #{exp}"
  2506.         raise RuntimeError.new(_INTL("The new level ({1}) is less than the Pokémon's\r\ncurrent level ({2}), which shouldn't happen.\r\n[Debug: {3}]",
  2507.                                newlevel,curlevel,debuginfo))
  2508.         return
  2509.       end
  2510.       if thispoke.respond_to?("isShadow?") && thispoke.isShadow?
  2511.         thispoke.exp+=exp
  2512.       else
  2513.         tempexp1=thispoke.exp
  2514.         tempexp2=0
  2515.         # Find battler
  2516.         battler=pbFindPlayerBattler(index)
  2517.         loop do
  2518.           # EXP Bar animation
  2519.           startexp=PBExperience.pbGetStartExperience(curlevel,growthrate)
  2520.           endexp=PBExperience.pbGetStartExperience(curlevel+1,growthrate)
  2521.           tempexp2=(endexp<newexp) ? endexp : newexp
  2522.           thispoke.exp=tempexp2
  2523.           @scene.pbEXPBar(thispoke,battler,startexp,endexp,tempexp1,tempexp2)
  2524.           tempexp1=tempexp2
  2525.           curlevel+=1
  2526.           if curlevel>newlevel
  2527.             thispoke.calcStats
  2528.             battler.pbUpdate(false) if battler
  2529.             @scene.pbRefresh
  2530.             break
  2531.           end
  2532.           oldtotalhp=thispoke.totalhp
  2533.           oldattack=thispoke.attack
  2534.           olddefense=thispoke.defense
  2535.           oldspeed=thispoke.speed
  2536.           oldspatk=thispoke.spatk
  2537.           oldspdef=thispoke.spdef
  2538.           if battler && battler.pokemon && @internalbattle
  2539.             battler.pokemon.changeHappiness("level up")
  2540.           end
  2541.           thispoke.calcStats
  2542.           battler.pbUpdate(false) if battler
  2543.           @scene.pbRefresh
  2544.           pbDisplayPaused(_INTL("{1} grew to Level {2}!",thispoke.name,curlevel))
  2545.           @scene.pbLevelUp(thispoke,battler,oldtotalhp,oldattack,
  2546.                            olddefense,oldspeed,oldspatk,oldspdef)
  2547.           # Finding all moves learned at this level
  2548.           movelist=thispoke.getMoveList
  2549.           for k in movelist
  2550.             if k[0]==thispoke.level   # Learned a new move
  2551.               pbLearnMove(index,k[1])
  2552.             end
  2553.           end
  2554.           newspecies=pbCheckEvolution(thispoke)#edit
  2555.           if newspecies>0
  2556.             pbFadeOutInWithMusic(99999){
  2557.             evo=PokemonEvolutionScene.new
  2558.             evo.pbStartScreen(thispoke,newspecies)
  2559.             evo.pbEvolution
  2560.             evo.pbEndScreen
  2561.             if battler
  2562.               @scene.pbChangePokemon(@battlers[battler.index],@battlers[battler.index].pokemon)
  2563.             end
  2564.           }
  2565.           end
  2566.         end
  2567.       end
  2568.     end
  2569.   end
  2570.  
  2571.  
  2572. ################################################################################
  2573. # Learning a move.
  2574. ################################################################################
  2575.   def pbLearnMove(pkmnIndex,move,topscreen=false)
  2576.     pokemon=@party1[pkmnIndex]
  2577.     return if !pokemon
  2578.     pkmnname=pokemon.name
  2579.     battler=pbFindPlayerBattler(pkmnIndex)
  2580.     movename=PBMoves.getName(move)
  2581.     for i in 0...4
  2582.       return if pokemon.moves[i].id==move
  2583.       if pokemon.moves[i].id==0
  2584.         pokemon.moves[i]=PBMove.new(move)
  2585.         battler.moves[i]=PokeBattle_Move.pbFromPBMove(self,pokemon.moves[i]) if battler
  2586.         pbDisplayPaused(_INTL("{1} learned {2}!",pkmnname,movename))
  2587.         PBDebug.log("[#{pkmnname} learned #{movename}]")
  2588.         return
  2589.       end
  2590.     end
  2591.     loop do
  2592.     if !topscreen
  2593.       pbDisplayPaused(_INTL("{1} is trying to learn {2}.",pkmnname,movename))
  2594.       pbDisplayPaused(_INTL("But {1} can't learn more than four moves.",pkmnname))
  2595.       if pbDisplayConfirm(_INTL("Delete a move to make room for {1}?",movename))
  2596.         pbDisplayPaused(_INTL("Which move should be forgotten?"))
  2597.         forgetmove=@scene.pbForgetMove(pokemon,move)
  2598.         if forgetmove>=0
  2599.           oldmovename=PBMoves.getName(pokemon.moves[forgetmove].id)
  2600.           pokemon.moves[forgetmove]=PBMove.new(move) # Replaces current/total PP
  2601.           battler.moves[forgetmove]=PokeBattle_Move.pbFromPBMove(self,pokemon.moves[forgetmove]) if battler
  2602.           pbDisplayPaused(_INTL("1,  2, and... ... ..."))
  2603.           pbDisplayPaused(_INTL("Poof!"))
  2604.           pbDisplayPaused(_INTL("{1} forgot {2}.",pkmnname,oldmovename))
  2605.           pbDisplayPaused(_INTL("And..."))
  2606.           pbDisplayPaused(_INTL("{1} learned {2}!",pkmnname,movename))
  2607.           PBDebug.log("[#{pkmnname} forgot #{oldmovename} and learned #{movename}]")
  2608.           return
  2609.         elsif pbDisplayConfirm(_INTL("Should {1} stop learning {2}?",pkmnname,movename))
  2610.           pbDisplayPaused(_INTL("{1} did not learn {2}.",pkmnname,movename))
  2611.           return
  2612.         end
  2613.       elsif pbDisplayConfirm(_INTL("Should {1} stop learning {2}?",pkmnname,movename))
  2614.         pbDisplayPaused(_INTL("{1} did not learn {2}.",pkmnname,movename))
  2615.         return
  2616.       end
  2617.   else
  2618.       pbMessage(_INTL("{1} is trying to learn {2}.",pkmnname,movename))
  2619.       pbMessage(_INTL("But {1} can't learn more than four moves.",pkmnname))
  2620.       if pbConfirmMessage(1,false,_INTL("Delete a move to make room for {1}?",movename))
  2621.         pbMessage(_INTL("Which move should be forgotten?"))
  2622.         forgetmove=@scene.pbForgetMove(pokemon,move)
  2623.         if forgetmove>=0
  2624.           oldmovename=PBMoves.getName(pokemon.moves[forgetmove].id)
  2625.           pokemon.moves[forgetmove]=PBMove.new(move) # Replaces current/total PP
  2626.           battler.moves[forgetmove]=PokeBattle_Move.pbFromPBMove(self,pokemon.moves[forgetmove]) if battler
  2627.           pbMessage(_INTL("1,  2, and... ... ..."))
  2628.           pbMessage(_INTL("Poof!"))
  2629.           pbMessage(_INTL("{1} forgot {2}.",pkmnname,oldmovename))
  2630.           pbMessage(_INTL("And..."))
  2631.           pbMessage(_INTL("{1} learned {2}!",pkmnname,movename))
  2632.           PBDebug.log("[#{pkmnname} forgot #{oldmovename} and learned #{movename}]")
  2633.           return
  2634.         elsif pbConfirmMessage(1,false,_INTL("Should {1} stop learning {2}?",pkmnname,movename))
  2635.           pbMessage(_INTL("{1} did not learn {2}.",pkmnname,movename))
  2636.           return
  2637.         end
  2638.       elsif pbConfirmMessage(1,false,_INTL("Should {1} stop learning {2}?",pkmnname,movename))
  2639.         pbMessage(_INTL("{1} did not learn {2}.",pkmnname,movename))
  2640.         return
  2641.       end
  2642.     end
  2643.   end
  2644.  
  2645.   end
  2646.  
  2647. ################################################################################
  2648. # Abilities.
  2649. ################################################################################
  2650.   def pbOnActiveAll
  2651.     for i in 0...4 # Currently unfainted participants will earn EXP even if they faint afterwards
  2652.       @battlers[i].pbUpdateParticipants if pbIsOpposing?(i)
  2653.       @amuletcoin=true if !pbIsOpposing?(i) &&
  2654.                           (isConst?(@battlers[i].item,PBItems,:AMULETCOIN) ||
  2655.                            isConst?(@battlers[i].item,PBItems,:LUCKINCENSE))
  2656.     end
  2657.     for i in 0...4
  2658.       if !@battlers[i].isFainted?
  2659.         if @battlers[i].isShadow? && pbIsOpposing?(i)
  2660.           pbCommonAnimation("Shadow",@battlers[i],nil)
  2661.           pbDisplay(_INTL("Oh!\nA Shadow Pokemon!"))
  2662.         end
  2663.       end
  2664.     end
  2665.     # Weather-inducing abilities, Trace, Imposter, etc.
  2666.     @usepriority=false
  2667.     priority=pbPriority
  2668.     for i in priority
  2669.       i.pbAbilitiesOnSwitchIn(true)
  2670.     end
  2671.     # Check forms are correct
  2672.     for i in 0...4
  2673.       next if @battlers[i].isFainted?
  2674.       @battlers[i].pbCheckForm
  2675.     end
  2676.   end
  2677.  
  2678.   def pbOnActiveOne(pkmn,onlyabilities=false,moldbreaker=false)
  2679.     return false if pkmn.isFainted?
  2680.     if !onlyabilities
  2681.       for i in 0...4 # Currently unfainted participants will earn EXP even if they faint afterwards
  2682.         @battlers[i].pbUpdateParticipants if pbIsOpposing?(i)
  2683.         @amuletcoin=true if !pbIsOpposing?(i) &&
  2684.                             (isConst?(@battlers[i].item,PBItems,:AMULETCOIN) ||
  2685.                              isConst?(@battlers[i].item,PBItems,:LUCKINCENSE))
  2686.       end
  2687.       if pkmn.isShadow? && pbIsOpposing?(pkmn.index)
  2688.         pbCommonAnimation("Shadow",pkmn,nil)
  2689.         pbDisplay(_INTL("Oh!\nA Shadow Pokemon!"))
  2690.       end
  2691.       # Healing Wish
  2692.       if pkmn.effects[PBEffects::HealingWish]
  2693.         PBDebug.log("[#{pkmn.pbThis}'s Healing Wish triggered]")
  2694.         pkmn.pbRecoverHP(pkmn.totalhp,true)
  2695.         pkmn.status=0
  2696.         pkmn.statusCount=0
  2697.         pbDisplayPaused(_INTL("The healing wish came true for {1}!",pkmn.pbThis(true)))
  2698.         pkmn.effects[PBEffects::HealingWish]=false
  2699.       end
  2700.       # Lunar Dance
  2701.       if pkmn.effects[PBEffects::LunarDance]
  2702.         PBDebug.log("[#{pkmn.pbThis}'s Lunar Dance triggered]")
  2703.         pkmn.pbRecoverHP(pkmn.totalhp,true)
  2704.         pkmn.status=0
  2705.         pkmn.statusCount=0
  2706.         for i in 0...4
  2707.           pkmn.moves[i].pp=pkmn.moves[i].totalpp
  2708.         end
  2709.         pbDisplayPaused(_INTL("{1} became cloaked in mystical moonlight!",pkmn.pbThis))
  2710.         pkmn.effects[PBEffects::LunarDance]=false
  2711.       end
  2712.       # Spikes
  2713.       if pkmn.pbOwnSide.effects[PBEffects::Spikes]>0 && !pkmn.isAirborne?(moldbreaker)
  2714.         if !pkmn.isAirborne?
  2715.           if !pkmn.hasWorkingAbility(:MAGICGUARD)
  2716.             PBDebug.log("[#{pkmn.pbThis} took damage from Spikes]")
  2717.             spikesdiv=[8,8,6,4][pkmn.pbOwnSide.effects[PBEffects::Spikes]]
  2718.             @scene.pbDamageAnimation(pkmn,0)
  2719.             pkmn.pbReduceHP([(pkmn.totalhp/spikesdiv).floor,1].max)
  2720.             pbDisplayPaused(_INTL("{1} was hurt by spikes!",pkmn.pbThis))
  2721.           end
  2722.         end
  2723.       end
  2724.       pkmn.pbFaint if pkmn.isFainted?
  2725.       # Stealth Rock
  2726.       if pkmn.pbOwnSide.effects[PBEffects::StealthRock]
  2727.         if !pkmn.hasWorkingAbility(:MAGICGUARD)
  2728.           atype=getConst(PBTypes,:ROCK) || 0
  2729.           eff=PBTypes.getCombinedEffectiveness(atype,pkmn.type1,pkmn.type2)
  2730.           if eff>0
  2731.             PBDebug.log("[#{pkmn.pbThis} took damage from Stealth Rock]")
  2732.             @scene.pbDamageAnimation(pkmn,0)
  2733.             pkmn.pbReduceHP([(pkmn.totalhp*eff/32).floor,1].max)
  2734.             pbDisplayPaused(_INTL("{1} was hurt by stealth rocks!",pkmn.pbThis))
  2735.           end
  2736.         end
  2737.       end
  2738.       pkmn.pbFaint if pkmn.isFainted?
  2739.       # Toxic Spikes
  2740.       if pkmn.pbOwnSide.effects[PBEffects::ToxicSpikes]>0
  2741.         if !pkmn.isAirborne?(moldbreaker)
  2742.           if pkmn.pbHasType?(:POISON)
  2743.             PBDebug.log("[#{pkmn.pbThis} absorbed Toxic Spikes]")
  2744.             pkmn.pbOwnSide.effects[PBEffects::ToxicSpikes]=0
  2745.             pbDisplayPaused(_INTL("{1} absorbed the poison spikes!",pkmn.pbThis))
  2746.           elsif pkmn.pbCanPoisonSpikes?(moldbreaker)
  2747.             PBDebug.log("[#{pkmn.pbThis} was affected by Toxic Spikes]")
  2748.             if pkmn.pbOwnSide.effects[PBEffects::ToxicSpikes]==2
  2749.               pkmn.pbPoison(pkmn,true)
  2750.               pbDisplayPaused(_INTL("{1} was badly poisoned!",pkmn.pbThis))
  2751.             else
  2752.               pkmn.pbPoison(pkmn)
  2753.               pbDisplayPaused(_INTL("{1} was poisoned!",pkmn.pbThis))
  2754.             end
  2755.           end
  2756.         end
  2757.       end
  2758.     end
  2759.     pkmn.pbAbilityCureCheck
  2760.     if pkmn.isFainted?
  2761.       pbGainEXP
  2762.       pbJudge #      pbSwitch
  2763.       return false
  2764.     end
  2765. #    pkmn.pbAbilitiesOnSwitchIn(true)
  2766.     if !onlyabilities
  2767.       pkmn.pbCheckForm
  2768.       pkmn.pbBerryCureCheck
  2769.     end
  2770.     return true
  2771.   end
  2772.  
  2773.   def pbPrimordialWeather
  2774.     # End Primordial Sea, Desolate Land, Delta Stream
  2775.     hasabil=false
  2776.     case @weather
  2777.     when PBWeather::HEAVYRAIN
  2778.       for i in 0...4
  2779.         if isConst?(@battlers[i].ability,PBAbilities,:PRIMORDIALSEA) &&
  2780.            !@battlers[i].isFainted?
  2781.           hasabil=true; break
  2782.         end
  2783.         if !hasabil
  2784.           @weather=0
  2785.           pbDisplayBrief("The heavy rain has lifted!")
  2786.         end
  2787.       end
  2788.     when PBWeather::HARSHSUN
  2789.       for i in 0...4
  2790.         if isConst?(@battlers[i].ability,PBAbilities,:DESOLATELAND) &&
  2791.            !@battlers[i].isFainted?
  2792.           hasabil=true; break
  2793.         end
  2794.         if !hasabil
  2795.           @weather=0
  2796.           pbDisplayBrief("The harsh sunlight faded!")
  2797.         end
  2798.       end
  2799.     when PBWeather::STRONGWINDS
  2800.       for i in 0...4
  2801.         if isConst?(@battlers[i].ability,PBAbilities,:DELTASTREAM) &&
  2802.            !@battlers[i].isFainted?
  2803.           hasabil=true; break
  2804.         end
  2805.         if !hasabil
  2806.           @weather=0
  2807.           pbDisplayBrief("The mysterious air current has dissipated!")
  2808.         end
  2809.       end
  2810.     end
  2811.   end
  2812.  
  2813. ################################################################################
  2814. # Judging.
  2815. ################################################################################
  2816.   def pbJudgeCheckpoint(attacker,move=0)
  2817.   end
  2818.  
  2819.   def pbDecisionOnTime
  2820.     count1=0
  2821.     count2=0
  2822.     hptotal1=0
  2823.     hptotal2=0
  2824.     for i in @party1
  2825.       next if !i
  2826.       if i.hp>0 && !i.isEgg?
  2827.         count1+=1
  2828.         hptotal1+=i.hp
  2829.       end
  2830.     end
  2831.     for i in @party2
  2832.       next if !i
  2833.       if i.hp>0 && !i.isEgg?
  2834.         count2+=1
  2835.         hptotal2+=i.hp
  2836.       end
  2837.     end
  2838.     return 1 if count1>count2     # win
  2839.     return 2 if count1<count2     # loss
  2840.     return 1 if hptotal1>hptotal2 # win
  2841.     return 2 if hptotal1<hptotal2 # loss
  2842.     return 5                      # draw
  2843.   end
  2844.  
  2845.   def pbDecisionOnTime2
  2846.     count1=0
  2847.     count2=0
  2848.     hptotal1=0
  2849.     hptotal2=0
  2850.     for i in @party1
  2851.       next if !i
  2852.       if i.hp>0 && !i.isEgg?
  2853.         count1+=1
  2854.         hptotal1+=(i.hp*100/i.totalhp)
  2855.       end
  2856.     end
  2857.     hptotal1/=count1 if count1>0
  2858.     for i in @party2
  2859.       next if !i
  2860.       if i.hp>0 && !i.isEgg?
  2861.         count2+=1
  2862.         hptotal2+=(i.hp*100/i.totalhp)
  2863.       end
  2864.     end
  2865.     hptotal2/=count2 if count2>0
  2866.     return 1 if count1>count2     # win
  2867.     return 2 if count1<count2     # loss
  2868.     return 1 if hptotal1>hptotal2 # win
  2869.     return 2 if hptotal1<hptotal2 # loss
  2870.     return 5                      # draw
  2871.   end
  2872.  
  2873.   def pbDecisionOnDraw
  2874.     return 5 # draw
  2875.   end
  2876.  
  2877.   def pbJudge
  2878. #   PBDebug.log("[Counts: #{pbPokemonCount(@party1)}/#{pbPokemonCount(@party2)}]")
  2879.     if pbAllFainted?(@party1) && pbAllFainted?(@party2)
  2880.       @decision=pbDecisionOnDraw() # Draw
  2881.       return
  2882.     end
  2883.     if pbAllFainted?(@party1)
  2884.       @decision=2 # Loss
  2885.       return
  2886.     end
  2887.     if pbAllFainted?(@party2)
  2888.       @decision=1 # Win
  2889.       return
  2890.     end
  2891.   end
  2892.  
  2893. ################################################################################
  2894. # Messages and animations.
  2895. ################################################################################
  2896.   def pbDisplay(msg)
  2897.     @scene.pbDisplayMessage(msg)
  2898.   end
  2899.  
  2900.   def pbDisplayPaused(msg)
  2901.     @scene.pbDisplayPausedMessage(msg)
  2902.   end
  2903.  
  2904.   def pbDisplayBrief(msg)
  2905.     @scene.pbDisplayMessage(msg,true)
  2906.   end
  2907.  
  2908.   def pbDisplayConfirm(msg)
  2909.     @scene.pbDisplayConfirmMessage(msg)
  2910.   end
  2911.  
  2912.   def pbDisplayConfirmBW(msg,msg1,msg2,updateall=true)
  2913.     @scene.pbDisplayConfirmMessageBW(msg,msg1,msg2,updateall)
  2914.   end
  2915.  
  2916.   def pbShowCommands(msg,commands,cancancel=true)
  2917.     @scene.pbShowCommands(msg,commands,cancancel)
  2918.   end
  2919.  
  2920.   def pbAnimation(move,attacker,opponent,hitnum=0)
  2921.     if @battlescene
  2922.       @scene.pbAnimation(move,attacker,opponent,hitnum)
  2923.     end
  2924.   end
  2925.  
  2926.   def pbCommonAnimation(name,attacker,opponent,hitnum=0)
  2927.     if @battlescene
  2928.       @scene.pbCommonAnimation(name,attacker,opponent,hitnum)
  2929.     end
  2930.   end
  2931.  
  2932.   def pbDisplayEffect(battler,hide=true)
  2933.     @scene.pbDisplayEffect(battler,hide)
  2934.   end
  2935.  
  2936.   def pbHideEffect(battler)
  2937.     @scene.pbHideEffect(battler)
  2938.   end
  2939.  
  2940. ################################################################################
  2941. # Battle core.
  2942. ################################################################################
  2943.   def pbStartBattle(canlose=false)
  2944.     PBDebug.log("******************************************")
  2945.     begin
  2946.       pbStartBattleCore(canlose)
  2947.     rescue BattleAbortedException
  2948.       @decision=0
  2949.       @scene.pbEndBattle(@decision)
  2950.     end
  2951.     $game_switches[ENEMYZMOVE]=true
  2952.     return @decision
  2953.   end
  2954.  
  2955.   def pbStartBattleCore(canlose)
  2956.     if !@fullparty1 && @party1.length>MAXPARTYSIZE
  2957.       raise ArgumentError.new(_INTL("Party 1 has more than {1} Pokémon.",MAXPARTYSIZE))
  2958.     end
  2959.     if !@fullparty2 && @party2.length>MAXPARTYSIZE
  2960.       raise ArgumentError.new(_INTL("Party 2 has more than {1} Pokémon.",MAXPARTYSIZE))
  2961.     end
  2962. #========================
  2963. # Initialize wild Pokémon
  2964. #========================
  2965.     if !@opponent
  2966.       if @party2.length==1
  2967.         if @doublebattle
  2968.           raise _INTL("Only two wild Pokémon are allowed in double battles")
  2969.         end
  2970.         wildpoke=@party2[0]
  2971.         @battlers[1].pbInitialize(wildpoke,0,false)
  2972.         @peer.pbOnEnteringBattle(self,wildpoke)
  2973.         pbSetSeen(wildpoke)
  2974.         @scene.pbStartBattle(self)
  2975.         pbDisplayPaused(_INTL("Wild {1} appeared!",wildpoke.name))
  2976.       elsif @party2.length==2
  2977.         if !@doublebattle
  2978.           raise _INTL("Only one wild Pokémon is allowed in single battles")
  2979.         end
  2980.         @battlers[1].pbInitialize(@party2[0],0,false)
  2981.         @battlers[3].pbInitialize(@party2[1],0,false)
  2982.         @peer.pbOnEnteringBattle(self,@party2[0])
  2983.         @peer.pbOnEnteringBattle(self,@party2[1])
  2984.         pbSetSeen(@party2[0])
  2985.         pbSetSeen(@party2[1])
  2986.         @scene.pbStartBattle(self)
  2987.         pbDisplayPaused(_INTL("Wild {1} and\r\n{2} appeared!",
  2988.            @party2[0].name,@party2[1].name))
  2989.       else
  2990.         raise _INTL("Only one or two wild Pokémon are allowed")
  2991.       end
  2992. #=======================================
  2993. # Initialize opponents in double battles
  2994. #=======================================
  2995.     elsif @doublebattle
  2996.       if @opponent.is_a?(Array)
  2997.         if @opponent.length==1
  2998.           @opponent=@opponent[0]
  2999.         elsif @opponent.length!=2
  3000.           raise _INTL("Opponents with zero or more than two people are not allowed")
  3001.         end
  3002.       end
  3003.       if @player.is_a?(Array)
  3004.         if @player.length==1
  3005.           @player=@player[0]
  3006.         elsif @player.length!=2
  3007.           raise _INTL("Player trainers with zero or more than two people are not allowed")
  3008.         end
  3009.       end
  3010.       @scene.pbStartBattle(self)
  3011.       if @opponent.is_a?(Array)
  3012.         pbDisplayPaused(_INTL("{1} and {2} want to battle!",@opponent[0].fullname,@opponent[1].fullname))
  3013.         sendout1=pbFindNextUnfainted(@party2,0,pbSecondPartyBegin(1))
  3014.         raise _INTL("Opponent 1 has no unfainted Pokémon") if sendout1<0
  3015.         sendout2=pbFindNextUnfainted(@party2,pbSecondPartyBegin(1))
  3016.         raise _INTL("Opponent 2 has no unfainted Pokémon") if sendout2<0
  3017.         pbDisplayBrief(_INTL("{1} sent\r\nout {2}!",@opponent[0].fullname,@party2[sendout1].name))
  3018.         @battlers[1].pbInitialize(@party2[sendout1],sendout1,false)
  3019.         @battlers[3].pbInitialize(@party2[sendout2],sendout2,false)
  3020.         @battlers[1].pbInitialize(@party2[sendout1],sendout1,false)
  3021.         @battlers[3].pbInitialize(@party2[sendout2],sendout2,false)
  3022.         pbDisplayBrief(_INTL("{1} sent\r\nout {2}!",@opponent[0].fullname,@battlers[1].name)) #ILLUSION
  3023.         pbSendOut(1,@party2[sendout1])
  3024.         pbDisplayBrief(_INTL("{1} sent\r\nout {2}!",@opponent[1].fullname,@battlers[3].name)) #ILLUSION
  3025.         pbSendOut(3,@party2[sendout2])
  3026.       else
  3027.         pbDisplayPaused(_INTL("{1}\r\nwould like to battle!",@opponent.fullname))
  3028.         sendout1=pbFindNextUnfainted(@party2,0)
  3029.         sendout2=pbFindNextUnfainted(@party2,sendout1+1)
  3030.         @battlers[1].pbInitialize(@party2[sendout1],sendout1,false) #ILLUSION
  3031.         @battlers[3].pbInitialize(@party2[sendout2],sendout2,false)
  3032.         pbDisplayBrief(_INTL("{1} sent\r\nout {2} and {3}!",
  3033.            @opponent.fullname,@battlers[1].name,@battlers[3].name)) #ILLUSION
  3034.         pbSendOut(1,@party2[sendout1])
  3035.         pbSendOut(3,@party2[sendout2])
  3036.       end
  3037. #======================================
  3038. # Initialize opponent in single battles
  3039. #======================================
  3040.     else
  3041.       sendout=pbFindNextUnfainted(@party2,0)
  3042.       raise _INTL("Trainer has no unfainted Pokémon") if sendout<0
  3043.       if @opponent.is_a?(Array)
  3044.         raise _INTL("Opponent trainer must be only one person in single battles") if @opponent.length!=1
  3045.         @opponent=@opponent[0]
  3046.       end
  3047.       if @player.is_a?(Array)
  3048.         raise _INTL("Player trainer must be only one person in single battles") if @player.length!=1
  3049.         @player=@player[0]
  3050.       end
  3051.       trainerpoke=@party2[sendout]
  3052.       @scene.pbStartBattle(self)
  3053.       pbDisplayPaused(_INTL("{1}\r\nwould like to battle!",@opponent.fullname))
  3054.       @battlers[1].pbInitialize(trainerpoke,sendout,false) #ILLUSION
  3055.       pbDisplayBrief(_INTL("{1} sent\r\nout {2}!",@opponent.fullname,@battlers[1].name))
  3056.       pbSendOut(1,trainerpoke)
  3057.     end
  3058. #=====================================
  3059. # Initialize players in double battles
  3060. #=====================================
  3061.     if @doublebattle
  3062.       if @player.is_a?(Array)
  3063.         sendout1=pbFindNextUnfainted(@party1,0,pbSecondPartyBegin(0))
  3064.         raise _INTL("Player 1 has no unfainted Pokémon") if sendout1<0
  3065.         sendout2=pbFindNextUnfainted(@party1,pbSecondPartyBegin(0))
  3066.         raise _INTL("Player 2 has no unfainted Pokémon") if sendout2<0
  3067.         @battlers[0].pbInitialize(@party1[sendout1],sendout1,false) #ILLUSION
  3068.         #@battlers[2].pbInitialize(@party1[sendout2],sendout2,false)
  3069.         pbDisplayBrief(_INTL("{1} sent\r\nout {2}!  Go! {3}!",
  3070.     player[1].fullname,@battlers[2].name,@battlers[0].name))#ILLUSION
  3071.         pbSetSeen(@party1[sendout1])
  3072.         pbSetSeen(@party1[sendout2])
  3073.       else
  3074.         sendout1=pbFindNextUnfainted(@party1,0)
  3075.         sendout2=pbFindNextUnfainted(@party1,sendout1+1)
  3076.         if sendout1<0 || sendout2<0
  3077.           raise _INTL("Player doesn't have two unfainted Pokémon")
  3078.         end
  3079.     @battlers[0].pbInitialize(@party1[sendout1],sendout1,false) #ILLUSION
  3080.     @battlers[2].pbInitialize(@party1[sendout2],sendout2,false)
  3081.         pbDisplayBrief(_INTL("Go! {1} and {2}!",@battlers[0].name,@battlers[2].name)) #ILLUSION
  3082.     end
  3083.       pbSendOut(0,@party1[sendout1])
  3084.       pbSendOut(2,@party1[sendout2])
  3085. #====================================
  3086. # Initialize player in single battles
  3087. #====================================
  3088.     else
  3089.       sendout=pbFindNextUnfainted(@party1,0)
  3090.       if sendout<0
  3091.         raise _INTL("Player has no unfainted Pokémon")
  3092.       end
  3093.       playerpoke=@party1[sendout]
  3094.       @battlers[0].pbInitialize(playerpoke,sendout,false) #Illusion
  3095.       pbDisplayBrief(_INTL("Go! {1}!",@battlers[0].name))
  3096.       pbSendOut(0,playerpoke)
  3097.     end
  3098. #==================
  3099. # Initialize battle
  3100. #==================
  3101.     if @weather==PBWeather::SUNNYDAY
  3102.       pbCommonAnimation("Sunny",nil,nil)
  3103.       pbDisplay(_INTL("The sunlight is strong."))
  3104.     elsif @weather==PBWeather::RAINDANCE
  3105.       pbCommonAnimation("Rain",nil,nil)
  3106.       pbDisplay(_INTL("It is raining."))
  3107.     elsif @weather==PBWeather::SANDSTORM
  3108.       pbCommonAnimation("Sandstorm",nil,nil)
  3109.       pbDisplay(_INTL("A sandstorm is raging."))
  3110.     elsif @weather==PBWeather::HAIL
  3111.       pbCommonAnimation("Hail",nil,nil)
  3112.       pbDisplay(_INTL("Hail is falling."))
  3113.     end
  3114.     pbOnActiveAll   # Abilities
  3115.     @turncount=0
  3116.     loop do   # Now begin the battle loop
  3117.       PBDebug.log("***Round #{@turncount+1}***")
  3118.       if @debug && @turncount>=100
  3119.         @decision=pbDecisionOnTime()
  3120.         PBDebug.log("***Undecided after 100 rounds, aborting***")
  3121.         pbAbort
  3122.         break
  3123.       end
  3124.       PBDebug.logonerr{
  3125.          pbCommandPhase
  3126.       }
  3127.       break if @decision>0
  3128.       PBDebug.logonerr{
  3129.          pbAttackPhase
  3130.       }
  3131.       break if @decision>0
  3132.       PBDebug.logonerr{
  3133.          pbEndOfRoundPhase
  3134.       }
  3135.       break if @decision>0
  3136.       @turncount+=1
  3137.     end
  3138.     return pbEndOfBattle(canlose)
  3139.   end
  3140.  
  3141.  
  3142. ################################################################################
  3143. # Command phase.
  3144. ################################################################################
  3145.   def pbCommandMenu(i)
  3146.     return @scene.pbCommandMenu(i)
  3147.   end
  3148.  
  3149.   def pbItemMenu(i)
  3150.     return @scene.pbItemMenu(i)
  3151.   end
  3152.  
  3153.   def pbAutoFightMenu(i)
  3154.     return false
  3155.   end
  3156.  
  3157.   def pbCommandPhase
  3158.     @scene.pbBeginCommandPhase
  3159.     @scene.pbResetCommandIndices
  3160.     for i in 0...4   # Reset choices if commands can be shown
  3161.       if pbCanShowCommands?(i) || @battlers[i].isFainted?
  3162.         @choices[i][0]=0
  3163.         @choices[i][1]=0
  3164.         @choices[i][2]=nil
  3165.         @choices[i][3]=-1
  3166.       else
  3167.         battler=@battlers[i]
  3168.         unless !@doublebattle && pbIsDoubleBattler?(i)
  3169.           PBDebug.log("[Reusing commands for #{battler.pbThis(true)}]")
  3170.         end
  3171.       end
  3172.     end
  3173.     # Reset choices to perform Mega Evolution if it wasn't done somehow
  3174.     for i in 0..1
  3175.       for j in 0...@megaEvolution[i].length
  3176.         @megaEvolution[i][j]=-1 if @megaEvolution[i][j]>=0
  3177.       end
  3178.     end
  3179.     for i in 0...4
  3180.       break if @decision!=0
  3181.       next if @choices[i][0]!=0
  3182.       if !pbOwnedByPlayer?(i) || @controlPlayer
  3183.         if !@battlers[i].isFainted? && pbCanShowCommands?(i)
  3184.           @scene.pbChooseEnemyCommand(i)
  3185.         end
  3186.       else
  3187.         commandDone=false
  3188.         commandEnd=false
  3189.         if pbCanShowCommands?(i)
  3190.          
  3191.           loop do
  3192.             cmd=pbCommandMenu(i)
  3193.             if cmd==0 # Fight
  3194.               if pbCanShowFightMenu?(i)
  3195.                 commandDone=true if pbAutoFightMenu(i)
  3196.                 until commandDone
  3197.                   index=@scene.pbFightMenu(i)
  3198.                   if index<0
  3199.                     side=(pbIsOpposing?(i)) ? 1 : 0
  3200.                     owner=pbGetOwnerIndex(i)
  3201.                     if @megaEvolution[side][owner]==i
  3202.                       @megaEvolution[side][owner]=-1
  3203.                     end
  3204.                     break
  3205.                   end
  3206.                   next if !pbRegisterMove(i,index)
  3207.                   if @doublebattle
  3208.                     thismove=@battlers[i].moves[index]
  3209.                     target=@battlers[i].pbTarget(thismove)
  3210.                     if target==PBTargets::SingleNonUser # single non-user
  3211.                       target=@scene.pbChooseTarget(i)
  3212.                       next if target<0
  3213.                       pbRegisterTarget(i,target)
  3214.                     elsif target==PBTargets::UserOrPartner # Acupressure
  3215.                       target=@scene.pbChooseTarget(i)
  3216.                       next if target<0 || (target&1)==1
  3217.                       pbRegisterTarget(i,target)
  3218.                     end
  3219.                   end
  3220.                   commandDone=true
  3221.                 end
  3222.               else
  3223.                 pbAutoChooseMove(i)
  3224.                 commandDone=true
  3225.               end
  3226.             elsif cmd==1 # Bag
  3227.               if !@internalbattle
  3228.                 if pbOwnedByPlayer?(i)
  3229.                   pbDisplay(_INTL("Items can't be used here."))
  3230.                 end
  3231.               else
  3232.                 item=pbItemMenu(i)
  3233.                 if item[0]>0
  3234.                   if pbRegisterItem(i,item[0],item[1])
  3235.                     commandDone=true
  3236.                   end
  3237.                 end
  3238.               end
  3239.             elsif cmd==2 # Pokémon
  3240.               pkmn=pbSwitchPlayer(i,false,true)
  3241.               if pkmn>=0
  3242.                 commandDone=true if pbRegisterSwitch(i,pkmn)
  3243.               end
  3244.             elsif cmd==3   # Run
  3245.               run=pbRun(i)
  3246.               if run>0
  3247.                 commandDone=true
  3248.                 return
  3249.               elsif run<0
  3250.                 commandDone=true
  3251.                 side=(pbIsOpposing?(i)) ? 1 : 0
  3252.                 owner=pbGetOwnerIndex(i)
  3253.                 if @megaEvolution[side][owner]==i
  3254.                   @megaEvolution[side][owner]=-1
  3255.                 end
  3256.               end
  3257.             elsif cmd==4   # Call
  3258.               thispkmn=@battlers[i]
  3259.               @choices[i][0]=4   # "Call Pokémon"
  3260.               @choices[i][1]=0
  3261.               @choices[i][2]=nil
  3262.               side=(pbIsOpposing?(i)) ? 1 : 0
  3263.               owner=pbGetOwnerIndex(i)
  3264.               if @megaEvolution[side][owner]==i
  3265.                 @megaEvolution[side][owner]=-1
  3266.               end
  3267.               commandDone=true
  3268.             elsif cmd==-1   # Go back to first battler's choice
  3269.               @megaEvolution[0][0]=-1 if @megaEvolution[0][0]>=0
  3270.               @megaEvolution[1][0]=-1 if @megaEvolution[1][0]>=0
  3271.               # Restore the item the player's first Pokémon was due to use
  3272.               if @choices[0][0]==3 && $PokemonBag && $PokemonBag.pbCanStore?(@choices[0][1])
  3273.                 $PokemonBag.pbStoreItem(@choices[0][1])
  3274.               end
  3275.               pbCommandPhase
  3276.               return
  3277.             end
  3278.             SetInputPlayer(0)
  3279.             break if commandDone
  3280.           end
  3281.         end
  3282.       end
  3283.     end
  3284.   end
  3285.  
  3286. ################################################################################
  3287. # Attack phase.
  3288. ################################################################################
  3289.   def pbAttackPhase
  3290.     @scene.pbBeginAttackPhase
  3291.     for i in 0...4
  3292.       @successStates[i].clear
  3293.       if @choices[i][0]!=1 && @choices[i][0]!=2
  3294.         @battlers[i].effects[PBEffects::DestinyBond]=false
  3295.         @battlers[i].effects[PBEffects::Grudge]=false
  3296.       end
  3297.       @battlers[i].turncount+=1 if !@battlers[i].isFainted?
  3298.       @battlers[i].effects[PBEffects::Rage]=false if !pbChoseMove?(i,:RAGE)
  3299.     end
  3300.     # Calculate priority at this time
  3301.     @usepriority=false
  3302.     priority=pbPriority
  3303.     # Mega Evolution
  3304.     for i in priority
  3305.       next if @choices[i.index][0]!=1
  3306.       side=(pbIsOpposing?(i.index)) ? 1 : 0
  3307.       owner=pbGetOwnerIndex(i.index)
  3308.       if @megaEvolution[side][owner]==i.index
  3309.         pbMegaEvolve(i.index)
  3310.       end
  3311.     end
  3312.    
  3313.         # Call at Pokémon
  3314.     for i in priority
  3315.       if @choices[i.index][0]==4
  3316.         pbCall(i.index)
  3317.       end
  3318.     end
  3319.     # Switch out Pokémon
  3320.     @switching=true
  3321.     switched=[]
  3322.     for i in priority
  3323.       if @choices[i.index][0]==2
  3324.         index=@choices[i.index][1] # party position of Pokémon to switch to
  3325.         self.lastMoveUser=i.index
  3326.         if !pbOwnedByPlayer?(i.index)
  3327.           owner=pbGetOwner(i.index)
  3328.           pbDisplayBrief(_INTL("{1} withdrew {2}!",owner.fullname,i.name))
  3329.           PBDebug.log("[Opponent withdrew #{i.pbThis(true)}]")
  3330.         else
  3331.           pbDisplayBrief(_INTL("{1}, that's enough!\r\nCome back!",i.name))
  3332.           PBDebug.log("[Player withdrew #{i.pbThis(true)}]")
  3333.         end
  3334.         for j in priority
  3335.           next if !i.pbIsOpposing?(j.index)
  3336.           # if Pursuit and this target ("i") was chosen
  3337.           if pbChoseMoveFunctionCode?(j.index,0x88) &&
  3338.              !j.effects[PBEffects::Pursuit] &&
  3339.              (@choices[j.index][3]==-1 || @choices[j.index][3]==i.index)
  3340.             if j.status!=PBStatuses::SLEEP &&
  3341.                j.status!=PBStatuses::FROZEN &&
  3342.                (!j.hasWorkingAbility(:TRUANT) || !j.effects[PBEffects::Truant])
  3343.               j.pbUseMove(@choices[j.index])
  3344.               j.effects[PBEffects::Pursuit]=true
  3345.               # UseMove calls pbGainEXP as appropriate
  3346.               @switching=false
  3347.               return if @decision>0
  3348.             end
  3349.           end
  3350.           break if i.isFainted?
  3351.         end
  3352.         if !pbRecallAndReplace(i.index,index)
  3353.           # If a forced switch somehow occurs here in single battles
  3354.           # the attack phase now ends
  3355.           if !@doublebattle
  3356.             @switching=false
  3357.             return
  3358.           end
  3359.         else
  3360.           switched.push(i.index)
  3361.         end
  3362.       end
  3363.     end
  3364.     if switched.length>0
  3365.       for i in priority
  3366.         i.pbAbilitiesOnSwitchIn(true) if switched.include?(i.index)
  3367.       end
  3368.     end
  3369.     @switching=false
  3370.     # Use items
  3371.     for i in priority
  3372.       if pbIsOpposing?(i.index) && @choices[i.index][0]==3
  3373.         pbEnemyUseItem(@choices[i.index][1],i)
  3374.       elsif @choices[i.index][0]==3
  3375.         # Player use item
  3376.         item=@choices[i.index][1]
  3377.         if item>0
  3378.           usetype=$ItemData[item][ITEMBATTLEUSE]
  3379.           if usetype==1 || usetype==3
  3380.             if @choices[i.index][2]>=0
  3381.               pbUseItemOnPokemon(item,@choices[i.index][2],i,@scene)
  3382.             end
  3383.           elsif usetype==2 || usetype==4
  3384.             if !ItemHandlers.hasUseInBattle(item) # Poké Ball/Poké Doll used already
  3385.               pbUseItemOnBattler(item,@choices[i.index][2],i,@scene)
  3386.             end
  3387.           end
  3388.         end
  3389.       end
  3390.     end
  3391.     # Use attacks
  3392.     for i in priority
  3393.       if pbChoseMoveFunctionCode?(i.index,0x115) # Focus Punch
  3394.         pbCommonAnimation("FocusPunch",i,nil)
  3395.         pbDisplay(_INTL("{1} is tightening its focus!",i.pbThis))
  3396.       elsif pbChoseMoveFunctionCode?(i.index,0x1DF) # Beak Blast
  3397.         pbCommonAnimation("Burn",i,nil)
  3398.         pbDisplay(_INTL("{1} started heating up its beak!",i.pbThis))
  3399.       elsif pbChoseMoveFunctionCode?(i.index,0x1AE) # Shell Trap
  3400.         pbDisplay(_INTL("{1} set up a Shell-Trap!",i.pbThis))    
  3401.       end
  3402.     end
  3403.     10.times do
  3404.       # Forced to go next
  3405.       advance=false
  3406.       for i in priority
  3407.         next if !i.effects[PBEffects::MoveNext]
  3408.         next if i.effects[PBEffects::SkipTurn]
  3409.         advance=i.pbProcessTurn(@choices[i.index])
  3410.         break if advance
  3411.       end
  3412.     end
  3413.     for i in priority
  3414.       i.pbProcessTurn(@choices[i.index])
  3415.       return if @decision>0
  3416.     end
  3417.     pbWait(20)
  3418.   end
  3419.  
  3420. ################################################################################
  3421. # End of round.
  3422. ################################################################################
  3423.   def pbEndOfRoundPhase
  3424.     for i in 0...4
  3425.       @battlers[i].effects[PBEffects::Roost]=false
  3426.       @battlers[i].effects[PBEffects::Protect]=false
  3427.       @battlers[i].effects[PBEffects::ProtectNegation]=false
  3428.       @battlers[i].effects[PBEffects::Endure]=false
  3429.       @battlers[i].effects[PBEffects::FirstPledge]=0
  3430.       @battlers[i].effects[PBEffects::KingsShield]=false
  3431.       @battlers[i].effects[PBEffects::SpikyShield]=false
  3432.       @battlers[i].effects[PBEffects::BanefulBunker]=false
  3433.       @battlers[i].effects[PBEffects::HyperBeam]-=1 if @battlers[i].effects[PBEffects::HyperBeam]>0
  3434.       @battlers[i].effects[PBEffects::MoveNext]=false
  3435.     end
  3436.     @usepriority=false  # recalculate priority
  3437.     priority=pbPriority(true) # Ignoring Quick Claw here
  3438.     # Weather
  3439.     case @weather
  3440.     when PBWeather::SUNNYDAY
  3441.       @weatherduration=@weatherduration-1 if @weatherduration>0
  3442.       if @weatherduration==0
  3443.         pbDisplay(_INTL("The sunlight faded."))
  3444.         @weather=0
  3445.         PBDebug.log("[Sunlight weather ended]")
  3446.       else
  3447.         pbCommonAnimation("Sunny",nil,nil)
  3448. #        pbDisplay(_INTL("The sunlight is strong."));
  3449.         for i in priority
  3450.           if i.hasWorkingAbility(:SOLARPOWER)
  3451.             PBDebug.log("[#{i.pbThis}'s Solar Power triggered]")
  3452.             @scene.pbDamageAnimation(i,0)
  3453.             i.pbReduceHP((i.totalhp/8).floor)
  3454.             pbDisplay(_INTL("{1} was hurt by the sunlight!",i.pbThis))
  3455.             if i.isFainted?
  3456.               return if !i.pbFaint
  3457.             end
  3458.           end
  3459.         end
  3460.       end
  3461.     when PBWeather::RAINDANCE
  3462.       @weatherduration=@weatherduration-1 if @weatherduration>0
  3463.       if @weatherduration==0
  3464.         pbDisplay(_INTL("The rain stopped."))
  3465.         @weather=0
  3466.         PBDebug.log("[Rain weather ended]")
  3467.       else
  3468.         pbCommonAnimation("Rain",nil,nil)
  3469. #        pbDisplay(_INTL("Rain continues to fall."));
  3470.       end
  3471.     when PBWeather::SANDSTORM
  3472.       @weatherduration=@weatherduration-1 if @weatherduration>0
  3473.       if @weatherduration==0
  3474.         pbDisplay(_INTL("The sandstorm subsided."))
  3475.         @weather=0
  3476.         PBDebug.log("[Sandstorm weather ended]")
  3477.       else
  3478.         pbCommonAnimation("Sandstorm",nil,nil)
  3479. #        pbDisplay(_INTL("The sandstorm rages."))
  3480.         if pbWeather==PBWeather::SANDSTORM
  3481.           PBDebug.log("[Sandstorm weather inflicted damage]")
  3482.           for i in priority
  3483.             next if i.isFainted?
  3484.             if !i.pbHasType?(:GROUND) && !i.pbHasType?(:ROCK) && !i.pbHasType?(:STEEL) &&
  3485.                !i.hasWorkingAbility(:SANDVEIL) &&
  3486.                !i.hasWorkingAbility(:SANDRUSH) &&
  3487.                !i.hasWorkingAbility(:SANDFORCE) &&
  3488.                !i.hasWorkingAbility(:MAGICGUARD) &&
  3489.                !i.hasWorkingAbility(:OVERCOAT) &&
  3490.                ![0xCA,0xCB].include?(PBMoveData.new(i.effects[PBEffects::TwoTurnAttack]).function) # Dig, Dive
  3491.               @scene.pbDamageAnimation(i,0)
  3492.               i.pbReduceHP((i.totalhp/16).floor)
  3493.               pbDisplay(_INTL("{1} is buffeted by the sandstorm!",i.pbThis))
  3494.               if i.isFainted?
  3495.                 return if !i.pbFaint
  3496.               end
  3497.             end
  3498.           end
  3499.         end
  3500.       end
  3501.     when PBWeather::HAIL
  3502.       @weatherduration=@weatherduration-1 if @weatherduration>0
  3503.       if @weatherduration==0
  3504.         pbDisplay(_INTL("The hail stopped."))
  3505.         @weather=0
  3506.         PBDebug.log("[Hail weather ended]")
  3507.       else
  3508.         pbCommonAnimation("Hail",nil,nil)
  3509. #        pbDisplay(_INTL("Hail continues to fall."))
  3510.         if pbWeather==PBWeather::HAIL
  3511.           PBDebug.log("[Hail weather inflicted damage]")
  3512.           for i in priority
  3513.             next if i.isFainted?
  3514.             if !i.pbHasType?(:ICE) &&
  3515.                !i.hasWorkingAbility(:ICEBODY) &&
  3516.                !i.hasWorkingAbility(:SNOWCLOAK) &&
  3517.                !i.hasWorkingAbility(:MAGICGUARD) &&
  3518.                !i.hasWorkingAbility(:OVERCOAT) &&
  3519.                ![0xCA,0xCB].include?(PBMoveData.new(i.effects[PBEffects::TwoTurnAttack]).function) # Dig, Dive
  3520.               @scene.pbDamageAnimation(i,0)
  3521.               i.pbReduceHP((i.totalhp/16).floor)
  3522.               pbDisplay(_INTL("{1} is buffeted by the hail!",i.pbThis))
  3523.               if i.isFainted?
  3524.                 return if !i.pbFaint
  3525.               end
  3526.             end
  3527.           end
  3528.         end
  3529.       end
  3530.     when PBWeather::HEAVYRAIN
  3531.       hasabil=false
  3532.       for i in 0...4
  3533.         if isConst?(@battlers[i].ability,PBAbilities,:PRIMORDIALSEA) && !@battlers[i].isFainted?
  3534.           hasabil=true; break
  3535.         end
  3536.       end
  3537.       @weatherduration=0 if !hasabil
  3538.       if @weatherduration==0
  3539.         pbDisplay(_INTL("The heavy rain stopped."))
  3540.         @weather=0
  3541.         PBDebug.log("[End of effect] Primordial Sea's rain weather ended")
  3542.       else
  3543.         pbCommonAnimation("HeavyRain",nil,nil)
  3544. #        pbDisplay(_INTL("It is raining heavily."))
  3545.       end
  3546.     when PBWeather::HARSHSUN
  3547.       hasabil=false
  3548.       for i in 0...4
  3549.         if isConst?(@battlers[i].ability,PBAbilities,:DESOLATELAND) && !@battlers[i].isFainted?
  3550.           hasabil=true; break
  3551.         end
  3552.       end
  3553.       @weatherduration=0 if !hasabil
  3554.       if @weatherduration==0
  3555.         pbDisplay(_INTL("The harsh sunlight faded."))
  3556.         @weather=0
  3557.         PBDebug.log("[End of effect] Desolate Land's sunlight weather ended")
  3558.       else
  3559.         pbCommonAnimation("HarshSun",nil,nil)
  3560. #        pbDisplay(_INTL("The sunlight is extremely harsh."))
  3561.         if pbWeather==PBWeather::HARSHSUN
  3562.           for i in priority
  3563.             if i.hasWorkingAbility(:SOLARPOWER)
  3564.               PBDebug.log("[Ability triggered] #{i.pbThis}'s Solar Power")
  3565.               @scene.pbDamageAnimation(i,0)
  3566.               i.pbReduceHP((i.totalhp/8).floor)
  3567.               pbDisplay(_INTL("{1} was hurt by the sunlight!",i.pbThis))
  3568.               if i.isFainted?
  3569.                 return if !i.pbFaint
  3570.               end
  3571.             end
  3572.           end
  3573.         end
  3574.       end
  3575.     when PBWeather::STRONGWINDS
  3576.       hasabil=false
  3577.       for i in 0...4
  3578.         if isConst?(@battlers[i].ability,PBAbilities,:DELTASTREAM) && !@battlers[i].isFainted?
  3579.           hasabil=true; break
  3580.         end
  3581.       end
  3582.       @weatherduration=0 if !hasabil
  3583.       if @weatherduration==0
  3584.         pbDisplay(_INTL("The air current subsided."))
  3585.         @weather=0
  3586.         PBDebug.log("[End of effect] Delta Stream's wind weather ended")
  3587.       else
  3588.         pbCommonAnimation("StrongWinds",nil,nil)
  3589. #        pbDisplay(_INTL("The wind is strong."))
  3590.       end
  3591.     end
  3592.     # Shadow Sky weather
  3593.     if isConst?(@weather,PBWeather,:SHADOWSKY)
  3594.       @weatherduration=@weatherduration-1 if @weatherduration>0
  3595.       if @weatherduration==0
  3596.         pbDisplay(_INTL("The shadow sky faded."))
  3597.         @weather=0
  3598.         PBDebug.log("[Shadow Sky weather ended]")
  3599.       else
  3600.         pbCommonAnimation("ShadowSky",nil,nil)
  3601. #        pbDisplay(_INTL("The shadow sky continues."));
  3602.         if isConst?(pbWeather,PBWeather,:SHADOWSKY)
  3603.           PBDebug.log("[Shadow Sky weather inflicted damage]")
  3604.           for i in priority
  3605.             next if i.isFainted?
  3606.             if !i.isShadow?
  3607.               @scene.pbDamageAnimation(i,0)
  3608.               i.pbReduceHP((i.totalhp/16).floor)
  3609.               pbDisplay(_INTL("{1} was hurt by the shadow sky!",i.pbThis))
  3610.               if i.isFainted?
  3611.                 return if !i.pbFaint
  3612.               end
  3613.             end
  3614.           end
  3615.         end
  3616.       end
  3617.     end
  3618.     # Future Sight/Doom Desire
  3619.     for i in battlers   # not priority
  3620.       next if i.isFainted?
  3621.       if i.effects[PBEffects::FutureSight]>0
  3622.         i.effects[PBEffects::FutureSight]-=1
  3623.         if i.effects[PBEffects::FutureSight]==0
  3624.           PBDebug.log("[Future Sight struck #{i.pbThis(true)}]")
  3625.           move=PokeBattle_Move.pbFromPBMove(self,PBMove.new(i.effects[PBEffects::FutureSightMove]))
  3626.           pbDisplay(_INTL("{1} took the {2} attack!",i.pbThis,move.name))
  3627.           moveuser=@battlers[i.effects[PBEffects::FutureSightUser]]
  3628.           if i.isFainted? || move.pbAccuracyCheck(moveuser,i)
  3629.             damage=((i.effects[PBEffects::FutureSightDamage]*85)/100).floor
  3630.             damage=1 if damage<1
  3631.             i.damagestate.reset
  3632.             pbCommonAnimation("FutureSight",i,nil)
  3633.             move.pbReduceHPDamage(damage,nil,i)
  3634.           else
  3635.             pbDisplay(_INTL("But it failed!"))
  3636.           end
  3637.           i.effects[PBEffects::FutureSight]=0
  3638.           i.effects[PBEffects::FutureSightMove]=0
  3639.           i.effects[PBEffects::FutureSightDamage]=0
  3640.           i.effects[PBEffects::FutureSightUser]=-1
  3641.           if i.isFainted?
  3642.             return if !i.pbFaint
  3643.             next
  3644.           end
  3645.         end
  3646.       end
  3647.     end
  3648.     # Godly
  3649.     for i in battlers
  3650.   if i.hasWorkingAbility(:GODLY)
  3651.     break if rand(3) > 0
  3652.     for j in battlers
  3653.       next if j.index == i.index
  3654.       next if (j.index%2) == (i.index%2)
  3655.       next if j.isFainted?
  3656.       next if opponent
  3657.       opponent = j
  3658.     end
  3659.     break if opponent.nil?
  3660.     type = rand(2)==0 ? opponent.type1 : opponent.type2
  3661.     types = []
  3662.     for t in 0..PBTypes.maxValue
  3663.       next if PBTypes.isPseudoType?(t)
  3664.       types.push(t) if PBTypes.getEffectiveness(t,type) > 2
  3665.     end
  3666.     break if types.length < 1
  3667.     final = types[rand(types.length)]
  3668.     break if i.type1 == final
  3669.     i.type1 = final
  3670.     i.type2 = final
  3671.     pbDisplay(_INTL("{1} is exerting a tremendous Aura!",i.pbThis))
  3672.     i.pokemon.form = final
  3673.     @scene.pbChangePokemon(i,i.pokemon)
  3674.     pbDisplay(_INTL("{1} changed to the {2} type!",i.pbThis,PBTypes.getName(final)))
  3675.   end
  3676. end
  3677.     for i in priority
  3678.       next if i.isFainted?
  3679.       # Rain Dish
  3680.       if pbWeather==PBWeather::RAINDANCE && i.hasWorkingAbility(:RAINDISH)
  3681.         PBDebug.log("[#{i.pbThis}'s Rain Dish triggered]")
  3682.         hpgain=i.pbRecoverHP((i.totalhp/16).floor,true)
  3683.         pbDisplay(_INTL("{1}'s Rain Dish restored its HP a little!",i.pbThis)) if hpgain>0
  3684.       end
  3685.       # Dry Skin
  3686.       if i.hasWorkingAbility(:DRYSKIN)
  3687.         PBDebug.log("[#{i.pbThis}'s Dry Skin triggered]")
  3688.         if pbWeather==PBWeather::RAINDANCE
  3689.           hpgain=i.pbRecoverHP((i.totalhp/8).floor,true)
  3690.           pbDisplay(_INTL("{1}'s Dry Skin was healed by the rain!",i.pbThis)) if hpgain>0
  3691.         elsif pbWeather==PBWeather::SUNNYDAY
  3692.           @scene.pbDamageAnimation(i,0)
  3693.           hploss=i.pbReduceHP((i.totalhp/8).floor)
  3694.           pbDisplay(_INTL("{1}'s Dry Skin was hurt by the sunlight!",i.pbThis)) if hploss>0
  3695.         end
  3696.       end
  3697.       # Ice Body
  3698.       if pbWeather==PBWeather::HAIL && i.hasWorkingAbility(:ICEBODY)
  3699.         PBDebug.log("[#{i.pbThis}'s Ice Body triggered]")
  3700.         hpgain=i.pbRecoverHP((i.totalhp/16).floor,true)
  3701.         pbDisplay(_INTL("{1}'s Ice Body restored its HP a little!",i.pbThis)) if hpgain>0
  3702.       end
  3703.       if i.isFainted?
  3704.         return if !i.pbFaint
  3705.         next
  3706.       end
  3707.     end
  3708.     # Wish
  3709.     for i in priority
  3710.       next if i.isFainted?
  3711.       if i.effects[PBEffects::Wish]>0
  3712.         i.effects[PBEffects::Wish]-=1
  3713.         if i.effects[PBEffects::Wish]==0
  3714.           PBDebug.log("[#{i.pbThis}'s wish triggered]")
  3715.           hpgain=i.pbRecoverHP(i.effects[PBEffects::WishAmount],true)
  3716.           if hpgain>0
  3717.             wishmaker=pbThisEx(i.index,i.effects[PBEffects::WishMaker])
  3718.             pbDisplay(_INTL("{1}'s wish came true!",wishmaker))
  3719.           end
  3720.         end
  3721.       end
  3722.     end
  3723.     # Fire Pledge + Grass Pledge combination damage - should go here
  3724.     for i in priority
  3725.       next if i.isFainted?
  3726.       # Shed Skin
  3727.       if i.hasWorkingAbility(:SHEDSKIN)
  3728.         if pbRandom(10)<3 && i.status>0
  3729.           case i.status
  3730.           when PBStatuses::SLEEP
  3731.             pbDisplay(_INTL("{1}'s {2} cured its sleep problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3732.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its sleep]")
  3733.           when PBStatuses::POISON
  3734.             pbDisplay(_INTL("{1}'s {2} cured its poison problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3735.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its poison]")
  3736.           when PBStatuses::BURN
  3737.             pbDisplay(_INTL("{1}'s {2} cured its burn problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3738.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its burn]")
  3739.           when PBStatuses::PARALYSIS
  3740.             pbDisplay(_INTL("{1}'s {2} cured its paralysis problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3741.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its paralysis]")
  3742.           when PBStatuses::FROZEN
  3743.             pbDisplay(_INTL("{1}'s {2} cured its ice problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3744.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its frozen]")
  3745.           end
  3746.           i.status=0
  3747.           i.statusCount=0
  3748.         end
  3749.       end
  3750.       # Hydration
  3751.       if i.hasWorkingAbility(:HYDRATION) && pbWeather==PBWeather::RAINDANCE
  3752.         if i.status>0
  3753.           case i.status
  3754.           when PBStatuses::SLEEP
  3755.             pbDisplay(_INTL("{1}'s {2} cured its sleep problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3756.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its sleep]")
  3757.           when PBStatuses::POISON
  3758.             pbDisplay(_INTL("{1}'s {2} cured its poison problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3759.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its poison]")
  3760.           when PBStatuses::BURN
  3761.             pbDisplay(_INTL("{1}'s {2} cured its burn problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3762.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its burn]")
  3763.           when PBStatuses::PARALYSIS
  3764.             pbDisplay(_INTL("{1}'s {2} cured its paralysis problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3765.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its paralysis]")
  3766.           when PBStatuses::FROZEN
  3767.             pbDisplay(_INTL("{1}'s {2} cured its ice problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3768.             PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured its frozen]")
  3769.           end
  3770.           i.status=0
  3771.           i.statusCount=0
  3772.         end
  3773.       end
  3774.       # Healer
  3775.       if i.hasWorkingAbility(:HEALER)
  3776.         partner=i.pbPartner
  3777.         if partner
  3778.           if pbRandom(10)<3 && partner.status>0
  3779.             case partner.status
  3780.             when PBStatuses::SLEEP
  3781.               pbDisplay(_INTL("{1}'s {2} cured its partner's sleep problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3782.               PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured #{partner.pbThis(true)}'s sleep]")
  3783.             when PBStatuses::POISON
  3784.               pbDisplay(_INTL("{1}'s {2} cured its partner's poison problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3785.               PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured #{partner.pbThis(true)}'s poison]")
  3786.             when PBStatuses::BURN
  3787.               pbDisplay(_INTL("{1}'s {2} cured its partner's burn problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3788.               PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured #{partner.pbThis(true)}'s burn]")
  3789.             when PBStatuses::PARALYSIS
  3790.               pbDisplay(_INTL("{1}'s {2} cured its partner's paralysis problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3791.               PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured #{partner.pbThis(true)}'s paralysis]")
  3792.             when PBStatuses::FROZEN
  3793.               pbDisplay(_INTL("{1}'s {2} cured its partner's ice problem!",i.pbThis,PBAbilities.getName(i.ability)))
  3794.               PBDebug.log("[#{i.pbThis}'s #{PBAbilities.getName(i.ability)} cured #{partner.pbThis(true)}'s frozen]")
  3795.             end
  3796.             partner.status=0
  3797.             partner.statusCount=0
  3798.           end
  3799.         end
  3800.       end
  3801.     end
  3802.     # Held berries/Leftovers/Black Sludge
  3803.     for i in priority
  3804.       next if i.isFainted?
  3805.       # Grassy Terrain (healing)
  3806.       if @field.effects[PBEffects::GrassyTerrain]>0 && !i.isAirborne?
  3807.         hpgain=i.pbRecoverHP((i.totalhp/16).floor,true)
  3808.         pbDisplay(_INTL("{1}'s HP was restored.",i.pbThis)) if hpgain>0
  3809.       end
  3810.       i.pbBerryCureCheck(true)
  3811.       if i.isFainted?
  3812.         return if !i.pbFaint
  3813.         next
  3814.       end
  3815.     end
  3816.     # Aqua Ring
  3817.     for i in priority
  3818.       next if i.isFainted?
  3819.       if i.effects[PBEffects::AquaRing]
  3820.         PBDebug.log("[#{i.pbThis}'s Aqua Ring triggered]")
  3821.         hpgain=(i.totalhp/16).floor
  3822.         hpgain=(hpgain*1.3).floor if i.hasWorkingItem(:BIGROOT)
  3823.         hpgain=i.pbRecoverHP(hpgain,true)
  3824.         pbDisplay(_INTL("{1}'s Aqua Ring restored its HP a little!",i.pbThis)) if hpgain>0
  3825.       end
  3826.     end
  3827.     # Ingrain
  3828.     for i in priority
  3829.       next if i.isFainted?
  3830.       if i.effects[PBEffects::Ingrain]
  3831.         PBDebug.log("[#{i.pbThis}'s Ingrain triggered]")
  3832.         hpgain=(i.totalhp/16).floor
  3833.         hpgain=(hpgain*1.3).floor if i.hasWorkingItem(:BIGROOT)
  3834.         hpgain=i.pbRecoverHP(hpgain,true)
  3835.         pbDisplay(_INTL("{1} absorbed nutrients with its roots!",i.pbThis)) if hpgain>0
  3836.       end
  3837.     end
  3838.     # Leech Seed
  3839.     for i in priority
  3840.       next if i.isFainted?
  3841.       if i.effects[PBEffects::LeechSeed]>=0
  3842.         recipient=@battlers[i.effects[PBEffects::LeechSeed]]
  3843.         if recipient && !recipient.isFainted? # if recipient exists
  3844.           PBDebug.log("[#{i.pbThis}'s Leech Seed triggered]")
  3845.           pbCommonAnimation("LeechSeed",recipient,i)
  3846.           hploss=i.pbReduceHP((i.totalhp/8).floor,true)
  3847.           if i.hasWorkingAbility(:LIQUIDOOZE)
  3848.             recipient.pbReduceHP(hploss,true)
  3849.             pbDisplay(_INTL("{1} sucked up the liquid ooze!",recipient.pbThis))
  3850.           elsif recipient.effects[PBEffects::HealBlock]==0
  3851.             hploss=(hploss*1.3).floor if recipient.hasWorkingItem(:BIGROOT)
  3852.             recipient.pbRecoverHP(hploss,true)
  3853.             pbDisplay(_INTL("{1}'s health was sapped by Leech Seed!",i.pbThis))
  3854.           end
  3855.           if i.isFainted?
  3856.             return if !i.pbFaint
  3857.           end
  3858.           if recipient.isFainted?
  3859.             return if !recipient.pbFaint
  3860.           end
  3861.         end
  3862.       end
  3863.     end
  3864.     for i in priority
  3865.       next if i.isFainted?
  3866.       # Poison/Bad poison
  3867.       if i.status==PBStatuses::POISON
  3868.         if i.hasWorkingAbility(:POISONHEAL)
  3869.           PBDebug.log("[#{i.pbThis}'s Poison Heal triggered]")
  3870.           if i.effects[PBEffects::HealBlock]==0
  3871.             if i.hp<i.totalhp
  3872.               pbCommonAnimation("Poison",i,nil)
  3873.               i.pbRecoverHP((i.totalhp/8).floor,true)
  3874.               pbDisplay(_INTL("{1} is healed by poison!",i.pbThis))
  3875.             end
  3876.             if i.statusCount>0
  3877.               i.effects[PBEffects::Toxic]+=1
  3878.               i.effects[PBEffects::Toxic]=[15,i.effects[PBEffects::Toxic]].min
  3879.             end
  3880.           end
  3881.         else
  3882.           PBDebug.log("[#{i.pbThis} took damage from poison/toxic]")
  3883.           if i.statusCount==0
  3884.             i.pbReduceHP((i.totalhp/8).floor)
  3885.           else
  3886.             i.effects[PBEffects::Toxic]+=1
  3887.             i.effects[PBEffects::Toxic]=[15,i.effects[PBEffects::Toxic]].min
  3888.             i.pbReduceHP((i.totalhp/16).floor*i.effects[PBEffects::Toxic])
  3889.           end
  3890.           i.pbContinueStatus
  3891.         end
  3892.       end
  3893.       # Burn
  3894.       if i.status==PBStatuses::BURN
  3895.         PBDebug.log("[#{i.pbThis} took damage from burn]")
  3896.         if i.hasWorkingAbility(:HEATPROOF)
  3897.           PBDebug.log("[#{i.pbThis}'s Heatproof triggered]")
  3898.           i.pbReduceHP((i.totalhp/16).floor)
  3899.         else
  3900.           i.pbReduceHP((i.totalhp/8).floor)
  3901.         end
  3902.         i.pbContinueStatus
  3903.       end
  3904.       # Nightmare
  3905.       if i.effects[PBEffects::Nightmare]
  3906.         if i.status==PBStatuses::SLEEP
  3907.           PBDebug.log("[#{i.pbThis} took damage from a nightmare]")
  3908.           i.pbReduceHP((i.totalhp/4).floor,true)
  3909.           pbDisplay(_INTL("{1} is locked in a nightmare!",i.pbThis))
  3910.         else
  3911.           i.effects[PBEffects::Nightmare]=false
  3912.         end
  3913.       end
  3914.       if i.isFainted?
  3915.         return if !i.pbFaint
  3916.         next
  3917.       end
  3918.     end
  3919.     # Curse
  3920.     for i in priority
  3921.       next if i.isFainted?
  3922.       if i.effects[PBEffects::Curse]
  3923.         PBDebug.log("[#{i.pbThis} took damage from a curse]")
  3924.         i.pbReduceHP((i.totalhp/4).floor,true)
  3925.         pbDisplay(_INTL("{1} is afflicted by the curse!",i.pbThis))
  3926.       end
  3927.       if i.isFainted?
  3928.         return if !i.pbFaint
  3929.         next
  3930.       end
  3931.     end
  3932.     # Multi-turn attacks (Bind/Clamp/Fire Spin/Magma Storm/Sand Tomb/Whirlpool/Wrap)
  3933.     for i in priority
  3934.       next if i.isFainted?
  3935.       if i.effects[PBEffects::MultiTurn]>0
  3936.         i.effects[PBEffects::MultiTurn]-=1
  3937.         movename=PBMoves.getName(i.effects[PBEffects::MultiTurnAttack])
  3938.         if i.effects[PBEffects::MultiTurn]==0
  3939.           PBDebug.log("[Trapping move #{movename} affecting #{i.pbThis} ended]")
  3940.           pbDisplay(_INTL("{1} was freed from {2}!",i.pbThis,movename))
  3941.         else
  3942.           PBDebug.log("[#{i.pbThis} took damage from trapping move #{movename}]")
  3943.           if isConst?(i.effects[PBEffects::MultiTurnAttack],PBMoves,:BIND)
  3944.             pbCommonAnimation("Bind",i,nil)
  3945.           elsif isConst?(i.effects[PBEffects::MultiTurnAttack],PBMoves,:CLAMP)
  3946.             pbCommonAnimation("Clamp",i,nil)
  3947.           elsif isConst?(i.effects[PBEffects::MultiTurnAttack],PBMoves,:FIRESPIN)
  3948.             pbCommonAnimation("FireSpin",i,nil)
  3949.           elsif isConst?(i.effects[PBEffects::MultiTurnAttack],PBMoves,:MAGMASTORM)
  3950.             pbCommonAnimation("MagmaStorm",i,nil)
  3951.           elsif isConst?(i.effects[PBEffects::MultiTurnAttack],PBMoves,:SANDTOMB)
  3952.             pbCommonAnimation("SandTomb",i,nil)
  3953.           elsif isConst?(i.effects[PBEffects::MultiTurnAttack],PBMoves,:WRAP)
  3954.             pbCommonAnimation("Wrap",i,nil)
  3955.           else
  3956.             pbCommonAnimation("Wrap",i,nil)
  3957.           end
  3958.           @scene.pbDamageAnimation(i,0)
  3959.           i.pbReduceHP((i.totalhp/16).floor)
  3960.           pbDisplay(_INTL("{1} is hurt by {2}!",i.pbThis,movename))
  3961.         end
  3962.       end  
  3963.       if i.isFainted?
  3964.         return if !i.pbFaint
  3965.         next
  3966.       end
  3967.     end
  3968.     # Taunt
  3969.     for i in priority
  3970.       next if i.isFainted?
  3971.       if i.effects[PBEffects::Taunt]>0
  3972.         i.effects[PBEffects::Taunt]-=1
  3973.         if i.effects[PBEffects::Taunt]==0
  3974.           pbDisplay(_INTL("{1} recovered from the taunting!",i.pbThis))
  3975.           PBDebug.log("[#{i.pbThis} is no longer taunted]")
  3976.         end
  3977.       end
  3978.     end
  3979.     # Encore
  3980.     for i in priority
  3981.       next if i.isFainted?
  3982.       if i.effects[PBEffects::Encore]>0
  3983.         if i.moves[i.effects[PBEffects::EncoreIndex]].id!=i.effects[PBEffects::EncoreMove]
  3984.           i.effects[PBEffects::Encore]=0
  3985.           i.effects[PBEffects::EncoreIndex]=0
  3986.           i.effects[PBEffects::EncoreMove]=0
  3987.           PBDebug.log("[#{i.pbThis} is no longer encored (encored move was lost)]")
  3988.         else
  3989.           i.effects[PBEffects::Encore]-=1
  3990.           if i.effects[PBEffects::Encore]==0 || i.moves[i.effects[PBEffects::EncoreIndex]].pp==0
  3991.             i.effects[PBEffects::Encore]=0
  3992.             pbDisplay(_INTL("{1}'s encore ended!",i.pbThis))
  3993.             PBDebug.log("[#{i.pbThis} is no longer encored]")
  3994.           end
  3995.         end
  3996.       end
  3997.     end
  3998.     # Disable/Cursed Body
  3999.     for i in priority
  4000.       next if i.isFainted?
  4001.       if i.effects[PBEffects::Disable]>0
  4002.         i.effects[PBEffects::Disable]-=1
  4003.         if i.effects[PBEffects::Disable]==0
  4004.           i.effects[PBEffects::DisableMove]=0
  4005.           pbDisplay(_INTL("{1} is disabled no more!",i.pbThis))
  4006.           PBDebug.log("[#{i.pbThis} is no longer disabled]")
  4007.         end
  4008.       end
  4009.     end
  4010.     # Magnet Rise
  4011.     for i in priority
  4012.       next if i.isFainted?
  4013.       if i.effects[PBEffects::MagnetRise]>0
  4014.         i.effects[PBEffects::MagnetRise]-=1
  4015.         if i.effects[PBEffects::MagnetRise]==0
  4016.           pbDisplay(_INTL("{1} stopped levitating.",i.pbThis))
  4017.           PBDebug.log("[#{i.pbThis} is no longer levitating by Magnet Rise]")
  4018.         end
  4019.       end
  4020.     end
  4021.     # Telekinesis
  4022.     for i in priority
  4023.       next if i.isFainted?
  4024.       if i.effects[PBEffects::Telekinesis]>0
  4025.         i.effects[PBEffects::Telekinesis]-=1
  4026.         if i.effects[PBEffects::Telekinesis]==0
  4027.           pbDisplay(_INTL("{1} stopped levitating.",i.pbThis))
  4028.           PBDebug.log("[#{i.pbThis} is no longer levitating by Telekinesis]")
  4029.         end
  4030.       end
  4031.     end
  4032.     # Heal Block
  4033.     for i in priority
  4034.       next if i.isFainted?
  4035.       if i.effects[PBEffects::HealBlock]>0
  4036.         i.effects[PBEffects::HealBlock]-=1
  4037.         if i.effects[PBEffects::HealBlock]==0
  4038.           pbDisplay(_INTL("The heal block on {1} ended.",i.pbThis))
  4039.           PBDebug.log("[#{i.pbThis} is no longer Heal Blocked]")
  4040.         end
  4041.       end
  4042.     end
  4043.     # Embargo
  4044.     for i in priority
  4045.       next if i.isFainted?
  4046.       if i.effects[PBEffects::Embargo]>0
  4047.         i.effects[PBEffects::Embargo]-=1
  4048.         if i.effects[PBEffects::Embargo]==0
  4049.           pbDisplay(_INTL("The embargo on {1} was lifted.",i.pbThis(true)))
  4050.           PBDebug.log("[#{i.pbThis} is no longer affected by an embarge]")
  4051.         end
  4052.       end
  4053.     end
  4054.     # Yawn
  4055.     for i in priority
  4056.       next if i.isFainted?
  4057.       if i.effects[PBEffects::Yawn]>0
  4058.         i.effects[PBEffects::Yawn]-=1
  4059.         if i.effects[PBEffects::Yawn]==0 && i.pbCanSleepYawn?
  4060.           PBDebug.log("[#{i.pbThis}'s yawning triggered]")
  4061.           i.pbSleep
  4062.           pbDisplay(_INTL("{1} fell asleep!",i.pbThis))
  4063.         end
  4064.       end
  4065.     end
  4066.     # Perish Song
  4067.     perishSongUsers=[]
  4068.     for i in priority
  4069.       next if i.isFainted?
  4070.       if i.effects[PBEffects::PerishSong]>0
  4071.         i.effects[PBEffects::PerishSong]-=1
  4072.         pbDisplay(_INTL("{1}'s Perish count fell to {2}!",i.pbThis,i.effects[PBEffects::PerishSong]))
  4073.         PBDebug.log("[#{i.pbThis}'s Perish Song count dropped to #{i.effects[PBEffects::PerishSong]}]")
  4074.         if i.effects[PBEffects::PerishSong]==0
  4075.           perishSongUsers.push(i.effects[PBEffects::PerishSongUser])
  4076.           i.pbReduceHP(i.hp,true)
  4077.         end
  4078.       end
  4079.       if i.isFainted?
  4080.         return if !i.pbFaint
  4081.       end
  4082.     end
  4083.     if perishSongUsers.length>0
  4084.       # If all remaining Pokemon fainted by a Perish Song triggered by a single side
  4085.       if (perishSongUsers.find_all{|item| pbIsOpposing?(item) }.length==perishSongUsers.length) ||
  4086.          (perishSongUsers.find_all{|item| !pbIsOpposing?(item) }.length==perishSongUsers.length)
  4087.         pbJudgeCheckpoint(@battlers[perishSongUsers[0]])
  4088.       end
  4089.     end
  4090.     if @decision>0
  4091.       pbGainEXP
  4092.       return
  4093.     end
  4094.     # Reflect
  4095.     for i in 0...2
  4096.       if sides[i].effects[PBEffects::Reflect]>0
  4097.         sides[i].effects[PBEffects::Reflect]-=1
  4098.         if sides[i].effects[PBEffects::Reflect]==0
  4099.           pbDisplay(_INTL("Your team's Reflect faded!")) if i==0
  4100.           pbDisplay(_INTL("The opposing team's Reflect faded!")) if i==1
  4101.           PBDebug.log("[Reflect ended on the player's side]") if i==0
  4102.           PBDebug.log("[Reflect ended on the opponent's side]") if i==1
  4103.         end
  4104.       end
  4105.     end
  4106.     # Light Screen
  4107.     for i in 0...2
  4108.       if sides[i].effects[PBEffects::LightScreen]>0
  4109.         sides[i].effects[PBEffects::LightScreen]-=1
  4110.         if sides[i].effects[PBEffects::LightScreen]==0
  4111.           pbDisplay(_INTL("Your team's Light Screen faded!")) if i==0
  4112.           pbDisplay(_INTL("The opposing team's Light Screen faded!")) if i==1
  4113.           PBDebug.log("[Light Screen ended on the player's side]") if i==0
  4114.           PBDebug.log("[Light Screen ended on the opponent's side]") if i==1
  4115.         end
  4116.       end
  4117.     end
  4118.     # Safeguard
  4119.     for i in 0...2
  4120.       if sides[i].effects[PBEffects::Safeguard]>0
  4121.         sides[i].effects[PBEffects::Safeguard]-=1
  4122.         if sides[i].effects[PBEffects::Safeguard]==0
  4123.           pbDisplay(_INTL("Your team is no longer protected by Safeguard!")) if i==0
  4124.           pbDisplay(_INTL("The opposing team is no longer protected by Safeguard!")) if i==1
  4125.           PBDebug.log("[Safeguard ended on the player's side]") if i==0
  4126.           PBDebug.log("[Safeguard ended on the opponent's side]") if i==1
  4127.         end
  4128.       end
  4129.     end
  4130.     # Mist
  4131.     for i in 0...2
  4132.       if sides[i].effects[PBEffects::Mist]>0
  4133.         sides[i].effects[PBEffects::Mist]-=1
  4134.         if sides[i].effects[PBEffects::Mist]==0
  4135.           pbDisplay(_INTL("Your team's Mist faded!")) if i==0
  4136.           pbDisplay(_INTL("The opposing team's Mist faded!")) if i==1
  4137.           PBDebug.log("[Mist ended on the player's side]") if i==0
  4138.           PBDebug.log("[Mist ended on the opponent's side]") if i==1
  4139.         end
  4140.       end
  4141.     end
  4142.     # Tailwind
  4143.     for i in 0...2
  4144.       if sides[i].effects[PBEffects::Tailwind]>0
  4145.         sides[i].effects[PBEffects::Tailwind]-=1
  4146.         if sides[i].effects[PBEffects::Tailwind]==0
  4147.           pbDisplay(_INTL("Your team's tailwind stopped blowing!")) if i==0
  4148.           pbDisplay(_INTL("The opposing team's tailwind stopped blowing!")) if i==1
  4149.           PBDebug.log("[Tailwind ended on the player's side]") if i==0
  4150.           PBDebug.log("[Tailwind ended on the opponent's side]") if i==1
  4151.         end
  4152.       end
  4153.     end
  4154.     # Lucky Chant
  4155.     for i in 0...2
  4156.       if sides[i].effects[PBEffects::LuckyChant]>0
  4157.         sides[i].effects[PBEffects::LuckyChant]-=1
  4158.         if sides[i].effects[PBEffects::LuckyChant]==0
  4159.           pbDisplay(_INTL("Your team's Lucky Chant faded!")) if i==0
  4160.           pbDisplay(_INTL("The opposing team's Lucky Chant faded!")) if i==1
  4161.           PBDebug.log("[Lucky Chant ended on the player's side]") if i==0
  4162.           PBDebug.log("[Lucky Chant ended on the opponent's side]") if i==1
  4163.         end
  4164.       end
  4165.     end
  4166.     # End of Pledge move combinations
  4167.     # Gravity
  4168.     if @field.effects[PBEffects::Gravity]>0
  4169.       @field.effects[PBEffects::Gravity]-=1
  4170.       if @field.effects[PBEffects::Gravity]==0
  4171.         pbDisplay(_INTL("Gravity returned to normal."))
  4172.         PBDebug.log("[Strong gravity ended]")
  4173.       end
  4174.     end
  4175.     # Electric Terrain
  4176.     if @field.effects[PBEffects::ElectricTerrain]>0
  4177.       @field.effects[PBEffects::ElectricTerrain]-=1
  4178.       if @field.effects[PBEffects::ElectricTerrain]==0
  4179.         pbDisplay(_INTL("The electric current disappeared from the battlefield."))
  4180.         PBDebug.log("[End of effect] Electric Terrain ended")
  4181.       end
  4182.     end
  4183.     # Grassy Terrain (counting down)
  4184.     if @field.effects[PBEffects::GrassyTerrain]>0
  4185.       @field.effects[PBEffects::GrassyTerrain]-=1
  4186.       if @field.effects[PBEffects::GrassyTerrain]==0
  4187.         pbDisplay(_INTL("The grass disappeared from the battlefield."))
  4188.         PBDebug.log("[End of effect] Grassy Terrain ended")
  4189.       end
  4190.     end
  4191.     # Misty Terrain
  4192.     if @field.effects[PBEffects::MistyTerrain]>0
  4193.       @field.effects[PBEffects::MistyTerrain]-=1
  4194.       if @field.effects[PBEffects::MistyTerrain]==0
  4195.         pbDisplay(_INTL("The mist disappeared from the battlefield."))
  4196.         PBDebug.log("[End of effect] Misty Terrain ended")
  4197.       end
  4198.     end
  4199.     # Psychic Terrain
  4200.     if @field.effects[PBEffects::PsychicTerrain]>0
  4201.       @field.effects[PBEffects::PsychicTerrain]-=1
  4202.       if @field.effects[PBEffects::PsychicTerrain]==0
  4203.         pbDisplay(_INTL("The energy disappeared from the battlefield."))
  4204.         PBDebug.log("[End of effect] Psychic Terrain ended")
  4205.       end
  4206.     end
  4207.     # Trick Room - should go here
  4208.     # Wonder Room - should go here
  4209.     # Magic Room
  4210.     if @field.effects[PBEffects::MagicRoom]>0
  4211.       @field.effects[PBEffects::MagicRoom]-=1
  4212.       if @field.effects[PBEffects::MagicRoom]==0
  4213.         pbDisplay(_INTL("The area returned to normal."))
  4214.         PBDebug.log("[Magic Room ended]")
  4215.       end
  4216.     end
  4217.     # Uproar
  4218.     for i in priority
  4219.       next if i.isFainted?
  4220.       if i.effects[PBEffects::Uproar]>0
  4221.         for j in priority
  4222.           if !j.isFainted? && j.status==PBStatuses::SLEEP && !j.hasWorkingAbility(:SOUNDPROOF)
  4223.             j.effects[PBEffects::Nightmare]=false
  4224.             j.status=0
  4225.             j.statusCount=0
  4226.             pbDisplay(_INTL("{1} woke up in the uproar!",j.pbThis))
  4227.             PBDebug.log("[#{j.pbThis} awoke in the uproar]")
  4228.           end
  4229.         end
  4230.         i.effects[PBEffects::Uproar]-=1
  4231.         if i.effects[PBEffects::Uproar]==0
  4232.           pbDisplay(_INTL("{1} calmed down.",i.pbThis))
  4233.           PBDebug.log("[#{i.pbThis} is no longer uproaring]")
  4234.         else
  4235.           pbDisplay(_INTL("{1} is making an uproar!",i.pbThis))
  4236.         end
  4237.       end
  4238.     end
  4239.     for i in priority
  4240.       next if i.isFainted?
  4241.       # Speed Boost
  4242.       # A Pokémon's turncount is 0 if it became active after the beginning of a round
  4243.       if i.turncount>0 && i.hasWorkingAbility(:SPEEDBOOST)
  4244.         PBDebug.log("[#{i.pbThis}'s Speed Boost triggered]")
  4245.         if !i.pbTooHigh?(PBStats::SPEED)
  4246.           i.pbIncreaseStatBasic(PBStats::SPEED,1)
  4247.           pbCommonAnimation("StatUp",i,nil)
  4248.           pbDisplay(_INTL("{1}'s Speed Boost raised its Speed!",i.pbThis))
  4249.         end
  4250.       end
  4251.       # Bad Dreams
  4252.       if i.status==PBStatuses::SLEEP
  4253.         if i.pbOpposing1.hasWorkingAbility(:BADDREAMS) ||
  4254.            i.pbOpposing2.hasWorkingAbility(:BADDREAMS)
  4255.           PBDebug.log("[#{i.pbThis}'s opponent's Bad Dreams triggered]")
  4256.           hploss=i.pbReduceHP((i.totalhp/8).floor,true)
  4257.           pbDisplay(_INTL("{1} is having a bad dream!",i.pbThis)) if hploss>0
  4258.         end
  4259.       end
  4260.       if i.isFainted?
  4261.         return if !i.pbFaint
  4262.         next
  4263.       end
  4264.       # Harvest - should go here
  4265.       # Moody
  4266.       if i.hasWorkingAbility(:MOODY)
  4267.         PBDebug.log("[#{i.pbThis}'s Moody triggered]")
  4268.         randomup=[]; randomdown=[]
  4269.         for i in [PBStats::ATTACK,PBStats::DEFENSE,PBStats::SPEED,PBStats::SPATK,
  4270.                   PBStats::SPDEF,PBStats::ACCURACY,PBStats::EVASION]
  4271.           randomup.push(i) if !i.pbTooHigh?(i)
  4272.           randomdown.push(i) if !i.pbTooLow?(i)
  4273.         end
  4274.         statnames=[_INTL("Attack"),_INTL("Defense"),_INTL("Speed"),_INTL("Special Attack"),
  4275.                    _INTL("Special Defense"),_INTL("accuracy"),_INTL("evasiveness")]
  4276.         if randomup.length>0
  4277.           r=self.pbRandom(randomup.length)
  4278.           i.pbIncreaseStatBasic(randomup[r],2)
  4279.           pbCommonAnimation("StatUp",i,nil)
  4280.           pbDisplay(_INTL("{1}'s Moody sharply raised its {2}!",i.pbThis,statnames[randomup[r]-1]))
  4281.         end
  4282.         if randomdown.length>0
  4283.           r=self.pbRandom(randomdown.length)
  4284.           i.pbReduceStatBasic(randomdown[r],1)
  4285.           pbCommonAnimation("StatDown",i,nil)
  4286.           pbDisplay(_INTL("{1}'s Moody lowered its {2}!",i.pbThis,statnames[randomdown[r]-1]))
  4287.         end
  4288.       end
  4289.     end
  4290.     for i in priority
  4291.       next if i.isFainted?
  4292.       # Toxic Orb
  4293.       if i.hasWorkingItem(:TOXICORB) && i.status==0 && i.pbCanPoison?(false)
  4294.         PBDebug.log("[#{i.pbThis}'s Toxic Orb triggered]")
  4295.         PBDebug.log("[#{i.pbThis}: was poisoned")
  4296.         i.status=PBStatuses::POISON
  4297.         i.statusCount=1
  4298.         i.effects[PBEffects::Toxic]=0
  4299.         pbCommonAnimation("Poison",i,nil)
  4300.         pbDisplay(_INTL("{1} was poisoned by its {2}!",i.pbThis,PBItems.getName(i.item)))
  4301.       end
  4302.       # Flame Orb
  4303.       if i.hasWorkingItem(:FLAMEORB) && i.status==0 && i.pbCanBurn?(false)
  4304.         PBDebug.log("[#{i.pbThis}'s Flame Orb triggered]")
  4305.         PBDebug.log("[#{i.pbThis}: was burned")
  4306.         i.status=PBStatuses::BURN
  4307.         i.statusCount=0
  4308.         pbCommonAnimation("Burn",i,nil)
  4309.         pbDisplay(_INTL("{1} was burned by its {2}!",i.pbThis,PBItems.getName(i.item)))
  4310.       end
  4311.       # Sticky Barb
  4312.       if i.hasWorkingItem(:STICKYBARB) && !i.hasWorkingAbility(:MAGICGUARD)
  4313.         PBDebug.log("[#{i.pbThis}'s Sticky Barb triggered]")
  4314.         pbDisplay(_INTL("{1} is hurt by its {2}!",i.pbThis,PBItems.getName(i.item)))
  4315.         @scene.pbDamageAnimation(i,0)
  4316.         i.pbReduceHP((i.totalhp/8).floor)
  4317.       end
  4318.       if i.isFainted?
  4319.         return if !i.pbFaint
  4320.         next
  4321.       end
  4322.     end
  4323.     # Form checks
  4324.     for i in 0...4
  4325.       next if @battlers[i].isFainted?
  4326.       @battlers[i].pbCheckForm
  4327.     end
  4328.     pbGainEXP
  4329.     pbSwitch
  4330.     return if @decision>0
  4331.     for i in priority
  4332.       next if i.isFainted?
  4333.       i.pbAbilitiesOnSwitchIn(false)
  4334.     end
  4335.     # Healing Wish/Lunar Dance - should go here
  4336.     # Spikes/Toxic Spikes/Stealth Rock - should go here (in order of their 1st use)
  4337.     for i in 0...4
  4338.       if @battlers[i].turncount>0 && @battlers[i].hasWorkingAbility(:TRUANT)
  4339.         @battlers[i].effects[PBEffects::Truant]=!@battlers[i].effects[PBEffects::Truant]
  4340.       end
  4341.       if @battlers[i].effects[PBEffects::LockOn]>0   # Also Mind Reader
  4342.         @battlers[i].effects[PBEffects::LockOn]-=1
  4343.         @battlers[i].effects[PBEffects::LockOnPos]=-1 if @battlers[i].effects[PBEffects::LockOn]==0
  4344.       end
  4345.       if @battlers[i].effects[PBEffects::LaserFocus]>0   # Also Mind Reader
  4346.         @battlers[i].effects[PBEffects::LaserFocus]-=2
  4347.       end
  4348.       @battlers[i].effects[PBEffects::Flinch]=false
  4349.       @battlers[i].effects[PBEffects::FollowMe]=false
  4350.       @battlers[i].effects[PBEffects::Spotlight]=false
  4351.       @battlers[i].effects[PBEffects::HelpingHand]=false
  4352.       @battlers[i].effects[PBEffects::MagicCoat]=false
  4353.       @battlers[i].effects[PBEffects::Snatch]=false
  4354.       @battlers[i].effects[PBEffects::Charge]-=1 if @battlers[i].effects[PBEffects::Charge]>0
  4355.       @battlers[i].lastHPLost=0
  4356.       @battlers[i].lastAttacker=-1
  4357.       @battlers[i].effects[PBEffects::Counter]=-1
  4358.       @battlers[i].effects[PBEffects::CounterTarget]=-1
  4359.       @battlers[i].effects[PBEffects::ShellTrap]=-1
  4360.       @battlers[i].effects[PBEffects::MirrorCoat]=-1
  4361.       @battlers[i].effects[PBEffects::MirrorCoatTarget]=-1
  4362.     end
  4363.     @field.effects[PBEffects::FusionBolt]=false
  4364.     @field.effects[PBEffects::FusionFlare]=false
  4365.     @field.effects[PBEffects::IonDeluge]=false
  4366.     # invalidate stored priority
  4367.     @usepriority=false
  4368.   end
  4369.  
  4370. ################################################################################
  4371. # End of battle.
  4372. ################################################################################
  4373.   def pbEndOfBattle(canlose=false)
  4374.     case @decision
  4375.     ##### WIN #####
  4376.     when 1
  4377.       PBDebug.log("***Player won***")
  4378.       if @opponent
  4379.         @scene.pbTrainerBattleSuccess
  4380.         if @opponent.is_a?(Array)
  4381.           pbDisplayPaused(_INTL("{1} defeated {2} and {3}!",self.pbPlayer.name,@opponent[0].fullname,@opponent[1].fullname))
  4382.         else
  4383.           pbDisplayPaused(_INTL("{1} defeated\r\n{2}!",self.pbPlayer.name,@opponent.fullname))
  4384.         end
  4385.         @scene.pbShowOpponent(0)
  4386.         pbDisplayPaused(@endspeech.gsub(/\\[Pp][Nn]/,self.pbPlayer.name))
  4387.         if @opponent.is_a?(Array)
  4388.           @scene.pbHideOpponent
  4389.           @scene.pbShowOpponent(1)
  4390.           pbDisplayPaused(@endspeech2.gsub(/\\[Pp][Nn]/,self.pbPlayer.name))
  4391.         end
  4392.         # Calculate money gained for winning
  4393.         if @internalbattle
  4394.           tmoney=0
  4395.           if @opponent.is_a?(Array)   # Double battles
  4396.             maxlevel1=0; maxlevel2=0; limit=pbSecondPartyBegin(1)
  4397.             for i in 0...limit
  4398.               if @party2[i]
  4399.                 maxlevel1=@party2[i].level if maxlevel1<@party2[i].level
  4400.               end
  4401.               if @party2[i+limit]
  4402.                 maxlevel2=@party2[i+limit].level if maxlevel1<@party2[i+limit].level
  4403.               end
  4404.             end
  4405.             tmoney+=maxlevel1*@opponent[0].moneyEarned
  4406.             tmoney+=maxlevel2*@opponent[1].moneyEarned
  4407.           else
  4408.             maxlevel=0
  4409.             for i in @party2
  4410.               next if !i
  4411.               maxlevel=i.level if maxlevel<i.level
  4412.             end
  4413.             tmoney+=maxlevel*@opponent.moneyEarned
  4414.           end
  4415.           # If Amulet Coin/Luck Incense's effect applies, double money earned
  4416.           tmoney*=2 if @amuletcoin
  4417.           oldmoney=self.pbPlayer.money
  4418.           self.pbPlayer.money+=tmoney
  4419.           moneygained=self.pbPlayer.money-oldmoney
  4420.           if moneygained>0
  4421.             pbDisplayPaused(_INTL("{1} got ${2}\r\nfor winning!",self.pbPlayer.name,tmoney))
  4422.           end
  4423.         end
  4424.       end
  4425.       if @internalbattle && @extramoney>0
  4426.         @extramoney*=2 if @amuletcoin
  4427.         oldmoney=self.pbPlayer.money
  4428.         self.pbPlayer.money+=@extramoney
  4429.         moneygained=self.pbPlayer.money-oldmoney
  4430.         if moneygained>0
  4431.           pbDisplayPaused(_INTL("{1} picked up ${2}!",self.pbPlayer.name,@extramoney))
  4432.         end
  4433.       end
  4434.       for pkmn in @snaggedpokemon
  4435.         pbStorePokemon(pkmn)
  4436.         self.pbPlayer.shadowcaught=[] if !self.pbPlayer.shadowcaught
  4437.         self.pbPlayer.shadowcaught[pkmn.species]=true
  4438.       end
  4439.       @snaggedpokemon.clear
  4440.     ##### LOSE, DRAW #####
  4441.     when 2, 5
  4442.       PBDebug.log("***Player lost***") if @decision==2
  4443.       PBDebug.log("***Player drew with opponent***") if @decision==5
  4444.       if @internalbattle
  4445.         pbDisplayPaused(_INTL("{1} is out of usable Pokémon!",self.pbPlayer.name))
  4446.         moneylost=pbMaxLevelFromIndex(0)   # Player's Pokémon only, not partner's
  4447.         multiplier=[8,16,24,36,48,60,80,100,120]
  4448.         moneylost*=multiplier[[multiplier.length-1,self.pbPlayer.numbadges].min]
  4449.         moneylost=self.pbPlayer.money if moneylost>self.pbPlayer.money
  4450.         moneylost=0 if $game_switches[NO_MONEY_LOSS]
  4451.         oldmoney=self.pbPlayer.money
  4452.         self.pbPlayer.money-=moneylost
  4453.         lostmoney=oldmoney-self.pbPlayer.money
  4454.         if @opponent
  4455.           if @opponent.is_a?(Array)
  4456.             pbDisplayPaused(_INTL("{1} lost against {2} and {3}!",self.pbPlayer.name,@opponent[0].fullname,@opponent[1].fullname))
  4457.           else
  4458.             pbDisplayPaused(_INTL("{1} lost against\r\n{2}!",self.pbPlayer.name,@opponent.fullname))
  4459.           end
  4460.           if moneylost>0
  4461.             pbDisplayPaused(_INTL("{1} paid ${2}\r\nas the prize money...",self.pbPlayer.name,lostmoney))  
  4462.             pbDisplayPaused(_INTL("...")) if !canlose
  4463.           end
  4464.         else
  4465.           if moneylost>0
  4466.             pbDisplayPaused(_INTL("{1} panicked and lost\r\n${2}...",self.pbPlayer.name,lostmoney))
  4467.             pbDisplayPaused(_INTL("...")) if !canlose
  4468.           end
  4469.         end
  4470.         pbDisplayPaused(_INTL("{1} blacked out!",self.pbPlayer.name)) if !canlose
  4471.       elsif @decision==2
  4472.         @scene.pbShowOpponent(0)
  4473.         pbDisplayPaused(@endspeechwin.gsub(/\\[Pp][Nn]/,self.pbPlayer.name))
  4474.         if @opponent.is_a?(Array)
  4475.           @scene.pbHideOpponent
  4476.           @scene.pbShowOpponent(1)
  4477.           pbDisplayPaused(@endspeechwin2.gsub(/\\[Pp][Nn]/,self.pbPlayer.name))
  4478.         end
  4479.       end
  4480.     end
  4481.     # Pass on Pokérus within the party
  4482.     infected=[]
  4483.     for i in 0...$Trainer.party.length
  4484.       if $Trainer.party[i].pokerusStage==1
  4485.         infected.push(i)
  4486.       end
  4487.     end
  4488.     if infected.length>=1
  4489.       for i in infected
  4490.         strain=$Trainer.party[i].pokerus/16
  4491.         if i>0 && $Trainer.party[i-1].pokerusStage==0
  4492.           $Trainer.party[i-1].givePokerus(strain) if rand(3)==0
  4493.         end
  4494.         if i<$Trainer.party.length-1 && $Trainer.party[i+1].pokerusStage==0
  4495.           $Trainer.party[i+1].givePokerus(strain) if rand(3)==0
  4496.         end
  4497.       end
  4498.     end
  4499.     @scene.pbEndBattle(@decision)
  4500.     for i in @battlers
  4501.       i.pbResetForm
  4502.       if i.hasWorkingAbility(:NATURALCURE)
  4503.         i.status=0
  4504.       end
  4505.     end
  4506.     for i in $Trainer.party
  4507.       i.setItem(i.itemInitial)
  4508.       i.itemInitial=i.itemRecycle=0
  4509.     end
  4510.     if !$game_switches[NO_Z_MOVEI]
  4511.       $game_switches[NO_Z_MOVEI]=true
  4512.     end
  4513.     return @decision
  4514.   end
  4515.   ### Wild pokemon drops item if defeated
  4516.   def pbDropItem (i)
  4517.     if rand(100)>50 && @battlers[i].item!=0 && !@opponent
  4518.       $PokemonBag.pbStoreItem(@battlers[i].item)
  4519.       pbDisplay(_INTL("{1} picked up {2} from the pokemon!", $Trainer.name, PBItems.getName(@battlers[i].item)))
  4520.     end
  4521.   end  
  4522. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement