Solved Debug Menu opens by itself

Marina

Elite Trainer
Member
Posts
106
#1
Edit: it seems to work now, I just deleted 2 Scripts from Cilerba, Leilou and removed the Debug option in DP Pause Menu.

I just added 2 scripts "Cilerba's Drop Item" and "Random Pokemon by Leilou", idk why the debug menu opens by itselfs all the time,
even when I press X and it opens again, all the time. I deleted those 2 scripts from Leilou and Cilerba and the problem is still there!
I tried to start a new game, but the debug menu opens by itself even in the intro.
I looked into the script of DP Pause Menu from Marin, where I had an option, which called the debug menu. I removed this option.
And the problem is still there. Now, I can't think of what causes this strange behavior of the game...
I am translating my game into german, that's why the message texts are in german and the comments too.
Maybe I should list here the scripts I have, right under the compiler. I also use version 17.2 of Essentials.

Scripts:

Ruby:
#===============================================================================
# * Konfigurationsskript für Ihr Spiel hier. Ändert das emo_ in irgendeine
#        Nummer, welche die Zelle hält, in der sich auch die Animation befindet.
#===============================================================================
Unused_Common_Event         = 5          #Das allgemeine Ereignis sollte leer sein, aber reserviert.
Following_Activated_Switch = 126      # Schalter sollte reserviert sein.
Toggle_Following_Switch = 103         # Schalter sollte reserviert sein.
Current_Following_Variable = 36       # Variabel sollte reserviert sein.
ItemWalk=26                           # Variabel sollte reserviert sein.
Walking_Time_Variable = 27            # Variabel sollte reserviert sein.
Walking_Item_Variable = 28            # Variabel sollte reserviert sein.
Animation_Come_Out = 93             
Animation_Come_In = 94
Emo_Happy = 95
Emo_Normal = 96
Emo_Hate = 97
Emo_Poison= 98
Emo_sing= 99
Emo_love= 100

# * Unterstützung für Pokémon Birthsigns Skript
Emo_Cake= 92 if self.class.const_defined?(:PBBirthsigns) &&  self.class.const_get(:PBBirthsigns).instance_of?(::Module)

ALLOWTOGGLEFOLLOW = true       #Ermöglicht den Spieler die Begleiter an/aus zu schalten.
ALLOWFIELDSWITCHING = true     #Ermöglicht den Spieler durch Pokemon zu kreisen.
APPLYSTATUSTONES = true #Fügt dem Begleiter einen Ton hinzu, wenn es eine Statusbedingung hat.
#Statustöne, die verwendet werden sollen, wenn das Obige wahr ist (Rot, Grün, Blau, Grau)
BURNTONE = [204,51,51,50]
POISONTONE = [153,102,204,50]
PARALYSISTONE = [255,255,153,50]
FREEZETONE = [153,204,204,50]
SLEEPTONE = [0,0,0,0]  # Ich habe diesen Ton nicht verwendet, aber du kannst wenn du möchtest.
ALWAYS_ANIMATE  = true #Das Begleiter-Sprite wird im Stillstand immer animiert sein.
#Unabhängig von der obigen Einstellung werden die Arten in diesem Array immer animiert.
ALWAYS_ANIMATED_FOLLOWERS=[151]  # Mew
#Hinzufügen von Ausnahmen zu immer animierten (kleine Vögel wie Taubsi hüpfen meistens aufgrund kleiner Flügel)
ALWAYS_ANIMATED_EXCEPTION=[16] #Taubsi
#Für jetzt entfernt:
#REGULAR_WALKING = true
WATERPOKEMONCANSURF = true  #Ermöglicht es Wasser-Pokémon, dem Spieler während des surfens, zu begleiten.
WATERPOKEMONCANDIVE = true #Ermöglicht es Wasser-Pokémon, dem Spieler während des tauchens, zu begleiten.
ALWAYS_ANIMATED_CAN_SURF = true #Pokémon die immer animiert sind, können dich
                                # übers Wasser (fliegend, Schwebend, oder spezifiziert) begleiten.

#Nicht Verändern!
FOLLOWER_FILE_PATH = "Graphics/Characters/"
#Der Unterordner, indem sich eure Begleiter-Sprites befinden.
#Muss sich innerhalb von Graphics/Characters befinden
FOLLOWER_FILE_DIR = ""
                                          

#===============================================================================
# * Gutschrift an: Help-14 sowohl für die Original-Skripte als auch für die Sprites.
# * Änderungsprotokoll:
#===============================================================================

#===============================================================================
# * Bearbeitet von: zingzags
#===============================================================================
# * Fehler behoben.
# * Aufräumarbeiten
# * Surf fehler wurde behoben (Nachdem Surfer eingesetzt wurde)
# * Definition: talk_to_pokemon während des Surfens wurde behoben.
# * Surf-Prüfer wurde behoben.
# * Typ-Prüfer wurde behoben.
# * Unterstützung für Türen wurde hinzugefügt.
# * HP-Fehler wurde behoben.
# * Unterstützung für das Pokémon Center, wurde hinzugefügt.
# * Animationsprobleme wurden behoben.
# * Walk_time_variable Problem behoben.
# * Zufällige Item-Beute wurden hinzugefügt.
# * Ei-Prüfer wurde hinzugefügt.
#===============================================================================

#===============================================================================
# * Bearbeitet von: Rayd12smitty
# * Version 1.0
#===============================================================================
# * Walk_Time_Variable behoben.
# * Absturz behoben, wenn mit Pokémon auf einer anderen Karte gesprochen wurde,
#   als auf der Originalkarte.
# * Das Erhalten der Items von Pokémon funktioniert jetzt.
# * Talk_to_Pokemon mit mehr Nachrichten und speziellen Nachrichten verbessert.
# * Nachrichten für alle Statusbedingungen wurde hinzugefügt.
# * Team-Wechsel (Rotation) wurde hinzugefügt, um den Begleiter zu wechseln.
# * Pokémon-Begleiter wurde umschaltbar gemacht.
# * Animation für Pokémon hinzugefügt, welche in sprite_refresh aus Pokéball kommen.
# * Skript-Layout aufgeräumt und benutzerfreundlicher gemacht.
# * Problem behoben, bei dem Pokemon auf Leisten herumsprangen.
# * Der Tippfehlers beim Surfer-Orden im Skript wurde behoben.
#===============================================================================
# * Version 1.1
#===============================================================================
# * Das Surfen wurde korrigiert, sodass Pokemon nicht wieder auf dem Wasser
#                             angezeigt werden, wenn es ausgeschaltet wurde.
# * Layout und Position des Toggle-Skripts wurden geändert.
#===============================================================================

#===============================================================================
# * Bearbeitet von Rayd12smitty und venom12
# * Version 1.2
#===============================================================================
# * Fixed Walk step count so it doesn't add on when Pokemon is toggled off
# * Ihr müsst Toggle_Following_Switch und following_Activated_Switch nicht mehr
#    manuell einstellen, wenn "pbPokemonFollow (x)" aufgerufen wird
# * Unterstützt jetzt Pokémon mit verschiedenen Formen!
# * Items, die auf bestimmte Maps gefunden werden können, werden unterstützt.
# * Unterstützung für Nachrichten auf einer Map mit einem Wort / Satz im Namen
#   anstelle einer einzelnen Map
# * Schritt-Animation wurde für die Begleiter-Pokémon hinzugefügt.
# * Problem beim Absteigen behoben, sodass Pokémon erneut angezeigt werden.
# * Fahrrad repariert, wenn es nicht verwendet werden kann, kann es jetzt.
# * Einige andere kleine Fahrradkorrekturen.
#===============================================================================

#===============================================================================
# * Version 1.3
#===============================================================================
# * Fehler beim Surfen behoben, bei dem der Begleiter den Spieler daran hindern
#   konnte zu surfen und möglicherweise den Spieler zu einer Strandung zu bringen.
# * Skript hinzugefügt, um alle Ereignisse mit dem Namen "Poke" zu animieren.
# * Die Zeit um ein Item zu finden, wurde erhöht. Ich erkenne jetzt,
#   dass 5000 Frames weniger als 5 Minuten sind. viel zu kurz.
#===============================================================================

#===============================================================================
# * Bearbeitet von: mej71
# * Version 1.4
#===============================================================================
# * Alles in einem Skriptabschnitt zusammengefasst, um die Installation zu vereinfachen.
# * Einstellung wurde hinzugefügt, um das Radfahren durch Pokemon im Feld zu aktivieren/deaktivieren.
# * Ton-Effekt zum folgenden Pokemon hinzugefügt, wenn Statusprobleme hervorliegen.
# * Die Gras Animation vom Begleiter wurde behoben.
# * NPC's gehen jetzt nicht mehr über den Begleiter.
# * Absturz behoben, der durch das Umschalten des Begleiters beim Laden einer Map verursacht wurde. Dieser Fehler wurde behoben
# * Verhindert die Verwendung von VM, wenn ihr ein Nicht-Begleiter-abhängiges Ereignis habt.
#   hoffentlich wird dies mehr dazu beitragen, regelmäßige abhängige Ereignisse zu unterstützen
# * Euer Begleiter dreht sich nicht automatisch, wenn ihr das tut, daher wirkt es natürlicher.
# * Es gibt jetzt eine Einstellung, mit der Pokémon immer animiert werden, während du stillstehst.
# * Beachtet dabei, dass das Fliegen, Schweben oder irgendeine angegebene
#  Pokémon-Art immer unabhängig von dieser Einstellung animiert wird.
# *Reflektierte Sprites Unterstützung für Begleiter-Pokémon.
# *Die Spielerübertragung funktioniert etwas besser, Dein Begleiter
#  sollte nicht mehr über dir erscheinen.
# *Es gibt eine Einstellung, welche die Wasser-Pokémon ermöglicht, euch über Wasser zu begleiten.
# *Zusätzliche Einstellungen ermöglichen das Fliegen, Schweben, oder andere
#  Pokémon-Arten, die euch auch über Wasser begleiten.
# *Sprite wird nach der Weiterentwicklung aktualisiert.
# *In Ohnmacht fallen, verursacht keine Fehler.
# *v15.1 Kompatibilität
# *Begleiter Laufzyklus funktioniert ordnungsgemäß
# *Beweg-Routen funktionieren ordnungsgemäß
# (sie funktionierten schon in ältere Versionen, aber waren in meiner Version
#  vorübergehend kaputt)
# *Pokémon werden beim fahrradfahren zurückgesetzt, nur in der Map
# *Begleiter werden geprüft wenn sie unterwasser gehen (Wasser-Pokémon können auch unterwasser begleiten)
# *Unterstützung für Pokémon Birthsigns Script
#===============================================================================

#===============================================================================
# * Zu erledigen:
#===============================================================================
# * Keine.  Perfekt?
#===============================================================================



#===============================================================================
# * Kontrolliere das Begleiter-Pokemon
# * Zum Beispiel:
#     FollowingMoveRoute([
#         PBMoveRoute::TurnRight,
#         PBMoveRoute::Wait,4,
#         PBMoveRoute::Jump,0,0
#     ])
# * Das Pokémon dreht sich nach rechts, wartet 4 Frames, und springt.
# * Rufe pbPokeStep um alle Events auf der Map namens "Poke", zu animieren.
#===============================================================================
def FollowingMoveRoute(commands,waitComplete=false)
  return if $Trainer.party[0].hp<=0 || $Trainer.party[0].isEgg? ||
      $game_variables[Current_Following_Variable]==0 ||
      !$game_switches[Toggle_Following_Switch]
  $PokemonTemp.dependentEvents.SetMoveRoute(commands,waitComplete)
end

def pbPokeStep
  for event in $game_map.events.values
    if event.name=="Poke"             
      pbMoveRoute(event,[PBMoveRoute::StepAnimeOn])
    end
  end
end
#===============================================================================
# * Umschalter für Begleiter Pokémon
#===============================================================================
def pbToggleFollowingPokemon
  return if $Trainer.party[0].hp<=0 || $Trainer.party[0].isEgg?
  if $game_switches[Following_Activated_Switch]
    if $game_switches[Toggle_Following_Switch]
      $game_switches[Toggle_Following_Switch]=false
      $PokemonTemp.dependentEvents.remove_sprite(true)
      pbWait(1)   
    else
      $game_switches[Toggle_Following_Switch]=true
      $PokemonTemp.dependentEvents.refresh_sprite
      pbWait(1)
    
    end
  end
end



class DependentEvents
  attr_accessor :realEvents
#===============================================================================
# Erhöht den Freundschaftsgrad des aktuellen Pokémon um +1, für jedes Mal der
# Walk_time_Variable erreicht 5000 und setzt sich dann auf 0 zurück.
# ItemWalk, Wenn die Variable einen bestimmten Betrag erreicht,
# könnt ihr mit eurem Pokemon sprechen, um ein Item zu erhalten.
#===============================================================================
  def add_following_time
    if $game_switches[Toggle_Following_Switch] && $Trainer.party.length>=1
      $game_variables[Walking_Time_Variable]+=1 if $game_variables[Current_Following_Variable]!=0
      $game_variables[Walking_Item_Variable]+=1 if $game_variables[Current_Following_Variable]!=0
      if $game_variables[Walking_Time_Variable]==5000
        $Trainer.party[0].happiness+=1
        $game_variables[Walking_Time_Variable]=0
      end
      if $game_variables[Walking_Item_Variable]==1000
        if $game_variables[ItemWalk]==15
        else
          $game_variables[ItemWalk]+=1
        end
        $game_variables[Walking_Item_Variable]=0
      end
    end
  end
#===============================================================================
# * refresh_sprite = Aktualisiert die Sprites.
# * Aktualisiert die Sprite Sprite mit einer Animation.
#===============================================================================
  def refresh_sprite(animation=true)
    if $game_variables[Current_Following_Variable]!=0
      return unless $game_switches[Toggle_Following_Switch]
      return if $PokemonGlobal.bicycle
      if $Trainer.party[0].isShiny?
        shiny=true
      else
        shiny=false
      end
      if $Trainer.party[0].form>0
        form=$Trainer.party[0].form
      else
        form=nil
      end
      if defined?($Trainer.party[0].isShadow?)
        shadow = $Trainer.party[0].isShadow?
      else
        shadow = false
      end
      if $PokemonGlobal.surfing
        if $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg? && $Trainer.party[0].hasType?(:WATER)
          events=$PokemonGlobal.dependentEvents
          if animation
            for i in 0...events.length
              $scene.spriteset.addUserAnimation(Animation_Come_Out,@realEvents[i].x,@realEvents[i].y)
              pbWait(10)
            end
          end
          change_sprite($Trainer.party[0].species, shiny, false, form, $Trainer.party[0].gender, shadow)
        elsif ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
          isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
          ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
          !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species)) &&
          $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg?
          events=$PokemonGlobal.dependentEvents
          if animation
            for i in 0...events.length
              $scene.spriteset.addUserAnimation(Animation_Come_Out,@realEvents[i].x,@realEvents[i].y)
              pbWait(10)
            end
          end
          change_sprite($Trainer.party[0].species, shiny, false, form, $Trainer.party[0].gender, shadow)
        else
          remove_sprite(false)
        end
      elsif $PokemonGlobal.diving
        if $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg? && $Trainer.party[0].hasType?(:WATER) && WATERPOKEMONCANDIVE
          events=$PokemonGlobal.dependentEvents
          if animation
            for i in 0...events.length
              $scene.spriteset.addUserAnimation(Animation_Come_Out,@realEvents[i].x,@realEvents[i].y)
              pbWait(10)
            end
          end
          change_sprite($Trainer.party[0].species, shiny, false, form, $Trainer.party[0].gender, shadow)
        else
          remove_sprite(false)
        end
      else
        if $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg? && $scene.is_a?(Scene_Map)
          events=$PokemonGlobal.dependentEvents
          if animation
            for i in 0...events.length
              $scene.spriteset.addUserAnimation(Animation_Come_Out,@realEvents[i].x,@realEvents[i].y)
              pbWait(10)
            end
          end
          change_sprite($Trainer.party[0].species, shiny, false, form, $Trainer.party[0].gender, shadow)
        elsif $Trainer.party[0].hp<=0 || $Trainer.party[0].isEgg?
          remove_sprite(animation)
        end
      end
    else
      check_faint
    end
  end
#===============================================================================
# * change_sprite(id, shiny, animation) = ändere den Sprite (ID, Schillernd, Animation (bewegung))
# * Zum Beispiel, um den Sprite zu einem schillernden Lugia
# * mit Animation (Bewegung) zu verändern, tue folgendes:
#     change_sprite(249, true, true)
# * Falls nur der Sprite geändert werden soll:
#     change_sprite(249) = verändert den Sprite(249)
#===============================================================================
  def change_sprite(id, shiny=nil, animation=nil, form=nil, gender=nil, shadow=false)
    events=$PokemonGlobal.dependentEvents
    for i in 0...events.length
      if events[i] && events[i][8]=="Dependent"
        tgender = (gender==1)? "f" : ""
        tshiny  = (shiny)? "s" : ""
        tform   = (form && form>0) ? "_#{form}" : ""
        tshadow = (shadow)? "_shadow": ""
        speciesname = getConstantName(PBSpecies,id)
        bitmapFileName=sprintf("%s%s%s%s%s",speciesname,tgender,tshiny,tform,tshadow)
        if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
          events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
          @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
        else
          bitmapFileName=sprintf("%s%s",speciesname,tshiny)
          if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
            events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
            @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
          else
            bitmapFileName=sprintf("%s",speciesname)
            if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
              events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
              @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
            else
              bitmapFileName=sprintf("%03d%s%s%s%s",id,tgender,tshiny,tform,tshadow)
              if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
                events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
                @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
              else
                bitmapFileName=sprintf("%03d%s%s%s",id,tshiny,tform,tshadow)
                if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
                  events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
                  @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
                else
                  bitmapFileName=sprintf("%03d%s",id,tshiny)
                  if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
                    events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
                    @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
                  else
                    bitmapFileName=sprintf("%03d",id)
                    events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
                    @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
                  end
                end
              end
            end
          end
        end
        if animation
          $scene.spriteset.addUserAnimation(Animation_Come_Out,@realEvents[i].x,@realEvents[i].y)
        end
        $game_variables[Walking_Time_Variable]=0
      end
    end
  end
#===============================================================================
# * update_stepping = Aktualisiere die Schritte
# * fügt Schritt-Animation für die Begleiter hinzu.
#===============================================================================
  def update_stepping
    FollowingMoveRoute([PBMoveRoute::StepAnimeOn])
  end

  def stop_stepping
    FollowingMoveRoute([PBMoveRoute::StepAnimeOff])
  end
#===============================================================================
# * remove_sprite(animation) = entfernt Sprite-Animation.
# * Zum Beispiel, um den Sprite mit Animation zu entfernen:
#     remove_sprite(true)
# * Falls nur der Sprite entfernt werden soll:
#     remove_sprite
#===============================================================================
  def remove_sprite(animation=nil)
    events=$PokemonGlobal.dependentEvents
    for i in 0...events.length
      if events[i] && events[i][8]=="Dependent"
        events[i][6]=sprintf("nil")
        @realEvents[i].character_name=sprintf("nil")
        if animation==true
          $scene.spriteset.addUserAnimation(Animation_Come_In,@realEvents[i].x,@realEvents[i].y)
          pbWait(10)
        end
        $game_variables[Current_Following_Variable]=$Trainer.party[0]
        $game_variables[Walking_Time_Variable]=0
      end
    end
  end
#===============================================================================
# * check_surf(animation) = prüft die Surf-Animation.
# * Falls das aktuelle Pokémon ein Wasser-Pokémon ist, folgt es immer noch.
# * Falls das aktuelle Pokémon kein Wasser-Pokémon ist, entfernt es den Sprite.
# * Benötigt Water_Pokemon_Can_Surf = true um es zu aktivieren.
#===============================================================================
  def check_surf(animation=nil)
    if $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg?
      if ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
        isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
        ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
        !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species))
      
          #tut nichts
      elsif $Trainer.party[0].hasType?(:WATER) && WATERPOKEMONCANSURF
        #tut nichts
      else
        remove_sprite(animation)
      end
    
    end
  end
#===============================================================================
# * talk_to_pokemon
# * Es wird ausgeführt, sobald ihr mit Pokemon spricht.
#===============================================================================
  def talk_to_pokemon
    e=$Trainer.party[0]
    events=$PokemonGlobal.dependentEvents
    for i in 0...events.length
      if events[i] && events[i][8]=="Dependent"
        pos_x=@realEvents[i].x
        pos_y=@realEvents[i].y
        case $game_player.direction
        when 2 # Facing Down
          return if $game_player.x != pos_x
          return if $game_player.y != pos_y-1
        when 4 # Facing Left
          return if $game_player.x != pos_x+1
          return if $game_player.y != pos_y
        when 6 # Facing Right
          return if $game_player.x != pos_x-1
          return if $game_player.y != pos_y
        when 8 # Facing Up
          return if $game_player.x != pos_x
          return if $game_player.y != pos_y+1
        else
          return false
        end
      end
    end
    if e!=0
      if e.hp>0 && !$Trainer.party[0].isEgg?     
        if $PokemonGlobal.bicycle
          return
        elsif $PokemonGlobal.surfing
          flag = true
          if WATERPOKEMONCANSURF && $Trainer.party[0].hasType?(:WATER)
            flag = false
          elsif ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
              isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
              ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
              !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species))
            flag = false
          end
          return if flag
        elsif $PokemonGlobal.diving && (!WATERPOKEMONCANDIVE || !$Trainer.party[0].hasType?(:WATER))
          return
        end
#===============================================================================
# * Überprüft, ob das Pokemon keine surfbare Wasseroberfläche blockiert
# * Wenn das Wasser vom Sprite blockiert wird (obwohl es unsichtbar ist)
# * und der Spieler surfen können sollte, ruft surfen herbei.
#===============================================================================
        terrain=Kernel.pbFacingTerrainTag
        notCliff=$game_map.passable?($game_player.x,$game_player.y,$game_player.direction)
        if PBTerrain.isWater?(terrain) || !notCliff
          if !pbGetMetadata($game_map.map_id,MetadataBicycleAlways) && !$PokemonGlobal.surfing
            if $DEBUG
              Kernel.pbSurf
              return
            elsif (HIDDENMOVESCOUNTBADGES ? $Trainer.numbadges>=BADGEFORSURF : $Trainer.badges[BADGEFORSURF])
              Kernel.pbSurf
              return
            end
          end
        end
#===============================================================================
# * talk_to_pokemon wenn möglich beginnt hier
#===============================================================================
        if e!=6 && $game_switches[Toggle_Following_Switch]==true
          pbPlayCry(e.species)
          random1=rand(7) # Zufälliger Zitat falls keine besonderen Bedingungen gelten.
          mapname=$game_map.name # Holt sich die aktuelle Name der Map.
#===============================================================================
# * Pokemon Zitate bei Statusprobleme
#===============================================================================       
          if e.status==PBStatuses::POISON && e.hp>0 && !e.isEgg? # Pokemon vergiftet
            $scene.spriteset.addUserAnimation(Emo_Poison, pos_x, pos_y-2)
            pbWait(120)
            Kernel.pbMessage(_INTL("{1} zittert vor den Auswirkungen der Vergiftung.",e.name))
        
          elsif e.status==PBStatuses::BURN && e.hp>0 && !e.isEgg? # Pokemon verbrannt
            $scene.spriteset.addUserAnimation(Emo_Hate, pos_x, pos_y-2)
            pbWait(70)
            Kernel.pbMessage(_INTL("{1}s Verbrennung sieht schmerzhaft aus.",e.name))
          
          elsif e.status==PBStatuses::FROZEN && e.hp>0 && !e.isEgg? # Pokemon gefroren
            $scene.spriteset.addUserAnimation(Emo_Normal, pos_x, pos_y-2)
            pbWait(100)
            Kernel.pbMessage(_INTL("{1} scheint sehr kalt zu sein. Es ist fest gefroren!",e.name))
        
          elsif e.status==PBStatuses::SLEEP && e.hp>0 && !e.isEgg? # Pokemon schläft
            $scene.spriteset.addUserAnimation(Emo_Normal, pos_x, pos_y-2)
            pbWait(100)
            Kernel.pbMessage(_INTL("{1} scheint sehr müde zu sein.",e.name))
          
          elsif e.status==PBStatuses::PARALYSIS && e.hp>0 && !e.isEgg? # Pokemon paralysiert.
            $scene.spriteset.addUserAnimation(Emo_Normal, pos_x, pos_y-2)
            pbWait(100)
            Kernel.pbMessage(_INTL("{1} steht still und zuckt.",e.name))
#===============================================================================
# * Pokemon hält ein Item an einer Spezifischen Map
#===============================================================================         
          elsif $game_variables[ItemWalk]==15 and mapname=="Item Map" # Pokemon hat Item und ist auf der Map "Item Map"
            items=[:MASTERBALL,:MASTERBALL] # Dieses Array kann bearbeitet und erweitert werden. Schaut euch den unten stehenden Leitfaden an.
            random2=0
            loop do
              random2=rand(items.length)
              break if hasConst?(PBItems,items[random2])
            end
            Kernel.pbMessage(_INTL("{1} scheint etwas zu halten.",e.name))
            Kernel.pbPokemonFound(getConst(PBItems,items[random2]))
            $game_variables[ItemWalk]=0
#===============================================================================
# * Pokemon hält ein Item auf irgendeiner anderen Map.
#===============================================================================         
          elsif $game_variables[ItemWalk]==15 # Pokemon hat Item
            items=[:POTION,:SUPERPOTION,:FULLRESTORE,:REVIVE,:PPUP,
                 :PPMAX,:RARECANDY,:REPEL,:MAXREPEL,:ESCAPEROPE,
                 :HONEY,:TINYMUSHROOM,:PEARL,:NUGGET,:GREATBALL,
                 :ULTRABALL,:THUNDERSTONE,:MOONSTONE,:SUNSTONE,:DUSKSTONE,
                 :REDAPRICORN,:BLUAPRICORN,:YLWAPRICORN,:GRNAPRICORN,:PNKAPRICORN,
                 :BLKAPRICORN,:WHTAPRICORN
            ]
            random2=0
            loop do
              random2=rand(items.length)
              break if hasConst?(PBItems,items[random2])
            end

            Kernel.pbMessage(_INTL("{1} scheint etwas zu halten.",e.name))
            Kernel.pbPokemonFound(getConst(PBItems,items[random2]))
            $game_variables[ItemWalk]=0
