0

I have two Players and one Player to damage the other. Because I don't want to use a Singleton or reference my Game Manager class and referencing a Player from within in a Player is impossible, i don't have a reference to the Enemy. If some one knows an alternative to make this reference that would also be a great solution.

Therefore I want to use events and send them from Player to all other Players. To check, if the enemy should take damage I use a player ID. I want to test the listener and the only method which comes to mind is to fake the enemy who damages the Player and the player should receive a call to take Damage. I would have to use a fake for the player and simultaneously create him which seems kind of awkward and I don't even know if possible.

[Test]  
public void ctor_WhenCreated_CallsTakeDamage()            
{                
    Player enemy = Substitute.For<Player>();
    BasePlayer player = createPlayer();

    enemy.DoDamage += Raise.Event<Action<int,int>>(Arg.Any<int>(),Arg.Any<int>());

    //this was my potentially very stupid plan
    //player.Received().takeDamage(Arg.Any<int>(),Arg.Any<int>());
}



public class BasePlayer : Player
{

      public readonly int playerNumber;
      public event Action<int,int> DoDamage;

      public BasePlayer()
      {
           DoDamage += takeDamage;
      }

      public void takeDamage(int amount,int playerNumber)
      {
          if(playerNumber != this.playerNumber)
                lifeCount-=amount;
      }
}

public interface Player
{
    void takeDamage(int amount, int playerNumber);
    event Action<int, int> DoDamage;
}

I currently have a game class which has a reference to both players. Its used for the general sequenc of the game. I first tried to reference the opponent through the game class, but than I would need a refrence to the game class in the constructor of the player. I thought it was a good idea to decouple them by just sending events instead, so that I don't have to go over the game class but whenever a event is fired all players can see the event and take damage, if their id was sent. But maybe thats not even possible.

  • Does this answer your question? [Unit-testing of a constructor](https://stackoverflow.com/questions/8746762/unit-testing-of-a-constructor) – Mehdi Dehghani Dec 24 '19 at 09:41
  • Welcome to StackOverflow! :) From the example in your question I'm not sure on how the two players are linked. Would you be able to add some code showing how one `Player` will affect a second player? (Something will need a reference to both to wire up the event, in which case it might be easier to add a `Player.doDamage(Player other, int amount)` method, although you mentioned that `Player` can't reference another `Player`. Could you elaborate on this constraint?) – David Tchepak Dec 26 '19 at 09:45

0 Answers0