From 3c2761e1604c35971de855a1b23a16843c088153 Mon Sep 17 00:00:00 2001 From: delfi-fenoy Date: Thu, 14 Nov 2024 01:08:02 -0300 Subject: [PATCH 1/5] RegisterFuncionality --- .../InvalidUsernameOrPasswordException.java | 8 + .../UsernameUnavailableException.java | 7 + src/gameState/GameState.java | 2 +- src/gameState/Register.java | 138 ++++++++++++------ src/json/JSONUserManager.java | 109 ++++++++++++++ src/json/ReadWriteOperations.java | 69 +++++++++ src/main/Game.java | 13 +- src/main/Main.java | 3 +- src/users/User.java | 62 +++++++- src/utilz/Constants.java | 1 + users.json | 1 + 11 files changed, 362 insertions(+), 51 deletions(-) create mode 100644 src/exceptions/InvalidUsernameOrPasswordException.java create mode 100644 src/exceptions/UsernameUnavailableException.java create mode 100644 src/json/JSONUserManager.java create mode 100644 src/json/ReadWriteOperations.java create mode 100644 users.json diff --git a/src/exceptions/InvalidUsernameOrPasswordException.java b/src/exceptions/InvalidUsernameOrPasswordException.java new file mode 100644 index 0000000..c072b43 --- /dev/null +++ b/src/exceptions/InvalidUsernameOrPasswordException.java @@ -0,0 +1,8 @@ +package exceptions; + +public class InvalidUsernameOrPasswordException extends Exception { + + public InvalidUsernameOrPasswordException() { + super("Nombre de usuario o contraseña inválidos."); + } +} diff --git a/src/exceptions/UsernameUnavailableException.java b/src/exceptions/UsernameUnavailableException.java new file mode 100644 index 0000000..2978512 --- /dev/null +++ b/src/exceptions/UsernameUnavailableException.java @@ -0,0 +1,7 @@ +package exceptions; + +public class UsernameUnavailableException extends RuntimeException { + public UsernameUnavailableException() { + super("Nombre de usuario existente."); + } +} diff --git a/src/gameState/GameState.java b/src/gameState/GameState.java index a5291c6..22ed94a 100644 --- a/src/gameState/GameState.java +++ b/src/gameState/GameState.java @@ -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. } diff --git a/src/gameState/Register.java b/src/gameState/Register.java index 53d56c4..fe6a9d1 100644 --- a/src/gameState/Register.java +++ b/src/gameState/Register.java @@ -1,93 +1,141 @@ 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:"); + private JButton registerButton; + private JLabel userIDLabel; + private JLabel userPasswordLabel; + private JTextField userIDField; + private JPasswordField userPasswordField; + + private String name; + private String password; - String name = ""; - String password = ""; + boolean flagAddComponents = false; // Flag para agregar los componentes una única vez + boolean showMessage = false; + + private int aniTick = 0; - 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); + /** initUI ==> Instanciar los componentes. */ + public void initUI(){ + // Instanciar + registerButton = new JButton("Register"); + 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); + userIDLabel.setBounds(50, 100, 75, 25); + userPasswordLabel.setBounds(50, 150, 75, 25); + userIDField.setBounds(125, 100, 200, 25); + userPasswordField.setBounds(125, 150, 200, 25); + } - // 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); + /** addComponents() ==> Agregar los componentes al GamePanel. */ + public void addComponents(GamePanel panel){ + panel.setLayout(null); - // 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(); - }); - - uiInitialized = true; - } + 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()); + } - 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); + game.getGamePanel().removeAll(); + GameState.state = GameState.LOGIN; + + } catch (InvalidUsernameOrPasswordException e){ + e.getMessage(); + e.printStackTrace(); + showMessage = true; + + } catch (UsernameUnavailableException e){ + e.getMessage(); + e.printStackTrace(); + showMessage = true; + } } // Methods interfaz IRenderable @Override public void update() { - if(!uiInitialized){ - uiInit(); + + if(!flagAddComponents) { + GamePanel panel = game.getGamePanel(); + + if(panel != null){ + addComponents(panel); + flagAddComponents = true; + + } } + + 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("Error en la contraseña y/o usuario.", 150, 225); + } } } diff --git a/src/json/JSONUserManager.java b/src/json/JSONUserManager.java new file mode 100644 index 0000000..5da299b --- /dev/null +++ b/src/json/JSONUserManager.java @@ -0,0 +1,109 @@ +package json; + +import main.Game; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; +import users.User; + +import javax.print.attribute.standard.Fidelity; +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Clase encargada de gestionar el archivo json de usuarios. + */ +public class JSONUserManager { + + // ====================> ATRIBUTOS <==================== + + // ====================> CONTRUCTOR <==================== + public JSONUserManager() { + } + + // ====================> METODOS <==================== + /** userToFile() ==> Pasar User al archivo. */ + public void userToFile(User user){ + JSONArray jsonArray = ReadWriteOperations.read(Game.nomJSON); // Pasar el contenido a un JSONArray + + JSONObject userJson = serialize(user); // Serializar user + jsonArray.put(userJson); // Agregarlo a array + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("users", jsonArray); // Pasar + + ReadWriteOperations.write(Game.nomJSON, jsonObject); + } + + /** serialize() ==> Pasar de User a JSONObject. */ + public JSONObject serialize(User user){ + JSONObject jsonObject = null; + + try { + jsonObject = new JSONObject(); + jsonObject.put("name", user.getName()); + jsonObject.put("password", user.getPassword()); + jsonObject.put("best score", user.getBestScore()); + jsonObject.put("is admin", user.isAdmin()); + + } catch (JSONException e){ + e.printStackTrace(); + } + + return jsonObject; + } + + /** fileToUser() ==> Pasar del archivo a User. */ + public Set fileToUsers(){ + Set users = new HashSet<>(); + + try { + // Obtener JSONArray con contenido del archivo + JSONArray usersArray = ReadWriteOperations.read(Game.nomJSON); + + // Convertir cada elemento en un JSONObject + for(int i = 0; i< usersArray.length(); i++){ + JSONObject userJson = usersArray.getJSONObject(i); + users.add(deserialize(userJson)); // Deserializar JSONObject a User + } + + } catch (JSONException e){ + e.printStackTrace(); + } + + return users; + } + + /** deserialize() ==> Pasar de JSONObject a User. */ + public User deserialize(JSONObject jsonObject){ + User user = new User(); + + try { + user.setName(jsonObject.getString("name")); + user.setPassword(jsonObject.getString("password")); + user.setBestScore(jsonObject.getInt("best score")); + user.setAdmin(jsonObject.getBoolean("is admin")); + + } catch (JSONException e){ + e.printStackTrace(); + } + + return user; + } + + /** isUsernameAvailable() ==> Method que verifica que no se repita el nombre. */ + public boolean isUsernameAvailable(String username){ + Set users = fileToUsers(); // Pasar archivo a coleccion para comparar + + for(User user : users){ + if(user.getName().equals(username)){ // Comparar nombre de cada usuario con nombre requerido + return false; // Retornar falso si ya hay uno igual + } + } + return true; // Retornar true si no hay uno igual + } +} diff --git a/src/json/ReadWriteOperations.java b/src/json/ReadWriteOperations.java new file mode 100644 index 0000000..d227186 --- /dev/null +++ b/src/json/ReadWriteOperations.java @@ -0,0 +1,69 @@ +package json; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + +import java.io.*; + +/** + *Clase con métodos estáticos para leer y escrbir en el archivo. + */ +public final class ReadWriteOperations { + + public ReadWriteOperations() { + } + + /** write() ==> Escribir en el archivo. */ + public static void write(String file, JSONObject jsonObject){ + try { + FileWriter fileWriter = new FileWriter(file); + fileWriter.write(jsonObject.toString()); // Pasar el JSONObject al archivo + fileWriter.close(); + + } catch (IOException e){ // Capturar excepcion de entrada/salida + e.printStackTrace(); + + } + } + + + /** read() ==> Leer el archivo. */ + public static JSONArray read(String file){ + JSONArray jsonArray = new JSONArray(); + File fileObj = new File(file); + + // Si el archivo no existe, se crea vacío + /*if (!fileObj.exists()) { + try { + fileObj.createNewFile(); // Crea el archivo vacío si no existe + } catch (IOException e) { + e.printStackTrace(); + } + + return jsonArray; // En caso de que el archivo no exista, se devuelve el JSONArray vacío + }*/ + + try { + // Leer el archivo + FileReader fileReader = new FileReader(file); + JSONTokener jsonTokener = new JSONTokener(fileReader); + // Convertir contenido del archivo a JSONObject + JSONObject jsonObject = new JSONObject(jsonTokener); + + if(jsonObject.has("users")){ // Ver si existe clave 'users' + jsonArray = jsonObject.getJSONArray("users"); + } + fileReader.close(); + + } catch (FileNotFoundException e) { // Capturar excepcion de archivo no encontrado + e.printStackTrace(); + + } catch (IOException | JSONException e) { + e.printStackTrace(); + } + + return jsonArray; + } +} diff --git a/src/main/Game.java b/src/main/Game.java index 9cc718d..20555e0 100644 --- a/src/main/Game.java +++ b/src/main/Game.java @@ -3,6 +3,7 @@ import java.awt.Graphics; import gameState.*; +import json.JSONUserManager; import utilz.IRenderable; /*** @@ -31,6 +32,10 @@ public class Game implements Runnable, IRenderable { private Register register; private Login login; + // JSON + protected JSONUserManager jsonUserManager; + public final static String nomJSON = "users.json"; + // Constantes Tiles public final static int TILES_DEFAULT_SIZE = 32; // 32 bits public final static float SCALE = 1.5f; // Variable que permite "agrandar" el tamaño de los Tile @@ -65,6 +70,10 @@ public GamePanel getGamePanel() { return gamePanel; } + public JSONUserManager getJsonUserManager(){ + return jsonUserManager; + } + // ====================> METODOS <==================== /** initClasses() ==> Instancia las clases. */ private void initClasses(){ @@ -72,6 +81,8 @@ private void initClasses(){ playing = new Playing(this); register = new Register(this); login = new Login(this); + + jsonUserManager = new JSONUserManager(); } /** startGameLoop() ==> Instancia el Thread e inicia el Game Loop. */ @@ -170,7 +181,7 @@ public void run() { // Cada segundo, muestra FPS y UPS por consola y reinicia contadores if (System.currentTimeMillis() - lastCheck >= 1000) { lastCheck = System.currentTimeMillis(); - System.out.println("FPS: " + frames + " | UPS: " + updates); +// System.out.println("FPS: " + frames + " | UPS: " + updates); frames = 0; updates = 0; diff --git a/src/main/Main.java b/src/main/Main.java index 87f900e..94a26f5 100644 --- a/src/main/Main.java +++ b/src/main/Main.java @@ -1,7 +1,6 @@ package main; -public class Main -{ +public class Main { public static void main(String[] args) { new Game(); } diff --git a/src/users/User.java b/src/users/User.java index ed34db9..b34be61 100644 --- a/src/users/User.java +++ b/src/users/User.java @@ -1,5 +1,7 @@ package users; +import java.util.Objects; + public class User { // ====================> ATRIBUTOS <==================== @@ -9,14 +11,70 @@ public class User { private boolean isAdmin; // ====================> CONTRUCTOR <==================== - public User(String name, String password, boolean isAdmin){ + public User(){} + + public User(String name, String password){ this.name = name; this.password = password; - this.isAdmin = isAdmin; + this.isAdmin = false; bestScore = 0; } // ====================> GET | SET <==================== + public int getBestScore() { + return bestScore; + } + + public void setBestScore(int bestScore) { + this.bestScore = bestScore; + } + + public boolean isAdmin() { + return isAdmin; + } + + public void setAdmin(boolean admin) { + isAdmin = admin; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + // ====================> METODOS <==================== + @Override + public String toString() { + return "User{" + + "bestScore=" + bestScore + + ", name='" + name + '\'' + + ", password='" + password + '\'' + + ", isAdmin=" + isAdmin + + '}'; + } + + // Comparar por nombre + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || !(o instanceof User user)) return false; + return Objects.equals(name, user.name); + } + + @Override + public int hashCode() { + return Objects.hashCode(name); + } } diff --git a/src/utilz/Constants.java b/src/utilz/Constants.java index a6e3c18..e39767f 100644 --- a/src/utilz/Constants.java +++ b/src/utilz/Constants.java @@ -8,6 +8,7 @@ public class Constants { public static final int ANI_SPEED_ALIEN = 20; public static final int ANI_SPEED_ATTACK = 50; // Temporizador Disparo de Enemy || 2000 Milisegundos (2 segundos) public static final int ANI_RESTART_LEVEL = 150; // Temporizador para reiniciar nivel + public static final int ANI_ERROR_MESSAGE = 1000; // Temporizador para mostrar mensaje de error en Register public static class EnemyConstants{ diff --git a/users.json b/users.json new file mode 100644 index 0000000..61c809d --- /dev/null +++ b/users.json @@ -0,0 +1 @@ +{"users":[{"is admin":false,"password":"fenoy","best score":0,"name":"delfi"},{"is admin":false,"password":"feweewf","best score":0,"name":"g"},{"is admin":false,"password":"frefe","best score":0,"name":"gree"},{"is admin":false,"password":"gre","best score":0,"name":"gte"},{"is admin":false,"password":"bgfbf","best score":0,"name":"bgfbf"},{"is admin":false,"password":"nhgtn","best score":0,"name":"muny"},{"is admin":false,"password":"mjym","best score":0,"name":"mynm"},{"is admin":false,"password":"btbt","best score":0,"name":"hbytrbt"}]} \ No newline at end of file From 94f5f1714fdbe1f3903f2c551a42d7d8ee104bdc Mon Sep 17 00:00:00 2001 From: delfi-fenoy Date: Thu, 14 Nov 2024 01:40:01 -0300 Subject: [PATCH 2/5] RegisterFunctionalityFinished --- src/gameState/GameState.java | 2 +- src/gameState/Login.java | 1 + src/gameState/Register.java | 31 ++++++++++++++++++++++++++++--- src/json/ReadWriteOperations.java | 2 +- src/utilz/Constants.java | 2 +- users.json | 21 ++++++++++++++++++++- 6 files changed, 52 insertions(+), 7 deletions(-) diff --git a/src/gameState/GameState.java b/src/gameState/GameState.java index 22ed94a..a5291c6 100644 --- a/src/gameState/GameState.java +++ b/src/gameState/GameState.java @@ -9,6 +9,6 @@ public enum GameState { PLAYING, MENU, OPTIONS, RANKING, QUIT, REGISTER, LOGIN; - public static GameState state = REGISTER; // Estado por default. + public static GameState state = LOGIN; // Estado por default. } diff --git a/src/gameState/Login.java b/src/gameState/Login.java index 999051a..66a8f60 100644 --- a/src/gameState/Login.java +++ b/src/gameState/Login.java @@ -96,6 +96,7 @@ private void uiInit() { registerButton.addActionListener(e -> { panel.removeAll(); + uiInitialized = false; GameState.state = GameState.REGISTER; }); diff --git a/src/gameState/Register.java b/src/gameState/Register.java index fe6a9d1..742f008 100644 --- a/src/gameState/Register.java +++ b/src/gameState/Register.java @@ -14,7 +14,11 @@ public class Register extends State { // ====================> ATRIBUTOS <==================== + // Botones private JButton registerButton; + private JButton quitButton; + private JButton backButton; + private JLabel userIDLabel; private JLabel userPasswordLabel; private JTextField userIDField; @@ -44,6 +48,8 @@ public Register(Game game) { 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(); @@ -51,6 +57,8 @@ public void initUI(){ // 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); @@ -62,6 +70,8 @@ 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); @@ -70,7 +80,15 @@ public void addComponents(GamePanel panel){ /** 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; + }); } /** registerUser() ==> Registrar usuario. */ @@ -89,9 +107,11 @@ public void registerUser(){ User user = new User(name, password); game.getJsonUserManager().userToFile(user); game.getGamePanel().removeAll(); + flagAddComponents = false; GameState.state = GameState.LOGIN; } catch (InvalidUsernameOrPasswordException e){ + System.out.println(game.getJsonUserManager().fileToUsers()); e.getMessage(); e.printStackTrace(); showMessage = true; @@ -101,9 +121,16 @@ public void registerUser(){ e.printStackTrace(); showMessage = true; + } finally { + clearFields(); } } + public void clearFields(){ + userIDField.setText(""); + userPasswordField.setText(""); + } + // Methods interfaz IRenderable @Override public void update() { @@ -124,9 +151,7 @@ public void update() { aniTick = 0; // Fin Contador showMessage = false; } - } - } @Override @@ -135,7 +160,7 @@ public void draw(Graphics g) { g.fillRect(125, 200, 200, 50); g.setFont(new Font("Console", Font.BOLD, 12)); g.setColor(Color.RED); - g.drawString("Error en la contraseña y/o usuario.", 150, 225); + g.drawString("El nombre de usuario y/o contraseña no cumplen con las condiciones.", 150, 225); } } } diff --git a/src/json/ReadWriteOperations.java b/src/json/ReadWriteOperations.java index d227186..abd36ee 100644 --- a/src/json/ReadWriteOperations.java +++ b/src/json/ReadWriteOperations.java @@ -19,7 +19,7 @@ public ReadWriteOperations() { public static void write(String file, JSONObject jsonObject){ try { FileWriter fileWriter = new FileWriter(file); - fileWriter.write(jsonObject.toString()); // Pasar el JSONObject al archivo + fileWriter.write(jsonObject.toString(4)); // Pasar el JSONObject al archivo fileWriter.close(); } catch (IOException e){ // Capturar excepcion de entrada/salida diff --git a/src/utilz/Constants.java b/src/utilz/Constants.java index e39767f..e3ada1d 100644 --- a/src/utilz/Constants.java +++ b/src/utilz/Constants.java @@ -8,7 +8,7 @@ public class Constants { public static final int ANI_SPEED_ALIEN = 20; public static final int ANI_SPEED_ATTACK = 50; // Temporizador Disparo de Enemy || 2000 Milisegundos (2 segundos) public static final int ANI_RESTART_LEVEL = 150; // Temporizador para reiniciar nivel - public static final int ANI_ERROR_MESSAGE = 1000; // Temporizador para mostrar mensaje de error en Register + public static final int ANI_ERROR_MESSAGE = 700; // Temporizador para mostrar mensaje de error en Register public static class EnemyConstants{ diff --git a/users.json b/users.json index 61c809d..faa2b6a 100644 --- a/users.json +++ b/users.json @@ -1 +1,20 @@ -{"users":[{"is admin":false,"password":"fenoy","best score":0,"name":"delfi"},{"is admin":false,"password":"feweewf","best score":0,"name":"g"},{"is admin":false,"password":"frefe","best score":0,"name":"gree"},{"is admin":false,"password":"gre","best score":0,"name":"gte"},{"is admin":false,"password":"bgfbf","best score":0,"name":"bgfbf"},{"is admin":false,"password":"nhgtn","best score":0,"name":"muny"},{"is admin":false,"password":"mjym","best score":0,"name":"mynm"},{"is admin":false,"password":"btbt","best score":0,"name":"hbytrbt"}]} \ No newline at end of file +{"users": [ + { + "is admin": false, + "password": "fenoy", + "best score": 0, + "name": "delfi" + }, + { + "is admin": false, + "password": "tvconideas", + "best score": 0, + "name": "ian" + }, + { + "is admin": false, + "password": "fewfe", + "best score": 0, + "name": "ffwefew" + } +]} \ No newline at end of file From 034f4ed6a25e3e03900a0e8ec109830a551b82d2 Mon Sep 17 00:00:00 2001 From: delfi-fenoy Date: Thu, 14 Nov 2024 01:47:22 -0300 Subject: [PATCH 3/5] addComments --- src/gameState/Register.java | 45 ++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/src/gameState/Register.java b/src/gameState/Register.java index 742f008..7526ae0 100644 --- a/src/gameState/Register.java +++ b/src/gameState/Register.java @@ -19,18 +19,23 @@ public class Register extends State { private JButton quitButton; private JButton backButton; + // Labels private JLabel userIDLabel; private JLabel userPasswordLabel; + + // Fields private JTextField userIDField; private JPasswordField userPasswordField; + // Atributos a ingresar private String name; private String password; + // Flags boolean flagAddComponents = false; // Flag para agregar los componentes una única vez - boolean showMessage = false; + boolean showMessage = false; // Mostrar mensaje en pantalla al lanzar excepcion - private int aniTick = 0; + private int aniTick = 0; // Contador para mostrar mensaje al lanzar excepcion // ====================> CONTRUCTOR <==================== @@ -67,15 +72,15 @@ public void initUI(){ /** 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); + panel.setLayout(null); + + panel.add(registerButton); + panel.add(quitButton); + panel.add(backButton); + panel.add(userIDLabel); + panel.add(userPasswordLabel); + panel.add(userIDField); + panel.add(userPasswordField); } /** addEventListeners() ==> Settear los botones para que hagan una acción al ser oprimidos. */ @@ -105,18 +110,18 @@ public void registerUser(){ } User user = new User(name, password); - game.getJsonUserManager().userToFile(user); - game.getGamePanel().removeAll(); - flagAddComponents = false; - GameState.state = GameState.LOGIN; + 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){ + } 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){ + } catch (UsernameUnavailableException e){ // Excepcion si el name ya existe e.getMessage(); e.printStackTrace(); showMessage = true; @@ -126,6 +131,7 @@ public void registerUser(){ } } + /** clearFields() ==> Borrar los contenidos de los fields. */ public void clearFields(){ userIDField.setText(""); userPasswordField.setText(""); @@ -135,13 +141,12 @@ public void clearFields(){ @Override public void update() { - if(!flagAddComponents) { + if(!flagAddComponents) { // Entrar una unica vez GamePanel panel = game.getGamePanel(); if(panel != null){ addComponents(panel); - flagAddComponents = true; - + flagAddComponents = true; // Para que no se agreguen de nuevo } } From 4ece89dfbf97a0a0ee6a7796f5ff5da8a256ddb8 Mon Sep 17 00:00:00 2001 From: delfi-fenoy Date: Thu, 14 Nov 2024 02:59:31 -0300 Subject: [PATCH 4/5] loginAndRegister --- src/gameState/Login.java | 81 ++----------------------------- src/json/JSONUserManager.java | 47 +++++++++++++++--- src/json/ReadWriteOperations.java | 23 +++++---- src/main/Game.java | 1 - users.json | 12 +++++ 5 files changed, 65 insertions(+), 99 deletions(-) diff --git a/src/gameState/Login.java b/src/gameState/Login.java index 66a8f60..0842a33 100644 --- a/src/gameState/Login.java +++ b/src/gameState/Login.java @@ -16,99 +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 logininfo = new HashMap(); + // 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(); - uiInitialized = false; - 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 <==================== diff --git a/src/json/JSONUserManager.java b/src/json/JSONUserManager.java index 5da299b..6f35413 100644 --- a/src/json/JSONUserManager.java +++ b/src/json/JSONUserManager.java @@ -9,10 +9,7 @@ import javax.print.attribute.standard.Fidelity; import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; /** * Clase encargada de gestionar el archivo json de usuarios. @@ -20,6 +17,8 @@ public class JSONUserManager { // ====================> ATRIBUTOS <==================== + public final static String nomJSON = "users.json"; + // ====================> CONTRUCTOR <==================== public JSONUserManager() { @@ -28,7 +27,7 @@ public JSONUserManager() { // ====================> METODOS <==================== /** userToFile() ==> Pasar User al archivo. */ public void userToFile(User user){ - JSONArray jsonArray = ReadWriteOperations.read(Game.nomJSON); // Pasar el contenido a un JSONArray + JSONArray jsonArray = ReadWriteOperations.read(nomJSON); // Pasar el contenido a un JSONArray JSONObject userJson = serialize(user); // Serializar user jsonArray.put(userJson); // Agregarlo a array @@ -36,7 +35,15 @@ public void userToFile(User user){ JSONObject jsonObject = new JSONObject(); jsonObject.put("users", jsonArray); // Pasar - ReadWriteOperations.write(Game.nomJSON, jsonObject); + ReadWriteOperations.write(nomJSON, jsonObject); + } + + public void usersSetToFile(Set users){ + JSONArray jsonArray = new JSONArray(); + for(User user : users){ + jsonArray.put(serialize(user)); + } + ReadWriteOperations.write(nomJSON, jsonArray); } /** serialize() ==> Pasar de User a JSONObject. */ @@ -59,11 +66,11 @@ public JSONObject serialize(User user){ /** fileToUser() ==> Pasar del archivo a User. */ public Set fileToUsers(){ - Set users = new HashSet<>(); + Set users = new LinkedHashSet<>(); try { // Obtener JSONArray con contenido del archivo - JSONArray usersArray = ReadWriteOperations.read(Game.nomJSON); + JSONArray usersArray = ReadWriteOperations.read(nomJSON); // Convertir cada elemento en un JSONObject for(int i = 0; i< usersArray.length(); i++){ @@ -106,4 +113,28 @@ public boolean isUsernameAvailable(String username){ } return true; // Retornar true si no hay uno igual } + + public void overwriteUser(User newUser){ + Set users = new HashSet<>(); + users = fileToUsers(); + + for(User user : users){ + if(user.getName().equals(newUser.getName())){ + users.remove(user); + users.add(newUser); + } + } + +// for(int i=0; i Leer el archivo. */ public static JSONArray read(String file){ JSONArray jsonArray = new JSONArray(); - File fileObj = new File(file); - - // Si el archivo no existe, se crea vacío - /*if (!fileObj.exists()) { - try { - fileObj.createNewFile(); // Crea el archivo vacío si no existe - } catch (IOException e) { - e.printStackTrace(); - } - - return jsonArray; // En caso de que el archivo no exista, se devuelve el JSONArray vacío - }*/ try { // Leer el archivo diff --git a/src/main/Game.java b/src/main/Game.java index 20555e0..f9ce4ab 100644 --- a/src/main/Game.java +++ b/src/main/Game.java @@ -34,7 +34,6 @@ public class Game implements Runnable, IRenderable { // JSON protected JSONUserManager jsonUserManager; - public final static String nomJSON = "users.json"; // Constantes Tiles public final static int TILES_DEFAULT_SIZE = 32; // 32 bits diff --git a/users.json b/users.json index faa2b6a..a15f658 100644 --- a/users.json +++ b/users.json @@ -16,5 +16,17 @@ "password": "fewfe", "best score": 0, "name": "ffwefew" + }, + { + "is admin": false, + "password": "ian", + "best score": 0, + "name": "tvconideas" + }, + { + "is admin": false, + "password": "jby", + "best score": 0, + "name": "buybj" } ]} \ No newline at end of file From 39aab820ac9b7b9414410ad0ee752dc31051ba89 Mon Sep 17 00:00:00 2001 From: delfi-fenoy Date: Thu, 14 Nov 2024 03:07:00 -0300 Subject: [PATCH 5/5] smallChange --- src/gameState/GameState.java | 2 +- src/json/JSONUserManager.java | 10 +++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/gameState/GameState.java b/src/gameState/GameState.java index a5291c6..22ed94a 100644 --- a/src/gameState/GameState.java +++ b/src/gameState/GameState.java @@ -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. } diff --git a/src/json/JSONUserManager.java b/src/json/JSONUserManager.java index 6f35413..fab62f1 100644 --- a/src/json/JSONUserManager.java +++ b/src/json/JSONUserManager.java @@ -122,15 +122,11 @@ public void overwriteUser(User newUser){ if(user.getName().equals(newUser.getName())){ users.remove(user); users.add(newUser); + usersSetToFile(users); } } - -// for(int i=0; i