Skip to content

Commit 2af6f40

Browse files
author
Lavinia - Cristiana Bacaru
committed
Create JuegoAdivinanza.java
1 parent 3f8b1ef commit 2af6f40

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

JuegoAdivinanza.java

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import java.util.Random;
2+
3+
class NumeroOculto {
4+
private int numeroSecreto;
5+
private boolean juegoTerminado;
6+
7+
public NumeroOculto(int numeroSecreto) {
8+
this.numeroSecreto = numeroSecreto;
9+
this.juegoTerminado = false;
10+
}
11+
12+
synchronized public int propuestaNumero(int num) {
13+
if(juegoTerminado) {
14+
return -1;
15+
}
16+
if(num == numeroSecreto) {
17+
juegoTerminado = true;
18+
return 1;
19+
}
20+
return 0;
21+
}
22+
}
23+
24+
class HiloAdivinador implements Runnable {
25+
private NumeroOculto juego;
26+
private int id;
27+
private Random random;
28+
29+
public HiloAdivinador(NumeroOculto juego, int id) {
30+
this.juego = juego;
31+
this.id = id;
32+
this.random = new Random();
33+
}
34+
35+
@Override
36+
public void run() {
37+
while(true) {
38+
int propuesta = random.nextInt(101); // Número entre 0 y 100
39+
int resultado = juego.propuestaNumero(propuesta);
40+
41+
if(resultado == 1) {
42+
System.out.println("¡Hilo " + id + " ha adivinado el número! Era: " + propuesta);
43+
break;
44+
} else if(resultado == -1) {
45+
System.out.println("Hilo " + id + " termina: otro hilo ya adivinó el número");
46+
break;
47+
} else {
48+
System.out.println("Hilo " + id + " propone: " + propuesta + " (incorrecto)");
49+
}
50+
51+
try {
52+
Thread.sleep(100); // Pequeña pausa entre intentos
53+
} catch (InterruptedException e) {
54+
e.printStackTrace();
55+
}
56+
}
57+
}
58+
}
59+
60+
public class JuegoAdivinanza {
61+
public static void main(String[] args) {
62+
Random random = new Random();
63+
int numeroSecreto = random.nextInt(101); // Número entre 0 y 100
64+
System.out.println("Número secreto generado: " + numeroSecreto);
65+
66+
NumeroOculto juego = new NumeroOculto(numeroSecreto);
67+
Thread[] hilos = new Thread[10];
68+
69+
// Crear y lanzar los 10 hilos adivinadores
70+
for(int i = 0; i < 10; i++) {
71+
hilos[i] = new Thread(new HiloAdivinador(juego, i+1));
72+
hilos[i].start();
73+
}
74+
75+
// Esperar a que todos los hilos terminen
76+
for(Thread hilo : hilos) {
77+
try {
78+
hilo.join();
79+
} catch (InterruptedException e) {
80+
e.printStackTrace();
81+
}
82+
}
83+
84+
System.out.println("Juego terminado");
85+
}
86+
}

0 commit comments

Comments
 (0)