DaxSoft

Dax Core i2.3

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