Page:
Advanced Usage Example
1
Advanced Usage Example
VetheonGames edited this page 2023-06-08 11:46:59 -06:00
Advanced Usage Examples
Customizing the Input Handler
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
Using the Shorthand
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
Handling Multiple Input Contexts
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)