Typing Tutor


We are going to make a typing game.


1. Create a frame for your typing game.


2. Create a member variable and initialize it as shown below:


char currentLetter;

currentLetter = generateRandomLetter();

char generateRandomLetter() {
      Random r = new Random();
      return (char) (r.nextInt(26) + 'a');
}


3.Use a JLabel to show the value of currentLetter on the screen. Make sure it changes every time you start the game.


4. Format the letter so that it is nice and big. Here are some hints….


jLabel.setFont(jLabel.getFont().deriveFont(28.0f));
jLabel.setHorizontalAlignment(JLabel.CENTER);


5. Add a key listener to the frame.


6. Make the letter change every time a key is pressed.

To do that, in the keyReleased method:
      i) Reset currentLetter.
      ii) Update your JLabel.


7. In the keyPressed method, print out the character that the user typed.


8. If they typed the currentLetter, print “correct”.

9. If they typed the correct letter, set the frame background to green. Otherwise set it to red.

10. [optional] After a certain number of characters, show the users’ typing speed.


Date timeAtStart = new Date();

private void showTypingSpeed(int numberOfCorrectCharactersTyped) {
      Date timeAtEnd = new Date();
      long gameDuration = timeAtEnd.getTime() - timeAtStart.getTime();
      long gameInSeconds = (gameDuration / 1000) % 60;
      double charactersPerSecond = ((double) numberOfCorrectCharactersTyped / (double) gameInSeconds);
      int charactersPerMinute = (int) (charactersPerSecond * 60);
      JOptionPane.showMessageDialog(null, "Your typing speed is " + charactersPerMinute + " characters per minute.");
}