#===============================================================================
# * Beispiele von Map-Spezifische Zitate
#===============================================================================
          elsif mapname=="Dusk Forest" && e.hasType?(:BUG) # Käfer Typ im dunklen Wald
            $scene.spriteset.addUserAnimation(Emo_sing, pos_x, pos_y-2)
            pbWait(50)
            random3=rand(3)
            if random3==0
              Kernel.pbMessage(_INTL("{1} scheint sehr interessiert an den Bäumen zu sein.",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("{1} scheint das Summen der Käfer-Pokémon zu genießen.",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} springt unruhig im Wald herum.",e.name,$Trainer.name))
            end
        
          elsif mapname=="Old Lab" # Im alten Labor
            $scene.spriteset.addUserAnimation(Emo_Normal, pos_x, pos_y-2)
            pbWait(100)
            random3=rand(3)
            if random3==0
              Kernel.pbMessage(_INTL("{1} berührt eine Art Schalter.",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("{1} hat einen Kabel im Mund.",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} scheint die Maschinerie anfassen zu wollen.",e.name,$Trainer.name))
            end
          
          elsif mapname=="Home" # Im Haus des Spielers
            $scene.spriteset.addUserAnimation(Emo_Happy, pos_x, pos_y-2)
            pbWait(70)
            random3=rand(3)
            if random3==0
              Kernel.pbMessage(_INTL("{1} schnüffelt im Raum herum.",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("{1} bemerkt, dass {2}s Mutter in der Nähe ist.",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} scheint sich Zuhause einleben zu wollen.",e.name,$Trainer.name))
            end
#===============================================================================
# * Pokemon Zitate beim Geburtstag
# * Unterstützung für Pokémon Birthsigns Script
#===============================================================================       
          elsif defined?(e.isBirthday?) && e.isBirthday?
            $scene.spriteset.addUserAnimation(Emo_Cake, pos_x, pos_y-2)
            pbWait(50)
            messages=rand(10)
            case messages
            when 0
              Kernel.pbMessage(_INTL("{1} scheint sich an alles zu erinnern, was es im letzten Jahr gelernt hat.",e.name,$Trainer.name))
            when 1
              Kernel.pbMessage(_INTL("{1} scheint froh zu sein, seinen Geburtstag mit {2} zu verbringen.",e.name,$Trainer.name))
            when 2
              Kernel.pbMessage(_INTL("{1} hat den besten Geburtstag aller Zeiten!",e.name,$Trainer.name))
            when 3
              Kernel.pbMessage(_INTL("{1} kann nicht glauben, das schon ein ganzes Jahr vergangen ist!",e.name,$Trainer.name))
            when 4
              Kernel.pbMessage(_INTL("{1} scheint nach Geschenken zu schnuppern ...",e.name,$Trainer.name))
            when 5
              Kernel.pbMessage(_INTL("{1} scheint etwas außer Atem zu sein...\nDu wirst alt!",e.name,$Trainer.name))
            when 6
              Kernel.pbMessage(_INTL("{1} sieht aus als würde es gleich anfangen zu feiern!",e.name,$Trainer.name))
            when 7
              Kernel.pbMessage(_INTL("Du wünschst {1} alles Gute zum Geburtstag.\nAlles Gute zum Geburtstag, {1}!",e.name,$Trainer.name))
            when 8
              Kernel.pbMessage(_INTL("{1} scheint sich auf ein weiteres Jahr mit {2} zu freuen.",e.name,$Trainer.name))
            when 9
              Kernel.pbMessage(_INTL("{1} möchte Kuchen essen!",e.name,$Trainer.name))
            end
#===============================================================================
# * Zufällige Zitate falls keine der oben genannten zutreffen
#===============================================================================         
          elsif random1==0 # Musiknote
            $scene.spriteset.addUserAnimation(Emo_sing, pos_x, pos_y-2)
            pbWait(50)
            random3=rand(5)
            if random3==0
              Kernel.pbMessage(_INTL("{1} scheint mit {2} spielen zu wollen.",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("{1} singt und summt.",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} schaut in den Himmel.",e.name,$Trainer.name))
            elsif random3==3
              Kernel.pbMessage(_INTL("{1} schwankte und tanzte herum, wie es ihm gefiel.",e.name,$Trainer.name))
            elsif random3==4
              Kernel.pbMessage(_INTL("{1} zieht das Gras heraus.",e.name,$Trainer.name))
            end
          
          elsif random1==1 # Hass/wütendes Gesicht
            $scene.spriteset.addUserAnimation(Emo_Hate, pos_x, pos_y-2)
            pbWait(70)
            random3=rand(5)
            if random3==0
              Kernel.pbMessage(_INTL("{1} stieß ein Brüllen aus!",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("{1} macht ein Gesicht, als wäre es wütend!",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} scheint aus irgendeinem Grund wütend zu sein.",e.name,$Trainer.name))
            elsif random3==3
              Kernel.pbMessage(_INTL("{1} beißt an deinen Füßen herum.",e.name,$Trainer.name))
            elsif random3==4
              Kernel.pbMessage(_INTL("{1} versucht einschüchternd zu sein.",e.name,$Trainer.name))
            end
          
          elsif random1==2 # ... Emoji
            $scene.spriteset.addUserAnimation(Emo_Normal, pos_x, pos_y-2)
            pbWait(70)
            random3=rand(5)
            if random3==0
              Kernel.pbMessage(_INTL("{1} schaut stetig nach unten.",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("{1} schnuppert am Boden.",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} konzentriert sich tief.",e.name,$Trainer.name))
            elsif random3==3
              Kernel.pbMessage(_INTL("{1} schaute in diese Richtung und schlief ein.",e.name,$Trainer.name))
            elsif random3==4
              Kernel.pbMessage(_INTL("{1} blickt {2} direkt in die Augen.",e.name,$Trainer.name))
            end
          
          elsif random1==3 # Glückliches Gesicht
            $scene.spriteset.addUserAnimation(Emo_Happy, pos_x, pos_y-2)
            pbWait(70)
            random3=rand(5)
            if random3==0
              Kernel.pbMessage(_INTL("{1} fing an, dich in den Bauch zu stoßen.",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("{1} sieht sehr glücklich aus.",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} kuschelte sich glücklich an dich.",e.name,$Trainer.name))
            elsif random3==3
              Kernel.pbMessage(_INTL("{1} ist so glücklich, dass es nicht stillstehen kann.",e.name,$Trainer.name))
            elsif random3==4
              Kernel.pbMessage(_INTL("{1} sieht aus, als möchte es der Führer sein.",e.name,$Trainer.name))
            end
          
          elsif random1==4 # Herz Emoji
            $scene.spriteset.addUserAnimation(Emo_love, pos_x, pos_y-2)
            pbWait(70)
            random3=rand(5)
            if random3==0
              Kernel.pbMessage(_INTL("{1} begann plötzlich sich zu nähern.",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("Boah! {1} umarmt plötzlich {2}.",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} reibt sich gegen dich.",e.name,$Trainer.name))
            elsif random3==3
              Kernel.pbMessage(_INTL("{1} hält sich nahe an {2}.",e.name,$Trainer.name))
            elsif random3==4
              Kernel.pbMessage(_INTL("{1} errötet.",e.name,$Trainer.name))
            end
          
          elsif random1==5 # Kein Emoji
            random3=rand(5)
            if random3==0
              Kernel.pbMessage(_INTL("{1} wirbelte im Kreis herum!",e.name,$Trainer.name))
            elsif random3==1
              Kernel.pbMessage(_INTL("{1} stieß einen Schlachtruf aus!",e.name,$Trainer.name))
            elsif random3==2
              Kernel.pbMessage(_INTL("{1} ist auf der Suche!",e.name,$Trainer.name))
            elsif random3==3
              Kernel.pbMessage(_INTL("{1} steht geduldig.",e.name,$Trainer.name))
            elsif random3==4
              Kernel.pbMessage(_INTL("{1} schaut sich unruhig um.",e.name,$Trainer.name))
            end
#===============================================================================
# * Diese zufällige Nachricht zeigt den Freundschaftsgrad des Pokémon.
#===============================================================================           
          elsif random1==6 # Prüft Freundschaftsgrad
            if e.happiness>0 && e.happiness<=50
              $scene.spriteset.addUserAnimation(Emo_Hate, pos_x, pos_y-2)
              pbWait(70)
              Kernel.pbMessage(_INTL("{1} hasst es mit {2} zu reisen.",e.name,$Trainer.name))
            elsif e.happiness>50 && e.happiness<=100
              $scene.spriteset.addUserAnimation(Emo_Normal, pos_x, pos_y-2)
              pbWait(100)
              Kernel.pbMessage(_INTL("{1} ist sich immer noch nicht sicher, ob es eine gute Sache ist, mit {2} zu reisen.",e.name,$Trainer.name))
            elsif e.happiness>100 && e.happiness<150
              $scene.spriteset.addUserAnimation(Emo_Happy, pos_x, pos_y-2)
              Kernel.pbMessage(_INTL("{1} ist glücklich mit {2} zu reisen.",e.name,$Trainer.name))
            elsif e.happiness>=150
              $scene.spriteset.addUserAnimation(Emo_love, pos_x, pos_y-2)
              pbWait(70)
              Kernel.pbMessage(_INTL("{1} liebt es mit {2} zu reisen.",e.name,$Trainer.name))
            end
          end
        else
        end
    end
  end
end
#===============================================================================
# * Pokémon erscheinen nach der Verwendung von Surfer wieder
#===============================================================================
def Come_back(shiny=nil, animation=nil)
  return if !$game_variables[Following_Activated_Switch]
  return if $Trainer.party.length==0
  $PokemonTemp.dependentEvents.pbMoveDependentEvents
  events=$PokemonGlobal.dependentEvents
  if $game_variables[Current_Following_Variable]==$Trainer.party[0]
    remove_sprite(false)
    if $scene.is_a?(Scene_Map)
      for i in 0...events.length
        $scene.spriteset.addUserAnimation(Animation_Come_Out,@realEvents[i].x,@realEvents[i].y)
      end
    end
  end
  if $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg?
    $game_variables[Current_Following_Variable]=$Trainer.party[0]
    refresh_sprite(animation)
  end
  for i in 0...events.length
    if events[i] && events[i][8]=="Dependent"
      id = $Trainer.party[0].species
      tgender = ($Trainer.party[0].gender==1)? "f" : ""
      tshiny  = ($Trainer.party[0].isShiny?)? "s" : ""
      tform   = ($Trainer.party[0].form && $Trainer.party[0].form>0) ? "_#{$Trainer.party[0].form}" : ""
      tshadow = ($Trainer.party[0].shadow)? "_shadow": ""
      speciesname = getConstantName(PBSpecies,id)
      bitmapFileName=sprintf("%s%s%s%s%s",speciesname,tgender,tshiny,tform,tshadow)
      if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
        events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
        @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
      else
        bitmapFileName=sprintf("%s%s",speciesname,tshiny)
        if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
          events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
          @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
        else
          bitmapFileName=sprintf("%s",speciesname)
          if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
            events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
            @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
          else
            bitmapFileName=sprintf("%03d%s%s%s%s",id,tgender,tshiny,tform,tshadow)
            if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
              events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
              @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
            else
              bitmapFileName=sprintf("%03d%s",id,tshiny)
              if pbResolveBitmap(FOLLOWER_FILE_PATH+FOLLOWER_FILE_DIR+bitmapFileName)
                events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
                @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
              else
                bitmapFileName=sprintf("%03d",id)
                events[i][6] = FOLLOWER_FILE_DIR+bitmapFileName
                @realEvents[i].character_name=FOLLOWER_FILE_DIR+bitmapFileName
              end
            end
          end
        end
      end
    end
  end
end
#===============================================================================
# * check_faint = Überprüft ob das Pokémon besiegt ist.
# * Falls das aktuelle Pokémon besiegt ist, entfernt dieser Skript den Sprite.
#===============================================================================
def check_faint
  return if !$game_switches[Following_Activated_Switch] || $Trainer.party.length<=0
  if $PokemonGlobal.bicycle
    return
  elsif $PokemonGlobal.diving && WATERPOKEMONCANDIVE && $Trainer.party[0].hasType?(:WATER)
    return
  elsif $PokemonGlobal.surfing && WATERPOKEMONCANSURF && $Trainer.party[0].hasType?(:WATER)
    return
  elsif $PokemonGlobal.surfing && ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
        isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
        ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
        !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species))
    return
  else
    if $Trainer.party[0].hp<=0
      $game_variables[Current_Following_Variable]=0
      remove_sprite
    elsif $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg? && $game_variables[Current_Following_Variable]==0
        $game_variables[Current_Following_Variable]=$Trainer.party[0]
        refresh_sprite
    end
  end
end
#===============================================================================
# * SetMoveRoute = Die Route in der sich das abhägige Pokémon bewegt wird eingestellt.
# * Wird im "Control following Pokemon" Skript verwendet, das weiter oben aufgelistet ist.
#===============================================================================
def SetMoveRoute(commands,waitComplete=true)
    events=$PokemonGlobal.dependentEvents
    for i in 0...events.length
      if events[i] && events[i][8]=="Dependent"
        pbMoveRoute(@realEvents[i],commands,waitComplete)
      end
    end
  end
end



#===============================================================================
# * Aktualisiere die Begleiter für das Surfen
# * nicht-begleitende abhängige Ereignisse sind nicht zulässig.
#===============================================================================
def Kernel.pbSurf
  if $game_player.pbHasDependentEvents? && !$game_switches[Following_Activated_Switch]
    return false
  end
  if $DEBUG ||
    (HIDDENMOVESCOUNTBADGES ? $Trainer.numbadges>=BADGEFORSURF : $Trainer.badges[BADGEFORSURF])
    movefinder=Kernel.pbCheckMove(:SURF)
    if $DEBUG || movefinder
      if Kernel.pbConfirmMessage(_INTL("Das Wasser ist tiefblau gefärbt... Möchtest du surfen?"))
        speciesname=!movefinder ? $Trainer.name : movefinder.name
        Kernel.pbMessage(_INTL("{1} benutzt Surfer!",speciesname))
        pbHiddenMoveAnimation(movefinder)
        surfbgm=pbGetMetadata(0,MetadataSurfBGM)
        $PokemonTemp.dependentEvents.check_surf(true)
        if surfbgm
          pbCueBGM(surfbgm,0.5)
        end
        pbStartSurfing()
        return true
      end
    end
  end
  return false
end

alias follow_pbStartSurfing pbStartSurfing
def pbStartSurfing()
  follow_pbStartSurfing
  $PokemonGlobal.surfing=true
end

alias follow_pbEndSurf pbEndSurf
def pbEndSurf(xOffset,yOffset)
  ret = follow_pbEndSurf(xOffset,yOffset)
  if $game_switches[Toggle_Following_Switch] && ret && $game_variables[Current_Following_Variable]!=0
    if WATERPOKEMONCANSURF && $Trainer.party[0].hasType?(:WATER)
      $PokemonTemp.dependentEvents.Come_back($Trainer.party[0].isShiny?,false)
    elsif ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
        isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
        ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
        !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species))
        $PokemonTemp.dependentEvents.Come_back($Trainer.party[0].isShiny?,false)
    else
      $PokemonTemp.dependentEvents.Come_back(true)
    end
  end
end

#===============================================================================
# * Skript automatisch zu Kernel.pbCanUseHiddenMove hinzufügen, HM-Fehler beheben
# * Behoben, so das nicht-begleitende-abhängige Ereignisse sich zu "return false"
# * zurückgestellt werden.
#===============================================================================
def Kernel.pbCanUseHiddenMove?(pkmn,move,showmsg=true)
  case move
    when PBMoves::FLY
      if !$DEBUG && !$Trainer.badges[BADGEFORFLY]
        Kernel.pbMessage(_INTL("Entschuldigung, ein neuer Orden ist erforderlich.")) if showmsg
        return false
      end
     if $game_player.pbHasDependentEvents? && !$game_switches[Following_Activated_Switch]
       Kernel.pbMessage(_INTL("Du kannst das nicht verwenden, falls du jemanden bei dir hast.")) if showmsg
       return false
     end
      if !pbGetMetadata($game_map.map_id,MetadataOutdoor)
        Kernel.pbMessage(_INTL("Das kann hier nicht verwendet werden.")) if showmsg
        return false
      end
      return true
    when PBMoves::CUT
      if !$DEBUG && !$Trainer.badges[BADGEFORCUT]
        Kernel.pbMessage(_INTL("Entschuldigung, ein neuer Orden ist erforderlich.")) if showmsg
        return false
      end
      facingEvent=$game_player.pbFacingEvent
      if !facingEvent || facingEvent.name!="Baum"
        Kernel.pbMessage(_INTL("Das kann hier nicht verwendet werden.")) if showmsg
        return false
      end
      return true
    when PBMoves::HEADBUTT
      facingEvent=$game_player.pbFacingEvent
      if !facingEvent || facingEvent.name!="Kopfnussbaum"
        Kernel.pbMessage(_INTL("Das kann hier nicht verwendet werden.")) if showmsg
        return false
      end
      return true
    when PBMoves::SURF
      terrain=Kernel.pbFacingTerrainTag
      if !$DEBUG && !$Trainer.badges[BADGEFORSURF]
        Kernel.pbMessage(_INTL("Entschuldigung, ein neuer Orden ist erforderlich.")) if showmsg
        return false
      end
      if $PokemonGlobal.surfing
        Kernel.pbMessage(_INTL("Du surfst bereits.")) if showmsg
        return false
      end
      if $game_player.pbHasDependentEvents? && !$game_switches[Following_Activated_Switch]
         Kernel.pbMessage(_INTL("Du kannst das nicht verwenden, wenn du jemanden bei dir hast.")) if showmsg
         return false
      end
      terrain=Kernel.pbFacingTerrainTag
      if pbGetMetadata($game_map.map_id,MetadataBicycleAlways)
        Kernel.pbMessage(_INTL("Lass uns das Radfahren genießen!")) if showmsg
        return false
      end
      if !PBTerrain.isWater?(terrain)
        Kernel.pbMessage(_INTL("Kein Surfen hier!")) if showmsg
        return false
      end
      return true
    when PBMoves::STRENGTH
      if !$DEBUG && !$Trainer.badges[BADGEFORSTRENGTH]
        Kernel.pbMessage(_INTL("Entschuldigung, ein neuer Orden ist erforderlich.")) if showmsg
        return false
      end
      facingEvent=$game_player.pbFacingEvent
      if !facingEvent || facingEvent.name!="Felsen"
        Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden.")) if showmsg
        return false
      end
      return true
    when PBMoves::ROCKSMASH
      terrain=Kernel.pbFacingTerrainTag
      if !$DEBUG && !$Trainer.badges[BADGEFORROCKSMASH]
        Kernel.pbMessage(_INTL("Entschuldigung, ein neuer Orden ist erforderlich.")) if showmsg
        return false
      end
      facingEvent=$game_player.pbFacingEvent
      if !facingEvent || facingEvent.name!="Felsen"
        Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden.")) if showmsg
        return false
      end
      return true
    when PBMoves::FLASH
      if !$DEBUG && !$Trainer.badges[BADGEFORFLASH]
        Kernel.pbMessage(_INTL("Entschuldigung, ein neuer Orden ist erforderlich.")) if showmsg
        return false
      end
      if !pbGetMetadata($game_map.map_id,MetadataDarkMap)
        Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden.")) if showmsg
        return false
      end
      if $PokemonGlobal.flashUsed
        Kernel.pbMessage(_INTL("Dies wird bereits verwendet.")) if showmsg
        return false
      end
      return true
    when PBMoves::WATERFALL
      if !$DEBUG && !$Trainer.badges[BADGEFORWATERFALL]
        Kernel.pbMessage(_INTL("Entschuldigung, ein neuer Orden ist erforderlich.")) if showmsg
        return false
      end
      terrain=Kernel.pbFacingTerrainTag
      if terrain!=PBTerrain::Waterfall
        Kernel.pbMessage(_INTL("Das kann hier nicht verwendet werden.")) if showmsg
        return false
      end
      return true
    when PBMoves::DIVE
      if !$DEBUG && !$Trainer.badges[BADGEFORDIVE]
        Kernel.pbMessage(_INTL("Entschuldigung, ein neuer Orden ist erforderlich.")) if showmsg
        return false
      end
      if $PokemonGlobal.diving
        return true
      end
      if $game_player.terrain_tag!=PBTerrain::DeepWater
        Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden.")) if showmsg
        return false
      end
      if !pbGetMetadata($game_map.map_id,MetadataDiveMap)
        Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden.")) if showmsg
        return false
      end
      return true
    when PBMoves::TELEPORT
      if !pbGetMetadata($game_map.map_id,MetadataOutdoor)
        Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden.")) if showmsg
        return false
      end
     if $game_player.pbHasDependentEvents? && !$game_switches[Following_Activated_Switch]
       Kernel.pbMessage(_INTL("Du kannst das nicht verwenden, wenn du jemanden bei dir hast.")) if showmsg
       return false
     end
      healing=$PokemonGlobal.healingSpot
      if !healing
        healing=pbGetMetadata(0,MetadataHome) # Home
      end
      if healing
        mapname=pbGetMapNameFromId(healing[0])
        if Kernel.pbConfirmMessage(_INTL("Willst du zum letzten Pokémon Center in {1} zurückkehren?",mapname))
          return true
        end
        return false
      else
        Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden.")) if showmsg
        return false
      end
    when PBMoves::DIG
      escape=($PokemonGlobal.escapePoint rescue nil)
      if !escape || escape.empty?
        Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden.")) if showmsg
        return false
      end
      if $game_player.pbHasDependentEvents? && !$game_switches[Following_Activated_Switch]
        Kernel.pbMessage(_INTL("Du kannst das nicht verwenden, wenn du jemanden bei dir hast.")) if showmsg
        return false
      end
      mapname=pbGetMapNameFromId(escape[0])
      if Kernel.pbConfirmMessage(_INTL("Willst du von hier fliehen und in {1} zurückkehren?",mapname))
        return true
      end
      return false
    when PBMoves::SWEETSCENT
      return true
    else
      return HiddenMoveHandlers.triggerCanUseMove(move,pkmn)
    end
  return false
end


#===============================================================================
# * Verändert den Fahrrad Skript um den Begleiter-Sprite richtig zu beeinflussen.
#===============================================================================
module Kernel
  class << self
    alias follow_pbDismountBike pbDismountBike
    alias follow_pbMountBike pbMountBike
    alias follow_pbCancelVehicles pbCancelVehicles
  end

  def self.pbDismountBike
    return if !$PokemonGlobal.bicycle
    ret=follow_pbDismountBike
    if $game_switches[Toggle_Following_Switch]
      $PokemonTemp.dependentEvents.Come_back(true)
    end
    $PokemonTemp.dependentEvents.refresh_sprite
    return ret
  end

  def self.pbMountBike
    ret=follow_pbMountBike
    if $game_switches[Toggle_Following_Switch]
      if pbGetMetadata($game_map.map_id,MetadataBicycleAlways)
        $PokemonTemp.dependentEvents.remove_sprite
      else
        $PokemonTemp.dependentEvents.remove_sprite(true)
      end
    end
    return ret
  end

  def self.pbCancelVehicles(destination=nil)
    if $game_switches[Toggle_Following_Switch] && ($PokemonGlobal.bicycle ||
                                                    $PokemonGlobal.diving) &&
                                                    destination.nil?
      $PokemonTemp.dependentEvents.Come_back(false)
    end
    return follow_pbCancelVehicles(destination)
  end

end

#===============================================================================
# * Ersetzt pbBikeCheck = pbFahrradPrüfer
# * Kann für abhängige Ereignisse immer noch abgelehnt werden, wenn der
#   Pokémon-Begleiter entfernt wurde.
#===============================================================================
def pbBikeCheck
  if $PokemonGlobal.surfing ||
     (!$PokemonGlobal.bicycle && pbGetTerrainTag==PBTerrain::TallGrass)
    Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden."))
    return false
  end
  if $game_player.pbHasDependentEvents? && !$game_switches[Following_Activated_Switch]
    Kernel.pbMessage(_INTL("Es kann nicht verwendet werden, wenn du jemanden bei dir hast."))
    return false
  end
  if $PokemonGlobal.bicycle
    if pbGetMetadata($game_map.map_id,MetadataBicycleAlways)
      Kernel.pbMessage(_INTL("Du kannst dein Fahrrad hier nicht absteigen."))
      return false
    end
    return true
  else
    val=pbGetMetadata($game_map.map_id,MetadataBicycle)
    val=pbGetMetadata($game_map.map_id,MetadataOutdoor) if val==nil
    if !val
      Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden."))
      return false
    end
    return true
  end
end



#===============================================================================
# * Aktualisiere die Begleiter nach dem Zugriff auf TrainerPC
#===============================================================================
alias follow_pbTrainerPC pbTrainerPC
def pbTrainerPC
  follow_pbTrainerPC
  $PokemonTemp.dependentEvents.refresh_sprite
end
#===============================================================================
# * Aktualisiere Begleiter nach dem Zugriff auf TrainerPC
#===============================================================================
class TrainerPC

  alias follow_access access
  def access
    follow_access
    $PokemonTemp.dependentEvents.refresh_sprite
  end
end
#===============================================================================
# * Skript automatisch zu pbPokeCenterPC hinzufügen.
#===============================================================================
alias follow_pbPokeCenterPC pbPokeCenterPC
def pbPokeCenterPC
  follow_pbPokeCenterPC
  $PokemonTemp.dependentEvents.refresh_sprite
end
#===============================================================================
#Korrektur für das Umschalten der Begleiter mit Animationen (Gras usw.)
#Behandelt die Begleiter, als ob sie sich beim Umschalten unter einer Brücke befinden.
#===============================================================================
alias follow_pbGetTerrainTag pbGetTerrainTag
def pbGetTerrainTag(event=nil,countBridge=false)
  ret=follow_pbGetTerrainTag(event,countBridge)
  if event && event!=$game_player
    for devent in $PokemonGlobal.dependentEvents
      if event.id==devent[1] && (!$game_switches[Toggle_Following_Switch] ||
                                  $Trainer.party.length==0 ||
                                  $Trainer.party[0].isEgg? || $Trainer.party[0].hp<=0)
        ret = PBTerrain::Bridge
        break
      end
    end
  end
  return ret
end




#===============================================================================
# * Startet Pokemon-Begleiter Skript
# * x ist die Event ID, die zum Begleiter wird
#===============================================================================
def pbPokemonFollow(x)
  Kernel.pbAddDependency2(x, "Dependent", Unused_Common_Event)
  $PokemonTemp.dependentEvents.refresh_sprite
  $PokemonTemp.dependentEvents.Come_back(nil,false)
  $game_switches[Following_Activated_Switch]=true
  $game_switches[Toggle_Following_Switch]=true
end


def pbTestPass(follower,x,y,direction=nil)
  ret = $MapFactory.isPassable?(follower.map.map_id,x,y,follower)
  if !ret && $PokemonGlobal.bridge>0&&
          PBTerrain.isBridge?($MapFactory.getTerrainTag(follower.map.map_id,x,y))
    ret = true
  end
  return ret
end


class DependentEvents

  def pbFollowEventAcrossMaps(leader,follower,instant=false,leaderIsTrueLeader=true)
    d=leader.direction
    areConnected=$MapFactory.areConnected?(leader.map.map_id,follower.map.map_id)
    # schnappt sich die Position des Begleiters für die Rückseite
    facingDirection=[0,0,8,0,6,0,4,0,2][d]
    if !leaderIsTrueLeader && areConnected
      relativePos=$MapFactory.getThisAndOtherEventRelativePos(leader,follower)
      if (relativePos[1]==0 && relativePos[0]==2) # 2 Felder rechts vom Anführer.
        facingDirection=6
      elsif (relativePos[1]==0 && relativePos[0]==-2) # 2 Felder links vom Anführer.
        facingDirection=4
      elsif relativePos[1]==-2 && relativePos[0]==0 # 2 Felder über den Anführer.
        facingDirection=8
      elsif relativePos[1]==2 && relativePos[0]==0 # 2 Felder unterhalb des Anführers.
        facingDirection=2
      end
    end
    facings=[facingDirection] #Die Ausrichtungen in verschiedenen Positionen.
    facings.push([0,0,4,0,8,0,2,0,6][d]) # Richtet sich nach rechts.
    facings.push([0,0,6,0,2,0,8,0,4][d]) # Richtet sich nach links.
    if !leaderIsTrueLeader
      facings.push([0,0,2,0,4,0,6,0,8][d]) # Richtet sich nach vorne.
    end
    mapTile=nil
    if areConnected
      bestRelativePos=-1
      oldthrough=follower.through
      follower.through=false
      for i in 0...facings.length
        facing=facings[i]
        tile=$MapFactory.getFacingTile(facing,leader)
        passable=tile && $MapFactory.isPassable?(tile[0],tile[1],tile[2],follower)
        if !passable && $PokemonGlobal.bridge>0
          passable = PBTerrain.isBridge?($MapFactory.getTerrainTag(tile[0],tile[1],tile[2]))
        elsif passable && !$PokemonGlobal.surfing && $PokemonGlobal.bridge==0     
          passable=!PBTerrain.isWater?($MapFactory.getTerrainTag(tile[0],tile[1],tile[2]))
        end
        if i==0 && !passable && tile &&
           $MapFactory.getTerrainTag(tile[0],tile[1],tile[2],true)==PBTerrain::Ledge &&
           $PokemonGlobal.bridge==0
          # Wenn das Plättchen nicht begehbar ist und das Plättchen eine Leiste ist,
          # holt es sich das Plättchen von weiter hinten.
          tile=$MapFactory.getFacingTileFromPos(tile[0],tile[1],tile[2],facing)
          passable=tile && $MapFactory.isPassable?(tile[0],tile[1],tile[2],follower)
          if passable && !$PokemonGlobal.surfing
            passable=!PBTerrain.isWater?($MapFactory.getTerrainTag(tile[0],tile[1],tile[2]))
          end
        end
        if passable
          relativePos=$MapFactory.getThisAndOtherPosRelativePos(
             follower,tile[0],tile[1],tile[2])
          distance=Math.sqrt(relativePos[0]*relativePos[0]+relativePos[1]*relativePos[1])
          if bestRelativePos==-1 || bestRelativePos>distance
            bestRelativePos=distance
            mapTile=tile
          end
          if i==0 && distance<=1 # Bevorzuge es, wenn sich die Kachel um bis zu
                                 # 1 Feld bewegen kann.
            break
          end
        end
      end
      follower.through=oldthrough
    else
      tile=$MapFactory.getFacingTile(facings[0],leader)
      passable=tile && $MapFactory.isPassable?(
         tile[0],tile[1],tile[2],follower)
      mapTile=passable ? mapTile : nil
    end
    if mapTile && follower.map.map_id==mapTile[0]
      # Begleiter ist in der selben Map
      newX=mapTile[1]
      newY=mapTile[2]
      deltaX=(d == 6 ? -1 : d == 4 ? 1 : 0)
      deltaY=(d == 2 ? -1 : d == 8 ? 1 : 0)
      posX = newX + deltaX
      posY = newY + deltaY
      follower.move_speed=leader.move_speed # Synchronisierte Bewegungsgeschwindigkeit.
      if (follower.x-newX==-1 && follower.y==newY) ||
         (follower.x-newX==1 && follower.y==newY) ||
         (follower.y-newY==-1 && follower.x==newX) ||
         (follower.y-newY==1 && follower.x==newX)
        if instant
          follower.moveto(newX,newY)
        else
          pbFancyMoveTo(follower,newX,newY)
        end
      elsif (follower.x-newX==-2 && follower.y==newY) ||
            (follower.x-newX==2 && follower.y==newY) ||
            (follower.y-newY==-2 && follower.x==newX) ||
            (follower.y-newY==2 && follower.x==newX)
        if instant
          follower.moveto(newX,newY)
        else
          pbFancyMoveTo(follower,newX,newY)
        end
      elsif follower.x!=posX || follower.y!=posY
        if instant
          follower.moveto(newX,newY)
        else
          pbFancyMoveTo(follower,posX,posY)
          pbFancyMoveTo(follower,newX,newY)
        end
      end
    else
      if !mapTile
        # Mache die aktuelle Position zur Position des Anführers.
        mapTile=[leader.map.map_id,leader.x,leader.y]
      end
      if follower.map.map_id==mapTile[0]
        # Begleiter ist in der selben Map wie der Anführer.
        follower.moveto(leader.x,leader.y)
        #pbTurnTowardEvent(follower,leader)
      else
        # Begleiter wird sich zu einer anderen Map bewegen.
        events=$PokemonGlobal.dependentEvents
        eventIndex=pbEnsureEvent(follower,mapTile[0])
        if eventIndex>=0
          newFollower=@realEvents[eventIndex]
          newEventData=events[eventIndex]
          newFollower.moveto(mapTile[1],mapTile[2])
          newEventData[3]=mapTile[1]
          newEventData[4]=mapTile[2]
          if mapTile[0]==leader.map.map_id
            #pbTurnTowardEvent(follower,leader)
          end
        end
      end
    end
  end

  #Es wurde behoben, dass der Begleiter beim Speichern nicht an derselben Stelle war
  def pbMapChangeMoveDependentEvents
    return
  end
end



class DependentEventSprites

  attr_accessor :sprites

  def refresh
    for sprite in @sprites
      sprite.dispose
    end
    @sprites.clear
    $PokemonTemp.dependentEvents.eachEvent {|event,data|
       if data[0]==@map.map_id # Prüfe ursprüngliche Map
         #@map.events[data[1]].erase
       end
       if data[2]==@map.map_id # Prüfe aktuelle Map
         spr = Sprite_Character.new(@viewport,event)
         @sprites.push(spr)
       end
    }
  end

  def update
    if $PokemonTemp.dependentEvents.lastUpdate!=@lastUpdate
      refresh
      @lastUpdate=$PokemonTemp.dependentEvents.lastUpdate
    end
    for sprite in @sprites
      sprite.update
    end
    for i in 0...@sprites.length
      pbDayNightTint(@sprites[i])
      if $game_switches[Toggle_Following_Switch] && APPLYSTATUSTONES && $Trainer.party[0] && $Trainer.party[0].hp>0
        case $Trainer.party[0].status
        when PBStatuses::BURN
          @sprites[i].tone.set(@sprites[i].tone.red+BURNTONE[0],@sprites[i].tone.green+BURNTONE[1],@sprites[i].tone.blue+BURNTONE[2],@sprites[i].tone.gray+BURNTONE[3])
        when PBStatuses::POISON
          @sprites[i].tone.set(@sprites[i].tone.red+POISONTONE[0],@sprites[i].tone.green+POISONTONE[1],@sprites[i].tone.blue+POISONTONE[2],@sprites[i].tone.gray+POISONTONE[3])
        when PBStatuses::PARALYSIS
          @sprites[i].tone.set(@sprites[i].tone.red+PARALYSISTONE[0],@sprites[i].tone.green+PARALYSISTONE[1],@sprites[i].tone.blue+PARALYSISTONE[2],@sprites[i].tone.gray+PARALYSISTONE[3])
        when PBStatuses::FROZEN
          @sprites[i].tone.set(@sprites[i].tone.red+FREEZETONE[0],@sprites[i].tone.green+FREEZETONE[1],@sprites[i].tone.blue+FREEZETONE[2],@sprites[i].tone.gray+FREEZETONE[3])
        when PBStatuses::SLEEP
          @sprites[i].tone.set(@sprites[i].tone.red+SLEEPTONE[0],@sprites[i].tone.green+SLEEPTONE[1],@sprites[i].tone.blue+SLEEPTONE[2],@sprites[i].tone.gray+SLEEPTONE[3])
        end
      end
    end
  end

end


#Aktualisiere das Begleiter-Pokémon, nachdem es gewechselt wurde.
class PokemonPartyScreen

  alias follow_pbSwitch pbSwitch
  def pbSwitch(oldid,newid)
    follow_pbSwitch(oldid,newid)
    $PokemonTemp.dependentEvents.refresh_sprite(false)
  end

  alias follow_pbRefreshSingle pbRefreshSingle
  def pbRefreshSingle(pkmnid)
    follow_pbRefreshSingle(pkmnid)
    $PokemonTemp.dependentEvents.refresh_sprite(false)
  end

end

#Aktualisiere nach der Weiterentwicklung.
class PokemonEvolutionScene

  alias follow_pbEndScreen pbEndScreen
  def pbEndScreen
    follow_pbEndScreen
    if @pokemon==$Trainer.party[0]
      $PokemonTemp.dependentEvents.refresh_sprite(false)
    end
  end

end

#Aktualisiere die begleitende Zeit des Begleiters.
class Game_Player < Game_Character

  alias follow_update update
  def update
    follow_update
    $PokemonTemp.dependentEvents.add_following_time
  end

  alias follow_moveto moveto
  def moveto(x,y)
    ret = follow_moveto(x,y)
    events=$PokemonGlobal.dependentEvents
    leader=$game_player
    for i in 0...events.length
      event=$PokemonTemp.dependentEvents.realEvents[i]
      $PokemonTemp.dependentEvents.pbFollowEventAcrossMaps(leader,event,true,i==0)
    end
    return ret
  end

end

#Aktualisiere den Begleiter nach jedem Kampf.
class PokeBattle_Scene

  alias follow_pbEndBattle pbEndBattle
  def pbEndBattle(result)
    follow_pbEndBattle(result)
    $PokemonTemp.dependentEvents.check_faint
  end

end

#Skript, wenn ein Pokémon ein Item im Feld findet.
class PokemonField

  def Kernel.pbPokemonFound(item,quantity=1,plural=nil)
    itemname=PBItems.getName(item)
    pocket=pbGetPocket(item)
    e=$Trainer.party[0].name
    if $PokemonBag.pbStoreItem(item,quantity)
      pbWait(5)
      if $ItemData[item][ITEMUSE]==3 || $ItemData[item][ITEMUSE]==4
        Kernel.pbMessage(_INTL("\\se[]{1} hat {2} gefunden!\\se[itemlevel]\\nEs enthält {3}.\\wtnp[30]",e,itemname,PBMoves.getName($ItemData[item][ITEMMACHINE])))
        Kernel.pbMessage(_INTL("{1} legt das {2}\r\nin dem {3} Beutel.",$Trainer.name,itemname,PokemonBag.pocketNames()[pocket]))
      elsif PBItems.const_defined?(:LEFTOVERS) && isConst?(item,PBItems,:LEFTOVERS)
        Kernel.pbMessage(_INTL("\\se[]{1} hat einige {2} gefunden!\\se[itemlevel]\\wtnp[30]",e,itemname))
        Kernel.pbMessage(_INTL("{1} legt die {2}\r\nin dem {3} Beutel.",$Trainer.name,itemname,PokemonBag.pocketNames()[pocket]))
      else
        if quantity>1
          if plural
            Kernel.pbMessage(_INTL("\\se[]{1} hat {2} {3} gefunden!\\se[itemlevel]\\wtnp[30]",e,quantity,plural))
            Kernel.pbMessage(_INTL("{1} legt die {2}\r\nin dem {3} Beutel.",$Trainer.name,plural,PokemonBag.pocketNames()[pocket]))
          else
            Kernel.pbMessage(_INTL("\\se[]{1} hat {2}e {3} gefunden!\\se[itemlevel]\\wtnp[30]",e,quantity,itemname))
            Kernel.pbMessage(_INTL("{1} legt die {2}e\r\nin dem {3} Beutel.",$Trainer.name,itemname,PokemonBag.pocketNames()[pocket]))
          end
        else
          Kernel.pbMessage(_INTL("\\se[]{1} hat einen {2} gefunden!\\se[itemlevel]\\wtnp[30]",e,itemname))
          Kernel.pbMessage(_INTL("{1} legt das {2}\r\nin dem {3} Beutel.",$Trainer.name,itemname,PokemonBag.pocketNames()[pocket]))
        end
      end
      return true
    else   # Kann das Item nicht hinzufügen
      if $ItemData[item][ITEMUSE]==3 || $ItemData[item][ITEMUSE]==4
        Kernel.pbMessage(_INTL("{1} hat {2} gefunden!\\wtnp[20]",e,itemname))
      elsif PBItems.const_defined?(:LEFTOVERS) && isConst?(item,PBItems,:LEFTOVERS)
        Kernel.pbMessage(_INTL("{1} hat einige {2} gefunden!\\wtnp[20]",$Trainer.name,itemname))
      else
        if quantity>1
          if plural
            Kernel.pbMessage(_INTL("{1} hat {2} {3} gefunden!\\wtnp[20]",e,quantity,plural))
          else
            Kernel.pbMessage(_INTL("{1} hat {2} {3}e gefunden!\\wtnp[20]",$Trainer.name,quantity,itemname))
          end
        else
          Kernel.pbMessage(_INTL("{1} hat einen {2} gefunden!\\wtnp[20]",e,itemname))
        end
      end
      Kernel.pbMessage(_INTL("Schade... Der Beutel ist voll..."))
      return false
    end
  end
end

$IssueStop = false

#Begleiter ein- / ausschalten, durch Pokemon im Feld blättern.
class Scene_Map

  alias follow_update update
  def update
    follow_update
    return if $FollowerMoveRoute
    for i in 0...$PokemonGlobal.dependentEvents.length
      event=$PokemonTemp.dependentEvents.realEvents[i]
      return if event.move_route_forcing
    end 
    if $game_switches[Following_Activated_Switch] && $Trainer.party.length>0
      if Input.trigger?(Input::C) # versuche mit Pokémon zu sprechen.
        $PokemonTemp.dependentEvents.talk_to_pokemon
      end
      #Pokémon bewegt sich immer, wenn der Schalter eingeschaltet ist, einen fliegenden Typ besitzt oder sich in einem Einstellungsfeld befindet.
      moving = Input.press?(Input::DOWN) || Input.press?(Input::UP) ||
                Input.press?(Input::RIGHT) || Input.press?(Input::LEFT)
      if (ALWAYS_ANIMATE || $game_player.moving? || moving ||
        $Trainer.party[0].hasType?(:FLYING) ||
        isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
        ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
        !$PokemonGlobal.surfing
          if !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species))
            $PokemonTemp.dependentEvents.update_stepping
          end
      elsif $PokemonGlobal.surfing && $Trainer.party[0].hasType?(:WATER)
        if !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species))
          $PokemonTemp.dependentEvents.update_stepping
        end
      elsif $PokemonGlobal.surfing &&
                ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
                isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
                ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
                !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species)) &&
                $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg?
          $PokemonTemp.dependentEvents.update_stepping
      elsif $PokemonGlobal.diving && $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg? && $Trainer.party[0].hasType?(:WATER)  && WATERPOKEMONCANDIVE
            $PokemonTemp.dependentEvents.update_stepping
      else
            $PokemonTemp.dependentEvents.stop_stepping
      end
      if Input.trigger?(Input::CTRL) && ALLOWTOGGLEFOLLOW && !$PokemonGlobal.bicycle
        if $PokemonGlobal.surfing
          if $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg? && $Trainer.party[0].hasType?(:WATER)
            if WATERPOKEMONCANSURF
              pbToggleFollowingPokemon
            end
          elsif ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
            isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
            ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
            !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species))
          
            pbToggleFollowingPokemon
          end
        elsif $PokemonGlobal.diving
          if $Trainer.party[0].hp>0 && !$Trainer.party[0].isEgg? && $Trainer.party[0].hasType?(:WATER)
            if WATERPOKEMONCANDIVE
              pbToggleFollowingPokemon
            end
          end
        else
          pbToggleFollowingPokemon
        end
      end
      if ALLOWFIELDSWITCHING && !$PokemonGlobal.bicycle
        tlength=$Trainer.party.length-1
        tparty=$Trainer.party
        return if tlength<=0
        if Input.trigger?(Input::X) && $Trainer.party.size > 1
          tparty.push(tparty.delete_at(0))
          if $game_switches[Toggle_Following_Switch]
            if $PokemonGlobal.surfing
              if tparty[0].hp>0 && !tparty[0].isEgg? && tparty[0].hasType?(:WATER)
                $PokemonTemp.dependentEvents.refresh_sprite
              elsif ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
                isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
                ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
                !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species)) &&
                tparty[0].hp>0 && !tparty[0].isEgg?
              
                $PokemonTemp.dependentEvents.refresh_sprite
              else
                $PokemonTemp.dependentEvents.refresh_sprite(false)
              end
              if tparty[tlength].hp>0 && !tparty[tlength].isEgg? && tparty[tlength].hasType?(:WATER)
                $PokemonTemp.dependentEvents.check_surf(true)
              elsif ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[tlength].hasType?(:FLYING) ||
                isConst?($Trainer.party[tlength].ability,PBAbilities,:LEVITATE) ||
                ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[tlength].species)) &&
                !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[tlength].species)) &&
                tparty[tlength].hp>0 && !tparty[tlength].isEgg?
              
                $PokemonTemp.dependentEvents.check_surf(true)
              else
                $PokemonTemp.dependentEvents.check_surf(false)
              end
            elsif $PokemonGlobal.diving
              if tparty[0].hp>0 && !tparty[0].isEgg? && tparty[0].hasType?(:WATER) && WATERPOKEMONCANDIVE
                $PokemonTemp.dependentEvents.refresh_sprite
              end
              if tparty[tlength].hp>0 && !tparty[tlength].isEgg? && tparty[tlength].hasType?(:WATER) && WATERPOKEMONCANDIVE
                $PokemonTemp.dependentEvents.check_surf(true)
              end
            else
              $PokemonTemp.dependentEvents.refresh_sprite
            end
          end
        end
        if Input.trigger?(Input::Z) && $Trainer.party.size > 1
          $Trainer.party.insert(0,$Trainer.party.pop)
          if $game_switches[Toggle_Following_Switch]
            if $PokemonGlobal.surfing
              if tparty[0].hp>0 && !tparty[0].isEgg? && tparty[0].hasType?(:WATER)
                $PokemonTemp.dependentEvents.refresh_sprite
              elsif ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[0].hasType?(:FLYING) ||
                isConst?($Trainer.party[0].ability,PBAbilities,:LEVITATE) ||
                ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[0].species)) &&
                !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[0].species)) &&
                tparty[0].hp>0 && !tparty[0].isEgg?
              
                $PokemonTemp.dependentEvents.refresh_sprite
              
              else
                $PokemonTemp.dependentEvents.refresh_sprite(false)
              end
              if tparty[1].hp>0 && !tparty[1].isEgg? && tparty[1].hasType?(:WATER)
                $PokemonTemp.dependentEvents.check_surf(true)
              elsif ALWAYS_ANIMATED_CAN_SURF && ($Trainer.party[1].hasType?(:FLYING) ||
                isConst?($Trainer.party[1].ability,PBAbilities,:LEVITATE) ||
                ALWAYS_ANIMATED_FOLLOWERS.include?($Trainer.party[1].species)) &&
                !(ALWAYS_ANIMATED_EXCEPTION.include?($Trainer.party[1].species)) &&
                tparty[1].hp>0 && !tparty[1].isEgg?
              
                $PokemonTemp.dependentEvents.check_surf(true)
              else
                $PokemonTemp.dependentEvents.check_surf(false)
              end
            elsif $PokemonGlobal.diving
               if tparty[0].hp>0 && !tparty[0].isEgg? && tparty[0].hasType?(:WATER)  && WATERPOKEMONCANDIVE
                $PokemonTemp.dependentEvents.refresh_sprite
              end
              if tparty[1].hp>0 && !tparty[1].isEgg? && tparty[1].hasType?(:WATER) && WATERPOKEMONCANDIVE
                $PokemonTemp.dependentEvents.check_surf(true)
              end
            else
              $PokemonTemp.dependentEvents.refresh_sprite
            end
          end
        end
      end
    end
  end

  alias follow_transfer transfer_player
  def transfer_player(cancelVehicles=true)
    follow_transfer(cancelVehicles)
    events=$PokemonGlobal.dependentEvents
    $PokemonTemp.dependentEvents.updateDependentEvents
    leader=$game_player
    for i in 0...events.length
      event=$PokemonTemp.dependentEvents.realEvents[i]
      $PokemonTemp.dependentEvents.pbFollowEventAcrossMaps(leader,event,false,i==0)
    end
    $PokemonTemp.dependentEvents.refresh_sprite
  end

