init: correction bug et conflit

This commit is contained in:
2026-03-25 11:09:13 +01:00
19 changed files with 384 additions and 82 deletions

BIN
projet_linea/Niveaux.db Normal file

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

@@ -143,6 +143,11 @@ public class Cercle extends ObjetGraphique{ // il s'agit plutôt d'arcs de cercl
}
}
// Méthode pour réinitialiser la vitesse
public void resetVitesse(){
vitesse = 0;
}
}

View File

@@ -4,85 +4,157 @@ import java.util.List;
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 {
return DriverManager.getConnection(URL);
}
//creation de la table score a ca premiere execution
public static void creerTableSiAbsente() {
// Création table utilisateur
public static void creerTableUtilisateurSiAbsente() {
String sql = """
CREATE TABLE IF NOT EXISTS scores (
CREATE TABLE IF NOT EXISTS utilisateur (
id INTEGER PRIMARY KEY AUTOINCREMENT,
score INTEGER NOT NULL,
date TEXT NOT NULL
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
);
""";
try (Connection connexion = connecter();
Statement statement = connexion.createStatement()) {
try (Connection conn = connecter();
Statement stmt = conn.createStatement()) {
statement.execute(sql);
stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
// Ajouter un score a la fin de la partie
public static void ajouterScore(int score) {
// Création table 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();
PreparedStatement requete = connexion.prepareStatement(sql)) {
try (Connection conn = connecter();
Statement stmt = conn.createStatement()) {
requete.setInt(1, score);
requete.setString(2, java.time.LocalDate.now().toString());
requete.executeUpdate();
stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
// Récupérer tous les scores
public static List<Integer> recupererTousLesScores() {
// Créer un utilisateur
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();
Statement statement = connexion.createStatement();
ResultSet resultat = statement.executeQuery(sql)) {
stmt.setString(1, username);
stmt.setString(2, password);
while (resultat.next()) {
listeScores.add(resultat.getInt("score"));
stmt.executeUpdate();
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) {
e.printStackTrace();
}
return listeScores;
return -1;
}
// Récupérer le meilleur score
public static int recupererMeilleurScore() {
// Ajouter score
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();
Statement statement = connexion.createStatement();
ResultSet resultat = statement.executeQuery(sql)) {
try (Connection conn = connecter();
PreparedStatement stmt = conn.prepareStatement(sql)) {
if (resultat.next()) {
return resultat.getInt("meilleur");
stmt.setInt(1, score);
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) {
@@ -91,4 +163,79 @@ public class GestionBDD {
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

@@ -1,4 +1,3 @@
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
@@ -47,6 +46,8 @@ public class Jeu implements KeyListener, ActionListener{
// Propriété de ma connexion à ma base de données
Connection conn = null;
private int utilisateurId;
// Variables actuelles du début de jeu
protected int idNiveauActuel = 1;
protected Niveau niveauEnCours;
@@ -60,9 +61,11 @@ public class Jeu implements KeyListener, ActionListener{
//-------------------------------------------------------------------------
// Constructeur de la classe
//-------------------------------------------------------------------------
public Jeu(){
public Jeu(int utilisateurId){
JFrame fenetre = new JFrame();
this.utilisateurId = utilisateurId;
Background premierFond = null;
// On crée le jeu avec sa base de données
try {
@@ -191,43 +194,9 @@ public class Jeu implements KeyListener, ActionListener{
ecran.requestFocusInWindow();
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
javax.swing.JButton boutonscores = BoutonScoresUtilisateur.creerBouton(fenetre, utilisateurId);
// Position du bouton
boutonScores.setBounds(300, 20, 160, 30);
// 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);
this.ecran.add(boutonscores);
// Création du timer
horloge = new Timer(40, this);
@@ -357,7 +326,7 @@ public class Jeu implements KeyListener, ActionListener{
this.ecran.partiePerdue = true; // 2. Signaler à l'écran
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)this.score);// enregistrement du score dans la base de donne
}
}

View File

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

Binary file not shown.