DaxSoft

Dax Core i2.4

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