Skip to content

Commit

Permalink
publi
Browse files Browse the repository at this point in the history
  • Loading branch information
JaimeArboleda committed Jan 18, 2023
1 parent 1c17e1e commit 21e0d30
Show file tree
Hide file tree
Showing 8 changed files with 33,140 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .metals/metals.lock.db
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#FileLock
#Wed Jan 18 14:50:05 CET 2023
server=localhost\:59949
hostName=localhost
method=file
id=185c524ddc815a09720402f4a408bc58934a865f8e9
32,750 changes: 32,750 additions & 0 deletions .metals/metals.log

Large diffs are not rendered by default.

Binary file added .metals/metals.mv.db
Binary file not shown.
Binary file added publicidad/ejercicio_connect/Conecta$Estado.class
Binary file not shown.
Binary file added publicidad/ejercicio_connect/Conecta.class
Binary file not shown.
171 changes: 171 additions & 0 deletions publicidad/ejercicio_connect/Conecta.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import java.util.Scanner;
import java.util.ArrayList;

public class Conecta{

enum Estado {
EN_JUEGO,
EMPATE,
GANAO,
GANAX
}

private final char[] jugadores = new char[] { 'O', 'X' };
private final int ancho = 7;
private final int alto = 6;
private final char[][] tablero;
private int turno = 0;
private Estado estado = Estado.EN_JUEGO;

public Conecta() {
this.tablero = new char[this.ancho][this.alto];
for (int x = 0; x < this.ancho; x++) {
for (int y = 0; y < this.alto; y++) {
this.tablero[x][y] = ' ';
}
}
}

public String pintaTablero() {
String salida = "1234567\n";
for (int y = 0; y < this.alto; y++) {
for (int x = 0; x < this.ancho; x++) {
salida += this.tablero[x][this.alto - y - 1];
}
salida += '\n';
}
return salida;
}

public void mueve(Scanner input) {
System.out.print("\nTurno del jugador " + this.jugadores[this.turno]);
System.out.println("\nIntroduce un número de columna");
do {
int col = input.nextInt() - 1;

if (! (0 <= col && col < this.ancho)) {
System.out.println("La columna debe estar entre 1 y 7");
continue;
}
for (int y = 0; y < this.alto; y++) {
if (this.tablero[col][y] == ' ') {
this.tablero[col][y] = this.jugadores[this.turno];
this.turno = (this.turno - 1) * (this.turno - 1);
return;
}
}
System.out.println("La columna " + (col + 1) + " está llena. Selecciona otra");
} while (true);
}

public char ganadorLinea(char[] linea) {
char actual = linea[0];
int longitudLinea = 1;
for (int j = 1; j < linea.length; j++) {
char nuevo = linea[j];
if (nuevo == actual) {
longitudLinea++;
} else {
actual = nuevo;
longitudLinea = 1;
}
if (longitudLinea == 4 && actual != ' ') {
return actual;
}
}
return ' ';
}

public ArrayList<char[]> obtenerLineas() {
ArrayList<char[]> lineas = new ArrayList<char[]>();

// Busca lineas horizontales
for (int y = 0; y < this.alto; y++) {
char[] nuevaLinea = new char[this.ancho];
for (int x = 0; x < this.ancho; x++) {
nuevaLinea[x] = this.tablero[x][y];
}
lineas.add(nuevaLinea);
}

// Busca lineas verticales
for (int x = 0; x < this.ancho; x++) {
char[] nuevaLinea = new char[this.alto];
for (int y = 0; y < this.alto; y++) {
nuevaLinea[y] = this.tablero[x][y];
}
lineas.add(nuevaLinea);
}

// Busca lineas diagonales /
for (int x = -this.alto + 1; x < this.ancho; x++) {
char[] nuevaLinea = new char[this.alto];
for (int y = 0; y < this.alto; y++) {
int posx = x + y;
if ( (posx < 0) || (posx >= this.ancho)) {
nuevaLinea[y] = ' ';
} else {
nuevaLinea[y] = this.tablero[posx][y];
}
}
lineas.add(nuevaLinea);
}

// Busca lineas antidiagonales \
for (int x = 0; x < this.ancho + this.alto - 1; x++) {
char[] nuevaLinea = new char[this.alto];
for (int y = 0; y < this.alto; y++) {
int posx = x - y;
if ( (posx < 0) || (posx >= this.ancho)) {
nuevaLinea[y] = ' ';
} else {
nuevaLinea[y] = this.tablero[posx][y];
}
}
lineas.add(nuevaLinea);
}
return lineas;
}

public void actualizaEstadoPartida() {
boolean tableroLleno = true;
for (int x = 0; x < this.ancho; x++) {
if(this.tablero[x][this.alto - 1] == ' ') {
tableroLleno = false;
}
}

ArrayList<char[]> lineasTablero = this.obtenerLineas();
for (char[] linea : lineasTablero) {
char ganador = this.ganadorLinea(linea);
if (ganador == 'X') {
this.estado = Estado.GANAX;
return;
}
if (ganador == 'O') {
this.estado = Estado.GANAO;
return;
}
}
if (tableroLleno) {
this.estado = Estado.EMPATE;
return;
}
this.estado = Estado.EN_JUEGO;
return;
}

public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
Conecta conecta = new Conecta();
while(conecta.estado == Estado.EN_JUEGO) {
System.out.println(conecta.pintaTablero());
conecta.mueve(input);
conecta.actualizaEstadoPartida();
}
System.out.println(conecta.pintaTablero());
System.out.println("La partida ha terminado");
System.out.println("El resultado es " + conecta.estado);
}
}
}
Binary file not shown.
213 changes: 213 additions & 0 deletions publicidad/ejercicio_connect/enunciado.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
# Problema de Programación (Ing. Telecomunicaciones)

## Enunciado

Queremos modelar el juego Conecta 4 y desarrollar un bucle que permita competir a dos humanos. Para ello, se pide desarrollar una clase Java Connect con los siguientes métodos:
* Método main, que tendrá el bucle del juego.
* Método actualizaEstadoPartida, actualiza un enum con los siguientes valores (enJuego, ganadorO, ganadorX, empate).
* Método mueve, que valida si la entrada y realiza el movimiento usando un input.
* Método pintaTablero, que pintará el tablero tras cada turno.
* Método mueve, que realiza el movimiento por parte del PC.

Nota: el tablero tiene 7 posiciones horizontales y 6 verticales.

Nota 2: hay dos jugadores, con fichas O y X respectivamente. El jugador con O empieza la partida.

## Solución

Por simplicidad lo haremos todo en el mismo fichero Conecta.java. Comencemos con los imports:

```java
import java.util.Scanner;
import java.util.ArrayList;
```

En primer lugar, dentro de la clase Conecta definiremos el enum con los valores posibles del Estado (este enum lo podríamos haber definido en un fichero auxiliar o fuera de la clase principal).

```java
public class Conecta{

enum Estado {
EN_JUEGO,
EMPATE,
GANAO,
GANAX
}
```

A continuación, definimos los atributos de la clase que almacenarán el estado del juego (incluyendo el tablero):

```java
private final char[] jugadores = new char[] { 'O', 'X' };
private final int ancho = 7;
private final int alto = 6;
private final char[][] tablero;
private int turno = 0;
private Estado estado = Estado.EN_JUEGO;
```

Como todo salvo el tablero lo hemos inicializado con valores por defecto, en el constructor tan sólo tenemos que rellenar el tablero (usamos un espacio para las posiciones no ocupadas):

```java
public Conecta() {
this.tablero = new char[this.ancho][this.alto];
for (int x = 0; x < this.ancho; x++) {
for (int y = 0; y < this.alto; y++) {
this.tablero[x][y] = ' ';
}
}
}
```

Pasamos ya a los métodos principales:

