Advertisement
DaxSoft

Dax Core i5.6

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