Advertisement
nitishsp

Hangman in Java

Mar 10th, 2012
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.38 KB | None | 0 0
  1. import java.io.*;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.imageio.*;
  6. import java.util.*;
  7.  
  8. /*
  9. * Title: Hangman in Java
  10. * Author: Nitish
  11. * Date Created: 06/03/2012
  12. * Last Modified: 22/03/2012
  13. * All files => https://sites.google.com/site/nitishspblog/test/Hangman.zip
  14. */
  15.  
  16. class Hangman extends JFrame{
  17.    
  18.     Hangman() {
  19.         super("Hangman");
  20.         HangmanDraw hdObj=new HangmanDraw();       
  21.         hdObj.init();
  22.         add(hdObj);
  23.         setSize(800,500);
  24.         setVisible(true);
  25.         hdObj.requestFocus();
  26.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  27.        
  28.     }
  29.  
  30.     public static void main(String args[]) {
  31.      
  32.        new Hangman();
  33.     }
  34. }
  35.  
  36.  
  37. class HangmanDraw extends Canvas implements KeyListener {
  38.     ArrayList<String> fileContent=null;
  39.     ArrayList<Character> selectedCharacters=null;
  40.     int missedChances=0;
  41.     char[] word;
  42.     char[] tmp;
  43.     String fruit;
  44.     String[] himages;
  45.    
  46.     void init() {
  47.        
  48.         addKeyListener(this);
  49.         fruit=new String();
  50.         himages=new String[7];
  51.         fileContent=new ArrayList<String>();
  52.         selectedCharacters=new ArrayList<Character>();
  53.        
  54.         try {
  55.             BufferedReader br=new BufferedReader(new FileReader("hmandata.txt"));
  56.             //Import all the fruit names in an ArrayList
  57.             while((fruit=br.readLine())!=null) {
  58.                 fileContent.add(fruit);
  59.             }
  60.         }
  61.         catch(Exception e) {
  62.             e.printStackTrace();
  63.         }
  64.        
  65.         //Randomly select 1 fruit name from the ArrayList
  66.         //lowercase conversion is done to simplify the comparison in later steps
  67.         fruit=fileContent.get(new Random().nextInt(fileContent.size())).toLowerCase();
  68.        
  69.         /* The array 'tmp' contains fruit name to guess.
  70.         *  The array 'word' is used to hold part of the fruit name correctly guessed by user.
  71.         *  Underscore represents the character that has not been guessed.
  72.         *  
  73.         *  Example: mango
  74.         *  Initialization:
  75.         *  word => _ _ _ _ _
  76.         *  tmp =>  m a n g o
  77.         */
  78.         word=new char[fruit.length()*2];
  79.         tmp=new char[fruit.length()*2];
  80.         for(int arri=0,i=0;arri<word.length;arri++) {
  81.             tmp[arri]=fruit.charAt(i++);
  82.             word[arri++]='_';
  83.             word[arri]=' ';
  84.             tmp[arri]=' ';
  85.         }
  86.        
  87.         /*
  88.         int tt=word.length/3;
  89.         while(tt-->0) {
  90.             int rr=new Random().nextInt(word.length);
  91.             word[rr]=tmp[rr];
  92.         }*/
  93.        
  94.         //generate the names of hangman images (from 1.jpg to 7.jpg)
  95.         for(int i=0;i<7;i++){
  96.             himages[i]=(i+1)+".jpg";
  97.         }
  98.        
  99.         //End of initialization, call paint() method and wait for user input
  100.         repaint();
  101.     }
  102.    
  103.     public void paint(Graphics g) {
  104.         setBackground(Color.WHITE);
  105.         g.setFont(new Font("Arial",Font.BOLD,50));
  106.         if(checkWin()){ //player guessed the word correctly
  107.             removeKeyListener(this);
  108.             g.drawString("Congratulations!",50,200);
  109.            
  110.         }
  111.         else if(missedChances<6) { // game is still on
  112.             g.drawString((6-missedChances)+" chance(s) remaining!",20,60);
  113.             g.drawString(new String(word),20,200);
  114.             String uw="";
  115.             for(int l=0;l<selectedCharacters.size();l++) {
  116.                 uw=uw+selectedCharacters.get(l)+" ";               
  117.             }
  118.             g.drawString("Used Characters:",20,400);
  119.             g.drawString(uw,20,440);
  120.         }
  121.         else { //player made 6 false guesses
  122.             removeKeyListener(this);
  123.             g.drawString("You couldn't guess the word!",20,40);
  124.             g.drawString("The word was:",20,150);
  125.             g.drawString(new String(tmp),20,200);
  126.         }
  127.        
  128.         //Load appropriate image based on missedChances
  129.         Image img=null;
  130.         try{
  131.             img=ImageIO.read(new File("himages/"+himages[missedChances]));
  132.         }
  133.         catch(IOException e) {
  134.             e.printStackTrace();
  135.         }
  136.         g.drawImage(img,450,70,this);
  137.     }
  138.    
  139.     public void keyPressed(KeyEvent e)  {
  140.     }
  141.    
  142.     public void keyReleased(KeyEvent e )  {
  143.     }
  144.        
  145.     public void keyTyped(KeyEvent e )  {
  146.         //Fired each time user presses & releases one of the non-virtual keys.
  147.         char c=e.getKeyChar();
  148.        
  149.         //process key press only if user hasn't pressed the key before
  150.         if(!selectedCharacters.contains(c)) {
  151.             //add the key to the list of entered characters
  152.             selectedCharacters.add(c);
  153.            
  154.             //if user guesses a valid character, update the 'word' array
  155.             //else increment missedChances
  156.             boolean flag=false;
  157.             for(int i=0;i<word.length;i++) {
  158.                 if(c==tmp[i]) {
  159.                     word[i]=tmp[i];
  160.                     flag=true;
  161.                 }
  162.             }
  163.             if(!flag) {
  164.                 missedChances++;
  165.             }
  166.             repaint();
  167.             //call the paint() method to reflect the changes
  168.         }
  169.     }
  170.    
  171.     boolean checkWin() {
  172.         for(int i=0;i<word.length;i++) {
  173.                 if(word[i]!=tmp[i]) {
  174.                     return false;
  175.                 }
  176.         }
  177.         return true;
  178.     }
  179.  
  180. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement