Partage
  • Partager sur Facebook
  • Partager sur Twitter

applet java : draw image dans une boucle !!!

demande d'aide SVP

    21 mai 2012 à 12:13:06

    salut pour tout le monde :) !!
    je suis entrain de programmer une applet java baser sur TSP ant (problème de voyageur de commerce) !! je suis dans une état de blocage :'( , mon code zéro erreur mais le résultat attendu pas affiché, tout simplement mon applet affiche un nombre des noeuds lorsque je click sur le bouton générer, puis calcule le plus cours chemin tout en traversant les noeuds une seule foi, je veut déplacer une image à l'aide du souris pour que le plus cours chemin sera calculé de nouveau, mais ça ne marche pas!! :( si quelqu'un a une idée pour ce problème ?! et merci d'avance :)

    voilà mon code :

    import java.applet.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.reflect.*;
    import java.util.*;
    import java.applet.Applet ;

    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    public class essai extends Applet
    implements MouseListener, MouseMotionListener {

    int xa, yb;
    boolean dragging;
    boolean dragRedSquare;
    int offsetX, offsetY;


    //-------
    boolean NoeudVisitee,AgentFourmi,QtePhero;
    String sauv_res_cycl="nombre de cycle bonne chemain\n";
    tsp myTsp;
    colony myColony;
    double averages[];

    TextField textNoeud,
    textAlpha,
    textBeta,
    textAnt,
    textVrate,
    textAmount,
    textRounds;

    Label labelBestPath;
    Button buttonGenerate,buttonGo;

    Image ord;

    public void init() {


    xa = 10;
    yb = 10;
    setBackground(Color.lightGray);
    addMouseListener(this);
    addMouseMotionListener(this);

    //---------
    NoeudVisitee = false;
    AgentFourmi = false;
    QtePhero = false;
    MediaTracker mt= new MediaTracker(this);
    ord = getImage(getCodeBase(),"ord1.jpg");
    mt.addImage(ord,0);
    Panel stat_cyc=new Panel();
    Panel panelRight = new Panel(new GridLayout(15, 2, 4, 4));
    BorderLayout bl = new BorderLayout();
    bl.setVgap(4);
    Panel panelLeft = new Panel(bl);
    Label labelNoeud = new Label("Noeud", Label.RIGHT);
    Label labelAnt = new Label("Fourmi", Label.RIGHT);
    Label labelVrate = new Label("Evaporation", Label.RIGHT);
    Label labelAmount = new Label("Pheromone", Label.RIGHT);
    Label labelRounds = new Label("Cycle", Label.RIGHT);
    Label labelAlpha = new Label("Alpha", Label.RIGHT);
    Label labelBeta = new Label("Beta", Label.RIGHT);
    labelBestPath = new Label("0.0", Label.CENTER);
    labelBestPath.setBackground(Color.red);
    textNoeud = new TextField("5", 6);
    textAnt = new TextField("1", 6);
    textVrate = new TextField("0.5", 6);
    textAmount = new TextField("1", 6);
    textRounds = new TextField("40", 6);
    textAlpha = new TextField("1", 6);
    textBeta = new TextField("5", 6);
    buttonGenerate = new Button("Generer");
    buttonGo = new Button("Demarrer!");
    buttonGo.setEnabled(false);
    buttonGenerate.addActionListener(new buttonAL());
    buttonGo.addActionListener(new buttonAL());
    panelRight.add(labelNoeud); panelRight.add(textNoeud);
    panelRight.add(labelAnt); panelRight.add(textAnt);
    panelRight.add(labelVrate); panelRight.add(textVrate);
    panelRight.add(labelAmount); panelRight.add(textAmount);
    panelRight.add(labelRounds); panelRight.add(textRounds);
    panelRight.add(labelAlpha); panelRight.add(textAlpha);
    panelRight.add(labelBeta); panelRight.add(textBeta);
    panelRight.add(new Label()); panelRight.add(buttonGenerate);
    panelRight.add(new Label()); panelRight.add(buttonGo);
    panelRight.add(new Label("MeilleurTrajet", Label.RIGHT));
    panelRight.add(labelBestPath);

    Panel panelMain = new Panel();
    panelMain.add(panelLeft);
    panelMain.add(panelRight);
    Panel panelTop = new Panel(new BorderLayout());
    panelTop.add("Center", panelMain);
    setBackground(new Color (30,210,242));
    add(panelTop);

    //---------
    }
    public void mousePressed(MouseEvent evt) {
    if (dragging)
    return;
    int x = evt.getX();
    int y = evt.getY();
    if (x >= xa && y >= yb ) {
    dragging = true;
    dragRedSquare = true;
    offsetX = x - xa;
    offsetY = y - yb;
    }

    System.out.println("PRESSED");

    this.update(this.getGraphics());
    }
    public void mouseReleased(MouseEvent evt) {
    dragging = false;
    System.out.println("released");

    this.update(this.getGraphics());
    }
    public void mouseDragged(MouseEvent evt) {
    if (dragging == false)
    return;
    int x = evt.getX();
    int y = evt.getY();
    if (dragRedSquare) {
    xa = x - offsetX;
    yb = y - offsetY;
    }
    System.out.println("dragged");

    this.update(this.getGraphics());
    }
    public void mouseMoved(MouseEvent evt) { }
    public void mouseClicked(MouseEvent evt) { }
    public void mouseEntered(MouseEvent evt) { }
    public void mouseExited(MouseEvent evt) { }
    //-------
    class buttonAL implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand() == "Demarrer!") {
    labelBestPath.setBackground(Color.blue);
    int n = Integer.parseInt( textRounds.getText() );
    int next_nbr_round=n+1;
    String nouv_round="";
    averages = new double[n];
    for(int i = 0; i < n; i++)
    averages[i] = myColony.runOneCycle();
    labelBestPath.setBackground(Color.yellow);
    AgentFourmi = true;
    labelBestPath.setText( Double.toString(
    Math.rint( myColony.bestLength*10000 ) / 10000) );
    paint(getGraphics());
    }

    if (e.getActionCommand() == "Generer") {
    myTsp = new tsp();
    long t = (new Date()).getTime();

    myTsp.GenererNoeud(Integer.parseInt(textNoeud.getText()), t);
    myColony = new colony(Integer.parseInt(textAnt.getText()),1,1,myTsp);
    NoeudVisitee = true;
    paint(getGraphics());
    buttonGo.setEnabled(true);

    }



    }
    }
    public void paint (Graphics g2) {

    super.paintComponents(g2);
    Graphics2D g = (Graphics2D)g2;
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    addMouseListener(this);
    addMouseMotionListener(this);
    int w = getSize().width,h = getSize().height;

    g.fillRect(0, 0, w, h);
    if (!NoeudVisitee) return;
    int n = myTsp.getNbreN();
    g.setColor(Color.red);
    for(int i = 0; i < n; i++) {g.drawImage(ord,(int)(myTsp.Noeud[i].x * w - 1),(int)(myTsp.Noeud[i].y * h - 1),this);}
    System.out.println("on repeint le panel");

    if (QtePhero) {
    double minV = Double.MAX_VALUE, maxV = Double.MIN_VALUE;
    for(int i = 0; i < n-1; i++)
    for(int j = i+1; j < n; j++) {
    if (minV > myColony.phMat[i][j])
    minV = myColony.phMat[i][j];
    if (maxV < myColony.phMat[i][j])
    maxV = myColony.phMat[i][j];
    }
    double s = maxV - minV;
    for(int i = 0; i < n-1; i++)
    for(int j = i+1; j < n; j++) {
    float t = (float)((myColony.phMat[i][j] - minV) / s);
    g.setColor(new Color(t, t, t));
    int x1 = (int)(myTsp.Noeud[i].x * w);
    int y1 = (int)(myTsp.Noeud[i].y * h);
    int x2 = (int)(myTsp.Noeud[j].x * w);
    int y2 = (int)(myTsp.Noeud[j].y * h);
    g.drawLine(x1, y1, x2, y2);
    }
    g.setColor(Color.yellow);

    for(int i = 0; i < n; i++) {g.drawImage(ord,(int)(myTsp.Noeud[i].x * w - 1),(int)(myTsp.Noeud[i].y * h - 1),this);}
    repaint();
    return;
    }
    if (!AgentFourmi) return;
    g.setColor(Color.white);
    for(int i = 0; i < n - 1; i++) {
    int c1 = myColony.bestPath[i];
    int c2 = myColony.bestPath[i+1];
    int x1 = (int)(myTsp.Noeud[c1].x * w);
    int y1 = (int)(myTsp.Noeud[c1].y * h);
    int x2 = (int)(myTsp.Noeud[c2].x * w);
    int y2 = (int)(myTsp.Noeud[c2].y * h);
    g.drawLine(x1, y1, x2, y2);
    }
    int c1 = myColony.bestPath[n-1];
    int c2 = myColony.bestPath[0];
    int x1 = (int)(myTsp.Noeud[c1].x * w);
    int y1 = (int)(myTsp.Noeud[c1].y * h);
    int x2 = (int)(myTsp.Noeud[c2].x * w);
    int y2 = (int)(myTsp.Noeud[c2].y * h);
    g.drawLine(x1, y1, x2, y2);

    }
    public void update(Graphics g2) // to stop refresh flickering
    {
    paint(g2);
    }


    }


    //______


    class tsp {

    int NbreN; // nombre des noeuds
    public node Noeud[]; // tableau contenant les noeuds de type node
    double distMat[][]; // distance entre les noeuds (matrice)
    public int getNbreN() { return NbreN; }

    //**** classe caractérise un noeud****
    public class node {


    double x, y; // x est l'absisse du noeud, y est l'ordonné

    public node(double a, double b) { x = a; y = b; }
    public void setX(double t) { x = t; }
    public void setY(double t) { y = t; }
    public double getX() { return x; }
    public double getY() { return y; }


    }


    // générer un ensemble des noeuds aléatoir

    public void GenererNoeud(int n, long s) {
    NbreN = n;
    Random r = new Random(s);
    Noeud = new node[n];
    for(int i = 0; i < n; i++) {
    Noeud[i] = new node(r.nextDouble(), r.nextDouble());

    }
    determineDistMat();


    }


    // ***calculer la distance entre 2 points***
    public double dist(int i, int j) {
    double t1 = Noeud[i].getX() - Noeud[j].getX(),
    t2 = Noeud[i].getY() - Noeud[j].getY();
    return Math.sqrt(t1*t1 + t2*t2);
    }

    // ***créer la matrice qui contient les distances entre les noeuds***
    public void determineDistMat() {
    distMat = new double[NbreN][NbreN];
    for(int i = 0; i < NbreN; i++)
    for(int j = i; j < NbreN; j++) {
    distMat[i][j] = dist(i, j);
    distMat[j][i] = dist(j, i);
    }
    }



    //----------------------------------------
    public double pathLength(int p[]) {// longeur de chemin

    double t = 0;
    for(int i = 0; i < NbreN - 1; i++)
    t += dist(p[i], p[i+1]);
    t += dist(p[NbreN-1], p[0]);
    return t;
    }
    //----------------------------------------
    public double getDist(int i, int j) {
    return distMat[i][j];
    }
    }

    class colony {
    public double phMat[][];
    double phAmt; // pheromone sur les arcs

    public int controlAnt;
    public int bestPath[];
    public double bestLength;

    public ant myAnts[];
    tsp myTsp;
    int na; // nombre de Fourmis
    double vRate; // taux de vaporisation
    Random rg;

    //**** calsse Fourmi*****
    class ant {
    public int path[], mark[]; // caractèristique du fourmi tableau liste des noeud visité,path = les chemins
    int noeudActuel;
    double traveledLength;
    public String ListeVisite[];

    // *****constructeur de la classe ant*****
    public ant(int n) {
    mark = new int[n];
    path = new int[n];
    ListeVisite= new String[n];
    }
    //*******fin de constructeur*****

    public double calculateTraveledLength()
    {
    traveledLength = myTsp.pathLength(path);
    return traveledLength;
    }

    public double getTraveledLength()
    { return traveledLength; }



    public void reset() {
    noeudActuel =0;
    path[0] = 0; // commencer au noeud[0]
    for(int i = 0; i < myTsp.getNbreN(); i++)
    mark[i] = 0;
    mark[0] = 1; // noeud[0]a été visitée
    }

    //----------------------------------------
    public void determineNextNoeud() {
    int n = myTsp.getNbreN();
    int countCandi = 0;// compteur
    double alpha=0.5 , beta=0.3;
    int[] candidate = new int[n];
    double[] prCandi = new double[n];
    for(int i = 0; i < n; i++) {
    if (mark[i] == 0) {
    candidate[countCandi] = i;// tableau des noeud non visité

    prCandi[countCandi] = Math.pow(phMat[ path[noeudActuel] ][i],alpha) /
    Math.pow(myTsp.getDist( path[noeudActuel], i ),beta);
    ++countCandi;// compteur des noeuds non visités
    }
    }

    double s = 0;
    for(int i = 0; i < countCandi; i++)
    s += prCandi[i];
    for(int i = 0; i < countCandi; i++)
    prCandi[i] /= s;
    // probabilité à choi

    double hit = rg.nextDouble(),
    t = prCandi[0];
    int w = 0;
    for(w = 0; w < countCandi - 1; w++) {
    if (t > hit) break;
    t += prCandi[w + 1];
    }
    ++noeudActuel;
    path[noeudActuel] = candidate[w];
    mark[ candidate[w] ] = 1;
    }
    }
    //******fin de la classe Fourmi*******

    // constructeur de la classe colony
    public colony(int n, double t, double p, tsp s) {
    na = n; //nombre des Fourmi
    vRate = t;
    phAmt = p;
    myTsp = s;
    bestLength = Double.MAX_VALUE;

    bestPath = new int[myTsp.getNbreN()];
    phMat = new double[myTsp.getNbreN()][myTsp.getNbreN()];
    myAnts = new ant[n];
    rg = new Random();
    for(int i = 0; i < n; i++)
    myAnts[i] = new ant(myTsp.getNbreN());
    for(int i = 0; i < myTsp.getNbreN(); i++)
    for(int j = 0; j < myTsp.getNbreN(); j++) {
    phMat[i][j] = 1;
    phMat[j][i] = 1;
    }
    }
    //----------------------------------------
    public void runOneAnt(int x) {
    int i=0 , j=0 ;
    myAnts[x].reset();
    if (myTsp.distMat[i][j] < 2) // condition ne fonctionne pas !!
    {for(int k = 0; k < myTsp.getNbreN() - 1; k++)
    myAnts[x].determineNextNoeud();

    myAnts[x].calculateTraveledLength();
    }}
    //----------------------------------------
    public double runOneCycle() {
    for(int i = 0; i < na; i++)
    runOneAnt(i);
    return updatePhMat();
    }
    //----------------------------------------
    public double updatePhMat() {
    int n = Array.getLength( myAnts );
    int m = myTsp.getNbreN();

    controlAnt = -1;

    for(int j = 0; j < myTsp.getNbreN(); j++)
    for(int k = 0; k < myTsp.getNbreN(); k++)
    phMat[j][k] *= vRate;

    for(int i = 0; i < n; i++) {
    double t = myAnts[i].getTraveledLength();

    if (t < bestLength) {
    controlAnt = i;// plusieur Fourmi
    bestLength = t;
    for(int j = 0; j < m; j++)
    bestPath[j] = myAnts[i].path[j];
    }

    for(int j = 0; j < m - 1; j++) {
    phMat[ myAnts[i].path[j] ][ myAnts[i].path[j+1] ] += phAmt / t;
    phMat[ myAnts[i].path[j+1] ][ myAnts[i].path[j] ] += phAmt / t;
    }

    }





    return bestLength;

    }
    }
    • Partager sur Facebook
    • Partager sur Twitter
      21 mai 2012 à 12:30:01

      Le message qui suit est une réponse automatique.
      Les réponses automatiques nous permettent d'éviter de répéter de nombreuses fois la même chose, et donc de gagner beaucoup de temps.
      Nous sommes néanmoins ouvert à toute question ou remarque, n'hésite pas à me contacter par messagerie privée à ce sujet.


      Merci d'utiliser les balises de code


      Bonjour,

      Les forums du Site du Zéro disposent d'une fonctionnalité permettant de colorer et mettre en forme les codes source.
      Tu as posté un code source sans utiliser cette fonctionnalité. Pourrais-tu éditer ton message afin d'ajouter ces balises ? Pour cela, sélectionne ton code à colorer et utilise le bouton Image utilisateur afin de choisir la coloration adaptée. Veille à bien choisir le langage de programmation afin que la coloration soit pertinente.

      De plus, veille à ce que ton code soit correctement indenté.

      Afin de ne pas surcharger le sujet, ne poste pas ton code coloré dans un nouveau message mais édite le premier (grâce au bouton Image utilisateur).

      Cela aura pour effet de "colorer" ton code et donc d'en faciliter grandement la lecture. Tu auras ainsi beaucoup plus de chances d'avoir des réponses.

      Voici un exemple de code non coloré (mauvais exemple) :
      int main(int argc, char *argv[])
      {
      long choixOperation;

      printf("Choisissez l'operation a effectuer");
      /* etc. */
      }

      Voici maintenant le même code coloré, utilisant la balise "code" (bon exemple) :
      int main(int argc, char *argv[])
      {
          long choixOperation;
      
          printf("Choisissez l'operation a effectuer");
          /* etc. */
      }
      


      C'est plus clair n'est-ce pas ? ;)

      Pour plus d'information à ce sujet, tu peux lire le tutoriel général sur le zCode.

      Merci de ta compréhension. :)
      • Partager sur Facebook
      • Partager sur Twitter
      Si vous voulez me retrouver, rendez-vous sur ZesteDeSavoir.
        21 mai 2012 à 12:41:43

        import java.applet.*;
        import java.io.*;
        import java.awt.*;
        import java.awt.event.*;
        import java.lang.reflect.*;
        import java.util.*;
        import java.applet.Applet ;
        
        import java.awt.BorderLayout;
        import java.awt.Graphics;
        import java.awt.event.MouseEvent;
        import java.awt.event.MouseListener;
        import java.awt.event.MouseMotionListener;
        
        import javax.swing.JFrame;
        import javax.swing.JLabel;
        import javax.swing.SwingConstants;
        public class essai extends Applet
        implements MouseListener, MouseMotionListener {
        
        int xa, yb;
        boolean dragging;
        boolean dragRedSquare;
        int offsetX, offsetY;
        
        
        //-------
        boolean NoeudVisitee,AgentFourmi,QtePhero;
        String sauv_res_cycl="nombre de cycle bonne chemain\n";
        tsp myTsp;
        colony myColony;
        double averages[];
        
        TextField textNoeud,
        textAlpha,
        textBeta,
        textAnt,
        textVrate,
        textAmount,
        textRounds;
        
        Label labelBestPath;
        Button buttonGenerate,buttonGo;
        
        Image ord;
        
        public void init() {
        
        
        xa = 10;
        yb = 10;
        setBackground(Color.lightGray);
        addMouseListener(this);
        addMouseMotionListener(this);
        
        //---------
        NoeudVisitee = false;
        AgentFourmi = false;
        QtePhero = false;
        MediaTracker mt= new MediaTracker(this);
        ord = getImage(getCodeBase(),"ord1.jpg");
        mt.addImage(ord,0);
        Panel stat_cyc=new Panel();
        Panel panelRight = new Panel(new GridLayout(15, 2, 4, 4));
        BorderLayout bl = new BorderLayout();
        bl.setVgap(4);
        Panel panelLeft = new Panel(bl);
        Label labelNoeud = new Label("Noeud", Label.RIGHT);
        Label labelAnt = new Label("Fourmi", Label.RIGHT);
        Label labelVrate = new Label("Evaporation", Label.RIGHT);
        Label labelAmount = new Label("Pheromone", Label.RIGHT);
        Label labelRounds = new Label("Cycle", Label.RIGHT);
        Label labelAlpha = new Label("Alpha", Label.RIGHT);
        Label labelBeta = new Label("Beta", Label.RIGHT);
        labelBestPath = new Label("0.0", Label.CENTER);
        labelBestPath.setBackground(Color.red);
        textNoeud = new TextField("5", 6);
        textAnt = new TextField("1", 6);
        textVrate = new TextField("0.5", 6);
        textAmount = new TextField("1", 6);
        textRounds = new TextField("40", 6);
        textAlpha = new TextField("1", 6);
        textBeta = new TextField("5", 6);
        buttonGenerate = new Button("Generer");
        buttonGo = new Button("Demarrer!");
        buttonGo.setEnabled(false);
        buttonGenerate.addActionListener(new buttonAL());
        buttonGo.addActionListener(new buttonAL());
        panelRight.add(labelNoeud); panelRight.add(textNoeud);
        panelRight.add(labelAnt);	 panelRight.add(textAnt);
        panelRight.add(labelVrate);	 panelRight.add(textVrate);
        panelRight.add(labelAmount);	 panelRight.add(textAmount);
        panelRight.add(labelRounds);	 panelRight.add(textRounds);
        panelRight.add(labelAlpha); panelRight.add(textAlpha);
        panelRight.add(labelBeta); panelRight.add(textBeta);
        panelRight.add(new Label()); panelRight.add(buttonGenerate);
        panelRight.add(new Label()); panelRight.add(buttonGo);
        panelRight.add(new Label("MeilleurTrajet", Label.RIGHT));
        panelRight.add(labelBestPath);
        
        Panel panelMain = new Panel();
        panelMain.add(panelLeft);
        panelMain.add(panelRight);
        Panel panelTop = new Panel(new BorderLayout());
        panelTop.add("Center", panelMain);
        setBackground(new Color (30,210,242));
        add(panelTop);
        
        //---------
        }
        public void mousePressed(MouseEvent evt) {
        if (dragging)
        return;
        int x = evt.getX();
        int y = evt.getY();
        if (x >= xa && y >= yb ) {
        dragging = true;
        dragRedSquare = true;
        offsetX = x - xa;
        offsetY = y - yb;
        }
        
        System.out.println("PRESSED");
        
        this.update(this.getGraphics());
        }
        public void mouseReleased(MouseEvent evt) {
        dragging = false;
        System.out.println("released");
        
        this.update(this.getGraphics());
        }
        public void mouseDragged(MouseEvent evt) {
        if (dragging == false)
        return;
        int x = evt.getX();
        int y = evt.getY();
        if (dragRedSquare) {
        xa = x - offsetX;
        yb = y - offsetY;
        }
        System.out.println("dragged");
        
        this.update(this.getGraphics());
        }
        public void mouseMoved(MouseEvent evt) { }
        public void mouseClicked(MouseEvent evt) { }
        public void mouseEntered(MouseEvent evt) { }
        public void mouseExited(MouseEvent evt) { }
        //-------
        class buttonAL implements ActionListener {
        public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand() == "Demarrer!") {
        labelBestPath.setBackground(Color.blue);
        int n = Integer.parseInt( textRounds.getText() );
        int next_nbr_round=n+1;
        String nouv_round="";
        averages = new double[n];
        for(int i = 0; i < n; i++)
        averages[i] = myColony.runOneCycle();
        labelBestPath.setBackground(Color.yellow);
        AgentFourmi = true;
        labelBestPath.setText( Double.toString(
        Math.rint( myColony.bestLength*10000 ) / 10000) );
        paint(getGraphics());
        }
        
        if (e.getActionCommand() == "Generer") {
        myTsp = new tsp();
        long t = (new Date()).getTime();
        
        myTsp.GenererNoeud(Integer.parseInt(textNoeud.getText()), t);
        myColony = new colony(Integer.parseInt(textAnt.getText()),1,1,myTsp);
        NoeudVisitee = true;
        paint(getGraphics());
        buttonGo.setEnabled(true);
        
        }
        
        
        
        }
        }
        public void paint (Graphics g2) {
        
        super.paintComponents(g2);
        Graphics2D g = (Graphics2D)g2;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
        addMouseListener(this);
        addMouseMotionListener(this);
        int w = getSize().width,h = getSize().height;
        
        g.fillRect(0, 0, w, h);
        if (!NoeudVisitee) return;
        int n = myTsp.getNbreN();
        g.setColor(Color.red);
        for(int i = 0; i < n; i++) {g.drawImage(ord,(int)(myTsp.Noeud[i].x * w - 1),(int)(myTsp.Noeud[i].y * h - 1),this);}
        System.out.println("on repeint le panel");
        
        if (QtePhero) {
        double minV = Double.MAX_VALUE, maxV = Double.MIN_VALUE;
        for(int i = 0; i < n-1; i++)
        for(int j = i+1; j < n; j++) {
        if (minV > myColony.phMat[i][j])
        minV = myColony.phMat[i][j];
        if (maxV < myColony.phMat[i][j])
        maxV = myColony.phMat[i][j];
        }
        double s = maxV - minV;
        for(int i = 0; i < n-1; i++)
        for(int j = i+1; j < n; j++) {
        float t = (float)((myColony.phMat[i][j] - minV) / s);
        g.setColor(new Color(t, t, t));
        int x1 = (int)(myTsp.Noeud[i].x * w);
        int y1 = (int)(myTsp.Noeud[i].y * h);
        int x2 = (int)(myTsp.Noeud[j].x * w);
        int y2 = (int)(myTsp.Noeud[j].y * h);
        g.drawLine(x1, y1, x2, y2);
        }
        g.setColor(Color.yellow);
        
        for(int i = 0; i < n; i++) {g.drawImage(ord,(int)(myTsp.Noeud[i].x * w - 1),(int)(myTsp.Noeud[i].y * h - 1),this);}
        repaint();
        return;
        }
        if (!AgentFourmi) return;
        g.setColor(Color.white);
        for(int i = 0; i < n - 1; i++) {
        int c1 = myColony.bestPath[i];
        int c2 = myColony.bestPath[i+1];
        int x1 = (int)(myTsp.Noeud[c1].x * w);
        int y1 = (int)(myTsp.Noeud[c1].y * h);
        int x2 = (int)(myTsp.Noeud[c2].x * w);
        int y2 = (int)(myTsp.Noeud[c2].y * h);
        g.drawLine(x1, y1, x2, y2);
        }
        int c1 = myColony.bestPath[n-1];
        int c2 = myColony.bestPath[0];
        int x1 = (int)(myTsp.Noeud[c1].x * w);
        int y1 = (int)(myTsp.Noeud[c1].y * h);
        int x2 = (int)(myTsp.Noeud[c2].x * w);
        int y2 = (int)(myTsp.Noeud[c2].y * h);
        g.drawLine(x1, y1, x2, y2);
        
        }
        public void update(Graphics g2) // to stop refresh flickering
        {
        paint(g2);
        }
        
        
        } 
        
        
        //______
        
        
        class tsp {
        
        int NbreN; // nombre des noeuds
        public node Noeud[]; // tableau contenant les noeuds de type node
        double distMat[][]; // distance entre les noeuds (matrice)
        public int getNbreN() { return NbreN; }
        
        //**** classe caractérise un noeud****
        public class node {
        
        
        double x, y; // x est l'absisse du noeud, y est l'ordonné
        
        public node(double a, double b) { x = a; y = b; }
        public void setX(double t) { x = t; }
        public void setY(double t) { y = t; }
        public double getX() { return x; }
        public double getY() { return y; }
        
        
        }
        
        
        // générer un ensemble des noeuds aléatoir
        
        public void GenererNoeud(int n, long s) {
        NbreN = n;
        Random r = new Random(s);
        Noeud = new node[n];
        for(int i = 0; i < n; i++) {
        Noeud[i] = new node(r.nextDouble(), r.nextDouble());
        
        }
        determineDistMat();
        
        
        }
        
        
        // ***calculer la distance entre 2 points***
        public double dist(int i, int j) {
        double t1 = Noeud[i].getX() - Noeud[j].getX(),
        t2 = Noeud[i].getY() - Noeud[j].getY();
        return Math.sqrt(t1*t1 + t2*t2);
        }
        
        // ***créer la matrice qui contient les distances entre les noeuds***
        public void determineDistMat() {
        distMat = new double[NbreN][NbreN];
        for(int i = 0; i < NbreN; i++)
        for(int j = i; j < NbreN; j++) {
        distMat[i][j] = dist(i, j);
        distMat[j][i] = dist(j, i);
        }
        }
        
        
        
        //----------------------------------------
        public double pathLength(int p[]) {// longeur de chemin
        
        double t = 0;
        for(int i = 0; i < NbreN - 1; i++)
        t += dist(p[i], p[i+1]);
        t += dist(p[NbreN-1], p[0]);
        return t;
        }
        //----------------------------------------
        public double getDist(int i, int j) {
        return distMat[i][j];
        }
        }
        
        class colony {
        public double phMat[][];
        double phAmt; // pheromone sur les arcs
        
        public int controlAnt;
        public int bestPath[];
        public double bestLength;
        
        public ant myAnts[];
        tsp myTsp;
        int na; // nombre de Fourmis
        double vRate; // taux de vaporisation
        Random rg;
        
        //**** calsse Fourmi*****
        class	ant {
        public int path[], mark[]; // caractèristique du fourmi tableau liste des noeud visité,path = les chemins
        int noeudActuel;
        double traveledLength;
        public String ListeVisite[];
        
        // *****constructeur de la classe ant*****
        public ant(int n) {
        mark = new int[n];
        path = new int[n];
        ListeVisite= new String[n];
        }
        //*******fin de constructeur*****
        
        public double calculateTraveledLength()
        {
        traveledLength = myTsp.pathLength(path);
        return traveledLength;
        }
        
        public double getTraveledLength()
        { return traveledLength; }
        
        
        
        public void reset() {
        noeudActuel =0;
        path[0] = 0; // commencer au noeud[0]
        for(int i = 0; i < myTsp.getNbreN(); i++)
        mark[i] = 0;
        mark[0] = 1; // noeud[0]a été visitée
        }
        
        //----------------------------------------
        public void determineNextNoeud() {
        int n = myTsp.getNbreN();
        int countCandi = 0;// compteur
        double alpha=0.5 , beta=0.3;
        int[] candidate = new int[n];
        double[] prCandi = new double[n];
        for(int i = 0; i < n; i++) {
        if (mark[i] == 0) {
        candidate[countCandi] = i;// tableau des noeud non visité
        
        prCandi[countCandi] = Math.pow(phMat[ path[noeudActuel] ][i],alpha) /
        Math.pow(myTsp.getDist( path[noeudActuel], i ),beta);
        ++countCandi;// compteur des noeuds non visités
        }
        }
        
        double s = 0;
        for(int i = 0; i < countCandi; i++)
        s += prCandi[i];
        for(int i = 0; i < countCandi; i++)
        prCandi[i] /= s;
        // probabilité à choi
        
        double hit = rg.nextDouble(),
        t = prCandi[0];
        int w = 0;
        for(w = 0; w < countCandi - 1; w++) {
        if (t > hit) break;
        t += prCandi[w + 1];
        }
        ++noeudActuel;
        path[noeudActuel] = candidate[w];
        mark[ candidate[w] ] = 1;
        }
        }
        //******fin de la classe Fourmi*******
        
        // constructeur de la classe colony
        public colony(int n, double t, double p, tsp s) {
        na = n; //nombre des Fourmi
        vRate = t;
        phAmt = p;
        myTsp = s;
        bestLength = Double.MAX_VALUE;
        
        bestPath = new int[myTsp.getNbreN()];
        phMat = new double[myTsp.getNbreN()][myTsp.getNbreN()];
        myAnts = new ant[n];
        rg = new Random();
        for(int i = 0; i < n; i++)
        myAnts[i] = new ant(myTsp.getNbreN());
        for(int i = 0; i < myTsp.getNbreN(); i++)
        for(int j = 0; j < myTsp.getNbreN(); j++) {
        phMat[i][j] = 1;
        phMat[j][i] = 1;
        }
        }
        //----------------------------------------
        public void runOneAnt(int x) {
        int i=0 , j=0 ;
        myAnts[x].reset();
        if (myTsp.distMat[i][j] < 2) // condition ne fonctionne pas !!
        {for(int k = 0; k < myTsp.getNbreN() - 1; k++)
        myAnts[x].determineNextNoeud();
        
        myAnts[x].calculateTraveledLength();
        }}
        //----------------------------------------
        public double runOneCycle() {
        for(int i = 0; i < na; i++)
        runOneAnt(i);
        return updatePhMat();
        }
        //----------------------------------------
        public double updatePhMat() {
        int n = Array.getLength( myAnts );
        int m = myTsp.getNbreN();
        
        controlAnt = -1;
        
        for(int j = 0; j < myTsp.getNbreN(); j++)
        for(int k = 0; k < myTsp.getNbreN(); k++)
        phMat[j][k] *= vRate;
        
        for(int i = 0; i < n; i++) {
        double t = myAnts[i].getTraveledLength();
        
        if (t < bestLength) {
        controlAnt = i;// plusieur Fourmi
        bestLength = t;
        for(int j = 0; j < m; j++)
        bestPath[j] = myAnts[i].path[j];
        }
        
        for(int j = 0; j < m - 1; j++) {
        phMat[ myAnts[i].path[j] ][ myAnts[i].path[j+1] ] += phAmt / t;
        phMat[ myAnts[i].path[j+1] ][ myAnts[i].path[j] ] += phAmt / t;
        }
        
        }
        
        
        
        
        
        return bestLength;
        
        }
        }
        




        désolée c'est la première foi que j'ai posté dans ce Forum :D
        • Partager sur Facebook
        • Partager sur Twitter

        applet java : draw image dans une boucle !!!

        × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
        × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
        • Editeur
        • Markdown