Advertisement
Deukhoofd

GTS

Jun 11th, 2018
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 17.53 KB | None | 0 0
  1. class GTSHandler
  2.   @Connect
  3.   class << self
  4.     attr_accessor :Connect
  5.   end
  6.   #Handles the menu choices
  7.   def self.handlegts()
  8.     commands = [_INTL("Create Trade"), _INTL("Find Trade"), _INTL("My Trades"),
  9.                 _INTL("Cancel")]
  10.     choice = Kernel.pbMessage(_INTL("What do you want to do?"), commands)
  11.     if choice == 0
  12.       create_trade
  13.     elsif choice == 1
  14.       find_trade
  15.     elsif choice == 2
  16.       $network.send("<GTSMINE>")
  17.     else
  18.       return @Connect.tradeorbattle
  19.     end
  20.   end
  21.  
  22.   def self.create_trade
  23.     pbChoosePokemon(1, 2, proc { |poke|
  24.       !poke.egg? && poke.hp > 0
  25.     }) #TODO
  26.     if $game_variables[1] == -1
  27.       handlegts
  28.     else
  29.       index = $game_variables[1]
  30.       pokestring = [JSON.encode($Trainer.party[index])].pack("m")
  31.       req = GTSRequestHolder.new
  32.  
  33.       pokemonList = ["(Any)", "(Search)"]
  34.       for poke in 1..PBSpecies.maxValue - 1
  35.         if $Trainer.seen[poke]
  36.           name = PBSpecies.getName(poke)
  37.           name = "Delta " + PBSpecies.getName(poke) if poke >= PBSpecies::DELTABULBASAUR
  38.           pokemonList.push(poke.to_s + ": " + PBSpecies.getName(poke))
  39.         end
  40.       end
  41.       pokeVar = Kernel.pbMessage("Please select a Pokemon to search for.", pokemonList)
  42.       if pokeVar < 0
  43.         handlegts
  44.       elsif pokeVar == 0
  45.         req.Species = 0
  46.       elsif pokeVar == 1
  47.         req.Species = -1
  48.         searchTerm = pbEnterText("Search for what Pokemon?", 3, 14).downcase
  49.         if searchTerm.include?("delta")
  50.           searchTerm.slice!("delta")
  51.           searchTerm.strip!
  52.           for i in PBSpecies::DELTABULBASAUR..PBSpecies.maxValue - 1
  53.             if PBSpecies.getName(i).include?(searchTerm)
  54.               req.Species = i
  55.               break
  56.             end
  57.           end
  58.         else
  59.           searchTerm.strip!
  60.           for i in PBSpecies::BULBASAUR..PBSpecies::MISSINGNO
  61.             if PBSpecies.getName(i).include?(searchTerm)
  62.               req.Species = i
  63.               break
  64.             end
  65.           end
  66.         end
  67.       else
  68.         tempAry = []
  69.         for poke in 1..PBSpecies.maxValue - 1
  70.           if $Trainer.seen[poke]
  71.             tempAry.push(poke)
  72.           end
  73.         end
  74.         req.Species = tempAry[pokeVar - 2]
  75.       end
  76.       if req.Species == -1
  77.         Kernel.pbMessage("Pokemon not found.")
  78.         tradeorbattle
  79.       else
  80.         params = ChooseNumberParams.new
  81.         params.setRange(1, 100)
  82.         params.setInitialValue(0)
  83.         params.setCancelValue(0)
  84.         req.MinLevel = Kernel.pbMessageChooseNumber(_INTL("What is the minimum level you want to search for?"), params)
  85.  
  86.         ary = ["Male", "Female", "(Any)"]
  87.         req.Gender = Kernel.pbMessage("What gender are you searching for?", ary)
  88.  
  89.         natureAry = []
  90.  
  91.         for i in 0..24
  92.           natureAry.push(PBNatures.getName(i))
  93.         end
  94.         natureAry.push("(Any)")
  95.         req.Nature = Kernel.pbMessage("What nature would you like to search for?", natureAry)
  96.       end
  97.  
  98.       reqstring = [JSON.encode(req)].pack("m")
  99.       $game_variables[181] = pokestring
  100.       $network.send("<GTSCREATE|offer=#{pokestring}|request=#{reqstring}|index=#{index}>")
  101.     end
  102.   end
  103.  
  104.   def self.checkgtscreate(result, teamindex)
  105.     if result == 0
  106.       Kernel.pbMessage("You were banned from the server")
  107.       return @Connect.tradeorbattle
  108.     elsif result == 1
  109.       Kernel.pbMessage("You already have the maximum number of allowed trades!")
  110.       return @Connect.tradeorbattle
  111.     elsif result == 2
  112.       Kernel.pbMessage("Something went wrong with your request")
  113.       return @Connect.tradeorbattle
  114.     elsif result == 3
  115.       $Trainer.party.delete_at(teamindex)
  116.       Kernel.pbMessage("Your trade was succesfully uploaded")
  117.       pbSave
  118.       return @Connect.tradeorbattle
  119.     end
  120.   end
  121.   ###################################################
  122.   #Simple function to request open trades in the GTS#
  123.   ###############################################################
  124.   #GTSIndex indicates the position you want to receive trades in#
  125.   ###############################################################
  126.   def self.find_trade(gtsindex = 0)
  127.     #the filter class can be found at the bottom of this script
  128.     #general rule of thumb, by changing nothing nothing is filtered out
  129.     filter = RequestFilter.new()
  130.     pokemonList = ["(Any)", "(Search)"]
  131.     for poke in 1..PBSpecies.maxValue - 1
  132.       if $Trainer.seen[poke]
  133.         name = PBSpecies.getName(poke)
  134.         name = "Delta " + PBSpecies.getName(poke) if poke >= PBSpecies::DELTABULBASAUR
  135.         pokemonList.push(poke.to_s + ": " + PBSpecies.getName(poke))
  136.       end
  137.     end
  138.     pokeVar = Kernel.pbMessage("Please select a Pokemon to search for.", pokemonList)
  139.     if pokeVar < 0
  140.       tradeorbattle
  141.     elsif pokeVar == 0
  142.       filter.Species = 0
  143.     elsif pokeVar == 1
  144.       filter.Species = -1
  145.       searchTerm = pbEnterText("Search for what Pokemon?", 3, 14).downcase
  146.       if searchTerm.include?("delta")
  147.         searchTerm.slice!("delta")
  148.         searchTerm.strip!
  149.         for i in PBSpecies::DELTABULBASAUR..PBSpecies.maxValue - 1
  150.           if PBSpecies.getName(i).include?(searchTerm)
  151.             filter.Species = i
  152.             break
  153.           end
  154.         end
  155.       else
  156.         searchTerm.strip!
  157.         for i in PBSpecies::BULBASAUR..PBSpecies::MISSINGNO
  158.           if PBSpecies.getName(i).include?(searchTerm)
  159.             filter.Species = i
  160.             break
  161.           end
  162.         end
  163.       end
  164.     else
  165.       tempAry = []
  166.       for poke in 1..PBSpecies.maxValue - 1
  167.         if $Trainer.seen[poke]
  168.           tempAry.push(poke)
  169.         end
  170.       end
  171.       filter.Species = tempAry[pokeVar - 2]
  172.     end
  173.     if filter.Species == -1
  174.       Kernel.pbMessage("Pokemon not found.")
  175.       return @Connect.tradeorbattle
  176.     else
  177.       params = ChooseNumberParams.new
  178.       params.setRange(1, 100)
  179.       params.setInitialValue(0)
  180.       params.setCancelValue(0)
  181.       filter.MinLevel = Kernel.pbMessageChooseNumber(_INTL("What is the minimum level you want to search for?"), params)
  182.  
  183.       ary = ["Male", "Female", "(Any)"]
  184.       filter.Gender = Kernel.pbMessage("What gender are you searching for?", ary)
  185.  
  186.       natureAry = []
  187.       for i in 0..24 #24
  188.         natureAry.push(PBNatures.getName(i))
  189.       end
  190.       natureAry.push("(Any)")
  191.       # for opt in natureAry
  192.       ##   Kernel.pbMessage(opt)
  193.       #end
  194.  
  195.       filter.Nature = Kernel.pbMessage("What nature would you like to search for?", natureAry)
  196.       #Kernel.pbMessage(filter.Nature.to_s)
  197.  
  198.       #  Kernel.pbMessage(filter.Species.to_s)
  199.       serializefilter = [(JSON.encode(filter))].pack("m")
  200.       $network.send("<GTSREQUEST|index=#{gtsindex}|filter=#{serializefilter}>")
  201.     end
  202.   end
  203.   #############################
  204.   # Display open trades in GTS#
  205.   ###########################################################################
  206.   #Occurs when receives callback message from server, where string contains #
  207.   #a joined array of Pokemon data separated by \r. Function splits up array,#
  208.   #turns the JSON string into an anonymous object, then displays the trades #
  209.   ###########################################################################
  210.   #Own bool indicates if the Trades displayed are the players own trades,in #
  211.   #that case, display options to cancel or, if it's accepted, to receive the#
  212.   #Pokemon traded for it                                                    #
  213.   ###########################################################################
  214.   def self.displaytrades(str, own = false)
  215.     decompressed = str.unpack("m")[0]
  216.     arr = decompressed.split("\r")
  217.     tradearr = []
  218.     if arr.length == 0
  219.       Kernel.pbMessage("No Pokemon found.")
  220.       return @Connect.tradeorbattle
  221.     end
  222.  
  223.     for pokestr in arr
  224.       obj = JSON.decode(pokestr)
  225.       if obj != nil
  226.         tradearr.push(obj)
  227.       end
  228.     end
  229.     #TODO: visual representation of Pokemon in the GTS
  230.     #trades are contained as anonymous objects in the tradearr
  231.     #Pokemons, and requirements are stored in hashes, and can be accessed as such:
  232.     #Request = obj["Request"], MinLevel = obj["Request"]["MinLevel"]
  233.     #OfferedPokemon = obj["Offer"]
  234.     #Offered Pokemon contains all public attributes of a PokeBattle_Pokemon,
  235.     #with the exact same names
  236.     #i.e. obj["Offer"]["species"]
  237.     #lastly the object also contains a bool, obj["Accepted"]
  238.     #this indicates whether the Pokemon has already been traded
  239.     #If the own bool is false, display the option to offer a Pokemon, using
  240.     #gts_offer function,
  241.     #if it's true, display the option to either cancel or, if obj["Accepted"]
  242.     #is true, to collect the trade.
  243.     #lastly the object contains the trade index (obj["Index"]), which is used
  244.     #to send messages to the server of the index of the trade (makes it possible
  245.     #for the server to known what trade you are talking about)
  246.  
  247.     #ALSO TODO make sure that the uplaod does the requests too
  248.     partyOfTrades = []
  249.     @reqData = []
  250.  
  251.     for i in 0..tradearr.length - 1
  252.       partyOfTrades.push(objecttobattler(tradearr[i]["Offer"]))
  253.       @reqData.push(tradearr[i]["Request"])
  254.     end
  255.     $own = own
  256.     #  arrrs=[]
  257.     #  for i in 0..tradearr.length-1
  258.     #    arrrs[i]=tradearr[i]["Offer"]
  259.     #  end
  260.  
  261.     while 1 == 1
  262.       pbChoosePokemon(1, 2, nil, false, partyOfTrades, tradearr)
  263.       var = $game_variables[1]
  264.       if var < 0
  265.         break
  266.       elsif var == 4
  267.         find_trade(tradearr[0]["Index"] - 4)
  268.       elsif var == 5
  269.         find_trade(tradearr[3]["Index"] + 1)
  270.       elsif own
  271.         ary = ["(Cancel)"]
  272.         if tradearr[var]["Accepted"]
  273.           ary.push("Accept")
  274.         end
  275.  
  276.         var2 = Kernel.pbMessage("This is your own. Select an option.", ary)
  277.         if ary[var2] == "(Cancel)"
  278.           gts_cancel(tradearr[var]["Index"])
  279.           return
  280.           #          find_trade(tradearr[0]["Index"])
  281.           #        else
  282.         end
  283.       elsif tradearr[var]["Accepted"]
  284.         Kernel.pbMessage("This trade has already been accepted.")
  285.         find_trade(tradearr[0]["Index"])
  286.       else
  287.         pbChoosePokemon(1, 2, proc { |poke|
  288.           !poke.egg? &&
  289.           (poke.species == tradearr[var]["Request"]["Species"] || tradearr[var]["Request"]["Species"] == 0) &&
  290.           poke.level >= tradearr[var]["Request"]["MinLevel"] &&
  291.           (poke.gender == tradearr[var]["Request"]["Gender"] || tradearr[var]["Request"]["Gender"] == 2) &&
  292.           (poke.nature == tradearr[var]["Request"]["Nature"] || tradearr[var]["Request"]["Nature"] == 25)
  293.         })
  294.         if pbGet(1) >= 0
  295.           gts_offer($game_variables[1], tradearr[var]["Index"])
  296.           break
  297.         end
  298.       end
  299.     end
  300.  
  301.     #Kernel.pbMessage(tradearr.length.to_s)
  302.     $own = nil
  303.     return @Connect.tradeorbattle
  304.   end
  305.  
  306.   ##################################################
  307.   #Simple function to request own trades in the GTS#
  308.   ##################################################
  309.   def self.own_trades
  310.     $network.send("<GTSMINE>")
  311.   end
  312.  
  313.   ##################################################
  314.   #Function to make an offer for a Pokemon         #
  315.   ##################################################
  316.   #Takes int for index of team position of offer,  #
  317.   #and an int for the index of the trade           #
  318.   ##################################################
  319.   def self.gts_offer(teamindex, tradeindex)
  320.     pokestring = [JSON.encode($Trainer.party[teamindex])].pack("m")
  321.     $tempteamno = teamindex
  322.     $network.send("<GTSOFFER|offer=#{pokestring}|id=#{tradeindex}>")
  323.   end
  324.  
  325.   ##########################################################
  326.   #Simple function to display result after making an offer #
  327.   #pkmn contains string "nil", unless result is 3.         #
  328.   ##########################################################
  329.   def self.gts_offer_response(result, pkmn)
  330.     if result == 0
  331.       Kernel.pbMessage("You have been banned from the online server")
  332.       return @Connect.tradeorbattle
  333.     elsif result == 1
  334.       Kernel.pbMessage("This trade has already been traded away")
  335.       return @Connect.tradeorbattle
  336.     elsif result == 2
  337.       Kernel.pbMessage("Your offered Pokemon doesn't fill the requirements for this trade")
  338.       return @Connect.tradeorbattle
  339.     elsif result != 3
  340.       return @Connect.tradeorbattle
  341.     end
  342.     #if we arrived here the trade is accepted, and the pkmn variable contains
  343.     #the new Pokemon
  344.     $Trainer[$tempteamno] = objecttobattler(JSON.decode(pkmn.unpack("m")[0]))
  345.     Kernel.pbMessage("The trade was accepted!")
  346.   end
  347.   #####################################
  348.   #Function to cancel a players trade #
  349.   #####################################
  350.   # index should be index of the trade#
  351.   #####################################
  352.   def self.gts_cancel(index)
  353.     $network.send("<GTSCANCEL|id=#{index}>")
  354.   end
  355.  
  356.   def self.gts_cancel_response(result, pkmn)
  357.     if result == 0
  358.       Kernel.pbMessage("You do not own that trade.")
  359.       return @Connect.tradeorbattle
  360.     elsif result == 1
  361.       Kernel.pbMessage("That trade was already accepted.")
  362.       return @Connect.tradeorbattle
  363.     elsif result != 2
  364.       return @Connect.tradeorbattle
  365.     end
  366.  
  367.     #Trade has been cancelled, put the pokemon back in the team/PC
  368.     #deserialize string pkmn to object, turn object into Battler
  369.     battler = objecttobattler(JSON.decode(pkmn.unpack("m")[0]))
  370.     pbAddPokemonSilent(battler)
  371.     pbSave
  372.     return @Connect.tradeorbattle
  373.   end
  374.  
  375.   #####################################
  376.   #Function to collect a players trade#
  377.   #####################################
  378.   # index should be index of the trade#
  379.   #####################################
  380.   def self.gts_collect(index)
  381.     #    Kernel.pbMessage("Sending collect response...")
  382.     $network.send("<GTSCOLLECT|id=#{index}>")
  383.   end
  384.  
  385.   def self.gts_cancel(index)
  386.     #    Kernel.pbMessage("Sending collect response...")
  387.     $network.send("<GTSCANCEL|id=#{index}>")
  388.   end
  389.  
  390.   def self.gts_collect_response(result, pkmn)
  391.     #  Kernel.pbMessage("Hmm?")
  392.     if result == 0
  393.       Kernel.pbMessage("You do not own that trade")
  394.       return @Connect.tradeorbattle
  395.     elsif result == 1
  396.       Kernel.pbMessage("That trade has not been accepted yet")
  397.       return @Connect.tradeorbattle
  398.     elsif result != 2
  399.       return @Connect.tradeorbattle
  400.     end
  401.  
  402.     #Trade has been completed, put new pokemon in Team/PC
  403.     #deserialize string into object, turn object into Battler
  404.     battler = objecttobattler(JSON.decode(pkmn.unpack("m")[0]))
  405.     Kernel.pbMessage("Received the trade!")
  406.     pbAddPokemonSilent(battler)
  407.     pbSave
  408.   end
  409.  
  410.   def self.objecttobattler(obj, withlevel = false)
  411.     species = obj["species"].to_i
  412.     exp = obj["exp"].to_i
  413.  
  414.     dexdata = pbOpenDexData
  415.     pbDexDataOffset(dexdata, species, 20)
  416.     growth = dexdata.fgetb
  417.     dexdata.close
  418.     if !withlevel
  419.       level = PBExperience.pbGetLevelFromExperience(exp, growth)
  420.     else
  421.       level = obj["level"]
  422.     end
  423.  
  424.     battler = PokeBattle_Pokemon.new(species, level)
  425.     battler.ev = obj["ev"] if obj["ev"].is_a?(Array)
  426.     battler.hp = obj["hp"].to_i
  427.     battler.iv = obj["iv"] if obj["ev"].is_a?(Array)
  428.     battler.ot = obj["ot"].to_s
  429.     battler.exp = obj["exp"].to_i
  430.     battler.setNature(obj["nature"].to_i)
  431.     battler.item = obj["item"].to_i
  432.     battler.setAbility(obj["abilityflag"])
  433.     battler.mail = nil
  434.     battler.name = obj["name"].to_s
  435.     battler.fused = nil
  436.     begin
  437.       battler.moves = []
  438.       for i in 0..(obj["moves"].length - 1)
  439.         m = PBMove.new(obj["moves"][i]["id"].to_i)
  440.         m.pp = obj["moves"][i]["pp"].to_i
  441.         m.ppup = obj["moves"][i]["ppup"].to_i
  442.         battler.moves.push(m)
  443.       end
  444.     rescue
  445.     end
  446.     battler.personalID = obj["personalID"].to_i
  447.     shinyHash = {"true" => true, true => true, "false" => false, false => false}
  448.     battler.makeShiny if shinyHash[obj["isShiny"]]
  449.     for key in obj.keys
  450.       #Kernel.pbMessage(key)
  451.     end
  452.  
  453.     battler.calcStats
  454.     battler.ribbons = obj["ribbons"]
  455.     battler.ballused = obj["ballused"]
  456.     battler.eggsteps = obj["eggsteps"]
  457.     battler.language = obj["language"]
  458.     if obj["markings"] == ""
  459.       battler.markings = 0
  460.     else
  461.       battler.markings = obj["markings"].to_i
  462.     end
  463.     battler.markings = obj["abilityflag"]
  464.     battler.otgender = obj["otgender"]
  465.     battler.happiness = obj["happiness"].to_i - 50
  466.     battler.obtainMap = obj["obtainMap"].to_i
  467.     battler.trainerID = obj["trainerID"].to_i
  468.     battler.hatchedMap = obj["hatchedMap"].to_i
  469.     battler.obtainMode = obj["obtainMode"].to_i
  470.     battler.obtainText = obj["obtainText"].to_s
  471.     battler.itemInitial = obj["itemInitial"].to_i
  472.     battler.itemRecycle = obj["itemRecycle"].to_i
  473.     battler.obtainLevel = obj["obtainLevel"].to_i
  474.     battler.statusCount = obj["statusCount"].to_i
  475.     battler.ballcapsule0 = obj["ballcapsule0"]
  476.     battler.ballcapsule1 = obj["ballcapsule1"]
  477.     battler.ballcapsule2 = obj["ballcapsule2"]
  478.     battler.ballcapsule3 = obj["ballcapsule3"]
  479.     battler.ballcapsule4 = obj["ballcapsule4"]
  480.     battler.ballcapsule5 = obj["ballcapsule5"]
  481.     battler.ballcapsule6 = obj["ballcapsule6"]
  482.     battler.ballcapsule7 = obj["ballcapsule7"]
  483.     battler.timeReceived = obj["timeReceived"]
  484.     battler.pokerus = obj["pokerus"]
  485.  
  486.     return battler
  487.   end
  488. end
  489.  
  490. class RequestFilter
  491.   attr_accessor :MinLevel
  492.   attr_accessor :Species
  493.   attr_accessor :Gender
  494.   attr_accessor :Nature
  495.  
  496.   @MinLevel = 0
  497.   @Species = 0
  498.   @Nature = 0
  499.   @Gender = 0
  500.  
  501.   def initialize()
  502.     @MinLevel = 0
  503.     @Species = 0
  504.     @Gender = 2
  505.     @Nature = 25
  506.   end
  507. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement