Advertisement
DaxSoft

Dax Core i7.1

Jun 20th, 2015
1,728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 193.80 KB | None | 0 0
  1. #==============================================================================
  2. # * Dax Core
  3. #==============================================================================
  4. # Autor : Dax Aquatic X
  5. # Coadjuvantes :
  6. # Gab! : Bitmap#save
  7. # Gotoken : Módulo de Benchmark.
  8. # Versão : Core i7.1
  9. # Site : www.dax-soft.weebly.com
  10. # Suporte : dax-soft@live.com
  11. #==============================================================================
  12. # Um Core com vários módulos e métodos que facilitará na hora de programar os
  13. # seus scripts, bom proveito.
  14. #==============================================================================
  15. # Conteúdo : • TAGS : Para facilitar a localização dos códigos e explicações. Para acessar
  16. # o comando para localizar, basta apertar Ctrl+F.
  17. #==============================================================================
  18. # i :
  19. # - Module :module
  20. # - Array :array
  21. # - Api :api
  22. # - String :string
  23. # - Integer :integer
  24. # - Numeric :numeric
  25. # - File :file
  26. # - Dir :dir
  27. # - IO :io
  28. # - Color :color
  29. # - Rect :rect
  30. # - DMath :dmath
  31. # - Move :move
  32. # - Key :key
  33. # - Sprite :sprite
  34. # - Bitmap :bitmap (Método #save por Gab! -> Créditos a ele)
  35. # - Mouse :mouse
  36. # - Sprite_Mouse :sprite_mouse
  37. # - Object :object
  38. # - Entries :entries
  39. # - DRGSS :drgss
  40. # - Backup :backup
  41. # - SceneManager :scenemanager
  42. # - Sprite_Text :sprite_text
  43. # - Sprite_Icon :sprite_icon
  44. # - Opacity :opacity
  45. # - Read :read
  46. # - Background :background
  47. # - Window_Base :window_base
  48. # - Sound_Base :sound_base
  49. # - Position :position
  50. # - Animation :animation
  51. # - Sprite_Anime_Horz :sprite_anime_horz
  52. # - Sprite_Anime_Vert :sprite_anime_vert
  53. # - Crypt :crypt
  54. # - Benchmark :benchmark
  55. # - RTP :rtp
  56. # - SO :so
  57. #==============================================================================
  58. # • Adicionado comentário padrão. Veja o modo que agora os comentários dos
  59. # métodos estão.
  60. #==============================================================================
  61. # • [Classe do Retorno] : Explicação.
  62. # * Exemplo.(Se possível.)
  63. #==============================================================================
  64. module Dax
  65. extend self
  66. #----------------------------------------------------------------------------
  67. # • Constantes
  68. #----------------------------------------------------------------------------
  69. # A imagem do ícone do Mouse tem que estar na pasta [System]. Basta você
  70. # por o nome da imagem dentro das áspas. Caso você queira usar um ícone
  71. # do Rpg Maker no lugar de uma imagem, basta você por o id do ícone no lugar
  72. # das áspas.
  73. Mouse_Name = ""
  74. #----------------------------------------------------------------------------
  75. # • Variáveis
  76. #----------------------------------------------------------------------------
  77. @register = { } # Variável útilizada para registrar os scripts que fora criado.
  78. @benchmark = "" # Armazena os testes conclusos de benchmark.
  79. #----------------------------------------------------------------------------
  80. # • Método de registrar scripts :
  81. #----------------------------------------------------------------------------
  82. # ** Este método tem de ser definido alguns valores como :
  83. # symbol - nome do script, que é posto em símbolo : Ex - :arrow
  84. # name - nome do autor do script, que é posto em áspas
  85. # version - versão do script;
  86. # data - data do script;
  87. # Dax.register(symbol, name, version, data)
  88. # ** Você pode usá-lo para somente registrar o nome do script.
  89. # Dax.register(symbol)
  90. #----------------------------------------------------------------------------
  91. def register(*args)
  92. if @register.has_key?(args[0])
  93. @register[args[0]][:version] = args[1]
  94. @register[args[0]][:data] = args[2]
  95. else
  96. @register[args[0]] = {name: args[1], version: args[2], data: args[3], script: nil}
  97. end
  98. end
  99. #----------------------------------------------------------------------------
  100. # • Somente executará o bloco caso estiver registrado o script. Compatível
  101. # com o $imported. Caso não esteja registrado no Core e esteja registrado
  102. # na variável $imported, dará!
  103. #----------------------------------------------------------------------------
  104. # Exemplo:
  105. # Dax.required_script(:teste) { # Só irá executar caso estiver registrado.
  106. # methods...
  107. # }
  108. #----------------------------------------------------------------------------
  109. def required_script(symbol, &block)
  110. return unless block_given?
  111. block.call if @register.has_key?(symbol) or $imported.has_key?(symbol)
  112. end
  113. #----------------------------------------------------------------------------
  114. # • Método de verificar se o objeto existe.
  115. #----------------------------------------------------------------------------
  116. # Dax.if_defined?("Objeto") { }
  117. # Dentro das chaves você poem o script.
  118. # * Exemplo :
  119. # Dax.required_class("Window_Base") {
  120. # class Window_Base < Window
  121. # def example
  122. # self.x = self.x + self.width
  123. # end
  124. # end
  125. # }
  126. #----------------------------------------------------------------------------
  127. # Executa o bloco se o objeto existir.
  128. #----------------------------------------------------------------------------
  129. def if_defined?(name, &block)
  130. return unless defined?(name)
  131. eval("block.call if defined?(name)")
  132. end
  133. #----------------------------------------------------------------------------
  134. # • Fazer benchmark de um bloco. O resultado será impresso no Console do
  135. # Maker.
  136. #----------------------------------------------------------------------------
  137. # Dax.benchmark(name(opcional)) { BLOCO }
  138. #----------------------------------------------------------------------------
  139. def benchmark(name="", &block)
  140. time = Time.now
  141. block.call
  142. puts "Benchmark: #{name} : #{(time - Time.now).abs.to_f} segundos!"
  143. @benchmark += "#{name} : #{(time - Time.now).to_f} segundos!\r\n"
  144. end
  145. #----------------------------------------------------------------------------
  146. # • Salva os testes de benchmark num arquivo chamado 'Benchmark' de extensão
  147. # .txt.
  148. #----------------------------------------------------------------------------
  149. def benchmark_save
  150. File.open("Benchmark.txt", "a+") do |file|
  151. file.write(@benchmark)
  152. file.close
  153. end
  154. end
  155. #----------------------------------------------------------------------------
  156. # • Requirir um arquivo.
  157. # arquivo : Arquivo...
  158. #----------------------------------------------------------------------------
  159. def require(arquivo)
  160. $: << "./"
  161. Kernel.send(:require, arquivo)
  162. end
  163. #----------------------------------------------------------------------------
  164. # * Remove uma [Classe], exemplo: Dax.remove(:Scene_Menu)
  165. #----------------------------------------------------------------------------
  166. def remove(symbol_name)
  167. Object.send(:remove_const, symbol_name)
  168. end
  169. end
  170. #==============================================================================
  171. # • Module
  172. #==============================================================================
  173. Dax.register :module
  174. class Module
  175. #----------------------------------------------------------------------------
  176. # • [NilClass] : Definir um método constante.
  177. # Exemplo:
  178. # U = Class.new { attrib :x, %w(Z) }
  179. # puts U.x # Z
  180. #----------------------------------------------------------------------------
  181. def attrib(name, default)
  182. module_eval("
  183. def self.#{name}
  184. @#{name} = #{default} unless defined?(@#{name})
  185. return @#{name}
  186. end
  187. ")
  188. return nil
  189. end
  190. end
  191. #==============================================================================
  192. # • Array
  193. #==============================================================================
  194. Dax.register :array
  195. class Array
  196. #----------------------------------------------------------------------------
  197. # • [Hash] : Transforma a Array para uma Hash.
  198. # Define um valor padrão para todas as chaves.
  199. # [1, 2].to_hash_keys { :default_value }
  200. # { 1 => :default_value, 2 => :default_value }
  201. #----------------------------------------------------------------------------
  202. def to_hash_keys(&block)
  203. Hash[*self.collect { |v|
  204. [v, block.call(v)]
  205. }.flatten]
  206. end
  207. #----------------------------------------------------------------------------
  208. # • [Array] : Sorteia os objetos em ordem crescente.
  209. #----------------------------------------------------------------------------
  210. def crescent
  211. sort { |a, b| a <=> b }
  212. end
  213. #----------------------------------------------------------------------------
  214. # • [Array] : Sorteia os objetos em ordem decrescente.
  215. #----------------------------------------------------------------------------
  216. def decrescent
  217. sort { |a, b| b <=> a }
  218. end
  219. #----------------------------------------------------------------------------
  220. # • [Object] : Retorna para o próximo objeto da id da Array.
  221. # x = [1, 8]
  222. # x.next # 1
  223. # x.next # 8
  224. #----------------------------------------------------------------------------
  225. def next(x=0)
  226. @next = (@next.nil? ? 0 : @next == self.size - 1 ? 0 : @next.next + x)
  227. return self[@next]
  228. end
  229. #----------------------------------------------------------------------------
  230. # • [Object] : Retorna para o objeto anterior da id da Array.
  231. # x = [1, 8]
  232. # x.prev # 8
  233. # x.prev # 1
  234. #----------------------------------------------------------------------------
  235. def pred(x = 0)
  236. @prev = (@prev.nil? ? self.size-1 : @prev == 0 ? self.size-1 : @prev.pred + x)
  237. return self[@prev]
  238. end
  239. #----------------------------------------------------------------------------
  240. # • [Integer] Retorna ao número do @next
  241. #----------------------------------------------------------------------------
  242. def _next
  243. return @next || 0
  244. end
  245. #----------------------------------------------------------------------------
  246. # • [Integer] Retorna ao número do @pred
  247. #----------------------------------------------------------------------------
  248. def _pred
  249. return @pred || 0
  250. end
  251. #----------------------------------------------------------------------------
  252. # • [Array] Retorna ao elemento da array que condiz com a condição
  253. # definida no bloco.
  254. # Exemplo:
  255. # [2, 4, 5, 6, 8].if { |element| element >= 4 }
  256. # # 5, 6, 8
  257. #----------------------------------------------------------------------------
  258. def if
  259. return unless block_given?
  260. getResult ||= []
  261. self.each_with_index{ |arrays| getResult << arrays if yield(arrays) }
  262. return getResult
  263. end
  264. #----------------------------------------------------------------------------
  265. # • [Mixed] : Retorna ao primeiro valor da array, que obedeça a
  266. # condição posta.
  267. # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_evan? } #> 2
  268. # msgbox [2, 3, 4, 5, 6].first! { |n| n.is_odd? } #> 3
  269. #----------------------------------------------------------------------------
  270. def first!
  271. return unless block_given?
  272. return self.each { |element| return element if yield(element) }.at(0)
  273. end
  274. #----------------------------------------------------------------------------
  275. # • [Numeric] : Retorna ao valor de todos os conteúdos, desde que seja números,
  276. # somados, ou subtraidos, ou multiplicado. Por padrão é soma.
  277. # v : :+ # Somar
  278. # :- # Subtrair
  279. # :* # Multiplicar.
  280. #----------------------------------------------------------------------------
  281. def alln?(v=:+)
  282. n = v == :* ? 1 : 0
  283. self.if {|i| i.is_a?(Numeric) }.each { |content|
  284. n += content if v == :+
  285. n -= content if v == :-
  286. n *= content if v == :*
  287. }
  288. return n
  289. end
  290. end
  291. #==============================================================================
  292. # • Hash
  293. #==============================================================================
  294. Dax.register :hash
  295. class Hash
  296. #----------------------------------------------------------------------------
  297. # • [NilClass] : Pega o valor da chave específicada.
  298. # {1 => 12}.get(1) #=> 12
  299. #----------------------------------------------------------------------------
  300. def get(key)
  301. self.keys.each { |data|
  302. return self[data] if key == data
  303. }
  304. return nil
  305. end
  306. #----------------------------------------------------------------------------
  307. # • [Mix] : Retorna a última chave adicionada.
  308. #----------------------------------------------------------------------------
  309. def last_key
  310. return self.keys.last
  311. end
  312. end
  313. Dax.register :api
  314. #==============================================================================
  315. # • API : Módulo que armazena informações de algumas APIS.
  316. #==============================================================================
  317. module API
  318. extend self
  319. #----------------------------------------------------------------------------
  320. # • [String] : Tipos e seus retornos.. Pegado da internet.. Autor desconhecido
  321. #----------------------------------------------------------------------------
  322. TYPES = {
  323. struct: "p",
  324. int: "i",
  325. long: "l",
  326. INTERNET_PORT: "l",
  327. SOCKET: "p",
  328. C: "p", #– 8-bit unsigned character (byte)
  329. c: "p", # 8-bit character (byte)
  330. # "i"8 – 8-bit signed integer
  331. # "i"8 – 8-bit unsigned integer
  332. S: "N", # – 16-bit unsigned integer (Win32/API: S used for string params)
  333. s: "n", # – 16-bit signed integer
  334. # "i"16 – 16-bit unsigned integer
  335. # "i"16 – 16-bit signed integer
  336. I: "I", # 32-bit unsigned integer
  337. i: "i", # 32-bit signed integer
  338. # "i"32 – 32-bit unsigned integer
  339. # "i"32 – 32-bit signed integer
  340. L: "L", # unsigned long int – platform-specific size
  341. l: "l", # long int – platform-specific size. For discussion of platforms, see:
  342. # (http://groups.google.com/group/ruby-ffi/browse_thread/thread/4762fc77130339b1)
  343. # "i"64 – 64-bit signed integer
  344. # "i"64 – 64-bit unsigned integer
  345. # "l"_long – 64-bit signed integer
  346. # "l"_long – 64-bit unsigned integer
  347. F: "L", # 32-bit floating point
  348. D: "L", # 64-bit floating point (double-precision)
  349. P: "P", # pointer – platform-specific size
  350. p: "p", # C-style (NULL-terminated) character string (Win32API: S)
  351. B: "i", # (?? 1 byte in C++)
  352. V: "V", # For functions that return nothing (return type void).
  353. v: "v", # For functions that return nothing (return type void).
  354. LPPOINT: "p",
  355. # Windows-specific type defs (ms-help://MS.MSDNQTR.v90.en/winprog/winprog/windows_data_types.htm):
  356. ATOM: "I", # Atom ~= Symbol: Atom table stores strings and corresponding identifiers. Application
  357. # places a string in an atom table and receives a 16-bit integer, called an atom, that
  358. # can be used to access the string. Placed string is called an atom name.
  359. # See: http://msdn.microsoft.com/en-us/library/ms648708%28VS.85%29.aspx
  360. BOOL: "i",
  361. BOOLEAN: "i",
  362. BYTE: "p", # Byte (8 bits). Declared as unsigned char
  363. #CALLBACK: K, # Win32.API gem-specific ?? MSDN: #define CALLBACK __stdcall
  364. CHAR: "p", # 8-bit Windows (ANSI) character. See http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  365. COLORREF: "i", # Red, green, blue (RGB) color value (32 bits). See COLORREF for more info.
  366. DWORD: "i", # 32-bit unsigned integer. The range is 0 through 4,294,967,295 decimal.
  367. DWORDLONG: "i", # 64-bit unsigned integer. The range is 0 through 18,446,744,073,709,551,615 decimal.
  368. DWORD_PTR: "l", # Unsigned long type for pointer precision. Use when casting a pointer to a long type
  369. # to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have
  370. # been extended to 64 bits in 64-bit Windows.) BaseTsd.h: #typedef ULONG_PTR DWORD_PTR;
  371. DWORD32: "I",
  372. DWORD64: "I",
  373. HALF_PTR: "i", # Half the size of a pointer. Use within a structure that contains a pointer and two small fields.
  374. # BaseTsd.h: #ifdef (_WIN64) typedef int HALF_PTR; #else typedef short HALF_PTR;
  375. HACCEL: "i", # (L) Handle to an accelerator table. WinDef.h: #typedef HANDLE HACCEL;
  376. # See http://msdn.microsoft.com/en-us/library/ms645526%28VS.85%29.aspx
  377. HANDLE: "l", # (L) Handle to an object. WinNT.h: #typedef PVOID HANDLE;
  378. # todo: Platform-dependent! Need to change to "i"64 for Win64
  379. HBITMAP: "l", # (L) Handle to a bitmap: http://msdn.microsoft.com/en-us/library/dd183377%28VS.85%29.aspx
  380. HBRUSH: "l", # (L) Handle to a brush. http://msdn.microsoft.com/en-us/library/dd183394%28VS.85%29.aspx
  381. HCOLORSPACE: "l", # (L) Handle to a color space. http://msdn.microsoft.com/en-us/library/ms536546%28VS.85%29.aspx
  382. HCURSOR: "l", # (L) Handle to a cursor. http://msdn.microsoft.com/en-us/library/ms646970%28VS.85%29.aspx
  383. HCONV: "l", # (L) Handle to a dynamic data exchange (DDE) conversation.
  384. HCONVLIST: "l", # (L) Handle to a DDE conversation list. HANDLE - L ?
  385. HDDEDATA: "l", # (L) Handle to DDE data (structure?)
  386. HDC: "l", # (L) Handle to a device context (DC). http://msdn.microsoft.com/en-us/library/dd183560%28VS.85%29.aspx
  387. HDESK: "l", # (L) Handle to a desktop. http://msdn.microsoft.com/en-us/library/ms682573%28VS.85%29.aspx
  388. HDROP: "l", # (L) Handle to an internal drop structure.
  389. HDWP: "l", # (L) Handle to a deferred window position structure.
  390. HENHMETAFILE: "l", #(L) Handle to an enhanced metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  391. HFILE: "i", # (I) Special file handle to a file opened by OpenFile, not CreateFile.
  392. # WinDef.h: #typedef int HFILE;
  393. REGSAM: "i",
  394. HFONT: "l", # (L) Handle to a font. http://msdn.microsoft.com/en-us/library/dd162470%28VS.85%29.aspx
  395. HGDIOBJ: "l", # (L) Handle to a GDI object.
  396. HGLOBAL: "l", # (L) Handle to a global memory block.
  397. HHOOK: "l", # (L) Handle to a hook. http://msdn.microsoft.com/en-us/library/ms632589%28VS.85%29.aspx
  398. HICON: "l", # (L) Handle to an icon. http://msdn.microsoft.com/en-us/library/ms646973%28VS.85%29.aspx
  399. HINSTANCE: "l", # (L) Handle to an instance. This is the base address of the module in memory.
  400. # HMODULE and HINSTANCE are the same today, but were different in 16-bit Windows.
  401. HKEY: "l", # (L) Handle to a registry key.
  402. HKL: "l", # (L) Input locale identifier.
  403. HLOCAL: "l", # (L) Handle to a local memory block.
  404. HMENU: "l", # (L) Handle to a menu. http://msdn.microsoft.com/en-us/library/ms646977%28VS.85%29.aspx
  405. HMETAFILE: "l", # (L) Handle to a metafile. http://msdn.microsoft.com/en-us/library/dd145051%28VS.85%29.aspx
  406. HMODULE: "l", # (L) Handle to an instance. Same as HINSTANCE today, but was different in 16-bit Windows.
  407. HMONITOR: "l", # (L) ?andle to a display monitor. WinDef.h: if(WINVER >= 0x0500) typedef HANDLE HMONITOR;
  408. HPALETTE: "l", # (L) Handle to a palette.
  409. HPEN: "l", # (L) Handle to a pen. http://msdn.microsoft.com/en-us/library/dd162786%28VS.85%29.aspx
  410. HRESULT: "l", # Return code used by COM interfaces. For more info, Structure of the COM Error Codes.
  411. # To test an HRESULT value, use the FAILED and SUCCEEDED macros.
  412. HRGN: "l", # (L) Handle to a region. http://msdn.microsoft.com/en-us/library/dd162913%28VS.85%29.aspx
  413. HRSRC: "l", # (L) Handle to a resource.
  414. HSZ: "l", # (L) Handle to a DDE string.
  415. HWINSTA: "l", # (L) Handle to a window station. http://msdn.microsoft.com/en-us/library/ms687096%28VS.85%29.aspx
  416. HWND: "l", # (L) Handle to a window. http://msdn.microsoft.com/en-us/library/ms632595%28VS.85%29.aspx
  417. INT: "i", # 32-bit signed integer. The range is -2147483648 through 2147483647 decimal.
  418. INT_PTR: "i", # Signed integer type for pointer precision. Use when casting a pointer to an integer
  419. # to perform pointer arithmetic. BaseTsd.h:
  420. #if defined(_WIN64) typedef __int64 INT_PTR; #else typedef int INT_PTR;
  421. INT32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  422. INT64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  423. LANGID: "n", # Language identifier. For more information, see Locales. WinNT.h: #typedef WORD LANGID;
  424. # See http://msdn.microsoft.com/en-us/library/dd318716%28VS.85%29.aspx
  425. LCID: "i", # Locale identifier. For more information, see Locales.
  426. LCTYPE: "i", # Locale information type. For a list, see Locale Information Constants.
  427. LGRPID: "i", # Language group identifier. For a list, see EnumLanguageGroupLocales.
  428. LONG: "l", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  429. LONG32: "i", # 32-bit signed integer. The range is -2,147,483,648 through +...647 decimal.
  430. LONG64: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  431. LONGLONG: "i", # 64-bit signed integer. The range is –9,223,372,036,854,775,808 through +...807
  432. LONG_PTR: "l", # Signed long type for pointer precision. Use when casting a pointer to a long to
  433. # perform pointer arithmetic. BaseTsd.h:
  434. #if defined(_WIN64) typedef __int64 LONG_PTR; #else typedef long LONG_PTR;
  435. LPARAM: "l", # Message parameter. WinDef.h as follows: #typedef LONG_PTR LPARAM;
  436. LPBOOL: "i", # Pointer to a BOOL. WinDef.h as follows: #typedef BOOL far *LPBOOL;
  437. LPBYTE: "i", # Pointer to a BYTE. WinDef.h as follows: #typedef BYTE far *LPBYTE;
  438. LPCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  439. # See Character Sets Used By Fonts. http://msdn.microsoft.com/en-us/library/dd183415%28VS.85%29.aspx
  440. LPCTSTR: "p", # An LPCWSTR if UNICODE is defined, an LPCSTR otherwise.
  441. LPCVOID: "v", # Pointer to a constant of any type. WinDef.h as follows: typedef CONST void *LPCVOID;
  442. LPCWSTR: "P", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  443. LPDWORD: "p", # Pointer to a DWORD. WinDef.h as follows: typedef DWORD *LPDWORD;
  444. LPHANDLE: "l", # Pointer to a HANDLE. WinDef.h as follows: typedef HANDLE *LPHANDLE;
  445. LPINT: "I", # Pointer to an INT.
  446. LPLONG: "L", # Pointer to an LONG.
  447. LPSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters.
  448. LPTSTR: "p", # An LPWSTR if UNICODE is defined, an LPSTR otherwise.
  449. LPVOID: "v", # Pointer to any type.
  450. LPWORD: "p", # Pointer to a WORD.
  451. LPWSTR: "p", # Pointer to a null-terminated string of 16-bit Unicode characters.
  452. LRESULT: "l", # Signed result of message processing. WinDef.h: typedef LONG_PTR LRESULT;
  453. PBOOL: "i", # Pointer to a BOOL.
  454. PBOOLEAN: "i", # Pointer to a BOOL.
  455. PBYTE: "i", # Pointer to a BYTE.
  456. PCHAR: "p", # Pointer to a CHAR.
  457. PCSTR: "p", # Pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
  458. PCTSTR: "p", # A PCWSTR if UNICODE is defined, a PCSTR otherwise.
  459. PCWSTR: "p", # Pointer to a constant null-terminated string of 16-bit Unicode characters.
  460. PDWORD: "p", # Pointer to a DWORD.
  461. PDWORDLONG: "L", # Pointer to a DWORDLONG.
  462. PDWORD_PTR: "L", # Pointer to a DWORD_PTR.
  463. PDWORD32: "L", # Pointer to a DWORD32.
  464. PDWORD64: "L", # Pointer to a DWORD64.
  465. PFLOAT: "L", # Pointer to a FLOAT.
  466. PHALF_PTR: "L", # Pointer to a HALF_PTR.
  467. PHANDLE: "L", # Pointer to a HANDLE.
  468. PHKEY: "L", # Pointer to an HKEY.
  469. PINT: "i", # Pointer to an INT.
  470. PINT_PTR: "i", # Pointer to an INT_PTR.
  471. PINT32: "i", # Pointer to an INT32.
  472. PINT64: "i", # Pointer to an INT64.
  473. PLCID: "l", # Pointer to an LCID.
  474. PLONG: "l", # Pointer to a LONG.
  475. PLONGLONG: "l", # Pointer to a LONGLONG.
  476. PLONG_PTR: "l", # Pointer to a LONG_PTR.
  477. PLONG32: "l", # Pointer to a LONG32.
  478. PLONG64: "l", # Pointer to a LONG64.
  479. 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.
  480. 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.
  481. POINTER_SIGNED: "l", # A signed pointer.
  482. HPSS: "l",
  483. POINTER_UNSIGNED: "l", # An unsigned pointer.
  484. PSHORT: "l", # Pointer to a SHORT.
  485. PSIZE_T: "l", # Pointer to a SIZE_T.
  486. PSSIZE_T: "l", # Pointer to a SSIZE_T.
  487. PSS_CAPTURE_FLAGS: "l",
  488. PSTR: "p", # Pointer to a null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
  489. PTBYTE: "p", # Pointer to a TBYTE.
  490. PTCHAR: "p", # Pointer to a TCHAR.
  491. PTSTR: "p", # A PWSTR if UNICODE is defined, a PSTR otherwise.
  492. PUCHAR: "p", # Pointer to a UCHAR.
  493. PUINT: "i", # Pointer to a UINT.
  494. PUINT_PTR: "i", # Pointer to a UINT_PTR.
  495. PUINT32: "i", # Pointer to a UINT32.
  496. PUINT64: "i", # Pointer to a UINT64.
  497. PULONG: "l", # Pointer to a ULONG.
  498. PULONGLONG: "l", # Pointer to a ULONGLONG.
  499. PULONG_PTR: "l", # Pointer to a ULONG_PTR.
  500. PULONG32: "l", # Pointer to a ULONG32.
  501. PULONG64: "l", # Pointer to a ULONG64.
  502. PUSHORT: "l", # Pointer to a USHORT.
  503. PVOID: "v", # Pointer to any type.
  504. PWCHAR: "p", # Pointer to a WCHAR.
  505. PWORD: "p", # Pointer to a WORD.
  506. PWSTR: "p", # Pointer to a null- terminated string of 16-bit Unicode characters.
  507. # For more information, see Character Sets Used By Fonts.
  508. SC_HANDLE: "l", # (L) Handle to a service control manager database.
  509. SERVICE_STATUS_HANDLE: "l", # (L) Handle to a service status value. See SCM Handles.
  510. SHORT: "i", # A 16-bit integer. The range is –32768 through 32767 decimal.
  511. 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.
  512. SSIZE_T: "l", # Signed SIZE_T.
  513. TBYTE: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  514. # http://msdn.microsoft.com/en-us/library/c426s321%28VS.80%29.aspx
  515. TCHAR: "p", # A WCHAR if UNICODE is defined, a CHAR otherwise.TCHAR:
  516. UCHAR: "p", # Unsigned CHAR (8 bit)
  517. UHALF_PTR: "i", # Unsigned HALF_PTR. Use within a structure that contains a pointer and two small fields.
  518. UINT: "i", # Unsigned INT. The range is 0 through 4294967295 decimal.
  519. UINT_PTR: "i", # Unsigned INT_PTR.
  520. UINT32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  521. UINT64: "i", # Unsigned INT64. The range is 0 through 18446744073709551615 decimal.
  522. ULONG: "l", # Unsigned LONG. The range is 0 through 4294967295 decimal.
  523. ULONGLONG: "l", # 64-bit unsigned integer. The range is 0 through 18446744073709551615 decimal.
  524. ULONG_PTR: "l", # Unsigned LONG_PTR.
  525. ULONG32: "i", # Unsigned INT32. The range is 0 through 4294967295 decimal.
  526. ULONG64: "i", # Unsigned LONG64. The range is 0 through 18446744073709551615 decimal.
  527. UNICODE_STRING: "P", # Pointer to some string structure??
  528. USHORT: "i", # Unsigned SHORT. The range is 0 through 65535 decimal.
  529. USN: "l", # Update sequence number (USN).
  530. WCHAR: "i", # 16-bit Unicode character. For more information, see Character Sets Used By Fonts.
  531. # In WinNT.h: typedef wchar_t WCHAR;
  532. #WINAPI: K, # Calling convention for system functions. WinDef.h: define WINAPI __stdcall
  533. WORD: "i", # 16-bit unsigned integer. The range is 0 through 65535 decimal.
  534. WPARAM: "i", # Message parameter. WinDef.h as follows: typedef UINT_PTR WPARAM;
  535. VOID: "v", # Any type ? Only use it to indicate no arguments or no return value
  536. vKey: "i",
  537. LPRECT: "p",
  538. char: "p",
  539. }
  540. #----------------------------------------------------------------------------
  541. # • [Array] : Pega os valores especificados no método.. depois verifica
  542. # cada um se é String ou Symbol. Se for Symbol retorna ao valor especificado
  543. # na Constante TYPES.
  544. # Exemplo: types([:BOOL, :WCHAR]) # ["i", "i"]
  545. #----------------------------------------------------------------------------
  546. def types(import)
  547. import2 = []
  548. import.each { |i|
  549. next if i.is_a?(NilClass) or i.is_a?(String)
  550. import2 << TYPES[i]
  551. }
  552. return import2
  553. end
  554. #----------------------------------------------------------------------------
  555. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  556. # Por padrão a DLL é a "user32". O valor de exportação será "i"
  557. #----------------------------------------------------------------------------
  558. def int(function, import, dll="user32")
  559. Win32API.new(dll, function, types(import), "i") rescue nil
  560. end
  561. #----------------------------------------------------------------------------
  562. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  563. # Por padrão a DLL é a "user32". O valor de exportação será "l"
  564. #----------------------------------------------------------------------------
  565. def long(function, import, dll="user32")
  566. Win32API.new(dll, function.to_s, types(import), "l") rescue nil
  567. end
  568. #----------------------------------------------------------------------------
  569. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  570. # Por padrão a DLL é a "user32". O valor de exportação será "v"
  571. #----------------------------------------------------------------------------
  572. def void(function, import, dll="user32")
  573. Win32API.new(dll, function.to_s, types(import), "v") rescue nil
  574. end
  575. #----------------------------------------------------------------------------
  576. # • [Dll]// : Especifica uma função, com o valor da importação é a DLL..
  577. # Por padrão a DLL é a "user32". O valor de exportação será "p"
  578. #----------------------------------------------------------------------------
  579. def char(function, import, dll="user32")
  580. Win32API.new(dll, function.to_s, types(import), "p") rescue nil
  581. end
  582. #----------------------------------------------------------------------------
  583. # • [Dll]// : Com esse método você pode especificar uma função de uma Dll.
  584. # function(export, function, import, dll)
  585. # export : Valor da exportação. Formato [Symbol]
  586. # function : Função da Dll.
  587. # import : Valor da importação.
  588. # dll : Dll. Por padrão é a User32
  589. # Esconder o Mouse.
  590. # Exemplo: function(:int, "ShowCursor", [:BOOL]).call(0)
  591. #----------------------------------------------------------------------------
  592. def function(export, function, import, dll="user32")
  593. eval("#{export}(function, import, dll)")
  594. end
  595. #----------------------------------------------------------------------------
  596. # • Especificando o método protegido.
  597. #----------------------------------------------------------------------------
  598. # Métodos privados.
  599. private :long, :int, :char, :void, :types
  600. #----------------------------------------------------------------------------
  601. # • [CopyFile]/Dll : Função da DLL Kernel32 que permite copiar arquivos.
  602. # CopyFile.call(filename_to_copy, filename_copied, replace)
  603. # filename_to_copy : Formato [String]
  604. # filename_copied : Formato [String]
  605. # replace : Formato [Integer] 0 - false 1 - true
  606. # Exemplo: CopyFile.call("System/RGSS300.dll", "./RGSS300.dll", 1)
  607. #----------------------------------------------------------------------------
  608. CopyFile = long("CopyFile", [:LPCTSTR, :LPCTSTR, :BOOL], "kernel32")
  609. #----------------------------------------------------------------------------
  610. # • [Beep]/Dll : Emitir uma frequência de um som do sistema com duração.
  611. # Beep.call(freq, duration)
  612. # freq : Formato [Integer\Hexadécimal]
  613. # duration : Formato [Integer\Hexadécimal]
  614. # Exemplo: Beep.call(2145, 51)
  615. #----------------------------------------------------------------------------
  616. Beep = long('Beep', [:DWORD, :DWORD], 'kernel32')
  617. #----------------------------------------------------------------------------
  618. # • [keybd_event]/Dll : Ela é usada para sintentizar uma combinação de teclas.
  619. # KEYBD_EVENT.call(vk, scan, fdwFlags, dwExtraInfo)
  620. # vk : Formato [Integer/Hexadécimal].
  621. # scan : Formato [Integer]
  622. # fdwFlags : Formato [Integer]
  623. # dwExtraInfo : Formato [Integer]
  624. # Exemplo: KEYBD_EVENT.call(0x01, 0, 0, 0)
  625. #----------------------------------------------------------------------------
  626. KEYBD_EVENT = void('keybd_event', [:BYTE, :BYTE, :DWORD, :ULONG_PTR])
  627. #----------------------------------------------------------------------------
  628. # • Função de limpar memória.
  629. # Permite definir por um comando eval algo que aconteça antes.
  630. # Permite definir com um bloco, algo que aconteça no processo.
  631. #----------------------------------------------------------------------------
  632. def clearMemory(deval="", &block)
  633. eval(deval) unless deval.empty? and !deval.is_a?(String)
  634. KEYBD_EVENT.call(0x7B, 0, 0, 0)
  635. block.call if block_given?
  636. sleep(0.1)
  637. KEYBD_EVENT.call(0x7B, 0, 2, 0)
  638. end
  639. #----------------------------------------------------------------------------
  640. # • Tela chéia
  641. #----------------------------------------------------------------------------
  642. def full_screen
  643. KEYBD_EVENT.(18, 0, 0, 0)
  644. KEYBD_EVENT.(18, 0, 0, 0)
  645. KEYBD_EVENT.(13, 0, 0, 0)
  646. KEYBD_EVENT.(13, 0, 2, 0)
  647. KEYBD_EVENT.(18, 0, 2, 0)
  648. end
  649. #----------------------------------------------------------------------------
  650. # • [GetKeyState]/Dll : Pega o status da chave.
  651. # GetKeyState.call(vk)
  652. # vk : Formato [Integer/Hexadécimal].
  653. # Exemplo: GetKeyState.call(0x01)
  654. #----------------------------------------------------------------------------
  655. GetKeyState = int('GetAsyncKeyState', [:int])
  656. #----------------------------------------------------------------------------
  657. # • [MapVirtualKey] : Traduz (maps) o código de uma key para um código
  658. # escaneado ou o valor de um character.
  659. #----------------------------------------------------------------------------
  660. MapVirtualKey = int("MapVirtualKey", [:UINT, :UINT])
  661. #----------------------------------------------------------------------------
  662. # • [MouseShowCursor]/Dll : Mostrar ou desativar o cusor do Mouse.
  663. # MouseShowCursor.call(value)
  664. # value : Formato [Integer] 0 - false 1 - true
  665. # Exemplo: MouseShowCursor.call(0)
  666. #----------------------------------------------------------------------------
  667. MouseShowCursor = int("ShowCursor", [:int])
  668. #----------------------------------------------------------------------------
  669. # • [CursorPosition]/Dll : Obtem a posição do cursor do Mouse na tela.
  670. # CursorPosition.call(lpPoint)
  671. # lpPoint : Formato [Array]
  672. # Ex: CursorPosition.call([0, 0].pack('ll'))
  673. #----------------------------------------------------------------------------
  674. CursorPosition = int('GetCursorPos', [:LPPOINT])
  675. #----------------------------------------------------------------------------
  676. # • [ScreenToClient]/Dll : Converte as coordenadas da tela para um ponto
  677. # em especifico da área da tela do cliente.
  678. # ScreenToClient.call(hWnd, lpPoint)
  679. #----------------------------------------------------------------------------
  680. ScreenToClient = int('ScreenToClient', [:HWND, :LPPOINT])
  681. #----------------------------------------------------------------------------
  682. # • [GetPrivateProfileString]/Dll : */Ainda não explicado./*
  683. #----------------------------------------------------------------------------
  684. GetPrivateProfileString = long('GetPrivateProfileStringA', [:LPCTSTR, :LPCTSTR, :LPCTSTR, :LPTSTR, :DWORD, :LPCTSTR], 'kernel32')
  685. #----------------------------------------------------------------------------
  686. # • [FindWindow]/Dll : Recupera o identificador da janela superior. Cujo
  687. # o nome da janela é o nome da classe da janela se combina com as cadeias
  688. # especificas.
  689. # FindWindow.call(lpClassName, lpWindowName)
  690. # lpClassName : Formato [String]
  691. # lpWindowName : Formato [String]
  692. #----------------------------------------------------------------------------
  693. FindWindow = long('FindWindowA', [:LPCTSTR, :LPCTSTR])
  694. #----------------------------------------------------------------------------
  695. # • [Handle]/Dll : Retorna ao Handle da janela.
  696. #----------------------------------------------------------------------------
  697. def hWND(game_title=nil)
  698. return API::FindWindow.call('RGSS Player', game_title || load_data("./Data/System.rvdata2").game_title.to_s)
  699. end
  700. #----------------------------------------------------------------------------
  701. # • [Handle]/Dll : Retorna ao Handle da janela. Método protegido.
  702. #----------------------------------------------------------------------------
  703. def hwnd(*args)
  704. hWND(*args)
  705. end
  706. #----------------------------------------------------------------------------
  707. # • [ReadIni]/Dll : */Ainda não explicado./*
  708. #----------------------------------------------------------------------------
  709. ReadIni = GetPrivateProfileString
  710. #----------------------------------------------------------------------------
  711. # • [SetWindowPos]/Dll : Modifica os elementos da janela como, posição, tamanho.
  712. #----------------------------------------------------------------------------
  713. SetWindowPos = int("SetWindowPos", [:HWND, :HWND, :int, :int, :int, :int, :UINT])
  714. #----------------------------------------------------------------------------
  715. # • [GetWindowRect]/Dll : Obtem as dimensões do retângulo da janela.
  716. # GetWindowRect.call(hWnd, lpRect)
  717. #----------------------------------------------------------------------------
  718. GetWindowRect = int('GetWindowRect', [:HWND, :LPRECT])
  719. #----------------------------------------------------------------------------
  720. # • [StateKey]/Dll : Retorna ao status específico da chave.
  721. # StateKey.call(VK)
  722. # VK : Formato [Integer/Hexadécimal].
  723. #----------------------------------------------------------------------------
  724. StateKey = int("GetKeyState", [:int])
  725. #----------------------------------------------------------------------------
  726. # • [SetCursorPos]/Dll : Move o cursor do Mouse para um ponto específico
  727. # da tela.
  728. # SetCursorPos.call(x, y)
  729. # x, y : Formato [Integer/Float]
  730. #----------------------------------------------------------------------------
  731. SetCursorPos = int("SetCursorPos", [:long, :long])
  732. #----------------------------------------------------------------------------
  733. # • [GetKeyboardState]/Dll : Cópia o status das 256 chaves para um
  734. # buffer especificado.
  735. #----------------------------------------------------------------------------
  736. GetKeyboardState = Win32API.new('user32', 'GetKeyboardState', ['P'], 'V')
  737. #----------------------------------------------------------------------------
  738. # • [GetAsyncKeyState]/Dll : Determina o estado da chave no momento em que a
  739. # função é chamada.
  740. # GetAsyncKeyState.call(Vk)
  741. # VK : Formato [Integer/Hexadécimal].
  742. #----------------------------------------------------------------------------
  743. GetAsyncKeyState = int('GetAsyncKeyState', [:int])
  744. #----------------------------------------------------------------------------
  745. # • [WideCharToMultiByte] : [MultiByteToWideChar] // Comentários
  746. # não adicionados.
  747. #----------------------------------------------------------------------------
  748. WideCharToMultiByte = Win32API.new('kernel32', 'WideCharToMultiByte', 'ilpipipp', 'i')
  749. MultiByteToWideChar = Win32API.new('kernel32', 'MultiByteToWideChar', 'ilpipi', 'i')
  750. #----------------------------------------------------------------------------
  751. # • [AdjustWindowRect] : Calcula o tamanho requerido do retângulo da Janela.
  752. #----------------------------------------------------------------------------
  753. AdjustWindowRect = int("AdjustWindowRect", [:LPRECT, :DWORD, :BOOL])
  754. #----------------------------------------------------------------------------
  755. # • Constantes [SetWindowPos]
  756. #----------------------------------------------------------------------------
  757. SWP_ASYNCWINDOWPOS = 0x4000
  758. # Desenha os frames (definidos na classe da janela descrita) em torno na janela.
  759. SWP_DRAWFRAME = 0x0020
  760. # Esconde a janela.
  761. SWP_HIDEWINDOW = 0x0080
  762. # Não pode ser ativada nem movida
  763. SWP_NOACTIVATE = 0x0010
  764. # Não permite mover
  765. SWP_NOMOVE = 0x0002
  766. # Não permite redimensionar
  767. SWP_NOSIZE = 0x0001
  768. # Mostra a Janela
  769. SWP_SHOWWINDOW = 0x0040
  770. # Coloca a janela na parte inferior na ordem de Z. Se identificar uma janela
  771. # superior ela perde os seus status.
  772. HWND_BOTTOM = 1
  773. # Coloca a janela acima de todas as janelas que não estão em primeiro plano.
  774. HWND_NOTOPMOST = -2
  775. # Poem a janela no Topo na ordem de Z.
  776. HWND_TOP = 0
  777. # Poem a janela acima de todas que não estão em primeiro plano. Mantendo a
  778. # posição.
  779. HWND_TOPMOST = -1
  780. #----------------------------------------------------------------------------
  781. # • [SetActiveWindow]/ Dll : Ativa a Window.
  782. #----------------------------------------------------------------------------
  783. SetActiveWindow = long("SetActiveWindow", [:HWND])
  784. #----------------------------------------------------------------------------
  785. # • WindowFromPoint : Retorna ao handle da janela, que contém um ponto
  786. # específico.
  787. #----------------------------------------------------------------------------
  788. WindowFromPoint = long("WindowFromPoint", [:HWND])
  789. #----------------------------------------------------------------------------
  790. # • ShowWindow : Mostra a janela em um estado específico.
  791. #----------------------------------------------------------------------------
  792. ShowWindow = long("ShowWindow", [:HWND, :LONG])
  793. # Força a janela a minimizar
  794. SW_FORCEMINIMIZE = 11
  795. # Esconde a janela, ativa outra.
  796. SW_HIDE = 0
  797. # Maximiza a janela.
  798. SW_MAXIMIZE = 3
  799. # Minimiza a janela
  800. SW_MINIMIZE = 6
  801. # Restaura o estado da janela.
  802. SW_RESTORE = 9
  803. # Ativa a janela a mostrando na posição original.
  804. SW_SHOW = 5
  805. #----------------------------------------------------------------------------
  806. # • [SetWindowText] : Permite modificar o título da janela.
  807. #----------------------------------------------------------------------------
  808. SetWindowText = int("SetWindowText", [:HWND, :LPCTSTR])
  809. #----------------------------------------------------------------------------
  810. # • [GetDesktopWindow] : Retorna ao handle da janela em relação ao Desktop.
  811. #----------------------------------------------------------------------------
  812. GetDesktopWindow = long("GetDesktopWindow", [:HWND])
  813. #----------------------------------------------------------------------------
  814. # • [GetSystemMetric] : Obtem um sistema métrico específico ou a configuração
  815. # do sistema. As dimensões retornadas são em pixel.
  816. #----------------------------------------------------------------------------
  817. GetSystemMetric = int("GetSystemMetric", [:int])
  818. #----------------------------------------------------------------------------
  819. # • [GetSystemMetric]/Constantes:
  820. #----------------------------------------------------------------------------
  821. # Obtem a flag que especifica como o sistema está organizando as janelas
  822. # minimizadas.
  823. SM_ARRANGE = 56
  824. # Obtem o tamanho da borda da Janela em pixel.
  825. SM_CXBORDER = 5
  826. # Valor do tamanho da área do cliente pra uma Janela em modo de tela-chéia.
  827. # em pixel.
  828. SM_CXFULLSCREEN = 16
  829. # Para mais informações dos valores, visite :
  830. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  831. #----------------------------------------------------------------------------
  832. # • [GetClientRect] : Retorna ao rect da área da Janela.
  833. # Uses :
  834. # lpRect = [0,0,0,0].pack("L*")
  835. # GetClientRect.(hwnd, lpRect)
  836. # lpRect = lpRect.unpack("L*")
  837. #----------------------------------------------------------------------------
  838. GetClientRect = int("GetClientRect", [:HWND, :LPRECT])
  839. #----------------------------------------------------------------------------
  840. # • [GetModuleHandle] : Retorna ao Handle do módulo, do módulo específicado.
  841. # Pode ser aquivo '.dll' ou '.exe'. Exemplo:
  842. # GetModuleHandle.call('System/RGSS300.dll')
  843. #----------------------------------------------------------------------------
  844. GetModuleHandle = long("GetModuleHandle", [:LPCTSTR], "kerne32")
  845. #----------------------------------------------------------------------------
  846. # • [FreeLibrary] : Libera o módulo que está carregado na DLL específica.
  847. #----------------------------------------------------------------------------
  848. FreeLibrary = long("FreeLibrary", [:HMODULE], "kernel32")
  849. #----------------------------------------------------------------------------
  850. # • [LoadLibrary] : Carrega um endereço de um módulo em específico.
  851. # LoadLibrary.call(Nome da Libraria(dll/exe))
  852. # [Handle] : Retorna ao valor do Handle do módulo caso der certo.
  853. #----------------------------------------------------------------------------
  854. LoadLibrary = long("LoadLibrary", [:LPCTSTR], "kernel32")
  855. #----------------------------------------------------------------------------
  856. # • [GetProcAddress] : Retorna ao endereço da função exportada ou a variável
  857. # de uma DLL específica.
  858. # GetProcAddress.call(hModule, lpProcName)
  859. # hModule : É o valor do handle. Você pode pega-lo usando o LoadLibrary
  860. # lpProcName : A função ou o nome da variável.
  861. #----------------------------------------------------------------------------
  862. GetProcAddress = long("GetProcAddress", [:HMODULE, :LPCSTR], "kernel32")
  863. #----------------------------------------------------------------------------
  864. # • [GetSystemMetrics] : Retorna á uma configuração específica do sistema
  865. # métrico.
  866. #----------------------------------------------------------------------------
  867. GetSystemMetrics = int("GetSystemMetrics", [:int])
  868. #----------------------------------------------------------------------------
  869. # • [GetSystemMetrics]::Constantes. #Para mais visite:
  870. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
  871. #----------------------------------------------------------------------------
  872. SM_CXSCREEN = 0 # O tamanho(width/largura) da janela em pixel.
  873. SM_CYSCREEN = 1 # O tamanho(height/comprimento) da janela em pixel.
  874. SM_CXFULLSCREEN = 16 # O tamanho da largura da tela chéia da janela.
  875. SM_CYFULLSCREEN = 17 # O tamanho do comprimento da tela chéia da janela.
  876. #----------------------------------------------------------------------------
  877. # • [SetPriorityClass] : Definir a classe prioritária para um processo
  878. # específico.
  879. # Para ver os processo e tal : Link abaixo.
  880. # http://msdn.microsoft.com/en-us/library/windows/desktop/ms686219(v=vs.85).aspx
  881. #----------------------------------------------------------------------------
  882. SetPriorityClass = int("SetPriorityClass", [:HANDLE, :DWORD], "kernel32")
  883. #----------------------------------------------------------------------------
  884. # • [InternetOpenA] : Inicializa o uso de uma aplicação, de uma função da
  885. # WinINet.
  886. #----------------------------------------------------------------------------
  887. InternetOpenA = function(:int, "InternetOpenA", [:LPCTSTR, :DWORD, :LPCTSTR, :LPCTSTR, :DWORD], "wininet")
  888. #----------------------------------------------------------------------------
  889. # • [RtlMoveMemory] : Movimenta um bloco de memoria para outra locação.
  890. #----------------------------------------------------------------------------
  891. RtlMoveMemory = function(:int, "RtlMoveMemory", [:char, :char, :int], "kernel32")
  892. #----------------------------------------------------------------------------
  893. # • [Método protegido] : Método usado para chamar a função LoadLibrary.
  894. #----------------------------------------------------------------------------
  895. def dlopen(name, fA=nil)
  896. l = LoadLibrary.(String(name))
  897. return l if fA.nil?
  898. return GetProcAddress.(l, String(fA))
  899. end
  900. #----------------------------------------------------------------------------
  901. # • Converte um texto para o formato UTF-8
  902. # textUTF(text)
  903. # * text : Texto.
  904. #----------------------------------------------------------------------------
  905. def textUTF(text)
  906. wC = MultiByteToWideChar.call(65001, 0, text, -1, "", 0)
  907. MultiByteToWideChar.call(65001, 0, text, -1, text = "\0\0" * wC, wC)
  908. return text
  909. end
  910. #----------------------------------------------------------------------------
  911. # • [TrueClass/FalseClass] : Retorna verdadeiro caso o Caps Lock esteja
  912. # ativo e retorna Falso caso não esteja ativo.
  913. #----------------------------------------------------------------------------
  914. def get_caps_lock
  915. return int("GetKeyState", [:vKey]).call(20) == 1
  916. end
  917. #----------------------------------------------------------------------------
  918. # • Abre a URL de um site o direcionado para o navegador padrão do usuário.
  919. #----------------------------------------------------------------------------
  920. def open_site(url)
  921. c = Win32API.new("Shell32", "ShellExecute", "pppppl", "l")
  922. c.call(nil, "open", url, nil, nil, 0)
  923. end
  924. #----------------------------------------------------------------------------
  925. # • Valor dá base é o endereço. Pegar a variável.
  926. # base = 0x10000000
  927. # adr_loc_ram(0x25EB00 + 0x214, val, base)
  928. #----------------------------------------------------------------------------
  929. def adr_loc_ram(adr, val, base)
  930. return DL::CPtr.new(base + adr)[0, val.size] = size
  931. end
  932. #============================================================================
  933. # • MessageBox
  934. #============================================================================
  935. module MessageBox
  936. extend self
  937. # handle, string, title, format.
  938. FunctionMessageBox = Win32API.new("user32", "MessageBoxW", "lppl", "l")
  939. #--------------------------------------------------------------------------
  940. # • [Constantes] Botões:
  941. #--------------------------------------------------------------------------
  942. # Adiciona três botões a mensagem: Anular, Repetir e Ignorar.
  943. ABORTRETRYIGNORE = 0x00000002
  944. # Adiciona três botões a mensagem: Cancelar, Tentar e Continuar.
  945. CANCELTRYCONTINUE = 0x00000006
  946. # Adiciona o botão de ajuda.
  947. HELP = 0x00004000
  948. # Adiciona o botão Ok.
  949. SOK = 0x00000000
  950. # Adiciona o botão OK e Cancelar.
  951. OKCANCEL = 0x00000001
  952. # Adiciona os botões: Repetir e Cancelar.
  953. RETRYCANCEL = 0x00000005
  954. # Adiciona os botões: Sim e Não
  955. YESNO = 0x00000004
  956. # Adiciona os botões: Sim, Não e Cancelar
  957. YESNOCANCEL = 0x00000003
  958. #--------------------------------------------------------------------------
  959. # • [Constantes] Ícones:
  960. #--------------------------------------------------------------------------
  961. # Adiciona um ícone de exclamação
  962. ICONEXCLAMATION = 0x00000030
  963. # Adiciona um ícone de informação.
  964. ICONINFORMATION = 0x00000040
  965. # Adiciona um ícone de um círculo com um ponto de interrogação.
  966. ICONQUESTION = 0x00000020
  967. # Adiciona um íconde parar na mensagem.
  968. ICONSTOP = 0x00000010
  969. #--------------------------------------------------------------------------
  970. # • [Constantes] Valores de retorno dos botões:
  971. #--------------------------------------------------------------------------
  972. ABORT = 3 # Retorno do valor do botão de Anular
  973. CANCEL = 2 # Retorno do valor do botão de Cancelar.
  974. CONTINUE = 11 # Retorno do valor do botão de Continuar.
  975. IGNORE = 5 # Retorno do valor de ignonar.
  976. NO = 7 # Retorno do valor do botão de Não.
  977. OK = 1 # Retorno do valor do botão de Ok.
  978. RETRY = 4 # Retorno do valor de repetir.
  979. TRYAGAIN = 10 # Retorno do valor de Repetir.
  980. YES = 6 # Retorno do valor do botão de Sim.
  981. #--------------------------------------------------------------------------
  982. # • [Constantes] Valores adicionais.
  983. #--------------------------------------------------------------------------
  984. RIGHT = 0x00080000 # Os textos ficarão justificados a direita.
  985. TOPMOST = 0x00040000 # O estilo da mensagem é criado como WB_EX_TOPMOST
  986. #--------------------------------------------------------------------------
  987. # • [call] : Retorna aos valores dos botões. Para serem usados
  988. # como condição, de que se ao clicar.
  989. # API::MessageBox.call(title, string, format)
  990. # title -> Título da caixa.
  991. # string -> Conteúdo da caixa.
  992. # format -> Formato, no caso seria os botões e ícones.
  993. #--------------------------------------------------------------------------
  994. def call(title, string, format)
  995. return FunctionMessageBox.call(API.hWND, API.textUTF(string), API.textUTF(title), format)
  996. end
  997. #--------------------------------------------------------------------------
  998. # • [messageBox] : Mesma função do Call a diferença é que e protegido.
  999. #--------------------------------------------------------------------------
  1000. def messageBox(*args)
  1001. self.call(*args)
  1002. end
  1003. protected :messageBox
  1004. end
  1005. #============================================================================
  1006. # • ::PNG
  1007. #============================================================================
  1008. module PNG
  1009. extend self
  1010. private
  1011. #--------------------------------------------------------------------------
  1012. # • Criar o header do arquivo
  1013. #--------------------------------------------------------------------------
  1014. def make_header(file)
  1015. # Número mágico
  1016. file.write([0x89].pack('C'))
  1017. # PNG
  1018. file.write([0x50, 0x4E, 0x47].pack('CCC'))
  1019. # Fim de linha estilo DOS para verificação de conversão DOS - UNIX
  1020. file.write([0x0D, 0x0A].pack('CC'))
  1021. # Caractere de fim de linha (DOS)
  1022. file.write([0x1A].pack('C'))
  1023. # Caractere de fim de linha (UNIX)
  1024. file.write([0x0A].pack('C'))
  1025. end
  1026. #--------------------------------------------------------------------------
  1027. # • Aquisição da soma mágica
  1028. #--------------------------------------------------------------------------
  1029. def checksum(string)
  1030. Zlib.crc32(string)
  1031. end
  1032. #--------------------------------------------------------------------------
  1033. # • Criação do chunk de cabeçalho
  1034. #--------------------------------------------------------------------------
  1035. def make_ihdr(bitmap, file)
  1036. data = ''
  1037. # Largura
  1038. data += [bitmap.width, bitmap.height].pack('NN')
  1039. # Bit depth (???)
  1040. data += [0x8].pack('C')
  1041. # Tipo de cor
  1042. data += [0x6].pack('C')
  1043. data += [0x0, 0x0, 0x0].pack('CCC')
  1044. # Tamanho do chunk
  1045. file.write([data.size].pack('N'))
  1046. # Tipo de chunk
  1047. file.write('IHDR')
  1048. file.write(data)
  1049. # Soma mágica
  1050. file.write([checksum('IHDR' + data)].pack('N'))
  1051. end
  1052. #--------------------------------------------------------------------------
  1053. # • Criação do chunk de dados
  1054. #--------------------------------------------------------------------------
  1055. def make_idat(bitmap, file)
  1056. data = ''
  1057. for y in 0...bitmap.height
  1058. data << "\0"
  1059. for x in 0...bitmap.width
  1060. color = bitmap.get_pixel(x, y)
  1061. data << [color.red, color.green, color.blue, color.alpha].pack('C*')
  1062. end
  1063. end
  1064. # Desinflamento (jeito legal de dizer compressão...) dos dados
  1065. data = Zlib::Deflate.deflate(data)
  1066. # Tamanho do chunk
  1067. file.write([data.size].pack('N'))
  1068. # Tipo de chunk
  1069. file.write('IDAT')
  1070. # Dados (a imagem)
  1071. file.write(data)
  1072. # Soma mágica
  1073. file.write([checksum('IDAT' + data)].pack('N'))
  1074. end
  1075. #--------------------------------------------------------------------------
  1076. # • Criação do chunk final.
  1077. #--------------------------------------------------------------------------
  1078. def make_iend(file)
  1079. # Tamanho do chunk
  1080. file.write([0].pack('N'))
  1081. # Tipo de chunk
  1082. file.write('IEND')
  1083. # Soma mágica
  1084. file.write([checksum('IEND')].pack('N'))
  1085. end
  1086. public
  1087. #--------------------------------------------------------------------------
  1088. # • Salvar :
  1089. # bitmap : Bitmap.
  1090. # filename : Nome do arquivo.
  1091. #--------------------------------------------------------------------------
  1092. def save(bitmap, filename)
  1093. # Verificar se tem a extenção .png
  1094. filename = filename.include?(".png") ? filename : filename << ".png"
  1095. # Criação do arquivo
  1096. file = File.open(filename, 'wb')
  1097. # Criação do cabeçalho
  1098. make_header(file)
  1099. # Criação do primeiro chunk
  1100. make_ihdr(bitmap, file)
  1101. # Criação dos dados
  1102. make_idat(bitmap, file)
  1103. # Criação do final
  1104. make_iend(file)
  1105. file.close
  1106. end
  1107. end
  1108. protected :hwnd, :open, :function
  1109. end
  1110. #==============================================================================
  1111. # • RTP
  1112. #==============================================================================
  1113. Dax.register :rtp
  1114. module RTP
  1115. extend self
  1116. extend API
  1117. #--------------------------------------------------------------------------
  1118. # • Variável & Constante
  1119. #--------------------------------------------------------------------------
  1120. @@rtp =
  1121. DPATH = 'Software\Enterbrain\RGSS3\RTP'
  1122. DLL = 'Advapi32.dll'
  1123. #--------------------------------------------------------------------------
  1124. # • Retorna ao caminho do diretório do RTP.
  1125. #--------------------------------------------------------------------------
  1126. def path
  1127. unless @@rtp
  1128. read_ini = ->(val) { File.foreach("Game.ini") { |line| break($1) if line =~ /^#{val}=(.*)$/ }
  1129. }
  1130. key = type = size = [].pack("x4")
  1131. long("RegOpenKeyEx", [:HKEY, :LPCTST, :DWORD, :REGSAM, :PHKEY], DLL).call(
  1132. 2147483650, DPATH, 0, 131097, key)
  1133. key = key.unpack('l').first
  1134. rtp_data = read_ini["RTP"]
  1135. long("RegQueryValueEx", [:HKEY, :LPCTSTR, :LPDWORD, :LPDWORD, :LPBYTE, :LPDWORD], DLL).call(
  1136. key, rtp_data, 0, type, 0, size)
  1137. buffer = ' '*size.unpack('l').first
  1138. long("RegQueryValueEx", [:HKEY, :LPCTSTR, :LPDWORD, :LPDWORD, :LPBYTE, :LPDWORD], DLL).call(
  1139. key, rtp_data, 0, type, buffer, size)
  1140. long("RegCloseKey", [:HKEY], DLL).call(key)
  1141. @@rtp = (buffer.gsub(/\\/, '/')).delete!(0.chr)
  1142. @@rtp += "/" if @@rtp[-1] != "/"
  1143. end
  1144. return @@rtp
  1145. end
  1146. end
  1147. #==============================================================================
  1148. # * String
  1149. #==============================================================================
  1150. Dax.register(:string)
  1151. class String
  1152. #----------------------------------------------------------------------------
  1153. # • [String] : Remove a extensão do nome do arquivo e assume por outra.
  1154. # filename : Nome do aquivo.
  1155. # extension : Nova extensão.
  1156. # "Hello.rb".extn(".rvdata2") # "Hello.rvdata2"
  1157. #----------------------------------------------------------------------------
  1158. def extn(extension)
  1159. return self.gsub(/\.(\w+)/, extension.include?(".") ? extension : "." + extension)
  1160. end
  1161. #--------------------------------------------------------------------------
  1162. # • [String] : converter à String em UTF8
  1163. #--------------------------------------------------------------------------
  1164. def to_utf8
  1165. API.textUTF(self)
  1166. end
  1167. #----------------------------------------------------------------------------
  1168. # • [String] : Converter a String para w_char. Pra chamadas WinAPI.
  1169. #----------------------------------------------------------------------------
  1170. def w_char
  1171. wstr = ""
  1172. self.size.times { |i| wstr += self[i, 1] + "\0" }
  1173. wstr += "\0"
  1174. return wstr
  1175. end
  1176. #--------------------------------------------------------------------------
  1177. # • [Array] : Extrai somente os números da String, e retorna a uma Array.
  1178. # Exemplo: "João89".numbers # [8, 9]
  1179. #--------------------------------------------------------------------------
  1180. def numbers
  1181. self.scan(/-*\d+/).collect{|n|n.to_i}
  1182. end
  1183. #----------------------------------------------------------------------------
  1184. # • [String] : Aplicando Case Sensitive
  1185. # "Exemplo 2" => "Exemplo_2"
  1186. #----------------------------------------------------------------------------
  1187. def case_sensitive
  1188. return self.gsub(" ", "_")
  1189. end
  1190. #----------------------------------------------------------------------------
  1191. # • [Symbol] : Transforma em símbolo a string.
  1192. # "Ola Meu Nome É" #:ola_menu_nome_é
  1193. #----------------------------------------------------------------------------
  1194. def symbol
  1195. return self.case_sensitive.downcase.to_sym
  1196. end
  1197. #----------------------------------------------------------------------------
  1198. # • [String] : Remove o último caractere da String.
  1199. #----------------------------------------------------------------------------
  1200. def backslash
  1201. return String(self[0, self.split(//).size-1])
  1202. end
  1203. #----------------------------------------------------------------------------
  1204. # • Método xor.
  1205. #----------------------------------------------------------------------------
  1206. def ^(string)
  1207. bytes.map.with_index{|byte, index| byte ^ other[index % other.size].ord }.pack("C*")
  1208. end
  1209. alias xor ^
  1210. end
  1211. #==============================================================================
  1212. # * Integer
  1213. #==============================================================================
  1214. Dax.register(:integer)
  1215. class Integer
  1216. #----------------------------------------------------------------------------
  1217. # • [TrueClass/FalseClass] : Verifica-se e par.
  1218. #----------------------------------------------------------------------------
  1219. def is_evan?
  1220. return (self & 1) == 0
  1221. end
  1222. #----------------------------------------------------------------------------
  1223. # • [TrueClass/FalseClass] : Verifica-se e impar.
  1224. #----------------------------------------------------------------------------
  1225. def is_odd?
  1226. return (self & 1) == 1
  1227. end
  1228. #----------------------------------------------------------------------------
  1229. # • [Integer] : Aumenta o valor até chegar ao máximo(definido), quando
  1230. # chegar ao máximo(definido) retorna a zero(pode definir).
  1231. #----------------------------------------------------------------------------
  1232. def up(max, r=0)
  1233. n = self
  1234. n = n > max ? r : n.next
  1235. return n
  1236. end
  1237. #----------------------------------------------------------------------------
  1238. # • [Integer] : Diminui o valor até chegar a zero, quando chegar a zero(pode definir)
  1239. # retorna ao valor máximo(defindo).
  1240. #----------------------------------------------------------------------------
  1241. def down(max, r=0)
  1242. n = self
  1243. n = n < r ? max : n.pred
  1244. return n
  1245. end
  1246. #----------------------------------------------------------------------------
  1247. # • [Integer] : Sistema simplificado para fazer calculos factoriais.
  1248. # !4 #> 24
  1249. #----------------------------------------------------------------------------
  1250. def !@
  1251. return 1 unless self > 0
  1252. return self.downto(1).reduce(:*)
  1253. end
  1254. alias factorial !@
  1255. #----------------------------------------------------------------------------
  1256. # • [Integer] : Formula de número randômico.
  1257. #----------------------------------------------------------------------------
  1258. def aleatory
  1259. return ((1..(self.abs)).to_a).shuffle[rand(self).to_i].to_i
  1260. end
  1261. end
  1262. #==============================================================================
  1263. # • Float
  1264. #==============================================================================
  1265. Dax.register(:float)
  1266. class Float
  1267. #----------------------------------------------------------------------------
  1268. # • [Float] : Sistema simplificado para fazer calculos factoriais em floats.
  1269. # !1.5 #> 3.6036
  1270. #----------------------------------------------------------------------------
  1271. def !@
  1272. return 0.1 unless self > 0.1
  1273. return (1..(self)).step(0.1).reduce(:*)
  1274. end
  1275. alias factorial !@
  1276. end
  1277. #==============================================================================
  1278. # • Numeric
  1279. #==============================================================================
  1280. Dax.register(:numeric)
  1281. class Numeric
  1282. #----------------------------------------------------------------------------
  1283. # * [Numeric] : Transformar em porcentagem
  1284. # a : Valor atual.
  1285. # b : Valor máximo.
  1286. #----------------------------------------------------------------------------
  1287. def to_p(a, b)
  1288. self * a / b
  1289. end
  1290. alias :percent :to_p
  1291. #----------------------------------------------------------------------------
  1292. # • [Numeric] : Pega um do porcento.
  1293. #----------------------------------------------------------------------------
  1294. def p_to(max)
  1295. (self * max) / 100
  1296. end
  1297. alias :proportion :p_to
  1298. #----------------------------------------------------------------------------
  1299. # * [Numeric] : Variação do número.
  1300. #----------------------------------------------------------------------------
  1301. def randomic(x=4)
  1302. return ( (self+rand(2)) + (self + (rand(2) == 0 ? rand(x) : -rand(x)) ) ) / 2
  1303. end
  1304. #----------------------------------------------------------------------------
  1305. # * [Boolean] : Verifica se o número é igual a um dos especificados.
  1306. # 1.if_equals?(2, 3) # false
  1307. #----------------------------------------------------------------------------
  1308. def if_equals?(*args)
  1309. args.each { |i|
  1310. if self == i
  1311. return true
  1312. else
  1313. next
  1314. end
  1315. }
  1316. return false
  1317. end
  1318. end
  1319. #==============================================================================
  1320. # • Position.
  1321. #==============================================================================
  1322. Dax.register :position
  1323. class Position
  1324. #----------------------------------------------------------------------------
  1325. # • Modificar a posição de um objeto, que deve de conter as variáveis
  1326. # x, y, width, height.
  1327. # pos : Defina aqui o valor que definirá a posição da escola. Veja abaixo
  1328. # object : Objeto que contenha as variáveis x, y, width, height.
  1329. # os valores.
  1330. # 0 : Ficará no canto esquerdo superior.
  1331. # 1 : Posição X mudará para o centro da tela.
  1332. # 2 : Ficará no canto direito superior.
  1333. # 3 : Ficará no canto esquerdo inferior.
  1334. # 4 : Posição Y mudará para o centro da tela.
  1335. # 5 : Ficará no canto direito inferior.
  1336. # :center : Mudar a posição para o centro da tela.
  1337. # :center_left : Centralizar à esquerda da tela.
  1338. # :center_right : Centralizar à direita da tela.
  1339. # :center_up : Centralizar no centro superior.
  1340. # :center_down : Centralizar no centro inferior.
  1341. #----------------------------------------------------------------------------
  1342. def self.[](pos, object)
  1343. return if object.nil? or pos.nil?
  1344. return object.x, object.y = pos[0], pos[1] if pos.is_a?(Array)
  1345. return object.x, object.y = pos.x, pos.y if pos.is_a?(Position)
  1346. case pos
  1347. when 0 then object.x, object.y = 0, 0
  1348. when 1 then object.x = DMath.get_x_center_screen(object.width)
  1349. when 2 then object.x, object.y = Graphics.width - object.width, 0
  1350. when 3 then object.x, object.y = 0, Graphics.height - object.height
  1351. when 4 then object.y = DMath.get_y_center_screen(object.height)
  1352. when 5 then object.x, object.y = Graphics.width - object.width, Graphics.height - object.height
  1353. when :center
  1354. object.x = (Graphics.width - object.width) / 2
  1355. object.y = (Graphics.height - object.height) / 2
  1356. when :center_left
  1357. object.x = 0
  1358. object.y = (Graphics.height - object.height) / 2
  1359. when :center_right
  1360. object.x = Graphics.width - object.width
  1361. object.y = (Graphics.height - object.height) / 2
  1362. when :center_up
  1363. object.x = (Graphics.width - object.width) / 2
  1364. object.y = 0
  1365. when :center_down
  1366. object.x = (Graphics.width - object.width) / 2
  1367. object.y = Graphics.height - object.height
  1368. end
  1369. end
  1370. #----------------------------------------------------------------------------
  1371. # • Variáveis públicas da instância.
  1372. #----------------------------------------------------------------------------
  1373. attr_accessor :x # Variável que retorna ao valor que indica a posição X.
  1374. attr_accessor :y # Variável que retorna ao valor que indica a posição Y.
  1375. #----------------------------------------------------------------------------
  1376. # • Inicialização dos objetos.
  1377. #----------------------------------------------------------------------------
  1378. def initialize(x, y)
  1379. @x = x || 0
  1380. @y = y || 0
  1381. end
  1382. #----------------------------------------------------------------------------
  1383. # • Somar com outra posição.
  1384. #----------------------------------------------------------------------------
  1385. def +(position)
  1386. position = position.position unless position.is_a?(Position)
  1387. Position.new(self.x + position.x, self.y + position.y)
  1388. end
  1389. #----------------------------------------------------------------------------
  1390. # • Subtrair com outra posição.
  1391. #----------------------------------------------------------------------------
  1392. def -(position)
  1393. position = position.position unless position.is_a?(Position)
  1394. Position.new(self.x - position.x, self.y - position.y)
  1395. end
  1396. #----------------------------------------------------------------------------
  1397. # • Multiplicar com outra posição.
  1398. #----------------------------------------------------------------------------
  1399. def *(position)
  1400. position = position.position unless position.is_a?(Position)
  1401. Position.new(self.x * position.x, self.y * position.y)
  1402. end
  1403. #----------------------------------------------------------------------------
  1404. # • Dividir com outra posição.
  1405. #----------------------------------------------------------------------------
  1406. def /(position)
  1407. position = position.position unless position.is_a?(Position)
  1408. return if (self.x or position.x or self.y or position.y) <= 0
  1409. Position.new(self.x / position.x, self.y / position.y)
  1410. end
  1411. #----------------------------------------------------------------------------
  1412. # • Comparar com outra posição.
  1413. #----------------------------------------------------------------------------
  1414. def ==(position)
  1415. position = position.position unless position.is_a?(Position)
  1416. return self.x == position.x && self.y == position.y
  1417. end
  1418. #----------------------------------------------------------------------------
  1419. # • Distância de um ponto de posição com relação a outro.
  1420. # other : Outro ponto de posição.
  1421. #----------------------------------------------------------------------------
  1422. def distance(other)
  1423. other = other.position unless other.is_a?(Position)
  1424. (self.x - other.x).abs + (self.y - other.y).abs
  1425. end
  1426. #----------------------------------------------------------------------------
  1427. # • Converter em string.
  1428. #----------------------------------------------------------------------------
  1429. def to_s
  1430. return "position x: #{self.x}\nposition y: #{self.y}"
  1431. end
  1432. #----------------------------------------------------------------------------
  1433. # • Converter em array.
  1434. #----------------------------------------------------------------------------
  1435. def to_a
  1436. return [@x, @y]
  1437. end
  1438. #----------------------------------------------------------------------------
  1439. # • Converter em hash.
  1440. #----------------------------------------------------------------------------
  1441. def to_h
  1442. return {x: @x, y: @y}
  1443. end
  1444. #----------------------------------------------------------------------------
  1445. # • Clonar
  1446. #----------------------------------------------------------------------------
  1447. def clone
  1448. return Position.new(@x, @y)
  1449. end
  1450. end
  1451. #==============================================================================
  1452. # • IO
  1453. #==============================================================================
  1454. Dax.register(:io)
  1455. class << IO
  1456. #----------------------------------------------------------------------------
  1457. # • [Array] : Obtêm a largura e a altura da imagem.
  1458. # filename : Nome do arquivo.
  1459. # [Retorna Nil, caso o arquivo não exista]
  1460. #----------------------------------------------------------------------------
  1461. def size_picture(filename)
  1462. return nil unless FileTest.file?(filename)
  1463. return IO.read(filename, 8, 16).unpack("NN")
  1464. end
  1465. end
  1466. #==============================================================================
  1467. # • File
  1468. #==============================================================================
  1469. Dax.register(:file)
  1470. class << File
  1471. #----------------------------------------------------------------------------
  1472. # • [NilClass] : Executa o script que está no arquivo.
  1473. #----------------------------------------------------------------------------
  1474. def eval(filename)
  1475. return unless filename.match(/.rb|.rvdata2/) or FileTest.exist?(filename)
  1476. script = ""
  1477. nilcommand = false
  1478. IO.readlines(filename).each { |i|
  1479. if i.match(/^=begin/)
  1480. nilcommand = true
  1481. elsif i.match(/^=end/) and nilcommand
  1482. nilcommand = false
  1483. elsif !nilcommand
  1484. script += i.gsub(/#(.*)/, "").to_s + "\n"
  1485. end
  1486. }
  1487. Kernel.eval(script)
  1488. return nil
  1489. end
  1490. #----------------------------------------------------------------------------
  1491. # • Verificar se é GIF|JPEG|BM|PNG -> 0|1|2|3
  1492. #----------------------------------------------------------------------------
  1493. def is_gjb?(filename)
  1494. file = open(filename, "rb")
  1495. data = file.read(9)
  1496. file.close
  1497. return 0 if data[0, 4] == "GIF8"
  1498. return 1 if data[0, 4] == "\xff\xd8\xff\xe0"
  1499. return 2 if data[0, 2] == "MB"
  1500. return 3 if data[0, 4] == "\x89PNG\r\n\x1a\n"
  1501. end
  1502. end
  1503. #==============================================================================
  1504. # • Dir
  1505. #==============================================================================
  1506. Dax.register(:dir)
  1507. class << Dir
  1508. #----------------------------------------------------------------------------
  1509. # • [NilClass] Cria pasta e subpasta em conjunto.
  1510. # Separe todo com vírgulas. A primeira que você definir será a pasta,
  1511. # o resto será as subpasta.
  1512. # Dir.mksdir("Pasta", "Subpasta1, Subpasta2")
  1513. #----------------------------------------------------------------------------
  1514. def mksdir(dir="", subdir="")
  1515. self.mkdir(dir) unless File.directory?(dir)
  1516. subdir = subdir.split(/,/)
  1517. subdir.each { |data| self.mkdir(dir + "/" + data.strip) unless File.directory?(dir + "/" + data.gsub(" ", "")) }
  1518. return nil
  1519. end
  1520. end
  1521. #==============================================================================
  1522. # * Color
  1523. #==============================================================================
  1524. Dax.register(:color)
  1525. class Color
  1526. #----------------------------------------------------------------------------
  1527. # • [Color] : Permite você modificar a opacidade da cor.
  1528. # Color.new(r, g, b).opacity([alpha])
  1529. # O valor padrão do alpha e 128.. não é preciso espeficar.
  1530. #----------------------------------------------------------------------------
  1531. def opacity(alpha=nil)
  1532. self.set(self.red, self.green, self.blue, alpha || 128)
  1533. end
  1534. #----------------------------------------------------------------------------
  1535. # • [Color] : Inverte as cores.
  1536. # Color.new(r, g, b[, a).invert!
  1537. #----------------------------------------------------------------------------
  1538. def invert!
  1539. self.set(255-self.red, 255-self.green, 255-self.blue, self.alpha)
  1540. end
  1541. #----------------------------------------------------------------------------
  1542. # • [Color] : Reverte as cores.
  1543. # Color.new(r, g, b[, a).revert
  1544. #----------------------------------------------------------------------------
  1545. def revert
  1546. self.set(*[self.red, self.green, self.blue, self.alpha].reverse!)
  1547. end
  1548. #----------------------------------------------------------------------------
  1549. # • [String] : Converte para string as informações dos valores das cores.
  1550. # Color.new(0, 0, 0).to_s
  1551. # red: 0
  1552. # blue: 0
  1553. # green: 0
  1554. # alpha: 255
  1555. #----------------------------------------------------------------------------
  1556. def to_s
  1557. "red: #{self.red}\nblue: #{self.blue}\ngreen: #{self.green}\nalpha: #{self.alpha}"
  1558. end
  1559. #----------------------------------------------------------------------------
  1560. # • [TrueClass/FalseClass] : Comparar cores, retorna a [true] se for igual..
  1561. # retorna a [false] se não for igual.
  1562. #----------------------------------------------------------------------------
  1563. def ==(color)
  1564. return (self.red == color.red and self.green == color.green and self.blue == color.blue and
  1565. self.alpha == color.alpha) ? true : false
  1566. end
  1567. #----------------------------------------------------------------------------
  1568. # • [Hash] : Retorna aos valores das cores em formato de Hash.
  1569. # Color.new(0, 0, 0).to_h
  1570. # {:red => 0, :green => 0, :blue => 0, :alpha => 255}
  1571. #----------------------------------------------------------------------------
  1572. def to_h
  1573. return {
  1574. red: self.red, green: self.green, blue: self.blue, alpha: self.alpha,
  1575. }
  1576. end
  1577. #----------------------------------------------------------------------------
  1578. # • [Array] : Retorna aos valores das cores em formato de Array.
  1579. # includeAlpha : Incluir o valor alpha?
  1580. # Color.new(0, 0, 0).to_a
  1581. # [0, 0, 0, 255]
  1582. #----------------------------------------------------------------------------
  1583. def to_a(includeAlpha=false)
  1584. array = [self.red, self.green, self.blue]
  1585. array += [self.alpha] if includeAlpha
  1586. return array
  1587. end
  1588. #----------------------------------------------------------------------------
  1589. # • [Color] : Dispoem os valores das cores em ordem crescente e cria uma
  1590. # nova cor.
  1591. # includeAlpha : Incluir o valor alpha?
  1592. #----------------------------------------------------------------------------
  1593. def crescent(includeAlpha=false)
  1594. set(*to_a(includeAlpha).crescent)
  1595. end
  1596. #----------------------------------------------------------------------------
  1597. # • [Color] : Dispoem os valores das cores em ordem decrescente e cria uma
  1598. # nova cor.
  1599. # includeAlpha : Incluir o valor alpha?
  1600. #----------------------------------------------------------------------------
  1601. def decrescent(includeAlpha=false)
  1602. set(*to_a(includeAlpha).decrescent)
  1603. end
  1604. #----------------------------------------------------------------------------
  1605. # • [Color] Soma os valores das cores com os valores de outras cores.
  1606. # Ex: color + Color.new(21,54,255)
  1607. #----------------------------------------------------------------------------
  1608. def +(color)
  1609. return unless color.is_a?(Color)
  1610. self.set(
  1611. *color.to_a(false).each_with_index { |i, n| i + to_a[n] }
  1612. )
  1613. end
  1614. #----------------------------------------------------------------------------
  1615. # • [Color] Subtrai os valores das cores com os valores de outras cores.
  1616. # Ex: color - Color.new(21,54,255)
  1617. #----------------------------------------------------------------------------
  1618. def -(color)
  1619. return unless color.is_a?(Color)
  1620. self.set(
  1621. *color.to_a(false).each_with_index { |i, n| i - to_a[n] }
  1622. )
  1623. end
  1624. #----------------------------------------------------------------------------
  1625. # • [Color] Multiplica os valores das cores com os valores de outras cores.
  1626. # Ex: color * Color.new(21,54,255)
  1627. #----------------------------------------------------------------------------
  1628. def *(color)
  1629. return unless color.is_a?(Color)
  1630. self.set(
  1631. *color.to_a(false).each_with_index { |i, n| (i * to_a[n]) / 255.0 }
  1632. )
  1633. end
  1634. #----------------------------------------------------------------------------
  1635. # • [Color] Divide os valores das cores com os valores de outras cores.
  1636. # Ex: color / Color.new(21,54,255)
  1637. #----------------------------------------------------------------------------
  1638. def /(color)
  1639. return unless color.is_a?(Color)
  1640. self.set(
  1641. *color.to_a(false).each_with_index { |i, n| i.zero? ? 0 : to_a[n] / i }
  1642. )
  1643. end
  1644. #----------------------------------------------------------------------------
  1645. # • [Color] : Aumentar/Diminuir as cores em porcento.
  1646. # value : Valor da porcentagem. Vai de 0~100
  1647. # includeAlpha : Incluir o valor alpha?
  1648. #----------------------------------------------------------------------------
  1649. def percent(value, includeAlpha=true)
  1650. value = DMath.clamp(value, 0, 100)
  1651. Color.new(
  1652. *to_a(includeAlpha).collect! { |i| i.to_p(value * 2.55, 255) }
  1653. )
  1654. end
  1655. #----------------------------------------------------------------------------
  1656. # • [Numeric] : Retorna a lumonisidade das cores.
  1657. #----------------------------------------------------------------------------
  1658. def luminosity
  1659. return to_a(false).each_with_index { |i, n| i * [0.21, 0.71, 0.07][n] }.alln?
  1660. end
  1661. #----------------------------------------------------------------------------
  1662. # • [Numeric] : Retorna a media entre os valores(canais).
  1663. # includeAlpha : Incluir o valor alpha?
  1664. #----------------------------------------------------------------------------
  1665. def avarange(includeAlpha=true)
  1666. n = includeAlpha ? 4 : 3
  1667. return to_a(includeAlpha).alln? / n
  1668. end
  1669. #----------------------------------------------------------------------------
  1670. # • [Numeric] : Retorna ao valor mais alto que tiver, dentre os valores
  1671. # especificados das cores.
  1672. #----------------------------------------------------------------------------
  1673. def max
  1674. [red, green, blue].max
  1675. end
  1676. #----------------------------------------------------------------------------
  1677. # • [Numeric] : Retorna ao valor menor que tiver, dentre os valores
  1678. # especificados das cores.
  1679. #----------------------------------------------------------------------------
  1680. def min
  1681. [red, green, blue].min
  1682. end
  1683. #----------------------------------------------------------------------------
  1684. # • [Color] : Define uma cor aleatória:
  1685. # Exemplo: Color.new.random
  1686. #----------------------------------------------------------------------------
  1687. def random
  1688. return Color.new(rand(256), rand(256), rand(256))
  1689. end
  1690. #----------------------------------------------------------------------------
  1691. # • [Color] : Define uma cor em hexadécimal.
  1692. # Exemplo : Color.new.hex("ffffff")
  1693. #----------------------------------------------------------------------------
  1694. def hex(string)
  1695. self.set(*string.scan(/../).map { |color| color.to_i(16)})
  1696. end
  1697. #----------------------------------------------------------------------------
  1698. # • [Color] : Retorna a cor padrão.
  1699. # Exemplo : Color.new.default
  1700. #----------------------------------------------------------------------------
  1701. def default
  1702. self.hex("ffffff")
  1703. end
  1704. end
  1705. #==============================================================================
  1706. # • Rect
  1707. #==============================================================================
  1708. Dax.register(:rect)
  1709. class Rect
  1710. #----------------------------------------------------------------------------
  1711. # • [TrueClass/FalseClass] : Verificar se algo está na área.
  1712. #----------------------------------------------------------------------------
  1713. def in?(x, y)
  1714. x.between?(self.x, self.x + self.width) &&
  1715. y.between?(self.y, self.y + self.height)
  1716. end
  1717. #----------------------------------------------------------------------------
  1718. # • [NilClass] : Cada elemento em um bloco.
  1719. # rect.each { |x, y, w, h| }
  1720. #----------------------------------------------------------------------------
  1721. def each
  1722. yield(self.x, self.y, self.width, self.height)
  1723. return nil
  1724. end
  1725. #----------------------------------------------------------------------------
  1726. # • [NilClass] : Retorna a cada parte do rect definida por ti, ponto-a-ponto.
  1727. # p : Ponto A.
  1728. # q : Ponto B.
  1729. # Rect.new(0, 0, 1, 1).step(1.0, 1.0) { |i, j| p [i, j] }
  1730. # [0.0, 0.0]
  1731. # [0.0, 1.0]
  1732. # [1.0, 0.0]
  1733. # [1.0, 1.0]
  1734. #----------------------------------------------------------------------------
  1735. def step(p=1, q=1)
  1736. (self.x..(self.x + self.width)).step(p) { |i|
  1737. (self.y..(self.y + self.height)).step(q) { |j|
  1738. yield(i, j)
  1739. }
  1740. }
  1741. return nil
  1742. end
  1743. #----------------------------------------------------------------------------
  1744. # • [Array] : Retorna aos valores do Rect em uma Array.
  1745. #----------------------------------------------------------------------------
  1746. def to_a
  1747. return [self.x, self.y, self.width, self.height]
  1748. end
  1749. #----------------------------------------------------------------------------
  1750. # • Retorna interseção com o argumento, que deve ser também do tipo Rect
  1751. #----------------------------------------------------------------------------
  1752. def intercept(rect)
  1753. x = [self.x, rect.x].max
  1754. y = [self.y, rect.y].max
  1755. w = [self.x + self.width, rect.x + rect.width ].min - x
  1756. h = [self.y + self.height, rect.y + rect.height].min - y
  1757.  
  1758. return Rect.new(x, y, w, h)
  1759. end
  1760. alias & intercept
  1761. end
  1762. #==============================================================================
  1763. # • DMath
  1764. #==============================================================================
  1765. Dax.register(:dmath, 'Dax', 1.5, '04/05/13')
  1766. module DMath
  1767. extend self
  1768. #----------------------------------------------------------------------------
  1769. # • Constantes para fórmula de dano.
  1770. #----------------------------------------------------------------------------
  1771. MAX_VALUE_PARAM = 256
  1772. MAX_VALUE_PARAM_AXE = 128
  1773. MAX_VALUE_PARAM_DAGGER = 218
  1774. MAX_VALUE_PARAM_GUN = 99
  1775. MAX_VALUE_MAGIC = 218
  1776. #----------------------------------------------------------------------------
  1777. # • [Numeric] : Calcula o ângulo entre dóis pontos.
  1778. #----------------------------------------------------------------------------
  1779. def angle(pA, pB, quad4=false)
  1780. pA = pA.position unless pA.is_a?(Position)
  1781. pB = pB.position unless pB.is_a?(Position)
  1782. x = pB.x - pA.x
  1783. y = pB.y - pA.y
  1784. y *= -1 if quad4
  1785. radian = Math.atan2(y, x)
  1786. angle = (radian * 180 / Math::PI)
  1787. angle = 360 + angle if angle < 0
  1788. return angle
  1789. end
  1790. #----------------------------------------------------------------------------
  1791. # • [Boolean] : Verifica se a posição é igual.
  1792. #----------------------------------------------------------------------------
  1793. def equal_pos?(a, b)
  1794. (a.x == b.x) && (a.y == b.y)
  1795. end
  1796. #----------------------------------------------------------------------------
  1797. # • [Float] : Cálcula a raíz quadrada que qualquer grau.
  1798. # n : Número que será calculado.
  1799. # g : Grau da raíz.
  1800. # Dmath.sqrt(27, 3) # Cálculo da raíz cúbica de 27 => 3.0
  1801. #----------------------------------------------------------------------------
  1802. def sqrt(n, g)
  1803. raise(ArgumentError) if n < 0 && n.is_evan?
  1804. x, count, num = 1.0, 0.0, 0.0
  1805. while
  1806. num = x - ( ( x ** g - n ) / ( g * ( x ** g.pred ) ) )
  1807. (x == num) || (count > 20) ? break : eval("x = num; count += 1")
  1808. end
  1809. return num
  1810. end
  1811. #----------------------------------------------------------------------------
  1812. # • [Numeric] : Clamp | Delimitar o inteiro
  1813. # num : Número.
  1814. # low : Número minímo. Sê o 'num' for menor que min retorna a low.
  1815. # high : Número máximo. Sê o 'num' for maior que hight retorna a high, caso
  1816. # não retorna ao próprio número(num).
  1817. #----------------------------------------------------------------------------
  1818. def clamp(num, low, high)
  1819. num, low, high = num.to_i, low.to_i, high.to_i
  1820. num = num < low ? low : num > high ? high : num
  1821. num
  1822. end
  1823. #----------------------------------------------------------------------------
  1824. # • [Array] : Centralizar um objeto n'outro.
  1825. # object : Objeto, tem que ser do tipo [Sprite] ou [Window_Base]
  1826. # object_for_centralize : Objeto que irá se centralizar no 'object', tem
  1827. # que ser do tipo [Sprite] ou [Window_Base]
  1828. # * Retorna a uma Array contendo as informações das novas posições em X e Y.
  1829. #----------------------------------------------------------------------------
  1830. def centralize_object(object, object_for_centralize)
  1831. x = object.x + (object.width - object_for_centralize.width) / 2
  1832. y = object.y + (object.height - object_for_centralize.height) / 2
  1833. return x, y
  1834. end
  1835. #----------------------------------------------------------------------------
  1836. # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição X.
  1837. # objectx : Valor da posição X do objeto número 1.
  1838. # objectwidth : Valor da largura do objeto número 1.
  1839. # object_for_centralizewidth : Valor da largura do objeto que irá se
  1840. # centralizar no objeto número 1.
  1841. # * Retorna ao valor da posição X.
  1842. #----------------------------------------------------------------------------
  1843. def centralize_x(objectx, objectwidth, object_for_centralizewidth)
  1844. return objectx + (objectwidth - object_for_centralizewidth) / 2
  1845. end
  1846. #----------------------------------------------------------------------------
  1847. # • [Numeric] : Centralizar um objeto n'outro, obtendo somente a posição Y.
  1848. # objecty : Valor da posição Y do objeto número 1.
  1849. # objectheight : Valor da altura do objeto número 1.
  1850. # object_for_centralizeheight : Valor da altura do objeto que irá se
  1851. # centralizar no objeto número 1.
  1852. # * Retorna ao valor da posição Y.
  1853. #----------------------------------------------------------------------------
  1854. def centralize_y(objecty, objectheight, object_for_centralizeheight)
  1855. return objecty + (objectheight - object_for_centralizeheight) / 2
  1856. end
  1857. #----------------------------------------------------------------------------
  1858. # • [Numeric] : Obter a posição X do centro da tela referente a largura do objeto X.
  1859. # Exemplo: get_x_center_screen(sprite.width) : Irá retornar ao valor da posição
  1860. # X para que o objeto fique no centro da tela.
  1861. # Exemplo: sprite.x = get_x_center_screen(sprite.width)
  1862. #----------------------------------------------------------------------------
  1863. def get_x_center_screen(width)
  1864. return (Graphics.width - width) / 2
  1865. end
  1866. #----------------------------------------------------------------------------
  1867. # • [Numeric] : Obter a posição Y do centro da tela referente a altura do objeto X.
  1868. # Exemplo: get_y_center_screen(sprite.height) : Irá retornar ao valor da posição
  1869. # Y para que o objeto fique no centro da tela.
  1870. # Exemplo: sprite.y = get_y_center_screen(sprite.height)
  1871. #----------------------------------------------------------------------------
  1872. def get_y_center_screen(height)
  1873. return (Graphics.height - height) / 2
  1874. end
  1875. #--------------------------------------------------------------------------
  1876. # • [TrueClass/FalseClass] : Verifica se um objeto está na área de um círculo.
  1877. # object : Objeto do tipo da classe [Sprite].
  1878. # object2 : Objeto do tipo da classe [Sprite].
  1879. # size : Tamanho geral do círculo.
  1880. #--------------------------------------------------------------------------
  1881. def circle(object, object2, size)
  1882. ( (object.x - object2.x) ** 2) + ( (object.y - object2.y) ** 2) <= (size ** 2)
  1883. end
  1884. #----------------------------------------------------------------------------
  1885. # • [Numeric] : Converter o valor em graus.
  1886. #----------------------------------------------------------------------------
  1887. def graus
  1888. 360 / (2 * Math::PI)
  1889. end
  1890. #----------------------------------------------------------------------------
  1891. # • [Numeric] : Converte o valor em radiano.
  1892. #----------------------------------------------------------------------------
  1893. def radian(degree)
  1894. return (degree.to_f/180) * Math::PI
  1895. end
  1896. #----------------------------------------------------------------------------
  1897. # • [Numeric] : Converte o valor em grau.
  1898. #----------------------------------------------------------------------------
  1899. def degree(radian)
  1900. return (radian.to_f/Math::PI) * 180
  1901. end
  1902. #----------------------------------------------------------------------------
  1903. # • [Numeric] : Retorna pra base de 4 decimais.
  1904. #----------------------------------------------------------------------------
  1905. def to_4_dec(n)
  1906. ((n * 1000).ceil) / 1000
  1907. end
  1908. #----------------------------------------------------------------------------
  1909. # • [Numeric] : Retorna a área do triângulo.
  1910. # x : x : Posição x do ponto 1
  1911. # y : Posição y do ponto 1
  1912. # x2 : Posição x do ponto 2
  1913. # y2 : Posição y do ponto 2
  1914. # x3 : Posição x do ponto 3
  1915. # y3 : Posição y do ponto 3
  1916. #----------------------------------------------------------------------------
  1917. def triangle_area(*args)
  1918. x, y, x2, y2, x3, y3 = *args
  1919. return (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y)
  1920. end
  1921. #----------------------------------------------------------------------------
  1922. # • [Numeric] : Método para calcular a distância de um objeto para com outro.
  1923. #----------------------------------------------------------------------------
  1924. def distance_sensor(target, target2)
  1925. return (target.x - target2.x).abs + (target.y - target2.y).abs
  1926. end
  1927. #----------------------------------------------------------------------------
  1928. # • [Integer] : Método euclidiano para mediar a distância de um ponto
  1929. # para outro ponto. Primeira dimensão.
  1930. # p : Ponto A. [x, y]
  1931. # q : Ponto B. [x, y]
  1932. # euclidean_distance_1d(5, 1) #4
  1933. #----------------------------------------------------------------------------
  1934. def euclidean_distance_1d(p, q)
  1935. return sqrt( (p - q) ** 2, 2 ).floor
  1936. end
  1937. #----------------------------------------------------------------------------
  1938. # • [Integer] : Método euclidiano para mediar a distância de um ponto
  1939. # para outro ponto. Segunda dimensão.
  1940. # p : Ponto A. [x, y]
  1941. # q : Ponto B. [x, y]
  1942. # euclidean_distance_2d([1, 3], [1, 5]) #2
  1943. #----------------------------------------------------------------------------
  1944. def euclidean_distance_2d(p, q)
  1945. p = p.position unless p.is_a?(Position)
  1946. q = q.position unless q.is_a?(Position)
  1947. return sqrt( ((p.x - q.x) ** 2) + ((p.y - q.y) ** 2), 2 ).floor
  1948. end
  1949. #----------------------------------------------------------------------------
  1950. # • [Numeric] : Dentro do círculo.
  1951. #----------------------------------------------------------------------------
  1952. def circle_in(t, b, c, d)
  1953. return -c * (Math.sqrt(1 - (t /= d.to_f) * t) - 1) + b
  1954. end
  1955. #----------------------------------------------------------------------------
  1956. # • [Numeric] : Fora do círculo
  1957. #----------------------------------------------------------------------------
  1958. def circle_out(t, b, c, d)
  1959. return c * Math.sqrt(1 - (t=t/d.to_f-1)*t) + b
  1960. end
  1961. #----------------------------------------------------------------------------
  1962. # • [Numeric] : Retorna ao valor minímo, do valor máximo de min & v, com o
  1963. # valor de max.
  1964. #----------------------------------------------------------------------------
  1965. def force_range(v, min, max)
  1966. [[min, v].max, max].min
  1967. end
  1968. #----------------------------------------------------------------------------
  1969. # • Cálculo de variação para o dano. Para equilibrar.
  1970. #----------------------------------------------------------------------------
  1971. def random
  1972. (1 + 2.aleatory) ** 0.125
  1973. end
  1974. #----------------------------------------------------------------------------
  1975. # • Resultado final.
  1976. #----------------------------------------------------------------------------
  1977. def lastResult(x)
  1978. return x <= 0 ? 0 : x.round
  1979. end
  1980. #----------------------------------------------------------------------------
  1981. # • [Formula de dano] : Espadas(1 & 2 mão), lanças, bestas, cajado.
  1982. #----------------------------------------------------------------------------
  1983. def sword(attack, strength, defense, level)
  1984. str = strength.randomic
  1985. return lastResult((attack.randomic * random - defense.randomic) * (1 + str * (level + str) / MAX_VALUE_PARAM))
  1986. end
  1987. #----------------------------------------------------------------------------
  1988. # • [Formula de dano] : Desarmado.
  1989. #----------------------------------------------------------------------------
  1990. def unarmed(strength, defense, level)
  1991. str = strength.randomic
  1992. lastResult((11 * random - defense.randomic) * str * (level + str) / MAX_VALUE_PARAM)
  1993. end
  1994. #----------------------------------------------------------------------------
  1995. # • [Formula de dano] : Desarmado com luva.
  1996. #----------------------------------------------------------------------------
  1997. def unarmed_brawler(strength, defense, level)
  1998. str = strength.randomic
  1999. lastResult(((level + str) / 2 * random - defense.randomic) * str * (level + str) / MAX_VALUE_PARAM)
  2000. end
  2001. #----------------------------------------------------------------------------
  2002. # • [Formula de dano] : Cajado de mágia.
  2003. #----------------------------------------------------------------------------
  2004. def pole(attack, strength, defense, level, magicDefense)
  2005. str = strength.randomic
  2006. lastResult((attack.randomic * random - magicDefense.randomic) * (1 + str * (level + str))/ MAX_VALUE_PARAM)
  2007. end
  2008. #----------------------------------------------------------------------------
  2009. # • [Formula de dano] : Maças..
  2010. #----------------------------------------------------------------------------
  2011. def mace(attack, defense, magic, level)
  2012. mag = magic.randomic
  2013. lastResult((attack.randomic * random - defense.randomic) * (1 + mag * (level + mag)) / MAX_VALUE_PARAM)
  2014. end
  2015. #----------------------------------------------------------------------------
  2016. # • [Formula de dano] : Katanas, staves..
  2017. #----------------------------------------------------------------------------
  2018. def katana(attack, defense, strength, magic, level)
  2019. lastResult((attack.randomic * random - defense.randomic) * (1 + strength.randomic * (level + magic.randomic) / MAX_VALUE_PARAM))
  2020. end
  2021. #----------------------------------------------------------------------------
  2022. # • [Formula de dano] : Machados, marretas..
  2023. #----------------------------------------------------------------------------
  2024. def axe(attack, strength, defense, level, vitality)
  2025. lastResult((attack.randomic * random - defense.randomic) * (1 + strength.randomic * (level+vitality.randomic)/MAX_VALUE_PARAM_AXE))
  2026. end
  2027. #----------------------------------------------------------------------------
  2028. # • [Formula de dano] : Adagas, espadas ninjas e arco..
  2029. #----------------------------------------------------------------------------
  2030. def dagger(attack, defense, strength, level, speed)
  2031. lastResult ((attack.randomic * random) - defense.randomic) * (1 + strength.randomic * (level + speed.randomic) / 218)
  2032. end
  2033. #----------------------------------------------------------------------------
  2034. # • [Formula de dano] : Revolvers
  2035. #----------------------------------------------------------------------------
  2036. def gun(attack,defense,strength, level)
  2037. str = strength.randomic
  2038. lastResult ( (((attack.randomic * random) - defense.randomic) ** 2) / 64 ) * (1 + str * (level + str) / MAX_VALUE_PARAM_GUN)
  2039. end
  2040. #----------------------------------------------------------------------------
  2041. # • [Formula de dano] : Mágicas de ataques.
  2042. #----------------------------------------------------------------------------
  2043. def magicAttack(magicDefense, level, magicAttack, attackMagic)
  2044. mag = magicAttack.randomic
  2045. lastResult ( (attackMagic.randomic * random) - magicDefense.randomic ) * (2 + mag.randomic * (level + mag) / MAX_VALUE_MAGIC)
  2046. end
  2047. #----------------------------------------------------------------------------
  2048. # • [Formula de dano] : Mágicas de cura;
  2049. #----------------------------------------------------------------------------
  2050. def magicHeal(strengthMagic, magicAttack, level)
  2051. mag = magicAttack.randomic
  2052. lastResult (strengthMagic * random) * (2 + mag * (level + mag) / MAX_VALUE_MAGIC)
  2053. end
  2054. #----------------------------------------------------------------------------
  2055. # • [Formula de EXP] : Gerador de curva de exp.
  2056. # minlv : Level minimo.
  2057. # maxlv : Level máximo.
  2058. # stvalue : Valor inicial.
  2059. # infl : Inflação.
  2060. #----------------------------------------------------------------------------
  2061. def generate_curve_exp(minlv, maxlv, stvalue, infl)
  2062. table = []
  2063. (minlv..maxlv).each { |i| table[i] = (stvalue + (infl + (Random.new.rand(infl..(infl+i)).to_i % i )) * i).to_i.round}
  2064. table
  2065. end
  2066. end
  2067. #==============================================================================
  2068. # • Keyboard | Método para usar todas as teclas do teclado.
  2069. #==============================================================================
  2070. Dax.register(:key, "Dax", 2.0)
  2071. module Key
  2072. #----------------------------------------------------------------------------
  2073. # • Extensão & Variáveis da instância do módulo.
  2074. #----------------------------------------------------------------------------
  2075. extend self
  2076. attr_accessor :_cacheText # Armazena os textos.
  2077. #----------------------------------------------------------------------------
  2078. # • Chaves.
  2079. #----------------------------------------------------------------------------
  2080. KEY = {
  2081. # Chaves diversas.
  2082. CANCEL: 0x03, BACKSPACE: 0x08, TAB: 0x09, CLEAR: 0x0C,
  2083. ENTER: 0x0D, SHIFT: 0x10, CONTROL: 0x11, MENU: 0x12,
  2084. PAUSE: 0x13, ESC: 0x1B, CONVERT: 0x1C, NONCONVERT: 0x1D,
  2085. ACCEPT: 0x1E, SPACE: 0x20, PRIOR: 0x21, NEXT: 0x22,
  2086. ENDS: 0x23, HOME: 0x24, LEFT: 0x25, UP: 0x26, RIGHT: 0x27,
  2087. DOWN: 0x28, SELECT: 0x29, PRINT: 0x2A, EXECUTE: 0x2B,
  2088. SNAPSHOT: 0x2C, DELETE: 0x2E, HELP: 0x2F, LSHIFT: 0xA0, RSHIFT: 0xA1,
  2089. LCONTROL: 0xA2, RCONTROL: 0xA3, LALT: 0xA4, RALT: 0xA5, PACKET: 0xE7,
  2090. # MOUSE
  2091. MOUSE_RIGHT: 0x01, MOUSE_LEFT: 0x02, MOUSE_MIDDLE: 0x04, X1: 0x05, X2: 0x06,
  2092. # Chaves de números.
  2093. N0: 0x30, N1: 0x31, N2: 0x32, N3: 0x33, N4: 0x34, N5: 0x35, N6: 0x36,
  2094. N7: 0x37, N8: 0x38, N9: 0x39,
  2095. # Chaves de letras.
  2096. A: 0x41, B: 0x42, C: 0x43, D: 0x44, E: 0x45,
  2097. F: 0x46, G: 0x47, H: 0x48, I: 0x49, J: 0x4A,
  2098. K: 0x4B, L: 0x4C, M: 0x4D, N: 0x4E, O: 0x4F,
  2099. P: 0x50, Q: 0x51, R: 0x52, S: 0x53, T: 0x54,
  2100. U: 0x55, V: 0x56, W: 0x57, X: 0x58, Y: 0x59,
  2101. Z: 0x5A, Ç: 0xBA,
  2102. # Chaves do window.
  2103. LWIN: 0x5B, RWIN: 0x5C, APPS: 0x5D, SLEEP: 0x5F, BROWSER_BACK: 0xA6,
  2104. BROWSER_FORWARD: 0xA7, BROWSER_REFRESH: 0xA8, BROWSER_STOP: 0xA9,
  2105. BROWSER_SEARCH: 0xAA, BROWSER_FAVORITES: 0xAB, BROWSER_HOME: 0xAC,
  2106. VOLUME_MUTE: 0xAD, VOLUME_DOWN: 0xAE, VOLUME_UP: 0xAF,
  2107. MEDIA_NEXT_TRACK: 0xB0, MEDIA_PREV_TRACK: 0xB1, MEDIA_STOP: 0xB2,
  2108. MEDIA_PLAY_PAUSE: 0xB3, LAUNCH_MAIL: 0xB4, LAUNCH_MEDIA_SELECT: 0xB5,
  2109. LAUNCH_APP1: 0xB6, LAUNCH_APP2: 0xB7, PROCESSKEY: 0xE5, ATIN: 0xF6,
  2110. CRSEL: 0xF7, EXSEL: 0xF8, EREOF: 0xF9, PLAY: 0xFA, ZOOM: 0xFB,
  2111. PA1: 0xFD,
  2112. # Chaves do NUMPAD
  2113. NUMPAD0: 0x60, NUMPAD1: 0x61, NUMPAD2: 0x62,
  2114. NUMPAD3: 0x63, NUMPAD4: 0x64, NUMPAD5: 0x65,
  2115. NUMPAD6: 0x66, NUMPAD7: 0x67, NUMPAD8: 0x68, NUMPAD9: 0x69,
  2116. MULTIPLY: 0x6A, ADD: 0x6B, SEPARATOR: 0x6C,
  2117. SUBTRACT: 0x6D, DECIMAL: 0x6E, DIVIDE: 0x6F,
  2118. # Caches de função.
  2119. F1: 0x70, F2: 0x71, F3: 0x72, F4: 0x73, F5: 0x74, F6: 0x75,
  2120. F7: 0x76, F8: 0x77, F9: 0x78, F10: 0x79, F11: 0x7A, F12: 0x7B,
  2121. F13: 0x7C, F14: 0x7D, F15: 0x7E, F16: 0x7F, F17: 0x80, F18: 0x81,
  2122. F19: 0x82, F20: 0x83, F21: 0x84, F22: 0x85, F23: 0x86, F24: 0x87,
  2123. # Chaves alternativas.
  2124. CAPS: 0x14, INSERT: 0x2D, NUMLOCK: 0x90, SCROLL: 0x91,
  2125. # Chaves OEM, variadas.
  2126. OEM_1: 0xC1, OEM_PLUS: 0xBB, OEM_COMMA: 0xBC,
  2127. OEM_MINUS: 0xBD, OEM_PERIOD: 0xBE,
  2128. OEM_2: 0xBF, QUOTE: 0xC0,
  2129. ACCUTE: 0xDB, OEM_6: 0xDD, OEM_7: 0xDC, TIL: 0xDE,
  2130. OEM_102: 0xE2, OEM_CLEAR: 0xFE,
  2131. }
  2132. #----------------------------------------------------------------------------
  2133. # • Chave dos números. (Símbolos)
  2134. #----------------------------------------------------------------------------
  2135. KEY_NUMBER = %W(NUMPAD0 NUMPAD1 NUMPAD2 NUMPAD3 NUMPAD4 NUMPAD5 NUMPAD6
  2136. NUMPAD7 NUMPAD8 NUMPAD9 N0 N1 N2 N3 N4 N5 N6 N7 N8 N9 MULTIPLY OEM_PERIOD
  2137. OEM_COMMA ADD SEPARATOR DIVIDE SUBTRACT DECIMAL).collect!(&:intern)
  2138. SPECIAL_CHAR_NUMBER = {
  2139. N1: %w(! ¹), N2: %w(@ ²), N3: %w(# ³), N4: %w($ £),
  2140. N5: %w(% ¢), N6: %w(¨ ¬), N7: %w(&), N8: %w(*),
  2141. N9: ["("], N0: [")"], OEM_PERIOD: %w(>), OEM_COMMA: %w(<)
  2142. }
  2143. #----------------------------------------------------------------------------
  2144. # • Chave das letras. (Símbolos)
  2145. #----------------------------------------------------------------------------
  2146. 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)
  2147. KEY_CHAR_ACCUTE = %W(A E I O U Y).collect!(&:intern)
  2148. KEY_CHAR_ACCUTE_STR = {
  2149. UPCASE: {
  2150. A: %w(Â Ã À Á), E: %w(Ê ~E È É), I: %w(Î ~I Ì Í), O: %w(Ô Õ Ò Ó),
  2151. Y: %w(^Y ~Y `Y Ý), U: %w(Û ~U Ù Ú)
  2152. },
  2153. DOWNCASE: {
  2154. A: %w(â ã à á), E: %w(ê ~e è é), I: %w(î ~i ì í), O: %w(ô õ ò ó),
  2155. Y: %w(^y ~y `y ý), U: %w(û ~u ù ú)
  2156. }
  2157. }
  2158. #----------------------------------------------------------------------------
  2159. # • Chaves especiais.
  2160. #----------------------------------------------------------------------------
  2161. KEY_SPECIAL = %w(SPACE OEM_1 OEM_PLUS OEM_MINUS OEM_2
  2162. OEM_6 OEM_7 OEM_102).collect!(&:intern)
  2163. SKEY_SPECIAL = {
  2164. OEM_1: %w(? °), OEM_2: %w(:), OEM_7: %w(} º), OEM_6: %w({ ª),
  2165. OEM_PLUS: %w(+ §), OEM_MINUS: %w(_), OEM_102: %w(|)
  2166. }
  2167. #----------------------------------------------------------------------------
  2168. # • Chaves especiais. [^~ ´` '"]
  2169. #----------------------------------------------------------------------------
  2170. KEY_SPECIAL2 = %w(ACCUTE TIL QUOTE N6).collect!(&:intern)
  2171. #----------------------------------------------------------------------------
  2172. # • Variáveis do módulo.
  2173. #----------------------------------------------------------------------------
  2174. @_cacheText = ""
  2175. @til = 0
  2176. @tils = false
  2177. @accute = 0
  2178. @accutes = false
  2179. @unpack_string = 'b'*256
  2180. @last_array = '0'*256
  2181. @press = Array.new(256, false)
  2182. @trigger = Array.new(256, false)
  2183. @repeat = Array.new(256, false)
  2184. @release = Array.new(256, false)
  2185. @repeat_counter = Array.new(256, 0)
  2186. @getKeyboardState = API::GetKeyboardState
  2187. @getAsyncKeyState = API::GetAsyncKeyState
  2188. @getKeyboardState.call(@last_array)
  2189. @last_array = @last_array.unpack(@unpack_string)
  2190. for i in 0...@last_array.size
  2191. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  2192. end
  2193. #----------------------------------------------------------------------------
  2194. # • Atualização.
  2195. #----------------------------------------------------------------------------
  2196. def update
  2197. @trigger = Array.new(256, false)
  2198. @repeat = Array.new(256, false)
  2199. @release = Array.new(256, false)
  2200. array = '0'*256
  2201. @getKeyboardState.call(array)
  2202. array = array.unpack(@unpack_string)
  2203. for i in 0...array.size
  2204. if array[i] != @last_array[i]
  2205. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  2206. if @repeat_counter[i] <= 0 && @press[i]
  2207. @repeat[i] = true
  2208. @repeat_counter[i] = 15
  2209. end
  2210. if !@press[i]
  2211. @release[i] = true
  2212. else
  2213. @trigger[i] = true
  2214. end
  2215. else
  2216. if @press[i] == true
  2217. @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
  2218. @release[i] = true if !@press[i]
  2219. end
  2220. if @repeat_counter[i] > 0 && @press[i] == true
  2221. @repeat_counter[i] -= 1
  2222. elsif @repeat_counter[i] <= 0 && @press[i] == true
  2223. @repeat[i] = true
  2224. @repeat_counter[i] = 3
  2225. elsif @repeat_counter[i] != 0
  2226. @repeat_counter[i] = 0
  2227. end
  2228. end
  2229. end
  2230. @last_array = array
  2231. end
  2232. #--------------------------------------------------------------------------
  2233. # * [TrueClass/FalseClass] Obter o estado quando a chave for pressionada.
  2234. # key : key index
  2235. #--------------------------------------------------------------------------
  2236. def press?(key)
  2237. return @press[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  2238. end
  2239. #--------------------------------------------------------------------------
  2240. # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada.
  2241. # key : key index
  2242. #--------------------------------------------------------------------------
  2243. def trigger?(key)
  2244. return @trigger[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  2245. end
  2246. #--------------------------------------------------------------------------
  2247. # * [TrueClass/FalseClass] Obter o estado quando a chave for teclada repetidamente.
  2248. # key : key index
  2249. #--------------------------------------------------------------------------
  2250. def repeat?(key)
  2251. return @repeat[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  2252. end
  2253. #--------------------------------------------------------------------------
  2254. # * [TrueClass/FalseClass] Obter o estado quando a chave for "lançada"
  2255. # key : key index
  2256. #--------------------------------------------------------------------------
  2257. def release?(key)
  2258. return @release[ key.is_a?(Symbol) ? KEY.get(key) : key ]
  2259. end
  2260. #----------------------------------------------------------------------------
  2261. # • [String] Obtêm a string correspondente à tecla do número. Às Strings ficará
  2262. # armazenada na varíavel _cacheText
  2263. #----------------------------------------------------------------------------
  2264. def get_number(special=false)
  2265. KEY_NUMBER.each { |key|
  2266. unless special
  2267. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  2268. else
  2269. if shift?
  2270. next @_cacheText += SPECIAL_CHAR_NUMBER[key][0] || "" if trigger?(key)
  2271. elsif ctrl_alt?
  2272. next @_cacheText += SPECIAL_CHAR_NUMBER[key][1] || "" if trigger?(key)
  2273. else
  2274. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  2275. end
  2276. end
  2277. }
  2278. end
  2279. #----------------------------------------------------------------------------
  2280. # • [String] Obtêm a string correspondente à tecla do teclado pressionado.
  2281. # Às Strings ficará armazenada na varíavel _cacheText
  2282. #----------------------------------------------------------------------------
  2283. def get_string(backslash=:trigger)
  2284. get_number(true)
  2285. KEY_CHAR.each { |key|
  2286. next unless trigger?(key)
  2287. x = "".concat(API::MapVirtualKey.call(KEY.get(key), 2))
  2288. if @tils
  2289. n = shift? ? 0 : 1 if @tils
  2290. x = KEY_CHAR_ACCUTE_STR[caps? ? :UPCASE : :DOWNCASE][key][n] || "" if KEY_CHAR_ACCUTE.include?(key) and !n.nil?
  2291. @tils = false
  2292. @accutes = false
  2293. elsif @accutes
  2294. n = shift? ? 2 : 3 if @accutes
  2295. x = KEY_CHAR_ACCUTE_STR[caps? ? :UPCASE : :DOWNCASE][key][n] || "" if KEY_CHAR_ACCUTE.include?(key) and !n.nil?
  2296. @tils = false
  2297. @accutes = false
  2298. end
  2299. @_cacheText += (caps? ? x : x.downcase)
  2300. }
  2301. KEY_SPECIAL.each { |key|
  2302. if shift?
  2303. next @_cacheText += SKEY_SPECIAL[key][0] || "" if trigger?(key)
  2304. elsif ctrl_alt?
  2305. next @_cacheText += SKEY_SPECIAL[key][1] || "" if trigger?(key)
  2306. else
  2307. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if trigger?(key)
  2308. end
  2309. }
  2310. KEY_SPECIAL2.each { |key|
  2311. if trigger?(key)
  2312. if key == :TIL
  2313. @tils = !@tils
  2314. @accutes = false if @tils
  2315. elsif key == :ACCUTE
  2316. @accutes = !@accutes
  2317. @tils = false if @accutes
  2318. end
  2319. @til = @til == 3 ? @til : @til + 1 if key == :TIL
  2320. @accute = @accute == 3 ? @accute : @accute + 1 if key == :ACCUTE
  2321. if shift?
  2322. next @_cacheText += '"' if key == :QUOTE
  2323. next unless @til == 3 or @accute == 3
  2324. @_cacheText += "^" if key == :TIL
  2325. @_cacheText += "`" if key == :ACCUTE
  2326. next @til = 0 if key == :TIL
  2327. next @accute = 0 if key == :ACCUTE
  2328. else
  2329. next @_cacheText.concat(API::MapVirtualKey.call(KEY.get(key), 2)) if key == :QUOTE
  2330. next unless @til == 3 or @accute == 3
  2331. @_cacheText += "~" if key == :TIL
  2332. @_cacheText += "´" if key == :ACCUTE
  2333. next @til = 0 if key == :TIL
  2334. next @accute = 0 if key == :ACCUTE
  2335. end
  2336. end
  2337. }
  2338. if backslash == :press
  2339. @_cacheText = @_cacheText.backslash if press?(:BACKSPACE)
  2340. else
  2341. @_cacheText = @_cacheText.backslash if trigger?(:BACKSPACE)
  2342. end
  2343. @_cacheText += " " * 4 if trigger?(:TAB)
  2344. end
  2345. #----------------------------------------------------------------------------
  2346. # • Verificar se o CAPS LOCK está ativado ou desativado.
  2347. #----------------------------------------------------------------------------
  2348. def caps?
  2349. API.get_caps_lock
  2350. end
  2351. #----------------------------------------------------------------------------
  2352. # • Verificar se o Shift está pressionado
  2353. #----------------------------------------------------------------------------
  2354. def shift?
  2355. press?(:SHIFT)
  2356. end
  2357. #----------------------------------------------------------------------------
  2358. # • Verificar se o CTRL + ALT está pressionado.
  2359. #----------------------------------------------------------------------------
  2360. def ctrl_alt?
  2361. (press?(:LCONTROL) and press?(:LALT)) or press?(:RALT)
  2362. end
  2363. #----------------------------------------------------------------------------
  2364. # • [Boolean] : Retorna true caso alguma tecla foi teclada.
  2365. #----------------------------------------------------------------------------
  2366. def any?
  2367. Key::KEY.each_value { |i|
  2368. next if i == 25
  2369. return true if trigger?(i)
  2370. }
  2371. return false
  2372. end
  2373. #----------------------------------------------------------------------------
  2374. # • Para movimento WSAD
  2375. #----------------------------------------------------------------------------
  2376. def wsad
  2377. return 8 if press?(:W)
  2378. return 4 if press?(:A)
  2379. return 6 if press?(:D)
  2380. return 2 if press?(:S)
  2381. return 0
  2382. end
  2383. end
  2384. #==============================================================================
  2385. # • Sprite
  2386. #==============================================================================
  2387. Dax.register(:sprite)
  2388. class Sprite
  2389. #----------------------------------------------------------------------------
  2390. # • Variáveis públicas da instância.
  2391. #----------------------------------------------------------------------------
  2392. attr_accessor :clone_sprite
  2393. attr_accessor :outline_fill_rect
  2394. #----------------------------------------------------------------------------
  2395. # • Novo método. Modos de usos abaixo:
  2396. # * [normal] : É o método normal, na qual você não define nada. Sprite.new
  2397. # * [viewport] : É o método na qual você define um viewport.
  2398. # Sprite.new(Viewport)
  2399. # * [system] : É o método na qual você já define um bitmap que irá carregar
  2400. # uma imagem já direto da pasta System, através do Cache.
  2401. # Sprite.new("S: Nome do Arquivo")
  2402. # * [picture] : É o método na qual você já define um bitmap que irá carregar
  2403. # uma imagem já direito da pasta Pictures, através do Cache.
  2404. # Sprite.new("P: Nome do Arquivo")
  2405. # * [graphics] : É o método na qual você já define um bitmap com uma imagem
  2406. # que está dentro da pasta Graphics, através do Cache.
  2407. # Sprite.new("G: Nome do Arquivo.")
  2408. # * [width, height] : É o método na qual você já define a largura e altura
  2409. # do bitmap. Sprite.new([width, height])
  2410. # * [elements] : É o método na qual você já define a largura, altura,
  2411. # posição X, posição Y e Prioridade do bitmap.
  2412. # Sprite.new([width, height, x, y, z])
  2413. #----------------------------------------------------------------------------
  2414. alias new_initialize initialize
  2415. def initialize(viewport=nil)
  2416. @clone_sprite = []
  2417. @outline_fill_rect = nil
  2418. if viewport.is_a?(String)
  2419. new_initialize(nil)
  2420. if viewport.match(/S: ([^>]*)/)
  2421. self.bitmap = Cache.system($1.to_s)
  2422. elsif viewport.match(/P: ([^>]*)/)
  2423. self.bitmap = Cache.picture($1.to_s)
  2424. elsif viewport.match(/G: ([^>]*)/)
  2425. self.bitmap = Cache.load_bitmap("Graphics/", $1.to_s)
  2426. else
  2427. self.bitmap = Bitmap.new(viewport)
  2428. end
  2429. elsif viewport.is_a?(Array)
  2430. if viewport.size == 2
  2431. new_initialize(nil)
  2432. self.bitmap = Bitmap.new(viewport[0], viewport[1])
  2433. elsif viewport.size == 5
  2434. new_initialize(nil)
  2435. self.bitmap = Bitmap.new(viewport[0], viewport[1])
  2436. self.x, self.y, self.z = viewport[2], viewport[3], viewport[4]
  2437. end
  2438. elsif viewport.is_a?(Viewport) or viewport.nil?
  2439. new_initialize(viewport)
  2440. end
  2441. end
  2442. #----------------------------------------------------------------------------
  2443. # • Renovação do Sprite.
  2444. #----------------------------------------------------------------------------
  2445. alias :dax_core_dispose :dispose
  2446. def dispose
  2447. dax_core_dispose
  2448. @outline_fill_rect.dispose unless @outline_fill_rect.nil? or @outline_fill_rect.disposed?
  2449. end
  2450. #----------------------------------------------------------------------------
  2451. # • Definir um contorno no Sprite em forma de retângulo.
  2452. # color : Cor do contorno.
  2453. # size : Tamanho da linha do contorno.
  2454. # vis : Visibilidade. true - visível | false - invisível.
  2455. #----------------------------------------------------------------------------
  2456. def set_outline(color=Color.new.default, size=2, vis=true)
  2457. @outline_fill_rect = Sprite.new([self.width, self.height, self.x, self.y, self.z+2])
  2458. @outline_fill_rect.bitmap.fill_rect(0, 0, self.width, size, color)
  2459. @outline_fill_rect.bitmap.fill_rect(0, self.height-size, self.width, size, color)
  2460. @outline_fill_rect.bitmap.fill_rect(0, 0, size, self.height, color)
  2461. @outline_fill_rect.bitmap.fill_rect(self.width-size, 0, size, self.height, color)
  2462. @outline_fill_rect.visible = vis
  2463. end
  2464. #----------------------------------------------------------------------------
  2465. # • Atualização do contorno.
  2466. # vis : Visibilidade. true - visível | false - invisível.
  2467. #----------------------------------------------------------------------------
  2468. def update_outline(vis=true)
  2469. @outline_fill_rect.visible = vis
  2470. @outline_fill_rect.x, @outline_fill_rect.y = self.x, self.y
  2471. end
  2472. #----------------------------------------------------------------------------
  2473. # • Slide pela direita.
  2474. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  2475. #----------------------------------------------------------------------------
  2476. def slide_right(speed, point)
  2477. self.x += speed unless self.x >= point
  2478. end
  2479. #----------------------------------------------------------------------------
  2480. # • Slide pela esquerda.
  2481. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  2482. #----------------------------------------------------------------------------
  2483. def slide_left(speed, point)
  2484. self.x -= speed unless self.x <= point
  2485. end
  2486. #----------------------------------------------------------------------------
  2487. # • Slide por cima.
  2488. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  2489. #----------------------------------------------------------------------------
  2490. def slide_up(speed, point)
  2491. self.y -= speed unless self.y <= point
  2492. end
  2493. #----------------------------------------------------------------------------
  2494. # • Slide por baixo.
  2495. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  2496. #----------------------------------------------------------------------------
  2497. def slide_down(speed, point)
  2498. self.y += speed unless self.y >= point
  2499. end
  2500. #----------------------------------------------------------------------------
  2501. # • Define aqui uma posição fixa para um objeto.
  2502. # command : Veja na classe Position.
  2503. #----------------------------------------------------------------------------
  2504. def position(command=0)
  2505. return if command.nil?
  2506. Position[command, self]
  2507. end
  2508. #----------------------------------------------------------------------------
  2509. # • [Numeric] : Tamanho geral
  2510. #----------------------------------------------------------------------------
  2511. def size
  2512. return self.width + self.height
  2513. end
  2514. #----------------------------------------------------------------------------
  2515. # • [Rect] : Retorna ao Rect do Bitmap.
  2516. #----------------------------------------------------------------------------
  2517. def rect
  2518. return self.bitmap.rect
  2519. end
  2520. #----------------------------------------------------------------------------
  2521. # • Base para clonar um Sprite.
  2522. # * depht : Prioridade no mapa.
  2523. # * clone_bitmap : Se irá clonar o bitmap.
  2524. # Exemplo: sprite = sprite2.clone
  2525. #----------------------------------------------------------------------------
  2526. def clone(depht=0, clone_bitmap=false)
  2527. @clone_sprite.delete_if { |bitmap| bitmap.disposed? }
  2528. cloned = Sprite.new(self.viewport)
  2529. cloned.x, cloned.y = self.x, self.y
  2530. cloned.bitmap = self.bitmap
  2531. cloned.bitmap = self.bitmap.clone if clone_bitmap
  2532. unless depht == 0
  2533. cloned.z = self.z + depht
  2534. else
  2535. @clone_sprite.each { |sprite| sprite.z -= 1 }
  2536. cloned.z = self.z - 1
  2537. end
  2538. cloned.src_rect.set(self.src_rect)
  2539. ["zoom_x", "zoom_y", "angle", "mirror", "opacity", "blend_type", "visible",
  2540. "ox", "oy"].each { |meth|
  2541. eval("cloned.#{meth} = self.#{meth}")
  2542. }
  2543. cloned.color.set(color)
  2544. cloned.tone.set(tone)
  2545. after_clone(cloned)
  2546. @clone_sprite.push(cloned)
  2547. return cloned
  2548. end
  2549. #----------------------------------------------------------------------------
  2550. # • Efeito após ter clonado o Sprite.
  2551. #----------------------------------------------------------------------------
  2552. def after_clone(clone)
  2553. end
  2554. #----------------------------------------------------------------------------
  2555. # • O que irá acontecer sê o mouse estiver em cima do sprite?
  2556. #----------------------------------------------------------------------------
  2557. def mouse_over
  2558. end
  2559. #----------------------------------------------------------------------------
  2560. # • O que irá acontecer sê o mouse não estiver em cima do sprite?
  2561. #----------------------------------------------------------------------------
  2562. def mouse_no_over
  2563. end
  2564. #----------------------------------------------------------------------------
  2565. # • O que irá acontecer sê o mouse clicar no objeto
  2566. #----------------------------------------------------------------------------
  2567. def mouse_click
  2568. end
  2569. #----------------------------------------------------------------------------
  2570. # • Atualização dos sprites.
  2571. #----------------------------------------------------------------------------
  2572. alias :dax_update :update
  2573. def update(*args, &block)
  2574. dax_update(*args, &block)
  2575. unless Mouse.cursor.nil?
  2576. self.if_mouse_over { |over| over ? mouse_over : mouse_no_over }
  2577. self.if_mouse_click { mouse_click }
  2578. end
  2579. end
  2580. #----------------------------------------------------------------------------
  2581. # • Inverter o lado do sprite.
  2582. #----------------------------------------------------------------------------
  2583. def mirror!
  2584. self.mirror = !self.mirror
  2585. end
  2586. #----------------------------------------------------------------------------
  2587. # • Inverter o ângulo do sprite em 180°(Pode ser mudado.).
  2588. #----------------------------------------------------------------------------
  2589. def angle!(ang=180)
  2590. self.ox, self.oy = self.bitmap.width, self.bitmap.height
  2591. self.angle += ang
  2592. self.angle += 360 while self.angle < 0
  2593. self.angle %= 360
  2594. end
  2595. end
  2596. #==============================================================================
  2597. # • Bitmap
  2598. #==============================================================================
  2599. Dax.register(:bitmap)
  2600. class Bitmap
  2601. #--------------------------------------------------------------------------
  2602. # • Constantes.
  2603. #--------------------------------------------------------------------------
  2604. Directory = 'Data/Bitmaps/'
  2605. #--------------------------------------------------------------------------
  2606. # • Salvar as informações do bitmap em um arquivo.
  2607. #--------------------------------------------------------------------------
  2608. def self.saveInfo(bitmap, filename)
  2609. return unless bitmap.is_a?(Bitmap)
  2610. red = Table.new(bitmap.width, bitmap.height)
  2611. green = Table.new(bitmap.width, bitmap.height)
  2612. blue = Table.new(bitmap.width, bitmap.height)
  2613. alpha = Table.new(bitmap.width, bitmap.height)
  2614. bitmap.rect.step(1, 1) { |i, j|
  2615. color = bitmap.get_pixel(i, j)
  2616. red[i, j] = color.red
  2617. green[i, j] = color.green
  2618. blue[i, j] = color.blue
  2619. alpha[i, j] = color.alpha
  2620. }
  2621. Dir.mkdir(Directory) unless File.directory?(Directory)
  2622. file = File.open(Directory + filename + '.rvdata2', 'wb')
  2623. Marshal.dump([red, green, blue, alpha], file)
  2624. file.close
  2625. p "ok"
  2626. end
  2627. #--------------------------------------------------------------------------
  2628. # * Abrir o arquivo.
  2629. #--------------------------------------------------------------------------
  2630. def self.readInfo(filename)
  2631. return unless FileTest.exist?(Directory + filename + '.rvdata2')
  2632. file = File.open(Directory + filename + '.rvdata2', "rb")
  2633. colors = Marshal.load(file).compact
  2634. file.close
  2635. red, green, blue, alpha = *colors
  2636. bitmap = Bitmap.new(red.xsize, red.ysize)
  2637. for i in 0...bitmap.width
  2638. for j in 0...bitmap.height
  2639. bitmap.set_pixel(i, j, Color.new(red[i, j], green[i, j], blue[i, j], alpha[i, j]))
  2640. end
  2641. end
  2642. return bitmap
  2643. end
  2644. #----------------------------------------------------------------------------
  2645. # • Modifica o sprite para ficar do tamanho definido.
  2646. #----------------------------------------------------------------------------
  2647. def resize(width=Graphics.width, height=Graphics.height)
  2648. self.stretch_blt(Rect.new(0, 0, width, height), self, self.rect)
  2649. end
  2650. #----------------------------------------------------------------------------
  2651. # • Criar uma barra.
  2652. # color : Objeto de Cor [Color]
  2653. # actual : Valor atual da barra.
  2654. # max : Valor máximo da barra.
  2655. # borda : Tamanho da borda da barra.
  2656. #----------------------------------------------------------------------------
  2657. def bar(color, actual, max, borda=1)
  2658. rate = self.width.to_p(actual, max)
  2659. self.fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  2660. color)
  2661. end
  2662. #----------------------------------------------------------------------------
  2663. # • Barra em forma de gradient.
  2664. # color : Objeto de Cor, em forma de [Array] para conter 2 [Color]
  2665. # exemplo -> [Color.new(x), Color.new(y)]
  2666. # actual : Valor atual da barra.
  2667. # max : Valor máximo da barra.
  2668. # borda : Tamanho da borda da barra.
  2669. #----------------------------------------------------------------------------
  2670. def gradient_bar(color, actual, max, borda=1)
  2671. rate = self.width.to_p(actual, max)
  2672. self.gradient_fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
  2673. color[0], color[1], 2)
  2674. end
  2675. #----------------------------------------------------------------------------
  2676. # • Limpar uma área num formato de um círculo.
  2677. #----------------------------------------------------------------------------
  2678. def clear_rect_circle(x, y, r)
  2679. rr = r*r
  2680. for i in 0...r
  2681. adj = Math.sqrt(rr - (i*i)).ceil
  2682. xd = x - adj
  2683. wd = 2 * adj
  2684. self.clear_rect(xd, y-i, wd, 1)
  2685. self.clear_rect(xd, y+i, wd, 1)
  2686. end
  2687. end
  2688. #----------------------------------------------------------------------------
  2689. # • Novo modo de desenhar textos. Configurações já especificadas.
  2690. #----------------------------------------------------------------------------
  2691. def draw_text_rect(*args)
  2692. self.draw_text(self.rect, *args)
  2693. end
  2694. #----------------------------------------------------------------------------
  2695. # • Salvar em png.
  2696. # --- Autor : Gab! ---
  2697. #----------------------------------------------------------------------------
  2698. def save(file_name)
  2699. def chunk(type, data)
  2700. [data.size, type, data, Zlib.crc32(type + data)].pack("NA4A*N")
  2701. end
  2702. img_data = ""
  2703. width, height = self.width, self.height
  2704. for j in 0...(height)
  2705. img_data << "\0"
  2706. for i in 0...(width)
  2707. pos_c = self.get_pixel(i, j)
  2708. img_data << [pos_c.red, pos_c.green, pos_c.blue, pos_c.alpha].pack("C*")
  2709. end
  2710. end
  2711. c = [
  2712. "\x89PNG\r\n\x1a\n",
  2713. chunk("IHDR", [width, height, 8, 6, 0, 0, 0].pack("N2C5")),
  2714. chunk("IDAT", Zlib::Deflate.deflate(img_data)),
  2715. chunk("IEND", "")
  2716. ]
  2717. File.open(file_name << ".png", "wb"){|file| c.each{|chunk| file.write(chunk) }}
  2718. end
  2719. #----------------------------------------------------------------------------
  2720. # • Permite salvar várias imagens em cima de outra.
  2721. # Exemplo de comando:
  2722. # Bitmap.overSave("Pictures/Nova", "Pictures/1", "Characters/2",
  2723. # "Pictures/3", "Characters/4", "Pictures/5")
  2724. # NÃO ESQUEÇA DE ESPECIFICAR ÀS PASTAS.
  2725. #----------------------------------------------------------------------------
  2726. def self.overSave(newfile, first, *args)
  2727. return if first.empty? || first.nil? || args.empty? || args.nil?
  2728. firstB = Bitmap.new("Graphics/"+first)
  2729. args.each { |outhers|
  2730. firstB.stretch_blt(firstB.rect, Bitmap.new("Graphics/"+outhers), firstB.rect)
  2731. }
  2732. firstB.save("Graphics/"+newfile)
  2733. end
  2734. #----------------------------------------------------------------------------
  2735. # • Modificar as cores do [Bitmap] para ficarem Negativas.
  2736. #----------------------------------------------------------------------------
  2737. def negative
  2738. self.rect.step(1.0, 1.0) { |i, j|
  2739. pix = self.get_pixel(i, j)
  2740. pix.red = (pix.red - 255) * -1
  2741. pix.blue = (pix.blue - 255) * -1
  2742. pix.green = (pix.green - 255) * -1
  2743. self.set_pixel(i, j, pix)
  2744. }
  2745. end
  2746. #----------------------------------------------------------------------------
  2747. # • Grayscale : Modificar as cores do [Bitmap] para cor cinza. Efeito cinza.
  2748. #----------------------------------------------------------------------------
  2749. def grayscale(rect = Rect.new(0, 0, self.width, self.height))
  2750. self.rect.step(1, 1) { |i, j|
  2751. colour = self.get_pixel(i,j)
  2752. grey_pixel = (colour.red*0.3 + colour.green*0.59 + colour.blue*0.11)
  2753. colour.red = colour.green = colour.blue = grey_pixel
  2754. self.set_pixel(i,j,colour)
  2755. }
  2756. end
  2757. #----------------------------------------------------------------------------
  2758. # • Converter as cores para sepia.
  2759. #----------------------------------------------------------------------------
  2760. def sepia2
  2761. self.rect.step(1, 1) { |w, h|
  2762. nrow = row = get_pixel(w, h)
  2763. row.red = [(0.393 * nrow.red) + (0.769 * nrow.green) + (0.189 * nrow.blue), 255].min
  2764. row.green = [(0.349 * nrow.red) + (0.689 * nrow.green) + (0.168 * nrow.blue), 255].min
  2765. row.blue = [(0.272 * nrow.red) + (0.534 * nrow.green) + (0.131 * nrow.blue), 255].min
  2766. set_pixel(w, h, row)
  2767. }
  2768. end
  2769. #----------------------------------------------------------------------------
  2770. # • Suavidade nas cores do bitmap. Converte as cores em preto e branco.
  2771. # crlz : Controle da iluminidade.
  2772. #----------------------------------------------------------------------------
  2773. def black_whiteness(ctlz=2.0)
  2774. self.rect.step(1, 1) { |w, h|
  2775. row = get_pixel(w, h)
  2776. getArray__row = row.to_a(false)
  2777. lightCalc_ = (getArray__row.max + getArray__row.min) / ctlz
  2778. row.red = row.green = row.blue = lightCalc_
  2779. set_pixel(w, h, row)
  2780. }
  2781. end
  2782. #----------------------------------------------------------------------------
  2783. # • Novo fornecedor de pixel.
  2784. #----------------------------------------------------------------------------
  2785. def set_pixel_s(x, y, color, size)
  2786. for i in 0...size
  2787. self.set_pixel(x+i, y, color)
  2788. self.set_pixel(x-i, y, color)
  2789. self.set_pixel(x, y+i, color)
  2790. self.set_pixel(x, y-i, color)
  2791. self.set_pixel(x+i, y+i, color)
  2792. self.set_pixel(x-i, y-i, color)
  2793. self.set_pixel(x+i, y-i, color)
  2794. self.set_pixel(x-i, y+i, color)
  2795. end
  2796. end
  2797. #----------------------------------------------------------------------------
  2798. # • Desenhar uma linha.
  2799. # start_x : Início da linha em X.
  2800. # start_y : Início da linha em Y.
  2801. # end_x : Finalização da linha em X.
  2802. # end_y : Finalização da linha em Y.
  2803. #----------------------------------------------------------------------------
  2804. def draw_line(start_x, start_y, end_x, end_y, color, size=1)
  2805. set_pixel_s(start_x, start_y, color, size)
  2806. distance = (start_x - end_x).abs + (start_y - end_y).abs
  2807. for i in 1..distance
  2808. x = (start_x + 1.0 * (end_x - start_x) * i / distance).to_i
  2809. y = (start_y + 1.0 * (end_y - start_y) * i / distance).to_i
  2810. set_pixel_s(x, y, color, size)
  2811. end
  2812. set_pixel_s(end_x, end_y, color, size)
  2813. end
  2814. #----------------------------------------------------------------------------
  2815. # • draw_bar_gauge(x, y, current, current_max, border, colors)
  2816. # x : Coordenadas X.
  2817. # y : Coordenadas Y.
  2818. # current : Valor atual da barra.
  2819. # current_max : Valor maxímo da barra.
  2820. # border : Expressura da borda.
  2821. # colors : Cores. [0, 1]
  2822. #----------------------------------------------------------------------------
  2823. # Permite adicionar uma barra.
  2824. #----------------------------------------------------------------------------
  2825. def draw_bar_gauge(x, y, current, current_max, colors=[])
  2826. cw = self.width.to_p(current, current_max)
  2827. ch = self.height
  2828. self.gradient_fill_rect(x, y, self.width, self.height, colors[0], colors[1])
  2829. src_rect = Rect.new(0, 0, cw, ch)
  2830. self.blt(x, y, self, src_rect)
  2831. end
  2832. #----------------------------------------------------------------------------
  2833. # • draw_icon(icon_index, x, y, enabled)
  2834. # icon_index : ID do ícone.
  2835. # x : Coordenadas X.
  2836. # y : Coordenadas Y.
  2837. # enabled : Habilitar flag, translucido quando false
  2838. # filename : Podes definir uma imagem: Basta
  2839. # por o nome da imagem, ela deve estar na pasta System.
  2840. #----------------------------------------------------------------------------
  2841. def draw_icon(icon_index, x, y, enabled = true, filename="IconSet")
  2842. icon_index = icon_index.nil? ? 0 : icon_index
  2843. bitmap = Cache.system(filename)
  2844. rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
  2845. self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
  2846. end
  2847. #----------------------------------------------------------------------------
  2848. # • draw_gradation_gauge(x, y, width, height, current, current_max, border, colors, align)
  2849. # x : Coordenadas X.
  2850. # y : Coordenadas Y.
  2851. # width : Largura da barra.
  2852. # height : Altura da barra.
  2853. # current : Valor atual da barra.
  2854. # current_max : Valor maxímo da barra.
  2855. # border : Expressura da borda.
  2856. # colors : Cores. [0, 1]
  2857. # align : Alinhamento.
  2858. #----------------------------------------------------------------------------
  2859. # Permite adicionar uma barra.
  2860. #----------------------------------------------------------------------------
  2861. def draw_gradation_gauge(x, y, current, current_max, border, colors=[])
  2862. cw = self.width.to_p(current, current_max)
  2863. ch = self.height
  2864. self.fill_rect(x, y, self.width, self.height, colors[0])
  2865. self.gradient_fill_rect(x+border, y+border, self.width-(border/2), self.height-(border/2), colors[1], colors[2])
  2866. src_rect = Rect.new(0, 0, cw, ch)
  2867. self.blt(x, y, self, src_rect)
  2868. end
  2869. #----------------------------------------------------------------------------
  2870. # • Desenhar um círuclo preenchido.
  2871. #----------------------------------------------------------------------------
  2872. def fill_circle(x, y, r, c)
  2873. rr = r*r
  2874. for i in 0...r
  2875. adj = Math.sqrt(rr - (i*i)).ceil
  2876. xd = x - adj
  2877. wd = 2 * adj
  2878. self.fill_rect(xd, y-i, wd, 1, c)
  2879. self.fill_rect(xd, y+i, wd, 1, c)
  2880. end
  2881. end
  2882. #----------------------------------------------------------------------------
  2883. # • [Brilho] : Aumentar/Diminuir o brilho do sprite.
  2884. #----------------------------------------------------------------------------
  2885. def brightness(vl = 100)
  2886. self.rect.step(1.0, 1.0) { |i, j|
  2887. pix = self.get_pixel(i, j)
  2888. pix = pix.percent(vl)
  2889. self.set_pixel(i, j, pix)
  2890. }
  2891. end
  2892. end
  2893. #==============================================================================
  2894. # • Mouse
  2895. #==============================================================================
  2896. Dax.register(:mouse)
  2897. module Mouse
  2898. extend self
  2899. #--------------------------------------------------------------------------
  2900. # • Inicialização dos objetos.
  2901. #--------------------------------------------------------------------------
  2902. def start
  2903. @cursor = Sprite_Mouse.new(Dax::Mouse_Name, -128, -128, 100000)
  2904. @graphic = Dax::Mouse_Name
  2905. x = Dax::Mouse_Name == "" ? 1 : 0
  2906. API::MouseShowCursor.call(x)
  2907. @visible = true
  2908. end
  2909. #----------------------------------------------------------------------------
  2910. # • visible = (boolean)
  2911. # * boolean : true ou false
  2912. # Tornar vísivel ou não o cursor do Mouse.
  2913. #----------------------------------------------------------------------------
  2914. def visible=(boolean)
  2915. @visible = boolean
  2916. end
  2917. #--------------------------------------------------------------------------
  2918. # • graphic(graphic_set)
  2919. # graphic_set : Se for número é um ícone; Se for string é uma imagem.
  2920. #--------------------------------------------------------------------------
  2921. def graphic(graphic_set)
  2922. visible = false
  2923. @graphic = graphic_set
  2924. @cursor.set_graphic = graphic_set
  2925. end
  2926. #--------------------------------------------------------------------------
  2927. # • show(visible)
  2928. # visible : True - para mostrar o mouse | False - para esconder o mouse.
  2929. #--------------------------------------------------------------------------
  2930. def show(vis=true)
  2931. @cursor.visible = vis
  2932. end
  2933. #--------------------------------------------------------------------------
  2934. # • update (Atualização das coordenadas)
  2935. #--------------------------------------------------------------------------
  2936. def update
  2937. return if @cursor.nil?
  2938. API::MouseShowCursor.call(@visible.boolean)
  2939. if @cursor.disposed?
  2940. @cursor = Sprite_Mouse.new(@graphic, 0, 0, 100000)
  2941. end
  2942. @cursor.update
  2943. @cursor.x, @cursor.y = position
  2944. end
  2945. #--------------------------------------------------------------------------
  2946. # • Retorna a variável '@cursor' que tem como valor a classe [Sprite].
  2947. #--------------------------------------------------------------------------
  2948. def cursor
  2949. @cursor
  2950. end
  2951. #--------------------------------------------------------------------------
  2952. # • Clear.
  2953. #--------------------------------------------------------------------------
  2954. def clear
  2955. @cursor.dispose
  2956. end
  2957. #--------------------------------------------------------------------------
  2958. # • x (Coordenada X do Mouse)
  2959. #--------------------------------------------------------------------------
  2960. def x
  2961. @cursor.x
  2962. end
  2963. #--------------------------------------------------------------------------
  2964. # • y (Coordenada Y do Mouse)
  2965. #--------------------------------------------------------------------------
  2966. def y
  2967. @cursor.y
  2968. end
  2969. #--------------------------------------------------------------------------
  2970. # • position (Posição do Mouse!)
  2971. #--------------------------------------------------------------------------
  2972. def position
  2973. x, y = get_client_position
  2974. return x, y
  2975. end
  2976. #--------------------------------------------------------------------------
  2977. # • Grid do mapa.
  2978. #--------------------------------------------------------------------------
  2979. def map_grid
  2980. return unless defined?($game_map)
  2981. return nil if x == nil or y == nil
  2982. rx = ($game_map.display_x).to_i + (x / 32)
  2983. ry = ($game_map.display_y).to_i + (y / 32)
  2984. return [rx.to_i, ry.to_i]
  2985. end
  2986. #--------------------------------------------------------------------------
  2987. # • get_client_position (Posição original do Mouse!)
  2988. #--------------------------------------------------------------------------
  2989. def get_client_position
  2990. pos = [0, 0].pack('ll')
  2991. API::CursorPosition.call(pos)
  2992. API::ScreenToClient.call(WINDOW, pos)
  2993. return pos.unpack('ll')
  2994. end
  2995. #--------------------------------------------------------------------------
  2996. # • Verificação se o mouse está na área de um determinado objeto.
  2997. #--------------------------------------------------------------------------
  2998. def in_area?(x)
  2999. return if @cursor.disposed?
  3000. return unless x.is_a?(Sprite) or x.is_a?(Window)
  3001. #return @cursor.x.between?(object_sprite.x, object_sprite.x + object_sprite.width) &&
  3002. # @cursor.y.between?(object_sprite.y, object_sprite.y + object_sprite.height)
  3003. @cursor.x.between?(x.x, (x.x - x.ox + (x.viewport ? x.viewport.rect.x : 0)) + x.width) &&
  3004. @cursor.y.between?(x.y, (x.y - x.oy + (x.viewport ? x.viewport.rect.y : 0)) + x.height)
  3005. end
  3006. #----------------------------------------------------------------------------
  3007. # • Verificar se o mouse está em determinada área
  3008. #----------------------------------------------------------------------------
  3009. def area?(x, y, width, height)
  3010. return @cursor.x.between?(x, x + width) &&
  3011. @cursor.y.between?(y, y + height)
  3012. end
  3013. #----------------------------------------------------------------------------
  3014. # • Mudar posição do cursor.
  3015. #----------------------------------------------------------------------------
  3016. def set_mouse(pos)
  3017. SetCursorPos.call(pos.x, pos.y)
  3018. update
  3019. @cursor.x = @pos.x
  3020. @cursor.y = @pos.y
  3021. end
  3022. #----------------------------------------------------------------------------
  3023. # • Verifica se clicou com o botão esquerdo do Mouse.
  3024. #----------------------------------------------------------------------------
  3025. def left?
  3026. return Key.trigger?(0x01)
  3027. end
  3028. #----------------------------------------------------------------------------
  3029. # • Verifica se clicou com o botão direito do Mouse.
  3030. #----------------------------------------------------------------------------
  3031. def right?
  3032. return Key.trigger?(0x02)
  3033. end
  3034. WINDOW = API.hWND
  3035. end
  3036. #==============================================================================
  3037. # • Sprite_Mouse
  3038. #==============================================================================
  3039. Dax.register(:sprite_mouse)
  3040. class Sprite_Mouse < Sprite
  3041. #----------------------------------------------------------------------------
  3042. # • Variáveis públicas da instância.
  3043. #----------------------------------------------------------------------------
  3044. attr_accessor :set_graphic # definir o gráfico.
  3045. #----------------------------------------------------------------------------
  3046. # • Inicialização dos objetos.
  3047. #----------------------------------------------------------------------------
  3048. def initialize(graphic, x, y, z)
  3049. super(nil)
  3050. @set_graphic = graphic
  3051. if @set_graphic.is_a?(Fixnum)
  3052. self.bitmap = Bitmap.new(24, 24)
  3053. self.bitmap.draw_icon(@set_graphic, 0, 0)
  3054. elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  3055. self.bitmap = Bitmap.new(1, 1)
  3056. elsif @set_graphic.is_a?(String)
  3057. self.bitmap = Cache.system(@set_graphic)
  3058. end
  3059. self.x, self.y, self.z = x, y, z
  3060. @older = @set_graphic
  3061. end
  3062. #----------------------------------------------------------------------------
  3063. # • Renovação dos objetos.
  3064. #----------------------------------------------------------------------------
  3065. def dispose
  3066. self.bitmap.dispose
  3067. super
  3068. end
  3069. #----------------------------------------------------------------------------
  3070. # • Atualização dos objetos.
  3071. #----------------------------------------------------------------------------
  3072. def update
  3073. super
  3074. unless @older == @set_graphic
  3075. if @set_graphic.is_a?(Fixnum)
  3076. self.bitmap = Bitmap.new(24, 24)
  3077. self.bitmap.draw_icon(@set_graphic, 0, 0)
  3078. elsif @set_graphic.is_a?(NilClass) or @set_graphic == ""
  3079. self.bitmap = Bitmap.new(1, 1)
  3080. elsif @set_graphic.is_a?(String)
  3081. self.bitmap = Cache.system(@set_graphic)
  3082. end
  3083. @older = @set_graphic
  3084. end
  3085. end
  3086. end
  3087. Mouse.start
  3088. #==============================================================================
  3089. # • Object
  3090. #==============================================================================
  3091. Dax.register(:object)
  3092. class Object
  3093. #----------------------------------------------------------------------------
  3094. # • Carregar arquivo de script.
  3095. #----------------------------------------------------------------------------
  3096. def load_script(filename)
  3097. File.eval(filename)
  3098. #eval(load_data(filename))
  3099. end
  3100. #----------------------------------------------------------------------------
  3101. # • [Hex] : Retorna ao id do objeto em hexadécimal.
  3102. #----------------------------------------------------------------------------
  3103. def __hexid__
  3104. "0x" + ('%.X' % (self.__id__ * 2))
  3105. end
  3106. #----------------------------------------------------------------------------
  3107. # • O que irá ocorrer caso o mouse esteja sobre uma sprite.
  3108. # Tem que ser um objeto Sprite.
  3109. #----------------------------------------------------------------------------
  3110. def if_mouse_over(&block)
  3111. return if Mouse.cursor.nil?
  3112. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  3113. over ||= false
  3114. if Mouse.in_area?(self)
  3115. block.call
  3116. over = true
  3117. else
  3118. over = false
  3119. end
  3120. yield over
  3121. end
  3122. #----------------------------------------------------------------------------
  3123. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao clicar.
  3124. # Tem que ser um objeto Sprite.
  3125. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  3126. # EXPLICAÇÕES NO FINAL DO SCRIPT.
  3127. #----------------------------------------------------------------------------
  3128. def if_mouse_click(button=:left, &block)
  3129. return if Mouse.cursor.nil?
  3130. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  3131. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  3132. block.call if Mouse.in_area?(self) and trigger?(button)
  3133. end
  3134. #----------------------------------------------------------------------------
  3135. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao pressionar.
  3136. # Tem que ser um objeto Sprite.
  3137. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  3138. #----------------------------------------------------------------------------
  3139. def if_mouse_press(button=:left, &block)
  3140. return if Mouse.cursor.nil?
  3141. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  3142. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  3143. block.call if Mouse.in_area?(self) and press?(button)
  3144. end
  3145. #----------------------------------------------------------------------------
  3146. # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao ficar clicando.
  3147. # Tem que ser um objeto Sprite.
  3148. # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
  3149. #----------------------------------------------------------------------------
  3150. def if_mouse_repeat(button=:left, &block)
  3151. return if Mouse.cursor.nil?
  3152. return unless self.is_a?(Sprite) or self.is_a?(Window_Base) or block_given?
  3153. button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
  3154. block.call if Mouse.in_area?(self) and repeat?(button)
  3155. end
  3156. #----------------------------------------------------------------------------
  3157. # • Trigger
  3158. # * key : Chave.
  3159. # Você também pode usá-lo como condição para executar tal bloco;
  3160. #----------------------------------------------------------------------------
  3161. # trigger?(key) { bloco que irá executar }
  3162. #----------------------------------------------------------------------------
  3163. def trigger?(key, &block)
  3164. if key == :C or key == :B
  3165. ckey = Input.trigger?(key)
  3166. else
  3167. ckey = Key.trigger?(key)
  3168. end
  3169. return ckey unless block_given?
  3170. block.call if ckey
  3171. end
  3172. #----------------------------------------------------------------------------
  3173. # • Press
  3174. # * key : Chave.
  3175. # Você também pode usá-lo como condição para executar tal bloco;
  3176. #----------------------------------------------------------------------------
  3177. # press?(key) { bloco que irá executar. }
  3178. #----------------------------------------------------------------------------
  3179. def press?(key, &block)
  3180. if key == :C or key == :B
  3181. ckey = Input.press?(key)
  3182. else
  3183. ckey = Key.press?(key)
  3184. end
  3185. return ckey unless block_given?
  3186. block.call if ckey
  3187. end
  3188. #----------------------------------------------------------------------------
  3189. # • Repeat
  3190. # * key : Chave.
  3191. # Você também pode usá-lo como condição para executar tal bloco;
  3192. #----------------------------------------------------------------------------
  3193. # repeat?(key) { bloco que irá executar. }
  3194. #----------------------------------------------------------------------------
  3195. def repeat?(key, &block)
  3196. if key == :C or key == :B
  3197. ckey = Input.repeat?(key)
  3198. else
  3199. ckey = Key.repeat?(key)
  3200. end
  3201. return ckey unless block_given?
  3202. block.call if ckey
  3203. end
  3204. #----------------------------------------------------------------------------
  3205. # • Retorna em forma de número os valores true ou false. E caso seja
  3206. # 0 ou 1.. retorna a true ou false.
  3207. # Se for true, retorna a 1.
  3208. # Se for false, retorna a 0.
  3209. # Se for 1, retorna a true.
  3210. # Se for 0, retorna a false.
  3211. #----------------------------------------------------------------------------
  3212. def boolean
  3213. return self.is_a?(Integer) ? self == 0 ? false : 1 : self ? 1 : 0
  3214. end
  3215. #----------------------------------------------------------------------------
  3216. # • Converte para a classe Position.
  3217. #----------------------------------------------------------------------------
  3218. def position
  3219. return Position.new(self, self) if self.is_a?(Numeric)
  3220. return Position.new(self.x, self.y) if self.is_a?(Sprite) or self.is_a?(Window_Base) or self.is_a?(Rect)
  3221. return Position.new(self[0], self[1]) if self.is_a?(Array)
  3222. return Position.new(self[:x], self[:y]) if self.is_a?(Hash)
  3223. return Position.new(0, 0)
  3224. end
  3225. #----------------------------------------------------------------------------
  3226. # • Transforma em cor.
  3227. # Se for uma Array. Exemplo: [128, 174, 111].color =># Color.new(128, 174, 111)
  3228. # Se for uma String. Exemplo: "ffffff".color =># Color.new(255,255,255)
  3229. #----------------------------------------------------------------------------
  3230. def color
  3231. return Color.new(*self) if self.is_a?(Array)
  3232. return Color.new.hex(self) if self.is_a?(String)
  3233. end
  3234. end
  3235. #==============================================================================
  3236. # • Entries
  3237. #==============================================================================
  3238. Dax.register(:entries)
  3239. class Entries
  3240. #----------------------------------------------------------------------------
  3241. # • [Array] : Irá retornar a todos os nomes dos arquivos da pasta, dentro de
  3242. # uma Array em formato de String.
  3243. #----------------------------------------------------------------------------
  3244. attr_accessor :file
  3245. #----------------------------------------------------------------------------
  3246. # • [Integer] : Retorna a quantidade total de arquivos que têm na pasta.
  3247. #----------------------------------------------------------------------------
  3248. attr_reader :size
  3249. #----------------------------------------------------------------------------
  3250. # • Inicialização dos objetos.
  3251. # directory : Nome da pasta. Não ponha '/' no final do nome. Ex: 'Data/'
  3252. # typefile : Nome da extensão do arquivo. Não ponha '.' no começo. Ex: '.txt'
  3253. #----------------------------------------------------------------------------
  3254. def initialize(directory, typefile)
  3255. return unless FileTest.directory?(directory)
  3256. @file = Dir.glob(directory + "/*.{" + typefile + "}")
  3257. @file.each_index { |i| @size = i.to_i }
  3258. @name = split @file[0]
  3259. end
  3260. #----------------------------------------------------------------------------
  3261. # • [String] : Separar o nome do arquivo do nome da pasta.
  3262. #----------------------------------------------------------------------------
  3263. def split(file)
  3264. file.to_s.split('/').last
  3265. end
  3266. #----------------------------------------------------------------------------
  3267. # • [String] : Obtêm o nome do arquivo correspondente ao id configurado,
  3268. # separado do nome da pasta.
  3269. #----------------------------------------------------------------------------
  3270. def name(id)
  3271. return if @file.nil?
  3272. return split(@file[id])
  3273. end
  3274. end
  3275. #==============================================================================
  3276. # • DRGSS | Comandos do RGSS...
  3277. #==============================================================================
  3278. Dax.register(:drgss)
  3279. module DRGSS
  3280. extend self
  3281. #----------------------------------------------------------------------------
  3282. # • Extrair scripts do Database para um arquivo de extensão de texto.
  3283. # options : Caso você deixe assim: {folder: "NM"}
  3284. # NM => Nome da pasta na qual os arquivos irão.
  3285. #----------------------------------------------------------------------------
  3286. def extract_scripts(type=".txt",options={})
  3287. except = options[:except] || []
  3288. folder = options[:folder] || ""
  3289. id = 0 #
  3290. $RGSS_SCRIPTS.each do |script|
  3291. name = script[1]
  3292. data = script[3]
  3293. next if except.include? name or name.empty? or data.empty?
  3294. filename = sprintf("%03d", id) + "_" + name
  3295. p "Writing: #{filename}"
  3296. File.open(folder+filename+"#{type}", "wb") do |file|
  3297. file.write data
  3298. end
  3299. id += 1
  3300. end
  3301. end
  3302. #----------------------------------------------------------------------------
  3303. # • Guarda todos os scripts do Database num arquivo;
  3304. #----------------------------------------------------------------------------
  3305. def keep_scripts_in_file(filename="RGSS.rvdata2")
  3306. unless FileTest.exist?(filename)
  3307. self.extract_scripts(".txt")
  3308. file = File.open(filename, "wb")
  3309. Dir.glob("./*.{txt}").each_with_index { |v,i|
  3310. next unless v.match(/(\d+){3}_(\w*)/)
  3311. file.write(IO.readlines(v).to_s)
  3312. File.delete(v)
  3313. }
  3314. file.close
  3315. end
  3316. end
  3317. end
  3318. #==============================================================================
  3319. # • Backup Complete
  3320. #==============================================================================
  3321. Dax.register(:backup)
  3322. module Backup
  3323. extend self
  3324. #----------------------------------------------------------------------------
  3325. # • Criar as pastas.
  3326. #----------------------------------------------------------------------------
  3327. def make_past
  3328. Dir.mksdir("Backup", "Data, System, Movies, Graphics, Audio")
  3329. Dir.mksdir("Backup/Audio", "BGM, BGS, ME, SE")
  3330. Dir.mksdir("Backup/Graphics", "Animations, Battlebacks1, Battlebacks2, Battlers, Characters, Faces, Parallaxes, Pictures, System, Titles1, Titles2, Tilesets")
  3331. end
  3332. #----------------------------------------------------------------------------
  3333. # • Copiar a pasta system.
  3334. #----------------------------------------------------------------------------
  3335. def system
  3336. list = Dir.glob('System/*')
  3337. list.size.times { |i|API::CopyFile.call(list[i], "Backup/" + list[i], true.boolean)}
  3338. end
  3339. #----------------------------------------------------------------------------
  3340. # • Copiar a pasta movie.
  3341. #----------------------------------------------------------------------------
  3342. def movies
  3343. movies = Dir.glob("Movies/*")
  3344. movies.size.times { |i| API::CopyFile.call(movies[i], "Backup/" + movies[i], true.boolean)}
  3345. end
  3346. #----------------------------------------------------------------------------
  3347. # • Copiar a pasta audio
  3348. #----------------------------------------------------------------------------
  3349. def audio
  3350. bgm = Dir.glob('Audio/BGM/*')
  3351. bgs = Dir.glob('Audio/BGS/*')
  3352. me = Dir.glob('Audio/ME/*')
  3353. se = Dir.glob('Audio/SE/*')
  3354. bgm.size.times { |i| API::CopyFile.call(bgm[i], "Backup/" + bgm[i], true.boolean)}
  3355. bgs.size.times { |i| API::CopyFile.call(bgs[i], "Backup/" + bgs[i], true.boolean) }
  3356. me.size.times { |i| API::CopyFile.call(me[i], "Backup/" + me[i], true.boolean) }
  3357. se.size.times { |i| API::CopyFile.call(se[i], "Backup/" + se[i], true.boolean) }
  3358. end
  3359. #----------------------------------------------------------------------------
  3360. # • Copiar a pasta Data.
  3361. #----------------------------------------------------------------------------
  3362. def data
  3363. data = Dir.glob('Data/*')
  3364. data.size.times { |i| API::CopyFile.call(data[i], "Backup/" + data[i], true.boolean) }
  3365. end
  3366. #----------------------------------------------------------------------------
  3367. # • Copiar a pasta Graphic.
  3368. #----------------------------------------------------------------------------
  3369. def graphics
  3370. ["Animations", "Battlebacks1", "Battlebacks2", "Battlers", "Characters",
  3371. "Faces", "Parallaxes", "Pictures", "System", "Titles1", "Titles2",
  3372. "Tilesets"].each { |dirs|
  3373. d = Dir.glob("Graphics/#{dirs}/*")
  3374. d.size.times { |v| API::CopyFile.call(d[v], "Backup/" + d[v], true.boolean) }
  3375. }
  3376. end
  3377. #----------------------------------------------------------------------------
  3378. # • Executar
  3379. #----------------------------------------------------------------------------
  3380. def run(audios=false, graphic=false)
  3381. if $TEST
  3382. make_past
  3383. movies
  3384. data
  3385. system
  3386. audio if audios
  3387. graphics if graphic
  3388. end
  3389. end
  3390. end
  3391. #==============================================================================
  3392. # * SceneManager
  3393. #==============================================================================
  3394. Dax.register :scenemanager
  3395. if defined?("SceneManager")
  3396. class << SceneManager
  3397. #--------------------------------------------------------------------------
  3398. # • **** Método ainda não explicado ****
  3399. #--------------------------------------------------------------------------
  3400. def symbol(scene_symbol)
  3401. eval("self.call(#{scene_symbol.to_s})")
  3402. end
  3403. end
  3404. end
  3405. #==============================================================================
  3406. # • Sprite_Text
  3407. #==============================================================================
  3408. Dax.register(:sprite_text)
  3409. class Sprite_Text < Sprite
  3410. #----------------------------------------------------------------------------
  3411. # • Variáveis públicas da instância.
  3412. #----------------------------------------------------------------------------
  3413. attr_accessor :text # Mudar de texto...
  3414. attr_accessor :align
  3415. #----------------------------------------------------------------------------
  3416. # • Inicialização dos objetos.
  3417. #----------------------------------------------------------------------------
  3418. def initialize(x, y, width, height, text, align=0)
  3419. super([width, height])
  3420. self.x, self.y = x, y
  3421. @text = text
  3422. @align = align
  3423. self.bitmap.draw_text_rect(@text, align)
  3424. end
  3425. #----------------------------------------------------------------------------
  3426. # • Renovação dos objetos.
  3427. #----------------------------------------------------------------------------
  3428. def dispose
  3429. self.bitmap.dispose
  3430. super
  3431. end
  3432. #----------------------------------------------------------------------------
  3433. # • Atualização dos objetos.
  3434. #----------------------------------------------------------------------------
  3435. def update
  3436. self.bitmap.clear
  3437. super
  3438. self.bitmap.draw_text_rect(@text, @align)
  3439. end
  3440. def size=(value=18)
  3441. self.bitmap.font.size = value
  3442. end
  3443. def name=(value=nil)
  3444. self.bitmap.font.name = value || "Arial"
  3445. end
  3446. #----------------------------------------------------------------------------
  3447. # • Negrito na fonte?
  3448. #----------------------------------------------------------------------------
  3449. def bold=(value=nil)
  3450. self.bitmap.font.bold = value || true
  3451. end
  3452. #----------------------------------------------------------------------------
  3453. # • Itálico na fonte?
  3454. #----------------------------------------------------------------------------
  3455. def italic=(value=nil)
  3456. self.bitmap.font.italic = value || true
  3457. end
  3458. #----------------------------------------------------------------------------
  3459. # • Sombra na fonte?
  3460. #----------------------------------------------------------------------------
  3461. def shadow=(value=nil)
  3462. self.bitmap.font.shadow = value || true
  3463. end
  3464. #----------------------------------------------------------------------------
  3465. # • Borda na fonte?
  3466. #----------------------------------------------------------------------------
  3467. def outline=(value=nil)
  3468. self.bitmap.font.outline = value || true
  3469. end
  3470. #----------------------------------------------------------------------------
  3471. # • Mudar a cor da fonte:
  3472. #----------------------------------------------------------------------------
  3473. def color=(color=nil)
  3474. self.bitmap.font.color = color || Color.new.default
  3475. end
  3476. #----------------------------------------------------------------------------
  3477. # • Mudar a cor da borda da fonte.
  3478. #----------------------------------------------------------------------------
  3479. def out_color=(out_color=nil)
  3480. self.bitmap.font.out_color = out_color || Color.new.hex("000000")
  3481. end
  3482. end
  3483. #==============================================================================
  3484. # • Sprite_Icon
  3485. #==============================================================================
  3486. Dax.register(:sprite_icon)
  3487. class Sprite_Icon < Sprite
  3488. #----------------------------------------------------------------------------
  3489. # • Variáveis públicas da instância.
  3490. #----------------------------------------------------------------------------
  3491. attr_accessor :icon_index # Mudar de ícone.
  3492. attr_accessor :enabled # Tornar opaco ou não.
  3493. attr_accessor :filename # Nome do arquivo.
  3494. #----------------------------------------------------------------------------
  3495. # • Inicialização dos objetos.
  3496. #----------------------------------------------------------------------------
  3497. def initialize(icon_index, x, y, enabled=true)
  3498. super([24, 24])
  3499. self.x, self.y = x, y
  3500. @icon_index = icon_index.to_i
  3501. @enabled = enabled
  3502. self.bitmap.draw_icon(@icon_index, 0, 0, @enabled)
  3503. end
  3504. #----------------------------------------------------------------------------
  3505. # • Renovação dos objetos.
  3506. #----------------------------------------------------------------------------
  3507. def dispose
  3508. self.bitmap.dispose
  3509. super
  3510. end
  3511. #----------------------------------------------------------------------------
  3512. # • Atualização dos objetos.
  3513. #----------------------------------------------------------------------------
  3514. def update
  3515. self.bitmap.clear
  3516. super
  3517. self.bitmap.draw_icon(@icon_index, 0, 0, @enabled, @filename)
  3518. end
  3519. end
  3520. #==============================================================================
  3521. # • Opacity
  3522. #==============================================================================
  3523. Dax.register(:opacity)
  3524. module Opacity
  3525. extend self
  3526. @key ||= {}
  3527. @time ||= {}
  3528. #----------------------------------------------------------------------------
  3529. # • Efeito de opacidade que vai aumentando e diminuindo.
  3530. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3531. # speed : Velocidade na qual o efeito irá acontencer.
  3532. # max : Valor máximo na qual irá ser atingido.
  3533. # min : Valor minímo na qual irá ser atingido.
  3534. #----------------------------------------------------------------------------
  3535. def sprite_opacity(sprite, speed, max, min, hash=nil)
  3536. @key[hash.nil? ? hash.__id__ : hash] || false
  3537. unless @key[hash]
  3538. sprite.opacity += speed unless sprite.opacity >= max
  3539. @key[hash] = sprite.opacity >= max
  3540. else
  3541. sprite.opacity -= speed unless sprite.opacity <= min
  3542. @key[hash] = false if sprite.opacity <= min
  3543. end
  3544. end
  3545. #----------------------------------------------------------------------------
  3546. # • Efeito de opacidade por fora.
  3547. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3548. # speed : Velocidade na qual o efeito irá acontencer.
  3549. # max : Valor máximo na qual irá ser atingido.
  3550. #----------------------------------------------------------------------------
  3551. def sprite_opacity_out(sprite, speed, max)
  3552. return if sprite.nil?
  3553. sprite.opacity += speed unless sprite.opacity >= max
  3554. end
  3555. #----------------------------------------------------------------------------
  3556. # • Efeito de opacidade por dentro.
  3557. # sprite : Objeto na qual sofrerá o efeito. [Sprite]
  3558. # speed : Velocidade na qual o efeito irá acontencer.
  3559. # min : Valor minímo na qual irá ser atingido.
  3560. #----------------------------------------------------------------------------
  3561. def sprite_opacity_in(sprite, speed, min)
  3562. sprite.opacity -= speed unless sprite.opacity <= min
  3563. end
  3564. #----------------------------------------------------------------------------
  3565. # • Limpar variável.
  3566. #----------------------------------------------------------------------------
  3567. def clear
  3568. @key.clear
  3569. end
  3570. end
  3571. #==============================================================================
  3572. # • Read
  3573. #==============================================================================
  3574. Dax.register(:read, "Dax")
  3575. module Read
  3576. extend self
  3577. #----------------------------------------------------------------------------
  3578. # • Verificar valor numérico após uma palavra em um arquivo.
  3579. #----------------------------------------------------------------------------
  3580. def numeric(file, tag)
  3581. IO.readlines(file).each do |line|
  3582. return $1.to_i if line.match(/#{tag}(\d+)/)
  3583. end
  3584. end
  3585. #----------------------------------------------------------------------------
  3586. # • Verificar valor de uma palavra(string única) após uma palavra em um arquivo
  3587. #----------------------------------------------------------------------------
  3588. def string(file, tag)
  3589. IO.readlines(file).each do |line|
  3590. return $1.to_s if line.match(/#{tag}(\w+)/)
  3591. end
  3592. end
  3593. #----------------------------------------------------------------------------
  3594. # • Verificar um conteúdo após uma palavra de um arquivo.
  3595. #----------------------------------------------------------------------------
  3596. def content(file, tag)
  3597. IO.readlines(file).each do |line|
  3598. return $1 if line.match(/#{tag}([^>]*)/)
  3599. end
  3600. end
  3601. #----------------------------------------------------------------------------
  3602. # • Multiplo número..
  3603. #----------------------------------------------------------------------------
  3604. def multiple_numeric(file, tag)
  3605. IO.readlines(file).each do |line|
  3606. return [$1.to_i, $2.to_i] if line.match(/#{tag}(\d+), (\d+)/)
  3607. end
  3608. end
  3609. #----------------------------------------------------------------------------
  3610. # • Multiplo string..
  3611. #----------------------------------------------------------------------------
  3612. def multiple_string(file, tag)
  3613. IO.readlines(file).each do |line|
  3614. return [$1.to_s, $2.to_s] if line.match(/#{tag}(\w+), (\w+)/)
  3615. end
  3616. end
  3617. #----------------------------------------------------------------------------
  3618. # • Triplo número.
  3619. #----------------------------------------------------------------------------
  3620. def triple_numeric(file, tag)
  3621. IO.readlines(file).each do |line|
  3622. return [$1.to_i, $2.to_i, $3.to_i] if line.match(/#{tag}(\d+), (\d+), (\d+)/)
  3623. end
  3624. end
  3625. #----------------------------------------------------------------------------
  3626. # • Triplo string.
  3627. #----------------------------------------------------------------------------
  3628. def triple_string(file, tag)
  3629. IO.readlines(file).each do |line|
  3630. return [$1.to_s, $2.to_s, $3.to_s] if line.match(/#{tag}(\w+), (\w+), (\w+)/)
  3631. end
  3632. end
  3633. #----------------------------------------------------------------------------
  3634. # • Se é verdairo ou falo.
  3635. #----------------------------------------------------------------------------
  3636. def of(file, tag)
  3637. IO.readlines(file).each do |line|
  3638. return $1.to_s == "true" ? true : false if line.match(/#{tag}([^>]*)/)
  3639. end
  3640. end
  3641. end
  3642. #==============================================================================
  3643. # • Crypt
  3644. #==============================================================================
  3645. Dax.register(:crypt)
  3646. module Crypt
  3647. extend self
  3648. #----------------------------------------------------------------------------
  3649. # • Constantes
  3650. #---------------------------------------------------------------------------
  3651. # Chave de encriptação. 32-bit esse é o limite: 0xFFFFFFF ou 4294967295
  3652. KEY = 0xFFFFFFF
  3653. EXTN = ".drvd2" # Extensão do aquivo encriptado.
  3654. #----------------------------------------------------------------------------
  3655. # • Método de encriptação.
  3656. # string : String que será encriptado.
  3657. #----------------------------------------------------------------------------
  3658. def encrypt(string)
  3659. string.unpack("U*").collect! { |i|i^KEY}.compact.pack("U*").unpack("C*").pack("U*")
  3660. end
  3661. #----------------------------------------------------------------------------
  3662. # • Método de desencriptação.
  3663. # string : String que será desencriptado.
  3664. #----------------------------------------------------------------------------
  3665. def decrypt(string)
  3666. string.unpack("U*").pack("C*").unpack("U*").collect! {|i|i^KEY}.compact.pack("U*")
  3667. end
  3668. #----------------------------------------------------------------------------
  3669. # • [NilClass] : Método de encriptação de arquivos.
  3670. # filename : Nome do arquivo que será encriptado.
  3671. # delete : Deletar o arquivo não-encriptado. Por padrão é false.
  3672. #----------------------------------------------------------------------------
  3673. def enfile(filename, delete=false)
  3674. return unless FileTest.exist?(filename)
  3675. open(filename.extn(EXTN), "wb") { |file|
  3676. IO.readlines(filename).each { |i| file.write(encrypt(i)) }
  3677. file.close
  3678. }
  3679. File.delete(filename) if delete
  3680. return nil
  3681. end
  3682. #----------------------------------------------------------------------------
  3683. # • [NilClass] : Método de desencriptação de arquivos.
  3684. # filename : Nome do arquivo que será desencriptado.
  3685. # extension : Extensão do novo arquivo. Do arquivo com o conteúdo desencriptado.
  3686. # delete : Deletar o arquivo encriptado. Por padrão é false.
  3687. #----------------------------------------------------------------------------
  3688. def defile(filename, extension="rb", delete=false)
  3689. return unless FileTest.exist?(filename)
  3690. open(filename.extn(extension), "wb") { |file|
  3691. IO.readlines(filename).each { |i| file.write(decrypt(i)) }
  3692. file.close
  3693. }
  3694. File.delete(filename) if delete
  3695. return nil
  3696. end
  3697. #----------------------------------------------------------------------------
  3698. # • [String] : Método que lê o arquivo encriptado.
  3699. # filename : Nome do arquivo que será desencriptado.
  3700. #----------------------------------------------------------------------------
  3701. def rdefile(filename)
  3702. return unless FileTest.exist?(filename)
  3703. str = ""
  3704. IO.readlines(filename).each { |i| str << decrypt(i) }
  3705. str
  3706. end
  3707. end
  3708. #==============================================================================
  3709. # • Background
  3710. #==============================================================================
  3711. Dax.register :background
  3712. module Background
  3713. extend self
  3714. #----------------------------------------------------------------------------
  3715. # • Plano de fundo padrão...
  3716. #----------------------------------------------------------------------------
  3717. def default(alpha=128)
  3718. @background = Sprite.new
  3719. @background.bitmap = SceneManager.background_bitmap
  3720. @background.color.set(16, 16, 16, alpha)
  3721. end
  3722. #----------------------------------------------------------------------------
  3723. # • Plano de fundo padrão renovado.
  3724. #----------------------------------------------------------------------------
  3725. def default_dispose
  3726. return if @background.nil?
  3727. @background.dispose
  3728. end
  3729. end
  3730. #==============================================================================
  3731. # * Window_Base
  3732. #==============================================================================
  3733. Dax.register(:window_base)
  3734. Dax.if_defined?("Window_Base") {
  3735. class Window_Base < Window
  3736. #----------------------------------------------------------------------------
  3737. # • Slide pela direita.
  3738. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  3739. #----------------------------------------------------------------------------
  3740. def slide_right(speed, point)
  3741. self.x += speed unless self.x >= point
  3742. end
  3743. #----------------------------------------------------------------------------
  3744. # • Slide pela esquerda.
  3745. # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
  3746. #----------------------------------------------------------------------------
  3747. def slide_left(speed, point)
  3748. self.x -= speed unless self.x <= point
  3749. end
  3750. #----------------------------------------------------------------------------
  3751. # • Slide por cima.
  3752. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  3753. #----------------------------------------------------------------------------
  3754. def slide_up(speed, point)
  3755. self.y -= speed unless self.y <= point
  3756. end
  3757. #----------------------------------------------------------------------------
  3758. # • Slide por baixo.
  3759. # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
  3760. #----------------------------------------------------------------------------
  3761. def slide_down(speed, point)
  3762. self.y += speed unless self.y >= point
  3763. end
  3764. #----------------------------------------------------------------------------
  3765. # • Define aqui uma posição fixa para um objeto.
  3766. # command : Retorna a uma base padrão.
  3767. #----------------------------------------------------------------------------
  3768. def position(command=0)
  3769. return if command.nil?
  3770. Position[command, self]
  3771. end
  3772. end
  3773. }
  3774. #==============================================================================
  3775. # • Sound Base
  3776. #==============================================================================
  3777. Dax.register(:sound_base)
  3778. module Sound_Base
  3779. #----------------------------------------------------------------------------
  3780. # • Função do módulo.
  3781. #----------------------------------------------------------------------------
  3782. module_function
  3783. #----------------------------------------------------------------------------
  3784. # • Executar um som.
  3785. #----------------------------------------------------------------------------
  3786. def play(name, volume, pitch, type = :se)
  3787. case type
  3788. when :se ; RPG::SE.new(name, volume, pitch).play rescue valid?(name)
  3789. when :me ; RPG::ME.new(name, volume, pitch).play rescue valid?(name)
  3790. when :bgm ; RPG::BGM.new(name, volume, pitch).play rescue valid?(name)
  3791. when :bgs ; RPG::BGS.new(name, volume, pitch).play rescue valid?(name)
  3792. end
  3793. end
  3794. #----------------------------------------------------------------------------
  3795. # • Validar som.
  3796. #----------------------------------------------------------------------------
  3797. def valid?(name)
  3798. raise("Arquivo de som não encontrado: #{name}")
  3799. exit
  3800. end
  3801. end
  3802. #==============================================================================
  3803. # • Animation
  3804. #==============================================================================
  3805. Dax.register :animation
  3806. class Animation
  3807. attr_reader :size, :frame_size, :index, :max_width, :max_height
  3808. #----------------------------------------------------------------------------
  3809. # • Inicialização.
  3810. #----------------------------------------------------------------------------
  3811. def initialize(size, frame_size, wait=1)
  3812. @size = size
  3813. @frame_size = frame_size
  3814. @index = 0
  3815. @max_width = @size[0] / @frame_size[0]
  3816. @max_height = @size[1] / @frame_size[1]
  3817. @wait = wait
  3818. @time = 0
  3819. end
  3820. #----------------------------------------------------------------------------
  3821. # • Animação na horizontal.
  3822. #----------------------------------------------------------------------------
  3823. def horz
  3824. @time += 1 unless @time >= @wait
  3825. if @time >= @wait
  3826. @index = @index.up(@index, @max_width)
  3827. @time = 0
  3828. end
  3829. end
  3830. #----------------------------------------------------------------------------
  3831. # • Animação na vertical.
  3832. #----------------------------------------------------------------------------
  3833. def vert
  3834. @time += 1 unless @time >= @wait
  3835. if @time >= @wait
  3836. @index = @index.up(@index, @max_height)
  3837. @time = 0
  3838. end
  3839. end
  3840. end
  3841. #==============================================================================
  3842. # • Sprite_Anime_Horz
  3843. #==============================================================================
  3844. Dax.register :sprite_anime_horz
  3845. class Sprite_Anime_Horz < Sprite
  3846. #----------------------------------------------------------------------------
  3847. # • Inicialização dos objetos
  3848. # filename : Nome do arquivo.
  3849. # frame_size : Tamanho de cada frame.
  3850. # wait : Tempo de espera para mudar de um frame para outro.
  3851. #----------------------------------------------------------------------------
  3852. def initialize(filename, frame_size, wait=1)
  3853. @bitmap = Bitmap.new(filename)
  3854. super(frame_size)
  3855. @animation = Animation.new([@bitmap.width, @bitmap.height],
  3856. frame_size, wait)
  3857. end
  3858. #----------------------------------------------------------------------------
  3859. # • Renovação dos objetos.
  3860. #----------------------------------------------------------------------------
  3861. def dispose
  3862. self.bitmap.dispose
  3863. super
  3864. end
  3865. #----------------------------------------------------------------------------
  3866. # • Atualização dos objetos.
  3867. #----------------------------------------------------------------------------
  3868. def update
  3869. self.bitmap.clear
  3870. super
  3871. @animation.horz
  3872. rect = Rect.new(@animation.index % @animation.max_width * @animation.frame_size[0],
  3873. 0, *@animation.frame_size)
  3874. self.bitmap.blt(0, 0, @bitmap, rect)
  3875. end
  3876. end
  3877. #==============================================================================
  3878. # • Sprite_Anime_Vert
  3879. #==============================================================================
  3880. Dax.register :sprite_anime_vert
  3881. class Sprite_Anime_Vert < Sprite
  3882. #----------------------------------------------------------------------------
  3883. # • Inicialização dos objetos
  3884. # filename : Nome do arquivo.
  3885. # frame_size : Tamanho de cada frame.
  3886. # wait : Tempo de espera para mudar de um frame para outro.
  3887. #----------------------------------------------------------------------------
  3888. def initialize(filename, frame_size, wait=1)
  3889. @bitmap = Bitmap.new(filename)
  3890. super(frame_size)
  3891. @animation = Animation.new([@bitmap.width, @bitmap.height],
  3892. frame_size, wait)
  3893. end
  3894. #----------------------------------------------------------------------------
  3895. # • Renovação dos objetos.
  3896. #----------------------------------------------------------------------------
  3897. def dispose
  3898. self.bitmap.dispose
  3899. super
  3900. end
  3901. #----------------------------------------------------------------------------
  3902. # • Atualização dos objetos.
  3903. #----------------------------------------------------------------------------
  3904. def update
  3905. self.bitmap.clear
  3906. super
  3907. @animation.vert
  3908. rect = Rect.new(0,
  3909. @animation.index % @animation.max_height * @animation.frame_size[1], *@animation.frame_size)
  3910. self.bitmap.blt(0, 0, @bitmap, rect)
  3911. end
  3912. end
  3913. #==============================================================================
  3914. # • Benchmark
  3915. #==============================================================================
  3916. Dax.register(:benchmark)
  3917. module Benchmark
  3918. extend self
  3919. #----------------------------------------------------------------------------
  3920. # • Constantes.
  3921. #----------------------------------------------------------------------------
  3922. CAPTION = " user system total real\n"
  3923. FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
  3924. def Benchmark::times() # :nodoc:
  3925. Process::times()
  3926. end
  3927. #----------------------------------------------------------------------------
  3928. # • Método do benchmark.:.
  3929. # ** Exemplo:.:
  3930. # n = 50000
  3931. # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
  3932. # tf = x.report("for:") { for i in 1..n; a = "1"; end }
  3933. # tt = x.report("times:") { n.times do ; a = "1"; end }
  3934. # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  3935. # [tf+tt+tu, (tf+tt+tu)/3]
  3936. # end
  3937. # ** Gera:.:
  3938. # user system total real
  3939. # for: 1.016667 0.016667 1.033333 ( 0.485749)
  3940. # times: 1.450000 0.016667 1.466667 ( 0.681367)
  3941. # upto: 1.533333 0.000000 1.533333 ( 0.722166)
  3942. # >total: 4.000000 0.033333 4.033333 ( 1.889282)
  3943. # >avg: 1.333333 0.011111 1.344444 ( 0.629761)
  3944. #----------------------------------------------------------------------------
  3945. def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report
  3946. sync = STDOUT.sync
  3947. STDOUT.sync = true
  3948. label_width ||= 0
  3949. fmtstr ||= FMTSTR
  3950. raise ArgumentError, "no block" unless iterator?
  3951. print caption
  3952. results = yield(Report.new(label_width, fmtstr))
  3953. Array === results and results.grep(Tms).each {|t|
  3954. print((labels.shift || t.label || "").ljust(label_width),
  3955. t.format(fmtstr))
  3956. }
  3957. STDOUT.sync = sync
  3958. end
  3959. #----------------------------------------------------------------------------
  3960. # • Versão simplificada para benchmark.
  3961. # ** Exemplo:.:
  3962. # n = 50000
  3963. # Benchmark.bm(7) do |x|
  3964. # x.report("for:") { for i in 1..n; a = "1"; end }
  3965. # x.report("times:") { n.times do ; a = "1"; end }
  3966. # x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  3967. # end
  3968. # ** Gera:.:
  3969. # user system total real
  3970. # for: 1.050000 0.000000 1.050000 ( 0.503462)
  3971. # times: 1.533333 0.016667 1.550000 ( 0.735473)
  3972. # upto: 1.500000 0.016667 1.516667 ( 0.711239)
  3973. #----------------------------------------------------------------------------
  3974. def bm(label_width = 0, *labels, &blk) # :yield: report
  3975. benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
  3976. end
  3977. #----------------------------------------------------------------------------
  3978. # • Retorna ao tempo usado para executar o bloco como um objeto Benchmark::Tms
  3979. #----------------------------------------------------------------------------
  3980. def measure(label = "") # :yield:
  3981. t0, r0 = Benchmark.times, Time.now
  3982. yield
  3983. t1, r1 = Benchmark.times, Time.now
  3984. Benchmark::Tms.new(t1.utime - t0.utime,
  3985. t1.stime - t0.stime,
  3986. t1.cutime - t0.cutime,
  3987. t1.cstime - t0.cstime,
  3988. r1.to_f - r0.to_f,
  3989. label)
  3990. end
  3991. #----------------------------------------------------------------------------
  3992. # • Retorna ao tempo real decorrido, o tempo usado para executar o bloco.
  3993. #----------------------------------------------------------------------------
  3994. def realtime(&blk) # :yield:
  3995. r0 = Time.now
  3996. yield
  3997. r1 = Time.now
  3998. r1.to_f - r0.to_f
  3999. end
  4000. #============================================================================
  4001. # • Report ::
  4002. #============================================================================
  4003. class Report
  4004. #--------------------------------------------------------------------------
  4005. # • Retorna uma instância inicializada.
  4006. # Usualmente não é bom chamar esse método diretamente.
  4007. #--------------------------------------------------------------------------
  4008. def initialize(width = 0, fmtstr = nil)
  4009. @width, @fmtstr = width, fmtstr
  4010. end
  4011. #--------------------------------------------------------------------------
  4012. # • Imprime o _label_ e o tempo marcado pelo bloco, formatado por _fmt_.
  4013. #--------------------------------------------------------------------------
  4014. def item(label = "", *fmt, &blk) # :yield:
  4015. print label.ljust(@width)
  4016. res = Benchmark::measure(&blk)
  4017. print res.format(@fmtstr, *fmt)
  4018. res
  4019. end
  4020. #--------------------------------------------------------------------------
  4021. # • Método :alias:
  4022. #--------------------------------------------------------------------------
  4023. alias :report :item
  4024. end
  4025. #============================================================================
  4026. # • Tms
  4027. #============================================================================
  4028. class Tms
  4029. #--------------------------------------------------------------------------
  4030. # • Constantes
  4031. #--------------------------------------------------------------------------
  4032. CAPTION = " user system total real\n"
  4033. FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
  4034. #--------------------------------------------------------------------------
  4035. # • Variáveis da instância.
  4036. #--------------------------------------------------------------------------
  4037. attr_reader :utime # Tempo da CPU do Usuário.
  4038. attr_reader :stime # Tempo da CPU do Sistema.
  4039. attr_reader :cutime # Tempo da CPU do usuário-criança.
  4040. attr_reader :cstime # Tempo da CPU do sistema-criança.
  4041. attr_reader :real # Tempo real corrido.
  4042. attr_reader :total # Tempo total, que é _utime_ + _stime_ + _cutime_ + _cstime_
  4043. attr_reader :label # Label.
  4044. #--------------------------------------------------------------------------
  4045. # • Retorna ao objeto inicializado na qual tem _u_ como tempo dá CPU do
  4046. # usuário, _s_ como o tempo da CPU do sistema, _cu_ como tempo dá CPU
  4047. # do usuário-criança, _cs_ como o tempo dá CPU sistema-criança, _real_
  4048. # como o tempo real corrido e _l_ como label.
  4049. #--------------------------------------------------------------------------
  4050. def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)
  4051. @utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l
  4052. @total = @utime + @stime + @cutime + @cstime
  4053. end
  4054. #--------------------------------------------------------------------------
  4055. # • Retorna a um novo objeto Tms, na qual os tempos são somados num todo
  4056. # pelo objeto Tms.
  4057. #--------------------------------------------------------------------------
  4058. def add(&blk) # :yield:
  4059. self + Benchmark::measure(&blk)
  4060. end
  4061. #--------------------------------------------------------------------------
  4062. # • Uma versão no lugar do método #add
  4063. #--------------------------------------------------------------------------
  4064. def add!
  4065. t = Benchmark::measure(&blk)
  4066. @utime = utime + t.utime
  4067. @stime = stime + t.stime
  4068. @cutime = cutime + t.cutime
  4069. @cstime = cstime + t.cstime
  4070. @real = real + t.real
  4071. self
  4072. end
  4073. #--------------------------------------------------------------------------
  4074. # • Soma com outro objeto do mesmo.
  4075. #--------------------------------------------------------------------------
  4076. def +(other); memberwise(:+, other) end
  4077. #--------------------------------------------------------------------------
  4078. # • Subtrai com outro objeto do mesmo.
  4079. #--------------------------------------------------------------------------
  4080. def -(other); memberwise(:-, other) end
  4081. #--------------------------------------------------------------------------
  4082. # • Multiplica com outro objeto do mesmo.
  4083. #--------------------------------------------------------------------------
  4084. def *(x); memberwise(:*, x) end
  4085. #--------------------------------------------------------------------------
  4086. # • Divide com outro objeto do mesmo.
  4087. #--------------------------------------------------------------------------
  4088. def /(x); memberwise(:/, x) end
  4089. #--------------------------------------------------------------------------
  4090. # • Retorna ao conteudo dos objetos formatados como uma string.
  4091. #--------------------------------------------------------------------------
  4092. def format(arg0 = nil, *args)
  4093. fmtstr = (arg0 || FMTSTR).dup
  4094. fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label}
  4095. fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime}
  4096. fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime}
  4097. fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime}
  4098. fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime}
  4099. fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total}
  4100. fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real}
  4101. arg0 ? Kernel::format(fmtstr, *args) : fmtstr
  4102. end
  4103. #--------------------------------------------------------------------------
  4104. # • Mesmo que o método formato.
  4105. #--------------------------------------------------------------------------
  4106. def to_s
  4107. format
  4108. end
  4109. #--------------------------------------------------------------------------
  4110. # • Retorna a uma array contendo os elementos:
  4111. # @label, @utime, @stime, @cutime, @cstime, @real
  4112. #--------------------------------------------------------------------------
  4113. def to_a
  4114. [@label, @utime, @stime, @cutime, @cstime, @real]
  4115. end
  4116. protected
  4117. def memberwise(op, x)
  4118. case x
  4119. when Benchmark::Tms
  4120. Benchmark::Tms.new(utime.__send__(op, x.utime),
  4121. stime.__send__(op, x.stime),
  4122. cutime.__send__(op, x.cutime),
  4123. cstime.__send__(op, x.cstime),
  4124. real.__send__(op, x.real)
  4125. )
  4126. else
  4127. Benchmark::Tms.new(utime.__send__(op, x),
  4128. stime.__send__(op, x),
  4129. cutime.__send__(op, x),
  4130. cstime.__send__(op, x),
  4131. real.__send__(op, x)
  4132. )
  4133. end
  4134. end
  4135. CAPTION = Benchmark::Tms::CAPTION
  4136. FMTSTR = Benchmark::Tms::FMTSTR
  4137. end
  4138. end
  4139. #==============================================================================
  4140. # • Desativar scripts : Para fazer, basta por no nome do script da lista,
  4141. # [D].
  4142. # • Salvar script em arquivo de texto : Para fazer, basta por no nome do script da lista,
  4143. # [S].
  4144. #==============================================================================
  4145. Dax.register(:disable_script)
  4146. $RGSS_SCRIPTS.each_with_index { |data, index|
  4147. if data.at(1).include?("[S]")
  4148. File.open("#{rgss.at(1)}.txt", "wb") { |file|
  4149. file.write(String($RGSS_SCRIPTS.at(index)[3]))
  4150. file.close
  4151. }
  4152. end
  4153. $RGSS_SCRIPTS.at(index)[2] = $RGSS_SCRIPTS.at(index)[3] = "" if data.at(1).include?("[D]")
  4154. }
  4155. #==============================================================================
  4156. # * Input
  4157. #==============================================================================
  4158. class << Input
  4159. alias :upft :update
  4160. def update
  4161. upft
  4162. Key.update
  4163. end
  4164. end
  4165. #==============================================================================
  4166. # • Graphics
  4167. #==============================================================================
  4168. class << Graphics
  4169. attr_reader :fps
  4170. alias :uptf :update
  4171. def update
  4172. @fps ||= 0
  4173. @fps_temp ||= []
  4174. time = Time.now
  4175. uptf
  4176. Mouse.update
  4177. @fps_temp[frame_count % frame_rate] = Time.now != time
  4178. @fps = 0
  4179. frame_rate.times { |i| @fps += 1 if @fps_temp[i] }
  4180. end
  4181. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement