Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #==============================================================================
- # * Dax Core
- #==============================================================================
- # Autor : Dax Aquatic X
- # Versão : Core i3.7
- # Site : www.dax-soft.weebly.com
- # Suporte : dax-soft@live.com
- #==============================================================================
- # Um Core com vários módulos e métodos que facilitará na hora de programar os
- # seus scripts, bom proveito.
- #==============================================================================
- # Conteúdo :
- #==============================================================================
- # i :
- # - API
- # - String
- # - Integer
- # - Float
- # - Color
- # - ColorBasic
- # - DMath
- # - Key
- # - Mouse
- # - Entries
- # - Rpg Module
- # - Read
- # - DRGSS
- # - Rect
- # - Sprite
- # - Bitmap : method (save) by Gab!
- # - Object
- # - Touch_Picture
- # - Simple_Touch_Picture
- # - Sprite_Text
- # - Text_Base
- # - Touch_Icon
- # - Simple_Touch_Icon
- # - Touch_Text
- # - Simple_Touch_Text
- # - Opacity
- # - DString
- # - Background
- # - Background
- # - Window_Base
- # - Map
- # - VS
- # - Sound Base
- # - Disable Script
- # - Regexp Symbols
- # - Enumerables
- # - Cache
- # - Sprite_Icon
- # - Module
- # - Window_CommandEx
- # - Crypt
- # - Vector
- # - Matrix
- # - Animation(BASE para estudos.)
- # - Sprite_Anime_Horz(BASE para estudos.)
- # - Sprite_Anime_Vert(BASE para estudos.)
- # - KeyStringSprite(BASE para estudos.)
- # - Clipboard
- # - Array
- # - MessageBox
- #==============================================================================
- # • Adicionado comentário padrão. Veja o modo que agora os comentários dos
- # métodos estão.
- #==============================================================================
- # • [Classe do Retorno] : Explicação.
- # * Exemplo.
- #==============================================================================
- # • TAGS : Para facilitar a localização dos códigos e explicações. Para acessar
- # o comando para localizar, basta apertar Ctrl+F.
- #==============================================================================
- # :api -> Ir até módulos das API;
- # :enumerables -> Ir até add-ons para Enumerables.
- # :string -> Ir até add-ons para a classe String.
- # :integer -> Ir até add-ons para a classe Integer.
- # :float -> Ir até add-ons para a classe Float.
- # :color -> Ir até add-ons para a classe Color.
- # :rect -> Ir até add-ons para a classe Rect.
- # :dmath -> Ir até o módulo DMath.
- # :colorbasic -> Ir até o módulo ColorBasic.
- # :key -> Ir até o módulo Key.
- # :sprite -> Ir até add-ons para a classe Sprite.
- # :bitmap -> Ir até add-ons para a classe Bitmap.
- # :mouse -> Ir até o módulo Mouse.
- # :object -> Ir até add-ons para a classe Object.
- # :entries -> Ir até a classe Entries.
- # :text_base -> Ir até a classe Text Base.
- # :drgss -> Ir até o módulo DRGSS.
- # :outline_fill_rect -> Ir até a classe OutlineFillRect
- # :backupsystem -> Ir até o método de backup. Para fazer backup só chamar o
- # método backup.
- # :dstring -> Ir até o módulo DString.
- # :scenemanager -> Ir até add-ons para o módulo SceneManager.
- # :sprite_text -> Ir até a classe Sprite_Text.
- # :opacity -> Ir até o módulo Opacity.
- # :rpg -> Ir até o módulo Rpg.
- # :shortcut -> Ir até o método Shortcut.
- # :read -> Ir até o módulo Read.
- # :background -> Ir até o módulo Background.
- # :window_base -> Ir até add-ons para a classe Window_Base.
- # :map -> Ir até o módulo Map.
- # :vs -> Ir até o módulo VS.
- # :sound_base -> Ir até o módulo Sound_Base.
- # :position -> Ir até a classe Positions.
- # :cache -> Ir até add-ons para o módulo Cache.
- # :sprite_icon -> Ir até a classe Sprite_Icon.
- # :wcEx -> Ir até a classe Window_CommandEx
- # :crypt -> Ir até o módulo Crypt.
- # :vector -> Ir até a classe Vector
- # :matrix -> Ir até a classe Matrix.
- # :animation -> Ir até o módulo de Animation.
- # :sprite_anime_horz -> Ir até a classe Sprite_Anime_Horz
- # :sprite_anime_vert -> Ir até a classe Sprite_Anime_Vert
- # :key_string_sprite -> Ir até a classe KeyStringSprite
- # :array -> Ir até os Add-ons da classe Array.
- #==============================================================================
- module Dax
- extend self
- #----------------------------------------------------------------------------
- # Ajuste aqui as configurações básicas da fonte padrão do jogo.
- #----------------------------------------------------------------------------
- Font.default_name = "Trebuchet MS" # Nome padrão da fonte do jogo.
- Font.default_size = 22 # Tamanho padrão da fonte do jogo.
- Font.default_bold = true # true - Para usar negrito | false - para não usar.
- Font.default_italic = false # true - Para usar italico | false - para não usar.
- Font.default_shadow = false # true - Para usar sombra na fonte | false - para não usar.
- Font.default_outline = false # true - Para usar borda da fonte | false - para não usar.
- Font.default_out_color = Color.new(0, 0, 0) # Cor da fonte padrão da borda da fonte.
- Font.default_color = Color.new(255, 255, 255) # Cor da fonte padrão.
- FontArray = ["name", "size", "bold", "italic", "shadow", "outline", "color"]
- #----------------------------------------------------------------------------
- # * Constantes e variáveis
- #----------------------------------------------------------------------------
- @register = {} # Armazena os scripts criados que foram registrados.
- @benchmark = "" # Armazena os testes conclusos de benchmark.
- # A imagem do ícone do Mouse tem que estar na pasta System. Basta você
- # por o nome da imagem dentro das áspas. Caso você queira usar um ícone
- # do Rpg Maker no lugar de uma imagem, basta você por o id do ícone no lugar
- # das áspas.
- Mouse_Name = ""
- #----------------------------------------------------------------------------
- # * Somente executará o bloco caso estiver registrado o script.
- #----------------------------------------------------------------------------
- # Exemplo:
- # Dax.required_script(:teste) { # Só irá executar caso estiver registrado.
- # methods...
- # }
- #----------------------------------------------------------------------------
- def required_script(symbol, &block)
- block.call if @register.has_key?(symbol) and block_given?
- end
- #----------------------------------------------------------------------------
- # * Método de registrar scripts :
- #----------------------------------------------------------------------------
- # ** Este método tem de ser definido alguns valores como :
- # symbol - nome do script, que é posto em símbolo : Ex - :arrow
- # name - nome do autor do script, que é posto em áspas
- # version - versão do script;
- # data - data do script;
- # Dax.register(symbol, name, version, data)
- # ** Você pode usá-lo para somente registrar o nome do script.
- # Dax.register(symbol)
- #----------------------------------------------------------------------------
- def register(*args)
- if @register.has_key?(args[0])
- @register[args[0]][:version] = args[1]
- @register[args[0]][:data] = args[2]
- else
- @register[args[0]] = {name: args[1], version: args[2], data: args[3], script: nil}
- end
- end
- #----------------------------------------------------------------------------
- # * Método de verificar se o objeto existe.
- #----------------------------------------------------------------------------
- # Dax.required_class("Objeto") { }
- # Dentro das chaves você poem o script.
- # * Exemplo :
- # Dax.required_class("Window_Base") {
- # class Window_Base < Window
- # def example
- # self.x = self.x + self.width
- # end
- # end
- # }
- #----------------------------------------------------------------------------
- # Executa o bloco se o objeto existir.
- #----------------------------------------------------------------------------
- def required_class(name, &block)
- return unless defined?(name)
- eval("block.call if defined?(name)")
- end
- #----------------------------------------------------------------------------
- # • Fazer benchmark de um bloco. O resultado será impresso no Console do
- # Maker.
- #----------------------------------------------------------------------------
- # Dax.benchmark(name(opcional)) { BLOCO }
- #----------------------------------------------------------------------------
- def benchmark(name="", &block)
- time = Time.now
- block.call
- print "Benchmark: #{(time - Time.now).abs.to_f} segundos!\r\n"
- @benchmark += "#{name} : #{(time - Time.now).to_f} segundos!\r\n"
- end
- #----------------------------------------------------------------------------
- # • Salva os testes de benchmark num arquivo chamado 'Benchmark' de extensão
- # .txt.
- #----------------------------------------------------------------------------
- def benchmark_save
- self.required_file("Benchmark.txt") { File.delete("Benchmark.txt") }
- File.open("Benchmark.txt", "a+") do |file|
- file.write(@benchmark)
- file.close
- end
- end
- #----------------------------------------------------------------------------
- # • Requirir um arquivo.
- # arquivo : Arquivo...
- #----------------------------------------------------------------------------
- def require(arquivo)
- $: << "./"
- Kernel.send(:require, arquivo)
- end
- #----------------------------------------------------------------------------
- # * Somente executa um bloco case existir um arquivo.
- #----------------------------------------------------------------------------
- # Dax.required_file("arquivo.tipo") { # Exemplo.
- # Métodos;
- # }
- #----------------------------------------------------------------------------
- def required_file(filename, &block)
- return unless FileTest.exist?(filename)
- block.call
- end
- # Requer a existência de uma pasta para executar tal bloco.
- def required_directory(directory, &block)
- return unless File.directory?(directory) and block_given?
- block.call
- end
- #----------------------------------------------------------------------------
- # * Remove uma [Classe], exemplo: Dax.remove(:Scene_Menu)
- #----------------------------------------------------------------------------
- def remove(symbol_name)
- Object.send(:remove_const, symbol_name)
- end
- #----------------------------------------------------------------------------
- # * Tela chéia
- #----------------------------------------------------------------------------
- def full_screen
- res = Win32API.new 'user32', 'keybd_event', %w(l l l l), ''
- res.call(18,0,0,0)
- res.call(13,0,0,0)
- res.call(13,0,2,0)
- res.call(18,0,2,0)
- end
- end
- #==============================================================================
- # • Module
- #==============================================================================
- Dax.register(:module)
- class Module
- #----------------------------------------------------------------------------
- # • [NilClass] Permite definir uma variável de instância com um valor definido.
- # Exemplo:
- # Test = Class.new {
- # attr_value :gold, 0
- # }
- # msgbox Test.new.gold #=> 0
- #----------------------------------------------------------------------------
- def attr_value(symbol, value=nil)
- attr_accessor(symbol)
- module_eval("def #{symbol}
- @#{symbol} = #{value} unless defined?(@#{symbol})
- return @#{symbol}
- end")
- return nil
- end
- end
- Dax.register(:dax)
- #==============================================================================
- # • Array
- #==============================================================================
- Dax.register :array
- class Array
- #----------------------------------------------------------------------------
- # • [Array] Retorna ao elemento da array que condiz com a condição
- # definida no bloco.
- # Exemplo:
- # [2, 4, 5, 6, 8].rIf { |element| element >= 4 }
- # # 5, 6, 8
- #----------------------------------------------------------------------------
- def rIf
- return unless block_given?
- getResult ||= []
- self.each_with_index{ |arrays|
- getResult << arrays if yield(arrays)
- }
- return getResult
- end
- end
- #==============================================================================
- # * API : Módulo que armazena informações de algumas APIS.
- #==============================================================================
- Dax.register(:api)
- module API
- extend self
- #----------------------------------------------------------------------------
- # • [String] : Tipos e seus retornos.. Pegado da internet.. Autor desconhecido
- #----------------------------------------------------------------------------
- TYPES = {
- struct: "p",
- int: "i",
- long: "l",
- INTERNET_PORT: "l",
- SOCKET: "p",
- C: "p", #– 8-bit unsigned character (byte)
- c: "p", # 8-bit character (byte)
- # "i"8 – 8-bit signed integer
- # "i"8 – 8-bit unsigned integer
- S: "N", # – 16-bit unsigned integer (Win32/API: S used for string params)
- s: "n", # – 16-bit signed integer
- # "i"16 – 16-bit unsigned integer
- # "i"16 – 16-bit signed integer
- I: "I", # 32-bit unsigned integer
- i: "i", # 32-bit signed integer
- # "i"32 – 32-bit unsigned integer
- # "i"32 – 32-bit signed integer
- L: "L", # unsigned long int – platform-specific size
- l: "l", # long int – platform-specific size. For discussion of platforms, see:
- # (http://groups.google.com/group/ruby-ffi/browse_thread/thread/4762fc77130339b1)
- # "i"64 – 64-bit signed integer
- # "i"64 – 64-bit unsigned integer
- # "l"_long – 64-bit signed integer
- # "l"_long – 64-bit unsigned integer
- F: "L", # 32-bit floating point
- D: "L", # 64-bit floating point (double-precision)
- P: "P", # pointer – platform-specific size
- p: "p", # C-style (NULL-terminated) character string (Win32API: S)
- B: "i", # (?? 1 byte in C++)
- V: "V", # For functions that return nothing (return type void).
- v: "v", # For functions that return nothing (return type void).
- # For function argument type only:
- # :buffer_in – Similar to "l", but optimized for Buffers that the function can only read (not write).
- # :buffer_out – Similar to "l", but optimized for Buffers that the function can only write (not read).
- # :buffer_inout – Similar to "l", but may be optimized for Buffers.
- # :varargs – Variable arguments
- # :enum - Enumerable type (should be defined)
- # "p"_array - ??
- # Windows-specific type defs (ms-help://MS.MSDNQTR.v90.en/winprog/winprog/windows_data_types.htm):
- ATOM: "I", # Atom ~= Symbol: Atom table stores strings and corresponding identifiers. Application
- # places a string in an atom table and receives a 16-bit integer, called an atom, that
- # can be used to access the string. Placed string is called an atom name.
- # See: http://msdn.microsoft.com/en-us/library/ms648708%28VS.85%29.aspx
- BOOL: "i",
- BOOLEAN: "i",
- BYTE: "p", # Byte (8 bits). Declared as unsigned char
- #CALLBACK: K, # Win32.API gem-specific ?? MSDN: #define CALLBACK __stdcall
- CHAR: "p", # 8-bit Windows (ANSI) character. See http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
- COLORREF: "i", # Red, green, blue (RGB) color value (32 bits). See COLORREF for more info.
- DWORD: "i", # 32-bit unsigned integer. The range is 0 through 4,294,967,295 decimal.
- DWORDLONG: "i", # 64-bit unsigned integer. The range is 0 through 18,446,744,073,709,551,615 decimal.
- DWORD_PTR: "l", # Unsigned long type for pointer precision. Use when casting a pointer to a long type
- # to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have
- # been extended to 64 bits in 64-bit Windows.) BaseTsd.h: #typedef ULONG_PTR DWORD_PTR;
- DWORD32: "I",
- DWORD64: "I",
- HALF_PTR: "i", # Half the size of a pointer. Use within a structure that contains a pointer and two small fields.
- # BaseTsd.h: #ifdef (_WIN64) typedef int HALF_PTR; #else typedef short HALF_PTR;
- HACCEL: "i", # (L) Handle to an accelerator table. WinDef.h: #typedef HANDLE HACCEL;
- # See http://msdn.microsoft.com/en-us/library/ms645526%28VS.85%29.aspx
- HANDLE: "l", # (L) Handle to an object. WinNT.h: #typedef PVOID HANDLE;
- # todo: Platform-dependent! Need to change to "i"64 for Win64
- HBITMAP: "l", # (L) Handle to a bitmap: http://msdn.microsoft.com/en-us/library/dd183377%28VS.85%29.aspx
- HBRUSH: "l", # (L) Handle to a brush. http://msdn.microsoft.com/en-us/library/dd183394%28VS.85%29.aspx
- HCOLORSPACE: "l", # (L) Handle to a color space. http://msdn.microsoft.com/en-us/library/ms536546%28VS.85%29.aspx
- HCURSOR: "l", # (L) Handle to a cursor. http://msdn.microsoft.com/en-us/library/ms646970%28VS.85%29.aspx
- HCONV: "l", # (L) Handle to a dynamic data exchange (DDE) conversation.
- HCONVLIST: "l", # (L) Handle to a DDE conversation list. HANDLE - L ?
- HDDEDATA: "l", # (L) Handle to DDE data (structure?)
- HDC: "l", # (L) Handle to a device context (DC). http://msdn.microsoft.com/en-us/library/dd183560%28VS.85%29.aspx
- HDESK: "l", # (L) Handle to a desktop. http://msdn.microsoft.com/en-us/library/ms682573%28VS.85%29.aspx
- HDROP: "l", # (L) Handle to an internal drop structure.
- HDWP: "l", # (L) Handle to a deferred window position structure.
- HENHMETAFILE: "l", #(L) Handle to an enhanced metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
- HFILE: "i", # (I) Special file handle to a file opened by OpenFile, not CreateFile.
- # WinDef.h: #typedef int HFILE;
- HFONT: "l", # (L) Handle to a font. http://msdn.microsoft.com/en-us/library/dd162470%28VS.85%29.aspx
- HGDIOBJ: "l", # (L) Handle to a GDI object.
- HGLOBAL: "l", # (L) Handle to a global memory block.
- HHOOK: "l", # (L) Handle to a hook. http://msdn.microsoft.com/en-us/library/ms632589%28VS.85%29.aspx
- HICON: "l", # (L) Handle to an icon. http://msdn.microsoft.com/en-us/library/ms646973%28VS.85%29.aspx
- HINSTANCE: "l", # (L) Handle to an instance. This is the base address of the module in memory.
- # HMODULE and HINSTANCE are the same today, but were different in 16-bit Windows.
- HKEY: "l", # (L) Handle to a registry key.
- HKL: "l", # (L) Input locale identifier.
- HLOCAL: "l", # (L) Handle to a local memory block.
- HMENU: "l", # (L) Handle to a menu. http://msdn.microsoft.com/en-us/library/ms646977%28VS.85%29.aspx
- HMETAFILE: "l", # (L) Handle to a metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
- HMODULE: "l", # (L) Handle to an instance. Same as HINSTANCE today, but was different in 16-bit Windows.
- HMONITOR: "l", # (L) Рandle to a display monitor. WinDef.h: if(WINVER >= 0x0500) typedef HANDLE HMONITOR;
- HPALETTE: "l", # (L) Handle to a palette.
- HPEN: "l", # (L) Handle to a pen. http://msdn.microsoft.com/en-us/library/dd162786%28VS.85%29.aspx
- HRESULT: "l", # Return code used by COM interfaces. For more info, Structure of the COM Error Codes.
- # To test an HRESULT value, use the FAILED and SUCCEEDED macros.
- HRGN: "l", # (L) Handle to a region. http://msdn.microsoft.com/en-us/library/dd162913%28VS.85%29.aspx
- HRSRC: "l", # (L) Handle to a resource.
- HSZ: "l", # (L) Handle to a DDE string.
- HWINSTA: "l", # (L) Handle to a window station. http://msdn.microsoft.com/en-us/library/ms687096%28VS.85%29.aspx
- HWND: "l", # (L) Handle to a window. http://msdn.microsoft.com/en-us/library/ms632595%28VS.85%29.aspx
- INT: "i", # 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.
- INT_PTR: "i", # Signed integer type for pointer precision. Use when casting a pointer to an integer
- # to perform pointer arithmetic. BaseTsd.h:
- #if defined(_WIN64) typedef __int64 INT_PTR; #else typedef int INT_PTR;
- INT32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
- INT64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
- LANGID: "n", # Language identifier. For more information, see Locales. WinNT.h: #typedef WORD LANGID;
- # See http://msdn.microsoft.com/en-us/library/dd318716%28VS.85%29.aspx
- LCID: "i", # Locale identifier. For more information, see Locales.
- LCTYPE: "i", # Locale information type. For a list, see Locale Information Constants.
- LGRPID: "i", # Language group identifier. For a list, see EnumLanguageGroupLocales.
- LONG: "l", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
- LONG32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
- LONG64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
- LONGLONG: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
- LONG_PTR: "l", # Signed long type for pointer precision. Use when casting a pointer to a long to
- # perform pointer arithmetic. BaseTsd.h:
- #if defined(_WIN64) typedef __int64 LONG_PTR; #else typedef long LONG_PTR;
- LPARAM: "l", # Message parameter. WinDef.h as follows: #typedef LONG_PTR LPARAM;
- LPBOOL: "i", # Pointer to a BOOL. WinDef.h as follows: #typedef BOOL far *LPBOOL;
- LPBYTE: "i", # Pointer to a BYTE. WinDef.h as follows: #typedef BYTE far *LPBYTE;
- LPCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
- # See Character Sets Used By Fonts. http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
- LPCTSTR: "p", # An LPCWSTR if UNICODE is defined, an LPCSTR otherwise.
- LPCVOID: "v", # Pointer to a constant of any type. WinDef.h as follows: typedef CONST void *LPCVOID;
- LPCWSTR: "P", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
- LPDWORD: "p", # Pointer to a DWORD. WinDef.h as follows: typedef DWORD *LPDWORD;
- LPHANDLE: "l", # Pointer to a HANDLE. WinDef.h as follows: typedef HANDLE *LPHANDLE;
- LPINT: "I", # Pointer to an INT.
- LPLONG: "L", # Pointer to an LONG.
- LPSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters.
- LPTSTR: "p", # An LPWSTR if UNICODE is defined, an LPSTR otherwise.
- LPVOID: "v", # Pointer to any type.
- LPWORD: "p", # Pointer to a WORD.
- LPWSTR: "p", # Pointer to a null-terminated string of 16-bit Unicode characters.
- LRESULT: "l", # Signed result of message processing. WinDef.h: typedef LONG_PTR LRESULT;
- PBOOL: "i", # Pointer to a BOOL.
- PBOOLEAN: "i", # Pointer to a BOOL.
- PBYTE: "i", # Pointer to a BYTE.
- PCHAR: "p", # Pointer to a CHAR.
- PCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
- PCTSTR: "p", # A PCWSTR if UNICODE is defined, a PCSTR otherwise.
- PCWSTR: "p", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
- PDWORD: "p", # Pointer to a DWORD.
- PDWORDLONG: "L", # Pointer to a DWORDLONG.
- PDWORD_PTR: "L", # Pointer to a DWORD_PTR.
- PDWORD32: "L", # Pointer to a DWORD32.
- PDWORD64: "L", # Pointer to a DWORD64.
- PFLOAT: "L", # Pointer to a FLOAT.
- PHALF_PTR: "L", # Pointer to a HALF_PTR.
- PHANDLE: "L", # Pointer to a HANDLE.
- PHKEY: "L", # Pointer to an HKEY.
- PINT: "i", # Pointer to an INT.
- PINT_PTR: "i", # Pointer to an INT_PTR.
- PINT32: "i", # Pointer to an INT32.
- PINT64: "i", # Pointer to an INT64.
- PLCID: "l", # Pointer to an LCID.
- PLONG: "l", # Pointer to a LONG.
- PLONGLONG: "l", # Pointer to a LONGLONG.
- PLONG_PTR: "l", # Pointer to a LONG_PTR.
- PLONG32: "l", # Pointer to a LONG32.
- PLONG64: "l", # Pointer to a LONG64.
- 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.
- 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.
- POINTER_SIGNED: "l", # A signed pointer.
- HPSS: "l",
- POINTER_UNSIGNED: "l", # An unsigned pointer.
- PSHORT: "l", # Pointer to a SHORT.
- PSIZE_T: "l", # Pointer to a SIZE_T.
- PSSIZE_T: "l", # Pointer to a SSIZE_T.
- PSS_CAPTURE_FLAGS: "l",
- PSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
- PTBYTE: "p", # Pointer to a TBYTE.
- PTCHAR: "p", # Pointer to a TCHAR.
- PTSTR: "p", # A PWSTR if UNICODE is defined, a PSTR otherwise.
- PUCHAR: "p", # Pointer to a UCHAR.
- PUINT: "i", # Pointer to a UINT.
- PUINT_PTR: "i", # Pointer to a UINT_PTR.
- PUINT32: "i", # Pointer to a UINT32.
- PUINT64: "i", # Pointer to a UINT64.
- PULONG: "l", # Pointer to a ULONG.
- PULONGLONG: "l", # Pointer to a ULONGLONG.
- PULONG_PTR: "l", # Pointer to a ULONG_PTR.
- PULONG32: "l", # Pointer to a ULONG32.
- PULONG64: "l", # Pointer to a ULONG64.
- PUSHORT: "l", # Pointer to a USHORT.
- PVOID: "v", # Pointer to any type.
- PWCHAR: "p", # Pointer to a WCHAR.
- PWORD: "p", # Pointer to a WORD.
- PWSTR: "p", # Pointer to a null- terminated string of 16-bit Unicode characters.
- # For more information, see Character Sets Used By Fonts.
- SC_HANDLE: "l", # (L) Handle to a service control manager database.
- SERVICE_STATUS_HANDLE: "l", # (L) Handle to a service status value. See SCM Handles.
- SHORT: "i", # A 16-bit integer. The range is –32768 through 32767 decimal.
- 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.
- SSIZE_T: "l", # Signed SIZE_T.
- TBYTE: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
- # http://msdn.microsoft.com/en-us/library/c426s321%28VS.80%29.aspx
- TCHAR: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
- UCHAR: "p", # Unsigned CHAR (8 bit)
- UHALF_PTR: "i", # Unsigned HALF_PTR. Use within a structure that contains a pointer and two small fields.
- UINT: "i", # Unsigned INT. The range is 0 through 4294967295 decimal.
- UINT_PTR: "i", # Unsigned INT_PTR.
- UINT32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
- UINT64: "i", # Unsigned INT64. The range is 0 through 18446744073709551615 decimal.
- ULONG: "l", # Unsigned LONG. The range is 0 through 4294967295 decimal.
- ULONGLONG: "l", # 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
- ULONG_PTR: "l", # Unsigned LONG_PTR.
- ULONG32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
- ULONG64: "i", # Unsigned LONG64. The range is 0 through 18446744073709551615 decimal.
- UNICODE_STRING: "P", # Pointer to some string structure??
- USHORT: "i", # Unsigned SHORT. The range is 0 through 65535 decimal.
- USN: "l", # Update sequence number (USN).
- WCHAR: "i", # 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
- # In WinNT.h: typedef wchar_t WCHAR;
- #WINAPI: K, # Calling convention for system functions. WinDef.h: define WINAPI __stdcall
- WORD: "i", # 16-bit unsigned integer. The range is 0 through 65535 decimal.
- WPARAM: "i", # Message parameter. WinDef.h as follows: typedef UINT_PTR WPARAM;
- VOID: "v", # Any type ? Only use it to indicate no arguments or no return value
- vKey: "i",
- LPRECT: "p",
- }
- #----------------------------------------------------------------------------
- # • [Array] : Pega os valores especificados no método.. depois verifica
- # cada um se é String ou Symbol. Se for Symbol retorna ao valor especificado
- # na Constante TYPES.
- # Exemplo: types([:BOOL, :WCHAR]) # ["i", "i"]
- #----------------------------------------------------------------------------
- def types(import)
- import2 = []
- import.each { |i|
- next if i.is_a?(NilClass) or i.is_a?(String)
- import2 << TYPES[i]
- }
- return import2
- end
- #----------------------------------------------------------------------------
- # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
- # Por padrão a DLL é a "user32". O valor de exportação será "i"
- #----------------------------------------------------------------------------
- def int(function, import, dll="user32")
- Win32API.new(dll, function, types(import), "i") rescue nil
- end
- #----------------------------------------------------------------------------
- # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
- # Por padrão a DLL é a "user32". O valor de exportação será "l"
- #----------------------------------------------------------------------------
- def long(function, import, dll="user32")
- Win32API.new(dll, function.to_s, types(import), "l") rescue nil
- end
- #----------------------------------------------------------------------------
- # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
- # Por padrão a DLL é a "user32". O valor de exportação será "v"
- #----------------------------------------------------------------------------
- def void(function, import, dll="user32")
- Win32API.new(dll, function.to_s, types(import), "v") rescue nil
- end
- #----------------------------------------------------------------------------
- # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
- # Por padrão a DLL é a "user32". O valor de exportação será "p"
- #----------------------------------------------------------------------------
- def char(function, import, dll="user32")
- Win32API.new(dll, function.to_s, types(import), "p") rescue nil
- end
- #----------------------------------------------------------------------------
- # • [Dll]// : Com esse método você pode especificar uma função de uma Dll.
- # function(export, function, import, dll)
- # export : Valor da exportação. Formato [Symbol]
- # function : Função da Dll.
- # import : Valor da importação.
- # dll : Dll. Por padrão é a User32
- # Esconder o Mouse.
- # Exemplo: function(:int, "ShowCursor", [:BOOL]).call(0)
- #----------------------------------------------------------------------------
- def function(export, function, import, dll="user32")
- eval("#{export}(function, import, dll)")
- end
- #----------------------------------------------------------------------------
- # • Especificando o método protegido.
- #----------------------------------------------------------------------------
- # Métodos privados.
- private :long, :int, :char, :void, :types
- #----------------------------------------------------------------------------
- # • [CopyFile]/Dll : Função da DLL Kernel32 que permite copiar arquivos.
- # CopyFile.call(filename_to_copy, filename_copied, replace)
- # filename_to_copy : Formato [String]
- # filename_copied : Formato [String]
- # replace : Formato [Integer] 0 - false 1 - true
- # Exemplo: CopyFile.call("System/RGSS300.dll", "./RGSS300.dll", 1)
- #----------------------------------------------------------------------------
- CopyFile = Win32API.new('kernel32', 'CopyFile', 'ppl', 'l')
- #----------------------------------------------------------------------------
- # • [Beep]/Dll : Emitir uma frequência de um som do sistema com duração.
- # Beep.call(freq, duration)
- # freq : Formato [Integer\Hexadécimal]
- # duration : Formato [Integer\Hexadécimal]
- # Exemplo: Beep.call(2145, 51)
- #----------------------------------------------------------------------------
- Beep = Win32API.new('kernel32', 'Beep', 'LL', 'L')
- #----------------------------------------------------------------------------
- # • [keybd_event]/Dll : Ela é usada para sintentizar uma combinação de teclas.
- # KEYBD_EVENT.call(vk, scan, fdwFlags, dwExtraInfo)
- # vk : Formato [Integer/Hexadécimal].
- # scan : Formato [Integer]
- # fdwFlags : Formato [Integer]
- # dwExtraInfo : Formato [Integer]
- # Exemplo: KEYBD_EVENT.call(0x01, 0, 0, 0)
- #----------------------------------------------------------------------------
- KEYBD_EVENT = Win32API.new('user32', 'keybd_event', 'LLLL', '')
- #----------------------------------------------------------------------------
- # • [GetKeyState]/Dll : Pega o status da chave.
- # GetKeyState.call(vk)
- # vk : Formato [Integer/Hexadécimal].
- # Exemplo: GetKeyState.call(0x01)
- #----------------------------------------------------------------------------
- GetKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'i', 'i')
- #----------------------------------------------------------------------------
- # • [MouseShowCursor]/Dll : Mostrar ou desativar o cusor do Mouse.
- # MouseShowCursor.call(value)
- # value : Formato [Integer] 0 - false 1 - true
- # Exemplo: MouseShowCursor.call(0)
- #----------------------------------------------------------------------------
- MouseShowCursor = Win32API.new("user32", "ShowCursor", "i", "i")
- #----------------------------------------------------------------------------
- # • [CursorPosition]/Dll : Obtem a posição do cursor do Mouse na tela.
- # CursorPosition.call(lpPoint)
- # lpPoint : Formato [Array]
- # Ex: CursorPosition.call([0, 0].pack('ll'))
- #----------------------------------------------------------------------------
- CursorPosition = Win32API.new('user32', 'GetCursorPos', 'p', 'i')
- #----------------------------------------------------------------------------
- # • [ScreenToClient]/Dll : Converte as coordenadas da tela para um ponto
- # em especifico da área da tela do cliente.
- # ScreenToClient.call(hWnd, lpPoint)
- #----------------------------------------------------------------------------
- ScreenToClient = Win32API.new('user32', 'ScreenToClient', 'lp', 'i')
- #----------------------------------------------------------------------------
- # • [ReadIni]/Dll : */Ainda não explicado./*
- #----------------------------------------------------------------------------
- ReadIni = Win32API.new('kernel32', 'GetPrivateProfileStringA', %w(p p p p l p), 'l')
- #----------------------------------------------------------------------------
- # • [FindWindow]/Dll : Recupera o identificador da janela superior. Cujo
- # o nome da janela é o nome da classe da janela se combina com as cadeias
- # especificas.
- # FindWindow.call(lpClassName, lpWindowName)
- # lpClassName : Formato [String]
- # lpWindowName : Formato [String]
- #----------------------------------------------------------------------------
- FindWindow = Win32API.new('user32', 'FindWindowA', %w(p p), 'l')
- #----------------------------------------------------------------------------
- # • [Handle]/Dll : Retorna ao Handle da janela.
- #----------------------------------------------------------------------------
- def hWND
- return API::FindWindow.call('RGSS Player', load_data("./Data/System.rvdata2").game_title.to_s)
- end
- #----------------------------------------------------------------------------
- # • [Handle]/Dll : Retorna ao Handle da janela. Método protegido.
- #----------------------------------------------------------------------------
- def hwnd
- hWND
- end
- #----------------------------------------------------------------------------
- # • [GetPrivateProfileString]/Dll : */Ainda não explicado./*
- #----------------------------------------------------------------------------
- GetPrivateProfileString = Win32API.new('kernel32', 'GetPrivateProfileStringA',%w(p p p p l p),'l')
- #----------------------------------------------------------------------------
- # • [SetWindowPos]/Dll : Modifica os elementos da janela como, posição, tamanho.
- #----------------------------------------------------------------------------
- SetWindowPos = Win32API.new("user32", "SetWindowPos", "lliiiii", "i")
- #----------------------------------------------------------------------------
- # • [GetWindowRect]/Dll : Obtem as dimensões do retângulo da janela.
- # GetWindowRect.call(hWnd, lpRect)
- #----------------------------------------------------------------------------
- GetWindowRect = Win32API.new('user32','GetWindowRect',%w(l p),'i')
- #----------------------------------------------------------------------------
- # • [StateKey]/Dll : Retorna ao status específico da chave.
- # StateKey.call(VK)
- # VK : Formato [Integer/Hexadécimal].
- #----------------------------------------------------------------------------
- StateKey = Win32API.new("user32", "GetKeyState", ["i"], "i")
- #----------------------------------------------------------------------------
- # • [SetCursorPos]/Dll : Move o cursor do Mouse para um ponto específico
- # da tela.
- # SetCursorPos.call(x, y)
- # x, y : Formato [Integer/Float]
- #----------------------------------------------------------------------------
- SetCursorPos = Win32API.new("user32", "SetCursorPos", "ll", "i")
- #----------------------------------------------------------------------------
- # • [GetKeyboardState]/Dll : Cópia o status das 256 chaves para um
- # buffer especificado.
- #----------------------------------------------------------------------------
- GetKeyboardState = Win32API.new('user32', 'GetKeyboardState', ['P'], 'V')
- #----------------------------------------------------------------------------
- # • [GetAsyncKeyState]/Dll : Determina o estado da chave no momento em que a
- # função é chamada.
- # GetAsyncKeyState.call(Vk)
- # VK : Formato [Integer/Hexadécimal].
- #----------------------------------------------------------------------------
- GetAsyncKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'i', 'i')
- #----------------------------------------------------------------------------
- # • [WideCharToMultiByte] : [MultiByteToWideChar] // Comentários
- # não adicionados.
- #----------------------------------------------------------------------------
- WideCharToMultiByte = Win32API.new('kernel32', 'WideCharToMultiByte', 'ilpipipp', 'i')
- MultiByteToWideChar = Win32API.new('kernel32', 'MultiByteToWideChar', 'ilpipi', 'i')
- #----------------------------------------------------------------------------
- # • [ZeroMemoy]/Dll : Enche um bloco da memória com zeros.
- #----------------------------------------------------------------------------
- ZeroMemory = Win32API.new("kernel32", "RtlZeroMemory", "pl", "")
- #----------------------------------------------------------------------------
- # • [AdjustWindowRect] : Calcula o tamanho requerido do retângulo da Janela.
- #----------------------------------------------------------------------------
- AdjustWindowRect = int("AdjustWindowRect", [:LPRECT, :DWORD, :BOOL])
- #----------------------------------------------------------------------------
- # • Constantes [SetWindowPos]
- #----------------------------------------------------------------------------
- SWP_ASYNCWINDOWPOS = 0x4000
- # Desenha os frames (definidos na classe da janela descrita) em torno na janela.
- SWP_DRAWFRAME = 0x0020
- # Esconde a janela.
- SWP_HIDEWINDOW = 0x0080
- # Não pode ser ativada nem movida
- SWP_NOACTIVATE = 0x0010
- # Não permite mover
- SWP_NOMOVE = 0x0002
- # Não permite redimensionar
- SWP_NOSIZE = 0x0001
- # Mostra a Janela
- SWP_SHOWWINDOW = 0x0040
- # Coloca a janela na parte inferior na ordem de Z. Se identificar uma janela
- # superior ela perde os seus status.
- HWND_BOTTOM = 1
- # Coloca a janela acima de todas as janelas que não estão em primeiro plano.
- HWND_NOTOPMOST = -2
- # Poem a janela no Topo na ordem de Z.
- HWND_TOP = 0
- # Poem a janela acima de todas que não estão em primeiro plano. Mantendo a
- # posição.
- HWND_TOPMOST = -1
- #----------------------------------------------------------------------------
- # • [SetActiveWindow]/ Dll : Ativa a Window.
- #----------------------------------------------------------------------------
- SetActiveWindow = long("SetActiveWindow", [:HWND])
- #----------------------------------------------------------------------------
- # • WindowFromPoint : Retorna ao handle da janela, que contém um ponto
- # específico.
- #----------------------------------------------------------------------------
- WindowFromPoint = long("WindowFromPoint", [:HWND])
- #----------------------------------------------------------------------------
- # • ShowWindow : Mostra a janela em um estado específico.
- #----------------------------------------------------------------------------
- ShowWindow = long("ShowWindow", [:HWND, :LONG])
- # Força a janela a minimizar
- SW_FORCEMINIMIZE = 11
- # Esconde a janela, ativa outra.
- SW_HIDE = 0
- # Maximiza a janela.
- SW_MAXIMIZE = 3
- # Minimiza a janela
- SW_MINIMIZE = 6
- # Restaura o estado da janela.
- SW_RESTORE = 9
- # Ativa a janela a mostrando na posição original.
- SW_SHOW = 5
- #----------------------------------------------------------------------------
- # • [SetWindowText] : Permite modificar o título da janela.
- #----------------------------------------------------------------------------
- SetWindowText = int("SetWindowText", [:HWND, :LPCTSTR])
- #----------------------------------------------------------------------------
- # • [GetDesktopWindow] : Retorna ao handle da janela em relação ao Desktop.
- #----------------------------------------------------------------------------
- GetDesktopWindow = long("GetDesktopWindow", [:HWND])
- #----------------------------------------------------------------------------
- # • [GetSystemMetric] : Obtem um sistema métrico específico ou a configuração
- # do sistema. As dimensões retornadas são em pixel.
- #----------------------------------------------------------------------------
- GetSystemMetric = int("GetSystemMetric", [:int])
- #----------------------------------------------------------------------------
- # • [GetSystemMetric]/Constantes:
- #----------------------------------------------------------------------------
- # Obtem a flag que especifica como o sistema está organizando as janelas
- # minimizadas.
- SM_ARRANGE = 56
- # Obtem o tamanho da borda da Janela em pixel.
- SM_CXBORDER = 5
- # Valor do tamanho da área do cliente pra uma Janela em modo de tela-chéia.
- # em pixel.
- SM_CXFULLSCREEN = 16
- # Para mais informações dos valores, visite :
- # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
- #----------------------------------------------------------------------------
- # • [GetClientRect] : Retorna ao rect da área da Janela.
- # Uses :
- # lpRect = [0,0,0,0].pack("L*")
- # GetClientRect.(hwnd, lpRect)
- # lpRect = lpRect.unpack("L*")
- #----------------------------------------------------------------------------
- GetClientRect = int("GetClientRect", [:HWND, :LPRECT])
- #----------------------------------------------------------------------------
- # • [GetModuleHandle] : Retorna ao Handle do módulo, do módulo específicado.
- # Pode ser aquivo '.dll' ou '.exe'. Exemplo:
- # GetModuleHandle.call('System/RGSS300.dll')
- #----------------------------------------------------------------------------
- GetModuleHandle = long("GetModuleHandle", [:LPCTSTR], "kerne32")
- #----------------------------------------------------------------------------
- # • [FreeLibrary] : Libera o módulo que está carregado na DLL específica.
- #----------------------------------------------------------------------------
- FreeLibrary = long("FreeLibrary", [:HMODULE], "kernel32")
- #----------------------------------------------------------------------------
- # • [LoadLibrary] : Carrega um endereço de um módulo em específico.
- # LoadLibrary.call(Nome da Libraria(dll/exe))
- # [Handle] : Retorna ao valor do Handle do módulo caso der certo.
- #----------------------------------------------------------------------------
- LoadLibrary = long("LoadLibrary", [:LPCTSTR], "kernel32")
- #----------------------------------------------------------------------------
- # • [GetProcAddress] : Retorna ao endereço da função exportada ou a variável
- # de uma DLL específica.
- # GetProcAddress.call(hModule, lpProcName)
- # hModule : É o valor do handle. Você pode pega-lo usando o LoadLibrary
- # lpProcName : A função ou o nome da variável.
- #----------------------------------------------------------------------------
- GetProcAddress = long("GetProcAddress", [:HMODULE, :LPCSTR], "kernel32")
- #----------------------------------------------------------------------------
- # • [GetSystemMetrics] : Retorna á uma configuração específica do sistema
- # métrico.
- #----------------------------------------------------------------------------
- GetSystemMetrics = int("GetSystemMetrics", [:int])
- #----------------------------------------------------------------------------
- # • [GetSystemMetrics]::Constantes. #Para mais visite:
- # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
- #----------------------------------------------------------------------------
- SM_CXSCREEN = 0 # O tamanho(width/largura) da janela em pixel.
- SM_CYSCREEN = 1 # O tamanho(height/comprimento) da janela em pixel.
- SM_CXFULLSCREEN = 16 # O tamanho da largura da tela chéia da janela.
- SM_CYFULLSCREEN = 17 # O tamanho do comprimento da tela chéia da janela.
- #----------------------------------------------------------------------------
- # • [Método protegido] : Método usado para chamar a função LoadLibrary.
- #----------------------------------------------------------------------------
- def dlopen(name, fA=nil)
- l = LoadLibrary.(String(name))
- return l if fA.nil?
- return GetProcAddress.(l, String(fA))
- end
- #----------------------------------------------------------------------------
- # • Converte um texto para o formato UTF-8
- # textUTF(text)
- # * text : Texto.
- #----------------------------------------------------------------------------
- def textUTF(text)
- wC = API::MultiByteToWideChar.call(65001, 0, text, -1, "", 0)
- API::MultiByteToWideChar.call(65001, 0, text, -1, text = "\0\0" * wC, wC)
- return text
- end
- #----------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Retorna verdadeiro caso o Caps Lock esteja
- # ativo e retorna Falso caso não esteja ativo.
- #----------------------------------------------------------------------------
- def get_caps_lock
- return int("GetKeyState", [:vKey]).call(20) == 1
- end
- #----------------------------------------------------------------------------
- # • Abre a URL de um site o direcionado para o navegador padrão do usuário.
- #----------------------------------------------------------------------------
- def open_site(url)
- c = Win32API.new("Shell32", "ShellExecute", "pppppl", "l")
- c.call(nil, "open", url, nil, nil, 0)
- end
- #==============================================================================
- # • Clipboard
- #==============================================================================
- module Clipboard
- extend self
- #----------------------------------------------------------------------------
- # • Constantes do módulo:
- #----------------------------------------------------------------------------
- Close = Win32API.new("user32", "CloseClipboard", "v", "l")
- GetData = Win32API.new("user32", "GetClipboardData", "n", "l")
- Open = Win32API.new('user32', 'OpenClipboard', "N", "L")
- FormatAvailable = Win32API.new('user32', 'IsClipboardFormatAvailable', "i", "i")
- GlobalAlloc = Win32API.new('kernel32', 'GlobalAlloc', 'll', 'l')
- GlobalLock = Win32API.new('kernel32', 'GlobalLock', 'l', 'l')
- GlobalSize = Win32API.new('kernel32', 'GlobalSize', 'l', 'l')
- GlobalUnlock = Win32API.new('kernel32', 'GlobalUnlock', 'l', '')
- MemCpy = Win32API.new('ntdll', 'memcpy', 'ppl', 'l')
- FORMATS = {text: 1, dib: 2, bitmap: 8}
- #----------------------------------------------------------------------------
- # • Data. Retorna a Data do clipboard. Especificar o formato para receber
- # o retorno do formato especifico. Formato padrão é o texto.
- #----------------------------------------------------------------------------
- def data(format=FORMATS[:text])
- begin
- self.open
- if FormatAvailable.call(format)
- handle = GetData.call(format)
- case format
- when 1
- clip_data = 0.chr * GlobalSize.call(handle)
- MemCpy.call(clip_data, handle, clip_data.size)
- clip_data = clip_data[ /^[^\0]*/ ]
- when 2, 8 then clip_data = get_image_data(handle)
- else
- raise Error, 'format not supported'
- end
- else
- clip_data = ''
- end
- ensure
- self.close
- end
- clip_data
- end
- #----------------------------------------------------------------------------
- # • Singleton Class
- #----------------------------------------------------------------------------
- class << self
- alias :get_data :data
- end
- #----------------------------------------------------------------------------
- # • Formato aceito.
- #----------------------------------------------------------------------------
- def formatAvailable?(format)
- FormatAvailable.call(format).boolean
- end
- private
- #----------------------------------------------------------------------------
- # • Abrir clipboard
- #----------------------------------------------------------------------------
- def open
- Open.call(0)
- end
- #----------------------------------------------------------------------------
- # • Fechar
- #----------------------------------------------------------------------------
- def close
- Close.call
- end
- #----------------------------------------------------------------------------
- # • Obter a data de uma imagem, bitmap.
- #----------------------------------------------------------------------------
- def get_image_data(handle)
- buf = nil
- bmi = 0.chr * 44 # BITMAPINFO
- begin
- address = GlobalLock.call(handle)
- buf_size = GlobalSize.call(handle)
- MemCpy.call(bmi, address, bmi.length)
- bit_count = bmi[14,2].unpack('S').first # biBitCount
- compression = bmi[16,4].unpack('L').first # biCompression
- size_image = bmi[20,4].unpack('L').first # biSizeImage
- clr_used = bmi[32,4].unpack('L').first # biClrUsed
- size_image = buf_size + 16 if size_image == 0
- # Calculate the header size
- case bit_count
- when 1 then table_size = 2
- when 4 then table_size = 16
- when 8 then table_size = 256
- when 16, 32
- if compression == 0
- table_size = clr_used
- elsif compression == 3
- table_size = 3
- else
- msgbox "ERROR: invalid bit/compression combination"
- end
- when 24 then table_size = crl_used
- else
- msgbox "ERROR: invalid bit count"
- end
- offset = 0x36 + (table_size * 4)
- buf = 0.chr * buf_size
- MemCpy.call(buf, address, buf.size)
- buf = "\x42\x4D" + [size_image].pack('L') + 0.chr * 4 + [offset].pack('L') + buf
- ensure
- GlobalUnlock.call(handle)
- end
- buf
- end
- end
- #============================================================================
- # • MessageBox
- #============================================================================
- module MessageBox
- extend self
- # handle, string, title, format.
- FunctionMessageBox = Win32API.new("user32", "MessageBoxW", "lppl", "l")
- #--------------------------------------------------------------------------
- # • [Constantes] Botões:
- #--------------------------------------------------------------------------
- # Adiciona três botões a mensagem: Anular, Repetir e Ignorar.
- ABORTRETRYIGNORE = 0x00000002
- # Adiciona três botões a mensagem: Cancelar, Tentar e Continuar.
- CANCELTRYCONTINUE = 0x00000006
- # Adiciona o botão de ajuda.
- HELP = 0x00004000
- # Adiciona o botão Ok.
- OK = 0x00000000
- # Adiciona o botão OK e Cancelar.
- OKCANCEL = 0x00000001
- # Adiciona os botões: Repetir e Cancelar.
- RETRYCANCEL = 0x00000005
- # Adiciona os botões: Sim e Não
- YESNO = 0x00000004
- # Adiciona os botões: Sim, Não e Cancelar
- YESNOCANCEL = 0x00000003
- #--------------------------------------------------------------------------
- # • [Constantes] Ícones:
- #--------------------------------------------------------------------------
- # Adiciona um ícone de exclamação
- ICONEXCLAMATION = 0x00000030
- # Adiciona um ícone de informação.
- ICONINFORMATION = 0x00000040
- # Adiciona um ícone de um círculo com um ponto de interrogação.
- ICONQUESTION = 0x00000020
- # Adiciona um íconde parar na mensagem.
- ICONSTOP = 0x00000010
- #--------------------------------------------------------------------------
- # • [Constantes] Valores de retorno dos botões:
- #--------------------------------------------------------------------------
- ABORT = 3 # Retorno do valor do botão de Anular
- CANCEL = 2 # Retorno do valor do botão de Cancelar.
- CONTINUE = 11 # Retorno do valor do botão de Continuar.
- IGNORE = 5 # Retorno do valor de ignonar.
- NO = 7 # Retorno do valor do botão de Não.
- OK = 1 # Retorno do valor do botão de Ok.
- RETRY = 4 # Retorno do valor de repetir.
- TRYAGAIN = 10 # Retorno do valor de Repetir.
- YES = 6 # Retorno do valor do botão de Sim.
- #--------------------------------------------------------------------------
- # • [Constantes] Valores adicionais.
- #--------------------------------------------------------------------------
- RIGHT = 0x00080000 # Os textos ficarão justificados a direita.
- TOPMOST = 0x00040000 # O estilo da mensagem é criado como WB_EX_TOPMOST
- #--------------------------------------------------------------------------
- # • [call] : Retorna aos valores dos botões. Para serem usados
- # como condição, de que se ao clicar.
- # API::MessageBox.call(title, string, format)
- # title -> Título da caixa.
- # string -> Conteúdo da caixa.
- # format -> Formato, no caso seria os botões e ícones.
- #--------------------------------------------------------------------------
- def call(title, string, format)
- return FunctionMessageBox.call(API.hWND, API.textUTF(string), API.textUTF(title), format)
- end
- #--------------------------------------------------------------------------
- # • [messageBox] : Mesma função do Call a diferença é que e protegido.
- #--------------------------------------------------------------------------
- def messageBox(*args)
- self.call(*args)
- end
- protected :messageBox
- end
- #============================================================================
- # • Sock
- #============================================================================
- @dll = "ws2_32"
- #--------------------------------------------------------------------------
- # • [accept] : Permite uma tentativa de entrada na conexão da internet
- # atráves do socket.
- #--------------------------------------------------------------------------
- Accept = long("accept", [:SOCKET, :struct, :int], @dll)
- #--------------------------------------------------------------------------
- # • [bind] : Associa um endereço local com o socket.
- #--------------------------------------------------------------------------
- Bind = long("bind", [:SOCKET, :struct, :int], @dll)
- #--------------------------------------------------------------------------
- # • [closesocket] : Fecha uma conexão socket existente.
- #--------------------------------------------------------------------------
- CloseSocket = long("closesocket", [:SOCKET], @dll)
- #--------------------------------------------------------------------------
- # • [connect] : Estabeliza uma conexão com um socket específico.
- #--------------------------------------------------------------------------
- Connect = int("connect", [:SOCKET, :struct, :int], @dll)
- #--------------------------------------------------------------------------
- # • [gethostbyaddr] : Essa função retorna a informação do host
- # que corresponde ao endereço network.
- #--------------------------------------------------------------------------
- GetHostByAddr = long("gethostbyaddr", [:c, :int, :int], @dll)
- #--------------------------------------------------------------------------
- # • [gethostbyname] : Essa função retorna a informação do host
- # correspondente ao nome do host.
- #--------------------------------------------------------------------------
- GetHostByName = long("gethostbyname", [:c], @dll)
- #--------------------------------------------------------------------------
- # • [gethostname] : Essa função retorna ao nome do host padrão do computador
- # local.
- #--------------------------------------------------------------------------
- GetHostName = void("gethostname", [:c, :int], @dll)
- #--------------------------------------------------------------------------
- # • [getservbyname] : Essa função retorna as informações do sistema
- # correspondente ao nome do serviço é do protocolo.
- #--------------------------------------------------------------------------
- GetServByName = char("getservbyname", [:c, :c], @dll)
- protected :hwnd, :open, :function
- end
- #==============================================================================
- # • Enumerables;
- #==============================================================================
- Dax.register(:enumerables)
- module Enumerables
- #----------------------------------------------------------------------------
- # • Retorna a uma nova array com todos os resultados retirando os vazio.
- #----------------------------------------------------------------------------
- def select_map(&aProc)
- map(&aProc).reject { |e| e.nil? }
- end
- end
- #==============================================================================
- # * String
- #==============================================================================
- Dax.register(:string)
- class String
- #--------------------------------------------------------------------------
- # * [String] : converter a String em UTF8
- #--------------------------------------------------------------------------
- def to_utf8
- API.textUTF(self)
- end
- #--------------------------------------------------------------------------
- # * [String] : Extrai os números.
- #--------------------------------------------------------------------------
- def extract_numbers
- self.scan(/-*\d+/).collect{|n|n.to_i}
- end
- #----------------------------------------------------------------------------
- # • [String] : Aplicando Case Sensitive
- # "Exemplo 2" => "Exemplo_2"
- #----------------------------------------------------------------------------
- def case_sensitive
- return self.gsub(" ", "_")
- end
- #----------------------------------------------------------------------------
- # • [String] : Transormar em símbolo.
- #----------------------------------------------------------------------------
- def symbol
- return self.case_sensitive.downcase.to_sym
- end
- #----------------------------------------------------------------------------
- # • [String] : Converte para Windows Unicode
- #----------------------------------------------------------------------------
- def to_w
- (self+"\x00").encode('utf-16LE')
- end
- #----------------------------------------------------------------------------
- # • Método Xor. Realiza byte per byte. [Actor Desconhecido]
- #----------------------------------------------------------------------------
- def ^(string)
- bytes.map.with_index{|byte, index|
- byte ^ string[index % other.size].ord
- }.pack("C*")
- end
- end
- #==============================================================================
- # • DString
- #==============================================================================
- Dax.register :dstring
- module DString
- extend self
- #----------------------------------------------------------------------------
- # • [String] : Deletar a útlima letra de uma string..
- # Exemplo: DString.backslash("ok!") #=> ok
- #----------------------------------------------------------------------------
- def backslash(text)
- text2 ||= ""
- text = text.to_s.split(//)
- text[text.size-1] = "" unless text[0].to_s.empty?
- for i in 0..text.size-1
- text2 += text[i].to_s
- end
- return text2
- end
- end
- #==============================================================================
- # * Integer
- #==============================================================================
- Dax.register(:integer)
- class Integer
- #----------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Verifica-se e par.
- #----------------------------------------------------------------------------
- def is_evan?
- return (self & 1) == 0
- end
- #----------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Verifica-se e impar.
- #----------------------------------------------------------------------------
- def is_odd?
- return (self & 1) == 1
- end
- #----------------------------------------------------------------------------
- # * [Integer] : Transformar o valor em porcentagem : Útil para fazer barras
- # como por exemplo barras de HP.
- # a : Valor atual.
- # b : Valor máximo.
- #----------------------------------------------------------------------------
- def to_p(a, b)
- self * a / b
- end
- #----------------------------------------------------------------------------
- # * [Integer] : Multiplica o número pelo tamanho de uma grid.
- #----------------------------------------------------------------------------
- def grid_on(grid_size=32)
- return self * grid_size
- end
- #----------------------------------------------------------------------------
- # * [Integer] : Divide o número pelo tamanho de uma grid.
- #----------------------------------------------------------------------------
- def grid_off(grid_size=32)
- return self / grid_size
- end
- #----------------------------------------------------------------------------
- # • [Array] : Retorna aos divisores primos.
- #----------------------------------------------------------------------------
- def primeDivision
- raise ZeroDivisionError if self == 0
- ps = DMath::Prime.new
- value = self
- pv = []
- for prime in ps
- count = 0
- while (value1, mod = value.divmod(prime)
- mod) == 0
- value = value1
- count += 1
- end
- pv.push [prime, count] unless count == 0
- break if prime * prime >= value
- end
- pv.push [value, 1] if value > 1
- return pv
- end
- end
- #==============================================================================
- # * Float
- #==============================================================================
- Dax.register(:float)
- class Float
- #----------------------------------------------------------------------------
- # * [Float] : Transformar em porcentagem
- # a : Valor atual.
- # b : Valor máximo.
- #----------------------------------------------------------------------------
- def to_p(a, b)
- self * a / b
- end
- end
- #==============================================================================
- # • Crypt
- #==============================================================================
- Dax.register(:crypt)
- module Crypt
- #============================================================================
- # • Cesar : Criptográfia de Cesar.
- #============================================================================
- module Cesar
- extend self
- #--------------------------------------------------------------------------
- # • Constantes.
- #--------------------------------------------------------------------------
- AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(//)
- DC = "DEFGHIJKLMNOPQRSTUVWXYZABC".split(//)
- #--------------------------------------------------------------------------
- # • [String] : Codificar.
- # Crypt::Cesar.codify("AMA", 1) : #=> dpd
- #--------------------------------------------------------------------------
- def codify(string, ty=0)
- string = string.split(//)
- ns = ""
- dc = []
- string.each { |i|
- next dc << "" if i == ""
- next dc << " " if i == " "
- AZ.each_with_index { |v, id|
- next dc << DC[id] if i == v
- }}
- dc.size.times { |i| ns += dc[i] }
- return ty == 0 ? ns : ns.downcase!
- end
- #--------------------------------------------------------------------------
- # • [String] : Decodificar.
- # Crypt::Cesar.decodify("dpd", 0) #=> AMA
- #--------------------------------------------------------------------------
- def decodify(string, ty=0)
- string = string.split(//)
- ns = ""
- az = []
- string.each { |i|
- next az << "" if i == ""
- next az << " " if i == " "
- DC.each_with_index { |v,id|
- next az << AZ[id] if i == v
- }
- }
- az.size.times { |i| ns += az[i] }
- return ty == 0 ? ns : ns.downcase!
- end
- end
- end
- #==============================================================================
- # * Color
- #==============================================================================
- Dax.register(:color)
- class Color
- #----------------------------------------------------------------------------
- # • [Color] : Diminui a opacidade da cor, deixando-a opaca.
- # Color.new(r, g, b).opacity([alpha])
- # O valor padrão do alpha e 128.. não é preciso espeficar.
- #----------------------------------------------------------------------------
- def opacity(alpha=nil)
- self.set(self.red, self.green, self.blue, alpha || 128)
- end
- #----------------------------------------------------------------------------
- # • [Color] : Inverte as cores.
- # Color.new(r, g, b[, a).invert!
- #----------------------------------------------------------------------------
- def invert!
- self.set(255-self.red, 255-self.green, 255-self.blue, self.alpha)
- end
- #----------------------------------------------------------------------------
- # • [Color] : Reverte as cores.
- # Color.new(r, g, b[, a).revert
- #----------------------------------------------------------------------------
- def revert
- colors = [self.red, self.green, self.blue, self.alpha].reverse!
- self.set(*colors)
- end
- #----------------------------------------------------------------------------
- # • [String] : Converte para string as informações dos valores das cores.
- # Color.new(0, 0, 0).to_s
- # red: 0
- # blue: 0
- # green: 0
- # alpha: 255
- #----------------------------------------------------------------------------
- def to_s
- "red: #{self.red}\nblue: #{self.blue}\ngreen: #{self.green}\nalpha: #{self.alpha}"
- end
- #----------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Comparar cores, retorna a [true] se for igual..
- # retorna a [false] se não for igual.
- #----------------------------------------------------------------------------
- def ==(color)
- return (self.red == color.red and self.green == color.green and self.blue == color.blue and
- self.alpha == color.alpha) ? true : false
- end
- #----------------------------------------------------------------------------
- # • [Hash] : Retorna aos valores das cores em formato de Hash.
- # Color.new(0, 0, 0).to_h
- # {:red => 0, :green => 0, :blue => 0, :alpha => 255}
- #----------------------------------------------------------------------------
- def to_h
- return {
- red: self.red, green: self.green, blue: self.blue, alpha: self.alpha,
- }
- end
- #----------------------------------------------------------------------------
- # • [Array] : Retorna aos valores das cores em formato de Array.
- # Color.new(0, 0, 0).to_a
- # [0, 0, 0, 255]
- #----------------------------------------------------------------------------
- def to_a
- return [self.red, self.green, self.blue, self.alpha]
- end
- #----------------------------------------------------------------------------
- # • [Color] Soma os valores das cores com os valores de outras cores.
- # Ex: color + Color.new(21,54,255)
- #----------------------------------------------------------------------------
- def +(color)
- return unless color.is_a?(Color)
- red = self.red + color.red
- green = self.green + color.green
- blue = self.blue + color.blue
- self.set(red, green, blue)
- end
- #----------------------------------------------------------------------------
- # • [Color] Subtrai os valores das cores com os valores de outras cores.
- # Ex: color - Color.new(21,54,255)
- #----------------------------------------------------------------------------
- def -(color)
- return unless color.is_a?(Color)
- red = self.red - color.red
- green = self.green - color.green
- blue = self.blue - color.blue
- self.set(red, green, blue)
- end
- #----------------------------------------------------------------------------
- # • [Color] Multiplica os valores das cores com os valores de outras cores.
- # Ex: color * Color.new(21,54,255)
- #----------------------------------------------------------------------------
- def *(color)
- return unless color.is_a?(Color)
- red = (self.red * color.red) / 255.0
- green = (self.green * color.green) / 255.0
- blue = (self.blue * color.blue) / 255.0
- self.set(red, green, blue)
- end
- #----------------------------------------------------------------------------
- # • Métodos Privados.
- #----------------------------------------------------------------------------
- private
- def max
- [red, green, blue].max
- end
- def min
- [red, green, blue].min
- end
- end
- #==============================================================================
- # * ColorBasic
- #==============================================================================
- Dax.register(:colorbasic)
- module ColorBasic
- extend self
- #----------------------------------------------------------------------------
- # • [Color] : Cores no formato de hexadécimal.
- # * ColorBasic.hex("ffffff") #=> 255, 255, 255 | Branco.
- #----------------------------------------------------------------------------
- def hex(color)
- Color.new(*color.scan(/../).map { |color| color.to_i(16)})
- end
- #----------------------------------------------------------------------------
- # • [Color] : Cores do índice. Veja abaixo.
- #----------------------------------------------------------------------------
- def [](id)
- case id
- when -1 then Color.new(255, 255, 255) # White
- when 0 then Color.new(240, 248, 255) # Alice Blue
- when 1 then Color.new(250, 235, 215) # Antique_White
- when 2 then Color.new(0, 255, 255) # Aqua
- when 3 then Color.new(127, 255, 255) # Aqua Marine
- when 4 then Color.new(240, 255, 255) # Azure
- when 5 then Color.new(245, 245, 220) # Beige
- when 6 then Color.new(255, 228, 196) # Bisque
- when 7 then Color.new(0, 0, 0) # Black
- when 8 then Color.new(255, 235, 205) # Blanchedalmond
- when 9 then Color.new(0, 0, 255) # Blue
- when 10 then Color.new(138, 43, 226) # Blue Violet
- when 11 then Color.new(165, 42, 42) # Brown
- when 12 then Color.new(222, 184, 135) # Burly Wood
- when 13 then Color.new(93, 158, 160) # Cadet Blue
- when 14 then Color.new(127, 255, 0) # Chatreuse
- when 15 then Color.new(210, 105, 30) # Chocolate
- when 16 then Color.new(255, 127, 80) # Coral
- when 17 then Color.new(100, 149, 237) # Corn Flower Blue
- when 18 then Color.new(255, 248, 220) # CornSilk
- when 19 then Color.new(220, 20, 60) # Crimson
- when 20 then Color.new(0, 255, 255) # Cyan
- when 21 then Color.new(0, 0, 139) # DarkBlue
- when 22 then Color.new(0, 139, 139) # DarkCyan
- when 23 then Color.new(184, 134, 11) # DarkGoldEnrod
- when 24 then Color.new(169, 169, 169) # Dark Gray
- when 25 then Color.new(0, 100, 0) # Dark Green
- when 26 then Color.new(189, 183, 107) # Dark Khaki
- when 27 then Color.new(139, 0, 139) # Dark Magenta
- when 28 then Color.new(85, 107, 47) # Dark Oliver Green
- when 29 then Color.new(255, 140, 0) # Dark Orange
- when 30 then Color.new(153, 50, 204) # Dark orchid
- when 31 then Color.new(139, 0, 0) # Dark Red
- when 32 then Color.new(233, 150, 120) # Dark Salmon
- when 33 then Color.new(143, 188, 143) # Dark Sea Green
- when 34 then Color.new(72, 61, 139) # Dark Slate Blue
- when 35 then Color.new(255, 255, 0) # Yellow
- when 36 then Color.new(255, 0, 0) # Red
- when 37 then Color.new(0, 255, 0) # Green
- when 38 then Color.new(255, 128, 0) # Orange
- else
- self.default
- end
- end
- #----------------------------------------------------------------------------
- # • [Color] : Cor padrão.
- #----------------------------------------------------------------------------
- def default
- return self.hex "ffffff"
- end
- #----------------------------------------------------------------------------
- # • [Color] : Retorna a uma cor padrão.
- #----------------------------------------------------------------------------
- def rand
- Color.new(rand(256), rand(256), rand(256))
- end
- end
- #==============================================================================
- # • Rect
- #==============================================================================
- Dax.register(:rect)
- class Rect
- #----------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Verificar se está na área.
- #----------------------------------------------------------------------------
- def in?(x, y)
- x.between?(self.x, self.x + self.width) &&
- y.between?(self.y, self.y + self.height)
- end
- #----------------------------------------------------------------------------
- # • [NilClass] : Cada elemento em um bloco.
- # rect.each { |x, y, w, h| }
- #----------------------------------------------------------------------------
- def each
- yield(self.x, self.y, self.width, self.height)
- return nil
- end
- end
- #==============================================================================
- # • DMath
- #==============================================================================
- Dax.register(:dmath, 'Dax', 1.5, '04/05/13')
- module DMath
- extend self
- #----------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Clamp | Delimitar o inteiro
- # num : Número.
- # low : Número minímo. Sê o 'num' for menor que min retorna a low.
- # high : Número máximo. Sê o 'num' for maior que hight retorna a high.
- #----------------------------------------------------------------------------
- def clamp(num, low, high)
- return num < low ? low : num > high ? high : low
- end
- #----------------------------------------------------------------------------
- # • [Array] : Centralizar um objeto n'outro.
- # object : Objeto, tem que ser do tipo [Sprite] ou [Window_Base]
- # object_for_centralize : Objeto que irá se centralizar no 'object', tem
- # que ser do tipo [Sprite] ou [Window_Base]
- # * Retorna a uma Array contendo as informações das novas posições em X e Y.
- #----------------------------------------------------------------------------
- def centralize_object(object, object_for_centralize)
- x = object.x + (object.width - object_for_centralize.width) / 2
- y = object.y + (object.height - object_for_centralize.height) / 2
- return x, y
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição X.
- # objectx : Valor da posição X do objeto número 1.
- # objectwidth : Valor da largura do objeto número 1.
- # object_for_centralizewidth : Valor da largura do objeto que irá se
- # centralizar no objeto número 1.
- # * Retorna ao valor da posição X.
- #----------------------------------------------------------------------------
- def centralize_x(objectx, objectwidth, object_for_centralizewidth)
- return objectx + (objectwidth - object_for_centralizewidth) / 2
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição Y.
- # objecty : Valor da posição Y do objeto número 1.
- # objectheight : Valor da altura do objeto número 1.
- # object_for_centralizeheight : Valor da altura do objeto que irá se
- # centralizar no objeto número 1.
- # * Retorna ao valor da posição Y.
- #----------------------------------------------------------------------------
- def centralize_y(objecty, objectheight, object_for_centralizeheight)
- return objecty + (objectheight - object_for_centralizeheight) / 2
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Obter a posição X do centro da tela referente a largura do objeto X.
- # Exemplo: get_x_center_screen(sprite.width) : Irá retornar ao valor da posição
- # X para que o objeto fique no centro da tela.
- # Exemplo: sprite.x = get_x_center_screen(sprite.width)
- #----------------------------------------------------------------------------
- def get_x_center_screen(width)
- return (Graphics.width - width) / 2
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Obter a posição Y do centro da tela referente a altura do objeto X.
- # Exemplo: get_y_center_screen(sprite.height) : Irá retornar ao valor da posição
- # Y para que o objeto fique no centro da tela.
- # Exemplo: sprite.y = get_y_center_screen(sprite.height)
- #----------------------------------------------------------------------------
- def get_y_center_screen(height)
- return (Graphics.height - height) / 2
- end
- #--------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Verifica se um objeto está na área de um círculo.
- # object : Objeto do tipo da classe [Sprite].
- # object2 : Objeto do tipo da classe [Sprite].
- # size : Tamanho geral do círculo.
- #--------------------------------------------------------------------------
- def circle(object, object2, size)
- ( (object.x - object2.x) ** 2) + ( (object.y - object2.y) ** 2) <= (size ** 2)
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Converter o valor em graus.
- #----------------------------------------------------------------------------
- def graus
- 360 / (2 * Math::PI)
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Converte o valor em radiano.
- #----------------------------------------------------------------------------
- def radian(degree)
- return (degree.to_f/180) * Math::PI
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Converte o valor em grau.
- #----------------------------------------------------------------------------
- def degree(radian)
- return (radian.to_f/Math::PI) * 180
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Para 4 decimals.
- #----------------------------------------------------------------------------
- def to_4_dec(n)
- ((n * 1000).ceil) / 1000
- end
- #----------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Verifica se está na área de um triângulo.
- #----------------------------------------------------------------------------
- def triangle_area(*args)
- x, y, x2, y2, x3, y3 = *args
- return (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y)
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Método para calcular a distância de um objeto para com outro.
- #----------------------------------------------------------------------------
- def distance_sensor(target, target2)
- return (target.x - target2.x).abs + (target.y - target2.y).abs
- end
- #============================================================================
- # • Prime
- #============================================================================
- class Prime
- #--------------------------------------------------------------------------
- # • Variáveis públicas
- #--------------------------------------------------------------------------
- attr_accessor :primes, :counts
- #--------------------------------------------------------------------------
- # • Incluir
- #--------------------------------------------------------------------------
- include Enumerables
- #--------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #--------------------------------------------------------------------------
- def initialize
- @seed ||= 1
- @primes ||= []
- @counts ||= []
- end
- #--------------------------------------------------------------------------
- # • Succ
- #--------------------------------------------------------------------------
- def succ
- i = -1
- size = @primes.size
- while i < size
- if i == -1
- @seed += 1
- i += 1
- else
- while @seed > @counts[i]
- @counts[i] += @primes[i]
- end
- i = @seed != @counts[i] ? i + 1 : -1
- end
- end
- @primes.push @seed
- @counts.push @seed + @seed
- return @seed
- end
- alias next succ
- #--------------------------------------------------------------------------
- # • Cada elemento
- #--------------------------------------------------------------------------
- def each
- loop { yield succ }
- end
- end
- #----------------------------------------------------------------------------
- # • Dentro do círculo.
- #----------------------------------------------------------------------------
- def circle_in(t, b, c, d)
- return -c * (Math.sqrt(1 - (t /= d.to_f) * t) - 1) + b
- end
- #----------------------------------------------------------------------------
- # • Fora do círculo
- #----------------------------------------------------------------------------
- def circle_out(t, b, c, d)
- return c * Math.sqrt(1 - (t=t/d.to_f-1)*t) + b
- end
- def force_range(v, min, max)
- [[min, v].max, max].min
- end
- end
- #==============================================================================
- # • Keyboard | Método para usar todas as teclas do teclado.
- #==============================================================================
- Dax.register(:key, "Dax", 1.0)
- module Key
- extend self
- #--------------------------------------------------------------------------
- # * Chaves diversos.
- #--------------------------------------------------------------------------
- CANCEL = 0x03 # Control-Break Processing
- BACKSPACE = 0x08 # Backspace Key
- TAB = 0x09 # Tab Key
- CLEAR = 0x0C # Clear Key
- ENTER = 0x0D # Enter Key
- SHIFT = 0x10 # Shift Key
- CONTROL = 0x11 # Ctrl Key
- MENU = 0x12 # Alt Key
- PAUSE = 0x13 # Pause Key
- ESC = 0x1B # Esc Key
- CONVERT = 0x1C # IME Convert Key
- NONCONVERT = 0x1D # IME Nonconvert Key
- ACCEPT = 0x1E # IME Accept Key
- SPACE = 0x20 # Space Bar Key (Space, usually blank)
- PRIOR = 0x21 # Page Up Key
- NEXT = 0x22 # Page Down Key
- ENDS = 0x23 # End Key
- HOME = 0x24 # Home Key
- LEFT = 0x25 # Left Arrow Key
- UP = 0x26 # Up Arrow Key
- RIGHT = 0x27 # Right Arrow Key
- DOWN = 0x28 # Down Arrow Key
- SELECT = 0x29 # Select Key
- PRINT = 0x2A # Print Key
- EXECUTE = 0x2B # Execute Key
- SNAPSHOT = 0x2C # Print Screen Key
- DELETE = 0x2E # Delete Key
- HELP = 0x2F # Help Key
- LSHIFT = 0xA0 # Left Shift Key
- RSHIFT = 0xA1 # Right Shift Key
- LCONTROL = 0xA2 # Left Control Key (Ctrl)
- RCONTROL = 0xA3 # Right Control Key (Ctrl)
- LMENU = 0xA4 # Left Menu Key (Alt)
- RMENU = 0xA5 # Right Menu Key (Alt)
- PACKET = 0xE7 # Used to Pass Unicode Characters as Keystrokes
- MOUSE_RIGHT = 0x01 # Button Mouse Right
- MOUSE_LEFT = 0x02 # Button Mouse Left
- MOUSE_MIDDLE = 0x04 # Button Mouse Middle
- #--------------------------------------------------------------------------
- # * Chaves de números.
- #--------------------------------------------------------------------------
- N0 = 0x30 # 0 Key
- N1 = 0x31 # 1 Key
- N2 = 0x32 # 2 Key
- N3 = 0x33 # 3 Key
- N4 = 0x34 # 4 Key
- N5 = 0x35 # 5 Key
- N6 = 0x36 # 6 Key
- N7 = 0x37 # 7 Key
- N8 = 0x38 # 8 Key
- N9 = 0x39 # 9 Key
- #--------------------------------------------------------------------------
- # * Chaves de letras
- #--------------------------------------------------------------------------
- A = 0x41 # A Key
- B = 0x42 # B Key
- C = 0x43 # C Key
- D = 0x44 # D Key
- E = 0x45 # E Key
- F = 0x46 # F Key
- G = 0x47 # G Key
- H = 0x48 # H Key
- I = 0x49 # I Key
- J = 0x4A # J Key
- K = 0x4B # K Key
- L = 0x4C # L Key
- M = 0x4D # M Key
- N = 0x4E # N Key
- O = 0x4F # O Key
- P = 0x50 # P Key
- Q = 0x51 # Q Key
- R = 0x52 # R Key
- S = 0x53 # S Key
- T = 0x54 # T Key
- U = 0x55 # U Key
- V = 0x56 # V Key
- W = 0x57 # W Key
- X = 0x58 # X Key
- Y = 0x59 # Y Key
- Z = 0x5A # Z Key
- #--------------------------------------------------------------------------
- # * Chaves de windows
- #--------------------------------------------------------------------------
- LWIN = 0x5B # Left Windows Key (Natural keyboard)
- RWIN = 0x5C # Right Windows Key (Natural Keyboard)
- APPS = 0x5D # Applications Key (Natural keyboard)
- SLEEP = 0x5F # Computer Sleep Key
- BROWSER_BACK = 0xA6 # Browser Back Key
- BROWSER_FORWARD = 0xA7 # Browser Forward Key
- BROWSER_REFRESH = 0xA8 # Browser Refresh Key
- BROWSER_STOP = 0xA9 # Browser Stop Key
- BROWSER_SEARCH = 0xAA # Browser Search Key
- BROWSER_FAVORITES = 0xAB # Browser Favorites Key
- BROWSER_HOME = 0xAC # Browser Start and Home Key
- VOLUME_MUTE = 0xAD # Volume Mute Key
- VOLUME_DOWN = 0xAE # Volume Down Key
- VOLUME_UP = 0xAF # Volume Up Key
- MEDIA_NEXT_TRACK = 0xB0 # Next Track Key
- MEDIA_PREV_TRACK = 0xB1 # Previous Track Key
- MEDIA_STOP = 0xB2 # Stop Media Key
- MEDIA_PLAY_PAUSE = 0xB3 # Play/Pause Media Key
- LAUNCH_MAIL = 0xB4 # Start Mail Key
- LAUNCH_MEDIA_SELECT = 0xB5 # Select Media Key
- LAUNCH_APP1 = 0xB6 # Start Application 1 Key
- LAUNCH_APP2 = 0xB7 # Start Application 2 Key
- PROCESSKEY = 0xE5 # IME Process Key
- ATTN = 0xF6 # Attn Key
- CRSEL = 0xF7 # CrSel Key
- EXSEL = 0xF8 # ExSel Key
- EREOF = 0xF9 # Erase EOF Key
- PLAY = 0xFA # Play Key
- ZOOM = 0xFB # Zoom Key
- PA1 = 0xFD # PA1 Key
- #--------------------------------------------------------------------------
- # * Chaves do Numpad
- #--------------------------------------------------------------------------
- NUMPAD0 = 0x60 # Numeric Keypad 0 Key
- NUMPAD1 = 0x61 # Numeric Keypad 1 Key
- NUMPAD2 = 0x62 # Numeric Keypad 2 Key
- NUMPAD3 = 0x63 # Numeric Keypad 3 Key
- NUMPAD4 = 0x64 # Numeric Keypad 4 Key
- NUMPAD5 = 0x65 # Numeric Keypad 5 Key
- NUMPAD6 = 0x66 # Numeric Keypad 6 Key
- NUMPAD7 = 0x67 # Numeric Keypad 7 Key
- NUMPAD8 = 0x68 # Numeric Keypad 8 Key
- NUMPAD9 = 0x69 # Numeric Keypad 9 Key
- MULTIPLY = 0x6A # Multiply Key (*)
- ADD = 0x6B # Add Key (+)
- SEPARATOR = 0x6C # Separator Key
- SUBTRACT = 0x6D # Subtract Key (-)
- DECIMAL = 0x6E # Decimal Key (.)
- DIVIDE = 0x6F # Divide Key (/)
- #--------------------------------------------------------------------------
- # * Chaves de funções
- #--------------------------------------------------------------------------
- F1 = 0x70 # F1 Key
- F2 = 0x71 # F2 Key
- F3 = 0x72 # F3 Key
- F4 = 0x73 # F4 Key
- F5 = 0x74 # F5 Key
- F6 = 0x75 # F6 Key
- F7 = 0x76 # F7 Key
- F8 = 0x77 # F8 Key
- F9 = 0x78 # F9 Key
- F10 = 0x79 # F10 Key
- F11 = 0x7A # F11 Key
- F12 = 0x7B # F12 Key
- F13 = 0x7C # F13 Key
- F14 = 0x7D # F14 Key
- F15 = 0x7E # F15 Key
- F16 = 0x7F # F16 Key
- F17 = 0x80 # F17 Key
- F18 = 0x81 # F18 Key
- F19 = 0x82 # F19 Key
- F20 = 0x83 # F20 Key
- F21 = 0x84 # F21 Key
- F22 = 0x85 # F22 Key
- F23 = 0x86 # F23 Key
- F24 = 0x87 # F24 Key
- #--------------------------------------------------------------------------
- # * Chaves alternativas
- #--------------------------------------------------------------------------
- CAPITAL = 0x14 # Caps Lock Key
- KANA = 0x15 # IME Kana Mode Key
- HANGUL = 0x15 # IME Hangul Mode Key
- JUNJA = 0x17 # IME Junja Mode Key
- FINAL = 0x18 # IME Final Mode Key
- HANJA = 0x19 # IME Hanja Mode Key
- KANJI = 0x19 # IME Kanji Mode Key
- MODECHANGE = 0x1F # IME Mode Change Request Key
- INSERT = 0x2D # Insert Key
- NUMLOCK = 0x90 # Num Lock Key
- SCROLL = 0x91 # Scroll Lock Key
- #--------------------------------------------------------------------------
- # * Chaves OEM, variadas
- #--------------------------------------------------------------------------
- OEM_1 = 0xBA # Misc Characters (; : in USA 101/102 Keyboards)
- OEM_PLUS = 0xBB # + = Key
- OEM_COMMA = 0xBC # , < Key
- OEM_MINUS = 0xBD # - _ Key
- OEM_PERIOD = 0xBE # . > Key
- OEM_2 = 0xBF # Misc Characters (/ ? in USA 101/102 Keyboards)
- OEM_3 = 0xC0 # Misc Characters (` ~ in USA 101/102 Keyboards)
- OEM_4 = 0xDB # Misc Characters ([ { in USA 101/102 Keyboards)
- OEM_5 = 0xDC # Misc Characters (\ | in USA 101/102 Keyboards)
- OEM_6 = 0xDD # Misc Characters (] } in USA 101/102 Keyboards)
- OEM_7 = 0xDE # Misc Characters (' " in USA 101/102 Keyboards)
- OEM_8 = 0xDF # Misc Characters (Varies by Keyboard)
- OEM_9 = 0xE1 # OEM Specific
- OEM_10 = 0x92 # OEM Specific
- OEM_11 = 0x93 # OEM Specific
- OEM_12 = 0x94 # OEM Specific
- OEM_13 = 0x95 # OEM Specific
- OEM_14 = 0x96 # OEM Specific
- OEM_15 = 0xE3 # OEM Specific
- OEM_16 = 0xE4 # OEM Specific
- OEM_17 = 0xE6 # OEM Specific
- OEM_18 = 0xE9 # OEM Specific
- OEM_19 = 0xEA # OEM Specific
- OEM_20 = 0xEB # OEM Specific
- OEM_21 = 0xEC # OEM Specific
- OEM_22 = 0xED # OEM Specific
- OEM_23 = 0xEE # OEM Specific
- OEM_24 = 0xEF # OEM Specific
- OEM_25 = 0xF1 # OEM Specific
- OEM_26 = 0xF2 # OEM Specific
- OEM_27 = 0xF3 # OEM Specific
- OEM_28 = 0xF4 # OEM Specific
- OEM_29 = 0xF5 # OEM Specific
- OEM_102 = 0xE2 # Angle Bracket or Backslash on RT-102 Keyboards
- OEM_CLEAR = 0xFE # Clear Key
- #--------------------------------------------------------------------------
- # * Variáveis do módulo.
- #--------------------------------------------------------------------------
- @unpack_string = 'b'*256
- @last_array = '0'*256
- @press = Array.new(256, false)
- @trigger = Array.new(256, false)
- @repeat = Array.new(256, false)
- @release = Array.new(256, false)
- @repeat_counter = Array.new(256, 0)
- @getKeyboardState = API::GetKeyboardState
- @getAsyncKeyState = API::GetAsyncKeyState
- @getKeyboardState.call(@last_array)
- @last_array = @last_array.unpack(@unpack_string)
- for i in 0...@last_array.size
- @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
- end
- #--------------------------------------------------------------------------
- # * Atualização dos objetos do módulo.
- #--------------------------------------------------------------------------
- def update
- @trigger = Array.new(256, false)
- @repeat = Array.new(256, false)
- @release = Array.new(256, false)
- array = '0'*256
- @getKeyboardState.call(array)
- array = array.unpack(@unpack_string)
- for i in 0...array.size
- if array[i] != @last_array[i]
- @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
- if @repeat_counter[i] <= 0 && @press[i]
- @repeat[i] = true
- @repeat_counter[i] = 15
- end
- if !@press[i]
- @release[i] = true
- else
- @trigger[i] = true
- end
- else
- if @press[i] == true
- @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
- @release[i] = true if !@press[i]
- end
- if @repeat_counter[i] > 0 && @press[i] == true
- @repeat_counter[i] -= 1
- elsif @repeat_counter[i] <= 0 && @press[i] == true
- @repeat[i] = true
- @repeat_counter[i] = 3
- elsif @repeat_counter[i] != 0
- @repeat_counter[i] = 0
- end
- end
- end
- @last_array = array
- end
- #--------------------------------------------------------------------------
- # * Get Key Pressed State
- # key : key index
- #--------------------------------------------------------------------------
- def press?(key)
- return @press[key]
- end
- #--------------------------------------------------------------------------
- # * Get Key Triggered State
- # key : key index
- #--------------------------------------------------------------------------
- def trigger?(key)
- return @trigger[key]
- end
- #--------------------------------------------------------------------------
- # * Get Key Repeated State
- # key : key index
- #--------------------------------------------------------------------------
- def repeat?(key)
- return @repeat[key]
- end
- #--------------------------------------------------------------------------
- # * Get Key Released State
- # key : key index
- #--------------------------------------------------------------------------
- def release?(key)
- return @release[key]
- end
- #----------------------------------------------------------------------------
- # • CONSTANTES.
- #----------------------------------------------------------------------------
- AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(//)
- @az = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".downcase!.split(//)
- NUM = "0123456789".split(//)
- @@string_char = @@string_num = @@string_az = ""
- @@string = ""
- #----------------------------------------------------------------------------
- # • [String] : Retornar a String correspondente a tecla pressionada dos números.
- #----------------------------------------------------------------------------
- def stringNUM(input='trigger?')
- n = "N0,N1,N2,N3,N4,N5,N6,N7,N8,N9".split(',')
- numpad = "NUMPAD0,NUMPAD1,NUMPAD2,NUMPAD3,NUMPAD4,NUMPAD5,NUMPAD6,NUMPAD7,NUMPAD8,NUMPAD9".split(',')
- n.each_with_index { |v,i| eval("return NUM[i] if #{input}(#{v})") }
- numpad.each_with_index { |v,i| eval("return NUM[i] if #{input}(#{v})") }
- return ""
- end
- #----------------------------------------------------------------------------
- # • [String] : Retorar a String correspondente a tecla pressionada dos alfabeto
- #----------------------------------------------------------------------------
- def stringAZ(input='trigger?')
- if API.get_caps_lock
- AZ.each_with_index { |v,i| eval("return AZ[i] if #{input}(#{v})") }
- else
- AZ.each_with_index { |v,i| eval("return @az[i] if #{input}(#{v})") }
- end
- return ""
- end
- #----------------------------------------------------------------------------
- # • [String] : Obter a String das teclas. [ Retorna a variável @@string ]
- #----------------------------------------------------------------------------
- def string(input='trigger?')
- @@string_num = self.stringNUM(input)
- @@string_az = self.stringAZ(input)
- @@string = @@string_num + @@string_az
- @@string += " " if trigger?(SPACE)
- return @@string
- end
- end
- #==============================================================================
- # • Sprite
- #==============================================================================
- Dax.register(:sprite)
- class Sprite
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância.
- #----------------------------------------------------------------------------
- attr_accessor :clone_sprite
- #----------------------------------------------------------------------------
- # • Novo método. Modos de usos abaixo:
- # * [normal] : É o método normal, na qual você não define nada. Sprite.new
- # * [viewport] : É o método na qual você define um viewport.
- # Sprite.new(Viewport)
- # * [system] : É o método na qual você já define um bitmap que irá carregar
- # uma imagem já direto da pasta System, através do Cache.
- # Sprite.new("S: Nome do Arquivo")
- # * [picture] : É o método na qual você já define um bitmap que irá carregar
- # uma imagem já direito da pasta Pictures, através do Cache.
- # Sprite.new("P: Nome do Arquivo")
- # * [graphics] : É o método na qual você já define um bitmap com uma imagem
- # que está dentro da pasta Graphics, através do Cache.
- # Sprite.new("G: Nome do Arquivo.")
- # * [width, height] : É o método na qual você já define a largura e altura
- # do bitmap. Sprite.new([width, height])
- # * [elements] : É o método na qual você já define a largura, altura,
- # posição X, posição Y e Prioridade do bitmap.
- # Sprite.new([width, height, x, y, z])
- #----------------------------------------------------------------------------
- alias new_initialize initialize
- def initialize(viewport=nil)
- @clone_sprite = []
- if viewport.is_a?(String)
- new_initialize(nil)
- if viewport.match(/S: ([^>]*)/)
- self.bitmap = Cache.system($1.to_s)
- elsif viewport.match(/P: ([^>]*)/)
- self.bitmap = Cache.picture($1.to_s)
- elsif viewport.match(/G: ([^>]*)/)
- self.bitmap = Cache.load_bitmap("Graphics/", $1.to_s)
- else
- self.bitmap = Bitmap.new(viewport)
- end
- elsif viewport.is_a?(Array)
- if viewport.size == 2
- new_initialize(nil)
- self.bitmap = Bitmap.new(viewport[0], viewport[1])
- elsif viewport.size == 5
- new_initialize(nil)
- self.bitmap = Bitmap.new(viewport[0], viewport[1])
- self.x, self.y, self.z = viewport[2], viewport[3], viewport[4]
- end
- elsif viewport.is_a?(Viewport) or viewport.nil?
- new_initialize(viewport)
- end
- end
- #----------------------------------------------------------------------------
- # • Slide pela direita.
- # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
- #----------------------------------------------------------------------------
- def slide_right(speed, point)
- self.x += speed unless self.x >= point
- end
- #----------------------------------------------------------------------------
- # • Slide pela esquerda.
- # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
- #----------------------------------------------------------------------------
- def slide_left(speed, point)
- self.x -= speed unless self.x <= point
- end
- #----------------------------------------------------------------------------
- # • Slide por cima.
- # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
- #----------------------------------------------------------------------------
- def slide_up(speed, point)
- self.y -= speed unless self.y <= point
- end
- #----------------------------------------------------------------------------
- # • Slide por baixo.
- # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
- #----------------------------------------------------------------------------
- def slide_down(speed, point)
- self.y += speed unless self.y >= point
- end
- #----------------------------------------------------------------------------
- # • Define aqui uma posição fixa para um objeto.
- # command : Retorna a uma base padrão.
- #----------------------------------------------------------------------------
- def position(command=0)
- return if command.nil?
- case command
- # Imagem ficará no canto esquerdo superior. Posição X
- when 0 then self.x = 0
- # A posição X ficará no centro da tela.
- when 1 then self.x = DMath.get_x_center_screen(self.width)
- # A posição X ficará no canto direito superior.
- when 2 then self.x = Graphics.width - self.width
- # A posição Y ficará no canto esquerdo inferior.
- when 3 then self.y = 0
- # Posicionar o Y para ficar no centro.
- when 4 then self.y = DMath.get_y_center_screen(self.height)
- # Posicionar o Y para ficar no fundo da tela.
- when 5 then self.y = Graphics.height - self.height
- # Posicionar a imagem no centro da tela.
- when :center
- self.x = (Graphics.width - self.width) / 2
- self.y = Graphics.height / 2 - self.height / 2
- # Posicionar no centro esquerdo da tela.
- when :center_left
- self.x = 0
- self.y = (Graphics.height - self.height) / 2
- # Posicionar no centro direito da tela.
- when :center_right
- self.x = Graphics.width - self.height
- self.y = (Graphics.height - self.height) / 2
- end
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Tamanho geral
- #----------------------------------------------------------------------------
- def size
- return self.width + self.height
- end
- #----------------------------------------------------------------------------
- # • [Rect] : Retorna ao Rect do Bitmap.
- #----------------------------------------------------------------------------
- def rect
- return self.bitmap.rect
- end
- #----------------------------------------------------------------------------
- # • Base para clonar um Sprite.
- # * depht : Prioridade no mapa.
- # * clone_bitmap : Se irá clonar o bitmap.
- # Exemplo: sprite = sprite2.clone
- #----------------------------------------------------------------------------
- def clone(depht=0, clone_bitmap=false)
- @clone_sprite.delete_if { |bitmap| bitmap.disposed? }
- cloned = Sprite.new(self.viewport)
- cloned.x, cloned.y = self.x, self.y
- cloned.bitmap = self.bitmap
- cloned.bitmap = self.bitmap.clone if clone_bitmap
- unless depht == 0
- cloned.z = self.z + depht
- else
- @clone_sprite.each { |sprite| sprite.z -= 1 }
- cloned.z = self.z - 1
- end
- cloned.src_rect.set(self.src_rect)
- ["zoom_x", "zoom_y", "angle", "mirror", "opacity", "blend_type", "visible",
- "ox", "oy"].each { |meth|
- eval("cloned.#{meth} = self.#{meth}")
- }
- cloned.color.set(color)
- cloned.tone.set(tone)
- after_clone(cloned)
- @clone_sprite.push(cloned)
- return cloned
- end
- #----------------------------------------------------------------------------
- # • Efeito após ter clonado o Sprite.
- #----------------------------------------------------------------------------
- def after_clone(clone)
- end
- #----------------------------------------------------------------------------
- # • O que irá acontecer sê o mouse estiver em cima do sprite?
- #----------------------------------------------------------------------------
- def mouse_over
- end
- #----------------------------------------------------------------------------
- # • O que irá acontecer sê o mouse não estiver em cima do sprite?
- #----------------------------------------------------------------------------
- def mouse_no_over
- end
- #----------------------------------------------------------------------------
- # • O que irá acontecer sê o mouse clicar no objeto
- #----------------------------------------------------------------------------
- def mouse_click
- end
- #----------------------------------------------------------------------------
- # • Atualização dos sprites.
- #----------------------------------------------------------------------------
- alias :dax_update :update
- def update(*args, &block)
- dax_update(*args, &block)
- unless Mouse.cursor.nil?
- self.if_mouse_over { |over| over ? mouse_over : mouse_no_over }
- self.if_mouse_click { mouse_click }
- end
- end
- #----------------------------------------------------------------------------
- # • Inverter o lado do sprite.
- #----------------------------------------------------------------------------
- def invert!
- self.mirror = self.mirror ? false : true
- end
- end
- #==============================================================================
- # • Bitmap
- #==============================================================================
- Dax.register(:bitmap)
- class Bitmap
- #----------------------------------------------------------------------------
- # • Criar uma barra.
- # color : Objeto de Cor [Color]
- # actual : Valor atual da barra.
- # max : Valor máximo da barra.
- # borda : Tamanho da borda da barra.
- #----------------------------------------------------------------------------
- def bar(color, actual, max, borda=1)
- rate = self.width.to_p(actual, max)
- self.fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
- color)
- end
- #----------------------------------------------------------------------------
- # • Barra em forma de gradient.
- # color : Objeto de Cor, em forma de [Array] para conter 2 [Color]
- # exemplo -> [Color.new(x), Color.new(y)]
- # actual : Valor atual da barra.
- # max : Valor máximo da barra.
- # borda : Tamanho da borda da barra.
- #----------------------------------------------------------------------------
- def gradient_bar(color, actual, max, borda=1)
- rate = self.width.to_p(actual, max)
- self.gradient_fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
- color[0], color[1], 2)
- end
- #--------------------------------------------------------------------------
- # * Desenho do gráfico do personagem
- # character_name : nome do gráfico do personagem
- # character_index : índice do gráfico de personagem
- # x : coordenada X
- # y : coordenada Y
- #--------------------------------------------------------------------------
- def draw_character(character_name, character_index, x, y)
- return unless character_name
- bitmap = Cache.character(character_name)
- sign = character_name[/^[\!\$]./]
- if sign && sign.include?('$')
- cw = bitmap.width / 3
- ch = bitmap.height / 4
- else
- cw = bitmap.width / 12
- ch = bitmap.height / 8
- end
- n = character_index
- src_rect = Rect.new((n%4*3+1)*cw, (n/4*4)*ch, cw, ch)
- self.blt(x - cw / 2, y - ch, bitmap, src_rect)
- end
- #--------------------------------------------------------------------------
- # * Desenho do gráfico de personagem do herói
- # actor : herói
- # x : coordenada X
- # y : coordenada Y
- #--------------------------------------------------------------------------
- def draw_actor_graphic(actor, x, y)
- draw_character(actor.character_name, actor.character_index, x, y)
- end
- #----------------------------------------------------------------------------
- # • Limpar uma área num formato de um círculo.
- #----------------------------------------------------------------------------
- def clear_rect_circle(x, y, r)
- rr = r*r
- for i in 0...r
- adj = Math.sqrt(rr - (i*i)).ceil
- xd = x - adj
- wd = 2 * adj
- self.clear_rect(xd, y-i, wd, 1)
- self.clear_rect(xd, y+i, wd, 1)
- end
- end
- #----------------------------------------------------------------------------
- # • Novo modo de desenhar textos. Configurações já especificadas.
- #----------------------------------------------------------------------------
- def draw_text_rect(*args)
- self.draw_text(self.rect, *args)
- end
- #----------------------------------------------------------------------------
- # • Salvar em png.
- # --- Autor : Gab! ---
- #----------------------------------------------------------------------------
- def save(file_name)
- def chunk(type, data)
- [data.size, type, data, Zlib.crc32(type + data)].pack("NA4A*N")
- end
- img_data = ""
- width, height = self.width, self.height
- for j in 0...(height)
- img_data << "\0"
- for i in 0...(width)
- pos_c = self.get_pixel(i, j)
- img_data << [pos_c.red, pos_c.green, pos_c.blue, pos_c.alpha].pack("C*")
- end
- end
- c = [
- "\x89PNG\r\n\x1a\n",
- chunk("IHDR", [width, height, 8, 6, 0, 0, 0].pack("N2C5")),
- chunk("IDAT", Zlib::Deflate.deflate(img_data)),
- chunk("IEND", "")
- ]
- File.open(file_name << ".png", "wb"){|file| c.each{|chunk| file.write(chunk) }}
- end
- #----------------------------------------------------------------------------
- # • Modificar as cores do [Bitmap] para ficarem Negativas.
- #----------------------------------------------------------------------------
- def negative
- for i in 0...(self.width)
- for j in 0...(self.height)
- pix = self.get_pixel(i, j)
- pix.red = (pix.red - 255) * -1
- pix.blue = (pix.blue - 255) * -1
- pix.green = (pix.green - 255) * -1
- self.set_pixel(i, j, pix)
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Grayscale : Modificar as cores do [Bitmap] para cor cinza.
- #----------------------------------------------------------------------------
- def grayscale(rect = Rect.new(0, 0, self.width, self.height))
- for i in rect.x...rect.x + rect.width
- for j in rect.y...rect.y + rect.height
- colour = self.get_pixel(i,j)
- grey_pixel = (colour.red*0.3 + colour.green*0.59 + colour.blue*0.11)
- colour.red = colour.green = colour.blue = grey_pixel
- self.set_pixel(i,j,colour)
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Novo fornecedor de pixel.
- #----------------------------------------------------------------------------
- def set_pixel_s(x, y, color, size)
- for i in 0...size
- self.set_pixel(x+i, y, color)
- self.set_pixel(x-i, y, color)
- self.set_pixel(x, y+i, color)
- self.set_pixel(x, y-i, color)
- self.set_pixel(x+i, y+i, color)
- self.set_pixel(x-i, y-i, color)
- self.set_pixel(x+i, y-i, color)
- self.set_pixel(x-i, y+i, color)
- end
- end
- #----------------------------------------------------------------------------
- # • Desenhar uma linha.
- # start_x : Início da linha em X.
- # start_y : Início da linha em Y.
- # end_x : Finalização da linha em X.
- # end_y : Finalização da linha em Y.
- #----------------------------------------------------------------------------
- def draw_line(start_x, start_y, end_x, end_y, color, size=1)
- set_pixel_s(start_x, start_y, color, size)
- distance = (start_x - end_x).abs + (start_y - end_y).abs
- for i in 1..distance
- x = (start_x + 1.0 * (end_x - start_x) * i / distance).to_i
- y = (start_y + 1.0 * (end_y - start_y) * i / distance).to_i
- set_pixel_s(x, y, color, size)
- end
- set_pixel_s(end_x, end_y, color, size)
- end
- #----------------------------------------------------------------------------
- # • draw_bar_gauge(x, y, current, current_max, border, colors)
- # x : Coordenadas X.
- # y : Coordenadas Y.
- # current : Valor atual da barra.
- # current_max : Valor maxímo da barra.
- # border : Expressura da borda.
- # colors : Cores. [0, 1, 2]
- #----------------------------------------------------------------------------
- # Permite adicionar uma barra.
- #----------------------------------------------------------------------------
- def draw_bar_gauge(x, y, current, current_max, colors=[])
- cw = self.width.to_p(current, current_max)
- ch = self.height
- self.gradient_fill_rect(x, y, self.width, self.height, colors[0], colors[1])
- src_rect = Rect.new(0, 0, cw, ch)
- self.blt(x, y, self, src_rect)
- end
- #----------------------------------------------------------------------------
- # • draw_icon(icon_index, x, y, enabled)
- # icon_index : ID do ícone.
- # x : Coordenadas X.
- # y : Coordenadas Y.
- # enabled : Habilitar flag, translucido quando false
- #----------------------------------------------------------------------------
- #----------------------------------------------------------------------------
- def draw_icon(icon_index, x, y, enabled = true)
- icon_index = icon_index.nil? ? 0 : icon_index
- bitmap = Cache.system("Iconset")
- rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
- self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
- end
- #----------------------------------------------------------------------------
- # • draw_gradation_gauge(x, y, width, height, current, current_max, border, colors, align)
- # x : Coordenadas X.
- # y : Coordenadas Y.
- # width : Largura da barra.
- # height : Altura da barra.
- # current : Valor atual da barra.
- # current_max : Valor maxímo da barra.
- # border : Expressura da borda.
- # colors : Cores. [0, 1, 2]
- # align : Alinhamento.
- #----------------------------------------------------------------------------
- # Permite adicionar uma barra.
- #----------------------------------------------------------------------------
- def draw_gradation_gauge(x, y, current, current_max, border, colors=[])
- cw = self.width.to_p(current, current_max)
- ch = self.height
- self.fill_rect(x, y, self.width, self.height, colors[0])
- self.gradient_fill_rect(x+border, y+border, self.width-(border/2), self.height-(border/2), colors[1], colors[2])
- src_rect = Rect.new(0, 0, cw, ch)
- self.blt(x, y, self, src_rect)
- end
- #--------------------------------------------------------------------------
- # • Desenho do gráfico de rosto
- # face_name : nome do gráfico de face
- # face_index : índice do gráfico de face
- # x : coordenada X
- # y : coordenada Y
- # enabled : habilitar flag, translucido quando false
- #--------------------------------------------------------------------------
- def draw_face(face_name, face_index, x, y, enabled = true)
- bitmap = Cache.face(face_name)
- rect = Rect.new(face_index % 4 * 96, face_index / 4 * 96, 96, 96)
- self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
- end
- #--------------------------------------------------------------------------
- # • Desenho do gráfico de face do herói
- # actor : herói
- # x : coordenada X
- # y : coordenada Y
- # enabled : habilitar flag, translucido quando false
- #--------------------------------------------------------------------------
- def draw_actor_face(actor, x, y, enabled = true)
- draw_face(actor.face_name, actor.face_index, x, y, enabled)
- end
- #--------------------------------------------------------------------------
- # • Desenho do nível
- # actor : herói
- # x : coordenada X
- # y : coordenada Y
- #--------------------------------------------------------------------------
- def draw_actor_level(actor, x, y)
- self.font.name = "Comic Sans MS"
- self.font.color = ColorBasic[35]
- self.font.size = 18
- self.draw_text(x, y, 32, 20, Vocab::level_a)
- self.font.size = 22
- draw_text(x + 16, y, 32, 20, actor.level, 2)
- end
- #----------------------------------------------------------------------------
- # • Desenhar um círuclo preenchido.
- #----------------------------------------------------------------------------
- def fill_circle(x, y, r, c)
- rr = r*r
- for i in 0...r
- adj = Math.sqrt(rr - (i*i)).ceil
- xd = x - adj
- wd = 2 * adj
- self.fill_rect(xd, y-i, wd, 1, c)
- self.fill_rect(xd, y+i, wd, 1, c)
- end
- end
- #----------------------------------------------------------------------------
- # • Desenhar um triângulo preenchido
- #----------------------------------------------------------------------------
- def fill_triangle3(pts, c, pos=[0, 0])
- return if pts.size != 3
- pts.sort! {|a, b| a[1] - b[1]}
- pt1, pt2, pt3 = pts
- dxt = (pt3[0] - pt1[0]) / 2
- dyt = (pt3[1] - pt1[1]) / 2
- dxm = pt2[0] - pt1[0]
- dym = pt2[1] - pt1[1]
- dm = dym.abs
- if dm > 0 and dyt != 0
- for i in 0...(dm+2)
- ix = ((dxm*i) / (dm+1))
- iy = ((dym*i) / (dm+1))
- edx = ix - (dxt * iy / dyt)
- self.fill_rect(ix+pt1[0]-[edx,0].max-2+pos[0], iy+pt1[1]+pos[1], edx.abs+4, 1, c)
- end
- end
- dxm = pt2[0] - pt3[0]
- dym = pt2[1] - pt3[1]
- dm = dym.abs
- if dm > 0 and dyt != 0
- for i in 0...(dm+2)
- ix = ((dxm*i) / (dm+1))
- iy = ((dym*i) / (dm+1))
- edx = ix - (dxt * iy / dyt)
- self.fill_rect(ix+pt3[0]-[edx,0].max-2+pos[0], iy+pt3[1]+pos[1], edx.abs+4, 1, c)
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Desenhar um polígono.
- #----------------------------------------------------------------------------
- def fill_polygon(pts, c, pos=[0, 0])
- return if pts.size <= 2
- n = pts.size - 2
- for i in 0...n
- self.fill_triangle3(pts[i..(i + 2)], c, pos)
- end
- end
- end
- #==============================================================================
- # • Mouse
- #==============================================================================
- Dax.register(:mouse)
- module Mouse
- extend self
- #--------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #--------------------------------------------------------------------------
- def start
- @cursor = Sprite.new
- @cursor.z = 100000
- @cursor.bitmap = Bitmap.new(1, 1)
- x = Dax::Mouse_Name == "" ? 1 : 0
- API::MouseShowCursor.call(x)
- @dgraphic = Dax::Mouse_Name
- graphic Dax::Mouse_Name
- @old_graphic = @dgraphic
- update
- end
- #----------------------------------------------------------------------------
- # • visible = (boolean)
- # * boolean : true ou false
- # Tornar vísivel ou não o cursor do Mouse.
- #----------------------------------------------------------------------------
- def visible=(boolean)
- API::MouseShowCursor.call(boolean.boolean)
- end
- #--------------------------------------------------------------------------
- # • graphic(graphic_set)
- # graphic_set : Se for número é um ícone; Se for string é uma imagem.
- #--------------------------------------------------------------------------
- def graphic(graphic_set)
- return unless graphic_set == "" or graphic_set.nil?
- set_graphic
- @dgraphic = graphic_set
- end
- #--------------------------------------------------------------------------
- # • show(visible)
- # visible : True - para mostrar o mouse | False - para esconder o mouse.
- #--------------------------------------------------------------------------
- def show(visible=true)
- @cursor.visible = visible
- end
- #--------------------------------------------------------------------------
- # • update (Atualização das coordenadas)
- #--------------------------------------------------------------------------
- def update
- return if @cursor.nil?
- @cursor.x, @cursor.y = position
- end
- #----------------------------------------------------------------------------
- # • Mudança do gráfico.
- #----------------------------------------------------------------------------
- def set_graphic
- unless @old_graphic == @dgraphic
- if @dgraphic.is_a?(Fixnum)
- @cursor.bitmap = Bitmap.new(24, 24)
- @cursor.bitmap.draw_icon(@dgraphic.to_i, 0, 0)
- else
- @cursor.bitmap = Cache.picture(@dgraphic.to_s)
- end
- @old_graphic = @dgraphic
- end
- end
- #--------------------------------------------------------------------------
- # • Retorna a variável '@cursor' que tem como valor a classe [Sprite].
- #--------------------------------------------------------------------------
- def cursor
- @cursor
- end
- #--------------------------------------------------------------------------
- # • x (Coordenada X do Mouse)
- #--------------------------------------------------------------------------
- def x
- @cursor.x
- end
- #--------------------------------------------------------------------------
- # • y (Coordenada Y do Mouse)
- #--------------------------------------------------------------------------
- def y
- @cursor.y
- end
- #----------------------------------------------------------------------------
- # • Elementos das coordenadas do mouse.
- #----------------------------------------------------------------------------
- def eachPos
- yield(x, y, @cursor.z)
- return nil
- end
- #--------------------------------------------------------------------------
- # • position (Posição do Mouse!)
- #--------------------------------------------------------------------------
- def position
- x, y = get_client_position
- return x, y
- end
- #--------------------------------------------------------------------------
- # • get_client_position (Posição original do Mouse!)
- #--------------------------------------------------------------------------
- def get_client_position
- pos = [0, 0].pack('ll')
- API::CursorPosition.call(pos)
- API::ScreenToClient.call(WINDOW, pos)
- return pos.unpack('ll')
- end
- #--------------------------------------------------------------------------
- # • find_window (Tamanho da window)
- #--------------------------------------------------------------------------
- def find_window
- game_name = '\0' * 256
- API::ReadIni.call('Game', 'Title', '', game_name, 255, '.\\Game.ini')
- game_name.delete!('\0') ensure game_name
- return API::FindWindow.call('RGSS Player', game_name)
- end
- #--------------------------------------------------------------------------
- # • Verificação se o mouse está na área de um determinado objeto.
- #--------------------------------------------------------------------------
- def in_area?(object_sprite)
- return @cursor.x.between?(object_sprite.x, object_sprite.x + object_sprite.width) &&
- @cursor.y.between?(object_sprite.y, object_sprite.y + object_sprite.height)
- end
- #----------------------------------------------------------------------------
- # • Verificar se o mouse está em determinada área
- #----------------------------------------------------------------------------
- def area?(x, y, width, height)
- return @cursor.x.between?(x, x + width) &&
- @cursor.y.between?(y, y + height)
- end
- #----------------------------------------------------------------------------
- # • Mudar posição do cursor.
- #----------------------------------------------------------------------------
- def set_mouse(pos)
- SetCursorPos.call(pos.x, pos.y)
- update
- @cursor.x = @pos.x
- @cursor.y = @pos.y
- end
- WINDOW = find_window
- end
- #==============================================================================
- # • Object
- #==============================================================================
- Dax.register(:object)
- class Object
- #----------------------------------------------------------------------------
- # • O que irá ocorrer caso o mouse esteja sobre uma sprite.
- # Tem que ser um objeto Sprite. EXPLICAÇÕES NO FINAL DO SCRIPT.
- #----------------------------------------------------------------------------
- def if_mouse_over(&block)
- return if Mouse.cursor.nil?
- return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
- over ||= false
- if Mouse.in_area?(self)
- block.call
- over = true
- else
- over = false
- end
- yield over
- end
- #----------------------------------------------------------------------------
- # • Retorna no bloco os nomes e quantidade de cada arquivo. Mais o nome
- # separado. Mais o tipo de cada elemento.
- # "Nome da Pasta".dirGlob { |filename, size| }
- #----------------------------------------------------------------------------
- def dirGlob
- return unless self.is_a?(String) or File.directory?(self)
- dir = Dir.glob(self.include?("/") ? self + "*" : self + "/*")
- yield dir
- yield dir.size
- end
- #----------------------------------------------------------------------------
- # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao clicar.
- # Tem que ser um objeto Sprite.
- # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
- # EXPLICAÇÕES NO FINAL DO SCRIPT.
- #----------------------------------------------------------------------------
- def if_mouse_click(button=:left, &block)
- return if Mouse.cursor.nil?
- return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
- button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
- block.call if Mouse.in_area?(self) and trigger?(button)
- end
- #----------------------------------------------------------------------------
- # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao pressionar.
- # Tem que ser um objeto Sprite.
- # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
- #----------------------------------------------------------------------------
- def if_mouse_press(button=:left, &block)
- return if Mouse.cursor.nil?
- return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
- button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
- block.call if Mouse.in_area?(self) and press?(button)
- end
- #----------------------------------------------------------------------------
- # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao ficar clicando.
- # Tem que ser um objeto Sprite.
- # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
- #----------------------------------------------------------------------------
- def if_mouse_repeat(button=:left, &block)
- return if Mouse.cursor.nil?
- return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
- button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
- block.call if Mouse.in_area?(self) and repeat?(button)
- end
- #----------------------------------------------------------------------------
- # • Trigger
- # * key : Chave.
- # Você também pode usá-lo como condição para executar tal bloco;
- #----------------------------------------------------------------------------
- # trigger?(key) { bloco que irá executar }
- #----------------------------------------------------------------------------
- def trigger?(key, &block)
- ckey = key.is_a?(Symbol) ? Input.trigger?(key) : Key.trigger?(key)
- return ckey unless block_given?
- block.call if ckey
- end
- #----------------------------------------------------------------------------
- # • Press
- # * key : Chave.
- # Você também pode usá-lo como condição para executar tal bloco;
- #----------------------------------------------------------------------------
- # press?(key) { bloco que irá executar. }
- #----------------------------------------------------------------------------
- def press?(key, &block)
- ckey = key.is_a?(Symbol) ? Input.press?(key) : Key.press?(key)
- return ckey unless block_given?
- block.call if ckey
- end
- #----------------------------------------------------------------------------
- # • Repeat
- # * key : Chave.
- # Você também pode usá-lo como condição para executar tal bloco;
- #----------------------------------------------------------------------------
- # repeat?(key) { bloco que irá executar. }
- #----------------------------------------------------------------------------
- def repeat?(key)
- ckey = key.is_a?(Symbol) ? Input.repeat?(key) : Key.repeat?(key)
- return ckey unless block_given?
- block.call if ckey
- end
- #----------------------------------------------------------------------------
- # • Retorna em forma de número os valores true ou false. E caso seja
- # 0 ou 1.. retorna a true ou false.
- # Se for true, retorna a 1.
- # Se for false, retorna a 0.
- # Se for 1, retorna a true.
- # Se for 0, retorna a false.
- #----------------------------------------------------------------------------
- def boolean
- return self.is_a?(Integer) ? self == 0 ? false : 1 : self ? 1 : 0
- end
- #----------------------------------------------------------------------------
- # • Converte para a classe Position.
- #----------------------------------------------------------------------------
- def position
- return Position.new(self, self) if self.is_a?(Numeric)
- return Position.new(self.x, self.y) if self.is_a?(Sprite) or self.is_a?(Window_Base)
- return Position.new(self[0], self[1]) if self.is_a?(Array)
- return Position.new(0, 0)
- end
- #----------------------------------------------------------------------------
- # • Transforma em cor.
- # Se for uma Array. Exemplo: [128, 174, 111].color =># Color.new(128, 174, 111)
- # Se for uma String. Exemplo: "ffffff".color =># Color.new(255,255,255)
- # Se for um número, aí retorna a uma cor de acordo com o Index do ColorBasic.
- #----------------------------------------------------------------------------
- def color
- return Color.new(*self) if self.is_a?(Array)
- return ColorBasic.hex(self) if self.is_a?(String)
- return ColorBasic[self] if self.is_a?(Integer)
- end
- end
- #==============================================================================
- # • Entries *** Classe ainda não explicada ******
- #==============================================================================
- Dax.register(:entries)
- class Entries
- #----------------------------------------------------------------------------
- # • Variável pública da instância.
- #----------------------------------------------------------------------------
- attr_accessor :file
- attr_reader :get_number
- attr_reader :get_file
- attr_reader :get_array
- attr_reader :name
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(directory, typefile)
- return unless FileTest.directory?(directory)
- @file = Dir.glob(directory + "/*.{" + typefile + "}")
- @file.each_index { |i| @get_number = i.to_i }
- @file.each { |i| @get_file = i.to_s }
- @file.each_with_index { |i| @get_array = i }
- @name = split @file[0]
- end
- #----------------------------------------------------------------------------
- # • Split | Separar
- #----------------------------------------------------------------------------
- def split(file)
- file.to_s.split('/').last
- end
- #----------------------------------------------------------------------------
- # • Obter nome.
- #----------------------------------------------------------------------------
- def name(id)
- return if @file.nil?
- return split(@file[id])
- end
- end
- #==============================================================================
- # • TextBase
- #==============================================================================
- Dax.register(:text_base)
- class TextBase
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(filename="File_#{rand(999)}", type="a+")
- @text = ""
- filename = filename.include?(".txt") ? filename : filename << ".txt"
- @file = File.open(filename, type)
- end
- #----------------------------------------------------------------------------
- # • Adicionar texto.
- #----------------------------------------------------------------------------
- def text=(text_add)
- @text += text_add
- end
- #----------------------------------------------------------------------------
- # • Adicionar uma nova linha.
- #----------------------------------------------------------------------------
- def text(text, nspace=0)
- @text += "\r\n" + (" " * nspace) + text
- end
- #----------------------------------------------------------------------------
- # • Adicionar comentário;
- #----------------------------------------------------------------------------
- def comment=(text_add, comment="#")
- @text += comment + text_add
- end
- #----------------------------------------------------------------------------
- # • Adicionar uma nova linha como comentário.
- #----------------------------------------------------------------------------
- def comment(text, nspace=0, comment="#")
- @text += "\r\n" + (" " * nspace) + comment + text
- end
- #----------------------------------------------------------------------------
- # • Salvar o texto.
- #----------------------------------------------------------------------------
- def save
- @file.write(@text)
- @file.close
- end
- end
- #==============================================================================
- # • DRGSS | Comandos do RGSS...
- #==============================================================================
- Dax.register(:drgss)
- module DRGSS
- extend self
- #----------------------------------------------------------------------------
- # • **** Método ainda não explicado ****
- #----------------------------------------------------------------------------
- def recursive_delete(dir)
- files = []
- Dir.foreach(dir) do |fname|
- next if fname == '.' || fname == '..'
- path = dir + '/' + fname
- if File.directory?(path)
- puts "dir #{path}"
- recursive_delete(path)
- else
- puts "file #{path}"
- files << path
- end
- end
- files.each do |path|
- msgbox "delete file #{path}"
- end
- msgbox "delete dir #{dir}"
- Dir.rmdir(dir)
- end
- #----------------------------------------------------------------------------
- # • **** Método ainda não explicado ****
- #----------------------------------------------------------------------------
- def delete(directory)
- if File.directory?(directory)
- Dir.foreach(directory) do |file_or_directory|
- File.delete(directory+"/"+file_or_directory) if file_or_directory != "." and file_or_directory != ".."
- end
- else
- begin
- File.delete(directory) if File.new(directory).stat.size == 0
- rescue
- msgbox "#{$!} Error in deleting zero size file "
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Extrair scripts do Database para um arquivo de extensão de texto.
- # options : Caso você deixe assim: {folder: "NM"}
- # NM => Nome da pasta na qual os arquivos irão.
- #----------------------------------------------------------------------------
- def extract_scripts(type=".txt",options={})
- except = options[:except] || []
- folder = options[:folder] || ""
- id = 0 #
- $RGSS_SCRIPTS.each do |script|
- name = script[1]
- data = script[3]
- next if except.include? name or name.empty? or data.empty?
- filename = sprintf("%03d", id) + "_" + name
- p "Writing: #{filename}"
- File.open(folder+filename+"#{type}", "wb") do |file|
- file.write data
- end
- id += 1
- end
- end
- #----------------------------------------------------------------------------
- # • Guarda todos os scripts do Database num arquivo;
- #----------------------------------------------------------------------------
- def keep_scripts_in_file(filename="RGSS.rvdata2")
- unless FileTest.exist?(filename)
- self.extract_scripts(".txt")
- file = File.open(filename, "wb")
- Dir.glob("./*.{txt}").each_with_index { |v,i|
- next unless v.match(/(\d+){3}_(\w*)/)
- file.write(IO.readlines(v).to_s)
- File.delete(v)
- }
- file.close
- end
- end
- #----------------------------------------------------------------------------
- # • **** Método ainda não explicado ****
- #----------------------------------------------------------------------------
- def load_scripts(type=".txt",options={})
- skip = options[:skip] || []
- folder = options[:folder] || ""
- begin
- Dir.foreach(folder) do |file|
- file_id = file[0,3].to_i
- break if file_id == options[:limit]
- next if file == "." or file == ".." or File.extname(file) != "#{type}" or skip.include?(file_id)
- r = load(folder+"#{file}")
- p "Loaded: #{r}"
- end
- end
- end
- end
- #==============================================================================
- # • OutlineFillRect **** Método ainda não explicado ****
- #==============================================================================
- Dax.register(:outline_fill_rect)
- class OutlineFillRect < Sprite
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(object, max=2, color=ColorBasic[-1])
- super([object.width, object.height])
- @object = object
- self.x, self.y, self.z = object.x, object.y, object.z
- self.bitmap.fill_rect(0, 0, max, self.height, color)
- self.bitmap.fill_rect(self.width-max, 0, max, self.height, color)
- self.bitmap.fill_rect(0, 0, self.width, max, color)
- self.bitmap.fill_rect(0, self.height-max, self.width, max, color)
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose unless self.bitmap.disposed?
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização das coordenadas.
- #----------------------------------------------------------------------------
- def update
- self.x, self.y, self.z = @object.x, @object.y, @object.z
- end
- end
- #==============================================================================
- # • Backup Complete
- #==============================================================================
- Dax.register(:backup)
- module Backup
- extend self
- # Criar as pastas.
- def make_past
- Dir.mkdir("Backup") unless File.directory?("Backup")
- ["Data", "System", "Movies", "Graphics", "Audio", "Audio/BGM", "Audio/BGS", "Audio/ME", "Audio/SE"].each { |i|
- Dir.mkdir("Backup/#{i}") unless File.directory?("Backup/#{i}")
- }
- end
- # Cópiar da pasta system.
- def system
- list = Dir.glob('System/*')
- list.size.times { |i|API::CopyFile.call(list[i], "Backup/" + list[i], true.boolean)}
- end
- # Cópiar da pasta Movies.
- def movies
- movies = Dir.glob("Movies/*")
- movies.size.times { |i| API::CopyFile.call(movies[i], "Backup/" + movies[i], true.boolean)}
- end
- # Cópiar da pasta Audio.
- def audio
- bgm = Dir.glob('Audio/BGM/*')
- bgs = Dir.glob('Audio/BGS/*')
- me = Dir.glob('Audio/ME/*')
- se = Dir.glob('Audio/SE/*')
- bgm.size.times { |i| API::CopyFile.call(bgm[i], "Backup/" + bgm[i], true.boolean)}
- bgs.size.times { |i| API::CopyFile.call(bgs[i], "Backup/" + bgs[i], true.boolean) }
- me.size.times { |i| API::CopyFile.call(me[i], "Backup/" + me[i], true.boolean) }
- se.size.times { |i| API::CopyFile.call(se[i], "Backup/" + se[i], true.boolean) }
- end
- # Cópiar da pasta Data
- def data
- data = Dir.glob('Data/*')
- data.size.times { |i| API::CopyFile.call(data[i], "Backup/" + data[i], true.boolean) }
- end
- # Cópiar da pasta Graphics.
- def graphics
- ["Animations", "Battlebacks1", "Battlebacks2", "Battlers", "Characters",
- "Faces", "Parallaxes", "Pictures", "System", "Titles1", "Titles2",
- "Tilesets"].each { |dirs|
- Dir.mkdir("Backup/Graphics/#{dirs}") unless File.directory?("Backup/Graphics/#{dirs}")
- d = Dir.glob("Graphics/#{dirs}/*")
- d.size.times { |v| API::CopyFile.call(d[v], "Backup/" + d[v], true.boolean) }
- }
- end
- # Executar
- def run(audios=false, graphic=false)
- return unless $TEST
- make_past
- movies
- data
- system
- audio if audios
- graphics if graphic
- end
- end
- #==============================================================================
- # * SceneManager
- #==============================================================================
- Dax.register :scenemanager
- Dax.required_class("SceneManager"){
- class << SceneManager
- #----------------------------------------------------------------------------
- # • **** Método ainda não explicado ****
- #----------------------------------------------------------------------------
- def symbol(scene_symbol)
- eval("self.call(#{scene_symbol.to_s})")
- end
- end
- }
- #==============================================================================
- # • Sprite_Text
- #==============================================================================
- Dax.register(:sprite_text)
- class Sprite_Text < Sprite
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância.
- #----------------------------------------------------------------------------
- attr_accessor :text # Mudar de texto...
- attr_accessor :align
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(x, y, width, height, text, align=0)
- super([width, height])
- self.x, self.y = x, y
- @text = text
- @align = align
- self.bitmap.draw_text_rect(@text, align)
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização dos objetos.
- #----------------------------------------------------------------------------
- def update
- self.bitmap.clear
- super
- self.bitmap.draw_text_rect(@text, @align)
- end
- def name=(value=nil)
- self.bitmap.font.name = name || Font.default_name.to_s
- end
- #----------------------------------------------------------------------------
- # • Negrito na fonte?
- #----------------------------------------------------------------------------
- def bold=(value=nil)
- self.bitmap.font.bold = value || true
- end
- #----------------------------------------------------------------------------
- # • Itálico na fonte?
- #----------------------------------------------------------------------------
- def italic=(value=nil)
- self.bitmap.font.italic = value || true
- end
- #----------------------------------------------------------------------------
- # • Sombra na fonte?
- #----------------------------------------------------------------------------
- def shadow=(value=nil)
- self.bitmap.font.shadow = value || true
- end
- #----------------------------------------------------------------------------
- # • Borda na fonte?
- #----------------------------------------------------------------------------
- def outline=(value=nil)
- self.bitmap.font.outline = value || true
- end
- #----------------------------------------------------------------------------
- # • Mudar a cor da fonte:
- #----------------------------------------------------------------------------
- def color=(color=nil)
- self.bitmap.font.color = color || -1.color
- end
- #----------------------------------------------------------------------------
- # • Mudar a cor da borda da fonte.
- #----------------------------------------------------------------------------
- def out_color=(out_color=nil)
- self.bitmap.font.out_color = out_color || 7.color
- end
- end
- #==============================================================================
- # • StringSprite : Permite digitar pelo teclado.
- #==============================================================================
- Dax.register :key_string_sprite
- class KeyStringSprite < Sprite_Text
- attr_reader :text
- #--------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #--------------------------------------------------------------------------
- def initialize(x, y, width, height, input="trigger?")
- super(x, y, width, height, "")
- @input = input
- end
- #--------------------------------------------------------------------------
- # • Renovação dos objetos.
- #--------------------------------------------------------------------------
- def dispose
- super
- end
- #--------------------------------------------------------------------------
- # • Atualização dos objetos.
- #--------------------------------------------------------------------------
- def update
- @text += Key.string(@input) unless Key.string(@input) == ""
- @text = DString.backslash(@text) if Key.trigger?(Key::BACKSPACE)
- super
- end
- end
- #==============================================================================
- # • Sprite_Icon
- #==============================================================================
- Dax.register(:sprite_icon)
- class Sprite_Icon < Sprite
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância.
- #----------------------------------------------------------------------------
- attr_accessor :icon_index # Mudar de ícone.
- attr_accessor :enabled # Tornar opaco ou não.
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(x, y, icon_index, enabled=true)
- super([24, 24])
- self.x, self.y = x, y
- @icon_index = icon_index.to_i
- @enabled = enabled
- self.bitmap.draw_icon(@icon_index, 0, 0, @enabled)
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização dos objetos.
- #----------------------------------------------------------------------------
- def update
- self.bitmap.clear
- super
- self.bitmap.draw_icon(@icon_index, 0, 0, @enabled)
- end
- end
- #==============================================================================
- # • Opacity
- #==============================================================================
- Dax.register(:opacity)
- module Opacity
- extend self
- @key ||= {}
- #----------------------------------------------------------------------------
- # • Efeito de opacidade que vai aumentando e diminuindo.
- # sprite : Objeto na qual sofrerá o efeito. [Sprite]
- # speed : Velocidade na qual o efeito irá acontencer.
- # max : Valor máximo na qual irá ser atingido.
- # min : Valor minímo na qual irá ser atingido.
- #----------------------------------------------------------------------------
- def sprite_opacity(sprite, speed, max, min, hash=nil)
- @key[hash.nil? ? hash.__id__ : hash] || false
- unless @key[hash]
- sprite.opacity += speed unless sprite.opacity >= max
- @key[hash] = sprite.opacity >= max
- else
- sprite.opacity -= speed unless sprite.opacity <= min
- @key[hash] = false if sprite.opacity <= min
- end
- end
- #----------------------------------------------------------------------------
- # • Efeito de opacidade por fora.
- # sprite : Objeto na qual sofrerá o efeito. [Sprite]
- # speed : Velocidade na qual o efeito irá acontencer.
- # max : Valor máximo na qual irá ser atingido.
- #----------------------------------------------------------------------------
- def sprite_opacity_out(sprite, speed, max)
- sprite.opacity += speed unless sprite.opacity >= max
- end
- #----------------------------------------------------------------------------
- # • Efeito de opacidade por dentro.
- # sprite : Objeto na qual sofrerá o efeito. [Sprite]
- # speed : Velocidade na qual o efeito irá acontencer.
- # min : Valor minímo na qual irá ser atingido.
- #----------------------------------------------------------------------------
- def sprite_opacity_in(sprite, speed, min)
- sprite.opacity -= speed unless sprite.opacity <= min
- end
- #--------------------------------------------------------------------------
- # • Efeito de fade out em massa
- # time : duração (em milesegundo)
- #--------------------------------------------------------------------------
- def fadeout_all(time = 1000)
- RPG::BGM.fade(time)
- RPG::BGS.fade(time)
- RPG::ME.fade(time)
- Graphics.fadeout(time * Graphics.frame_rate / 1000)
- RPG::BGM.stop
- RPG::BGS.stop
- RPG::ME.stop
- end
- #----------------------------------------------------------------------------
- # • Limpar variável.
- #----------------------------------------------------------------------------
- def clear
- @key.clear
- end
- end
- #==============================================================================
- # • Rpg
- #==============================================================================
- Dax.register(:rpg)
- module Rpg
- def self.data_manager
- end
- #============================================================================
- # • Hud
- #============================================================================
- module Hud
- end
- #============================================================================
- # • Menu
- #============================================================================
- module Menu
- extend self
- def include_item?(item)
- item.is_a?(RPG::Item) && !item.key_item?
- end
- #--------------------------------------------------------------------------
- # • *** Método aidna não explicado ****
- #--------------------------------------------------------------------------
- def cursor_up(variable, max)
- variable += 1 unless variable > max
- variable = 0 if variable > max
- return variable
- end
- #--------------------------------------------------------------------------
- # • *** Método aidna não explicado ****
- #--------------------------------------------------------------------------
- def cursor_down(variable, max)
- variable -= 1 unless variable < 0
- variable = max if variable < 0
- return variable
- end
- end
- #============================================================================
- # • Battle
- #============================================================================
- module Battle
- end
- #============================================================================
- # • Title
- #============================================================================
- module Title
- end
- end
- #==============================================================================
- # • String
- #==============================================================================
- Dax.register :shortcut
- class String
- #----------------------------------------------------------------------------
- # • *** Método aidna não explicado ****
- #----------------------------------------------------------------------------
- def call
- if self.match(/G: ([^>]*)/)
- return "Graphics/#{$1}"
- elsif self.match(/C:(\w+):([^>]*)/)
- case $1
- when "S"
- return Cache.system($2.to_s)
- when "P"
- return Cache.picture($2.to_s)
- when "Pl"
- return Cache.parallax($2.to_s)
- when "C"
- return Cache.character($2.to_s)
- when "A"
- return Cache.animation($2.to_s)
- when "B1"
- return Cache.battleback1($2.to_s)
- when "B2"
- return Cache.battleback2($2.to_s)
- when "B"
- return Cache.battler($2.to_s)
- when "F"
- return Cache.face($2.to_s)
- when "T1"
- return Cache.title1($2.to_s)
- when "T2"
- return Cache.title2($2.to_s)
- when "T"
- return Cache.tileset($2.to_s)
- end
- end
- end
- end
- #==============================================================================
- # • Txt
- #==============================================================================
- Dax.register(:read, "Dax")
- module Read
- extend self
- #----------------------------------------------------------------------------
- # • Verificar valor numérico após uma palavra em um arquivo.
- #----------------------------------------------------------------------------
- def numeric(file, tag)
- IO.readlines(file).each do |line|
- return $1.to_i if line.match(/#{tag} (\d+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Verificar valor de uma palavra(string única) após uma palavra em um arquivo
- #----------------------------------------------------------------------------
- def string(file, tag)
- IO.readlines(file).each do |line|
- return $1.to_s if line.match(/#{tag} (\w+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Verificar um conteúdo após uma palavra de um arquivo.
- #----------------------------------------------------------------------------
- def content(file, tag)
- IO.readlines(file).each do |line|
- return $1 if line.match(/#{tag} ([^>]*)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Multiplo número..
- #----------------------------------------------------------------------------
- def multiple_numeric(file, tag)
- IO.readlines(file).each do |line|
- return [$1.to_i, $2.to_i] if line.match(/#{tag} (\d+), (\d+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Multiplo string..
- #----------------------------------------------------------------------------
- def multiple_string(file, tag)
- IO.readlines(file).each do |line|
- return [$1.to_s, $2.to_s] if line.match(/#{tag} (\w+), (\w+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Triplo número.
- #----------------------------------------------------------------------------
- def triple_numeric(file, tag)
- IO.readlines(file).each do |line|
- return [$1.to_i, $2.to_i, $3.to_i] if line.match(/#{tag} (\d+), (\d+), (\d+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Triplo string.
- #----------------------------------------------------------------------------
- def triple_string(file, tag)
- IO.readlines(file).each do |line|
- return [$1.to_s, $2.to_s, $3.to_s] if line.match(/#{tag} (\w+), (\w+), (\w+)/)
- end
- end
- # true or false
- def of(file, tag)
- IO.readlines(file).each do |line|
- return $1.to_s == "true" ? true : false if line.match(/#{tag} ([^>]*)/)
- end
- end
- end
- #==============================================================================
- # • Background
- #==============================================================================
- Dax.register :background
- module Background
- extend self
- @background ||= {}
- #----------------------------------------------------------------------------
- # • Plano de fundo padrão...
- #----------------------------------------------------------------------------
- def default(alpha=128, key=nil)
- @background[key.__id__] = Sprite.new
- @background[key.__id__].bitmap = SceneManager.background_bitmap
- @background[key.__id__].color.set(16, 16, 16, alpha)
- end
- #----------------------------------------------------------------------------
- # • Plano de fundo padrão renovado.
- #----------------------------------------------------------------------------
- def default_dispose
- return if @background.nil?
- @background.each_value(&:dispose)
- end
- # Definir um sprite de fundo
- def define_back(color="ffffff".color, key=nil)
- @background[key.__id__] = Sprite.new([Graphics.width, Graphics.height])
- @background[key.__id__].bitmap.fill_rect(@background[key.__id__].rect, color)
- end
- end
- #==============================================================================
- # * Window_Base
- #==============================================================================
- Dax.register(:window_base)
- Dax.required_class("Window_Base") {
- class Window_Base < Window
- #----------------------------------------------------------------------------
- # • Slide pela direita.
- # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
- #----------------------------------------------------------------------------
- def slide_right(speed, point)
- self.x += speed unless self.x >= point
- end
- #----------------------------------------------------------------------------
- # • Slide pela esquerda.
- # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
- #----------------------------------------------------------------------------
- def slide_left(speed, point)
- self.x -= speed unless self.x <= point
- end
- #----------------------------------------------------------------------------
- # • Slide por cima.
- # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
- #----------------------------------------------------------------------------
- def slide_up(speed, point)
- self.y -= speed unless self.y <= point
- end
- #----------------------------------------------------------------------------
- # • Slide por baixo.
- # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
- #----------------------------------------------------------------------------
- def slide_down(speed, point)
- self.y += speed unless self.y >= point
- end
- #----------------------------------------------------------------------------
- # • Define aqui uma posição fixa para um objeto.
- # command : Retorna a uma base padrão.
- #----------------------------------------------------------------------------
- def position(command=0)
- return if command.nil?
- case command
- # Imagem ficará no canto esquerdo superior. Posição X
- when 0 then self.x = 0
- # A posição X ficará no centro da tela.
- when 1 then self.x = DMath.get_x_center_screen(self.width)
- # A posição X ficará no canto direito superior.
- when 2 then self.x = Graphics.width - self.width
- # A posição Y ficará no canto esquerdo inferior.
- when 3 then self.y = 0
- # Posicionar o Y para ficar no centro.
- when 4 then self.y = DMath.get_y_center_screen(self.height)
- # Posicionar o Y para ficar no fundo da tela.
- when 5 then self.y = Graphics.height - self.height
- # Posicionar a imagem no centro da tela.
- when :center
- self.x = (Graphics.width - self.width) / 2
- self.y = Graphics.height / 2 - self.height / 2
- # Posicionar no centro esquerdo da tela.
- when :center_left
- self.x = 0
- self.y = (Graphics.height - self.height) / 2
- # Posicionar no centro direito da tela.
- when :center_right
- self.x = Graphics.width - self.height
- self.y = (Graphics.height - self.height) / 2
- end
- end
- end
- }
- #==============================================================================
- # • Map
- #==============================================================================
- Dax.register(:map)
- module Map
- extend self
- #----------------------------------------------------------------------------
- # • Mapeiar área.
- # map : Objeto [SPRITE].. que será escaniado..
- # scan_sprite : Objeto [SPRITE].. que irá projetar o scan.
- # color : Cor do scan.
- #----------------------------------------------------------------------------
- def char_area(map, scan_sprite, color=ColorBasic[-1])
- _table = Table.new(map.width, map.height)
- for x in 0..._table.xsize
- for y in 0..._table.ysize
- next if map.bitmap.get_pixel(x, y).alpha == 0
- scan_sprite.bitmap.set_pixel(x, y, color)
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Colidir com determinada cor de um objeto sprite.
- # ar : [largura, altura, bloqueio da esquerda, bloqueio de cima]
- # object : Objeto a colidir. [SPRITE]
- # map : Mapa. [SPRITE]
- # color : Cor, na qual quando o objeto colidir com está cor.. ativa.
- #---------------------------------------------------------------------------
- def collide_with_color(object, map, color, ar=[28,30,30,30])
- (ar[0]...object.width).each { |w| (ar[1]...object.height).each { |h|
- _r = map.bitmap.get_pixel(object.x+w, object.y+h) == color[:right]
- _l = map.bitmap.get_pixel(object.x+ar[2]-w, object.y+h) == color[:left]
- _d = map.bitmap.get_pixel(object.x+w, object.y+h) == color[:down]
- _u = map.bitmap.get_pixel(object.x+w, object.y+ar[3]-h) == color[:up]
- return {right: _r, left: _l, down: _d, up: _u}
- }}
- end
- end
- #==============================================================================
- # • VS | Variables & Switches
- #==============================================================================
- Dax.register(:vs)
- module VS
- #----------------------------------------------------------------------------
- # • Função do módulo.
- #----------------------------------------------------------------------------
- module_function
- #----------------------------------------------------------------------------
- # • Desligar a quantia predestinada de switches...
- #----------------------------------------------------------------------------
- def off_switche(value=9999)
- Dax.required_class("$game_switches"){value.times { |index| $game_switches[index] = false }
- $game_switches.on_change}
- end
- #----------------------------------------------------------------------------
- # • Ativar a quantia predestinada de switches...
- #----------------------------------------------------------------------------
- def on_switche(value=9999)
- Dax.required_class("$game_switches"){value.times { |index| $game_switches[index] = true }
- $game_switches.on_change}
- end
- #----------------------------------------------------------------------------
- # • Salvar as variáveis do jogo em um arquivo
- # *args : IDs delas.. exemplo: 1, 2, 3, 4
- #----------------------------------------------------------------------------
- def save_game_variable(*args)
- Dax.required_class("$game_variables"){
- Dax.required_file("savedGameVariables.rvdata2"){File.delete("savedGameVariables.rvdata2")}
- i = [*args]
- sgv = [{}]
- (0...i.size-1).each { |index| sgv[0][index] = $game_variables[index] }
- save_data(sgv, "savedGameVariables.rvdata2")
- }
- end
- #----------------------------------------------------------------------------
- # • Carregar as variáveis do jogo dum arquivo
- # *args : IDs delas.. exemplo: 1, 2, 3, 4
- #----------------------------------------------------------------------------
- def load_game_variable(*args)
- Dax.required_class("$game_variables"){
- Dax.required_file("savedGameVariables.rvdata2"){
- i = [*args]
- sgv = load_data("savedGameVariables.rvdata2")
- (0...i.size-1).each { |index| $game_variables[index] = sgv[0][index]}
- }}
- end
- #----------------------------------------------------------------------------
- # • Salvar as switches do jogo em um arquivo
- # *args : IDs delas.. exemplo: 1, 2, 3, 4
- #----------------------------------------------------------------------------
- def save_switches_variable(*args)
- Dax.required_class("$game_switches"){
- Dax.required_file("savedGameSwitches.rvdata2"){File.delete("savedGameSwitches.rvdata2")}
- i = [*args]
- sgs= [{}]
- (0...i.size-1).each { |index| sgs[0][index] = $game_switches[index] }
- save_data(sgs, "savedGameSwitches.rvdata2")
- }
- end
- #----------------------------------------------------------------------------
- # • Carregar as variáveis do jogo dum arquivo
- # *args : IDs delas.. exemplo: 1, 2, 3, 4
- #----------------------------------------------------------------------------
- def load_game_variable(*args)
- Dax.required_class("$game_switches"){
- Dax.required_file("savedGameSwitches.rvdata2"){
- i = [*args]
- sgs = load_data("savedGameSwitches.rvdata2")
- (0...i.size-1).each { |index| $game_switches[index] = sgs[0][index]}
- }}
- end
- end
- #==============================================================================
- # • Sound Base
- #==============================================================================
- Dax.register(:sound_base)
- module Sound_Base
- #----------------------------------------------------------------------------
- # • Função do módulo.
- #----------------------------------------------------------------------------
- module_function
- #----------------------------------------------------------------------------
- # • Executar um som.
- #----------------------------------------------------------------------------
- def play(name, volume, pitch, type = :se)
- case type
- when :se ; RPG::SE.new(name, volume, pitch).play rescue valid?(name)
- when :me ; RPG::ME.new(name, volume, pitch).play rescue valid?(name)
- when :bgm ; RPG::BGM.new(name, volume, pitch).play rescue valid?(name)
- when :bgs ; RPG::BGS.new(name, volume, pitch).play rescue valid?(name)
- end
- end
- #----------------------------------------------------------------------------
- # • Validar som.
- #----------------------------------------------------------------------------
- def valid?(name)
- raise("Arquivo de som não encontrado: #{name}")
- exit
- end
- end
- #==============================================================================
- # • Position.
- #==============================================================================
- Dax.register :position
- class Position
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância.
- #----------------------------------------------------------------------------
- attr_accessor :x # Variável que retorna ao valor que indica a posição X.
- attr_accessor :y # Variável que retorna ao valor que indica a posição Y.
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(x, y)
- @x = x || 0
- @y = y || 0
- end
- #----------------------------------------------------------------------------
- # • Somar com outra posição.
- #----------------------------------------------------------------------------
- def +(position)
- position = position.position unless position.is_a?(Position)
- Position.new(self.x + position.x, self.y + position.y)
- end
- #----------------------------------------------------------------------------
- # • Subtrair com outra posição.
- #----------------------------------------------------------------------------
- def -(position)
- position = position.position unless position.is_a?(Position)
- Position.new(self.x - position.x, self.y - position.y)
- end
- #----------------------------------------------------------------------------
- # • Multiplicar com outra posição.
- #----------------------------------------------------------------------------
- def *(position)
- position = position.position unless position.is_a?(Position)
- Position.new(self.x * position.x, self.y * position.y)
- end
- #----------------------------------------------------------------------------
- # • Dividir com outra posição.
- #----------------------------------------------------------------------------
- def /(position)
- position = position.position unless position.is_a?(Position)
- return if (self.x or position.x or self.y or position.y) <= 0
- Position.new(self.x / position.x, self.y / position.y)
- end
- #----------------------------------------------------------------------------
- # • Comparar com outra posição.
- #----------------------------------------------------------------------------
- def ==(position)
- position = position.position unless position.is_a?(Position)
- return self.x == position.x && self.y == position.y
- end
- #----------------------------------------------------------------------------
- # • Converter em string.
- #----------------------------------------------------------------------------
- def to_s
- return "position x: #{self.x}\nposition y: #{self.y}"
- end
- end
- #==============================================================================
- # • Vector
- #==============================================================================
- Dax.register(:vector)
- class Vector
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos. x, y, w, h
- #----------------------------------------------------------------------------
- def initialize(*args)
- @vector = *args
- end
- #----------------------------------------------------------------------------
- # • Rotacionar
- #----------------------------------------------------------------------------
- def rotate(angle)
- x = @vector[0] * Math.cos(Math::PI / 180 * angle) - @vector[1] * Math.sin(Math::PI / 180 * angle)
- y = @vector[0] * Math.sin(Math::PI / 180 * angle) + @vector[1] * Math.cos(Math::PI / 180 * angle)
- temp = @vector.dup
- temp[0], temp[1] = x, y
- return Vector.new(*temp)
- end
- #----------------------------------------------------------------------------
- # • Somar com outra classe Vector
- #----------------------------------------------------------------------------
- def +(v)
- return Vector.new(*@vector.map.each_index{|s,i| s + v[i]}) if v.is_a?(Vector)
- return Vector.new(*@vector.map.each_index{|s,i| s + v[i]}) if v.is_a?(Array)
- return Vector.new(*@vector.map{|s| + v}) if v.is_a?(Numeric)
- return nil
- end
- #----------------------------------------------------------------------------
- # • Multiplicar com Matrix.
- #----------------------------------------------------------------------------
- def *(matrix)
- result = []
- for i in 0..(matrix.size-1)
- data = 0
- for j in 0..(@vector.size-1)
- data += @vector[j] * matrix[j][i]
- end
- result.push(data)
- end
- return Vector.new(*result)
- end
- #----------------------------------------------------------------------------
- # • Arr.
- #----------------------------------------------------------------------------
- def [](index)
- return @vector[index]
- end
- #----------------------------------------------------------------------------
- # • Tamanho.
- #----------------------------------------------------------------------------
- def size
- @vector.size
- end
- #----------------------------------------------------------------------------
- # • Converter para array.
- #----------------------------------------------------------------------------
- def to_a
- @vector
- end
- # x
- def x; return @vector[0]; end;
- # Y
- def y; return @vector[1]; end;
- # z
- def z; return @vector[2]; end;
- # w
- def w; return @vector[3]; end;
- end
- #==============================================================================
- # • Matrix
- #==============================================================================
- Dax.register(:matrix)
- class Matrix
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(*args)
- @arr = Array.new(4) { |i| Vector.new(*args[i]) }
- end
- #----------------------------------------------------------------------------
- # • Multiplicar.
- #----------------------------------------------------------------------------
- def *(a)
- result = []
- for i in 0..(a.size-1)
- result.push(@arr[i] * a)
- end
- return Matrix.new(*result)
- end
- #----------------------------------------------------------------------------
- # • []
- #----------------------------------------------------------------------------
- def [](index)
- return @arr[index]
- end
- #----------------------------------------------------------------------------
- # • Tamanho
- #----------------------------------------------------------------------------
- def size
- return @arr.size
- end
- #----------------------------------------------------------------------------
- # • Criar rotação em z.
- #----------------------------------------------------------------------------
- def self.create_rotation_z(angle)
- cos = Math.cos(Math::PI/180 * angle)
- sin = Math.sin(Math::PI/180 * angle)
- return Matrix.new(
- [ cos, sin, 0, 0],
- [-sin, cos, 0, 0],
- [ 0, 0, 1, 0],
- [ 0, 0, 0, 1]
- )
- end
- #----------------------------------------------------------------------------
- # • Rotação em X
- #----------------------------------------------------------------------------
- def self.create_rotation_x(angle)
- cos = Math.cos(Math::PI/180 * angle)
- sin = Math.sin(Math::PI/180 * angle)
- return Matrix.new(
- [ 1, 0, 0, 0],
- [ 0, cos, sin, 0],
- [ 0,-sin, cos, 0],
- [ 0, 0, 0, 1]
- )
- end
- #----------------------------------------------------------------------------
- # • Rotação em Y
- #----------------------------------------------------------------------------
- def self.create_rotation_y(angle)
- cos = Math.cos(Math::PI/180 * angle)
- sin = Math.sin(Math::PI/180 * angle)
- return Matrix.new(
- [ cos, 0,-sin, 0],
- [ 0, 1, 0, 0],
- [ sin, 0, cos, 0],
- [ 0, 0, 0, 1]
- )
- end
- #----------------------------------------------------------------------------
- # • Transição.
- #----------------------------------------------------------------------------
- def self.create_transration(x, y, z)
- return Matrix.new(
- [ 1, 0, 0, 0],
- [ 0, 1, 0, 0],
- [ 0, 0, 1, 0],
- [ x, y, z, 1]
- )
- end
- #----------------------------------------------------------------------------
- # • Para array
- #----------------------------------------------------------------------------
- def to_a
- @arr.map {|v|v.to_a}.flatten
- end
- end
- #==============================================================================
- # • Animation
- #==============================================================================
- Dax.register :animation
- class Animation
- attr_reader :size, :frame_size, :index, :max_width, :max_height
- #----------------------------------------------------------------------------
- # • Inicialização.
- #----------------------------------------------------------------------------
- def initialize(size, frame_size, wait=1)
- @size = size
- @frame_size = frame_size
- @index = 0
- @max_width = @size[0] / @frame_size[0]
- @max_height = @size[1] / @frame_size[1]
- @wait = wait
- @time = 0
- end
- #----------------------------------------------------------------------------
- # • Animação na horizontal.
- #----------------------------------------------------------------------------
- def horz
- @time += 1 unless @time >= @wait
- if @time >= @wait
- @index = Rpg::Menu.cursor_up(@index, @max_width)
- @time = 0
- end
- end
- #----------------------------------------------------------------------------
- # • Animação na vertical.
- #----------------------------------------------------------------------------
- def vert
- @time += 1 unless @time >= @wait
- if @time >= @wait
- @index = Rpg::Menu.cursor_up(@index, @max_height)
- @time = 0
- end
- end
- end
- #==============================================================================
- # • Sprite_Anime_Horz
- #==============================================================================
- Dax.register :sprite_anime_horz
- class Sprite_Anime_Horz < Sprite
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos
- # filename : Nome do arquivo.
- # frame_size : Tamanho de cada frame.
- # wait : Tempo de espera para mudar de um frame para outro.
- #----------------------------------------------------------------------------
- def initialize(filename, frame_size, wait=1)
- @bitmap = Bitmap.new(filename)
- super(frame_size)
- @animation = Animation.new([@bitmap.width, @bitmap.height],
- frame_size, wait)
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização dos objetos.
- #----------------------------------------------------------------------------
- def update
- self.bitmap.clear
- super
- @animation.horz
- rect = Rect.new(@animation.index % @animation.max_width * @animation.frame_size[0],
- 0, *@animation.frame_size)
- self.bitmap.blt(0, 0, @bitmap, rect)
- end
- end
- #==============================================================================
- # • Sprite_Anime_Vert
- #==============================================================================
- Dax.register :sprite_anime_vert
- class Sprite_Anime_Vert < Sprite
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos
- # filename : Nome do arquivo.
- # frame_size : Tamanho de cada frame.
- # wait : Tempo de espera para mudar de um frame para outro.
- #----------------------------------------------------------------------------
- def initialize(filename, frame_size, wait=1)
- @bitmap = Bitmap.new(filename)
- super(frame_size)
- @animation = Animation.new([@bitmap.width, @bitmap.height],
- frame_size, wait)
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização dos objetos.
- #----------------------------------------------------------------------------
- def update
- self.bitmap.clear
- super
- @animation.vert
- rect = Rect.new(0,
- @animation.index % @animation.max_height * @animation.frame_size[1], *@animation.frame_size)
- self.bitmap.blt(0, 0, @bitmap, rect)
- end
- end
- #==============================================================================
- # • Desativar scripts : Para fazer, basta por no nome do script da lista,
- # [D].
- #==============================================================================
- Dax.register(:disable_script)
- $RGSS_SCRIPTS.each_with_index { |data, index|
- $RGSS_SCRIPTS.at(index)[2] = $RGSS_SCRIPTS.at(index)[3] = "" if data.at(1).include?("[D]")
- }
- #==============================================================================
- # • Salvar scripts em arquivo de texto : Para fazer, basta por no nome do script
- # da lista, [S].
- #==============================================================================
- $RGSS_SCRIPTS.each_with_index { |rgss, index|
- if rgss.at(1).include?("[S]")
- File.open("#{rgss.at(1)}.txt", "wb") { |file|
- file.write(String($RGSS_SCRIPTS.at(index)[3]))
- file.close
- }
- end
- }
- #==============================================================================
- # • Cache
- #==============================================================================
- Dax.register :cache
- Dax.required_class("Cache") {
- class << Cache
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância
- #----------------------------------------------------------------------------
- attr_accessor :cache # Variável cache.
- end
- }
- #==============================================================================
- # * DataManager
- #==============================================================================
- unless defined?(DataManager)
- Mouse.start
- Rpg.data_manager
- else
- class << DataManager
- alias :new_init :init
- def init
- Rpg.data_manager
- Mouse.start
- new_init
- end
- end
- end
- #==============================================================================
- # * Input
- #==============================================================================
- class << Input
- alias :upft :update
- def update
- upft
- Key.update
- end
- end
- #==============================================================================
- # • Graphics
- #==============================================================================
- class << Graphics
- alias :uptf :update
- def update
- uptf
- Mouse.update
- end
- end
- #==============================================================================
- # • Explicações, comentários... Um Báu!
- #==============================================================================
- __END__
- :regexp_symbol
- #==============================================================================
- # • Regexp Symbol
- #==============================================================================
- Símbolos:
- [x]|[abc] : Um único caractér de: a, b ou c
- [^x]|[^abc] : Qualquer caractér exceto: a, b, ou c
- [a-z] : Um único caractér no intervalo de a...z
- [a-zA-Z] : Um único caractér no intervalo de a...z ou A...Z
- ^ : Começo da linha.
- $ : Fim da linha.
- \A : Começo da string.
- \z : Fim da string.
- . : Um único caractér
- \s : Qualquer carácter com espaço
- \S : Qualquer carácter sem espaço
- \d : Qualquer dígito
- \D : Qualquer um que não seja um dígito
- \w : Qualquer palavra
- \W : Qualquer um que não seja uma palavra.
- \b : Qualquer limite de palavra.
- (...) : Capturar tudo fechado.
- (x|y)|(a|b) : A(X) ou B(Y)
- x? : Zero ou um de x.
- x* : Zero ou mais de x.
- x+ : Um ou mais de x.
- x{3} : Exatamente 3 de x.
- x{3,} : Exatamente 3 ou mais de um de x.
- x{3,6} : Entre 3 e 6 de x.
- Opções:
- /i : Sem case sensitive
- /m : Para mais de uma linha
- /x : Ingnorar espaços brancos
- /o : Executar o #{...}, alterações apenas uma vez.
- /<tagName>(.*?)<\/tagName>/im
- <tagName>
- type: skill
- id: 2
- forced: true
- </tagName>
- p = -> { [1, 2] }
- msgbox_p(p.call)
- ==============================================================================
- **** Método : 'if_mouse_over'
- O que esse método trata? Trata-se de que quando o Mouse estiver por cima de
- determinado objeto.. algo irá acontecer.
- Como eu configuro a ação que irá ocorrer caso o Mouse esteja por cima de
- determinado objeto?
- Bom, o método só irá funcionar com objetos que são da classe [Sprite], e ele
- retorna a um bloco(somente se definir)! Exemplo:
- sprite.if_mouse_over # Chamou o método.. Mais agora para definir o bloco basta
- usar as {chaves} e dentro da chave o bloco que irá ser executado. Ex:
- sprite.if_mouse_over {
- Comando que irá se executar caso o Mouse esteja por cima do determinado objeto.
- }
- Certo, mais agora como faço uma condição para fazer uma ação de que.. Se
- o Mouse esteja por cima de determinado objeto acontece algo, e quando ele não
- estiver ele executa outra coisa?
- Simples basta chamar a variável 'over', como chamar? Após o '{' usa-se
- |over| .. Essa variável retorna caso o Mouse esteja por cima ou não de um objeto
- com os valores true or false.. Um exemplo abaixo.
- sprite.if_mouse_over { |over|
- sprite.opacity = over ? 255 : 128
- }
- # O Exemplo acima.. Quando o Mouse estiver por cima.. a opacidade ficará com o
- valor de '255'.. e quando não estiver ficará em '128'.
- ==============================================================================
- *** Método : 'if_mouse_click'
- O que esse método trata? Trata-se de que quando o Mouse estiver por cima de
- determinado objeto e a clicar nele(com o botão direito/esquerdo). algo irá acontecer
- Como eu configuro a ação que irá ocorrer caso o Mouse esteja por cima de
- determinado objeto ao ser clicado? O mesmo método do de cima.
- Bom, o método só irá funcionar com objetos que são da classe [Sprite], e ele
- retorna a um bloco(somente se definir)! Exemplo:
- sprite.if_mouse_click(button) {
- Comando que irá se executar caso o sprite seja clicado com o Mouse.
- }
- * button * O button naturalmente e o botão esquerdo.. Então se quiser não
- precisa o configurar.. Mais caso queira olhe abaixo os valores a por em ()
- button : Button : (:right - botão direito do mouse | :left - botão esq.)
- Um Exemplo abaixo :
- sprite.if_mouse_click { msgbox("Você clicou em mim!") }
- ==============================================================================
- S = Struct.new("S", :methods)
- # past RGSSAD.. quando encriptado;
- # my = "%01d %06d %02d" % [4, 15646, 21]
- # fruit = ["apple","red","banana","yellow"]
- #Hash[*fruit]
- #=> {"apple"=>"red", "banana"=>"yellow"}
- #----------------------------------------------------------------------------
- # • [Array] Renova todos os sprites e depois deleta.
- #----------------------------------------------------------------------------
- def spriteDelete
- self.each_with_index { |sprite, index|
- return unless sprite.is_a?(Sprite)
- sprite.dispose
- self.delete_at(index)
- }
- end
- ceil arredonda para cima;
- floor arredonda para baixo;
- round arredonda para o número mais próximo;
- --Pegado do site : http://www.ruby-doc.org/
- Integer | Array |
- Directive | Element | Meaning
- ---------------------------------------------------------------------------
- C | Integer | 8-bit unsigned (unsigned char)
- S | Integer | 16-bit unsigned, native endian (uint16_t)
- L | Integer | 32-bit unsigned, native endian (uint32_t)
- Q | Integer | 64-bit unsigned, native endian (uint64_t)
- | |
- c | Integer | 8-bit signed (signed char)
- s | Integer | 16-bit signed, native endian (int16_t)
- l | Integer | 32-bit signed, native endian (int32_t)
- q | Integer | 64-bit signed, native endian (int64_t)
- | |
- S_, S! | Integer | unsigned short, native endian
- I, I_, I! | Integer | unsigned int, native endian
- L_, L! | Integer | unsigned long, native endian
- Q_, Q! | Integer | unsigned long long, native endian (ArgumentError
- | | if the platform has no long long type.)
- | | (Q_ and Q! is available since Ruby 2.1.)
- | |
- s_, s! | Integer | signed short, native endian
- i, i_, i! | Integer | signed int, native endian
- l_, l! | Integer | signed long, native endian
- q_, q! | Integer | signed long long, native endian (ArgumentError
- | | if the platform has no long long type.)
- | | (q_ and q! is available since Ruby 2.1.)
- | |
- S> L> Q> | Integer | same as the directives without ">" except
- s> l> q> | | big endian
- S!> I!> | | (available since Ruby 1.9.3)
- L!> Q!> | | "S>" is same as "n"
- s!> i!> | | "L>" is same as "N"
- l!> q!> | |
- | |
- S< L< Q< | Integer | same as the directives without "<" except
- s< l< q< | | little endian
- S!< I!< | | (available since Ruby 1.9.3)
- L!< Q!< | | "S<" is same as "v"
- s!< i!< | | "L<" is same as "V"
- l!< q!< | |
- | |
- n | Integer | 16-bit unsigned, network (big-endian) byte order
- N | Integer | 32-bit unsigned, network (big-endian) byte order
- v | Integer | 16-bit unsigned, VAX (little-endian) byte order
- V | Integer | 32-bit unsigned, VAX (little-endian) byte order
- | |
- U | Integer | UTF-8 character
- w | Integer | BER-compressed integer
- Float | |
- Directive | | Meaning
- ---------------------------------------------------------------------------
- D, d | Float | double-precision, native format
- F, f | Float | single-precision, native format
- E | Float | double-precision, little-endian byte order
- e | Float | single-precision, little-endian byte order
- G | Float | double-precision, network (big-endian) byte order
- g | Float | single-precision, network (big-endian) byte order
- String | |
- Directive | | Meaning
- ---------------------------------------------------------------------------
- A | String | arbitrary binary string (space padded, count is width)
- a | String | arbitrary binary string (null padded, count is width)
- Z | String | same as ``a'', except that null is added with *
- B | String | bit string (MSB first)
- b | String | bit string (LSB first)
- H | String | hex string (high nibble first)
- h | String | hex string (low nibble first)
- u | String | UU-encoded string
- M | String | quoted printable, MIME encoding (see RFC2045)
- m | String | base64 encoded string (see RFC 2045, count is width)
- | | (if count is 0, no line feed are added, see RFC 4648)
- P | String | pointer to a structure (fixed-length string)
- p | String | pointer to a null-terminated string
- Misc. | |
- Directive | | Meaning
- ---------------------------------------------------------------------------
- @ | --- | moves to absolute position
- X | --- | back up a byte
- x | --- | null byte
- ---------------------------------------------------------------------------
- module MyModule
- NOME = "Algo"
- end
- autoload(:MyModule, "my_module.rb")
- print MyModule::NOME #=> "Algo"
- # Constante base para ponteiros números em formato Float. Regexp
- FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?[\d]+)?$/
- # Constante base para ponteiros de parameters. Regexp
- PARAM_RE = /^-(-|\.$|[^\d\.])/
Add Comment
Please, Sign In to add comment