mercredi 19 août 2020

Attaching an event-listener to Polymorphic object

Suppose I have an interface PlayerMoveStrategy which has two methods, move(GameBoard b) and utility(GameBoard b), that moves the implementing player by a strategy and evaluates the move by some metric respectively.

Now, the implementing classes can be rulebased or learning based algorithms (Neural Networks, Q-learning) where the move method is calculated. However, to test the game I will need to make one implementing class a HumanPlayer where key presses decide the next move.

The board controls that the next move is allowed, and the player controls the actual movement, see pseudocode:

// Pseudocode GameBoard.java
while (gameLoop) {
  Move m = this.player.move(this.board)
  if (this.moveAllowed(m)) {
    this.board.move(m)
  }
}

Now the issue is how to attach the actual listener to the JPanel representing the Board if the chosen player is human. To me, this will always be a clunky case of

if (this.player instanceof HumanPlayer)
   HumanPlayer humanPlayer = (HumanPlayer) this.player;
   this.addKeyListener(new HumanKeyListener(humanPlayer));

with some decent implementation of the HumanKeyListener. The next problem is that now I need to provide the HumanPlayer implementation with the data needed to move.

How would I design this system to facilitate this design? What am I missing? Should the HumanPlayer implement KeyListener?

My class diagram(ish).

Game has a Board; Board has a player; Board has n*n tiles; Player has a strategy

Aucun commentaire:

Enregistrer un commentaire