public Message PlayerAttack(Position coordinates, Guid playerId)
{
//check if its player turn and that the game is active
if (Turn != playerId || !this.PlayingNow)
return new Message { Action = GameAction.ShotMissed, Player1 = Player1, Player2 = Player2, Command = Command.NotYourTurn, MatchId = MatchId };
//determine if its a hit
var unit = Units.FirstOrDefault(u => u.Row == coordinates.Row && u.Column == coordinates.Column && u.PlayerId != playerId);
bool wasHit;
if (unit != null && unit.Health > 0)
{
//update the unit status, and queue a message
unit.TakeDamage(1);
UpdateUnit(columns: new { Health = unit.Health }, where: new { MatchId = unit.MatchId, And_UnitId = unit.UnitId, And_PlayerId = unit.PlayerId });
wasHit = true;
}
else
{
wasHit = false;
}
//queue proper message
if (wasHit)
{
//check if player won the match
if (Units.Count(u => u.Health > 0 && u.PlayerId != playerId) == 0)
{
//inform players the match result
return MatchFinished(winner: playerId, losser: unit.PlayerId);
}
else
{
//inform the hit
var msg = new Message { Action = GameAction.ShotMade, Player1 = Player1, Player2 = Player2, Command = Command.GameAction, HealthAfterAttack = unit.Health, MatchId = MatchId, UnitId = unit.UnitId, Coordinates = coordinates };
return msg;
}
}
else
{
//inform the missing
var msg = new Message { Action = GameAction.ShotMissed, Player1 = Player1, Player2 = Player2, Command = Command.GameAction, MatchId = MatchId, Coordinates = coordinates };
//change the turn
Turn = Turn == Player1 ? Player2 : Player1;
UpdateMatch();
return msg;
}
}