vendredi 21 septembre 2018

Java Game attempts in Loop with if statement

I'm developing a Hangmen game, and I want to have left attempts on every turn, I'm using While and in the While have added if statement if the player has guessed the letter to NOT decrease the attempts left and if fails to guess the letter to make every attempt decreased.

Everything is working fine except the first statement when guessing the letter, no matter of the guess the attempts also were decreased by -1. When you guess the letter it should keep the attempts.

I think the problem is around here but tried a lot of combinations.

    if (convertedUserInput.equals(chosenWord)) {
        victory = true;
        break;


package hangman;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class Hangman {

    public static void main(String[] args) {

        showOptions();

    }

    // The csv file with all words
    static String fileName = "../JavaProjectHangman/src/MOCK_DATA.csv";

    // Different ArrayLists with words to pick form each category
    static ArrayList<String> footballWords = new ArrayList<String>();
    static ArrayList<String> booksWords = new ArrayList<String>();
    static ArrayList<String> programmingWords = new ArrayList<String>();

    static String gameWord; // word to be guessed

    static Random rnd = new Random();

    static char hidingSymbol = '_'; // Displayed when the letter/or phrase of
                                    // word is not guessed.

    static char[] currentGuessedWord; // Contains chars for user's input

    /*
     * Reads through csv file with all words and based on different categories
     * adds them to different ArrayList(which stores words only from one
     * category). Depending on user's choice returns one random word from the
     * listed categories.
     */
    public static String getWord(String userInput) throws IOException {

        Reader reader = Files.newBufferedReader(Paths.get(fileName));
        CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);

        for (CSVRecord csvRecord : csvParser) {

            // Accessing Values by Column Index
            String football = csvRecord.get(0);
            String books = csvRecord.get(1);
            String programming = csvRecord.get(2);

            // check what is the user input
            switch (userInput) {
            case "football teams":
                if (football != null && !football.isEmpty()) {

                    footballWords.add(football.toLowerCase());
                }

                int indexFootball = rnd.nextInt(footballWords.size());
                gameWord = footballWords.get(indexFootball);
                break;

            case "books":
                if (books != null && !books.isEmpty()) {
                    booksWords.add(books.toLowerCase());
                }
                int indexBooks = rnd.nextInt(booksWords.size());
                gameWord = booksWords.get(indexBooks);
                break;

            case "programming principles":
                if (programming != null && !programming.isEmpty()) {
                    programmingWords.add(programming.toLowerCase());
                }

                int indexProgramming = rnd.nextInt(programmingWords.size());
                gameWord = programmingWords.get(indexProgramming);
            default:
                break;

            }

        }

        csvParser.close();

        return gameWord;
    }

    // check if currentGuessdWord is completely guessed
    static boolean isGuessed() {

        boolean isGuessed = false;

        for (int i = 0; i <= currentGuessedWord.length - 1; i++) {

            if (hidingSymbol == currentGuessedWord[i]) {

                isGuessed = false;
                break;
            } else {
                isGuessed = true;
            }

        }

        return isGuessed;

    }

    // check user input
    static int checkEnteredWord(String inputToCheck) {
        int trials = 0; // When the current char is not inside the word to be
                        // guessed
                        // the value of trials will be raised.

        boolean currentCharIsInWord = false;

        // check if the input is one symbol
        if (inputToCheck.length() == 1) {

            // loop through the word and check if the symbol is in the gameWord
            for (int i = 0; i < currentGuessedWord.length; i++) {

                if (inputToCheck.charAt(0) == gameWord.charAt(i)) {

                    currentCharIsInWord = true;
                    currentGuessedWord[i] = inputToCheck.charAt(0);

                } else if (inputToCheck.charAt(0) != gameWord.charAt(i)) {
                    currentCharIsInWord = false;
                }

            }
            if (currentCharIsInWord == false) {
                trials += 1;
            }
        }

        // check if the input is more than one symbol
        else if (inputToCheck.length() > 1) {

            for (int i = 0; i < inputToCheck.length(); i++) {

                for (int j = 0; j < currentGuessedWord.length; j++) {

                    if (inputToCheck.charAt(i) == gameWord.charAt(j)) {

                        currentCharIsInWord = true;
                        currentGuessedWord[j] = inputToCheck.charAt(i);
                    }

                    else if (inputToCheck.charAt(i) != gameWord.charAt(j)) {
                        currentCharIsInWord = false;
                    }
                }
            }

            if (currentCharIsInWord == false) {
                trials += 1;
            }
        }

        return trials;
    }

    public static void play(String category) throws IOException {

        Scanner scanner = new Scanner(System.in);

        int maxAttempts = 10;
        int currentAttemptsLeft = maxAttempts;

        String chosenWord = getWord(category);
        currentGuessedWord = new char[chosenWord.length()];

        for (int i = 0; i < chosenWord.length(); i++) {

            currentGuessedWord[i] = hidingSymbol;
        }

        System.out.println();

        boolean victory = false;


        while (currentAttemptsLeft>0) {

            if (isGuessed() == true) // if the word is guessed, there is victory
            {
                victory = true;
                break;
            }

            System.out.println("Attempts left " + currentAttemptsLeft);

            // print the currently guessed letters
            System.out.print("Current word/phrase: ");

            for (int y = 0; y < currentGuessedWord.length; y++) {
                System.out.print(currentGuessedWord[y]);
            }
            System.out.println("\n");

            System.out.println(chosenWord); // comment this <==

            System.out.println("");

            System.out.println("Please enter a letter");
            System.out.print(">");
            String userInput = scanner.nextLine();

            String convertedUserInput = userInput.toLowerCase().trim();

            if (convertedUserInput.equals(chosenWord)) {
                victory = true;
                break;
            }

            else {
                currentAttemptsLeft -= checkEnteredWord(convertedUserInput);
            }


        } // while end

        if (victory == true) {
            System.out.println("Congratulations you have revealed the word/phrase: " + chosenWord);

        } else {
            System.out.println("Unfortunately you did not revealed the word/phrase, which was: " + chosenWord);
        }


        scanner.close();

        return;

    }// end play method

    public static void showOptions() {

        System.out.println("Please choose a category:\nFootball teams \nBooks \nProgramming principles");
        Scanner sc = new Scanner(System.in);
        String userChosenCategory = sc.nextLine();
        try {
            play(userChosenCategory.toLowerCase().trim());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            sc.close();
        }

    }
}

Will appreciate if someone helps me.

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire