Advertisement
Guest User

Untitled

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