Advertisement
DaxSoft

Dax Core i5.5.1

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