DaxSoft

Dax Core i3.1

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