DaxSoft

Dax Core i3.3

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