Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions src/main/java/es/iesquevedo/controller/GameController.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import es.iesquevedo.model.GameState;
import es.iesquevedo.model.Move;
import es.iesquevedo.model.Player;
import es.iesquevedo.service.impl.GameServiceImpl;
import es.iesquevedo.service.impl.InazumaGoMoveValidator;
import es.iesquevedo.exception.InvalidMoveException;
import es.iesquevedo.exception.PlayerNotInTurnException;
Expand Down Expand Up @@ -43,6 +44,7 @@ public class GameController {

private String player1Name = "Jugador 1";
private String player2Name = "Jugador 2";
private String matchingPlayerName = "Jugador";
private long player1TimeMs = 0;
private long player2TimeMs = 0;
private AnimationTimer gameTimer;
Expand Down Expand Up @@ -313,8 +315,15 @@ private void onBoardClick(MouseEvent event) {
}

public void initGame(String gameId, String playerName) {
this.player1Name = playerName + " (Negro)";
this.player2Name = "Oponente (Blanco)";
this.matchingPlayerName = playerName != null ? playerName : "Jugador";
this.player1Name = this.matchingPlayerName;
this.player2Name = "Oponente";

if (game != null && game.getPlayers().size() >= 2) {
game.getPlayers().get(0).setName(this.player1Name);
game.getPlayers().get(1).setName(this.player2Name);
}

updatePlayerInfo();
LOGGER.log(Level.INFO, "Partida iniciada - GameID: " + gameId + " - Jugador: " + playerName);
}
Expand Down Expand Up @@ -462,10 +471,27 @@ private void onSurrender() {
@FXML
private void onBackToMenu() {
stopGameTimer();
LOGGER.log(Level.INFO, "Volviendo al menú");
// Castear a Stage para poder cerrar la ventana
javafx.stage.Stage stage = (javafx.stage.Stage) boardCanvas.getScene().getWindow();
stage.close();
LOGGER.log(Level.INFO, "Volviendo al emparejamiento");
goToMatchingScreen();
}

private void goToMatchingScreen() {
try {
javafx.fxml.FXMLLoader loader = new javafx.fxml.FXMLLoader(getClass().getResource("/fxml/MatchingScreen.fxml"));
javafx.scene.Parent root = loader.load();

es.iesquevedo.ui.MatchingScreenController controller = loader.getController();
controller.setGameService(new GameServiceImpl());
controller.startMatching(new Player(matchingPlayerName, matchingPlayerName));

javafx.stage.Stage stage = (javafx.stage.Stage) boardCanvas.getScene().getWindow();
stage.setScene(new javafx.scene.Scene(root, 500, 300));
stage.setTitle("InazumaGo - Emparejamiento");
stage.show();
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error al volver al emparejamiento", e);
statusLabel.setText("Error al volver al emparejamiento");
}
}

private void endGame() {
Expand Down
64 changes: 48 additions & 16 deletions src/main/java/es/iesquevedo/controller/LoginController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.util.logging.Level;
import java.util.logging.Logger;
Expand All @@ -31,6 +33,9 @@ public class LoginController {
@FXML
private Label statusLabel;

@FXML
private Button registerButton;

private AuthService authService;
private AppState appState;

Expand Down Expand Up @@ -105,8 +110,8 @@ public void onLoginClicked() {
emailField.clear();
passwordField.clear();

// Navegar a la pantalla de juego
navigateToGame(email);
// Navegar a la pantalla de emparejamiento
navigateToMatching(email);

} catch (Exception e) {
updateStatus("✗ Error de login: " + e.getMessage(), "error");
Expand All @@ -115,29 +120,37 @@ public void onLoginClicked() {
}

/**
* Navega a la pantalla de juego después del login exitoso.
* Navega a la pantalla de emparejamiento después del login exitoso.
*
* @param playerName nombre del jugador autenticado
* @param playerEmail email del jugador autenticado
*/
private void navigateToGame(String playerName) {
private void navigateToMatching(String playerEmail) {
try {
FXMLLoader gameLoader = new FXMLLoader(getClass().getResource("/fxml/Game.fxml"));
Parent gameRoot = gameLoader.load();
FXMLLoader matchingLoader = new FXMLLoader(getClass().getResource("/fxml/MatchingScreen.fxml"));
Parent matchingRoot = matchingLoader.load();

GameController gameController = gameLoader.getController();
gameController.setPlayerNames(playerName, "Oponente");
gameController.setInitialScores(0, 0);
es.iesquevedo.ui.MatchingScreenController matchingController = matchingLoader.getController();
String playerName = buildDisplayName(playerEmail);
matchingController.startMatching(new es.iesquevedo.model.Player(playerEmail, playerName));

Scene scene = emailField.getScene();
scene.setRoot(gameRoot);
scene.setRoot(matchingRoot);
javafx.stage.Stage stage = (javafx.stage.Stage) scene.getWindow();
stage.setTitle("InazumaGo - Partida");
stage.setTitle("InazumaGo - Emparejamiento");

LOGGER.log(Level.INFO, "Navegado a pantalla de juego para: " + playerName);
LOGGER.log(Level.INFO, "Navegado a pantalla de emparejamiento para: " + playerEmail);
} catch (Exception e) {
updateStatus("✗ Error al cargar pantalla de juego: " + e.getMessage(), "error");
LOGGER.log(Level.SEVERE, "Error al cargar Game.fxml: " + e.getMessage());
updateStatus("✗ Error al cargar pantalla de emparejamiento: " + e.getMessage(), "error");
LOGGER.log(Level.SEVERE, "Error al cargar MatchingScreen.fxml: " + e.getMessage());
}
}

private String buildDisplayName(String email) {
if (email == null || email.trim().isEmpty()) {
return "Jugador";
}
int atIndex = email.indexOf('@');
return atIndex > 0 ? email.substring(0, atIndex) : email;
}

/**
Expand Down Expand Up @@ -171,6 +184,25 @@ private void updateStatus(String message, String type) {
}
}

// ...existing code...
/**
* Navega a la pantalla de registro.
*/
@FXML
public void onRegisterClicked() {
try {
FXMLLoader registerLoader = new FXMLLoader(getClass().getResource("/fxml/Register.fxml"));
Parent registerRoot = registerLoader.load();

Scene scene = emailField.getScene();
scene.setRoot(registerRoot);
Stage stage = (Stage) scene.getWindow();
stage.setTitle("InazumaGo - Registro");

LOGGER.log(Level.INFO, "Navegado a pantalla de registro");
} catch (Exception e) {
updateStatus("✗ Error al cargar pantalla de registro: " + e.getMessage(), "error");
LOGGER.log(Level.SEVERE, "Error al cargar Register.fxml: " + e.getMessage());
}
}
}

115 changes: 105 additions & 10 deletions src/main/java/es/iesquevedo/controller/MainController.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,38 @@
import es.iesquevedo.service.MainService;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MainController {
private static final Logger LOGGER = Logger.getLogger(MainController.class.getName());
private final MainErrorHandler errorHandler = new MainErrorHandler();

// Configurable image paths
private static final String GAME_BOARD_PATH = "/images/game-board.png";
private static final String BLACK_STONE_PATH = "/images/stone-black.png";
private static final String WHITE_STONE_PATH = "/images/stone-white.png";
private static final String RESOURCE_NOT_FOUND_PREFIX = "Recurso no encontrado: ";

private MainService mainService;

@FXML
private Label salutoLabel;

@FXML
@SuppressWarnings("FieldCanBeLocal")
private ImageView gameBoardImageView;

@FXML
@SuppressWarnings("FieldCanBeLocal")
private ImageView blackStoneImageView;

@FXML
@SuppressWarnings("FieldCanBeLocal")
private ImageView whiteStoneImageView;

public MainController() {
// Constructor sin parámetros necesario para FXML
this.mainService = null;
Expand All @@ -31,30 +51,105 @@ public void setService(MainService mainService) {
@FXML
public void initialize() {
// Este método se llama automáticamente después de que FXML carga los componentes
setupGreeting();

// Cargar imagen del tablero y fichas
loadGameBoard();
loadStones();
}

private void setupGreeting() {
if (mainService != null && salutoLabel != null) {
try {
String saludo = mainService.greet();
salutoLabel.setText(saludo);
LOGGER.info("Saludo establecido: " + saludo);
handleGreetingSuccess(saludo);
} catch (RuntimeException e) {
ApiError apiError = errorHandler.toApiError(e);
LOGGER.log(Level.SEVERE, "Error al obtener saludo del servicio", e);
salutoLabel.setText(formatApiError(apiError));
handleGreetingError(e);
}
} else if (salutoLabel != null) {
salutoLabel.setText("Servicio no disponible");
}
}

private void handleGreetingSuccess(String saludo) {
salutoLabel.setText(saludo);
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info(String.format("Saludo establecido: %s", saludo));
}
}

private void handleGreetingError(RuntimeException e) {
ApiError apiError = errorHandler.toApiError(e);
LOGGER.log(Level.SEVERE, "Error al obtener saludo del servicio", e);
salutoLabel.setText(formatApiError(apiError));
}

private void loadGameBoard() {
if (gameBoardImageView != null) {
loadImage(gameBoardImageView, GAME_BOARD_PATH, "Tablero cargado correctamente", "No se pudo cargar la imagen del tablero");
}
}

private void loadStones() {
loadStone(blackStoneImageView, BLACK_STONE_PATH, 100, 100);
loadStone(whiteStoneImageView, WHITE_STONE_PATH, 200, 200);
}

private void loadImage(ImageView imageView, String path, String successMessage, String errorMessage) {
try {
var resourceStream = getClass().getResourceAsStream(path);
if (resourceStream != null) {
Image image = new Image(resourceStream);
imageView.setImage(image);
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info(successMessage);
}
} else {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, String.format("%s%s", RESOURCE_NOT_FOUND_PREFIX, path));
}
}
} catch (Exception e) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, errorMessage, e);
}
// El ImageView se queda vacío si no encuentra la imagen
}
}

private void loadStone(ImageView imageView, String path, double x, double y) {
if (imageView == null) return;
try {
var stream = getClass().getResourceAsStream(path);
if (stream == null) {
logResourceNotFound(path);
return;
}
Image stone = new Image(stream);
imageView.setImage(stone);
imageView.setFitWidth(40);
imageView.setFitHeight(40);
// Ejemplo: posición sobre el tablero (ajustar según el layout real)
imageView.setLayoutX(x);
imageView.setLayoutY(y);
} catch (Exception e) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, "No se pudo cargar la ficha", e);
}
}
}

private void logResourceNotFound(String path) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, String.format("%s%s", RESOURCE_NOT_FOUND_PREFIX, path));
}
}

public String greet() {
return mainService != null ? mainService.greet() : "Servicio no disponible";
}

static String formatApiError(ApiError apiError) {
return "Error [" + apiError.getCode() + "]: " + apiError.getMessage();
}

public void setSalutoLabel(Label label) {
this.salutoLabel = label;
return String.format("Error [%s]: %s", apiError.getCode(), apiError.getMessage());
}
}
Loading
Loading