DaxSoft

Dax Core i2.7

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