-
Notifications
You must be signed in to change notification settings - Fork 0
Advanced Usage Example
VetheonGames edited this page Jun 8, 2023
·
1 revision
The DynamicCursesInput::InputHandler
class is highly customizable. You can create a subclass and override the handle_key method to add custom behavior for specific keys. For example:
class MyInputHandler < DynamicCursesInput::InputHandler
private
def handle_key(chk)
case chk
when 'a'
# Do something special when 'a' is pressed
else
super
end
end
end
Then, you can use MyInputHandler
instead of DynamicCursesInput::InputHandler:
Curses.init_screen
Curses.addstr("Enter your name: ")
name = MyInputHandler.catch_input(true)
Curses.addstr("\nYou entered: #{name}")
Curses.getch
Curses.close_screen
The DCI
shorthand can be used for easier access to the gem's functionality. For example:
Curses.init_screen
Curses.addstr("Enter your name: ")
name = DCI.catch_input(true)
Curses.addstr("\nYou entered: #{name}")
Curses.getch
Curses.close_screen
If your application has multiple input contexts (e.g., different screens or modes), you can create a separate InputHandler
instance for each context. This allows you to customize the input handling behavior for each context.
class MainMenuInputHandler < DynamicCursesInput::InputHandler
# Custom behavior for the main menu
end
class GameInputHandler < DynamicCursesInput::InputHandler
# Custom behavior for the game
end
Then, use the appropriate input handler depending on the current context:
input_handler = case current_context
when :main_menu then MainMenuInputHandler
when :game then GameInputHandler
end
input = input_handler.catch_input(true)