1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include "Animation.h"
Animation::Animation(int x, QWidget *parent = 0) : QDialog(parent)
{
QColor couleur[] = {Qt::darkRed, Qt::cyan, Qt::magenta, Qt::gray, Qt::green, Qt::yellow, Qt::red, Qt::blue};
/* On stock les x rectangles voulu dans la première tour */
for (int i = 0; i<x ; i++) {
tmp.q = QRect(-150+(i*5), 100-(i*25), 100-(i*10), -25);
tmp.taille = 100-(i*10);
tmp.in = couleur[i];
tour1.push_back(tmp);
}
Fond(); /* On crée le fond */
Rectangles(); /* Et on ajoute les rectangles */
hanoi(x, tour1, tour3, tour2); /* Puis on lance l'algorithme sur les tours d'Hanoi */
}
/* Création du fond de la scène */
void Animation::Fond() {
scene = new QGraphicsScene(-200, -200, 400, 400);
QPen pen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
base = scene->addLine(QLine(-150, 100, 150, 100), pen);
baton1 = scene->addLine(QLine(0, 100, 0, -100), pen);
baton2 = scene->addLine(QLine(100, 100, 100, -100), pen);
baton3 = scene->addLine(QLine(-100, 100, -100, -100), pen);
base->setZValue(-1); baton1->setZValue(-1); baton3->setZValue(-1); baton2->setZValue(-1);
QGraphicsView *vue = new QGraphicsView(scene, this);
vue->setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing);
vue->setGeometry(50, 50, 405, 405);
vue->setStyleSheet("background-color: #FFFFFF");
setFixedSize(510,510);
quitter = new QPushButton("Quitter", this);
quitter->setGeometry(180, 480, 150, 20);
connect(quitter,SIGNAL(clicked()),this, SLOT(accept()));
}
/* Ajout des rectangles dans la scène */
void Animation::Rectangles() {
QPen pen(Qt::black, 1, Qt::SolidLine);
for (int i = 0; i<(int)tour1.size() ; i++) {
tour1[i].q = QRect(-100-(tour1[i].taille/2), 100-(i*25), tour1[i].taille, -25);
scene->addRect(tour1[i].q,pen,tour1[i].in);
}
for (int i = 0; i<(int)tour2.size() ; i++) {
tour2[i].q = QRect(0-(tour2[i].taille/2), 100-(i*25), tour2[i].taille, -25);
scene->addRect(tour2[i].q,pen,tour2[i].in);
}
for (int i = 0; i<(int)tour3.size() ; i++) {
tour3[i].q = QRect(100-(tour3[i].taille/2), 100-(i*25), tour3[i].taille, -25);
scene->addRect(tour3[i].q,pen,tour3[i].in);
}
}
/* Algorithme de résolution */
void Animation::hanoi(int x, QVector<Rect> &t1, QVector<Rect> &t3, QVector<Rect> &t2){
if ( x > 0 ) {
hanoi(x-1, t1, t2, t3);
bouger(t1, t3);
hanoi(x-1, t2, t3, t1);
}
}
void Animation::bouger(QVector<Rect> &t1, QVector<Rect> &t3) {
Rect tmp = t1.back();
t1.pop_back();
t3.push_back(tmp);
/* Méthode de rafraîchissement brute */
delete scene; /* On supprime la scène */
Fond(); /* Et on recréer le fond */
Rectangles(); /* Et on place les rectangles à leur nouvelle place */
} |
Partager