forked from menault/TD3_DEV51_Qualite_Algo
76 lines
2.2 KiB
Java
76 lines
2.2 KiB
Java
package back;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.HashSet;
|
|
import java.util.List;
|
|
import java.util.Set;
|
|
|
|
/**
|
|
* Logique principale du jeu du pendu (back).
|
|
* Gère le mot, les lettres trouvées, et les conditions de victoire/défaite.
|
|
*/
|
|
public class Game {
|
|
private final String word;
|
|
private final Set<Character> correct = new HashSet<>();
|
|
private final Set<Character> all = new HashSet<>();
|
|
private final int maxErrors;
|
|
private int errors;
|
|
|
|
public Game(String word, int maxErrors) {
|
|
this.word = word.toLowerCase();
|
|
this.maxErrors = maxErrors;
|
|
}
|
|
|
|
/** Tente une lettre et renvoie le résultat */
|
|
public Result play(char letter) {
|
|
char c = Character.toLowerCase(letter);
|
|
if (all.contains(c)) return Result.ALREADY;
|
|
all.add(c);
|
|
if (word.indexOf(c) >= 0) {
|
|
correct.add(c);
|
|
return Result.HIT;
|
|
} else {
|
|
errors++;
|
|
return Result.MISS;
|
|
}
|
|
}
|
|
|
|
/** Retourne le mot masqué avec les lettres trouvées */
|
|
public String maskedWord() {
|
|
StringBuilder sb = new StringBuilder();
|
|
for (int i = 0; i < word.length(); i++) {
|
|
char c = word.charAt(i);
|
|
if (!Character.isLetter(c)) sb.append(c);
|
|
else if (correct.contains(c)) sb.append(c);
|
|
else sb.append('_');
|
|
if (i < word.length() - 1) sb.append(' ');
|
|
}
|
|
return sb.toString();
|
|
}
|
|
|
|
/** Vérifie si le joueur a gagné */
|
|
public boolean isWin() {
|
|
for (int i = 0; i < word.length(); i++) {
|
|
char c = word.charAt(i);
|
|
if (Character.isLetter(c) && !correct.contains(c)) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/** Vérifie si le joueur a perdu */
|
|
public boolean isLose() {
|
|
return errors >= maxErrors;
|
|
}
|
|
|
|
/** Renvoie le nombre d'erreurs actuelles */
|
|
public int getErrors() { return errors; }
|
|
|
|
/** Liste les lettres déjà essayées */
|
|
public List<String> triedLetters() {
|
|
List<Character> sorted = new ArrayList<>(all);
|
|
sorted.sort(Character::compareTo);
|
|
List<String> out = new ArrayList<>();
|
|
for (Character ch : sorted) out.add(String.valueOf(ch));
|
|
return out;
|
|
}
|
|
} |