Wie könnte man diesen Code kürzer machen ?

asasasasas

Mitglied
Hangman
Java:
public class hangiman {
    public static void main(String[] args) {
        System.out.println("Starting game");

        String notUsed = "abcdefghijklmnopqrstuvwxyz";

        String[] words = new String[]{"computer", "mouse", "screen", "display", "language"};

        String randomWord = words[(int) (Math.random() * words.length)];

        System.out.println("The word has " + randomWord.length() + " letters.");

        char[] letters = new char[randomWord.length()];

        Arrays.fill(letters, '.');
        int lives = 3;

        Scanner scanner = new Scanner(System.in);

        while (lives > 0) {
            System.out.print("Lives: ");

            for (int i = 0; i < lives; i++) {
                System.out.print("♥");
            }
            System.out.println();

            System.out.println("Input: ");

            String input = scanner.nextLine();

            char letter = input.charAt(0);


            boolean isGuessCorrect = false;
            for (int i = 0; i < randomWord.length(); i++) {
                char l = randomWord.charAt(i);

                if (l == letter) {
                    letters[i] = l;
                    isGuessCorrect = true;
                }
            }
            if (!isGuessCorrect) {
                lives = lives - 1;
            }
            boolean isGameFinished = true;

            System.out.print("Word: ");


            for (char c : letters) {
                if (c == '.') {
                    isGameFinished = false;
                }
                System.out.print(c);
            }
            System.out.println();

            notUsed = notUsed.replace(letter, '.');
            System.out.println("Not used " + notUsed);

            System.out.println("----------------------------------");

            if (isGameFinished) {
                System.out.println("You won!");
                break;
            }
        }
        if (lives == 0) {
            System.out.println("You lost! The word was: " + randomWord);
        }
        System.out.println("Exiting game");
    }
}
 
Sorry, bin nicht gut im Kreativ sein, aber so wäre es sauberer:

Java:
import java.util.Random;
import java.util.Scanner;

public class Hangiman {
    private static final String[] words = {"eins", "zwei", "drei"};
    private final Random ran = new Random();
    private String toGuess;
    private StringBuilder toGuessHidden;
    private int lives;

    public void newGame() {
        toGuess = words[ran.nextInt(words.length)];
        toGuessHidden = new StringBuilder(repeatChar('.', toGuess.length()));
        lives = 3;
        boolean won = false;
        while (lives > 0 && !toGuess.contentEquals(toGuessHidden)) {
            won = guess();
        }
        if (won) {
            System.out.println("You won. :)");
        } else {
            System.out.println("You lost. :(");
        }
        System.out.println("The word was: " + toGuess);
        System.out.println("Lives: " + repeatChar('♥', lives));
    }

    public boolean guess() {
        if (lives > 0) {
            System.out.println("Live: " + repeatChar('♥', lives));
            System.out.println("Word: " + toGuessHidden);
            System.out.println("Please insert the char you want:");
            char ch = new Scanner(System.in).nextLine().charAt(0);
            int c = 0;
            for (int i = 0; i < toGuess.length(); i++) {
                if (toGuessHidden.charAt(i) == '.' && toGuess.charAt(i) == ch) {
                    c++;
                    toGuessHidden.setCharAt(i, ch);
                }
            }
            if (c == 0) {
                System.out.println("Sorry, You haven't guessed the character.");
                lives--;
                return false;
            } else {
                System.out.println("Wow, You have guessed the character " + c + " times. =)");
                return true;
            }
        } else {
            System.out.println("I'm sorry, the game is over.");
            return false;
        }
    }

    public String repeatChar(char ch, int times) {
        return new String(new char[times]).replace('\0', ch);
    }

    public static void main(String[] args) {
        Hangiman hangiman = new Hangiman();
        hangiman.newGame();
    }
}

Und weniger Zeilen. =)
 
Diese Strukturierung geht schon in die richtige Richtung und die kann man noch deutlich weiter treiben und weiter umstrukturieren.

