Hangman Source Code: Java

Graphix 2 Tallied Votes 4K Views Share

Hey everybody,

Lately I have written the game Hangman in many different languages (C, JavaScript, Java and PHP so far). Here is the code snippet for Java! It uses a words file, on the bottom of this post you will see a small example of a few words. The source code for other languages can be found here on DaniWeb and on my new website: http://www.hangman.symbolwebdesign.nl/.

Due to the fact it is not possible (in web apllications) to open a words file using Java, it is required to directly put the words string separated by a | into the string variable. Modify the string in the initGame() function in the script (line 59).

~G

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.lang.reflect.Array;

public class hangman extends Applet implements ActionListener{
  
        static final int DEAD=13;   // amount of errors till loss
        private int errors;        // amount of errors
        private String message;   // error or victorie
        private String information; // information of the message
        private String rword;      // the rword
        private StringBuffer gword;// the gword
        private Button bStart;      // Button "Restart"
        private Button bGo;         // Button "Go"
        private TextField tfLetter; // letter box
        private Font fnt;           // common font
		
        public void init(){
				
		fnt = new Font( "Monospaced", 0, 12 );
		setFont(fnt);
				
                // Create textbox for guess letter
                
                tfLetter = new TextField();

                // Create buttons and labels
                
                bStart = new Button("Restart");
                bGo = new Button("Go");

                // Add the graphical elements to the applet
                
                add(bStart);
                add(new Label("Guess a letter:"));
                add(tfLetter);
                add(bGo);
  
                // Buttons are events:

                bStart.addActionListener(this);
                bGo.addActionListener(this);
  
                // Start first game

                initGame();
        }
        
        public void initGame(){

		
		/* Setting the errors to 0 */
                errors=0;
				
				
		/* Enter the wordslist, separated by a | here: */
                String str = "computer|radio|calculator|teacher|bureau|police|geometry|president|subject|country|enviroment|classroom|animals|province|month|politics|puzzle|instrument|kitchen|language|vampire|ghost|solution|service|software|virus25|security|phonenumber|expert|website|agreement|support|compatibility|advanced|search|triathlon|immediately|encyclopedia|endurance|distance|nature|history|organization|international|championship|government|popularity|thousand|feature|wetsuit|fitness|legendary|variation|equal|approximately|segment|priority|physics|branche|science|mathematics|lightning|dispersion|accelerator|detector|terminology|design|operation|foundation|application|prediction|reference|measurement|concept|perspective|overview|position|airplane|symmetry|dimension|toxic|algebra|illustration|classic|verification|citation|unusual|resource|analysis|license|comedy|screenplay|production|release|emphasis|director|trademark|vehicle|aircraft|experiment";
                String[] temp;
				
                /* delimiter */
                String delimiter = "\\|";
				
                /* given string will be split by the argument delimiter provided. */
                temp = str.split(delimiter);
				
		/* Setting the seed */
		Random randomGenerator = new Random();
				
		/* Generating random number */
		int randomInt = randomGenerator.nextInt(temp.length);

                rword = new String(temp[randomInt]);

                char positions[] = new char[rword.length()];
                for (int i=0; i<rword.length(); i++) {
                        positions[i] = '.';
                }
                String s = new String(positions);
                gword = new StringBuffer(s);

                tfLetter.setText("");
  
                // Delete the messages

                message="";
                information = "";
                repaint();
        }

        public void paint(Graphics g) {
		
                
                // Draw the hangman
                int baseY = 250;
                
                if (errors >  0){    // ground
                        g.drawLine(90, baseY,200,baseY);
                }
                if (errors >  1){    // bar up
                        g.drawLine(125,baseY,125,baseY-100);
                }
                if (errors >  2){
                        g.drawLine(110,baseY,125,baseY-15);
                }
                if (errors >  3){
                        g.drawLine(140,baseY,125,baseY-15);
                }
                if (errors >  4){    // side bar
                        g.drawLine(125,baseY-100,175,baseY-100);
                }
                if (errors >  5){
                        g.drawLine(125,baseY-85,140,baseY-100);
                }
                if (errors >  6){    // rope
                        g.drawLine(175,baseY-100,175,baseY-75);
                }
                if (errors >  7){    // body
                        g.drawOval(170,baseY-75,10,12);
                }
                if (errors >  8){
                        g.drawOval(170,baseY-65,15,25);
                }
                if (errors >  9){    // arms
                        g.drawLine(160,baseY-65,170,baseY-60);
                }
                if (errors > 10){
                        g.drawLine(183,baseY-60,193,baseY-65);
                }
                if (errors > 11){    // legs
                        g.drawLine(165,baseY-30,170,baseY-45);
                }
                if (errors > 12){
                        g.drawLine(183,baseY-45,193,baseY-30);
                }
                
                // Show the messages
                g.drawString( message, 40, baseY+25 );
                g.drawString( information, 25, baseY+45 );
				g.drawString( new String (gword), 110, 60);
        
        }
        
