DaxSoft

Dax Core i3.5

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