```java
public String pintaTablero() {
String salida = "1234567\n";
for (int y = 0; y < this.alto; y++) {
for (int x = 0; x < this.ancho; x++) {
salida += this.tablero[x][this.alto - y - 1];
}
salida += '\n';
}
return salida;
}

public void mueve(Scanner input) {
System.out.print("\nTurno del jugador " + this.jugadores[this.turno]);
System.out.println("\nIntroduce un número de columna");
do {
int col = input.nextInt() - 1;

if (! (0 <= col && col < this.ancho)) {
System.out.println("La columna debe estar entre 1 y 7");
continue;
}
for (int y = 0; y < this.alto; y++) {
if (this.tablero[col][y] == ' ') {
this.tablero[col][y] = this.jugadores[this.turno];
this.turno = (this.turno - 1) * (this.turno - 1);
return;
}
}
System.out.println("La columna " + (col + 1) + " está llena. Selecciona otra");
} while (true);
}

public char ganadorLinea(char[] linea) {
char actual = linea[0];
int longitudLinea = 1;
for (int j = 1; j < linea.length; j++) {
char nuevo = linea[j];
if (nuevo == actual) {
longitudLinea++;
} else {
actual = nuevo;
longitudLinea = 1;
}
if (longitudLinea == 4 && actual != ' ') {
return actual;
}
}
return ' ';
}

public ArrayList<char[]> obtenerLineas() {
ArrayList<char[]> lineas = new ArrayList<char[]>();

// Busca lineas horizontales
for (int y = 0; y < this.alto; y++) {
char[] nuevaLinea = new char[this.ancho];
for (int x = 0; x < this.ancho; x++) {
nuevaLinea[x] = this.tablero[x][y];
}
lineas.add(nuevaLinea);
}

// Busca lineas verticales
for (int x = 0; x < this.ancho; x++) {
char[] nuevaLinea = new char[this.alto];
for (int y = 0; y < this.alto; y++) {
nuevaLinea[y] = this.tablero[x][y];
}
lineas.add(nuevaLinea);
}

// Busca lineas diagonales /
for (int x = -this.alto + 1; x < this.ancho; x++) {
char[] nuevaLinea = new char[this.alto];
for (int y = 0; y < this.alto; y++) {
int posx = x + y;
if ( (posx < 0) || (posx >= this.ancho)) {
nuevaLinea[y] = ' ';
} else {
nuevaLinea[y] = this.tablero[posx][y];
}
}
lineas.add(nuevaLinea);
}

// Busca lineas antidiagonales \
for (int x = 0; x < this.ancho + this.alto - 1; x++) {
char[] nuevaLinea = new char[this.alto];
for (int y = 0; y < this.alto; y++) {
int posx = x - y;
if ( (posx < 0) || (posx >= this.ancho)) {
nuevaLinea[y] = ' ';
} else {
nuevaLinea[y] = this.tablero[posx][y];
}
}
lineas.add(nuevaLinea);
}
return lineas;
}

public void actualizaEstadoPartida() {
boolean tableroLleno = true;
for (int x = 0; x < this.ancho; x++) {
if(this.tablero[x][this.alto - 1] == ' ') {
tableroLleno = false;
}
}

ArrayList<char[]> lineasTablero = this.obtenerLineas();
for (char[] linea : lineasTablero) {
char ganador = this.ganadorLinea(linea);
if (ganador == 'X') {
this.estado = Estado.GANAX;
return;
}
if (ganador == 'O') {
this.estado = Estado.GANAO;
return;
}
}
if (tableroLleno) {
this.estado = Estado.EMPATE;
return;
}
this.estado = Estado.EN_JUEGO;
return;
}
```

Nótese que la lógica de comprobar si hay una línea se ha dividido en varios métodos: por un lado, tenemos un método que devuelve un ArrayList con todas las líneas del tablero (horizontales, verticales y ambas diagonales). Luego, hay un método que comprueba si en una determinada línea hay un ganador. Y por último tenemos el método principal de actualizar el estado que hace uso de los dos anteriores.

Por último, el método main con el bucle principal del juego:

```java
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
Conecta conecta = new Conecta();
while(conecta.estado == Estado.EN_JUEGO) {
System.out.println(conecta.pintaTablero());
conecta.mueve(input);
conecta.actualizaEstadoPartida();
}
System.out.println(conecta.pintaTablero());
System.out.println("La partida ha terminado");
System.out.println("El resultado es " + conecta.estado);
}
}
```

0 comments on commit 21e0d30

Please sign in to comment.