DaxSoft

Dax Core i3.4

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