Advertisement
Vendily

updated

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