DaxSoft

Dax Core i2.2

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