Search code examples
javaoopmultiplayer

Multiplayer in a game. How to design it object wise?


I'm working on a simple game and I was thinking of adding multiplayer feature but I'm a bit stuck. I'm not sure what approach should I take, keeping in mind good programming practices.

I have a Player object which is created for each player but then I have many other classes that would have to be able to access them. The thing is, if I initialise them in, let's say my main method, then I can't relate to different instances of player class from other classes. The only solution to my problem that comes to my mind is using some form of global objects but afaik using anything globally in apps is usually not a good practice. Any suggestions/ideas?


Solution

  • Although I am not sure what the context is, here is my suggestion according to my perception of the problem.

    A common practice in games is to have a more abstract object to manage the game. Within this 'Game'-object you can manage the addition/removal of players. To fix your problem of being unable to reach the other players from one player, you provide the players with the game-object as an attribute. Using the Game-attribute a player can access the other players and any other data which is relevant meta-data to the game (such as the rules of the game).