end

#Die Landung der Begleiter beim Übertragen wurde korrigiert.
$NeedFollowerUpdate = false
#Versuche nicht, die Begleiterereignisse freizuschalten.
class Interpreter

  def command_end
    #Liste der Ereignisbefehle löschen
    @list = nil
    #Falls das Haupt-Map-Ereignis und die Ereignis-ID gültig sind
    if @main && @event_id > 0 && !($game_map.events[@event_id] && $game_map.events[@event_id].name=="Dependent")
      # Ereignis freischalten
      $game_map.events[@event_id].unlock if $game_map.events[@event_id]
    end
    if $NeedFollowerUpdate
      events=$PokemonGlobal.dependentEvents
      $PokemonTemp.dependentEvents.updateDependentEvents
      leader=$game_player
      for i in 0...events.length
        event=$PokemonTemp.dependentEvents.realEvents[i]
        $PokemonTemp.dependentEvents.pbFollowEventAcrossMaps(leader,event,false,i==0)
      end
      $NeedFollowerUpdate=false
    end
  end

  alias follow_201 command_201
  def command_201
    ret=follow_201
    $NeedFollowerUpdate=true
    return ret
  end

end


# Behebe andere Ereignisse, die durch abhängige Ereignisse durch laufen.
class Game_Map

  alias follow_passable? passable?
  def passable?(x, y, d, self_event=nil)
    ret=follow_passable?(x,y,d,self_event)
    if !ret && !$game_temp.player_transferring && $game_player.pbHasDependentEvents? && $game_switches[Toggle_Following_Switch] &&
       self_event != $game_player
         dependent=pbGetDependency("Dependent")
         if dependent != nil && self_event != dependent
           if dependent.x==x && dependent.y==y
             return false
           end
         end
    end
    return ret
   end
  
end


#"In Ohnmacht fallen" wurde behoben.
#Überschreibe den Anfang, um den "In Ohnmacht fallen"-Fehler zu beheben
def Kernel.pbStartOver(gameover=false)
  if pbInBugContest?
    Kernel.pbBugContestStartOver
    return
  end
  pbHealAll()
  if $PokemonGlobal.pokecenterMapId && $PokemonGlobal.pokecenterMapId>=0
    if gameover
      Kernel.pbMessage(_INTL("\\w[]\\wm\\c[8]\\l[3]Nach der unglücklichen Niederlage eilte {1} zu einem Pokémon-Center.",$Trainer.name))
    else
      Kernel.pbMessage(_INTL("\\w[]\\wm\\c[8]\\l[3]{1} eilte zu einem Pokémon-Center und beschützte das erschöpfte und ohnmächtige Pokémon vor weiterem Schaden.",$Trainer.name))
    end
    Kernel.pbCancelVehicles
    pbRemoveDependencies()
    $game_switches[STARTING_OVER_SWITCH]=true
    $game_temp.player_new_map_id=$PokemonGlobal.pokecenterMapId
    $game_temp.player_new_x=$PokemonGlobal.pokecenterX
    $game_temp.player_new_y=$PokemonGlobal.pokecenterY
    $game_temp.player_new_direction=$PokemonGlobal.pokecenterDirection
    $scene.transfer_player if $scene.is_a?(Scene_Map)
    $game_map.refresh
  else
    homedata=pbGetMetadata(0,MetadataHome)
    if (homedata && !pbRxdataExists?(sprintf("Data/Map%03d",homedata[0])) )
      if $DEBUG
        Kernel.pbMessage(_ISPRINTF("Kann die Map {1:03d}' im Data Ordner nicht finden. Das Spiel wird an der Position des Spielers fortgesetzt.",homedata[0]))
      end
      pbHealAll()
      return
    end
    if gameover
      Kernel.pbMessage(_INTL("\\w[]\\wm\\c[8]\\l[3]Nach der unglücklichen Niederlage eilte {1} nach Hause.",$Trainer.name))
    else
      Kernel.pbMessage(_INTL("\\w[]\\wm\\c[8]\\l[3]{1} eilte nach Hause, um das erschöpfte und besiegte Pokémon vor weiterem Schaden zu schützen.",$Trainer.name))
    end
    if homedata
      Kernel.pbCancelVehicles
      pbRemoveDependencies() if !$game_switches[Following_Activated_Switch]
      $game_switches[STARTING_OVER_SWITCH]=true
      $game_temp.player_new_map_id=homedata[0]
      $game_temp.player_new_x=homedata[1]
      $game_temp.player_new_y=homedata[2]
      $game_temp.player_new_direction=homedata[3]
      $scene.transfer_player if $scene.is_a?(Scene_Map)
      $game_map.refresh
    else
      pbHealAll()
    end
  end
  pbEraseEscapePoint
end

#Fluchtseil behoben.
ItemHandlers::UseInField.add(:ESCAPEROPE,proc{|item|
   escape=($PokemonGlobal.escapePoint rescue nil)
   if !escape || escape==[]
     Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden."))
     next
   end
   if $game_player.pbHasDependentEvents? && !$game_switches[Following_Activated_Switch]
     Kernel.pbMessage(_INTL("Es kann nicht verwendet werden, wenn du jemanden bei dir hast."))
     next
   end
   Kernel.pbMessage(_INTL("{1} verwendet den {2}.",$Trainer.name,PBItems.getName(item)))
   pbFadeOutIn(99999){
      Kernel.pbCancelVehicles
      $game_temp.player_new_map_id=escape[0]
      $game_temp.player_new_x=escape[1]
      $game_temp.player_new_y=escape[2]
      $game_temp.player_new_direction=escape[3]
      $scene.transfer_player
      $game_map.autoplay
      $game_map.refresh
   }
   pbEraseEscapePoint
})


ItemHandlers::UseFromBag.add(:ESCAPEROPE,proc{|item|
   if $game_player.pbHasDependentEvents? && !$game_switches[Following_Activated_Switch]
     Kernel.pbMessage(_INTL("Es kann nicht verwendet werden, wenn du jemanden bei dir hast."))
     next 0
   end
   if ($PokemonGlobal.escapePoint rescue false) && $PokemonGlobal.escapePoint.length>0
     next 4 # Beendungsbildschirm und Verbrauchungsbildschirm
   else
     Kernel.pbMessage(_INTL("Du kannst das hier nicht verwenden."))
     next 0
   end
})


#Aktualisiere die Sprites während das Item gegeben wird.
class PokemonPartyScreen

  alias follow_pbPokemonGiveScreen pbPokemonGiveScreen
  def pbPokemonGiveScreen(item)
    ret=follow_pbPokemonGiveScreen(item)
    $PokemonTemp.dependentEvents.refresh_sprite(false) if ret
    return ret
  end

end

#Aktualisiere die Sprites während das Item verwendet wird.
module ItemHandlers

  class << self
    alias follow_triggerUseOnPokemon triggerUseOnPokemon
  end

  def self.triggerUseOnPokemon(item,pokemon,scene)
    ret = follow_triggerUseOnPokemon(item,pokemon,scene)
    $PokemonTemp.dependentEvents.refresh_sprite(false) if ret
    return ret
  end

end


Ruby:
# Whether or not you want to use these utility methods. Toggling this off will
# likely break your scripts. So don't do it unless you know what you're doing :)
USING_MARIN_UTILITY = true

# Whether or not you want the custom/better errors message.
SPECIAL_ERRORS = true



# These two settings only apply if SPECIAL_ERRORS is TRUE

DOUBLE_BACKTRACE = false # The interpreter already contains a small
                         # backtrace for errors in events and such by default.
                         # Settings this to false will not show the custom
                         # backtrace.

BACKTRACE_MAX_SIZE = 12 # The backtrace can go all the way from the very first
                        # call to the very last call. This is the limit as far
                        # as it can go back, because you could have a massive
                        # backtrace otherwise.


def pbMarinUtility
  return USING_MARIN_UTILITY
end

if USING_MARIN_UTILITY

class Object
  def get_variables
    return self.instance_variables.map { |v| [v,self.method(v.to_s.gsub(/@/, "").to_sym).call] }
  end

  def set_variables(vars)
    vars.each do |v|
      self.method((v[0].to_s.gsub(/@/, "") + "=").to_sym).call(v[1])
    end
  end
end

# E.g. PokeBattle_Pokemon -> to_sym -> :PokeBattle_Pokemon
class Class
  def to_sym
    return self.to_s.to_sym
  end
end

class NilClass
  def empty?
    return true
  end
end

class Numeric
  # Formats the number nicely (e.g. 1234567890 -> format() -> 1,234,567,890)
  def format(separator = ',')
    a = self.to_s.split('').reverse.breakup(3)
    return a.map { |e| e.join('') }.join(separator).reverse
  end

  # Makes sure the returned string is at least n characters long
  # (e.g. 4   -> to_digits -> "004")
  # (e.g. 19  -> to_digits -> "019")
  # (e.g. 123 -> to_digits -> "123")
  def to_digits(n = 3)
    str = self.to_s
    return str if str.size >= n
    ret = ""
    (n - str.size).times { ret += "0" }
    return ret + str
  end

  # n root of self. Defaults to 2 => square root.
  def root(n = 2)
    return (self ** (1.0 / n))
  end

  # Factorial
  # 4 -> fact -> (4 * 3 * 2 * 1) -> 24
  def fact
    raise ArgumentError, "Cannot execute factorial on negative numerics" if self < 0
    tot = 1
    for i in 2..self
      tot *= i
    end
    return tot
  end

  # Combinations
  def ncr(k)
    return (self.fact / (k.fact * (self - k).fact))
  end

  # k permutations of n (self)
  def npr(k)
    return (self.fact / (self - k).fact)
  end

  # Converts number to binary number (returns as string)
  def to_b
    return self.to_s(2)
  end

  def empty?
    return false
  end

  def numeric?
    return true
  end
end

# Included in TrueClass and FalseClass to be able to call _.is_a?(Boolean)_
# true.is_a?(Boolean)
module Boolean end

class TrueClass
  include Boolean

  def to_i
    return 1
  end
end

# false.is_a?(Boolean)
class FalseClass
  include Boolean

  def to_i
    return 0
  end
end

# Calculates the total amount of elements in an Enumerable. Example:
# ["one","two","three"].fullsize #=> 11
module Enumerable
  def fullsize
    n = 0
    for e in self
      if e.is_a?(String)
        n += e.size
      elsif e.respond_to?(:fullsize)
        n += e.fullsize
      elsif e.respond_to?(:size) && !e.is_a?(Numeric)
        n += e.size
      else
        n += 1
      end
    end
    return n
  end
end

class Array
  # Returns a random element of the array
  def random
    return self[rand(self.size)]
  end

  # Shuffles the order of the array
  def shuffle
    indexes = []
    new = []
    while new.size != self.size
      i = rand(self.size)
      if !indexes.include?(i)
        indexes << i
        new << self[i]
      end
    end
    return new
  end

  # Shuffles the order of the array and replaces itself
  def shuffle!
    self.replace(shuffle)
  end

  # Breaks the array up every n elements
  def breakup(n)
    ret = []
    for i in 0...self.size
      ret[(i / n).floor] ||= []
      ret[(i / n).floor] << self[i]
    end
    return ret
  end

  # Breaks the array up every n elements and replaces itself
  def breakup!(n)
    self.replace(breakup(n))
  end

  # Swaps two elements' indexes
  def swap(index1, index2)
    new = self.clone
    tmp = new[index2].clone
    new[index2] = new[index1]
    new[index1] = tmp
    return new
  end

  # Swaps two elements' indexes and replaces itself
  def swap!(index1, index2)
    self.replace(swap(index1, index2))
  end

  # Returns whether or not the first element is equal to the passed argument
  def starts_with?(e)
    return self.first == e
  end

  # Returns whether or not the last element is equal to the passed argument
  def ends_with?(e)
   return self.last == e
  end

  # Does the same as <<, but concatenates if argument passed is an array
  def +(var)
    if var.is_a?(Array)
      self.concat(var)
    else
      self << var
    end
    return self
  end

  # Deletes every instance of <var> in the array
  def -(var)
    if var.is_a?(Array)
      var.each { |e| self.delete(e) if self.include?(e) }
    else
      self.delete(var) if self.include?(var)
    end
    return self
  end

  # Converts itself to a hash where possible
  def to_hash(delete_nil_entries = false)
    ret = {}
    for i in 0...self.size
      next if self[i].nil? && delete_nil_entries
      ret[i] = self[i]
    end
    return ret
  end

  # If you have 8 elements, if true, grabs the 5th element, the 4rd if false.
  # If you have 7 elements, grabs the 4th.
  def mid(round_up = true)
    i = (self.size - 1) / 2.0
    i = i.ceil if round_up
    return self[i].floor
  end

  # Returns the average of all elements in the array. Will throw errors on non-numerics.
  # Skips <nil> entries.
  def average
    total = 0
    self.each { |n| total += n unless n.nil? }
    return total / self.compact.size.to_f
  end

  # Adds some aliases for <include?>: <has?>, <includes?>, <contains?>
  alias has? include?
  alias includes? include?
  alias contains? include?

  # Evaluates the block you pass it for every number between 0 and "slots".
  # Example usage:
  # Array.make_table { |i| i ** 2 }
  #   =>  [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  # Array.make_table(10..16) { |i| i.to_s(2) }
  #   => ["1010", "1011", "1100", "1101", "1110", "1111", "10000"]
  # (you can also pass it an array of values to iterate over)
  def self.make_table(range = 1..10, &proc)
    return range.map { |n| next proc.call(n) }
  end

  # If true:
  # [0, 1, 3, 4, 5]  --  etc
  # If false:
  # [0,1,2,3,4,5]  --  etc
  Json_Extra_Space_After_Entry = false

  # Converts _self_ to a JSON string with an indent of Json_Indent_Width per layer.
  def to_json(indent = Hash::Json_Indent_Width, inline = false)
    return "[]" unless self.size > 0
    full = "["
    for i in 0...self.size
      nl = false
      if self[i].is_a?(Hash) || self[i].is_a?(Array)
        val = self[i].to_json(indent + Hash::Json_Indent_Width, i == 0)
        nl = !(inline && i == 0)
      else
        val = self[i]
        val = "\"#{val}\"" if val.is_a?(String)
        nl = (self.fullsize > 24 || self.map { |e| e.class.to_sym }.include?(:Hash))
      end
      full += "\n" + " " * indent if nl
      full += val.to_s + ","
      full += " " if Json_Extra_Space_After_Entry
    end
    i = 2 + Json_Extra_Space_After_Entry.to_i
    full = full[0..(-i)]
    full += "\n#{" " * (indent - Hash::Json_Indent_Width)}" if self.fullsize > 24 ||
                                 self.map { |e| e.class.to_sym }.include?(:Hash)
    full += "]"
    return full
  end
end

class Hash
  # Converts itself to an array where possible
  def to_array(delete_nil_entries = false)
    ret = []
    keys = self.keys.sort
    for key in keys
      next if self[key].nil? && delete_nil_entries
      ret[key] = self[key]
    end
    return ret
  end

  def compact
    new = {}
    for key in self.keys
      new[key] = self[key] unless self[key].nil?
    end
    return new
  end

  def compact!
    self.replace(compact)
  end

  # Amount of spaces per "layer" in the JSON.
  Json_Indent_Width = 4

  # Converts _self_ to a JSON string with an indent of Json_Indent_Width per layer.
  def to_json(indent = Json_Indent_Width, _ = nil)
    return "{}" if self.size == 0
    full = "{"
    keys = self.keys.sort do |a,b|
      if $JSON_Sort_Order
        if $JSON_Sort_Order.include?(a)
          if $JSON_Sort_Order.include?(b)
            next $JSON_Sort_Order.index(a) <=> $JSON_Sort_Order.index(b)
          else
            next -1
          end
        else
          if $JSON_Sort_Order.include?(b)
            next 1
          end
          # If neither are in the key, go alphabetical
        end
      end
      if a.numeric?
        if b.numeric?
          next a <=> b
        else
          next -1
        end
      else
        if b.numeric?
          next 1
        else
          next a <=> b
        end
      end
    end
    for key in keys
      if self[key].is_a?(Hash) || self[key].is_a?(Array)
        val = self[key].to_json(indent + Json_Indent_Width, key == self.keys[0])
      else
        val = self[key]
        val = "\"#{val}\"" if val.is_a?(String)
      end
      full += "\n#{" " * indent}\"#{key}\": #{val},"
    end
    full = full[0..-2]
    full += "\n#{" " * (indent - Json_Indent_Width)}}"
    return full
  end
end

# String class extensions
class String
  # Returns true if the string starts with the passed substring.
  def starts_with?(str)
    return false if !str.is_a?(String)
    return false if str.size > self.size
    return self[0...str.length] == str
  end

  # Returns true if the string ends with the passed substring.
  def ends_with?(str)
    return self.reverse.starts_with?(str.reverse)
  end

  # Converts to bits
  def to_b
    return self.unpack('b*')[0]
  end

  # Converts to bits and replaces itself
  def to_b!
    self.replace(to_b)
  end

  # Converts from bits
  def from_b
    return [self].pack('b*')
  end

  # Convert from bits and replaces itself
  def from_b!
    self.replace(from_b)
  end

  # Returns the first n characters
  def first(n = 1)
    return self.clone if n >= self.size
    return self[0] if n == 1
    return self[0...n]
  end

  # Returns the last n characters
  def last(n = 1)
    return self.clone if n >= self.size
    return self[-1] if n == 1
    return self.reverse[0...n].reverse
  end

  # Returns a random character from the string
  def random
    return self[rand(self.size)]
  end

  # Shuffles the order of the characters
  def shuffle
    return self.split("").shuffle.join("")
  end

  # Breaks the string up every _n_ characters
  def breakup(n)
    new = []
    for i in 0...self.size
      new[(i / n).floor] ||= ""
      new[(i / n).floor] += self[i]
    end
    return new
  end

  def empty?
    return (self.size == 0)
  end

  def numeric?
    i = 0
    for e in self.split("")
      next if i == 0 && e == "-"
      return false unless [0,1,2,3,4,5,6,7,8,9].map { |n| n.to_s }.include?(e)
    end
    return true
  end

  # Deflates itself and returns the result
  def deflate
    return Zlib::Deflate.deflate(self)
  end

  # Deflates and replaces itself
  def deflate!
    self.replace(deflate)
  end

  # Inflates itself and returns the result
  def inflate
    return Zlib::Inflate.inflate(self)
  end

  # Inflates and replaces itself
  def inflate!
    self.replace(inflate)
  end

  # Adds some aliases for <include?>: <has?>, <includes?>, <contains?>
  alias has? include?
  alias includes? include?
  alias contains? include?
end

# File class extensions
class File
  # Copies the source file to the destination path.
  def self.copy(source, destination)
    data = ""
    t = Time.now
    File.open(source, 'rb') do |f|
      while r = f.read(4096)
        if Time.now - t > 1
          Graphics.update
          t = Time.now
        end
        data += r
      end
    end
    File.delete(destination) if File.file?(destination)
    f = File.new(destination, 'wb')
    f.write data
    f.close
  end

  # Renames the old file to be the new file. //exact same as File::move
  def self.rename(old, new)
    File.move(old, new)
  end

  # Copies the source to the destination and deletes the source.
  def self.move(source, destination)
    File.copy(source, destination)
    File.delete(source)
  end

  # Reads the file's data and inflates it with Zlib
  def self.inflate(file)
    data = ""
    t = Time.now
    File.open(file, 'rb') do |f|
      while r = f.read(4096)
        if Time.now - t > 1
          Graphics.update
          t = Time.now
        end
        data += r
      end
    end
    data.inflate!
    File.delete(file)
    f = File.new(file, 'wb')
    f.write data
    f.close
    return data
  end

  # Reads the file's data and deflates it with Zlib
  def self.deflate(file)
    data = ""
    t = Time.now
    File.open(file, 'rb') do |f|
      while r = f.read(4096)
        if Time.now - t > 1
          Graphics.update
          t = Time.now
        end
        data += r
      end
    end
    data.deflate!
    File.delete(file)
    f = File.new(file, 'wb')
    f.write data
    f.close
    return data
  end

  # Note: This is VERY basic compression and should NOT serve as encryption.
  # Compresses all specified files into one, big package
  def self.compress(outfile, files, delete_files = true)
    start = Time.now
    files = [files] unless files.is_a?(Array)
    for i in 0...files.size
      if !File.file?(files[i])
        raise "Could not find part of the path `#{files[i]}`"
      end
    end
    files.breakup(500) # 500 files per compressed file
    full = ""
    t = Time.now
    for i in 0...files.size
      if Time.now - t > 1
        Graphics.update
        t = Time.now
      end
      data = ""
      File.open(files[i], 'rb') do |f|
        while r = f.read(4096)
          if Time.now - t > 1
            Graphics.update
            t = Time.now
          end
          data += r
        end
      end
      File.delete(files[i]) if delete_files
      full += "#{data.size}|#{files[i]}|#{data}"
      full += "|" if i != files.size - 1
    end
    File.delete(outfile) if File.file?(outfile)
    f = File.new(outfile, 'wb')
    f.write full.deflate
    f.close
    return Time.now - start
  end

  # Decompresses files compressed with File.compress
  def self.decompress(filename, delete_package = true)
    start = Time.now
    data = ""
    t = Time.now
    File.open(filename, 'rb') do |f|
      while r = f.read(4096)
        if Time.now - t > 1
          Graphics.update
          t = Time.now
        end
        data += r
      end
    end
    data.inflate!
    loop do
      size, name = data.split('|')
      data = data.split(size + "|" + name + "|")[1..-1].join(size + "|" + name + "|")
      size = size.to_i
      content = data[0...size]
      data = data[(size + 1)..-1]
      File.delete(name) if File.file?(name)
      f = File.new(name, 'wb')
      f.write content
      f.close
      break if !data || data.size == 0 || data.split('|').size <= 1
    end
    File.delete(filename) if delete_package
    return Time.now - start
  end

  # Creates all directories that don't exist in the given path, as well as the
  # file. If given a second argument, it'll write that to the file.
  def self.create(path, data = nil)
    start = Time.now
    Dir.create(path.split('/')[0..-2].join('/'))
    f = File.new(path, 'wb')
    f.write data if data && data.size > 0
    f.close
    return Time.now - start
  end
end

# Dir class extensions
class Dir
  class << Dir
    alias marin_delete delete
  end

  # Returns all files in the targeted path
  def self.get_files(path, recursive = true)
    return Dir.get_all(path, recursive).select { |path| File.file?(path) }
  end

  # Returns all directories in the targeted path
  def self.get_dirs(path, recursive = true)
    return Dir.get_all(path, recursive).select { |path| File.directory?(path) }
  end

  # Returns all files and directories in the targeted path
  def self.get_all(path, recursive = true)
    files = []
    Dir.foreach(path) do |f|
      next if f == "." || f == ".."
      if File.directory?(path + "/" + f) && recursive
        files.concat(Dir.get_files(path + "/" + f))
      end
      files << path + "/" + f
    end
    return files
  end

  # Deletes a directory and all files/directories within, unless non_empty is false
  def self.delete(path, non_empty = true)
    if non_empty
    for file in Dir.get_all(path)
      if File.directory?(file)
        Dir.delete(file, non_empty)
      elsif File.file?(file)
        File.delete(file)
      end
    end
  end
    marin_delete(path)
  end

  # Creates all directories that don't exist in the given path.
  def self.create(path)
    split = path.split('/')
    for i in 0...split.size
      Dir.mkdir(split[0..i].join('/')) unless File.directory?(split[0..i].join('/'))
    end
  end
end


# Sprite class extensions
class Sprite
  # Shorthand for initializing a bitmap by path, bitmap, or width/height:
  # -> bmp("Graphics/Pictures/bag")
  # -> bmp(32, 32)
  # -> bmp(some_other_bitmap)
  def bmp(arg1 = nil, arg2 = nil)
    if arg1
      if arg2
        arg1 = Graphics.width if arg1 == -1
        arg2 = Graphics.height if arg2 == -1
        self.bitmap = Bitmap.new(arg1, arg2)
      elsif arg1.is_a?(Bitmap)
        self.bitmap = arg1.clone
      else
        self.bitmap = Bitmap.new(arg1)
      end
    else
      return self.bitmap
    end
  end

  # Alternative to bmp(path):
  # -> bmp = "Graphics/Pictures/bag"
  def bmp=(arg1)
    bmp(arg1)
  end

  # Usage:
  # -> [x]             # Sets sprite.x to x
  # -> [x,y]           # Sets sprite.x to x and sprite.y to y
  # -> [x,y,z]         # Sets sprite.x to x and sprite.y to y and sprite.z to z
  # -> [nil,y]         # Sets sprite.y to y
  # -> [nil,nil,z]     # Sets sprite.z to z
  # -> [x,nil,z]       # Sets sprite.x to x and sprite.z to z
  # Etc.
  def xyz=(args)
    self.x = args[0] || self.x
    self.y = args[1] || self.y
    self.z = args[2] || self.z
  end

  # Returns the x, y, and z coordinates in the xyz=(args) format, [x,y,z]
  def xyz
    return [self.x,self.y,self.z]
  end

  # Centers the sprite by setting the origin points to half the width and height
  def center_origins
    return if !self.bitmap
    self.ox = self.bitmap.width / 2
    self.oy = self.bitmap.height / 2
  end

  # Returns the sprite's full width, taking zoom_x into account
  def fullwidth
    return self.bitmap.width.to_f * self.zoom_x
  end

  # Returns the sprite's full height, taking zoom_y into account
  def fullheight
    return self.bitmap.height.to_f * self.zoom_y
  end
end

class TextSprite < Sprite
  # Sets up the sprite and bitmap. You can also pass text to draw
  # either an array of arrays, or an array containing the normal "parameters"
  # for drawing text:
  # [text,x,y,align,basecolor,shadowcolor]
  def initialize(viewport = nil, text = nil, width = -1, height = -1)
    super(viewport)
    @width = width
    @height = height
    self.bmp(@width, @height)
    pbSetSystemFont(self.bmp)
    if text.is_a?(Array)
      if text[0].is_a?(Array)
        pbDrawTextPositions(self.bmp,text)
      else
        pbDrawTextPositions(self.bmp,[text])
      end
    end
  end

  # Clears the bitmap (and thus all drawn text)
  def clear
    self.bmp.clear
    pbSetSystemFont(self.bmp)
  end

  # You can also pass text to draw either an array of arrays, or an array
  # containing the normal "parameters" for drawing text:
  # [text,x,y,align,basecolor,shadowcolor]
  def draw(text, clear = false)
    self.clear if clear
    if text[0].is_a?(Array)
      pbDrawTextPositions(self.bmp,text)
    else
      pbDrawTextPositions(self.bmp,[text])
    end
  end

  # Draws text with outline
  # [text,x,y,align,basecolor,shadowcolor]
  def draw_outline(text, clear = false)
    self.clear if clear
    if text[0].is_a?(Array)
      for e in text
        pbDrawOutlineText(self.bmp,e[1],e[2],640,480,e[0],e[4],e[5],e[3])
      end
    else
      e = text
      pbDrawOutlineText(self.bmp,e[1],e[2],640,480,e[0],e[4],e[5],e[3])
    end
  end

  # Draws and breaks a line if the width is exceeded
  # [text,x,y,width,numlines,basecolor,shadowcolor]
  def draw_ex(text, clear = false)
    self.clear if clear
    if text[0].is_a?(Array)
      for e in text
        drawTextEx(self.bmp,e[1],e[2],e[3],e[4],e[0],e[5],e[6])
      end
    else
      e = text
      drawTextEx(self.bmp,e[1],e[2],e[3],e[4],e[0],e[5],e[6])
    end
  end

  # Clears and disposes the sprite
  def dispose
    clear
    super
  end
end

