Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #==============================================================================
- # * Dax Core
- #==============================================================================
- # Autor : Dax Aquatic X
- # Versão : Core i1.8
- # Site : www.dax-soft.weebly.com
- # Suporte : dax-soft@live.com
- #==============================================================================
- # Um Core com vários módulos e métodos que facilitará na hora de programar os
- # seus scripts, bom proveito.
- #==============================================================================
- # Conteúdo :
- #==============================================================================
- # i :
- # - API
- # - String
- # - Integer
- # - Float
- # - Color
- # - ColorBasic
- # - DMath
- # - Key
- # - Mouse
- # - Entries
- # - Rpg Module
- # - Read
- # - DRGSS
- # - Rect
- # - Sprite
- # - Bitmap : method (save) by Gab!
- # - Object
- # - Touch_Picture
- # - Simple_Touch_Picture
- # - Sprite_Text
- # - Text_Base
- # - Touch_Icon
- # - Simple_Touch_Icon
- # - Touch_Text
- # - Simple_Touch_Text
- # - Opacity
- # - DString
- # - Background
- # - Window_Base
- # - Map
- # - User32
- # - VS
- # - Sound Base
- # - Disable Script
- # - Regexp Symbols
- # - Enumerables
- #==============================================================================
- module Dax
- extend self
- #----------------------------------------------------------------------------
- # Ajuste aqui as configurações básicas da fonte padrão do jogo.
- #----------------------------------------------------------------------------
- Font.default_name = ["Arial"] # Nome padrão da fonte do jogo.
- Font.default_size = 18 # Tamanho padrão da fonte do jogo.
- Font.default_bold = true # true - Para usar negrito | false - para não usar.
- Font.default_italic = false # true - Para usar italico | false - para não usar.
- Font.default_shadow = false # true - Para usar sombra na fonte | false - para não usar.
- Font.default_outline = true # true - Para usar borda da fonte | false - para não usar.
- Font.default_out_color = Color.new(0, 0, 0) # Cor da fonte padrão da borda da fonte.
- Font.default_color = Color.new(255, 255, 255) # Cor da fonte padrão.
- #----------------------------------------------------------------------------
- # * Constantes e variáveis
- #----------------------------------------------------------------------------
- @register = {} # Armazena os scripts criados que foram registrados.
- @benchmark = "" # Armazena os testes conclusos de benchmark.
- # A imagem do ícone do Mouse tem que estar na pasta System. Basta você
- # por o nome da imagem dentro das áspas. Caso você queira usar um ícone
- # do Rpg Maker no lugar de uma imagem, basta você por o id do ícone no lugar
- # das áspas.
- Mouse_Name = ""
- #----------------------------------------------------------------------------
- # * Somente executará o bloco caso estiver registrado o script.
- #----------------------------------------------------------------------------
- # Exemplo:
- # Dax.required_script(:teste) { # Só irá executar caso estiver registrado.
- # methods...
- # }
- #----------------------------------------------------------------------------
- def required_script(symbol, &block)
- block.call if @register.has_key?(symbol) and block_given?
- end
- #----------------------------------------------------------------------------
- # * Método de registrar scripts :
- #----------------------------------------------------------------------------
- # ** Este método tem de ser definido alguns valores como :
- # symbol - nome do script, que é posto em símbolo : Ex - :arrow
- # name - nome do autor do script, que é posto em áspas
- # version - versão do script;
- # data - data do script;
- # Dax.register(symbol, name, version, data)
- # ** Você pode usá-lo para somente registrar o nome do script.
- # Dax.register(symbol)
- # ** Você pode usá-lo para modificar a versão e a data do script.
- # --- Mas só funciona caso o script já tenha se registrado.
- # Dax.register(symbol, version, data)
- #----------------------------------------------------------------------------
- def register(*args)
- if @register.has_key?(args[0])
- @register[args[0]][:version] = args[1]
- @register[args[0]][:data] = args[2]
- else
- @register[args[0]] = {name: args[1], version: args[2], data: args[3], script: nil}
- end
- end
- #----------------------------------------------------------------------------
- # * Método de verificar se o objeto existe.
- #----------------------------------------------------------------------------
- # Dax.required_class("Objeto") { }
- # Dentro das chaves você poem o script.
- # * Exemplo :
- # Dax.required_class("Window_Base") {
- # class Window_Base < Window
- # def example
- # self.x = self.x + self.width
- # end
- # end
- # }
- #----------------------------------------------------------------------------
- # Executa o bloco se o objeto existir.
- #----------------------------------------------------------------------------
- def required_class(name, &block)
- eval("block.call if defined?(name)")
- end
- #----------------------------------------------------------------------------
- # • Fazer benchmark de um bloco.
- #----------------------------------------------------------------------------
- # Dax.benchmark(name(opcional)) { BLOCO }
- #----------------------------------------------------------------------------
- def benchmark(name="", &block)
- time = Time.now
- block.call
- print "Benchmark: #{(time - Time.now).abs.to_f} segundos!\r\n"
- @benchmark += "#{name} : #{(time - Time.now).to_f} segundos!\r\n"
- end
- #----------------------------------------------------------------------------
- # • Salva os testes de benchmark.
- #----------------------------------------------------------------------------
- def benchmark_save
- File.open("Benchmark.txt", "a+") do |file|
- file.write(@benchmark)
- file.close
- end
- end
- #----------------------------------------------------------------------------
- # • Requirir um arquivo.
- # arquivo : Arquivo...
- #----------------------------------------------------------------------------
- def require(arquivo)
- $: << "./"
- Kernel.send(:require, arquivo)
- end
- #----------------------------------------------------------------------------
- # * Somente executa um bloco case existir um arquivo.
- #----------------------------------------------------------------------------
- # Dax.required_file("arquivo.tipo") { # Exemplo.
- # Métodos;
- # }
- #----------------------------------------------------------------------------
- def required_file(filename, &block)
- block.call if FileTest.exist?(filename)
- end
- #----------------------------------------------------------------------------
- # * Remove uma [Classe], exemplo: Dax.remove(:Scene_Menu)
- #----------------------------------------------------------------------------
- def remove(symbol_name)
- Object.send(:remove_const, symbol_name)
- end
- #----------------------------------------------------------------------------
- # * Retorna a variável [$RGSS_SCRIPT]
- #----------------------------------------------------------------------------
- def rgss_script
- return $RGSS_SCRIPTS
- end
- #----------------------------------------------------------------------------
- # * Tela chéia
- #----------------------------------------------------------------------------
- def full_screen
- res = Win32API.new 'user32', 'keybd_event', %w(l l l l), ''
- res.call(18,0,0,0)
- res.call(13,0,0,0)
- res.call(13,0,2,0)
- res.call(18,0,2,0)
- end
- end
- Dax.register(:dax)
- #==============================================================================
- # * API : Módulo que armazena informações de algumas APIS.
- #==============================================================================
- Dax.register(:api)
- module API
- extend self
- # Permite acessar as teclas do teclado.
- GetKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'i', 'i')
- # Permite ativar/desativar o ícone do mouse.
- MouseShowCursor = Win32API.new("user32", "ShowCursor", "i", "i")
- # Permite achar a posição do mouse.
- CursorPosition = Win32API.new('user32', 'GetCursorPos', 'p', 'i')
- # Permite achar o tamanho da screen.
- ScreenToClient = Win32API.new('user32', 'ScreenToClient', %w(l p), 'i')
- # Permite fazer a leitura do game.ini.
- ReadIni = Win32API.new('kernel32', 'GetPrivateProfileStringA', %w(p p p p l p), 'l')
- # Permite achar o tamando da window.
- FindWindow = Win32API.new('user32', 'FindWindowA', %w(p p), 'l')
- # API da Message Box.
- MessageBoxA = Win32API.new('user32', 'MessageBoxA', %w(p p p i), 'i')
- # Recupera uma string especificada de um arquivo em inicialização.
- GetPrivateProfileString = Win32API.new('kernel32', 'GetPrivateProfileStringA',%w(p p p p l p),'l')
- # Get Systeme Metrics
- GetSystemMetrics = Win32API.new("user32", "GetSystemMetrics", "i", "i")
- # Posição da janela.
- SetWindowPos = Win32API.new("user32", "SetWindowPos", "lliiiii", "i")
- # Obtem o 'Rect' da janela.
- GetWindowRect = Win32API.new('user32','GetWindowRect',%w(l p),'i')
- # Define a Win32API do comando print
- MessageBoxW = Win32API.new("user32", "MessageBoxW", "LPPL", "L")
- # Caps Lock
- CapsLock = Win32API.new("user32", "GetKeyState", "i", "i").call(20) != 0
- # State Key
- StateKey = Win32API.new("user32", "GetKeyState", ["i"], "i")
- # SetCursorPos
- SetCursorPos = Win32API.new("user32", "SetCursorPos", "ll", "i")
- SetCursorPos = Win32API.new("user32", "SetCursorPos", "ii", "i")
- GetKeyboardState = Win32API.new('user32', 'GetKeyboardState', ['P'], 'V')
- GetAsyncKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'i', 'i')
- # Criar uma nova pasta.
- CreateDirectory = Win32API.new("kernel32", "CreateDirectory", "p", "lll")
- # Remover uma pasta existente.
- RemoveDirectory = Win32API.new("kernel32", "RemoveDirectory", "p", "l")
- WideCharToMultiByte = Win32API.new('kernel32', 'WideCharToMultiByte', 'ilpipipp', 'i')
- MultiByteToWideChar = Win32API.new('kernel32', 'MultiByteToWideChar', 'ilpipi', 'i')
- # retorna para a data do ponteiro.
- def copymen(len)
- buf = "\0" * len
- Win32API.new("kernel32", "RtlMoveMemory", "ppl", "").call(buf, self, len)
- buf
- end
- # Shell
- Open = Win32API.new('shell32', 'ShellExecute', 'LPPPPI', 'L')
- def open_file(name)
- API::Open.call(0, 'open', "#{name}.exe", 0, 0, 1)
- end
- # Converter texto
- def convert_text(text, from, to)
- size = MultiByteToWideChar.(from, 0, text, -1, nil, 0)
- buffer = [].pack("x#{size*2}")
- MultiByteToWideChar.(from, 0, text, -1, buffer, buffer.size/2)
- size = WideCharToMultiByte.(to, 0, buffer, -1, nil, 0, nil, nil)
- second_buffer = [].pack("x#{size}")
- WideCharToMultiByte.(to, 0, buffer, -1, second_buffer, second_buffer.size, nil, nil)
- second_buffer.delete!("\000") if to == 65001
- second_buffer.delete!("\x00") if to == 0
- return second_buffer
- end
- end
- #==============================================================================
- # • User32
- #==============================================================================
- Dax.register(:user32, "Dax", 1.0, "18/05/13")
- module User32
- GSM = Win32API.new('user32', 'GetSystemMetrics', 'I', 'I')
- SetWindowPos = Win32API.new('user32', 'SetWindowPos', 'LLIIIII', 'I')
- SetWindowLong = Win32API.new('user32', 'SetWindowLong', 'LIL', 'L')
- Keybd_Event = Win32API.new('user32', 'keybd_event', 'LLLL', '')
- FindWindow = Win32API.new('user32', 'FindWindow', 'PP', 'L')
- GetDesktopWindow = Win32API.new('user32', 'GetDesktopWindow', '', 'L')
- GetWindowInfo = Win32API.new('user32', 'GetWindowInfo', 'LP', 'I')
- SetForegroundWindow = Win32API.new('user32', 'SetForegroundWindow', 'L', 'L')
- GetCursorPos = Win32API.new('user32', 'GetCursorPos', 'P', 'I')
- ShowCursor = Win32API.new('user32', 'ShowCursor', 'L', 'L')
- ScreenToClient = Win32API.new('user32', 'ScreenToClient', 'LP', 'I')
- GetKeyState = Win32API.new('user32', 'GetKeyState', 'I', 'I')
- GetAsyncKeyState = Win32API.new('user32', 'GetAsyncKeyState', 'I', 'I')
- # GSM Constants: Visit the site: microsoft msdn
- # http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx
- SM_CXSCREEN = 0 # Width of the current master screen resolution
- SM_CYSCREEN = 1 # Height of the current master screen resolution
- SM_CXVSCROLL = 2 # Width of a vertical scroll bar
- SM_CYHSCROLL = 3 # Height of a horizontal scroll bar
- SM_CYCAPTION = 4 # Height of a caption area
- SM_CXBORDER = 5 # Width of a window border
- SM_CYBORDER = 6 # Height of a window border
- SM_CXDLGFRAME = 7
- SM_CXFIXEDFRAME = 7 # Width of non-resizable captioned window frame
- SM_CYDLGFRAME = 8
- SM_CYFIXEDFRAME = 8 # Height of non-resizable captioned window frame
- SM_CYVTHUMB = 9 # Height of a thumb button on vertical scrollbars
- SM_CXHTHUMB = 10 # Width of a thumb button on horizontal scrollbars
- SM_CXICON = 11 # Default width of an icon
- SM_CYICON = 12 # Default height of an icon
- SM_CXCURSOR = 13 # Width of a cursor
- SM_CYCURSOR = 14 # Height of a cursor
- SM_CYMENU = 15 # Height of a single-line menu bar
- SM_CXFULLSCREEN = 16 # Width of client rect for a full-screen window
- SM_CYFULLSCREEN = 17 # Height of client rect for a full-screen window
- SM_CYKANJIWINDOW = 18 # Height of kanji window at bottom of screen, if there
- SM_MOUSEPRESENT = 19 # Non-zero if mouse is present; 0 if not
- SM_CYVSCROLL = 20 # Height of the arrow bitmap on vertical scrollbars
- SM_CXHSCROLL = 21 # Width of the arrow bitmap on horizontal scrollbars
- SM_DEBUG = 22 # Non-zero if debug User.exe is installed; 0 if not
- SM_SWAPBUTTON = 23 # Non-zero if mouse button values are swapped
- SM_CXMIN = 28 # Minimum width of a window
- SM_CYMIN = 29 # Minimum height of a window
- SM_CXSIZE = 30 # Width of a button in a window caption or title bar
- SM_CYSIZE = 31 # Height of a button in a window caption or title bar
- SM_CXFRAME = 32
- SM_CXSIZEFRAME = 32 # Width of the sizing border around a resizable window
- SM_CYFRAME = 33
- SM_CYSIZEFRAME = 33 # Height of the sizing border around a resizable window
- SM_CXMINTRACK = 34 # Minimum "tracking" width of a window
- SM_CYMINTRACK = 35 # Minimum "tracking" height of a window
- SM_CXDOUBLECLK = 36 # Width of rect which second click must be in for double
- SM_CYDOUBLECLK = 37 # Hght of rect which second click must be in for double
- SM_CXICONSPACING = 38 # Width of a grid cell for items in large icon view
- SM_CYICONSPACING = 39 # Height of a grid cell for items in large icon view
- SM_MENUDROPALIGNMENT = 40 # 0 if drop-down menus are left-aligned...
- SM_PENWINDOWS = 41 # Non-zero if Microsoft Windows for Pen computing
- # extensions are installed; 0 if not
- SM_DBCSENABLED = 42 # Non-zero if user32.dll supports DBCS; 0 if not
- SM_CMOUSEBUTTONS = 43 # Number of available mouse buttons, or 0 for no mouse
- SM_SECURE = 44 # Always returns 0
- SM_CXEDGE = 45 # Width of a 3-D style border
- SM_CYEDGE = 46 # Height of a 3-D style border
- SM_CXMINSPACING = 47 # Width of a grid cell for minimized windows
- SM_CYMINSPACING = 48 # Height of a grid cell for minimized windows
- SM_CXSMICON = 49 # Recommended width of a small icon
- SM_CYSMICON = 50 # Recommended height of a small icon
- SM_CYSMCAPTION = 51 # Height of a small caption
- SM_CXSMSIZE = 52 # Width of small caption buttons
- SM_CYSMSIZE = 53 # Height of small caption buttons
- SM_CXMENUSIZE = 54 # Width of menu bar buttons
- SM_CYMENUSIZE = 55 # Height of menu bar buttons
- SM_ARRANGE = 56 # Flags about how system the arranges minimized windows
- SM_CXMINIMIZED = 57 # Width of a minimized window
- SM_CYMINIMIZED = 58 # Height of a minimized window
- SM_CXMAXTRACK = 59 # Default maximum width of resizable windows
- SM_CYMAXTRACK = 60 # Default maximum height of resizable windows
- SM_CXMAXIMIZED = 61 # Default width of maximized top-level window
- SM_CYMAXIMIZED = 62 # Default height of maximized top-level window
- SM_NETWORK = 63 # The least significant bit is set if a network is
- # present; otherwise, it is cleared
- SM_CLEANBOOT = 67 # System boot type; 0:Normal, 1:Safe, 2:Safe w/network
- SM_CXDRAG = 68
- SM_CYDRAG = 69 # Number of pixels mouse can move before initiating drag
- SM_SHOWSOUNDS = 70 # Non-zero if user requires visible output; 0 if not
- SM_CXMENUCHECK = 71 # Width of the default menu check-mark bitmap
- SM_CYMENUCHECK = 72 # Height of the default menu check-mark bitmap
- SM_SLOWMACHINE = 73 # Non-zero if system has a slow processor; 0 if not
- # No, seriously, that's what Microsoft said!
- SM_MIDEASTENABLED = 74 # Non-zero if system can use Hebrew, Arabic languages
- SM_MOUSEWHEELPRESENT = 75 # Nonzero mouse has vertical scroll wheel; 0 if not
- SM_XVIRTUALSCREEN = 76 # Coordinates of the left side of the virtual screen
- SM_YVIRTUALSCREEN = 77 # Coordinates of the top of the virtual screen
- SM_CXVIRTUALSCREEN = 78 # Virtual width of all screens put together
- SM_CYVIRTUALSCREEN = 79 # Virtual height of all screen put together
- SM_CMONITORS = 80 # Numbers of display monitors on a desktop
- SM_SAMEDISPLAYFORMAT = 81 # Non-zero if all screen use same color depth...
- # SetWindowPos constants
- HWND_NOTOPMOST = -2 # Make window not always on top (and bring to front)
- HWND_TOPMOST = -1 # Put window in front and make it always on top
- HWND_TOP = 0 # Put window in front of all non-topmost windows
- HWND_BOTTOM = 1 # Put window behind all other windows
- SWP_NOSIZE = 0x0001 # Keep current size (ignores w and h)
- SWP_NOMOVE = 0x0002 # Keep current position (ignores X and Y)
- SWP_NOZORDER = 0x0004 # Keep current Z order (ignores hWndInsertAfter)
- SWP_NOREDRAW = 0x0008 # Does NOT redraw changes
- SWP_NOACTIVATE = 0x0010 # Does NOT automatically activate the window
- SWP_FRAMECHANGED = 0x0020 # Applies new frame styles set with SetWindowLong
- SWP_SHOWWINDOW = 0x0040 # Displays the window
- SWP_HIDEWINDOW = 0x0080 # Hides the window
- SWP_NOCOPYBITS = 0x0100 # Discards the entire contents of the client area
- SWP_NOOWNERZORDER = 0x0200 # Doesn't change the window display order
- SWP_NOSENDCHANGING = 0x0400 # Don't send WM_WINDOWPOSCHANGING
- SWP_DEFERERASE = 0x2000 # Prevents generation of the WM_SYNCPAINT message
- SWP_ASYNCWINDOWPOS = 0x4000 # Use if calling thread does not own the window
- # SetWindowLong constants
- GWL_USERDATA = -21 # Sets data reserved for use by the application
- GWL_EXSTYLE = -20 # Sets a new extended window style
- GWL_STYLE = -16 # Sets a new window style
- GWL_ID = -12 # Sets a new identifier of the window
- GWL_HWNDPARENT = -8 # Sets a new parent hWnd
- GWL_HINSTANCE = -6 # Sets a new application instance handle
- GWL_WNDPROC = -4 # Sets a new addr for the window calling procedure
- # Only available when the hWnd parameter identifies a dialog box:
- DWL_MSGRESULT = 0 # Sets the return message of the dialog box proc
- DWL_DLGPROC = 4 # Sets the new address of the dialog box proc
- DWL_USER = 8 # Sets new extra information private to application
- # Window Styles (SetWindowLong(hWnd, GWL_STYLE, WS_*))
- WS_OVERLAPPED = 0x00000000 # Overlapped window has title and border
- WS_TABSTOP = 0x00010000 # Can receive focus from TAB key
- WS_GROUP = 0x00020000 # First control of group of controls
- WS_MAXIMIZEBOX = 0x00010000 # Has a mazimize button
- WS_MINIMIZEBOX = 0x00020000 # Has a minimize button
- WS_THICKFRAME = 0x00040000 # Has sizing border
- WS_SYSMENU = 0x00080000 # Has buttons on title bar (reqs WS_CAPTION)
- WS_HSCROLL = 0x00100000 # Has horizontal scroll bar
- WS_VSCROLL = 0x00200000 # Has vertical scroll bar
- WS_DLGFRAME = 0x00400000 # Dialog-style border. Cannot have title bar
- WS_BORDER = 0x00800000 # Thin border
- WS_CAPTION = 0x00C00000 # Has a title bar (implies WS_BORDER)
- WS_MAXIMIZE = 0x01000000 # Initially maximized
- WS_CLIPCHILDREN = 0x02000000 # Exclude area for children when drawing
- WS_CLIPSIBLINGS = 0x04000000 # Exclude sibling client rects when drawing
- WS_DISABLED = 0x08000000 # Initially disabled (no input)
- WS_VISIBLE = 0x10000000 # Initially visible
- WS_MINIMIZE = 0x20000000 # Initially minimized
- WS_CHILD = 0x40000000 # Child cannot have menu bar or WS_POPUP
- WS_POPUP = 0x80000000 # Popup window
- # Window style aliases
- WS_OVERLAPPEDWINDOW = WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_THICKFRAME|
- WS_MINIMIZEBOX|WS_MAXIMIZEBOX
- WS_POPUPWINDOW = WS_POPUP|WS_BORDER|WS_SYSMENU
- WS_CHILDWINDOW = WS_CHILD
- WS_TILED = WS_OVERLAPPED
- WS_ICONIC = WS_MINIMIZE
- WS_SIZEBOX = WS_THICKFRAME
- WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW
- end
- #==============================================================================
- # • Enumerables;
- #==============================================================================
- Dax.register(:enumerables)
- module Enumerables
- #----------------------------------------------------------------------------
- # • Retorna a uma nova array com todos os resultados retirando os zeros.
- #----------------------------------------------------------------------------
- def select_map(&aProc)
- map(&aProc).reject { |e| e.nil? }
- end
- end
- #==============================================================================
- # * String
- #==============================================================================
- Dax.register(:string)
- class String
- #----------------------------------------------------------------------------
- # * Método com a função de decodificar a base 64.
- #----------------------------------------------------------------------------
- def decode_base64
- self.unpack("m")[0]
- end
- #----------------------------------------------------------------------------
- # * Obtem a palavra do méio de uma frase/palavra
- #----------------------------------------------------------------------------
- def get_string_between(start_at, end_at)
- my_string = " #{self}"
- ini = my_string.index(start_at)
- return my_string if ini == 0
- ini += start_at.length
- length = my_string.index(end_at, ini).to_i - ini
- return my_string[ini,length]
- end
- #--------------------------------------------------------------------------
- # * retorna self em ASCII-8BIT
- #--------------------------------------------------------------------------
- def to_ascii
- API.convert_text(self, 65001, 0)
- end
- #--------------------------------------------------------------------------
- # * converte self em ASCII-8BIT
- #--------------------------------------------------------------------------
- def to_ascii!
- self.replace(self.to_ascii)
- end
- #--------------------------------------------------------------------------
- # * retorna self para UTF8
- #--------------------------------------------------------------------------
- def to_utf8
- API.convert_text(self, 0, 65001)
- end
- #--------------------------------------------------------------------------
- # * converte self em UTF8
- #--------------------------------------------------------------------------
- def to_utf8!
- self.replace(self.to_utf8)
- end
- #--------------------------------------------------------------------------
- # * Extrai os números.
- #--------------------------------------------------------------------------
- def extract_numbers
- self.scan(/-*\d+/).collect{|n|n.to_i}
- end
- end
- #==============================================================================
- # * Integer
- #==============================================================================
- Dax.register(:integer)
- class Integer
- #----------------------------------------------------------------------------
- # * Transformar o valor em porcentagem : Útil para fazer barras como por exemplo
- # barras de HP.
- # a : Valor atual.
- # b : Valor máximo.
- #----------------------------------------------------------------------------
- def to_p(a, b)
- self * a / b
- end
- #----------------------------------------------------------------------------
- # * Grid On : Multiplica o número pelo tamanho de uma grid.
- #----------------------------------------------------------------------------
- def grid_on(grid_size=32)
- return self * grid_size
- end
- #----------------------------------------------------------------------------
- # * Grid Off : Divide o número pelo tamanho de uma grid.
- #----------------------------------------------------------------------------
- def grid_off(grid_size=32)
- return self / grid_size
- end
- end
- #==============================================================================
- # * Float
- #==============================================================================
- Dax.register(:float)
- class Float
- #----------------------------------------------------------------------------
- # * Transformar em porcentagem :
- # a : Valor atual.
- # b : Valor máximo.
- #----------------------------------------------------------------------------
- def to_p(a, b)
- self * a / b
- end
- end
- #==============================================================================
- # * Color
- #==============================================================================
- Dax.register(:color)
- class Color
- #----------------------------------------------------------------------------
- # • Diminui a opacidade da cor, deixando-a opaca..
- #----------------------------------------------------------------------------
- def opacity
- self.set(self.red, self.green, self.blue, 128)
- end
- #----------------------------------------------------------------------------
- # • Inverte as cores.
- #----------------------------------------------------------------------------
- def invert!
- self.set(255-self.red, 255-self.green, 255-self.blue, self.alpha)
- end
- #----------------------------------------------------------------------------
- # • Reverter as cores.
- #----------------------------------------------------------------------------
- def revert
- colors = [self.red, self.green, self.blue, self.alpha].reverse!
- self.set(*colors)
- end
- #----------------------------------------------------------------------------
- # • Converte para string.
- #----------------------------------------------------------------------------
- def to_s
- "red: #{self.red}\nblue: #{self.blue}\ngreen: #{self.green}\nalpha: #{self.alpha}"
- end
- #----------------------------------------------------------------------------
- # • Comparar cores, retorna a [true] se for igual.. returna a [false] se não
- # for igual.
- #----------------------------------------------------------------------------
- def ==(color)
- (self.red == color.red and self.green == color.green and self.blue == color.blue and
- self.alpha == color.alpha) ? true : false
- end
- #----------------------------------------------------------------------------
- # • Retorna os valores da classe [COLOR] para hash;;
- #----------------------------------------------------------------------------
- def to_h
- return {
- red: self.red, green: self.green, blue: self.blue, alpha: self.alpha,
- }
- end
- #----------------------------------------------------------------------------
- # • Retorna os valores da classe [COLOR] para array;;
- #----------------------------------------------------------------------------
- def to_a
- return [self.red, self.green, self.blue, self.alpha]
- end
- end
- #==============================================================================
- # * ColorBasic
- #==============================================================================
- Dax.register(:colorbasic)
- module ColorBasic
- extend self
- #----------------------------------------------------------------------------
- # • Cores Hexadécimais
- # * ColorBasic.hex("ffffff") #=> 255, 255, 255 | Branco.
- #----------------------------------------------------------------------------
- def hex(color)
- Color.new(*color.scan(/../).map { |color| color.to_i(16)})
- end
- #----------------------------------------------------------------------------
- # • Cores em Index
- #----------------------------------------------------------------------------
- def [](id)
- case id
- when -1 then Color.new(255, 255, 255) # White
- when 0 then Color.new(240, 248, 255) # Alice Blue
- when 1 then Color.new(250, 235, 215) # Antique_White
- when 2 then Color.new(0, 255, 255) # Aqua
- when 3 then Color.new(127, 255, 255) # Aqua Marine
- when 4 then Color.new(240, 255, 255) # Azure
- when 5 then Color.new(245, 245, 220) # Beige
- when 6 then Color.new(255, 228, 196) # Bisque
- when 7 then Color.new(0, 0, 0) # Black
- when 8 then Color.new(255, 235, 205) # Blanchedalmond
- when 9 then Color.new(0, 0, 255) # Blue
- when 10 then Color.new(138, 43, 226) # Blue Violet
- when 11 then Color.new(165, 42, 42) # Brown
- when 12 then Color.new(222, 184, 135) # Burly Wood
- when 13 then Color.new(93, 158, 160) # Cadet Blue
- when 14 then Color.new(127, 255, 0) # Chatreuse
- when 15 then Color.new(210, 105, 30) # Chocolate
- when 16 then Color.new(255, 127, 80) # Coral
- when 17 then Color.new(100, 149, 237) # Corn Flower Blue
- when 18 then Color.new(255, 248, 220) # CornSilk
- when 19 then Color.new(220, 20, 60) # Crimson
- when 20 then Color.new(0, 255, 255) # Cyan
- when 21 then Color.new(0, 0, 139) # DarkBlue
- when 22 then Color.new(0, 139, 139) # DarkCyan
- when 23 then Color.new(184, 134, 11) # DarkGoldEnrod
- when 24 then Color.new(169, 169, 169) # Dark Gray
- when 25 then Color.new(0, 100, 0) # Dark Green
- when 26 then Color.new(189, 183, 107) # Dark Khaki
- when 27 then Color.new(139, 0, 139) # Dark Magenta
- when 28 then Color.new(85, 107, 47) # Dark Oliver Green
- when 29 then Color.new(255, 140, 0) # Dark Orange
- when 30 then Color.new(153, 50, 204) # Dark orchid
- when 31 then Color.new(139, 0, 0) # Dark Red
- when 32 then Color.new(233, 150, 120) # Dark Salmon
- when 33 then Color.new(143, 188, 143) # Dark Sea Green
- when 34 then Color.new(72, 61, 139) # Dark Slate Blue
- when 35 then Color.new(255, 255, 0) # Yellow
- when 36 then Color.new(255, 0, 0) # Red
- when 37 then Color.new(0, 255, 0) # Green
- when 38 then Color.new(255, 128, 0) # Orange
- end
- end
- #----------------------------------------------------------------------------
- # • Cor padrão.
- #----------------------------------------------------------------------------
- def default
- return self.hex "ffffff"
- end
- #----------------------------------------------------------------------------
- # • * Forma uma cor aleátoria, retornando para um objeto de Cor.
- #----------------------------------------------------------------------------
- def rand
- return Color.new(rand(256), rand(256), rand(256))
- end
- end
- #==============================================================================
- # • Rect
- #==============================================================================
- Dax.register(:rect)
- class Rect
- #----------------------------------------------------------------------------
- # • Verificar se está na área.
- #----------------------------------------------------------------------------
- def in?(x, y)
- x.between?(self.x, self.x + self.width) &&
- y.between?(self.y, self.y + self.height)
- end
- end
- #==============================================================================
- # • DMath
- #==============================================================================
- Dax.register(:dmath, 'Dax', 1.5, '04/05/13')
- module DMath
- extend self
- #----------------------------------------------------------------------------
- # • Clamp.
- #----------------------------------------------------------------------------
- def clamp(num, low, high)
- return num < low ? low : num > high ? high : low
- end
- #----------------------------------------------------------------------------
- # • Centralizar um objeto n'outro.
- #----------------------------------------------------------------------------
- def centralize_object(object, object_for_centralize)
- x = object.x + (object.width - object_for_centralize.width) / 2
- y = object.y + (object.height - object_for_centralize.height) / 2
- return x, y
- end
- #----------------------------------------------------------------------------
- # • Centralizar um objeto n'outro.
- #----------------------------------------------------------------------------
- def centralize_x(objectx, objectwidth, object_for_centralizewidth)
- return objectx + (objectwidth - object_for_centralizewidth) / 2
- end
- #----------------------------------------------------------------------------
- # • Centralizar um objeto n'outro.
- #----------------------------------------------------------------------------
- def centralize_y(objecty=0, objectheight = 0, object_for_centralizeheight=0)
- return objecty + (objectheight - object_for_centralizeheight) / 2
- end
- #----------------------------------------------------------------------------
- # • Rotc | Rotacionar.
- #----------------------------------------------------------------------------
- def rotc(vmn, v, vmx, c = 100)
- ((v - vmn) * c) / (vmx - vmn)
- end
- #----------------------------------------------------------------------------
- # • Obter o X do centro da tela para um determinado objeto|sprite,bitmap.
- #----------------------------------------------------------------------------
- def get_x_center_screen(width)
- return (Graphics.width - width) / 2
- end
- #----------------------------------------------------------------------------
- # • Obter o Y do centro da tela para um determinado objeto|sprite,bitmap.
- #----------------------------------------------------------------------------
- def get_y_center_screen(height)
- return (Graphics.height - height) / 2
- end
- #--------------------------------------------------------------------------
- # • Verifica se um objeto está na área. Círculo | Circle
- #--------------------------------------------------------------------------
- def circle(object, object2, size)
- ( (object.x - object2.x) ** 2) + ( (object.y - object2.y) ** 2) <= (size ** 2)
- end
- #----------------------------------------------------------------------------
- # • Converter em graus, multiplique a variável com isto.
- #----------------------------------------------------------------------------
- def graus
- 360 / (2 * Math::PI)
- end
- #----------------------------------------------------------------------------
- # • Radiano
- #----------------------------------------------------------------------------
- def radian(degree)
- return (degree.to_f/180) * Math::PI
- end
- #----------------------------------------------------------------------------
- # • Degree
- #----------------------------------------------------------------------------
- def degree(radian)
- return (radian.to_f/Math::PI) * 180
- end
- #----------------------------------------------------------------------------
- # • Para 4 decimals.
- #----------------------------------------------------------------------------
- def to_4_dec(n)
- ((n * 1000).ceil) / 1000
- end
- #----------------------------------------------------------------------------
- # • Área de um triângulo.
- #----------------------------------------------------------------------------
- def triangle_area(*args)
- x, y, x2, y2, x3, y3 = *args
- return (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y)
- end
- #----------------------------------------------------------------------------
- # • Calcular distância para scripts como sensor.
- #----------------------------------------------------------------------------
- def distance_sensor(target, target2)
- return (target.x - target2.x).abs + (target.y - target2.y).abs
- end
- end
- #==============================================================================
- # • Keyboard | Método para usar todas as teclas do teclado.
- #==============================================================================
- Dax.register(:key, "Dax", 1.0)
- module Key
- extend self
- #--------------------------------------------------------------------------
- # * Chaves diversos.
- #--------------------------------------------------------------------------
- CANCEL = 0x03 # Control-Break Processing
- BACKSPACE = 0x08 # Backspace Key
- TAB = 0x09 # Tab Key
- CLEAR = 0x0C # Clear Key
- ENTER = 0x0D # Enter Key
- SHIFT = 0x10 # Shift Key
- CONTROL = 0x11 # Ctrl Key
- MENU = 0x12 # Alt Key
- PAUSE = 0x13 # Pause Key
- ESC = 0x1B # Esc Key
- CONVERT = 0x1C # IME Convert Key
- NONCONVERT = 0x1D # IME Nonconvert Key
- ACCEPT = 0x1E # IME Accept Key
- SPACE = 0x20 # Space Bar Key (Space, usually blank)
- PRIOR = 0x21 # Page Up Key
- NEXT = 0x22 # Page Down Key
- ENDS = 0x23 # End Key
- HOME = 0x24 # Home Key
- LEFT = 0x25 # Left Arrow Key
- UP = 0x26 # Up Arrow Key
- RIGHT = 0x27 # Right Arrow Key
- DOWN = 0x28 # Down Arrow Key
- SELECT = 0x29 # Select Key
- PRINT = 0x2A # Print Key
- EXECUTE = 0x2B # Execute Key
- SNAPSHOT = 0x2C # Print Screen Key
- DELETE = 0x2E # Delete Key
- HELP = 0x2F # Help Key
- LSHIFT = 0xA0 # Left Shift Key
- RSHIFT = 0xA1 # Right Shift Key
- LCONTROL = 0xA2 # Left Control Key (Ctrl)
- RCONTROL = 0xA3 # Right Control Key (Ctrl)
- LMENU = 0xA4 # Left Menu Key (Alt)
- RMENU = 0xA5 # Right Menu Key (Alt)
- PACKET = 0xE7 # Used to Pass Unicode Characters as Keystrokes
- MOUSE_RIGHT = 0x01 # Button Mouse Right
- MOUSE_LEFT = 0x02 # Button Mouse Left
- MOUSE_MIDDLE = 0x04 # Button Mouse Middle
- #--------------------------------------------------------------------------
- # * Chaves de números.
- #--------------------------------------------------------------------------
- N0 = 0x30 # 0 Key
- N1 = 0x31 # 1 Key
- N2 = 0x32 # 2 Key
- N3 = 0x33 # 3 Key
- N4 = 0x34 # 4 Key
- N5 = 0x35 # 5 Key
- N6 = 0x36 # 6 Key
- N7 = 0x37 # 7 Key
- N8 = 0x38 # 8 Key
- N9 = 0x39 # 9 Key
- #--------------------------------------------------------------------------
- # * Chaves de letras
- #--------------------------------------------------------------------------
- A = 0x41 # A Key
- B = 0x42 # B Key
- C = 0x43 # C Key
- D = 0x44 # D Key
- E = 0x45 # E Key
- F = 0x46 # F Key
- G = 0x47 # G Key
- H = 0x48 # H Key
- I = 0x49 # I Key
- J = 0x4A # J Key
- K = 0x4B # K Key
- L = 0x4C # L Key
- M = 0x4D # M Key
- N = 0x4E # N Key
- O = 0x4F # O Key
- P = 0x50 # P Key
- Q = 0x51 # Q Key
- R = 0x52 # R Key
- S = 0x53 # S Key
- T = 0x54 # T Key
- U = 0x55 # U Key
- V = 0x56 # V Key
- W = 0x57 # W Key
- X = 0x58 # X Key
- Y = 0x59 # Y Key
- Z = 0x5A # Z Key
- #--------------------------------------------------------------------------
- # * Chaves de windows
- #--------------------------------------------------------------------------
- LWIN = 0x5B # Left Windows Key (Natural keyboard)
- RWIN = 0x5C # Right Windows Key (Natural Keyboard)
- APPS = 0x5D # Applications Key (Natural keyboard)
- SLEEP = 0x5F # Computer Sleep Key
- BROWSER_BACK = 0xA6 # Browser Back Key
- BROWSER_FORWARD = 0xA7 # Browser Forward Key
- BROWSER_REFRESH = 0xA8 # Browser Refresh Key
- BROWSER_STOP = 0xA9 # Browser Stop Key
- BROWSER_SEARCH = 0xAA # Browser Search Key
- BROWSER_FAVORITES = 0xAB # Browser Favorites Key
- BROWSER_HOME = 0xAC # Browser Start and Home Key
- VOLUME_MUTE = 0xAD # Volume Mute Key
- VOLUME_DOWN = 0xAE # Volume Down Key
- VOLUME_UP = 0xAF # Volume Up Key
- MEDIA_NEXT_TRACK = 0xB0 # Next Track Key
- MEDIA_PREV_TRACK = 0xB1 # Previous Track Key
- MEDIA_STOP = 0xB2 # Stop Media Key
- MEDIA_PLAY_PAUSE = 0xB3 # Play/Pause Media Key
- LAUNCH_MAIL = 0xB4 # Start Mail Key
- LAUNCH_MEDIA_SELECT = 0xB5 # Select Media Key
- LAUNCH_APP1 = 0xB6 # Start Application 1 Key
- LAUNCH_APP2 = 0xB7 # Start Application 2 Key
- PROCESSKEY = 0xE5 # IME Process Key
- ATTN = 0xF6 # Attn Key
- CRSEL = 0xF7 # CrSel Key
- EXSEL = 0xF8 # ExSel Key
- EREOF = 0xF9 # Erase EOF Key
- PLAY = 0xFA # Play Key
- ZOOM = 0xFB # Zoom Key
- PA1 = 0xFD # PA1 Key
- #--------------------------------------------------------------------------
- # * Chaves do Numpad
- #--------------------------------------------------------------------------
- NUMPAD0 = 0x60 # Numeric Keypad 0 Key
- NUMPAD1 = 0x61 # Numeric Keypad 1 Key
- NUMPAD2 = 0x62 # Numeric Keypad 2 Key
- NUMPAD3 = 0x63 # Numeric Keypad 3 Key
- NUMPAD4 = 0x64 # Numeric Keypad 4 Key
- NUMPAD5 = 0x65 # Numeric Keypad 5 Key
- NUMPAD6 = 0x66 # Numeric Keypad 6 Key
- NUMPAD7 = 0x67 # Numeric Keypad 7 Key
- NUMPAD8 = 0x68 # Numeric Keypad 8 Key
- NUMPAD9 = 0x69 # Numeric Keypad 9 Key
- MULTIPLY = 0x6A # Multiply Key (*)
- ADD = 0x6B # Add Key (+)
- SEPARATOR = 0x6C # Separator Key
- SUBTRACT = 0x6D # Subtract Key (-)
- DECIMAL = 0x6E # Decimal Key (.)
- DIVIDE = 0x6F # Divide Key (/)
- #--------------------------------------------------------------------------
- # * Chaves de funções
- #--------------------------------------------------------------------------
- F1 = 0x70 # F1 Key
- F2 = 0x71 # F2 Key
- F3 = 0x72 # F3 Key
- F4 = 0x73 # F4 Key
- F5 = 0x74 # F5 Key
- F6 = 0x75 # F6 Key
- F7 = 0x76 # F7 Key
- F8 = 0x77 # F8 Key
- F9 = 0x78 # F9 Key
- F10 = 0x79 # F10 Key
- F11 = 0x7A # F11 Key
- F12 = 0x7B # F12 Key
- F13 = 0x7C # F13 Key
- F14 = 0x7D # F14 Key
- F15 = 0x7E # F15 Key
- F16 = 0x7F # F16 Key
- F17 = 0x80 # F17 Key
- F18 = 0x81 # F18 Key
- F19 = 0x82 # F19 Key
- F20 = 0x83 # F20 Key
- F21 = 0x84 # F21 Key
- F22 = 0x85 # F22 Key
- F23 = 0x86 # F23 Key
- F24 = 0x87 # F24 Key
- #--------------------------------------------------------------------------
- # * Chaves alternativas
- #--------------------------------------------------------------------------
- CAPITAL = 0x14 # Caps Lock Key
- KANA = 0x15 # IME Kana Mode Key
- HANGUL = 0x15 # IME Hangul Mode Key
- JUNJA = 0x17 # IME Junja Mode Key
- FINAL = 0x18 # IME Final Mode Key
- HANJA = 0x19 # IME Hanja Mode Key
- KANJI = 0x19 # IME Kanji Mode Key
- MODECHANGE = 0x1F # IME Mode Change Request Key
- INSERT = 0x2D # Insert Key
- NUMLOCK = 0x90 # Num Lock Key
- SCROLL = 0x91 # Scroll Lock Key
- #--------------------------------------------------------------------------
- # * Chaves OEM, variadas
- #--------------------------------------------------------------------------
- OEM_1 = 0xBA # Misc Characters (; : in USA 101/102 Keyboards)
- OEM_PLUS = 0xBB # + = Key
- OEM_COMMA = 0xBC # , < Key
- OEM_MINUS = 0xBD # - _ Key
- OEM_PERIOD = 0xBE # . > Key
- OEM_2 = 0xBF # Misc Characters (/ ? in USA 101/102 Keyboards)
- OEM_3 = 0xC0 # Misc Characters (` ~ in USA 101/102 Keyboards)
- OEM_4 = 0xDB # Misc Characters ([ { in USA 101/102 Keyboards)
- OEM_5 = 0xDC # Misc Characters (\ | in USA 101/102 Keyboards)
- OEM_6 = 0xDD # Misc Characters (] } in USA 101/102 Keyboards)
- OEM_7 = 0xDE # Misc Characters (' " in USA 101/102 Keyboards)
- OEM_8 = 0xDF # Misc Characters (Varies by Keyboard)
- OEM_9 = 0xE1 # OEM Specific
- OEM_10 = 0x92 # OEM Specific
- OEM_11 = 0x93 # OEM Specific
- OEM_12 = 0x94 # OEM Specific
- OEM_13 = 0x95 # OEM Specific
- OEM_14 = 0x96 # OEM Specific
- OEM_15 = 0xE3 # OEM Specific
- OEM_16 = 0xE4 # OEM Specific
- OEM_17 = 0xE6 # OEM Specific
- OEM_18 = 0xE9 # OEM Specific
- OEM_19 = 0xEA # OEM Specific
- OEM_20 = 0xEB # OEM Specific
- OEM_21 = 0xEC # OEM Specific
- OEM_22 = 0xED # OEM Specific
- OEM_23 = 0xEE # OEM Specific
- OEM_24 = 0xEF # OEM Specific
- OEM_25 = 0xF1 # OEM Specific
- OEM_26 = 0xF2 # OEM Specific
- OEM_27 = 0xF3 # OEM Specific
- OEM_28 = 0xF4 # OEM Specific
- OEM_29 = 0xF5 # OEM Specific
- OEM_102 = 0xE2 # Angle Bracket or Backslash on RT-102 Keyboards
- OEM_CLEAR = 0xFE # Clear Key
- #--------------------------------------------------------------------------
- # * Variáveis do módulo.
- #--------------------------------------------------------------------------
- @unpack_string = 'b'*256
- @last_array = '0'*256
- @press = Array.new(256, false)
- @trigger = Array.new(256, false)
- @repeat = Array.new(256, false)
- @release = Array.new(256, false)
- @repeat_counter = Array.new(256, 0)
- @getKeyboardState = API::GetKeyboardState
- @getAsyncKeyState = API::GetAsyncKeyState
- @getKeyboardState.call(@last_array)
- @last_array = @last_array.unpack(@unpack_string)
- for i in 0...@last_array.size
- @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
- end
- #--------------------------------------------------------------------------
- # * Atualização dos objetos do módulo.
- #--------------------------------------------------------------------------
- def update
- @trigger = Array.new(256, false)
- @repeat = Array.new(256, false)
- @release = Array.new(256, false)
- array = '0'*256
- @getKeyboardState.call(array)
- array = array.unpack(@unpack_string)
- for i in 0...array.size
- if array[i] != @last_array[i]
- @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
- if @repeat_counter[i] <= 0 && @press[i]
- @repeat[i] = true
- @repeat_counter[i] = 15
- end
- if !@press[i]
- @release[i] = true
- else
- @trigger[i] = true
- end
- else
- if @press[i] == true
- @press[i] = @getAsyncKeyState.call(i) == 0 ? false : true
- @release[i] = true if !@press[i]
- end
- if @repeat_counter[i] > 0 && @press[i] == true
- @repeat_counter[i] -= 1
- elsif @repeat_counter[i] <= 0 && @press[i] == true
- @repeat[i] = true
- @repeat_counter[i] = 3
- elsif @repeat_counter[i] != 0
- @repeat_counter[i] = 0
- end
- end
- end
- @last_array = array
- end
- #--------------------------------------------------------------------------
- # * Get Key Pressed State
- # key : key index
- #--------------------------------------------------------------------------
- def press?(key)
- return @press[key]
- end
- #--------------------------------------------------------------------------
- # * Get Key Triggered State
- # key : key index
- #--------------------------------------------------------------------------
- def trigger?(key)
- return @trigger[key]
- end
- #--------------------------------------------------------------------------
- # * Get Key Repeated State
- # key : key index
- #--------------------------------------------------------------------------
- def repeat?(key)
- return @repeat[key]
- end
- #--------------------------------------------------------------------------
- # * Get Key Released State
- # key : key index
- #--------------------------------------------------------------------------
- def release?(key)
- return @release[key]
- end
- end
- #==============================================================================
- # • Sprite
- #==============================================================================
- Dax.register(:sprite)
- class Sprite
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância.
- #----------------------------------------------------------------------------
- attr_accessor :clone_sprite
- #----------------------------------------------------------------------------
- # • Novo método.
- #----------------------------------------------------------------------------
- alias new_initialize initialize
- def initialize(viewport=nil)
- @clone_sprite = []
- if viewport.is_a?(String)
- new_initialize(nil)
- if viewport.match(/S: ([^>]*)/)
- self.bitmap = Cache.system($1.to_s)
- elsif viewport.match(/P: ([^>]*)/)
- self.bitmap = Cache.picture($1.to_s)
- elsif viewport.match(/G: ([^>]*)/)
- self.bitmap = Bitmap.new("Graphics/#{$1.to_s}")
- else
- self.bitmap = Bitmap.new(viewport)
- end
- elsif viewport.is_a?(Array)
- if viewport.size == 2
- new_initialize(nil)
- self.bitmap = Bitmap.new(viewport[0], viewport[1])
- elsif viewport.size == 5
- new_initialize(nil)
- self.bitmap = Bitmap.new(viewport[0], viewport[1])
- self.x, self.y, self.z = viewport[2], viewport[3], viewport[4]
- end
- elsif viewport.is_a?(Viewport) or viewport.nil?
- new_initialize(viewport)
- end
- end
- #----------------------------------------------------------------------------
- # • Slide pela direita.
- # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
- #----------------------------------------------------------------------------
- def slide_right(speed, point)
- self.x += speed unless self.x >= point
- end
- #----------------------------------------------------------------------------
- # • Slide pela esquerda.
- # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
- #----------------------------------------------------------------------------
- def slide_left(speed, point)
- self.x -= speed unless self.x <= point
- end
- #----------------------------------------------------------------------------
- # • Slide por cima.
- # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
- #----------------------------------------------------------------------------
- def slide_up(speed, point)
- self.y -= speed unless self.y <= point
- end
- #----------------------------------------------------------------------------
- # • Slide por baixo.
- # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
- #----------------------------------------------------------------------------
- def slide_down(speed, point)
- self.y += speed unless self.y >= point
- end
- #----------------------------------------------------------------------------
- # • Define aqui uma posição fixa para um objeto.
- #----------------------------------------------------------------------------
- def position(command=0)
- return if command.nil?
- case command
- when 0 then self.x = 0
- when 1 then self.x = (Graphics.width - self.width) / 2
- when 2 then self.x = Graphics.width - self.width
- when 3 then self.y = 0
- when 4 then self.y = (Graphics.height - self.height) / 2
- when 5 then self.y = Graphics.height - self.height
- when :center
- self.x = (Graphics.width - self.width) / 2
- self.y = Graphics.height / 2 - self.height / 2
- when :center_left
- self.x = 0
- self.y = (Graphics.height - self.height) / 2
- when :center_right
- self.x = Graphics.width - self.height
- self.y = (Graphics.height - self.height) / 2
- end
- end
- #----------------------------------------------------------------------------
- # • Tamanho geral
- #----------------------------------------------------------------------------
- def size
- return self.width + self.height
- end
- #----------------------------------------------------------------------------
- # • Rect
- #----------------------------------------------------------------------------
- def rect
- return self.bitmap.rect
- end
- #----------------------------------------------------------------------------
- # • Base para função de clone.
- # * depht : Prioridade no mapa.
- # * clone_bitmap : Se irá clonar o bitmap.
- #----------------------------------------------------------------------------
- def clone(depht=0, clone_bitmap=false)
- @clone_sprite.delete_if { |bitmap| bitmap.disposed? }
- cloned = Sprite.new(self.viewport)
- cloned.x, cloned.y = self.x, self.y
- cloned.bitmap = self.bitmap
- cloned.bitmap = self.bitmap.clone if clone_bitmap
- unless depht == 0
- cloned.z = self.z + depht
- else
- @clone_sprite.each { |sprite| sprite.z -= 1 }
- cloned.z = self.z - 1
- end
- cloned.src_rect.set(self.src_rect)
- ["zoom_x", "zoom_y", "angle", "mirror", "opacity", "blend_type", "visible",
- "bush_depht", "bush_opacity", "ox", "oy"].each { |meth|
- eval("cloned.#{meth} = self.#{meth}")
- }
- cloned.color.set(color)
- cloned.tone.set(tone)
- after_clone(cloned)
- @clone_sprite.push(cloned)
- return cloned
- end
- #----------------------------------------------------------------------------
- # • Efeito após ter clonado.
- #----------------------------------------------------------------------------
- def after_clone(clone)
- end
- end
- #==============================================================================
- # • Bitmap
- #==============================================================================
- Dax.register(:bitmap)
- class Bitmap
- #-------------------------------------------------------------------------
- # Desenhar meter... Gradient
- #-------------------------------------------------------------------------
- def draw_meter_line(x, y, min, max, width = 156, height = 4,
- bar_start = Color.new(255, 0, 0, 192), bar_end = Color.new(255, 255, 0, 192),
- background = Color.new(0, 0, 0, 128))
- w = width * min / max
- 4.times do
- fill_rect(x + 8, y + 4, width, height / 4, background)
- draw_gradient_line(x, y, x + w, y, height / 4, bar_start, bar_end)
- x -= 1
- y += height / 4
- end
- end
- #----------------------------------------------------------------------------
- # • Definir gradiente..
- #----------------------------------------------------------------------------
- def gradient_color(colors, width, percentage)
- width_per = ((width * 1.0) * percentage)
- width_per = width_per.round
- if colors.size == 1
- return colors[0]
- elsif colors.size > 1
- i = 0
- sections_per = (1.0 / colors.size)
- equationa = (sections_per * colors.size)
- equationb = (sections_per * (colors.size - 1))
- if equationa >= percentage and equationb < percentage
- i = (colors.size - 1)
- else
- for j in 0..(colors.size - 1)
- equationc = (sections_per * (j + 1))
- equationd = (sections_per * (j + 2))
- if equationc < percentage and equationd > percentage
- i = j + 1
- end
- end
- end
- if i == (colors.size - 1)
- for k in 0..width
- if k == width_per
- r = colors[i - 1].red * (width - k) / width + colors[i].red * k / width
- g = colors[i - 1].green * (width - k) / width + colors[i].green * k / width
- b = colors[i - 1].blue * (width - k) / width + colors[i].blue * k / width
- a = colors[i - 1].alpha * (width - k) / width + colors[i].alpha * k / width
- return Color.new(r,g,b,a)
- end
- end
- else
- for k in 0..width
- if k == width_per
- r = colors[i].red * (width - k) / width + colors[i + 1].red * k / width
- g = colors[i].green * (width - k) / width + colors[i + 1].green * k / width
- b = colors[i].blue * (width - k) / width + colors[i + 1].blue * k / width
- a = colors[i].alpha * (width - k) / width + colors[i + 1].alpha * k / width
- return Color.new(r,g,b,a)
- end
- end
- end
- elsif colors.size < 1
- msgbox 'ERROR : No Colors Were Supplied'
- exit
- end
- end
- #----------------------------------------------------------------------------
- # • Barra.
- #----------------------------------------------------------------------------
- def bar(color, actual, max, borda=1)
- rate = self.width.to_p(actual, max)
- self.fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
- color)
- end
- #----------------------------------------------------------------------------
- # • Barra em forma de gradient;.
- #----------------------------------------------------------------------------
- def gradient_bar(color, actual, max, borda=1)
- rate = self.width.to_p(actual, max)
- self.gradient_fill_rect(borda, borda, rate-(borda*2), self.height-(borda*2),
- color[0], color[1], 2)
- end
- #----------------------------------------------------------------------------
- # • Efeito de Shader Sill
- #----------------------------------------------------------------------------
- def shader_sill
- ra = 500
- re = 0 ; gr = 0 ; bl = 0
- for i in 1..(self.height-1)
- for j in 1..(self.width-1)
- for m in -1..1
- for n in -1..1
- if m != 0 and n != 0
- a = self.get_pixel(j+m,i+n)
- re = re + a.red
- gr = gr + a.green
- bl = bl + a.blue
- end
- end
- end
- b = self.get_pixel(j,i)
- re = (b.red-re/8).abs
- gr = (b.green-gr/8).abs
- bl = (b.blue-bl/8).abs
- self.set_pixel(j,i,Color.new(0, 0, 0, b.alpha) )
- end
- end
- end
- #--------------------------------------------------------------------------
- # * Desenho do gráfico do personagem
- # character_name : nome do gráfico do personagem
- # character_index : índice do gráfico de personagem
- # x : coordenada X
- # y : coordenada Y
- #--------------------------------------------------------------------------
- def draw_character(character_name, character_index, x, y)
- return unless character_name
- bitmap = Cache.character(character_name)
- sign = character_name[/^[\!\$]./]
- if sign && sign.include?('$')
- cw = bitmap.width / 3
- ch = bitmap.height / 4
- else
- cw = bitmap.width / 12
- ch = bitmap.height / 8
- end
- n = character_index
- src_rect = Rect.new((n%4*3+1)*cw, (n/4*4)*ch, cw, ch)
- self.blt(x - cw / 2, y - ch, bitmap, src_rect)
- end
- #--------------------------------------------------------------------------
- # * Desenho do gráfico de personagem do herói
- # actor : herói
- # x : coordenada X
- # y : coordenada Y
- #--------------------------------------------------------------------------
- def draw_actor_graphic(actor, x, y)
- draw_character(actor.character_name, actor.character_index, x, y)
- end
- #----------------------------------------------------------------------------
- # • Limpar uma área num formato de círculo.
- #----------------------------------------------------------------------------
- def clear_rect_circle(x, y, r)
- rr = r*r
- for i in 0...r
- adj = Math.sqrt(rr - (i*i)).ceil
- xd = x - adj
- wd = 2 * adj
- self.clear_rect(xd, y-i, wd, 1)
- self.clear_rect(xd, y+i, wd, 1)
- end
- end
- #----------------------------------------------------------------------------
- # • Novo modo de desenhar textos. Configurações já especificadas.
- #----------------------------------------------------------------------------
- def draw_text_rect(*args)
- self.draw_text(self.rect, *args)
- end
- #----------------------------------------------------------------------------
- # • Salvar em png.
- # --- Autor : Gab! ---
- #----------------------------------------------------------------------------
- def save(file_name)
- def chunk(type, data)
- [data.size, type, data, Zlib.crc32(type + data)].pack("NA4A*N")
- end
- img_data = ""
- width, height = self.width, self.height
- for j in 0...(height)
- img_data << "\0"
- for i in 0...(width)
- pos_c = self.get_pixel(i, j)
- img_data << [pos_c.red, pos_c.green, pos_c.blue, pos_c.alpha].pack("C*")
- end
- end
- c = [
- "\x89PNG\r\n\x1a\n",
- chunk("IHDR", [width, height, 8, 6, 0, 0, 0].pack("N2C5")),
- chunk("IDAT", Zlib::Deflate.deflate(img_data)),
- chunk("IEND", "")
- ]
- File.open(file_name, "wb"){|file| c.each{|chunk| file.write(chunk) }}
- end
- #----------------------------------------------------------------------------
- # • Efeito negativo.
- #----------------------------------------------------------------------------
- def negative
- for i in 0...(self.width)
- for j in 0...(self.height)
- pix = self.get_pixel(i, j)
- pix.red = (pix.red - 255) * -1
- pix.blue = (pix.blue - 255) * -1
- pix.green = (pix.green - 255) * -1
- self.set_pixel(i, j, pix)
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Grayscale
- #----------------------------------------------------------------------------
- def grayscale(rect = Rect.new(0, 0, self.width, self.height))
- for i in rect.x...rect.x + rect.width
- for j in rect.y...rect.y + rect.height
- colour = self.get_pixel(i,j)
- grey_pixel = (colour.red*0.3 + colour.green*0.59 + colour.blue*0.11)
- colour.red = colour.green = colour.blue = grey_pixel
- self.set_pixel(i,j,colour)
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Novo fornecedor de pixel.
- #----------------------------------------------------------------------------
- def set_pixel_s(x, y, color, size)
- for i in 0...size
- self.set_pixel(x+i, y, color)
- self.set_pixel(x-i, y, color)
- self.set_pixel(x, y+i, color)
- self.set_pixel(x, y-i, color)
- self.set_pixel(x+i, y+i, color)
- self.set_pixel(x-i, y-i, color)
- self.set_pixel(x+i, y-i, color)
- self.set_pixel(x-i, y+i, color)
- end
- end
- #----------------------------------------------------------------------------
- # • Desenhar uma linha.
- #----------------------------------------------------------------------------
- def draw_line(start_x, start_y, end_x, end_y, color, size=1)
- set_pixel_s(start_x, start_y, color, size)
- distance = (start_x - end_x).abs + (start_y - end_y).abs
- for i in 1..distance
- x = (start_x + 1.0 * (end_x - start_x) * i / distance).to_i
- y = (start_y + 1.0 * (end_y - start_y) * i / distance).to_i
- set_pixel_s(x, y, color, size)
- end
- set_pixel_s(end_x, end_y, color, size)
- end
- #----------------------------------------------------------------------------
- # • draw_bar_gauge(x, y, current, current_max, border, colors)
- # x : Coordenadas X.
- # y : Coordenadas Y.
- # current : Valor atual da barra.
- # current_max : Valor maxímo da barra.
- # border : Expressura da borda.
- # colors : Cores. [0, 1, 2]
- #----------------------------------------------------------------------------
- # Permite adicionar uma barra.
- #----------------------------------------------------------------------------
- def draw_bar_gauge(x, y, current, current_max, colors=[])
- cw = self.width.to_p(current, current_max)
- ch = self.height
- self.gradient_fill_rect(x, y, self.width, self.height, colors[0], colors[1])
- src_rect = Rect.new(0, 0, cw, ch)
- self.blt(x, y, self, src_rect)
- end
- #----------------------------------------------------------------------------
- # • draw_icon(icon_index, x, y, enabled)
- # icon_index : ID do ícone.
- # x : Coordenadas X.
- # y : Coordenadas Y.
- # enabled : Habilitar flag, translucido quando false
- #----------------------------------------------------------------------------
- #----------------------------------------------------------------------------
- def draw_icon(icon_index, x, y, enabled = true)
- icon_index = icon_index.nil? ? 0 : icon_index
- bitmap = Cache.system("Iconset")
- rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
- self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
- end
- #----------------------------------------------------------------------------
- # • draw_gradation_gauge(x, y, width, height, current, current_max, border, colors, align)
- # x : Coordenadas X.
- # y : Coordenadas Y.
- # width : Largura da barra.
- # height : Altura da barra.
- # current : Valor atual da barra.
- # current_max : Valor maxímo da barra.
- # border : Expressura da borda.
- # colors : Cores. [0, 1, 2]
- # align : Alinhamento.
- #----------------------------------------------------------------------------
- # Permite adicionar uma barra.
- #----------------------------------------------------------------------------
- def draw_gradation_gauge(x, y, current, current_max, border, colors=[])
- cw = self.width.to_p(current, current_max)
- ch = self.height
- self.fill_rect(x, y, self.width, self.height, colors[0])
- self.gradient_fill_rect(x+border, y+border, self.width-(border/2), self.height-(border/2), colors[1], colors[2])
- src_rect = Rect.new(0, 0, cw, ch)
- self.blt(x, y, self, src_rect)
- end
- #--------------------------------------------------------------------------
- # • Desenho do gráfico de rosto
- # face_name : nome do gráfico de face
- # face_index : índice do gráfico de face
- # x : coordenada X
- # y : coordenada Y
- # enabled : habilitar flag, translucido quando false
- #--------------------------------------------------------------------------
- def draw_face(face_name, face_index, x, y, enabled = true)
- bitmap = Cache.face(face_name)
- rect = Rect.new(face_index % 4 * 96, face_index / 4 * 96, 96, 96)
- self.blt(x, y, bitmap, rect, enabled ? 255 : 128)
- end
- #--------------------------------------------------------------------------
- # • Desenho do gráfico de face do herói
- # actor : herói
- # x : coordenada X
- # y : coordenada Y
- # enabled : habilitar flag, translucido quando false
- #--------------------------------------------------------------------------
- def draw_actor_face(actor, x, y, enabled = true)
- draw_face(actor.face_name, actor.face_index, x, y, enabled)
- end
- #--------------------------------------------------------------------------
- # • Desenho do nível
- # actor : herói
- # x : coordenada X
- # y : coordenada Y
- #--------------------------------------------------------------------------
- def draw_actor_level(actor, x, y)
- self.font.name = "Comic Sans MS"
- self.font.color = ColorBasic[35]
- self.font.size = 18
- self.draw_text(x, y, 32, 20, Vocab::level_a)
- self.font.size = 22
- draw_text(x + 16, y, 32, 20, actor.level, 2)
- end
- #----------------------------------------------------------------------------
- # • Desenhar um círuclo preenchido.
- #----------------------------------------------------------------------------
- def fill_circle(x, y, r, c)
- rr = r*r
- for i in 0...r
- adj = Math.sqrt(rr - (i*i)).ceil
- xd = x - adj
- wd = 2 * adj
- self.fill_rect(xd, y-i, wd, 1, c)
- self.fill_rect(xd, y+i, wd, 1, c)
- end
- end
- #----------------------------------------------------------------------------
- # • Desenhar um triângulo preenchido
- #----------------------------------------------------------------------------
- def fill_triangle3(pts, c, pos=[0, 0])
- return if pts.size != 3
- pts.sort! {|a, b| a[1] - b[1]}
- pt1, pt2, pt3 = pts
- dxt = (pt3[0] - pt1[0]) / 2
- dyt = (pt3[1] - pt1[1]) / 2
- dxm = pt2[0] - pt1[0]
- dym = pt2[1] - pt1[1]
- dm = dym.abs
- if dm > 0 and dyt != 0
- for i in 0...(dm+2)
- ix = ((dxm*i) / (dm+1))
- iy = ((dym*i) / (dm+1))
- edx = ix - (dxt * iy / dyt)
- self.fill_rect(ix+pt1[0]-[edx,0].max-2+pos[0], iy+pt1[1]+pos[1], edx.abs+4, 1, c)
- end
- end
- dxm = pt2[0] - pt3[0]
- dym = pt2[1] - pt3[1]
- dm = dym.abs
- if dm > 0 and dyt != 0
- for i in 0...(dm+2)
- ix = ((dxm*i) / (dm+1))
- iy = ((dym*i) / (dm+1))
- edx = ix - (dxt * iy / dyt)
- self.fill_rect(ix+pt3[0]-[edx,0].max-2+pos[0], iy+pt3[1]+pos[1], edx.abs+4, 1, c)
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Desenhar um polígono.
- #----------------------------------------------------------------------------
- def fill_polygon(pts, c, pos=[0, 0])
- return if pts.size <= 2
- n = pts.size - 2
- for i in 0...n
- self.fill_triangle3(pts[i..(i + 2)], c, pos)
- end
- end
- end
- #==============================================================================
- # • Mouse
- #==============================================================================
- Dax.register(:mouse, "Dax", 1.1)
- module Mouse
- extend self
- #--------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #--------------------------------------------------------------------------
- def start
- @cursor = Sprite.new
- @cursor.z = 100000
- @cursor.bitmap = Bitmap.new(1, 1)
- x = Dax::Mouse_Name == "" ? 1 : 0
- API::MouseShowCursor.call(x)
- @dgraphic = Dax::Mouse_Name
- graphic Dax::Mouse_Name
- update
- end
- #----------------------------------------------------------------------------
- # • visible = (boolean)
- # * boolean : true ou false
- # Tornar vísivel ou não o cursor do Mouse.
- #----------------------------------------------------------------------------
- def visible=(boolean)
- API::MouseShowCursor.call(boolean.visible.boolean_number)
- end
- #--------------------------------------------------------------------------
- # • graphic(graphic_set)
- # graphic_set : Se for número é um ícone; Se for string é uma imagem.
- #--------------------------------------------------------------------------
- def graphic(graphic_set)
- return if graphic_set == "" or graphic_set.nil?
- if graphic_set.is_a?(Fixnum)
- @cursor.bitmap = Bitmap.new(24, 24)
- @cursor.bitmap.draw_icon(graphic_set.to_i, 0, 0)
- else
- @cursor.bitmap = Cache.picture(graphic_set.to_s)
- end
- @dgraphic = graphic_set
- end
- #--------------------------------------------------------------------------
- # • show(visible)
- # visible : True - para mostrar o mouse | False - para esconder o mouse.
- #--------------------------------------------------------------------------
- def show(visible=true)
- @cursor.visible = visible
- end
- #--------------------------------------------------------------------------
- # • update (Atualização das coordenadas)
- #--------------------------------------------------------------------------
- def update
- return if @cursor.nil?
- @cursor.x, @cursor.y = position
- end
- #--------------------------------------------------------------------------
- # • cursor
- #--------------------------------------------------------------------------
- def cursor
- @cursor
- end
- #--------------------------------------------------------------------------
- # • x (Coordenada X do Mouse)
- #--------------------------------------------------------------------------
- def x
- @cursor.x
- end
- #--------------------------------------------------------------------------
- # • y (Coordenada Y do Mouse)
- #--------------------------------------------------------------------------
- def y
- @cursor.y
- end
- #--------------------------------------------------------------------------
- # • position (Posição do Mouse!)
- #--------------------------------------------------------------------------
- def position
- x, y = get_client_position
- return x, y
- end
- #--------------------------------------------------------------------------
- # • get_client_position (Posição original do Mouse!)
- #--------------------------------------------------------------------------
- def get_client_position
- pos = [0, 0].pack('ll')
- API::CursorPosition.call(pos)
- API::ScreenToClient.call(WINDOW, pos)
- return pos.unpack('ll')
- end
- #--------------------------------------------------------------------------
- # • find_window (Tamanho da window)
- #--------------------------------------------------------------------------
- def find_window
- game_name = '\0' * 256
- API::ReadIni.call('Game', 'Title', '', game_name, 255, '.\\Game.ini')
- game_name.delete!('\0') ensure game_name
- return API::FindWindow.call('RGSS Player', game_name)
- end
- #--------------------------------------------------------------------------
- # • Verificação se o mouse está na área de um determinado objeto.
- #--------------------------------------------------------------------------
- def in_area?(object_sprite)
- return @cursor.x.between?(object_sprite.x, object_sprite.x + object_sprite.width) &&
- @cursor.y.between?(object_sprite.y, object_sprite.y + object_sprite.height)
- end
- #----------------------------------------------------------------------------
- # • Mudar posição do cursor.
- #----------------------------------------------------------------------------
- def set_mouse(pos)
- SetCursorPos.call(pos.x, pos.y)
- update
- @cursor.x = @pos.x
- @cursor.y = @pos.y
- end
- WINDOW = find_window
- end
- #==============================================================================
- # • Object
- #==============================================================================
- Dax.register(:object)
- class Object
- #----------------------------------------------------------------------------
- # • O que irá ocorrer caso o mouse esteja sobre uma sprite.
- # Tem que ser um objeto Sprite.
- #----------------------------------------------------------------------------
- def if_mouse_over(&block)
- return unless self.is_a?(Sprite) or block_given?
- over ||= false
- if Mouse.in_area?(self)
- block.call
- over = true
- else
- over = false
- end
- yield over
- end
- #----------------------------------------------------------------------------
- # • O que irá ocorrer caso o mouse esteja sobre uma sprite, e ao clicar.
- # Tem que ser um objeto Sprite.
- # * button : Button : (:right - botão direito do mouse | :left - botão esq.)
- #----------------------------------------------------------------------------
- def if_mouse_click(button=:left, &block)
- return unless self.is_a?(Sprite) or block_given?
- button = button == :left ? 0x01 : button == :right ? 0x02 : 0x01
- block.call if Mouse.in_area?(self) and trigger?(button)
- end
- #----------------------------------------------------------------------------
- # • Profunda cópia
- #----------------------------------------------------------------------------
- def deep_clone
- Marshal.load(Marshal.dump(self))
- end
- #----------------------------------------------------------------------------
- # * Trigger ou Repeat
- #----------------------------------------------------------------------------
- def trigger_or_repeat?(key)
- trigger?(key) or repeat?(key)
- end
- #----------------------------------------------------------------------------
- # • Trigger
- #----------------------------------------------------------------------------
- def trigger?(key)
- return key.is_a?(Symbol) ? Input.trigger?(key) : Key.trigger?(key)
- end
- #----------------------------------------------------------------------------
- # • Press
- #----------------------------------------------------------------------------
- def press?(key)
- return key.is_a?(Symbol) ? Input.press?(key) : Key.press?(key)
- end
- #----------------------------------------------------------------------------
- # • Repeat
- #----------------------------------------------------------------------------
- def repeat?(key)
- return key.is_a?(Symbol) ? Input.repeat?(key) : Key.repeat?(key)
- end
- #----------------------------------------------------------------------------
- # • Retorna em forma de número.. os valores Boolean.
- #----------------------------------------------------------------------------
- def boolean_number
- return self ? 1 : 0
- end
- end
- #==============================================================================
- # • Entries
- #==============================================================================
- Dax.register(:entries)
- class Entries
- #----------------------------------------------------------------------------
- # • Variável pública da instância.
- #----------------------------------------------------------------------------
- attr_accessor :file
- attr_reader :get_number
- attr_reader :get_file
- attr_reader :get_array
- attr_reader :name
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(directory, typefile)
- return unless FileTest.directory?(directory)
- @file = Dir.glob(directory + "/*.{" + typefile + "}")
- @file.each_index { |i| @get_number = i.to_i }
- @file.each { |i| @get_file = i.to_s }
- @file.each_with_index { |i| @get_array = i }
- @name = split @file[0]
- end
- #----------------------------------------------------------------------------
- # • Split | Separar
- #----------------------------------------------------------------------------
- def split(file)
- file.to_s.split('/').last
- end
- #----------------------------------------------------------------------------
- # • Obter nome.
- #----------------------------------------------------------------------------
- def name(id)
- return split(@file[id])
- end
- end
- #==============================================================================
- # • TextBase
- #==============================================================================
- Dax.register(:text_base)
- class TextBase
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize
- @text = ""
- end
- #----------------------------------------------------------------------------
- # • Adicionar texto.
- #----------------------------------------------------------------------------
- def text=(text_add)
- @text += text_add
- end
- #----------------------------------------------------------------------------
- # • Adicionar uma nova linha.
- #----------------------------------------------------------------------------
- def text(text, nspace=0)
- @text += "\r\n" + (" " * nspace) + text
- end
- #----------------------------------------------------------------------------
- # • Adicionar comentário;
- #----------------------------------------------------------------------------
- def comment=(text_add, comment="#")
- @text += comment + text_add
- end
- #----------------------------------------------------------------------------
- # • Adicionar uma nova linha como comentário.
- #----------------------------------------------------------------------------
- def comment(text, nspace=0, comment="#")
- @text += "\r\n" + (" " * nspace) + comment + text
- end
- #----------------------------------------------------------------------------
- # • Salvar o texto.
- #----------------------------------------------------------------------------
- def save(filename="")
- _file = File.open(filename, "a+").each { |file|
- file.write(@text.to_s)
- file.close
- }
- end
- end
- #==============================================================================
- # • DRGSS | Comandos do RGSS...
- #==============================================================================
- Dax.register(:drgss)
- module DRGSS
- extend self
- #----------------------------------------------------------------------------
- # • Deleta a pasta, os arquivos.
- #----------------------------------------------------------------------------
- def recursive_delete(dir)
- files = []
- Dir.foreach(dir) do |fname|
- next if fname == '.' || fname == '..'
- path = dir + '/' + fname
- if File.directory?(path)
- puts "dir #{path}"
- recursive_delete(path)
- else
- puts "file #{path}"
- files << path
- end
- end
- files.each do |path|
- msgbox "delete file #{path}"
- end
- msgbox "delete dir #{dir}"
- Dir.rmdir(dir)
- end
- #----------------------------------------------------------------------------
- # • Deleta tudo.. Só use caso você saiba o que está fazendo
- #----------------------------------------------------------------------------
- def delete(directory)
- if File.directory?(directory)
- Dir.foreach(directory) do |file_or_directory|
- File.delete(directory+"/"+file_or_directory) if file_or_directory != "." and file_or_directory != ".."
- end
- else
- begin
- File.delete(directory) if File.new(directory).stat.size == 0
- rescue
- msgbox "#{$!} Error in deleting zero size file "
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Extrair scripts.
- #----------------------------------------------------------------------------
- def extract_scripts(type=".txt",options={})
- except = options[:except] || []
- folder = options[:folder] || ""
- id = 0 #
- $RGSS_SCRIPTS.each do |script|
- name = script[1]
- data = script[3]
- next if except.include? name or name.empty? or data.empty?
- filename = sprintf("%03d", id) + "_" + name
- p "Writing: #{filename}"
- File.open(folder+filename+"#{type}", "wb") do |file|
- file.write data
- end
- id += 1
- end
- end
- #----------------------------------------------------------------------------
- # • Carregar scripts.
- #----------------------------------------------------------------------------
- def load_scripts(type=".txt",options={})
- skip = options[:skip] || []
- folder = options[:folder] || ""
- begin
- Dir.foreach(folder) do |file|
- file_id = file[0,3].to_i
- break if file_id == options[:limit]
- next if file == "." or file == ".." or File.extname(file) != "#{type}" or skip.include?(file_id)
- r = load (folder+"#{file}")
- p "Loaded: #{r}"
- end
- end
- end
- end
- #==============================================================================
- # • Módulo Touch
- #==============================================================================
- Dax.register(:touch)
- module Touch
- #============================================================================
- # * Picture : Sistema onde você define uma imagem na qual pode ser acessada
- # pelo mouse.
- #============================================================================
- class Picture < Sprite
- #--------------------------------------------------------------------------
- # * Variáveis públicas da instância;
- #--------------------------------------------------------------------------
- attr_accessor :show
- #--------------------------------------------------------------------------
- # ** Inicialização dos objetos **
- #--------------------------------------------------------------------------
- # Argumentos do método *** : ***
- #
- # name/args[0] : Nome do arquivo.
- # x/args[1] : Coordenada X
- # y/args[2] : Coordenada Y
- # switche/args[3] : ID da switche para que quando ela estiver ativada, você não
- # poderá acessar a imagem, caso ela não esteja ativada, você poderá
- # acessar a imagem, agora caso você coloque 'nil' ela poderá ser acessada
- # a qualquer momento.
- # mode/args[4] : 0 - Para identificar se o arquivo está na pasta System
- # 1 - Para identificar se o arquivo está na pasta Picture.
- #--------------------------------------------------------------------------
- def initialize(*args)
- super((args[4] == 0 ? "S: " : "P: ") + args[0])
- [1, 2].each { |number| self.x, self.y = args[number] }
- @clicked, @in_area, @switche_id = false, args[3], false
- self.z = 200
- end
- #--------------------------------------------------------------------------
- # * Verifica se está na área do objeto.
- #--------------------------------------------------------------------------
- def in_area?
- return @in_area
- end
- #--------------------------------------------------------------------------
- # * Renovar os objetos
- #--------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose
- super
- end
- #--------------------------------------------------------------------------
- # * Atualizar os objetos.
- #--------------------------------------------------------------------------
- def update
- self.visible = !$game_switches[@switche_id] unless @switche_id.nil?
- if @show
- if Mouse.in_area?(self)
- @in_area = true
- effect_on_area?
- @clicked = trigger_or_repeat?(0x01)
- action if @clicked && trigger_or_repeat?(0x01)
- else
- @in_area = false
- effect_off_area?
- @clicked = false if trigger_or_repeat?(0x01)
- end
- else
- self.opacity = 0
- end
- end
- #--------------------------------------------------------------------------
- # * Ação ao clicar o mouse.
- #--------------------------------------------------------------------------
- def action
- end
- #--------------------------------------------------------------------------
- # * Efeito de quando estiver na área.
- #--------------------------------------------------------------------------
- def effect_on_area?
- self.opacity = 255
- end
- #--------------------------------------------------------------------------
- # * Efeito de quando não estiver na área.
- #--------------------------------------------------------------------------
- def effect_off_area?
- self.opacity = 127.5
- end
- end
- #============================================================================
- # * Simple_Picture : Versão simplificada da Picture
- #============================================================================
- class Simple_Picture < Picture
- #--------------------------------------------------------------------------
- # * Inicialização dos objetos
- #--------------------------------------------------------------------------
- def initialize(action, *args)
- end
- #--------------------------------------------------------------------------
- # * Renovar
- #--------------------------------------------------------------------------
- def dispose
- super
- end
- #--------------------------------------------------------------------------
- # * Atualizar
- #--------------------------------------------------------------------------
- def update
- super
- end
- #--------------------------------------------------------------------------
- # * Ação
- #--------------------------------------------------------------------------
- def action
- unless action.nil?
- eval(action.to_s)
- else
- eval(@action.to_s) unless @action.nil?
- end
- end
- #--------------------------------------------------------------------------
- # * Efeito da área
- #--------------------------------------------------------------------------
- def effect_on_area?; super; end;
- def effect_off_area?; super; end;
- def in_area?; super; end;
- #--------------------------------------------------------------------------
- # * Conteúdo
- #--------------------------------------------------------------------------
- def self; self; end;
- end
- #============================================================================
- # * Icon
- #============================================================================
- class Icon < Sprite
- #--------------------------------------------------------------------------
- # • Inicialização dos objetos.
- # id : ID do ícone no database.
- # x : Posição X do objeto.
- # y : Posição Y do objeto.
- # z : Altura do objeto.
- #--------------------------------------------------------------------------
- def initialize(*args)
- super([24, 24])
- (1..3).each { |number| self.x, self.y, self.z = args[number] }
- self.bitmap.draw_icon(args[0].to_i, 0, 0)
- @clicked = false
- @switche_id = args[4]
- @effect = args[5]
- end
- #--------------------------------------------------------------------------
- # • Renovação dos objetos.
- #--------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose if !self.bitmap.nil?
- super
- end
- #--------------------------------------------------------------------------
- # • Atualizaçaõ dos objetos.
- # action_clicked : Caso seja um nome em formato de String irá chamar uma
- # scene, caso seja em formato de número irá chamar um evento comum.
- #--------------------------------------------------------------------------
- def update
- if @effect == :visible then self.visible = !$game_switches[@switche_id] unless @switche_id.nil? end
- unless @switche_id.nil? then self.opacity = 64 if @effect == :opacity and !$game_switches[@switche_id] end
- if Mouse.in_area?(self)
- effect_on_area?
- @clicked = trigger?(0x01) or repeat?(0x01)
- action if @clicked && trigger?(0x01) or repeat?(0x01)
- else
- effect_off_area?
- @clicked = false if trigger?(0x01) or repeat?(0x01)
- end
- end
- #----------------------------------------------------------------------------
- # • Acão após o clique na imagem.
- #----------------------------------------------------------------------------
- def action
- return if self.visible or self.opacity == 64
- end
- #----------------------------------------------------------------------------
- # • Efeito quando estiver na área.
- #----------------------------------------------------------------------------
- def effect_on_area?
- self.opacity = 255
- end
- #----------------------------------------------------------------------------
- # • Efeito quando estiver fora da área.
- #----------------------------------------------------------------------------
- def effect_off_area?(new=nil)
- self.opacity = new.nil? ? 128 : new
- end
- end
- #==============================================================================
- # • Simple_Icon
- #============================================================================
- class Simple_Icon < Icon
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(action, *args)
- super(*args)
- self.opacity = 128
- @action = action
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização dos objetos.
- #----------------------------------------------------------------------------
- def update
- super
- end
- #----------------------------------------------------------------------------
- # • Ação após o clique.
- #----------------------------------------------------------------------------
- def action
- super
- eval(@action.to_s) unless @action.nil?
- end
- #----------------------------------------------------------------------------
- # • Efeito do objeto quando estiver na área.
- #----------------------------------------------------------------------------
- def effect_on_area?
- super
- end
- #----------------------------------------------------------------------------
- # • Efeito do objeto quando estiver fora da área.
- #----------------------------------------------------------------------------
- def effect_off_area?(value=nil)
- super(value)
- end
- #----------------------------------------------------------------------------
- # • Retorna ao conteúdo.
- #----------------------------------------------------------------------------
- def contents
- self
- end
- end
- #==============================================================================
- # • Mouse Extension | Touch Text
- #==============================================================================
- class Text < Sprite
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- # id : ID do ícone no database.
- # x : Posição X do objeto.
- # y : Posição Y do objeto.
- # z : Altura do objeto.
- #----------------------------------------------------------------------------
- def initialize(text="", x=0, y=0, z=0, switche_id=nil,color=[ColorBasic[-1], ColorBasic[7]],font=["Arial", 16],align=0)
- super([font[1] + (text.split(//).size ** 2), args[6][1]])
- (1..3).each { |xyz| self.x, self.y, self.z = args[xyz] }
- self.bitmap.draw_text(0, 0, self.width, self.height, args[0], args[7])
- @clicked = false
- @switche_id = args[4]
- @color = args[5]
- self.bitmap.font.name, self.bitmap.font.size = args[6]
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose if !self.bitmap.nil?
- super
- end
- #----------------------------------------------------------------------------
- # • Atualizaçaõ dos objetos.
- # action_clicked : Caso seja um nome em formato de String irá chamar uma
- # scene, caso seja em formato de número irá chamar um evento comum.
- #----------------------------------------------------------------------------
- def update
- self.visible = !$game_switches[@switche_id] unless @switche_id.nil?
- if Mouse.in_area?(self)
- effect_on_area?
- @clicked = trigger?(0x01) or repeat?(0x01)
- action if @clicked && trigger?(0x01) or repeat?(0x01)
- else
- effect_off_area?
- @clicked = false if trigger?(0x01) or repeat?(0x01)
- end
- end
- #----------------------------------------------------------------------------
- # • Acão após o clique na imagem.
- #----------------------------------------------------------------------------
- def action
- end
- #----------------------------------------------------------------------------
- # • Efeito quando estiver na área.
- #----------------------------------------------------------------------------
- def effect_on_area?
- self.color = @color[1]
- end
- #----------------------------------------------------------------------------
- # • Efeito quando estiver fora da área.
- #----------------------------------------------------------------------------
- def effect_off_area?
- self.color = @color[0]
- end
- end
- #============================================================================
- # Simple Touch Icon
- #============================================================================
- class Simple_Text < Text
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(action, *args)
- super(*args)
- @action = action
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização dos objetos.
- #----------------------------------------------------------------------------
- def update
- super
- end
- #----------------------------------------------------------------------------
- # • Ação após o clique.
- #----------------------------------------------------------------------------
- def action
- eval(@action.to_s) unless @action.nil?
- end
- #----------------------------------------------------------------------------
- # • Efeito do objeto quando estiver na área.
- #----------------------------------------------------------------------------
- def effect_on_area?
- super
- end
- #----------------------------------------------------------------------------
- # • Efeito do objeto quando estiver fora da área.
- #----------------------------------------------------------------------------
- def effect_off_area?
- super
- end
- #----------------------------------------------------------------------------
- # • Retorna ao conteúdo.
- #----------------------------------------------------------------------------
- def contents
- self
- end
- end
- end
- #==============================================================================
- # • OutlineFillRect
- #==============================================================================
- Dax.register(:outline_fill_rect)
- class OutlineFillRect < Sprite
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(object, max=2, color=ColorBasic[-1])
- super([object.width, object.height])
- @object = object
- self.x, self.y, self.z = object.x, object.y, object.z
- self.bitmap.fill_rect(0, 0, max, self.height, color)
- self.bitmap.fill_rect(self.width-max, 0, max, self.height, color)
- self.bitmap.fill_rect(0, 0, self.width, max, color)
- self.bitmap.fill_rect(0, self.height-max, self.width, max, color)
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose unless self.bitmap.disposed?
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização das coordenadas.
- #----------------------------------------------------------------------------
- def update
- self.x, self.y, self.z = @object.x, @object.y, @object.z
- end
- end
- #==============================================================================
- # • BackupSystem
- #==============================================================================
- Dax.register :backupsystem
- $BACKUP = <<_SCRIPT_
- if $TEST
- time = Time.now
- Dir.mkdir('Backup') unless File.directory?('Backup')
- ftype = 'rvdata2'
- flist = Dir.glob('./Data/*.{' + ftype + '}')
- flist.each_index do |i|
- flist[i] = flist[i].split('/').last
- save_data(load_data('Data/' + flist[i]), 'Backup' + '/' + flist[i])
- end
- print("Backup em:" + (Time.now - time).to_s + ' segundos')
- end
- _SCRIPT_
- def backup; eval($BACKUP); end;
- #==============================================================================
- # • BackString
- #==============================================================================
- Dax.register :dstring
- module DString
- extend self
- #----------------------------------------------------------------------------
- # • Deletar a útlima letra de uma string..
- #----------------------------------------------------------------------------
- def backslash(text)
- text2 = ""
- text = text.to_s.split(//)
- text[text.size-1] = "" unless text[0].to_s.empty?
- for i in 0..text.size-1
- text2 += text[i].to_s
- end
- return text2
- end
- end
- #==============================================================================
- # * SceneManager
- #==============================================================================
- Dax.register :scenemanager
- class << SceneManager
- #----------------------------------------------------------------------------
- # • Chama uma scene através de uma palavra.;
- #----------------------------------------------------------------------------
- def symbol(scene_symbol)
- eval("self.call(#{scene_symbol.to_s})")
- end
- end
- #==============================================================================
- # • Sprite_Text
- #==============================================================================
- Dax.register(:sprite_text)
- class Sprite_Text < Sprite
- #----------------------------------------------------------------------------
- # • Variáveis públicas da instância.
- #----------------------------------------------------------------------------
- attr_accessor :text # Mudar de texto...
- #----------------------------------------------------------------------------
- # • Inicialização dos objetos.
- #----------------------------------------------------------------------------
- def initialize(x, y, width, height, text, align=0)
- super([width, height])
- self.x, self.y = x, y
- @text = text
- self.bitmap.draw_text_rect(@text, align)
- end
- #----------------------------------------------------------------------------
- # • Renovação dos objetos.
- #----------------------------------------------------------------------------
- def dispose
- self.bitmap.dispose
- super
- end
- #----------------------------------------------------------------------------
- # • Atualização dos objetos.
- #----------------------------------------------------------------------------
- def update
- self.bitmap.clear
- super
- self.bitmap.draw_text_rect(@text)
- end
- end
- #==============================================================================
- # • Opacity
- #==============================================================================
- Dax.register(:opacity)
- module Opacity
- extend self
- @key ||= {}
- #----------------------------------------------------------------------------
- # • Efeito de opacidade + e -.
- #----------------------------------------------------------------------------
- def sprite_opacity(sprite, speed, max, min, hash=nil)
- @key[hash.nil? ? hash.__id__ : hash] || false
- unless @key[hash]
- sprite.opacity += speed unless sprite.opacity >= max
- @key[hash] = sprite.opacity >= max
- else
- sprite.opacity -= speed unless sprite.opacity <= min
- @key[hash] = false if sprite.opacity <= min
- end
- end
- #----------------------------------------------------------------------------
- # • Efeito de opacidade por fora.
- #----------------------------------------------------------------------------
- def sprite_opacity_out(sprite, speed, max)
- sprite.opacity += speed unless sprite.opacity >= max
- end
- #----------------------------------------------------------------------------
- # • Efeito de opacidade por dentro.
- #----------------------------------------------------------------------------
- def sprite_opacity_in(sprite, speed, min)
- sprite.opacity -= speed unless sprite.opacity <= min
- end
- #--------------------------------------------------------------------------
- # • Efeito de fade out em massa
- # time : duração (em milesegundo)
- #--------------------------------------------------------------------------
- def fadeout_all(time = 1000)
- RPG::BGM.fade(time)
- RPG::BGS.fade(time)
- RPG::ME.fade(time)
- Graphics.fadeout(time * Graphics.frame_rate / 1000)
- RPG::BGM.stop
- RPG::BGS.stop
- RPG::ME.stop
- end
- end
- #==============================================================================
- # • Rpg
- #==============================================================================
- Dax.register(:rpg)
- module Rpg
- def self.data_manager
- end
- #============================================================================
- # • Hud
- #============================================================================
- module Hud
- end
- #============================================================================
- # • Menu
- #============================================================================
- module Menu
- extend self
- def include_item?(item)
- item.is_a?(RPG::Item) && !item.key_item?
- end
- #--------------------------------------------------------------------------
- # • Cursor...
- #--------------------------------------------------------------------------
- def cursor_up(variable, max)
- variable += 1 unless variable > max
- variable = 0 if variable > max
- return variable
- end
- #--------------------------------------------------------------------------
- # • Cursor...
- #--------------------------------------------------------------------------
- def cursor_down(variable, max)
- variable -= 1 unless variable < 0
- variable = max if variable < 0
- return variable
- end
- end
- #============================================================================
- # • Battle
- #============================================================================
- module Battle
- end
- #============================================================================
- # • Title
- #============================================================================
- module Title
- end
- end
- #==============================================================================
- # • String
- #==============================================================================
- class String
- #----------------------------------------------------------------------------
- # • Comandos.
- #----------------------------------------------------------------------------
- def script
- if self.match(/sprite: ([^>]*)/)
- return Sprite.new($1)
- elsif self.match(/cb|CB: (\d+)/)
- return ColorBasic[$1.to_i]
- elsif self.match(/window: x: (\d+) y: (\d+) width: (\d+) height: (\d+)/)
- return Window_Base.new($1.to_i, $2.to_i, $3.to_i, $4.to_i)
- elsif self.match(/G: ([^>]*)/)
- return "Graphics/#{$1}"
- elsif self.match(/C:(\w+):([^>]*)/)
- case $1
- when "S"
- return Cache.system($2.to_s)
- when "P"
- return Cache.picture($2.to_s)
- when "Pl"
- return Cache.parallax($2.to_s)
- when "C"
- return Cache.character($2.to_s)
- when "A"
- return Cache.animation($2.to_s)
- when "B1"
- return Cache.battleback1($2.to_s)
- when "B2"
- return Cache.battleback2($2.to_s)
- when "B"
- return Cache.battler($2.to_s)
- when "F"
- return Cache.face($2.to_s)
- when "T1"
- return Cache.title1($2.to_s)
- when "T2"
- return Cache.title2($2.to_s)
- when "T"
- return Cache.tileset($2.to_s)
- end
- elsif self.match(/scall: (\w+)/)
- return eval("SceneManager.call(#{$1})")
- elsif self.match(/sgoto: (\w+)/)
- return eval("SceneManager.goto(#{$1})")
- elsif self.match(/text: x: (\d+) y: (\d+) width: (\d+) height: (\d+) text: ([^>]*)/)
- return Sprite_Text.new($1.to_f, $2.to_f, $3.to_f, $4.to_f, $5.to_s)
- elsif self.match(/r(\d+) g(\d+) b(\d+) a(\d+)/)
- return Color.new($1.to_f, $2.to_f, $3.to_f, $4.to_f)
- end
- end
- end
- #==============================================================================
- # • Txt
- #==============================================================================
- Dax.register(:read, "Dax")
- module Read
- extend self
- #----------------------------------------------------------------------------
- # • Verificar valor numérico após uma palavra em um arquivo.
- #----------------------------------------------------------------------------
- def numeric(file, tag)
- IO.readlines(file).each do |line|
- return $1.to_i if line.match(/#{tag} (\d+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Verificar valor de uma palavra(string única) após uma palavra em um arquivo
- #----------------------------------------------------------------------------
- def string(file, tag)
- IO.readlines(file).each do |line|
- return $1.to_s if line.match(/#{tag} (\w+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Verificar um conteúdo após uma palavra de um arquivo.
- #----------------------------------------------------------------------------
- def content(file, tag)
- IO.readlines(file).each do |line|
- return $1 if line.match(/#{tag} ([^>]*)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Multiplo número..
- #----------------------------------------------------------------------------
- def multiple_numeric(file, tag)
- IO.readlines(file).each do |line|
- return [$1.to_i, $2.to_i] if line.match(/#{tag} (\d+), (\d+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Multiplo string..
- #----------------------------------------------------------------------------
- def multiple_string(file, tag)
- IO.readlines(file).each do |line|
- return [$1.to_s, $2.to_s] if line.match(/#{tag} (\w+), (\w+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Triplo número.
- #----------------------------------------------------------------------------
- def triple_numeric(file, tag)
- IO.readlines(file).each do |line|
- return [$1.to_i, $2.to_i, $3.to_i] if line.match(/#{tag} (\d+), (\d+), (\d+)/)
- end
- end
- #----------------------------------------------------------------------------
- # • Triplo string.
- #----------------------------------------------------------------------------
- def triple_string(file, tag)
- IO.readlines(file).each do |line|
- return [$1.to_s, $2.to_s, $3.to_s] if line.match(/#{tag} (\w+), (\w+), (\w+)/)
- end
- end
- # true or false
- def of(file, tag)
- IO.readlines(file).each do |line|
- return $1.to_s == "true" ? true : false if line.match(/#{tag} ([^>]*)/)
- end
- end
- end
- #==============================================================================
- # • Background
- #==============================================================================
- Dax.register :background
- module Background
- extend self
- #----------------------------------------------------------------------------
- # • Plano de fundo padrão...
- #----------------------------------------------------------------------------
- def default(alpha=128)
- @background = Sprite.new
- @background.bitmap = SceneManager.background_bitmap
- @background.color.set(16, 16, 16, alpha)
- end
- #----------------------------------------------------------------------------
- # • Plano de fundo padrão renovado.
- #----------------------------------------------------------------------------
- def default_dispose
- return if @background.nil?
- @background.dispose
- end
- end
- #==============================================================================
- # * Window_Base
- #==============================================================================
- Dax.register(:window_base)
- Dax.required_class("Window_Base") {
- class Window_Base < Window
- #----------------------------------------------------------------------------
- # • Slide pela direita.
- # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
- #----------------------------------------------------------------------------
- def slide_right(speed, point)
- self.x += speed unless self.x >= point
- end
- #----------------------------------------------------------------------------
- # • Slide pela esquerda.
- # * speed : Velocidade | point : Ponto da coordenada X que irá chegar.
- #----------------------------------------------------------------------------
- def slide_left(speed, point)
- self.x -= speed unless self.x <= point
- end
- #----------------------------------------------------------------------------
- # • Slide por cima.
- # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
- #----------------------------------------------------------------------------
- def slide_up(speed, point)
- self.y -= speed unless self.y <= point
- end
- #----------------------------------------------------------------------------
- # • Slide por baixo.
- # * speed : Velocidade | point : Ponto da coordenada Y que irá chegar.
- #----------------------------------------------------------------------------
- def slide_down(speed, point)
- self.y += speed unless self.y >= point
- end
- end
- }
- #==============================================================================
- # • Map
- #==============================================================================
- Dax.register(:map)
- module Map
- extend self
- #----------------------------------------------------------------------------
- # • Mapeiar área.
- # map : Objeto [SPRITE].. que será escaniado..
- # scan_sprite : Objeto [SPRITE].. que irá projetar o scan.
- # color : Cor do scan.
- #----------------------------------------------------------------------------
- def char_area(map, scan_sprite, color=ColorBasic[-1])
- _table = Table.new(map.width, map.height)
- for x in 0..._table.xsize
- for y in 0..._table.ysize
- next if map.bitmap.get_pixel(x, y).alpha == 0
- scan_sprite.bitmap.set_pixel(x, y, color)
- end
- end
- end
- #----------------------------------------------------------------------------
- # • Colidir com determinada cor de um objeto sprite.
- # ar : [largura, altura, bloqueio da esquerda, bloqueio de cima]
- # object : Objeto a colidir. [SPRITE]
- # map : Mapa. [SPRITE]
- # color : Cor, na qual quando o objeto colidir com está cor.. ativa.
- #---------------------------------------------------------------------------
- def collide_with_color(object, map, color, ar=[28,30,30,30])
- (ar[0]...object.width).each { |w| (ar[1]...object.height).each { |h|
- _r = map.bitmap.get_pixel(object.x+w, object.y+h) == color[:right]
- _l = map.bitmap.get_pixel(object.x+ar[2]-w, object.y+h) == color[:left]
- _d = map.bitmap.get_pixel(object.x+w, object.y+h) == color[:down]
- _u = map.bitmap.get_pixel(object.x+w, object.y+ar[3]-h) == color[:up]
- return {right: _r, left: _l, down: _d, up: _u}
- }}
- end
- end
- #==============================================================================
- # • VS | Variables & Switches
- #==============================================================================
- Dax.register(:vs)
- module VS
- #----------------------------------------------------------------------------
- # • Função do módulo.
- #----------------------------------------------------------------------------
- module_function
- #----------------------------------------------------------------------------
- # • Desligar a quantia predestinada de switches...
- #----------------------------------------------------------------------------
- def off_switche(value=9999)
- Dax.required_class("$game_switches"){value.times { |index| $game_switches[index] = false }
- $game_switches.on_change}
- end
- #----------------------------------------------------------------------------
- # • Ativar a quantia predestinada de switches...
- #----------------------------------------------------------------------------
- def on_switche(value=9999)
- Dax.required_class("$game_switches"){value.times { |index| $game_switches[index] = true }
- $game_switches.on_change}
- end
- #----------------------------------------------------------------------------
- # • Salvar as variáveis do jogo em um arquivo
- # *args : IDs delas.. exemplo: 1, 2, 3, 4
- #----------------------------------------------------------------------------
- def save_game_variable(*args)
- Dax.required_class("$game_variables"){
- Dax.required_file("savedGameVariables.rvdata2"){File.delete("savedGameVariables.rvdata2")}
- i = [*args]
- sgv = [{}]
- (0...i.size-1).each { |index| sgv[0][index] = $game_variables[index] }
- save_data(sgv, "savedGameVariables.rvdata2")
- }
- end
- #----------------------------------------------------------------------------
- # • Carregar as variáveis do jogo dum arquivo
- # *args : IDs delas.. exemplo: 1, 2, 3, 4
- #----------------------------------------------------------------------------
- def load_game_variable(*args)
- Dax.required_class("$game_variables"){
- Dax.required_file("savedGameVariables.rvdata2"){
- i = [*args]
- sgv = load_data("savedGameVariables.rvdata2")
- (0...i.size-1).each { |index| $game_variables[index] = sgv[0][index]}
- }}
- end
- #----------------------------------------------------------------------------
- # • Salvar as switches do jogo em um arquivo
- # *args : IDs delas.. exemplo: 1, 2, 3, 4
- #----------------------------------------------------------------------------
- def save_switches_variable(*args)
- Dax.required_class("$game_switches"){
- Dax.required_file("savedGameSwitches.rvdata2"){File.delete("savedGameSwitches.rvdata2")}
- i = [*args]
- sgs= [{}]
- (0...i.size-1).each { |index| sgs[0][index] = $game_switches[index] }
- save_data(sgs, "savedGameSwitches.rvdata2")
- }
- end
- #----------------------------------------------------------------------------
- # • Carregar as variáveis do jogo dum arquivo
- # *args : IDs delas.. exemplo: 1, 2, 3, 4
- #----------------------------------------------------------------------------
- def load_game_variable(*args)
- Dax.required_class("$game_switches"){
- Dax.required_file("savedGameSwitches.rvdata2"){
- i = [*args]
- sgs = load_data("savedGameSwitches.rvdata2")
- (0...i.size-1).each { |index| $game_switches[index] = sgs[0][index]}
- }}
- end
- end
- #==============================================================================
- # • Sound Base
- #==============================================================================
- Dax.register(:sound_base)
- module Sound_Base
- #----------------------------------------------------------------------------
- # • Função do módulo.
- #----------------------------------------------------------------------------
- module_function
- #----------------------------------------------------------------------------
- # • Executar um som.
- #----------------------------------------------------------------------------
- def play(name, volume, pitch, type = :se)
- case type
- when :se ; RPG::SE.new(name, volume, pitch).play rescue valid?(name)
- when :me ; RPG::ME.new(name, volume, pitch).play rescue valid?(name)
- when :bgm ; RPG::BGM.new(name, volume, pitch).play rescue valid?(name)
- when :bgs ; RPG::BGS.new(name, volume, pitch).play rescue valid?(name)
- end
- end
- #----------------------------------------------------------------------------
- # • Validar som.
- #----------------------------------------------------------------------------
- def valid?(name)
- raise("Arquivo de som não encontrado: #{name}")
- exit
- end
- end
- #==============================================================================
- # • Desativar scripts : Para fazer, basta por no nome do script da lista,
- # [D].
- #==============================================================================
- Dax.register(:disable_script)
- Dax.rgss_script.each_with_index { |data, index|
- $RGSS_SCRIPTS.at(index)[2] = $RGSS_SCRIPTS.at(index)[3] = "" if data.at(1).include?("[D]")
- }
- #==============================================================================
- # * DataManager
- #==============================================================================
- class << DataManager
- alias :new_init :init
- def init
- Rpg.data_manager
- Mouse.start
- new_init
- end
- end
- #==============================================================================
- # * Input
- #==============================================================================
- class << Input
- alias :upft :update
- def update
- upft
- Key.update
- end
- end
- class << Graphics
- alias :uptf :update
- def update
- uptf
- Mouse.update
- end
- end
- __END__
- :regexp_symbol
- #==============================================================================
- # • Regexp Symbol
- #==============================================================================
- Símbolos:
- [x]|[abc] : Um único caractér de: a, b ou c
- [^x]|[^abc] : Qualquer caractér exceto: a, b, ou c
- [a-z] : Um único caractér no intervalo de a...z
- [a-zA-Z] : Um único caractér no intervalo de a...z ou A...Z
- ^ : Começo da linha.
- $ : Fim da linha.
- \A : Começo da string.
- \z : Fim da string.
- . : Um único caractér
- \s : Qualquer carácter com espaço
- \S : Qualquer carácter sem espaço
- \d : Qualquer dígito
- \D : Qualquer um que não seja um dígito
- \w : Qualquer palavra
- \W : Qualquer um que não seja uma palavra.
- \b : Qualquer limite de palavra.
- (...) : Capturar tudo fechado.
- (x|y)|(a|b) : A(X) ou B(Y)
- x? : Zero ou um de x.
- x* : Zero ou mais de x.
- x+ : Um ou mais de x.
- x{3} : Exatamente 3 de x.
- x{3,} : Exatamente 3 ou mais de um de x.
- x{3,6} : Entre 3 e 6 de x.
- Opções:
- /i : Sem case sensitive
- /m : Para mais de uma linha
- /x : Ingnorar espaços brancos
- /o : Executar o #{...}, alterações apenas uma vez.
Add Comment
Please, Sign In to add comment