• Just a reminder that providing specifics on, sharing links to, or naming websites where ROMs can be accessed is against the rules. If your post has any of this information it will be removed.
  • Ever thought it'd be cool to have your art, writing, or challenge runs featured on PokéCommunity? Click here for info - we'd love to spotlight your work!
  • It's time to vote for your favorite Pokémon Battle Revolution protagonist in our new weekly protagonist poll! Click here to cast your vote and let us know which PBR protagonist you like most.
  • Welcome to PokéCommunity! Register now and join one of the best fan communities on the 'net to talk Pokémon and more! We are not affiliated with The Pokémon Company or Nintendo.

Poke-Essentials Trade system!!

Status
Not open for further replies.

Ho-oh 112

Advance Scripter
  • 311
    Posts
    14
    Years
    • Seen Mar 8, 2014
    THIS IS A LONG ONE....

    Code:
    def pbLoadPokemonFromBase64(string)
      ary=string.unpack("m*")
      string=ary[0]
      numary=string.unpack("V*")
      rnd=numary.pop
      for i in 0...numary.length
        numary[i]^=rnd
      end
      nameary=[numary.pop,numary.pop].reverse
      trainername=nameary.pack("V2").sub(/\s*?$/,"")
      trainerID=numary.pop
      trainer=PokeBattle_Trainer.new(trainername,0)
      trainer.id=trainerID
      string=numary.pack("V*")
      return [PokeBattle_Pokemon.pbLoadFromString2(string),rnd,trainer]
    end
    def pbDumpPokemonToBase64(pokemon,rnd,trainer)
      string=pokemon.pbDumpToString2
      numary=string.unpack("V*")
      numary.push(trainer.id)
      name="        "
      for i in 0...$Trainer.name.length
        name[i]=$Trainer.name[i]
      end
      trainername=name.unpack("V2")
      numary+=trainername
      for i in 0...numary.length
        numary[i]^=rnd
      end
      numary.push(rnd)
      string=numary.pack("V*")
      ret=[string].pack("m*")
      return ret
    end
    def pbSelectFile(path="",filetype="*")
      names=[]
      Dir.chdir(path){
        Dir.glob("*."+filetype){|f|
          names.push(f)
        }
      }
      names.push(_INTL("Cancel"))
      cmdwindow=Window_CommandPokemon.new(names,Graphics.width)
      cmdwindow.height=Graphics.height if cmdwindow.height>Graphics.height
      cmdwindow.x=0
      cmdwindow.y=0
      loop do
        cmdwindow.update
        pbUpdateSceneMap
        Graphics.update
        Input.update
        if Input.trigger?(Input::C)
          Audio.se_play("Audio/SE/Choose.wav")
          cmdwindow.dispose
          if cmdwindow.index>=names.length-1
            return ""
          else
            return path+"/"+names[cmdwindow.index]
          end
        end
        if Input.trigger?(Input::B)
          Audio.se_play("Audio/SE/Choose.wav")
          cmdwindow.dispose
          return ""
        end
      end
    end
    # Trading
    def pbCancelTrade
      pbCancelPlayerTrade
      pbCancelPartnerTrade
    end
    def pbCancelPlayerTrade
      $PokemonGlobal.tradingPokemon=nil
      $PokemonGlobal.sendingPassword=nil
      $PokemonGlobal.sentConfirmation=false
      $PokemonGlobal.receivedConfirmation=false
    end
    def pbCancelPartnerTrade
      $PokemonGlobal.receivingPokemon=nil
      $PokemonGlobal.receivingPassword=nil
      $PokemonGlobal.sentConfirmation=false
      $PokemonGlobal.receivedConfirmation=false
      $PokemonGlobal.tradePartnerName=""
    end
    def pbGetOfferedPokemonInfo
      return if !$PokemonGlobal.tradingPokemon
      $game_variables[3]=$PokemonGlobal.tradingPokemon.name
      $game_variables[4]=PBSpecies.getName($PokemonGlobal.tradingPokemon.species)
    end
    def pbGetReceivingPokemonInfo
      return if !$PokemonGlobal.receivingPokemon
      $game_variables[3]=$PokemonGlobal.receivingPokemon.name
      $game_variables[4]=PBSPecies.getName($PokemonGlobal.receivingPokemon.species)
    end
    def pbUploadPokemon(index)
      return if index>=$Trainer.party.length
      $PokemonGlobal.tradingPokemon=$Trainer.party[index]
      $PokemonGlobal.tradingPokemon.heal
      $PokemonGlobal.sendingPassword=rand(256)
      $PokemonGlobal.sendingPassword|=rand(256)<<8
      $PokemonGlobal.sendingPassword|=rand(256)<<16
      $PokemonGlobal.sendingPassword|=rand(256)<<24
      $Trainer.party[index]=nil
      $Trainer.party.compact!
    end
    def pbLoadTradingFile(filename)
      begin
        data=""
        File.open(filename,"rb"){|f|
          code=f.read(4)
          type=f.read(1)
          if code!=GAMECODE || type!="T"
            Kernel.pbMessage(_INTL("This is not a valid trade file!"))
            return false
          end
          data=f.read
        }
        dataary=pbLoadPokemonFromBase64(data)
        pokemon=dataary[0]
        rnd=dataary[1]
        trainer=dataary[2]
        if trainer.id==$Trainer.id
          Kernel.pbMessage(_INTL("You can't trade with yourself!"))
          return false
        end
        if !pbGetAllValidSpecies.include?(pokemon.species)
          Kernel.pbMessage(_INTL("You can't accept the POKéMON at this time!"))
        end
        $PokemonGlobal.receivingPokemon=pokemon
        $PokemonGlobal.receivingPassword=rnd
        $PokemonGlobal.tradePartnerName=trainer.name
        return true
      rescue
        echoln $!.inspect
        Kernel.pbMessage(_INTL("The trade file is corrupted!"))
        return false
      end
    end
    def pbWithdrawOwnPokemon
      return false if !$PokemonGlobal.tradingPokemon
      if $Trainer.party.length==6
        Kernel.pbMessage(_INTL("Your party is full!"))
        return false
      end
      $Trainer.party.push($PokemonGlobal.tradingPokemon)
      pbCancelPlayerTrade
      Kernel.pbMessage(_INTL("{1} was withdrawn.",$Trainer.party.last.name))
      return true
    end
    def pbCreateTradingFile(pokemon=nil)
      if !pokemon
        pokemon=$PokemonGlobal.tradingPokemon
      end
      return false if !pokemon
      File.open("Trades/trade.txt","wb"){|f|
        f.write(GAMECODE)
        f.write("T")
        f.write(pbDumpPokemonToBase64(pokemon,$PokemonGlobal.sendingPassword,$Trainer))
      }
      return true
    end
    def pbShowStoredSummary
      return if !$PokemonGlobal.tradingPokemon
      scene=PokemonSummaryScene.new
      screen=PokemonSummary.new(scene)
      pbFadeOutIn(99999){
        screen.pbStartScreen([$PokemonGlobal.tradingPokemon],0)
      }
    end
    def pbShowReceivingSummary
      return if !$PokemonGlobal.receivingPokemon
      scene=PokemonSummaryScene.new
      screen=PokemonSummary.new(scene)
      pbFadeOutIn(99999){
        screen.pbStartScreen([$PokemonGlobal.receivingPokemon],0)
      }
    end
    def pbCreateConfirmationFile
      return false if !$PokemonGlobal.tradingPokemon
      return false if !$PokemonGlobal.receivingPokemon
      pokemon=$PokemonGlobal.tradingPokemon
      pokemon2=$PokemonGlobal.receivingPokemon
      time=Time.now.strftime("%H%M_%d%m%y")
      filename="Confirmation/#{pokemon.name}_#{pokemon2.name}_#{time}.txt"
      password=$PokemonGlobal.receivingPassword^pokemon.personalID
      echoln "Receiving password: "+$PokemonGlobal.receivingPassword.to_s
      echoln "Sending password: "+$PokemonGlobal.sendingPassword.to_s
      password=[password].pack("V")
      password=[password].pack("m*")
      if FileTest.exist?(filename)
        if !Kernel.pbConfirmMessage(_INTL("The confirmation file already exists. Would you like to overwrite it?"))
          return false
        end
      end
      File.open(filename,"wb"){|f|
        f.write(GAMECODE)
        f.write("C")
        f.write(password)
      }
      $PokemonGlobal.sentConfirmation=true
      return true
    end
    def pbCheckConfirmationFile(filename)
      begin
        return false if !$PokemonGlobal.tradingPokemon
        return false if !$PokemonGlobal.receivingPokemon
        password=""
        File.open(filename,"rb"){|f|
          code=f.read(4)
          type=f.read(1)
          if code!=GAMECODE || type!="C"
            Kernel.pbMessage(_INTL("This is not a valid confirmation file!"))
            return false
          end
          password=f.read
        }
        password=password.unpack("m*")[0]
        password=password.unpack("V")[0]
        pid=$PokemonGlobal.receivingPokemon.personalID
        if password^pid==$PokemonGlobal.sendingPassword
          $PokemonGlobal.receivedConfirmation=true
          return true
        else
          Kernel.pbMessage(_INTL("This is not the correct confirmation file!"))
          return false
        end
      rescue
        echoln $!.inspect
        Kernel.pbMessage(_INTL("The confirmation file is corrupted!"))
        return false
      end
    end
    def pbSelectAndLoadTradingFile
      filename=pbSelectFile("Trades","txt")
      if filename==""
        return false
      end
      return pbLoadTradingFile(filename)
    end
    def pbShowTradeScreen
      pbFadeOutInWithMusic(99999){
        trade=PokemonTradeScene.new
        trade.pbStartScreen($PokemonGlobal.tradingPokemon,$PokemonGlobal.receivingPokemon,$Trainer.name,$PokemonGlobal.tradePartnerName)
        $game_system.bgm_play(RPG::AudioFile.new("Evolution.mid",100,100))
        trade.pbTrade
        trade.pbEndScreen
      }
    end
    def pbCanCancelTrade?
      if $PokemonGlobal.sentConfirmation && $PokemonGlobal.receivedConfirmation
        return false
      end
      return true
    end
      
    def pbHasConfirmed?
      return false if !$PokemonGlobal.tradingPokemon
      return false if !$PokemonGlobal.receivingPokemon
      if !$PokemonGlobal.sentConfirmation || !$PokemonGlobal.receivedConfirmation
        return false
      end
      return true
    end
    def pbFinishTrade
      return false if !pbHasConfirmed?
      if $Trainer.party.length==6
        Kernel.pbMessage(_INTL("Your party is full!"))
        return false
      end
      pbShowTradeScreen
      $PokemonGlobal.receivingPokemon.happiness=70
      $Trainer.party.push($PokemonGlobal.receivingPokemon)
      pbCancelTrade
      return true
    end
    def pbSelectAndLoadConfirmationFile
      filename=pbSelectFile("Confirmation","txt")
      if filename==""
        return false
      end
      return pbCheckConfirmationFile(filename)
    end

    NOTE: THIS WAS POKEMON RAPTOR'S TRADE SYSTEM MODIFIED TO WORK ON THE NEWEST VERSION CREDITS GO TO THEM.

    THIS SCRIPT WILL BE REMOVED IF ASKED BY THE MAKER OF THE SCRIPT, I HAVE NO AUTHORITY OF IT...

    New PokeBattle_Pokemon script
    Code:
    # This class stores data on each Pokemon.  Refer to $Trainer.party for an array
    # of each Pokemon in the Trainer's current party.
    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(: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_accessor(:hp)          # Current HP
      attr_accessor(:pokerus)     # Three states: Not infected, infected, cured
      attr_accessor(:pokerusTime) # Time infected by Pokerus
      attr_accessor(:item)        # Held item
      attr_accessor(:mail)        # Mail
      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(:ballused)    # Ball used
      attr_accessor(:markings)    # Markings
      attr_accessor(:obtainMode)  # Manner obtained: 1 - egg, 4 - fateful encounter
      attr_accessor(:obtainMap)   # Map where obtained
      attr_accessor(:obtainLevel) # Level obtained
      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 Pokemon
      attr_accessor(:abilityflag) # Forces the first (0) or second (1) ability
      attr_accessor :cool,:beauty,:cute,:smart,:tough,:sheen # Contest stats
    # Time object specifying the time egg hatched.
      def timeEggHatched
        if obtainMode==1
          return @timeEggHatched ? Time.at(@timeEggHatched) : Time.gm(2000)
        else
          return Time.gm(2000)
        end
      end
    # Sets a Time object specifying the time egg hatched.
      def timeEggHatched=(value)
        # Seconds since Unix epoch
        if value.is_a?(Time)
          @timeEggHatched=value.to_i
        else
          @timeEggHatched=value
        end
      end
    # Sets a Time object specifying the time the Pokemon was received.
      def timeReceived=(value)
        # Seconds since Unix epoch
        if value.is_a?(Time)
          @timeReceived=value.to_i
        else
          @timeReceived=value
        end
      end
    #Time object specifying the time the Pokemon was received.
      def timeReceived
        return @timeReceived ? Time.at(@timeReceived) : Time.gm(2000)
      end
    # Pokemon Contest attribute
      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
      def language; @language ? @language : 0; end
    # Number of ribbons this Pokemon has
      def ribbonCount
        count=0
        for i in 0..self.maxRibbon
          count+=1 if getRibbon(i)
        end
        return count
      end
    # Maximum ribbon, for iterating through a Pokemon's ribbons
      def maxRibbon
        return @ribbons ? @ribbons.length*32-1 : 31
      end
    # Specifies whether the Pokemon has the ribbon of the specified number
      def getRibbon(ribbon)
        return false if [EMAIL="!@ribbons"]!@ribbons[/EMAIL] || [EMAIL="!@ribbons[ribbon>>5"]!@ribbons[ribbon>>5[/EMAIL]]
        return ((@ribbons[ribbon>>5]) & (1<<(ribbon&31)))!=0
      end
    # Sets whether the Pokemon has the ribbon of the specified number
      def setRibbon(ribbon, value=true)
        @ribbons=[] if [EMAIL="!@ribbons"]!@ribbons[/EMAIL]
        @ribbons[ribbon>>5]=0 if [EMAIL="!@ribbons[ribbon>>5"]!@ribbons[ribbon>>5[/EMAIL]]
        if value
          (@ribbons[ribbon>>5] |= (1<<(ribbon&31)))
        else
          (@ribbons[ribbon>>5] &=~ (1<<(ribbon&31)))
        end
      end
    # Clears the ribbon of the specified number
      def clearRibbon(ribbon)
        setRibbon(ribbon,false)
      end
    # Clears all ribbons of this Pokemon
      def clearAllRibbons
        @ribbons=[]
      end
    # Determines whether the Pokemon has the specified type.
    # Type is either a number or the internal name of the 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
    # Gets this Pokemon's mail.
      def mail
        return nil if [EMAIL="!@mail"]!@mail[/EMAIL]
        if @mail.item==0 || self.item==0 || @mail.item!=self.item
          @mail=nil
          return nil
        end
        return @mail
      end
      def obtainLevel
        @obtainLevel=0 if [EMAIL="!@obtainLevel"]!@obtainLevel[/EMAIL]
        return @obtainLevel
      end
      def otgender
        @otgender=3 if [EMAIL="!@otgender"]!@otgender[/EMAIL]
        return @otgender
      end
      def markings
        @markings=0 if [EMAIL="!@markings"]!@markings[/EMAIL]
        return @markings
      end
      def nature
        return @personalID%25
      end
    # Gets a string stating the Unown form of this Pokemon.
      def unownShape
        [EMAIL="d=@personalID&3"]d=@personalID&3[/EMAIL]
        d|=((@personalID>>8)&3)<<2
        d|=((@personalID>>16)&3)<<4
        d|=((@personalID>>24)&3)<<6
        return "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?"[d%28,1]
      end
      def abilityflag
        return @abilityflag if @abilityflag
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,29)
        ret1=dexdata.fgetb
        ret2=dexdata.fgetb
        dexdata.close
        if ret1==ret2 || ret2==0
          return 0
        end
        return (@personalID&1)
      end
    # Gets the ID of this Pokemon's ability
      def ability
        [EMAIL="abil=@abilityflag"]abil=@abilityflag[/EMAIL] ? @abilityflag : (@personalID&1)
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,29)
        ret1=dexdata.fgetb
        ret2=dexdata.fgetb
        pbDexDataOffset(dexdata,@species,37)
        ret3=dexdata.fgetb
        dexdata.close
        ret=ret1
        if abil==2
          if ret3>0
            return ret3
          else
            abil=(@personalID&1)
          end
        end
        if abil==1
          ret=ret2
          if ret2==0
            ret=ret1
          end
        end
        return ret
      end
      def self.isFemale(b,genderRate)
        return (b<=30) if genderRate==0x1F # FemaleOneEighth
        return (b<=63) if genderRate==0x3F # Female25Percent
        return (b<=126) if genderRate==0x7F # Female50Percent
        return (b<=190) if genderRate==0xBF # Female75Percent
        return true if genderRate==0xFE
        return false if genderRate==0 || genderRate==0xFF
        return (b<genderRate)
      end
    # Gets this Pokemon's gender. 0=male, 1=female, 2=genderless
      def gender
        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
            [EMAIL="lowbyte=@personalID&0xFF"]lowbyte=@personalID&0xFF[/EMAIL]
            return PokeBattle_Pokemon.isFemale(lowbyte,genderbyte) ? 1 : 0
        end
      end
      def setGenderAndNature(female,nature)
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,18)
        genderbyte=dexdata.fgetb
        dexdata.close
        case genderbyte
          when 255
            setNature(nature)
            return false # genderless
          when 254
            setNature(nature)
            return female # always female
          when 0
            setNature(nature)
            return !female # always male
          else
            [EMAIL="lowbyte=@personalID&0xFF"]lowbyte=@personalID&0xFF[/EMAIL]
            if PokeBattle_Pokemon.isFemale(lowbyte,genderbyte)==female && self.nature==nature
              return true
            end
            loop do
              value=rand(256)
              if female==PokeBattle_Pokemon.isFemale(value,genderbyte)
                @personalID&=~0xFF
                @personalID|=value
                done=false
                if female
                  while (@personalID&0xFF)>0
                    if self.nature==nature
                      done=true; break
                    end
                    @personalID-=1
                  end
                else
                  while (@personalID&0xFF)<0xFF
                    if self.nature==nature
                      done=true; break
                    end
                    @personalID+=1
                  end     
                end
                if done
                  calcStats
                  return true
                else
                  @personalID=rand(256)<<8
                  @personalID|=rand(256)<<16
                  @personalID|=rand(256)<<24
                end
              end
            end
        end
      end
      def setNature(nature)
        changed=false
        while self.nature!=nature
          @personalID=rand(256)
          @personalID|=rand(256)<<8
          @personalID|=rand(256)<<16
          @personalID|=rand(256)<<24
          changed=true
        end
        self.calcStats if changed
      end
      def setGender(female)
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,18)
        genderbyte=dexdata.fgetb
        dexdata.close
        case genderbyte
          when 255
            return false # genderless
          when 254
            return female # always female
          when 0
            return !female # always male
          else
            [EMAIL="lowbyte=@personalID&0xFF"]lowbyte=@personalID&0xFF[/EMAIL]
            return true if PokeBattle_Pokemon.isFemale(lowbyte,genderbyte)==female
            loop do
              value=rand(256)
              if female==PokeBattle_Pokemon.isFemale(value,genderbyte)
                @personalID&=~0xFF
                @personalID|=value
                calcStats
                return true
              end
            end
        end
      end
    # Sets this Pokemon'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
      
    def pbDumpToString2
      p 'hi'
      #          ||
      # Compiler VV
      array=[]
      movesarray=[]
      for i in 0...4
        movesarray.push(@moves[i].id)
      end
      movesarray.push(@moves[0].ppup|(@moves[1].ppup<<2)|(@moves[2].ppup<<4)|(@moves[3].ppup<<6))
      shiny=isShiny?
      shadow=isShadow?
      if shiny == true
        shiny = 0
      else
        shiny = 1
      end
      if shadow == true
        shadow = 0
      else
        shadow = 1
      end
      # Ends compile
         #                                ||
      # Wrties Array with the data in it. VV
      p 'hi'
      array = [@species,level,@iv,@ev,shiny,shadow,@totalhp,@attack,@defense,
      @speed,@spatk,@spdef,@personalID,@TrainerID,@ot.unpack("C7"),@pokerus,@pokerusTime,
      @item,@mail,@name.unpack("C"),@exp,@happiness,@status,@statusCount,@eggsteps,
      @ballused,@markings,@obtainMode,@obtainMap,@obtainLevel,@language,@otgender,
      movesarray,0,0]
      array.flatten!
      p array
      return array.pack("VvVVCVvC7C10VCvv4CCC6C3")
    end
      
    def self.pbLoadFromString2(string)
      array=[]
      movesarray=[]
      array=string.unpack("VvVVCVvC7C10VCvv4CCC6C3")
      species2=array[0]
      level2=array[1]
      ivs=[array[2],array[3],array[4],array[5],array[6],array[7]]
      evs=[array[8],array[9],array[10],array[11],array[12],array[13]]
      shiny=array[14]
      shadow=array[15]
      totalhp=array[16]
      attack=array[17]
      defense=array[18]
      speed=array[19]
      spatk=array[20]
      spdef=array[21]
      pid=array[22]
      id=array[23]
      ot=array[24,10].pack("C7").gsub("\000","")
      pokerus=array[34]
      pokerusTime=array[35]
      item=array[36]
      mail=array[37]
      name=array[38,7].pack("C").gsub("\000","")
      exp=array[44]
      happiness=array[45]
      status=array[46]
      statusCount=array[47]
      eggsteps=array[48]
      ballused=array[49]
      markings=array[50]
      obtainMode=array[51]
      obtainMap=array[52]
      obtainLevel=array[53]
      language=array[54]
      otgender=array[55]
      form=array[56]
      poke=self.new(species2,level2)
      poke.iv=ivs
      poke.ev=evs
      for i in 0...3
        poke.moves[i]=array[57+i]
      end
      if shiny == 0
        poke.makeShiny
      end
      if shadow == 0
        poke.makeShadow
      end
      poke.personalID=pid
      poke.trainerID=id
      poke.ot=ot
      poke.pokerus=pokerus
      poke.pokerusTime=pokerusTime
      poke.item=item
      poke.mail=mail
      poke.name=name
      poke.exp=exp
      poke.happiness=happiness
      poke.status=status
      poke.statusCount=statusCount
      poke.ballused=ballused
      poke.markings=markings
      poke.obtainMode=obtainMode
      poke.obtainMap=obtainMap
      poke.obtainLevel=obtainLevel
      poke.language=language
      poke.otgender=otgender
      #poke.attack=attack
      #poke.defense=defense
      #poke.speed=speed
      #poke.spatk=spatk
      #poke.spdef=spdef
      poke.calcStats
      return poke
    end
    # Gets this Pokemon's level.
      def level
        return PBExperience.pbGetLevelFromExperience(@exp,self.growthrate)
      end
    # Returns whether this Pokemon is an egg.
      def egg?
        return @eggsteps>0
      end
    # Gets whether the specified Trainer is not this Pokemon's original trainer.
      def isForeign?(trainer)
        return @trainerID!=trainer.id || @ot!=trainer.name
      end
    # Gets whether this Pokemon is shiny (different colored).
      def isShiny?
        [EMAIL="a=@personalID^@trainerID"]a=@personalID^@trainerID[/EMAIL]
        b=a&0xFFFF
        c=(a>>16)&0xFFFF
        d=b^c
        return (d<SHINYPOKEMONCHANCE)
      end
    # Makes this Pokemon shiny.
      def makeShiny
        if !isShiny?
          rnd=rand(65536)
          rnd|=(rnd<<16)
          rnd&=0xFFFFFFF8
          rnd|=rand(8)
          [EMAIL="self.personalID=rnd^@trainerID"]self.personalID=rnd^@trainerID[/EMAIL]
          calcStats
        end
      end
      def calcHP(base,level,iv,ev) # :nodoc:
        return 1 if base==1
        return ((base*2+iv+(ev>>2))*level/100).floor+level+10
      end
      def calcStat(base,level,iv,ev,pv)# :nodoc:
        return ((((base*2+iv+(ev>>2))*level/100).floor+5)*pv/100).floor
      end
    # Returns this Pokemon's growth rate.
      def growthrate
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,20)
        ret=dexdata.fgetb
        dexdata.close
        return ret
      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(@species-1)
        length=atkdata.getLength(@species-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
    # Returns this Pokemon's first type.
      def type1
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,8)
        ret=dexdata.fgetb
        dexdata.close
        return ret
      end
    # Returns this Pokemon's second type.
      def type2
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,9)
        ret=dexdata.fgetb
        dexdata.close
        return ret
      end
    # Heals all HP, PP, and status problems of this Pokemon.
      def heal
        return if egg?
        @hp=@totalhp
        @status=0
        @statusCount=0
        for i in 0..3
          @moves[i].pp=@moves[i].totalpp
        end 
      end
    # Gets the public portion of the trainer ID.
      def publicID
        return @trainerID&0xFFFF
      end
    # Sets this Pokemon's HP.
      def hp=(value)
        value=0 if value<0
        @hp=value
        if @hp==0
          @status=0
          @statusCount=0
        end
      end
    # Gets this Pokemon's base stats. An array of six values
    # for HP, Attack, Defense, Speed, Sp. Atk, and Sp. Def.
      def baseStats
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,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
    # Recalculates this Pokemon'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
          base=bs[i]
          if i==0
            stats[i]=calcHP(base,level,@iv[i],@ev[i])
          else
            stats[i]=calcStat(base,level,@iv[i],@ev[i],pvalues[i-1])
          end
        end
        [EMAIL="diff=@totalhp-@hp"]diff=@totalhp-@hp[/EMAIL]
        @totalhp=stats[0]
        if @hp>0
          @hp=@totalhp-diff
          @hp=1 if @hp<=0
          @hp=@totalhp if @hp>@totalhp
        end
        @attack=stats[1]
        @defense=stats[2]
        @speed=stats[3]
        @spatk=stats[4]
        @spdef=stats[5]
      end
    # Creates a new Pokemon object.
    #  species - Pokemon species. level - Pokemon level.
    #  player - PokeBattle_Trainer object for the original trainer.
    #  withMoves - if false, this Pokemon has no moves.
      def initialize(species,level,player=nil,withMoves=true)
        @ev=[0,0,0,0,0,0]
        if species<1||species>PBSpecies.maxValue
          raise ArgumentError.new(_INTL("The species number (no. {1} of {2}) is invalid.",
             species,PBSpecies.maxValue))
          return nil
        end
        @timeReceived=Time.now.getgm.to_i # Use GMT
        @species=species
        # Individual Values
        @hp=1
        @totalhp=1
        @iv=[]
        @iv[0]=rand(32)
        @iv[1]=rand(32)
        @iv[2]=rand(32)
        @iv[3]=rand(32)
        @iv[4]=rand(32)
        @iv[5]=rand(32)
        @personalID=rand(256)
        @personalID|=rand(256)<<8
        @personalID|=rand(256)<<16
        @personalID|=rand(256)<<24
        if player
          @trainerID=player.id
          @ot=player.name
          @otgender=player.gender
          @language=player.language
        else
          @trainerID=0
          @ot=""
          @otgender=3
        end
        dexdata=pbOpenDexData
        pbDexDataOffset(dexdata,@species,19)
        @happiness=dexdata.fgetb
        pbDexDataOffset(dexdata,@species,29)
        ability1=dexdata.fgetb
        ability2=dexdata.fgetb
        dexdata.close
        @name=PBSpecies.getName(@species)
        @eggsteps=0
        @status=0
        @statusCount=0
        @item=0
        @mail=nil
        @moves=[]
        @ballused=0
        self.level=level
        calcStats
        @hp=@totalhp
        if $game_map
          @obtainMode=0 # met
          @obtainMap=$game_map.map_id
          @obtainLevel=level
        else
          @obtainMode=0
          @obtainMap=0
          @obtainLevel=level
        end
        if withMoves
          atkdata=pbRgssOpen("Data/attacksRS.dat","rb")
          offset=atkdata.getOffset(species-1)
          length=atkdata.getLength(species-1)>>1
          atkdata.pos=offset
          # Generating move list
          movelist=[]
          for i in 0..length-1
            alevel=atkdata.fgetw
            move=atkdata.fgetw
            if alevel<=level
              movelist[movelist.length]=move
            end
          end
          atkdata.close
          movelist|=[] # Remove duplicates
          # Use the last 4 items in the move list
          listend=movelist.length-4
          listend=0 if listend<0
          j=0
          for i in listend..listend+3
            moveid=(i>=movelist.length) ? 0 : movelist[i]
            @moves[j]=PBMove.new(moveid)
            j+=1
          end
        end
      end
    end


    New Pokemon Map Script

    Code:
    ################################################################################
    # This class keeps track of erased and moved events so their position
    # can remain after a game is saved and loaded.  This class also includes
    # variables that should remain valid only for the current map.
    ################################################################################
    class PokemonMapMetadata
      attr_reader :erasedEvents
      attr_reader :movedEvents    
      attr_accessor :strengthUsed
      attr_accessor :blackFluteUsed
      attr_accessor :whiteFluteUsed
      attr_accessor :bridge
      attr_accessor :bridgeTile
      def initialize
        clear
      end
      def clear
        @strengthUsed=false
        @blackFluteUsed=false
        @whiteFluteUsed=false
        @erasedEvents={}
        @movedEvents={}
        @bridge=nil
      end
      def addErasedEvent(eventID)
        key=[$game_map.map_id,eventID]
        @erasedEvents[key]=true
      end
      def addMovedEvent(eventID)
        key=[$game_map.map_id,eventID]
        event=$game_map.events[eventID]
        @movedEvents[key]=[event.x,event.y,event.direction,event.through]
      end
      def updateMap
        for i in @erasedEvents
          if i[0][0]==$game_map.map_id && i[1]
            event=$game_map.events[i[0][1]]
            event.erase if event
          end
        end
        for i in @movedEvents
          if i[0][0]==$game_map.map_id && i[1]
            next if !$game_map.events[i[0][1]]
            $game_map.events[i[0][1]].moveto(i[1][0],i[1][1])
            case i[1][2]
              when 2
                $game_map.events[i[0][1]].turn_down
              when 4
                $game_map.events[i[0][1]].turn_left
              when 6
                $game_map.events[i[0][1]].turn_right
              when 8
                $game_map.events[i[0][1]].turn_up
            end
          end
          if i[1][3]!=nil
            $game_map.events[i[0][1]].through=i[1][3]
          end
        end
      end
    end
     
    def getTileId(map,x,y)
      for i in [2,1,0]
        id=map.data[x,y,i]
        return id if id!=nil && id>0
      end
      return id
    end
    def pbBridgeFacing(direction)
      tile=$MapFactory.getFacingTile(direction)
      return if !tile
      facingMap=$MapFactory.getMap(tile[0])
      facingID=getTileId(facingMap,tile[1],tile[2]) 
      $PokemonMap.bridge=[0,direction,facingID,
         facingMap.priorities[facingID]]
    end
    def pbBridgeFacingLeft
      pbBridgeFacing(4)
    end
    def pbBridgeFacingRight
      pbBridgeFacing(6)
    end
    def pbBridgeFacingUp
      pbBridgeFacing(8)
    end
    def pbBridgeFacingDown
      pbBridgeFacing(2)
    end
    def pbBridgeCheck(direction)
      bridge=$PokemonMap.bridge
      if bridge
        if bridge[0]==0 # entering bridge
          if direction==bridge[1]
            tile=$MapFactory.getFacingTile(direction)
            if tile
              facingMap=$MapFactory.getMap(tile[0])
              facingID=getTileId(facingMap,tile[1],tile[2])
              if facingID==bridge[2]
                # now entering bridge
                $PokemonMap.bridge[0]=1
                facingMap.priorities[bridge[2]]=0
                return
              end
            end
          end
          $PokemonMap.bridge=nil
        elsif bridge[0]==1 # on bridge
          $game_map.priorities[bridge[2]]=0
          if bridge[1]==4 || bridge[1]==6 # if left or right
            return if direction==2 || direction==8 # up or down
          elsif bridge[1]==2 || bridge[1]==8 # if up or down
            return if direction==4 || direction==6 # left or right
          end
          currentID=getTileId($game_map,$game_player.x,$game_player.y)
          tile=$MapFactory.getFacingTile(direction)
          return if !tile
          facingMap=$MapFactory.getMap(tile[0])
          facingID=getTileId(facingMap,tile[1],tile[2])
          if facingID!=bridge[2]
            # now leaving bridge; restore priorities
            facingMap.priorities[bridge[2]]=$PokemonMap.bridge[3]
            $PokemonMap.bridge=nil
          end
        end
      end
    end
     
    ################################################################################
    # Global metadata not specific to a map.  This class holds
    # field state data that span multiple maps.
    ################################################################################
    class PokemonGlobalMetadata
      attr_accessor :repel
      attr_accessor :bicycle
      attr_accessor :surfing
      attr_accessor :fishing
      attr_accessor :diving
      attr_accessor :coins
      attr_accessor :sootsack
      attr_accessor :flashUsed
      attr_accessor :runningShoes
      attr_accessor :pokedexUnlocked # Array storing which Dexes are unlocked
      attr_accessor :pokedexViable   # All Dexes of non-zero length and unlocked
      attr_accessor :pokedexDex      # Dex currently looking at (-1 is National Dex)
      attr_accessor :pokedexIndex    # Last species viewed per Dex
      attr_accessor :pokedexMode     # Search mode
      attr_accessor :happinessSteps
      attr_accessor :pokecenterMapId
      attr_accessor :pokecenterX
      attr_accessor :pokecenterY
      attr_accessor :pokecenterDirection
      attr_accessor :daycare
      attr_accessor :daycareEgg
      attr_accessor :daycareEggSteps
      attr_accessor :healingSpot
      attr_accessor :stepcount
      attr_accessor :playerID
      attr_accessor :seenStorageCreator
      attr_accessor :visitedMaps
      attr_accessor :mapTrail
      attr_accessor :regionMapTrail
      attr_accessor :eventvars
      attr_accessor :savedColorTone
      attr_accessor :nextBattleBGM
      attr_accessor :nextBattleME
      attr_accessor :nextBattleBack
      attr_accessor :phoneNumbers
      attr_accessor :phoneTime
      attr_accessor :challenge
      attr_accessor :safesave
      attr_accessor :lastbattle
      attr_accessor :safariState
      attr_accessor :bugContestState
      attr_accessor :partyMail
      attr_accessor :mailbox
      attr_accessor :pcItemStorage
      attr_accessor :nextBattleBG
      attr_accessor :partner
      attr_accessor :tradingPokemon
      attr_accessor :receivingPokemon
      attr_accessor :sendingPassword
      attr_accessor :receivingPassword
      attr_accessor :sentConfirmation
      attr_accessor :receivedConfirmation
      attr_accessor :tradePartnerName
      def initialize
        @repel=0
        @coins=0
        @sootsack=0
        @playerID=-1
        @daycareEgg=false
        @daycareEggSteps=0
        @healingSpot=nil
        @daycare=[[nil,0],[nil,0]]
        @eventvars={}
        @savedColorTone=Tone.new(0,0,0,0)
        numRegions=0
        pbRgssOpen("Data/regionals.dat","rb"){|f|
           numRegions=f.fgetw
        }
        @pokedexDex=(numRegions==0) ? -1 : 0
        @pokedexViable=[]
        @pokedexUnlocked=[]
        @pokedexIndex=[]
        for i in 0...numRegions+1     # National Dex isn't a region, but is included
          @pokedexIndex[i]=0
          @pokedexUnlocked[i]=(i==0) ? true : false
        end
        @pokedexMode=0
        @pokecenterMapId=-1
        @visitedMaps=[]
        @mapTrail=[]
        @regionMapTrail=[]
        @pokecenterX=-1
        @pokecenterY=-1
        @pokecenterDirection=-1
        @seenStorageCreator=false
        @surfing=false
        @bicycle=false
        @diving=false
        @runningShoes=false
        @fishing=false
        @happinessSteps=0
        @nextBattleBGM=nil
        @nextBattleME=nil
        @phoneNumbers=[]
        @phoneTime=0
        @safesave=false
        @lastbattle=nil
        @safariState=nil
        tradingPokemon=nil
        receivingPokemon=nil
        sendingPassword=nil
        receivingPassword=nil
        sentConfirmation=false
        receivedConfirmation=false
        tradePartnerName=nil
      end 
    end
     
    ################################################################################
    # Temporary data which is not saved and which is erased when a game restarts.
    ################################################################################
    class PokemonTemp
      attr_accessor :menuLastChoice
      attr_accessor :keyItemCalling
      attr_accessor :hiddenMoveEventCalling
      attr_accessor :begunNewGame
      attr_accessor :miniupdate
      attr_accessor :waitingTrainer
      attr_accessor :darknessSprite
      attr_accessor :pokemonDexData
      attr_accessor :pokemonMetadata
      attr_accessor :pokemonPhoneData
      attr_accessor :lastbattle
      attr_accessor :flydata
      def initialize
        @darknessSprite=nil
        @mapChanged=false
        @menuLastChoice=0
        @lastitem=0
        @keyItemCalling=false
        @begunNewGame=false
        @hiddenMoveEventCalling=false
        @miniupdate=false
        @waitingTrainer=nil
        @pokemonDexData=nil
        @pokemonMetadata=nil
        @pokemonPhoneData=nil
        @lastbattle=nil
      end
    end
     
    class PhoneDatabase
      attr_accessor :generics
      attr_accessor :greetings
      attr_accessor :greetingsMorning
      attr_accessor :greetingsEvening
      attr_accessor :battleRequests
      attr_accessor :bodies1
      attr_accessor :bodies2
      attr_accessor :trainers
      def initialize
        @generics=[]
        @greetings=[]
        @greetingsMorning=[]
        @greetingsEvening=[]
        @battleRequests=[]
        @bodies1=[]
        @bodies2=[]
        @trainers=[]
      end
    end
     
    module PhoneMsgType
      Generic=0
      Greeting=1
      Body=2
      BattleRequest=3 
    end
     
    MetadataHome=1
    MetadataStorageCreator=2
    MetadataWildBattleBGM=3
    MetadataTrainerBattleBGM=4
    MetadataWildVictoryME=5
    MetadataTrainerVictoryME=6
    MetadataTextSkin=7
    MetadataSurfBGM=8
    MetadataBicycleBGM=9
    MetadataPlayerA=10
    MetadataPlayerB=11
    MetadataPlayerC=12
    MetadataPlayerD=13
    MetadataPlayerE=14
    MetadataPlayerF=15
    MetadataPlayerG=16
    MetadataPlayerH=17
    MetadataOutdoor=1
    MetadataEscapePoint=2
    MetadataShowArea=3
    MetadataBicycle=4
    MetadataBicycleAlways=5
    MetadataHealingSpot=6
    MetadataWeather=7
    MetadataMapPosition=8
    MetadataDiveMap=9
    MetadataDarkMap=10
    MetadataSafariMap=11
    MetadataSnapEdges=12
    MetadataDungeon=13
    MetadataBattleBack=14
    MetadataMapWildBattleBGM=15
    MetadataMapTrainerBattleBGM=16
    MetadataMapWildVictoryME=17
    MetadataMapTrainerVictoryME=18
     
    module PokemonMetadata
      GlobalTypes={
         "Home"=>[1,"uuuu"],
         "StorageCreator"=>[2,"s"],
         "WildBattleBGM"=>[3,"s"],
         "TrainerBattleBGM"=>[4,"s"],
         "WildVictoryME"=>[5,"s"],
         "TrainerVictoryME"=>[6,"s"],
         "TextSkin"=>[7,"s"],
         "SurfBGM"=>[8,"s"],
         "BicycleBGM"=>[9,"s"],
         "PlayerA"=>[10,"essssss",:PBTrainers],
         "PlayerB"=>[11,"essssss",:PBTrainers],
         "PlayerC"=>[12,"essssss",:PBTrainers],
         "PlayerD"=>[13,"essssss",:PBTrainers],
         "PlayerE"=>[14,"essssss",:PBTrainers],
         "PlayerF"=>[15,"essssss",:PBTrainers],
         "PlayerG"=>[16,"essssss",:PBTrainers],
         "PlayerH"=>[17,"essssss",:PBTrainers]
      }
      NonGlobalTypes={
         "Outdoor"=>[1,"b"],
         "EscapePoint"=>[2,"uuu"],
         "ShowArea"=>[3,"b"],
         "Bicycle"=>[4,"b"],
         "BicycleAlways"=>[5,"b"],
         "HealingSpot"=>[6,"uuu"],
         "Weather"=>[7,"eu",["","Rain","Storm","Snow","Sandstorm"]],
         "MapPosition"=>[8,"uuu"],
         "DiveMap"=>[9,"u"],
         "DarkMap"=>[10,"b"],
         "SafariMap"=>[11,"b"],
         "SnapEdges"=>[12,"b"],
         "Dungeon"=>[13,"b"],
         "BattleBack"=>[14,"s"],
         "WildBattleBGM"=>[15,"s"],
         "TrainerBattleBGM"=>[16,"s"],
         "WildVictoryME"=>[17,"s"],
         "TrainerVictoryME"=>[18,"s"],
      }
    end
     
    def pbClearData
      if $PokemonTemp
        $PokemonTemp.pokemonDexData=nil
        $PokemonTemp.pokemonMetadata=nil
        $PokemonTemp.pokemonPhoneData=nil
      end
      MapFactoryHelper.clear
      if $game_map && $PokemonEncounters
        $PokemonEncounters.setup($game_map.map_id)
      end
      if pbRgssExists?("Data/Tilesets.rxdata")
        $data_tilesets=load_data("Data/Tilesets.rxdata")
      end
      if pbRgssExists?("Data/Tilesets.rvdata")
        $data_tilesets=load_data("Data/Tilesets.rvdata")
      end
    end
    def pbOpenDexData
      $PokemonTemp=PokemonTemp.new if !$PokemonTemp
      if !$PokemonTemp.pokemonDexData
        pbRgssOpen("Data/dexdata.dat","rb"){|f|
           $PokemonTemp.pokemonDexData=f.read
        }
      end
      if block_given?
        StringInput.open($PokemonTemp.pokemonDexData) {|f| yield f }
      else
        return StringInput.open($PokemonTemp.pokemonDexData)
      end
    end
    def pbDexDataOffset(dexdata,species,offset)
      dexdata.pos=76*(species-1)+offset
    end
    def pbLoadPhoneData
      $PokemonTemp=PokemonTemp.new if !$PokemonTemp
      if !$PokemonTemp.pokemonPhoneData
        pbRgssOpen("Data/phone.dat","rb"){|f|
           $PokemonTemp.pokemonPhoneData=Marshal.load(f)
        }
      end
      return $PokemonTemp.pokemonPhoneData
    end
    def pbLoadMetadata
      $PokemonTemp=PokemonTemp.new if !$PokemonTemp
      if !$PokemonTemp.pokemonMetadata
        if !pbRgssExists?("Data/metadata.dat")
          $PokemonTemp.pokemonMetadata=[]
        else
          $PokemonTemp.pokemonMetadata=load_data("Data/metadata.dat")
        end
      end
      return $PokemonTemp.pokemonMetadata
    end
    def pbGetMetadata(mapid,metadataType)
      meta=pbLoadMetadata
      if meta[mapid]
        return meta[mapid][metadataType]
      end
      return nil
    end
     
    module MapFactoryHelper
      @@MapConnections=nil
      @@MapDims=nil
      def self.clear
        @@MapConnections=nil
        @@MapDims=nil
      end
    # Returns the X or Y coordinate of an edge on the map with id.
    # Considers the special strings "N","W","E","S"
      def self.getMapEdge(id,edge)
        return 0 if edge=="N"||edge=="W"
        dims=getMapDims(id) # Get dimensions
        return dims[0] if edge=="E"
        return dims[1] if edge=="S"
        return dims[0] # real dimension (use width)
      end
    # Gets the height and width of the map with id
      def self.getMapDims(id)
        # Create cache if doesn't exist
        if [EMAIL="!@@MapDims"]!@@MapDims[/EMAIL]
          @@MapDims=[]
        end
        # Add map to cache if can't be found
        if [EMAIL="!@@MapDims"]!@@MapDims[/EMAIL][id]
          begin
            map = pbLoadRxData(sprintf("Data/Map%03d", id))
            @@MapDims[id]=[map.width,map.height]
            rescue
            @@MapDims[id]=[0,0]
          end
        end
        # Return map in cache
        return @@MapDims[id]
      end
      def self.getMapConnections
        if [EMAIL="!@@MapConnections"]!@@MapConnections[/EMAIL]
          @@MapConnections=[]
          begin
            conns=load_data("Data/connections.dat")
            rescue
            conns=[]
          end
          for i in 0...conns.length
            conn=conns[i]
            v=getMapEdge(conn[0],conn[1])
            dims=getMapDims(conn[0])
            next if dims[0]==0 || dims[1]==0
            if conn[1]=="N"||conn[1]=="S"
              conn[1]=conn[2]
              conn[2]=v
            elsif conn[1]=="E"||conn[1]=="W"
              conn[1]=v
            end
            v=getMapEdge(conn[3],conn[4])
            dims=getMapDims(conn[3])
            next if dims[0]==0 || dims[1]==0
            if conn[4]=="N"||conn[4]=="S"
              conn[4]=conn[5]
              conn[5]=v
            elsif conn[4]=="E"||conn[4]=="W"
              conn[4]=v
            end
            @@MapConnections.push(conn)
          end
        end
        return @@MapConnections
      end
      def self.hasConnections?(id)
        conns=MapFactoryHelper.getMapConnections
        for conn in conns
          return true if conn[0]==id || conn[3]==id
        end
        return false
      end
      def self.mapInRange?(map)
        dispx=map.display_x
        dispy=map.display_y
        return false if dispx>=map.width*Game_Map.realResX+768
        return false if dispy>=map.height*Game_Map.realResY+768
        return false if dispx<=-(Graphics.width*Game_Map::XSUBPIXEL+768)
        return false if dispy<=-(Graphics.height*Game_Map::YSUBPIXEL+768)
        return true
      end
      def self.mapInRangeById?(id,dispx,dispy)
        dims=MapFactoryHelper.getMapDims(id)
        return false if dispx>=dims[0]*Game_Map.realResX+768
        return false if dispy>=dims[1]*Game_Map.realResY+768
        return false if dispx<=-(Graphics.width*Game_Map::XSUBPIXEL+768)
        return false if dispy<=-(Graphics.height*Game_Map::XSUBPIXEL+768)
        return true
      end
    end
     
    class Game_Map
      def updateTileset
        tileset = $data_tilesets[@map.tileset_id]
        @tileset_name = tileset.tileset_name
        @autotile_names = tileset.autotile_names
        @panorama_name = tileset.panorama_name
        @panorama_hue = tileset.panorama_hue
        @fog_name = tileset.fog_name
        @fog_hue = tileset.fog_hue
        @fog_opacity = tileset.fog_opacity
        @fog_blend_type = tileset.fog_blend_type
        @fog_zoom = tileset.fog_zoom
        @fog_sx = tileset.fog_sx
        @fog_sy = tileset.fog_sy
        @battleback_name = tileset.battleback_name
        @passages = tileset.passages
        @priorities = tileset.priorities
        @terrain_tags = tileset.terrain_tags
      end
    end
     
    def updateTilesets
      maps=$MapFactory.maps
      for map in maps
        map.updateTileset if map
      end
    end
     
    class PokemonMapFactory
      attr_reader :maps
      def initialize(id)
        @fixup=false
        @maps=[]
        @mapChanged=false # transient instance variable
        setup(id)
      end
      def map
        @mapIndex=0 if [EMAIL="!@mapIndex"]!@mapIndex[/EMAIL] || @mapIndex<0
        if [EMAIL="!@maps"]!@maps[/EMAIL][@mapIndex]
          if @maps.length==0
            raise "No maps in save file... ([EMAIL="mapIndex=#{@mapIndex"]mapIndex=#{@mapIndex[/EMAIL]})"
          else
            for i in [EMAIL="[email protected]"][email protected][/EMAIL]
              if @maps[i]
                echo("Using next map, may be incorrect ([EMAIL="mapIndex=#{@mapIndex"]mapIndex=#{@mapIndex[/EMAIL]}, [EMAIL="length=#{@maps.length"]length=#{@maps.length[/EMAIL]})")
                return @maps[i]
              end
              raise "No maps in save file... (all maps empty; [EMAIL="mapIndex=#{@mapIndex"]mapIndex=#{@mapIndex[/EMAIL]})"
            end
          end
        else
          return @maps[@mapIndex]
        end
      end
    # Clears all maps and sets up the current map with id.  This function also sets
    # the positions of neighboring maps and notifies the game system of a map change.
      def setup(id)
        @maps.clear
        @maps[0]=Game_Map.new
        @mapIndex=0
        oldID=(!$game_map) ? 0 : $game_map.map_id
        if oldID!=0 && [EMAIL="oldID!=@maps"]oldID!=@maps[/EMAIL][0]
          setMapChanging(id,@maps[0])
        end
        [EMAIL="$game_map=@maps"]$game_map=@maps[/EMAIL][0]
        @maps[0].setup(id)
        setMapsInRange
        setMapChanged(oldID)
      end
      def hasMap?(id)
        for map in @maps
          if map.map_id==id
            return true
          end
        end
        return false
      end
      def getMapIndex(id)
        for i in [EMAIL="[email protected]"][email protected][/EMAIL]
          if @maps[i].map_id==id
            return i
          end
        end
        return -1
      end
      def setMapChanging(newID,newMap)
        Events.onMapChanging.trigger(self,newID,newMap)
      end
      def setMapChanged(prevMap)
        Events.onMapChange.trigger(self,prevMap)
        @mapChanged=true
      end
      def setSceneStarted(scene)
        Events.onMapSceneChange.trigger(self,scene,@mapChanged)
        @mapChanged=false
      end
    # Similar to Game_Player#passable?, but supports map connections
      def isPassableFromEdge?(x,y)
        return true if $game_map.valid?(x,y)
        newmap=getNewMap(x,y)
        return false if !newmap
        return isPassable?(newmap[0].map_id,newmap[1],newmap[2])
      end
      def isPassableStrict?(mapID,x,y,thisEvent=nil)
        thisEvent=$game_player if !thisEvent
        map=getMapNoAdd(mapID)
        return false if !map
        return false if !map.valid?(x,y)
        return true if thisEvent.through
        if thisEvent==$game_player
          return false unless ($DEBUG && Input.press?(Input::CTRL)) || 
             map.passableStrict?(x,y,0,thisEvent)
        else
          return false unless map.passableStrict?(x,y,0,thisEvent)
        end
        for event in map.events.values
          if event.x == x and event.y == y
            return false if !event.through && (event.character_name!="")
          end
        end
        return true
      end
      def isPassable?(mapID,x,y,thisEvent=nil)
        thisEvent=$game_player if !thisEvent
        map=getMapNoAdd(mapID)
        return false if !map
        return false if !map.valid?(x,y)
        return true if thisEvent.through
        if thisEvent==$game_player
          return false unless ($DEBUG && Input.press?(Input::CTRL)) || 
             map.passable?(x,y,0,thisEvent)
        else
          return false unless map.passable?(x,y,0,thisEvent)
        end
        for event in map.events.values
          if event.x == x and event.y == y
            return false if !event.through && (event.character_name!="")
          end
        end
        if thisEvent.is_a?(Game_Player)
          if thisEvent.x == x and thisEvent.y == y
            return false if !thisEvent.through && thisEvent.character_name != ""
          end
        end
        return true
      end
      def getMap(id)
        for map in @maps
          if map.map_id==id
            return map
          end
        end
        map=Game_Map.new
        map.setup(id)
        @maps.push(map)
        return map
      end
      def getMapNoAdd(id)
        for map in @maps
          if map.map_id==id
            return map
          end
        end
        map=Game_Map.new
        map.setup(id)
        return map
      end
      def updateMaps(scene)
        updateMapsInternal()
        if @mapChanged
          $MapFactory.setSceneStarted(scene)
        end
      end
      def updateMapsInternal # :internal:
        return if $game_player.moving?
        if !MapFactoryHelper.hasConnections?($game_map.map_id)
          return if @maps.length==1
          for i in [EMAIL="[email protected]"][email protected][/EMAIL]
            if [EMAIL="$game_map.map_id!=@maps"]$game_map.map_id!=@maps[/EMAIL][i].map_id
              @maps[i]=nil
            end
          end
          @maps.compact!
          @mapIndex=getMapIndex($game_map.map_id)
          return
        end
        setMapsInRange
        deleted=false
        for i in [EMAIL="[email protected]"][email protected][/EMAIL]
          if !MapFactoryHelper.mapInRange?(@maps[i])
            @maps[i]=nil
            deleted=true 
          end
        end
        if deleted
          @maps.compact!
          @mapIndex=getMapIndex($game_map.map_id)
        end
      end
      def areConnected?(mapID1,mapID2)
        return true if mapID1==mapID2
        conns=MapFactoryHelper.getMapConnections
        for conn in conns
          if (conn[0]==mapID1 && conn[3]==mapID2) ||
             (conn[0]==mapID2 && conn[3]==mapID1)
            return true
          end
        end
        return false
      end
      def getNewMap(playerX,playerY)
        id=$game_map.map_id
        conns=MapFactoryHelper.getMapConnections
        for conn in conns
          next if conn[0]!=id&&conn[3]!=id
          mapidB=nil
          newx=0
          newy=0
          if conn[0]==id
            mapidB=conn[3]
            mapB=MapFactoryHelper.getMapDims(conn[3])
            newx=(conn[4]-conn[1]) + playerX
            newy=(conn[5]-conn[2]) + playerY
          else
            mapidB=conn[0]
            mapB=MapFactoryHelper.getMapDims(conn[0])
            newx=(conn[1]-conn[4]) + playerX
            newy=(conn[2]-conn[5]) + playerY
          end
          if (newx>=0 && newx<mapB[0] && newy>=0 && newy<mapB[1])
            return [getMap(mapidB),newx,newy]
          end
        end
        return nil
      end
      def setCurrentMap
        return if $game_player.moving?
        return if $game_map.valid?($game_player.x,$game_player.y)
        newmap=getNewMap($game_player.x,$game_player.y)
        if newmap
          oldmap=$game_map.map_id
          if oldmap!=0 && oldmap!=newmap[0].map_id
            setMapChanging(newmap[0].map_id,newmap[0])
          end
          $game_map=newmap[0]
          @mapIndex=getMapIndex($game_map.map_id)
          $game_player.moveto(newmap[1],newmap[2])
          $game_map.update
          pbAutoplayOnTransition
          $game_map.refresh
          setMapChanged(oldmap)
        end
      end
      def getTerrainTag(mapid,x,y)
        map=getMapNoAdd(mapid)
        return map.terrain_tag(x,y)
      end
      def getFacingTerrainTag
        tile=getFacingTile
        return 0 if !tile
        return getTerrainTag(tile[0],tile[1],tile[2]) 
      end
      def getRelativePos(thisMapID,thisX,thisY,otherMapID,otherX,otherY)
        if thisMapID==otherMapID
          # Both events share the same map
          return [otherX-thisX,otherY-thisY]
        end
        conns=MapFactoryHelper.getMapConnections
        for conn in conns
          if conn[0]==thisMapID && conn[1]==otherMapID
            posX=(thisX+conn[4]-conn[1])+otherX
            posY=(thisY+conn[5]-conn[2])+otherY
            return [posX,posY]
          elsif conn[1]==thisMapID && conn[0]==otherMapID
            posX=(thisX+conn[1]-conn[4])+otherX
            posY=(thisY+conn[2]-conn[5])+otherY
            return [posX,posY]
          end
        end
        return [0,0]
      end
    # Gets the distance from this event to another event.  Example: If this event's
    # coordinates are (2,5) and the other event's coordinates are (5,1), returns
    # the array (3,-4), because (5-2=3) and (1-5=-4)
      def getThisAndOtherEventRelativePos(thisEvent,otherEvent)
        return [0,0] if !thisEvent || !otherEvent
        return getRelativePos(
           thisEvent.map.map_id,thisEvent.x,thisEvent.y,
           otherEvent.map.map_id,otherEvent.x,otherEvent.y)
      end
      def getThisAndOtherPosRelativePos(thisEvent,otherMapID,otherX,otherY)
        return [0,0] if !thisEvent
        return getRelativePos(
           thisEvent.map.map_id,thisEvent.x,thisEvent.y,
           otherMapID,otherX,otherY)  
      end
      def getOffsetEventPos(event,xOffset,yOffset)
        event=$game_player if !event
        return nil if !event
        return getRealTilePos(event.map.map_id,event.x+xOffset,event.y+yOffset)
      end
      def getRealTilePos(mapID,x,y)
        id=mapID
        if getMapNoAdd(id).valid?(x,y)
          return [id,x,y]
        end
        conns=MapFactoryHelper.getMapConnections
        for conn in conns
          if conn[0]==id
            newX=(x+conn[4]-conn[1])
            newY=(y+conn[5]-conn[2])
            next if newX<0 || newY<0
            dims=MapFactoryHelper.getMapDims(conn[3])
            next if newX>=dims[0] || newY>=dims[1]
            return [conn[3],newX,newY]
          elsif conn[3]==id
            newX=(x+conn[1]-conn[4])
            newY=(y+conn[2]-conn[5])
            next if newX<0 || newY<0
            dims=MapFactoryHelper.getMapDims(conn[0])
            next if newX>=dims[0] || newY>=dims[1]
            return [conn[0],newX,newY]
          end
        end
        return nil
      end
      def getFacingTileFromPos(mapID,x,y,direction=0,steps=1)
        id=mapID
        case direction
          when 1; y+=steps; x-=steps
          when 2; y+=steps
          when 3; y+=steps; x+=steps
          when 4; x-=steps
          when 6; x+=steps
          when 7; y-=steps; x-=steps
          when 8; y-=steps
          when 9; y-=steps; x+=steps
          else
            return [id,x,y]
        end
        return getRealTilePos(mapID,x,y)
      end
      def getFacingTile(direction=nil,event=nil,steps=1)
        event=$game_player if event==nil
        return [0,0,0] if !event
        x=event.x
        y=event.y
        id=event.map.map_id
        direction=event.direction if direction==nil
        return getFacingTileFromPos(id,x,y,direction,steps)
      end
      def setMapsInRange
        return if @fixup
        @fixup=true
        id=$game_map.map_id
        conns=MapFactoryHelper.getMapConnections
        for conn in conns
          if conn[0]==id
            mapA=getMap(conn[0])
            newdispx=(conn[4]-conn[1]) * Game_Map.realResX + mapA.display_x
            newdispy=(conn[5]-conn[2]) * Game_Map.realResY + mapA.display_y
            if hasMap?(conn[3]) || MapFactoryHelper.mapInRangeById?(conn[3],newdispx,newdispy)
              mapB=getMap(conn[3])
              mapB.display_x=newdispx if mapB.display_x!=newdispx
              mapB.display_y=newdispy if mapB.display_y!=newdispy
            end
          elsif conn[3]==id
            mapA=getMap(conn[3])
            newdispx=(conn[1]-conn[4]) * Game_Map.realResX + mapA.display_x
            newdispy=(conn[2]-conn[5]) * Game_Map.realResY + mapA.display_y
            if hasMap?(conn[0]) || MapFactoryHelper.mapInRangeById?(conn[0],newdispx,newdispy)
              mapB=getMap(conn[0])
              mapB.display_x=newdispx if mapB.display_x!=newdispx
              mapB.display_y=newdispy if mapB.display_y!=newdispy
            end
          end
        end
        @fixup=false
      end
    end


    THE LAST 2 SCRIPTS ARE MODIFIED TO WORK WITH THE TRADE SYSTEM


    DO NOT USE WITHOUT SCRIPTING KNOWLEDGE!!!

    NOT TESTED THROUGH FULLY REPORT ANY AND ALL PROBLEMS!!!
     
    There's a problem

    i'm not sure if i don't understand (like with the MGift) but i've tried this from your data pack and from this page and it simply doesnt let me create a trade
    ---------------------------
    Pokemon
    ---------------------------
    Exception: RuntimeError

    Message: Script error within event 4, map 40 (Pokemon Center):

    Exception: Errno::ENOENT

    Message: File Section142:168:in `initialize'Trades/trade.txt not found.

    ***Full script:

    pbCreateTradingFile

    Interpreter:243:in `pbExecuteScript'

    Trading:168:in `open'

    Trading:168:in `pbCreateTradingFile'

    (eval):1:in `pbExecuteScript'

    Interpreter:787:in `eval'

    Interpreter:243:in `pbExecuteScript'

    Interpreter:787:in `command_111'

    Interpreter:319:in `execute_command'

    Interpreter:193:in `update'

    Interpreter:106:in `loop'



    Interpreter:275:in `pbExecuteScript'

    Interpreter:787:in `command_111'

    Interpreter:319:in `execute_command'

    Interpreter:193:in `update'

    Interpreter:106:in `loop'

    Interpreter:198:in `update'

    Scene_Map:103:in `update'

    Scene_Map:101:in `loop'

    Scene_Map:114:in `update'

    Scene_Map:68:in `main'
     
    Status
    Not open for further replies.
    Back
    Top