Files
Projet_DEV/src/linea/GestionnaireBDD.java

182 lines
8.0 KiB
Java
Raw Normal View History

package linea;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class GestionnaireBDD {
private Connection conn = null;
private final String DB_URL = "jdbc:sqlite:linea.db";
public GestionnaireBDD() {
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(DB_URL);
System.out.println("Connexion à la base de données SQLite établie.");
} catch (SQLException e) {
System.out.println("Erreur de connexion à la BDD : " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Le pilote JDBC SQLite n'a pas été trouvé. Veuillez l'ajouter à votre projet.");
}
}
public void initialiserBaseDeDonnees() {
// Crée les tables si elles n'existent pas et insère les données de difficulté.
try (Statement stmt = conn.createStatement()) {
// Table pour les difficultés
stmt.execute("CREATE TABLE IF NOT EXISTS difficultes (" +
"id_difficulte INT PRIMARY KEY, " +
"vitesse REAL NOT NULL, " +
2026-03-16 16:11:07 +01:00
"pente REAL NOT NULL, " +
"segments INT NOT NULL DEFAULT 50)");
try {
stmt.execute("ALTER TABLE difficultes ADD COLUMN segments INT NOT NULL DEFAULT 50");
} catch (SQLException e) {
// Ignorer si la colonne existe déjà
}
// Table pour les scores des parties
stmt.execute("CREATE TABLE IF NOT EXISTS parties (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"duree INT, " +
"campagne_id INT, " +
"difficulte_id INT, " +
"score INT, " +
"utilisateur_id INT, " +
"date_partie TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " +
"FOREIGN KEY(utilisateur_id) REFERENCES utilisateurs(id))");
// TABLE POUR LES UTILISATEURS
2026-03-11 17:20:25 +01:00
stmt.execute("CREATE TABLE IF NOT EXISTS utilisateurs (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"identifiant TEXT UNIQUE NOT NULL, " +
"mot_de_passe TEXT NOT NULL)");
// Insertion des valeurs de difficulté par défaut
2026-03-16 16:11:07 +01:00
// On utilise INSERT OR REPLACE pour mettre à jour les valeurs si elles existent déjà
stmt.execute("INSERT OR REPLACE INTO difficultes (id_difficulte, vitesse, pente, segments) VALUES (1, 6, 20, 35);");
stmt.execute("INSERT OR REPLACE INTO difficultes (id_difficulte, vitesse, pente, segments) VALUES (2, 7, 45, 50);");
stmt.execute("INSERT OR REPLACE INTO difficultes (id_difficulte, vitesse, pente, segments) VALUES (3, 8, 60, 85);");
} catch (SQLException e) {
System.out.println("Erreur lors de l'initialisation de la base de données : " + e.getMessage());
}
}
public int verifierUtilisateur(String identifiant, String motDePasse) {
2026-03-11 17:20:25 +01:00
String sql = "SELECT id FROM utilisateurs WHERE identifiant = ? AND mot_de_passe = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, identifiant);
pstmt.setString(2, motDePasse);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt("id");
}
2026-03-11 17:20:25 +01:00
} catch (SQLException e) {
System.out.println("Erreur lors de la vérification des identifiants : " + e.getMessage());
}
return -1;
2026-03-11 17:20:25 +01:00
}
public boolean creerCompte(String identifiant, String motDePasse) {
String checkSql = "SELECT id FROM utilisateurs WHERE identifiant = ?";
try (PreparedStatement checkPstmt = conn.prepareStatement(checkSql)) {
checkPstmt.setString(1, identifiant);
if (checkPstmt.executeQuery().next()) {
System.out.println("L'identifiant '" + identifiant + "' existe déjà.");
return false; // L'utilisateur existe déjà
}
} catch (SQLException e) {
System.out.println("Erreur lors de la vérification de l'utilisateur : " + e.getMessage());
return false;
}
String insertSql = "INSERT INTO utilisateurs(identifiant, mot_de_passe) VALUES(?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertSql)) {
pstmt.setString(1, identifiant);
pstmt.setString(2, motDePasse);
pstmt.executeUpdate();
System.out.println("Compte pour '" + identifiant + "' créé avec succès.");
return true;
} catch (SQLException e) {
System.out.println("Erreur lors de la création du compte : " + e.getMessage());
return false;
}
}
public double[] getParametresDifficulte(int difficulteId) {
// Par défaut (si non trouvé), on retourne les valeurs pour la difficulté 1.
2026-03-16 16:11:07 +01:00
double[] params = {6.0, 20.0, 50.0};
String sql = "SELECT vitesse, pente, segments FROM difficultes WHERE id_difficulte = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, difficulteId);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
params[0] = rs.getDouble("vitesse");
params[1] = rs.getDouble("pente");
2026-03-16 16:11:07 +01:00
params[2] = rs.getDouble("segments");
}
} catch (SQLException e) {
System.out.println("Erreur lors de la récupération des paramètres de difficulté : " + e.getMessage());
}
return params;
}
public void enregistrerPartie(int dureePartie, int idCampagneActive, int difficulteActive, int score, int utilisateurId) {
if (utilisateurId == -1) {
System.out.println("Partie non enregistrée : aucun utilisateur connecté.");
return;
}
String sql = "INSERT INTO parties(duree, campagne_id, difficulte_id, score, utilisateur_id) VALUES(?,?,?,?,?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, dureePartie);
pstmt.setInt(2, idCampagneActive);
pstmt.setInt(3, difficulteActive);
pstmt.setInt(4, score);
pstmt.setInt(5, utilisateurId);
pstmt.executeUpdate();
System.out.println("Partie enregistrée pour l'utilisateur ID " + utilisateurId);
} catch (SQLException e) {
System.out.println("Erreur lors de l'enregistrement de la partie : " + e.getMessage());
}
}
public Object[][] getLeaderboardData() {
2026-03-16 15:45:04 +01:00
String sql = "SELECT u.identifiant, MAX(p.score) AS score, p.date_partie, p.campagne_id, p.difficulte_id " +
"FROM parties p " +
"JOIN utilisateurs u ON p.utilisateur_id = u.id " +
2026-03-16 15:45:04 +01:00
"GROUP BY p.campagne_id, p.difficulte_id " +
"ORDER BY p.campagne_id ASC, p.difficulte_id ASC";
List<Object[]> data = new ArrayList<>();
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
Object[] row = {
rs.getString("identifiant"),
rs.getInt("score"),
2026-03-16 15:40:32 +01:00
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(rs.getTimestamp("date_partie")),
rs.getInt("campagne_id"),
rs.getInt("difficulte_id")
};
data.add(row);
}
} catch (SQLException e) {
System.out.println("Erreur lors de la récupération du leaderboard : " + e.getMessage());
}
return data.toArray(new Object[0][]);
}
public void fermerConnexion() {
try {
if (conn != null) {
conn.close();
System.out.println("Connexion BDD fermée.");
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}