Advertisement
DaxSoft

Dax Core i4.4

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