Holy87

Universal Module - EN

Jul 23rd, 2015
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 44.69 KB | None | 0 0
  1. $imported = {} if $imported == nil
  2. $imported["H87_UniversalModule"] = 1.6
  3. =begin
  4.  ==============================================================================
  5.   ■ Holy87's Universal Module
  6.       version 1.6.2 - EN
  7.       User difficulty: ★★★
  8.       License: CC-BY. Everyone can distribute this script and use in their free
  9.       and commercial games. Credit required.
  10.  
  11.   ■ This module helps to expand to new levels your scripts and games, allowing
  12.     you to create unique features unthinkable before, in the simplies possible
  13.     method. What you can do with this script?
  14.     ● Saving universal variables that not depend on the savegame
  15.     ● Obtain system information, like screen resolution, system language,
  16.       Windows version, user name, documents folder path etc..
  17.     ● Download a file and/or obtain response from a web server in the easiest
  18.       way
  19.     ● Obtain and set game version information
  20.     ● Coding and decoding strings in Base64 or ROT13
  21.     ● And other features!
  22.  ==============================================================================
  23.   ■ Compatibility
  24.     DataManager -> alias load_normal_database, load_battle_test_database
  25.     Scene_Base  -> alias update
  26.     Window_Base -> alias update
  27.  ==============================================================================
  28.   ■ Installation
  29.     Install this script under Materials, above Main and all scripts that use
  30.     the Universal Module
  31.  ==============================================================================
  32.   ■ Istructions
  33.     Use those methods from script calls or inside your scripts: when you see
  34.     square brackets [] it means that that parameter is optional.
  35.    
  36.   ▼ Universal variables
  37.     The $game_settings global variable saves and stores in game_settings.rvdata2
  38.     file (in the gmae folder) a value that not depends on the savegame. You can
  39.     use this script to save settings in the title screen or unlock an extra option
  40.     when the player ends the game.
  41.     Substantially, the Game_Settings class is an hash, so you can use a key to
  42.     store and load a value. For example:
  43.  
  44.     ● $game_settings[key] = value
  45.       Saves the value with the key. The data is automatically stored when you
  46.       assign a value, but sometimes you need to manually update the file when
  47.       for example the value is an object and you may chang a property in that
  48.       object. So use $game_settings.save to force save.
  49.  
  50.     ● $game_settings[key]
  51.       returns the value provided by key
  52.  
  53.     The data is autmatical
  54.      
  55.     ● You can set up the game version by creating a file in the project's
  56.       folder with "version.ini" name, and write inside the version value
  57.       like 1.0.2.5. You can call the game version with the
  58.       $game_system.game_version method call.
  59.       Ex. version = $game_system.game_version
  60.       print version.major => 1
  61.       print version.minor => 0
  62.       print version.build => 2
  63.       print version.revision => 5
  64.       print version => 1.0.2.5
  65.       print version > "1.0.1.7" => false
  66.  
  67.       vers2 = Version.new("2.0")
  68.       print version < vers2 => true
  69.  
  70.   ▼ System calls
  71.  
  72.     ● Win.version:
  73.       returns a float with the Windows kernel version.
  74.         5.0 -> Windows 2000
  75.         5.1 -> Windows Xp
  76.         5.2 -> Windows Xp (64 bit)
  77.         6.0 -> Windows Vista
  78.         6.1 -> Windows 7
  79.         6.2 -> Windows 8
  80.         6.3 -> Windows 8.1
  81.         10.0-> Windows 10
  82.  
  83.     ● Win.username
  84.       Returns a string with the actual user name of Windows account.
  85.       I.E. print Win.username => "Francesco"
  86.  
  87.     ● Win.homepath
  88.       Returns the user path. I.E.:
  89.       C:/Users/username/                      in Windows Vista, 7, 8
  90.       C:/Documents and Settings/username      in Windows 2000 and Xp
  91.  
  92.     ● Win.getFolderPath([symbol])
  93.       Returns a folder path defined by symbol:
  94.         :docs -> My Documents folder
  95.         :imgs -> My Pictures folder
  96.         :dskt -> Desktop folder
  97.         :musc -> Music folder
  98.         :vdeo -> Movies folder
  99.         :prog -> Program Files folder (C:\Program Files (x86))
  100.         * if a symbol is not defined, it means :docs
  101.  
  102.         Example:
  103.         print Win.getFolderPath(:deskt) => "C:/Users/Francesco/Desktop"
  104.  
  105.     ● Win.shutdown[(mode)]
  106.       Shuts down the PC, settings by mode (0 for default):
  107.         0: normal shutdown
  108.         1: reset
  109.         2: hybernate
  110.  
  111.     ● Win.open(filepath)
  112.       Opens a folder or a file. Specify the path in filepath
  113.         Win.open(C:/Windows/system32/calc.exe) opens calculator
  114.         Win.open(Win.getFolderPath(:imgs)) it will open the Images
  115.         folder
  116.  
  117.     ● Win.temp_flush(nomefile)
  118.       Deletes the temporary data of the file name (if downloaded more
  119.       times) This method is not used anymore.
  120.      
  121.     ● Win.language
  122.       Returns a int code with the system language in use. For the complete
  123.       code list, see this link below:
  124.       http://support.microsoft.com/kb/193080
  125.  
  126.     ● Win.screen_resolution
  127.       returns an array with two integers containing the screen resolution
  128.       (es. [1024,730]). You may know that this method doesn't return the
  129.       full resolution, but only the screen part not covered by the taskbar.
  130.  
  131.     ● Screen.resize(width, height)
  132.       Change the game screen size. This method NOT changes the game resolution,
  133.       only makes the screen bigger.
  134.      
  135.   ▼ String methods
  136.  
  137.     ● println
  138.       like print, but adds automatically \n at the end of the string
  139.    
  140.     ● String.random([lenght])
  141.       Returns a random string. If lenght is not defined, then the string
  142.       is 4
  143.       Examples:
  144.       print String.random     #=> ajpf
  145.       print String.random(7)  #=> opetnpg
  146.      
  147.     ● crypt_rot13
  148.       Crypts a string in ROT13 format (moves all characters by 13 steps
  149.       in the alphabet). Recall this method on the same string to decode
  150.       print "Casa".crypt_rot13    #=> "Pnfn"
  151.       print "Pnfn".crypt_rot13    #=> "Casa"
  152.      
  153.     ● Base64.encode(string) and Base64.decode(string)
  154.       Returns a string coded in Base64 for interchange of web data
  155.       Per other info: wikipedia.org/wiki/Base64
  156.  
  157.   ▼ Internet and HTTP
  158.  
  159.     ----------------------------------------------------------------------------
  160.     * Simplified method for sync operations
  161.     ----------------------------------------------------------------------------
  162.     The async methods allow an easy handle for download and internet responses,
  163.     so you can use less code possible and be more efficient. Those methods can
  164.     be only used within Scene and Window classes, if you want to use in your
  165.     custom classes, then include the Async_Downloads module.
  166.    
  167.     ● download_async(url, method[, priority, folder])
  168.       Starts a download from url. It launchs automatically the method when the
  169.       download is completed.
  170.       Examples:
  171.       download_async("www.mysite.com/image.jpg", method(:image_downloaded))
  172.       (you must defined the image_downloaded method also)
  173.       The file download is slow, to not slow the game. If you want speed up
  174.       the download, set true in priority
  175.      
  176.     ● get_response_async(url, method, priority)
  177.       Starts the reception of a web service response from the URL, and launches
  178.       the defined method when the response is received. Unlike the previous,
  179.       the method that will be called must have an input parameter, that will
  180.       be the string that you receive from the internet call.      
  181.      
  182.     ● abort_download(filename)
  183.       Cancels the file download.
  184.      
  185.     ● download_status(filename)
  186.       Retrns a number from 0 to 100 that represents the download progress.
  187.      
  188.     ----------------------------------------------------------------------------
  189.     * Complex methods for downloads
  190.     ----------------------------------------------------------------------------
  191.     Questi metodi possono essere usati ovunque e permettono una gestione più
  192.     complessa e funzionale dei download. Possono anche essere usati affiancati
  193.     ai metodi più semplici.
  194.    
  195.     ● await_response(url)
  196.       Send a request to a web server and wait for the response, then returns
  197.       the value. Example:
  198.       print await_response(www.mysite.com)
  199.       This code will print the HTML code of mysite.com.
  200.  
  201.     ● HTTP.domain
  202.       returns your main server domain (configured below).
  203.    
  204.     ● HTTP.download(url[,folderpath[,low_priority]])
  205.       Downloads a file from url. If the folderpath is omitted, it will store the
  206.       file in the game_folder ("./"). Example:
  207.       HTTP.download("http://www.miosito.it/immagine.png","./Graphics/Pictures")
  208.         it will download immagine.png in the Pictures folder.
  209.       HTTP.download("http://www.miosito.it/immagine.png")
  210.         it will download the immagine.png file in game folder.
  211.       HTTP.download(HTTP.domain+"/immagine.png", Win.getFolderPath(:dskt))
  212.         it will download immagine.png from mysite.com on my desktop.
  213.       You can set true to download the file more slowly, but you will have
  214.       less game shuttering.
  215.      
  216.     ● HTTP.get_server_response(url, response_name)
  217.       Sent a request to url and stores the response in an hash with
  218.       response_name key.
  219.      
  220.     ● HTTP.await_response(url)
  221.       Like await_response
  222.      
  223.     ● HTTP.response(response_name)
  224.       Returns the response stored.
  225.  
  226.     ● HTTP.downloaded?(filename/response_name)
  227.       Returns true if the response is obtained or the file is downloaded.
  228.       Returns false if is not completely downloaded or the download isn't
  229.       started.
  230.      
  231.     ● HTTP.progress(filename)
  232.       Return the download progress of filename (from 0.0 to 100.0)
  233.  
  234.     ● HTTP.filesize(nomefile)
  235.       returns the file size of the downloading file
  236.  
  237.     ● HTTP.sizeloaded(nomefile)
  238.       returns the downloaded data of the file in bit. You may divide per 8
  239.       to obtain the byte size.
  240.  
  241.     ● HTTP.time_passed(nomefile)
  242.       returns the time passed from the start of the download
  243.  
  244.     ● HTTP.downloads
  245.       returns an hash containing all the download instances
  246.  
  247.     ● HTTP.completed
  248.       returns the number of completed downloads
  249.      
  250.     ● HTTP.get_file_size(url)
  251.       returns the file size on a weblink
  252.  
  253.     ● HTTP.file_good?(nomefile)
  254.       checks if the file is good
  255.  
  256.     ● Browser.open(url)
  257.       opens your default browser on the url.
  258. =end
  259.  
  260. #==============================================================================
  261. module H87_ModConfig
  262.   HTTPDOMAIN = "http://mysite.com"
  263.   SETTINGNAME = "game_settings.rvdata2"
  264.   VERSIONFILE = "version.ini"
  265. end
  266. #==============================================================================
  267. # ** Win
  268. #------------------------------------------------------------------------------
  269. #  Questo modulo gestisce le chiamate di sistema e recupera informazioni sul
  270. #  computer
  271. #==============================================================================
  272. module Win
  273.   #-----------------------------------------------------------------------------
  274.   # *Nome Utente Windows
  275.   # Restituisce il nome utente di Windows
  276.   #-----------------------------------------------------------------------------
  277.   def self.username
  278.     name = " " * 128  
  279.     size = "128"  
  280.     Win32API.new('advapi32','GetUserName',['P','P'],'I').call(name,size)
  281.     username = name.unpack("A*")
  282.     return username[0]
  283.   end  
  284.   # --------------------------------------------------------------------------
  285.   # * Restituisce la cartella utente di Windows
  286.   # --------------------------------------------------------------------------
  287.   def self.homepath
  288.     name = " " * 128  
  289.     size = "128"  
  290.     username = "\0" * 256 #userprofile
  291.     Win32API.new('kernel32', 'GetEnvironmentVariable', %w(p p l), 'l').call("userprofile", username, 256)
  292.     username.delete!("\0")
  293.     return username.gsub("\\","/")
  294.   end
  295.   # --------------------------------------------------------------------------
  296.   # * Restituisce il percorso di una cartella del computer
  297.   # --------------------------------------------------------------------------
  298.   def self.getFolderPath(symbol = :docs)
  299.     case symbol
  300.     when :user; index = 40
  301.     when :docs; index = 5
  302.     when :imgs; index = 39
  303.     when :musc; index = 13
  304.     when :vdeo; index = 14
  305.     when :strp; index = 2
  306.     when :prog; index = 38
  307.     when :appd; index = 28
  308.     else; index = 0
  309.     end
  310.     path = "\0" * 128  
  311.     Win32API.new('shell32', 'SHGetFolderPath', 'LLLLP', 'L').call(0, index, 0, 2, path)
  312.     return path.delete("\0").gsub("\\","/")
  313.   end
  314.   # --------------------------------------------------------------------------
  315.   # * Restituisce la larghezza della cornice della finestra
  316.   # --------------------------------------------------------------------------
  317.   def self.window_frame_width
  318.     return Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(7)
  319.   end
  320.   # --------------------------------------------------------------------------
  321.   # * Restituisce l'altezza della barra del titolo
  322.   # --------------------------------------------------------------------------
  323.   def self.window_title_height
  324.     return Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(4)
  325.   end
  326.   #-----------------------------------------------------------------------------
  327.   # * Elimina il file temporaneo per aggiornarlo prima di un download.
  328.   #   inserire il nome del file.
  329.   #-----------------------------------------------------------------------------
  330.   def self.temp_flush(nomefile)
  331.     if version < 6
  332.       path = homepath+"/Impostazioni locali/Temporary Internet Files"
  333.       unless File.directory?(path)
  334.         path = homepath+"/Local Settings/Temporary Internet Files"
  335.         return unless File.directory?(path)
  336.       end
  337.       fetch_folder_for_delete(path,nomefile)
  338.     else
  339.       path = homepath+"/AppData/Local/Microsoft/Windows/Temporary Internet Files/Content.IE5"
  340.       unless File.directory?(path)
  341.         path = cartella_utente_win+"/AppData/Local/Microsoft/Windows/INetCache/IE"
  342.       end
  343.       return unless File.directory?(path)
  344.       Dir.foreach(path) {|x|                        #per ogni file nel percorso
  345.         next if x == "." or x == ".."               #passa al prossimo se è ind.
  346.         if File.directory?(path+"/"+x)              #se il file è una cartella
  347.           folder = path+"/"+x                       #entra nella cartella
  348.           fetch_folder_for_delete(folder,nomefile)
  349.         end
  350.       }
  351.     end
  352.   end
  353.   # --------------------------------------------------------------------------
  354.   # * Cerca nella cartella il file da cancellare
  355.   #   path: directory
  356.   #   nomefile: file da cancellare
  357.   # --------------------------------------------------------------------------
  358.   def self.fetch_folder_for_delete(path,nomefile)
  359.     Dir.foreach(path) {|y|                  #per ogni file nella cartella
  360.       next if File.directory?(path+"/"+y)   #passa al prossimo se è una c.
  361.       if no_ext(nomefile) == y[0..no_ext(nomefile).size-1]#se l'inizio del nome corrisp.
  362.         begin
  363.           File.delete(path+"/"+y)             #eliminalo
  364.         rescue
  365.           next
  366.         end
  367.       end
  368.     }
  369.   end
  370.   # --------------------------------------------------------------------------
  371.   # * Restituisce la versione di Windows in uso
  372.   # --------------------------------------------------------------------------
  373.   def self.version
  374.     gvex = Win32API.new( 'kernel32', 'GetVersionEx', ['P'], 'I' )
  375.     s = [20+128, 0, 0, 0, 0, '' ].pack('LLLLLa128')
  376.     gvex.call( s );
  377.     a = s.unpack( 'LLLLLa128' )
  378.     indice = a[1].to_f;dec = a[2].to_f/10
  379.     return indice + dec
  380.   end
  381.   #-----------------------------------------------------------------------------
  382.   # * Restituisce il nome del file senza estensione.
  383.   #-----------------------------------------------------------------------------
  384.   def self.no_ext(nomefile)
  385.     nome = nomefile.split(".")
  386.     return nome[0]
  387.   end
  388.   #-----------------------------------------------------------------------------
  389.   # * Restituisce un array di larghezza e altezza della parte utilizzabile dello
  390.   #   schermo: non conta lo spazio della barra delle applicazioni.
  391.   #-----------------------------------------------------------------------------
  392.   def self.screen_resolution
  393.     x = Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(16)
  394.     y = Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(17)
  395.     return [x,y]
  396.   end
  397.   #-----------------------------------------------------------------------------
  398.   # * Restituisce un intero come codice della lingua del sistema
  399.   #-----------------------------------------------------------------------------
  400.   def self.language
  401.     return Win32API.new("kernel32", "GetUserDefaultLCID", [], 'I').call
  402.   end
  403.   #-----------------------------------------------------------------------------
  404.   # * Restituisce la data attuale
  405.   #-----------------------------------------------------------------------------
  406.   def self.datenow(partition = -1)
  407.     date = Time.now
  408.     case partition
  409.     when -1
  410.       return sprintf("%d/%d/%d",date.day,date.month,date.year)
  411.     when 0
  412.       return date.day
  413.     when 1
  414.       return date.month
  415.     when 2
  416.       return date.year
  417.     end
  418.   end
  419.   #-----------------------------------------------------------------------------
  420.   # * Restituisce l'ora attuale
  421.   #-----------------------------------------------------------------------------
  422.   def self.timenow(partition = -1)
  423.     date = Time.now
  424.     case partition
  425.     when -1
  426.       return sprintf("%d:%d",date.hour,date.min)
  427.     when 0
  428.       return date.hour
  429.     when 1
  430.       return date.min
  431.     when 2
  432.       return date.sec
  433.     end
  434.   end
  435.   #-----------------------------------------------------------------------------
  436.   # * arresta il computer in modalità diverse.
  437.   #-----------------------------------------------------------------------------
  438.   def self.shutdown(mode = 0)
  439.     string = "system "
  440.     case mode
  441.     when 0
  442.       string += "-s"
  443.     when 1
  444.       string += "-r"
  445.     when 2
  446.       string += "-h"
  447.     end
  448.     system(string)
  449.   end  
  450. end #win
  451.  
  452. #==============================================================================
  453. # ** Screen
  454. #------------------------------------------------------------------------------
  455. #  Questo modulo gestisce il ridimensionamento della finestra di gioco
  456. #==============================================================================
  457. module Screen
  458.   #-----------------------------------------------------------------------------
  459.   # * ridimensiona la finestra e la centra
  460.   #   width = nuova larghezza
  461.   #   height = nuova altezza
  462.   #-----------------------------------------------------------------------------
  463.   def self.resize(width ,height)
  464.     #API
  465.     getSystemMetrics = Win32API.new("user32", "GetSystemMetrics", 'I', 'I')
  466.     moveWindow = Win32API.new("user32","MoveWindow",['l','i','i','i','i','l'],'l')
  467.     findWindowEx = Win32API.new("user32","FindWindowEx",['l','l','p','p'],'i')
  468.     this_window = findWindowEx.call(0,0,"RGSS Player",0)
  469.     res_x = Win.screen_resolution[0] #risoluzione x
  470.     res_y = Win.screen_resolution[1] #risoluzione y
  471.     width += Win.window_frame_width*2
  472.     height += Win.window_frame_width*2 + Win.window_title_height
  473.     new_x = [(res_x-width)/2, 0].max #ottiene la nuova coordinata, ma non
  474.     new_y = [(res_y-height)/2, 0].max#fa passare oltre il bordo
  475.     moveWindow.call(this_window, new_x, new_y, width, height, 1)
  476.   end
  477. end #screen
  478.  
  479. #==============================================================================
  480. # ** HTTP
  481. #------------------------------------------------------------------------------
  482. #  Questo modulo permette di interfacciarsi ad internet e gestire i download.
  483. #  Ringraziamenti: Berka (il codice è ispirato al suo)
  484. #==============================================================================
  485. module HTTP  
  486.   SetPrClass = Win32API.new('kernel32','SetPriorityClass','pi','i').call(-1,128)
  487.   InternetOpenA = Win32API.new("wininet",'InternetOpenA','plppl','l').call('',0,'','',0)
  488.   InternetConnectA = Win32API.new("wininet",'InternetConnectA','lplpplll','l')
  489.   InternetOpenUrl = Win32API.new("wininet",'InternetOpenUrl','lppllp','l')
  490.   InternetReadFile = Win32API.new("wininet",'InternetReadFile','lpip','l')
  491.   InternetCloseHandle = Win32API.new("wininet",'InternetCloseHandle','l','l')
  492.   HttpQueryInfo = Win32API.new("wininet",'HttpQueryInfo','llppp','i')
  493.   #--------------------------------------------------------------------------
  494.   # * Scarica un file da internet in un thread separato
  495.   # url = indirizzo completo del nome del file
  496.   # folder = cartella dove depositare il file scaricato
  497.   #--------------------------------------------------------------------------
  498.   def self.download(url, folder = "./", low_priority = false, filename = nil, save = true)
  499.     #inizializzazione
  500.     @downloaded = 0 if @downloaded.nil?
  501.     @downloads = {} if @downloads.nil?
  502.     @counter = -1 if @counter.nil?
  503.     @size = {} if @size.nil?
  504.     @received = {} if @received.nil?
  505.     @timepassed = {} if @timepassed.nil?
  506.     @response = {} if @response.nil?
  507.     @completed = {} if @completed.nil?
  508.    
  509.     #ottenimento dell'indirizzo
  510.     address = url.split('/')
  511.     server = address[2]
  512.     root = address[3..address.size].join('/')
  513.     filename = address[-1] if filename == nil
  514.    
  515.     #crezione del thread
  516.     @downloads[filename] = Thread.start(url,folder, save){|url,folder,save|
  517.       txt = ""
  518.       t = Time.now
  519.       "Serv f" if(e=InternetConnectA.call(InternetOpenA,server,80,'','',3,1,0))==0
  520.       file = InternetOpenUrl.call(InternetOpenA,url,nil,0,0,0)
  521.       HttpQueryInfo.call(file,5,k="\0"*1024,[k.size-1].pack('l'),nil)
  522.       @received[filename] = 0
  523.       @size[filename] = k.delete!("\0").to_i
  524.       loop do
  525.         buffer = " "*1024
  526.         n = 0
  527.         r = InternetReadFile.call(file,buffer,1024,o=[n].pack('i!'))
  528.         n = o.unpack('i!')[0]
  529.         txt<<buffer[0,n]
  530.         @response[filename] = txt if !save
  531.         @received[filename] = txt.size
  532.         if r&&n==0
  533.           break
  534.         end
  535.         sleep(0.001) if low_priority
  536.       end
  537.       #creazione del file nel percorso
  538.       if save
  539.         if File.directory?(folder)
  540.           obj = File.open(folder + filename,'wb')<<txt
  541.           obj.close #chiusura del file
  542.         else
  543.           string = "%s non è un percorso valido, pertanto %s non verrà salvato."
  544.           println sprintf(string, folder, filename)
  545.         end
  546.       end
  547.       @received[filename] = @size[filename]
  548.       @completed[filename] = true
  549.       @downloaded += @received[filename]
  550.       InternetCloseHandle.call(file)
  551.       sleep(0.01)
  552.       @timepassed[filename] = Time.now-t
  553.       }
  554.   end
  555.   #--------------------------------------------------------------------------
  556.   # * Ottiene la dimensione di un file remoto in modo asincrono
  557.   #--------------------------------------------------------------------------
  558.   def self.get_file_size_async(url)
  559.     @filesize = {} if @filesize.nil?
  560.     Thread.start(url){|url|
  561.       @filesize[url] = get_file_size(url)
  562.     }
  563.   end
  564.   #--------------------------------------------------------------------------
  565.   # * Restituisce true se la dimensione del file è stata ottenuta
  566.   #--------------------------------------------------------------------------
  567.   def self.size_get?(url)
  568.     return false if @filesize.nil?
  569.     return @filesize[url] != nil?
  570.   end
  571.   #--------------------------------------------------------------------------
  572.   # * Ottiene la dimensione di un file remoto
  573.   #--------------------------------------------------------------------------
  574.   def self.get_file_size(url)
  575.     file = InternetOpenUrl.call(InternetOpenA,url,nil,0,0,0)
  576.     HttpQueryInfo.call(file,5,k="\0"*1024,[k.size-1].pack('l'),nil)
  577.     InternetCloseHandle.call(file)
  578.     return k.delete!("\0").to_i
  579.   end
  580.   #--------------------------------------------------------------------------
  581.   # * Ottiene la risposta del server e la piazza nell'array delle rispose
  582.   #   url: indirizzo della richiesta
  583.   #   response_name: nome della risposta (per poterla leggere)
  584.   #   low_priority: priorità (false se normale, true se bassa)
  585.   #--------------------------------------------------------------------------
  586.   def self.get_server_response(url, response_name, low_priority = false)
  587.     download(url, "", low_priority, response_name, false)
  588.   end
  589.   #--------------------------------------------------------------------------
  590.   # * Restituisce direttamente il testo di risposta dal server, interrompendo
  591.   #   l'esecuzione del gioco fino a quando non arriva la risposta.
  592.   #   url: indirizzo della richiesta
  593.   #--------------------------------------------------------------------------
  594.   def self.await_get_server_response(url)
  595.     response = "response"
  596.     @response.delete(response) if @response != nil
  597.     @received.delete(response) if @received != nil
  598.     @downloads.delete(response) if @downloads != nil
  599.     download(url, "", false, response, false)
  600.     loop {break if downloaded?(response)}
  601.     return @response[response]
  602.   end
  603.   class << self; alias await_response await_get_server_response; end
  604.   #--------------------------------------------------------------------------
  605.   # * Restituisce true se il file è scaricato.
  606.   # filename: nome del file
  607.   #--------------------------------------------------------------------------
  608.   def self.downloaded?(filename)
  609.     return false if @received.nil?
  610.     return false if @received[filename].nil?
  611.     return false if @size[filename].nil?
  612.     return true if @received[filename] >= @size[filename]
  613.     return true if progress(filename) >= 100
  614.     return true if progress(filename).to_s == "NaN"
  615.     return true if @completed[filename]
  616.     return false
  617.   end
  618.   #--------------------------------------------------------------------------
  619.   # * Restituisce la grandezza del file da scaricare in byte
  620.   # filename: nome del file
  621.   #--------------------------------------------------------------------------
  622.   def self.filesize(filename)
  623.     return 0 if @size.nil?
  624.     return 0 if @size[filename].nil?
  625.     return @size[filename]
  626.   end
  627.   #--------------------------------------------------------------------------
  628.   # * Restituisce la quantità di byte scaricati
  629.   # filename: nome del file
  630.   #--------------------------------------------------------------------------
  631.   def self.sizeloaded(filename)
  632.     return 0 if @received.nil?
  633.     return 0 if @received[filename].nil?
  634.     return @received[filename]
  635.   end
  636.   #--------------------------------------------------------------------------
  637.   # * Restituisce la percentuale di progresso del download
  638.   # filename: nome del file
  639.   #--------------------------------------------------------------------------
  640.   def self.progress(filename)
  641.     @received = {} if @received.nil?
  642.     return 0 if @received[filename].nil?
  643.     return @received[filename].to_f/@size[filename]*100
  644.   end
  645.   #--------------------------------------------------------------------------
  646.   # * Restituisce l'hash dei download
  647.   #--------------------------------------------------------------------------
  648.   def downloads
  649.     return {} if @downloads.nil?
  650.     return @downloads
  651.   end
  652.   #--------------------------------------------------------------------------
  653.   # * Restituisce il numero di secondi che ci sono voluti per scaricare
  654.   #--------------------------------------------------------------------------
  655.   def self.time_passed(filename)
  656.     return 0 if @timepassed[filename] == nil
  657.     return @timepassed[filename]
  658.   end
  659.   #--------------------------------------------------------------------------
  660.   # * Restituisce il numero dei download completati
  661.   #--------------------------------------------------------------------------
  662.   def self.completed
  663.     return 0 if @downloaded.nil?
  664.     return @downloaded
  665.   end
  666.   #--------------------------------------------------------------------------
  667.   # * Restituisce la risposta dal server
  668.   #   response_name: id della risposta
  669.   #--------------------------------------------------------------------------
  670.   def self.response(response_name)
  671.     return 0 if @response.nil? || @response[response_name].nil?
  672.     return @response[response_name]
  673.   end
  674.   #--------------------------------------------------------------------------
  675.   # * Restituisce i download
  676.   #--------------------------------------------------------------------------
  677.   def self.downloads
  678.     @downloads ||= {}
  679.     return @downloads
  680.   end
  681.   #--------------------------------------------------------------------------
  682.   # * Restituisce il dominio principale
  683.   #--------------------------------------------------------------------------
  684.   def self.domain
  685.     H87_ModConfig::HTTPDOMAIN
  686.   end
  687.   #--------------------------------------------------------------------------
  688.   # * Controlla se il file scaricato è buono e restituisce true o false
  689.   #--------------------------------------------------------------------------
  690.   def self.file_good?(filename)
  691.     if File.exist? (filename) #apre il file in sola lett.
  692.       File.open(filename,"r") do |f|
  693.       f.lineno = 1 # imposta la riga n.1
  694.       txt = f.gets
  695.       return check_response(txt)
  696.       end
  697.     else
  698.       return false
  699.     end
  700.   end
  701.   #--------------------------------------------------------------------------
  702.   # * Restituisce true se il testo non è vuoto
  703.   #--------------------------------------------------------------------------
  704.   def self.check_response(text)
  705.     return false if text == "" or text.nil?
  706.     first = text[0].chr
  707.     return false if first == "" or first == nil
  708.     return true
  709.   end
  710. end #http
  711.  
  712. #==============================================================================
  713. # ** Async_Downloads
  714. #------------------------------------------------------------------------------
  715. #  Dev'essere incluso nelle classi che fanno uso dei metodi download_async.
  716. #==============================================================================
  717. module Async_Downloads
  718.   #--------------------------------------------------------------------------
  719.   # * Scarica un file in modo asincrono lanciando automaticamente il metodo.
  720.   #   url:          indirizzo del file
  721.   #   method_name:  nome del metodo, in simbolo (ad es. :apri)
  722.   #   low:          true se è a bassa incidenza, false altrimenti
  723.   #   folder:       percorso del file di salvataggio
  724.   #--------------------------------------------------------------------------
  725.   def download_async(url, method, folder = "./", low = true)
  726.     filename = url.split('/')[-1]
  727.     if filename.downcase.include? ".php"
  728.       println "Questo URL chiama un file PHP, pertanto non verrà salvato."
  729.       println "Utilizzare invece il metodo get_repsonse_async."
  730.       return
  731.     end
  732.     @async_downloads = {} if @async_downloads.nil?
  733.     @async_downloads[filename] = method
  734.     HTTP.download(url, folder, low)
  735.   end
  736.   #--------------------------------------------------------------------------
  737.   # * Ottiene la risposta di un servizio web in modo asincrono, lanciando
  738.   #   automaticamente il metodo associato.
  739.   #   url:          indirizzo della richiesta
  740.   #   method_name:  nome del metodo, in simbolo (ad es. :apri)
  741.   #   low:          true se è a bassa incidenza, false altrimenti
  742.   #   response_id:  id della risposta.
  743.   #--------------------------------------------------------------------------
  744.   def get_response_async(url, method, low = true, response_id = String.random(20))
  745.     @async_responses = {} if @async_responses.nil?
  746.     @async_responses[response_id] = method
  747.     HTTP.get_server_response(url, response_id, low)
  748.   end
  749.   #--------------------------------------------------------------------------
  750.   # * Restituisce direttamente la stringa di risposta dal server
  751.   #   url: indirizzo della richiesta
  752.   #--------------------------------------------------------------------------
  753.   def await_response(url)
  754.     return HTTP.await_get_server_response(url)
  755.   end
  756.   #--------------------------------------------------------------------------
  757.   # * Controlla i download e lancia il metodo associato se completato.
  758.   #--------------------------------------------------------------------------
  759.   def check_async_downloads
  760.     return if @async_downloads.nil? || @async_downloads.size == 0
  761.     @async_downloads.each_key do |key|
  762.       if HTTP.downloaded?(key)
  763.         @async_downloads[key].call
  764.         @async_downloads.delete(key)
  765.       end
  766.     end
  767.   end
  768.   #--------------------------------------------------------------------------
  769.   # * Controlla le risposte e lancia il metodo associato quando ricevuta.
  770.   #--------------------------------------------------------------------------
  771.   def check_async_requests
  772.     return if @async_responses.nil? || @async_responses.size == 0
  773.     @async_responses.each_key do |key|
  774.       if HTTP.downloaded?(key) && HTTP.response(key) != nil
  775.         @async_responses[key].call(HTTP.response(key))
  776.         @async_responses.delete(key)
  777.       end
  778.     end
  779.   end
  780.   #--------------------------------------------------------------------------
  781.   # * Cancella un download o l'attesa di una risposta
  782.   #   filename: nome del file o id della risposta
  783.   #--------------------------------------------------------------------------
  784.   def abort_download(filename)
  785.     Thread.kill(HTTP.downloads(filename))
  786.   end
  787.   #--------------------------------------------------------------------------
  788.   # * Restituisce la percentuale di download da 0 a 100
  789.   #   filename: nome del file
  790.   #--------------------------------------------------------------------------
  791.   def download_status(filename)
  792.     status = HTTP.progress(filename)
  793.     return [[0, status].max, 100].min.to_i
  794.   end
  795. end
  796.  
  797. #==============================================================================
  798. # ** Modulo Browser per aprire il browser predefinito del PC
  799. #==============================================================================
  800. module Browser
  801.   #--------------------------------------------------------------------------
  802.   # * apre il browser
  803.   #   url: url impostato
  804.   #--------------------------------------------------------------------------
  805.   def self.open(url)
  806.     #controlla che ci siano prefissi
  807.     if url[0..6] != "http://" and url[0..7] != "https://"
  808.       open_url = "http://"+url
  809.     else
  810.       open_url = url
  811.     end
  812.     shell = Win32API.new("Shell32", "ShellExecute", ['L', 'P', 'P', 'P','P', 'L'], 'L')
  813.     Thread.new{shell.call(0, "open", open_url, 0, 0, 1)}
  814.     sleep(0.01)
  815.     SceneManager.exit
  816.   end
  817. end #browser
  818.  
  819. #==============================================================================
  820. # ** Modulo Browser per la codifica/decodifica di stringhe in Base64
  821. #==============================================================================
  822. module Base64
  823.   #--------------------------------------------------------------------------
  824.   # * Restituisce una stringa decodificata da Base64
  825.   #     string: stringa da decodificare
  826.   #--------------------------------------------------------------------------
  827.   def self.decode(string)
  828.     return string.gsub(/\s+/, "").unpack("m")[0]
  829.   end
  830.   #--------------------------------------------------------------------------
  831.   # * Restituisce una stringa codificata in Base64
  832.   #     string: stringa da codificare
  833.   #--------------------------------------------------------------------------
  834.   def self.encode(string)
  835.     return [string].pack("m")
  836.   end
  837. end #base64
  838.  
  839. #==============================================================================
  840. # ** Classe Settings (per le impostazioni comuni ai salvataggi)
  841. #==============================================================================
  842. class H87_Settings
  843.   #--------------------------------------------------------------------------
  844.   # * restituisce l'elemento corrispondente al parametro
  845.   #--------------------------------------------------------------------------
  846.   def [](param)
  847.     @settings[param]
  848.   end
  849.   #--------------------------------------------------------------------------
  850.   # * inizializzazione
  851.   #--------------------------------------------------------------------------
  852.   def initialize
  853.     @settings = {}
  854.   end
  855.   #--------------------------------------------------------------------------
  856.   # * cambia o aggiunge un elemento dell'hash
  857.   #--------------------------------------------------------------------------
  858.   def []=(param_name,value)
  859.     @settings[param_name] = value
  860.     save
  861.   end
  862.   #--------------------------------------------------------------------------
  863.   # * Registra i dati salvati
  864.   #--------------------------------------------------------------------------
  865.   def save
  866.     save_data($game_settings,DataManager.settings_path)
  867.   end
  868. end #settings
  869.  
  870. #==============================================================================
  871. # ** Game_Version
  872. #------------------------------------------------------------------------------
  873. # Questa classe è d'appoggio per gestire la versione del gioco.
  874. #==============================================================================
  875. class Game_Version
  876.   include Comparable        #per la verifica delle versioni se maggiore o minore
  877.   attr_accessor :major      #numero di major release
  878.   attr_accessor :minor      #numero di minor release
  879.   attr_accessor :build      #numero di versione build
  880.   attr_accessor :revision   #numero di revisione
  881.   #--------------------------------------------------------------------------
  882.   # * Inizializzazione
  883.   #     version_string: versione in stringa (ad es. 1.5.3.1)
  884.   #--------------------------------------------------------------------------
  885.   def initialize(version_string, starting_major = 1)
  886.     @major = starting_major
  887.     @minor = 0
  888.     @build = 0
  889.     @revision = 0
  890.     version_string.gsub!(/\s\n\r/,"")
  891.     return unless version_string =~ /[\d]+([\.[\d]]*)/
  892.     version_string = version_string.split(".")
  893.     @major = version_string[0].to_i
  894.     return if version_string[1].nil?
  895.     @minor = version_string[1].to_i
  896.     return if version_string[2].nil?
  897.     @build = version_string[2].to_i
  898.     return if version_string[3].nil?
  899.     @revision = version_string[3].to_i
  900.   end
  901.   #--------------------------------------------------------------------------
  902.   # * Restituisce la versione attuale del gioco
  903.   #--------------------------------------------------------------------------
  904.   def self.now
  905.     if File.exist?(H87_ModConfig::VERSIONFILE)
  906.       file = File.open(H87_ModConfig::VERSIONFILE,"r")
  907.       str = file.read
  908.       file.close
  909.       return Game_Version.new(str)
  910.     else
  911.       return Game_Version.new("1.0.0.0")
  912.     end
  913.   end
  914.   #--------------------------------------------------------------------------
  915.   # * Compara una versione o una stringa con se stessa
  916.   #--------------------------------------------------------------------------
  917.   def <=> other
  918.     return self <=> Game_Version.new(other) if other.is_a?(String)
  919.     return self.major <=> other.major if self.major != other.major
  920.     return self.minor <=> other.minor if self.minor != other.minor
  921.     return self.build <=> other.build if self.build != other.build
  922.     return self.revision <=> other.revision
  923.   end
  924.   #--------------------------------------------------------------------------
  925.   # * restituisce la versione in stringa
  926.   #--------------------------------------------------------------------------
  927.   def to_s
  928.     return sprintf("%d.%d.%d.%d", @major, @minor, @build, @revision)
  929.   end
  930. end #game_version
  931.  
  932. #==============================================================================
  933. # ** RPG::System -> aggiunta del metodo per la versione del gioco
  934. #==============================================================================
  935. class Game_System
  936.   #--------------------------------------------------------------------------
  937.   # * Restituisce la versione del gioco attuale
  938.   #--------------------------------------------------------------------------
  939.   def game_version
  940.     return Game_Version.now
  941.   end
  942. end #rpg_system
  943.  
  944. #==============================================================================
  945. # ** DataManager -> aggiunta dei metodi per caricare i settaggi
  946. #==============================================================================
  947. module DataManager
  948.   #--------------------------------------------------------------------------
  949.   # * alias
  950.   #--------------------------------------------------------------------------
  951.   class << self
  952.     alias h87set_load_n_db load_normal_database
  953.     alias h87set_load_b_db load_battle_test_database
  954.   end
  955.   # --------------------------------------------------------------------------
  956.   # * caricamento nd
  957.   # --------------------------------------------------------------------------
  958.   def self.load_normal_database
  959.     load_h87settings
  960.     h87set_load_n_db
  961.   end
  962.   # --------------------------------------------------------------------------
  963.   # * caricamento btd
  964.   # --------------------------------------------------------------------------
  965.   def self.load_battle_test_database
  966.     load_h87settings
  967.     h87set_load_b_db
  968.   end
  969.   # --------------------------------------------------------------------------
  970.   # * restituisce il percorso delle impostazioni
  971.   # --------------------------------------------------------------------------
  972.   def self.settings_path
  973.     H87_ModConfig::SETTINGNAME
  974.   end
  975.   #--------------------------------------------------------------------------
  976.   # * carica le impostazioni universali
  977.   #--------------------------------------------------------------------------
  978.   def self.load_h87settings
  979.     return if $game_settings
  980.     if File.exist?(settings_path)
  981.       $game_settings = load_data(settings_path)
  982.     else
  983.       $game_settings = H87_Settings.new
  984.       save_data($game_settings,settings_path)
  985.     end
  986.   end
  987. end #datamanager
  988.  
  989. #==============================================================================
  990. # ** Aggiunta di alcuni metodi utili per le stringhe
  991. #==============================================================================
  992. class String
  993.   #--------------------------------------------------------------------------
  994.   # * Metodo Random: restituisce una stringa a caso
  995.   #   size: numero di caratteri della stringa
  996.   #--------------------------------------------------------------------------
  997.   def self.random(size = 4)
  998.     stringa = rand(36**size).to_s(36)
  999.     return stringa
  1000.   end
  1001.   #--------------------------------------------------------------------------
  1002.   # * Restituisce la stessa stringa ma crittografata in ROT13
  1003.   #   http://it.wikipedia.org/wiki/ROT13
  1004.   #--------------------------------------------------------------------------
  1005.   def crypt_rot13
  1006.     return self.tr("A-Za-z", "N-ZA-Mn-za-m")
  1007.   end
  1008. end #fine della stringa
  1009.  
  1010. #==============================================================================
  1011. # ** Inclusione dei metodi asincroni in Scene_Base
  1012. #==============================================================================
  1013. class Scene_Base
  1014.   include Async_Downloads # inclusione del modulo
  1015.   #--------------------------------------------------------------------------
  1016.   # * Alias del metodo d'aggiornamento
  1017.   #--------------------------------------------------------------------------
  1018.   alias h87_module_update update unless $@
  1019.   def update
  1020.     h87_module_update
  1021.     check_async_downloads #controlla i download
  1022.     check_async_requests  #controlla le richieste
  1023.   end
  1024. end #scene_base
  1025.  
  1026. #==============================================================================
  1027. # ** Inclusione dei metodi asincroni in Window_Base
  1028. #==============================================================================
  1029. class Window_Base
  1030.   include Async_Downloads # inclusione del modulo
  1031.   #--------------------------------------------------------------------------
  1032.   # * Alias del metodo d'aggiornamento
  1033.   #--------------------------------------------------------------------------
  1034.   alias h87_module_update update unless $@
  1035.   def update
  1036.     h87_module_update
  1037.     check_async_downloads #controlla i download
  1038.     check_async_requests  #controlla le richieste
  1039.   end
  1040. end #scene_base
  1041.  
  1042. class Object
  1043.   #--------------------------------------------------------------------------
  1044.   # * Metodo di stampa riga
  1045.   #--------------------------------------------------------------------------
  1046.   def println(*args)
  1047.     print(*args, "\n")
  1048.   end
  1049.   #--------------------------------------------------------------------------
  1050.   # * Metodi di conversione Base64
  1051.   #--------------------------------------------------------------------------
  1052.   def base64_encode(string); Base64.encode(string); end
  1053.   def base64_decode(string); Base64.decode(string); end
  1054.   #--------------------------------------------------------------------------
  1055.   # * Restituisce direttamente la stringa di risposta dal server
  1056.   #   url: indirizzo della richiesta
  1057.   #--------------------------------------------------------------------------
  1058.   def await_response(url)
  1059.     return HTTP.await_get_server_response(url)
  1060.   end
  1061. end
Add Comment
Please, Sign In to add comment