-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathahorcado.java
More file actions
269 lines (245 loc) · 12.5 KB
/
ahorcado.java
File metadata and controls
269 lines (245 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import java.util.*;
import java.text.Normalizer;
import java.io.*;
public class ahorcado {
public static void main(String[] args) {
// Provider: primero intenta cargar words.txt; si falla, usa la lista por defecto
WordProvider baseProvider = FileWordProvider.tryLoad("words.txt").orElse(new ListWordProvider());
ConsoleUI ui = new ConsoleUI(baseProvider);
ui.run();
}
// ======== Dificultades ========
enum Difficulty {
FACIL(8, 4, 7),
MEDIO(6, 6, 10),
DIFICIL(5, 8, 100);
final int attempts; final int minLen; final int maxLen;
Difficulty(int attempts, int minLen, int maxLen){
this.attempts = attempts; this.minLen = minLen; this.maxLen = maxLen;
}
}
// ======== Provider de palabras ========
interface WordProvider { String nextWord(); }
// Lista por defecto (sin tildes; MAYÚSCULAS)
static class ListWordProvider implements WordProvider {
private final List<String> words = Arrays.asList(
"PROGRAMACION","JAVA","ALGORITMO","VARIABLE","FUNCION",
"COMPUTADORA","SEGURIDAD","DATOS","SERVIDOR","CLIENTE",
"FIREWALL","COMPILADOR","INTERFAZ","ABSTRACCION","POLIMORFISMO",
"MICROSERVICIOS","REPOSITORIO","CONTENEDOR","DEPURACION","RECURSIVO"
);
private final Random rnd = new Random();
public String nextWord(){ return words.get(rnd.nextInt(words.size())); }
}
// Lee archivo words.txt (UTF-8). Una palabra por línea. Ignora vacías y espacios.
static class FileWordProvider implements WordProvider {
private final List<String> words;
private final Random rnd = new Random();
private FileWordProvider(List<String> words){ this.words = words; }
public static Optional<WordProvider> tryLoad(String path){
File f = new File(path);
if (!f.exists() || !f.isFile()) return Optional.empty();
List<String> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"))){
String line;
while ((line = br.readLine()) != null){
String w = normalizeUpper(line.trim());
if (!w.isBlank() && w.chars().allMatch(Character::isLetter)) list.add(w);
}
} catch (Exception e){
return Optional.empty();
}
if (list.isEmpty()) return Optional.empty();
return Optional.of(new FileWordProvider(list));
}
@Override public String nextWord(){ return words.get(rnd.nextInt(words.size())); }
}
// Envuelve otro provider y busca palabras en un rango de longitud; si no encuentra, cae al base
static class FilterWordProvider implements WordProvider {
private final WordProvider base; private final int minLen; private final int maxLen;
FilterWordProvider(WordProvider base, int minLen, int maxLen){ this.base = base; this.minLen = minLen; this.maxLen = maxLen; }
@Override public String nextWord(){
// Intentamos varias veces para hallar una palabra en rango
for (int i=0; i<200; i++){
String w = base.nextWord();
int len = w.length();
if (len >= minLen && len <= maxLen) return w;
}
// Fallback
return base.nextWord();
}
}
// ======== Modelo del juego (estado + reglas) ========
static class HangmanGame {
private final String secret; // palabra en MAYÚSCULAS (sin tildes)
private final char[] progress; // progreso: '_' o letra
private final Set<Character> used; // letras ya intentadas
private final int maxAttempts;
private int attemptsLeft;
private boolean won = false;
private final Random rnd = new Random();
public HangmanGame(String rawSecret, int maxAttempts) {
this.secret = normalizeUpper(rawSecret);
this.maxAttempts = maxAttempts;
this.attemptsLeft = maxAttempts;
this.progress = new char[secret.length()];
Arrays.fill(this.progress, '_');
this.used = new LinkedHashSet<>();
}
public int getAttemptsLeft() { return attemptsLeft; }
public int getMaxAttempts() { return maxAttempts; }
public boolean isWon() { return won; }
public boolean isLost() { return attemptsLeft <= 0 && !won; }
public String getSecret() { return secret; }
public String getProgressText() {
StringBuilder sb = new StringBuilder();
for (char c : progress) sb.append(c).append(' ');
return sb.toString().trim();
}
public String getUsedLetters() {
StringBuilder sb = new StringBuilder();
for (char c : used) sb.append(c).append(' ');
return sb.toString().trim();
}
/** Adivinar letra; devuelve mensaje para la UI */
public String guessLetter(char ch) {
if (won || isLost()) return "La partida ya terminó.";
char letter = Character.toUpperCase(ch);
if (!Character.isLetter(letter)) return "Ingresa una letra válida.";
if (used.contains(letter)) return "Ya probaste la letra '" + letter + "'.";
used.add(letter);
boolean hit = false;
for (int i = 0; i < secret.length(); i++) {
if (secret.charAt(i) == letter) { progress[i] = letter; hit = true; }
}
if (!hit) {
attemptsLeft--;
if (attemptsLeft <= 0) return "Fallaste. No quedan intentos.";
return "No está la '" + letter + "'. Intentos restantes: " + attemptsLeft + ".";
} else {
if (isFullyRevealed()) { won = true; return "¡Adivinaste la palabra!"; }
return "¡Bien! La '" + letter + "' está.";
}
}
/** Adivinar palabra completa; penaliza 1 intento si falla. */
public String guessWord(String rawGuess) {
if (won || isLost()) return "La partida ya terminó.";
String guess = normalizeUpper(rawGuess);
if (guess.isBlank()) return "Ingresa una palabra válida.";
if (guess.equals(secret)) { won = true; revealAll(); return "¡Correcto! Adivinaste la palabra completa."; }
attemptsLeft--;
if (attemptsLeft <= 0) return "Palabra incorrecta. No quedan intentos.";
return "No es '" + guess + "'. Intentos restantes: " + attemptsLeft + ".";
}
/** Usa una pista: revela una letra aleatoria no descubierta y descuenta 1 intento. */
public String useHint() {
if (won || isLost()) return "La partida ya terminó.";
List<Integer> hidden = new ArrayList<>();
for (int i = 0; i < progress.length; i++) if (progress[i] == '_') hidden.add(i);
if (hidden.isEmpty()) return "No hay nada que revelar.";
// Elige una posición oculta al azar y la revela
int idx = hidden.get(rnd.nextInt(hidden.size()));
char letter = secret.charAt(idx);
for (int i = 0; i < secret.length(); i++) if (secret.charAt(i) == letter) progress[i] = letter;
used.add(letter);
attemptsLeft--;
if (isFullyRevealed()) { won = true; return "Pista usada: se reveló '" + letter + "'. ¡Ganaste!"; }
if (attemptsLeft <= 0) return "Pista usada: se reveló '" + letter + "'. No quedan intentos.";
return "Pista usada: se reveló '" + letter + "'. Intentos restantes: " + attemptsLeft + ".";
}
private boolean isFullyRevealed() { for (char c : progress) if (c == '_') return false; return true; }
private void revealAll() { for (int i = 0; i < secret.length(); i++) progress[i] = secret.charAt(i); }
}
// ======== Vista + Control (consola) ========
static class ConsoleUI {
private final Scanner sc = new Scanner(System.in);
private final WordProvider baseProvider;
private WordProvider currentProvider; // puede ser filtrado por dificultad
private HangmanGame game;
private Difficulty difficulty;
// 7 etapas de la horca (se clampa según intentos usados)
private static final String[] GALLOWS = new String[]{
"\n +---+\n | |\n |\n |\n |\n |\n=========\n",
"\n +---+\n | |\n O |\n |\n |\n |\n=========\n",
"\n +---+\n | |\n O |\n | |\n |\n |\n=========\n",
"\n +---+\n | |\n O |\n /| |\n |\n |\n=========\n",
"\n +---+\n | |\n O |\n /|\\ |\n |\n |\n=========\n",
"\n +---+\n | |\n O |\n /|\\ |\n / |\n |\n=========\n",
"\n +---+\n | |\n O |\n /|\\ |\n / \\ |\n |\n=========\n"
};
public ConsoleUI(WordProvider provider){ this.baseProvider = provider; this.currentProvider = provider; }
public void run(){
println("=== AHORCADO (Java) ===");
selectDifficulty();
boolean again;
do {
startNewGame();
loop();
again = askYesNo("¿Jugar otra vez? (s/n): ");
if (again && askYesNo("¿Cambiar dificultad? (s/n): ")) selectDifficulty();
} while (again);
println("¡Gracias por jugar!");
}
private void selectDifficulty(){
println("Selecciona dificultad:");
println("1) Fácil (8 intentos, palabras 4-7)\n2) Medio (6 intentos, palabras 6-10)\n3) Difícil(5 intentos, palabras 8+)");
while (true){
String s = ask("Opción [1-3]: ");
switch (s){
case "1": difficulty = Difficulty.FACIL; break;
case "2": difficulty = Difficulty.MEDIO; break;
case "3": difficulty = Difficulty.DIFICIL; break;
default: println("Elige 1, 2 o 3."); continue;
}
currentProvider = new FilterWordProvider(baseProvider, difficulty.minLen, difficulty.maxLen);
break;
}
}
private void startNewGame(){
String secret = currentProvider.nextWord();
game = new HangmanGame(secret, difficulty.attempts);
}
private void loop(){
while (!game.isWon() && !game.isLost()){
draw();
String input = ask("Letra/palabra (?=pista, :salir): ");
if (input.equalsIgnoreCase(":salir")) { println("Saliendo de la partida actual..."); break; }
if (input.equals("?")) { println(game.useHint()); continue; }
if (input.length() == 1) println(game.guessLetter(input.charAt(0)));
else println(game.guessWord(input));
}
draw();
if (game.isWon()) println("✅ ¡GANASTE! La palabra era: " + game.getSecret());
else if (game.isLost()) println("❌ PERDISTE. La palabra era: " + game.getSecret());
}
private void draw(){
int stage = game.getMaxAttempts() - game.getAttemptsLeft();
stage = Math.max(0, Math.min(stage, GALLOWS.length - 1));
println(GALLOWS[stage]);
println("Palabra: " + game.getProgressText());
println("Usadas: " + (game.getUsedLetters().isEmpty()? "(ninguna)" : game.getUsedLetters()));
println("Intentos: " + game.getAttemptsLeft() + "/" + game.getMaxAttempts());
println("");
}
private String ask(String msg){ System.out.print(msg); return sc.nextLine().trim(); }
private boolean askYesNo(String msg){
while (true){
String a = ask(msg);
if (a.equalsIgnoreCase("s")) return true;
if (a.equalsIgnoreCase("n")) return false;
println("Responde 's' o 'n'.");
}
}
private void println(String s){ System.out.println(s); }
}
// ======== Utilidad de normalización ========
static String normalizeUpper(String s){
if (s == null) return "";
String u = s.toUpperCase(Locale.ROOT);
String norm = Normalizer.normalize(u, Normalizer.Form.NFD);
// Quitamos diacríticos; Ñ se mantiene como Ñ.
norm = norm.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
norm = norm.replace('Á','A').replace('É','E').replace('Í','I').replace('Ó','O').replace('Ú','U');
return norm;
}
}