Hey everyone, iv'e been working on a Hangman code for weeks for the beginning of a semester long portfolio, iv'e tried several codes, but no matter what i do i can't seem to make it work...

The specifics for the program were:

  • Create a list of possible words called "words.txt" (iv'e got that down obviously
  • The games suppose to display the word to be guessed as a series of "*"'s.

  • If the letters guessed correctly, the letter becomes displayed amongst the series of "*"'s.

  • Display all the letters used (correctly & incorrectly) above the word.
  • If the words guessed correctly, add up the score (5 points per letters and -5 off the final score per word that was guessing incorrectly e.g. - if the words "blue" then it'll be worth 20 points, 3 wrong guesses makes the final score 5).
  • If the player gets 5 wrong guesses, it's an instant loss, and they get a score of 0.
  • If the player looses, prompt them to input their name and have it stored in another text file labelled "scores.txt".
  • And then, start again with a new word.

And last but most certainly not least, it all needs to be done using console only.

All in all it's a pretty straight forward game of Hangman, but since it's only my first semester in software development, i still REALLY suck ...

Don't get the wrong idea though, i'm not asking you guys to do my work for me, this is only the first part of our portfolio work, it'll need to be developed each week as the semester goes.

I'm just looking for some help on the foundation of the code, since i'm literally clueless as to how it's suppose to be done, or even started.

Thank you all for at least reading all this, my lecturer doesn't even seem to know how to do it ...

see this tutorial on how to get the words in from the file
http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html

once you have all the words sorted into an array, select one at random using the random number method of your choice (Math.random () or java.util.Random)

now break your word down into a char array

char [] charWord = word.toCharArray();

creat a new char array of the same length as your word

char [] guessed = new char [charWord.length];

now populate it with stars

for (int i = 0; i < guessed.length; i++)
{
    guessed [i] = '\*';
}

check if the person guessed a correct letter using
if they did guess correctly then replace the star with a letter

int instancesFound = 0;
for (int i = 0; i < charWord.length; i++)
{
    if (charWord[i] == letter)
    {
        instancesFound ++;
        guessed[i] = letter;
    }
}

if they did not guess correctly then instancesFound will still be 0

you need a way of keeping track of how many wrong guesses and what they were

String guessedLetters = "";
if (!guessedLetters.contains (letter))
{
    guessedLetters+=letter;
}
if (guessedLetters.length () > MAX_GUESSES)
{
    game over
}

to get input from the user use Scanner class

import java.util.Scanner;





Scanner scanner = new Scanner (System.in);
String input = scanner.nextLine();

or

char inputchar = scanner.nextLine().charAt(0);

to output to the user use System.out.println()

System.out.println (output);
System.out.print(output);

use a while loop to continuously go back to the start.

while (true)
{
    // insert code here
}

I know i've done quite a bit of the work for you here but you will still need to figure out what to do with what I have given you.

best of luck

commented: Very clear, very helpful +14

Hello alastair
That was a very clear and helpful post, but it did spoon-feed the OP a lot of code. There's always a danger that someone will copy/paste those blocks without understanding how they work, and thus learn nothing. If you use pseudo-code to illustrate the logic then the OP has to write their own code, and learn in the process. So next time please do exactly what you just did, except use more pseudo code and less finished Java. Thank you.

Well iv'e got this so far:

  import java.util.Scanner;
    import java.util.Random;
    import java.io.*;

    public class Hangman {

        private Scanner in = new Scanner(System.in);
        private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
                                      new boardPiece(1),new boardPiece(2),new boardPiece(0)};
        private String puzzle; 
        private String puzzleWord;
        private int puzzleIndex;
        private Random generator = new Random(System.currentTimeMillis());
        private boolean win;
        private boolean over;
        private String correct = "";
        //private String guesses = "";
        private char guesses[] = new char[26];
        private int guessed;
        private int misses;
        private String puzzles[] = new String[5];

        public static void main(String [] args){

            String letter;
            String again = "y";

            Hangman game = new Hangman();

            try{
                BufferedReader in = 
                    new BufferedReader(new FileReader("words.txt"));

                int count = 0;
                while (in.ready()) { //while there is another line in the input file
                      game.puzzles[1] = in.readLine(); //get line of data
                      count++; //Increment CWID counter
                    }
                in.close(); 
                }
                catch(IOException e){
                    System.out.println("Error");
                }

            /*for(int x=0;x<game.puzzles.length;x++)
                System.out.println("PUZZLE " + x + ": " + game.puzzles[x]);*/


            System.out.println("Welcome to HangMan! Good Luck!");

            while(again.charAt(0) == 'y'){
                game.init();

                while(!game.over){
                    game.printBoard();
                    //System.out.println("Guessed: " + game.guesses);
                    game.printGuesses();
                    System.out.println("Word: " + game.puzzle);
                    System.out.println("Guess a letter: ");
                    letter = game.in.next();

                    //game.guesses = game.guesses + " " + letter.charAt(0);
                    game.guesses[game.guessed] = letter.charAt(0);
                    game.guessed++;
                    game.sort();

                    if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
                        game.correct = game.correct + letter.charAt(0);
                        game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
                        if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
                            game.win = true;
                            game.over = true;
                        }
                    }
                    else
                        game.miss();
                }
                game.printBoard();
                System.out.println("Solution: " + game.puzzleWord);
                if(game.win)
                    System.out.println("Congratulations! You've won!");
                else
                    System.out.println("Ahahahaha, you failed!");

                System.out.println();
                System.out.println("Another round? (y/n)");
                again = game.in.next();
            }
            System.out.println("Goodbye!");
        }

        void init(){

            win = false;
            over = false;

            board[0].piece = "    ______ ";
            board[1].piece = "    |    | ";
            board[2].piece = "         | ";
            board[3].piece = "         | ";
            board[4].piece = "         | ";
            board[5].piece = "  _______| ";

            puzzleIndex = generator.nextInt(puzzles.length);
            puzzleWord = puzzles[puzzleIndex];
            puzzle = puzzleWord.replaceAll("[A-Z-a-z]","*");
            correct = "";
            //guesses = "";
            for(int x=0;x<26;x++)
                guesses[x] = '~';
            guessed = 0;
            misses = 0;
        }

        void printBoard(){
            for(int x =0;x<6;x++)
                System.out.println(board[x].piece);
        }

        void miss(){
            misses++;
            if(misses == 1)
                board[2].piece = "    0    | ";
            else if(misses == 2)
                board[2].piece = "   \\0    | ";
            else if(misses == 3)
                board[2].piece = "   \\0/   | ";
            else if(misses == 4)
                board[3].piece = "    |    | ";
            else if(misses == 5)
                board[4].piece = "   /     | ";
            else if(misses == 6){
                board[4].piece = "   / \\   | ";
                over = true;
            }
        }

        void printGuesses(){
            System.out.print("Guesses: ");
            for(int x=0;x<26;x++){
                if(guesses[x] != '~')
                    System.out.print(guesses[x] + " ");
            }
            System.out.println();
        }

        void sort(){
            boolean doMore = true;
            while (doMore) {
                doMore = false;  // assume this is last pass over array
                for (int i=0; i<guesses.length-1; i++) {
                    if (guesses[i] > guesses[i+1]) {
                        char temp = guesses[i];  
                        guesses[i] = guesses[i+1];  
                        guesses[i+1] = temp;
                        doMore = true;  // after an exchange, must look again 
                    }
                }
            }
        }

        class boardPiece{
            public String piece;
            public int total;
            public int used;

            boardPiece(int x){
                used = 0;
                total = x;
            }
        }   
    }

