Skip to content

Commit

Permalink
Register and Login (incomplete) to main
Browse files Browse the repository at this point in the history
Sistema usuario
  • Loading branch information
delfi-fenoy authored Nov 14, 2024
2 parents 9af98ae + 39aab82 commit 3d7155d
Show file tree
Hide file tree
Showing 12 changed files with 455 additions and 132 deletions.
8 changes: 8 additions & 0 deletions src/exceptions/InvalidUsernameOrPasswordException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package exceptions;

public class InvalidUsernameOrPasswordException extends Exception {

public InvalidUsernameOrPasswordException() {
super("Nombre de usuario o contraseña inválidos.");
}
}
7 changes: 7 additions & 0 deletions src/exceptions/UsernameUnavailableException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package exceptions;

public class UsernameUnavailableException extends RuntimeException {
public UsernameUnavailableException() {
super("Nombre de usuario existente.");
}
}
2 changes: 1 addition & 1 deletion src/gameState/GameState.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ public enum GameState {

PLAYING, MENU, OPTIONS, RANKING, QUIT, REGISTER, LOGIN;

public static GameState state = LOGIN; // Estado por default.
public static GameState state = REGISTER; // Estado por default.

}
80 changes: 3 additions & 77 deletions src/gameState/Login.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,98 +16,24 @@ public class Login extends State {

// Contenedores
JTextField userIDField = new JTextField();
JTextField adminCode = new JTextField();
JPasswordField userPasswordField = new JPasswordField();

// CheckBox
JCheckBox adminCheckBox = new JCheckBox("Admin");

// Texto
JLabel userIDLabel = new JLabel("Username: ");
JLabel userPasswordLabel = new JLabel("Password: ");
JLabel adminCodeLabel = new JLabel("Admin Code: ");

// Varibles
HashMap<String, String> logininfo = new HashMap<String, String>();
// Variables
boolean uiInitialized = false;

// ====================> CONSTRUCTOR <====================
public Login(Game game) {
super(game);

}

// ====================> METODOS <====================
private void uiInit() {
GamePanel panel = game.getGamePanel();

if(panel != null){

//Configurar Ubicaciones

// Usuario
userIDLabel.setBounds(50, 100, 75, 25);
userIDField.setBounds(125, 100, 200, 25);

// Contraseña
userPasswordLabel.setBounds(50, 150, 75, 25);
userPasswordField.setBounds(125, 150, 200, 25);

// Botones
loginButton.setBounds(125, 200, 100, 25);
quitButton.setBounds(225, 200, 100, 25);
registerButton.setBounds(Game.GAME_WIDTH-150, Game.GAME_HEIGHT-50, 100, 25);

// CheckBox
adminCheckBox.setBounds(225, 250, 100, 25);
adminCode.setBounds(225, 250, 100, 25);
adminCodeLabel.setBounds(225, 250, 100, 25);
public void uiInit(){

// Agregar los componentes al panel
panel.setLayout(null);
panel.add(userIDLabel);
panel.add(userIDField);
panel.add(userPasswordLabel);
panel.add(userPasswordField);
panel.add(loginButton);
panel.add(quitButton);
panel.add(adminCheckBox);
panel.add(registerButton);

// Cuando Toque el Boton Login (Crear metodo Comprobar Usuario)
loginButton.addActionListener(e -> {
String userID = userIDField.getText();
String password = new String(userPasswordField.getPassword());

if (logininfo.containsKey(userID) && logininfo.get(userID).equals(password)) {
System.out.println("Login exitoso");
panel.removeAll();
GameState.state = GameState.MENU;
} else {
System.out.println("Usuario: " + userID + "\nContraseña: " + password);
panel.removeAll();
GameState.state = GameState.MENU;
}
});

// Cuando Toque el Boton Quit
quitButton.addActionListener(e -> {
GameState.state = GameState.QUIT;
});

registerButton.addActionListener(e -> {
panel.removeAll();
GameState.state = GameState.REGISTER;
});

// Cuando se toque el CheckBox
adminCheckBox.addActionListener(e -> {
panel.add(adminCodeLabel);
panel.add(adminCode);
});

// Reanudar el Update
uiInitialized = true;
}
}

// ====================> METODOS INTERFACE <====================
Expand Down
176 changes: 127 additions & 49 deletions src/gameState/Register.java
Original file line number Diff line number Diff line change
@@ -1,93 +1,171 @@
package gameState;

import exceptions.InvalidUsernameOrPasswordException;
import exceptions.UsernameUnavailableException;
import main.Game;
import main.GamePanel;
import users.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import static utilz.Constants.ANI_ERROR_MESSAGE;

public class Register extends State {

// ====================> ATRIBUTOS <====================
JButton registerButton = new JButton("Register");
JTextField userIDField = new JTextField();
JPasswordField userPasswordField = new JPasswordField();
JLabel userIDLabel = new JLabel("userID:");
JLabel userPasswordLabel = new JLabel("password:");
// Botones
private JButton registerButton;
private JButton quitButton;
private JButton backButton;

// Labels
private JLabel userIDLabel;
private JLabel userPasswordLabel;

// Fields
private JTextField userIDField;
private JPasswordField userPasswordField;

String name = "";
String password = "";
// Atributos a ingresar
private String name;
private String password;

// Flags
boolean flagAddComponents = false; // Flag para agregar los componentes una única vez
boolean showMessage = false; // Mostrar mensaje en pantalla al lanzar excepcion

private int aniTick = 0; // Contador para mostrar mensaje al lanzar excepcion

boolean uiInitialized = false;

// ====================> CONTRUCTOR <====================
public Register(Game game) {
super(game);
initUI();
addEventListeners();
}

// ====================> GET | SET <====================

// ====================> METODOS <====================

public void uiInit(){
GamePanel panel = game.getGamePanel();
if(panel != null){
panel.setLayout(null);

// Configura los componentes de la interfaz (etiquetas, campos, botones)
registerButton.setBounds(125, 200, 100, 25);
userIDField.setBounds(125, 100, 200, 25);
userPasswordField.setBounds(125, 150, 200, 25);
userIDLabel.setBounds(50, 100, 75, 25);
userPasswordLabel.setBounds(50, 150, 75, 25);

// Agregar los componentes al panel
panel.add(registerButton);
panel.add(userIDField);
panel.add(userPasswordField);
panel.add(userIDLabel);
panel.add(userPasswordLabel);

// Agregar ActionListener al botón de login
registerButton.addActionListener(e -> {

createAccount();
});
/** initUI ==> Instanciar los componentes. */
public void initUI(){
// Instanciar
registerButton = new JButton("Register");
quitButton = new JButton("Quit");
backButton = new JButton("Back");
userIDLabel = new JLabel("User name:");
userPasswordLabel = new JLabel("Password:");
userIDField = new JTextField();
userPasswordField = new JPasswordField();

// Limites
registerButton.setBounds(Game.GAME_WIDTH-150, Game.GAME_HEIGHT-100, 100, 25);
quitButton.setBounds(20, Game.GAME_HEIGHT-100, 100, 25);
backButton.setBounds(20, Game.GAME_HEIGHT-150, 100, 25);
userIDLabel.setBounds(50, 100, 75, 25);
userPasswordLabel.setBounds(50, 150, 75, 25);
userIDField.setBounds(125, 100, 200, 25);
userPasswordField.setBounds(125, 150, 200, 25);
}

uiInitialized = true;
}
/** addComponents() ==> Agregar los componentes al GamePanel. */
public void addComponents(GamePanel panel){
panel.setLayout(null);

panel.add(registerButton);
panel.add(quitButton);
panel.add(backButton);
panel.add(userIDLabel);
panel.add(userPasswordLabel);
panel.add(userIDField);
panel.add(userPasswordField);
}

public void createAccount(){
/** addEventListeners() ==> Settear los botones para que hagan una acción al ser oprimidos. */
public void addEventListeners(){

registerButton.addActionListener(e -> registerUser());
quitButton.addActionListener(e -> GameState.state = GameState.QUIT);
backButton.addActionListener(e -> {
game.getGamePanel().removeAll();
flagAddComponents = false; // Para que cuando vuelva a REGISTER entre a addComponents
clearFields();
GameState.state = GameState.LOGIN;
});
}

name = userIDField.getText();
password = userPasswordField.getText();
/** registerUser() ==> Registrar usuario. */
public void registerUser(){
name = userIDField.getText(); // Leer nombre
password = new String(userPasswordField.getPassword()); // Leer contraseña

try {
if(name.length() >= 5 || password.length() == 0){
throw new IllegalArgumentException();
if(name.isBlank() || password.isBlank() || name.length() >20 || password.length() >20){ // Si esta vacio o es >20
throw new InvalidUsernameOrPasswordException();

} else if (!game.getJsonUserManager().isUsernameAvailable(name)) { // Si el nombre de usuario ya existe
throw new UsernameUnavailableException();
}
System.out.println("Registrado.");
game.getGamePanel().removeAll(); // Limpiar pantalla
GameState.state = GameState.MENU;

} catch (IllegalArgumentException exception){
System.out.println("Error. Ingrese nuevamente.");
User user = new User(name, password);
game.getJsonUserManager().userToFile(user); // Pasar user al archivo
game.getGamePanel().removeAll(); // Eliminar componentes de la pantalla
flagAddComponents = false; // Para que cuando vuelva a REGISTER pueda entrar a addComponents
GameState.state = GameState.LOGIN; // Cambiar de state

} catch (InvalidUsernameOrPasswordException e){ // Excepcion si name o password esta vacio y mas de 20 caracteres
System.out.println(game.getJsonUserManager().fileToUsers());
e.getMessage();
e.printStackTrace();
showMessage = true;

} catch (UsernameUnavailableException e){ // Excepcion si el name ya existe
e.getMessage();
e.printStackTrace();
showMessage = true;

} finally {
clearFields();
}
}

/** clearFields() ==> Borrar los contenidos de los fields. */
public void clearFields(){
userIDField.setText("");
userPasswordField.setText("");
}

// Methods interfaz IRenderable
@Override
public void update() {
if(!uiInitialized){
uiInit();

if(!flagAddComponents) { // Entrar una unica vez
GamePanel panel = game.getGamePanel();

if(panel != null){
addComponents(panel);
flagAddComponents = true; // Para que no se agreguen de nuevo
}
}

if(showMessage){ // Si se mostró el mensaje de error
aniTick++;
if(aniTick >= ANI_ERROR_MESSAGE){ // Mostrar hasta que se cumpla un tiempo determinado
aniTick = 0; // Fin Contador
showMessage = false;
}
}
}

@Override
public void draw(Graphics g) {

if(showMessage){
g.fillRect(125, 200, 200, 50);
g.setFont(new Font("Console", Font.BOLD, 12));
g.setColor(Color.RED);
g.drawString("El nombre de usuario y/o contraseña no cumplen con las condiciones.", 150, 225);
}
}
}
Loading

0 comments on commit 3d7155d

Please sign in to comment.