GAMES TWO: LESSON SEVEN: Hangman
We will deal with an event-driven game in this lesson. Instead of using a
Thread (and the run method) to drive the game, this game will only progress
as the user responds. A perfect, event-driven game is the game of Hangman.
Go ahead and try out the sample:
As you can see, this is a very compact version of the game. It lacks the
usual graphics components of the game (something you get to add in the
assignment part of this lesson). Probably the most important part of this
game is the reset method:
public void reset(){
Random r = new Random();
index = Math.abs(r.nextInt()%bank.length);
String word = bank[index];
letters = new String[word.length()];
found = new boolean[word.length()];
for(int i=0; i
In the reset method all the variables used to keep track of the various
aspects of this game are provided with starting values.
The events dealt with in this game are fairly simple:
requestFocus();
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent k) {
if(!winner && !loser){
if(k.getKeyCode() == KeyEvent.VK_BACK_SPACE ||
k.getKeyCode() == KeyEvent.VK_DELETE){
guess = "";
}
else if(k.getKeyCode() == KeyEvent.VK_ENTER){
check();
}
else if(k.getKeyCode() != KeyEvent.VK_SHIFT){
guess = "" + k.getKeyChar();
}
}
else{
reset();
}
repaint();
}
});
The check method isn't too complicated either:
public void check(){
boolean missflag = true;
for(int i = 0; i-1) not_in_list=false;
}
if(not_in_list) used+=guess;
}
winner=true;
for(int i=0; i10) loser=true;
guess="";
}
ASSIGNMENT:
Piecing together the missing code for this applet should not be too
difficult. BUT adding the lines necessary to draw appropriate graphics to go
along with the game of Hangman could be a little more challenging. Good
luck.