I just can't find out how to:

  • Take the words from my "words.txt" file (only uses the words "pong").
  • Get it to record scores into my "scores.txt" file (and prompt the user to enter their name at the end for the score submission).
  • Tally up a score.
  • Make the game loop.

Any ideas?

Almost finished :)

Heres the code so far:

import java.util.Scanner;
import java.util.Random;
import java.io.*;

public class Hangman {

    private Scanner in = new Scanner(System.in);
    private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
                                  new boardPiece(1),new boardPiece(2),new boardPiece(0)};
    private String puzzle; 
    private String puzzleWord;
    private int puzzleIndex;
    private Random generator = new Random(System.currentTimeMillis());
    private boolean win;
    private boolean over;
    private String correct = "Nice!";
    //private String guesses = "";
    private char guesses[] = new char[26];
    private int guessed;
    private int misses;
    private String puzzles[] = new String[98];

    public static void main(String [] args){

        String letter;
        String again = "y";

        Hangman game = new Hangman();

        try{
            BufferedReader in = 
                new BufferedReader(new FileReader("words.txt"));

            int count = 0;
         String theNextLine;
            while ((theNextLine = in.readLine()) != null ) { //while there is another line in the input file
                  game.puzzles[count] = theNextLine; //get line of data
                  count++; //Increment CWID counter
                }
            in.close(); 
            }
            catch(IOException e){
                System.out.println("Error");
            }

        /*for(int x=0;x<game.puzzles.length;x++)
            System.out.println("PUZZLE " + x + ": " + game.puzzles[x]);*/


        System.out.println("Welcome to HangMan! Good Luck!");

        while(again.charAt(0) == 'y'){
            game.init();
            while(!game.over){
                game.printBoard();
                //System.out.println("Guessed: " + game.guesses);
                game.printGuesses();
                System.out.println("Word: " + game.puzzle);
                System.out.println("Guess a letter: ");
                letter = game.in.next();

                //game.guesses = game.guesses + " " + letter.charAt(0);
                game.guesses[game.guessed] = letter.charAt(0);
                game.guessed++;
                game.sort();

                if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
                    game.correct = game.correct + letter.charAt(0);
                    game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
                    if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
                        game.win = true;
                        game.over = true;
                    }
                }
                else
                    game.miss();
            }
            game.printBoard();
            System.out.println("Solution: " + game.puzzleWord);
            if(game.win)
                System.out.println("Congratulations! You've won!");
            else
                System.out.println("Ahahahaha, you failed!");

            System.out.println();
            System.out.println("Another round? (y/n)");
            again = game.in.next();
        }
        System.out.println("See ya!");
    }

    void init(){

        win = false;
        over = false;

        board[0].piece = "    ______ ";
        board[1].piece = "    |    | ";
        board[2].piece = "         | ";
        board[3].piece = "         | ";
        board[4].piece = "         | ";
        board[5].piece = "  _______| ";

        puzzleIndex = generator.nextInt(puzzles.length);
        puzzleWord = puzzles[puzzleIndex];
        puzzle = puzzleWord.replaceAll("[A-Z,a-z]","*");
        correct = "";
        //guesses = "";
        for(int x=0;x<26;x++)
            guesses[x] = '~';
        guessed = 0;
        misses = 0;
    }

    void printBoard(){
        for(int x =0;x<5;x++)
            System.out.println(board[x].piece);
    }

    void miss(){
        misses++;
        if(misses == 1)
            board[2].piece = "    0    | ";
        else if(misses == 2)
            board[2].piece = "   \\0    | ";
        else if(misses == 3)
            board[2].piece = "   \\0/   | ";
        else if(misses == 4)
            board[3].piece = "    |    | ";
        else if(misses == 5){
            board[4].piece = "   / \\   | ";
            over = true;
        }
    }

    void printGuesses(){
        System.out.print("Guesses: ");
        for(int x=0;x<26;x++){
            if(guesses[x] != '~')
                System.out.print(guesses[x] + " ");
        }
        System.out.println();
    }

    void sort(){
        boolean doMore = true;
        while (doMore) {
            doMore = false;  // assume this is last pass over array
            for (int i=0; i<guesses.length-1; i++) {
                if (guesses[i] > guesses[i+1]) {
                    char temp = guesses[i];  
                    guesses[i] = guesses[i+1];  
                    guesses[i+1] = temp;
                    doMore = true;  // after an exchange, must look again 
                }
            }
        }
    }

    class boardPiece{
        public String piece;
        public int total;
        public int used;

        boardPiece(int x){
            used = 0;
            total = x;
        }
    }   
}

The only thing that i haven't been able to achieve is anything to do with recording & adding up the players scores;

What i need to get the code to do, is add up a total score of 5 per word ( -1 per incorrectly chosen letter).
Once the player is done (they exit the code), the code is suppose to prompt the user to enter their name, and it will automatically record that name & their score into a text file called "scores.txt".

Does anyone know a link or 2 to some tutorials or a few coding examples on how it's done?

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.