Files
Projet_DEV/src/linea/GestionnaireBDD.java

231 lines
10 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;
2026-03-25 13:07:41 +01:00
private Connection connDifficulte = null;
private final String DB_URL = "jdbc:sqlite:linea.db";
2026-03-25 13:07:41 +01:00
private final String DB_DIFFICULTE_URL = "jdbc:sqlite:difficultes.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.");
2026-03-25 13:07:41 +01:00
connDifficulte = DriverManager.getConnection(DB_DIFFICULTE_URL);
System.out.println("Connexion à la base de données SQLite pour les difficultés é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 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)");
2026-03-27 09:57:12 +01:00
try { stmt.execute("ALTER TABLE utilisateurs ADD COLUMN is_admin INTEGER DEFAULT 0"); } catch (SQLException e) {}
stmt.execute("INSERT OR IGNORE INTO utilisateurs(identifiant, mot_de_passe, is_admin) VALUES('admin', 'admin', 1)");
} catch (SQLException e) {
2026-03-25 13:07:41 +01:00
System.out.println("Erreur lors de l'initialisation de la base de données principale : " + e.getMessage());
}
try (Statement stmtDiff = connDifficulte.createStatement()) {
stmtDiff.execute("CREATE TABLE IF NOT EXISTS difficultes (" +
"id_difficulte INT PRIMARY KEY, " +
"vitesse REAL NOT NULL, " +
"pente REAL NOT NULL, " +
"segments INT NOT NULL DEFAULT 50)");
try {
stmtDiff.execute("ALTER TABLE difficultes ADD COLUMN segments INT NOT NULL DEFAULT 50");
} catch (SQLException e) {
// Ignorer si la colonne existe déjà
}
// 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à
2026-03-25 13:07:41 +01:00
stmtDiff.execute("INSERT OR REPLACE INTO difficultes (id_difficulte, vitesse, pente, segments) VALUES (1, 6, 20, 35);");
stmtDiff.execute("INSERT OR REPLACE INTO difficultes (id_difficulte, vitesse, pente, segments) VALUES (2, 7, 45, 50);");
stmtDiff.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
}
2026-03-27 09:57:12 +01:00
public boolean estAdmin(int userId) {
try (PreparedStatement p = conn.prepareStatement("SELECT is_admin FROM utilisateurs WHERE id = ?")) {
p.setInt(1, userId);
ResultSet rs = p.executeQuery();
return rs.next() && rs.getInt("is_admin") == 1;
} catch (SQLException e) { return false; }
}
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 = ?";
2026-03-25 13:07:41 +01:00
try (PreparedStatement pstmt = connDifficulte.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][]);
}
2026-03-24 21:09:41 +01:00
public Object[][] getHistoriqueParties() {
String sql = "SELECT u.identifiant, p.date_partie, p.score, p.campagne_id, p.difficulte_id, p.duree " +
"FROM parties p " +
"JOIN utilisateurs u ON p.utilisateur_id = u.id " +
"ORDER BY p.date_partie DESC";
List<Object[]> data = new ArrayList<>();
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
Object[] row = {
rs.getString("identifiant"),
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(rs.getTimestamp("date_partie")),
rs.getInt("score"),
rs.getInt("campagne_id"),
rs.getInt("difficulte_id"),
rs.getInt("duree")
};
data.add(row);
}
} catch (SQLException e) {
System.out.println("Erreur lors de la récupération de l'historique : " + e.getMessage());
}
return data.toArray(new Object[0][]);
}
public void fermerConnexion() {
try {
if (conn != null) {
conn.close();
System.out.println("Connexion BDD fermée.");
}
2026-03-25 13:07:41 +01:00
if (connDifficulte != null) {
connDifficulte.close();
System.out.println("Connexion BDD difficultés fermée.");
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}