So eine if else Struktur, wie in guess() gefällt mir in der Regel nicht. Das if kann man umdrehen und als reine Abbruchbedingung führen, also ein:
Java:
if (lives == 0) {
    System.out.println("I'm sorry, the game is over.");
    return false;
}

Das reduziert die Einrücktiefe und ist besser lesbar (in meinen Augen), weil das Pattern immer gleich ist mit
1. Abbruchbedingungen
2. eigentliches doing.

Die Lesbarkeit wird auch oft besser, wenn Bedingungen formuliert werden. if (!hasLivesLeft()) oder so.

Dann arbeite ich gerne noch mehr mit Instanzvariablen. Denkbar ist also ein state oder gameState vom Typ GameState das ein Enum ist mit ONGOING, WON, LOST oder so. Aber das braucht man nicht zwingend. Aber man kann so Prüfungen deutlich besser über eine Methode machen. Die while Schleife wäre dann einfach etwas wie:
Java:
while (isGameOngoing()) {
    guess();
}

Wobei guess nicht selbst rät weshalb meiner Meinung nach ein besserer Name her müsste.
 
Sorry, bin nicht gut im Kreativ sein, aber so wäre es sauberer:

Java:
import java.util.Random;
import java.util.Scanner;

public class Hangiman {
    private static final String[] words = {"eins", "zwei", "drei"};
    private final Random ran = new Random();
    private String toGuess;
    private StringBuilder toGuessHidden;
    private int lives;

    public void newGame() {
        toGuess = words[ran.nextInt(words.length)];
        toGuessHidden = new StringBuilder(repeatChar('.', toGuess.length()));
        lives = 3;
        boolean won = false;
        while (lives > 0 && !toGuess.contentEquals(toGuessHidden)) {
            won = guess();
        }
        if (won) {
            System.out.println("You won. :)");
        } else {
            System.out.println("You lost. :(");
        }
        System.out.println("The word was: " + toGuess);
        System.out.println("Lives: " + repeatChar('♥', lives));
    }

    public boolean guess() {
        if (lives > 0) {
            System.out.println("Live: " + repeatChar('♥', lives));
            System.out.println("Word: " + toGuessHidden);
            System.out.println("Please insert the char you want:");
            char ch = new Scanner(System.in).nextLine().charAt(0);
            int c = 0;
            for (int i = 0; i < toGuess.length(); i++) {
                if (toGuessHidden.charAt(i) == '.' && toGuess.charAt(i) == ch) {
                    c++;
                    toGuessHidden.setCharAt(i, ch);
                }
            }
            if (c == 0) {
                System.out.println("Sorry, You haven't guessed the character.");
                lives--;
                return false;
            } else {
                System.out.println("Wow, You have guessed the character " + c + " times. =)");
                return true;
            }
        } else {
            System.out.println("I'm sorry, the game is over.");
            return false;
        }
    }

    public String repeatChar(char ch, int times) {
        return new String(new char[times]).replace('\0', ch);
    }

    public static void main(String[] args) {
        Hangiman hangiman = new Hangiman();
        hangiman.newGame();
    }
}

Und weniger Zeilen. =)

Hier könnte man ein short if verwenden
Java:
        if (won) {
            System.out.println("You won. :)");
        } else {
            System.out.println("You lost. :(");
        }

Man könnte die Strings auch auslagern und hier das else weglassen.
Code:
            if (c == 0) {

                System.out.println("Sorry, You haven't guessed the character.");

                lives--;

                return false;

            } else {

                System.out.println("Wow, You have guessed the character " + c + " times. =)");

                return true;

            }

Könnte man zusammen nehmen:
Code:
       System.out.println("The word was: " + toGuess);
        System.out.println("Lives: " + repeatChar('♥', lives));

Der Code sieht sicher einiges Lesbarer aus und strukturierter, als der ursprüngliche aus.
 
Meinst du das so?

Java:
import java.util.Random;
import java.util.Scanner;

public class Hangiman {
    private static final String[] words = {"eins", "zwei", "drei"};
    private final Random ran = new Random();
    private String toGuess;
    private StringBuilder toGuessHidden;
    private int lives;