        public void actionPerformed(ActionEvent e){

                if (e.getSource() == bStart){
                        initGame();
                }

                if (e.getSource() == bGo){

                        processTurn();

                        // Delete the letter input box

                        tfLetter.setText("");
                        repaint();
                }
        }

        private void processTurn(){
                String s, t;
                char a;
                
                s = tfLetter.getText();
                a = s.charAt(0);
                
                if (!Character.isLetter(a)){
                          message="Only enter letters!";
                          return;
                }
                if (s.length()>1){
                          message="One letter at a time!";
                          return;
                }
        
                // Has the letter been guessed
    
                t = new String(gword);
                if (t.indexOf(s) != -1){
                        message="Letter has already been guessed";
                        return;
                }
        
                // If the letter doesn't occur in the rword
        
                if (rword.indexOf(s) == -1){
                        message="";
                        errors++;
                        if (errors==DEAD){
                                message="You lost!";
                                information = 
                                      "Click on restart for another chance!";
                        }
                        
                        return;
                }
        
                // Replace dots in gword with the found letter.
        
                for (int i=0; i<rword.length(); i++){
                        if (rword.charAt(i) == a){
                                gword.setCharAt(i, a);
                        }
                }
                t = new String(gword);
        
                // If all the dots have been filled, you win
        
                if (t.indexOf('.') == -1){
                        message="You win!";
                        return;
                }
              
                // Delete message
                
                message="";
				repaint();
        }
}
stultuske 1,116 Posting Maven Featured Poster

why don't you just put the words in a .txt (or whatever) file and read them from your application? it's a lot easier if you want to add or remove words from the list

neekia 0 Newbie Poster

Will this work in Netbeans IDE? I really don't know how to input your code using netbeans>.<

peter_budo 2,532 Code tags enforcer Team Colleague Featured Poster

Will this work in Netbeans IDE? I really don't know how to input your code using netbeans>.<

That's good, at least you cannot submit it as your own work...

salomonsk8 0 Newbie Poster

For it to work in Netbeans you will have to first scan the code into your JCode scanner. So print it off on paper first, then use a flatbed scanner (must be at least 1200 dpi I think, might be 1300 though) then send the file to the JCode scanner and it will convert it to the type of Java you need for Netbeans IDE, since Netbeans doesn't accept regular Java form code.

Hope this helps.

stultuske 1,116 Posting Maven Featured Poster

salomonsk8: not only are you incorrect, but you are bumping a dead thread.
what on earth makes you believe that an IDE that is used for Java development would NOT understand Java code?????
all the "skills" needed to have the above code in NetBeans is copy-paste.

riahc3 commented: Hello, Mr. Sense Of Humor -1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I thought that was quite funny.

riahc3 50   Team Colleague

He was obviously being sarcastic....

Due to the fact it is not possible (in web apllications) to open a words file using Java, it is required to directly put the words string separated by a | into the string variable. Modify the string in the initGame() function in the script (line 59).

Since when? JS can do it perfectly AFAIK. Obviously we wont get into Java....

salomonsk8 0 Newbie Poster

HAHAHAHAHAH! Thanks guys, you just made my morning. Sorry, I just couldn't help myself with that last post. I was in a good mood yesterday I guess. This would have been a great oportunity to mess with Stultuske a bit, but in the interest of not completely trolling a usefull and productive thread I will refrain ;) "Fact. Bears eat beets. Bears. Beets. Battlestar Galactica." lol.

iceman22 0 Newbie Poster

lol nice man. i thought it was pretty hillarious. "JCode scanner" HAHAHA! That part cracked me up man. I was like WTF is that?!?!? then i realized you were joking.

salomonsk8 0 Newbie Poster

Haha thanks. Just kidding around, all in good fun. Hope I didn't offend anyone, it's a good community here.

stultuske 1,116 Posting Maven Featured Poster

He was obviously being sarcastic....

riahc3: yes, you are right. there are absolutely no "just beginning developers and members" who would believe him.
(now THAT was sarcasm). sure, a joke now and then is not that big a problem, but make sure it's clear to all (even those that don't know any better) that it actually is just that - a joke -. and I'm afraid you would be surprised as to what some would believe just because it appears on the internet and is written by someone with more experience than they have.

in my opinion, this is supposed to be a forum by which we help people improve their skills, not ridicule them or set them on a false path, but "hey, who am I?"

salomonsk8: you didn't offend anyone, but do keep in mind, not all those who read your reply are smart enough (or have enough knowledge) to actually realise it's a joke.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, I think we'v exhausted this one now. No more posts that aren't directly relevant to the original topic please.
Thanks
J.

Logeeks 0 Newbie Poster

What does dilimiter = "\|"; do?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The | character is used as a delimiter in data file for this app. The pcode uses a reguar expression to parse the file, but in a REGEX | is a special character, so to use it as a literal you "escape" it with a \

Ryuga_1 0 Newbie Poster

how i run this code, there is no main class?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's an applet - you run it in a browser window. The tutorial starts here:
http://docs.oracle.com/javase/tutorial/deployment/applet/index.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.