IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

AWT/Swing Java Discussion :

4 thread = lag affichage


Sujet :

AWT/Swing Java

  1. #1
    Membre expérimenté Avatar de Ivelios
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juillet 2008
    Messages
    1 031
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Ain (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 031
    Points : 1 540
    Points
    1 540
    Par défaut 4 thread = lag affichage
    Bonjour à tous,
    Je développe actuellement un bomberman en JAVA.
    Jusqu'alors, je n'affichais que 2 joueurs dans mon jeu.
    Mais arrivant dans les phases terminales, j'ai décidé hier d'en mettre 4 et là... c'est le drame.
    Le jeu commence à bien ramer

    Pour ne pas vous surcharger du code de mon jeu, j'ai réalisé ce petit programme qui résume parfaitement mon problème :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import test.Joueur.*;
     
    /**
     *
     * @author Ivelios
     */
    public class Affichage extends JPanel implements KeyListener{
     
        private Joueur joueur1, joueur2, joueur3, joueur4;
     
        //Constructeur
        public Affichage(){
            joueur1 = new Joueur(this);
            joueur2 = new Joueur(this);
            joueur3 = new Joueur(this);
            joueur4 = new Joueur(this);
     
            new Thread(joueur1).start();
            new Thread(joueur2).start();
            new Thread(joueur3).start();
            new Thread(joueur4).start();
     
            this.setFocusable(true);
            this.addKeyListener(this);
        }
     
        /************* Affichage ****************/
         public void paintComponent(Graphics g) {
             //fond
             g.setColor(Color.WHITE);g.fillRect(0,0, 400, 400);
     
             //Joueurs
             g.setColor(Color.BLUE);g.fillOval(joueur1.getPosX(), joueur1.getPosY(), 40, 40);
             g.setColor(Color.ORANGE);g.fillOval(joueur2.getPosX(), joueur2.getPosY(), 40, 40);
             g.setColor(Color.BLACK);g.fillOval(joueur3.getPosX(), joueur3.getPosY(), 40, 40);
             g.setColor(Color.RED);g.fillOval(joueur4.getPosX(), joueur4.getPosY(), 40, 40);
         }
     
     
     
     
     
        /************ Gestion de l'appuie sur une touche ************************/
     
        public void keyTyped(KeyEvent e) {}
     
        public void keyPressed(KeyEvent e) {
            int touche = e.getKeyCode();
     
            this.appuieTouche(90,81,83,68,touche,joueur1);//zqsd
            this.appuieTouche(38,37,40,39,touche,joueur2);//fleches directionnelles
            this.appuieTouche(85,72,74,75,touche,joueur3);//uhjk
            this.appuieTouche(104,100,101,102,touche,joueur4);//8456
        }
     
        public void keyReleased(KeyEvent e) {
            int touche = e.getKeyCode();
     
            this.relacherTouche(90,81,83,68,touche,joueur1);//zqsd
            this.relacherTouche(38,37,40,39,touche,joueur2);//fleches directionnelles
            this.relacherTouche(85,72,74,75,touche,joueur3);//uhjk
            this.relacherTouche(104,100,101,102,touche,joueur4);//8456
        }
     
     
        private void appuieTouche(int haut,int gauche,int bas,int droite,int touche,Joueur j){
            if(touche == gauche){ j.setDx( DEPLACEMENT_X.GAUCHE );}
            else if(touche == droite){ j.setDx( DEPLACEMENT_X.DROITE );}
            else if(touche == haut){j.setDy( DEPLACEMENT_Y.HAUT );}
            else if(touche == bas){j.setDy( DEPLACEMENT_Y.BAS ); }
        }
     
     
     
        private void relacherTouche(int haut,int gauche,int bas,int droite,int touche,Joueur j){
               if( (touche == haut && j.getDy() == DEPLACEMENT_Y.HAUT) || (touche == bas && j.getDy() == DEPLACEMENT_Y.BAS) ){
                  j.setDy( DEPLACEMENT_Y.RIEN );
               }else if( (touche == gauche && j.getDx() == DEPLACEMENT_X.GAUCHE) || (touche == droite && j.getDx() == DEPLACEMENT_X.DROITE) ){
                  j.setDx( DEPLACEMENT_X.RIEN );
               }
        }
     
        /******************** Lanceur ******************************/
        public static void main(String[] args){
            JFrame f = new JFrame("Test");
            f.setSize(400,400);
            f.setLocationRelativeTo(null);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Affichage panel = new Affichage();
            f.add(panel,BorderLayout.CENTER);
            f.setVisible(true);
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    /**
     *
     * @author Ivelios
     */
    public class Joueur implements Runnable{
     
        public enum DEPLACEMENT_X { GAUCHE, RIEN, DROITE };
        public enum DEPLACEMENT_Y { HAUT, RIEN, BAS };
     
        private DEPLACEMENT_X dx;//Déplacement horizontal du joueur
        private DEPLACEMENT_Y dy;//Déplacement verticale du jour
        private int posX, posY;//Position du personnage
        private Affichage panel;
     
        //Constructeur
        public Joueur(Affichage panel){
            this.panel = panel;
            this.posX = 0;
            this.posY = 0;
        }
     
     
        //Accesseurs
        public DEPLACEMENT_X getDx(){return dx;}
        public DEPLACEMENT_Y getDy(){return dy;}
        public int getPosX(){return posX;}
        public int getPosY(){return posY;}
     
        //Modificateurs
        public void setPosX(int posX){this.posX = posX;}
        public void setPosY(int posY){this.posY = posY;}
        public void setDx( DEPLACEMENT_X dx ) { this.dx = dx; }
        public void setDy( DEPLACEMENT_Y dy ) { this.dy = dy; }
     
     
        public void run() {
            while(true){
                if( dx == DEPLACEMENT_X.GAUCHE ){//Déplacement gauche
                    try {
                        Thread.sleep(10);
                        posX--;
                        panel.repaint();
                    }catch( InterruptedException exc ) {}
     
                }else if( dx == DEPLACEMENT_X.DROITE ){//Déplacement droite
                    try {
                        Thread.sleep(10);
                        posX++;
                        panel.repaint();
                    }catch( InterruptedException exc ) {}
     
                }
     
                if( dy == DEPLACEMENT_Y.HAUT ){//Déplacement haut
                    try {
                        Thread.sleep(10);
                        posY--;
                        panel.repaint();
                    }catch( InterruptedException exc ) {}
     
                } else if( dy == DEPLACEMENT_Y.BAS ){//Déplacement bas
                    try {
                        Thread.sleep(10);
                        posY++;
                        panel.repaint();
                    }catch( InterruptedException exc ) {}
     
               }
            }
        }
    }
    Pour finir, ma question : Peut on supprimer ce lag?... et comment bien sûre ?
    Il était une fois [...] Et ils vécurent heureux et eurent beaucoup d'enfants!

  2. #2
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    Ouais, en utilisant un seul thread (ou un seul timer swing) qui recalcule les positions de tous les joueurs toutes les x millisecondes.
    Le reste se passe via des variables stockant les actions de chaque joueur et basta.

    Un thread par joueur c'est un peu bourrin comme méthode.Car là avec 4 threads tu lances des demandes de repaint dans tous les sens...
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  3. #3
    Membre expérimenté Avatar de Ivelios
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juillet 2008
    Messages
    1 031
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Ain (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 031
    Points : 1 540
    Points
    1 540
    Par défaut
    [...] et basta
    Effectivement, dit comme ça
    ça marche nickel maintenant.
    Mes joueurs ne font plus office de Thread mais stockent juste les positions.
    Et j'ai rajouté une classe déplacement qui repaint() tous les 10 ms en reprenant les positions des joueurs.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    90
    91
    92
    93
    94
    95
    96
    97
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import test.Joueur.*;
     
    /**
     *
     * @author Ivelios
     */
    public class Affichage extends JPanel implements KeyListener{
     
        private Joueur joueur1, joueur2, joueur3, joueur4;
     
        //Constructeur
        public Affichage(){
            joueur1 = new Joueur();
            joueur2 = new Joueur();
            joueur3 = new Joueur();
            joueur4 = new Joueur();
     
            new Thread(new Deplacement(joueur1,joueur2,joueur3,joueur4,this)).start();
     
            this.setFocusable(true);
            this.addKeyListener(this);
        }
     
        /************* Affichage ****************/
         public void paintComponent(Graphics g) {
             //fond
             g.setColor(Color.WHITE);g.fillRect(0,0, 400, 400);
     
             //Joueurs
             g.setColor(Color.BLUE);g.fillOval(joueur1.getPosX(), joueur1.getPosY(), 40, 40);
             g.setColor(Color.ORANGE);g.fillOval(joueur2.getPosX(), joueur2.getPosY(), 40, 40);
             g.setColor(Color.BLACK);g.fillOval(joueur3.getPosX(), joueur3.getPosY(), 40, 40);
             g.setColor(Color.RED);g.fillOval(joueur4.getPosX(), joueur4.getPosY(), 40, 40);
         }
     
     
     
     
     
        /************ Gestion de l'appuie sur une touche ************************/
     
        public void keyTyped(KeyEvent e) {}
     
        public void keyPressed(KeyEvent e) {
            int touche = e.getKeyCode();
     
            this.appuieTouche(90,81,83,68,touche,joueur1);//zqsd
            this.appuieTouche(38,37,40,39,touche,joueur2);//fleches directionnelles
            this.appuieTouche(85,72,74,75,touche,joueur3);//uhjk
            this.appuieTouche(104,100,101,102,touche,joueur4);//8456
        }
     
        public void keyReleased(KeyEvent e) {
            int touche = e.getKeyCode();
     
            this.relacherTouche(90,81,83,68,touche,joueur1);//zqsd
            this.relacherTouche(38,37,40,39,touche,joueur2);//fleches directionnelles
            this.relacherTouche(85,72,74,75,touche,joueur3);//uhjk
            this.relacherTouche(104,100,101,102,touche,joueur4);//8456
        }
     
     
        private void appuieTouche(int haut,int gauche,int bas,int droite,int touche,Joueur j){
            if(touche == gauche){ j.setDx( DEPLACEMENT_X.GAUCHE );}
            else if(touche == droite){ j.setDx( DEPLACEMENT_X.DROITE );}
            else if(touche == haut){j.setDy( DEPLACEMENT_Y.HAUT );}
            else if(touche == bas){j.setDy( DEPLACEMENT_Y.BAS ); }
        }
     
     
     
        private void relacherTouche(int haut,int gauche,int bas,int droite,int touche,Joueur j){
               if( (touche == haut && j.getDy() == DEPLACEMENT_Y.HAUT) || (touche == bas && j.getDy() == DEPLACEMENT_Y.BAS) ){
                  j.setDy( DEPLACEMENT_Y.RIEN );
               }else if( (touche == gauche && j.getDx() == DEPLACEMENT_X.GAUCHE) || (touche == droite && j.getDx() == DEPLACEMENT_X.DROITE) ){
                  j.setDx( DEPLACEMENT_X.RIEN );
               }
        }
     
        /******************** Lanceur ******************************/
        public static void main(String[] args){
            JFrame f = new JFrame("Test");
            f.setSize(400,400);
            f.setLocationRelativeTo(null);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Affichage panel = new Affichage();
            f.add(panel,BorderLayout.CENTER);
            f.setVisible(true);
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    /**
     *
     * @author Ivelios
     */
    public class Joueur{
     
        public enum DEPLACEMENT_X { GAUCHE, RIEN, DROITE };
        public enum DEPLACEMENT_Y { HAUT, RIEN, BAS };
     
        private DEPLACEMENT_X dx;//Déplacement horizontal du joueur
        private DEPLACEMENT_Y dy;//Déplacement verticale du jour
        private int posX, posY;//Position du personnage
     
     
        //Constructeur
        public Joueur(){
            this.posX = 0;
            this.posY = 0;
        }
     
     
        //Accesseurs
        public DEPLACEMENT_X getDx(){return dx;}
        public DEPLACEMENT_Y getDy(){return dy;}
        public int getPosX(){return posX;}
        public int getPosY(){return posY;}
     
        //Modificateurs
        public void setPosX(int posX){this.posX = posX;}
        public void setPosY(int posY){this.posY = posY;}
        public void setDx( DEPLACEMENT_X dx ) { this.dx = dx; }
        public void setDy( DEPLACEMENT_Y dy ) { this.dy = dy; }  
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    /**
     *
     * @author Ivelios
     */
    public class Deplacement implements Runnable{
     
        private Joueur j1,j2,j3,j4;
        Affichage panel;
     
        public Deplacement(Joueur j1,Joueur j2,Joueur j3,Joueur j4, Affichage panel){
            this.j1 = j1;
            this.j2 = j2;
            this.j3 = j3;
            this.j4 = j4;
            this.panel = panel;
        }
     
        public void run() {
             while(true){
     
                 this.deplacerJoueur(j1);
                 this.deplacerJoueur(j2);
                 this.deplacerJoueur(j3);
                 this.deplacerJoueur(j4);
     
                 try {
                    Thread.sleep(10);
                    panel.repaint();
                }catch( InterruptedException exc ) {}
     
            }
        }
     
        private void deplacerJoueur(Joueur j) {
            if( j.getDx() == Joueur.DEPLACEMENT_X.GAUCHE ){//Déplacement gauche
                j.setPosX(j.getPosX()-1);
            }else if( j.getDx() == Joueur.DEPLACEMENT_X.DROITE ){//Déplacement droite
                j.setPosX(j.getPosX()+1);
     
            }
     
            if( j.getDy() == Joueur.DEPLACEMENT_Y.HAUT ){//Déplacement haut
                j.setPosY(j.getPosY()-1);
            } else if( j.getDy() == Joueur.DEPLACEMENT_Y.BAS ){//Déplacement bas
                j.setPosY(j.getPosY()+1);
            }
        }
     
    }
    Je faisais aussi un Thread pour chaque bombe . Je vais aussi modifier ça.
    Objectif : 1 Thread pour tous l'affichage

    Bon, le mieux dans une situation pareil c'est de tous reprendre depuis le début. Pas mal de travail en perspective

    ps : merci sinok
    Il était une fois [...] Et ils vécurent heureux et eurent beaucoup d'enfants!

  4. #4
    Modérateur
    Avatar de wax78
    Homme Profil pro
    Chef programmeur
    Inscrit en
    Août 2006
    Messages
    4 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : Belgique

    Informations professionnelles :
    Activité : Chef programmeur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2006
    Messages : 4 073
    Points : 7 978
    Points
    7 978
    Par défaut
    1 Thread pour l'affichage oui a interval regulier ou autre.

    1 Thread pour l evolution des bonhommes (ou 1 thread par bonhomme mais vaut mieux eviter si tu te retrouves avec 20000 truc a gerer).
    (Les "ça ne marche pas", même écrits sans faute(s), vous porteront discrédit ad vitam æternam et malheur pendant 7 ans)

    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Threads et Affichage
    Par Clout dans le forum C++Builder
    Réponses: 4
    Dernier message: 02/11/2007, 08h55
  2. [C# 2.0] Thread d'affichage
    Par OtI$ dans le forum Windows Forms
    Réponses: 4
    Dernier message: 07/06/2007, 12h07
  3. [1.1] Comment accéder au thread d'affichage ?
    Par fregolo52 dans le forum Framework .NET
    Réponses: 1
    Dernier message: 20/09/2006, 11h27
  4. [MFC] thread d'affichage
    Par Joeleclems dans le forum MFC
    Réponses: 31
    Dernier message: 23/05/2005, 14h47
  5. Thread et affichage direct3D plein écran
    Par Harry_polin dans le forum DirectX
    Réponses: 8
    Dernier message: 13/03/2003, 22h22

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo