Question
java code write a method Handling Key Events The starter code does not react to key presses, because we havent defined how to handle the
java code
write a method
Handling Key Events
The starter code does not react to key presses, because we havent defined how to handle the key presses yet. We will define what each key press does in this private class:
class MyKeyHandler implements EventHandler {
@Override
public void handle(KeyEvent e) {
// TODO
} }
Inside the handle() method is where you will write code to handle what the game should do when a key is pressed.
Handling KeyEvent
When a key is pressed, handle() will be called, and a KeyEvent is passed in. We have provided a helper method handleKeyCode() you can then call.
void handleKeyCode(KeyCode keyCode)
Based on which key is pressed, your game should do the following:
- - move up
- - move down
- - move left
- - move right
- - undo
- - output to file
(Were using the arrow keys now instead of WASD. You shouldnt need to change any Streamline class code for this).
Notice this is very similar to play() in Streamline.java, except that now, instead of using a Scanner to read the user input, we use the KeyEvent (and its KeyCode) to distinguish which key is pressed.
In Streamline class - Keyevent/Key code similar to this
void play() while(currentstate.levelPassed !-true) System.out.println(currentstate.toString ()); System.out.print(">) Scanner theUser new Scanner (System.in); string theinput theUser.nextLine(); if ("w".equals (theInput)) t recordAndMove (Direction.UP); else if("a".equals (theInput)) f recordAndMove (Direction. LEFT); else if ("s".equals (theInput)) t recordAndMove (Direction. DOWN); else if ("d".equals (theInput)) t recordAndMove (Direction. RIGHT) else if ("u".equals (theInput)) undo (); else if ("o".equals (theInput)) t this.saveToFile() else if ("q".equals (theInput)) [ return; else System.out.println("Wrong Input, Try Again."); System.out.println(currentstate.tostring)); if (currentstate.levelPassed true) System.out.println("Level Passed!"); returnStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started