Advertisement
DaxSoft

Dax Core i5.6 - No Mouse

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