# A better alternative to the typical @sprites = {}
class SpriteHash
  attr_reader :x
  attr_reader :y
  attr_reader :z
  attr_reader :visible
  attr_reader :opacity

  def initialize
    @hash = {}
    @x = 0
    @y = 0
    @z = 0
    @visible = true
    @opacity = 255
  end

  # Returns the object in the specified key
  def [](key)
    key = key.to_sym if key.respond_to?(:to_sym) && !key.is_a?(Numeric)
    return @hash[key]
  end

  # Sets an object in specified key to the specified value
  def []=(key, value)
  key = key.to_sym if key.respond_to?(:to_sym) && !key.is_a?(Numeric)
    add(key, value)
  end

  # Returns the raw hash
  def raw
    return @hash
  end

  # Returns the keys in the hash
  def keys
    return @hash.keys
  end

  def length; return self.size; end
  def count; return self.size; end

  # Returns the amount of keys in the hash
  def size
    return @hash.keys.size
  end

  # Clones the hash
  def clone
    return @hash.clone
  end

  # Adds an object to the specified key
  def add(key, value)
    clear_disposed
    key = key.to_sym if key.respond_to?(:to_sym) && !key.is_a?(Numeric)
    @hash[key] if @hash[key] && @hash[key].respond_to?(:dispose)
    @hash[key] = value
    clear_disposed
  end

  # Deletes an object in the specified key
  def delete(key)
    key = key.to_sym if key.respond_to?(:to_sym) && !key.is_a?(Numeric)
    @hash[key] = nil
    clear_disposed
  end

  # Iterates over all sprites
  def each
    clear_disposed
    @hash.each { |s| yield s[1] if block_given? }
  end

  # Updates all sprites
  def update
    clear_disposed
    for key in @hash.keys
      @hash[key].update if @hash[key].respond_to?(:update)
    end
  end

  # Disposes all sprites
  def dispose
    clear_disposed
    for key in @hash.keys
      @hash[key].dispose if @hash[key].respond_to?(:dispose)
    end
    clear_disposed
  end

  # Compatibility
  def disposed?
    return false
  end

  # Changes x on all sprites
  def x=(value)
    clear_disposed
    for key in @hash.keys
      @hash[key].x += value - @x
    end
    @x = value
  end

  # Changes y on all sprites
  def y=(value)
    clear_disposed
    for key in @hash.keys
      @hash[key].y += value - @y
    end
    @y = value
  end

  # Changes z on all sprites
  def z=(value)
    clear_disposed
    for key in @hash.keys
      @hash[key].z += value - @z
    end
    @z = value
  end

  # Changes visibility on all sprites
  def visible=(value)
    clear_disposed
    for key in @hash.keys
      @hash[key].visible = value
    end
  end

  # Changes opacity on all sprites
  def opacity=(value)
    clear_disposed
    for key in @hash.keys
      @hash[key].opacity += value - @opacity
    end
    @opacity = [0,value,255].sort[1]
  end

  # Fades out all sprites
  def hide(frames = 16)
    clear_disposed
    frames.times do
      Graphics.update
      Input.update
      for key in @hash.keys
        @hash[key].opacity -= 255 / frames.to_f
      end
    end
    @opacity = 0
  end

  # Fades in all sprites
  def show(frames = 16)
    clear_disposed
    frames.times do
      Graphics.update
      Input.update
      for key in @hash.keys
        @hash[key].opacity += 255 / frames.to_f
      end
    end
    @opacity = 255
  end

  # Deletes all disposed sprites from the hash
  def clear_disposed
    for key in @hash.keys
      if (@hash[key].disposed? rescue true)
        @hash[key] = nil
        @hash.delete(key)
      end
    end
  end

  # Renames the old key to the new key
  def rename(old, new)
    self[new] = self[old]
    delete(old)
  end
end


# Stand-alone methods

# Fades in a black overlay
def showBlk(n = 16)
  return if $blkVp || $blk
  $blkVp = Viewport.new(0,0,DEFAULTSCREENWIDTH,DEFAULTSCREENHEIGHT)
  $blkVp.z = 9999999
  $blk = Sprite.new($blkVp)
  $blk.bmp(-1,-1)
  $blk.bitmap.fill_rect(0,0,DEFAULTSCREENWIDTH,DEFAULTSCREENHEIGHT,Color.new(0,0,0))
  $blk.opacity = 0
  for i in 0...(n + 1)
    Graphics.update
    Input.update
    yield i if block_given?
    $blk.opacity += 256 / n.to_f
  end
end

# Fades out and disposes a black overlay
def hideBlk(n = 16)
  return if !$blk || !$blkVp
  for i in 0...(n + 1)
    Graphics.update
    Input.update
    yield i if block_given?
    $blk.opacity -= 256 / n.to_f
  end
  $blk.dispose
  $blk = nil
  $blkVp.dispose
  $blkVp = nil
end

# Returns the percentage of exp the Pokémon has compared to the next level
def pbGetExpPercentage(pokemon)
  pokemon = pokemon.pokemon if pokemon.respond_to?("pokemon")
  startexp = PBExperience.pbGetStartExperience(pokemon.level, pokemon.growthrate)
  endexp = PBExperience.pbGetStartExperience(pokemon.level + 1, pokemon.growthrate)
  return (pokemon.exp - startexp).to_f / (endexp - startexp).to_f
end

alias oldrand rand
def rand(a = nil, b = nil)
  if a.is_a?(Range)
    l = a.min
    u = a.max
    return l + oldrand(u - l + 1)
  elsif a.is_a?(Numeric)
    if b.is_a?(Numeric)
      return a + oldrand(b - a)
    else
      return oldrand(a)
    end
  elsif a.nil?
    if b
      return rand(b)
    else
      return oldrand(2)
    end
  end
end

# Input module extensions
module Input
  # Returns true if any of the buttons below are pressed
  def self.any?
    return true if defined?(Game_Mouse) && $mouse && $mouse.click?
    keys = [Input::C,Input::B,Input::LEFT,Input::RIGHT,Input::UP,Input::DOWN,
            # 0-9, a-z
            0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x41,0x42,0x43,0x44,
            0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x50,0x51,0x52,0x53,
            0x54,0x55,0x56,0x57,0x58,0x59,0x5A]
    for key in keys
      return true if Input.triggerex?(key)
    end
    return false
  end
end





if SPECIAL_ERRORS

MessageBox = Win32API.new('user32', 'MessageBox', ['I','P','P','I'], 'I')

def p_msg(msg, title = nil, icon = nil)
  case icon
  when :error, :err
    uType = 0x10
    title ||= "Error"
  when :q, :question, :ask
    uType = 0x20
    title ||= "Question"
  when :warning, :warn
    uType = 0x30
    title ||= "Warning"
  when :inform, :info, :information
    uType = 0x40
    title ||= "Info"
  else
    uType = 0
    title ||= "Pokémon"
  end
  hwnd = Win32API.pbFindRgssWindow
  Graphics.update
  t = Thread.new { MessageBox.call(hwnd, msg, title, uType); Thread.exit }
  while t.status
    Graphics.update
  end
end

def p_err(ex = $!, message = nil)
  if $Rescue
    raise
    return
  end
  if ex.is_a?(String)
    ex = RuntimeError.new ex
  elsif ex.is_a?(Class)
    ex = ex.new
  end
  trace = ex.backtrace || caller
  script_id = trace[0][7..-1].split(':')[0].to_i
  script = $RGSS_SCRIPTS[script_id][1]
  line = trace[0].split(':')[1].to_i
  msg = "Script '#{script}' line #{line}: #{ex.class} occurred."
  if message || ex.message != ex.class.to_s
    if message
      msg << "\n\n#{message}"
    else
      msg << "\n\n#{ex.message}"
      message = ex.message
    end
  end
  showtrace = (trace.size > 2)
  showtrace = false if !DOUBLE_BACKTRACE && message.include?(':in `')
  if showtrace
    msg << "\n\n"
    msg << trace[0...BACKTRACE_MAX_SIZE].map do |e|
      sID = e.split(':')[0][7..-1]
      if sID.numeric?
        sID = sID.to_i
        s = "'" + $RGSS_SCRIPTS[sID][1] + "'"
      else
        s = "eval"
      end
      line = e.split(':')[1].to_i
      code = e.split(':')[2..-1].join(':')
      str = "from #{s} line #{line}"
      str << " #{code}" unless code.empty?
      next str
    end.join("\n")
  end
  p_msg(msg, "Error", :err)
  Kernel.exit! true
end

def p_info(msg, title = nil)
  p_msg(msg, title, :info)
end

def p_warn(msg, title = nil)
  p_msg(msg, title, :warn)
end

def p_question(msg, title = nil)
  p_msg(msg, title, :question)
end

trace_var(:$scene, proc do |object|
  break unless object
  unless object.instance_variable_get(:@__old_main)
    object.instance_variable_set(:@__old_main, object.method(:main))
    def object.main
      self.instance_variable_get(:@__old_main).call
    rescue
      p_err
    end
  end
end)

else

def p_err(*args)
  raise *args
end

end # if SPECIAL_ERRORS


def pbGetActiveEventPage(event, mapid = nil)
  mapid ||= event.map.map_id if event.respond_to?(:map)
  pages = (event.is_a?(RPG::Event) ? event.pages : event.instance_eval { @event.pages })
  for i in 0...pages.size
    c = pages[pages.size - 1 - i].condition
    ss = !(c.self_switch_valid && !$game_self_switches[[mapid,
        event.id,c.self_switch_ch]])
    sw1 = !(c.switch1_valid && !$game_switches[c.switch1_id])
    sw2 = !(c.switch2_valid && !$game_switches[c.switch2_id])
    var = true
    if c.variable_valid
      if !c.variable_value || !$game_variables[c.variable_id].is_a?(Numeric) ||
         $game_variables[c.variable_id] < c.variable_value
        var = false
      end
    end
    if ss && sw1 && sw2 && var # All conditions are met
      return pages[pages.size - 1 - i]
    end
  end
  return nil
end



end # if USING_MARIN_UTILITY

Ruby:
#==============================================================================#
#                         Diamond/Pearl Pause Menu                             #
#                                  by Marin                                    #
#==============================================================================#
#                                Instructions                                  #
#                                                                              #
#  To call the Pause menu individually (not by pressing B), use _pbPauseMenu_  #
#                                                                              #
# To make/add your own options, find _@options = []_. Underneath, all options  #
#        are initialized and added. They follow a very simple format:          #
#           [displayname, unselected, selected, code, (condition)]             #
# _displayname_ : This is what's actually displayed on screen.                 #
# _unselected_ : This is the icon that will be displayed when the option is    #
#                NOT selected. For it to be gender dependent, make it an array #
# _selected_ : This is the icon that will be displayed when the option IS      #
#              selected. For it to be gender dependent, make it an array.      #
# _code_ : This is what's executed when you click the button.                  #
# _condition_ : If you only want the option to be visible at certain times,    #
#               this is where you can add a condition (e.g. $Trainer.pokedex). #
#==============================================================================#
#                    Please give credit when using this.                       #
#==============================================================================#

# Calls the Pause menu
def pbPauseMenu
  DP_PauseMenu.new
end

# This overwrites the old pause menu. Take/comment out these 10 lines to keep
# the old Pause menu.
class Scene_Map
  def call_menu
    $game_temp.menu_calling = false
    $game_temp.in_menu = true
    $game_player.straighten
    $game_map.update
    pbPauseMenu # Calls the DP Pause Menu
    $game_temp.in_menu = false
  end
end

# Variables used to store last selected index.
class PokemonGlobalMetadata
  attr_accessor :last_menu_index
end

class DP_PauseMenu
  # Base color of the displayed text
  BaseColor = Color.new(82,82,90)
  # Shadow color of the displayed text
  ShadowColor = Color.new(165,165,173)

  def initialize
      unless (pbMarinUtility rescue false)
      raise "You need to have Marin's Scripting Utilities active!"
    end
    @options = []
    @options << ["Pokédex", "pokedexA", "pokedexB", proc {
      if DEXDEPENDSONLOCATION
        pbFadeOutIn(99999) do
          scene = PokemonPokedex_Scene.new
          screen = PokemonPokedexScreen.new(scene)
          screen.pbStartScreen
          end
      else
        if $PokemonGlobal.pokedexViable.length == 1
          $PokemonGlobal.pokedexDex = $PokemonGlobal.pokedexViable[0]
          $PokemonGlobal.pokedexDex = -1 if $PokemonGlobal.pokedexDex == $PokemonGlobal.pokedexUnlocked.length-1
          pbFadeOutIn(99999) do
            scene = PokemonPokedex_Scene.new
            screen = PokemonPokedexScreen.new(scene)
            screen.pbStartScreen
           end
        else
          pbFadeOutIn(99999) do
          scene = PokemonPokedexMenu_Scene.new
          screen = PokemonPokedexMenuScreen.new(scene)
          screen.pbStartScreen
          end
        end
      end
    }] if $Trainer.pokedex
    @options << ["Pokémon", "pokemonA", "pokemonB", proc {
      hiddenmove = nil
      pbFadeOutIn(99999) do
        sscene = PokemonParty_Scene.new
        sscreen = PokemonPartyScreen.new(sscene,$Trainer.party)
        hiddenmove = sscreen.pbPokemonScreen
        if hiddenmove
          @sprites.visible = false
          @done = true
        end
      end
      if hiddenmove
        $game_temp.in_menu = false
        Kernel.pbUseHiddenMove(hiddenmove[0],hiddenmove[1])
      end
    }] if $Trainer.party.size > 0
    @options << ["Beutel", "bagA", ["bagBm", "bagBf"], proc {
    item = 0
      pbFadeOutIn(99999) do
        scene = PokemonBag_Scene.new
        screen = PokemonBagScreen.new(scene,$PokemonBag)
        item = screen.pbStartScreen
        if item > 0
          @done = true
          @sprites.visible = false
        end
      end
      Kernel.pbUseKeyItemInField(item) if item > 0
    }]
    @options << [$Trainer.name, "trainercardA", "trainercardB", proc {
      pbFadeOutIn(99999) do
        scene = PokemonTrainerCard_Scene.new
        screen = PokemonTrainerCardScreen.new(scene)
        screen.pbStartScreen
      end
    }]
    @options << ["Speichern", "saveA", ["saveBm","saveBf"], proc {
    @sprites.visible = false
      scene = PokemonSave_Scene.new
      screen = PokemonSaveScreen.new(scene)
      if screen.pbSaveScreen
        @done = true
      else
        @sprites.visible = true
      end
    }]
    @options << ["Optionen", "optionsA", "optionsB", proc {
      pbFadeOutIn(99999) do
        scene = PokemonOption_Scene.new
        screen = PokemonOptionScreen.new(scene)
        screen.pbStartScreen
        pbUpdateSceneMap
      end
    }]
    @options << ["Beenden", "exitA", "exitB", proc {
      @done = true
    }]
  
    @count = @options.size
    return if @count == 0
    $PokemonGlobal.last_menu_index ||= 0
    @option = $PokemonGlobal.last_menu_index
    @option = 0 if @option >= @options.size
    @done = false
    @i = 0
    @scaling = 0
    @viewport = Viewport.new(Graphics.width - 204, 4, 200, 24 + 48 * @count)
    @viewport.z = 99999
    @sprites = SpriteHash.new
    @sprites["bgTop"] = Sprite.new(@viewport)
    @sprites["bgTop"].bmp("Graphics/Pictures/DP Pause Menu/bgTop")
    @sprites["bgMid"] = Sprite.new(@viewport)
    @sprites["bgMid"].bmp("Graphics/Pictures/DP Pause Menu/bgMid")
    @sprites["bgMid"].y = 12
    @sprites["bgMid"].zoom_y = 48 * @count
    @sprites["bgBtm"] = Sprite.new(@viewport)
    @sprites["bgBtm"].bmp("Graphics/Pictures/DP Pause Menu/bgBtm")
    @sprites["bgBtm"].y = 12 + @sprites["bgMid"].zoom_y
    @sprites["sel"] = Sprite.new(@viewport)
    @sprites["sel"].bmp("Graphics/Pictures/DP Pause Menu/selector")
    @sprites["sel"].xyz = 8, 10 + 48 * @option, 1
    @sprites["txt"] = TextSprite.new(@viewport)
    for i in 0...@options.size
      @sprites["txt"].draw([
          @options[i][0],68,20 + 48 * i,0,BaseColor,ShadowColor
      ])
      @sprites[@options[i][0]] = Sprite.new(@viewport)
      idx = (i == @option ? 2 : 1)
      path = @options[i][idx]
      path = path[$Trainer.gender] if path.is_a?(Array)
      @sprites[@options[i][0]].bmp("Graphics/Pictures/DP Pause Menu/#{path}")
      @sprites[@options[i][0]].center_origins
      @sprites[@options[i][0]].xyz = 39, 36 + 48 * i
    end
    main
  end

  def main
    loop do
      update
      old = @option
      if Input.repeat?(Input::DOWN)
        pbPlayDecisionSE
        @option += 1
        @option = 0 if @option == @count
        changed = true
      end
      if Input.repeat?(Input::UP)
        pbPlayDecisionSE
        @option -= 1
        @option = @count - 1 if @option == -1
        changed = true
      end
      if $mouse
        for i in 0...@count
          if i != @option && $mouse.inArea?(316,14 + 48 * i,184,52)
            @option = i
            changed = true
          end
        end
      end
      confirmed = ($mouse && $mouse.x >= 316 && $mouse.x <= 500 && $mouse.y >= 14 &&
         $mouse.y <= 14 + 48 * @count && $mouse.click?)
      confirmed = true if Input.trigger?(Input::C)
      if changed
        $PokemonGlobal.last_menu_index = @option
        path = @options[old][1]
        path = path[$Trainer.gender] if path.is_a?(Array)
        @sprites[@options[old][0]].bmp("Graphics/Pictures/DP Pause Menu/#{path}")
        @sprites[@options[old][0]].angle = 0
        @sprites[@options[old][0]].zoom_x = 1
        @sprites[@options[old][0]].zoom_y = 1
        @sprites["sel"].y = 10 + 48 * @option
        path = @options[@option][2]
        path = path[$Trainer.gender] if path.is_a?(Array)
        @sprites[@options[@option][0]].bmp("Graphics/Pictures/DP Pause Menu/#{path}")
        changed = false
        @scaling = 0
      end
      if confirmed
        @options[@option][3].call
        Input.update
      end
      confirmed = false
      break if Input.trigger?(Input::B) || @done
    end
    dispose
  end

  def update
    Graphics.update
    Input.update
    pbUpdateSceneMap
    if @scaling
      @scaling += 1
      case @scaling
      when 1..4
        @sprites[@options[@option][0]].zoom_x += 0.05
        @sprites[@options[@option][0]].zoom_y += 0.05
      when 8..12
        @sprites[@options[@option][0]].zoom_x -= 0.05
        @sprites[@options[@option][0]].zoom_y -= 0.05
      end
      @scaling = nil if @scaling == 12
    else
      @i += 1
      case @i
      when 1..6
        @sprites[@options[@option][0]].angle -= 2
      when 7..18
        @sprites[@options[@option][0]].angle += 2
      when 19..24
        @sprites[@options[@option][0]].angle -= 2
      end
      @i = 0 if @i == 24
    end
  end

  def dispose
    @sprites.dispose
    @viewport.dispose
    Input.update
  end
end

Ruby:
#=====================================================================================
# * Gender Selection Script for the Pokemon Essentials BW2 Mod made by shiney570.
#
# * What it will do:
#
#  - create a scene, where the player can choose his gender.
#
#  Tips:
#
#  - if you don't want the intro background for this scene, you can erase the
#    background for this scene, if you set GENDERSELECTION_BG =false (in the
#    Settings Script).
#  
#===================================================================================
class PokemonGenderSelection

  def initialize
 
    @select=1; @close=0
 
    @viewport=Viewport.new(0,0,Graphics.width,Graphics.height)
    @viewport.z=99999
    @sprites={}
 
    @sprites["1"]=IconSprite.new(0,0,@viewport)
    @sprites["1"].setBitmap("Graphics/Pictures/GenderSelection/default")
 
    @sprites["2"]=IconSprite.new(0,0,@viewport)
    @sprites["2"].setBitmap("Graphics/Pictures/GenderSelection/boy_1")
    @sprites["2"].visible=false
 
    @sprites["3"]=IconSprite.new(0,0,@viewport)
    @sprites["3"].setBitmap("Graphics/Pictures/GenderSelection/boy_2")
    @sprites["3"].visible=false
 
    @sprites["4"]=IconSprite.new(0,0,@viewport)
    @sprites["4"].setBitmap("Graphics/Pictures/GenderSelection/girl_1")
    @sprites["4"].visible=false
 
    @sprites["5"]=IconSprite.new(0,0,@viewport)
    @sprites["5"].setBitmap("Graphics/Pictures/GenderSelection/girl_2")
    @sprites["5"].visible=false
    pbWait(10)
    Kernel.pbMessage("Wie siehst du eigentlich aus?")
    main_method
  end

  # Input method.
  def input
    if Input.trigger?(Input::LEFT)  && (@select==1 || @select==4)
      @select=2
    end
    if Input.trigger?(Input::RIGHT) && (@select==1 || @select==2)
      @select=4
    end
    if Input.trigger?(Input::C)
      @select+=1
      for i in 1..5
        @sprites["#{i}"].visible = @select==i
      end
      self.continue
    end
    if defined?($mouse)
      if $mouse.leftClick?(@sprites["2"]) || $mouse.leftClick?(@sprites["4"])
        @select+=1
        for i in 1..5
          @sprites["#{i}"].visible = @select==i
        end
        self.continue
      end
    end
  end

  # Main Method
  def main_method
    while @close!=1
      Graphics.update
      Input.update
      for i in 1..5
        @sprites["#{i}"].visible = @select==i
      end
      input
    end
  end

  # Confirm method.
  def continue
    if @select==3
      pbWait(20)
      if Kernel.pbConfirmMessage("Du bist also ein Junge?")
        pbChangePlayer(0)
        @close=1
        20.times do
          @sprites["#{@select}"].opacity-= 12.75
          pbWait(1)
        end
      else
        @select=2
      end
    elsif @select==5
      pbWait(20)
      if Kernel.pbConfirmMessage("Du bist also ein Mädchen?")
        pbChangePlayer(1)
        @close=1
        20.times do
          @sprites["#{@select}"].opacity-= 12.75
          pbWait(1)
        end
      else
        @select=4
      end
    end
  end
end

Ruby:
#=====================================================================================
# * Rival Screen by Marina
#
# * What it will do:
#
#  - create a scene, where you can see the Rival.
#
#
#  
#===================================================================================
class RivalAnsehen

  def initialize
    @viewport=Viewport.new(0,0,Graphics.width,Graphics.height)
    @viewport.z=99999
    @sprites={}
 
    @sprites["1"]=IconSprite.new(256,120,@viewport)
    @sprites["1"].setBitmap("Graphics/Pictures/introRival")
    pbWait(10)
  end
      end


Ruby:
#=====================================================================================
# * Rival Screen by (Marina)
#
# * What it will do:
#
#  - create a scene, where you can see the Rival.
#
#
#  
#===================================================================================
class RivalScreen

  def initialize
    @viewport=Viewport.new(0,0,Graphics.width,Graphics.height)
    @viewport.z=99999
    @sprites={}
 
    @sprites["1"]=IconSprite.new(256,120,@viewport)
    @sprites["1"].setBitmap("Graphics/Pictures/introRival")
    pbWait(10)
    Kernel.pbMessage("Diesen jungen Mann hier kennst du, oder? Haha! Klar kennst du ihn.")
    Kernel.pbMessage("Schließlich seid ihr schon von Kindesbeinen an die besten Freunde. Und die größten Rivalen!")
  end
      end

============
KLEIN STUDIO

Ruby:
#===============================================================================
# ■ Always on bush by KleinStudio
# https://wahpokemon.com
# http://pokemonfangames.com
#===============================================================================
class Game_Character
  def bush_depth
    if @tile_id > 0 or @always_on_top
      return 0
    end
    xnext=(@direction==4) ? @x-1 : (@direction==6) ? @x+1 : @x
    ynext=(@direction==8) ? @y-1 : (@direction==2) ? @y+1 : @y

    xbehind=(@direction==4) ? @x+1 : (@direction==6) ? @x-1 : @x
    ybehind=(@direction==8) ? @y+1 : (@direction==2) ? @y-1 : @y

    if @jump_count <= 0 and self.map.bush?(@x, @y) and
      !self.map.bush?(xbehind, ybehind) and !moving?
      return 12
    elsif @jump_count <= 0 and self.map.bush?(@x, @y) and
      self.map.bush?(xbehind, ybehind)
      return 12
    else
      return 0
    end
  end
end

========================

Ruby:
# This class stores data on each Pokémon. Refer to $Trainer.party for an array
# of each Pokémon in the Trainer's current party.
class PokeBattle_Pokemon
  attr_accessor :special
end

class PokeBattle_Battler
  attr_accessor :special

  def isSpecial?
    if @pokemon
      return (@pokemon.special rescue false)
    end
    return false
  end
end

class PokeBattle_Pokemon
  attr_reader(:totalhp)       # Current Total HP
  attr_reader(:attack)        # Current Attack stat
  attr_reader(:defense)       # Current Defense stat
  attr_reader(:speed)         # Current Speed stat
  attr_reader(:spatk)         # Current Special Attack stat
  attr_reader(:spdef)         # Current Special Defense stat
  attr_accessor(:iv)          # Array of 6 Individual Values for HP, Atk, Def,
                              #    Speed, Sp Atk, and Sp Def
  attr_accessor(:wake)                        
  attr_accessor(:ev)          # Effort Values
  attr_accessor(:species)     # Species (National Pokedex number)
  attr_accessor(:personalID)  # Personal ID
  attr_accessor(:trainerID)   # 32-bit Trainer ID (the secret ID is in the upper
                              #    16 bits)
  attr_reader(:hp)            # Current HP
  attr_writer(:pokerus)       # Pokérus strain and infection time
  attr_accessor(:item)        # Held item
  attr_accessor(:itemRecycle) # Consumed held item (used in battle only)
  attr_accessor(:itemInitial) # Resulting held item (used in battle only)
  attr_accessor(:belch)       # Whether Pokémon can use Belch (used in battle only)
  attr_accessor(:mail)        # Mail
  attr_accessor(:fused)       # The Pokémon fused into this one
  attr_accessor(:name)        # Nickname
  attr_accessor(:exp)         # Current experience points
  attr_accessor(:happiness)   # Current happiness
  attr_accessor(:status)      # Status problem (PBStatuses)
  attr_accessor(:statusCount) # Sleep count/Toxic flag
  attr_accessor(:eggsteps)    # Steps to hatch egg, 0 if Pokémon is not an egg
  attr_accessor(:moves)       # Moves (PBMove)
  attr_accessor(:firstmoves)  # The moves known when this Pokémon was obtained
  attr_accessor(:ballused)    # Ball used
  attr_accessor(:markings)    # Markings
  attr_accessor(:obtainMode)  # Manner obtained:
                              #    0 - met, 1 - as egg, 2 - traded,
                              #    4 - fateful encounter
  attr_accessor(:obtainMap)   # Map where obtained
  attr_accessor(:obtainText)  # Replaces the obtain map's name if not nil
  attr_accessor(:obtainLevel) # Level obtained
  attr_accessor(:hatchedMap)  # Map where an egg was hatched
  attr_accessor(:language)    # Language
  attr_accessor(:ot)          # Original Trainer's name
  attr_accessor(:otgender)    # Original Trainer's gender:
                              #    0 - male, 1 - female, 2 - mixed, 3 - unknown
                              #    For information only, not used to verify
                              #    ownership of the Pokémon
  attr_accessor(:abilityflag) # Forces the first/second/hidden (0/1/2) ability
  attr_accessor(:genderflag)  # Forces male (0) or female (1)
  attr_accessor(:natureflag)  # Forces a particular nature
  attr_accessor(:shinyflag)   # Forces the shininess (true/false)
  attr_accessor(:ribbons)     # Array of ribbons
  attr_accessor :cool,:beauty,:cute,:smart,:tough,:sheen   # Contest stats

  EVLIMIT     = 510   # Max total EVs
  EVSTATLIMIT = 252   # Max EVs that a single stat can have
  NAMELIMIT   = 10    # Maximum length a Pokémon's nickname can be

