GAMES LESSON ELEVEN: Keyboard Events

We've already seen how to trigger events with the keyboard. In this lesson we discuss taking input from the keyboard. Take a look at the sample applet.

We had to modify the keyPressed method in order to take user input. Here's the altered method:

requestFocus(); this.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent k) { if(k.getKeyCode() != KeyEvent.VK_SHIFT){ if(!gameOver){ user+=k.getKeyChar(); check(); } else{ repaint(); } } } });
As you can see after user input is taken a call is made to the check method which compares the user input to the correct input. If the user matches the proper letter, a new letter is displayed through a call to the spawn method. You can trace the activity of the applet by inspecting the code shown below:

KEY.java

import java.awt.*; import java.applet.*; import java.util.*; import java.awt.event.*; public class KEY extends Applet implements Runnable{ Dimension d; Image offI; Thread tt; int x, y, index; String user = ""; String letter = ""; String letters = "abcdefghijklmnopqrstuvwxyz"; boolean gameOver; Random r; public void init(){ d = getSize(); r=new Random(); spawn(); offI=createImage(d.width,d.height); tt = new Thread(this); tt.start(); requestFocus(); this.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent k) { if(k.getKeyCode() != KeyEvent.VK_SHIFT){ if(!gameOver){ user+=k.getKeyChar(); check(); } else{ repaint(); } } } }); } public void check(){ if(user.equals(letter)){ if(index<letters.length()) spawn(); else gameOver=true; } user=""; } public void spawn(){ letter = letters.substring(index,index+1); x = Math.abs(r.nextInt()%400)+20; y = 0; index++; } public void run(){ while(!gameOver){ y+=3; if(y>d.height) y = 0; repaint(); try{ Thread.sleep(50); }catch(InterruptedException ie){ } } } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ Graphics offG = offI.getGraphics(); offG.setColor(Color.yellow); offG.fillRect(0,0,d.width,d.height); offG.setColor(Color.black); if(!gameOver) offG.drawString(letter, x, y); else offG.drawString("GAME OVER", 50,50); offG.drawString("INDEX: " + index, 10, 150); g.drawImage(offI, 0,0, this); } }


ASSIGNMENT: