public async Task <IActionResult> Fight(StartFightDTO fight) { return(Ok(await this.fightService.StartFight(fight))); }
public async Task <ServiceResponse <GetFightResultDTO> > StartFight(StartFightDTO fight) { var response = new ServiceResponse <GetFightResultDTO>() { Data = new GetFightResultDTO() }; var characters = await context.Characters .Include(c => c.Weapon) .Include(c => c.CharacterSpells).ThenInclude(cs => cs.Spell) .Where(c => fight.CharacterIds.Contains(c.Id)) .ToListAsync(); bool defeated = false; while (!defeated) { foreach (Character attacker in characters) { var opponents = characters.Where(c => c.Id != attacker.Id).ToList(); var opponent = opponents[new Random().Next(opponents.Count)]; int damage; string attackUsed; bool useWeapon = new Random().Next(2) == 0; if (useWeapon) { attackUsed = attacker.Weapon.Name; damage = DoWeaponAttack(attacker, opponent); } else { var spell = new Random().Next(attacker.CharacterSpells.Count); attackUsed = attacker.CharacterSpells[spell].Spell.Name; damage = DoSpellAttack(attacker, opponent, attacker.CharacterSpells[spell]); } response.Data.Log.Add($"{attacker.Name} attacks {opponent.Name} using {attackUsed} for {(damage > 0 ? damage : 0)} damage."); if (opponent.HitPoint <= 0) { defeated = true; attacker.Victories++; opponent.Defeats++; response.Data.Log.Add($"{opponent.Name} has been defetead."); response.Data.Log.Add($"{attacker.Name} wins with {attacker.HitPoint} HP left"); break; } } } characters.ForEach(c => { c.Fights++; c.HitPoint = 100; }); context.Characters.UpdateRange(characters); await context.SaveChangesAsync(); return(response); }