# Game Manager

This class manages games on the server.

In joinGame, gameRestert, and leaveFromGame methods define the logic of joining the game, leaving, and game restarting system.



The library has a default restarting system, to enable it, you must create RestertingGameState and define your restart logic.



{% hint style="danger" %}
The GameManage must be set in your name class by method. setGameManager(new MyGameManager());
{% endhint %}



GameManager methods:

```java
Optional<Game> getGameByPlayer(Player player); // Gets game by player
Optional<Game> getGameByArenaName(String arenaName); //Gets game by arena name
String randomGame(); //Draws arena name
void gameRestart(Game game); //Restart game    
void joinGame(Arena arena, Player player); //Joins player to arena
void leaveFromGame(Game game, Player player); //Leaves player from game
Set<Game> getGames(); //Gets list of arenas
```

**How to define your own GameManager to define game logic?**

Every game manager must extend AbstractGameManager.

```java
public class MyGameManager extends AbstractGameManager {

    @Override
    public String randomGame() {
        //Define your logic of drawing new arena name
       return "";
    }

    @Override
    public void joinGame(Arena arena, Player player) {
     //Define your logic of joining to arena        
    }

    @Override
    public void leaveFromGame(Game game, Player player) {
     //Define your logic of leaving from arena   
    }
}
```

**How to enable the default restarting system?**

```java
@Override
protected GameState getRestartingGameState(Game game) {
   //enables default game restarting system
   return new RestartingGameState(this, game);
}
```

Define your restarting system.

```java
@Override
public void gameRestart(Game game) {
    //define your own logic of restarting game
 }
```

How to use rejoin feature ? (The documentation is not completed)

```java
Optional<Game> gameOptional = gameManager.rejoin(player, 
(game) -> game.getState() instanceof PlayingGameState, (rejoinState) -> {
            UserGameConverter userGameConverter = gameManager.getUserGameConverter();

            RecoverableUserGame recoverableUserGame = rejoinState.getRecoverableUserGame();
            Game game = rejoinState.getGame();

            MyUserGame myUserGame = userGameConverter.convertToUserGame(recoverableUserGame, MyUserGame.class);

            game.addUserGame(myUserGame);

            rejoinState.teleportToLatestLocation(player);

            rejoinState.restorePlayerOptions(player);
            rejoinState.restorePlayerInventory(player);

            game.removeRecoverableUserGame(recoverableUserGame);
        });
```
