Search code examples
javamultiplayer2d-games

Best way to store data on server side for Java multilayer top down game


Me and some friends are making a top down shooter in Java and wanted to make it online we have set up a UDP socket connection which works fine but we aren't to sure about how to store data that we receive from the client.

at the moment we are using a number of hashmaps to store the data, for example we have three hashmaps for player tracking, game information (number of players etc) and bullets (bullet locations, who fired etc).

But I am sure that there must be a better more secure way of storing this data other than hashmaps but not to sure what.

edit thx- Philipp (Sorry it took so long for a half decent question)

My concern about using hashmaps to store this data is that there are quite a lot of data to be put into them and we are currently using a single row to store all data for a object for example a row in the player hashmap would have the player id as the key, with a string value to store anything else such as "hp,xloc,yloc". which we then split to use. Which I cant seem to think is the most efficient way to store and retrieve the data.

Sorry if this still doesn't make sense.

I suppose my real question is are there any alternatives that are more efficient or if the hashmap is the best way to go?

Thanks


Solution

  • As you figured out yourself, storing the data about each entity in the game in a string is not a good idea.

    You have to parse the string whenever you need some information about it, and string parsing isn't very fast and can easily get pretty complicated when the data about each entity gets more complex.

    A much better way to do this is to create a class for each entity type with a set of class variables and use this to store the data about each entity:

    class Player {
        public: 
             int positionX;
             int positionY;
             int lifes;
             String name;
             //...
    }
    

    (by the way: an experienced object-oriented programmer would declare these variables as private and use getter and setter methods for changing them, but let's not go that far for now)

    Your hash maps would then store instances of this class:

     HashMap<Integer, Player> players;
    

    Setting these up is easy:

     Player p = new Player();
     p.positionX = 200;
     p.positionY = 400;
     p.lifes = 3;
     p.name = "Ford Prefect";
     players.put(42, p);
    

    (By the way: An experienced OOP programmer would use a constructor)

    You can set and get the variables of each player by accessing the hash map:

     players.get(42).positionX += 10; // move player 42 10 pixels to the right