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

Communauté Java Discussion :

Variable qui se réinitialise sans raison.


Sujet :

Communauté Java

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Développeur de jeux vidéo
    Inscrit en
    Avril 2016
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur de jeux vidéo
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2016
    Messages : 6
    Points : 7
    Points
    7
    Par défaut Variable qui se réinitialise sans raison.
    Bonjour tout le monde.

    Je developpe un jeu 2d en java , application client serveur.
    Tout fonctionne comme il faut sauf un gros probleme:

    La variable "position" de ma classe ServerPlayer reprend sa valeur initiale sans raison un coup sur deux lorsque je la lis.
    J'a tout tenté, comme j 'utilise plusieurs threads:

    mot clé volatile
    synchronized
    locks
    sémaphores

    Rien n'y fait , une lecture sur deux de la variable donne comme resultat la valeur initiale de cette variable.

    J'ai tenté de rendre cette variable statique et mon jeu fonctionne parfaitement , simplement c'étais juste pour verifier que le reste de mon code est valide car si la variable est statique tous les player auront la meme position.

    Qu'est ce qui peut faire qu'une variable reprend sa valeur initiale en java?

    Voici les deux classes concernées:

    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
    import org.newdawn.slick.geom.Vector2f;
    import java.io.IOException;
    import java.net.Socket;
    import java.util.concurrent.Semaphore;
    import java.util.concurrent.atomic.AtomicReference;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
     
     
    public class ServerPlayer
    {
        private final Server serverRef;
     
        Semaphore semaphore = new Semaphore(1);
        private final NetworkConnection nc;
        private final float speed = 1000;
        public volatile AtomicReference<Vector2f> position = new AtomicReference<Vector2f>(new Vector2f(555.0f,555.0f));
     
        public ServerMap mapRef;
     
     
     
     
        public ServerPlayer(Socket s , Server server) throws IOException
        {
            this.nc = new NetworkConnection(s);
            this.serverRef = server;
     
        }
     
        public   void init()
        {
     
     
            Thread moveThread = new Thread( () ->
            {
                while(true)
                {
     
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
     
                    String receivedMessage = "";
                    try {
                        receivedMessage = nc.receive();
                    } catch (IOException e) {
                        System.out.println("ERROR RECEIVING MESSAGE");
                        throw new RuntimeException(e);
     
                    }
                    System.out.println(receivedMessage);
                    if(receivedMessage.contains("[clientpos]"))
                    {
                        receivedMessage = receivedMessage.replace("[clientpos]" , "");
                        String regex = "(-?\\d*\\.\\d*)\\|(-?\\d*\\.\\d*)";
                        Pattern pattern = Pattern.compile(regex);
                        Matcher matcher = pattern.matcher(receivedMessage);
                        System.out.println(receivedMessage);
                        if (matcher.find())
                        {
                            String xStr = matcher.group(1);
                            String yStr = matcher.group(2);
                            float x = Float.parseFloat(xStr);
                            float y = Float.parseFloat(yStr);
                            System.out.println("x et y valent: " + x + " " + y);
     
                            synchronized (position) {
                                position.set(new Vector2f(x,y));
                                //position.x = x;
                                //position.y = y;
                            }
                        }
                            //System.out.println("Nouvelle position player envoyée par le client: " + (int)getLocation().x + " | " + (int)getLocation().y);
                    }
                }
     
     
            });
            moveThread.start();
     
     
        }
     
     
        public void closeConnection() throws IOException {
            nc.close();
        }
     
    }
    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
    import java.io.IOException;
    import java.net.Socket;
    import java.util.*;
     
    public class ServerMap
    {
        private final NetworkConnection nc;
        private final Server serverRef;
        public volatile ServerPlayer playerRef;
        private final Map<ChunkCoordinates, MapChunk> chunks ;
        private ChunkCoordinates currentPlayerChunk ;
     
        public ServerMap(Socket s , Server server ) throws IOException
        {
            this.nc = new NetworkConnection(s);
            this.serverRef = server;
            chunks = new HashMap<>();
            currentPlayerChunk = new ChunkCoordinates(0,0);
        }
     
     
        public   void init()
        {
     
     
            Thread chunkUpdateSendThread = new Thread( () ->
            {
                while(true) {
                    try {
                        //Thread.sleep(50);
                        if(playerRef != null)
                        {
                            synchronized (playerRef) {
                                currentPlayerChunk.x =  (int)(playerRef.position.get().x / (20.0f * 32.0f));
                                currentPlayerChunk.y =  (int)(playerRef.position.get().y / (20.0f * 32.0f));
                                System.out.println("current chunk player = " + currentPlayerChunk.x + " " + currentPlayerChunk.y);
                                System.out.println("position actuelle du joueur = " + playerRef.position.get().x + " " + playerRef.position.get().y);
                            }
     
                        }
     
     
                        int abcisseMinChunkToLoad = currentPlayerChunk.x - 4;
                        int ordonneeMinChunkToLoad = currentPlayerChunk.y - 4;
                        int abcisseMaxChunkToLoad = currentPlayerChunk.x + 4;
                        int ordonneeMaxChunkToLoad = currentPlayerChunk.y + 4;
     
                        for (int i = abcisseMinChunkToLoad; i <= abcisseMaxChunkToLoad; i++)
                        {
                            for (int j = ordonneeMinChunkToLoad; j <= ordonneeMaxChunkToLoad; j++)
                            {
                                //System.out.println(" Indices = " + i + " " + j);
     
                                ChunkCoordinates chc = new ChunkCoordinates(i, j);
                                MapChunk chunk = new MapChunk(i, j);
                                chunks.put(chc, chunk);
                                if (!FileReaderWriter.fileExists("map/chunks/MapChunk[" + i + "," + j + "].chunk")) {
                                    chunk.randomizedGeneration();
                                    chunk.saveInFile();
                                } else {
                                    chunk.readFromFile("map/chunks/MapChunk[" + i + "," + j + "].chunk");
                                }
     
     
                                String chunkMessage = chunk.createMessageChunk();
                                //System.out.println(chunkMessage);
                                Thread.sleep(10);
                                nc.send(chunkMessage);
                            }
                        }
                    } catch (IOException e) {
                        System.out.println("current chunk player = " + currentPlayerChunk.x + " " + currentPlayerChunk.y);
     
                        throw new RuntimeException(e);
                    } catch (InterruptedException e) {
                        System.out.println("current chunk player = " + currentPlayerChunk.x + " " + currentPlayerChunk.y);
     
                        throw new RuntimeException(e);
                    }
                }
            });
            chunkUpdateSendThread.start();
     
        }
     
     
    }
    J'ai vraiment besoin de votre aide car je ne peux pas avancer a cause de ça.

  2. #2
    Futur Membre du Club
    Homme Profil pro
    Développeur de jeux vidéo
    Inscrit en
    Avril 2016
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur de jeux vidéo
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2016
    Messages : 6
    Points : 7
    Points
    7
    Par défaut portion de code problematique
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    while(true) {
                    try {
                        //Thread.sleep(50);
                        if(playerRef != null)
                        {
                            synchronized (playerRef) {
                                currentPlayerChunk.x =  (int)(playerRef.position.get().x / (20.0f * 32.0f));
                                currentPlayerChunk.y =  (int)(playerRef.position.get().y / (20.0f * 32.0f));
                                System.out.println("current chunk player = " + currentPlayerChunk.x + " " + currentPlayerChunk.y);
                                System.out.println("position actuelle du joueur = " + playerRef.position.get().x + " " + playerRef.position.get().y);
                            }
    lorsque je lis la variable position depuis playerRef voici ce que j obtiens dans la console:

    Nom : Capture d’écran 2023-06-08 211649.png
Affichages : 129
Taille : 39,5 Ko

Discussions similaires

  1. variable qui se réinitialise toujours à zéro
    Par ordi_pentium dans le forum Qt
    Réponses: 6
    Dernier message: 22/04/2010, 12h32
  2. Socket qui se ferme sans raison
    Par rXpCH dans le forum Développement Web en Java
    Réponses: 2
    Dernier message: 10/07/2009, 12h54
  3. Job sql qui se désactive sans raison
    Par panif dans le forum MS SQL Server
    Réponses: 4
    Dernier message: 21/05/2008, 14h10
  4. [MySQL] Un if qui passe à else sans raison
    Par SnoT- dans le forum PHP & Base de données
    Réponses: 5
    Dernier message: 29/01/2008, 13h06
  5. fenêtre qui s'élargit sans raison apparente
    Par Lcf.vs dans le forum Mise en page CSS
    Réponses: 13
    Dernier message: 24/11/2007, 22h02

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