DaxSoft

Dax Core i2.8

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