Holy87

Keyboard Core

Sep 19th, 2020
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 23.65 KB | None | 0 0
  1. #===============================================================================
  2. # Interfaccia Tastiera di Holy87
  3. # Difficoltà utente: ★
  4. # Versione 1.0
  5. # Licenza: CC. Chiunque può scaricare, modificare, distribuire e utilizzare
  6. # lo script nei propri progetti, sia amatoriali che commerciali. Vietata
  7. # l'attribuzione impropria.
  8. #===============================================================================
  9. # Questo script vi permette di ottenere il completo controllo della tastiera e
  10. # sarà una base per script futuri.
  11. # Ecco le emozionanti FICIURS!
  12. # ● Possibilità di rimappare completamente tutti i comandi di gioco ed aggiungere
  13. #    nuovi comandi oltre a quelli già presenti (:C, :A, :X...)
  14. # ● Ottieni il nome del tasto da premere
  15. # ● Segue il layout della tastiera
  16. #===============================================================================
  17. # Istruzioni: inserire lo script sotto Materials, prima del Main. Se avete lo
  18. # script del Gamepad, installatelo AL DI SOPRA di quest'ultimo.
  19. # Lo script è plug & play, ma è possibile configurarne i tasti.
  20. #
  21. # Alcuni metodi comuni:
  22. # ● Vocab.key_name(key): restituisce il nome del tasto. Ad esempio,
  23. # Vocab.key_name(:C) -> 'BARRA SPAZIATRICE' perché il pulsante di spazio è il primo
  24. # configurato sul comando :C
  25. # Vocab.key_name(:X) -> 'MAIUSC'
  26. # Vocab.key_name(:VK_RETURN) -> 'INVIO' puoi anche specificare direttamente il tasto
  27. # ● Keyboard.caps_lock? -> determina se è attivo il "blocca maiuscole"
  28. # ● Keyboard.num_lock? -> determina se è attivo il "blocca numeri"
  29. # ● Keyboard.unicode_char(codice) -> ok, questo dovrebbe essere utile per script
  30. # di immissione testi. Ottiene il carattere di immissione del tasto tenendo in
  31. # considerazione lo stato ed il layout della tastiera. Perciò, con una tastiera
  32. # italiana, Keyboard.unicode_char(:KEY_E) dovrebbe restituire 'e' in stato normale,
  33. # 'E' se nel frattempo si teneva premuto Maiuscole o se il Bloc Num era attivato, ed
  34. # il simbolo dell'euro '€' se era tenuto premuto il simbolo Alt Gr.
  35. #
  36. # Funzioni in gioco:
  37. # Se inserisci in un box di messaggio \K[x] dove x è il numero del comando (vedi
  38. # in basso), puoi far dire al messaggio il nome del tasto assegnato.
  39. # Esempio
  40. # Usa il tasto \K[0] per correre -> 'Usa il tasto [MAIUSCOLA] per correre'
  41. #
  42. # ■ IMPOSTAZIONI GIOCATORE
  43. # È possibile definire le impostazioni della tastiera che sono memorizzate in
  44. # $game_system per impostare altri tasti per i comandi e aggiungerne anche di
  45. # nuovi.
  46. # Configura DEFAULT_KEY_SET per personalizzare i comandi da dare.
  47. # Nota 1: questo script non sovrascrive le funzioni del tasto F1 e F12.
  48. # Nota 2: le impostazioni del menu F1 verranno ignorate.
  49. #===============================================================================
  50.  
  51. module Keyboard
  52.   # IMPOSTAZIONI GENERALI
  53.   module Settings
  54.  
  55.     # CONFIGURAZIONE DEI COMANDI
  56.     # Puoi definire sia direttamente il comando associato, sia un array. In questo
  57.     # caso qualsiasi dei tasti sarà valido.
  58.     DEFAULT_KEY_SET = {
  59.         :UP => [:VK_UP],
  60.         :DOWN => [:VK_DOWN],
  61.         :LEFT => [:VK_LEFT],
  62.         :RIGHT => [:VK_RIGHT],
  63.         :START => [], #not really used by RPG Maker
  64.         :SELECT => [], #not used too, but you can if you want
  65.         :L => [:KEY_Q, :VK_PRIOR],
  66.         :R => [:KEY_W, :VK_NEXT],
  67.         :A => [:VK_SHIFT],
  68.         :B => [:KEY_X, :VK_ESCAPE, :VK_NUMPAD0],
  69.         :C => [:KEY_Z, :VK_RETURN, :VK_SPACE],
  70.         :X => [:KEY_A],
  71.         :Y => [:KEY_S],
  72.         :Z => [:KEY_D],
  73.         :F9 => :VK_F9, # for debug window
  74.         :F12 => :VK_F12, # not used in game
  75.         :CTRL => :VK_CONTROL, # for pass throught objects in debug mode
  76.         :F1 => :VK_F1 # not used in game
  77.     }
  78.  
  79.     # TRADUZIONI PERSONALIZZATE
  80.     # Talvolta il nome del pulsante restituito da Windows non è molto leggibile.
  81.     # Qui puoi definire una traduzione custom (valido solo se chiami con
  82.     # Vocab::key_name)
  83.     CUSTOM_KEY_TRANSLATION = {
  84.         :VK_UP => 'FR. SU',
  85.         :VK_LEFT => 'FR. SINISTRA',
  86.         :VK_RIGHT => 'FR. DESTRA',
  87.         :VK_DOWN => 'FR. GIÙ',
  88.         :VK_SHIFT => 'MAIUSCOLA',
  89.         :VK_PRIOR => 'PAG. SU',
  90.         :VK_NEXT => 'PAG. GIÙ'
  91.     }
  92.  
  93.     # Questo array serve per mostrare il nome del tasto nella finestra di messaggio
  94.     # e di aiuto. Ad ogni indice corrisponde un pulsante. Ad esempio, se scrivi \K[0]
  95.     # nel messaggio, mostrerà 'MAIUSCOLA'. Se scrivi \K[Y] mostrerà invece 'S'.
  96.     # NOTA: Se hai installato lo script delle icone tasti, questa configurazione
  97.     # verrà ignorata (usa la configurazione dell'altro script)
  98.     #               0   1   2   3   4   5   6   7   8      9       10   11
  99.     KEY_INDEXES = [:A, :B, :C, :X, :Y, :Z, :L, :R, :LEFT, :RIGHT, :UP, :DOWN]
  100.     # imposta questo valore a true quando vuoi mostrare le parentesi quadre [ e ]
  101.     # quando usi \K nel messaggio. Esempio:
  102.     # Premi \K[:UP] per salire -> Premi [FRECCIA SU] per salire
  103.     USE_BRACKETS = true
  104.     # Imposta un valore diverso da zero se vuoi che il testo del comando sia mostrato
  105.     # in un colore diverso. Il colore dipende dal valore che imposterai.
  106.     CHANGE_COLOR = 2
  107.   end
  108.  
  109.   # key codes. The documentation can be found at
  110.   # https://docs.microsoft.com/it-it/windows/win32/inputdev/virtual-key-codes
  111.   VK_BACK = 0x08 # BACKSPACE key
  112.   VK_TAB = 0x09 # TAB key
  113.   VK_RETURN = 0x0D # ENTER key
  114.   VK_SHIFT = 0x10 # Shift key
  115.   VK_CONTROL = 0x11 # CTRL key
  116.   VK_MENU = 0x12 # Alt key
  117.   VK_PAUSE = 0x13 # Pause key
  118.   VK_CAPITAL = 0x14 # CAPS LOCK key
  119.   VK_ESCAPE = 0x1B # ESCAPE key
  120.   VK_SPACE = 0x20 # SPACEBAR
  121.   VK_PRIOR = 0x21 # PAGE UP key
  122.   VK_NEXT = 0x22 # PAGE DOWN key
  123.   VK_END = 0x23 # END key
  124.   VK_HOME = 0x24 # HOME key
  125.   VK_LEFT = 0x25 # LEFT ARROW key
  126.   VK_UP = 0x26 # UP ARROW key
  127.   VK_RIGHT = 0x27 # RIGHT ARROW key
  128.   VK_DOWN = 0x28 # DOWN ARROW key
  129.   VK_SELECT = 0x29 # SELECT key
  130.   VK_PRINT = 0x2A # PRINT key
  131.   VK_SNAPSHOT = 0x2C # LEFT ARROW key
  132.   VK_INSERT = 0x2D # INS
  133.   VK_DELETE = 0x2E # DEL
  134.   VK_HELP = 0x2F # HELP
  135.  
  136.   # numbers
  137.   NUM_0 = 0x30
  138.   NUM_1 = 0x31
  139.   NUM_2 = 0x32
  140.   NUM_3 = 0x33
  141.   NUM_4 = 0x34
  142.   NUM_5 = 0x35
  143.   NUM_6 = 0x36
  144.   NUM_7 = 0x37
  145.   NUM_8 = 0x38
  146.   NUM_9 = 0x39
  147.  
  148.   # letters
  149.   KEY_A = 0x41
  150.   KEY_B = 0x42
  151.   KEY_C = 0x43
  152.   KEY_D = 0x44
  153.   KEY_E = 0x45
  154.   KEY_F = 0x46
  155.   KEY_G = 0x47
  156.   KEY_H = 0x48
  157.   KEY_I = 0x49
  158.   KEY_J = 0x4A
  159.   KEY_K = 0x4B
  160.   KEY_L = 0x4C
  161.   KEY_M = 0x4D
  162.   KEY_N = 0x4E
  163.   KEY_O = 0x4F
  164.   KEY_P = 0x50
  165.   KEY_Q = 0x51
  166.   KEY_R = 0x52
  167.   KEY_S = 0x53
  168.   KEY_T = 0x54
  169.   KEY_U = 0x55
  170.   KEY_V = 0x56
  171.   KEY_W = 0x57
  172.   KEY_X = 0x58
  173.   KEY_Y = 0x59
  174.   KEY_Z = 0x5A
  175.  
  176.   # numpad keys
  177.   VK_NUMPAD0 = 0x60
  178.   VK_NUMPAD1 = 0x61
  179.   VK_NUMPAD2 = 0x62
  180.   VK_NUMPAD3 = 0x63
  181.   VK_NUMPAD4 = 0x64
  182.   VK_NUMPAD5 = 0x65
  183.   VK_NUMPAD6 = 0x66
  184.   VK_NUMPAD7 = 0x67
  185.   VK_NUMPAD8 = 0x68
  186.   VK_NUMPAD9 = 0x69
  187.   VK_MULTIPLY = 0x6A
  188.   VK_ADD = 0x6B
  189.   VK_SEPARATOR = 0x6C
  190.   VK_SUBTRACT = 0x6D
  191.   VK_DECIMAL = 0x6E
  192.   VK_DIVIDE = 0x6F
  193.  
  194.   # function keys
  195.   VK_F1 = 0x70
  196.   VK_F2 = 0x71
  197.   VK_F3 = 0x72
  198.   VK_F4 = 0x73
  199.   VK_F5 = 0x74
  200.   VK_F6 = 0x75
  201.   VK_F7 = 0x76
  202.   VK_F8 = 0x77
  203.   VK_F9 = 0x78
  204.   VK_F10 = 0x79
  205.   VK_F11 = 0x7A
  206.   VK_F12 = 0x7B
  207.  
  208.   VK_NUMLOCK = 0x90 # NUM Lock
  209.  
  210.   # control keys
  211.   VK_LSHIFT = 0xA0 # Left SHIFT key
  212.   VK_RSHIFT = 0xA1 # Right SHIFT key
  213.   VK_LCONTROL = 0xA2 # Left CONTROL key
  214.   VK_RCONTROL = 0xA3 # Right CONTROL key
  215.   VK_LMENU = 0xA4 # Left Menu key
  216.   VK_RMENU = 0xA5 # Right MENU key
  217.  
  218.   # media controls
  219.   VK_MEDIA_NEXT_TRACK = 0xB0 # Next Track key
  220.   VK_MEDIA_PREV_TRACK = 0xB1 # Previous Track key
  221.   VK_MEDIA_STOP = 0xB2 # Stop Media key
  222.   VK_MEDIA_PLAY_PAUSE = 0xB3 # Play/Pause Media key
  223.   VK_VOLUME_MUTE = 0xAD # Volume Mute key
  224.   VK_VOLUME_DOWN = 0xAE # Volume Down key
  225.   VK_VOLUME_UP = 0xAF # Volume Up key
  226.  
  227.   # Used for miscellaneous characters; some can vary by keyboard.
  228.   VK_OEM_1 = 0xBA # For the US standard keyboard, the ';:' key
  229.   VK_OEM_PLUS = 0xBB # For any country/region, the '+' key
  230.   VK_OEM_COMMA = 0xBC # For any country/region, the ',' key
  231.   VK_OEM_MINUS = 0xBD # For any country/region, the '-' key
  232.   VK_OEM_PERIOD = 0xBE # For any country/region, the '.' key
  233.   VK_OEM_2 = 0xBF # For the US standard keyboard, the '/?' key
  234.   VK_OEM_3 = 0xC0 # For the US standard keyboard, the '`~' key
  235.   VK_OEM_4 = 0xDB # For the US standard keyboard, the '[{' key
  236.   VK_OEM_5 = 0xDC # For the US standard keyboard, the '\|' key
  237.   VK_OEM_6 = 0xDD # For the US standard keyboard, the ']}' key
  238.   VK_OEM_7 = 0xDE # For the US standard keyboard, the 'single-quote/double-quote' key
  239.   VK_OEM_8 = 0xDF # Used for miscellaneous characters; it can vary by keyboard.
  240.   VK_OEM_102 = 0xE2 # Either the angle bracket key or the backslash key on the RT 102-key keyboard
  241.  
  242.   # Special keyboard keys
  243.   VK_BROWSER_BACK = 0xA6 # Browser Back key
  244.   VK_BROWSER_FORWARD = 0xA7 # Browser Forward key
  245.   VK_BROWSER_REFRESH = 0xA8 # Browser Refresh key
  246.   VK_BROWSER_STOP = 0xA9 # Browser Stop key
  247.   VK_BROWSER_SEARCH = 0xAA # Browser Search key
  248.   VK_BROWSER_FAVORITES = 0xAB # Browser Favorites key
  249.   VK_BROWSER_HOME = 0xAC # Browser Start and Home key
  250.   VK_LAUNCH_MAIL = 0xB4 # Start Mail key
  251.   VK_LAUNCH_MEDIA_SELECT = 0xB5 # Select Media key
  252.   VK_LAUNCH_APP1 = 0xB6 #Start Application 1 key
  253.   VK_LAUNCH_APP2 = 0xB7 # Start Application 2 key
  254.  
  255.   # Use as MapVirtualKeyEx second parameter function
  256.   # ---------------------------------------------------------------------------------------------------
  257.   # The uCode parameter is a virtual-key code and is translated into an unshifted character value in the
  258.   # low order word of the return value. Dead keys (diacritics) are indicated by setting the top bit of
  259.   # the return value. If there is no translation, the function returns 0.
  260.   MAPVK_VK_TO_CHAR = 2
  261.   # The uCode parameter is a virtual-key code and is translated into a scan code.
  262.   # If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand
  263.   # scan code is returned. If there is no translation, the function returns 0.
  264.   MAPVK_VK_TO_VSC = 0
  265.   # The uCode parameter is a virtual-key code and is translated into a scan code. If it is a virtual-key
  266.   # code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned.
  267.   # If the scan code is an extended scan code, the high byte of the uCode value can contain either 0xe0 or
  268.   # 0xe1 to specify the extended scan code. If there is no translation, the function returns 0.
  269.   MAPVK_VK_TO_VSC_EX = 4
  270.   # The uCode parameter is a scan code and is translated into a virtual-key code that does not distinguish
  271.   # between left- and right-hand keys. If there is no translation, the function returns 0.
  272.   MAPVK_VSC_TO_VK = 1
  273.   # The uCode parameter is a scan code and is translated into a virtual-key code that distinguishes between
  274.   # left- and right-hand keys. If there is no translation, the function returns 0.
  275.   MAPVK_VSC_TO_VK_EX = 3
  276.  
  277.   # Win32 libraries
  278.   # Retrieves a string that represents the name of a key
  279.   # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mapvirtualkeyexa
  280.   GetKeyNameTextA = Win32API.new('User32', 'GetKeyNameTextA', 'LPI', 'I')
  281.   # Translates (maps) a virtual-key code into a scan code or character value, or translates a scan code
  282.   # into a virtual-key code. The function translates the codes using the input language and an input
  283.   # locale identifier.
  284.   # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mapvirtualkeyexa
  285.   MapVirtualKeyEx = Win32API.new('User32', 'MapVirtualKey', 'IIP', 'I')
  286.   GetKeyState = Win32API.new('User32', 'GetKeyState', 'I', 'I')
  287.   GetKeyboardState = Win32API.new('User32', 'GetKeyboardState', 'P', 'I')
  288.   # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate
  289.   GetAsyncKeyState = Win32API.new('User32', 'GetAsyncKeyState', 'I', 'I')
  290.   GetKeyboardLayout = Win32API.new('User32', 'GetKeyboardLayout', 'I', 'I')
  291.   ToUnicode = Win32API.new('User32', 'ToUnicode', 'IIPPII', 'I')
  292.  
  293.   # returns a keyboard layout identifier
  294.   # see https://docs.microsoft.com/it-it/windows/win32/intl/language-identifier-constants-and-strings
  295.   # @return [Integer] the keyboard layout identifier
  296.   def self.get_keyboard_layout
  297.     GetKeyboardLayout.call 0
  298.   end
  299.  
  300.   # gets the key name as Windows named it.
  301.   # @param [Integer, Symbol] key_code
  302.   # @param [Integer] buffer_size
  303.   # @return [String]
  304.   def self.get_key_name_text(key_code, buffer_size = 32)
  305.     key_code = key_symbol_to_code(key_code)
  306.     buffer = ' ' * buffer_size
  307.     scan_code = map_virtual_key(key_code)
  308.     name_size = GetKeyNameTextA.call(scan_code << 16 | (1 << 25), buffer, buffer_size)
  309.     raise KeyboardInputNameError.new("Error processing character #{key_code} name") if name_size == 0
  310.     name = buffer.unpack('A*').first
  311.     return name if name_size > 1
  312.     unicode_to_char(name.codepoints.map { |c| "\\u%04X" % c }.first)
  313.   end
  314.  
  315.   # The return value is either a scan code, a virtual-key code, or a character value, depending on the value of
  316.   # virtual_key_code and map_type. If there is no translation, the return value is zero.
  317.   # @param [Object] virtual_key_code
  318.   # @param [Integer] map_type
  319.   def self.map_virtual_key(virtual_key_code, map_type = MAPVK_VK_TO_VSC)
  320.     MapVirtualKeyEx.call(virtual_key_code, map_type, get_keyboard_layout)
  321.   end
  322.  
  323.   # obtains the key state in a 2-bit integer
  324.   # @param [Integer] key
  325.   def self.get_key_state(key)
  326.     GetKeyState.call key
  327.   end
  328.  
  329.   # returns a 256bit array with the state of each key.
  330.   # ex. get_keyboard_state[KEY_C] -> you get the value
  331.   # @return [Array]
  332.   def self.get_keyboard_state_ary
  333.     get_keyboard_state.unpack('C*')
  334.   end
  335.  
  336.   def self.get_keyboard_state
  337.     buffer = ' ' * 256
  338.     GetKeyboardState.call(buffer)
  339.     buffer
  340.   end
  341.  
  342.   # returns the key letter inpuy in relation to the keyboard layout
  343.   # and status (ex. e key + SHIFT -> E)
  344.   # @param [Integer, Symbol] key
  345.   # @param [Integer] buff_size
  346.   # @return [String] the key text
  347.   def self.unicode_char(key, buff_size = 10)
  348.     key = key_symbol_to_code(key)
  349.     buffer = ' ' * buff_size
  350.     res = ToUnicode.call(key, map_virtual_key(key), get_keyboard_state, buffer, buff_size, 0)
  351.     return '' if res != 1
  352.     unicode_to_char(sprintf('\u%04x', buffer.unpack('Q')[0]))
  353.   end
  354.  
  355.   def self.get_async_key_state(key)
  356.     GetAsyncKeyState.call key
  357.   end
  358.  
  359.   # determines if a key is pressed
  360.   # @param [Integer, Symbol] key
  361.   # @return [Boolean]
  362.   def self.key_pressed?(key)
  363.     return false if key.nil?
  364.     key = key_symbol_to_code(key)
  365.     get_async_key_state(key).abs & 0x8000 == 0x8000
  366.   end
  367.  
  368.   # determines if the CAPS LOCK state is on
  369.   # @return [Boolean]
  370.   def self.caps_lock?
  371.     get_key_state(VK_CAPITAL) == 1
  372.   end
  373.  
  374.   # determines if the NUMPAD LOCK state is on
  375.   # @return [Boolean]
  376.   def self.numpad_lock?
  377.     get_key_state(VK_NUMLOCK) == 1
  378.   end
  379.  
  380.   # returns the const value from a key button
  381.   # ex. :VK_LSHIFT => 0xA0
  382.   # @param [Symbol, Integer] key_symbol
  383.   # @return [Integer]
  384.   def self.key_symbol_to_code(key_symbol)
  385.     return key_symbol if key_symbol.is_a?(Integer)
  386.     Keyboard.const_get key_symbol
  387.   end
  388.  
  389.   # Converts an Unicode identifier to a char
  390.   # ex. '\u00E8'  -> 'è'
  391.   #     '\u0034'  -> '4'
  392.   #     '\u20AC'  -> '€'
  393.   # @param [String] code
  394.   # @return [String]
  395.   def self.unicode_to_char(code)
  396.     code.gsub(/\\u[\da-f]{4}/i) { |m| [m[-4..-1].to_i(16)].pack('U') }
  397.   end
  398. end
  399.  
  400. $imported = {} if $imported == nil
  401. $imported['H87-Keyboard'] = 1.0
  402.  
  403. #===============================================================================
  404. # ** Game_System
  405. #===============================================================================
  406. class Game_System
  407.  
  408.   # converts the game key symbol with the configured virtual key
  409.   # ex. :UP -> [:VK_UP]
  410.   #     :C  -> [:VK_SPACE, :VK_RETURN, :KEY_Z]
  411.   # @param [Array<Symbol>] original_key
  412.   def adjust_keyboard(original_key)
  413.     if keyboard_set.include? original_key
  414.       keyboard_set[original_key]
  415.     else
  416.       original_key
  417.     end
  418.   end
  419.  
  420.   # initializes and returns the configured keyboard set
  421.   # this attribute can be customized with a script, so the
  422.   # player can customize the keyboard game mapping
  423.   # @return [Hash]
  424.   def keyboard_set
  425.     @keyboard_set ||= create_default_keyboard_set
  426.   end
  427.  
  428.   # creates the default keyboard game mapping
  429.   # @return [Hash{Symbol->Array<Symbol>}]
  430.   def create_default_keyboard_set
  431.     #noinspection RubyResolve
  432.     @keyboard_set = Marshal.load(Marshal.dump(Keyboard::Settings::DEFAULT_KEY_SET))
  433.   end
  434. end
  435.  
  436. #===============================================================================
  437. # ** Vocab
  438. #===============================================================================
  439. module Vocab
  440.  
  441.   # gets the key name as configured. Example:
  442.   # key_name(:C) -> 'SPACING'
  443.   # key_name(:X) -> 'LEFT SHIFT'
  444.   # Returns the custom traslation CUSTOM_KEY_TRANSLATION if present
  445.   # @param [Symbol, Integer] key
  446.   # @return [String, nil]
  447.   def self.key_name(key)
  448.     if $game_system
  449.       conf = $game_system.keyboard_set
  450.     else
  451.       conf = Keyboard::Settings::DEFAULT_KEY_SET
  452.     end
  453.     if conf.keys.include?(key)
  454.       key = conf[key].is_a?(Array) ? conf[key].first : conf[key]
  455.     end
  456.     if Keyboard::Settings::CUSTOM_KEY_TRANSLATION.include?(key)
  457.       Keyboard::Settings::CUSTOM_KEY_TRANSLATION[key]
  458.     else
  459.       keyboard_button(key)
  460.     end
  461.   end
  462.  
  463.   # gets the key name
  464.   # @param [Symbol, Integer] key
  465.   # @return [String]
  466.   def self.keyboard_button(key)
  467.     if key.is_a?(Symbol)
  468.       code = Keyboard.key_symbol_to_code(key)
  469.     elsif key.is_a?(Integer)
  470.       code = key
  471.     else
  472.       return '';
  473.     end
  474.     begin
  475.       Keyboard.get_key_name_text(code)
  476.     rescue KeyboardInputNameError => err
  477.       puts err.message
  478.       ''
  479.     end
  480.   end
  481. end
  482.  
  483. #===============================================================================
  484. # ** Keyboard_Status
  485. #===============================================================================
  486. class Keyboard_Status
  487.   attr_reader :state
  488.   attr_reader :old_state
  489.  
  490.   def initialize
  491.     @state = keyboard_state
  492.     @old_state = @state
  493.     @timing = [nil] * 256
  494.   end
  495.  
  496.   def timing(key_symbol)
  497.     @timing[Keyboard.key_symbol_to_code(key_symbol)]
  498.   end
  499.  
  500.   def update
  501.     @old_state = @state
  502.     @state = keyboard_state
  503.     @timing.each_with_index do |count, index|
  504.       @timing[index] = calculate_timing(count, index)
  505.     end
  506.   end
  507.  
  508.   def keyboard_state
  509.     Keyboard.get_keyboard_state_ary.map { |x| x > 100 }
  510.   end
  511.  
  512.  
  513.   # @param [Symbol, Array<Symbol>] data
  514.   # @return [TrueClass, FalseClass]
  515.   def pressed?(data)
  516.     return key_pressed?(data) if data.is_a?(Symbol)
  517.     data.each { |key| return true if key_pressed?(key) }
  518.     false
  519.   end
  520.  
  521.   # determines if a key is pressed. needs a symbol as constant name,
  522.   # for ex. :KEY_C. Only KEYBOARD keys, not game as :X, :UP, :L
  523.   # @param [Symbol] key
  524.   def key_pressed?(key)
  525.     hw_key = Keyboard.key_symbol_to_code(key)
  526.     @state[hw_key]
  527.     #Keyboard_Data.key_pressed?(hw_key)
  528.   end
  529.  
  530.   private
  531.  
  532.   def calculate_timing(count, index)
  533.     return nil unless @state[index]
  534.     return 0 unless @old_state[index]
  535.     count.nil? ? 0 : count + 1
  536.   end
  537. end
  538.  
  539. #===============================================================================
  540. # ** Input
  541. #===============================================================================
  542. module Input
  543.   KB_NORMALIZER = {2 => :DOWN, 4 => :LEFT, 6 => :RIGHT, 8 => :UP, 11 => :A,
  544.                    12 => :B, 13 => :C, 14 => :X, 15 => :Y, 16 => :Z, 17 => :L, 18 => :R}
  545.   @keyboard = Keyboard_Status.new
  546.  
  547.   # @param [Integer, Symbol] key
  548.   # @return [Symbol]
  549.   def self.normalize_keyboard_input(key)
  550.     KB_NORMALIZER[key]
  551.   end
  552.  
  553.   # @return [Array<Symbol>, Symbol]
  554.   # @param [Symbol, Integer] key
  555.   def self.get_virtual_key(key)
  556.     if $game_system
  557.       $game_system.adjust_keyboard(key)
  558.     elsif Keyboard::Settings::DEFAULT_KEY_SET[key]
  559.       Keyboard::Settings::DEFAULT_KEY_SET[key]
  560.     else
  561.       key
  562.     end
  563.   end
  564.  
  565.   # update the keyboard status
  566.   def self.update_keyboard_state
  567.     @keyboard.update
  568.   end
  569.  
  570.   # updates the input status
  571.   def self.update
  572.     update_keyboard_state
  573.   end
  574.  
  575.   # Direction pressed
  576.   def self.dir4
  577.     return 2 if press?(:DOWN)
  578.     return 4 if press?(:LEFT)
  579.     return 6 if press?(:RIGHT)
  580.     return 8 if press?(:UP)
  581.     0
  582.   end
  583.  
  584.   # Eight directions pressed
  585.   def self.dir8
  586.     return 1 if press?(:DOWN) and press?(:LEFT)
  587.     return 3 if press?(:DOWN) and press?(:RIGHT)
  588.     return 7 if press?(:UP) and press?(:LEFT)
  589.     return 9 if press?(:UP) and press?(:RIGHT)
  590.     dir4
  591.   end
  592.  
  593.   # determines if a key is triggered down and then up.
  594.   # You can insert a game key (:X, :L, :UP...) or a keyboard hardware
  595.   # key (:KEY_C, :VK_TAB, :VK_RETURN...)
  596.   # @param [Symbol] key
  597.   def self.trigger?(key)
  598.     return false if key.nil?
  599.     real_key = get_virtual_key(key)
  600.     return v_key_trigger?(real_key) if real_key.is_a?(Symbol)
  601.     return real_key.compact.any? { |k| v_key_trigger?(k) } if real_key.is_a?(Array)
  602.     false
  603.   end
  604.  
  605.   # determines if a key is continuously pressed.
  606.   # You can insert a game key (:X, :L, :UP...) or a keyboard hardware
  607.   # key (:KEY_C, :VK_TAB, :VK_RETURN...) or an integer representing
  608.   # the key ID.
  609.   # @param [Integer, Symbol] key
  610.   def self.press?(key)
  611.     return false if key.nil?
  612.     key = normalize_keyboard_input(key) if key.is_a?(Integer)
  613.     hw_key = get_virtual_key(key)
  614.     @keyboard.pressed?(hw_key)
  615.   end
  616.  
  617.   def self.repeat?(key)
  618.     return false if key.nil?
  619.     real_key = get_virtual_key(key)
  620.     return v_key_repeat?(real_key) if real_key.is_a?(Symbol)
  621.     return real_key.compact.any? { |k| v_key_repeat?(k) } if real_key.is_a?(Array)
  622.   end
  623.  
  624.   # @param [Symbol] key
  625.   def self.v_key_trigger?(key)
  626.     timing = @keyboard.timing(key)
  627.     timing == 0
  628.   end
  629.  
  630.   # @param [Symbol] key
  631.   def self.v_key_repeat?(key)
  632.     timing = @keyboard.timing(key)
  633.     timing != nil and (timing == 0 or timing == 30 or timing > 30 and timing % 5 == 0)
  634.   end
  635. end
  636.  
  637. #===============================================================================
  638. # ** Window_Base
  639. #===============================================================================
  640. class Window_Base < Window
  641.   alias h87_k_normal_process_escape process_escape_character unless $@
  642.  
  643.   def process_escape_character(code, text, pos)
  644.     if code.upcase == 'K'
  645.       process_draw_key_name(obtain_escape_param(text), pos)
  646.       return
  647.     end
  648.     h87_k_normal_process_escape(code, text, pos)
  649.   end
  650.  
  651.   #--------------------------------------------------------------------------
  652.   # * Draws the key name
  653.   # @param [Integer] index
  654.   # @param [Hash<Integer>] pos
  655.   #--------------------------------------------------------------------------
  656.   def process_draw_key_name(index, pos)
  657.     if $imported['H87-ControllerMapper']
  658.       symbol = Controller_Mapper::Settings::KEY_INDEXES[index]
  659.     else
  660.       symbol = Keyboard::Settings::KEY_INDEXES[index]
  661.     end
  662.     puts "Key not found for index #{index}" if symbol.nil?
  663.     key_name = Vocab.key_name(symbol)
  664.     if use_keyboard_brackets?
  665.       key_name = sprintf('[%s]', key_name)
  666.     end
  667.     if custom_keyboard_color?
  668.       old_color = contents.font.color.clone
  669.       change_color(text_color(Keyboard::Settings::CHANGE_COLOR))
  670.     end
  671.     draw_text(pos[:x], pos[:y], text_size(key_name).width + 2, line_height, key_name)
  672.     change_color(old_color) if custom_keyboard_color?
  673.     pos[:x] += text_size(key_name).width
  674.   end
  675.  
  676.   def custom_keyboard_color?
  677.     Keyboard::Settings::CHANGE_COLOR > 0
  678.   end
  679.  
  680.   def use_keyboard_brackets?
  681.     Keyboard::Settings::USE_BRACKETS
  682.   end
  683. end
  684.  
  685.  
  686. class KeyboardInputNameError < StandardError
  687.  
  688. end
Add Comment
Please, Sign In to add comment