    public void newGame() {
        toGuess = words[ran.nextInt(words.length)];
        toGuessHidden = new StringBuilder(repeatChar('.', toGuess.length()));
        lives = 3;
        while (lives > 0 && !(guess() && toGuess.contentEquals(toGuessHidden)))
            ;
        System.out.println(lives > 0 ? "You won. :)" : "You lost. :(");
        System.out.println("The word was: " + toGuess);
        calculateLives();
    }

    private boolean guess() {
        calculateLives();
        System.out.println("Word: " + toGuessHidden);
        System.out.println("Please insert the char you want:");
        char ch = new Scanner(System.in).nextLine().charAt(0);
        int c = 0;
        for (int i = 0; i < toGuess.length(); i++) {
            if (toGuessHidden.charAt(i) == '.' && toGuess.charAt(i) == ch) {
                c++;
                toGuessHidden.setCharAt(i, ch);
            }
        }
        if (c == 0) {
            System.out.println("Sorry, You haven't guessed the character.");
            lives--;
            return false;
        } else {
            System.out.println("Wow, You have guessed the character " + c + " times. =)");
            return true;
        }
    }

    private void calculateLives() {
        System.out.println("Remaining lives: " + repeatChar('♥', lives));
    }

    public String repeatChar(char ch, int times) {
        return new String(new char[times]).replace('\0', ch);
    }

    public static void main(String[] args) {
        Hangiman hangiman = new Hangiman();
        hangiman.newGame();
        hangiman.newGame();
        hangiman.newGame();
    }
}

Ich möchte zu bedenken geben: Die while-Bedingung ist nicht in einer kanonischen Normalform (schwerer zu lesen) und der Scanner wird nicht wiederverwendet (fehleranfälliger).
 
Meinst du das so?

Java:
import java.util.Random;
import java.util.Scanner;

public class Hangiman {
    private static final String[] words = {"eins", "zwei", "drei"};
    private final Random ran = new Random();
    private String toGuess;
    private StringBuilder toGuessHidden;
    private int lives;

    public void newGame() {
        toGuess = words[ran.nextInt(words.length)];
        toGuessHidden = new StringBuilder(repeatChar('.', toGuess.length()));
        lives = 3;
        while (lives > 0 && !(guess() && toGuess.contentEquals(toGuessHidden)))
            ;
        System.out.println(lives > 0 ? "You won. :)" : "You lost. :(");
        System.out.println("The word was: " + toGuess);
        calculateLives();
    }

    private boolean guess() {
        calculateLives();
        System.out.println("Word: " + toGuessHidden);
        System.out.println("Please insert the char you want:");
        char ch = new Scanner(System.in).nextLine().charAt(0);
        int c = 0;
        for (int i = 0; i < toGuess.length(); i++) {
            if (toGuessHidden.charAt(i) == '.' && toGuess.charAt(i) == ch) {
                c++;
                toGuessHidden.setCharAt(i, ch);
            }
        }
        if (c == 0) {
            System.out.println("Sorry, You haven't guessed the character.");
            lives--;
            return false;
        } else {
            System.out.println("Wow, You have guessed the character " + c + " times. =)");
            return true;
        }
    }

    private void calculateLives() {
        System.out.println("Remaining lives: " + repeatChar('♥', lives));
    }

    public String repeatChar(char ch, int times) {
        return new String(new char[times]).replace('\0', ch);
    }

    public static void main(String[] args) {
        Hangiman hangiman = new Hangiman();
        hangiman.newGame();
        hangiman.newGame();
        hangiman.newGame();
    }
}

Ich möchte zu bedenken geben: Die while-Bedingung ist nicht in einer kanonischen Normalform (schwerer zu lesen) und der Scanner wird nicht wiederverwendet (fehleranfälliger).
Das mit dem System.out.println sieht besser aus.
Warum machst du char ch = new Scanner(System.in).nextLine().charAt(0);?
 

Neue Themen


Zurück
Oben