################################################################################
# Ownership, obtained information
################################################################################
# Returns the gender of this Pokémon's original trainer (2=unknown).
  def otgender
    @otgender=2 if !@otgender
    return @otgender
  end

# Returns whether the specified Trainer is NOT this Pokémon's original trainer.
  def isForeign?(trainer)
    return @trainerID!=trainer.id || @ot!=trainer.name
  end

# Returns the public portion of the original trainer's ID.
  def publicID
    return @trainerID&0xFFFF
  end

# Returns this Pokémon's level when this Pokémon was obtained.
  def obtainLevel
    @obtainLevel=0 if !@obtainLevel
    return @obtainLevel
  end

# Returns the time when this Pokémon was obtained.
  def timeReceived
    return @timeReceived ? Time.at(@timeReceived) : Time.gm(2000)
  end

# Sets the time when this Pokémon was obtained.
  def timeReceived=(value)
    # Seconds since Unix epoch
    if value.is_a?(Time)
      @timeReceived=value.to_i
    else
      @timeReceived=value
    end
  end

# Returns the time when this Pokémon hatched.
  def timeEggHatched
    if obtainMode==1
      return @timeEggHatched ? Time.at(@timeEggHatched) : Time.gm(2000)
    else
      return Time.gm(2000)
    end
  end

# Sets the time when this Pokémon hatched.
  def timeEggHatched=(value)
    # Seconds since Unix epoch
    if value.is_a?(Time)
      @timeEggHatched=value.to_i
    else
      @timeEggHatched=value
    end
  end

################################################################################
# Level
################################################################################
# Returns this Pokémon's level.
  def level
    return PBExperience.pbGetLevelFromExperience(@exp,self.growthrate)
  end

# Sets this Pokémon's level by changing its Exp. Points.
  def level=(value)
    if value<1 || value>PBExperience::MAXLEVEL
      raise ArgumentError.new(_INTL("The level number ({1}) is invalid.",value))
    end
    self.exp=PBExperience.pbGetStartExperience(value,self.growthrate)
  end

# Returns whether this Pokémon is an egg.
  def egg?
    return @eggsteps>0
  end

  alias isEgg? egg?

# Returns this Pokémon's growth rate.
  def growthrate
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,@species,20)
    ret=dexdata.fgetb
    dexdata.close
    return ret
  end

# Returns this Pokémon's base Experience value.
  def baseExp
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,38)
    ret=dexdata.fgetw
    dexdata.close
    return ret
  end

################################################################################
# Gender
################################################################################
# Returns this Pokémon's gender. 0=male, 1=female, 2=genderless
  def gender
    return @genderflag if @genderflag!=nil
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,@species,18)
    genderbyte=dexdata.fgetb
    dexdata.close
    case genderbyte
    when 255
      return 2 # genderless
    when 254
      return 1 # always female
    else
      lowbyte=@personalID&0xFF
      return PokeBattle_Pokemon.isFemale(lowbyte,genderbyte) ? 1 : 0
    end
  end

# Helper function that determines whether the input values would make a female.
  def self.isFemale(b,genderRate)
    return true if genderRate==254    # AlwaysFemale
    return false if genderRate==255   # Genderless
    return b<=genderRate
  end

# Returns whether this Pokémon species is restricted to only ever being one
# gender (or genderless).
  def isSingleGendered?
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,@species,18)
    genderbyte=dexdata.fgetb
    dexdata.close
    return genderbyte==255 || genderbyte==254 || genderbyte==0
  end

# Returns whether this Pokémon is male.
  def isMale?
    return self.gender==0
  end

# Returns whether this Pokémon is female.
  def isFemale?
    return self.gender==1
  end

# Returns whether this Pokémon is genderless.
  def isGenderless?
    return self.gender==2
  end

# Sets this Pokémon's gender to a particular gender (if possible).
  def setGender(value)
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,@species,18)
    genderbyte=dexdata.fgetb
    dexdata.close
    if genderbyte!=255 && genderbyte!=0 && genderbyte!=254
      @genderflag=value
    end
  end

  def makeMale; setGender(0); end
  def makeFemale; setGender(1); end

################################################################################
# Ability
################################################################################
# Returns the index of this Pokémon's ability.
  def abilityIndex
    abil=@abilityflag!=nil ? @abilityflag : (@personalID&1)
    return abil
  end

# Returns the ID of this Pokémon's ability.
  def ability
    abil=abilityIndex
    abils=getAbilityList
    ret1=0; ret2=0
    for i in 0...abils.length
      next if !abils[i][0] || abils[i][0]<=0
      return abils[i][0] if abils[i][1]==abil
      ret1=abils[i][0] if abils[i][1]==0
      ret2=abils[i][0] if abils[i][1]==1
    end
    abil=(@personalID&1) if abil>=2
    return ret2 if abil==1 && ret2>0
    return ret1
  end

# Returns whether this Pokémon has a particular ability.
  def hasAbility?(value=0)
    if value==0
      return self.ability>0
    else
      if value.is_a?(String) || value.is_a?(Symbol)
        value=getID(PBAbilities,value)
      end
      return self.ability==value
    end
    return false
  end

# Sets this Pokémon's ability to a particular ability (if possible).
  def setAbility(value)
    @abilityflag=value
  end

  def hasHiddenAbility?
    abil=abilityIndex
    return abil!=nil && abil>=2
  end

# Returns the list of abilities this Pokémon can have.
  def getAbilityList
    abils=[]; ret=[]
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,2)
    abils.push(dexdata.fgetw)
    abils.push(dexdata.fgetw)
    pbDexDataOffset(dexdata,self.fSpecies,40)
    abils.push(dexdata.fgetw)
    abils.push(dexdata.fgetw)
    abils.push(dexdata.fgetw)
    abils.push(dexdata.fgetw)
    dexdata.close
    for i in 0...abils.length
      next if !abils[i] || abils[i]<=0
      ret.push([abils[i],i])
    end
    return ret
  end

################################################################################
# Nature
################################################################################
# Returns the ID of this Pokémon's nature.
  def nature
    return @natureflag if @natureflag!=nil
    return @personalID%25
  end

# Returns whether this Pokémon has a particular nature.
  def hasNature?(value=-1)
    if value<0
      return self.nature>=0
    else
      if value.is_a?(String) || value.is_a?(Symbol)
        value=getID(PBNatures,value)
      end
      return self.nature==value
    end
    return false
  end

# Sets this Pokémon's nature to a particular nature.
  def setNature(value)
    if value.is_a?(String) || value.is_a?(Symbol)
      value=getID(PBNatures,value)
    end
    @natureflag=value
    self.calcStats
  end

################################################################################
# Shininess
################################################################################
# Returns whether this Pokémon is shiny (differently colored).
  def isShiny?
    return @shinyflag if @shinyflag!=nil
    a=@personalID^@trainerID
    b=a&0xFFFF
    c=(a>>16)&0xFFFF
    d=b^c
    return (d<SHINYPOKEMONCHANCE)
  end

# Makes this Pokémon shiny.
  def makeShiny
    @shinyflag=true
  end

# Makes this Pokémon not shiny.
  def makeNotShiny
    @shinyflag=false
  end

################################################################################
# Pokérus
################################################################################
# Returns the full value of this Pokémon's Pokérus.
  def pokerus
    return @pokerus
  end

# Returns the Pokérus infection stage for this Pokémon.
  def pokerusStrain
    return @pokerus/16
  end

# Returns the Pokérus infection stage for this Pokémon.
  def pokerusStage
    return 0 if !@pokerus || @pokerus==0        # Not infected
    return 2 if @pokerus>0 && (@pokerus%16)==0  # Cured
    return 1                                    # Infected
  end

# Gives this Pokémon Pokérus (either the specified strain or a random one).
  def givePokerus(strain=0)
    return if self.pokerusStage==2 # Can't re-infect a cured Pokémon
    if strain<=0 || strain>=16
      strain=1+rand(15)
    end
    time=1+(strain%4)
    @pokerus=time
    @pokerus|=strain<<4
  end

# Resets the infection time for this Pokémon's Pokérus (even if cured).
  def resetPokerusTime
    return if @pokerus==0
    strain=@pokerus%16
    time=1+(strain%4)
    @pokerus=time
    @pokerus|=strain<<4
  end

# Reduces the time remaining for this Pokémon's Pokérus (if infected).
  def lowerPokerusCount
    return if self.pokerusStage!=1
    @pokerus-=1
  end

################################################################################
# Types
################################################################################
# Returns whether this Pokémon has the specified type.
  def hasType?(type)
    if type.is_a?(String) || type.is_a?(Symbol)
      return isConst?(self.type1,PBTypes,type) || isConst?(self.type2,PBTypes,type)
    else
      return self.type1==type || self.type2==type
    end
  end

# Returns this Pokémon's first type.
  def type1
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,8)
    ret=dexdata.fgetb
    dexdata.close
    return ret
  end

# Returns this Pokémon's second type.
  def type2
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,9)
    ret=dexdata.fgetb
    dexdata.close
    return ret
  end

################################################################################
# Moves
################################################################################
# Returns the number of moves known by the Pokémon.
  def numMoves
    ret=0
    for i in 0...4
      ret+=1 if @moves[i].id!=0
    end
    return ret
  end

# Returns true if the Pokémon knows the given move.
  def hasMove?(move)
    if move.is_a?(String) || move.is_a?(Symbol)
      move=getID(PBMoves,move)
    end
    return false if !move || move<=0
    for i in 0...4
      return true if @moves[i].id==move
    end
    return false
  end

  def knowsMove?(move); return self.hasMove?(move); end

# Returns the list of moves this Pokémon can learn by levelling up.
  def getMoveList
    movelist=[]
    atkdata=pbRgssOpen("Data/attacksRS.dat","rb")
    offset=atkdata.getOffset(self.fSpecies-1)
    length=atkdata.getLength(self.fSpecies-1)>>1
    atkdata.pos=offset
    for k in 0..length-1
      level=atkdata.fgetw
      move=atkdata.fgetw
      movelist.push([level,move])
    end
    atkdata.close
    return movelist
  end

# Sets this Pokémon's movelist to the default movelist it originally had.
  def resetMoves
    moves=self.getMoveList
    movelist=[]
    for i in moves
      if i[0]<=self.level
        movelist[movelist.length]=i[1]
      end
    end
    movelist|=[] # Remove duplicates
    listend=movelist.length-4
    listend=0 if listend<0
    j=0
    for i in listend...listend+4
      moveid=(i>=movelist.length) ? 0 : movelist[i]
      @moves[j]=PBMove.new(moveid)
      j+=1
    end
  end

# Silently learns the given move. Will erase the first known move if it has to.
  def pbLearnMove(move)
    if move.is_a?(String) || move.is_a?(Symbol)
      move=getID(PBMoves,move)
    end
    return if move<=0
    for i in 0...4
      if @moves[i].id==move
        j=i+1; while j<4
          break if @moves[j].id==0
          tmp=@moves[j]
          @moves[j]=@moves[j-1]
          @moves[j-1]=tmp
          j+=1
        end
        return
      end
    end
    for i in 0...4
      if @moves[i].id==0
        @moves[i]=PBMove.new(move)
        return
      end
    end
    @moves[0]=@moves[1]
    @moves[1]=@moves[2]
    @moves[2]=@moves[3]
    @moves[3]=PBMove.new(move)
  end

# Deletes the given move from the Pokémon.
  def pbDeleteMove(move)
    if move.is_a?(String) || move.is_a?(Symbol)
      move=getID(PBMoves,move)
    end
    return if !move || move<=0
    newmoves=[]
    for i in 0...4
      newmoves.push(@moves[i]) if @moves[i].id!=move
    end
    newmoves.push(PBMove.new(0))
    for i in 0...4
      @moves[i]=newmoves[i]
    end
  end

# Deletes the move at the given index from the Pokémon.
  def pbDeleteMoveAtIndex(index)
    newmoves=[]
    for i in 0...4
      newmoves.push(@moves[i]) if i!=index
    end
    newmoves.push(PBMove.new(0))
    for i in 0...4
      @moves[i]=newmoves[i]
    end
  end

# Deletes all moves from the Pokémon.
  def pbDeleteAllMoves
    for i in 0...4
      @moves[i]=PBMove.new(0)
    end
  end

# Copies currently known moves into a separate array, for Move Relearner.
  def pbRecordFirstMoves
    @firstmoves=[]
    for i in 0...4
      @firstmoves.push(@moves[i].id) if @moves[i].id>0
    end
  end

  def pbAddFirstMove(move)
    move = getID(PBMoves,move) if !move.is_a?(Integer)
    @firstmoves.push(move) if move>0 && !@firstmoves.include?(move)
  end

  def pbRemoveFirstMove(move)
    move = getID(PBMoves,move) if !move.is_a?(Integer)
    @firstmoves.delete(move) if move>0
  end

  def pbClearFirstMoves
    @firstmoves = []
  end

  def isCompatibleWithMove?(move)
    return pbSpeciesCompatible?(self.species,move)
  end

################################################################################
# Contest attributes, ribbons
################################################################################
  def cool; @cool ? @cool : 0; end
  def beauty; @beauty ? @beauty : 0; end
  def cute; @cute ? @cute : 0; end
  def smart; @smart ? @smart : 0; end
  def tough; @tough ? @tough : 0; end
  def sheen; @sheen ? @sheen : 0; end

# Returns the number of ribbons this Pokémon has.
  def ribbonCount
    @ribbons=[] if !@ribbons
    return @ribbons.length
  end

# Returns whether this Pokémon has the specified ribbon.
  def hasRibbon?(ribbon)
    @ribbons=[] if !@ribbons
    ribbon=getID(PBRibbons,ribbon) if !ribbon.is_a?(Integer)
    return false if ribbon==0
    return @ribbons.include?(ribbon)
  end

# Gives this Pokémon the specified ribbon.
  def giveRibbon(ribbon)
    @ribbons=[] if !@ribbons
    ribbon=getID(PBRibbons,ribbon) if !ribbon.is_a?(Integer)
    return if ribbon==0
    @ribbons.push(ribbon) if !@ribbons.include?(ribbon)
  end

# Replaces one ribbon with the next one along, if possible.
  def upgradeRibbon(*arg)
    @ribbons=[] if !@ribbons
    for i in 0...arg.length-1
      for j in 0...@ribbons.length
        thisribbon=(arg[i].is_a?(Integer)) ? arg[i] : getID(PBRibbons,arg[i])
        if @ribbons[j]==thisribbon
          nextribbon=(arg[i+1].is_a?(Integer)) ? arg[i+1] : getID(PBRibbons,arg[i+1])
          @ribbons[j]=nextribbon
          return nextribbon
        end
      end
    end
    if !hasRibbon?(arg[arg.length-1])
      firstribbon=(arg[0].is_a?(Integer)) ? arg[0] : getID(PBRibbons,arg[0])
      giveRibbon(firstribbon)
      return firstribbon
    end
    return 0
  end

# Removes the specified ribbon from this Pokémon.
  def takeRibbon(ribbon)
    return if !@ribbons
    ribbon=getID(PBRibbons,ribbon) if !ribbon.is_a?(Integer)
    return if ribbon==0
    for i in 0...@ribbons.length
      if @ribbons[i]==ribbon
        @ribbons[i]=nil; break
      end
    end
    @ribbons.compact!
  end

# Removes all ribbons from this Pokémon.
  def clearAllRibbons
    @ribbons=[]
  end

################################################################################
# Items
################################################################################
# Returns whether this Pokémon has a hold item.
  def hasItem?(value=0)
    if value==0
      return self.item>0
    else
      if value.is_a?(String) || value.is_a?(Symbol)
        value=getID(PBItems,value)
      end
      return self.item==value
    end
    return false
  end

# Sets this Pokémon's item. Accepts symbols.
  def setItem(value)
    if value.is_a?(String) || value.is_a?(Symbol)
      value=getID(PBItems,value)
    end
    self.item=value
  end

# Returns the items this species can be found holding in the wild.
  def wildHoldItems
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,48)
    itemcommon=dexdata.fgetw
    itemuncommon=dexdata.fgetw
    itemrare=dexdata.fgetw
    dexdata.close
    return [itemcommon || 0,itemuncommon || 0,itemrare || 0]
  end

# Returns this Pokémon's mail.
  def mail
    return nil if !@mail
    if @mail.item==0 || !self.hasItem? || @mail.item!=self.item
      @mail=nil
      return nil
    end
    return @mail
  end

################################################################################
# Other
################################################################################
# Returns the species name of this Pokémon.
  def speciesName
    return PBSpecies.getName(@species)
  end

# Returns this Pokémon's language.
  def language; @language ? @language : 0; end

# Returns the markings this Pokémon has.
  def markings
    @markings=0 if !@markings
    return @markings
  end

# Returns a string stating the Unown form of this Pokémon.
  def unownShape
    return "ABCDEFGHIJKLMNOPQRSTUVWXYZ?!"[@form,1]
  end

# Returns the height of this Pokémon.
  def height
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,33)
    height=dexdata.fgetw
    dexdata.close
    return height
  end

# Returns the weight of this Pokémon.
  def weight
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,35)
    weight=dexdata.fgetw
    dexdata.close
    return weight
  end

# Returns the EV yield of this Pokémon.
  def evYield
    ret=[]
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,23)
    for i in 0...6
      v=dexdata.fgetb
      v=0 if !v
      ret.push(v)
    end
    dexdata.close
    return ret
  end

# Sets this Pokémon's HP.
  def hp=(value)
    value=0 if value<0
    @hp=value
    if @hp==0
      @status=0
      @statusCount=0
    end
  end

  def fainted?
    return !egg? && @hp<=0
  end

  alias isFainted? fainted?

# Heals all HP of this Pokémon.
  def healHP
    return if egg?
    @hp=@totalhp
  end

# Heals the status problem of this Pokémon.
  def healStatus
    return if egg?
    @status=0
    @statusCount=0
  end

# Heals all PP of this Pokémon.
  def healPP(index=-1)
    return if egg?
    if index>=0
      @moves[index].pp=@moves[index].totalpp
    else
      for i in 0...4
        @moves[i].pp=@moves[i].totalpp
      end
    end
  end

# Heals all HP, PP, and status problems of this Pokémon.
  def heal
    return if egg?
    healHP
    healStatus
    healPP
  end

# Changes the happiness of this Pokémon depending on what happened to change it.
  def changeHappiness(method)
    gain=0; luxury=false
    case method
    when "walking"
      gain=1
      gain+=1 if @happiness<200
      gain+=1 if @obtainMap==$game_map.map_id
      luxury=true
    when "levelup"
      gain=2
      gain=3 if @happiness<200
      gain=5 if @happiness<100
      luxury=true
    when "groom"
      gain=4
      gain=10 if @happiness<200
      luxury=true
    when "faint"
      gain=-1
    when "vitamin"
      gain=2
      gain=3 if @happiness<200
      gain=5 if @happiness<100
    when "evberry"
      gain=2
      gain=5 if @happiness<200
      gain=10 if @happiness<100
    when "powder"
      gain=-10
      gain=-5 if @happiness<200
    when "energyroot"
      gain=-15
      gain=-10 if @happiness<200
    when "revivalherb"
      gain=-20
      gain=-15 if @happiness<200
    else
      Kernel.pbMessage(_INTL("Unknown happiness-changing method."))
    end
    gain+=1 if luxury && self.ballused==pbGetBallType(:LUXURYBALL)
    if isConst?(self.item,PBItems,:SOOTHEBELL) && gain>0
      gain=(gain*1.5).floor
    end
    @happiness+=gain
    @happiness=[[255,@happiness].min,0].max
  end

################################################################################
# Stat calculations, Pokémon creation
################################################################################
# Returns this Pokémon's base stats.  An array of six values.
  def baseStats
    dexdata=pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,10)
    ret=[
       dexdata.fgetb, # HP
       dexdata.fgetb, # Attack
       dexdata.fgetb, # Defense
       dexdata.fgetb, # Speed
       dexdata.fgetb, # Special Attack
       dexdata.fgetb  # Special Defense
    ]
    dexdata.close
    return ret
  end

# Returns the maximum HP of this Pokémon.
  def calcHP(base,level,iv,ev)
    return 1 if base==1
    return ((base*2+iv+(ev>>2))*level/100).floor+level+10
  end

# Returns the specified stat of this Pokémon (not used for total HP).
  def calcStat(base,level,iv,ev,pv)
    return ((((base*2+iv+(ev>>2))*level/100).floor+5)*pv/100).floor
  end

# Recalculates this Pokémon's stats.
  def calcStats
    nature=self.nature
    stats=[]
    pvalues=[100,100,100,100,100]
    nd5=(nature/5).floor
    nm5=(nature%5).floor
    if nd5!=nm5
      pvalues[nd5]=110
      pvalues[nm5]=90
    end
    level=self.level
    bs=self.baseStats
    for i in 0..5
      if @wake[i]!=0
        # overwrite IVs in calcStats formula
        for j in 0..5
        base=bs[i]
          if i==PBStats::HP
            stats[i]=calcHP(base,level,@wake[j],@ev[i])
          else
            stats[i]=calcStat(base,level,@wake[j],@ev[i],pvalues[i-1])
          end
        end
      else
        for j in 0..5
        base=bs[i]
          if i==PBStats::HP
            stats[i]=calcHP(base,level,@iv[j],@ev[i])
          else
            stats[i]=calcStat(base,level,@iv[j],@ev[i],pvalues[i-1])
          end
        end
      end
    end
    diff=@totalhp-@hp
    @totalhp=stats[0]
    @hp=@totalhp-diff
    @hp=0 if @hp<=0
    @hp=@totalhp if @hp>@totalhp
    @attack=stats[1]
    @defense=stats[2]
    @speed=stats[3]
    @spatk=stats[4]
    @spdef=stats[5]
  end

# Creates a new Pokémon object.
#    species   - Pokémon species.
#    level     - Pokémon level.
#    player    - PokeBattle_Trainer object for the original trainer.
#    withMoves - If false, this Pokémon has no moves.
  def initialize(species,level,player=nil,withMoves=true)
    if species.is_a?(String) || species.is_a?(Symbol)
      species = getID(PBSpecies,species)
    end
    cname = getConstantName(PBSpecies,species) rescue nil
    if !species || species<1 || species>PBSpecies.maxValue || !cname
      raise ArgumentError.new(_INTL("The species number (no. {1} of {2}) is invalid.",species,PBSpecies.maxValue))
      return nil
    end
    # Ditto
    @special       = false
    @species       = species
    @name          = PBSpecies.getName(@species)
    @personalID    = rand(256)
    @personalID    |= rand(256)<<8
    @personalID    |= rand(256)<<16
    @personalID    |= rand(256)<<24
    @hp            = 1
    @totalhp       = 1
    @ev            = [0,0,0,0,0,0]
    @iv            = []
    for i in 0...6
      @iv[i]       = rand(32)
    end
    @wake          = [0,0,0,0,0,0]
    @moves         = []
    @status        = 0
    @statusCount   = 0
    @item          = 0
    @mail          = nil
    @fused         = nil
    @ribbons       = []
    @ballused      = 0
    @eggsteps      = 0
    if player
      @trainerID   = player.id
      @ot          = player.name
      @otgender    = player.gender
      @language    = player.language
    else
      @trainerID   = 0
      @ot          = ""
      @otgender    = 2
    end
    if $game_map
      @obtainMap   = $game_map.map_id
      @obtainText  = nil
      @obtainLevel = level
    else
      @obtainMap   = 0
      @obtainText  = nil
      @obtainLevel = level
    end
    @obtainMode    = 0   # Met
    @obtainMode    = 4 if $game_switches && $game_switches[FATEFUL_ENCOUNTER_SWITCH]
    @hatchedMap    = 0
    @timeReceived  = pbGetTimeNow.to_i
    self.level     = level
    calcStats
    @hp            = @totalhp
    dexdata = pbOpenDexData
    pbDexDataOffset(dexdata,self.fSpecies,19)
    @happiness     = dexdata.fgetb
    dexdata.close
    if withMoves
      self.resetMoves
    else
      for i in 0...4
        @moves[i] = PBMove.new(0)
      end
    end
  end
end



def pbGenPkmn(species,level,owner=nil)
  owner = $Trainer if !owner
  return PokeBattle_Pokemon.new(species,level,owner)
end

def pbGenPoke(species,level,owner=nil); return pbGenPkmn(species,level,owner); end

