Advertisement
DaxSoft

Dax Core i5.7

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