Advertisement
DaxSoft

Dax Core i8.3

Jul 21st, 2015
661
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 185.27 KB | None | 0 0
  1. #==============================================================================
  2. # * Dax Core
  3. #==============================================================================
  4. # Autor : Dax Aquatic X
  5. # Coadjuvantes :
  6. # Gab!(Método de registrar scripts)
  7. # Gotoken : Módulo de Benchmark.
  8. # Module PNG&RTP : Autor desconhecido.
  9. # Versão : Core i8.3
  10. # Site : www.dax-soft.weebly.com
  11. # Suporte : dax-soft@live.com
  12. #==============================================================================
  13. # Um Core com vários módulos e métodos que facilitará na hora de programar os
  14. # seus scripts, bom proveito.
  15. #==============================================================================
  16. # Conteúdo : • TAGS : Para facilitar a localização dos códigos e explicações. Para acessar
  17. # o comando para localizar, basta apertar Ctrl+F.
  18. #==============================================================================
  19. # i :
  20. # - Array :array
  21. # - Hash :hash
  22. # - API :api
  23. # - String :string
  24. # - Integer :integer
  25. # - Numeric :numeric
  26. # - Position :position
  27. # - File :file
  28. # - Dir :dir
  29. # - Rect :rect
  30. # - Color :color
  31. # - DMath :dmath
  32. # - Key :key
  33. # - Mouse :mouse
  34. # - Object :object
  35. # - Entries :entries
  36. # - DRGSS :drgss
  37. # - Backup :backup
  38. # - SceneManager :scenemanager
  39. # - Sprite_Text :sprite_text
  40. # - Opacity :opacity
  41. # - Read :read
  42. # - Window_Base :window_base
  43. # - SoundBase :soundbase
  44. # - Benchmark :benchmark
  45. # - Input :input
  46. # - Graphics :graphics
  47. #==============================================================================
  48. # • Adicionado comentário padrão. Veja o modo que agora os comentários dos
  49. # métodos estão.
  50. #==============================================================================
  51. # • [Classe do Retorno] : Explicação.
  52. # * Exemplo.(Se possível.)
  53. #==============================================================================
  54. module Dax
  55. extend self
  56. #----------------------------------------------------------------------------
  57. # • Constantes :
  58. #----------------------------------------------------------------------------
  59. # A imagem do ícone do Mouse tem que estar na pasta [System]. Basta você
  60. # por o nome da imagem dentro das áspas. Caso você queira usar um ícone
  61. # do Rpg Maker no lugar de uma imagem, basta você por o id do ícone no lugar
  62. # das áspas.
  63. MOUSE_NAME = ""
  64. #----------------------------------------------------------------------------
  65. # • Variáveis.
  66. #----------------------------------------------------------------------------
  67. @@data = {} # Variável que irá cuidar do registro.
  68. @@__data = {} # Variável cache do registro.
  69. #----------------------------------------------------------------------------
  70. # • [NilClas] : Registrar o script, caso já exista ele atualiza.
  71. # [symbol] : name : Nome do script.
  72. # [string] : author : Autor(es) do script.
  73. # [numeric] : version : Versão do script.
  74. # [array] : requires : Requerimento para o script ser executado. OPCIONAL
  75. # [proc] : &block : Bloco do script que será executado.
  76. #
  77. # requires : Defina dentro da array, uma outra array, que contenha
  78. # o nome do script, o nome do autor e caso deseja, a versão do mesmo.
  79. #
  80. # * Script registrado.
  81. #
  82. # Dax.register(:test, "dax", 1.0) {
  83. # Test = Class.new { def initialize; msgbox("ok"); end; }
  84. # Test.new
  85. # }
  86. #
  87. # * Script registrado com requerimentos.
  88. #
  89. # Dax.register(:test2, "dax", 1.0, [[:test, "dax", 1.0]]) {
  90. # Test.new
  91. # }
  92. #----------------------------------------------------------------------------
  93. def register(name, author, version, requires=[], &block)
  94. need = []
  95. requires.each { |data| need << data unless self.registred?(*data) }
  96. if need.empty?
  97. @@data[[name, author]] = version
  98. block.call
  99. @@__data.each_pair { |(cache_name, cache_author, cache_version), (_need, _block)|
  100. _need.delete_if { |_n_| self.registred?(*_n_) }
  101. next unless _need.empty?
  102. @@__data.delete([cache_name, cache_author, cache_version])
  103. self.register(cache_name, cache_author, cache_version, &_block)
  104. }
  105. else
  106. @@__data[[name, author, version]] = [need, block]
  107. end
  108. return nil
  109. end
  110. #----------------------------------------------------------------------------
  111. # • [Boolean] : Verificar se está registrado.
  112. # [symbol] : name : Nome do script.
  113. # [string] : author : Autor(es) do script.
  114. # [numeric] : version : Versão do script.
  115. # [array] : requires : Requerimento para o script ser executado. OPCIONAL
  116. #----------------------------------------------------------------------------
  117. def registred?(name, author, version=nil)
  118. if @@data.has_key?([name, author])
  119. return true if version.nil?
  120. _version = @@data[[name, author]]
  121. return _version >= version
  122. else
  123. return false
  124. end
  125. end
  126. #----------------------------------------------------------------------------
  127. # • Definir um script como requisição. Caso o script não exista, uma mensagem
  128. # de erro será executado.
  129. # [symbol] : name : Nome do script.
  130. # [string] : author : Autor(es) do script.
  131. # [numeric] : version : Versão do script.
  132. #----------------------------------------------------------------------------
  133. def required(name, author, version=nil)
  134. if @@data.has_key?([name, author])
  135. return true if version.nil?
  136. _version = @@data[[name, author]]
  137. if _version >= version
  138. return true
  139. else
  140. msgbox("Script desatualizado: #{String(name)} v#{String(_version)} por #{String(author)}\nVersão requerida: #{version}")
  141. exit
  142. end
  143. else
  144. msgbox("Script não encontrado: #{String(name)} v#{String(version)} por #{String(author)}")
  145. exit
  146. end
  147. end
  148.  
  149. #----------------------------------------------------------------------------
  150. # • Retorna a variável @@data.
  151. #----------------------------------------------------------------------------
  152. def data
  153. @@data
  154. end
  155. #----------------------------------------------------------------------------
  156. # * Remove uma [Classe], exemplo: Dax.remove(:Scene_Menu)
  157. #----------------------------------------------------------------------------
  158. def remove(symbol_name)
  159. Object.send(:remove_const, symbol_name)
  160. end
  161. end
  162. #==============================================================================
  163. # • Array
  164. #==============================================================================
  165. Dax.register(:array, "dax", 2.0) {
  166. class Array
  167. attr_reader :next
  168. attr_reader :pred
  169. #----------------------------------------------------------------------------
  170. # • [Hash] : Transforma a Array para uma Hash.
  171. # Define um valor padrão para todas as chaves.
  172. # [1, 2].to_hash_keys { :default_value }
  173. # { 1 => :default_value, 2 => :default_value }
  174. #----------------------------------------------------------------------------
  175. def to_hash_keys(&block)
  176. Hash[*self.collect { |v|
  177. [v, block.call(v)]
  178. }.flatten]
  179. end
  180. #----------------------------------------------------------------------------
  181. # • [Array] : Sorteia os objetos em ordem crescente.
  182. #----------------------------------------------------------------------------
  183. def crescent
  184. sort! { |a, b| a <=> b }
  185. end
  186. #----------------------------------------------------------------------------
  187. # • [Array] : Sorteia os objetos em ordem decrescente.
  188. #----------------------------------------------------------------------------
  189. def decrescent
  190. sort! { |a, b| b <=> a }
  191. end
  192. #----------------------------------------------------------------------------
  193. # • [Object] : Retorna para o próximo objeto da id da Array.
  194. # x = [1, 8]
  195. # x.next # 1
  196. # x.next # 8
  197. #----------------------------------------------------------------------------
  198. def next(x=0)
  199. @next = (@next.nil? ? 0 : @next == self.size - 1 ? 0 : @next.next + x)
  200. return self[@next]
  201. end
  202. alias :+@ :next
  203. #----------------------------------------------------------------------------
  204. # • [Object] : Retorna para o objeto anterior da id da Array.
  205. # x = [1, 8]
  206. # x.prev # 8
  207. # x.prev # 1
  208. #----------------------------------------------------------------------------
  209. def pred(x = 0)
  210. @prev = (@prev.nil? ? self.size-1 : @prev == 0 ? self.size-1 : @prev.pred + x)
  211. return self[@prev]
  212. end
  213. alias :-@ :pred
  214. #----------------------------------------------------------------------------
  215. # • [Array] Retorna ao elemento da array que condiz com a condição
  216. # definida no bloco.
  217. # Exemplo:
  218. # [2, 4, 5, 6, 8].if { |element| element >= 4 }
  219. # # 5, 6, 8
  220. #----------------------------------------------------------------------------
  221. def if
  222. return unless block_given?
  223. getResult = []
  224. self.each_with_index{ |arrays| getResult << arrays if yield(arrays) }
  225. return getResult
  226. end
  227. #----------------------------------------------------------------------------
  228. # • [Mixed] : Retorna ao primeiro valor da array, que obedeça a
  229. # condição posta.
  230. # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_evan? } #> 2
  231. # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_odd? } #> 3
  232. #----------------------------------------------------------------------------
  233. def first!
  234. return unless block_given?
  235. return self.each { |element| return element if yield(element) }.at(0)
  236. end
  237. #----------------------------------------------------------------------------
  238. # • [Numeric] : Retorna ao valor de todos os conteúdos, desde que seja números,
  239. # somados, ou subtraidos, ou multiplicado. Por padrão é soma.
  240. # v : :+ # Somar
  241. # :- # Subtrair
  242. # :* # Multiplicar.
  243. #----------------------------------------------------------------------------
  244. def alln?(v=:+)
  245. n = v == :* ? 1 : 0
  246. self.if {|i| i.is_a?(Numeric) }.each { |content|
  247. n += content if v == :+
  248. n -= content if v == :-
  249. n *= content if v == :*
  250. }
  251. return n
  252. end
  253. end
  254. }
  255. #==============================================================================
  256. # • Hash
  257. #==============================================================================
  258. Dax.register(:hash, "dax", 1.3) {
  259. class Hash
  260. #----------------------------------------------------------------------------
  261. # • [NilClass or Mixed] : Pega o valor da chave específicada.
  262. # key : Chave.
  263. # block(proc) : Condição para que retorna ao valor da chave. Opcional.
  264. # {1 => 12}.get(1) #=> 12
  265. # {1 => 12}.get(1) { |k| k.is_a?(String) } #=> nil
  266. #----------------------------------------------------------------------------
  267. def get(key)
  268. if block_given?
  269. self.keys.each { |data|
  270. next unless key == data
  271. return self[data] if yield(self[data])
  272. }
  273. else
  274. self.keys.each { |data| return self[data] if key == data }
  275. end
  276. return nil
  277. end
  278. #----------------------------------------------------------------------------
  279. # • [Mix] : Retorna a última chave adicionada.
  280. #----------------------------------------------------------------------------
  281. def last_key
  282. return self.keys.last
  283. end
  284. end
  285. }
  286. #==============================================================================
  287. # • API : Módulo que armazena informações de algumas APIS.
  288. #==============================================================================
  289. Dax.register(:api, "dax", 3.0) {
  290. module API
  291. extend self
  292. #----------------------------------------------------------------------------
  293. # • [String] : Tipos e seus retornos.. Pegado da internet.. Autor desconhecido
  294. #----------------------------------------------------------------------------
  295. TYPES = {
  296. struct: "p",
  297. int: "i",
  298. long: "l",
  299. INTERNET_PORT: "l",
  300. SOCKET: "p",
  301. C: "p", #– 8-bit unsigned character (byte)
  302. c: "p", # 8-bit character (byte)
  303. # "i"8 – 8-bit signed integer
  304. # "i"8 – 8-bit unsigned integer
  305. S: "N", # – 16-bit unsigned integer (Win32/API: S used for string params)
  306. s: "n", # – 16-bit signed integer
  307. # "i"16 – 16-bit unsigned integer
  308. # "i"16 – 16-bit signed integer
  309. I: "I", # 32-bit unsigned integer
  310. i: "i", # 32-bit signed integer
  311. # "i"32 – 32-bit unsigned integer
  312. # "i"32 – 32-bit signed integer
  313. L: "L", # unsigned long int – platform-specific size
  314. l: "l", # long int – platform-specific size. For discussion of platforms, see:
  315. # (http://groups.google.com/group/ruby-ffi/browse_thread/thread/4762fc77130339b1)
  316. # "i"64 – 64-bit signed integer
  317. # "i"64 – 64-bit unsigned integer
  318. # "l"_long – 64-bit signed integer
  319. # "l"_long – 64-bit unsigned integer
  320. F: "L", # 32-bit floating point
  321. D: "L", # 64-bit floating point (double-precision)
  322. P: "P", # pointer – platform-specific size
  323. p: "p", # C-style (NULL-terminated) character string (Win32API: S)
  324. B: "i", # (?? 1 byte in C++)
  325. V: "V", # For functions that return nothing (return type void).
  326. v: "v", # For functions that return nothing (return type void).
  327. LPPOINT: "p",
  328. # Windows-specific type defs (ms-help://MS.MSDNQTR.v90.en/winprog/winprog/windows_data_types.htm):
  329. ATOM: "I", # Atom ~= Symbol: Atom table stores strings and corresponding identifiers. Application
  330. # places a string in an atom table and receives a 16-bit integer, called an atom, that
  331. # can be used to access the string. Placed string is called an atom name.
  332. # See: http://msdn.microsoft.com/en-us/library/ms648708%28VS.85%29.aspx
  333. BOOL: "i",
  334. BOOLEAN: "i",
  335. BYTE: "p", # Byte (8 bits). Declared as unsigned char
  336. #CALLBACK: K, # Win32.API gem-specific ?? MSDN: #define CALLBACK __stdcall
  337. CHAR: "p", # 8-bit Windows (ANSI) character. See http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  338. COLORREF: "i", # Red, green, blue (RGB) color value (32 bits). See COLORREF for more info.
  339. DWORD: "i", # 32-bit unsigned integer. The range is 0 through 4,294,967,295 decimal.
  340. DWORDLONG: "i", # 64-bit unsigned integer. The range is 0 through 18,446,744,073,709,551,615 decimal.
  341. DWORD_PTR: "l", # Unsigned long type for pointer precision. Use when casting a pointer to a long type
  342. # to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have
  343. # been extended to 64 bits in 64-bit Windows.) BaseTsd.h: #typedef ULONG_PTR DWORD_PTR;
  344. DWORD32: "I",
  345. DWORD64: "I",
  346. HALF_PTR: "i", # Half the size of a pointer. Use within a structure that contains a pointer and two small fields.
  347. # BaseTsd.h: #ifdef (_WIN64) typedef int HALF_PTR; #else typedef short HALF_PTR;
  348. HACCEL: "i", # (L) Handle to an accelerator table. WinDef.h: #typedef HANDLE HACCEL;
  349. # See http://msdn.microsoft.com/en-us/library/ms645526%28VS.85%29.aspx
  350. HANDLE: "l", # (L) Handle to an object. WinNT.h: #typedef PVOID HANDLE;
  351. # todo: Platform-dependent! Need to change to "i"64 for Win64
  352. HBITMAP: "l", # (L) Handle to a bitmap: http://msdn.microsoft.com/en-us/library/dd183377%28VS.85%29.aspx
  353. HBRUSH: "l", # (L) Handle to a brush. http://msdn.microsoft.com/en-us/library/dd183394%28VS.85%29.aspx
  354. HCOLORSPACE: "l", # (L) Handle to a color space. http://msdn.microsoft.com/en-us/library/ms536546%28VS.85%29.aspx
  355. HCURSOR: "l", # (L) Handle to a cursor. http://msdn.microsoft.com/en-us/library/ms646970%28VS.85%29.aspx
  356. HCONV: "l", # (L) Handle to a dynamic data exchange (DDE) conversation.
  357. HCONVLIST: "l", # (L) Handle to a DDE conversation list. HANDLE - L ?
  358. HDDEDATA: "l", # (L) Handle to DDE data (structure?)
  359. HDC: "l", # (L) Handle to a device context (DC). http://msdn.microsoft.com/en-us/library/dd183560%28VS.85%29.aspx
  360. HDESK: "l", # (L) Handle to a desktop. http://msdn.microsoft.com/en-us/library/ms682573%28VS.85%29.aspx
  361. HDROP: "l", # (L) Handle to an internal drop structure.
  362. HDWP: "l", # (L) Handle to a deferred window position structure.
  363. HENHMETAFILE: "l", #(L) Handle to an enhanced metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  364. HFILE: "i", # (I) Special file handle to a file opened by OpenFile, not CreateFile.
  365. # WinDef.h: #typedef int HFILE;
  366. REGSAM: "i",
  367. HFONT: "l", # (L) Handle to a font. http://msdn.microsoft.com/en-us/library/dd162470%28VS.85%29.aspx
  368. HGDIOBJ: "l", # (L) Handle to a GDI object.
  369. HGLOBAL: "l", # (L) Handle to a global memory block.
  370. HHOOK: "l", # (L) Handle to a hook. http://msdn.microsoft.com/en-us/library/ms632589%28VS.85%29.aspx
  371. HICON: "l", # (L) Handle to an icon. http://msdn.microsoft.com/en-us/library/ms646973%28VS.85%29.aspx
  372. HINSTANCE: "l", # (L) Handle to an instance. This is the base address of the module in memory.
  373. # HMODULE and HINSTANCE are the same today, but were different in 16-bit Windows.
  374. HKEY: "l", # (L) Handle to a registry key.
  375. HKL: "l", # (L) Input locale identifier.
  376. HLOCAL: "l", # (L) Handle to a local memory block.
  377. HMENU: "l", # (L) Handle to a menu. http://msdn.microsoft.com/en-us/library/ms646977%28VS.85%29.aspx
  378. HMETAFILE: "l", # (L) Handle to a metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  379. HMODULE: "l", # (L) Handle to an instance. Same as HINSTANCE today, but was different in 16-bit Windows.
  380. HMONITOR: "l", # (L) ?andle to a display monitor. WinDef.h: if(WINVER >= 0x0500) typedef HANDLE HMONITOR;
  381. HPALETTE: "l", # (L) Handle to a palette.
  382. HPEN: "l", # (L) Handle to a pen. http://msdn.microsoft.com/en-us/library/dd162786%28VS.85%29.aspx
  383. HRESULT: "l", # Return code used by COM interfaces. For more info, Structure of the COM Error Codes.
  384. # To test an HRESULT value, use the FAILED and SUCCEEDED macros.
  385. HRGN: "l", # (L) Handle to a region. http://msdn.microsoft.com/en-us/library/dd162913%28VS.85%29.aspx
  386. HRSRC: "l", # (L) Handle to a resource.
  387. HSZ: "l", # (L) Handle to a DDE string.
  388. HWINSTA: "l", # (L) Handle to a window station. http://msdn.microsoft.com/en-us/library/ms687096%28VS.85%29.aspx
  389. HWND: "l", # (L) Handle to a window. http://msdn.microsoft.com/en-us/library/ms632595%28VS.85%29.aspx
  390. INT: "i", # 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.
  391. INT_PTR: "i", # Signed integer type for pointer precision. Use when casting a pointer to an integer
  392. # to perform pointer arithmetic. BaseTsd.h:
  393. #if defined(_WIN64) typedef __int64 INT_PTR; #else typedef int INT_PTR;
  394. INT32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  395. INT64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  396. LANGID: "n", # Language identifier. For more information, see Locales. WinNT.h: #typedef WORD LANGID;
  397. # See http://msdn.microsoft.com/en-us/library/dd318716%28VS.85%29.aspx
  398. LCID: "i", # Locale identifier. For more information, see Locales.
  399. LCTYPE: "i", # Locale information type. For a list, see Locale Information Constants.
  400. LGRPID: "i", # Language group identifier. For a list, see EnumLanguageGroupLocales.
  401. LONG: "l", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  402. LONG32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  403. LONG64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  404. LONGLONG: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  405. LONG_PTR: "l", # Signed long type for pointer precision. Use when casting a pointer to a long to
  406. # perform pointer arithmetic. BaseTsd.h:
  407. #if defined(_WIN64) typedef __int64 LONG_PTR; #else typedef long LONG_PTR;
  408. LPARAM: "l", # Message parameter. WinDef.h as follows: #typedef LONG_PTR LPARAM;
  409. LPBOOL: "i", # Pointer to a BOOL. WinDef.h as follows: #typedef BOOL far *LPBOOL;
  410. LPBYTE: "i", # Pointer to a BYTE. WinDef.h as follows: #typedef BYTE far *LPBYTE;
  411. LPCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  412. # See Character Sets Used By Fonts. http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  413. LPCTSTR: "p", # An LPCWSTR if UNICODE is defined, an LPCSTR otherwise.
  414. LPCVOID: "v", # Pointer to a constant of any type. WinDef.h as follows: typedef CONST void *LPCVOID;
  415. LPCWSTR: "P", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  416. LPDWORD: "p", # Pointer to a DWORD. WinDef.h as follows: typedef DWORD *LPDWORD;
  417. LPHANDLE: "l", # Pointer to a HANDLE. WinDef.h as follows: typedef HANDLE *LPHANDLE;
  418. LPINT: "I", # Pointer to an INT.
  419. LPLONG: "L", # Pointer to an LONG.
  420. LPSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters.
  421. LPTSTR: "p", # An LPWSTR if UNICODE is defined, an LPSTR otherwise.
  422. LPVOID: "v", # Pointer to any type.
  423. LPWORD: "p", # Pointer to a WORD.
  424. LPWSTR: "p", # Pointer to a null-terminated string of 16-bit Unicode characters.
  425. LRESULT: "l", # Signed result of message processing. WinDef.h: typedef LONG_PTR LRESULT;
  426. PBOOL: "i", # Pointer to a BOOL.
  427. PBOOLEAN: "i", # Pointer to a BOOL.
  428. PBYTE: "i", # Pointer to a BYTE.
  429. PCHAR: "p", # Pointer to a CHAR.
  430. PCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  431. PCTSTR: "p", # A PCWSTR if UNICODE is defined, a PCSTR otherwise.
  432. PCWSTR: "p", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  433. PDWORD: "p", # Pointer to a DWORD.
  434. PDWORDLONG: "L", # Pointer to a DWORDLONG.
  435. PDWORD_PTR: "L", # Pointer to a DWORD_PTR.
  436. PDWORD32: "L", # Pointer to a DWORD32.
  437. PDWORD64: "L", # Pointer to a DWORD64.
  438. PFLOAT: "L", # Pointer to a FLOAT.
  439. PHALF_PTR: "L", # Pointer to a HALF_PTR.
  440. PHANDLE: "L", # Pointer to a HANDLE.
  441. PHKEY: "L", # Pointer to an HKEY.
  442. PINT: "i", # Pointer to an INT.
  443. PINT_PTR: "i", # Pointer to an INT_PTR.
  444. PINT32: "i", # Pointer to an INT32.
  445. PINT64: "i", # Pointer to an INT64.
  446. PLCID: "l", # Pointer to an LCID.
  447. PLONG: "l", # Pointer to a LONG.
  448. PLONGLONG: "l", # Pointer to a LONGLONG.
  449. PLONG_PTR: "l", # Pointer to a LONG_PTR.
  450. PLONG32: "l", # Pointer to a LONG32.
  451. PLONG64: "l", # Pointer to a LONG64.
  452. 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.
  453. 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.
  454. POINTER_SIGNED: "l", # A signed pointer.
  455. HPSS: "l",
  456. POINTER_UNSIGNED: "l", # An unsigned pointer.
  457. PSHORT: "l", # Pointer to a SHORT.
  458. PSIZE_T: "l", # Pointer to a SIZE_T.
  459. PSSIZE_T: "l", # Pointer to a SSIZE_T.
  460. PSS_CAPTURE_FLAGS: "l",
  461. PSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
  462. PTBYTE: "p", # Pointer to a TBYTE.
  463. PTCHAR: "p", # Pointer to a TCHAR.
  464. PTSTR: "p", # A PWSTR if UNICODE is defined, a PSTR otherwise.
  465. PUCHAR: "p", # Pointer to a UCHAR.
  466. PUINT: "i", # Pointer to a UINT.
  467. PUINT_PTR: "i", # Pointer to a UINT_PTR.
  468. PUINT32: "i", # Pointer to a UINT32.
  469. PUINT64: "i", # Pointer to a UINT64.
  470. PULONG: "l", # Pointer to a ULONG.
  471. PULONGLONG: "l", # Pointer to a ULONGLONG.
  472. PULONG_PTR: "l", # Pointer to a ULONG_PTR.
  473. PULONG32: "l", # Pointer to a ULONG32.
  474. PULONG64: "l", # Pointer to a ULONG64.
  475. PUSHORT: "l", # Pointer to a USHORT.
  476. PVOID: "v", # Pointer to any type.
  477. PWCHAR: "p", # Pointer to a WCHAR.
  478. PWORD: "p", # Pointer to a WORD.
  479. PWSTR: "p", # Pointer to a null- terminated string of 16-bit Unicode characters.
  480. # For more information, see Character Sets Used By Fonts.
  481. SC_HANDLE: "l", # (L) Handle to a service control manager database.
  482. SERVICE_STATUS_HANDLE: "l", # (L) Handle to a service status value. See SCM Handles.
  483. SHORT: "i", # A 16-bit integer. The range is –32768 through 32767 decimal.
  484. 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.
  485. SSIZE_T: "l", # Signed SIZE_T.
  486. TBYTE: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  487. # http://msdn.microsoft.com/en-us/library/c426s321%28VS.80%29.aspx
  488. TCHAR: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  489. UCHAR: "p", # Unsigned CHAR (8 bit)
  490. UHALF_PTR: "i", # Unsigned HALF_PTR. Use within a structure that contains a pointer and two small fields.
  491. UINT: "i", # Unsigned INT. The range is 0 through 4294967295 decimal.
  492. UINT_PTR: "i", # Unsigned INT_PTR.
  493. UINT32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  494. UINT64: "i", # Unsigned INT64. The range is 0 through 18446744073709551615 decimal.
  495. ULONG: "l", # Unsigned LONG. The range is 0 through 4294967295 decimal.
  496. ULONGLONG: "l", # 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
  497. ULONG_PTR: "l", # Unsigned LONG_PTR.
  498. ULONG32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  499. ULONG64: "i", # Unsigned LONG64. The range is 0 through 18446744073709551615 decimal.
  500. UNICODE_STRING: "P", # Pointer to some string structure??
  501. USHORT: "i", # Unsigned SHORT. The range is 0 through 65535 decimal.
  502. USN: "l", # Update sequence number (USN).
  503. WCHAR: "i", # 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
  504. # In WinNT.h: typedef wchar_t WCHAR;
  505. #WINAPI: K, # Calling convention for system functions. WinDef.h: define WINAPI __stdcall
  506. WORD: "i", # 16-bit unsigned integer. The range is 0 through 65535 decimal.
  507. WPARAM: "i", # Message parameter. WinDef.h as follows: typedef UINT_PTR WPARAM;
  508. VOID: "v", # Any type ? Only use it to indicate no arguments or no return value
  509. vKey: "i",
  510. LPRECT: "p",
  511. char: "p",
  512. }
  513. #----------------------------------------------------------------------------
  514. # • [Array] : Pega os valores especificados no método.. depois verifica
  515. # cada um se é String ou Symbol. Se for Symbol retorna ao valor especificado
  516. # na Constante TYPES.
  517. # Exemplo: types([:BOOL, :WCHAR]) # ["i", "i"]
  518. #----------------------------------------------------------------------------
  519. def types(import)
  520. import2 = []
  521. import.each { |i|
  522. next if i.is_a?(NilClass) or i.is_a?(String)
  523. import2 << TYPES[i]
  524. }
  525. return import2
  526. end
  527. #----------------------------------------------------------------------------
  528. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  529. # Por padrão a DLL é a "user32". O valor de exportação será "i"
  530. #----------------------------------------------------------------------------
  531. def int(function, import, dll="user32")
  532. api = Win32API.new(dll, function, types(import), "i") rescue nil
  533. return api unless block_given?
  534. return Module.new {
  535. yield.each { |key, value|
  536. define_method(key) { return value.is_a?(Array) ? api.call(*value) : value }
  537. module_function key
  538. } if yield.is_a?(Hash)
  539. define_method(:call) { |*args| api.call(*args) }
  540. module_function(:call)
  541. }
  542. end
  543. alias :bool :int
  544. #----------------------------------------------------------------------------
  545. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  546. # Por padrão a DLL é a "user32". O valor de exportação será "l"
  547. #----------------------------------------------------------------------------
  548. def long(function, import, dll="user32")
  549. api = Win32API.new(dll, function, types(import), "l") rescue nil
  550. return api unless block_given?
  551. return Module.new {
  552. yield.each { |key, value|
  553. define_method(key) { return value.is_a?(Array) ? api.call(*value) : value }
  554. module_function key
  555. } if yield.is_a?(Hash)
  556. define_method(:call) { |*args| api.call(*args) }
  557. module_function(:call)
  558. }
  559. end
  560. #----------------------------------------------------------------------------
  561. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  562. # Por padrão a DLL é a "user32". O valor de exportação será "v"
  563. #----------------------------------------------------------------------------
  564. def void(function, import, dll="user32")
  565. api = Win32API.new(dll, function, types(import), "v") rescue nil
  566. return api unless block_given?
  567. return Module.new {
  568. yield.each { |key, value|
  569. define_method(key) { return value.is_a?(Array) ? api.call(*value) : value }
  570. module_function key
  571. } if yield.is_a?(Hash)
  572. define_method(:call) { |*args| api.call(*args) }
  573. module_function(:call)
  574. }
  575. end
  576. #----------------------------------------------------------------------------
  577. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  578. # Por padrão a DLL é a "user32". O valor de exportação será "p"
  579. #----------------------------------------------------------------------------
  580. def char(function, import, dll="user32")
  581. api = Win32API.new(dll, function, types(import), "p") rescue nil
  582. return api unless block_given?
  583. return Module.new {
  584. yield.each { |key, value|
  585. define_method(key) { return value.is_a?(Array) ? api.call(*value) : value }
  586. module_function key
  587. } if yield.is_a?(Hash)
  588. define_method(:call) { |*args| api.call(*args) }
  589. module_function(:call)
  590. }
  591. end
  592. #----------------------------------------------------------------------------
  593. # • [Dll]// : Com esse método você pode especificar uma função de uma Dll.
  594. # function(export, function, import, dll)
  595. # export : Valor da exportação. Formato [Symbol]
  596. # function : Função da Dll.
  597. # import : Valor da importação.
  598. # dll : Dll. Por padrão é a User32
  599. # Esconder o Mouse.
  600. # Exemplo: function(:int, "ShowCursor", [:BOOL]).call(0)
  601. #----------------------------------------------------------------------------
  602. def function(export, function, import, dll="user32")
  603. eval("#{export}(function, import, dll)")
  604. end
  605. #----------------------------------------------------------------------------
  606. # • Especificando o método protegido.
  607. #----------------------------------------------------------------------------
  608. # Métodos privados.
  609. private :long, :int, :char, :void, :types
  610. #----------------------------------------------------------------------------
  611. # • [CopyFile]/Dll : Função da DLL Kernel32 que permite copiar arquivos.
  612. # CopyFile.call(filename_to_copy, filename_copied, replace)
  613. # filename_to_copy : Formato [String]
  614. # filename_copied : Formato [String]
  615. # replace : Formato [Integer] 0 - false 1 - true
  616. # Exemplo: CopyFile.call("System/RGSS300.dll", "./RGSS300.dll", 1)
  617. #----------------------------------------------------------------------------
  618. CopyFile = long("CopyFile", [:LPCTSTR, :LPCTSTR, :BOOL], "kernel32")
  619. #----------------------------------------------------------------------------
  620. # • [Beep]/Dll : Emitir uma frequência de um som do sistema com duração.
  621. # Beep.call(freq, duration)
  622. # freq : Formato [Integer\Hexadécimal]
  623. # duration : Formato [Integer\Hexadécimal]
  624. # Exemplo: Beep.call(2145, 51)
  625. #----------------------------------------------------------------------------
  626. Beep = long('Beep', [:DWORD, :DWORD], 'kernel32')
  627. #----------------------------------------------------------------------------
  628. # • [keybd_event]/Dll : Ela é usada para sintentizar uma combinação de teclas.
  629. # KEYBD_EVENT.call(vk, scan, fdwFlags, dwExtraInfo)
  630. # vk : Formato [Integer/Hexadécimal].
  631. # scan : Formato [Integer]
  632. # fdwFlags : Formato [Integer]
  633. # dwExtraInfo : Formato [Integer]
  634. # Exemplo: KEYBD_EVENT.call(0x01, 0, 0, 0)
  635. #----------------------------------------------------------------------------
  636. KEYBD_EVENT = void('keybd_event', [:BYTE, :BYTE, :DWORD, :ULONG_PTR])
  637. #----------------------------------------------------------------------------
  638. # • Função de limpar memória.
  639. # Permite definir por um comando eval algo que aconteça antes.
  640. # Permite definir com um bloco, algo que aconteça no processo.
  641. #----------------------------------------------------------------------------
  642. def clearMemory(deval="", &block)
  643. eval(deval) unless deval.empty? and !deval.is_a?(String)
  644. KEYBD_EVENT.call(0x7B, 0, 0, 0)
  645. block.call if block_given?
  646. sleep(0.1)
  647. KEYBD_EVENT.call(0x7B, 0, 2, 0)
  648. end
  649. #----------------------------------------------------------------------------
  650. # • Tela chéia
  651. #----------------------------------------------------------------------------
  652. def full_screen
  653. KEYBD_EVENT.(18, 0, 0, 0)
  654. KEYBD_EVENT.(18, 0, 0, 0)
  655. KEYBD_EVENT.(13, 0, 0, 0)
  656. KEYBD_EVENT.(13, 0, 2, 0)
  657. KEYBD_EVENT.(18, 0, 2, 0)
  658. end
  659. #----------------------------------------------------------------------------
  660. # • [GetKeyState]/Dll : Pega o status da chave.
  661. # GetKeyState.call(vk)
  662. # vk : Formato [Integer/Hexadécimal].
  663. # Exemplo: GetKeyState.call(0x01)
  664. #----------------------------------------------------------------------------
  665. GetKeyState = int('GetAsyncKeyState', [:int])
  666. #----------------------------------------------------------------------------
  667. # • [MapVirtualKey] : Traduz (maps) o código de uma key para um código
  668. # escaneado ou o valor de um character.
  669. #----------------------------------------------------------------------------
  670. MapVirtualKey = int("MapVirtualKey", [:UINT, :UINT])
  671. #----------------------------------------------------------------------------
  672. # • [MouseShowCursor]/Dll : Mostrar ou desativar o cusor do Mouse.
  673. # MouseShowCursor.call(value)
  674. # value : Formato [Integer] 0 - false 1 - true
  675. # Exemplo: MouseShowCursor.call(0)
  676. #----------------------------------------------------------------------------
  677. MouseShowCursor = int("ShowCursor", [:int])
  678. #----------------------------------------------------------------------------
  679. # • [CursorPosition]/Dll : Obtem a posição do cursor do Mouse na tela.
  680. # CursorPosition.call(lpPoint)
  681. # lpPoint : Formato [Array]
  682. # Ex: CursorPosition.call([0, 0].pack('ll'))
  683. #----------------------------------------------------------------------------
  684. CursorPosition = int('GetCursorPos', [:LPPOINT])
  685. #----------------------------------------------------------------------------
  686. # • [ScreenToClient]/Dll : Converte as coordenadas da tela para um ponto
  687. # em especifico da área da tela do cliente.
  688. # ScreenToClient.call(hWnd, lpPoint)
  689. #----------------------------------------------------------------------------
  690. ScreenToClient = int('ScreenToClient', [:HWND, :LPPOINT])
  691. #----------------------------------------------------------------------------
  692. # • [GetPrivateProfileString]/Dll : */Ainda não explicado./*
  693. #----------------------------------------------------------------------------
  694. GetPrivateProfileString = long('GetPrivateProfileStringA', [:LPCTSTR, :LPCTSTR, :LPCTSTR, :LPTSTR, :DWORD, :LPCTSTR], 'kernel32')
  695. #----------------------------------------------------------------------------
  696. # • [FindWindow]/Dll : Recupera o identificador da janela superior. Cujo
  697. # o nome da janela é o nome da classe da janela se combina com as cadeias
  698. # especificas.
  699. # FindWindow.call(lpClassName, lpWindowName)
  700. # lpClassName : Formato [String]
  701. # lpWindowName : Formato [String]
  702. #----------------------------------------------------------------------------
  703. FindWindow = long('FindWindowA', [:LPCTSTR, :LPCTSTR])
  704. #----------------------------------------------------------------------------
  705. # • [Handle]/Dll : Retorna ao Handle da janela.
  706. #----------------------------------------------------------------------------
  707. def hWND(game_title=nil)
  708. return API::FindWindow.call('RGSS Player', game_title || load_data("./Data/System.rvdata2").game_title.to_s)
  709. end
  710. #----------------------------------------------------------------------------
  711. # • [Handle]/Dll : Retorna ao Handle da janela. Método protegido.
  712. #----------------------------------------------------------------------------
  713. def hwnd(*args)
  714. hWND(*args)
  715. end
  716. #----------------------------------------------------------------------------
  717. # • [ReadIni]/Dll : */Ainda não explicado./*
  718. #----------------------------------------------------------------------------
  719. ReadIni = GetPrivateProfileString
  720. #----------------------------------------------------------------------------
  721. # • [SetWindowPos]/Dll : Modifica os elementos da janela como, posição, tamanho.
  722. #----------------------------------------------------------------------------
  723. SetWindowPos = int("SetWindowPos", [:HWND, :HWND, :int, :int, :int, :int, :UINT])
  724. #----------------------------------------------------------------------------
  725. # • [GetWindowRect]/Dll : Obtem as dimensões do retângulo da janela.
  726. # GetWindowRect.call(hWnd, lpRect)
  727. #----------------------------------------------------------------------------
  728. GetWindowRect = int('GetWindowRect', [:HWND, :LPRECT])
  729. #----------------------------------------------------------------------------
  730. # • [StateKey]/Dll : Retorna ao status específico da chave.
  731. # StateKey.call(VK)
  732. # VK : Formato [Integer/Hexadécimal].
  733. #----------------------------------------------------------------------------
  734. StateKey = int("GetKeyState", [:int])
  735. #----------------------------------------------------------------------------
  736. # • [SetCursorPos]/Dll : Move o cursor do Mouse para um ponto específico
  737. # da tela.
  738. # SetCursorPos.call(x, y)
  739. # x, y : Formato [Integer/Float]
  740. #----------------------------------------------------------------------------
  741. SetCursorPos = int("SetCursorPos", [:long, :long])
  742. #----------------------------------------------------------------------------
  743. # • [GetKeyboardState]/Dll : Cópia o status das 256 chaves para um
  744. # buffer especificado.
  745. #----------------------------------------------------------------------------
  746. GetKeyboardState = Win32API.new('user32', 'GetKeyboardState', ['P'], 'V')
  747. #----------------------------------------------------------------------------
  748. # • [GetAsyncKeyState]/Dll : Determina o estado da chave no momento em que a
  749. # função é chamada.
  750. # GetAsyncKeyState.call(Vk)
  751. # VK : Formato [Integer/Hexadécimal].
  752. #----------------------------------------------------------------------------
  753. GetAsyncKeyState = int('GetAsyncKeyState', [:int])
  754. #----------------------------------------------------------------------------
  755. # • [WideCharToMultiByte] : [MultiByteToWideChar] // Comentários
  756. # não adicionados.
  757. #----------------------------------------------------------------------------
  758. WideCharToMultiByte = Win32API.new('kernel32', 'WideCharToMultiByte', 'ilpipipp', 'i')
  759. MultiByteToWideChar = Win32API.new('kernel32', 'MultiByteToWideChar', 'ilpipi', 'i')
  760. #----------------------------------------------------------------------------
  761. # • [AdjustWindowRect] : Calcula o tamanho requerido do retângulo da Janela.
  762. #----------------------------------------------------------------------------
  763. AdjustWindowRect = int("AdjustWindowRect", [:LPRECT, :DWORD, :BOOL])
  764. #----------------------------------------------------------------------------
  765. # • Constantes [SetWindowPos]
  766. #----------------------------------------------------------------------------
  767. SWP_ASYNCWINDOWPOS = 0x4000
  768. # Desenha os frames (definidos na classe da janela descrita) em torno na janela.
  769. SWP_DRAWFRAME = 0x0020
  770. # Esconde a janela.
  771. SWP_HIDEWINDOW = 0x0080
  772. # Não pode ser ativada nem movida
  773. SWP_NOACTIVATE = 0x0010
  774. # Não permite mover
  775. SWP_NOMOVE = 0x0002
  776. # Não permite redimensionar
  777. SWP_NOSIZE = 0x0001
  778. # Mostra a Janela
  779. SWP_SHOWWINDOW = 0x0040
  780. # Coloca a janela na parte inferior na ordem de Z. Se identificar uma janela
  781. # superior ela perde os seus status.
  782. HWND_BOTTOM = 1
  783. # Coloca a janela acima de todas as janelas que não estão em primeiro plano.
  784. HWND_NOTOPMOST = -2
  785. # Poem a janela no Topo na ordem de Z.
  786. HWND_TOP = 0
  787. # Poem a janela acima de todas que não estão em primeiro plano. Mantendo a
  788. # posição.
  789. HWND_TOPMOST = -1
  790. #----------------------------------------------------------------------------
  791. # • [SetActiveWindow]/ Dll : Ativa a Window.
  792. #----------------------------------------------------------------------------
  793. SetActiveWindow = long("SetActiveWindow", [:HWND])
  794. #----------------------------------------------------------------------------
  795. # • WindowFromPoint : Retorna ao handle da janela, que contém um ponto
  796. # específico.
  797. #----------------------------------------------------------------------------
  798. WindowFromPoint = long("WindowFromPoint", [:HWND])
  799. #----------------------------------------------------------------------------
  800. # • ShowWindow : Mostra a janela em um estado específico.
  801. #----------------------------------------------------------------------------
  802. ShowWindow = long("ShowWindow", [:HWND, :LONG])
  803. # Força a janela a minimizar
  804. SW_FORCEMINIMIZE = 11
  805. # Esconde a janela, ativa outra.
  806. SW_HIDE = 0
  807. # Maximiza a janela.
  808. SW_MAXIMIZE = 3
  809. # Minimiza a janela
  810. SW_MINIMIZE = 6
  811. # Restaura o estado da janela.
  812. SW_RESTORE = 9
  813. # Ativa a janela a mostrando na posição original.
  814. SW_SHOW = 5
  815. #----------------------------------------------------------------------------
  816. # • [SetWindowText] : Permite modificar o título da janela.
  817. #----------------------------------------------------------------------------
  818. SetWindowText = int("SetWindowText", [:HWND, :LPCTSTR])
  819. #----------------------------------------------------------------------------
  820. # • [GetDesktopWindow] : Retorna ao handle da janela em relação ao Desktop.
  821. #----------------------------------------------------------------------------
  822. GetDesktopWindow = long("GetDesktopWindow", [:HWND])
  823. #----------------------------------------------------------------------------
  824. # • [GetSystemMetric] : Obtem um sistema métrico específico ou a configuração
  825. # do sistema. As dimensões retornadas são em pixel.
  826. #----------------------------------------------------------------------------
  827. GetSystemMetric = int("GetSystemMetric", [:int])
  828. #----------------------------------------------------------------------------
  829. # • [GetSystemMetric]/Constantes:
  830. #----------------------------------------------------------------------------
  831. # Obtem a flag que especifica como o sistema está organizando as janelas
  832. # minimizadas.
  833. SM_ARRANGE = 56
  834. # Obtem o tamanho da borda da Janela em pixel.
  835. SM_CXBORDER = 5
  836. # Valor do tamanho da área do cliente pra uma Janela em modo de tela-chéia.
  837. # em pixel.
  838. SM_CXFULLSCREEN = 16
  839. # Para mais informações dos valores, visite :
  840. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  841. #----------------------------------------------------------------------------
  842. # • [GetClientRect] : Retorna ao rect da área da Janela.
  843. # Uses :
  844. # lpRect = [0,0,0,0].pack("L*")
  845. # GetClientRect.(hwnd, lpRect)
  846. # lpRect = lpRect.unpack("L*")
  847. #----------------------------------------------------------------------------
  848. GetClientRect = int("GetClientRect", [:HWND, :LPRECT])
  849. #----------------------------------------------------------------------------
  850. # • [GetModuleHandle] : Retorna ao Handle do módulo, do módulo específicado.
  851. # Pode ser aquivo '.dll' ou '.exe'. Exemplo:
  852. # GetModuleHandle.call('System/RGSS300.dll')
  853. #----------------------------------------------------------------------------
  854. GetModuleHandle = long("GetModuleHandle", [:LPCTSTR], "kerne32")
  855. #----------------------------------------------------------------------------
  856. # • [FreeLibrary] : Libera o módulo que está carregado na DLL específica.
  857. #----------------------------------------------------------------------------
  858. FreeLibrary = long("FreeLibrary", [:HMODULE], "kernel32")
  859. #----------------------------------------------------------------------------
  860. # • [LoadLibrary] : Carrega um endereço de um módulo em específico.
  861. # LoadLibrary.call(Nome da Libraria(dll/exe))
  862. # [Handle] : Retorna ao valor do Handle do módulo caso der certo.
  863. #----------------------------------------------------------------------------
  864. LoadLibrary = long("LoadLibrary", [:LPCTSTR], "kernel32")
  865. #----------------------------------------------------------------------------
  866. # • [GetProcAddress] : Retorna ao endereço da função exportada ou a variável
  867. # de uma DLL específica.
  868. # GetProcAddress.call(hModule, lpProcName)
  869. # hModule : É o valor do handle. Você pode pega-lo usando o LoadLibrary
  870. # lpProcName : A função ou o nome da variável.
  871. #----------------------------------------------------------------------------
  872. GetProcAddress = long("GetProcAddress", [:HMODULE, :LPCSTR], "kernel32")
  873. #----------------------------------------------------------------------------
  874. # • [GetSystemMetrics] : Retorna á uma configuração específica do sistema
  875. # métrico.
  876. #----------------------------------------------------------------------------
  877. GetSystemMetrics = int("GetSystemMetrics", [:int])
  878. #----------------------------------------------------------------------------
  879. # • [GetSystemMetrics]::Constantes. #Para mais visite:
  880. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  881. #----------------------------------------------------------------------------
  882. SM_CXSCREEN = 0 # O tamanho(width/largura) da janela em pixel.
  883. SM_CYSCREEN = 1 # O tamanho(height/comprimento) da janela em pixel.
  884. SM_CXFULLSCREEN = 16 # O tamanho da largura da tela chéia da janela.
  885. SM_CYFULLSCREEN = 17 # O tamanho do comprimento da tela chéia da janela.
  886. #----------------------------------------------------------------------------
  887. # • [SetPriorityClass] : Definir a classe prioritária para um processo
  888. # específico.
  889. # Para ver os processo e tal : Link abaixo.
  890. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms686219(v=vs.85).aspx
  891. #----------------------------------------------------------------------------
  892. SetPriorityClass = int("SetPriorityClass", [:HANDLE, :DWORD], "kernel32")
  893. #----------------------------------------------------------------------------
  894. # • [InternetOpenA] : Inicializa o uso de uma aplicação, de uma função da
  895. # WinINet.
  896. #----------------------------------------------------------------------------
  897. InternetOpenA = function(:int, "InternetOpenA", [:LPCTSTR, :DWORD, :LPCTSTR, :LPCTSTR, :DWORD], "wininet")
  898. #----------------------------------------------------------------------------
  899. # • [RtlMoveMemory] : Movimenta um bloco de memoria para outra locação.
  900. #----------------------------------------------------------------------------
  901. RtlMoveMemory = function(:int, "RtlMoveMemory", [:char, :char, :int], "kernel32")
  902. #----------------------------------------------------------------------------
  903. # • [ShellExecute] :
  904. #----------------------------------------------------------------------------
  905. Shellxecute = long("ShellExecute", [:LPCTSTR, :LPCTSTR, :LPCTSTR,
  906. :LPCTSTR, :LPCTSTR, :LONG], "Shell32.dll")
  907. #----------------------------------------------------------------------------
  908. # • [Método protegido] : Método usado para chamar a função LoadLibrary.
  909. #----------------------------------------------------------------------------
  910. def dlopen(name, fA=nil)
  911. l = LoadLibrary.(String(name))
  912. return l if fA.nil?
  913. return GetProcAddress.(l, String(fA))
  914. end
  915. #----------------------------------------------------------------------------
  916. # • Converte um texto para o formato UTF-8
  917. # textUTF(text)
  918. # * text : Texto.
  919. #----------------------------------------------------------------------------
  920. def textUTF(text)
  921. wC = MultiByteToWideChar.call(65001, 0, text, -1, "", 0)
  922. MultiByteToWideChar.call(65001, 0, text, -1, text = "\0\0" * wC, wC)
  923. return text
  924. end
  925. #----------------------------------------------------------------------------
  926. # • [TrueClass/FalseClass] : Retorna verdadeiro caso o Caps Lock esteja
  927. # ativo e retorna Falso caso não esteja ativo.
  928. #----------------------------------------------------------------------------
  929. def get_caps_lock
  930. return int("GetKeyState", [:vKey]).call(20) == 1
  931. end
  932. #----------------------------------------------------------------------------
  933. # • Abre a URL de um site o direcionado para o navegador padrão do usuário.
  934. #----------------------------------------------------------------------------
  935. def open_site(url)
  936. c = Win32API.new("Shell32", "ShellExecute", "pppppl", "l")
  937. c.call(nil, "open", url, nil, nil, 0)
  938. end
  939. #----------------------------------------------------------------------------
  940. # • Valor dá base é o endereço. Pegar a variável.
  941. # base = 0x10000000
  942. # adr_loc_ram(0x25EB00 + 0x214, val, base)
  943. #----------------------------------------------------------------------------
  944. def adr_loc_ram(adr, val, base)
  945. return DL::CPtr.new(base + adr)[0, val.size] = size
  946. end
  947. #============================================================================
  948. # • MessageBox
  949. #============================================================================
  950. module MessageBox
  951. extend self
  952. # handle, string, title, format.
  953. FunctionMessageBox = Win32API.new("user32", "MessageBoxW", "lppl", "l")
  954. #--------------------------------------------------------------------------
  955. # • [Constantes] Botões:
  956. #--------------------------------------------------------------------------
  957. # Adiciona três botões a mensagem: Anular, Repetir e Ignorar.
  958. ABORTRETRYIGNORE = 0x00000002
  959. # Adiciona três botões a mensagem: Cancelar, Tentar e Continuar.
  960. CANCELTRYCONTINUE = 0x00000006
  961. # Adiciona o botão de ajuda.
  962. HELP = 0x00004000
  963. # Adiciona o botão Ok.
  964. SOK = 0x00000000
  965. # Adiciona o botão OK e Cancelar.
  966. OKCANCEL = 0x00000001
  967. # Adiciona os botões: Repetir e Cancelar.
  968. RETRYCANCEL = 0x00000005
  969. # Adiciona os botões: Sim e Não
  970. YESNO = 0x00000004
  971. # Adiciona os botões: Sim, Não e Cancelar
  972. YESNOCANCEL = 0x00000003
  973. #--------------------------------------------------------------------------
  974. # • [Constantes] Ícones:
  975. #--------------------------------------------------------------------------
  976. # Adiciona um ícone de exclamação
  977. ICONEXCLAMATION = 0x00000030
  978. # Adiciona um ícone de informação.
  979. ICONINFORMATION = 0x00000040
  980. # Adiciona um ícone de um círculo com um ponto de interrogação.
  981. ICONQUESTION = 0x00000020
  982. # Adiciona um íconde parar na mensagem.
  983. ICONSTOP = 0x00000010
  984. #--------------------------------------------------------------------------
  985. # • [Constantes] Valores de retorno dos botões:
  986. #--------------------------------------------------------------------------
  987. ABORT = 3 # Retorno do valor do botão de Anular
  988. CANCEL = 2 # Retorno do valor do botão de Cancelar.
  989. CONTINUE = 11 # Retorno do valor do botão de Continuar.
  990. IGNORE = 5 # Retorno do valor de ignonar.
  991. NO = 7 # Retorno do valor do botão de Não.
  992. OK = 1 # Retorno do valor do botão de Ok.
  993. RETRY = 4 # Retorno do valor de repetir.
  994. TRYAGAIN = 10 # Retorno do valor de Repetir.
  995. YES = 6 # Retorno do valor do botão de Sim.
  996. #--------------------------------------------------------------------------
  997. # • [Constantes] Valores adicionais.
  998. #--------------------------------------------------------------------------
  999. RIGHT = 0x00080000 # Os textos ficarão justificados a direita.
  1000. TOPMOST = 0x00040000 # O estilo da mensagem é criado como WB_EX_TOPMOST
  1001. #--------------------------------------------------------------------------
  1002. # • [call] : Retorna aos valores dos botões. Para serem usados
  1003. # como condição, de que se ao clicar.
  1004. # API::MessageBox.call(title, string, format)
  1005. # title -> Título da caixa.
  1006. # string -> Conteúdo da caixa.
  1007. # format -> Formato, no caso seria os botões e ícones.
  1008. #--------------------------------------------------------------------------
  1009. def call(title, string, format)
  1010. return FunctionMessageBox.call(API.hWND, API.textUTF(string), API.textUTF(title), format)
  1011. end
  1012. #--------------------------------------------------------------------------
  1013. # • [messageBox] : Mesma função do Call a diferença é que e protegido.
  1014. #--------------------------------------------------------------------------
  1015. def messageBox(*args)
  1016. self.call(*args)
  1017. end
  1018. protected :messageBox
  1019. end
  1020. #============================================================================
  1021. # • RTP
  1022. #============================================================================
  1023. module RTP
  1024. extend self
  1025. extend API
  1026. #--------------------------------------------------------------------------
  1027. # • Variável & Constante
  1028. #--------------------------------------------------------------------------
  1029. @@rtp = nil
  1030. DPATH = 'Software\Enterbrain\RGSS3\RTP'
  1031. DLL = 'Advapi32.dll'
  1032. #--------------------------------------------------------------------------
  1033. # • Retorna ao caminho do diretório do RTP.
  1034. #--------------------------------------------------------------------------
  1035. def path
  1036. unless @@rtp
  1037. read_ini = ->(val) { File.foreach("Game.ini") { |line| break($1) if line =~ /^#{val}=(.*)$/ }
  1038. }
  1039. key = type = size = [].pack("x4")
  1040. long("RegOpenKeyEx", [:HKEY, :LPCTST, :DWORD, :REGSAM, :PHKEY], DLL).call(
  1041. 2147483650, DPATH, 0, 131097, key)
  1042. key = key.unpack('l').first
  1043. rtp_data = read_ini["RTP"]
  1044. long("RegQueryValueEx", [:HKEY, :LPCTSTR, :LPDWORD, :LPDWORD, :LPBYTE, :LPDWORD], DLL).call(
  1045. key, rtp_data, 0, type, 0, size)
  1046. buffer = ' '*size.unpack('l').first
  1047. long("RegQueryValueEx", [:HKEY, :LPCTSTR, :LPDWORD, :LPDWORD, :LPBYTE, :LPDWORD], DLL).call(
  1048. key, rtp_data, 0, type, buffer, size)
  1049. long("RegCloseKey", [:HKEY], DLL).call(key)
  1050. @@rtp = (buffer.gsub(/\\/, '/')).delete!(0.chr)
  1051. @@rtp += "/" if @@rtp[-1] != "/"
  1052. end
  1053. return @@rtp
  1054. end
  1055. end
  1056. #============================================================================
  1057. # • ::PNG
  1058. #============================================================================
  1059. module PNG
  1060. extend self
  1061. private
  1062. #--------------------------------------------------------------------------
  1063. # • Criar o header do arquivo
  1064. #--------------------------------------------------------------------------
  1065. def make_header(file)
  1066. # Número mágico
  1067. file.write([0x89].pack('C'))
  1068. # PNG
  1069. file.write([0x50, 0x4E, 0x47].pack('CCC'))
  1070. # Fim de linha estilo DOS para verificação de conversão DOS - UNIX
  1071. file.write([0x0D, 0x0A].pack('CC'))
  1072. # Caractere de fim de linha (DOS)
  1073. file.write([0x1A].pack('C'))
  1074. # Caractere de fim de linha (UNIX)
  1075. file.write([0x0A].pack('C'))
  1076. end
  1077. #--------------------------------------------------------------------------
  1078. # • Aquisição da soma mágica
  1079. #--------------------------------------------------------------------------
  1080. def checksum(string)
  1081. Zlib.crc32(string)
  1082. end
  1083. #--------------------------------------------------------------------------
  1084. # • Criação do chunk de cabeçalho
  1085. #--------------------------------------------------------------------------
  1086. def make_ihdr(bitmap, file)
  1087. data = ''
  1088. # Largura
  1089. data += [bitmap.width, bitmap.height].pack('NN')
  1090. # Bit depth (???)
  1091. data += [0x8].pack('C')
  1092. # Tipo de cor
  1093. data += [0x6].pack('C')
  1094. data += [0x0, 0x0, 0x0].pack('CCC')
  1095. # Tamanho do chunk
  1096. file.write([data.size].pack('N'))
  1097. # Tipo de chunk
  1098. file.write('IHDR')
  1099. file.write(data)
  1100. # Soma mágica
  1101. file.write([checksum('IHDR' + data)].pack('N'))
  1102. end
  1103. #--------------------------------------------------------------------------
  1104. # • Criação do chunk de dados
  1105. #--------------------------------------------------------------------------
  1106. def make_idat(bitmap, file)
  1107. data = ''
  1108. for y in 0...bitmap.height
  1109. data << "\0"
  1110. for x in 0...bitmap.width
  1111. color = bitmap.get_pixel(x, y)
  1112. data << [color.red, color.green, color.blue, color.alpha].pack('C*')
  1113. end
  1114. end
  1115. # Desinflamento (jeito legal de dizer compressão...) dos dados
  1116. data = Zlib::Deflate.deflate(data)
  1117. # Tamanho do chunk
  1118. file.write([data.size].pack('N'))
  1119. # Tipo de chunk
  1120. file.write('IDAT')
  1121. # Dados (a imagem)
  1122. file.write(data)
  1123. # Soma mágica
  1124. file.write([checksum('IDAT' + data)].pack('N'))
  1125. end
  1126. #--------------------------------------------------------------------------
  1127. # • Criação do chunk final.
  1128. #--------------------------------------------------------------------------
  1129. def make_iend(file)
  1130. # Tamanho do chunk
  1131. file.write([0].pack('N'))
  1132. # Tipo de chunk
  1133. file.write('IEND')
  1134. # Soma mágica
  1135. file.write([checksum('IEND')].pack('N'))
  1136. end
  1137. public
  1138. #--------------------------------------------------------------------------
  1139. # • Salvar :
  1140. # bitmap : Bitmap.
  1141. # filename : Nome do arquivo.
  1142. #--------------------------------------------------------------------------
  1143. def save(bitmap, filename)
  1144. # Verificar se tem a extenção .png
  1145. filename = filename.include?(".png") ? filename : filename << ".png"
  1146. # Criação do arquivo
  1147. file = File.open(filename, 'wb')
  1148. # Criação do cabeçalho
  1149. make_header(file)
  1150. # Criação do primeiro chunk
  1151. make_ihdr(bitmap, file)
  1152. # Criação dos dados
  1153. make_idat(bitmap, file)
  1154. # Criação do final
  1155. make_iend(file)
  1156. file.close
  1157. end
  1158. end
  1159. #============================================================================
  1160. # • FindDir
  1161. #============================================================================
  1162. class FindDir
  1163. #--------------------------------------------------------------------------
  1164. # • Variáveis públicas da instâncias.
  1165. #--------------------------------------------------------------------------
  1166. attr_accessor :dir
  1167. attr_accessor :files
  1168. attr_accessor :folders
  1169. attr_accessor :type
  1170. #--------------------------------------------------------------------------
  1171. # • Diretórios principais.
  1172. #--------------------------------------------------------------------------
  1173. def self.env
  1174. env = ENV['USERPROFILE'].gsub("\\", "/")
  1175. return {
  1176. desktop: env + "/Desktop", # Desktop diretório.
  1177. recent: env + "/Recent", # Recent diretório.
  1178. drive: ENV["HOMEDRIVE"], # Diretório do Drive.
  1179. doc: env + "/Documents", # Diretório dos documento.
  1180. current: Dir.getwd, # Diretório da atual.
  1181. }
  1182. end
  1183. #--------------------------------------------------------------------------
  1184. # • Inicialização dos objetos.
  1185. #--------------------------------------------------------------------------
  1186. def initialize(direction=Dir.getwd)
  1187. @dir = String(direction)
  1188. @files = []
  1189. @folders = []
  1190. setup
  1191. end
  1192. #--------------------------------------------------------------------------
  1193. # • Configuração.
  1194. #--------------------------------------------------------------------------
  1195. def setup
  1196. @files = []
  1197. @folders = []
  1198. for data in Dir[@dir+"/*"]
  1199. if FileTest.directory?(data)
  1200. @folders << data
  1201. else
  1202. @files << data
  1203. end
  1204. end
  1205. end
  1206. #--------------------------------------------------------------------------
  1207. # • Todos os arquivos.
  1208. #--------------------------------------------------------------------------
  1209. def all_files
  1210. @folders + @files
  1211. end
  1212. #--------------------------------------------------------------------------
  1213. # • Mover para outro diretório.
  1214. #--------------------------------------------------------------------------
  1215. def move_to(dir)
  1216. @dir = File.expand_path(@dir + "/#{dir}")
  1217. setup
  1218. end
  1219. #--------------------------------------------------------------------------
  1220. # • Mover para os diretórios principais.
  1221. #--------------------------------------------------------------------------
  1222. def move_to_dir(sym)
  1223. @dir = API::FindDir.env.get(sym)
  1224. setup
  1225. end
  1226.  
  1227. def ret
  1228. @dir != API::FindDir.env.get(:drive)
  1229. end
  1230. end
  1231. #============================================================================
  1232. # • Network
  1233. #============================================================================
  1234. module Network
  1235. include API
  1236. extend self
  1237. #--------------------------------------------------------------------------
  1238. # • [InternetGetConnectedState] : Verifica o estado de conexão da internet.
  1239. #--------------------------------------------------------------------------
  1240. InternetGetConnectedState = int("InternetGetConnectedState", [:LPDWORD, :DWORD], "wininet.dll")
  1241. #--------------------------------------------------------------------------
  1242. # • [URLDownloadToFile] : Baixa um arquivo direto de um link da internet.
  1243. #--------------------------------------------------------------------------
  1244. URLDownloadToFile = int("URLDownloadToFile", [:LPCTSTR, :LPCTSTR, :LPCTSTR,
  1245. :int, :int], "urlmon.dll")
  1246. #--------------------------------------------------------------------------
  1247. # • Verificar a conexão com internet.
  1248. #--------------------------------------------------------------------------
  1249. def connected?
  1250. InternetGetConnectedState.call(' ', 0) == 0x01
  1251. end
  1252. #--------------------------------------------------------------------------
  1253. # • Baixar um arquivo direto de um link.
  1254. # url : Link do arquivo.
  1255. # dest : Pasta de destino.
  1256. # open : Abrir o arquivo ao terminar de baixar.
  1257. #
  1258. # • Example:
  1259. # url = "http://www.news2news.com/vfp/downloads/w32data.zip"
  1260. # dstfile = "w32data.zip"
  1261. # URLDownloadToFile.run(url, dstfile)
  1262. #--------------------------------------------------------------------------
  1263. def link_download(url, dest, open = false)
  1264. return unless connected?
  1265. hresult = URLDownloadToFile.call(NIL, url, dest, 0, 0)
  1266. if (hresult == 0)
  1267. return true unless open
  1268. Shellxecute.call(nil, "open", dest, nil, nil, 1)
  1269. return true
  1270. else
  1271. raise("URLDownloadToFile call failed: %X\n", hresult)
  1272. end
  1273. end
  1274. end
  1275. protected :hwnd, :open, :function
  1276. end
  1277. }
  1278. #==============================================================================
  1279. # * String
  1280. #==============================================================================
  1281. Dax.register(:string, "dax", 2.0) {
  1282. class String
  1283. #----------------------------------------------------------------------------
  1284. # • [String] : Remove a extensão do nome do arquivo e assume por outra.
  1285. # filename : Nome do aquivo.
  1286. # extension : Nova extensão.
  1287. # "Hello.rb".extn(".rvdata2") # "Hello.rvdata2"
  1288. #----------------------------------------------------------------------------
  1289. def extn(extension)
  1290. return self.gsub(/\.(\w+)/, extension.include?(".") ? extension : "." + extension)
  1291. end
  1292. #--------------------------------------------------------------------------
  1293. # • [String] : converter à String em UTF8
  1294. #--------------------------------------------------------------------------
  1295. def to_utf8
  1296. API.textUTF(self)
  1297. end
  1298. #----------------------------------------------------------------------------
  1299. # • [String] : Converter a String para w_char. Pra chamadas WinAPI.
  1300. #----------------------------------------------------------------------------
  1301. def w_char
  1302. wstr = ""
  1303. self.size.times { |i| wstr += self[i, 1] + "\0" }
  1304. wstr += "\0"
  1305. return wstr
  1306. end
  1307. #--------------------------------------------------------------------------
  1308. # • [Array] : Extrai somente os números da String, e retorna a uma Array.
  1309. # Exemplo: "João89".numbers # [8, 9]
  1310. #--------------------------------------------------------------------------
  1311. def numbers
  1312. self.scan(/-*\d+/).collect{|n|n.to_i}
  1313. end
  1314. alias :num :numbers
  1315. #----------------------------------------------------------------------------
  1316. # • [String] : Aplicando Case Sensitive
  1317. # "Exemplo 2" => "Exemplo_2"
  1318. #----------------------------------------------------------------------------
  1319. def case_sensitive
  1320. return self.gsub(" ", "_")
  1321. end
  1322. #----------------------------------------------------------------------------
  1323. # • [Symbol] : Transforma em símbolo a string.
  1324. # "Ola Meu Nome É" #:ola_menu_nome_é
  1325. #----------------------------------------------------------------------------
  1326. def symbol
  1327. return self.case_sensitive.downcase.to_sym
  1328. end
  1329. #----------------------------------------------------------------------------
  1330. # • [String] : Remove o último caractere da String.
  1331. #----------------------------------------------------------------------------
  1332. def backslash
  1333. return String(self[0, self.split(//).size-1])
  1334. end
  1335. #----------------------------------------------------------------------------
  1336. # • Método xor.
  1337. #----------------------------------------------------------------------------
  1338. def ^(string)
  1339. bytes.map.with_index{|byte, index| byte ^ other[index % other.size].ord }.pack("C*")
  1340. end
  1341. alias xor ^
  1342. end
  1343. }
  1344. #==============================================================================
  1345. # * Integer
  1346. #==============================================================================
  1347. Dax.register(:integer, "dax", 2.5) {
  1348. class Integer
  1349. #----------------------------------------------------------------------------
  1350. # • [TrueClass/FalseClass] : Verifica-se e par.
  1351. #----------------------------------------------------------------------------
  1352. def is_evan?
  1353. return (self & 1) == 0
  1354. end
  1355. #----------------------------------------------------------------------------
  1356. # • [TrueClass/FalseClass] : Verifica-se e impar.
  1357. #----------------------------------------------------------------------------
  1358. def is_odd?
  1359. return (self & 1) == 1
  1360. end
  1361. #----------------------------------------------------------------------------
  1362. # • [Integer] : Aumenta o valor até chegar ao máximo(definido), quando
  1363. # chegar ao máximo(definido) retorna a zero(pode definir).
  1364. # back : Valor de retorno.
  1365. # max : Valor máximo.
  1366. # compare : Método de comparação
  1367. #----------------------------------------------------------------------------
  1368. def up(back, max, compare=:>)
  1369. return (self.method(compare).call(max) ? back : (self + 1))
  1370. end
  1371. #----------------------------------------------------------------------------
  1372. # • [Integer] : Diminui o valor até chegar a zero, quando chegar a zero(pode definir)
  1373. # retorna ao valor máximo(defindo).
  1374. # back : Valor de retorno.
  1375. # max : Valor máximo.
  1376. # compare : Método de comparação
  1377. #----------------------------------------------------------------------------
  1378. def down(max, r=0, compare=:<)
  1379. return (self.method(compare).call(back) ? max : (self - 1))
  1380. end
  1381. #----------------------------------------------------------------------------
  1382. # • [Integer] : Formula de número randômico.
  1383. #----------------------------------------------------------------------------
  1384. def aleatory
  1385. return ((1..(self.abs)).to_a).shuffle[rand(self).to_i].to_i
  1386. end
  1387. end
  1388. }
  1389. #==============================================================================
  1390. # • Numeric
  1391. #==============================================================================
  1392. Dax.register(:numeric, "dax", 2.0) {
  1393. class Numeric
  1394. #----------------------------------------------------------------------------
  1395. # * [Numeric] : Transformar em porcentagem
  1396. # a : Valor atual.
  1397. # b : Valor máximo.
  1398. #----------------------------------------------------------------------------
  1399. def to_p(a, b)
  1400. self * a / b
  1401. end
  1402. alias :percent :to_p
  1403. #----------------------------------------------------------------------------
  1404. # • [Numeric] : Pega um do porcento.
  1405. # max : Valor máximo.
  1406. #----------------------------------------------------------------------------
  1407. def p_to(max)
  1408. (self * max) / 100
  1409. end
  1410. alias :proportion :p_to
  1411. #----------------------------------------------------------------------------
  1412. # * [Numeric] : Variação do número.
  1413. # x : Variação total. [-x, x]
  1414. #----------------------------------------------------------------------------
  1415. def randomic(x=4)
  1416. return ( (self+rand(2)) + (self + (rand(2) == 0 ? rand(x) : -rand(x)) ) ) / 2
  1417. end
  1418. #----------------------------------------------------------------------------
  1419. # * [Boolean] : Verifica se o número é igual a um dos especificados.
  1420. # 1.equal?(2, 3) # false
  1421. #----------------------------------------------------------------------------
  1422. def equal?(*args)
  1423. args.each { |i|
  1424. self == i ? (return true) : next
  1425. }
  1426. return false
  1427. end
  1428. end
  1429. }
  1430. #==============================================================================
  1431. # • Position.
  1432. #==============================================================================
  1433. Dax.register(:position, "dax", 3.0) {
  1434. class Position
  1435. #----------------------------------------------------------------------------
  1436. # • Modificar a posição de um objeto, que deve de conter as variáveis
  1437. # x, y, width, height.
  1438. # pos : Defina aqui o valor que definirá a posição da escola. Veja abaixo
  1439. # object : Objeto que contenha as variáveis x, y, width, height.
  1440. # os valores.
  1441. # 0 : Ficará no canto esquerdo superior.
  1442. # 1 : Posição X mudará para o centro da tela.
  1443. # 2 : Ficará no canto direito superior.
  1444. # 3 : Ficará no canto esquerdo inferior.
  1445. # 4 : Posição Y mudará para o centro da tela.
  1446. # 5 : Ficará no canto direito inferior.
  1447. # :center : Mudar a posição para o centro da tela.
  1448. # :center_left : Centralizar à esquerda da tela.
  1449. # :center_right : Centralizar à direita da tela.
  1450. # :center_up : Centralizar no centro superior.
  1451. # :center_down : Centralizar no centro inferior.
  1452. #----------------------------------------------------------------------------
  1453. def self.[](pos, object)
  1454. return if object.nil? or pos.nil?
  1455. return object.x, object.y = pos[0], pos[1] if pos.is_a?(Array)
  1456. return object.x, object.y = pos.x, pos.y if pos.is_a?(Position)
  1457. case pos
  1458. when 0 then object.x, object.y = 0, 0
  1459. when 1 then object.x = DMath.get_x_center_screen(object.width)
  1460. when 2 then object.x, object.y = Graphics.width - object.width, 0
  1461. when 3 then object.x, object.y = 0, Graphics.height - object.height
  1462. when 4 then object.y = DMath.get_y_center_screen(object.height)
  1463. when 5 then object.x, object.y = Graphics.width - object.width, Graphics.height - object.height
  1464. when :center
  1465. object.x = (Graphics.width - object.width) / 2
  1466. object.y = (Graphics.height - object.height) / 2
  1467. when :center_left
  1468. object.x = 0
  1469. object.y = (Graphics.height - object.height) / 2
  1470. when :center_right
  1471. object.x = Graphics.width - object.width
  1472. object.y = (Graphics.height - object.height) / 2
  1473. when :center_up
  1474. object.x = (Graphics.width - object.width) / 2
  1475. object.y = 0
  1476. when :center_down
  1477. object.x = (Graphics.width - object.width) / 2
  1478. object.y = Graphics.height - object.height
  1479. end
  1480. end
  1481. #----------------------------------------------------------------------------
  1482. # • Variáveis públicas da instância.
  1483. #----------------------------------------------------------------------------
  1484. attr_accessor :x # Variável que retorna ao valor que indica a posição X.
  1485. attr_accessor :y # Variável que retorna ao valor que indica a posição Y.
  1486. #----------------------------------------------------------------------------
  1487. # • Inicialização dos objetos.
  1488. #----------------------------------------------------------------------------
  1489. def initialize(x, y)
  1490. @x = x || 0
  1491. @y = y || 0
  1492. end
  1493. #----------------------------------------------------------------------------
  1494. # • Somar com outra posição.
  1495. #----------------------------------------------------------------------------
  1496. def +(position)
  1497. position = position.position unless position.is_a?(Position)
  1498. Position.new(self.x + position.x, self.y + position.y)
  1499. end
  1500. #----------------------------------------------------------------------------
  1501. # • Subtrair com outra posição.
  1502. #----------------------------------------------------------------------------
  1503. def -(position)
  1504. position = position.position unless position.is_a?(Position)
  1505. Position.new(self.x - position.x, self.y - position.y)
  1506. end
  1507. #----------------------------------------------------------------------------
  1508. # • Multiplicar com outra posição.
  1509. #----------------------------------------------------------------------------
  1510. def *(position)
  1511. position = position.position unless position.is_a?(Position)
  1512. Position.new(self.x * position.x, self.y * position.y)
  1513. end
  1514. #----------------------------------------------------------------------------
  1515. # • Dividir com outra posição.
  1516. #----------------------------------------------------------------------------
  1517. def /(position)
  1518. position = position.position unless position.is_a?(Position)
  1519. return if (self.x or position.x or self.y or position.y) <= 0
  1520. Position.new(self.x / position.x, self.y / position.y)
  1521. end
  1522. #----------------------------------------------------------------------------
  1523. # • Comparar com outra posição.
  1524. #----------------------------------------------------------------------------
  1525. def ==(position)
  1526. position = position.position unless position.is_a?(Position)
  1527. return self.x == position.x && self.y == position.y
  1528. end
  1529. #----------------------------------------------------------------------------
  1530. # • Distância de um ponto de posição com relação a outro.
  1531. # other : Outro ponto de posição.
  1532. #----------------------------------------------------------------------------
  1533. def distance(other)
  1534. other = other.position unless other.is_a?(Position)
  1535. (self.x - other.x).abs + (self.y - other.y).abs
  1536. end
  1537. #----------------------------------------------------------------------------
  1538. # • Converter em string.
  1539. #----------------------------------------------------------------------------
  1540. def to_s(broken="\n")
  1541. return "position x: #{self.x}#{broken}position y: #{self.y}"
  1542. end
  1543. #----------------------------------------------------------------------------
  1544. # • Converter em array.
  1545. #----------------------------------------------------------------------------
  1546. def to_a
  1547. return [@x, @y]
  1548. end
  1549. #----------------------------------------------------------------------------
  1550. # • Converter em hash.
  1551. #----------------------------------------------------------------------------
  1552. def to_h
  1553. return {x: @x, y: @y}
  1554. end
  1555. #----------------------------------------------------------------------------
  1556. # • Clonar
  1557. #----------------------------------------------------------------------------
  1558. def clone
  1559. return Position.new(@x, @y)
  1560. end
  1561. end
  1562. }
  1563. #==============================================================================
  1564. # • File
  1565. #==============================================================================
  1566. Dax.register(:file, "dax", 1.0) {
  1567. class << File
  1568. #----------------------------------------------------------------------------
  1569. # • [NilClass] : Executa o script que está no arquivo.
  1570. #----------------------------------------------------------------------------
  1571. def eval(filename)
  1572. return unless filename.match(/.rb|.rvdata2/) or FileTest.exist?(filename)
  1573. script = ""
  1574. nilcommand = false
  1575. IO.readlines(filename).each { |i|
  1576. if i.match(/^=begin/)
  1577. nilcommand = true
  1578. elsif i.match(/^=end/) and nilcommand
  1579. nilcommand = false
  1580. elsif !nilcommand
  1581. script += i.gsub(/#(.*)/, "").to_s + "\n"
  1582. end
  1583. }
  1584. Kernel.eval(script)
  1585. return nil
  1586. end
  1587. end
  1588. }
  1589. #==============================================================================
  1590. # • Dir
  1591. #==============================================================================
  1592. Dax.register(:dir, "dax", 1.0) {
  1593. class << Dir
  1594. #----------------------------------------------------------------------------
  1595. # • [NilClass] Cria pasta e subpasta em conjunto.
  1596. # Separe todo com vírgulas. A primeira que você definir será a pasta,
  1597. # o resto será as subpasta.
  1598. # Dir.mksdir("Pasta", "Subpasta1, Subpasta2")
  1599. #----------------------------------------------------------------------------
  1600. def mksdir(dir="", subdir="")
  1601. self.mkdir(dir) unless File.directory?(dir)
  1602. subdir = subdir.split(/,/)
  1603. subdir.each { |data| self.mkdir(dir + "/" + data.strip) unless File.directory?(dir + "/" + data.gsub(" ", "")) }
  1604. return nil
  1605. end
  1606. end
  1607. }
  1608. #==============================================================================
  1609. # * Color
  1610. #==============================================================================
  1611. Dax.register(:color, "dax", 3.5) {
  1612. class Color
  1613. #----------------------------------------------------------------------------
  1614. # • [Color] : Permite você modificar a opacidade da cor.
  1615. # Color.new(r, g, b).opacity([alpha])
  1616. # O valor padrão do alpha e 128.. não é preciso espeficar.
  1617. #----------------------------------------------------------------------------
  1618. def opacity(alpha=nil)
  1619. self.set(self.red, self.green, self.blue, alpha || 128)
  1620. end
  1621. #----------------------------------------------------------------------------
  1622. # • [Color] : Inverte as cores.
  1623. # Color.new(r, g, b[, a).invert!
  1624. #----------------------------------------------------------------------------
  1625. def invert!
  1626. self.set(255-self.red, 255-self.green, 255-self.blue, self.alpha)
  1627. end
  1628. #----------------------------------------------------------------------------
  1629. # • [Color] : Reverte as cores.
  1630. # Color.new(r, g, b[, a).revert
  1631. #----------------------------------------------------------------------------
  1632. def revert
  1633. self.set(*[self.red, self.green, self.blue, self.alpha].reverse!)
  1634. end
  1635. #----------------------------------------------------------------------------
  1636. # • [String] : Converte para string as informações dos valores das cores.
  1637. # Color.new(0, 0, 0).to_s
  1638. # red: 0
  1639. # blue: 0
  1640. # green: 0
  1641. # alpha: 255
  1642. #----------------------------------------------------------------------------
  1643. def to_s
  1644. "red: #{self.red}\nblue: #{self.blue}\ngreen: #{self.green}\nalpha: #{self.alpha}"
  1645. end
  1646. #----------------------------------------------------------------------------
  1647. # • [TrueClass/FalseClass] : Comparar cores, retorna a [true] se for igual..
  1648. # retorna a [false] se não for igual.
  1649. #----------------------------------------------------------------------------
  1650. def ==(color)
  1651. return (self.red == color.red and self.green == color.green and self.blue == color.blue and
  1652. self.alpha == color.alpha) ? true : false
  1653. end
  1654. #----------------------------------------------------------------------------
  1655. # • [Hash] : Retorna aos valores das cores em formato de Hash.
  1656. # Color.new(0, 0, 0).to_h
  1657. # {:red => 0, :green => 0, :blue => 0, :alpha => 255}
  1658. #----------------------------------------------------------------------------
  1659. def to_h
  1660. return {
  1661. red: self.red, green: self.green, blue: self.blue, alpha: self.alpha,
  1662. }
  1663. end
  1664. #----------------------------------------------------------------------------
  1665. # • [Array] : Retorna aos valores das cores em formato de Array.
  1666. # includeAlpha : Incluir o valor alpha?
  1667. # Color.new(0, 0, 0).to_a
  1668. # [0, 0, 0, 255]
  1669. #----------------------------------------------------------------------------
  1670. def to_a(includeAlpha=false)
  1671. array = [self.red, self.green, self.blue]
  1672. array += [self.alpha] if includeAlpha
  1673. return array
  1674. end
  1675. #----------------------------------------------------------------------------
  1676. # • [Color] : Dispoem os valores das cores em ordem crescente e cria uma
  1677. # nova cor.
  1678. # includeAlpha : Incluir o valor alpha?
  1679. #----------------------------------------------------------------------------
  1680. def crescent(includeAlpha=false)
  1681. set(*to_a(includeAlpha).crescent)
  1682. end
  1683. #----------------------------------------------------------------------------
  1684. # • [Color] : Dispoem os valores das cores em ordem decrescente e cria uma
  1685. # nova cor.
  1686. # includeAlpha : Incluir o valor alpha?
  1687. #----------------------------------------------------------------------------
  1688. def decrescent(includeAlpha=false)
  1689. set(*to_a(includeAlpha).decrescent)
  1690. end
  1691. #----------------------------------------------------------------------------
  1692. # • [Color] Soma os valores das cores com os valores de outras cores.
  1693. # Ex: color + Color.new(21,54,255)
  1694. #----------------------------------------------------------------------------
  1695. def +(color)
  1696. return unless color.is_a?(Color)
  1697. self.set(
  1698. *color.to_a(false).each_with_index { |i, n| i + to_a[n] }
  1699. )
  1700. end
  1701. #----------------------------------------------------------------------------
  1702. # • [Color] Subtrai os valores das cores com os valores de outras cores.
  1703. # Ex: color - Color.new(21,54,255)
  1704. #----------------------------------------------------------------------------
  1705. def -(color)
  1706. return unless color.is_a?(Color)
  1707. self.set(
  1708. *color.to_a(false).each_with_index { |i, n| i - to_a[n] }
  1709. )
  1710. end
  1711. #----------------------------------------------------------------------------
  1712. # • [Color] Multiplica os valores das cores com os valores de outras cores.
  1713. # Ex: color * Color.new(21,54,255)
  1714. #----------------------------------------------------------------------------
  1715. def *(color)
  1716. return unless color.is_a?(Color)
  1717. self.set(
  1718. *color.to_a(false).each_with_index { |i, n| (i * to_a[n]) / 255.0 }
  1719. )
  1720. end
  1721. #----------------------------------------------------------------------------
  1722. # • [Color] Divide os valores das cores com os valores de outras cores.
  1723. # Ex: color / Color.new(21,54,255)
  1724. #----------------------------------------------------------------------------
  1725. def /(color)
  1726. return unless color.is_a?(Color)
  1727. self.set(
  1728. *color.to_a(false).each_with_index { |i, n| i.zero? ? 0 : to_a[n] / i }
  1729. )
  1730. end
  1731. #----------------------------------------------------------------------------
  1732. # • [Color] : Aumentar/Diminuir as cores em porcento.
  1733. # value : Valor da porcentagem. Vai de 0~100
  1734. # includeAlpha : Incluir o valor alpha?
  1735. #----------------------------------------------------------------------------
  1736. def percent(value, includeAlpha=true)
  1737. value = DMath.clamp(value, 0, 100)
  1738. Color.new(
  1739. *to_a(includeAlpha).collect! { |i| i.to_p(value * 2.55, 255) }
  1740. )
  1741. end
  1742. #----------------------------------------------------------------------------
  1743. # • [Numeric] : Retorna a lumonisidade das cores.
  1744. #----------------------------------------------------------------------------
  1745. def luminosity
  1746. return to_a(false).each_with_index { |i, n| i * [0.21, 0.71, 0.07][n] }.alln?
  1747. end
  1748. #----------------------------------------------------------------------------
  1749. # • [Numeric] : Retorna a media entre os valores(canais).
  1750. # includeAlpha : Incluir o valor alpha?
  1751. #----------------------------------------------------------------------------
  1752. def avarange(includeAlpha=true)
  1753. n = includeAlpha ? 4 : 3
  1754. return to_a(includeAlpha).alln? / n
  1755. end
  1756. #----------------------------------------------------------------------------
  1757. # • [Numeric] : Retorna ao valor mais alto que tiver, dentre os valores
  1758. # especificados das cores.
  1759. #----------------------------------------------------------------------------
  1760. def max
  1761. [red, green, blue].max
  1762. end
  1763. #----------------------------------------------------------------------------
  1764. # • [Numeric] : Retorna ao valor menor que tiver, dentre os valores
  1765. # especificados das cores.
  1766. #----------------------------------------------------------------------------
  1767. def min
  1768. [red, green, blue].min
  1769. end
  1770. #----------------------------------------------------------------------------
  1771. # • [Color] : Define uma cor aleatória:
  1772. # Exemplo: Color.new.random
  1773. #----------------------------------------------------------------------------
  1774. def random
  1775. return Color.new(rand(256), rand(256), rand(256))
  1776. end
  1777. #----------------------------------------------------------------------------
  1778. # • [Color] : Define uma cor em hexadécimal.
  1779. # Exemplo : Color.new.hex("ffffff")
  1780. #----------------------------------------------------------------------------
  1781. def hex(string)
  1782. self.set(*string.scan(/../).map { |color| color.to_i(16)})
  1783. end
  1784. #----------------------------------------------------------------------------
  1785. # • [Color] : Retorna a cor padrão.
  1786. # Exemplo : Color.new.default
  1787. #----------------------------------------------------------------------------
  1788. def default
  1789. self.hex("ffffff")
  1790. end
  1791. end
  1792. }
  1793. #==============================================================================
  1794. # • Rect
  1795. #==============================================================================
  1796. Dax.register(:rect, "dax & gab!", 1.5) {
  1797. class Rect
  1798. #----------------------------------------------------------------------------
  1799. # • [TrueClass/FalseClass] : Verificar se algo está na área.
  1800. #----------------------------------------------------------------------------
  1801. def in?(x, y)
  1802. x.between?(self.x, self.x + self.width) &&
  1803. y.between?(self.y, self.y + self.height)
  1804. end
  1805. #----------------------------------------------------------------------------
  1806. # • [NilClass] : Retorna a cada parte do rect definida por ti, ponto-a-ponto.
  1807. # p : Ponto A.
  1808. # q : Ponto B.
  1809. # Rect.new(0, 0, 1, 1).step(1.0, 1.0) { |i, j| p [i, j] }
  1810. # [0.0, 0.0]
  1811. # [0.0, 1.0]
  1812. # [1.0, 0.0]
  1813. # [1.0, 1.0]
  1814. #----------------------------------------------------------------------------
  1815. def step(p=1, q=1)
  1816. (self.x..(self.x + self.width)).step(p) { |i|
  1817. (self.y..(self.y + self.height)).step(q) { |j|
  1818. yield(i, j)
  1819. }
  1820. }
  1821. return nil
  1822. end
  1823. #----------------------------------------------------------------------------
  1824. # • [Array] : Retorna aos valores do Rect em uma Array.
  1825. #----------------------------------------------------------------------------
  1826. def to_a
  1827. return [self.x, self.y, self.width, self.height]
  1828. end
  1829. #----------------------------------------------------------------------------
  1830. # • Retorna interseção com o argumento, que deve ser também do tipo Rect
  1831. #----------------------------------------------------------------------------
  1832. def intercept(rect)
  1833. x = [self.x, rect.x].max
  1834. y = [self.y, rect.y].max
  1835. w = [self.x + self.width, rect.x + rect.width ].min - x
  1836. h = [self.y + self.height, rect.y + rect.height].min - y
  1837. return Rect.new(x, y, w, h)
  1838. end
  1839. alias & intercept
  1840. end
  1841. }
  1842. #==============================================================================
  1843. # • DMath
  1844. #==============================================================================
  1845. Dax.register(:dmath, 'Dax', 4.0) {
  1846. module DMath
  1847. extend self
  1848. #----------------------------------------------------------------------------
  1849. # • Constantes para fórmula de dano.
  1850. #----------------------------------------------------------------------------
  1851. MAX_VALUE_PARAM = 256
  1852. MAX_VALUE_PARAM_AXE = 128
  1853. MAX_VALUE_PARAM_DAGGER = 218
  1854. MAX_VALUE_PARAM_GUN = 99
  1855. MAX_VALUE_MAGIC = 218
  1856. #----------------------------------------------------------------------------
  1857. # • [Numeric] : Calcula o ângulo entre dóis pontos.
  1858. #----------------------------------------------------------------------------
  1859. def angle(pA, pB, quad4=false)
  1860. pA = pA.position unless pA.is_a?(Position)
  1861. pB = pB.position unless pB.is_a?(Position)
  1862. x = pB.x - pA.x
  1863. y = pB.y - pA.y
  1864. y *= -1 if quad4
  1865. radian = Math.atan2(y, x)
  1866. angle = (radian * 180 / Math::PI)
  1867. angle = 360 + angle if angle < 0
  1868. return angle
  1869. end
  1870. #----------------------------------------------------------------------------
  1871. # • [Boolean] : Verifica se a posição é igual.
  1872. #----------------------------------------------------------------------------
  1873. def equal_pos?(a, b)
  1874. (a.x == b.x) && (a.y == b.y)
  1875. end
  1876. #----------------------------------------------------------------------------
  1877. # • [Float] : Cálcula a raíz quadrada que qualquer grau.
  1878. # n : Número que será calculado.
  1879. # g : Grau da raíz.
  1880. # Dmath.sqrt(27, 3) # Cálculo da raíz cúbica de 27 => 3.0
  1881. #----------------------------------------------------------------------------
  1882. def sqrt(n, g)
  1883. raise(ArgumentError) if n < 0 && n.is_evan?
  1884. x, count, num = 1.0, 0.0, 0.0
  1885. while
  1886. num = x - ( ( x ** g - n ) / ( g * ( x ** g.pred ) ) )
  1887. (x == num) || (count > 20) ? break : eval("x = num; count += 1")
  1888. end
  1889. return num
  1890. end
  1891. #----------------------------------------------------------------------------
  1892. # • [Numeric] : Clamp | Delimitar o inteiro
  1893. # num : Número.
  1894. # low : Número minímo. Sê o 'num' for menor que min retorna a low.
  1895. # high : Número máximo. Sê o 'num' for maior que hight retorna a high, caso
  1896. # não retorna ao próprio número(num).
  1897. #----------------------------------------------------------------------------
  1898. def clamp(num, low, high)
  1899. num, low, high = num.to_i, low.to_i, high.to_i
  1900. num = num < low ? low : num > high ? high : num
  1901. num
  1902. end
  1903. #----------------------------------------------------------------------------
  1904. # • [Array] : Centralizar um objeto n'outro.
  1905. # object : Objeto, tem que ser do tipo [Sprite] ou [Window_Base]
  1906. # object_for_centralize : Objeto que irá se centralizar no 'object', tem
  1907. # que ser do tipo [Sprite] ou [Window_Base]
  1908. # * Retorna a uma Array contendo as informações das novas posições em X e Y.
  1909. #----------------------------------------------------------------------------
  1910. def centralize_object(object, object_for_centralize)
  1911. x = object.x + (object.width - object_for_centralize.width) / 2
  1912. y = object.y + (object.height - object_for_centralize.height) / 2
  1913. return x, y
  1914. end
  1915. #----------------------------------------------------------------------------
  1916. # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição X.
  1917. # objectx : Valor da posição X do objeto número 1.
  1918. # objectwidth : Valor da largura do objeto número 1.
  1919. # object_for_centralizewidth : Valor da largura do objeto que irá se
  1920. # centralizar no objeto número 1.
  1921. # * Retorna ao valor da posição X.
  1922. #----------------------------------------------------------------------------
  1923. def centralize_x(objectx, objectwidth, object_for_centralizewidth)
  1924. return objectx + (objectwidth - object_for_centralizewidth) / 2
  1925. end
  1926. #----------------------------------------------------------------------------
  1927. # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição Y.
  1928. # objecty : Valor da posição Y do objeto número 1.
  1929. # objectheight : Valor da altura do objeto número 1.
  1930. # object_for_centralizeheight : Valor da altura do objeto que irá se
  1931. # centralizar no objeto número 1.
  1932. # * Retorna ao valor da posição Y.
  1933. #----------------------------------------------------------------------------
  1934. def centralize_y(objecty, objectheight, object_for_centralizeheight)
  1935. return objecty + (objectheight - object_for_centralizeheight) / 2
  1936. end
  1937. #----------------------------------------------------------------------------
  1938. # • [Numeric] : Obter a posição X do centro da tela referente a largura do objeto X.
  1939. # Exemplo: get_x_center_screen(sprite.width) : Irá retornar ao valor da posição
  1940. # X para que o objeto fique no centro da tela.
  1941. # Exemplo: sprite.x = get_x_center_screen(sprite.width)
  1942. #----------------------------------------------------------------------------
  1943. def get_x_center_screen(width)
  1944. return (Graphics.width - width) / 2
  1945. end
  1946. #----------------------------------------------------------------------------
  1947. # • [Numeric] : Obter a posição Y do centro da tela referente a altura do objeto X.
  1948. # Exemplo: get_y_center_screen(sprite.height) : Irá retornar ao valor da posição
  1949. # Y para que o objeto fique no centro da tela.
  1950. # Exemplo: sprite.y = get_y_center_screen(sprite.height)
  1951. #----------------------------------------------------------------------------
  1952. def get_y_center_screen(height)
  1953. return (Graphics.height - height) / 2
  1954. end
  1955. #--------------------------------------------------------------------------
  1956. # • [TrueClass/FalseClass] : Verifica se um objeto está na área de um círculo.
  1957. # object : Objeto do tipo da classe [Sprite].
  1958. # object2 : Objeto do tipo da classe [Sprite].
  1959. # size : Tamanho geral do círculo.
  1960. #--------------------------------------------------------------------------
  1961. def circle(object, object2, size)
  1962. ( (object.x - object2.x) ** 2) + ( (object.y - object2.y) ** 2) <= (size ** 2)
  1963. end
  1964. #----------------------------------------------------------------------------
  1965. # • [Numeric] : Converter o valor em graus.
  1966. #----------------------------------------------------------------------------
  1967. def graus
  1968. 360 / (2 * Math::PI)
  1969. end
  1970. #----------------------------------------------------------------------------
  1971. # • [Numeric] : Converte o valor em radiano.
  1972. #----------------------------------------------------------------------------
  1973. def radian(degree)
  1974. return (degree.to_f/180) * Math::PI
  1975. end
  1976. #----------------------------------------------------------------------------
  1977. # • [Numeric] : Converte o valor em grau.
  1978. #----------------------------------------------------------------------------
  1979. def degree(radian)
  1980. return (radian.to_f/Math::PI) * 180
  1981. end
  1982. #----------------------------------------------------------------------------
  1983. # • [Numeric] : Retorna pra base de 4 decimais.
  1984. #----------------------------------------------------------------------------
  1985. def to_4_dec(n)
  1986. ((n * 1000).ceil) / 1000
  1987. end
  1988. #----------------------------------------------------------------------------
  1989. # • [Numeric] : Retorna a área do triângulo.
  1990. # x : x : Posição x do ponto 1
  1991. # y : Posição y do ponto 1
  1992. # x2 : Posição x do ponto 2
  1993. # y2 : Posição y do ponto 2
  1994. # x3 : Posição x do ponto 3
  1995. # y3 : Posição y do ponto 3
  1996. #----------------------------------------------------------------------------
  1997. def triangle_area(*args)
  1998. x, y, x2, y2, x3, y3 = *args
  1999. return (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y)
  2000. end
  2001. #----------------------------------------------------------------------------
  2002. # • [Numeric] : Método para calcular a distância de um objeto para com outro.
  2003. #----------------------------------------------------------------------------
  2004. def distance_sensor(target, target2)
  2005. return (target.x - target2.x).abs + (target.y - target2.y).abs
  2006. end
  2007. #----------------------------------------------------------------------------
  2008. # • [Integer] : Método euclidiano para mediar a distância de um ponto
  2009. # para outro ponto. Primeira dimensão.
  2010. # p : Ponto A. [x, y]
  2011. # q : Ponto B. [x, y]
  2012. # euclidean_distance_1d(5, 1) #4
  2013. #----------------------------------------------------------------------------
  2014. def euclidean_distance_1d(p, q)
  2015. return sqrt( (p - q) ** 2, 2 ).floor
  2016. end
  2017. #----------------------------------------------------------------------------
  2018. # • [Integer] : Método euclidiano para mediar a distância de um ponto
  2019. # para outro ponto. Segunda dimensão.
  2020. # p : Ponto A. [x, y]
  2021. # q : Ponto B. [x, y]
  2022. # euclidean_distance_2d([1, 3], [1, 5]) #2
  2023. #----------------------------------------------------------------------------
  2024. def euclidean_distance_2d(p, q)
  2025. p = p.position unless p.is_a?(Position)
  2026. q = q.position unless q.is_a?(Position)
  2027. return sqrt( ((p.x - q.x) ** 2) + ((p.y - q.y) ** 2), 2 ).floor
  2028. end
  2029. #----------------------------------------------------------------------------
  2030. # • [Numeric] : Dentro do círculo.
  2031. #----------------------------------------------------------------------------
  2032. def circle_in(t, b, c, d)
  2033. return -c * (Math.sqrt(1 - (t /= d.to_f) * t) - 1) + b
  2034. end
  2035. #----------------------------------------------------------------------------
  2036. # • [Numeric] : Fora do círculo
  2037. #----------------------------------------------------------------------------
  2038. def circle_out(t, b, c, d)
  2039. return c * Math.sqrt(1 - (t=t/d.to_f-1)*t) + b
  2040. end
  2041. #----------------------------------------------------------------------------
  2042. # • [Numeric] : Retorna ao valor minímo, do valor máximo de min & v, com o
  2043. # valor de max.
  2044. #----------------------------------------------------------------------------
  2045. def force_range(v, min, max)
  2046. [[min, v].max, max].min
  2047. end
  2048. #----------------------------------------------------------------------------
  2049. # • Cálculo de variação para o dano. Para equilibrar.
  2050. #----------------------------------------------------------------------------
  2051. def random
  2052. (1 + 2.aleatory) ** 0.125
  2053. end
  2054. #----------------------------------------------------------------------------
  2055. # • Resultado final.
  2056. #----------------------------------------------------------------------------
  2057. def lastResult(x)
  2058. return x <= 0 ? 0 : x.round
  2059. end
  2060. #----------------------------------------------------------------------------
  2061. # • [Formula de dano] : Espadas(1 & 2 mão), lanças, bestas, cajado.
  2062. #----------------------------------------------------------------------------
  2063. def sword(attack, strength, defense, level)
  2064. str = strength.randomic
  2065. return lastResult((attack.randomic * random - defense.randomic) * (1 + str * (level + str) / MAX_VALUE_PARAM))
  2066. end
  2067. #----------------------------------------------------------------------------
  2068. # • [Formula de dano] : Desarmado.
  2069. #----------------------------------------------------------------------------
  2070. def unarmed(strength, defense, level)
  2071. str = strength.randomic
  2072. lastResult((11 * random - defense.randomic) * str * (level + str) / MAX_VALUE_PARAM)
  2073. end
  2074. #----------------------------------------------------------------------------
  2075. # • [Formula de dano] : Desarmado com luva.
  2076. #----------------------------------------------------------------------------
  2077. def unarmed_brawler(strength, defense, level)
  2078. str = strength.randomic
  2079. lastResult(((level + str) / 2 * random - defense.randomic) * str * (level + str) / MAX_VALUE_PARAM)
  2080. end
  2081. #----------------------------------------------------------------------------
  2082. # • [Formula de dano] : Cajado de mágia.
  2083. #----------------------------------------------------------------------------
  2084. def pole(attack, strength, defense, level, magicDefense)
  2085. str = strength.randomic
  2086. lastResult((attack.randomic * random - magicDefense.randomic) * (1 + str * (level + str))/ MAX_VALUE_PARAM)
  2087. end
  2088. #----------------------------------------------------------------------------
  2089. # • [Formula de dano] : Maças..
  2090. #----------------------------------------------------------------------------
  2091. def mace(attack, defense, magic, level)
  2092. mag = magic.randomic
  2093. lastResult((attack.randomic * random - defense.randomic) * (1 + mag * (level + mag)) / MAX_VALUE_PARAM)
  2094. end
  2095. #----------------------------------------------------------------------------
  2096. # • [Formula de dano] : Katanas, staves..
  2097. #----------------------------------------------------------------------------
  2098. def katana(attack, defense, strength, magic, level)
  2099. lastResult((attack.randomic * random - defense.randomic) * (1 + strength.randomic * (level + magic.randomic) / MAX_VALUE_PARAM))
  2100. end
  2101. #----------------------------------------------------------------------------
  2102. # • [Formula de dano] : Machados, marretas..
  2103. #----------------------------------------------------------------------------
  2104. def axe(attack, strength, defense, level, vitality)
  2105. lastResult((attack.randomic * random - defense.randomic) * (1 + strength.randomic * (level+vitality.randomic)/MAX_VALUE_PARAM_AXE))
  2106. end
  2107. #----------------------------------------------------------------------------
  2108. # • [Formula de dano] : Adagas, espadas ninjas e arco..
  2109. #----------------------------------------------------------------------------
  2110. def dagger(attack, defense, strength, level, speed)
  2111. lastResult ((attack.randomic * random) - defense.randomic) * (1 + strength.randomic * (level + speed.randomic) / 218)
  2112. end
  2113. #----------------------------------------------------------------------------
  2114. # • [Formula de dano] : Revolvers
  2115. #----------------------------------------------------------------------------
  2116. def gun(attack,defense,strength, level)
  2117. str = strength.randomic
  2118. lastResult ( (((attack.randomic * random) - defense.randomic) ** 2) / 64 ) * (1 + str * (level + str) / MAX_VALUE_PARAM_GUN)
  2119. end
  2120. #----------------------------------------------------------------------------
  2121. # • [Formula de dano] : Mágicas de ataques.
  2122. #----------------------------------------------------------------------------
  2123. def magicAttack(magicDefense, level, magicAttack, attackMagic)
  2124. mag = magicAttack.randomic
  2125. lastResult ( (attackMagic.randomic * random) - magicDefense.randomic ) * (2 + mag.randomic * (level + mag) / MAX_VALUE_MAGIC)
  2126. end
  2127. #----------------------------------------------------------------------------
  2128. # • [Formula de dano] : Mágicas de cura;
  2129. #----------------------------------------------------------------------------
  2130. def magicHeal(strengthMagic, magicAttack, level)
  2131. mag = magicAttack.randomic
  2132. lastResult (strengthMagic * random) * (2 + mag * (level + mag) / MAX_VALUE_MAGIC)
  2133. end
  2134. #----------------------------------------------------------------------------
  2135. # • [Formula de EXP] : Gerador de curva de exp.
  2136. # minlv : Level minimo.
  2137. # maxlv : Level máximo.
  2138. # stvalue : Valor inicial.
  2139. # infl : Inflação.
  2140. #----------------------------------------------------------------------------
  2141. def generate_curve_exp(minlv, maxlv, stvalue, infl)
  2142. table = []
  2143. (minlv..maxlv).each { |i| table[i] = (stvalue + (infl + (Random.new.rand(infl..(infl+i)).to_i % i )) * i).to_i.round}
  2144. table
  2145. end
  2146. end
  2147. }
  2148. #==============================================================================
  2149. # • Keyboard | Método para usar todas as teclas do teclado.
  2150. #==============================================================================
  2151. Dax.register(:key, "Dax", 2.0) {
  2152. module Key
  2153. #----------------------------------------------------------------------------
  2154. # • Extensão & Variáveis da instância do módulo.
  2155. #----------------------------------------------------------------------------
  2156. extend self
  2157. attr_accessor :_cacheText # Armazena os textos.
  2158. #----------------------------------------------------------------------------
  2159. # • Texto do cache
  2160. #----------------------------------------------------------------------------
  2161. def text
  2162. return @_cacheText
  2163. end
  2164. alias :to_s :text
  2165. #----------------------------------------------------------------------------
  2166. # • Chaves.
  2167. #----------------------------------------------------------------------------
  2168. KEY = {
  2169. # Chaves diversas.
  2170. CANCEL: 0x03, BACKSPACE: 0x08, TAB: 0x09, CLEAR: 0x0C,
  2171. ENTER: 0x0D, SHIFT: 0x10, CONTROL: 0x11, MENU: 0x12,
  2172. PAUSE: 0x13, ESC: 0x1B, CONVERT: 0x1C, NONCONVERT: 0x1D,
  2173. ACCEPT: 0x1E, SPACE: 0x20, PRIOR: 0x21, NEXT: 0x22,
  2174. ENDS: 0x23, HOME: 0x24, LEFT: 0x25, UP: 0x26, RIGHT: 0x27,
  2175. DOWN: 0x28, SELECT: 0x29, PRINT: 0x2A, EXECUTE: 0x2B,
  2176. SNAPSHOT: 0x2C, DELETE: 0x2E, HELP: 0x2F, LSHIFT: 0xA0, RSHIFT: 0xA1,
  2177. LCONTROL: 0xA2, RCONTROL: 0xA3, LALT: 0xA4, RALT: 0xA5, PACKET: 0xE7,
  2178. # MOUSE
  2179. MOUSE_RIGHT: 0x01, MOUSE_LEFT: 0x02, MOUSE_MIDDLE: 0x04, X1: 0x05, X2: 0x06,
  2180. # Chaves de números.
  2181. N0: 0x30, N1: 0x31, N2: 0x32, N3: 0x33, N4: 0x34, N5: 0x35, N6: 0x36,
  2182. N7: 0x37, N8: 0x38, N9: 0x39,
  2183. # Chaves de letras.
  2184. A: 0x41, B: 0x42, C: 0x43, D: 0x44, E: 0x45,
  2185. F: 0x46, G: 0x47, H: 0x48, I: 0x49, J: 0x4A,
  2186. K: 0x4B, L: 0x4C, M: 0x4D, N: 0x4E, O: 0x4F,
  2187. P: 0x50, Q: 0x51, R: 0x52, S: 0x53, T: 0x54,
  2188. U: 0x55, V: 0x56, W: 0x57, X: 0x58, Y: 0x59,
  2189. Z: 0x5A, Ç: 0xBA,
  2190. # Chaves do window.
  2191. LWIN: 0x5B, RWIN: 0x5C, APPS: 0x5D, SLEEP: 0x5F, BROWSER_BACK: 0xA6,
  2192. BROWSER_FORWARD: 0xA7, BROWSER_REFRESH: 0xA8, BROWSER_STOP: 0xA9,
  2193. BROWSER_SEARCH: 0xAA, BROWSER_FAVORITES: 0xAB, BROWSER_HOME: 0xAC,
  2194. VOLUME_MUTE: 0xAD, VOLUME_DOWN: 0xAE, VOLUME_UP: 0xAF,
  2195. MEDIA_NEXT_TRACK: 0xB0, MEDIA_PREV_TRACK: 0xB1, MEDIA_STOP: 0xB2,
  2196. MEDIA_PLAY_PAUSE: 0xB3, LAUNCH_MAIL: 0xB4, LAUNCH_MEDIA_SELECT: 0xB5,
  2197. LAUNCH_APP1: 0xB6, LAUNCH_APP2: 0xB7, PROCESSKEY: 0xE5, ATIN: 0xF6,
  2198. CRSEL: 0xF7, EXSEL: 0xF8, EREOF: 0xF9, PLAY: 0xFA, ZOOM: 0xFB,
  2199. PA1: 0xFD,
  2200. # Chaves do NUMPAD
  2201. NUMPAD0: 0x60, NUMPAD1: 0x61, NUMPAD2: 0x62,
  2202. NUMPAD3: 0x63, NUMPAD4: 0x64, NUMPAD5: 0x65,
  2203. NUMPAD6: 0x66, NUMPAD7: 0x67, NUMPAD8: 0x68, NUMPAD9: 0x69,
  2204. MULTIPLY: 0x6A, ADD: 0x6B, SEPARATOR: 0x6C,
  2205. SUBTRACT: 0x6D, DECIMAL: 0x6E, DIVIDE: 0x6F,
  2206. # Caches de função.
  2207. F1: 0x70, F2: 0x71, F3: 0x72, F4: 0x73, F5: 0x74, F6: 0x75,
  2208. F7: 0x76, F8: 0x77, F9: 0x78, F10: 0x79, F11: 0x7A, F12: 0x7B,
  2209. F13: 0x7C, F14: 0x7D, F15: 0x7E, F16: 0x7F, F17: 0x80, F18: 0x81,
  2210. F19: 0x82, F20: 0x83, F21: 0x84, F22: 0x85, F23: 0x86, F24: 0x87,
  2211. # Chaves alternativas.
  2212. CAPS: 0x14, INSERT: 0x2D, NUMLOCK: 0x90, SCROLL: 0x91,
  2213. # Chaves OEM, variadas.
  2214. OEM_1: 0xC1, OEM_PLUS: 0xBB, OEM_COMMA: 0xBC,
  2215. OEM_MINUS: 0xBD, OEM_PERIOD: 0xBE,
  2216. OEM_2: 0xBF, QUOTE: 0xC0,
  2217. ACCUTE: 0xDB, OEM_6: 0xDD, OEM_7: 0xDC, TIL: 0xDE,
  2218. OEM_102: 0xE2, OEM_CLEAR: 0xFE,
  2219. }
  2220. #----------------------------------------------------------------------------
  2221. # • Chave dos números. (Símbolos)
  2222. #----------------------------------------------------------------------------
  2223. KEY_NUMBER = %W(NUMPAD0 NUMPAD1 NUMPAD2 NUMPAD3 NUMPAD4 NUMPAD5 NUMPAD6
  2224. NUMPAD7 NUMPAD8 NUMPAD9 N0 N1 N2 N3 N4 N5 N6 N7 N8 N9 MULTIPLY OEM_PERIOD
  2225. OEM_COMMA ADD SEPARATOR DIVIDE SUBTRACT DECIMAL).collect!(&:intern)
  2226. SPECIAL_CHAR_NUMBER = {
  2227. N1: %w(! ¹), N2: %w(@ ²), N3: %w(# ³), N4: %w($ £),
  2228. N5: %w(% ¢), N6: %w(¨ ¬), N7: %w(&), N8: %w(*),
  2229. N9: ["("], N0: [")"], OEM_PERIOD: %w(>), OEM_COMMA: %w(<)
  2230. }
  2231. #----------------------------------------------------------------------------
  2232. # • Chave das letras. (Símbolos)
  2233. #----------------------------------------------------------------------------
  2234. KEY_CHAR = %W(A B C D E F G H I J L K M N O P Q R S T U V W X Y Z Ç).collect!(&:intern)
  2235. KEY_CHAR_ACCUTE = %W(A E I O U Y).collect!(&:intern)
  2236. KEY_CHAR_ACCUTE_STR = {
  2237. UPCASE: {
  2238. A: %w(Â Ã À Á), E: %w(Ê ~E È É), I: %w(Î ~I Ì Í), O: %w(Ô Õ Ò Ó),
  2239. Y: %w(^Y ~Y `Y Ý), U: %w(Û ~U Ù Ú)
  2240. },
  2241. DOWNCASE: {
  2242. A: %w(â ã à á), E: %w(ê ~e è é), I: %w(î ~i ì í), O: %w(ô õ ò ó),
  2243. Y: %w(^y ~y `y ý), U: %w(û ~u ù ú)
  2244. }
  2245. }
  2246. #----------------------------------------------------------------------------
  2247. # • Chaves especiais.
  2248. #----------------------------------------------------------------------------
  2249. KEY_SPECIAL = %w(SPACE OEM_1 OEM_PLUS OEM_MINUS OEM_2
  2250. OEM_6 OEM_7 OEM_102).collect!(&:intern)
  2251. SKEY_SPECIAL = {
  2252. OEM_1: %w(? °), OEM_2: %w(:), OEM_7: %w(} º), OEM_6: %w({ ª),
  2253. OEM_PLUS: %w(+ §), OEM_MINUS: %w(_), OEM_102: %w(|)
  2254. }
  2255. #----------------------------------------------------------------------------
  2256. # • Chaves especiais. [^~ ´` '"]
  2257. #----------------------------------------------------------------------------
  2258. KEY_SPECIAL2 = %w(ACCUTE TIL QUOTE N6).collect!(&:intern)
  2259. #----------------------------------------------------------------------------
  2260. # • Variáveis do módulo.
  2261. #----------------------------------------------------------------------------
  2262. @_cacheText = ""
  2263. @til = 0
  2264. @tils = false
  2265. @accute = 0
  2266. @accutes = false
  2267. @unpack_string = 'b'*256
  2268. @last_array = '0'*256
  2269. @press = Array.new(256, false)
  2270. @trigger = Array.new(256, false)
  2271. @repeat = Array.new(256, false)
  2272. @release = Array.new(256, false)
  2273. @repeat_counter = Array.new(256, 0)
  2274. @getKeyboardState = API::GetKeyboardState
  2275. @getAsyncKeyState = API::GetAsyncKeyState
  2276. @getKeyboardState.call(@last_array)
  2277. @last_array = @last_array.unpack(@unpack_string)
  2278. for i in 0...@last_array.size
  2279. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  2280. end
  2281. #----------------------------------------------------------------------------
  2282. # • Atualização.
  2283. #----------------------------------------------------------------------------
  2284. def update
  2285. @trigger = Array.new(256, false)
  2286. @repeat = Array.new(256, false)
  2287. @release = Array.new(256, false)
  2288. array = '0'*256
  2289. @getKeyboardState.call(array)
  2290. array = array.unpack(@unpack_string)
  2291. for i in 0...array.size
  2292. if array[i] != @last_array[i]
  2293. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  2294. if @repeat_counter[i] <= 0 && @press[i]
  2295. @repeat[i] = true
  2296. @repeat_counter[i] = 15
  2297. end
  2298. if !@press[i]
  2299. @release[i] = true
  2300. else
  2301. @trigger[i] = true
  2302. end
  2303. else
  2304. if @press[i] == true
  2305. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  2306. @release[i] = true if !@press[i]
  2307. end
  2308. if @repeat_counter[i] > 0 && @press[i] == true
  2309. @repeat_counter[i] -= 1
  2310. elsif @repeat_counter[i] <= 0 && @press[i] == true
  2311. @repeat[i] = true
  2312. @repeat_counter[i] = 3
  2313. elsif @repeat_counter[i] != 0
  2314. @repeat_counter[i] = 0
  2315. end
  2316. end
  2317. end
  2318. @last_array = array
  2319. end
  2320. #--------------------------------------------------------------------------
  2321. # * [TrueClass/FalseClass] Obter o estado quando a chave for pressionada.
  2322. # key : key index
  2323. #--------------------------------------------------------------------------
  2324. def press?(key)
  2325. return @press[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  2326. end
  2327. #--------------------------------------------------------------------------
  2328. # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada.
  2329. # key : key index
  2330. #--------------------------------------------------------------------------
  2331. def trigger?(key)
  2332. return @trigger[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  2333. end
  2334. #--------------------------------------------------------------------------
  2335. # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada repetidamente.
  2336. # key : key index
  2337. #--------------------------------------------------------------------------
  2338. def repeat?(key)
  2339. return @repeat[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  2340. end
  2341. #--------------------------------------------------------------------------
  2342. # * [TrueClass/FalseClass] Obter o estado quando a chave for "lançada"
  2343. # key : key index
  2344. #--------------------------------------------------------------------------
  2345. def release?(key)
  2346. return @release[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  2347. end
  2348. #----------------------------------------------------------------------------
  2349. # • [String] Obtêm a string correspondente à tecla do número. Às Strings ficará
  2350. # armazenada na varíavel _cacheText
  2351. #----------------------------------------------------------------------------
  2352. def get_number(special=false)
  2353. KEY_NUMBER.each { |key|
  2354. unless special
  2355. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  2356. else
  2357. if shift?
  2358. next @_cacheText += SPECIAL_CHAR_NUMBER[key][0] || "" if trigger?(key)
  2359. elsif ctrl_alt?
  2360. next @_cacheText += SPECIAL_CHAR_NUMBER[key][1] || "" if trigger?(key)
  2361. else
  2362. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  2363. end
  2364. end
  2365. }
  2366. end
  2367. #----------------------------------------------------------------------------
  2368. # • [String] Obtêm a string correspondente à tecla do teclado pressionado.
  2369. # Às Strings ficará armazenada na varíavel _cacheText
  2370. #----------------------------------------------------------------------------
  2371. def get_string(backslash=:trigger)
  2372. get_number(true)
  2373. KEY_CHAR.each { |key|
  2374. next unless trigger?(key)
  2375. x = "".concat(API::MapVirtualKey.call(KEY.get(key), 2))
  2376. if @tils
  2377. n = shift? ? 0 : 1 if @tils
  2378. x = KEY_CHAR_ACCUTE_STR[caps? ? :UPCASE : :DOWNCASE][key][n] || "" if KEY_CHAR_ACCUTE.include?(key) and !n.nil?
  2379. @tils = false
  2380. @accutes = false
  2381. elsif @accutes
  2382. n = shift? ? 2 : 3 if @accutes
  2383. x = KEY_CHAR_ACCUTE_STR[caps? ? :UPCASE : :DOWNCASE][key][n] || "" if KEY_CHAR_ACCUTE.include?(key) and !n.nil?
  2384. @tils = false
  2385. @accutes = false
  2386. end
  2387. @_cacheText += (caps? ? x : x.downcase)
  2388. }
  2389. KEY_SPECIAL.each { |key|
  2390. if shift?
  2391. next @_cacheText += SKEY_SPECIAL[key][0] || "" if trigger?(key)
  2392. elsif ctrl_alt?
  2393. next @_cacheText += SKEY_SPECIAL[key][1] || "" if trigger?(key)
  2394. else
  2395. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  2396. end
  2397. }
  2398. KEY_SPECIAL2.each { |key|
  2399. if trigger?(key)
  2400. if key == :TIL
  2401. @tils = !@tils
  2402. @accutes = false if @tils
  2403. elsif key == :ACCUTE
  2404. @accutes = !@accutes
  2405. @tils = false if @accutes
  2406. end
  2407. @til = @til == 3 ? @til : @til + 1 if key == :TIL
  2408. @accute = @accute == 3 ? @accute : @accute + 1 if key == :ACCUTE
  2409. if shift?
  2410. next @_cacheText += '"' if key == :QUOTE
  2411. next unless @til == 3 or @accute == 3
  2412. @_cacheText += "^" if key == :TIL
  2413. @_cacheText += "`" if key == :ACCUTE
  2414. next @til = 0 if key == :TIL
  2415. next @accute = 0 if key == :ACCUTE
  2416. else
  2417. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if key == :QUOTE
  2418. next unless @til == 3 or @accute == 3
  2419. @_cacheText += "~" if key == :TIL
  2420. @_cacheText += "´" if key == :ACCUTE
  2421. next @til = 0 if key == :TIL
  2422. next @accute = 0 if key == :ACCUTE
  2423. end
  2424. end
  2425. }
  2426. if backslash == :press
  2427. @_cacheText = @_cacheText.backslash if press?(:BACKSPACE)
  2428. else
  2429. @_cacheText = @_cacheText.backslash if trigger?(:BACKSPACE)
  2430. end
  2431. @_cacheText += " " * 4 if trigger?(:TAB)
  2432. end
  2433. #----------------------------------------------------------------------------
  2434. # • Verificar se o CAPS LOCK está ativado ou desativado.
  2435. #----------------------------------------------------------------------------
  2436. def caps?
  2437. API.get_caps_lock
  2438. end
  2439. #----------------------------------------------------------------------------
  2440. # • Verificar se o Shift está pressionado
  2441. #----------------------------------------------------------------------------
  2442. def shift?
  2443. press?(:SHIFT)
  2444. end
  2445. #----------------------------------------------------------------------------
  2446. # • Verificar se o CTRL + ALT está pressionado.
  2447. #----------------------------------------------------------------------------
  2448. def ctrl_alt?
  2449. (press?(:LCONTROL) and press?(:LALT)) or press?(:RALT)
  2450. end
  2451. #----------------------------------------------------------------------------
  2452. # • [Boolean] : Retorna true caso alguma tecla foi teclada.
  2453. #----------------------------------------------------------------------------
  2454. def any?
  2455. Key::KEY.each_value { |i|
  2456. next if i == 25
  2457. return true if trigger?(i)
  2458. }
  2459. return false
  2460. end
  2461. #----------------------------------------------------------------------------
  2462. # • Para movimento WSAD
  2463. #----------------------------------------------------------------------------
  2464. def wsad
  2465. return 8 if press?(:W)
  2466. return 4 if press?(:A)
  2467. return 6 if press?(:D)
  2468. return 2 if press?(:S)
  2469. return 0
  2470. end
  2471. end
  2472. }
  2473. #==============================================================================
  2474. # • Sprite
  2475. #==============================================================================
  2476. Dax.register(:sprite, "dax", 3.0) {
  2477. class Sprite
  2478. #----------------------------------------------------------------------------
  2479. # • Variáveis públicas da instância.
  2480. #----------------------------------------------------------------------------
  2481. attr_accessor :clone_sprite
  2482. attr_accessor :outline_fill_rect
  2483. #----------------------------------------------------------------------------
  2484. # • Novo método. Modos de usos abaixo:
  2485. # * [normal] : É o método normal, na qual você não define nada. Sprite.new
  2486. # * [viewport] : É o método na qual você define um viewport.
  2487. # Sprite.new(Viewport)
  2488. # * [system] : É o método na qual você já define um bitmap que irá carregar
  2489. # uma imagem já direto da pasta System, através do Cache.
  2490. # Sprite.new("S: Nome do Arquivo")
  2491. # * [picture] : É o método na qual você já define um bitmap que irá carregar
  2492. # uma imagem já direito da pasta Pictures, através do Cache.
  2493. # Sprite.new("P: Nome do Arquivo")
  2494. # * [graphics] : É o método na qual você já define um bitmap com uma imagem
  2495. # que está dentro da pasta Graphics, através do Cache.
  2496. # Sprite.new("G: Nome do Arquivo.")
  2497. # * [width, height] : É o método na qual você já define a largura e altura
  2498. # do bitmap. Sprite.new([width, height])
  2499. # * [elements] : É o método na qual você já define a largura, altura,
  2500. # posição X, posição Y e Prioridade do bitmap.
  2501. # Sprite.new([width, height, x, y, z])
  2502. #----------------------------------------------------------------------------
  2503. alias new_initialize initialize
  2504. def initialize(viewport=nil)
  2505. @clone_sprite = []
  2506. @outline_fill_rect = nil
  2507. if viewport.is_a?(String)
  2508. new_initialize(nil)
  2509. if viewport.match(/S: ([^>]*)/)
  2510. self.bitmap = Cache.system($1.to_s)
  2511. elsif viewport.match(/P: ([^>]*)/)
  2512. self.bitmap = Cache.picture($1.to_s)
  2513. elsif viewport.match(/G: ([^>]*)/)
  2514. self.bitmap = Cache.load_bitmap("Graphics/", $1.to_s)
  2515. else
  2516. self.bitmap = Bitmap.new(viewport)
  2517. end
  2518. elsif viewport.is_a?(Array)
  2519. if viewport.size == 2
  2520. new_initialize(nil)
  2521. self.bitmap = Bitmap.new(viewport[0], viewport[1])
  2522. elsif viewport.size == 5
  2523. new_initialize(nil)
  2524. self.bitmap = Bitmap.new(viewport[0], viewport[1])
  2525. self.x, self.y, self.z = viewport[2], viewport[3], viewport[4]
  2526. end
  2527. elsif viewport.is_a?(Viewport) or viewport.nil?
  2528. new_initialize(viewport)
  2529. end
  2530. end
  2531. #----------------------------------------------------------------------------
  2532. # • Renovação do Sprite.
  2533. #----------------------------------------------------------------------------
  2534. alias :dax_core_dispose :dispose
  2535. def dispose
  2536. dax_core_dispose
  2537. @outline_fill_rect.dispose unless @outline_fill_rect.nil? or @outline_fill_rect.disposed?
  2538. end
  2539. #----------------------------------------------------------------------------
  2540. # • Definir um contorno no Sprite em forma de retângulo.
  2541. # color : Cor do contorno.
  2542. # size : Tamanho da linha do contorno.
  2543. # vis : Visibilidade. true - visível | false - invisível.
  2544. #----------------------------------------------------------------------------
  2545. def set_outline(color=Color.new.default, size=2, vis=true)
  2546. @outline_fill_rect = Sprite.new([self.width, self.height, self.x, self.y, self.z+2])
  2547. @outline_fill_rect.bitmap.fill_rect(0, 0, self.width, size, color)
  2548. @outline_fill_rect.bitmap.fill_rect(0, self.height-size, self.width, size, color)
  2549. @outline_fill_rect.bitmap.fill_rect(0, 0, size, self.height, color)
  2550. @outline_fill_rect.bitmap.fill_rect(self.width-size, 0, size, self.height, color)
  2551. @outline_fill_rect.visible = vis
  2552. end
  2553. #----------------------------------------------------------------------------
  2554. # • Atualização do contorno.
  2555. # vis : Visibilidade. true - visível | false - invisível.
  2556. #----------------------------------------------------------------------------
  2557. def update_outline(vis=true)
  2558. @outline_fill_rect.visible = vis
  2559. @outline_fill_rect.x, @outline_fill_rect.y = self.x, self.y
  2560. end
  2561. #----------------------------------------------------------------------------
  2562. # • Slide pela direita.
  2563. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  2564. #----------------------------------------------------------------------------
  2565. def slide_right(speed, point)
  2566. self.x += speed unless self.x >= point
  2567. end
  2568. #----------------------------------------------------------------------------
  2569. # • Slide pela esquerda.
  2570. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  2571. #----------------------------------------------------------------------------
  2572. def slide_left(speed, point)
  2573. self.x -= speed unless self.x <= point
  2574. end
  2575. #----------------------------------------------------------------------------
  2576. # • Slide por cima.
  2577. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  2578. #----------------------------------------------------------------------------
  2579. def slide_up(speed, point)
  2580. self.y -= speed unless self.y <= point
  2581. end
  2582. #----------------------------------------------------------------------------
  2583. # • Slide por baixo.
  2584. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  2585. #----------------------------------------------------------------------------
  2586. def slide_down(speed, point)
  2587. self.y += speed unless self.y >= point
  2588. end
  2589. #----------------------------------------------------------------------------
  2590. # • Define aqui uma posição fixa para um objeto.
  2591. # command : Veja na classe Position.
  2592. #----------------------------------------------------------------------------
  2593. def position(command=0)
  2594. return if command.nil?
  2595. Position[command, self]
  2596. end
  2597. #----------------------------------------------------------------------------
  2598. # • [Numeric] : Tamanho geral
  2599. #----------------------------------------------------------------------------
  2600. def size
  2601. return self.width + self.height
  2602. end
  2603. #----------------------------------------------------------------------------
  2604. # • [Rect] : Retorna ao Rect do Bitmap.
  2605. #----------------------------------------------------------------------------
  2606. def rect
  2607. return self.bitmap.rect
  2608. end
  2609. #----------------------------------------------------------------------------
  2610. # • Base para clonar um Sprite.
  2611. # * depht : Prioridade no mapa.
  2612. # * clone_bitmap : Se irá clonar o bitmap.
  2613. # Exemplo: sprite = sprite2.clone
  2614. #----------------------------------------------------------------------------
  2615. def clone(depht=0, clone_bitmap=false)
  2616. @clone_sprite.delete_if { |bitmap| bitmap.disposed? }
  2617. cloned = Sprite.new(self.viewport)
  2618. cloned.x, cloned.y = self.x, self.y
  2619. cloned.bitmap = self.bitmap
  2620. cloned.bitmap = self.bitmap.clone if clone_bitmap
  2621. unless depht == 0
  2622. cloned.z = self.z + depht
  2623. else
  2624. @clone_sprite.each { |sprite| sprite.z -= 1 }
  2625. cloned.z = self.z - 1
  2626. end
  2627. cloned.src_rect.set(self.src_rect)
  2628. ["zoom_x", "zoom_y", "angle", "mirror", "opacity", "blend_type", "visible",
  2629. "ox", "oy"].each { |meth|
  2630. eval("cloned.#{meth} = self.#{meth}")
  2631. }
  2632. cloned.color.set(color)
  2633. cloned.tone.set(tone)
  2634. after_clone(cloned)
  2635. @clone_sprite.push(cloned)
  2636. return cloned
  2637. end
  2638. #----------------------------------------------------------------------------
  2639. # • Efeito após ter clonado o Sprite.
  2640. #----------------------------------------------------------------------------
  2641. def after_clone(clone)
  2642. end
  2643. #----------------------------------------------------------------------------
  2644. # • O que irá acontecer sê o mouse estiver em cima do sprite?
  2645. #----------------------------------------------------------------------------
  2646. def mouse_over
  2647. end
  2648. #----------------------------------------------------------------------------
  2649. # • O que irá acontecer sê o mouse não estiver em cima do sprite?
  2650. #----------------------------------------------------------------------------
  2651. def mouse_no_over
  2652. end
  2653. #----------------------------------------------------------------------------
  2654. # • O que irá acontecer sê o mouse clicar no objeto
  2655. #----------------------------------------------------------------------------
  2656. def mouse_click
  2657. end
  2658. #----------------------------------------------------------------------------
  2659. # • Atualização dos sprites.
  2660. #----------------------------------------------------------------------------
  2661. alias :dax_update :update
  2662. def update(*args, &block)
  2663. dax_update(*args, &block)
  2664. unless Mouse.cursor.nil?
  2665. self.if_mouse_over { |over| over ? mouse_over : mouse_no_over }
  2666. self.if_mouse_click { mouse_click }
  2667. end
  2668. end
  2669. #----------------------------------------------------------------------------
  2670. # • Inverter o lado do sprite.
  2671. #----------------------------------------------------------------------------
  2672. def mirror!
  2673. self.mirror = !self.mirror
  2674. end
  2675. #----------------------------------------------------------------------------
  2676. # • Inverter o ângulo do sprite em 180°(Pode ser mudado.).
  2677. #----------------------------------------------------------------------------
  2678. def angle!(ang=180)
  2679. self.ox, self.oy = self.bitmap.width, self.bitmap.height
  2680. self.angle += ang
  2681. self.angle += 360 while self.angle < 0
  2682. self.angle %= 360
  2683. end
  2684. end
  2685. }
  2686. #==============================================================================
  2687. # • Bitmap
  2688. #==============================================================================
  2689. Dax.register(:bitmap, "dax", 3.0) {
  2690. class Bitmap
  2691. #--------------------------------------------------------------------------
  2692. # • Constantes.
  2693. #--------------------------------------------------------------------------
  2694. Directory = 'Data/Bitmaps/'
  2695. #--------------------------------------------------------------------------
  2696. # • Salvar as informações do bitmap em um arquivo.
  2697. #--------------------------------------------------------------------------
  2698. def self.saveInfo(bitmap, filename)
  2699. return unless bitmap.is_a?(Bitmap)
  2700. red = Table.new(bitmap.width, bitmap.height)
  2701. green = Table.new(bitmap.width, bitmap.height)
  2702. blue = Table.new(bitmap.width, bitmap.height)
  2703. alpha = Table.new(bitmap.width, bitmap.height)
  2704. bitmap.rect.step(1, 1) { |i, j|
  2705. color = bitmap.get_pixel(i, j)
  2706. red[i, j] = color.red
  2707. green[i, j] = color.green
  2708. blue[i, j] = color.blue
  2709. alpha[i, j] = color.alpha
  2710. }
  2711. Dir.mkdir(Directory) unless File.directory?(Directory)
  2712. file = File.open(Directory + filename + '.rvdata2', 'wb')
  2713. Marshal.dump([red, green, blue, alpha], file)
  2714. file.close
  2715. puts "bitmap saved"
  2716. end
  2717. #--------------------------------------------------------------------------
  2718. # * Abrir o arquivo.
  2719. #--------------------------------------------------------------------------
  2720. def self.readInfo(filename)
  2721. return unless FileTest.exist?(Directory + filename + '.rvdata2')
  2722. file = File.open(Directory + filename + '.rvdata2', "rb")
  2723. colors = Marshal.load(file).compact
  2724. file.close
  2725. red, green, blue, alpha = *colors
  2726. bitmap = Bitmap.new(red.xsize, red.ysize)
  2727. for i in 0...bitmap.width
  2728. for j in 0...bitmap.height
  2729. bitmap.set_pixel(i, j, Color.new(red[i, j], green[i, j], blue[i, j], alpha[i, j]))
  2730. end
  2731. end
  2732. return bitmap
  2733. end
  2734. #----------------------------------------------------------------------------
  2735. # • Modifica o sprite para ficar do tamanho definido.
  2736. #----------------------------------------------------------------------------
  2737. def resize(width=Graphics.width, height=Graphics.height)
  2738. self.stretch_blt(Rect.new(0, 0, width, height), self, self.rect)
  2739. end
  2740. #----------------------------------------------------------------------------
  2741. # • Criar uma barra.
  2742. # color : Objeto de Cor [Color]
  2743. # actual : Valor atual da barra.
  2744. # max : Valor máximo da barra.
  2745. # borda : Tamanho da borda da barra.
  2746. #----------------------------------------------------------------------------
  2747. def bar(color, actual, max, borda=1)
  2748. rate = self.width.to_p(actual, max)
  2749. self.fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  2750. color)
  2751. end
  2752. #----------------------------------------------------------------------------
  2753. # • Barra em forma de gradient.
  2754. # color : Objeto de Cor, em forma de [Array] para conter 2 [Color]
  2755. # exemplo -> [Color.new(x), Color.new(y)]
  2756. # actual : Valor atual da barra.
  2757. # max : Valor máximo da barra.
  2758. # borda : Tamanho da borda da barra.
  2759. #----------------------------------------------------------------------------
  2760. def gradient_bar(color, actual, max, borda=1)
  2761. rate = self.width.to_p(actual, max)
  2762. self.gradient_fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  2763. color[0], color[1], 2)
  2764. end
  2765. #----------------------------------------------------------------------------
  2766. # • Limpar uma área num formato de um círculo.
  2767. #----------------------------------------------------------------------------
  2768. def clear_rect_circle(x, y, r)
  2769. rr = r*r
  2770. for i in 0...r
  2771. adj = Math.sqrt(rr - (i*i)).ceil
  2772. xd = x - adj
  2773. wd = 2 * adj
  2774. self.clear_rect(xd, y-i, wd, 1)
  2775. self.clear_rect(xd, y+i, wd, 1)
  2776. end
  2777. end
  2778. #----------------------------------------------------------------------------
  2779. # • Novo modo de desenhar textos. Configurações já especificadas.
  2780. #----------------------------------------------------------------------------
  2781. def draw_text_rect(*args)
  2782. self.draw_text(self.rect, *args)
  2783. end
  2784. #----------------------------------------------------------------------------
  2785. # • Permite salvar várias imagens em cima de outra.
  2786. # Exemplo de comando:
  2787. # Bitmap.overSave("Pictures/Nova", "Pictures/1", "Characters/2",
  2788. # "Pictures/3", "Characters/4", "Pictures/5")
  2789. # NÃO ESQUEÇA DE ESPECIFICAR ÀS PASTAS.
  2790. #----------------------------------------------------------------------------
  2791. def self.overSave(newfile, first, *args)
  2792. return if first.empty? || first.nil? || args.empty? || args.nil?
  2793. firstB = Bitmap.new("Graphics/"+first)
  2794. args.each { |outhers|
  2795. firstB.stretch_blt(firstB.rect, Bitmap.new("Graphics/"+outhers), firstB.rect)
  2796. }
  2797. firstB.save("Graphics/"+newfile)
  2798. end
  2799. #----------------------------------------------------------------------------
  2800. # • Modificar as cores do [Bitmap] para ficarem Negativas.
  2801. #----------------------------------------------------------------------------
  2802. def negative
  2803. self.rect.step(1.0, 1.0) { |i, j|
  2804. pix = self.get_pixel(i, j)
  2805. pix.red = (pix.red - 255) * -1
  2806. pix.blue = (pix.blue - 255) * -1
  2807. pix.green = (pix.green - 255) * -1
  2808. self.set_pixel(i, j, pix)
  2809. }
  2810. end
  2811. #----------------------------------------------------------------------------
  2812. # • Grayscale : Modificar as cores do [Bitmap] para cor cinza. Efeito cinza.
  2813. #----------------------------------------------------------------------------
  2814. def grayscale(rect = Rect.new(0, 0, self.width, self.height))
  2815. self.rect.step(1, 1) { |i, j|
  2816. colour = self.get_pixel(i,j)
  2817. grey_pixel = (colour.red*0.3 + colour.green*0.59 + colour.blue*0.11)
  2818. colour.red = colour.green = colour.blue = grey_pixel
  2819. self.set_pixel(i,j,colour)
  2820. }
  2821. end
  2822. #----------------------------------------------------------------------------
  2823. # • Converter as cores para sepia.
  2824. #----------------------------------------------------------------------------
  2825. def sepia2
  2826. self.rect.step(1, 1) { |w, h|
  2827. nrow = row = get_pixel(w, h)
  2828. row.red = [(0.393 * nrow.red) + (0.769 * nrow.green) + (0.189 * nrow.blue), 255].min
  2829. row.green = [(0.349 * nrow.red) + (0.689 * nrow.green) + (0.168 * nrow.blue), 255].min
  2830. row.blue = [(0.272 * nrow.red) + (0.534 * nrow.green) + (0.131 * nrow.blue), 255].min
  2831. set_pixel(w, h, row)
  2832. }
  2833. end
  2834. #----------------------------------------------------------------------------
  2835. # • Suavidade nas cores do bitmap. Converte as cores em preto e branco.
  2836. # crlz : Controle da iluminidade.
  2837. #----------------------------------------------------------------------------
  2838. def black_whiteness(ctlz=2.0)
  2839. self.rect.step(1, 1) { |w, h|
  2840. row = get_pixel(w, h)
  2841. getArray__row = row.to_a(false)
  2842. lightCalc_ = (getArray__row.max + getArray__row.min) / ctlz
  2843. row.red = row.green = row.blue = lightCalc_
  2844. set_pixel(w, h, row)
  2845. }
  2846. end
  2847. #----------------------------------------------------------------------------
  2848. # • Novo fornecedor de pixel.
  2849. #----------------------------------------------------------------------------
  2850. def set_pixel_s(x, y, color, size)
  2851. for i in 0...size
  2852. self.set_pixel(x+i, y, color)
  2853. self.set_pixel(x-i, y, color)
  2854. self.set_pixel(x, y+i, color)
  2855. self.set_pixel(x, y-i, color)
  2856. self.set_pixel(x+i, y+i, color)
  2857. self.set_pixel(x-i, y-i, color)
  2858. self.set_pixel(x+i, y-i, color)
  2859. self.set_pixel(x-i, y+i, color)
  2860. end
  2861. end
  2862. #----------------------------------------------------------------------------
  2863. # • Desenhar uma linha.
  2864. # start_x : Início da linha em X.
  2865. # start_y : Início da linha em Y.
  2866. # end_x : Finalização da linha em X.
  2867. # end_y : Finalização da linha em Y.
  2868. #----------------------------------------------------------------------------
  2869. def draw_line(start_x, start_y, end_x, end_y, color, size=1)
  2870. set_pixel_s(start_x, start_y, color, size)
  2871. distance = (start_x - end_x).abs + (start_y - end_y).abs
  2872. for i in 1..distance
  2873. x = (start_x + 1.0 * (end_x - start_x) * i / distance).to_i
  2874. y = (start_y + 1.0 * (end_y - start_y) * i / distance).to_i
  2875. set_pixel_s(x, y, color, size)
  2876. end
  2877. set_pixel_s(end_x, end_y, color, size)
  2878. end
  2879. #----------------------------------------------------------------------------
  2880. # • draw_bar_gauge(x, y, current, current_max, border, colors)
  2881. # x : Coordenadas X.
  2882. # y : Coordenadas Y.
  2883. # current : Valor atual da barra.
  2884. # current_max : Valor maxímo da barra.
  2885. # border : Expressura da borda.
  2886. # colors : Cores. [0, 1]
  2887. #----------------------------------------------------------------------------
  2888. # Permite adicionar uma barra.
  2889. #----------------------------------------------------------------------------
  2890. def draw_bar_gauge(x, y, current, current_max, colors=[])
  2891. cw = self.width.to_p(current, current_max)
  2892. ch = self.height
  2893. self.gradient_fill_rect(x, y, self.width, self.height, colors[0], colors[1])
  2894. src_rect = Rect.new(0, 0, cw, ch)
  2895. self.blt(x, y, self, src_rect)
  2896. end
  2897. #----------------------------------------------------------------------------
  2898. # • draw_icon(icon_index, x, y, enabled)
  2899. # icon_index : ID do ícone.
  2900. # x : Coordenadas X.
  2901. # y : Coordenadas Y.
  2902. # enabled : Habilitar flag, translucido quando false
  2903. # filename : Podes definir uma imagem: Basta
  2904. # por o nome da imagem, ela deve estar na pasta System.
  2905. #----------------------------------------------------------------------------
  2906. def draw_icon(icon_index, x, y, enabled = true, filename="IconSet")
  2907. icon_index = icon_index.nil? ? 0 : icon_index
  2908. bitmap = Cache.system(filename)
  2909. rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
  2910. self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
  2911. end
  2912. #----------------------------------------------------------------------------
  2913. # • draw_gradation_gauge(x, y, width, height, current, current_max, border, colors, align)
  2914. # x : Coordenadas X.
  2915. # y : Coordenadas Y.
  2916. # width : Largura da barra.
  2917. # height : Altura da barra.
  2918. # current : Valor atual da barra.
  2919. # current_max : Valor maxímo da barra.
  2920. # border : Expressura da borda.
  2921. # colors : Cores. [0, 1]
  2922. # align : Alinhamento.
  2923. #----------------------------------------------------------------------------
  2924. # Permite adicionar uma barra.
  2925. #----------------------------------------------------------------------------
  2926. def draw_gradation_gauge(x, y, current, current_max, border, colors=[])
  2927. cw = self.width.to_p(current, current_max)
  2928. ch = self.height
  2929. self.fill_rect(x, y, self.width, self.height, colors[0])
  2930. self.gradient_fill_rect(x+border, y+border, self.width-(border/2), self.height-(border/2), colors[1], colors[2])
  2931. src_rect = Rect.new(0, 0, cw, ch)
  2932. self.blt(x, y, self, src_rect)
  2933. end
  2934. #----------------------------------------------------------------------------
  2935. # • Desenhar um círuclo preenchido.
  2936. #----------------------------------------------------------------------------
  2937. def fill_circle(x, y, r, c)
  2938. rr = r*r
  2939. for i in 0...r
  2940. adj = Math.sqrt(rr - (i*i)).ceil
  2941. xd = x - adj
  2942. wd = 2 * adj
  2943. self.fill_rect(xd, y-i, wd, 1, c)
  2944. self.fill_rect(xd, y+i, wd, 1, c)
  2945. end
  2946. end
  2947. #----------------------------------------------------------------------------
  2948. # • [Brilho] : Aumentar/Diminuir o brilho do sprite.
  2949. #----------------------------------------------------------------------------
  2950. def brightness(vl = 100)
  2951. self.rect.step(1.0, 1.0) { |i, j|
  2952. pix = self.get_pixel(i, j)
  2953. pix = pix.percent(vl)
  2954. self.set_pixel(i, j, pix)
  2955. }
  2956. end
  2957. end
  2958. }
  2959. #==============================================================================
  2960. # • Mouse
  2961. #==============================================================================
  2962. Dax.register(:mouse, "dax", 2.5) {
  2963. module Mouse
  2964. extend self
  2965. #--------------------------------------------------------------------------
  2966. # • Inicialização dos objetos.
  2967. #--------------------------------------------------------------------------
  2968. def start
  2969. @cursor = Sprite_Mouse.new(Dax::MOUSE_NAME, -128, -128, 100000)
  2970. @graphic = Dax::MOUSE_NAME
  2971. x = Dax::MOUSE_NAME == "" ? 1 : 0
  2972. API::MouseShowCursor.call(x)
  2973. @visible = true
  2974. end
  2975. #----------------------------------------------------------------------------
  2976. # • visible = (boolean)
  2977. # * boolean : true ou false
  2978. # Tornar vísivel ou não o cursor do Mouse.
  2979. #----------------------------------------------------------------------------
  2980. def visible=(boolean)
  2981. @visible = boolean
  2982. end
  2983. #--------------------------------------------------------------------------
  2984. # • graphic(graphic_set)
  2985. # graphic_set : Se for número é um ícone; Se for string é uma imagem.
  2986. #--------------------------------------------------------------------------
  2987. def graphic(graphic_set)
  2988. visible = false
  2989. @graphic = graphic_set
  2990. @cursor.set_graphic = graphic_set
  2991. end
  2992. #--------------------------------------------------------------------------
  2993. # • show(visible)
  2994. # visible : True - para mostrar o mouse | False - para esconder o mouse.
  2995. #--------------------------------------------------------------------------
  2996. def show(vis=true)
  2997. @cursor.visible = vis
  2998. end
  2999. #--------------------------------------------------------------------------
  3000. # • update (Atualização das coordenadas)
  3001. #--------------------------------------------------------------------------
  3002. def update
  3003. return if @cursor.nil?
  3004. API::MouseShowCursor.call(@visible.boolean)
  3005. if @cursor.disposed?
  3006. @cursor = Sprite_Mouse.new(@graphic, 0, 0, 100000)
  3007. end
  3008. @cursor.update
  3009. @cursor.x, @cursor.y = position
  3010. end
  3011. #--------------------------------------------------------------------------
  3012. # • Retorna a variável '@cursor' que tem como valor a classe [Sprite].
  3013. #--------------------------------------------------------------------------
  3014. def cursor
  3015. @cursor
  3016. end
  3017. #--------------------------------------------------------------------------
  3018. # • Clear.
  3019. #--------------------------------------------------------------------------
  3020. def clear
  3021. @cursor.dispose
  3022. end
  3023. #--------------------------------------------------------------------------
  3024. # • x (Coordenada X do Mouse)
  3025. #--------------------------------------------------------------------------
  3026. def x
  3027. @cursor.x
  3028. end
  3029. #--------------------------------------------------------------------------
  3030. # • y (Coordenada Y do Mouse)
  3031. #--------------------------------------------------------------------------
  3032. def y
  3033. @cursor.y
  3034. end
  3035. #--------------------------------------------------------------------------
  3036. # • position (Posição do Mouse!)
  3037. #--------------------------------------------------------------------------
  3038. def position
  3039. x, y = get_client_position
  3040. return x, y
  3041. end
  3042. #--------------------------------------------------------------------------
  3043. # • Grid do mapa.
  3044. #--------------------------------------------------------------------------
  3045. def map_grid
  3046. return unless defined?($game_map)
  3047. return nil if x == nil or y == nil
  3048. rx = ($game_map.display_x).to_i + (x / 32)
  3049. ry = ($game_map.display_y).to_i + (y / 32)
  3050. return [rx.to_i, ry.to_i]
  3051. end
  3052. #--------------------------------------------------------------------------
  3053. # • get_client_position (Posição original do Mouse!)
  3054. #--------------------------------------------------------------------------
  3055. def get_client_position
  3056. pos = [0, 0].pack('ll')
  3057. API::CursorPosition.call(pos)
  3058. API::ScreenToClient.call(WINDOW, pos)
  3059. return pos.unpack('ll')
  3060. end
  3061. #--------------------------------------------------------------------------
  3062. # • Verificação se o mouse está na área de um determinado objeto.
  3063. #--------------------------------------------------------------------------
  3064. def in_area?(x)
  3065. return if @cursor.disposed?
  3066. return unless x.is_a?(Sprite) or x.is_a?(Window)
  3067. #return @cursor.x.between?(object_sprite.x, object_sprite.x + object_sprite.width) &&
  3068. # @cursor.y.between?(object_sprite.y, object_sprite.y + object_sprite.height)
  3069. @cursor.x.between?(x.x, (x.x - x.ox + (x.viewport ? x.viewport.rect.x : 0)) + x.width) &&
  3070. @cursor.y.between?(x.y, (x.y - x.oy + (x.viewport ? x.viewport.rect.y : 0)) + x.height)
  3071. end
  3072. #----------------------------------------------------------------------------
  3073. # • Verificar se o mouse está em determinada área
  3074. #----------------------------------------------------------------------------
  3075. def area?(x, y, width, height)
  3076. return @cursor.x.between?(x, x + width) &&
  3077. @cursor.y.between?(y, y + height)
  3078. end
  3079. #----------------------------------------------------------------------------
  3080. # • Mudar posição do cursor.
  3081. #----------------------------------------------------------------------------
  3082. def set_pos(pos)
  3083. pos = pos.position unless pos.is_a? Position
  3084. API::SetCursorPos.call(pos.x, pos.y)
  3085. update
  3086. @cursor.x = pos.x
  3087. @cursor.y = pos.y
  3088. end
  3089. #----------------------------------------------------------------------------
  3090. # • Verifica se clicou com o botão esquerdo do Mouse.
  3091. #----------------------------------------------------------------------------
  3092. def left?
  3093. return Key.trigger?(0x01)
  3094. end
  3095. #----------------------------------------------------------------------------
  3096. # • Verifica se clicou com o botão direito do Mouse.
  3097. #----------------------------------------------------------------------------
  3098. def right?
  3099. return Key.trigger?(0x02)
  3100. end
  3101. WINDOW = API.hWND
  3102. end
  3103. #==============================================================================
  3104. # • Sprite_Mouse
  3105. #==============================================================================
  3106. class Sprite_Mouse < Sprite
  3107. #----------------------------------------------------------------------------
  3108. # • Variáveis públicas da instância.
  3109. #----------------------------------------------------------------------------
  3110. attr_accessor :set_graphic # definir o gráfico.
  3111. #----------------------------------------------------------------------------
  3112. # • Inicialização dos objetos.
  3113. #----------------------------------------------------------------------------
  3114. def initialize(graphic, x, y, z)
  3115. super(nil)
  3116. @set_graphic = graphic
  3117. if @set_graphic.is_a?(Fixnum)
  3118. self.bitmap = Bitmap.new(24, 24)
  3119. self.bitmap.draw_icon(@set_graphic, 0, 0)
  3120. elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  3121. self.bitmap = Bitmap.new(1, 1)
  3122. elsif @set_graphic.is_a?(String)
  3123. self.bitmap = Cache.system(@set_graphic)
  3124. end
  3125. self.x, self.y, self.z = x, y, z
  3126. @older = @set_graphic
  3127. end
  3128. #----------------------------------------------------------------------------
  3129. # • Renovação dos objetos.
  3130. #----------------------------------------------------------------------------
  3131. def dispose
  3132. self.bitmap.dispose
  3133. super
  3134. end
  3135. #----------------------------------------------------------------------------
  3136. # • Atualização dos objetos.
  3137. #----------------------------------------------------------------------------
  3138. def update
  3139. super
  3140. unless @older == @set_graphic
  3141. if @set_graphic.is_a?(Fixnum)
  3142. self.bitmap = Bitmap.new(24, 24)
  3143. self.bitmap.draw_icon(@set_graphic, 0, 0)
  3144. elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  3145. self.bitmap = Bitmap.new(1, 1)
  3146. elsif @set_graphic.is_a?(String)
  3147. self.bitmap = Cache.system(@set_graphic)
  3148. end
  3149. @older = @set_graphic
  3150. end
  3151. end
  3152. end
  3153. Mouse.start
  3154. }
  3155. #==============================================================================
  3156. # • Object
  3157. #==============================================================================
  3158. Dax.register(:object, "dax", 2.0) {
  3159. class Object
  3160. #----------------------------------------------------------------------------
  3161. # • [Hex] : Retorna ao id do objeto em hexadécimal.
  3162. #----------------------------------------------------------------------------
  3163. def __hexid__
  3164. "0x" + ('%.X' % (self.__id__ * 2))
  3165. end
  3166. #----------------------------------------------------------------------------
  3167. # • O que irá ocorrer caso o mouse esteja sobre uma sprite.
  3168. # Tem que ser um objeto Sprite.
  3169. #----------------------------------------------------------------------------
  3170. def if_mouse_over(&block)
  3171. return if Mouse.cursor.nil?
  3172. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  3173. over ||= false
  3174. if Mouse.in_area?(self)
  3175. block.call
  3176. over = true
  3177. else
  3178. over = false
  3179. end
  3180. yield over
  3181. end
  3182. #----------------------------------------------------------------------------
  3183. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao clicar.
  3184. # Tem que ser um objeto Sprite.
  3185. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  3186. # EXPLICAÇÕES NO FINAL DO SCRIPT.
  3187. #----------------------------------------------------------------------------
  3188. def if_mouse_click(button=:left, &block)
  3189. return if Mouse.cursor.nil?
  3190. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  3191. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  3192. block.call if Mouse.in_area?(self) and trigger?(button)
  3193. end
  3194. #----------------------------------------------------------------------------
  3195. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao pressionar.
  3196. # Tem que ser um objeto Sprite.
  3197. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  3198. #----------------------------------------------------------------------------
  3199. def if_mouse_press(button=:left, &block)
  3200. return if Mouse.cursor.nil?
  3201. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  3202. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  3203. block.call if Mouse.in_area?(self) and press?(button)
  3204. end
  3205. #----------------------------------------------------------------------------
  3206. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao ficar clicando.
  3207. # Tem que ser um objeto Sprite.
  3208. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  3209. #----------------------------------------------------------------------------
  3210. def if_mouse_repeat(button=:left, &block)
  3211. return if Mouse.cursor.nil?
  3212. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  3213. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  3214. block.call if Mouse.in_area?(self) and repeat?(button)
  3215. end
  3216. #----------------------------------------------------------------------------
  3217. # • Trigger
  3218. # * key : Chave.
  3219. # Você também pode usá-lo como condição para executar tal bloco;
  3220. #----------------------------------------------------------------------------
  3221. # trigger?(key) { bloco que irá executar }
  3222. #----------------------------------------------------------------------------
  3223. def trigger?(key, &block)
  3224. if key == :C or key == :B
  3225. ckey = Input.trigger?(key)
  3226. else
  3227. ckey = Key.trigger?(key)
  3228. end
  3229. return ckey unless block_given?
  3230. block.call if ckey
  3231. end
  3232. #----------------------------------------------------------------------------
  3233. # • Press
  3234. # * key : Chave.
  3235. # Você também pode usá-lo como condição para executar tal bloco;
  3236. #----------------------------------------------------------------------------
  3237. # press?(key) { bloco que irá executar. }
  3238. #----------------------------------------------------------------------------
  3239. def press?(key, &block)
  3240. if key == :C or key == :B
  3241. ckey = Input.press?(key)
  3242. else
  3243. ckey = Key.press?(key)
  3244. end
  3245. return ckey unless block_given?
  3246. block.call if ckey
  3247. end
  3248. #----------------------------------------------------------------------------
  3249. # • Repeat
  3250. # * key : Chave.
  3251. # Você também pode usá-lo como condição para executar tal bloco;
  3252. #----------------------------------------------------------------------------
  3253. # repeat?(key) { bloco que irá executar. }
  3254. #----------------------------------------------------------------------------
  3255. def repeat?(key, &block)
  3256. if key == :C or key == :B
  3257. ckey = Input.repeat?(key)
  3258. else
  3259. ckey = Key.repeat?(key)
  3260. end
  3261. return ckey unless block_given?
  3262. block.call if ckey
  3263. end
  3264. #----------------------------------------------------------------------------
  3265. # • Retorna em forma de número os valores true ou false. E caso seja
  3266. # 0 ou 1.. retorna a true ou false.
  3267. # Se for true, retorna a 1.
  3268. # Se for false, retorna a 0.
  3269. # Se for 1, retorna a true.
  3270. # Se for 0, retorna a false.
  3271. #----------------------------------------------------------------------------
  3272. def boolean
  3273. return self.is_a?(Integer) ? self == 0 ? false : 1 : self ? 1 : 0
  3274. end
  3275. #----------------------------------------------------------------------------
  3276. # • Converte para a classe Position.
  3277. #----------------------------------------------------------------------------
  3278. def position
  3279. return Position.new(self, self) if self.is_a?(Numeric)
  3280. return Position.new(self.x, self.y) if self.is_a?(Sprite) or self.is_a?(Window_Base) or self.is_a?(Rect)
  3281. return Position.new(self[0], self[1]) if self.is_a?(Array)
  3282. return Position.new(self[:x], self[:y]) if self.is_a?(Hash)
  3283. return Position.new(self.x, self.y) if defined?(self.x) and defined?(self.y)
  3284. return Position.new(0, 0)
  3285. end
  3286. #----------------------------------------------------------------------------
  3287. # • Transforma em cor.
  3288. # Se for uma Array. Exemplo: [128, 174, 111].color =># Color.new(128, 174, 111)
  3289. # Se for uma String. Exemplo: "ffffff".color =># Color.new(255,255,255)
  3290. #----------------------------------------------------------------------------
  3291. def color
  3292. return Color.new(*self) if self.is_a?(Array)
  3293. return Color.new.hex(self) if self.is_a?(String)
  3294. end
  3295. end
  3296. }
  3297. #==============================================================================
  3298. # • Entries
  3299. #==============================================================================
  3300. Dax.register(:entries, "dax", 2.0) {
  3301. class Entries
  3302. #----------------------------------------------------------------------------
  3303. # • [Array] : Irá retornar a todos os nomes dos arquivos da pasta, dentro de
  3304. # uma Array em formato de String.
  3305. #----------------------------------------------------------------------------
  3306. attr_accessor :file
  3307. #----------------------------------------------------------------------------
  3308. # • [Integer] : Retorna a quantidade total de arquivos que têm na pasta.
  3309. #----------------------------------------------------------------------------
  3310. attr_reader :size
  3311. #----------------------------------------------------------------------------
  3312. # • Inicialização dos objetos.
  3313. # directory : Nome da pasta. Não ponha '/' no final do nome. Ex: 'Data/'
  3314. # typefile : Nome da extensão do arquivo. Não ponha '.' no começo. Ex: '.txt'
  3315. #----------------------------------------------------------------------------
  3316. def initialize(directory, typefile)
  3317. return unless FileTest.directory?(directory)
  3318. @file = Dir.glob(directory + "/*.{" + typefile + "}")
  3319. @file.each_index { |i| @size = i.to_i }
  3320. @name = split @file[0]
  3321. end
  3322. #----------------------------------------------------------------------------
  3323. # • [String] : Separar o nome do arquivo do nome da pasta.
  3324. #----------------------------------------------------------------------------
  3325. def split(file)
  3326. file.to_s.split('/').last
  3327. end
  3328. #----------------------------------------------------------------------------
  3329. # • [String] : Obtêm o nome do arquivo correspondente ao id configurado,
  3330. # separado do nome da pasta.
  3331. #----------------------------------------------------------------------------
  3332. def name(id)
  3333. return if @file.nil?
  3334. return split(@file[id])
  3335. end
  3336. end
  3337. }
  3338. #==============================================================================
  3339. # • DRGSS | Comandos do RGSS...
  3340. #==============================================================================
  3341. Dax.register(:drgss, "dax", 1.0) {
  3342. module DRGSS
  3343. extend self
  3344. #----------------------------------------------------------------------------
  3345. # • Extrair scripts do Database para um arquivo de extensão de texto.
  3346. # options : Caso você deixe assim: {folder: "NM"}
  3347. # NM => Nome da pasta na qual os arquivos irão.
  3348. #----------------------------------------------------------------------------
  3349. def extract_scripts(type=".txt",options={})
  3350. except = options[:except] || []
  3351. folder = options[:folder] || ""
  3352. id = 0 #
  3353. $RGSS_SCRIPTS.each do |script|
  3354. name = script[1]
  3355. data = script[3]
  3356. next if except.include? name or name.empty? or data.empty?
  3357. filename = sprintf("%03d", id) + "_" + name
  3358. puts "Writing: #{filename}"
  3359. File.open(folder+filename+"#{type}", "wb") do |file|
  3360. file.write data
  3361. end
  3362. id += 1
  3363. end
  3364. end
  3365. end
  3366. }
  3367. #==============================================================================
  3368. # • Backup Complete
  3369. #==============================================================================
  3370. Dax.register(:backup, "dax", 3.0) {
  3371. module Backup
  3372. extend self
  3373. #----------------------------------------------------------------------------
  3374. # • Const.
  3375. #----------------------------------------------------------------------------
  3376. DIR = "./Backup"
  3377. COPYFILE = ->(*args) { API::CopyFile.call(*args) }
  3378. #----------------------------------------------------------------------------
  3379. # • Call.
  3380. #----------------------------------------------------------------------------
  3381. def run(complete=false)
  3382. return unless $TEST
  3383. Dir.mkdir(DIR) unless FileTest.directory? DIR
  3384. complete ? call_complete : call_data
  3385. end
  3386. private
  3387. #----------------------------------------------------------------------------
  3388. # • Call of the Data.
  3389. #----------------------------------------------------------------------------
  3390. def call_data
  3391. Dir.mkdir(DIR + "/Data") unless FileTest.directory? DIR + "/Data"
  3392. Dir.glob("./Data/*").each { |_data| COPYFILE[_data, DIR + _data, 1] }
  3393. end
  3394. #----------------------------------------------------------------------------
  3395. # • Call Complete.
  3396. #----------------------------------------------------------------------------
  3397. def call_complete
  3398. Dir.glob(File.join("**", "**")).each { |_backup|
  3399. next if _backup.match(/Backup/im)
  3400. _dir = FileTest.directory?(_backup) ? _backup : _backup.gsub!(/\/\.(\w+)/, "")
  3401. Dir.mkdir(DIR + "/#{_dir}") unless FileTest.directory? DIR + "/#{_dir}"
  3402. COPYFILE[_backup, DIR + "/" + _backup, 1]
  3403. }
  3404. end
  3405. end
  3406. }
  3407. #==============================================================================
  3408. # * SceneManager
  3409. #==============================================================================
  3410. Dax.register(:scenemanager, "dax", 1.0) {
  3411. if defined?("SceneManager")
  3412. class << SceneManager
  3413. #--------------------------------------------------------------------------
  3414. # • Chama uma outra scene.
  3415. # scene_symbol : Nome da scene, podendo ser em símbolo ou string.
  3416. #--------------------------------------------------------------------------
  3417. def symbol(scene_symbol)
  3418. eval("self.call(#{scene_symbol.to_s})")
  3419. end
  3420. alias :eval :symbol
  3421. end
  3422. end
  3423. }
  3424. #==============================================================================
  3425. # • Sprite_Text
  3426. #==============================================================================
  3427. Dax.register(:sprite_text, "dax", 2.0) {
  3428. class Sprite_Text < Sprite
  3429. #----------------------------------------------------------------------------
  3430. # • Variáveis públicas da instância.
  3431. #----------------------------------------------------------------------------
  3432. attr_accessor :text # Mudar de texto...
  3433. attr_accessor :align
  3434. #----------------------------------------------------------------------------
  3435. # • Inicialização dos objetos.
  3436. #----------------------------------------------------------------------------
  3437. def initialize(x, y, width, height, text, align=0)
  3438. super([width, height])
  3439. self.x, self.y = x, y
  3440. @text = text
  3441. @align = align
  3442. self.bitmap.draw_text_rect(@text, align)
  3443. end
  3444. #----------------------------------------------------------------------------
  3445. # • Renovação dos objetos.
  3446. #----------------------------------------------------------------------------
  3447. def dispose
  3448. self.bitmap.dispose
  3449. super
  3450. end
  3451. #----------------------------------------------------------------------------
  3452. # • Atualização dos objetos.
  3453. #----------------------------------------------------------------------------
  3454. def update
  3455. self.bitmap.clear unless self.bitmap.disposed?
  3456. super
  3457. self.bitmap.draw_text_rect(@text, @align)
  3458. end
  3459.  
  3460. def size=(value=18)
  3461. self.bitmap.font.size = value
  3462. end
  3463. def name=(value=nil)
  3464. self.bitmap.font.name = value || "Arial"
  3465. end
  3466. #----------------------------------------------------------------------------
  3467. # • Negrito na fonte?
  3468. #----------------------------------------------------------------------------
  3469. def bold=(value=nil)
  3470. self.bitmap.font.bold = value || true
  3471. end
  3472. #----------------------------------------------------------------------------
  3473. # • Itálico na fonte?
  3474. #----------------------------------------------------------------------------
  3475. def italic=(value=nil)
  3476. self.bitmap.font.italic = value || true
  3477. end
  3478. #----------------------------------------------------------------------------
  3479. # • Sombra na fonte?
  3480. #----------------------------------------------------------------------------
  3481. def shadow=(value=nil)
  3482. self.bitmap.font.shadow = value || true
  3483. end
  3484. #----------------------------------------------------------------------------
  3485. # • Borda na fonte?
  3486. #----------------------------------------------------------------------------
  3487. def outline=(value=nil)
  3488. self.bitmap.font.outline = value || true
  3489. end
  3490. #----------------------------------------------------------------------------
  3491. # • Mudar a cor da fonte:
  3492. #----------------------------------------------------------------------------
  3493. def color=(color=nil)
  3494. self.bitmap.font.color = color || Color.new.default
  3495. end
  3496. #----------------------------------------------------------------------------
  3497. # • Mudar a cor da borda da fonte.
  3498. #----------------------------------------------------------------------------
  3499. def out_color=(out_color=nil)
  3500. self.bitmap.font.out_color = out_color || Color.new.hex("000000")
  3501. end
  3502. end
  3503. }
  3504. #==============================================================================
  3505. # • Opacity
  3506. #==============================================================================
  3507. Dax.register(:opacity, "dax", 2.0) {
  3508. module Opacity
  3509. extend self
  3510. @key ||= {}
  3511. @time ||= {}
  3512. #----------------------------------------------------------------------------
  3513. # • Efeito de opacidade que vai aumentando e diminuindo.
  3514. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3515. # speed : Velocidade na qual o efeito irá acontencer.
  3516. # max : Valor máximo na qual irá ser atingido.
  3517. # min : Valor minímo na qual irá ser atingido.
  3518. #----------------------------------------------------------------------------
  3519. def sprite_opacity(sprite, speed, max, min, hash=nil)
  3520. @key[hash.nil? ? hash.__id__ : hash] || false
  3521. unless @key[hash]
  3522. sprite.opacity += speed unless sprite.opacity >= max
  3523. @key[hash] = sprite.opacity >= max
  3524. else
  3525. sprite.opacity -= speed unless sprite.opacity <= min
  3526. @key[hash] = false if sprite.opacity <= min
  3527. end
  3528. end
  3529. #----------------------------------------------------------------------------
  3530. # • Efeito de opacidade por fora.
  3531. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3532. # speed : Velocidade na qual o efeito irá acontencer.
  3533. # max : Valor máximo na qual irá ser atingido.
  3534. #----------------------------------------------------------------------------
  3535. def sprite_opacity_out(sprite, speed, max)
  3536. return if sprite.nil?
  3537. sprite.opacity += speed unless sprite.opacity >= max
  3538. end
  3539. #----------------------------------------------------------------------------
  3540. # • Efeito de opacidade por dentro.
  3541. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3542. # speed : Velocidade na qual o efeito irá acontencer.
  3543. # min : Valor minímo na qual irá ser atingido.
  3544. #----------------------------------------------------------------------------
  3545. def sprite_opacity_in(sprite, speed, min)
  3546. sprite.opacity -= speed unless sprite.opacity <= min
  3547. end
  3548. #----------------------------------------------------------------------------
  3549. # • Limpar variável.
  3550. #----------------------------------------------------------------------------
  3551. def clear
  3552. @key.clear
  3553. end
  3554. end
  3555. }
  3556. #==============================================================================
  3557. # • Read
  3558. #==============================================================================
  3559. Dax.register(:read, "dax", 1.0) {
  3560. module Read
  3561. extend self
  3562. #----------------------------------------------------------------------------
  3563. # • Verificar valor numérico após uma palavra em um arquivo.
  3564. #----------------------------------------------------------------------------
  3565. def numeric(file, tag)
  3566. IO.readlines(file).each do |line|
  3567. return $1.to_i if line.match(/#{tag}(\d+)/)
  3568. end
  3569. end
  3570. #----------------------------------------------------------------------------
  3571. # • Verificar valor de uma palavra(string única) após uma palavra em um arquivo
  3572. #----------------------------------------------------------------------------
  3573. def string(file, tag)
  3574. IO.readlines(file).each do |line|
  3575. return $1.to_s if line.match(/#{tag}(\w+)/)
  3576. end
  3577. end
  3578. #----------------------------------------------------------------------------
  3579. # • Verificar um conteúdo após uma palavra de um arquivo.
  3580. #----------------------------------------------------------------------------
  3581. def content(file, tag)
  3582. IO.readlines(file).each do |line|
  3583. return $1 if line.match(/#{tag}([^>]*)/)
  3584. end
  3585. end
  3586. #----------------------------------------------------------------------------
  3587. # • Multiplo número..
  3588. #----------------------------------------------------------------------------
  3589. def multiple_numeric(file, tag)
  3590. IO.readlines(file).each do |line|
  3591. return [$1.to_i, $2.to_i] if line.match(/#{tag}(\d+), (\d+)/)
  3592. end
  3593. end
  3594. #----------------------------------------------------------------------------
  3595. # • Multiplo string..
  3596. #----------------------------------------------------------------------------
  3597. def multiple_string(file, tag)
  3598. IO.readlines(file).each do |line|
  3599. return [$1.to_s, $2.to_s] if line.match(/#{tag}(\w+), (\w+)/)
  3600. end
  3601. end
  3602. #----------------------------------------------------------------------------
  3603. # • Triplo número.
  3604. #----------------------------------------------------------------------------
  3605. def triple_numeric(file, tag)
  3606. IO.readlines(file).each do |line|
  3607. return [$1.to_i, $2.to_i, $3.to_i] if line.match(/#{tag}(\d+), (\d+), (\d+)/)
  3608. end
  3609. end
  3610. #----------------------------------------------------------------------------
  3611. # • Triplo string.
  3612. #----------------------------------------------------------------------------
  3613. def triple_string(file, tag)
  3614. IO.readlines(file).each do |line|
  3615. return [$1.to_s, $2.to_s, $3.to_s] if line.match(/#{tag}(\w+), (\w+), (\w+)/)
  3616. end
  3617. end
  3618. #----------------------------------------------------------------------------
  3619. # • Se é verdairo ou falo.
  3620. #----------------------------------------------------------------------------
  3621. def of(file, tag)
  3622. IO.readlines(file).each do |line|
  3623. return $1.to_s == "true" ? true : false if line.match(/#{tag}([^>]*)/)
  3624. end
  3625. end
  3626. end
  3627. }
  3628. #==============================================================================
  3629. # * Window_Base
  3630. #==============================================================================
  3631. Dax.register(:window_base, "dax", 1.5) {
  3632. if defined?("Window_Base")
  3633. class Window_Base < Window
  3634. #----------------------------------------------------------------------------
  3635. # • Slide pela direita.
  3636. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  3637. #----------------------------------------------------------------------------
  3638. def slide_right(speed, point)
  3639. self.x += speed unless self.x >= point
  3640. end
  3641. #----------------------------------------------------------------------------
  3642. # • Slide pela esquerda.
  3643. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  3644. #----------------------------------------------------------------------------
  3645. def slide_left(speed, point)
  3646. self.x -= speed unless self.x <= point
  3647. end
  3648. #----------------------------------------------------------------------------
  3649. # • Slide por cima.
  3650. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  3651. #----------------------------------------------------------------------------
  3652. def slide_up(speed, point)
  3653. self.y -= speed unless self.y <= point
  3654. end
  3655. #----------------------------------------------------------------------------
  3656. # • Slide por baixo.
  3657. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  3658. #----------------------------------------------------------------------------
  3659. def slide_down(speed, point)
  3660. self.y += speed unless self.y >= point
  3661. end
  3662. #----------------------------------------------------------------------------
  3663. # • Define aqui uma posição fixa para um objeto.
  3664. # command : Retorna a uma base padrão.
  3665. #----------------------------------------------------------------------------
  3666. def position(command=0)
  3667. return if command.nil?
  3668. Position[command, self]
  3669. end
  3670. end
  3671. end
  3672. }
  3673. #==============================================================================
  3674. # • Sound Base
  3675. #==============================================================================
  3676. Dax.register(:soundbase, "dax", 1.0) {
  3677. module SoundBase
  3678. #----------------------------------------------------------------------------
  3679. # • Função do módulo.
  3680. #----------------------------------------------------------------------------
  3681. module_function
  3682. #----------------------------------------------------------------------------
  3683. # • Executar um som.
  3684. # name : Nome do som.
  3685. # volume : Volume.
  3686. # pitch : Pitch;
  3687. #----------------------------------------------------------------------------
  3688. def play(name, volume, pitch, type = :se)
  3689. case type
  3690. when :se ; RPG::SE.new(name, volume, pitch).play rescue valid?(name)
  3691. when :me ; RPG::ME.new(name, volume, pitch).play rescue valid?(name)
  3692. when :bgm ; RPG::BGM.new(name, volume, pitch).play rescue valid?(name)
  3693. when :bgs ; RPG::BGS.new(name, volume, pitch).play rescue valid?(name)
  3694. end
  3695. end
  3696. #----------------------------------------------------------------------------
  3697. # • Validar som.
  3698. #----------------------------------------------------------------------------
  3699. def valid?(name)
  3700. raise("Arquivo de som não encontrado: #{name}")
  3701. exit
  3702. end
  3703. end
  3704. }
  3705. #==============================================================================
  3706. # • Benchmark
  3707. #==============================================================================
  3708. Dax.register(:benchmark, "Gotoken", 1.0) {
  3709. module Benchmark
  3710. extend self
  3711. #----------------------------------------------------------------------------
  3712. # • Constantes.
  3713. #----------------------------------------------------------------------------
  3714. CAPTION = " user system total real\n"
  3715. FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
  3716. def Benchmark::times() # :nodoc:
  3717. Process::times()
  3718. end
  3719. #----------------------------------------------------------------------------
  3720. # • Método do benchmark.:.
  3721. # ** Exemplo:.:
  3722. # n = 50000
  3723. # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
  3724. # tf = x.report("for:") { for i in 1..n; a = "1"; end }
  3725. # tt = x.report("times:") { n.times do ; a = "1"; end }
  3726. # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  3727. # [tf+tt+tu, (tf+tt+tu)/3]
  3728. # end
  3729. # ** Gera:.:
  3730. # user system total real
  3731. # for: 1.016667 0.016667 1.033333 ( 0.485749)
  3732. # times: 1.450000 0.016667 1.466667 ( 0.681367)
  3733. # upto: 1.533333 0.000000 1.533333 ( 0.722166)
  3734. # >total: 4.000000 0.033333 4.033333 ( 1.889282)
  3735. # >avg: 1.333333 0.011111 1.344444 ( 0.629761)
  3736. #----------------------------------------------------------------------------
  3737. def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report
  3738. sync = STDOUT.sync
  3739. STDOUT.sync = true
  3740. label_width ||= 0
  3741. fmtstr ||= FMTSTR
  3742. raise ArgumentError, "no block" unless iterator?
  3743. print caption
  3744. results = yield(Report.new(label_width, fmtstr))
  3745. Array === results and results.grep(Tms).each {|t|
  3746. print((labels.shift || t.label || "").ljust(label_width),
  3747. t.format(fmtstr))
  3748. }
  3749. STDOUT.sync = sync
  3750. end
  3751. #----------------------------------------------------------------------------
  3752. # • Versão simplificada para benchmark.
  3753. # ** Exemplo:.:
  3754. # n = 50000
  3755. # Benchmark.bm(7) do |x|
  3756. # x.report("for:") { for i in 1..n; a = "1"; end }
  3757. # x.report("times:") { n.times do ; a = "1"; end }
  3758. # x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  3759. # end
  3760. # ** Gera:.:
  3761. # user system total real
  3762. # for: 1.050000 0.000000 1.050000 ( 0.503462)
  3763. # times: 1.533333 0.016667 1.550000 ( 0.735473)
  3764. # upto: 1.500000 0.016667 1.516667 ( 0.711239)
  3765. #----------------------------------------------------------------------------
  3766. def bm(label_width = 0, *labels, &blk) # :yield: report
  3767. benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
  3768. end
  3769. #----------------------------------------------------------------------------
  3770. # • Retorna ao tempo usado para executar o bloco como um objeto Benchmark::Tms
  3771. #----------------------------------------------------------------------------
  3772. def measure(label = "") # :yield:
  3773. t0, r0 = Benchmark.times, Time.now
  3774. yield
  3775. t1, r1 = Benchmark.times, Time.now
  3776. Benchmark::Tms.new(t1.utime - t0.utime,
  3777. t1.stime - t0.stime,
  3778. t1.cutime - t0.cutime,
  3779. t1.cstime - t0.cstime,
  3780. r1.to_f - r0.to_f,
  3781. label)
  3782. end
  3783. #----------------------------------------------------------------------------
  3784. # • Retorna ao tempo real decorrido, o tempo usado para executar o bloco.
  3785. #----------------------------------------------------------------------------
  3786. def realtime(&blk) # :yield:
  3787. r0 = Time.now
  3788. yield
  3789. r1 = Time.now
  3790. r1.to_f - r0.to_f
  3791. end
  3792. #============================================================================
  3793. # • Report ::
  3794. #============================================================================
  3795. class Report
  3796. #--------------------------------------------------------------------------
  3797. # • Retorna uma instância inicializada.
  3798. # Usualmente não é bom chamar esse método diretamente.
  3799. #--------------------------------------------------------------------------
  3800. def initialize(width = 0, fmtstr = nil)
  3801. @width, @fmtstr = width, fmtstr
  3802. end
  3803. #--------------------------------------------------------------------------
  3804. # • Imprime o _label_ e o tempo marcado pelo bloco, formatado por _fmt_.
  3805. #--------------------------------------------------------------------------
  3806. def item(label = "", *fmt, &blk) # :yield:
  3807. print label.ljust(@width)
  3808. res = Benchmark::measure(&blk)
  3809. print res.format(@fmtstr, *fmt)
  3810. res
  3811. end
  3812. #--------------------------------------------------------------------------
  3813. # • Método :alias:
  3814. #--------------------------------------------------------------------------
  3815. alias :report :item
  3816. end
  3817. #============================================================================
  3818. # • Tms
  3819. #============================================================================
  3820. class Tms
  3821. #--------------------------------------------------------------------------
  3822. # • Constantes
  3823. #--------------------------------------------------------------------------
  3824. CAPTION = " user system total real\n"
  3825. FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
  3826. #--------------------------------------------------------------------------
  3827. # • Variáveis da instância.
  3828. #--------------------------------------------------------------------------
  3829. attr_reader :utime # Tempo da CPU do Usuário.
  3830. attr_reader :stime # Tempo da CPU do Sistema.
  3831. attr_reader :cutime # Tempo da CPU do usuário-criança.
  3832. attr_reader :cstime # Tempo da CPU do sistema-criança.
  3833. attr_reader :real # Tempo real corrido.
  3834. attr_reader :total # Tempo total, que é _utime_ + _stime_ + _cutime_ + _cstime_
  3835. attr_reader :label # Label.
  3836. #--------------------------------------------------------------------------
  3837. # • Retorna ao objeto inicializado na qual tem _u_ como tempo dá CPU do
  3838. # usuário, _s_ como o tempo da CPU do sistema, _cu_ como tempo dá CPU
  3839. # do usuário-criança, _cs_ como o tempo dá CPU sistema-criança, _real_
  3840. # como o tempo real corrido e _l_ como label.
  3841. #--------------------------------------------------------------------------
  3842. def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)
  3843. @utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l
  3844. @total = @utime + @stime + @cutime + @cstime
  3845. end
  3846. #--------------------------------------------------------------------------
  3847. # • Retorna a um novo objeto Tms, na qual os tempos são somados num todo
  3848. # pelo objeto Tms.
  3849. #--------------------------------------------------------------------------
  3850. def add(&blk) # :yield:
  3851. self + Benchmark::measure(&blk)
  3852. end
  3853. #--------------------------------------------------------------------------
  3854. # • Uma versão no lugar do método #add
  3855. #--------------------------------------------------------------------------
  3856. def add!
  3857. t = Benchmark::measure(&blk)
  3858. @utime = utime + t.utime
  3859. @stime = stime + t.stime
  3860. @cutime = cutime + t.cutime
  3861. @cstime = cstime + t.cstime
  3862. @real = real + t.real
  3863. self
  3864. end
  3865. #--------------------------------------------------------------------------
  3866. # • Soma com outro objeto do mesmo.
  3867. #--------------------------------------------------------------------------
  3868. def +(other); memberwise(:+, other) end
  3869. #--------------------------------------------------------------------------
  3870. # • Subtrai com outro objeto do mesmo.
  3871. #--------------------------------------------------------------------------
  3872. def -(other); memberwise(:-, other) end
  3873. #--------------------------------------------------------------------------
  3874. # • Multiplica com outro objeto do mesmo.
  3875. #--------------------------------------------------------------------------
  3876. def *(x); memberwise(:*, x) end
  3877. #--------------------------------------------------------------------------
  3878. # • Divide com outro objeto do mesmo.
  3879. #--------------------------------------------------------------------------
  3880. def /(x); memberwise(:/, x) end
  3881. #--------------------------------------------------------------------------
  3882. # • Retorna ao conteudo dos objetos formatados como uma string.
  3883. #--------------------------------------------------------------------------
  3884. def format(arg0 = nil, *args)
  3885. fmtstr = (arg0 || FMTSTR).dup
  3886. fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label}
  3887. fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime}
  3888. fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime}
  3889. fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime}
  3890. fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime}
  3891. fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total}
  3892. fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real}
  3893. arg0 ? Kernel::format(fmtstr, *args) : fmtstr
  3894. end
  3895. #--------------------------------------------------------------------------
  3896. # • Mesmo que o método formato.
  3897. #--------------------------------------------------------------------------
  3898. def to_s
  3899. format
  3900. end
  3901. #--------------------------------------------------------------------------
  3902. # • Retorna a uma array contendo os elementos:
  3903. # @label, @utime, @stime, @cutime, @cstime, @real
  3904. #--------------------------------------------------------------------------
  3905. def to_a
  3906. [@label, @utime, @stime, @cutime, @cstime, @real]
  3907. end
  3908. protected
  3909. def memberwise(op, x)
  3910. case x
  3911. when Benchmark::Tms
  3912. Benchmark::Tms.new(utime.__send__(op, x.utime),
  3913. stime.__send__(op, x.stime),
  3914. cutime.__send__(op, x.cutime),
  3915. cstime.__send__(op, x.cstime),
  3916. real.__send__(op, x.real)
  3917. )
  3918. else
  3919. Benchmark::Tms.new(utime.__send__(op, x),
  3920. stime.__send__(op, x),
  3921. cutime.__send__(op, x),
  3922. cstime.__send__(op, x),
  3923. real.__send__(op, x)
  3924. )
  3925. end
  3926. end
  3927. CAPTION = Benchmark::Tms::CAPTION
  3928. FMTSTR = Benchmark::Tms::FMTSTR
  3929. end
  3930. end
  3931. }
  3932. #==============================================================================
  3933. # • Desativar scripts : Para fazer, basta por no nome do script da lista,
  3934. # [D].
  3935. # • Salvar script em arquivo de texto : Para fazer, basta por no nome do script da lista,
  3936. # [S].
  3937. #==============================================================================
  3938. $RGSS_SCRIPTS.each_with_index { |data, index|
  3939. if data.at(1).include?("[S]")
  3940. File.open("#{rgss.at(1)}.txt", "wb") { |file|
  3941. file.write(String($RGSS_SCRIPTS.at(index)[3]))
  3942. file.close
  3943. }
  3944. end
  3945. $RGSS_SCRIPTS.at(index)[2] = $RGSS_SCRIPTS.at(index)[3] = "" if data.at(1).include?("[D]")
  3946. }
  3947. #-----------------------------------------------------------------------------
  3948. # • Carregar arquivo e executar.
  3949. # path : Nome do arquivo.
  3950. #-----------------------------------------------------------------------------
  3951. def load_script(path)
  3952. raise("Arquivo não encontrado %s" % path) unless FileTest.exist?(path)
  3953. return eval(load_data(path)) if File.extname(path) == ".rvdata2"
  3954. return eval(File.open(path).read)
  3955. end
  3956. #==============================================================================
  3957. # * Input
  3958. #==============================================================================
  3959. Dax.register(:input, "dax", 1.0) {
  3960. class << Input
  3961. alias :upft :update
  3962. def update
  3963. upft
  3964. Key.update
  3965. end
  3966. end
  3967. }
  3968. #==============================================================================
  3969. # • Graphics
  3970. #==============================================================================
  3971. Dax.register(:graphics, "dax", 1.0) {
  3972. class << Graphics
  3973. attr_reader :fps
  3974. alias :uptf :update
  3975. def update
  3976. @fps ||= 0
  3977. @fps_temp ||= []
  3978. time = Time.now
  3979. uptf
  3980. Mouse.update
  3981. @fps_temp[frame_count % frame_rate] = Time.now != time
  3982. @fps = 0
  3983. frame_rate.times { |i| @fps.next if @fps_temp[i] }
  3984. end
  3985. end
  3986. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement