DaxSoft

Dax Core i2.6

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