Ruby:
#===============================================================================
# Heart symbol for starter Pokémon (used in the party screen)
#===============================================================================
class StarterIconSprite < SpriteWrapper
  def initialize(x,y,pokemon,viewport=nil)
    super(viewport)
    self.x = x
    self.y = y
    @pokemon = pokemon
    @special = 0
    self.special = @pokemon.special
  end

  def pokemon=(value)
    @pokemon = value
    self.special = @pokemon.special
  end

  def special=(value)
    return if @special==value
    @special = value
    @animbitmap.dispose if @animbitmap
    @animbitmap = nil
    if @special && @special==true
      @animbitmap = AnimatedBitmap.new(pbStarterIconFile)
      self.bitmap = @animbitmap.bitmap
    else
      self.bitmap = nil
    end
  end

  def dispose
    @animbitmap.dispose if @animbitmap
    super
  end

  def update
    super
    self.special = @pokemon.special
    if @animbitmap
      @animbitmap.update
      self.bitmap = @animbitmap.bitmap
    end
  end
end

def pbStarterIconFile   # Used in the party screen
  bitmapFileName = sprintf("Graphics/Pictures/Party/icon_heart")
  return bitmapFileName
end

def pbHeldItemIconFile(item)   # Used in the party screen
  return nil if !item || item==0
  if pbIsMail?(item)
    namebase = "mail"
  elsif pbIsMegaStone?(item)
    namebase = "mega"
  # Uncomment this part if using Amethyst's Z-Move add-on
  #elsif pbIsZCrystal?(item) || pbIsZCrystal2?(item)
  #  namebase = "z_crystal"
  else
    namebase = "item"
  end
  bitmapFileName = sprintf("Graphics/Pictures/Party/icon_%s_%s",namebase,getConstantName(PBItems,item)) rescue nil
  if !pbResolveBitmap(bitmapFileName)
    bitmapFileName = sprintf("Graphics/Pictures/Party/icon_%s_%03d",namebase,item)
    if !pbResolveBitmap(bitmapFileName)
      bitmapFileName = sprintf("Graphics/Pictures/Party/icon_%s",namebase)
    end
  end
  return bitmapFileName
end

def easyItemType(item)
  type=0
  type=1 if pbIsMail?(item)
  type=2 if pbIsMegaStone?(item)
  # Uncomment this part if using Amethyst's Z-Move add-on
  #type=3 if pbIsZCrystal?(item) || pbIsZCrystal2?(item)
  return type
end

#===============================================================================
# Item held icon (used in the party screen)
#===============================================================================
class HeldItemIconSprite < SpriteWrapper
  def initialize(x,y,pokemon,viewport=nil)
    super(viewport)
    self.x = x
    self.y = y
    @pokemon = pokemon
    @item = 0
    self.item = @pokemon.item
    @mode = 0 # 0=item; 1=mail; 2=mega; 3=zcrystal
    @mode=easyItemType(@pokemon.item)
  end

  def mode
    return @mode
  end

  def pokemon=(value)
    @pokemon = value
    self.item = @pokemon.item
  end

  def item=(value)
    return if @item==value
    @item = value
    @animbitmap.dispose if @animbitmap
    @animbitmap = nil
    if @item && @item>0
      @animbitmap = AnimatedBitmap.new(pbHeldItemIconFile(value))
      self.bitmap = @animbitmap.bitmap
    else
      self.bitmap = nil
    end
  end

  def dispose
    @animbitmap.dispose if @animbitmap
    super
  end

  def update
    super
    self.item = @pokemon.item
    if @animbitmap
      @animbitmap.update
      self.bitmap = @animbitmap.bitmap
    end
  end
end
#===============================================================================
# Pokémon party buttons and menu
#===============================================================================
class PokemonPartyConfirmCancelSprite < SpriteWrapper
  attr_reader :selected

  def initialize(text,x,y,narrowbox=false,viewport=nil)
    super(viewport)
    @refreshBitmap = true
    @bgsprite = ChangelingSprite.new(0,0,viewport)
    if narrowbox
      @bgsprite.addBitmap("desel","Graphics/Pictures/Party/icon_cancel_narrow")
      @bgsprite.addBitmap("sel","Graphics/Pictures/Party/icon_cancel_narrow_sel")
    else
      @bgsprite.addBitmap("desel","Graphics/Pictures/Party/icon_cancel")
      @bgsprite.addBitmap("sel","Graphics/Pictures/Party/icon_cancel_sel")
    end
    @bgsprite.changeBitmap("desel")
    @overlaysprite = BitmapSprite.new(@bgsprite.bitmap.width,@bgsprite.bitmap.height,viewport)
    @overlaysprite.z = self.z+1
    pbSetSystemFont(@overlaysprite.bitmap)
    @yoffset = 8
    textpos = [[text,56,(narrowbox) ? 2 : 8,2,Color.new(248,248,248),Color.new(40,40,40)]]
    pbDrawTextPositions(@overlaysprite.bitmap,textpos)
    self.x = x
    self.y = y
  end

  def dispose
    @bgsprite.dispose
    @overlaysprite.bitmap.dispose
    @overlaysprite.dispose
    super
  end

  def viewport=(value)
    super
    refresh
  end

  def x=(value)
    super
    refresh
  end

  def y=(value)
    super
    refresh
  end

  def color=(value)
    super
    refresh
  end

  def selected=(value)
    if @selected!=value
      @selected = value
      refresh
    end
  end

  def refresh
    if @bgsprite && !@bgsprite.disposed?
      @bgsprite.changeBitmap((@selected) ? "sel" : "desel")
      @bgsprite.x     = self.x
      @bgsprite.y     = self.y
      @bgsprite.color = self.color
    end
    if @overlaysprite && !@overlaysprite.disposed?
      @overlaysprite.x     = self.x
      @overlaysprite.y     = self.y
      @overlaysprite.color = self.color
    end
  end
end



class PokemonPartyCancelSprite < PokemonPartyConfirmCancelSprite
  def initialize(viewport=nil)
    super(_INTL("CANCEL"),398,328,false,viewport)
  end
end



class PokemonPartyConfirmSprite < PokemonPartyConfirmCancelSprite
  def initialize(viewport=nil)
    super(_INTL("CONFIRM"),398,308,true,viewport)
  end
end



class PokemonPartyCancelSprite2 < PokemonPartyConfirmCancelSprite
  def initialize(viewport=nil)
    super(_INTL("CANCEL"),398,346,true,viewport)
  end
end



class Window_CommandPokemonColor < Window_CommandPokemon
  def initialize(commands,width=nil)
    @colorKey = []
    for i in 0...commands.length
      if commands[i].is_a?(Array)
        @colorKey[i] = commands[i][1]
        commands[i] = commands[i][0]
      end
    end
    super(commands,width)
  end

  def drawItem(index,count,rect)
    pbSetSystemFont(self.contents) if @starting
    rect = drawCursor(index,rect)
    base   = self.baseColor
    shadow = self.shadowColor
    if @colorKey[index] && @colorKey[index]==1
      base   = Color.new(0,80,160)
      shadow = Color.new(128,192,240)
    end
    pbDrawShadowText(self.contents,rect.x,rect.y,rect.width,rect.height,@commands[index],base,shadow)
  end
end



#===============================================================================
# Pokémon party panels
#===============================================================================
class PokemonPartyBlankPanel < SpriteWrapper
  attr_accessor :text

  def initialize(pokemon,index,viewport=nil)
    super(viewport)
    self.x = [0,256,0,256,0,256][index]
    self.y = [0,16,96,112,192,208][index]
    @panelbgsprite = AnimatedBitmap.new("Graphics/Pictures/Party/panel_blank")
    self.bitmap = @panelbgsprite.bitmap
    @text = nil
  end

  def dispose
    @panelbgsprite.dispose
    super
  end

  def selected; return false; end
  def selected=(value); end
  def preselected; return false; end
  def preselected=(value); end
  def switching; return false; end
  def switching=(value); end
  def refresh; end
end



class PokemonPartyPanel < SpriteWrapper
  attr_reader :pokemon
  attr_reader :active
  attr_reader :selected
  attr_reader :preselected
  attr_reader :switching
  attr_accessor :text

  def initialize(pokemon,index,viewport=nil)
    super(viewport)
    @pokemon = pokemon
    @active = (index==0)   # true = rounded panel, false = rectangular panel
    @refreshing = true
    self.x = [0,256,0,256,0,256][index]
    self.y = [0,16,96,112,192,208][index]
    @panelbgsprite = ChangelingSprite.new(0,0,viewport)
    @panelbgsprite.z = self.z
    if @active   # Rounded panel
      @panelbgsprite.addBitmap("able","Graphics/Pictures/Party/panel_round")
      @panelbgsprite.addBitmap("ablesel","Graphics/Pictures/Party/panel_round_sel")
      @panelbgsprite.addBitmap("fainted","Graphics/Pictures/Party/panel_round_faint")
      @panelbgsprite.addBitmap("faintedsel","Graphics/Pictures/Party/panel_round_faint_sel")
      @panelbgsprite.addBitmap("swap","Graphics/Pictures/Party/panel_round_swap")
      @panelbgsprite.addBitmap("swapsel","Graphics/Pictures/Party/panel_round_swap_sel")
      @panelbgsprite.addBitmap("swapsel2","Graphics/Pictures/Party/panel_round_swap_sel2")
    else   # Rectangular panel
      @panelbgsprite.addBitmap("able","Graphics/Pictures/Party/panel_rect")
      @panelbgsprite.addBitmap("ablesel","Graphics/Pictures/Party/panel_rect_sel")
      @panelbgsprite.addBitmap("fainted","Graphics/Pictures/Party/panel_rect_faint")
      @panelbgsprite.addBitmap("faintedsel","Graphics/Pictures/Party/panel_rect_faint_sel")
      @panelbgsprite.addBitmap("swap","Graphics/Pictures/Party/panel_rect_swap")
      @panelbgsprite.addBitmap("swapsel","Graphics/Pictures/Party/panel_rect_swap_sel")
      @panelbgsprite.addBitmap("swapsel2","Graphics/Pictures/Party/panel_rect_swap_sel2")
    end
    @hpbgsprite = ChangelingSprite.new(0,0,viewport)
    @hpbgsprite.z = self.z+1
    @hpbgsprite.addBitmap("able","Graphics/Pictures/Party/overlay_hp_back")
    @hpbgsprite.addBitmap("fainted","Graphics/Pictures/Party/overlay_hp_back_faint")
    @hpbgsprite.addBitmap("swap","Graphics/Pictures/Party/overlay_hp_back_swap")
    @ballsprite = ChangelingSprite.new(0,0,viewport)
    @ballsprite.z = self.z+1
    @ballsprite.addBitmap("desel","Graphics/Pictures/Party/icon_ball")
    @ballsprite.addBitmap("sel","Graphics/Pictures/Party/icon_ball_sel")
    @pkmnsprite = PokemonIconSprite.new(pokemon,viewport)
    @pkmnsprite.active = @active
    @pkmnsprite.z      = self.z+2
    @helditemsprite = HeldItemIconSprite.new(0,0,@pokemon,viewport)
    @mode=@helditemsprite.mode
    @helditemsprite.z = self.z+3
    @overlaysprite = BitmapSprite.new(Graphics.width,Graphics.height,viewport)
    @overlaysprite.z = self.z+4
    # New
    @startersprite = StarterIconSprite.new(0,0,@pokemon,viewport)
    @startersprite.z = self.z+5
  
    @hpbar    = AnimatedBitmap.new("Graphics/Pictures/Party/overlay_hp")
    @statuses = AnimatedBitmap.new(_INTL("Graphics/Pictures/statuses"))
    @selected      = false
    @preselected   = false
    @switching     = false
    @text          = nil
    @refreshBitmap = true
    @refreshing    = false
    refresh
  end

  def dispose
    @panelbgsprite.dispose
    @hpbgsprite.dispose
    @ballsprite.dispose
    @pkmnsprite.dispose
    @helditemsprite.dispose
    @overlaysprite.bitmap.dispose
    @overlaysprite.dispose
#@startersprite.bitmap.dispose
    @startersprite.dispose
    @hpbar.dispose
    @statuses.dispose
    super
  end

  def x=(value)
    super
    refresh
  end

  def y=(value)
    super
    refresh
  end

  def color=(value)
    super
    refresh
  end

  def text=(value)
    if @text!=value
      @text = value
      @refreshBitmap = true
      refresh
    end
  end

  def pokemon=(value)
    @pokemon = value
    @pkmnsprite.pokemon = value if @pkmnsprite && !@pkmnsprite.disposed?
    @helditemsprite.pokemon = value if @helditemsprite && !@helditemsprite.disposed?
    @startersprite.pokemon = value if @startersprite && !@startersprite.disposed?
    @refreshBitmap = true
    refresh
  end

  def selected=(value)
    if @selected!=value
      @selected = value
      refresh
    end
  end

  def preselected=(value)
    if @preselected!=value
      @preselected = value
      refresh
    end
  end

  def switching=(value)
    if @switching!=value
      @switching = value
      refresh
    end
  end

  def hp; return @pokemon.hp; end

  def refresh
    return if disposed?
    return if @refreshing
    @refreshing = true
    if @panelbgsprite && !@panelbgsprite.disposed?
      if self.selected
        if self.preselected;     @panelbgsprite.changeBitmap("swapsel2")
        elsif @switching;        @panelbgsprite.changeBitmap("swapsel")
        elsif @pokemon.fainted?; @panelbgsprite.changeBitmap("faintedsel")
        else;                    @panelbgsprite.changeBitmap("ablesel")
        end
      else
        if self.preselected;     @panelbgsprite.changeBitmap("swap")
        elsif @pokemon.fainted?; @panelbgsprite.changeBitmap("fainted")
        else;                    @panelbgsprite.changeBitmap("able")
        end
      end
      @panelbgsprite.x     = self.x
      @panelbgsprite.y     = self.y
      @panelbgsprite.color = self.color
    end
    if @hpbgsprite && !@hpbgsprite.disposed?
      @hpbgsprite.visible = (!@pokemon.egg? && !(@text && @text.length>0))
      if @hpbgsprite.visible
        if self.preselected || (self.selected && @switching); @hpbgsprite.changeBitmap("swap")
        elsif @pokemon.fainted?;                              @hpbgsprite.changeBitmap("fainted")
        else;                                                 @hpbgsprite.changeBitmap("able")
        end
        @hpbgsprite.x     = self.x+96
        @hpbgsprite.y     = self.y+50
        @hpbgsprite.color = self.color
      end
    end
    if @ballsprite && !@ballsprite.disposed?
      @ballsprite.changeBitmap((self.selected) ? "sel" : "desel")
      @ballsprite.x     = self.x+10
      @ballsprite.y     = self.y
      @ballsprite.color = self.color
    end
    if @pkmnsprite && !@pkmnsprite.disposed?
      @pkmnsprite.x        = self.x+28
      @pkmnsprite.y        = self.y
      @pkmnsprite.color    = self.color
      @pkmnsprite.selected = self.selected
    end
    if @helditemsprite && !@helditemsprite.disposed?
      if @helditemsprite.visible
        if @mode==0 # item
          @helditemsprite.x     = self.x+62
          @helditemsprite.y     = self.y+48
        elsif @mode==1 # mail
          @helditemsprite.x     = self.x+62
          @helditemsprite.y     = self.y+48
        elsif @mode==2 # mega stone
          @helditemsprite.x     = self.x+62
          @helditemsprite.y     = self.y+48-4*2
        # Uncomment this part if using Amethyst's Z-Move add-on
        #elsif @mode==3 # z-crystal
          #@helditemsprite.x     = self.x+62
          #@helditemsprite.y     = self.y+48-2
        end
        @helditemsprite.color = self.color
      end
    end
    if @overlaysprite && !@overlaysprite.disposed?
      @overlaysprite.x     = self.x
      @overlaysprite.y     = self.y
      @overlaysprite.color = self.color
    end
    if @startersprite && !@startersprite.disposed?
      if @startersprite.visible
        @startersprite.x     = self.x+62-62+18*2
        @startersprite.y     = self.y+48-2*2
        @startersprite.color = self.color
      end
    end
    if @refreshBitmap
      @refreshBitmap = false
      @overlaysprite.bitmap.clear if @overlaysprite.bitmap
      basecolor   = Color.new(248,248,248)
      shadowcolor = Color.new(40,40,40)
      pbSetSystemFont(@overlaysprite.bitmap)
      textpos = []
      # Draw Pokémon name
      textpos.push([@pokemon.name,96,16,0,basecolor,shadowcolor])
      if !@pokemon.egg?
        if !@text || @text.length==0
          # Draw HP numbers
          textpos.push([sprintf("% 3d /% 3d",@pokemon.hp,@pokemon.totalhp),224,60,1,basecolor,shadowcolor])
          # Draw HP bar
          if @pokemon.hp>0
            hpzone = 0
            hpzone = 1 if @pokemon.hp<=(@pokemon.totalhp/2).floor
            hpzone = 2 if @pokemon.hp<=(@pokemon.totalhp/4).floor
            hprect = Rect.new(0,hpzone*8,[@pokemon.hp*96/@pokemon.totalhp,2].max,8)
            @overlaysprite.bitmap.blt(128,52,@hpbar.bitmap,hprect)
          end
          # Draw status
          status = -1
          status = 6 if @pokemon.pokerusStage==1
          status = @pokemon.status-1 if @pokemon.status>0
          status = 5 if @pokemon.hp<=0
          if status>=0
            statusrect = Rect.new(0,16*status,44,16)
            @overlaysprite.bitmap.blt(78,68,@statuses.bitmap,statusrect)
          end
        end
        # Draw gender icon
        if @pokemon.isMale?
          textpos.push([_INTL("♂"),224,16,0,Color.new(0,112,248),Color.new(120,184,232)])
        elsif @pokemon.isFemale?
          textpos.push([_INTL("♀"),224,16,0,Color.new(232,32,16),Color.new(248,168,184)])
        end
      end
      pbDrawTextPositions(@overlaysprite.bitmap,textpos)
      # Draw level text
      if !@pokemon.egg?
        pbDrawImagePositions(@overlaysprite.bitmap,[[
           "Graphics/Pictures/Party/overlay_lv",20,70,0,0,22,14]])
        pbSetSmallFont(@overlaysprite.bitmap)
        pbDrawTextPositions(@overlaysprite.bitmap,[
           [@pokemon.level.to_s,42,62,0,basecolor,shadowcolor]
        ])
      end
      # Draw annotation text
      if @text && @text.length>0
        pbSetSystemFont(@overlaysprite.bitmap)
        pbDrawTextPositions(@overlaysprite.bitmap,[
           [@text,96,58,0,basecolor,shadowcolor]
        ])
      end
    end
    @refreshing = false
  end

  def update
    super
    @panelbgsprite.update if @panelbgsprite && !@panelbgsprite.disposed?
    @hpbgsprite.update if @hpbgsprite && !@hpbgsprite.disposed?
    @ballsprite.update if @ballsprite && !@ballsprite.disposed?
    @pkmnsprite.update if @pkmnsprite && !@pkmnsprite.disposed?
    @helditemsprite.update if @helditemsprite && !@helditemsprite.disposed?
    @startersprite.update if @startersprite && !@startersprite.disposed?
  end
end



#===============================================================================
# Pokémon party visuals
#===============================================================================
class PokemonParty_Scene
  def pbStartScene(party,starthelptext,annotations=nil,multiselect=false)
    @sprites = {}
    @party = party
    @viewport = Viewport.new(0,0,Graphics.width,Graphics.height)
    @viewport.z = 99999
    @multiselect = multiselect
    addBackgroundPlane(@sprites,"partybg","Party/bg",@viewport)
    @sprites["messagebox"] = Window_AdvancedTextPokemon.new("")
    @sprites["messagebox"].viewport       = @viewport
    @sprites["messagebox"].visible        = false
    @sprites["messagebox"].letterbyletter = true
    pbBottomLeftLines(@sprites["messagebox"],2)
    @sprites["helpwindow"] = Window_UnformattedTextPokemon.new(starthelptext)
    @sprites["helpwindow"].viewport = @viewport
    @sprites["helpwindow"].visible  = true
    pbBottomLeftLines(@sprites["helpwindow"],1)
    pbSetHelpText(starthelptext)
    # Add party Pokémon sprites
    for i in 0...6
      if @party[i]
        @sprites["pokemon#{i}"] = PokemonPartyPanel.new(@party[i],i,@viewport)
      else
        @sprites["pokemon#{i}"] = PokemonPartyBlankPanel.new(@party[i],i,@viewport)
      end
      @sprites["pokemon#{i}"].text = annotations[i] if annotations
    end
    if @multiselect
      @sprites["pokemon6"] = PokemonPartyConfirmSprite.new(@viewport)
      @sprites["pokemon7"] = PokemonPartyCancelSprite2.new(@viewport)
    else
      @sprites["pokemon6"] = PokemonPartyCancelSprite.new(@viewport)
    end
    # Select first Pokémon
    @activecmd = 0
    @sprites["pokemon0"].selected = true
    pbFadeInAndShow(@sprites) { update }
  end

  def pbEndScene
    pbFadeOutAndHide(@sprites) { update }
    pbDisposeSpriteHash(@sprites)
    @viewport.dispose
  end

  def pbDisplay(text)
    @sprites["messagebox"].text    = text
    @sprites["messagebox"].visible = true
    @sprites["helpwindow"].visible = false
    pbPlayDecisionSE
    loop do
      Graphics.update
      Input.update
      self.update
      if @sprites["messagebox"].busy?
        if Input.trigger?(Input::C)
          pbPlayDecisionSE if @sprites["messagebox"].pausing?
          @sprites["messagebox"].resume
        end
      else
        if Input.trigger?(Input::B) || Input.trigger?(Input::C)
          break
        end
      end
    end
    @sprites["messagebox"].visible = false
    @sprites["helpwindow"].visible = true
  end

  def pbDisplayConfirm(text)
    ret = -1
    @sprites["messagebox"].text    = text
    @sprites["messagebox"].visible = true
    @sprites["helpwindow"].visible = false
    using(cmdwindow = Window_CommandPokemon.new([_INTL("Yes"),_INTL("No")])) {
      cmdwindow.visible = false
      pbBottomRight(cmdwindow)
      cmdwindow.y -= @sprites["messagebox"].height
      cmdwindow.z = @viewport.z+1
      loop do
        Graphics.update
        Input.update
        cmdwindow.visible = true if !@sprites["messagebox"].busy?
        cmdwindow.update
        self.update
        if !@sprites["messagebox"].busy?
          if Input.trigger?(Input::B)
            ret = false
            break
          elsif Input.trigger?(Input::C) && @sprites["messagebox"].resume
            ret = (cmdwindow.index==0)
            break
          end
        end
      end
    }
    @sprites["messagebox"].visible = false
    @sprites["helpwindow"].visible = true
    return ret
  end

  def pbShowCommands(helptext,commands,index=0)
    ret = -1
    helpwindow = @sprites["helpwindow"]
    helpwindow.visible = true
    using(cmdwindow = Window_CommandPokemonColor.new(commands)) {
      cmdwindow.z     = @viewport.z+1
      cmdwindow.index = index
      pbBottomRight(cmdwindow)
      helpwindow.resizeHeightToFit(helptext,Graphics.width-cmdwindow.width)
      helpwindow.text = helptext
      pbBottomLeft(helpwindow)
      loop do
        Graphics.update
        Input.update
        cmdwindow.update
        self.update
        if Input.trigger?(Input::B)
          pbPlayCancelSE
          ret = -1
          break
        elsif Input.trigger?(Input::C)
          pbPlayDecisionSE
          ret = cmdwindow.index
          break
        end
      end
    }
    return ret
  end

  def pbMessageFreeText(text,startMsg,maxlength)   # Unused
    return Kernel.pbMessageFreeText(
       _INTL("Please enter a message (max. {1} characters).",maxlength),
       startMsg,false,maxlength,Graphics.width) { update }
  end

  def pbSetHelpText(helptext)
    helpwindow = @sprites["helpwindow"]
    pbBottomLeftLines(helpwindow,1)
    helpwindow.text = helptext
    helpwindow.width = 398
    helpwindow.visible = true
  end

  def pbAnnotate(annot)
    for i in 0...6
      @sprites["pokemon#{i}"].text = (annot) ? annot[i] : nil
    end
  end

  def pbSelect(item)
    @activecmd = item
    numsprites = (@multiselect) ? 8 : 7
    for i in 0...numsprites
      @sprites["pokemon#{i}"].selected = (i==@activecmd)
    end
  end

  def pbPreSelect(item)
    @activecmd = item
  end

  def pbSwitchBegin(oldid,newid)
    oldsprite = @sprites["pokemon#{oldid}"]
    newsprite = @sprites["pokemon#{newid}"]
    16.times do
      oldsprite.x += (oldid&1)==0 ? -16 : 16
      newsprite.x += (newid&1)==0 ? -16 : 16
      Graphics.update
      Input.update
      self.update
    end
  end

  def pbSwitchEnd(oldid,newid)
    oldsprite = @sprites["pokemon#{oldid}"]
    newsprite = @sprites["pokemon#{newid}"]
    oldsprite.pokemon = @party[oldid]
    newsprite.pokemon = @party[newid]
    16.times do
      oldsprite.x -= (oldid&1)==0 ? -16 : 16
      newsprite.x -= (newid&1)==0 ? -16 : 16
      Graphics.update
      Input.update
      self.update
    end
    for i in 0...6
      @sprites["pokemon#{i}"].preselected = false
      @sprites["pokemon#{i}"].switching   = false
    end
    pbRefresh
  end

  def pbClearSwitching
    for i in 0...6
      @sprites["pokemon#{i}"].preselected = false
      @sprites["pokemon#{i}"].switching   = false
    end
  end

  def pbSummary(pkmnid)
    oldsprites = pbFadeOutAndHide(@sprites)
    scene = PokemonSummary_Scene.new
    screen = PokemonSummaryScreen.new(scene)
    screen.pbStartScreen(@party,pkmnid)
    pbFadeInAndShow(@sprites,oldsprites)
  end

  def pbChooseItem(bag)
    ret = 0
    pbFadeOutIn(99999){
      scene = PokemonBag_Scene.new
      screen = PokemonBagScreen.new(scene,bag)
      ret = screen.pbChooseItemScreen(Proc.new{|item| pbCanHoldItem?(item) })
    }
    return ret
  end

  def pbUseItem(bag,pokemon)
    ret = 0
    pbFadeOutIn(99999){
      scene = PokemonBag_Scene.new
      screen = PokemonBagScreen.new(scene,bag)
      ret = screen.pbChooseItemScreen(Proc.new{|item|
        next false if !pbCanUseOnPokemon?(item)
        if pbIsMachine?(item)
          move = pbGetMachine(item)
          next false if pokemon.hasMove?(move) || !pokemon.isCompatibleWithMove?(move)
        end
        next true
      })
    }
    return ret
  end

  def pbChoosePokemon(switching=false,initialsel=-1,canswitch=0)
    for i in 0...6
      @sprites["pokemon#{i}"].preselected = (switching && i==@activecmd)
      @sprites["pokemon#{i}"].switching   = switching
    end
    @activecmd = initialsel if initialsel>=0
    pbRefresh
    loop do
      Graphics.update
      Input.update
      self.update
      oldsel = @activecmd
      key = -1
      key = Input::DOWN if Input.repeat?(Input::DOWN)
      key = Input::RIGHT if Input.repeat?(Input::RIGHT)
      key = Input::LEFT if Input.repeat?(Input::LEFT)
      key = Input::UP if Input.repeat?(Input::UP)
      if key>=0
        @activecmd = pbChangeSelection(key,@activecmd)
      end
      if @activecmd!=oldsel # Changing selection
        pbPlayCursorSE
        numsprites = (@multiselect) ? 8 : 7
        for i in 0...numsprites
          @sprites["pokemon#{i}"].selected = (i==@activecmd)
        end
      end
      cancelsprite = (@multiselect) ? 7 : 6
      if Input.trigger?(Input::A) && canswitch==1 && @activecmd!=cancelsprite
        pbPlayDecisionSE
        return [1,@activecmd]
      elsif Input.trigger?(Input::A) && canswitch==2
        return -1
      elsif Input.trigger?(Input::B)
        return -1
      elsif Input.trigger?(Input::C)
        pbPlayDecisionSE
        return (@activecmd==cancelsprite) ? -1 : @activecmd
      end
    end
  end

  def pbChangeSelection(key,currentsel)
    numsprites = (@multiselect) ? 8 : 7
    case key
    when Input::LEFT
      begin
        currentsel -= 1
      end while currentsel>0 && currentsel<@party.length && !@party[currentsel]
      if currentsel>=@party.length && currentsel<6
        currentsel = @party.length-1
      end
      currentsel = numsprites-1 if currentsel<0
    when Input::RIGHT
      begin
        currentsel += 1
      end while currentsel<@party.length && !@party[currentsel]
      if currentsel==@party.length
        currentsel = 6
      elsif currentsel==numsprites
        currentsel = 0
      end
    when Input::UP
      if currentsel>=6
        begin
          currentsel -= 1
        end while currentsel>0 && !@party[currentsel]
      else
        begin
          currentsel -= 2
        end while currentsel>0 && !@party[currentsel]
      end
      if currentsel>=@party.length && currentsel<6
        currentsel = @party.length-1
      end
      currentsel = numsprites-1 if currentsel<0
    when Input::DOWN
      if currentsel>=5
        currentsel += 1
      else
        currentsel += 2
        currentsel = 6 if currentsel<6 && !@party[currentsel]
      end
      if currentsel>=@party.length && currentsel<6
        currentsel = 6
      elsif currentsel>=numsprites
        currentsel = 0
      end
    end
    return currentsel
  end

  def pbHardRefresh
    oldtext = []
    lastselected = -1
    for i in 0...6
      oldtext.push(@sprites["pokemon#{i}"].text)
      lastselected = i if @sprites["pokemon#{i}"].selected
      @sprites["pokemon#{i}"].dispose
    end
    lastselected = @party.length-1 if lastselected>=@party.length
    lastselected = 0 if lastselected<0
    for i in 0...6
      if @party[i]
        @sprites["pokemon#{i}"] = PokemonPartyPanel.new(@party[i],i,@viewport)
      else
        @sprites["pokemon#{i}"] = PokemonPartyBlankPanel.new(@party[i],i,@viewport)
      end
      @sprites["pokemon#{i}"].text = oldtext[i]
    end
    pbSelect(lastselected)
  end

  def pbRefresh
    for i in 0...6
      sprite = @sprites["pokemon#{i}"]
      if sprite
        if sprite.is_a?(PokemonPartyPanel)
          sprite.pokemon = sprite.pokemon
        else
          sprite.refresh
        end
      end
    end
  end

  def pbRefreshSingle(i)
    sprite = @sprites["pokemon#{i}"]
    if sprite
      if sprite.is_a?(PokemonPartyPanel)
        sprite.pokemon = sprite.pokemon
      else
        sprite.refresh
      end
    end
  end

  def update
    pbUpdateSpriteHash(@sprites)
  end
end



#===============================================================================
# Pokémon party mechanics
#===============================================================================
class PokemonPartyScreen
  attr_reader :scene
  attr_reader :party

  def initialize(scene,party)
    @scene = scene
    @party = party
  end

  def pbStartScene(helptext,doublebattle,annotations=nil)
    @scene.pbStartScene(@party,helptext,annotations)
  end

  def pbChoosePokemon(helptext=nil)
    @scene.pbSetHelpText(helptext) if helptext
    return @scene.pbChoosePokemon
  end

  def pbPokemonGiveScreen(item)
    @scene.pbStartScene(@party,_INTL("Give to which Pokémon?"))
    pkmnid = @scene.pbChoosePokemon
    ret = false
    if pkmnid>=0
      ret = pbGiveItemToPokemon(item,@party[pkmnid],self,pkmnid)
    end
    pbRefreshSingle(pkmnid)
    @scene.pbEndScene
    return ret
  end

  def pbPokemonGiveMailScreen(mailIndex)
    @scene.pbStartScene(@party,_INTL("Give to which Pokémon?"))
    pkmnid = @scene.pbChoosePokemon
    if pkmnid>=0
      pkmn = @party[pkmnid]
      if pkmn.hasItem? || pkmn.mail
        pbDisplay(_INTL("This Pokémon is holding an item. It can't hold mail."))
      elsif pkmn.egg?
        pbDisplay(_INTL("Eggs can't hold mail."))
      else
        pbDisplay(_INTL("Mail was transferred from the Mailbox."))
        pkmn.mail = $PokemonGlobal.mailbox[mailIndex]
        pkmn.setItem(pkmn.mail.item)
        $PokemonGlobal.mailbox.delete_at(mailIndex)
        pbRefreshSingle(pkmnid)
      end
    end
    @scene.pbEndScene
  end

  def pbEndScene
    @scene.pbEndScene
  end

  def pbUpdate
    @scene.update
  end

  def pbHardRefresh
    @scene.pbHardRefresh
  end

  def pbRefresh
    @scene.pbRefresh
  end

  def pbRefreshSingle(i)
    @scene.pbRefreshSingle(i)
  end

  def pbDisplay(text)
    @scene.pbDisplay(text)
  end

  def pbConfirm(text)
    return @scene.pbDisplayConfirm(text)
  end

  def pbShowCommands(helptext,commands,index=0)
    @scene.pbShowCommands(helptext,commands,index)
  end

  # Checks for identical species
  def pbCheckSpecies(array)   # Unused
    for i in 0...array.length
      for j in i+1...array.length
        return false if array[i].species==array[j].species
      end
    end
    return true
  end

  # Checks for identical held items
  def pbCheckItems(array)   # Unused
    for i in 0...array.length
      next if !array[i].hasItem?
      for j in i+1...array.length
        return false if array[i].item==array[j].item
      end
    end
    return true
  end

  def pbSwitch(oldid,newid)
    if oldid!=newid
      @scene.pbSwitchBegin(oldid,newid)
      tmp = @party[oldid]
      @party[oldid] = @party[newid]
      @party[newid] = tmp
      @scene.pbSwitchEnd(oldid,newid)
    end
  end

  def pbChooseMove(pokemon,helptext,index=0)
    movenames = []
    for i in pokemon.moves
      break if i.id==0
      if i.totalpp==0
        movenames.push(_INTL("{1} (PP: ---)",PBMoves.getName(i.id),i.pp,i.totalpp))
      else
        movenames.push(_INTL("{1} (PP: {2}/{3})",PBMoves.getName(i.id),i.pp,i.totalpp))
      end
    end
    return @scene.pbShowCommands(helptext,movenames,index)
  end

  def pbRefreshAnnotations(ableProc)   # For after using an evolution stone
    annot = []
    for pkmn in @party
      elig = ableProc.call(pkmn)
      annot.push((elig) ? _INTL("ABLE") : _INTL("NOT ABLE"))
    end
    @scene.pbAnnotate(annot)
  end

  def pbClearAnnotations
    @scene.pbAnnotate(nil)
  end

  def pbPokemonMultipleEntryScreenEx(ruleset)
    annot = []
    statuses = []
    ordinals = [
       _INTL("INELIGIBLE"),
       _INTL("NOT ENTERED"),
       _INTL("BANNED"),
       _INTL("FIRST"),
       _INTL("SECOND"),
       _INTL("THIRD"),
       _INTL("FOURTH"),
       _INTL("FIFTH"),
       _INTL("SIXTH")
    ]
    return nil if !ruleset.hasValidTeam?(@party)
    ret = nil
    addedEntry = false
    for i in 0...@party.length
      statuses[i] = (ruleset.isPokemonValid?(@party[i])) ? 1 : 2
    end
    for i in 0...@party.length
      annot[i] = ordinals[statuses[i]]
    end
    @scene.pbStartScene(@party,_INTL("Choose Pokémon and confirm."),annot,true)
    loop do
      realorder = []
      for i in 0...@party.length
        for j in 0...@party.length
          if statuses[j]==i+3
            realorder.push(j)
            break
          end
        end
      end
      for i in 0...realorder.length
        statuses[realorder[i]] = i+3
      end
      for i in 0...@party.length
        annot[i] = ordinals[statuses[i]]
      end
      @scene.pbAnnotate(annot)
      if realorder.length==ruleset.number && addedEntry
        @scene.pbSelect(6)
      end
      @scene.pbSetHelpText(_INTL("Choose Pokémon and confirm."))
      pkmnid = @scene.pbChoosePokemon
      addedEntry = false
      if pkmnid==6 # Confirm was chosen
        ret = []
        for i in realorder; ret.push(@party[i]); end
        error = []
        break if ruleset.isValid?(ret,error)
        pbDisplay(error[0])
        ret = nil
      end
      break if pkmnid<0 # Canceled
      cmdEntry   = -1
      cmdNoEntry = -1
      cmdSummary = -1
      commands = []
      if (statuses[pkmnid] || 0) == 1
        commands[cmdEntry = commands.length]   = _INTL("Entry")
      elsif (statuses[pkmnid] || 0) > 2
        commands[cmdNoEntry = commands.length] = _INTL("No Entry")
      end
      pkmn = @party[pkmnid]
      commands[cmdSummary = commands.length]   = _INTL("Summary")
      commands[commands.length]                = _INTL("Cancel")
      command = @scene.pbShowCommands(_INTL("Do what with {1}?",pkmn.name),commands) if pkmn
      if cmdEntry>=0 && command==cmdEntry
        if realorder.length>=ruleset.number && ruleset.number>0
          pbDisplay(_INTL("No more than {1} Pokémon may enter.",ruleset.number))
        else
          statuses[pkmnid] = realorder.length+3
          addedEntry = true
          pbRefreshSingle(pkmnid)
        end
      elsif cmdNoEntry>=0 && command==cmdNoEntry
        statuses[pkmnid] = 1
        pbRefreshSingle(pkmnid)
      elsif cmdSummary>=0 && command==cmdSummary
        @scene.pbSummary(pkmnid)
      end
    end
    @scene.pbEndScene
    return ret
  end

  def pbChooseAblePokemon(ableProc,allowIneligible=false)
    annot = []
    eligibility = []
    for pkmn in @party
      elig = ableProc.call(pkmn)
      eligibility.push(elig)
      annot.push((elig) ? _INTL("ABLE") : _INTL("NOT ABLE"))
    end
    ret = -1
    @scene.pbStartScene(@party,
       (@party.length>1) ? _INTL("Choose a Pokémon.") : _INTL("Choose Pokémon or cancel."),annot)
    loop do
      @scene.pbSetHelpText(
         (@party.length>1) ? _INTL("Choose a Pokémon.") : _INTL("Choose Pokémon or cancel."))
      pkmnid = @scene.pbChoosePokemon
      break if pkmnid<0
      if !eligibility[pkmnid] && !allowIneligible
        pbDisplay(_INTL("This Pokémon can't be chosen."))
      else
        ret = pkmnid
        break
      end
    end
    @scene.pbEndScene
    return ret
  end

  def pbChooseTradablePokemon(ableProc,allowIneligible=false)
    annot = []
    eligibility = []
    for pkmn in @party
      elig = ableProc.call(pkmn)
      elig = false if pkmn.egg? || (pkmn.isShadow? rescue false)
      eligibility.push(elig)
      annot.push((elig) ? _INTL("ABLE") : _INTL("NOT ABLE"))
    end
    ret = -1
    @scene.pbStartScene(@party,
       (@party.length>1) ? _INTL("Choose a Pokémon.") : _INTL("Choose Pokémon or cancel."),annot)
    loop do
      @scene.pbSetHelpText(
         (@party.length>1) ? _INTL("Choose a Pokémon.") : _INTL("Choose Pokémon or cancel."))
      pkmnid = @scene.pbChoosePokemon
      break if pkmnid<0
      if !eligibility[pkmnid] && !allowIneligible
        pbDisplay(_INTL("This Pokémon can't be chosen."))
      else
        ret = pkmnid
        break
      end
    end
    @scene.pbEndScene
    return ret
  end

  def pbPokemonScreen
    @scene.pbStartScene(@party,
       (@party.length>1) ? _INTL("Choose a Pokémon.") : _INTL("Choose Pokémon or cancel."),nil)
    loop do
      @scene.pbSetHelpText((@party.length>1) ? _INTL("Choose a Pokémon.") : _INTL("Choose Pokémon or cancel."))
      pkmnid = @scene.pbChoosePokemon(false,-1,1)
      break if (pkmnid.is_a?(Numeric) && pkmnid<0) || (pkmnid.is_a?(Array) && pkmnid[1]<0)
      if pkmnid.is_a?(Array) && pkmnid[0]==1   # Switch
        @scene.pbSetHelpText(_INTL("Move to where?"))
        oldpkmnid = pkmnid[1]
        pkmnid = @scene.pbChoosePokemon(true,-1,2)
        if pkmnid>=0 && pkmnid!=oldpkmnid
          pbSwitch(oldpkmnid,pkmnid)
        end
        next
      end
      pkmn = @party[pkmnid]
      commands   = []
      cmdSummary = -1
      cmdDebug   = -1
      cmdMoves   = [-1,-1,-1,-1]
      cmdSwitch  = -1
      cmdMail    = -1
      cmdItem    = -1
      # Build the commands
      commands[cmdSummary = commands.length]      = _INTL("Summary")
      commands[cmdDebug = commands.length]        = _INTL("Debug") if $DEBUG
      for i in 0...pkmn.moves.length
        move = pkmn.moves[i]
        # Check for hidden moves and add any that were found
        if !pkmn.egg? && (isConst?(move.id,PBMoves,:MILKDRINK) ||
                          isConst?(move.id,PBMoves,:SOFTBOILED) ||
                          HiddenMoveHandlers.hasHandler(move.id))
          commands[cmdMoves[i] = commands.length] = [PBMoves.getName(move.id),1]
        end
      end
      commands[cmdSwitch = commands.length]       = _INTL("Switch") if @party.length>1
      if !pkmn.egg?
        if pkmn.mail
          commands[cmdMail = commands.length]     = _INTL("Mail")
        else
          commands[cmdItem = commands.length]     = _INTL("Item")
        end
      end
      commands[commands.length]                   = _INTL("Cancel")
      command = @scene.pbShowCommands(_INTL("Do what with {1}?",pkmn.name),commands)
      havecommand = false
      for i in 0...4
        if cmdMoves[i]>=0 && command==cmdMoves[i]
          havecommand = true
          if isConst?(pkmn.moves[i].id,PBMoves,:SOFTBOILED) ||
             isConst?(pkmn.moves[i].id,PBMoves,:MILKDRINK)
            amt = [(pkmn.totalhp/5).floor,1].max
            if pkmn.hp<=amt
              pbDisplay(_INTL("Not enough HP..."))
              break
            end
            @scene.pbSetHelpText(_INTL("Use on which Pokémon?"))
            oldpkmnid = pkmnid
            loop do
              @scene.pbPreSelect(oldpkmnid)
              pkmnid = @scene.pbChoosePokemon(true,pkmnid)
              break if pkmnid<0
              newpkmn = @party[pkmnid]
              movename = PBMoves.getName(pkmn.moves[i].id)
              if pkmnid==oldpkmnid
                pbDisplay(_INTL("{1} can't use {2} on itself!",pkmn.name,movename))
              elsif newpkmn.egg?
                pbDisplay(_INTL("{1} can't be used on an Egg!",movename))
              elsif newpkmn.hp==0 || newpkmn.hp==newpkmn.totalhp
                pbDisplay(_INTL("{1} can't be used on that Pokémon.",movename))
              else
                pkmn.hp -= amt
                hpgain = pbItemRestoreHP(newpkmn,amt)
                @scene.pbDisplay(_INTL("{1}'s HP was restored by {2} points.",newpkmn.name,hpgain))
                pbRefresh
              end
              break if pkmn.hp<=amt
            end
            @scene.pbSelect(oldpkmnid)
            pbRefresh
            break
          elsif Kernel.pbCanUseHiddenMove?(pkmn,pkmn.moves[i].id)
            if Kernel.pbConfirmUseHiddenMove(pkmn,pkmn.moves[i].id)
              @scene.pbEndScene
              if isConst?(pkmn.moves[i].id,PBMoves,:FLY)
                scene = PokemonRegionMap_Scene.new(-1,false)
                screen = PokemonRegionMapScreen.new(scene)
                ret = screen.pbStartFlyScreen
                if ret
                  $PokemonTemp.flydata=ret
                  return [pkmn,pkmn.moves[i].id]
                end
                @scene.pbStartScene(@party,
                   (@party.length>1) ? _INTL("Wähle ein Pokémon.") : _INTL("Wähle ein Pokémon oder breche ab."))
                break
              end
              return [pkmn,pkmn.moves[i].id]
            end
          else
            break
          end
        end
      end
      next if havecommand
      if cmdSummary>=0 && command==cmdSummary
        @scene.pbSummary(pkmnid)
      elsif cmdDebug>=0 && command==cmdDebug
        pbPokemonDebug(pkmn,pkmnid)
      elsif cmdSwitch>=0 && command==cmdSwitch
        @scene.pbSetHelpText(_INTL("Wohin bewegen?"))
        oldpkmnid = pkmnid
        pkmnid = @scene.pbChoosePokemon(true)
        if pkmnid>=0 && pkmnid!=oldpkmnid
          pbSwitch(oldpkmnid,pkmnid)
        end
      elsif cmdMail>=0 && command==cmdMail
        command = @scene.pbShowCommands(_INTL("Was möchtest du mit diesem Brief anstellen?"),
           [_INTL("Read"),_INTL("Take"),_INTL("Cancel")])
        case command
        when 0 # Read
          pbFadeOutIn(99999){ pbDisplayMail(pkmn.mail,pkmn) }
        when 1 # Take
          if pbTakeItemFromPokemon(pkmn,self)
            pbRefreshSingle(pkmnid)
          end
        end
      elsif cmdItem>=0 && command==cmdItem
        itemcommands = []
        cmdUseItem   = -1
        cmdGiveItem  = -1
        cmdTakeItem  = -1
        cmdMoveItem  = -1
        # Build the commands
        itemcommands[cmdUseItem=itemcommands.length]  = _INTL("Benutzen")
        itemcommands[cmdGiveItem=itemcommands.length] = _INTL("Geben")
        itemcommands[cmdTakeItem=itemcommands.length] = _INTL("Nehmen") if pkmn.hasItem?
        itemcommands[cmdMoveItem=itemcommands.length] = _INTL("Bewegen") if pkmn.hasItem? && !pbIsMail?(pkmn.item)
        itemcommands[itemcommands.length]             = _INTL("Abbrechen")
        command = @scene.pbShowCommands(_INTL("Was möchtest du mit diesem Item tun?"),itemcommands)
        if cmdUseItem>=0 && command==cmdUseItem   # Use
          item = @scene.pbUseItem($PokemonBag,pkmn)
          if item>0
            pbUseItemOnPokemon(item,pkmn,self)
            pbRefreshSingle(pkmnid)
          end
        elsif cmdGiveItem>=0 && command==cmdGiveItem   # Give
          item = @scene.pbChooseItem($PokemonBag)
          if item>0
            if pbGiveItemToPokemon(item,pkmn,self,pkmnid)
              pbRefreshSingle(pkmnid)
            end
          end
        elsif cmdTakeItem>=0 && command==cmdTakeItem   # Take
          if pbTakeItemFromPokemon(pkmn,self)
            pbRefreshSingle(pkmnid)
          end
        elsif cmdMoveItem>=0 && command==cmdMoveItem   # Move
          item = pkmn.item
          itemname = PBItems.getName(item)
          @scene.pbSetHelpText(_INTL("Move {1} to where?",itemname))
          oldpkmnid = pkmnid
          loop do
            @scene.pbPreSelect(oldpkmnid)
            pkmnid = @scene.pbChoosePokemon(true,pkmnid)
            break if pkmnid<0
            newpkmn = @party[pkmnid]
            if pkmnid==oldpkmnid
              break
            elsif newpkmn.egg?
              pbDisplay(_INTL("Eggs can't hold items."))
            elsif !newpkmn.hasItem?
              newpkmn.setItem(item)
              pkmn.setItem(0)
              @scene.pbClearSwitching
              pbRefresh
              pbDisplay(_INTL("{1} was given the {2} to hold.",newpkmn.name,itemname))
              break
            elsif pbIsMail?(newpkmn.item)
              pbDisplay(_INTL("{1}'s mail must be removed before giving it an item.",newpkmn.name))
            else
              newitem = newpkmn.item
              newitemname = PBItems.getName(newitem)
              if isConst?(newitem,PBItems,:LEFTOVERS)
                pbDisplay(_INTL("{1} is already holding some {2}.\1",newpkmn.name,newitemname))
              elsif ['a','e','i','o','u'].include?(newitemname[0,1].downcase)
                pbDisplay(_INTL("{1} is already holding an {2}.\1",newpkmn.name,newitemname))
              else
                pbDisplay(_INTL("{1} is already holding a {2}.\1",newpkmn.name,newitemname))
              end
              if pbConfirm(_INTL("Would you like to switch the two items?"))
                newpkmn.setItem(item)
                pkmn.setItem(newitem)
                @scene.pbClearSwitching
                pbRefresh
                pbDisplay(_INTL("{1} was given the {2} to hold.",newpkmn.name,itemname))
                pbDisplay(_INTL("{1} was given the {2} to hold.",pkmn.name,newitemname))
                break
              end
            end
          end
        end
      end
    end
    @scene.pbEndScene
    return nil
  end
end



def pbPokemonScreen
  return if !$Trainer
  pbFadeOutIn(99999){
    sscene = PokemonParty_Scene.new
    sscreen = PokemonPartyScreen.new(sscene,$Trainer.party)
    sscreen.pbPokemonScreen
  }
end

Ruby:
class Scene_DebugIntro
  def main
    Graphics.transition(0)
    sscene = PokemonLoad_Scene.new
    sscreen = PokemonLoadScreen.new(sscene)
    sscreen.pbStartLoadScreen
    Graphics.freeze
  end
end



def pbCallTitle
  if $DEBUG
    return Scene_DebugIntro.new
  else
    # First parameter is an array of images in the Titles
    # directory without a file extension, to show before the
    # actual title screen.  Second parameter is the actual
    # title screen filename, also in Titles with no extension.
    return Scene_Intro.new(['intro1'], 'splash')
  end
end

def mainFunction
  if $DEBUG
    pbCriticalCode { mainFunctionDebug }
  else
    mainFunctionDebug
  end
  return 1
end

def mainFunctionDebug
  begin
    getCurrentProcess = Win32API.new("kernel32.dll","GetCurrentProcess","","l")
    setPriorityClass  = Win32API.new("kernel32.dll","SetPriorityClass",%w(l i),"")
    setPriorityClass.call(getCurrentProcess.call(),32768) # "Above normal" priority class
    $data_animations    = pbLoadRxData("Data/Animations")
    $data_tilesets      = pbLoadRxData("Data/Tilesets")
    $data_common_events = pbLoadRxData("Data/CommonEvents")
    $data_system        = pbLoadRxData("Data/System")
    $game_system        = Game_System.new
    setScreenBorderName("border") # Sets image file for the border
    Graphics.update
    Graphics.freeze
    $scene = pbCallTitle
    while $scene!=nil
      $scene.main
    end
    Graphics.transition(20)
  rescue Hangup
    pbEmergencySave
    raise
  end
end

loop do
  retval = mainFunction
  if retval==0 # failed
    loop do
      Graphics.update
    end
  elsif retval==1 # ended successfully
    break
  end
end


This Error happens when compiling data. Edit: I think the game needed to much time to load the scripts, thats why this error occurred.

I hope somebody can help me out with this, in the meantime I'll look into the Script too, if you need any more details or screenshots just ask me and I'll provide them here. Thanks in advance.

Edit: It's working! I just removed 2 Scripts from Cilerba and Leilou and removed the Debug option in DP Pause Menu.
 
Last edited:
Top