0

I have a game project that must implement the Player and the Mode. The Player class has two subclasses which are HumanPlayer and BotPlayer and the Mode class has two modes: Easy mode and Hard mode.

This is my class diagram: My Class diagram

The human player and bot will have the "initialize weapon" function. For easy mode, the human player will have all kinds of weapon, while the bot player will only have limited number of weapons. So if I implement the bridge pattern like the picture above, how can I know in Easy mode which abstraction(player or bot) to implement the "initialize weapon" function ?

AlpacaFur
  • 194
  • 2
  • 12
Duy Phan
  • 27
  • 5
  • 1
    I think you're looking for the `instanceof` operator. ([See here](https://stackoverflow.com/q/7313559/8972283)). So you can make an if statement that looks like this: `if(player instanceof HumanPlayer){//deal with easy/hard mode initialization}` – Francis Bartkowiak Apr 20 '18 at 13:52
  • 1
    @FrancisBartkowiak [`instanceof` breaks the Open/Close principle](https://stackoverflow.com/questions/20589590/why-not-use-instanceof-operator-in-oop-design). – Turing85 Apr 20 '18 at 13:54
  • Possible duplicate of [How to determine an object's class?](https://stackoverflow.com/questions/541749/how-to-determine-an-objects-class) – Alexander Apr 20 '18 at 13:54

1 Answers1

0

Pass the weapons to the player before starting the game. So it is not the player object that knows which weapons it has, but the game (or the game mode) that knows the weapons.

There are many ways to do so, but as an example:

public abstract class Mode {
  public abstract Collection<Weapon> getHumanWeapons();
  public abstract CollectionWeapon> getBotWeapons();
}

public class Easy extends Mode{
  public Collection<Weapon> getHumanWeapons() {
         return Collections.singleton(new NukeBlaster()));
  }

  public Collection<Weapon> getBotWeapons() {
         return Collections.singleton(new Flower()));
  }
}


public HumanPlayer(Mode mode) {
   this.weapons = mode.getHumanWeapons(); 
}

public BotPlayer(Mode mode) {
   this.weapons = mode.getBotWeapons();
}

Or... have Mode return a HumanConfiguration and a BotConfiguration which in turn supply weapons and behaviour. That would give the Player class a single constructor and make sure bots do not secretly steal human weapons.

public abstract class Mode {
    public abstract Configuraton getHumanConfiguration();
    public abstract Configuraton getBotConfiguration();
}

public class Configuration {
    public Collection<Weapon> getWeapons() { ... }
}

public class Player {
    private Collection<Weapon> weapons;

    public Player(Configuration configuration) {
       this.weapons = configuration.getWeapons(); 
    }
}
M. le Rutte
  • 3,525
  • 3
  • 18
  • 31