Advertisement
DaxSoft

Dax Core i5.1

Dec 18th, 2014
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 160.38 KB | None | 0 0
  1. #==============================================================================
  2. # * Dax Core
  3. #==============================================================================
  4. # Autor : Dax Aquatic X
  5. # Versão : Core i5.1
  6. # Site : www.dax-soft.weebly.com
  7. # Suporte : dax-soft@live.com
  8. #==============================================================================
  9. #  Um Core com vários módulos e métodos que facilitará na hora de programar os
  10. # seus scripts, bom proveito.
  11. #==============================================================================
  12. # Conteúdo : • TAGS : Para facilitar a localização dos códigos e explicações. Para acessar
  13. # o comando para localizar, basta apertar Ctrl+F.
  14. #==============================================================================
  15. # i :
  16. #   - Array :array
  17. #   - Api :api
  18. #   - String :string
  19. #   - Integer :integer
  20. #   - Numeric :numeric
  21. #   - Color :color
  22. #   - Rect :rect
  23. #   - DMath :dmath
  24. #   - Key :key
  25. #   - Sprite :sprite
  26. #   - Bitmap :bitmap (Método #save por Gab! -> Créditos a ele)
  27. #   - Mouse :mouse
  28. #   - Sprite_Mouse :sprite_mouse
  29. #   - Object :object
  30. #   - Entries :entries
  31. #   - DRGSS :drgss
  32. #   - Backup :backup
  33. #   - SceneManager :scenemanager
  34. #   - Sprite_Text :sprite_text
  35. #   - Sprite_Icon :sprite_icon
  36. #   - Opacity :opacity
  37. #   - Read :read
  38. #   - Background :background
  39. #   - Window_Base :window_base
  40. #   - Sound_Base :sound_base
  41. #   - Position :position
  42. #   - Animation :animation
  43. #   - Sprite_Anime_Horz :sprite_anime_horz
  44. #   - Sprite_Anime_Vert :sprite_anime_vert
  45. #   - Audio :audio
  46. #==============================================================================
  47. # • Adicionado comentário padrão. Veja o modo que agora os comentários dos
  48. # métodos estão.
  49. #==============================================================================
  50. # • [Classe do Retorno] : Explicação.
  51. #   * Exemplo.(Se possível.)
  52. #==============================================================================
  53. module Dax
  54.   extend self
  55.   #----------------------------------------------------------------------------
  56.   # • Constantes
  57.   #----------------------------------------------------------------------------
  58.   #  A imagem do ícone do Mouse tem que estar na pasta [System]. Basta você
  59.   # por o nome da imagem dentro das áspas. Caso você queira usar um ícone
  60.   # do Rpg Maker no lugar de uma imagem, basta você por o id do ícone no lugar
  61.   # das áspas.
  62.   Mouse_Name = ""
  63.   #----------------------------------------------------------------------------
  64.   # • Variáveis
  65.   #----------------------------------------------------------------------------
  66.   @register = { } # Variável útilizada para registrar os scripts que fora criado.
  67.   @benchmark = "" # Armazena os testes conclusos de benchmark.
  68.   #----------------------------------------------------------------------------
  69.   # • Método de registrar scripts :
  70.   #----------------------------------------------------------------------------
  71.   # ** Este método tem de ser definido alguns valores como :
  72.   #     symbol - nome do script, que é posto em símbolo : Ex - :arrow
  73.   #     name - nome do autor do script, que é posto em áspas
  74.   #     version - versão do script;
  75.   #     data - data do script;
  76.   #  Dax.register(symbol, name, version, data)
  77.   # ** Você pode usá-lo para somente registrar o nome do script.
  78.   #  Dax.register(symbol)
  79.   #----------------------------------------------------------------------------
  80.   def register(*args)
  81.     if @register.has_key?(args[0])
  82.       @register[args[0]][:version] = args[1]
  83.       @register[args[0]][:data] = args[2]
  84.     else
  85.       @register[args[0]] = {name: args[1], version: args[2], data: args[3], script: nil}
  86.     end
  87.   end
  88.   #----------------------------------------------------------------------------
  89.   # • Somente executará o bloco caso estiver registrado o script. Compatível
  90.   # com o $imported. Caso não esteja registrado no Core e esteja registrado
  91.   # na variável $imported, dará!
  92.   #----------------------------------------------------------------------------
  93.   # Exemplo:
  94.   #  Dax.required_script(:teste) { # Só irá executar caso estiver registrado.
  95.   #    methods...
  96.   #  }
  97.   #----------------------------------------------------------------------------
  98.   def required_script(symbol, &block)
  99.     return unless block_given?
  100.     block.call if @register.has_key?(symbol) or $imported.has_key?(symbol)
  101.   end
  102.   #----------------------------------------------------------------------------
  103.   # • Método de verificar se o objeto existe.
  104.   #----------------------------------------------------------------------------
  105.   # Dax.if_defined?("Objeto") { }
  106.   # Dentro das chaves você poem o script.
  107.   # * Exemplo :
  108.   #   Dax.required_class("Window_Base") {
  109.   #     class Window_Base < Window
  110.   #        def example
  111.   #          self.x = self.x + self.width
  112.   #        end
  113.   #     end
  114.   #   }
  115.   #----------------------------------------------------------------------------
  116.   # Executa o bloco se o objeto existir.
  117.   #----------------------------------------------------------------------------
  118.   def if_defined?(name, &block)
  119.     return unless defined?(name)
  120.     eval("block.call if defined?(name)")
  121.   end
  122.   #----------------------------------------------------------------------------
  123.   # • Fazer benchmark de um bloco. O resultado será impresso no Console do
  124.   # Maker.
  125.   #----------------------------------------------------------------------------
  126.   # Dax.benchmark(name(opcional)) { BLOCO }
  127.   #----------------------------------------------------------------------------
  128.   def benchmark(name="", &block)
  129.     time = Time.now
  130.     block.call
  131.     print "Benchmark: #{(time - Time.now).abs.to_f} segundos!\r\n"
  132.     @benchmark += "#{name} : #{(time - Time.now).to_f} segundos!\r\n"
  133.   end
  134.   #----------------------------------------------------------------------------
  135.   # • Salva os testes de benchmark num arquivo chamado 'Benchmark' de extensão
  136.   # .txt.
  137.   #----------------------------------------------------------------------------
  138.   def benchmark_save
  139.     self.required_file("Benchmark.txt") { File.delete("Benchmark.txt") }
  140.     File.open("Benchmark.txt", "a+") do |file|
  141.       file.write(@benchmark)
  142.       file.close
  143.     end
  144.   end
  145.   #----------------------------------------------------------------------------
  146.   # • Requirir um arquivo.
  147.   #     arquivo : Arquivo...
  148.   #----------------------------------------------------------------------------
  149.   def require(arquivo)
  150.     $: << "./"
  151.     Kernel.send(:require, arquivo)
  152.   end
  153.   #----------------------------------------------------------------------------
  154.   # • Somente executa um bloco case existir um arquivo.
  155.   #----------------------------------------------------------------------------
  156.   # Dax.required_file("arquivo.tipo") { # Exemplo.
  157.   #  Métodos;
  158.   # }
  159.   #----------------------------------------------------------------------------
  160.   def required_file(filename, &block)
  161.     return unless FileTest.exist?(filename)
  162.     block.call
  163.   end
  164.   #----------------------------------------------------------------------------
  165.   # • Somente executa um bloco case existir uma pasta.
  166.   #----------------------------------------------------------------------------
  167.   # Dax.required_dir("arquivo.tipo") { # Exemplo.
  168.   #  Métodos;
  169.   # }
  170.   #----------------------------------------------------------------------------
  171.   def required_dir(directory, &block)
  172.     return unless File.directory?(directory) and block_given?
  173.     block.call
  174.   end
  175.   #----------------------------------------------------------------------------
  176.   # * Remove uma [Classe], exemplo: Dax.remove(:Scene_Menu)
  177.   #----------------------------------------------------------------------------
  178.   def remove(symbol_name)
  179.     Object.send(:remove_const, symbol_name)
  180.   end
  181.   #----------------------------------------------------------------------------
  182.   # • Tela chéia
  183.   #----------------------------------------------------------------------------
  184.   def full_screen
  185.     res = Win32API.new 'user32', 'keybd_event', %w(l l l l), ''
  186.     res.call(18,0,0,0)
  187.     res.call(13,0,0,0)
  188.     res.call(13,0,2,0)
  189.     res.call(18,0,2,0)
  190.   end
  191. end
  192. #==============================================================================
  193. # • Array
  194. #==============================================================================
  195. Dax.register :array
  196. class Array
  197.   #----------------------------------------------------------------------------
  198.   # • [Array] Retorna ao elemento da array que condiz com a condição
  199.   # definida no bloco.
  200.   # Exemplo:
  201.   #   [2, 4, 5, 6, 8].rIf { |element| element >= 4 }
  202.   #    # 5, 6, 8
  203.   #----------------------------------------------------------------------------
  204.   def rIf
  205.     return unless block_given?
  206.     getResult ||= []
  207.     self.each_with_index{ |arrays|
  208.       getResult << arrays if yield(arrays)
  209.     }
  210.     return getResult
  211.   end
  212.   #----------------------------------------------------------------------------
  213.   # • [Mixed] : Retorna ao primeiro valor da array, que obedeça a
  214.   # condição posta.
  215.   # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_evan? } #> 2
  216.   # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_odd? } #> 3
  217.   #----------------------------------------------------------------------------
  218.   def first!
  219.     return unless block_given?
  220.     return self.each { |element| return element if yield(element) }.at(0)
  221.   end
  222.   #----------------------------------------------------------------------------
  223.   # • [Numeric] : Retorna ao valor de todos os conteúdos, desde que seja números,
  224.   # somados, ou subtraidos, ou multiplicados.. Por padrão é soma.
  225.   #    v : :+ # Somar
  226.   #        :- # Subtrair
  227.   #        :* # Multiplicar
  228.   #----------------------------------------------------------------------------
  229.   def alln?(v=:+)
  230.     n = v == :* ? 1 : 0
  231.     self.rIf {|i| i.is_a?(Numeric) }.each { |content|
  232.       n += content if v == :+
  233.       n -= content if v == :-
  234.       n *= content if v == :*
  235.     }
  236.     return n
  237.   end
  238. end
  239. #==============================================================================
  240. # • Hash
  241. #==============================================================================
  242. Dax.register :hash
  243. class Hash
  244.   #----------------------------------------------------------------------------
  245.   # • [Object] : Pega o valor da chave específicada.
  246.   #     {1 => 12}.get(1) #=> 12
  247.   #----------------------------------------------------------------------------
  248.   def get(key)
  249.     self.keys.each { |data|
  250.       return self[data] if key == data
  251.     }
  252.     return nil
  253.   end
  254. end
  255. Dax.register :api
  256. #==============================================================================
  257. # • API : Módulo que armazena informações de algumas APIS.
  258. #==============================================================================
  259. module API
  260.   extend self
  261.   #----------------------------------------------------------------------------
  262.   # • [String] : Tipos e seus retornos.. Pegado da internet.. Autor desconhecido
  263.   #----------------------------------------------------------------------------
  264.   TYPES = {
  265.             struct: "p",
  266.             int: "i",
  267.             long: "l",
  268.             INTERNET_PORT: "l",
  269.             SOCKET: "p",
  270.             C:  "p", #– 8-bit unsigned character (byte)
  271.             c:  "p", # 8-bit character (byte)
  272.             #   "i"8       – 8-bit signed integer
  273.             #   "i"8      – 8-bit unsigned integer
  274.             S:  "N", # – 16-bit unsigned integer (Win32/API: S used for string params)
  275.             s:  "n", # – 16-bit signed integer
  276.             #   "i"16     – 16-bit unsigned integer
  277.             #   "i"16      – 16-bit signed integer
  278.             I:  "I", # 32-bit unsigned integer
  279.             i:  "i", # 32-bit signed integer
  280.             #   "i"32     – 32-bit unsigned integer
  281.             #   "i"32      – 32-bit signed integer
  282.             L:  "L", # unsigned long int – platform-specific size
  283.             l:  "l", # long int – platform-specific size. For discussion of platforms, see:
  284.             #                (http://groups.google.com/group/ruby-ffi/browse_thread/thread/4762fc77130339b1)
  285.             #   "i"64      – 64-bit signed integer
  286.             #   "i"64     – 64-bit unsigned integer
  287.             #   "l"_long  – 64-bit signed integer
  288.             #   "l"_long – 64-bit unsigned integer
  289.             F:  "L", # 32-bit floating point
  290.             D:  "L", # 64-bit floating point (double-precision)
  291.             P:  "P", # pointer – platform-specific size
  292.             p:  "p", # C-style (NULL-terminated) character string (Win32API: S)
  293.             B:  "i", # (?? 1 byte in C++)
  294.             V:  "V", # For functions that return nothing (return type void).
  295.             v:  "v", # For functions that return nothing (return type void).
  296.             # For function argument type only:
  297.             # :buffer_in    – Similar to "l", but optimized for Buffers that the function can only read (not write).
  298.             # :buffer_out   – Similar to "l", but optimized for Buffers that the function can only write (not read).
  299.             # :buffer_inout – Similar to "l", but may be optimized for Buffers.
  300.             # :varargs      – Variable arguments
  301.             # :enum         - Enumerable type (should be defined)
  302.             # "p"_array   - ??
  303.  
  304.             # Windows-specific type defs (ms-help://MS.MSDNQTR.v90.en/winprog/winprog/windows_data_types.htm):
  305.             ATOM:      "I", # Atom ~= Symbol: Atom table stores strings and corresponding identifiers. Application
  306.             # places a string in an atom table and receives a 16-bit integer, called an atom, that
  307.             # can be used to access the string. Placed string is called an atom name.
  308.             # See: http://msdn.microsoft.com/en-us/library/ms648708%28VS.85%29.aspx
  309.             BOOL:      "i",
  310.             BOOLEAN:   "i",
  311.             BYTE:      "p", # Byte (8 bits). Declared as unsigned char
  312.             #CALLBACK:  K,       # Win32.API gem-specific ?? MSDN: #define CALLBACK __stdcall
  313.             CHAR:      "p", # 8-bit Windows (ANSI) character. See http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  314.             COLORREF:  "i", # Red, green, blue (RGB) color value (32 bits). See COLORREF for more info.
  315.             DWORD:     "i", # 32-bit unsigned integer. The range is 0 through 4,294,967,295 decimal.
  316.             DWORDLONG: "i", # 64-bit unsigned integer. The range is 0 through 18,446,744,073,709,551,615 decimal.
  317.             DWORD_PTR: "l", # Unsigned long type for pointer precision. Use when casting a pointer to a long type
  318.             # to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have
  319.             # been extended to 64 bits in 64-bit Windows.)  BaseTsd.h: #typedef ULONG_PTR DWORD_PTR;
  320.             DWORD32:   "I",
  321.             DWORD64:   "I",
  322.             HALF_PTR:  "i", # Half the size of a pointer. Use within a structure that contains a pointer and two small fields.
  323.             # BaseTsd.h: #ifdef (_WIN64) typedef int HALF_PTR; #else typedef short HALF_PTR;
  324.             HACCEL:    "i", # (L) Handle to an accelerator table. WinDef.h: #typedef HANDLE HACCEL;
  325.             # See http://msdn.microsoft.com/en-us/library/ms645526%28VS.85%29.aspx
  326.             HANDLE:    "l", # (L) Handle to an object. WinNT.h: #typedef PVOID HANDLE;
  327.             # todo: Platform-dependent! Need to change to "i"64 for Win64
  328.             HBITMAP:   "l", # (L) Handle to a bitmap: http://msdn.microsoft.com/en-us/library/dd183377%28VS.85%29.aspx
  329.             HBRUSH:    "l", # (L) Handle to a brush. http://msdn.microsoft.com/en-us/library/dd183394%28VS.85%29.aspx
  330.             HCOLORSPACE: "l", # (L) Handle to a color space. http://msdn.microsoft.com/en-us/library/ms536546%28VS.85%29.aspx
  331.             HCURSOR:   "l", # (L) Handle to a cursor. http://msdn.microsoft.com/en-us/library/ms646970%28VS.85%29.aspx
  332.             HCONV:     "l", # (L) Handle to a dynamic data exchange (DDE) conversation.
  333.             HCONVLIST: "l", # (L) Handle to a DDE conversation list. HANDLE - L ?
  334.             HDDEDATA:  "l", # (L) Handle to DDE data (structure?)
  335.             HDC:       "l", # (L) Handle to a device context (DC). http://msdn.microsoft.com/en-us/library/dd183560%28VS.85%29.aspx
  336.             HDESK:     "l", # (L) Handle to a desktop. http://msdn.microsoft.com/en-us/library/ms682573%28VS.85%29.aspx
  337.             HDROP:     "l", # (L) Handle to an internal drop structure.
  338.             HDWP:      "l", # (L) Handle to a deferred window position structure.
  339.             HENHMETAFILE: "l", #(L) Handle to an enhanced metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  340.             HFILE:     "i", # (I) Special file handle to a file opened by OpenFile, not CreateFile.
  341.             # WinDef.h: #typedef int HFILE;
  342.             HFONT:     "l", # (L) Handle to a font. http://msdn.microsoft.com/en-us/library/dd162470%28VS.85%29.aspx
  343.             HGDIOBJ:   "l", # (L) Handle to a GDI object.
  344.             HGLOBAL:   "l", # (L) Handle to a global memory block.
  345.             HHOOK:     "l", # (L) Handle to a hook. http://msdn.microsoft.com/en-us/library/ms632589%28VS.85%29.aspx
  346.             HICON:     "l", # (L) Handle to an icon. http://msdn.microsoft.com/en-us/library/ms646973%28VS.85%29.aspx
  347.             HINSTANCE: "l", # (L) Handle to an instance. This is the base address of the module in memory.
  348.             # HMODULE and HINSTANCE are the same today, but were different in 16-bit Windows.
  349.             HKEY:      "l", # (L) Handle to a registry key.
  350.             HKL:       "l", # (L) Input locale identifier.
  351.             HLOCAL:    "l", # (L) Handle to a local memory block.
  352.             HMENU:     "l", # (L) Handle to a menu. http://msdn.microsoft.com/en-us/library/ms646977%28VS.85%29.aspx
  353.             HMETAFILE: "l", # (L) Handle to a metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  354.             HMODULE:   "l", # (L) Handle to an instance. Same as HINSTANCE today, but was different in 16-bit Windows.
  355.             HMONITOR:  "l", # (L) ?andle to a display monitor. WinDef.h: if(WINVER >= 0x0500) typedef HANDLE HMONITOR;
  356.             HPALETTE:  "l", # (L) Handle to a palette.
  357.             HPEN:      "l", # (L) Handle to a pen. http://msdn.microsoft.com/en-us/library/dd162786%28VS.85%29.aspx
  358.             HRESULT:   "l", # Return code used by COM interfaces. For more info, Structure of the COM Error Codes.
  359.             # To test an HRESULT value, use the FAILED and SUCCEEDED macros.
  360.             HRGN:      "l", # (L) Handle to a region. http://msdn.microsoft.com/en-us/library/dd162913%28VS.85%29.aspx
  361.             HRSRC:     "l", # (L) Handle to a resource.
  362.             HSZ:       "l", # (L) Handle to a DDE string.
  363.             HWINSTA:   "l", # (L) Handle to a window station. http://msdn.microsoft.com/en-us/library/ms687096%28VS.85%29.aspx
  364.             HWND:      "l", # (L) Handle to a window. http://msdn.microsoft.com/en-us/library/ms632595%28VS.85%29.aspx
  365.             INT:       "i", # 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.
  366.             INT_PTR:   "i", # Signed integer type for pointer precision. Use when casting a pointer to an integer
  367.             # to perform pointer arithmetic. BaseTsd.h:
  368.             #if defined(_WIN64) typedef __int64 INT_PTR; #else typedef int INT_PTR;
  369.             INT32:    "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  370.             INT64:    "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  371.             LANGID:   "n", # Language identifier. For more information, see Locales. WinNT.h: #typedef WORD LANGID;
  372.             # See http://msdn.microsoft.com/en-us/library/dd318716%28VS.85%29.aspx
  373.             LCID:     "i", # Locale identifier. For more information, see Locales.
  374.             LCTYPE:   "i", # Locale information type. For a list, see Locale Information Constants.
  375.             LGRPID:   "i", # Language group identifier. For a list, see EnumLanguageGroupLocales.
  376.             LONG:     "l", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  377.             LONG32:   "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  378.             LONG64:   "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  379.             LONGLONG: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  380.             LONG_PTR: "l", # Signed long type for pointer precision. Use when casting a pointer to a long to
  381.             # perform pointer arithmetic. BaseTsd.h:
  382.             #if defined(_WIN64) typedef __int64 LONG_PTR; #else typedef long LONG_PTR;
  383.             LPARAM:   "l", # Message parameter. WinDef.h as follows: #typedef LONG_PTR LPARAM;
  384.             LPBOOL:   "i", # Pointer to a BOOL. WinDef.h as follows: #typedef BOOL far *LPBOOL;
  385.             LPBYTE:   "i", # Pointer to a BYTE. WinDef.h as follows: #typedef BYTE far *LPBYTE;
  386.             LPCSTR:   "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  387.             # See Character Sets Used By Fonts. http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  388.             LPCTSTR:  "p", # An LPCWSTR if UNICODE is defined, an LPCSTR otherwise.
  389.             LPCVOID:  "v", # Pointer to a constant of any type. WinDef.h as follows: typedef CONST void *LPCVOID;
  390.             LPCWSTR:  "P", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  391.             LPDWORD:  "p", # Pointer to a DWORD. WinDef.h as follows: typedef DWORD *LPDWORD;
  392.             LPHANDLE: "l", # Pointer to a HANDLE. WinDef.h as follows: typedef HANDLE *LPHANDLE;
  393.             LPINT:    "I", # Pointer to an INT.
  394.             LPLONG:   "L", # Pointer to an LONG.
  395.             LPSTR:    "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters.
  396.             LPTSTR:   "p", # An LPWSTR if UNICODE is defined, an LPSTR otherwise.
  397.             LPVOID:   "v", # Pointer to any type.
  398.             LPWORD:   "p", # Pointer to a WORD.
  399.             LPWSTR:   "p", # Pointer to a null-terminated string of 16-bit Unicode characters.
  400.             LRESULT:  "l", # Signed result of message processing. WinDef.h: typedef LONG_PTR LRESULT;
  401.             PBOOL:    "i", # Pointer to a BOOL.
  402.             PBOOLEAN: "i", # Pointer to a BOOL.
  403.             PBYTE:    "i", # Pointer to a BYTE.
  404.             PCHAR:    "p", # Pointer to a CHAR.
  405.             PCSTR:    "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  406.             PCTSTR:   "p", # A PCWSTR if UNICODE is defined, a PCSTR otherwise.
  407.             PCWSTR:    "p", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  408.             PDWORD:    "p", # Pointer to a DWORD.
  409.             PDWORDLONG: "L", # Pointer to a DWORDLONG.
  410.             PDWORD_PTR: "L", # Pointer to a DWORD_PTR.
  411.             PDWORD32:  "L", # Pointer to a DWORD32.
  412.             PDWORD64:  "L", # Pointer to a DWORD64.
  413.             PFLOAT:    "L", # Pointer to a FLOAT.
  414.             PHALF_PTR: "L", # Pointer to a HALF_PTR.
  415.             PHANDLE:   "L", # Pointer to a HANDLE.
  416.             PHKEY:     "L", # Pointer to an HKEY.
  417.             PINT:      "i", # Pointer to an INT.
  418.             PINT_PTR:  "i", # Pointer to an INT_PTR.
  419.             PINT32:    "i", # Pointer to an INT32.
  420.             PINT64:    "i", # Pointer to an INT64.
  421.             PLCID:     "l", # Pointer to an LCID.
  422.             PLONG:     "l", # Pointer to a LONG.
  423.             PLONGLONG: "l", # Pointer to a LONGLONG.
  424.             PLONG_PTR: "l", # Pointer to a LONG_PTR.
  425.             PLONG32:   "l", # Pointer to a LONG32.
  426.             PLONG64:   "l", # Pointer to a LONG64.
  427.             POINTER_32: "l", # 32-bit pointer. On a 32-bit system, this is a native pointer. On a 64-bit system, this is a truncated 64-bit pointer.
  428.             POINTER_64: "l", # 64-bit pointer. On a 64-bit system, this is a native pointer. On a 32-bit system, this is a sign-extended 32-bit pointer.
  429.             POINTER_SIGNED:   "l", # A signed pointer.
  430.             HPSS: "l",
  431.             POINTER_UNSIGNED: "l", # An unsigned pointer.
  432.             PSHORT:     "l", # Pointer to a SHORT.
  433.             PSIZE_T:    "l", # Pointer to a SIZE_T.
  434.             PSSIZE_T:   "l", # Pointer to a SSIZE_T.
  435.             PSS_CAPTURE_FLAGS: "l",
  436.             PSTR:       "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
  437.             PTBYTE:     "p", # Pointer to a TBYTE.
  438.             PTCHAR:     "p", # Pointer to a TCHAR.
  439.             PTSTR:      "p", # A PWSTR if UNICODE is defined, a PSTR otherwise.
  440.             PUCHAR:     "p", # Pointer to a UCHAR.
  441.             PUINT:      "i", # Pointer to a UINT.
  442.             PUINT_PTR:  "i", # Pointer to a UINT_PTR.
  443.             PUINT32:    "i", # Pointer to a UINT32.
  444.             PUINT64:    "i", # Pointer to a UINT64.
  445.             PULONG:     "l", # Pointer to a ULONG.
  446.             PULONGLONG: "l", # Pointer to a ULONGLONG.
  447.             PULONG_PTR: "l", # Pointer to a ULONG_PTR.
  448.             PULONG32:   "l", # Pointer to a ULONG32.
  449.             PULONG64:   "l", # Pointer to a ULONG64.
  450.             PUSHORT:    "l", # Pointer to a USHORT.
  451.             PVOID:      "v", # Pointer to any type.
  452.             PWCHAR:     "p", # Pointer to a WCHAR.
  453.             PWORD:      "p", # Pointer to a WORD.
  454.             PWSTR:      "p", # Pointer to a null- terminated string of 16-bit Unicode characters.
  455.             # For more information, see Character Sets Used By Fonts.
  456.             SC_HANDLE:  "l", # (L) Handle to a service control manager database.
  457.             SERVICE_STATUS_HANDLE: "l", # (L) Handle to a service status value. See SCM Handles.
  458.             SHORT:     "i", # A 16-bit integer. The range is –32768 through 32767 decimal.
  459.             SIZE_T:    "l", #  The maximum number of bytes to which a pointer can point. Use for a count that must span the full range of a pointer.
  460.             SSIZE_T:   "l", # Signed SIZE_T.
  461.             TBYTE:     "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  462.             # http://msdn.microsoft.com/en-us/library/c426s321%28VS.80%29.aspx
  463.             TCHAR:     "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  464.             UCHAR:     "p", # Unsigned CHAR (8 bit)
  465.             UHALF_PTR: "i", # Unsigned HALF_PTR. Use within a structure that contains a pointer and two small fields.
  466.             UINT:      "i", # Unsigned INT. The range is 0 through 4294967295 decimal.
  467.             UINT_PTR:  "i", # Unsigned INT_PTR.
  468.             UINT32:    "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  469.             UINT64:    "i", # Unsigned INT64. The range is 0 through 18446744073709551615 decimal.
  470.             ULONG:     "l", # Unsigned LONG. The range is 0 through 4294967295 decimal.
  471.             ULONGLONG: "l", # 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
  472.             ULONG_PTR: "l", # Unsigned LONG_PTR.
  473.             ULONG32:   "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  474.             ULONG64:   "i", # Unsigned LONG64. The range is 0 through 18446744073709551615 decimal.
  475.             UNICODE_STRING: "P", # Pointer to some string structure??
  476.             USHORT:    "i", # Unsigned SHORT. The range is 0 through 65535 decimal.
  477.             USN:    "l", # Update sequence number (USN).
  478.             WCHAR:  "i", # 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
  479.             # In WinNT.h: typedef wchar_t WCHAR;
  480.             #WINAPI: K,      # Calling convention for system functions. WinDef.h: define WINAPI __stdcall
  481.             WORD: "i", # 16-bit unsigned integer. The range is 0 through 65535 decimal.
  482.             WPARAM: "i",    # Message parameter. WinDef.h as follows: typedef UINT_PTR WPARAM;
  483.             VOID:   "v", # Any type ? Only use it to indicate no arguments or no return value
  484.             vKey: "i",
  485.             LPRECT: "p",
  486.   }
  487.   #----------------------------------------------------------------------------
  488.   # • [Array] : Pega os valores especificados no método.. depois verifica
  489.   # cada um se é String ou Symbol. Se for Symbol retorna ao valor especificado
  490.   # na Constante TYPES.
  491.   #  Exemplo: types([:BOOL, :WCHAR]) # ["i", "i"]
  492.   #----------------------------------------------------------------------------
  493.   def types(import)
  494.     import2 = []
  495.     import.each { |i|
  496.      next if i.is_a?(NilClass) or i.is_a?(String)
  497.      import2 << TYPES[i]
  498.     }
  499.     return import2
  500.   end
  501.   #----------------------------------------------------------------------------
  502.   # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  503.   # Por padrão a DLL é a "user32". O valor de exportação será "i"
  504.   #----------------------------------------------------------------------------
  505.   def int(function, import, dll="user32")
  506.     Win32API.new(dll, function, types(import), "i") rescue nil
  507.   end
  508.   #----------------------------------------------------------------------------
  509.   # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  510.   # Por padrão a DLL é a "user32". O valor de exportação será "l"
  511.   #----------------------------------------------------------------------------
  512.   def long(function, import, dll="user32")
  513.     Win32API.new(dll, function.to_s, types(import), "l") rescue nil
  514.   end
  515.   #----------------------------------------------------------------------------
  516.   # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  517.   # Por padrão a DLL é a "user32". O valor de exportação será "v"
  518.   #----------------------------------------------------------------------------
  519.   def void(function, import, dll="user32")
  520.     Win32API.new(dll, function.to_s, types(import), "v") rescue nil
  521.   end
  522.   #----------------------------------------------------------------------------
  523.   # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  524.   # Por padrão a DLL é a "user32". O valor de exportação será "p"
  525.   #----------------------------------------------------------------------------
  526.   def char(function, import, dll="user32")
  527.     Win32API.new(dll, function.to_s, types(import), "p") rescue nil
  528.   end
  529.   #----------------------------------------------------------------------------
  530.   # • [Dll]// : Com esse método você pode especificar uma função de uma Dll.
  531.   #   function(export, function, import, dll)
  532.   #    export : Valor da exportação. Formato [Symbol]
  533.   #    function : Função da Dll.
  534.   #    import : Valor da importação.
  535.   #    dll : Dll. Por padrão é a User32
  536.   #          Esconder o Mouse.
  537.   # Exemplo: function(:int, "ShowCursor", [:BOOL]).call(0)
  538.   #----------------------------------------------------------------------------
  539.   def function(export, function, import, dll="user32")
  540.     eval("#{export}(function, import, dll)")
  541.   end
  542.   #----------------------------------------------------------------------------
  543.   # • Especificando o método protegido.
  544.   #----------------------------------------------------------------------------
  545.   # Métodos privados.
  546.   private :long, :int, :char, :void, :types
  547.   #----------------------------------------------------------------------------
  548.   # • [CopyFile]/Dll : Função da DLL Kernel32 que permite copiar arquivos.
  549.   #    CopyFile.call(filename_to_copy, filename_copied, replace)
  550.   #      filename_to_copy : Formato [String]
  551.   #      filename_copied : Formato [String]
  552.   #      replace : Formato [Integer] 0 - false 1 - true
  553.   #   Exemplo: CopyFile.call("System/RGSS300.dll", "./RGSS300.dll", 1)
  554.   #----------------------------------------------------------------------------
  555.   CopyFile = Win32API.new('kernel32', 'CopyFile', 'ppl', 'l')
  556.   #----------------------------------------------------------------------------
  557.   # • [Beep]/Dll : Emitir uma frequência de um som do sistema com duração.
  558.   #    Beep.call(freq, duration)
  559.   #      freq : Formato [Integer\Hexadécimal]
  560.   #      duration : Formato [Integer\Hexadécimal]
  561.   #    Exemplo: Beep.call(2145, 51)
  562.   #----------------------------------------------------------------------------
  563.   Beep = Win32API.new('kernel32', 'Beep', 'LL', 'L')
  564.   #----------------------------------------------------------------------------
  565.   # • [keybd_event]/Dll : Ela é usada para sintentizar uma combinação de teclas.
  566.   #    KEYBD_EVENT.call(vk, scan, fdwFlags, dwExtraInfo)
  567.   #      vk : Formato [Integer/Hexadécimal].
  568.   #      scan : Formato [Integer]
  569.   #      fdwFlags : Formato [Integer]
  570.   #      dwExtraInfo : Formato [Integer]
  571.   #    Exemplo: KEYBD_EVENT.call(0x01, 0, 0, 0)
  572.   #----------------------------------------------------------------------------
  573.   KEYBD_EVENT         = Win32API.new('user32', 'keybd_event', 'LLLL', '')
  574.   #----------------------------------------------------------------------------
  575.   # • [GetKeyState]/Dll : Pega o status da chave.
  576.   #    GetKeyState.call(vk)
  577.   #      vk : Formato [Integer/Hexadécimal].
  578.   #   Exemplo: GetKeyState.call(0x01)
  579.   #----------------------------------------------------------------------------
  580.   GetKeyState    = Win32API.new('user32', 'GetAsyncKeyState', 'i', 'i')
  581.   #----------------------------------------------------------------------------
  582.   # • [MouseShowCursor]/Dll : Mostrar ou desativar o cusor do Mouse.
  583.   #    MouseShowCursor.call(value)
  584.   #     value : Formato [Integer] 0 - false 1 - true
  585.   #   Exemplo: MouseShowCursor.call(0)
  586.   #----------------------------------------------------------------------------
  587.   MouseShowCursor = Win32API.new("user32", "ShowCursor", "i", "i")
  588.   #----------------------------------------------------------------------------
  589.   # • [CursorPosition]/Dll : Obtem a posição do cursor do Mouse na tela.
  590.   #     CursorPosition.call(lpPoint)
  591.   #      lpPoint : Formato [Array]
  592.   #   Ex: CursorPosition.call([0, 0].pack('ll'))
  593.   #----------------------------------------------------------------------------
  594.   CursorPosition = Win32API.new('user32', 'GetCursorPos', 'p', 'i')
  595.   #----------------------------------------------------------------------------
  596.   # • [ScreenToClient]/Dll : Converte as coordenadas da tela para um ponto
  597.   # em especifico da área da tela do cliente.
  598.   #     ScreenToClient.call(hWnd, lpPoint)
  599.   #----------------------------------------------------------------------------
  600.   ScreenToClient = Win32API.new('user32', 'ScreenToClient', 'lp', 'i')
  601.   #----------------------------------------------------------------------------
  602.   # • [ReadIni]/Dll : */Ainda não explicado./*
  603.   #----------------------------------------------------------------------------
  604.   ReadIni = Win32API.new('kernel32', 'GetPrivateProfileStringA', %w(p p p p l p), 'l')
  605.   #----------------------------------------------------------------------------
  606.   # • [FindWindow]/Dll : Recupera o identificador da janela superior. Cujo
  607.   # o nome da janela é o nome da classe da janela se combina com as cadeias
  608.   # especificas.
  609.   #    FindWindow.call(lpClassName,  lpWindowName)
  610.   #      lpClassName : Formato [String]
  611.   #      lpWindowName : Formato [String]
  612.   #----------------------------------------------------------------------------
  613.   FindWindow = Win32API.new('user32', 'FindWindowA', %w(p p), 'l')
  614.   #----------------------------------------------------------------------------
  615.   # • [Handle]/Dll : Retorna ao Handle da janela.
  616.   #----------------------------------------------------------------------------
  617.   def hWND
  618.     return API::FindWindow.call('RGSS Player', load_data("./Data/System.rvdata2").game_title.to_s)
  619.   end
  620.   #----------------------------------------------------------------------------
  621.   # • [Handle]/Dll : Retorna ao Handle da janela. Método protegido.
  622.   #----------------------------------------------------------------------------
  623.   def hwnd
  624.     hWND
  625.   end
  626.   #----------------------------------------------------------------------------
  627.   # • [GetPrivateProfileString]/Dll : */Ainda não explicado./*
  628.   #----------------------------------------------------------------------------
  629.   GetPrivateProfileString = Win32API.new('kernel32', 'GetPrivateProfileStringA',%w(p p p p l p),'l')
  630.   #----------------------------------------------------------------------------
  631.   # • [SetWindowPos]/Dll : Modifica os elementos da janela como, posição, tamanho.
  632.   #----------------------------------------------------------------------------
  633.   SetWindowPos = Win32API.new("user32", "SetWindowPos", "lliiiii", "i")  
  634.   #----------------------------------------------------------------------------
  635.   # • [GetWindowRect]/Dll : Obtem as dimensões do retângulo da janela.
  636.   #    GetWindowRect.call(hWnd, lpRect)
  637.   #----------------------------------------------------------------------------
  638.   GetWindowRect = Win32API.new('user32','GetWindowRect',%w(l p),'i')  
  639.   #----------------------------------------------------------------------------
  640.   # • [StateKey]/Dll : Retorna ao status específico da chave.
  641.   #    StateKey.call(VK)
  642.   #      VK : Formato [Integer/Hexadécimal].
  643.   #----------------------------------------------------------------------------
  644.   StateKey = Win32API.new("user32", "GetKeyState", ["i"], "i")
  645.   #----------------------------------------------------------------------------
  646.   # • [SetCursorPos]/Dll : Move o cursor do Mouse para um ponto específico
  647.   # da tela.
  648.   #    SetCursorPos.call(x, y)
  649.   #     x, y : Formato [Integer/Float]
  650.   #----------------------------------------------------------------------------
  651.   SetCursorPos    = Win32API.new("user32", "SetCursorPos", "ll", "i")
  652.   #----------------------------------------------------------------------------
  653.   # • [GetKeyboardState]/Dll : Cópia o status das 256 chaves para um
  654.   # buffer especificado.
  655.   #----------------------------------------------------------------------------
  656.   GetKeyboardState = Win32API.new('user32', 'GetKeyboardState', ['P'], 'V')
  657.   #----------------------------------------------------------------------------
  658.   # • [GetAsyncKeyState]/Dll : Determina o estado da chave no momento em que a
  659.   # função é chamada.
  660.   #    GetAsyncKeyState.call(Vk)
  661.   #     VK : Formato [Integer/Hexadécimal].
  662.   #----------------------------------------------------------------------------
  663.   GetAsyncKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'i', 'i')
  664.   #----------------------------------------------------------------------------
  665.   # • [WideCharToMultiByte] : [MultiByteToWideChar] // Comentários
  666.   # não adicionados.
  667.   #----------------------------------------------------------------------------
  668.   WideCharToMultiByte = Win32API.new('kernel32', 'WideCharToMultiByte', 'ilpipipp', 'i')
  669.   MultiByteToWideChar = Win32API.new('kernel32', 'MultiByteToWideChar', 'ilpipi', 'i')
  670.   #----------------------------------------------------------------------------
  671.   # • [ZeroMemoy]/Dll : Enche um bloco da memória com zeros.
  672.   #----------------------------------------------------------------------------
  673.   ZeroMemory = Win32API.new("kernel32", "RtlZeroMemory", "pl", "")
  674.   #----------------------------------------------------------------------------
  675.   # • [AdjustWindowRect] : Calcula o tamanho requerido do retângulo da Janela.
  676.   #----------------------------------------------------------------------------
  677.   AdjustWindowRect = int("AdjustWindowRect", [:LPRECT, :DWORD, :BOOL])
  678.   #----------------------------------------------------------------------------
  679.   # • Constantes [SetWindowPos]
  680.   #----------------------------------------------------------------------------
  681.   SWP_ASYNCWINDOWPOS = 0x4000
  682.   # Desenha os frames (definidos na classe da janela descrita) em torno na janela.
  683.   SWP_DRAWFRAME = 0x0020
  684.   # Esconde a janela.
  685.   SWP_HIDEWINDOW = 0x0080
  686.   # Não pode ser ativada nem movida
  687.   SWP_NOACTIVATE = 0x0010
  688.   # Não permite mover
  689.   SWP_NOMOVE = 0x0002
  690.   # Não permite redimensionar
  691.   SWP_NOSIZE = 0x0001
  692.   # Mostra a Janela
  693.   SWP_SHOWWINDOW = 0x0040
  694.   # Coloca a janela na parte inferior na ordem de Z. Se identificar uma janela
  695.   # superior ela perde os seus status.
  696.   HWND_BOTTOM = 1
  697.   # Coloca a janela acima de todas as janelas que não estão em primeiro plano.
  698.   HWND_NOTOPMOST = -2
  699.   # Poem a janela no Topo na ordem de Z.
  700.   HWND_TOP = 0
  701.   # Poem a janela acima de todas que não estão em primeiro plano. Mantendo a
  702.   # posição.
  703.   HWND_TOPMOST = -1
  704.   #----------------------------------------------------------------------------
  705.   # • [SetActiveWindow]/ Dll : Ativa a Window.
  706.   #----------------------------------------------------------------------------
  707.   SetActiveWindow = long("SetActiveWindow", [:HWND])
  708.   #----------------------------------------------------------------------------
  709.   # • WindowFromPoint : Retorna ao handle da janela, que contém um ponto
  710.   # específico.
  711.   #----------------------------------------------------------------------------
  712.   WindowFromPoint = long("WindowFromPoint", [:HWND])
  713.   #----------------------------------------------------------------------------
  714.   # • ShowWindow : Mostra a janela em um estado específico.
  715.   #----------------------------------------------------------------------------
  716.   ShowWindow = long("ShowWindow", [:HWND, :LONG])
  717.   # Força a janela a minimizar
  718.   SW_FORCEMINIMIZE = 11
  719.   # Esconde a janela, ativa outra.
  720.   SW_HIDE = 0
  721.   # Maximiza a janela.
  722.   SW_MAXIMIZE = 3
  723.   # Minimiza a janela
  724.   SW_MINIMIZE = 6
  725.   # Restaura o estado da janela.
  726.   SW_RESTORE = 9
  727.   # Ativa a janela a mostrando na posição original.
  728.   SW_SHOW = 5
  729.   #----------------------------------------------------------------------------
  730.   # • [SetWindowText] : Permite modificar o título da janela.
  731.   #----------------------------------------------------------------------------
  732.   SetWindowText = int("SetWindowText", [:HWND, :LPCTSTR])
  733.   #----------------------------------------------------------------------------
  734.   # • [GetDesktopWindow] : Retorna ao handle da janela em relação ao Desktop.
  735.   #----------------------------------------------------------------------------
  736.   GetDesktopWindow = long("GetDesktopWindow", [:HWND])
  737.   #----------------------------------------------------------------------------
  738.   # • [GetSystemMetric] : Obtem um sistema métrico específico ou a configuração
  739.   # do sistema. As dimensões retornadas são em pixel.
  740.   #----------------------------------------------------------------------------
  741.   GetSystemMetric = int("GetSystemMetric", [:int])
  742.   #----------------------------------------------------------------------------
  743.   # • [GetSystemMetric]/Constantes:
  744.   #----------------------------------------------------------------------------
  745.   #  Obtem a flag que especifica como o sistema está organizando as janelas
  746.   # minimizadas.
  747.   SM_ARRANGE = 56
  748.   # Obtem o tamanho da borda da Janela em pixel.
  749.   SM_CXBORDER = 5
  750.   # Valor do tamanho da área do cliente pra uma Janela em modo de tela-chéia.
  751.   # em pixel.
  752.   SM_CXFULLSCREEN = 16
  753.   # Para mais informações dos valores, visite :
  754.   #  http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  755.   #----------------------------------------------------------------------------
  756.   # • [GetClientRect] : Retorna ao rect da área da Janela.
  757.   # Uses :
  758.   #   lpRect = [0,0,0,0].pack("L*")
  759.   #   GetClientRect.(hwnd, lpRect)
  760.   #   lpRect = lpRect.unpack("L*")
  761.   #----------------------------------------------------------------------------
  762.   GetClientRect = int("GetClientRect", [:HWND, :LPRECT])
  763.   #----------------------------------------------------------------------------
  764.   # • [GetModuleHandle] : Retorna ao Handle do módulo, do módulo específicado.
  765.   # Pode ser aquivo '.dll' ou '.exe'. Exemplo:
  766.   #  GetModuleHandle.call('System/RGSS300.dll')
  767.   #----------------------------------------------------------------------------
  768.   GetModuleHandle = long("GetModuleHandle", [:LPCTSTR], "kerne32")
  769.   #----------------------------------------------------------------------------
  770.   # • [FreeLibrary] : Libera o módulo que está carregado na DLL específica.
  771.   #----------------------------------------------------------------------------
  772.   FreeLibrary = long("FreeLibrary", [:HMODULE], "kernel32")
  773.   #----------------------------------------------------------------------------
  774.   # • [LoadLibrary] : Carrega um endereço de um módulo em específico.
  775.   # LoadLibrary.call(Nome da Libraria(dll/exe))
  776.   #   [Handle] : Retorna ao valor do Handle do módulo caso der certo.
  777.   #----------------------------------------------------------------------------
  778.   LoadLibrary = long("LoadLibrary", [:LPCTSTR], "kernel32")
  779.   #----------------------------------------------------------------------------
  780.   # • [GetProcAddress] : Retorna ao endereço da função exportada ou a variável
  781.   # de uma DLL específica.
  782.   #  GetProcAddress.call(hModule, lpProcName)
  783.   #   hModule : É o valor do handle. Você pode pega-lo usando o LoadLibrary
  784.   #   lpProcName : A função ou o nome da variável.
  785.   #----------------------------------------------------------------------------
  786.   GetProcAddress = long("GetProcAddress", [:HMODULE, :LPCSTR], "kernel32")
  787.   #----------------------------------------------------------------------------
  788.   # • [GetSystemMetrics] : Retorna á uma configuração específica do sistema
  789.   # métrico.
  790.   #----------------------------------------------------------------------------
  791.   GetSystemMetrics = int("GetSystemMetrics", [:int])
  792.   #----------------------------------------------------------------------------
  793.   # • [GetSystemMetrics]::Constantes. #Para mais visite:
  794.   # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  795.   #----------------------------------------------------------------------------
  796.   SM_CXSCREEN = 0 # O tamanho(width/largura) da janela em pixel.
  797.   SM_CYSCREEN = 1 # O tamanho(height/comprimento) da janela em pixel.
  798.   SM_CXFULLSCREEN = 16 # O tamanho da largura da tela chéia da janela.
  799.   SM_CYFULLSCREEN = 17 # O tamanho do comprimento da tela chéia da janela.
  800.   #----------------------------------------------------------------------------
  801.   # • [Método protegido] : Método usado para chamar a função LoadLibrary.
  802.   #----------------------------------------------------------------------------
  803.   def dlopen(name, fA=nil)
  804.     l = LoadLibrary.(String(name))
  805.     return l if fA.nil?
  806.     return GetProcAddress.(l, String(fA))
  807.   end
  808.   #----------------------------------------------------------------------------
  809.   # • Converte um texto para o formato UTF-8
  810.   #    textUTF(text)
  811.   #      * text : Texto.
  812.   #----------------------------------------------------------------------------
  813.   def textUTF(text)
  814.     wC = API::MultiByteToWideChar.call(65001, 0, text, -1, "", 0)
  815.     API::MultiByteToWideChar.call(65001, 0, text, -1, text = "\0\0" * wC, wC)
  816.     return text
  817.   end
  818.   #----------------------------------------------------------------------------
  819.   # • [TrueClass/FalseClass] : Retorna verdadeiro caso o Caps Lock esteja
  820.   # ativo e retorna Falso caso não esteja ativo.
  821.   #----------------------------------------------------------------------------
  822.   def get_caps_lock
  823.     return int("GetKeyState", [:vKey]).call(20) == 1
  824.   end
  825.   #----------------------------------------------------------------------------
  826.   # • Abre a URL de um site o direcionado para o navegador padrão do usuário.
  827.   #----------------------------------------------------------------------------
  828.   def open_site(url)
  829.     c = Win32API.new("Shell32", "ShellExecute", "pppppl", "l")
  830.     c.call(nil, "open", url, nil, nil, 0)
  831.   end
  832.   #==============================================================================
  833.   # • Clipboard
  834.   #==============================================================================
  835.   module Clipboard
  836.     extend self
  837.     #----------------------------------------------------------------------------
  838.     # • Constantes do módulo:
  839.     #----------------------------------------------------------------------------
  840.     Close = Win32API.new("user32", "CloseClipboard", "v", "l")
  841.     GetData = Win32API.new("user32", "GetClipboardData", "n", "l")
  842.     Open = Win32API.new('user32', 'OpenClipboard', "N", "L")
  843.     FormatAvailable = Win32API.new('user32', 'IsClipboardFormatAvailable', "i", "i")
  844.     GlobalAlloc = Win32API.new('kernel32', 'GlobalAlloc', 'll', 'l')
  845.     GlobalLock = Win32API.new('kernel32', 'GlobalLock', 'l', 'l')
  846.     GlobalSize = Win32API.new('kernel32', 'GlobalSize', 'l', 'l')
  847.     GlobalUnlock = Win32API.new('kernel32', 'GlobalUnlock', 'l', '')
  848.     MemCpy = Win32API.new('ntdll', 'memcpy', 'ppl', 'l')
  849.     FORMATS = {text: 1, dib: 2, bitmap: 8}
  850.     #----------------------------------------------------------------------------
  851.     # • Data. Retorna a Data do clipboard. Especificar o formato para receber
  852.     # o retorno do formato especifico. Formato padrão é o texto.
  853.     #----------------------------------------------------------------------------
  854.     def data(format=FORMATS[:text])
  855.       begin
  856.         self.open
  857.           if FormatAvailable.call(format)
  858.             handle = GetData.call(format)
  859.             case format
  860.             when 1
  861.               clip_data = 0.chr * GlobalSize.call(handle)
  862.               MemCpy.call(clip_data, handle, clip_data.size)
  863.               clip_data = clip_data[ /^[^\0]*/ ]
  864.             when 2, 8 then clip_data = get_image_data(handle)
  865.             else
  866.               raise Error, 'format not supported'
  867.             end
  868.           else
  869.             clip_data = ''
  870.           end
  871.         ensure
  872.           self.close
  873.         end
  874.       clip_data
  875.     end
  876.     #----------------------------------------------------------------------------
  877.     # • Singleton Class
  878.     #----------------------------------------------------------------------------
  879.     class << self
  880.       alias :get_data :data
  881.     end
  882.     #----------------------------------------------------------------------------
  883.     # • Formato aceito.
  884.     #----------------------------------------------------------------------------
  885.     def formatAvailable?(format)
  886.       FormatAvailable.call(format).boolean
  887.     end
  888.     private
  889.     #----------------------------------------------------------------------------
  890.     # • Abrir clipboard
  891.     #----------------------------------------------------------------------------
  892.     def open
  893.       Open.call(0)
  894.     end
  895.     #----------------------------------------------------------------------------
  896.     # • Fechar
  897.     #----------------------------------------------------------------------------
  898.     def close
  899.       Close.call
  900.     end
  901.     #----------------------------------------------------------------------------
  902.     # • Obter a data de uma imagem, bitmap.
  903.     #----------------------------------------------------------------------------
  904.     def get_image_data(handle)
  905.       buf = nil
  906.       bmi = 0.chr * 44 # BITMAPINFO
  907.       begin
  908.         address  = GlobalLock.call(handle)
  909.         buf_size = GlobalSize.call(handle)
  910.         MemCpy.call(bmi, address, bmi.length)
  911.         bit_count   = bmi[14,2].unpack('S').first # biBitCount
  912.         compression = bmi[16,4].unpack('L').first # biCompression
  913.         size_image  = bmi[20,4].unpack('L').first # biSizeImage
  914.         clr_used    = bmi[32,4].unpack('L').first # biClrUsed
  915.         size_image = buf_size + 16 if size_image == 0
  916.         # Calculate the header size
  917.         case bit_count
  918.         when 1 then table_size = 2
  919.         when 4 then table_size = 16
  920.         when 8 then table_size = 256
  921.         when 16, 32
  922.           if compression == 0
  923.             table_size = clr_used
  924.           elsif compression == 3
  925.             table_size = 3
  926.           else
  927.             msgbox "ERROR: invalid bit/compression combination"
  928.           end
  929.         when 24 then table_size = crl_used
  930.         else
  931.           msgbox "ERROR: invalid bit count"
  932.         end
  933.         offset = 0x36 + (table_size * 4)
  934.         buf = 0.chr * buf_size
  935.         MemCpy.call(buf, address, buf.size)
  936.         buf = "\x42\x4D" + [size_image].pack('L') + 0.chr * 4 + [offset].pack('L') + buf
  937.       ensure
  938.         GlobalUnlock.call(handle)
  939.       end
  940.       buf
  941.     end
  942.   end
  943.   #============================================================================
  944.   # • MessageBox
  945.   #============================================================================
  946.   module MessageBox
  947.     extend self
  948.     # handle, string, title, format.
  949.     FunctionMessageBox = Win32API.new("user32", "MessageBoxW", "lppl", "l")
  950.     #--------------------------------------------------------------------------
  951.     # • [Constantes] Botões:
  952.     #--------------------------------------------------------------------------
  953.     # Adiciona três botões a mensagem: Anular, Repetir e Ignorar.
  954.     ABORTRETRYIGNORE = 0x00000002
  955.     # Adiciona três botões a mensagem: Cancelar, Tentar e Continuar.
  956.     CANCELTRYCONTINUE = 0x00000006
  957.     # Adiciona o botão de ajuda.
  958.     HELP = 0x00004000
  959.     # Adiciona o botão Ok.
  960.     OK = 0x00000000
  961.     # Adiciona o botão OK e Cancelar.
  962.     OKCANCEL = 0x00000001
  963.     # Adiciona os botões: Repetir e Cancelar.
  964.     RETRYCANCEL = 0x00000005
  965.     # Adiciona os botões: Sim e Não
  966.     YESNO = 0x00000004
  967.     # Adiciona os botões: Sim, Não e Cancelar
  968.     YESNOCANCEL = 0x00000003
  969.     #--------------------------------------------------------------------------
  970.     # • [Constantes] Ícones:
  971.     #--------------------------------------------------------------------------
  972.     # Adiciona um ícone de exclamação
  973.     ICONEXCLAMATION = 0x00000030
  974.     # Adiciona um ícone de informação.
  975.     ICONINFORMATION = 0x00000040
  976.     # Adiciona um ícone de um círculo com um ponto de interrogação.
  977.     ICONQUESTION = 0x00000020
  978.     # Adiciona um íconde parar na mensagem.
  979.     ICONSTOP = 0x00000010
  980.     #--------------------------------------------------------------------------
  981.     # • [Constantes] Valores de retorno dos botões:
  982.     #--------------------------------------------------------------------------
  983.     ABORT = 3 # Retorno do valor do botão de Anular
  984.     CANCEL = 2 # Retorno do valor do botão de Cancelar.
  985.     CONTINUE = 11 # Retorno do valor do botão de Continuar.
  986.     IGNORE = 5 # Retorno do valor de ignonar.
  987.     NO = 7 # Retorno do valor do botão de Não.
  988.     OK = 1 # Retorno do valor do botão de Ok.
  989.     RETRY = 4 # Retorno do valor de repetir.
  990.     TRYAGAIN = 10 # Retorno do valor de Repetir.
  991.     YES = 6 # Retorno do valor do botão de Sim.
  992.     #--------------------------------------------------------------------------
  993.     # • [Constantes] Valores adicionais.
  994.     #--------------------------------------------------------------------------
  995.     RIGHT = 0x00080000 # Os textos ficarão justificados a direita.
  996.     TOPMOST = 0x00040000 # O estilo da mensagem é criado como WB_EX_TOPMOST
  997.     #--------------------------------------------------------------------------
  998.     # • [call] : Retorna aos valores dos botões. Para serem usados
  999.     # como condição, de que se ao clicar.
  1000.     #   API::MessageBox.call(title, string, format)
  1001.     #    title -> Título da caixa.
  1002.     #    string -> Conteúdo da caixa.
  1003.     #    format -> Formato, no caso seria os botões e ícones.
  1004.     #--------------------------------------------------------------------------
  1005.     def call(title, string, format)
  1006.       return FunctionMessageBox.call(API.hWND, API.textUTF(string), API.textUTF(title), format)
  1007.     end
  1008.     #--------------------------------------------------------------------------
  1009.     # • [messageBox] : Mesma função do Call a diferença é que e protegido.
  1010.     #--------------------------------------------------------------------------
  1011.     def messageBox(*args)
  1012.       self.call(*args)
  1013.     end
  1014.     protected :messageBox
  1015.   end
  1016.   protected :hwnd, :open, :function
  1017. end
  1018. #==============================================================================
  1019. # * String
  1020. #==============================================================================
  1021. Dax.register(:string)
  1022. class String
  1023.   #--------------------------------------------------------------------------
  1024.   # • [String] : converter à String em UTF8
  1025.   #--------------------------------------------------------------------------
  1026.   def to_utf8
  1027.     API.textUTF(self)
  1028.   end
  1029.   #--------------------------------------------------------------------------
  1030.   # • [Array] : Extrai somente os números da String, e retorna a uma Array.
  1031.   # Exemplo: "João89".numbers # [8, 9]
  1032.   #--------------------------------------------------------------------------
  1033.   def numbers
  1034.     self.scan(/-*\d+/).collect{|n|n.to_i}
  1035.   end
  1036.   #----------------------------------------------------------------------------
  1037.   # • [String] : Aplicando Case Sensitive
  1038.   #   "Exemplo 2" => "Exemplo_2"
  1039.   #----------------------------------------------------------------------------
  1040.   def case_sensitive
  1041.     return self.gsub(" ", "_")
  1042.   end
  1043.   #----------------------------------------------------------------------------
  1044.   # • [String] : Transormar em símbolo.
  1045.   #----------------------------------------------------------------------------
  1046.   def symbol
  1047.     return self.case_sensitive.downcase.to_sym
  1048.   end
  1049.   #----------------------------------------------------------------------------
  1050.   # • [String] : Remove o último caractere da String.
  1051.   #----------------------------------------------------------------------------
  1052.   def backslash
  1053.     return String(self[0, self.split(//).size-1])
  1054.   end
  1055. end
  1056. #==============================================================================
  1057. # * Integer
  1058. #==============================================================================
  1059. Dax.register(:integer)
  1060. class Integer
  1061.   #----------------------------------------------------------------------------
  1062.   # • [TrueClass/FalseClass] : Verifica-se e par.
  1063.   #----------------------------------------------------------------------------
  1064.   def is_evan?
  1065.     return (self & 1) == 0
  1066.   end
  1067.   #----------------------------------------------------------------------------
  1068.   # • [TrueClass/FalseClass] : Verifica-se e impar.
  1069.   #----------------------------------------------------------------------------
  1070.   def is_odd?
  1071.     return (self & 1) == 1
  1072.   end
  1073.   #----------------------------------------------------------------------------
  1074.   # • [Integer] : Aumenta o valor até chegar ao máximo(definido), quando
  1075.   # chegar ao máximo(definido) retorna a zero.
  1076.   #----------------------------------------------------------------------------
  1077.   def up(max)
  1078.     n = self
  1079.     n = n > max ? 0 : n.next
  1080.     return n
  1081.   end
  1082.   #----------------------------------------------------------------------------
  1083.   # • [Integer] : Diminui o valor até chegar a zero, quando chegar a zero
  1084.   # retorna ao valor máximo(defindo).
  1085.   #----------------------------------------------------------------------------
  1086.   def down(max)
  1087.     n = self
  1088.     n = n < 0 ? max : n - 1
  1089.     return n
  1090.   end
  1091.   #----------------------------------------------------------------------------
  1092.   # • [Integer] : Sistema simplificado para fazer calculos factoriais.
  1093.   # !4 #> 24
  1094.   #----------------------------------------------------------------------------
  1095.   def !@
  1096.     return unless self > 0
  1097.     return self.downto(1).reduce(:*)
  1098.   end
  1099.   #----------------------------------------------------------------------------
  1100.   # • [Integer] : Formula de número randômico.
  1101.   #----------------------------------------------------------------------------
  1102.   def aleatory
  1103.     return ((1..(self.abs)).to_a).shuffle[rand(self).to_i].to_i
  1104.   end
  1105. end
  1106. #==============================================================================
  1107. # • Numeric
  1108. #==============================================================================
  1109. Dax.register(:numeric)
  1110. class Numeric
  1111.   #----------------------------------------------------------------------------
  1112.   # * [Numeric] : Transformar em porcentagem
  1113.   #    a : Valor atual.
  1114.   #    b : Valor máximo.
  1115.   #----------------------------------------------------------------------------
  1116.   def to_p(a, b)
  1117.     self * a / b
  1118.   end
  1119.   #----------------------------------------------------------------------------
  1120.   # * [Numeric] : Variação do número.
  1121.   #----------------------------------------------------------------------------
  1122.   def randomic
  1123.     return ( (self+rand(2)) + (self + (rand(2) == 0 ? rand(4) : -rand(4)) ) ) / 2
  1124.   end
  1125. end
  1126. #==============================================================================
  1127. # * Color
  1128. #==============================================================================
  1129. Dax.register(:color)
  1130. class Color
  1131.   #----------------------------------------------------------------------------
  1132.   # • [Color] : Permite você modificar a opacidade da cor.
  1133.   #     Color.new(r, g, b).opacity([alpha])
  1134.   #  O valor padrão do alpha e 128.. não é preciso espeficar.
  1135.   #----------------------------------------------------------------------------
  1136.   def opacity(alpha=nil)
  1137.     self.set(self.red, self.green, self.blue, alpha || 128)
  1138.   end
  1139.   #----------------------------------------------------------------------------
  1140.   # • [Color] : Inverte as cores.
  1141.   #     Color.new(r, g, b[, a).invert!
  1142.   #----------------------------------------------------------------------------
  1143.   def invert!
  1144.     self.set(255-self.red, 255-self.green, 255-self.blue, self.alpha)
  1145.   end
  1146.   #----------------------------------------------------------------------------
  1147.   # • [Color] : Reverte as cores.
  1148.   #     Color.new(r, g, b[, a).revert
  1149.   #----------------------------------------------------------------------------
  1150.   def revert
  1151.     self.set(*[self.red, self.green, self.blue, self.alpha].reverse!)
  1152.   end
  1153.   #----------------------------------------------------------------------------
  1154.   # • [String] : Converte para string as informações dos valores das cores.
  1155.   #      Color.new(0, 0, 0).to_s
  1156.   #       red: 0
  1157.   #       blue: 0
  1158.   #       green: 0
  1159.   #       alpha: 255
  1160.   #----------------------------------------------------------------------------
  1161.   def to_s
  1162.     "red: #{self.red}\nblue: #{self.blue}\ngreen: #{self.green}\nalpha: #{self.alpha}"
  1163.   end
  1164.   #----------------------------------------------------------------------------
  1165.   # • [TrueClass/FalseClass] : Comparar cores, retorna a [true] se for igual..
  1166.   # retorna a [false] se não for igual.
  1167.   #----------------------------------------------------------------------------
  1168.   def ==(color)
  1169.     return (self.red == color.red and self.green == color.green and self.blue == color.blue and
  1170.       self.alpha == color.alpha) ? true : false
  1171.   end
  1172.   #----------------------------------------------------------------------------
  1173.   # • [Hash] : Retorna aos valores das cores em formato de Hash.
  1174.   #      Color.new(0, 0, 0).to_h
  1175.   #      {:red => 0, :green => 0, :blue => 0, :alpha => 255}
  1176.   #----------------------------------------------------------------------------
  1177.   def to_h
  1178.     return {
  1179.       red: self.red, green: self.green, blue: self.blue, alpha: self.alpha,
  1180.     }
  1181.   end
  1182.   #----------------------------------------------------------------------------
  1183.   # • [Array] : Retorna aos valores das cores em formato de Array.
  1184.   #     Color.new(0, 0, 0).to_a
  1185.   #     [0, 0, 0, 255]
  1186.   #----------------------------------------------------------------------------
  1187.   def to_a
  1188.     return [self.red, self.green, self.blue, self.alpha]
  1189.   end
  1190.   #----------------------------------------------------------------------------
  1191.   # • [Color] Soma os valores das cores com os valores de outras cores.
  1192.   # Ex: color + Color.new(21,54,255)
  1193.   #----------------------------------------------------------------------------
  1194.   def +(color)
  1195.     return unless color.is_a?(Color)
  1196.     red = self.red + color.red
  1197.     green = self.green + color.green
  1198.     blue = self.blue + color.blue
  1199.     self.set(red, green, blue)
  1200.   end
  1201.   #----------------------------------------------------------------------------
  1202.   # • [Color] Subtrai os valores das cores com os valores de outras cores.
  1203.   # Ex: color - Color.new(21,54,255)
  1204.   #----------------------------------------------------------------------------
  1205.   def -(color)
  1206.     return unless color.is_a?(Color)
  1207.     red = self.red - color.red
  1208.     green = self.green - color.green
  1209.     blue = self.blue - color.blue
  1210.     self.set(red, green, blue)
  1211.   end
  1212.   #----------------------------------------------------------------------------
  1213.   # • [Color] Multiplica os valores das cores com os valores de outras cores.
  1214.   # Ex: color * Color.new(21,54,255)
  1215.   #----------------------------------------------------------------------------
  1216.   def *(color)
  1217.     return unless color.is_a?(Color)
  1218.     red = (self.red * color.red) / 255.0
  1219.     green = (self.green * color.green) / 255.0
  1220.     blue = (self.blue * color.blue) / 255.0
  1221.     self.set(red, green, blue)
  1222.   end
  1223.   #----------------------------------------------------------------------------
  1224.   # • [Numeric] : Retorna ao valor mais alto que tiver, dentre os valores
  1225.   # especificados das cores.
  1226.   #----------------------------------------------------------------------------
  1227.   def max
  1228.     [red, green, blue].max
  1229.   end
  1230.   #----------------------------------------------------------------------------
  1231.   # • [Numeric] : Retorna ao valor menor que tiver, dentre os valores
  1232.   # especificados das cores.
  1233.   #----------------------------------------------------------------------------
  1234.   def min
  1235.     [red, green, blue].min
  1236.   end
  1237.   #----------------------------------------------------------------------------
  1238.   # • [Color] : Define uma cor aleatória:
  1239.   #   Exemplo: Color.new.random
  1240.   #----------------------------------------------------------------------------
  1241.   def random
  1242.     self.set(rand(256), rand(256), rand(256))
  1243.   end
  1244.   #----------------------------------------------------------------------------
  1245.   # • [Color] : Define uma cor em hexadécimal.
  1246.   #   Exemplo : Color.new.hex("ffffff")
  1247.   #----------------------------------------------------------------------------
  1248.   def hex(string)
  1249.     self.set(*string.scan(/../).map { |color| color.to_i(16)})
  1250.   end
  1251.   #----------------------------------------------------------------------------
  1252.   # • [Color] : Retorna a cor padrão.
  1253.   #    Exemplo : Color.new.default
  1254.   #----------------------------------------------------------------------------
  1255.   def default
  1256.     self.hex("ffffff")
  1257.   end
  1258. end
  1259. #==============================================================================
  1260. # • Rect
  1261. #==============================================================================
  1262. Dax.register(:rect)
  1263. class Rect
  1264.   #----------------------------------------------------------------------------
  1265.   # • [TrueClass/FalseClass] : Verificar se algo está na área.
  1266.   #----------------------------------------------------------------------------
  1267.   def in?(x, y)
  1268.     x.between?(self.x, self.x + self.width) &&
  1269.     y.between?(self.y, self.y + self.height)
  1270.   end
  1271.   #----------------------------------------------------------------------------
  1272.   # • [NilClass] : Cada elemento em um bloco.
  1273.   #    rect.each { |x, y, w, h| }
  1274.   #----------------------------------------------------------------------------
  1275.   def each
  1276.     yield(self.x, self.y, self.width, self.height)
  1277.     return nil
  1278.   end
  1279. end
  1280. #==============================================================================
  1281. # • DMath
  1282. #==============================================================================
  1283. Dax.register(:dmath, 'Dax', 1.5, '04/05/13')
  1284. module DMath
  1285.   extend self
  1286.   #----------------------------------------------------------------------------
  1287.   # • Constantes para fórmula de dano.
  1288.   #----------------------------------------------------------------------------
  1289.   MAX_VALUE_PARAM = 256
  1290.   MAX_VALUE_PARAM_AXE = 128
  1291.   MAX_VALUE_PARAM_DAGGER = 218
  1292.   MAX_VALUE_PARAM_GUN = 99
  1293.   MAX_VALUE_MAGIC = 218
  1294.   #----------------------------------------------------------------------------
  1295.   # • [Float] : Cálcula a raíz quadrada que qualquer grau.
  1296.   #       n : Número que será calculado.
  1297.   #       g : Grau da raíz.
  1298.   # Dmath.sqrt(27, 3) # Cálculo da raíz cúbica de 27 => 3.0
  1299.   #----------------------------------------------------------------------------
  1300.   def sqrt(n, g)
  1301.     raise(ArgumentError) if n < 0 && n.is_evan?
  1302.     x, count, num = 1.0, 0.0, 0.0
  1303.     while
  1304.       num = x - ( ( x ** g - n ) / ( g * ( x ** g.pred ) ) )
  1305.       (x == num) || (count > 20) ? break : eval("x = num; count += 1")
  1306.     end
  1307.     return num
  1308.   end
  1309.   #----------------------------------------------------------------------------
  1310.   # • [Numeric] : Clamp | Delimitar o inteiro
  1311.   #    num : Número.
  1312.   #    low : Número minímo. Sê o 'num' for menor que min retorna a low.
  1313.   #    high : Número máximo. Sê o 'num' for maior que hight retorna a high, caso
  1314.   # não retorna ao próprio número(num).
  1315.   #----------------------------------------------------------------------------
  1316.   def clamp(num, low, high)
  1317.     num, low, high = num.to_i, low.to_i, high.to_i
  1318.     num = num < low ? low : num > high ? high : num
  1319.     num
  1320.   end
  1321.   #----------------------------------------------------------------------------
  1322.   # • [Array] : Centralizar um objeto n'outro.
  1323.   #    object : Objeto, tem que ser do tipo [Sprite] ou [Window_Base]
  1324.   #    object_for_centralize : Objeto que irá se centralizar no 'object', tem
  1325.   # que ser do tipo [Sprite] ou [Window_Base]
  1326.   # * Retorna a uma Array contendo as informações das novas posições em X e Y.
  1327.   #----------------------------------------------------------------------------
  1328.   def centralize_object(object, object_for_centralize)
  1329.     x = object.x + (object.width - object_for_centralize.width) / 2
  1330.     y = object.y + (object.height - object_for_centralize.height) / 2
  1331.     return x, y
  1332.   end
  1333.   #----------------------------------------------------------------------------
  1334.   # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição X.
  1335.   #    objectx : Valor da posição X do objeto número 1.
  1336.   #    objectwidth : Valor da largura do objeto número 1.
  1337.   #    object_for_centralizewidth : Valor da largura do objeto que irá se
  1338.   # centralizar no objeto número 1.
  1339.   # * Retorna ao valor da posição X.
  1340.   #----------------------------------------------------------------------------
  1341.   def centralize_x(objectx, objectwidth, object_for_centralizewidth)
  1342.     return objectx + (objectwidth - object_for_centralizewidth) / 2
  1343.   end
  1344.   #----------------------------------------------------------------------------
  1345.   # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição Y.
  1346.   #    objecty : Valor da posição Y do objeto número 1.
  1347.   #    objectheight : Valor da altura do objeto número 1.
  1348.   #    object_for_centralizeheight : Valor da altura do objeto que irá se
  1349.   # centralizar no objeto número 1.
  1350.   # * Retorna ao valor da posição Y.
  1351.   #----------------------------------------------------------------------------
  1352.   def centralize_y(objecty, objectheight, object_for_centralizeheight)
  1353.     return objecty + (objectheight - object_for_centralizeheight) / 2
  1354.   end
  1355.   #----------------------------------------------------------------------------
  1356.   # • [Numeric] : Obter a posição X do centro da tela referente a largura do objeto X.
  1357.   # Exemplo: get_x_center_screen(sprite.width) : Irá retornar ao valor da posição
  1358.   # X para que o objeto fique no centro da tela.
  1359.   # Exemplo: sprite.x = get_x_center_screen(sprite.width)
  1360.   #----------------------------------------------------------------------------
  1361.   def get_x_center_screen(width)
  1362.     return (Graphics.width - width) / 2
  1363.   end
  1364.   #----------------------------------------------------------------------------
  1365.   # • [Numeric] : Obter a posição Y do centro da tela referente a altura do objeto X.
  1366.   # Exemplo: get_y_center_screen(sprite.height) : Irá retornar ao valor da posição
  1367.   # Y para que o objeto fique no centro da tela.
  1368.   # Exemplo: sprite.y = get_y_center_screen(sprite.height)
  1369.   #----------------------------------------------------------------------------
  1370.   def get_y_center_screen(height)
  1371.     return (Graphics.height - height) / 2
  1372.   end
  1373.   #--------------------------------------------------------------------------
  1374.   # • [TrueClass/FalseClass] : Verifica se um objeto está na área de um círculo.
  1375.   #    object : Objeto do tipo da classe [Sprite].
  1376.   #    object2 : Objeto do tipo da classe [Sprite].
  1377.   #    size : Tamanho geral do círculo.
  1378.   #--------------------------------------------------------------------------
  1379.   def circle(object, object2, size)
  1380.     ( (object.x - object2.x) ** 2) + ( (object.y - object2.y) ** 2) <= (size ** 2)
  1381.   end
  1382.   #----------------------------------------------------------------------------
  1383.   # • [Numeric] : Converter o valor em graus.
  1384.   #----------------------------------------------------------------------------
  1385.   def graus
  1386.     360 / (2 * Math::PI)
  1387.   end
  1388.   #----------------------------------------------------------------------------
  1389.   # • [Numeric] : Converte o valor em radiano.
  1390.   #----------------------------------------------------------------------------
  1391.   def radian(degree)
  1392.     return (degree.to_f/180) * Math::PI
  1393.   end
  1394.   #----------------------------------------------------------------------------
  1395.   # • [Numeric] : Converte o valor em grau.
  1396.   #----------------------------------------------------------------------------
  1397.   def degree(radian)
  1398.     return (radian.to_f/Math::PI) * 180
  1399.   end
  1400.   #----------------------------------------------------------------------------
  1401.   # • [Numeric] : Retorna pra base de 4 decimais.
  1402.   #----------------------------------------------------------------------------
  1403.   def to_4_dec(n)
  1404.     ((n * 1000).ceil) / 1000
  1405.   end
  1406.   #----------------------------------------------------------------------------
  1407.   # • [Numeric] : Retorna a área do triângulo.
  1408.   # x : x  : Posição x do ponto 1
  1409.   #     y  : Posição y do ponto 1
  1410.   #     x2 : Posição x do ponto 2
  1411.   #     y2 : Posição y do ponto 2
  1412.   #     x3 : Posição x do ponto 3
  1413.   #     y3 : Posição y do ponto 3
  1414.   #----------------------------------------------------------------------------
  1415.   def triangle_area(*args)
  1416.     x, y, x2, y2, x3, y3 = *args
  1417.     return (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y)
  1418.   end
  1419.   #----------------------------------------------------------------------------
  1420.   # • [Numeric] : Método para calcular a distância de um objeto para com outro.
  1421.   #----------------------------------------------------------------------------
  1422.   def distance_sensor(target, target2)
  1423.     return (target.x - target2.x).abs + (target.y - target2.y).abs
  1424.   end
  1425.   #----------------------------------------------------------------------------
  1426.   # • [Numeric] : Dentro do círculo.
  1427.   #----------------------------------------------------------------------------
  1428.   def circle_in(t, b, c, d)
  1429.     return -c * (Math.sqrt(1 - (t /= d.to_f) * t) - 1) + b
  1430.   end
  1431.   #----------------------------------------------------------------------------
  1432.   # • [Numeric] : Fora do círculo
  1433.   #----------------------------------------------------------------------------
  1434.   def circle_out(t, b, c, d)
  1435.     return c * Math.sqrt(1 - (t=t/d.to_f-1)*t) + b
  1436.   end
  1437.   #----------------------------------------------------------------------------
  1438.   # • [Numeric] : Retorna ao valor minímo, do valor máximo de min & v, com o
  1439.   # valor de max.
  1440.   #----------------------------------------------------------------------------
  1441.   def force_range(v, min, max)
  1442.     [[min, v].max, max].min
  1443.   end
  1444.   #----------------------------------------------------------------------------
  1445.   # • Cálculo de variação para o dano. Para equilibrar.
  1446.   #----------------------------------------------------------------------------
  1447.   def random
  1448.     (1 + 2.aleatory) ** 0.125
  1449.   end
  1450.   #----------------------------------------------------------------------------
  1451.   # • Resultado final.
  1452.   #----------------------------------------------------------------------------
  1453.   def lastResult(x)
  1454.     return x <= 0 ? 0 : x.round
  1455.   end
  1456.   #----------------------------------------------------------------------------
  1457.   # • [Formula de dano] : Espadas(1 & 2 mão), lanças, bestas, cajado.
  1458.   #----------------------------------------------------------------------------
  1459.   def sword(attack, strength, defense, level)
  1460.     str = strength.randomic
  1461.     return lastResult((attack.randomic * random - defense.randomic) * (1 + str * (level + str) / MAX_VALUE_PARAM))
  1462.   end
  1463.   #----------------------------------------------------------------------------
  1464.   # • [Formula de dano] : Desarmado.
  1465.   #----------------------------------------------------------------------------
  1466.   def unarmed(strength, defense, level)
  1467.     str = strength.randomic
  1468.     lastResult((11 * random - defense.randomic) * str * (level + str) / MAX_VALUE_PARAM)
  1469.   end
  1470.   #----------------------------------------------------------------------------
  1471.   # • [Formula de dano] : Desarmado com luva.
  1472.   #----------------------------------------------------------------------------
  1473.   def unarmed_brawler(strength, defense, level)
  1474.     str = strength.randomic
  1475.     lastResult(((level + str) / 2 * random - defense.randomic) * str * (level + str) / MAX_VALUE_PARAM)
  1476.   end
  1477.   #----------------------------------------------------------------------------
  1478.   # • [Formula de dano] : Cajado de mágia.
  1479.   #----------------------------------------------------------------------------
  1480.   def pole(attack, strength, defense, level, magicDefense)
  1481.     str = strength.randomic
  1482.     lastResult((attack.randomic * random - magicDefense.randomic) * (1 + str * (level + str))/ MAX_VALUE_PARAM)
  1483.   end
  1484.   #----------------------------------------------------------------------------
  1485.   # • [Formula de dano] : Maças..
  1486.   #----------------------------------------------------------------------------
  1487.   def mace(attack, defense, magic, level)
  1488.     mag = magic.randomic
  1489.     lastResult((attack.randomic * random - defense.randomic) * (1 + mag * (level + mag)) / MAX_VALUE_PARAM)
  1490.   end
  1491.   #----------------------------------------------------------------------------
  1492.   # • [Formula de dano] : Katanas, staves..
  1493.   #----------------------------------------------------------------------------
  1494.   def katana(attack, defense, strength, magic, level)
  1495.      lastResult((attack.randomic * random - defense.randomic) * (1 + strength.randomic * (level + magic.randomic) / MAX_VALUE_PARAM))
  1496.   end
  1497.   #----------------------------------------------------------------------------
  1498.   # • [Formula de dano] : Machados, marretas..
  1499.   #----------------------------------------------------------------------------
  1500.   def axe(attack, strength, defense, level, vitality)
  1501.     lastResult((attack.randomic * random - defense.randomic) * (1 + strength.randomic * (level+vitality.randomic)/MAX_VALUE_PARAM_AXE))
  1502.   end
  1503.   #----------------------------------------------------------------------------
  1504.   # • [Formula de dano] : Adagas, espadas ninjas e arco..
  1505.   #----------------------------------------------------------------------------
  1506.   def dagger(attack, defense, strength, level, speed)
  1507.     lastResult ((attack.randomic * random) - defense.randomic) * (1 + strength.randomic * (level + speed.randomic) / 218)
  1508.   end
  1509.   #----------------------------------------------------------------------------
  1510.   # • [Formula de dano] : Revolvers
  1511.   #----------------------------------------------------------------------------
  1512.   def gun(attack,defense,strength, level)
  1513.     str = strength.randomic
  1514.     lastResult ( (((attack.randomic * random) - defense.randomic) ** 2) / 64 ) * (1 + str * (level + str) / MAX_VALUE_PARAM_GUN)
  1515.   end
  1516.   #----------------------------------------------------------------------------
  1517.   # • [Formula de dano] : Mágicas de ataques.
  1518.   #----------------------------------------------------------------------------
  1519.   def magicAttack(magicDefense, level, magicAttack, attackMagic)
  1520.     mag = magicAttack.randomic
  1521.     lastResult ( (attackMagic.randomic * random) - magicDefense.randomic ) * (2 + mag.randomic * (level + mag) / MAX_VALUE_MAGIC)
  1522.   end
  1523.   #----------------------------------------------------------------------------
  1524.   # • [Formula de dano] : Mágicas de cura;
  1525.   #----------------------------------------------------------------------------
  1526.   def magicHeal(strengthMagic, magicAttack, level)
  1527.     mag = magicAttack.randomic
  1528.     lastResult (strengthMagic * random) * (2 + mag * (level + mag) / MAX_VALUE_MAGIC)
  1529.   end
  1530. end
  1531. #==============================================================================
  1532. # • Keyboard | Método para usar todas as teclas do teclado.
  1533. #==============================================================================
  1534. Dax.register(:key, "Dax", 2.0)
  1535. module Key
  1536.   extend self
  1537.   attr_accessor :_cacheText # Armazena os textos.
  1538.   #----------------------------------------------------------------------------
  1539.   # • Chaves.
  1540.   #----------------------------------------------------------------------------
  1541.   KEY = {
  1542.     # Chaves diversas.
  1543.     CANCEL: [0x03], BACKSPACE: [0x08], TAB: [0x09], CLEAR: [0x0C],
  1544.     ENTER: [0x0D], SHIFT: [0x10], CONTROL: [0x11], MENU: [0x12],
  1545.     PAUSE: [0x13], ESC: [0x1B], CONVERT: [0x1C], NONCONVERT: [0x1D],
  1546.     ACCEPT: [0x1E], SPACE: [0x20, " "], PRIOR: [0x21], NEXT: [0x22],
  1547.     ENDS: [0x23], HOME: [0x24], LEFT: [0x25], UP: [0x26], RIGHT: [0x27],
  1548.     DOWN: [0x28], SELECT: [0x29], PRINT: [0x2A], EXECUTE: [0x2B],
  1549.     SNAPSHOT: [0x2C], DELETE: [0x2E], HELP: [0x2F], LSHIFT: [0xA0], RSHIFT: [0xA1],
  1550.     LCONTROL: [0xA2], RCONTROL: [0xA3], LALT: [0xA4], RALT: [0xA5], PACKET: [0xE7],
  1551.     MOUSE_RIGHT: [0x01], MOUSE_LEFT: [0x02], MOUSE_MIDDLE: [0x04],
  1552.     # Chaves de números.
  1553.     N0: [0x30, "0", ")"], N1: [0x31, "1", "!"], N2: [0x32, "2", "@"], N3: [0x33, "3", "#"],
  1554.     N4: [0x34, "4", "$"], N5: [0x35, "5", "%"], N6: [0x36, "6", "¨"], N7: [0x37, "7", "&"],
  1555.     N8: [0x38, "8", "*"], N9: [0x39, "9", "("],
  1556.     # Chaves de letras.
  1557.     A: [0x41, "A"], B: [0x42, "B"], C: [0x43, "C"], D: [0x44, "D"], E: [0x45, "E"],
  1558.     F: [0x46, "F"], G: [0x47, "G"], H: [0x48, "H"], I: [0x49, "I"], J: [0x4A, "J"],
  1559.     K: [0x4B, "K"], L: [0x4C, "L"], M: [0x4D, "M"], N: [0x4E, "N"], O: [0x4F, "O"],
  1560.     P: [0x50, "P"], Q: [0x51, "Q"], R: [0x52, "R"], S: [0x53, "S"], T: [0x54, "T"],
  1561.     U: [0x55, "U"], V: [0x56, "V"], W: [0x57, "W"], X: [0x58, "X"], Y: [0x59, "Y"],
  1562.     Z: [0x5A, "Z"],
  1563.     # Chaves do window.
  1564.     LWIN: [0x5B], RWIN: [0x5C], APPS: [0x5D], SLEEP: [0x5F], BROWSER_BACK: [0xA6],
  1565.     BROWSER_FORWARD: [0xA7], BROWSER_REFRESH: [0xA8], BROWSER_STOP: [0xA9],
  1566.     BROWSER_SEARCH: [0xAA], BROWSER_FAVORITES: [0xAB], BROWSER_HOME: [0xAC],
  1567.     VOLUME_MUTE: [0xAD], VOLUME_DOWN: [0xAE], VOLUME_UP: [0xAF],
  1568.     MEDIA_NEXT_TRACK: [0xB0], MEDIA_PREV_TRACK: [0xB1], MEDIA_STOP: [0xB2],
  1569.     MEDIA_PLAY_PAUSE: [0xB3], LAUNCH_MAIL: [0xB4], LAUNCH_MEDIA_SELECT: [0xB5],
  1570.     LAUNCH_APP1: [0xB6], LAUNCH_APP2: [0xB7], PROCESSKEY: [0xE5], ATIN: [0xF6],
  1571.     CRSEL: [0xF7], EXSEL: [0xF8], EREOF: [0xF9], PLAY: [0xFA], ZOOM: [0xFB],
  1572.     PA1: [0xFD],
  1573.     # Chaves do NUMPAD
  1574.     NUMPAD0: [0x60, "0"], NUMPAD1: [0x61, "1"], NUMPAD2: [0x62, "2"],
  1575.     NUMPAD3: [0x63, "3"], NUMPAD4: [0x64, "4"], NUMPAD5: [0x65, "5"],
  1576.     NUMPAD6: [0x66, "6"], NUMPAD7: [0x67, "7"], NUMPAD8: [0x68, "8"], NUMPAD9: [0x69, "9"],
  1577.     MULTIPLY: [0x6A, "*"], ADD: [0x6B, "+"], SEPARATOR: [0x6C, "-"],
  1578.     SUBTRACT: [0x6D, "-"], DECIMAL: [0x6E, "."], DIVIDE: [0x6F, "/"],
  1579.     # Caches de função.
  1580.     F1: [0x70], F2: [0x71], F3: [0x72], F4: [0x73], F5: [0x74], F6: [0x75],
  1581.     F7: [0x76], F8: [0x77], F9: [0x78], F10: [0x79], F11: [0x7A], F12: [0x7B],
  1582.     F13: [0x7C], F14: [0x7D], F15: [0x7E], F16: [0x7F], F17: [0x80], F18: [0x81],
  1583.     F19: [0x82], F20: [0x83], F21: [0x84], F22: [0x85], F23: [0x86], F24: [0x87],
  1584.     # Chaves alternativas.
  1585.     CAPS: [0x14], INSERT: [0x2D], NUMLOCK: [0x90], SCROLL: [0x91],
  1586.     # Chaves OEM, variadas.
  1587.     OEM_1: [0xBA, ";", ":"], OEM_PLUS: [0xBB, "+", "="], OEM_COMMA: [0xBC, ",", "<"],
  1588.     OEM_MINUS: [0xBD, "-", "_"], OEM_PERIOD: [0xBE, ".", ">"],
  1589.     OEM_2: [0xBF, ";", ":"], OEM_3: [0xC0, "'", '"'], OEM_4: [0xDB, "[", "{"],
  1590.     OEM_5: [0xDB, "[", "{"], OEM_6: [0xDD, "]", "}"], OEM_7: [0xDE, "~", '^'],
  1591.     OEM_102: [0xE2], OEM_CLEAR: [0xFE],
  1592.   }
  1593.   #----------------------------------------------------------------------------
  1594.   # • Variáveis do módulo.
  1595.   #----------------------------------------------------------------------------
  1596.   @_cacheText = ""
  1597.   @til ||= 0
  1598.   @unpack_string = 'b'*256
  1599.   @last_array = '0'*256
  1600.   @press = Array.new(256, false)
  1601.   @trigger = Array.new(256, false)
  1602.   @repeat = Array.new(256, false)
  1603.   @release = Array.new(256, false)
  1604.   @repeat_counter = Array.new(256, 0)
  1605.   @getKeyboardState = API::GetKeyboardState
  1606.   @getAsyncKeyState = API::GetAsyncKeyState
  1607.   @getKeyboardState.call(@last_array)
  1608.   @last_array = @last_array.unpack(@unpack_string)
  1609.   for i in 0...@last_array.size
  1610.     @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1611.   end
  1612.   #----------------------------------------------------------------------------
  1613.   # • Atualização.
  1614.   #----------------------------------------------------------------------------
  1615.   def update
  1616.     @trigger = Array.new(256, false)
  1617.     @repeat = Array.new(256, false)
  1618.     @release = Array.new(256, false)
  1619.     array = '0'*256
  1620.     @getKeyboardState.call(array)
  1621.     array = array.unpack(@unpack_string)
  1622.     for i in 0...array.size
  1623.       if array[i] != @last_array[i]
  1624.         @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1625.         if @repeat_counter[i] <= 0 && @press[i]
  1626.           @repeat[i] = true
  1627.           @repeat_counter[i] = 15
  1628.         end
  1629.         if !@press[i]
  1630.           @release[i] = true
  1631.         else
  1632.           @trigger[i] = true
  1633.         end
  1634.       else
  1635.         if @press[i] == true
  1636.           @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  1637.           @release[i] = true if !@press[i]
  1638.         end
  1639.         if @repeat_counter[i] > 0 && @press[i] == true
  1640.           @repeat_counter[i] -= 1
  1641.         elsif @repeat_counter[i] <= 0 && @press[i] == true
  1642.           @repeat[i] = true
  1643.           @repeat_counter[i] = 3
  1644.         elsif @repeat_counter[i] != 0
  1645.           @repeat_counter[i] = 0
  1646.         end
  1647.       end
  1648.     end
  1649.     @last_array = array
  1650.   end
  1651.   #--------------------------------------------------------------------------
  1652.   # * [TrueClass/FalseClass] Obter o estado quando a chave for pressionada.
  1653.   #     key : key index
  1654.   #--------------------------------------------------------------------------
  1655.   def press?(key)
  1656.     return @press[ key.is_a?(Symbol) ?  KEY.get(key)[0] : key ]
  1657.   end
  1658.   #--------------------------------------------------------------------------
  1659.   # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada.
  1660.   #     key : key index
  1661.   #--------------------------------------------------------------------------
  1662.   def trigger?(key)
  1663.     return @trigger[ key.is_a?(Symbol) ?  KEY.get(key)[0] : key ]
  1664.   end
  1665.   #--------------------------------------------------------------------------
  1666.   # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada repetidamente.
  1667.   #     key : key index
  1668.   #--------------------------------------------------------------------------
  1669.   def repeat?(key)
  1670.     return @repeat[ key.is_a?(Symbol) ?  KEY.get(key)[0] : key ]
  1671.   end
  1672.   #--------------------------------------------------------------------------
  1673.   # * [TrueClass/FalseClass] Obter o estado quando a chave for "lançada"
  1674.   #     key : key index
  1675.   #--------------------------------------------------------------------------
  1676.   def release?(key)
  1677.     return @release[ key.is_a?(Symbol) ?  KEY.get(key)[0] : key ]
  1678.   end
  1679.   #----------------------------------------------------------------------------
  1680.   # • [String] Obter à letra correspondente à tecla for pressionada.
  1681.   #     key : key index
  1682.   #----------------------------------------------------------------------------
  1683.   def pressString?(key,i=1)
  1684.     KEY.get(key)[i] rescue "" if press?(key)
  1685.   end
  1686.   #----------------------------------------------------------------------------
  1687.   # • [String] Obter à letra correspondente à tecla for teclada.
  1688.   #     key : key index
  1689.   #----------------------------------------------------------------------------
  1690.   def triggerString?(key,i=1)
  1691.     KEY.get(key)[i] rescue "" if trigger?(key)
  1692.   end
  1693.   #----------------------------------------------------------------------------
  1694.   # • [String] Obter à letra correspondente à tecla for teclada repetidamente.
  1695.   #     key : key index
  1696.   #----------------------------------------------------------------------------
  1697.   def repeatString?(key,i=1)
  1698.     KEY.get(key)[i] rescue "" if repeat?(key)
  1699.   end
  1700.   #----------------------------------------------------------------------------
  1701.   # • [String] Obtêm a string correspondente à tecla do número. Às Strings ficará
  1702.   # armazenada na varíavel _cacheText
  1703.   #----------------------------------------------------------------------------
  1704.   def number?
  1705.     @_cacheText += triggerString?(:NUMPAD0).to_s
  1706.     @_cacheText += triggerString?(:NUMPAD1).to_s
  1707.     @_cacheText += triggerString?(:NUMPAD2).to_s
  1708.     @_cacheText += triggerString?(:NUMPAD3).to_s
  1709.     @_cacheText += triggerString?(:NUMPAD4).to_s
  1710.     @_cacheText += triggerString?(:NUMPAD5).to_s
  1711.     @_cacheText += triggerString?(:NUMPAD6).to_s
  1712.     @_cacheText += triggerString?(:NUMPAD7).to_s
  1713.     @_cacheText += triggerString?(:NUMPAD8).to_s
  1714.     @_cacheText += triggerString?(:NUMPAD9).to_s
  1715.     @_cacheText += press?(:SHIFT) ? triggerString?(:N0, 2).to_s : triggerString?(:N0).to_s
  1716.     @_cacheText += press?(:SHIFT) ? triggerString?(:N1, 2).to_s : triggerString?(:N1).to_s
  1717.     @_cacheText += press?(:SHIFT) ? triggerString?(:N2, 2).to_s : triggerString?(:N2).to_s
  1718.     @_cacheText += press?(:SHIFT) ? triggerString?(:N3, 2).to_s : triggerString?(:N3).to_s
  1719.     @_cacheText += press?(:SHIFT) ? triggerString?(:N4, 2).to_s : triggerString?(:N4).to_s
  1720.     @_cacheText += press?(:SHIFT) ? triggerString?(:N5, 2).to_s : triggerString?(:N5).to_s
  1721.     @_cacheText += press?(:SHIFT) ? triggerString?(:N6, 2).to_s : triggerString?(:N6).to_s
  1722.     @_cacheText += press?(:SHIFT) ? triggerString?(:N7, 2).to_s : triggerString?(:N7).to_s
  1723.     @_cacheText += press?(:SHIFT) ? triggerString?(:N8, 2).to_s : triggerString?(:N8).to_s
  1724.     @_cacheText += press?(:SHIFT) ? triggerString?(:N9, 2).to_s : triggerString?(:N9).to_s
  1725.   end
  1726.   #----------------------------------------------------------------------------
  1727.   # • [String] : Retorna a string correspondente aos caractéres.
  1728.   #----------------------------------------------------------------------------
  1729.   def keysString?
  1730.     @til = @til > 0 ? 0 : @til.next if trigger?(:OEM_7)
  1731.     self.number?
  1732.     @_cacheText += triggerString?(:SPACE).to_s
  1733.     @_cacheText += triggerString?(:ADD).to_s
  1734.     @_cacheText += triggerString?(:SEPARATOR).to_s
  1735.     @_cacheText += triggerString?(:MULTIPLY).to_s
  1736.     @_cacheText += triggerString?(:SUBTRACT).to_s
  1737.     @_cacheText += triggerString?(:DECIMAL).to_s
  1738.     @_cacheText += triggerString?(:DIVIDE).to_s
  1739.     @_cacheText += press?(:SHIFT) ?  triggerString?(:OEM_MINUS, 2).to_s : triggerString?(:OEM_MINUS).to_s
  1740.     @_cacheText += press?(:SHIFT) ?  triggerString?(:OEM_2, 2).to_s : triggerString?(:OEM_2).to_s
  1741.     @_cacheText +=  press?(:SHIFT) ?  triggerString?(:OEM_PLUS, 2).to_s : triggerString?(:OEM_PLUS).to_s
  1742.     @_cacheText +=  press?(:SHIFT) ?  triggerString?(:OEM_COMMA, 2).to_s : triggerString?(:OEM_COMMA).to_s
  1743.     @_cacheText +=  press?(:SHIFT) ?  triggerString?(:OEM_PERIOD, 2).to_s : triggerString?(:OEM_PERIOD).to_s
  1744.     @_cacheText +=  press?(:SHIFT) ?  triggerString?(:OEM_3, 2).to_s : triggerString?(:OEM_3).to_s
  1745.     if press?(:SHIFT)
  1746.       @_cacheText += triggerString?(:OEM_7, 2).to_s
  1747.     else
  1748.       @_cacheText += triggerString?(:OEM_7, 1).to_s if @til > 0
  1749.     end
  1750.     @_cacheText += caps? ? triggerString?(:A).to_s : triggerString?(:A).to_s.downcase
  1751.     @_cacheText += caps? ? triggerString?(:B).to_s : triggerString?(:B).to_s.downcase
  1752.     @_cacheText += caps? ? triggerString?(:C).to_s : triggerString?(:C).to_s.downcase
  1753.     @_cacheText += caps? ? triggerString?(:D).to_s : triggerString?(:D).to_s.downcase
  1754.     @_cacheText += caps? ? triggerString?(:E).to_s : triggerString?(:E).to_s.downcase
  1755.     @_cacheText += caps? ? triggerString?(:F).to_s : triggerString?(:F).to_s.downcase
  1756.     @_cacheText += caps? ? triggerString?(:G).to_s : triggerString?(:G).to_s.downcase
  1757.     @_cacheText += caps? ? triggerString?(:H).to_s : triggerString?(:H).to_s.downcase
  1758.     @_cacheText += caps? ? triggerString?(:I).to_s : triggerString?(:I).to_s.downcase
  1759.     @_cacheText += caps? ? triggerString?(:J).to_s : triggerString?(:J).to_s.downcase
  1760.     @_cacheText += caps? ? triggerString?(:K).to_s : triggerString?(:K).to_s.downcase
  1761.     @_cacheText += caps? ? triggerString?(:N).to_s : triggerString?(:N).to_s.downcase
  1762.     @_cacheText += caps? ? triggerString?(:M).to_s : triggerString?(:M).to_s.downcase
  1763.     @_cacheText += caps? ? triggerString?(:O).to_s : triggerString?(:O).to_s.downcase
  1764.     @_cacheText += caps? ? triggerString?(:P).to_s : triggerString?(:P).to_s.downcase
  1765.     @_cacheText += caps? ? triggerString?(:Q).to_s : triggerString?(:Q).to_s.downcase
  1766.     @_cacheText += caps? ? triggerString?(:R).to_s : triggerString?(:R).to_s.downcase
  1767.     @_cacheText += caps? ? triggerString?(:S).to_s : triggerString?(:S).to_s.downcase
  1768.     @_cacheText += caps? ? triggerString?(:T).to_s : triggerString?(:T).to_s.downcase
  1769.     @_cacheText += caps? ? triggerString?(:U).to_s : triggerString?(:U).to_s.downcase
  1770.     @_cacheText += caps? ? triggerString?(:V).to_s : triggerString?(:V).to_s.downcase
  1771.     @_cacheText += caps? ? triggerString?(:W).to_s : triggerString?(:W).to_s.downcase
  1772.     @_cacheText += caps? ? triggerString?(:X).to_s : triggerString?(:X).to_s.downcase
  1773.     @_cacheText += caps? ? triggerString?(:Y).to_s : triggerString?(:Y).to_s.downcase
  1774.     @_cacheText += caps? ? triggerString?(:Z).to_s : triggerString?(:Z).to_s.downcase
  1775.     @_cacheText += caps? ? triggerString?(:L).to_s : triggerString?(:L).to_s.downcase
  1776.     self.backslash?
  1777.   end
  1778.   #----------------------------------------------------------------------------
  1779.   # • [String] : Retorna a string com à última letra removida.
  1780.   #     condition : trigger | press | repeat
  1781.   # Por padrão é trigger
  1782.   #----------------------------------------------------------------------------
  1783.   def backslash?(condition=:trigger)
  1784.     eval("return @_cacheText = @_cacheText.backslash if #{condition}?(:BACKSPACE)")
  1785.   end
  1786.   #----------------------------------------------------------------------------
  1787.   # • Verificar se o CAPS LOCK está ativado ou desativado.
  1788.   #----------------------------------------------------------------------------
  1789.   def caps?
  1790.     API.get_caps_lock
  1791.   end
  1792.   #----------------------------------------------------------------------------
  1793.   # • Verificar se pressionar qualquer tecla.
  1794.   #----------------------------------------------------------------------------
  1795.   def any_key?
  1796.     [0.upto(255).to_a - [0x19]].each { |i| @trigger[i] && (0x8 << 0x04) == (0x8 << 0x04) }
  1797.   end
  1798.   #----------------------------------------------------------------------------
  1799.   # • Para movimento WSAD
  1800.   #----------------------------------------------------------------------------
  1801.   def wsad
  1802.     return 8 if trigger?(:W)
  1803.     return 4 if trigger?(:A)
  1804.     return 6 if trigger?(:D)
  1805.     return 2 if trigger?(:S)
  1806.     return 0
  1807.   end
  1808. end
  1809. #==============================================================================
  1810. # • Sprite
  1811. #==============================================================================
  1812. Dax.register(:sprite)
  1813. class Sprite
  1814.   #----------------------------------------------------------------------------
  1815.   # • Variáveis públicas da instância.
  1816.   #----------------------------------------------------------------------------
  1817.   attr_accessor :clone_sprite
  1818.   attr_accessor :outline_fill_rect
  1819.   #----------------------------------------------------------------------------
  1820.   # • Novo método. Modos de usos abaixo:
  1821.   #  * [normal] : É o método normal, na qual você não define nada. Sprite.new
  1822.   #  * [viewport] : É o método na qual você define um viewport.
  1823.   # Sprite.new(Viewport)
  1824.   #  * [system] : É o método na qual você já define um bitmap que irá carregar
  1825.   # uma imagem já direto da pasta System, através do Cache.
  1826.   # Sprite.new("S: Nome do Arquivo")
  1827.   #  * [picture] : É o método na qual você já define um bitmap que irá carregar
  1828.   # uma imagem já direito da pasta Pictures, através do Cache.
  1829.   # Sprite.new("P: Nome do Arquivo")
  1830.   #  * [graphics] : É o método na qual você já define um bitmap com uma imagem
  1831.   # que está dentro da pasta Graphics, através do Cache.
  1832.   # Sprite.new("G: Nome do Arquivo.")
  1833.   #  * [width, height] : É o método na qual você já define a largura e altura
  1834.   # do bitmap. Sprite.new([width, height])
  1835.   #  * [elements] : É o método na qual você já define a largura, altura,
  1836.   # posição X, posição Y e Prioridade do bitmap.
  1837.   # Sprite.new([width, height, x, y, z])
  1838.   #----------------------------------------------------------------------------
  1839.   alias new_initialize initialize
  1840.   def initialize(viewport=nil)
  1841.     @clone_sprite = []
  1842.     @outline_fill_rect = nil
  1843.     if viewport.is_a?(String)
  1844.       new_initialize(nil)
  1845.       if viewport.match(/S: ([^>]*)/)
  1846.         self.bitmap = Cache.system($1.to_s)
  1847.       elsif viewport.match(/P: ([^>]*)/)
  1848.         self.bitmap = Cache.picture($1.to_s)
  1849.       elsif viewport.match(/G: ([^>]*)/)
  1850.         self.bitmap = Cache.load_bitmap("Graphics/", $1.to_s)
  1851.       else
  1852.         self.bitmap = Bitmap.new(viewport)
  1853.       end
  1854.     elsif viewport.is_a?(Array)
  1855.       if viewport.size == 2
  1856.         new_initialize(nil)
  1857.         self.bitmap = Bitmap.new(viewport[0], viewport[1])
  1858.       elsif viewport.size == 5
  1859.         new_initialize(nil)
  1860.         self.bitmap = Bitmap.new(viewport[0], viewport[1])
  1861.         self.x, self.y, self.z = viewport[2], viewport[3], viewport[4]
  1862.       end
  1863.     elsif viewport.is_a?(Viewport) or viewport.nil?
  1864.       new_initialize(viewport)
  1865.     end
  1866.   end
  1867.   #----------------------------------------------------------------------------
  1868.   # • Renovação do Sprite.
  1869.   #----------------------------------------------------------------------------
  1870.   alias :dax_core_dispose :dispose
  1871.   def dispose
  1872.     dax_core_dispose
  1873.     @outline_fill_rect.dispose unless @outline_fill_rect.nil?
  1874.   end
  1875.   #----------------------------------------------------------------------------
  1876.   # • Definir um contorno no Sprite em forma de retângulo.
  1877.   #     color : Cor do contorno.
  1878.   #     size : Tamanho da linha do contorno.
  1879.   #     vis : Visibilidade. true - visível | false - invisível.
  1880.   #----------------------------------------------------------------------------
  1881.   def set_outline(color=Color.new.default, size=2, vis=true)
  1882.     @outline_fill_rect = Sprite.new([self.width, self.height, self.x, self.y, self.z+2])
  1883.     @outline_fill_rect.bitmap.fill_rect(0, 0, self.width, size, color)
  1884.     @outline_fill_rect.bitmap.fill_rect(0, self.height-size, self.width, size, color)
  1885.     @outline_fill_rect.bitmap.fill_rect(0, 0, size, self.height, color)
  1886.     @outline_fill_rect.bitmap.fill_rect(self.width-size, 0, size, self.height, color)
  1887.     @outline_fill_rect.visible = vis
  1888.   end
  1889.   #----------------------------------------------------------------------------
  1890.   # • Atualização do contorno.
  1891.   #     vis : Visibilidade. true - visível | false - invisível.
  1892.   #----------------------------------------------------------------------------
  1893.   def update_outline(vis=true)
  1894.     @outline_fill_rect.visible = vis
  1895.     @outline_fill_rect.x, @outline_fill_rect.y = self.x, self.y
  1896.   end
  1897.   #----------------------------------------------------------------------------
  1898.   # • Slide pela direita.
  1899.   #   * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  1900.   #----------------------------------------------------------------------------
  1901.   def slide_right(speed, point)
  1902.     self.x += speed unless self.x >= point
  1903.   end
  1904.   #----------------------------------------------------------------------------
  1905.   # • Slide pela esquerda.
  1906.   #   * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  1907.   #----------------------------------------------------------------------------
  1908.   def slide_left(speed, point)
  1909.     self.x -= speed unless self.x <= point
  1910.   end
  1911.   #----------------------------------------------------------------------------
  1912.   # • Slide por cima.
  1913.   #   * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  1914.   #----------------------------------------------------------------------------
  1915.   def slide_up(speed, point)
  1916.     self.y -= speed unless self.y <= point
  1917.   end
  1918.   #----------------------------------------------------------------------------
  1919.   # • Slide por baixo.
  1920.   #   * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  1921.   #----------------------------------------------------------------------------
  1922.   def slide_down(speed, point)
  1923.     self.y += speed unless self.y >= point
  1924.   end
  1925.   #----------------------------------------------------------------------------
  1926.   # • Define aqui uma posição fixa para um objeto.
  1927.   #   command : Retorna a uma base padrão.
  1928.   #----------------------------------------------------------------------------
  1929.   def position(command=0)
  1930.     return if command.nil?
  1931.     case command
  1932.     # Imagem ficará no canto esquerdo superior. Posição X
  1933.     when 0 then self.x = 0
  1934.     # A posição X ficará no centro da tela.
  1935.     when 1 then self.x = DMath.get_x_center_screen(self.width)
  1936.     # A posição X ficará no canto direito superior.
  1937.     when 2 then self.x = Graphics.width - self.width
  1938.     # A posição Y ficará no canto esquerdo inferior.
  1939.     when 3 then self.y = 0
  1940.     # Posicionar o Y para ficar no centro.
  1941.     when 4 then self.y = DMath.get_y_center_screen(self.height)
  1942.     # Posicionar o Y para ficar no fundo da tela.
  1943.     when 5 then self.y = Graphics.height - self.height
  1944.     # Posicionar a imagem no centro da tela.
  1945.     when :center
  1946.       self.x = (Graphics.width - self.width) / 2
  1947.       self.y = Graphics.height / 2 - self.height / 2
  1948.     # Posicionar no centro esquerdo da tela.
  1949.     when :center_left
  1950.       self.x = 0
  1951.       self.y = (Graphics.height - self.height) / 2  
  1952.     # Posicionar no centro direito da tela.
  1953.     when :center_right
  1954.       self.x = Graphics.width - self.height
  1955.       self.y = (Graphics.height - self.height) / 2  
  1956.     end
  1957.   end
  1958.   #----------------------------------------------------------------------------
  1959.   # • [Numeric] : Tamanho geral
  1960.   #----------------------------------------------------------------------------
  1961.   def size
  1962.     return self.width + self.height
  1963.   end
  1964.   #----------------------------------------------------------------------------
  1965.   # • [Rect] : Retorna ao Rect do Bitmap.
  1966.   #----------------------------------------------------------------------------
  1967.   def rect
  1968.     return self.bitmap.rect
  1969.   end
  1970.   #----------------------------------------------------------------------------
  1971.   # • Base para clonar um Sprite.
  1972.   #    * depht : Prioridade no mapa.
  1973.   #    * clone_bitmap : Se irá clonar o bitmap.
  1974.   # Exemplo: sprite = sprite2.clone
  1975.   #----------------------------------------------------------------------------
  1976.   def clone(depht=0, clone_bitmap=false)
  1977.     @clone_sprite.delete_if { |bitmap| bitmap.disposed? }
  1978.     cloned = Sprite.new(self.viewport)
  1979.     cloned.x, cloned.y = self.x, self.y
  1980.     cloned.bitmap = self.bitmap
  1981.     cloned.bitmap = self.bitmap.clone if clone_bitmap
  1982.     unless depht == 0
  1983.       cloned.z = self.z + depht
  1984.     else
  1985.       @clone_sprite.each { |sprite| sprite.z -= 1 }
  1986.       cloned.z = self.z - 1
  1987.     end
  1988.     cloned.src_rect.set(self.src_rect)
  1989.     ["zoom_x", "zoom_y", "angle", "mirror", "opacity", "blend_type", "visible",
  1990.      "ox", "oy"].each { |meth|
  1991.       eval("cloned.#{meth} = self.#{meth}")
  1992.     }
  1993.     cloned.color.set(color)
  1994.     cloned.tone.set(tone)
  1995.     after_clone(cloned)
  1996.     @clone_sprite.push(cloned)
  1997.     return cloned
  1998.   end
  1999.   #----------------------------------------------------------------------------
  2000.   # • Efeito após ter clonado o Sprite.
  2001.   #----------------------------------------------------------------------------
  2002.   def after_clone(clone)
  2003.   end
  2004.   #----------------------------------------------------------------------------
  2005.   # • O que irá acontecer sê o mouse estiver em cima do sprite?
  2006.   #----------------------------------------------------------------------------
  2007.   def mouse_over
  2008.   end
  2009.   #----------------------------------------------------------------------------
  2010.   # • O que irá acontecer sê o mouse não estiver em cima do sprite?
  2011.   #----------------------------------------------------------------------------
  2012.   def mouse_no_over
  2013.   end
  2014.   #----------------------------------------------------------------------------
  2015.   # • O que irá acontecer sê o mouse clicar no objeto
  2016.   #----------------------------------------------------------------------------
  2017.   def mouse_click
  2018.   end
  2019.   #----------------------------------------------------------------------------
  2020.   # • Atualização dos sprites.
  2021.   #----------------------------------------------------------------------------
  2022.   alias :dax_update :update
  2023.   def update(*args, &block)
  2024.     dax_update(*args, &block)
  2025.     unless Mouse.cursor.nil?
  2026.       self.if_mouse_over { |over| over ? mouse_over : mouse_no_over }
  2027.       self.if_mouse_click { mouse_click }
  2028.     end
  2029.   end
  2030.   #----------------------------------------------------------------------------
  2031.   # • Inverter o lado do sprite.
  2032.   #----------------------------------------------------------------------------
  2033.   def invert!
  2034.     self.mirror = !self.mirror
  2035.   end
  2036. end
  2037. #==============================================================================
  2038. # • Bitmap
  2039. #==============================================================================
  2040. Dax.register(:bitmap)
  2041. class Bitmap
  2042.   #----------------------------------------------------------------------------
  2043.   # • Criar uma barra.
  2044.   #    color : Objeto de Cor [Color]
  2045.   #    actual : Valor atual da barra.
  2046.   #    max : Valor máximo da barra.
  2047.   #    borda : Tamanho da borda da barra.
  2048.   #----------------------------------------------------------------------------
  2049.   def bar(color, actual, max, borda=1)
  2050.     rate = self.width.to_p(actual, max)
  2051.     self.fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  2052.     color)
  2053.   end
  2054.   #----------------------------------------------------------------------------
  2055.   # • Barra em forma de gradient.
  2056.   #    color : Objeto de Cor, em forma de [Array] para conter 2 [Color]
  2057.   # exemplo -> [Color.new(x), Color.new(y)]
  2058.   #    actual : Valor atual da barra.
  2059.   #    max : Valor máximo da barra.
  2060.   #    borda : Tamanho da borda da barra.
  2061.   #----------------------------------------------------------------------------
  2062.   def gradient_bar(color, actual, max, borda=1)
  2063.     rate = self.width.to_p(actual, max)
  2064.     self.gradient_fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  2065.     color[0], color[1], 2)
  2066.   end
  2067.   #----------------------------------------------------------------------------
  2068.   # • Limpar uma área num formato de um círculo.
  2069.   #----------------------------------------------------------------------------
  2070.   def clear_rect_circle(x, y, r)
  2071.     rr = r*r
  2072.     for i in 0...r
  2073.       adj = Math.sqrt(rr - (i*i)).ceil
  2074.       xd = x - adj
  2075.       wd = 2 * adj
  2076.       self.clear_rect(xd, y-i, wd, 1)
  2077.       self.clear_rect(xd, y+i, wd, 1)
  2078.     end
  2079.   end
  2080.   #----------------------------------------------------------------------------
  2081.   # • Novo modo de desenhar textos. Configurações já especificadas.
  2082.   #----------------------------------------------------------------------------
  2083.   def draw_text_rect(*args)
  2084.     self.draw_text(self.rect, *args)
  2085.   end
  2086.   #----------------------------------------------------------------------------
  2087.   # • Salvar em png.
  2088.   #   --- Autor : Gab! ---
  2089.   #----------------------------------------------------------------------------
  2090.   def save(file_name)
  2091.     def chunk(type, data)
  2092.       [data.size, type, data, Zlib.crc32(type + data)].pack("NA4A*N")
  2093.     end
  2094.     img_data = ""
  2095.     width, height = self.width, self.height
  2096.     for j in 0...(height)
  2097.       img_data << "\0"
  2098.       for i in 0...(width)
  2099.         pos_c = self.get_pixel(i, j)
  2100.         img_data << [pos_c.red, pos_c.green, pos_c.blue, pos_c.alpha].pack("C*")
  2101.       end
  2102.     end
  2103.     c = [
  2104.       "\x89PNG\r\n\x1a\n",
  2105.       chunk("IHDR", [width, height, 8, 6, 0, 0, 0].pack("N2C5")),
  2106.       chunk("IDAT", Zlib::Deflate.deflate(img_data)),
  2107.       chunk("IEND", "")
  2108.     ]
  2109.     File.open(file_name << ".png", "wb"){|file| c.each{|chunk| file.write(chunk) }}
  2110.   end
  2111.   #----------------------------------------------------------------------------
  2112.   # • Permite salvar várias imagens em cima de outra.
  2113.   #    Exemplo de comando:
  2114.   # Bitmap.overSave("Pictures/Nova", "Pictures/1", "Characters/2",
  2115.   #                          "Pictures/3", "Characters/4", "Pictures/5")
  2116.   # NÃO ESQUEÇA DE ESPECIFICAR ÀS PASTAS.
  2117.   #----------------------------------------------------------------------------
  2118.   def self.overSave(newfile, first, *args)
  2119.     return if first.empty? || first.nil? || args.empty? || args.nil?
  2120.     firstB = Bitmap.new("Graphics/"+first)
  2121.     args.each { |outhers|
  2122.       firstB.stretch_blt(firstB.rect, Bitmap.new("Graphics/"+outhers), firstB.rect)
  2123.     }
  2124.     firstB.save("Graphics/"+newfile)
  2125.   end
  2126.   #----------------------------------------------------------------------------
  2127.   # • Modificar as cores do [Bitmap] para ficarem Negativas.
  2128.   #----------------------------------------------------------------------------
  2129.   def negative
  2130.     for i in 0...(self.width)
  2131.       for j in 0...(self.height)
  2132.         pix = self.get_pixel(i, j)
  2133.         pix.red = (pix.red - 255) * -1
  2134.         pix.blue = (pix.blue - 255) * -1
  2135.         pix.green = (pix.green - 255) * -1
  2136.         self.set_pixel(i, j, pix)
  2137.       end
  2138.     end
  2139.   end
  2140.   #----------------------------------------------------------------------------
  2141.   # • Grayscale : Modificar as cores do [Bitmap] para cor cinza. Efeito cinza.
  2142.   #----------------------------------------------------------------------------
  2143.   def grayscale(rect = Rect.new(0, 0, self.width, self.height))
  2144.     for i in rect.x...rect.x + rect.width
  2145.       for j in rect.y...rect.y + rect.height
  2146.         colour = self.get_pixel(i,j)
  2147.         grey_pixel = (colour.red*0.3 + colour.green*0.59 + colour.blue*0.11)
  2148.         colour.red = colour.green = colour.blue = grey_pixel
  2149.         self.set_pixel(i,j,colour)
  2150.       end
  2151.     end
  2152.   end
  2153.   #----------------------------------------------------------------------------
  2154.   # • Novo fornecedor de pixel.
  2155.   #----------------------------------------------------------------------------
  2156.   def set_pixel_s(x, y, color, size)
  2157.     for i in 0...size
  2158.       self.set_pixel(x+i, y, color)
  2159.       self.set_pixel(x-i, y, color)
  2160.       self.set_pixel(x, y+i, color)
  2161.       self.set_pixel(x, y-i, color)
  2162.       self.set_pixel(x+i, y+i, color)
  2163.       self.set_pixel(x-i, y-i, color)
  2164.       self.set_pixel(x+i, y-i, color)
  2165.       self.set_pixel(x-i, y+i, color)
  2166.     end
  2167.   end
  2168.   #----------------------------------------------------------------------------
  2169.   # • Desenhar uma linha.
  2170.   #    start_x : Início da linha em X.
  2171.   #    start_y : Início da linha em Y.
  2172.   #    end_x : Finalização da linha em X.
  2173.   #    end_y : Finalização da linha em Y.
  2174.   #----------------------------------------------------------------------------
  2175.   def draw_line(start_x, start_y, end_x, end_y, color, size=1)
  2176.     set_pixel_s(start_x, start_y, color, size)
  2177.     distance = (start_x - end_x).abs + (start_y - end_y).abs
  2178.     for i in 1..distance
  2179.       x = (start_x + 1.0 * (end_x - start_x) * i / distance).to_i
  2180.       y = (start_y + 1.0 * (end_y - start_y) * i / distance).to_i
  2181.       set_pixel_s(x, y, color, size)
  2182.     end
  2183.     set_pixel_s(end_x, end_y, color, size)
  2184.   end
  2185.   #----------------------------------------------------------------------------
  2186.   # • draw_bar_gauge(x, y, current, current_max, border, colors)
  2187.   #   x : Coordenadas X.
  2188.   #   y : Coordenadas Y.
  2189.   #   current : Valor atual da barra.
  2190.   #   current_max : Valor maxímo da barra.
  2191.   #   border : Expressura da borda.
  2192.   #   colors : Cores. [0, 1, 2]
  2193.   #----------------------------------------------------------------------------
  2194.   #  Permite adicionar uma barra.
  2195.   #----------------------------------------------------------------------------
  2196.   def draw_bar_gauge(x, y, current, current_max, colors=[])
  2197.     cw = self.width.to_p(current, current_max)    
  2198.     ch = self.height
  2199.     self.gradient_fill_rect(x, y, self.width, self.height, colors[0], colors[1])
  2200.     src_rect = Rect.new(0, 0, cw, ch)
  2201.     self.blt(x, y, self, src_rect)
  2202.   end
  2203.   #----------------------------------------------------------------------------
  2204.   # • draw_icon(icon_index, x, y, enabled)
  2205.   #   icon_index : ID do ícone.
  2206.   #   x : Coordenadas X.
  2207.   #   y : Coordenadas Y.
  2208.   #   enabled : Habilitar flag, translucido quando false
  2209.   #   filename : Podes definir uma imagem: Basta
  2210.   # por o nome da imagem, ela deve estar na pasta System.
  2211.   #----------------------------------------------------------------------------
  2212.   def draw_icon(icon_index, x, y, enabled = true, filename="IconSet")
  2213.     icon_index = icon_index.nil? ? 0 : icon_index
  2214.     bitmap = Cache.system(filename)
  2215.     rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
  2216.     self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
  2217.   end
  2218.   #----------------------------------------------------------------------------
  2219.   # • draw_gradation_gauge(x, y, width, height, current, current_max, border, colors, align)
  2220.   #   x : Coordenadas X.
  2221.   #   y : Coordenadas Y.
  2222.   #   width : Largura da barra.
  2223.   #   height : Altura da barra.
  2224.   #   current : Valor atual da barra.
  2225.   #   current_max : Valor maxímo da barra.
  2226.   #   border : Expressura da borda.
  2227.   #   colors : Cores. [0, 1, 2]
  2228.   #   align : Alinhamento.
  2229.   #----------------------------------------------------------------------------
  2230.   #  Permite adicionar uma barra.
  2231.   #----------------------------------------------------------------------------
  2232.   def draw_gradation_gauge(x, y, current, current_max, border, colors=[])
  2233.     cw = self.width.to_p(current, current_max)    
  2234.     ch = self.height
  2235.     self.fill_rect(x, y, self.width, self.height, colors[0])
  2236.     self.gradient_fill_rect(x+border, y+border, self.width-(border/2), self.height-(border/2), colors[1], colors[2])
  2237.     src_rect = Rect.new(0, 0, cw, ch)
  2238.     self.blt(x, y, self, src_rect)
  2239.   end
  2240.   #----------------------------------------------------------------------------
  2241.   # • Desenhar um círuclo preenchido.
  2242.   #----------------------------------------------------------------------------
  2243.   def fill_circle(x, y, r, c)
  2244.     rr = r*r
  2245.     for i in 0...r
  2246.       adj = Math.sqrt(rr - (i*i)).ceil
  2247.       xd = x - adj
  2248.       wd = 2 * adj
  2249.       self.fill_rect(xd, y-i, wd, 1, c)
  2250.       self.fill_rect(xd, y+i, wd, 1, c)
  2251.     end
  2252.   end
  2253. end
  2254. #==============================================================================
  2255. # • Mouse
  2256. #==============================================================================
  2257. Dax.register(:mouse)
  2258. module Mouse
  2259.   extend self
  2260.   #--------------------------------------------------------------------------
  2261.   # • Inicialização dos objetos.
  2262.   #--------------------------------------------------------------------------
  2263.   def start
  2264.     @cursor = Sprite_Mouse.new(Dax::Mouse_Name, 0, 0, 100000)
  2265.     x = Dax::Mouse_Name == "" ? 1 : 0
  2266.     API::MouseShowCursor.call(x)
  2267.     @visible = {old: x, actual: x}
  2268.     update
  2269.   end
  2270.   #----------------------------------------------------------------------------
  2271.   # • visible = (boolean)
  2272.   #  * boolean : true ou false
  2273.   # Tornar vísivel ou não o cursor do Mouse.
  2274.   #----------------------------------------------------------------------------
  2275.   def visible=(boolean)
  2276.     @visible[:actual] = boolean
  2277.   end
  2278.   #--------------------------------------------------------------------------
  2279.   # • graphic(graphic_set)
  2280.   #   graphic_set : Se for número é um ícone; Se for string é uma imagem.
  2281.   #--------------------------------------------------------------------------
  2282.   def graphic(graphic_set)
  2283.     @cursor.set_graphic = graphic_set
  2284.   end
  2285.   #--------------------------------------------------------------------------
  2286.   # • show(visible)
  2287.   #   visible : True - para mostrar o mouse | False - para esconder o mouse.
  2288.   #--------------------------------------------------------------------------
  2289.   def show(visible=true)
  2290.     @cursor.visible = visible
  2291.   end
  2292.   #--------------------------------------------------------------------------
  2293.   # • update (Atualização das coordenadas)
  2294.   #--------------------------------------------------------------------------
  2295.   def update
  2296.     return if @cursor.nil?
  2297.     unless @visible[:old] == @visible[:actual]
  2298.       API::MouseShowCursor.call(@visible[:actual])
  2299.     end
  2300.     @cursor.update
  2301.     @cursor.x, @cursor.y = position
  2302.   end
  2303.   #--------------------------------------------------------------------------
  2304.   # • Retorna a variável '@cursor' que tem como valor a classe [Sprite].
  2305.   #--------------------------------------------------------------------------
  2306.   def cursor
  2307.     @cursor
  2308.   end
  2309.   #--------------------------------------------------------------------------
  2310.   # • x (Coordenada X do Mouse)
  2311.   #--------------------------------------------------------------------------
  2312.   def x
  2313.     @cursor.x
  2314.   end
  2315.   #--------------------------------------------------------------------------
  2316.   # • y (Coordenada Y do Mouse)
  2317.   #--------------------------------------------------------------------------
  2318.   def y
  2319.     @cursor.y
  2320.   end
  2321.   #--------------------------------------------------------------------------
  2322.   # • position (Posição do Mouse!)
  2323.   #--------------------------------------------------------------------------
  2324.   def position
  2325.     x, y = get_client_position
  2326.     return x, y
  2327.   end
  2328.   #--------------------------------------------------------------------------
  2329.   # • get_client_position (Posição original do Mouse!)
  2330.   #--------------------------------------------------------------------------
  2331.   def get_client_position
  2332.     pos = [0, 0].pack('ll')
  2333.     API::CursorPosition.call(pos)
  2334.     API::ScreenToClient.call(WINDOW, pos)
  2335.     return pos.unpack('ll')
  2336.   end
  2337.   #--------------------------------------------------------------------------
  2338.   # • find_window (Tamanho da window)
  2339.   #--------------------------------------------------------------------------
  2340.   def find_window
  2341.     game_name = '\0' * 256
  2342.     API::ReadIni.call('Game', 'Title', '', game_name, 255, '.\\Game.ini')
  2343.     game_name.delete!('\0') ensure game_name
  2344.     return API::FindWindow.call('RGSS Player', game_name)
  2345.   end
  2346.   #--------------------------------------------------------------------------
  2347.   # • Verificação se o mouse está na área de um determinado objeto.
  2348.   #--------------------------------------------------------------------------
  2349.   def in_area?(object_sprite)
  2350.     return unless object_sprite.is_a?(Sprite) or object_sprite.is_a?(Window)
  2351.     return @cursor.x.between?(object_sprite.x, object_sprite.x + object_sprite.width) &&
  2352.       @cursor.y.between?(object_sprite.y, object_sprite.y + object_sprite.height)
  2353.   end
  2354.   #----------------------------------------------------------------------------
  2355.   # • Verificar se o mouse está em determinada área
  2356.   #----------------------------------------------------------------------------
  2357.   def area?(x, y, width, height)
  2358.     return @cursor.x.between?(x, x + width) &&
  2359.       @cursor.y.between?(y, y + height)
  2360.   end
  2361.   #----------------------------------------------------------------------------
  2362.   # • Mudar posição do cursor.
  2363.   #----------------------------------------------------------------------------
  2364.   def set_mouse(pos)
  2365.     SetCursorPos.call(pos.x, pos.y)
  2366.     update
  2367.     @cursor.x = @pos.x
  2368.     @cursor.y = @pos.y
  2369.   end
  2370.   #----------------------------------------------------------------------------
  2371.   # • [Numeric] : Retorna ao valor específico da coordenada X em relação ao Mapa.
  2372.   # Faz com que o valor da posição X do Mouse, seja convertida na coordenada X
  2373.   # do Mapa, em relação à GRID(tiles).
  2374.   #----------------------------------------------------------------------------
  2375.   def mapX
  2376.     return Integer(self.x).round / 32
  2377.   end
  2378.   #----------------------------------------------------------------------------
  2379.   # • [Numeric] : Retorna ao valor específico da coordenada Y em relação ao Mapa.
  2380.   # Faz com que o valor da posição Y do Mouse, seja convertida na coordenada Y
  2381.   # do Mapa, em relação à GRID(tiles).
  2382.   #----------------------------------------------------------------------------
  2383.   def mapY
  2384.     return Integer(self.x).round / 32
  2385.   end
  2386.   #----------------------------------------------------------------------------
  2387.   # • Verifica se clicou com o botão esquerdo do Mouse.
  2388.   #----------------------------------------------------------------------------
  2389.   def left?
  2390.     return Key.trigger?(0x01)
  2391.   end
  2392.   #----------------------------------------------------------------------------
  2393.   # • Verifica se clicou com o botão direito do Mouse.
  2394.   #----------------------------------------------------------------------------
  2395.   def right?
  2396.     return Key.trigger?(0x02)
  2397.   end
  2398.   WINDOW = find_window
  2399. end
  2400. #==============================================================================
  2401. # • Sprite_Mouse
  2402. #==============================================================================
  2403. Dax.register(:sprite_mouse)
  2404. class Sprite_Mouse < Sprite
  2405.   #----------------------------------------------------------------------------
  2406.   # • Variáveis públicas da instância.
  2407.   #----------------------------------------------------------------------------
  2408.   attr_accessor :set_graphic # definir o gráfico.
  2409.   #----------------------------------------------------------------------------
  2410.   # • Inicialização dos objetos.
  2411.   #----------------------------------------------------------------------------
  2412.   def initialize(graphic, x, y, z)
  2413.     super(nil)
  2414.     @set_graphic = graphic
  2415.     if @set_graphic.is_a?(Fixnum)
  2416.       self.bitmap = Bitmap.new(24, 24)
  2417.       self.bitmap.draw_icon(@set_graphic, 0, 0)
  2418.     elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  2419.       self.bitmap = Bitmap.new(1, 1)
  2420.     elsif @set_graphic.is_a?(String)
  2421.       self.bitmap = Cache.system(@set_graphic)
  2422.     end
  2423.     self.x, self.y, self.z = x, y, z
  2424.     @older = @set_graphic
  2425.   end
  2426.   #----------------------------------------------------------------------------
  2427.   # • Renovação dos objetos.
  2428.   #----------------------------------------------------------------------------
  2429.   def dispose
  2430.     self.bitmap.dispose
  2431.     super
  2432.   end
  2433.   #----------------------------------------------------------------------------
  2434.   # • Atualização dos objetos.
  2435.   #----------------------------------------------------------------------------
  2436.   def update
  2437.     super
  2438.     unless @older == @set_graphic
  2439.       if @set_graphic.is_a?(Fixnum)
  2440.         self.bitmap = Bitmap.new(24, 24)
  2441.         self.bitmap.draw_icon(@set_graphic, 0, 0)
  2442.       elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  2443.         self.bitmap = Bitmap.new(1, 1)
  2444.       elsif @set_graphic.is_a?(String)
  2445.         self.bitmap = Cache.system(@set_graphic)
  2446.       end
  2447.       @older = @set_graphic
  2448.     end
  2449.   end
  2450. end
  2451. #==============================================================================
  2452. # • Object
  2453. #==============================================================================
  2454. Dax.register(:object)
  2455. class Object
  2456.   #----------------------------------------------------------------------------
  2457.   # • O que irá ocorrer caso o mouse esteja sobre uma sprite.
  2458.   # Tem que ser um objeto Sprite.
  2459.   #----------------------------------------------------------------------------
  2460.   def if_mouse_over(&block)
  2461.     return if Mouse.cursor.nil?
  2462.     return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2463.     over ||= false
  2464.     if Mouse.in_area?(self)
  2465.       block.call
  2466.       over = true
  2467.     else
  2468.       over = false
  2469.     end
  2470.     yield over
  2471.   end
  2472.   #----------------------------------------------------------------------------
  2473.   # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao clicar.
  2474.   # Tem que ser um objeto Sprite.
  2475.   #  * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2476.   # EXPLICAÇÕES NO FINAL DO SCRIPT.
  2477.   #----------------------------------------------------------------------------
  2478.   def if_mouse_click(button=:left, &block)
  2479.     return if Mouse.cursor.nil?
  2480.     return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2481.     button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2482.     block.call if Mouse.in_area?(self)  and trigger?(button)
  2483.   end
  2484.   #----------------------------------------------------------------------------
  2485.   # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao pressionar.
  2486.   # Tem que ser um objeto Sprite.
  2487.   #  * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2488.   #----------------------------------------------------------------------------
  2489.   def if_mouse_press(button=:left, &block)
  2490.     return if Mouse.cursor.nil?
  2491.     return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2492.     button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2493.     block.call if Mouse.in_area?(self)  and press?(button)
  2494.   end
  2495.   #----------------------------------------------------------------------------
  2496.   # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao ficar clicando.
  2497.   # Tem que ser um objeto Sprite.
  2498.   #  * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  2499.   #----------------------------------------------------------------------------
  2500.   def if_mouse_repeat(button=:left, &block)
  2501.     return if Mouse.cursor.nil?
  2502.     return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  2503.     button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  2504.     block.call if Mouse.in_area?(self)  and repeat?(button)
  2505.   end
  2506.   #----------------------------------------------------------------------------
  2507.   # • Trigger
  2508.   #  * key : Chave.
  2509.   # Você também pode usá-lo como condição para executar tal bloco;
  2510.   #----------------------------------------------------------------------------
  2511.   # trigger?(key) { bloco que irá executar }
  2512.   #----------------------------------------------------------------------------
  2513.   def trigger?(key, &block)
  2514.     if key == :C or key == :B
  2515.       ckey = Input.trigger?(key)
  2516.     else
  2517.       ckey = Key.trigger?(key)
  2518.     end
  2519.     return ckey unless block_given?
  2520.     block.call if ckey
  2521.   end
  2522.   #----------------------------------------------------------------------------
  2523.   # • Press
  2524.   #  * key : Chave.
  2525.   # Você também pode usá-lo como condição para executar tal bloco;
  2526.   #----------------------------------------------------------------------------
  2527.   # press?(key) { bloco que irá executar. }
  2528.   #----------------------------------------------------------------------------
  2529.   def press?(key, &block)
  2530.     if key == :C or key == :B
  2531.       ckey = Input.press?(key)
  2532.     else
  2533.       ckey = Key.press?(key)
  2534.     end
  2535.     return ckey unless block_given?
  2536.     block.call if ckey
  2537.   end
  2538.   #----------------------------------------------------------------------------
  2539.   # • Repeat
  2540.   #  * key : Chave.
  2541.   # Você também pode usá-lo como condição para executar tal bloco;
  2542.   #----------------------------------------------------------------------------
  2543.   # repeat?(key) { bloco que irá executar. }
  2544.   #----------------------------------------------------------------------------
  2545.   def repeat?(key)
  2546.     if key == :C or key == :B
  2547.       ckey = Input.repeat?(key)
  2548.     else
  2549.       ckey = Key.repeat?(key)
  2550.     end
  2551.     return ckey unless block_given?
  2552.     block.call if ckey
  2553.   end
  2554.   #----------------------------------------------------------------------------
  2555.   # • Retorna em forma de número os valores true ou false. E caso seja
  2556.   # 0 ou 1.. retorna a true ou false.
  2557.   # Se for true, retorna a 1.
  2558.   # Se for false, retorna a 0.
  2559.   # Se for 1, retorna a true.
  2560.   # Se for 0, retorna a false.
  2561.   #----------------------------------------------------------------------------
  2562.   def boolean
  2563.     return self.is_a?(Integer) ? self == 0 ? false : 1  : self ? 1 : 0
  2564.   end
  2565.   #----------------------------------------------------------------------------
  2566.   # • Converte para a classe Position.
  2567.   #----------------------------------------------------------------------------
  2568.   def position
  2569.     return Position.new(self, self) if self.is_a?(Numeric)
  2570.     return Position.new(self.x, self.y) if self.is_a?(Sprite) or self.is_a?(Window_Base)
  2571.     return Position.new(self[0], self[1]) if self.is_a?(Array)
  2572.     return Position.new(0, 0)
  2573.   end
  2574.   #----------------------------------------------------------------------------
  2575.   # • Transforma em cor.
  2576.   #  Se for uma Array. Exemplo: [128, 174, 111].color =># Color.new(128, 174, 111)
  2577.   #  Se for uma String. Exemplo: "ffffff".color =># Color.new(255,255,255)
  2578.   #----------------------------------------------------------------------------
  2579.   def color
  2580.     return Color.new(*self) if self.is_a?(Array)
  2581.     return Color.new.hex(self) if self.is_a?(String)
  2582.   end
  2583.   #----------------------------------------------------------------------------
  2584.   # • Retorna verdadeiro caso pressione qualquer seta. Retorno padrão é falso.
  2585.   #----------------------------------------------------------------------------
  2586.   def keyArrows
  2587.     [:RIGHT, :LEFT, :UP, :DOWN].each { |i| trigger?(i) {return true} }
  2588.     return false
  2589.   end
  2590. end
  2591. #==============================================================================
  2592. # • Entries
  2593. #==============================================================================
  2594. Dax.register(:entries)
  2595. class Entries
  2596.   #----------------------------------------------------------------------------
  2597.   # • [Array] : Irá retornar a todos os nomes dos arquivos da pasta, dentro de
  2598.   # uma Array em formato de String.
  2599.   #----------------------------------------------------------------------------
  2600.   attr_accessor :file
  2601.   #----------------------------------------------------------------------------
  2602.   # • [Integer] : Retorna a quantidade total de arquivos que têm na pasta.
  2603.   #----------------------------------------------------------------------------
  2604.   attr_reader   :size
  2605.   #----------------------------------------------------------------------------
  2606.   # • Inicialização dos objetos.
  2607.   #     directory : Nome da pasta. Não ponha '/' no final do nome. Ex: 'Data/'
  2608.   #     typefile : Nome da extensão do arquivo. Não ponha '.' no começo. Ex: '.txt'
  2609.   #----------------------------------------------------------------------------
  2610.   def initialize(directory, typefile)
  2611.     return unless FileTest.directory?(directory)
  2612.     @file = Dir.glob(directory + "/*.{" + typefile + "}")
  2613.     @file.each_index { |i| @size = i.to_i }
  2614.     @name = split @file[0]
  2615.   end
  2616.   #----------------------------------------------------------------------------
  2617.   # • [String] : Separar o nome do arquivo do nome da pasta.
  2618.   #----------------------------------------------------------------------------
  2619.   def split(file)
  2620.     file.to_s.split('/').last
  2621.   end
  2622.   #----------------------------------------------------------------------------
  2623.   # • [String] : Obtêm o nome do arquivo correspondente ao id configurado,
  2624.   # separado do nome da pasta.
  2625.   #----------------------------------------------------------------------------
  2626.   def name(id)
  2627.     return if @file.nil?
  2628.     return split(@file[id])
  2629.   end
  2630. end
  2631. #==============================================================================
  2632. # • DRGSS | Comandos do RGSS...
  2633. #==============================================================================
  2634. Dax.register(:drgss)
  2635. module DRGSS
  2636.   extend self
  2637.   #----------------------------------------------------------------------------
  2638.   # • Extrair scripts do Database para um arquivo de extensão de texto.
  2639.   # options : Caso você deixe assim: {folder: "NM"}
  2640.   #  NM => Nome da pasta na qual os arquivos irão.
  2641.   #----------------------------------------------------------------------------
  2642.   def extract_scripts(type=".txt",options={})
  2643.     except = options[:except] || []
  2644.     folder = options[:folder] || ""
  2645.     id = 0 #
  2646.     $RGSS_SCRIPTS.each do |script|
  2647.       name = script[1]
  2648.       data = script[3]
  2649.       next if except.include? name or name.empty? or data.empty?
  2650.       filename = sprintf("%03d", id) + "_" + name
  2651.       p "Writing: #{filename}"
  2652.       File.open(folder+filename+"#{type}", "wb") do |file|
  2653.         file.write data
  2654.       end
  2655.       id += 1
  2656.     end
  2657.   end
  2658.   #----------------------------------------------------------------------------
  2659.   # • Guarda todos os scripts do Database num arquivo;
  2660.   #----------------------------------------------------------------------------
  2661.   def keep_scripts_in_file(filename="RGSS.rvdata2")
  2662.     unless FileTest.exist?(filename)
  2663.       self.extract_scripts(".txt")
  2664.       file = File.open(filename, "wb")
  2665.       Dir.glob("./*.{txt}").each_with_index { |v,i|
  2666.         next unless v.match(/(\d+){3}_(\w*)/)
  2667.         file.write(IO.readlines(v).to_s)
  2668.         File.delete(v)
  2669.       }
  2670.       file.close
  2671.     end
  2672.   end
  2673. end
  2674. #==============================================================================
  2675. # • Backup Complete
  2676. #==============================================================================
  2677. Dax.register(:backup)
  2678. module Backup
  2679.   extend self
  2680.   #----------------------------------------------------------------------------
  2681.   # • Criar as pastas.
  2682.   #----------------------------------------------------------------------------
  2683.   def make_past
  2684.     Dir.mkdir("Backup") unless File.directory?("Backup")
  2685.     ["Data", "System", "Movies", "Graphics", "Audio", "Audio/BGM", "Audio/BGS", "Audio/ME", "Audio/SE"].each { |i|
  2686.       Dir.mkdir("Backup/#{i}") unless File.directory?("Backup/#{i}")
  2687.     }
  2688.   end
  2689.   #----------------------------------------------------------------------------
  2690.   # • Copiar a pasta system.
  2691.   #----------------------------------------------------------------------------
  2692.   def system
  2693.     list = Dir.glob('System/*')
  2694.     list.size.times { |i|API::CopyFile.call(list[i], "Backup/" + list[i], true.boolean)}
  2695.   end
  2696.   #----------------------------------------------------------------------------
  2697.   # • Copiar a pasta movie.
  2698.   #----------------------------------------------------------------------------
  2699.   def movies
  2700.     movies = Dir.glob("Movies/*")
  2701.     movies.size.times { |i| API::CopyFile.call(movies[i], "Backup/" + movies[i], true.boolean)}
  2702.   end
  2703.   #----------------------------------------------------------------------------
  2704.   # • Copiar a pasta audio
  2705.   #----------------------------------------------------------------------------
  2706.   def audio
  2707.     bgm = Dir.glob('Audio/BGM/*')
  2708.     bgs = Dir.glob('Audio/BGS/*')
  2709.     me = Dir.glob('Audio/ME/*')
  2710.     se = Dir.glob('Audio/SE/*')
  2711.     bgm.size.times { |i| API::CopyFile.call(bgm[i], "Backup/" + bgm[i], true.boolean)}
  2712.     bgs.size.times { |i| API::CopyFile.call(bgs[i], "Backup/" + bgs[i], true.boolean) }
  2713.     me.size.times { |i| API::CopyFile.call(me[i], "Backup/" + me[i], true.boolean) }
  2714.     se.size.times { |i| API::CopyFile.call(se[i], "Backup/" + se[i], true.boolean) }
  2715.   end
  2716.   #----------------------------------------------------------------------------
  2717.   # • Copiar a pasta Data.
  2718.   #----------------------------------------------------------------------------
  2719.   def data
  2720.     data = Dir.glob('Data/*')
  2721.     data.size.times { |i| API::CopyFile.call(data[i], "Backup/" + data[i], true.boolean) }
  2722.   end
  2723.   #----------------------------------------------------------------------------
  2724.   # • Copiar a pasta Graphic.
  2725.   #----------------------------------------------------------------------------
  2726.   def graphics
  2727.     ["Animations", "Battlebacks1", "Battlebacks2", "Battlers", "Characters",
  2728.      "Faces", "Parallaxes", "Pictures", "System", "Titles1", "Titles2",
  2729.      "Tilesets"].each { |dirs|
  2730.        Dir.mkdir("Backup/Graphics/#{dirs}") unless File.directory?("Backup/Graphics/#{dirs}")
  2731.        d = Dir.glob("Graphics/#{dirs}/*")
  2732.        d.size.times { |v| API::CopyFile.call(d[v], "Backup/" + d[v], true.boolean) }
  2733.      }
  2734.   end
  2735.   #----------------------------------------------------------------------------
  2736.   # • Executar
  2737.   #----------------------------------------------------------------------------
  2738.   def run(audios=false, graphic=false)
  2739.     if $TEST
  2740.       make_past
  2741.       movies
  2742.       data
  2743.       system
  2744.       audio if audios
  2745.       graphics if graphic
  2746.     end
  2747.   end
  2748. end
  2749. #==============================================================================
  2750. # * SceneManager
  2751. #==============================================================================
  2752. Dax.register :scenemanager
  2753. if defined?("SceneManager")
  2754.   class  << SceneManager
  2755.     #--------------------------------------------------------------------------
  2756.     # • **** Método ainda não explicado ****
  2757.     #--------------------------------------------------------------------------
  2758.     def symbol(scene_symbol)
  2759.       eval("self.call(#{scene_symbol.to_s})")
  2760.     end
  2761.   end
  2762. end
  2763. #==============================================================================
  2764. # • Sprite_Text
  2765. #==============================================================================
  2766. Dax.register(:sprite_text)
  2767. class Sprite_Text < Sprite
  2768.   #----------------------------------------------------------------------------
  2769.   # • Variáveis públicas da instância.
  2770.   #----------------------------------------------------------------------------
  2771.   attr_accessor :text # Mudar de texto...
  2772.   attr_accessor :align
  2773.   #----------------------------------------------------------------------------
  2774.   # • Inicialização dos objetos.
  2775.   #----------------------------------------------------------------------------
  2776.   def initialize(x, y, width, height, text, align=0)
  2777.     super([width, height])
  2778.     self.x, self.y = x, y
  2779.     @text = text
  2780.     @align = align
  2781.     self.bitmap.draw_text_rect(@text, align)
  2782.   end
  2783.   #----------------------------------------------------------------------------
  2784.   # • Renovação dos objetos.
  2785.   #----------------------------------------------------------------------------
  2786.   def dispose
  2787.     self.bitmap.dispose
  2788.     super
  2789.   end
  2790.   #----------------------------------------------------------------------------
  2791.   # • Atualização dos objetos.
  2792.   #----------------------------------------------------------------------------
  2793.   def update
  2794.     self.bitmap.clear
  2795.     super
  2796.     self.bitmap.draw_text_rect(@text, @align)
  2797.   end
  2798.   def name=(value=nil)
  2799.     self.bitmap.font.name = name || Font.default_name.to_s
  2800.   end
  2801.   #----------------------------------------------------------------------------
  2802.   # • Negrito na fonte?
  2803.   #----------------------------------------------------------------------------
  2804.   def bold=(value=nil)
  2805.     self.bitmap.font.bold = value || true
  2806.   end
  2807.   #----------------------------------------------------------------------------
  2808.   # • Itálico na fonte?
  2809.   #----------------------------------------------------------------------------
  2810.   def italic=(value=nil)
  2811.     self.bitmap.font.italic = value || true
  2812.   end
  2813.   #----------------------------------------------------------------------------
  2814.   # • Sombra na fonte?
  2815.   #----------------------------------------------------------------------------
  2816.   def shadow=(value=nil)
  2817.     self.bitmap.font.shadow = value || true
  2818.   end
  2819.   #----------------------------------------------------------------------------
  2820.   # • Borda na fonte?
  2821.   #----------------------------------------------------------------------------
  2822.   def outline=(value=nil)
  2823.     self.bitmap.font.outline = value || true
  2824.   end
  2825.   #----------------------------------------------------------------------------
  2826.   # • Mudar a cor da fonte:
  2827.   #----------------------------------------------------------------------------
  2828.   def color=(color=nil)
  2829.     self.bitmap.font.color = color || Color.new.default
  2830.   end
  2831.   #----------------------------------------------------------------------------
  2832.   # • Mudar a cor da borda da fonte.
  2833.   #----------------------------------------------------------------------------
  2834.   def out_color=(out_color=nil)
  2835.     self.bitmap.font.out_color = out_color || Color.new.hex("000000")
  2836.   end
  2837. end
  2838. #==============================================================================
  2839. # • Sprite_Icon
  2840. #==============================================================================
  2841. Dax.register(:sprite_icon)
  2842. class Sprite_Icon < Sprite
  2843.   #----------------------------------------------------------------------------
  2844.   # • Variáveis públicas da instância.
  2845.   #----------------------------------------------------------------------------
  2846.   attr_accessor :icon_index # Mudar de ícone.
  2847.   attr_accessor :enabled # Tornar opaco ou não.
  2848.   attr_accessor :filename # Nome do arquivo.
  2849.   #----------------------------------------------------------------------------
  2850.   # • Inicialização dos objetos.
  2851.   #----------------------------------------------------------------------------
  2852.   def initialize(icon_index, x, y, enabled=true)
  2853.     super([24, 24])
  2854.     self.x, self.y = x, y
  2855.     @icon_index = icon_index.to_i
  2856.     @enabled = enabled
  2857.     self.bitmap.draw_icon(@icon_index, 0, 0, @enabled)
  2858.   end
  2859.   #----------------------------------------------------------------------------
  2860.   # • Renovação dos objetos.
  2861.   #----------------------------------------------------------------------------
  2862.   def dispose
  2863.     self.bitmap.dispose
  2864.     super
  2865.   end
  2866.   #----------------------------------------------------------------------------
  2867.   # • Atualização dos objetos.
  2868.   #----------------------------------------------------------------------------
  2869.   def update
  2870.     self.bitmap.clear
  2871.     super
  2872.     self.bitmap.draw_icon(@icon_index, 0, 0, @enabled, @filename)
  2873.   end
  2874. end
  2875. #==============================================================================
  2876. # • Opacity
  2877. #==============================================================================
  2878. Dax.register(:opacity)
  2879. module Opacity
  2880.   extend self
  2881.   @key ||= {}
  2882.   #----------------------------------------------------------------------------
  2883.   # • Efeito de opacidade que vai aumentando e diminuindo.
  2884.   # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  2885.   # speed : Velocidade na qual o efeito irá acontencer.
  2886.   # max : Valor máximo na qual irá ser atingido.
  2887.   # min : Valor minímo na qual irá ser atingido.
  2888.   #----------------------------------------------------------------------------
  2889.   def sprite_opacity(sprite, speed, max, min, hash=nil)
  2890.     @key[hash.nil? ? hash.__id__ : hash] || false
  2891.     unless @key[hash]
  2892.       sprite.opacity += speed unless sprite.opacity >= max
  2893.       @key[hash] = sprite.opacity >= max
  2894.     else
  2895.       sprite.opacity -= speed unless sprite.opacity <= min
  2896.       @key[hash] = false if sprite.opacity <= min
  2897.     end
  2898.   end
  2899.   #----------------------------------------------------------------------------
  2900.   # • Efeito de opacidade por fora.
  2901.   # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  2902.   # speed : Velocidade na qual o efeito irá acontencer.
  2903.   # max : Valor máximo na qual irá ser atingido.
  2904.   #----------------------------------------------------------------------------
  2905.   def sprite_opacity_out(sprite, speed, max)
  2906.     sprite.opacity += speed unless sprite.opacity >= max
  2907.   end
  2908.   #----------------------------------------------------------------------------
  2909.   # • Efeito de opacidade por dentro.
  2910.   # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  2911.   # speed : Velocidade na qual o efeito irá acontencer.
  2912.   #  min : Valor minímo na qual irá ser atingido.
  2913.   #----------------------------------------------------------------------------
  2914.   def sprite_opacity_in(sprite, speed, min)
  2915.     sprite.opacity -= speed unless sprite.opacity <= min
  2916.   end
  2917.   #----------------------------------------------------------------------------
  2918.   # • Limpar variável.
  2919.   #----------------------------------------------------------------------------
  2920.   def clear
  2921.     @key.clear
  2922.   end
  2923. end
  2924. #==============================================================================
  2925. # • Read
  2926. #==============================================================================
  2927. Dax.register(:read, "Dax")
  2928. module Read
  2929.   extend self
  2930.   #----------------------------------------------------------------------------
  2931.   # • Verificar valor numérico após uma palavra em um arquivo.
  2932.   #----------------------------------------------------------------------------
  2933.   def numeric(file, tag)
  2934.     IO.readlines(file).each do |line|
  2935.       return $1.to_i if line.match(/#{tag} (\d+)/)
  2936.     end
  2937.   end
  2938.   #----------------------------------------------------------------------------
  2939.   # • Verificar valor de uma palavra(string única) após uma palavra em um arquivo
  2940.   #----------------------------------------------------------------------------
  2941.   def string(file, tag)
  2942.     IO.readlines(file).each do |line|
  2943.       return $1.to_s if line.match(/#{tag} (\w+)/)
  2944.     end
  2945.   end
  2946.   #----------------------------------------------------------------------------
  2947.   # • Verificar um conteúdo após uma palavra de um arquivo.
  2948.   #----------------------------------------------------------------------------
  2949.   def content(file, tag)
  2950.     IO.readlines(file).each do |line|
  2951.       return $1 if line.match(/#{tag} ([^>]*)/)
  2952.     end
  2953.   end
  2954.   #----------------------------------------------------------------------------
  2955.   # • Multiplo número..
  2956.   #----------------------------------------------------------------------------
  2957.   def multiple_numeric(file, tag)
  2958.     IO.readlines(file).each do |line|
  2959.       return [$1.to_i, $2.to_i] if line.match(/#{tag} (\d+), (\d+)/)
  2960.     end
  2961.   end
  2962.   #----------------------------------------------------------------------------
  2963.   # • Multiplo string..
  2964.   #----------------------------------------------------------------------------
  2965.   def multiple_string(file, tag)
  2966.     IO.readlines(file).each do |line|
  2967.       return [$1.to_s, $2.to_s] if line.match(/#{tag} (\w+), (\w+)/)
  2968.     end
  2969.   end
  2970.   #----------------------------------------------------------------------------
  2971.   # • Triplo número.
  2972.   #----------------------------------------------------------------------------
  2973.   def triple_numeric(file, tag)
  2974.     IO.readlines(file).each do |line|
  2975.       return [$1.to_i, $2.to_i, $3.to_i] if line.match(/#{tag} (\d+), (\d+), (\d+)/)
  2976.     end
  2977.   end
  2978.   #----------------------------------------------------------------------------
  2979.   # • Triplo string.
  2980.   #----------------------------------------------------------------------------
  2981.   def triple_string(file, tag)
  2982.     IO.readlines(file).each do |line|
  2983.       return [$1.to_s, $2.to_s, $3.to_s] if line.match(/#{tag} (\w+), (\w+), (\w+)/)
  2984.     end
  2985.   end
  2986.   #----------------------------------------------------------------------------
  2987.   # • Se é verdairo ou falo.
  2988.   #----------------------------------------------------------------------------
  2989.   def of(file, tag)
  2990.     IO.readlines(file).each do |line|
  2991.       return $1.to_s == "true" ? true : false if line.match(/#{tag} ([^>]*)/)
  2992.     end
  2993.   end
  2994. end
  2995. #==============================================================================
  2996. # • Background
  2997. #==============================================================================
  2998. Dax.register :background
  2999. module Background
  3000.   extend self
  3001.   @background ||= {}
  3002.   #----------------------------------------------------------------------------
  3003.   # • Plano de fundo padrão...
  3004.   #----------------------------------------------------------------------------
  3005.   def default(alpha=128, key=nil)
  3006.     @background[key.__id__] = Sprite.new
  3007.     @background[key.__id__].bitmap = SceneManager.background_bitmap
  3008.     @background[key.__id__].color.set(16, 16, 16, alpha)
  3009.   end
  3010.   #----------------------------------------------------------------------------
  3011.   # • Plano de fundo padrão renovado.
  3012.   #----------------------------------------------------------------------------
  3013.   def default_dispose
  3014.     return if @background.nil?
  3015.     @background.each_value(&:dispose)
  3016.   end
  3017. end
  3018. #==============================================================================
  3019. # * Window_Base
  3020. #==============================================================================
  3021. Dax.register(:window_base)
  3022. Dax.if_defined?("Window_Base") {
  3023. class Window_Base < Window
  3024.   #----------------------------------------------------------------------------
  3025.   # • Slide pela direita.
  3026.   #   * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  3027.   #----------------------------------------------------------------------------
  3028.   def slide_right(speed, point)
  3029.     self.x += speed unless self.x >= point
  3030.   end
  3031.   #----------------------------------------------------------------------------
  3032.   # • Slide pela esquerda.
  3033.   #   * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  3034.   #----------------------------------------------------------------------------
  3035.   def slide_left(speed, point)
  3036.     self.x -= speed unless self.x <= point
  3037.   end
  3038.   #----------------------------------------------------------------------------
  3039.   # • Slide por cima.
  3040.   #   * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  3041.   #----------------------------------------------------------------------------
  3042.   def slide_up(speed, point)
  3043.     self.y -= speed unless self.y <= point
  3044.   end
  3045.   #----------------------------------------------------------------------------
  3046.   # • Slide por baixo.
  3047.   #   * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  3048.   #----------------------------------------------------------------------------
  3049.   def slide_down(speed, point)
  3050.     self.y += speed unless self.y >= point
  3051.   end
  3052.   #----------------------------------------------------------------------------
  3053.   # • Define aqui uma posição fixa para um objeto.
  3054.   #   command : Retorna a uma base padrão.
  3055.   #----------------------------------------------------------------------------
  3056.   def position(command=0)
  3057.     return if command.nil?
  3058.     case command
  3059.     # Imagem ficará no canto esquerdo superior. Posição X
  3060.     when 0 then self.x = 0
  3061.     # A posição X ficará no centro da tela.
  3062.     when 1 then self.x = DMath.get_x_center_screen(self.width)
  3063.     # A posição X ficará no canto direito superior.
  3064.     when 2 then self.x = Graphics.width - self.width
  3065.     # A posição Y ficará no canto esquerdo inferior.
  3066.     when 3 then self.y = 0
  3067.     # Posicionar o Y para ficar no centro.
  3068.     when 4 then self.y = DMath.get_y_center_screen(self.height)
  3069.     # Posicionar o Y para ficar no fundo da tela.
  3070.     when 5 then self.y = Graphics.height - self.height
  3071.     # Posicionar a imagem no centro da tela.
  3072.     when :center
  3073.       self.x = (Graphics.width - self.width) / 2
  3074.       self.y = Graphics.height / 2 - self.height / 2
  3075.     # Posicionar no centro esquerdo da tela.
  3076.     when :center_left
  3077.       self.x = 0
  3078.       self.y = (Graphics.height - self.height) / 2  
  3079.     # Posicionar no centro direito da tela.
  3080.     when :center_right
  3081.       self.x = Graphics.width - self.height
  3082.       self.y = (Graphics.height - self.height) / 2  
  3083.     end
  3084.   end
  3085. end
  3086. }
  3087. #==============================================================================
  3088. # • Sound Base
  3089. #==============================================================================
  3090. Dax.register(:sound_base)
  3091. module Sound_Base
  3092.   #----------------------------------------------------------------------------
  3093.   # • Função do módulo.
  3094.   #----------------------------------------------------------------------------
  3095.   module_function
  3096.   #----------------------------------------------------------------------------
  3097.   # • Executar um som.
  3098.   #----------------------------------------------------------------------------
  3099.   def play(name, volume, pitch, type = :se)
  3100.     case type
  3101.     when :se  ; RPG::SE.new(name, volume, pitch).play rescue valid?(name)
  3102.     when :me  ; RPG::ME.new(name, volume, pitch).play rescue valid?(name)
  3103.     when :bgm ; RPG::BGM.new(name, volume, pitch).play rescue valid?(name)
  3104.     when :bgs ; RPG::BGS.new(name, volume, pitch).play rescue valid?(name)
  3105.     end
  3106.   end
  3107.   #----------------------------------------------------------------------------
  3108.   # • Validar som.
  3109.   #----------------------------------------------------------------------------
  3110.   def valid?(name)
  3111.     raise("Arquivo de som não encontrado: #{name}")
  3112.     exit
  3113.   end
  3114. end
  3115. #==============================================================================
  3116. # • Position.
  3117. #==============================================================================
  3118. Dax.register :position
  3119. class Position
  3120.   #----------------------------------------------------------------------------
  3121.   # • Variáveis públicas da instância.
  3122.   #----------------------------------------------------------------------------
  3123.   attr_accessor :x  # Variável que retorna ao valor que indica a posição X.
  3124.   attr_accessor :y  # Variável que retorna ao valor que indica a posição Y.
  3125.   #----------------------------------------------------------------------------
  3126.   # • Inicialização dos objetos.
  3127.   #----------------------------------------------------------------------------
  3128.   def initialize(x, y)
  3129.     @x = x || 0
  3130.     @y = y || 0
  3131.   end
  3132.   #----------------------------------------------------------------------------
  3133.   # • Somar com outra posição.
  3134.   #----------------------------------------------------------------------------
  3135.   def +(position)
  3136.     position = position.position unless position.is_a?(Position)
  3137.     Position.new(self.x + position.x, self.y + position.y)
  3138.   end
  3139.   #----------------------------------------------------------------------------
  3140.   # • Subtrair com outra posição.
  3141.   #----------------------------------------------------------------------------
  3142.   def -(position)
  3143.     position = position.position unless position.is_a?(Position)
  3144.     Position.new(self.x - position.x, self.y - position.y)
  3145.   end
  3146.   #----------------------------------------------------------------------------
  3147.   # • Multiplicar com outra posição.
  3148.   #----------------------------------------------------------------------------
  3149.   def *(position)
  3150.     position = position.position unless position.is_a?(Position)
  3151.     Position.new(self.x * position.x, self.y * position.y)
  3152.   end
  3153.   #----------------------------------------------------------------------------
  3154.   # • Dividir com outra posição.
  3155.   #----------------------------------------------------------------------------
  3156.   def /(position)
  3157.     position = position.position unless position.is_a?(Position)
  3158.     return if (self.x or position.x or self.y or position.y) <= 0
  3159.     Position.new(self.x / position.x, self.y / position.y)
  3160.   end
  3161.   #----------------------------------------------------------------------------
  3162.   # • Comparar com outra posição.
  3163.   #----------------------------------------------------------------------------
  3164.   def ==(position)
  3165.     position = position.position unless position.is_a?(Position)
  3166.     return self.x == position.x && self.y == position.y
  3167.   end
  3168.   #----------------------------------------------------------------------------
  3169.   # • Converter em string.
  3170.   #----------------------------------------------------------------------------
  3171.   def to_s
  3172.     return "position x: #{self.x}\nposition y: #{self.y}"
  3173.   end
  3174. end
  3175. #==============================================================================
  3176. # • Animation
  3177. #==============================================================================
  3178. Dax.register :animation
  3179. class Animation
  3180.   attr_reader :size, :frame_size, :index, :max_width, :max_height
  3181.   #----------------------------------------------------------------------------
  3182.   # • Inicialização.
  3183.   #----------------------------------------------------------------------------
  3184.   def initialize(size, frame_size, wait=1)
  3185.     @size = size
  3186.     @frame_size = frame_size
  3187.     @index = 0
  3188.     @max_width = @size[0] / @frame_size[0]
  3189.     @max_height = @size[1] / @frame_size[1]
  3190.     @wait = wait
  3191.     @time = 0
  3192.   end
  3193.   #----------------------------------------------------------------------------
  3194.   # • Animação na horizontal.
  3195.   #----------------------------------------------------------------------------
  3196.   def horz
  3197.     @time += 1 unless @time >= @wait
  3198.     if @time >= @wait
  3199.       @index = @index.up(@index, @max_width)
  3200.       @time = 0
  3201.     end
  3202.   end
  3203.   #----------------------------------------------------------------------------
  3204.   # • Animação na vertical.
  3205.   #----------------------------------------------------------------------------
  3206.   def vert
  3207.     @time += 1 unless @time >= @wait
  3208.     if @time >= @wait
  3209.       @index = @index.up(@index, @max_height)
  3210.       @time = 0
  3211.     end
  3212.   end
  3213. end
  3214. #==============================================================================
  3215. # • Sprite_Anime_Horz
  3216. #==============================================================================
  3217. Dax.register :sprite_anime_horz
  3218. class Sprite_Anime_Horz < Sprite
  3219.   #----------------------------------------------------------------------------
  3220.   # • Inicialização dos objetos
  3221.   #    filename : Nome do arquivo.
  3222.   #    frame_size : Tamanho de cada frame.
  3223.   #    wait : Tempo de espera para mudar de um frame para outro.
  3224.   #----------------------------------------------------------------------------
  3225.   def initialize(filename, frame_size, wait=1)
  3226.     @bitmap = Bitmap.new(filename)
  3227.     super(frame_size)
  3228.     @animation = Animation.new([@bitmap.width, @bitmap.height],
  3229.     frame_size, wait)
  3230.   end
  3231.   #----------------------------------------------------------------------------
  3232.   # • Renovação dos objetos.
  3233.   #----------------------------------------------------------------------------
  3234.   def dispose
  3235.     self.bitmap.dispose
  3236.     super
  3237.   end
  3238.   #----------------------------------------------------------------------------
  3239.   # • Atualização dos objetos.
  3240.   #----------------------------------------------------------------------------
  3241.   def update
  3242.     self.bitmap.clear
  3243.     super
  3244.     @animation.horz
  3245.     rect = Rect.new(@animation.index % @animation.max_width * @animation.frame_size[0],
  3246.     0, *@animation.frame_size)
  3247.     self.bitmap.blt(0, 0, @bitmap, rect)
  3248.   end
  3249. end
  3250. #==============================================================================
  3251. # • Sprite_Anime_Vert
  3252. #==============================================================================
  3253. Dax.register :sprite_anime_vert
  3254. class Sprite_Anime_Vert < Sprite
  3255.   #----------------------------------------------------------------------------
  3256.   # • Inicialização dos objetos
  3257.   #    filename : Nome do arquivo.
  3258.   #    frame_size : Tamanho de cada frame.
  3259.   #    wait : Tempo de espera para mudar de um frame para outro.
  3260.   #----------------------------------------------------------------------------
  3261.   def initialize(filename, frame_size, wait=1)
  3262.     @bitmap = Bitmap.new(filename)
  3263.     super(frame_size)
  3264.     @animation = Animation.new([@bitmap.width, @bitmap.height],
  3265.     frame_size, wait)
  3266.   end
  3267.   #----------------------------------------------------------------------------
  3268.   # • Renovação dos objetos.
  3269.   #----------------------------------------------------------------------------
  3270.   def dispose
  3271.     self.bitmap.dispose
  3272.     super
  3273.   end
  3274.   #----------------------------------------------------------------------------
  3275.   # • Atualização dos objetos.
  3276.   #----------------------------------------------------------------------------
  3277.   def update
  3278.     self.bitmap.clear
  3279.     super
  3280.     @animation.vert
  3281.     rect = Rect.new(0,
  3282.     @animation.index % @animation.max_height * @animation.frame_size[1], *@animation.frame_size)
  3283.     self.bitmap.blt(0, 0, @bitmap, rect)
  3284.   end
  3285. end
  3286. #==============================================================================
  3287. # • Desativar scripts : Para fazer, basta por no nome do script da lista,
  3288. # [D].
  3289. # • Salvar script em arquivo de texto : Para fazer, basta por no nome do script da lista,
  3290. # [S].
  3291. #==============================================================================
  3292. Dax.register(:disable_script)
  3293. $RGSS_SCRIPTS.each_with_index { |data, index|
  3294.  if data.at(1).include?("[S]")
  3295.    File.open("#{rgss.at(1)}.txt", "wb") { |file|
  3296.       file.write(String($RGSS_SCRIPTS.at(index)[3]))
  3297.       file.close
  3298.     }
  3299.  end
  3300.  $RGSS_SCRIPTS.at(index)[2] = $RGSS_SCRIPTS.at(index)[3] = "" if data.at(1).include?("[D]")
  3301. }
  3302. #==============================================================================
  3303. # * DataManager
  3304. #==============================================================================
  3305. unless defined?(DataManager)
  3306.   Mouse.start
  3307.   Rpg.data_manager
  3308. else
  3309.   class << DataManager
  3310.     alias :new_init :init
  3311.     def init
  3312.       Mouse.start
  3313.       new_init
  3314.     end
  3315.   end
  3316. end
  3317. #==============================================================================
  3318. # * Input
  3319. #==============================================================================
  3320. class << Input
  3321.   alias :upft :update
  3322.   def update
  3323.     upft
  3324.     Key.update
  3325.   end
  3326. end
  3327. #==============================================================================
  3328. # • Graphics
  3329. #==============================================================================
  3330. class << Graphics
  3331.   alias :uptf :update
  3332.   def update
  3333.     uptf
  3334.     Mouse.update
  3335.   end
  3336. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement