Skip to content
Commits on Source (3)
package DAO;
import java.util.Collection;
/**
* Interface CRUD sur le stockage des données.
*
* @author stag
* @param <T> Le type du bean utilisé dans la DAO
*/
public interface Dao<T> {
/**
* Retourne l'objet lu en DB grâce à son identifiant ou null.
*
* @param id L'identifiant en DB de l'objet
* @return L'objet ou null
*/
T find(long id);
/**
* Hydrate la DB avec l'objet fourni. Cet objet doit avoir un id null.
*
* @param obj
*/
void create(T obj);
/**
* Supprime la ligne d'identifiant id dans la DB.
*
* @param id
*/
void delete(long id);
/**
* Met à jour l'objet dans la DB. L'objet doit avoir un id non null.
*
* @param obj
*/
void update(T obj);
/**
* Retourne toutes les lignes de la DB dans une collection.
*
* @return Collection contenant tous les objets hydratés par la DB.
*/
Collection<T> all();
}
package DAO;
import beans.Question;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import sql.MariaDbConnection;
/**
*
* @author stag
*/
public class DaoQuestion implements Dao<Question> {
private final Connection conn = MariaDbConnection.getInstance();
private Question createBean(ResultSet rs) {
Question obj = new Question();
try {
obj.setId(rs.getInt("id"));
obj.setLevel(rs.getInt("level"));
obj.setContent(rs.getString("content"));
obj.setAnswer(rs.getString("answer"));
} catch (SQLException ex) {
throw new RuntimeException("Impossible de parcourir le resultset");
}
return obj;
}
@Override
public Question find(long id) {
Question ret = null;
String sql = "SELECT * FROM JeuxBDD WHERE id=?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setLong(1, id);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
ret = createBean(rs);
}
} catch (SQLException ex) {
throw new RuntimeException("Sélection impossible dans la table JeuxBDD. Erreur :\n" + ex.getMessage());
}
return ret;
}
public Collection<Question> findByLevel(int level) {
Collection<Question> questions = new ArrayList<>();
String sql = "SELECT * FROM JeuxBDD WHERE level=?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, level);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
questions.add(createBean(rs));
}
} catch (SQLException ex) {
throw new RuntimeException("Sélection impossible dans la table JeuxBDD. Erreur :\n" + ex.getMessage());
}
return questions;
}
@Override
public void create(Question obj) {
String sql = "INSERT INTO JeuxBDD (level, content, answer) VALUES (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
pstmt.setInt(1, obj.getLevel());
pstmt.setString(2, obj.getContent());
pstmt.setString(3, obj.getAnswer());
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
if (keys.next()) {
obj.setId(keys.getInt(1));
}
} catch (SQLException ex) {
throw new RuntimeException("Insertion impossible dans la table JeuxBDD. Erreur :\n" + ex.getMessage());
}
}
@Override
public void delete(long id) {
String sql = "DELETE FROM JeuxBDD WHERE id=?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setLong(1, id);
pstmt.executeUpdate();
} catch (SQLException ex) {
throw new RuntimeException("Suppression impossible dans la table JeuxBDD. Erreur :\n" + ex.getMessage());
}
}
@Override
public void update(Question obj) {
String sql = "UPDATE JeuxBDD SET level=?, content=?, answer=? WHERE id=?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, obj.getLevel());
pstmt.setString(2, obj.getContent());
pstmt.setString(3, obj.getAnswer());
pstmt.setInt(4, obj.getId());
pstmt.executeUpdate();
} catch (SQLException ex) {
throw new RuntimeException("Update impossible dans la table JeuxBDD. Erreur :\n" + ex.getMessage());
}
}
@Override
public Collection<Question> all() {
Collection<Question> list = new ArrayList<>();
String sql = "SELECT * FROM jeuxBDD";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(createBean(rs));
}
} catch (SQLException ex) {
throw new RuntimeException("Liste impossible dans la table JeuxBDD. Erreur :\n" + ex.getMessage());
}
return list;
}
}
package beans;
import java.io.Serializable;
/**
*
* @author Mickael
*/
public class Question implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private int number;
private String question;
private int level;
private String content;
private String answer;
public int getId() {
......@@ -22,20 +24,20 @@ public class Question implements Serializable {
this.id = id;
}
public int getNumber() {
return number;
public int getLevel() {
return level;
}
public void setNumber(int number) {
this.number = number;
public void setLevel(int number) {
this.level = number;
}
public String getQuestion() {
return question;
public String getContent() {
return content;
}
public void setQuestion(String question) {
this.question = question;
public void setContent(String question) {
this.content = question;
}
public String getAnswer() {
......@@ -48,8 +50,7 @@ public class Question implements Serializable {
@Override
public String toString() {
return "Question{" + "id=" + id + ", number=" + number + ", question=" + question + ", answer=" + answer + '}';
return "Question{" + "id=" + id + ", number=" + level + ", question=" + content + ", answer=" + answer + '}';
}
}
package groupe3.jeux_enfants;
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
/**
*
* @author Mickael
*/
public class CalculWindow {
private final JPanel calculPanel;
private final JPanel calculPanel, group1Panel, group2Panel;
private final JLabel label;
private final JTextField txtCalcul;
private JTextField txtAnswer;
private final JTextField txtAnswer;
private final JButton btnVerify, btnSolution, btnNewCalcul;
private int resultat;
// CONSTRUCTOR
// CONSTRUCTOR -------------------------------------------------------------
public CalculWindow() {
//GUI ITEMS CREATION
calculPanel = new JPanel();
calculPanel.setLayout(new GridLayout(6, 0));
label = new JLabel("Combien font:");
txtCalcul = new JTextField();
txtAnswer = new JTextField();
group1Panel = new JPanel();
group2Panel = new JPanel();
label = new JLabel();
txtAnswer = new JTextField(2);
btnVerify = new JButton("Vérifier");
btnSolution = new JButton("Solution");
btnNewCalcul = new JButton("Autre Calcul");
//ADD GUI ITEM TO THE PANEL
calculPanel.add(label);
calculPanel.add(txtCalcul);
calculPanel.add(txtAnswer);
calculPanel.add(btnVerify);
calculPanel.add(btnSolution);
calculPanel.add(btnNewCalcul);
initGui();
initEvents();
generateCalcul();
}
private void initGui() {
//INTERFACE MANAGEMENT -------------------------------------------------
calculPanel.setLayout(new BoxLayout(calculPanel, BoxLayout.Y_AXIS));
calculPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));
group1Panel.setLayout(new BoxLayout(group1Panel, BoxLayout.X_AXIS));
group2Panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));
txtAnswer.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 20));
calculPanel.add(group1Panel);
calculPanel.add(group2Panel);
group1Panel.add(label);
group1Panel.add(txtAnswer);
group1Panel.add(btnVerify);
group2Panel.add(btnSolution);
group2Panel.add(btnNewCalcul);
}
// EVENTS MANAGEMENT
// EVENTS MANAGEMENT -------------------------------------------------------
private void initEvents() {
btnVerify.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
......@@ -64,6 +75,7 @@ public class CalculWindow {
});
}
// CALCULATION MANAGEMENT --------------------------------------------------
private void generateCalcul() {
// SELECT RANDOM NUMBERS
Random random = new Random();
......@@ -72,16 +84,17 @@ public class CalculWindow {
boolean addition = random.nextBoolean();
if (addition) {
txtCalcul.setText(a + " + " + b);
label.setText("Quel est le résultat de " + a + " + " + b + " ?");
resultat = a + b;
} else {
txtCalcul.setText(a + " - " + b);
label.setText("Quel est le résultat " + a + " - " + b + " ?");
resultat = a - b;
}
txtAnswer.setText("");
}
// VERIFY AND EXCEPTIONS MANAGEMENT -----------------------------------------
private void verifyAnswer() {
try {
int response = Integer.parseInt(txtAnswer.getText());
......
......@@ -5,72 +5,81 @@ import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* @author Mickael
* @author Kaoutar
*/
public class DrawWindow {
//DECLARATION
int x = 0, y = 0;
private final JPanel container; //window
private final JLabel label; //position
private final JPanel drawPanel; //dessin
private final JButton btnReset, btnBlueColor, btnRedColor;
private final JPanel container, drawPanel, btnGroup;
private final JButton btnReset, btnBlackColor, btnBlueColor, btnRedColor;
private Color currentColor;
public DrawWindow() {
container = new JPanel();
label = new JLabel();
//COMPONENTS INITIALISATION
container = new JPanel(); //MAIN PANEL
drawPanel = new JPanel();
drawPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
drawPanel.setPreferredSize(new Dimension(800, 450));
drawPanel.setBackground(Color.white);
btnReset = new JButton("Effacer");
btnBlackColor = new JButton("Black");
btnBlueColor = new JButton("Bleu");
btnRedColor = new JButton("Rouge");
btnGroup = new JPanel();
currentColor = Color.BLACK; //MAIN COLOR
initGui();
initEvents();
}
private void initGui() {
// POSITION MANAGEMENT
drawPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
drawPanel.setPreferredSize(new Dimension(800, 450));
drawPanel.setBackground(Color.white);
container.setLayout(new BorderLayout());
//container.add(btnReset, BorderLayout.NORTH);
container.add(btnBlueColor, BorderLayout.NORTH);
//container.add(btnRedColor, BorderLayout.NORTH);
container.add(label, BorderLayout.SOUTH);
container.add(drawPanel, BorderLayout.CENTER);
container.add(btnGroup, BorderLayout.NORTH);
btnGroup.add(btnReset);
btnGroup.add(btnBlackColor);
btnGroup.add(btnBlueColor);
btnGroup.add(btnRedColor);
}
// EVENTS MANAGEMENT
private void initEvents() {
// HERBERT'S CODE
container.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
setLabel(x, y);
}
});
container.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
Graphics g = drawPanel.getGraphics();
g.setColor(currentColor); // ADD COLOR
g.drawLine(x, y, e.getX(), e.getY());
x = e.getX();
y = e.getY();
setLabel(x, y);
}
});
setLabel(x, y);
btnReset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetDrawPanel();
}
});
}
private void setLabel(int x, int y) {
label.setText("x=" + x + ", y=" + y);
//BUTTON MANAGEMENT
btnReset.addActionListener(e -> resetDrawPanel());
btnBlackColor.addActionListener(e -> currentColor = Color.BLACK);
btnBlueColor.addActionListener(e -> currentColor = Color.BLUE);
btnRedColor.addActionListener(e -> currentColor = Color.RED);
}
public JPanel getPanel() {
......@@ -78,9 +87,7 @@ public class DrawWindow {
}
private void resetDrawPanel() {
drawPanel.removeAll();
drawPanel.revalidate();
drawPanel.repaint();
drawPanel.repaint(); // CLEAN SCREEN
}
}
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
*/
package groupe3.jeux_enfants;
import java.sql.Connection;
......@@ -10,15 +6,17 @@ import sql.MariaDbConnection;
/**
*
* @author
* @author Mickael
*/
public class Jeux_enfants {
public static void main(String[] args) {
Connection connection = MariaDbConnection.getInstance();
System.out.println("Connexion établie");
MariaDbConnection.closeConnection();
System.out.println("Connexion nettoyée");
JFrame mainwindow = new MainWindow();
//MariaDbConnection.closeConnection();
//System.out.println("Connexion nettoyée");
}
}
......@@ -15,47 +15,60 @@ import javax.swing.JPanel;
*
* @author Mickael
*/
public class MainWindow extends JFrame {
public class MainWindow extends JFrame {
//Creation of an activity array to manage the panels
//index 0: Drawing panel
//index 1: Calcul panel
//index 2: Questions and Answers panel"
private JPanel[] activities = new JPanel[3];
private final JPanel[] activities = new JPanel[3];
private final JPanel mainPanel;
private final JMenuBar menuBar;
private final JMenu menuActivities;
private final JMenuItem menuItemDrawing, menuItemCalcul, menuItemQuestion,
menuQuit;
// CONSTRUCTOR
// CONSTRUCTOR -------------------------------------------------------------
public MainWindow() {
mainPanel = new JPanel();
menuBar = new JMenuBar();
menuActivities = new JMenu("Activités");
menuItemDrawing = new JMenuItem("Ardoise Magique");
menuItemCalcul = new JMenuItem("Calcul");
menuItemQuestion = new JMenuItem("Questions-Réponses");
menuQuit = new JMenuItem("Quitter");
initGui();
initActivities();
initEvents();
setTitle("JEUX D'ENFANTS");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initActivities();
createMenu();
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
setContentPane(mainPanel);
setJMenuBar(menuBar);
setVisible(true);
}
private void initGui() {
mainPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
menuBar.setPreferredSize(new Dimension(800, 40));
menuActivities.add(menuItemDrawing);
menuActivities.add(menuItemCalcul);
menuActivities.add(menuItemQuestion);
menuBar.add(menuActivities); // Ajout du menu Activités
menuBar.add(menuQuit);
}
// ACTIVITIES INITIALISATION -----------------------------------------------
private void initActivities() {
//Store each panel in the activity list
activities[0] = new DrawWindow().getPanel();
activities[1] = new CalculWindow().getPanel();
//activities[2] = new QuestionWindow().getPanel();
activities[2] = new QuestionWindow().getPanel();
}
private JMenuBar createMenu() {
JMenuBar menuBar = new JMenuBar();
menuBar.setPreferredSize(new Dimension(800, 40));
setJMenuBar(menuBar);
JMenu menuActivities = new JMenu("Activités");
// DRAWING TAB
JMenuItem menuItemDrawing = new JMenuItem("Ardoise Magique");
// DRAWING TAB EVENT
private void initEvents() {
menuItemDrawing.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
......@@ -63,9 +76,6 @@ public class MainWindow extends JFrame {
}
});
// CALCUL TAB
JMenuItem menuItemCalcul = new JMenuItem("Calcul");
// CALCUL TAB EVENT
menuItemCalcul.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
......@@ -73,9 +83,6 @@ public class MainWindow extends JFrame {
}
});
// QUESTION TAB
JMenuItem menuItemQuestion = new JMenuItem("Questions-Réponses");
// QUESTION TAB EVENT
menuItemQuestion.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
......@@ -83,24 +90,12 @@ public class MainWindow extends JFrame {
}
});
//QUIT BUTTON
JMenuItem menuQuit = new JMenuItem("Quitter");
// QUIT BUTTON EVENT
menuQuit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0); // Ferme l'application
}
});
// ADD TAB TO MENU
menuActivities.add(menuItemDrawing);
menuActivities.add(menuItemCalcul);
menuActivities.add(menuItemQuestion);
menuBar.add(menuActivities); // Ajout du menu Activités
menuBar.add(menuQuit); // Ajout du menu Fichier
return menuBar; // Retourne la barre de menu complète
}
private void changeActivity(int index) {
......@@ -110,5 +105,4 @@ public class MainWindow extends JFrame {
mainPanel.revalidate();
mainPanel.repaint();
}
}
package groupe3.jeux_enfants;
import beans.Question;
import DAO.DaoQuestion;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.Normalizer;
import java.util.Collection;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
*
* @author yann
*/
public class QuestionWindow {
private final DaoQuestion daoQuestion;
private int lastQuestionId = -1;
private String resultat;
private final JPanel questionPanel;
private final JLabel titre;
private final JTextArea txtQuestion;
private JTextField txtAnswer;
private final JButton btnVerify, btnReponse, btnNewQuestion;
//Constructeur
public QuestionWindow() {
//Création des éléments de l'interface graphique utilisateur
questionPanel = new JPanel();
questionPanel.setLayout(new GridLayout(6, 0));
titre = new JLabel("Questions-réponses :");
txtQuestion = new JTextArea("[QUESTION PLACEHOLDER]");
txtQuestion.setLineWrap(true);
txtQuestion.setWrapStyleWord(true);
txtQuestion.setEditable(false);
txtQuestion.setPreferredSize(new Dimension(300, 75));
txtQuestion.setMaximumSize(new Dimension(300, 75));
// Optionnel : ajout de marges pour le confort
txtQuestion.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
txtAnswer = new JTextField();
btnVerify = new JButton("Vérifier");
btnReponse = new JButton("Réponse");
btnNewQuestion = new JButton("Autre question");
daoQuestion = new DaoQuestion();
//Ajout de tout les éléments au panel
questionPanel.add(titre);
questionPanel.add(txtQuestion);
questionPanel.add(txtAnswer);
questionPanel.add(btnVerify);
questionPanel.add(btnReponse);
questionPanel.add(btnNewQuestion);
generateQuestion();
//Gestion des évènements
btnVerify.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
verifyAnswer();
}
});
btnReponse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtAnswer.setText(String.valueOf(resultat));
}
});
btnNewQuestion.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
generateQuestion();
txtAnswer.setText("");
}
});
}
private void generateQuestion() {
// Récupère toutes les questions de niveau 1
Collection<Question> questions = daoQuestion.findByLevel(1);
if (questions != null && !questions.isEmpty()) {
// Convertit la collection en tableau pour faciliter la sélection aléatoire
Question[] questionArray = questions.toArray(new Question[0]);
Question randomQuestion;
// Sélectionne une question aléatoirement, mais différente de la dernière
do {
int randomIndex = new Random().nextInt(questions.size());
randomQuestion = questionArray[randomIndex];
} while (randomQuestion.getId() == lastQuestionId && questions.size() > 1);
// Met à jour le dernier ID de question pour éviter de la réafficher
lastQuestionId = randomQuestion.getId();
// Wrap la question dans une balise HTML avec une largeur fixée à 300px
txtQuestion.setText(randomQuestion.getContent());
txtQuestion.revalidate();
// Sauvegarde la réponse correcte pour une vérification ultérieure
resultat = randomQuestion.getAnswer();
} else {
txtQuestion.setText("Aucune question trouvée pour le niveau 1 !");
}
}
private void verifyAnswer() {
try {
// Récupère la réponse de l'utilisateur et la réponse correcte
String userAnswer = txtAnswer.getText().trim(); // Supprime les espaces avant/après
String correctAnswer = resultat.trim();
// Supprime les accents et rend insensible à la casse
userAnswer = normalizeString(userAnswer);
correctAnswer = normalizeString(correctAnswer);
// Vérifie si la réponse utilisateur correspond à la réponse correcte
if (userAnswer.equalsIgnoreCase(correctAnswer)) {
JOptionPane.showMessageDialog(null, "Bonne réponse !");
} else {
JOptionPane.showMessageDialog(null, "Mauvaise réponse. La bonne réponse est : " + resultat);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Veuillez entrer une réponse valide.");
}
}
private String normalizeString(String input) {
// Supprime les accents et normalise la chaîne
return Normalizer.normalize(input, Normalizer.Form.NFD)
.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "")
.toLowerCase(); // Rendre la chaîne en minuscules pour ignorer la casse
}
public JPanel getPanel() {
return questionPanel;
}
}