Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #==============================================================================
- # * Dax Core
- #==============================================================================
- # Autor : Dax Aquatic X
- # Versão : Core i4.2
- # 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 : • TAGS : Para facilitar a localização dos códigos e explicações. Para acessar
- # o comando para localizar, basta apertar Ctrl+F.
- #==============================================================================
- # i :
- # - Array :array
- # - Api :api
- # - String :string
- # - Integer :integer
- # - Numeric :numeric
- # - Color :color
- # - Rect :rect
- # - DMath :dmath
- # - Key :key
- # - Sprite :sprite
- # - Bitmap :bitmap (Método #save por Gab! -> Créditos a ele)
- # - Mouse :mouse
- # - Sprite_Mouse :sprite_mouse
- # - Object :object
- # - Entries :entries
- # - DRGSS :drgss
- # - Backup :backup
- # - SceneManager :scenemanager
- # - Sprite_Text :sprite_text
- # - Sprite_Icon :sprite_icon
- # - Opacity :opacity
- # - Read :read
- # - Background :background
- # - Window_Base :window_base
- # - Sound_Base :sound_base
- # - Position :position
- # - Animation :animation
- # - Sprite_Anime_Horz :sprite_anime_horz
- # - Sprite_Anime_Vert :sprite_anime_vert
- #==============================================================================
- # • Adicionado comentário padrão. Veja o modo que agora os comentários dos
- # métodos estão.
- #==============================================================================
- # • [Classe do Retorno] : Explicação.
- # * Exemplo.(Se possível.)
- #==============================================================================
- module Dax
- extend self
- #----------------------------------------------------------------------------
- # • Constantes
- #----------------------------------------------------------------------------
- # 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 = ""
- #----------------------------------------------------------------------------
- # • Variáveis
- #----------------------------------------------------------------------------
- @register = { } # Variável útilizada para registrar os scripts que fora criado.
- @benchmark = "" # Armazena os testes conclusos de benchmark.
- #----------------------------------------------------------------------------
- # • 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
- #----------------------------------------------------------------------------
- # • Somente executará o bloco caso estiver registrado o script. Compatível
- # com o $imported. Caso não esteja registrado no Core e esteja registrado
- # na variável $imported, dará!
- #----------------------------------------------------------------------------
- # Exemplo:
- # Dax.required_script(:teste) { # Só irá executar caso estiver registrado.
- # methods...
- # }
- #----------------------------------------------------------------------------
- def required_script(symbol, &block)
- return unless block_given?
- block.call if @register.has_key?(symbol) or $imported.has_key?(symbol)
- end
- #----------------------------------------------------------------------------
- # • Método de verificar se o objeto existe.
- #----------------------------------------------------------------------------
- # Dax.if_defined?("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 if_defined?(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
- #----------------------------------------------------------------------------
- # • Somente executa um bloco case existir uma pasta.
- #----------------------------------------------------------------------------
- # Dax.required_dir("arquivo.tipo") { # Exemplo.
- # Métodos;
- # }
- #----------------------------------------------------------------------------
- def required_dir(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
- #==============================================================================
- # • 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
- #----------------------------------------------------------------------------
- # • [Mixed] : Retorna ao primeiro valor da array, que obedeça a
- # condição posta.
- # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_evan? } #> 2
- # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_odd? } #> 3
- #----------------------------------------------------------------------------
- def first!
- return unless block_given?
- return self.each { |element| return element if yield(element) }.at(0)
- end
- end
- #==============================================================================
- # • API : Módulo que armazena informações de algumas APIS.
- #==============================================================================
- 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
- protected :hwnd, :open, :function
- end
- #==============================================================================
- # * String
- #==============================================================================
- Dax.register(:string)
- class String
- #--------------------------------------------------------------------------
- # • [String] : converter à String em UTF8
- #--------------------------------------------------------------------------
- def to_utf8
- API.textUTF(self)
- end
- #--------------------------------------------------------------------------
- # • [Array] : Extrai somente os números da String, e retorna a uma Array.
- # Exemplo: "João89".numbers # [8, 9]
- #--------------------------------------------------------------------------
- def 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] : Remove o último caractere da String.
- #----------------------------------------------------------------------------
- def backslash
- return String(self[0, self.split(//).size-1])
- 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] : Aumenta o valor até chegar ao máximo(definido), quando
- # chegar ao máximo(definido) retorna a zero.
- #----------------------------------------------------------------------------
- def up(max)
- n = self
- n = n > max ? 0 : n.next
- return n
- end
- #----------------------------------------------------------------------------
- # • [Integer] : Diminui o valor até chegar a zero, quando chegar a zero
- # retorna ao valor máximo(defindo).
- #----------------------------------------------------------------------------
- def down(max)
- n = self
- n = n < 0 ? max : n - 1
- return n
- end
- end
- #==============================================================================
- # • Numeric
- #==============================================================================
- Dax.register(:numeric)
- class Numeric
- #----------------------------------------------------------------------------
- # * [Numeric] : Transformar em porcentagem
- # a : Valor atual.
- # b : Valor máximo.
- #----------------------------------------------------------------------------
- def to_p(a, b)
- self * a / b
- end
- end
- #==============================================================================
- # * Color
- #==============================================================================
- Dax.register(:color)
- class Color
- #----------------------------------------------------------------------------
- # • [Color] : Permite você modificar a opacidade da cor.
- # 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
- self.set(*[self.red, self.green, self.blue, self.alpha].reverse!)
- 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
- #----------------------------------------------------------------------------
- # • [Numeric] : Retorna ao valor mais alto que tiver, dentre os valores
- # especificados das cores.
- #----------------------------------------------------------------------------
- def max
- [red, green, blue].max
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : Retorna ao valor menor que tiver, dentre os valores
- # especificados das cores.
- #----------------------------------------------------------------------------
- def min
- [red, green, blue].min
- end
- #----------------------------------------------------------------------------
- # • [Color] : Define uma cor aleatória:
- # Exemplo: Color.new.random
- #----------------------------------------------------------------------------
- def random
- self.set(rand(256), rand(256), rand(256))
- end
- #----------------------------------------------------------------------------
- # • [Color] : Define uma cor em hexadécimal.
- # Exemplo : Color.new.hex("ffffff")
- #----------------------------------------------------------------------------
- def hex(string)
- self.set(*string.scan(/../).map { |color| color.to_i(16)})
- end
- #----------------------------------------------------------------------------
- # • [Color] : Retorna a cor padrão.
- # Exemplo : Color.new.default
- #----------------------------------------------------------------------------
- def default
- self.hex("ffffff")
- end
- end
- #==============================================================================
- # • Rect
- #==============================================================================
- Dax.register(:rect)
- class Rect
- #----------------------------------------------------------------------------
- # • [TrueClass/FalseClass] : Verificar se algo 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
- #----------------------------------------------------------------------------
- # • [Numeric] : 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, caso
- # não retorna ao próprio número(num).
- #----------------------------------------------------------------------------
- def clamp(num, low, high)
- num, low, high = num.to_i, low.to_i, high.to_i
- num = num < low ? low : num > high ? high : num
- num
- 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] : Retorna pra base de 4 decimais.
- #----------------------------------------------------------------------------
- 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
- #----------------------------------------------------------------------------
- # • [Numeric] : Dentro do círculo.
- #----------------------------------------------------------------------------
- def circle_in(t, b, c, d)
- return -c * (Math.sqrt(1 - (t /= d.to_f) * t) - 1) + b
- end
- #----------------------------------------------------------------------------
- # • [Numeric] : 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
- #----------------------------------------------------------------------------
- # • [Numeric] : Retorna ao valor minímo, do valor máximo de min & v, com o
- # valor de max.
- #----------------------------------------------------------------------------
- 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
- #--------------------------------------------------------------------------
- # * [TrueClass/FalseClass] Obter o estado quando a chave for pressionada.
- # key : key index
- #--------------------------------------------------------------------------
- def press?(key)
- return @press[key]
- end
- #--------------------------------------------------------------------------
- # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada.
- # key : key index
- #--------------------------------------------------------------------------
- def trigger?(key)
- return @trigger[key]
- end
- #--------------------------------------------------------------------------
- # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada repetidamente.
- # key : key index
- #--------------------------------------------------------------------------
- def repeat?(key)
- return @repeat[key]
- end
- #--------------------------------------------------------------------------
- # * [TrueClass/FalseClass] Obter o estado quando a chave for "lançada"
- # key : key index
- #--------------------------------------------------------------------------
- def release?(key)
- return @release[key]
- end
- #----------------------------------------------------------------------------
- # • CONSTANTES.
- #----------------------------------------------------------------------------
- AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(//)
- Az = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".downcase!.split(//)
- NUM = "0123456789".split(//)
- #----------------------------------------------------------------------------
- # • [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
- end
- #==============================================================================
- # • Sprite
- #==============================================================================
- Dax.register(:sprite)
- class Sprite
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância.
- #----------------------------------------------------------------------------
- attr_accessor :clone_sprite
- attr_accessor :outline_fill_rect
- #----------------------------------------------------------------------------
- # • 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 = []
- @outline_fill_rect = nil
- 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
- #----------------------------------------------------------------------------
- # • Renovação do Sprite.
- #----------------------------------------------------------------------------
- alias :dax_core_dispose :dispose
- def dispose
- dax_core_dispose
- @outline_fill_rect.dispose unless @outline_fill_rect.nil?
- end
- #----------------------------------------------------------------------------
- # • Definir um contorno no Sprite em forma de retângulo.
- # color : Cor do contorno.
- # size : Tamanho da linha do contorno.
- # vis : Visibilidade. true - visível | false - invisível.
- #----------------------------------------------------------------------------
- def set_outline(color=Color.new.default, size=2, vis=true)
- @outline_fill_rect = Sprite.new([self.width, self.height, self.x, self.y, self.z+2])
- @outline_fill_rect.bitmap.fill_rect(0, 0, self.width, size, color)
- @outline_fill_rect.bitmap.fill_rect(0, self.height-size, self.width, size, color)
- @outline_fill_rect.bitmap.fill_rect(0, 0, size, self.height, color)
- @outline_fill_rect.bitmap.fill_rect(self.width-size, 0, size, self.height, color)
- @outline_fill_rect.visible = vis
- end
- #----------------------------------------------------------------------------
- # • Atualização do contorno.
- # vis : Visibilidade. true - visível | false - invisível.
- #----------------------------------------------------------------------------
- def update_outline(vis=true)
- @outline_fill_rect.visible = vis
- @outline_fill_rect.x, @outline_fill_rect.y = self.x, self.y
- 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
- 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
- #----------------------------------------------------------------------------
- # • 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. Efeito 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
- # filename : Podes definir uma imagem: Basta
- # por o nome da imagem, ela deve estar na pasta System.
- #----------------------------------------------------------------------------
- def draw_icon(icon_index, x, y, enabled = true, filename="IconSet")
- icon_index = icon_index.nil? ? 0 : icon_index
- bitmap = Cache.system(filename)
- 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
- #----------------------------------------------------------------------------
- # • 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
- end
- #==============================================================================
- # • Mouse
- #==============================================================================
- Dax.register(:mouse)
- module Mouse
- extend self
- #--------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #--------------------------------------------------------------------------
- def start
- @cursor = Sprite_Mouse.new(Dax::Mouse_Name, 0, 0, 100000)
- x = Dax::Mouse_Name == "" ? 1 : 0
- API::MouseShowCursor.call(x)
- @dgraphic = 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)
- @cursor.set_graphic = graphic_set
- @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
- #--------------------------------------------------------------------------
- # • 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
- #==============================================================================
- # • Sprite_Mouse
- #==============================================================================
- Dax.register(:sprite_mouse)
- class Sprite_Mouse < Sprite
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância.
- #----------------------------------------------------------------------------
- attr_accessor :set_graphic # definir o gráfico.
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(graphic, x, y, z)
- super(nil)
- @set_graphic = graphic
- if @set_graphic.is_a?(Fixnum)
- self.bitmap = Bitmap.new(24, 24)
- self.bitmap.draw_icon(@set_graphic, 0, 0)
- elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
- self.bitmap = Bitmap.new(1, 1)
- elsif @set_graphic.is_a?(String)
- self.bitmap = Cache.system(@set_graphic)
- end
- self.x, self.y, self.z = x, y, z
- @older = @set_graphic
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização dos objetos.
- #----------------------------------------------------------------------------
- def update
- super
- unless @older == @set_graphic
- if @set_graphic.is_a?(Fixnum)
- self.bitmap = Bitmap.new(24, 24)
- self.bitmap.draw_icon(@set_graphic, 0, 0)
- elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
- self.bitmap = Bitmap.new(1, 1)
- elsif @set_graphic.is_a?(String)
- self.bitmap = Cache.system(@set_graphic)
- end
- @older = @set_graphic
- end
- end
- end
- #==============================================================================
- # • Object
- #==============================================================================
- Dax.register(:object)
- class Object
- #----------------------------------------------------------------------------
- # • O que irá ocorrer caso o mouse esteja sobre uma sprite.
- # Tem que ser um objeto Sprite.
- #----------------------------------------------------------------------------
- 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
- #----------------------------------------------------------------------------
- # • 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)
- #----------------------------------------------------------------------------
- def color
- return Color.new(*self) if self.is_a?(Array)
- return Color.new.hex(self) if self.is_a?(String)
- end
- end
- #==============================================================================
- # • Entries
- #==============================================================================
- 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
- #----------------------------------------------------------------------------
- def split(file)
- file.to_s.split('/').last
- end
- #----------------------------------------------------------------------------
- # • Obter nome.
- #----------------------------------------------------------------------------
- def name(id)
- return if @file.nil?
- return split(@file[id])
- 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 "#{$!} Erro ao excluir um arquivo de tamanho zero."
- 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
- #==============================================================================
- # • 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
- #----------------------------------------------------------------------------
- # • Copiar a pasta system.
- #----------------------------------------------------------------------------
- def system
- list = Dir.glob('System/*')
- list.size.times { |i|API::CopyFile.call(list[i], "Backup/" + list[i], true.boolean)}
- end
- #----------------------------------------------------------------------------
- # • Copiar a pasta movie.
- #----------------------------------------------------------------------------
- def movies
- movies = Dir.glob("Movies/*")
- movies.size.times { |i| API::CopyFile.call(movies[i], "Backup/" + movies[i], true.boolean)}
- end
- #----------------------------------------------------------------------------
- # • Copiar a 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
- #----------------------------------------------------------------------------
- # • Copiar a pasta Data.
- #----------------------------------------------------------------------------
- def data
- data = Dir.glob('Data/*')
- data.size.times { |i| API::CopyFile.call(data[i], "Backup/" + data[i], true.boolean) }
- end
- #----------------------------------------------------------------------------
- # • Copiar a pasta Graphic.
- #----------------------------------------------------------------------------
- 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)
- unless $TEST
- DRGSS.delete("Backup")
- else
- make_past
- movies
- data
- system
- audio if audios
- graphics if graphic
- end
- end
- end
- #==============================================================================
- # * SceneManager
- #==============================================================================
- Dax.register :scenemanager
- if defined?("SceneManager")
- class << SceneManager
- #--------------------------------------------------------------------------
- # • **** Método ainda não explicado ****
- #--------------------------------------------------------------------------
- def symbol(scene_symbol)
- eval("self.call(#{scene_symbol.to_s})")
- end
- 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
- #==============================================================================
- # • 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.
- attr_accessor :filename # Nome do arquivo.
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(icon_index, x, y, 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, @filename)
- 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
- #----------------------------------------------------------------------------
- # • Limpar variável.
- #----------------------------------------------------------------------------
- def clear
- @key.clear
- end
- end
- #==============================================================================
- # • Read
- #==============================================================================
- 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
- #----------------------------------------------------------------------------
- # • Se é verdairo ou falo.
- #----------------------------------------------------------------------------
- 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.if_defined?("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
- }
- #==============================================================================
- # • 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
- #==============================================================================
- # • 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].
- # • Salvar script em arquivo de texto : Para fazer, basta por no nome do script da lista,
- # [S].
- #==============================================================================
- Dax.register(:disable_script)
- $RGSS_SCRIPTS.each_with_index { |data, index|
- if data.at(1).include?("[S]")
- File.open("#{rgss.at(1)}.txt", "wb") { |file|
- file.write(String($RGSS_SCRIPTS.at(index)[3]))
- file.close
- }
- end
- $RGSS_SCRIPTS.at(index)[2] = $RGSS_SCRIPTS.at(index)[3] = "" if data.at(1).include?("[D]")
- }
- #==============================================================================
- # * DataManager
- #==============================================================================
- unless defined?(DataManager)
- Mouse.start
- Rpg.data_manager
- else
- class << DataManager
- alias :new_init :init
- def init
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement