Un peu de ménage dans le git
This commit is contained in:
273
src/fr/monkhanny/dorfromantik/utils/Database.java
Normal file
273
src/fr/monkhanny/dorfromantik/utils/Database.java
Normal file
@@ -0,0 +1,273 @@
|
||||
package fr.monkhanny.dorfromantik.utils;
|
||||
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import javax.swing.ImageIcon;
|
||||
|
||||
import fr.monkhanny.dorfromantik.gui.Reward;
|
||||
|
||||
public class Database {
|
||||
// Chargement des variables d'environnement
|
||||
private static final String URL = "jdbc:mariadb://dwarves.iut-fbleau.fr/stiti";
|
||||
private static final String LOGIN = "stiti";
|
||||
private static final String PASSWORD = "stiti1234";
|
||||
|
||||
// Variable de passerelle entre le programme et la base de données
|
||||
private Connection database;
|
||||
|
||||
/**
|
||||
* Ouvre la connexion avec la base de données
|
||||
*/
|
||||
public Database() throws SQLException {
|
||||
try {
|
||||
// Chargement du driver MariaDB
|
||||
Class.forName("org.mariadb.jdbc.Driver");
|
||||
|
||||
try {
|
||||
// Connexion à la base de données
|
||||
this.database = DriverManager.getConnection(URL, LOGIN, PASSWORD);
|
||||
}catch (SQLException e) {
|
||||
// Gestion de l'erreur de connexion
|
||||
throw new SQLException("Échec de la connexion à la base de données: " + e.getMessage(), e);
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
// Si le driver n'est pas trouvé
|
||||
throw new SQLException("Driver MariaDB introuvable dans le classpath", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Connection getDatabase() {
|
||||
return this.database;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Récupère le seed correspondant au mode de jeu (series_id)
|
||||
* @param seriesId L'ID de la série (mode de jeu)
|
||||
* @return Le seed associé à ce mode de jeu
|
||||
* @throws SQLException Si une erreur se produit lors de la récupération du seed
|
||||
*/
|
||||
public long getSeedBySeriesId(long seriesId) throws SQLException {
|
||||
String query = "SELECT series_id FROM Series WHERE series_id = " + seriesId;
|
||||
long seed = -1; // Valeur par défaut si le seed n'est pas trouvé
|
||||
|
||||
try (Statement stmt = this.database.createStatement();
|
||||
ResultSet rs = stmt.executeQuery(query)) {
|
||||
if (rs.next()) {
|
||||
seed = rs.getLong("series_id");
|
||||
}
|
||||
}
|
||||
|
||||
return seed;
|
||||
}
|
||||
|
||||
public List<PlayerScore> getAllScores(long seriesId) throws SQLException {
|
||||
List<PlayerScore> allScores = new ArrayList<>();
|
||||
|
||||
String query = "SELECT username, score FROM Scores WHERE series_id = ? ORDER BY score DESC";
|
||||
try (PreparedStatement stmt = this.database.prepareStatement(query)) {
|
||||
stmt.setLong(1, seriesId);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
String username = rs.getString("username");
|
||||
if (username == null || username.trim().isEmpty()) {
|
||||
username = "Joueur Anonyme"; // Default name if empty
|
||||
}
|
||||
int score = rs.getInt("score");
|
||||
allScores.add(new PlayerScore(username, score));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return allScores;
|
||||
}
|
||||
|
||||
|
||||
public long getSeedByName(String name) throws SQLException {
|
||||
String query = "SELECT series_id FROM Series WHERE name = " + "\'" + name + "\'" +";";
|
||||
long seed = -1; // Valeur par défaut si le seed n'est pas trouvé
|
||||
|
||||
try (Statement stmt = this.database.createStatement();
|
||||
ResultSet rs = stmt.executeQuery(query)) {
|
||||
if (rs.next()) {
|
||||
seed = rs.getLong("series_id");
|
||||
}
|
||||
}
|
||||
|
||||
return seed;
|
||||
}
|
||||
|
||||
public void addScore(String username, long seriesId, int score) throws SQLException {
|
||||
String insertQuery = "INSERT INTO Scores (username, series_id, score) VALUES (?, ?, ?)";
|
||||
try (PreparedStatement stmt = this.database.prepareStatement(insertQuery)) {
|
||||
stmt.setString(1, username);
|
||||
stmt.setLong(2, seriesId);
|
||||
stmt.setInt(3, score);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Erreur lors de l'ajout du score: " + e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void addCustomSeed(String name, long customSeed) throws SQLException {
|
||||
// Vérifier si la seed existe déjà
|
||||
String checkQuery = "SELECT COUNT(*) FROM Series WHERE series_id = ?";
|
||||
try (PreparedStatement checkStmt = this.database.prepareStatement(checkQuery)) {
|
||||
checkStmt.setLong(1, customSeed);
|
||||
ResultSet rs = checkStmt.executeQuery();
|
||||
if (rs.next() && rs.getInt(1) > 0) {
|
||||
// la seed existe déjà
|
||||
return; // Ne pas insérer si la seed existe déjà
|
||||
}
|
||||
}
|
||||
|
||||
// Si la seed n'existe pas, procéder à l'insertion
|
||||
String insertQuery = "INSERT INTO Series (name, series_id, creation_date) VALUES (?, ?, CURRENT_TIMESTAMP)";
|
||||
try (PreparedStatement stmt = this.database.prepareStatement(insertQuery)) {
|
||||
stmt.setString(1, name);
|
||||
stmt.setLong(2, customSeed);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Erreur lors de l'ajout de la seed custom: " + e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Récupère les meilleurs scores des joueurs (limite de 10 scores)
|
||||
* @return une liste de résultats sous forme de tableau d'objets contenant le nom du joueur et son score
|
||||
*/
|
||||
public List<PlayerScore> getTopPlayers() throws SQLException {
|
||||
List<PlayerScore> topPlayers = new ArrayList<>();
|
||||
|
||||
String query = "SELECT username, score FROM Scores ORDER BY score DESC LIMIT 10";
|
||||
try (Statement stmt = this.database.createStatement();
|
||||
ResultSet rs = stmt.executeQuery(query)) {
|
||||
|
||||
while (rs.next()) {
|
||||
String username = rs.getString("username");
|
||||
if (username == null || username.trim().isEmpty()) {
|
||||
username = "Joueur Anonyme"; // Remplacer par "Joueur Anonyme" si le pseudo est vide ou nul
|
||||
}
|
||||
int score = rs.getInt("score");
|
||||
topPlayers.add(new PlayerScore(username, score));
|
||||
}
|
||||
}
|
||||
|
||||
return topPlayers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère les scores d'une série spécifique, triés en ordre décroissant (du plus élevé au plus bas)
|
||||
* @param seriesId L'ID de la série
|
||||
* @return Liste des scores pour la série donnée
|
||||
* @throws SQLException En cas d'erreur lors de la récupération des scores
|
||||
*/
|
||||
public List<Integer> getScoresBySeriesId(long seriesId) throws SQLException {
|
||||
List<Integer> scores = new ArrayList<>();
|
||||
|
||||
String query = "SELECT score FROM Scores WHERE series_id = ? ORDER BY score DESC";
|
||||
try (PreparedStatement stmt = this.database.prepareStatement(query)) {
|
||||
stmt.setLong(1, seriesId);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
scores.add(rs.getInt("score"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If you want the scores to be in descending order (from highest to lowest)
|
||||
Collections.sort(scores, Collections.reverseOrder());
|
||||
|
||||
return scores;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère les récompenses d'un utilisateur spécifique
|
||||
* @param username Le nom d'utilisateur pour lequel récupérer les récompenses
|
||||
* @return Liste des récompenses de l'utilisateur
|
||||
* @throws SQLException En cas d'erreur lors de la récupération des récompenses
|
||||
*/
|
||||
public List<Reward> getRewardsByUsername(String username) throws SQLException {
|
||||
List<Reward> rewards = new ArrayList<>();
|
||||
String query = "SELECT r.name, r.description, r.icon_path, ur.is_unlocked " +
|
||||
"FROM UserRewards ur " +
|
||||
"JOIN Rewards r ON ur.reward_id = r.reward_id " +
|
||||
"WHERE ur.username = ?";
|
||||
|
||||
try (PreparedStatement stmt = this.database.prepareStatement(query)) {
|
||||
stmt.setString(1, username);
|
||||
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
String name = rs.getString("name");
|
||||
String description = rs.getString("description");
|
||||
String iconPath = rs.getString("icon_path");
|
||||
boolean isUnlocked = rs.getBoolean("is_unlocked");
|
||||
|
||||
ImageIcon icon = (iconPath != null && !iconPath.isEmpty()) ? new ImageIcon(iconPath) : null;
|
||||
Reward reward = new Reward(name, description, isUnlocked, icon);
|
||||
rewards.add(reward);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rewards;
|
||||
}
|
||||
|
||||
public void unlockRewards(String username, int score) throws SQLException {
|
||||
// Vérifier les récompenses possibles en fonction du score du joueur
|
||||
String query = "SELECT reward_id FROM Rewards WHERE score_threshold <= ?";
|
||||
try (PreparedStatement stmt = this.database.prepareStatement(query)) {
|
||||
stmt.setInt(1, score);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
long rewardId = rs.getLong("reward_id");
|
||||
|
||||
// Ajouter la récompense à la table UserRewards si elle n'est pas déjà débloquée
|
||||
String checkQuery = "SELECT COUNT(*) FROM UserRewards WHERE username = ? AND reward_id = ?";
|
||||
try (PreparedStatement checkStmt = this.database.prepareStatement(checkQuery)) {
|
||||
checkStmt.setString(1, username);
|
||||
checkStmt.setLong(2, rewardId);
|
||||
|
||||
ResultSet checkRs = checkStmt.executeQuery();
|
||||
if (checkRs.next() && checkRs.getInt(1) == 0) {
|
||||
// Si la récompense n'est pas encore débloquée pour cet utilisateur, l'ajouter
|
||||
String insertQuery = "INSERT INTO UserRewards (username, reward_id, is_unlocked) VALUES (?, ?, 1)";
|
||||
try (PreparedStatement insertStmt = this.database.prepareStatement(insertQuery)) {
|
||||
insertStmt.setString(1, username);
|
||||
insertStmt.setLong(2, rewardId);
|
||||
insertStmt.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void close() {
|
||||
try {
|
||||
if (this.database != null && !this.database.isClosed()) {
|
||||
this.database.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Erreur lors de la fermeture de la base de données : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user