bdd connexion utilisateur

This commit is contained in:
llample3
2026-03-17 15:03:07 +01:00
parent 4ed51ead51
commit 69ebe7a09a
22 changed files with 382 additions and 80 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,47 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
public class BoutonScoresUtilisateur {
public static JButton creerBouton(JFrame fenetre, int utilisateurId) {
JButton boutonScores = new JButton("Voir mes scores");
// Style
boutonScores.setBackground(Color.BLACK);
boutonScores.setForeground(Color.WHITE);
// Position
boutonScores.setBounds(300, 20, 160, 30);
// Action au clic
boutonScores.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
List<Integer> scores = GestionBDD.recupererScoresUtilisateur(utilisateurId);
int meilleurScore = GestionBDD.recupererMeilleurScoreUtilisateur(utilisateurId);
StringBuilder message = new StringBuilder();
message.append("Meilleur score : ").append(meilleurScore).append("\n\n");
message.append("Tous les scores :\n");
for (int score : scores) {
message.append(score).append("\n");
}
JOptionPane.showMessageDialog(
fenetre,
message.toString(),
"Mes Scores",
JOptionPane.INFORMATION_MESSAGE
);
}
});
return boutonScores;
}
}

View File

@@ -0,0 +1,138 @@
import java.awt.*;
import javax.swing.*;
public class CadreDeConnexion extends JFrame {
public CadreDeConnexion() {
// 1. Configuration de base
setTitle("Connexion Linea");
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Centre la fenêtre
// 2. Style du panneau principal (Gris foncé)
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(new Color(30, 30, 30));
add(panel);
// Conteneur pour les éléments (pour les empiler verticalement)
Box box = Box.createVerticalBox();
// 3. Création des composants
JLabel titre = new JLabel("CONNEXION");
titre.setForeground(Color.WHITE);
titre.setFont(new Font("Arial", Font.BOLD, 24));
titre.setAlignmentX(Component.CENTER_ALIGNMENT);
JTextField userField = new JTextField(15);
userField.setMaximumSize(new Dimension(250, 30));
JPasswordField passField = new JPasswordField(15);
passField.setMaximumSize(new Dimension(250, 30));
JButton loginBtn = new JButton("Entrer");
loginBtn.setBackground(new Color(70, 130, 180)); // Bleu acier
loginBtn.setForeground(Color.WHITE);
loginBtn.setFocusPainted(false);
loginBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
// 4. Ajout des composants avec des espaces (Struts)
box.add(titre);
box.add(Box.createVerticalStrut(30)); // Espace
box.add(new JLabel("<html><font color='white'>Utilisateur :</font></html>"));
box.add(userField);
box.add(Box.createVerticalStrut(15));
box.add(new JLabel("<html><font color='white'>Mot de passe :</font></html>"));
box.add(passField);
box.add(Box.createVerticalStrut(30));
box.add(loginBtn);
box.add(Box.createVerticalStrut(10));
JButton createBtn = new JButton("Créer un compte");
createBtn.setBackground(new Color(70, 130, 180));
createBtn.setForeground(Color.WHITE);
createBtn.setFocusPainted(false);
createBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
box.add(createBtn);
panel.add(box); // Ajoute la boîte au centre du GridBagLayout
// 5. Logique du bouton
loginBtn.addActionListener(e -> {
String user = userField.getText();
String pass = new String(passField.getPassword());
int userId = GestionBDD.verifierConnexion(user, pass);
if (userId != -1) {
dispose();
Jeu jeu = new Jeu(userId);
jeu.demarrer();
} else {
JOptionPane.showMessageDialog(this, "Acces refuse");
}
});
createBtn.addActionListener(evt -> {
JFrame createFrame = new JFrame("Creation de compte");
createFrame.setSize(800, 600);
createFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
createFrame.setLocationRelativeTo(null);
JPanel createPanel = new JPanel(new GridBagLayout());
createPanel.setBackground(new Color(30, 30, 30));
createFrame.add(createPanel);
Box createBox = Box.createVerticalBox();
JLabel createTitre = new JLabel("CREATION DE COMPTE");
createTitre.setForeground(Color.WHITE);
createTitre.setFont(new Font("Arial", Font.BOLD, 24));
createTitre.setAlignmentX(Component.CENTER_ALIGNMENT);
JTextField newUserField = new JTextField(15);
newUserField.setMaximumSize(new Dimension(250, 30));
JPasswordField newPassField = new JPasswordField(15);
newPassField.setMaximumSize(new Dimension(250, 30));
JButton createAccountBtn = new JButton("Créer");
createAccountBtn.setBackground(new Color(70, 130, 180));
createAccountBtn.setForeground(Color.WHITE);
createAccountBtn.setFocusPainted(false);
createAccountBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
createBox.add(createTitre);
createBox.add(Box.createVerticalStrut(30));
createBox.add(new JLabel("<html><font color='white'>Nouvel utilisateur :</font></html>"));
createBox.add(newUserField);
createBox.add(Box.createVerticalStrut(15));
createBox.add(new JLabel("<html><font color='white'>Mot de passe :</font></html>"));
createBox.add(newPassField);
createBox.add(Box.createVerticalStrut(30));
createBox.add(createAccountBtn);
createPanel.add(createBox);
createAccountBtn.addActionListener(e -> {
String u = newUserField.getText().trim();
String p = new String(newPassField.getPassword());
if (u.isEmpty() || p.isEmpty()) {
JOptionPane.showMessageDialog(createFrame, "Utilisateur et mot de passe requis");
return;
}
boolean ok = GestionBDD.creerUtilisateur(u, p);
if (ok) {
JOptionPane.showMessageDialog(createFrame, "Compte cree avec succes.");
createFrame.dispose();
} else {
JOptionPane.showMessageDialog(createFrame, "Échec : le nom d'utilisateur existe deja ou erreur.");
}
});
createFrame.setVisible(true);
});
setVisible(true);
}
}

View File

@@ -4,85 +4,157 @@ import java.util.List;
public class GestionBDD { public class GestionBDD {
private static final String URL = "jdbc:sqlite:score.db"; private static final String URL = "jdbc:sqlite:UserScoreBDD.db";
//connexion bdd // connexion BDD
private static Connection connecter() throws SQLException { private static Connection connecter() throws SQLException {
return DriverManager.getConnection(URL); return DriverManager.getConnection(URL);
} }
//creation de la table score a ca premiere execution // Création table utilisateur
public static void creerTableSiAbsente() { public static void creerTableUtilisateurSiAbsente() {
String sql = """ String sql = """
CREATE TABLE IF NOT EXISTS scores ( CREATE TABLE IF NOT EXISTS utilisateur (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
score INTEGER NOT NULL, username TEXT NOT NULL UNIQUE,
date TEXT NOT NULL password TEXT NOT NULL
); );
"""; """;
try (Connection connexion = connecter(); try (Connection conn = connecter();
Statement statement = connexion.createStatement()) { Statement stmt = conn.createStatement()) {
statement.execute(sql); stmt.execute(sql);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
// Ajouter un score a la fin de la partie // Création table score
public static void ajouterScore(int score) { public static void creerTableScoreSiAbsente() {
String sql = "INSERT INTO scores(score, date) VALUES(?, ?)"; String sql = """
CREATE TABLE IF NOT EXISTS score (
id INTEGER PRIMARY KEY AUTOINCREMENT,
valeur INTEGER NOT NULL,
utilisateur_id INTEGER,
FOREIGN KEY(utilisateur_id) REFERENCES utilisateur(id)
);
""";
try (Connection connexion = connecter(); try (Connection conn = connecter();
PreparedStatement requete = connexion.prepareStatement(sql)) { Statement stmt = conn.createStatement()) {
requete.setInt(1, score); stmt.execute(sql);
requete.setString(2, java.time.LocalDate.now().toString());
requete.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
// Récupérer tous les scores // Créer un utilisateur
public static List<Integer> recupererTousLesScores() { public static boolean creerUtilisateur(String username, String password) {
List<Integer> listeScores = new ArrayList<>(); String sql = "INSERT INTO utilisateur(username, password) VALUES(?, ?)";
String sql = "SELECT score FROM scores ORDER BY date DESC"; try (Connection conn = connecter();
PreparedStatement stmt = conn.prepareStatement(sql)) {
try (Connection connexion = connecter(); stmt.setString(1, username);
Statement statement = connexion.createStatement(); stmt.setString(2, password);
ResultSet resultat = statement.executeQuery(sql)) {
while (resultat.next()) { stmt.executeUpdate();
listeScores.add(resultat.getInt("score")); return true;
} catch (SQLException e) {
System.out.println("Utilisateur déjà existant !");
return false;
}
}
// Vérifier connexion utilisateur
public static int verifierConnexion(String username, String password) {
String sql = "SELECT id FROM utilisateur WHERE username = ? AND password = ?";
try (Connection conn = connecter();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getInt("id");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
return listeScores; return -1;
} }
// Récupérer le meilleur score // Ajouter score
public static int recupererMeilleurScore() { public static void ajouterScore(int score, int utilisateurId) {
String sql = "SELECT MAX(score) AS meilleur FROM scores"; String sql = "INSERT INTO score(valeur, utilisateur_id) VALUES(?, ?)";
try (Connection connexion = connecter(); try (Connection conn = connecter();
Statement statement = connexion.createStatement(); PreparedStatement stmt = conn.prepareStatement(sql)) {
ResultSet resultat = statement.executeQuery(sql)) {
if (resultat.next()) { stmt.setInt(1, score);
return resultat.getInt("meilleur"); stmt.setInt(2, utilisateurId);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Récupérer scores d'un utilisateur
public static List<Integer> recupererScoresUtilisateur(int utilisateurId) {
List<Integer> scores = new ArrayList<>();
String sql = "SELECT valeur FROM score WHERE utilisateur_id = ? ORDER BY valeur DESC";
try (Connection conn = connecter();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, utilisateurId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
scores.add(rs.getInt("valeur"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return scores;
}
// Meilleur score d'un utilisateur
public static int recupererMeilleurScoreUtilisateur(int utilisateurId) {
String sql = "SELECT MAX(valeur) as meilleur FROM score WHERE utilisateur_id = ?";
try (Connection conn = connecter();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, utilisateurId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getInt("meilleur");
} }
} catch (SQLException e) { } catch (SQLException e) {
@@ -91,4 +163,79 @@ public class GestionBDD {
return 0; return 0;
} }
}
// Meilleur score global
public static int recupererMeilleurScoreGlobal() {
String sql = "SELECT MAX(valeur) as meilleur FROM score";
try (Connection conn = connecter();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
return rs.getInt("meilleur");
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
// Vérifier si un utilisateur existe (par username)
public static boolean utilisateurExiste(String username) {
String sql = "SELECT 1 FROM utilisateur WHERE username = ?";
try (Connection conn = connecter();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
// Créer un compte et retourner l'id de l'utilisateur créé, ou -1 en cas d'erreur
public static int creerCompte(String username, String password) {
if (username == null || username.isBlank() || password == null || password.isBlank()) {
return -1;
}
if (utilisateurExiste(username)) {
return -1; // déjà existant
}
String sql = "INSERT INTO utilisateur(username, password) VALUES(?, ?)";
try (Connection conn = connecter();
PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, username);
stmt.setString(2, password);
int affected = stmt.executeUpdate();
if (affected == 0) {
return -1;
}
try (ResultSet keys = stmt.getGeneratedKeys()) {
if (keys.next()) {
return keys.getInt(1);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
}

View File

@@ -40,6 +40,8 @@ public class Jeu implements KeyListener, ActionListener{
protected boolean jeuCommence = false; protected boolean jeuCommence = false;
protected boolean modeTriche = false; protected boolean modeTriche = false;
private int utilisateurId;
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// METHODES // METHODES
@@ -48,7 +50,11 @@ public class Jeu implements KeyListener, ActionListener{
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Constructeur de la classe // Constructeur de la classe
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
public Jeu(){ public Jeu(int utilisateurId){
this.utilisateurId = utilisateurId;
// Créer les tables si elles n'existent pas
GestionBDD.creerTableUtilisateurSiAbsente();
GestionBDD.creerTableScoreSiAbsente();
// Gestion du score : a réactiver en fin de TP, inutile au début // Gestion du score : a réactiver en fin de TP, inutile au début
ecran.setLayout(null); ecran.setLayout(null);
@@ -145,42 +151,9 @@ public class Jeu implements KeyListener, ActionListener{
ecran.requestFocusInWindow(); ecran.requestFocusInWindow();
fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 🔹 Création du bouton Voir Scores
javax.swing.JButton boutonScores = new javax.swing.JButton("Voir mes scores");
boutonScores.setBackground(Color.BLACK); // Couleur fond
boutonScores.setForeground(Color.WHITE); // Couleur texte
//boutonScores.setFont(new Font("Arial", Font.BOLD, 14)); // Police
// Position du bouton // 🔹 Bouton Voir Scores (appel de la classe externe)
boutonScores.setBounds(300, 20, 160, 30); javax.swing.JButton boutonScores = BoutonScoresUtilisateur.creerBouton(fenetre, utilisateurId);
// Action quand on clique
boutonScores.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
java.util.List<Integer> scores = GestionBDD.recupererTousLesScores();
int meilleurScore = GestionBDD.recupererMeilleurScore();
StringBuilder message = new StringBuilder();
message.append("Meilleur score : ").append(meilleurScore).append("\n\n");
message.append("Tous les scores :\n");
for (int score : scores) {
message.append(score).append("\n");
}
javax.swing.JOptionPane.showMessageDialog(
fenetre,
message.toString(),
"Mes Scores",
javax.swing.JOptionPane.INFORMATION_MESSAGE
);
}
});
// affichier le bouton à l'écran
ecran.setLayout(null);
ecran.add(boutonScores); ecran.add(boutonScores);
// Création du timer // Création du timer
@@ -244,7 +217,8 @@ public class Jeu implements KeyListener, ActionListener{
this.ecran.partiePerdue = true; // 2. Signaler à l'écran this.ecran.partiePerdue = true; // 2. Signaler à l'écran
this.ecran.repaint(); // 3. Forcer l'affichage du texte this.ecran.repaint(); // 3. Forcer l'affichage du texte
GestionBDD.ajouterScore((int)this.score);// enregistrement du score dans la base de donne GestionBDD.ajouterScore((int)score, utilisateurId);// enregistrement du score dans la base de donne
} else if (this.modeTriche && this.laLigne.getSegCourant() != null) { } else if (this.modeTriche && this.laLigne.getSegCourant() != null) {
// En mode triche, forcer le cercle à rester sur la ligne // En mode triche, forcer le cercle à rester sur la ligne
double yPoint = this.laLigne.SegCourant.y + (this.laLigne.SegCourant.yLong / this.laLigne.SegCourant.xLong) * (this.demiCercleAvant.x - this.laLigne.SegCourant.x); double yPoint = this.laLigne.SegCourant.y + (this.laLigne.SegCourant.yLong / this.laLigne.SegCourant.xLong) * (this.demiCercleAvant.x - this.laLigne.SegCourant.x);

View File

@@ -5,11 +5,7 @@ public class LineaAppli {
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
public static void main(String[] arg) { public static void main(String[] arg) {
GestionBDD.creerTableSiAbsente(); new CadreDeConnexion();
Jeu jeu = new Jeu();
jeu.demarrer();
} }