├── Dtos ├── Skill │ └── GetSkillDto.cs ├── Weapon │ ├── GetWeaponDto.cs │ └── AddWeaponDto.cs ├── User │ ├── UserLoginDto.cs │ └── UserRegisterDto.cs ├── Fight │ ├── FightRequestDto.cs │ ├── WeaponAttackDto.cs │ ├── FightResultDto.cs │ ├── SkillAttackDto.cs │ ├── HighscoreDto.cs │ └── AttackResultDto.cs └── Character │ ├── AddCharacterSkillDto.cs │ ├── AddCharacterDto.cs │ ├── UpdateCharacterDto.cs │ └── GetCharacterDto.cs ├── appsettings.Development.json ├── Models ├── ServiceResponse.cs ├── RpgClass.cs ├── Skill.cs ├── Weapon.cs ├── User.cs └── Character.cs ├── WeatherForecast.cs ├── Services ├── WeaponService │ ├── IWeaponService.cs │ └── WeaponService.cs ├── FightService │ ├── IFightService.cs │ └── FightService.cs └── CharacterService │ ├── ICharacterService.cs │ └── CharacterService.cs ├── Data ├── IAuthRepository.cs ├── DataContext.cs └── AuthRepository.cs ├── appsettings.json ├── AutoMapperProfile.cs ├── Program.cs ├── Controllers ├── WeaponController.cs ├── WeatherForecastController.cs ├── AuthController.cs ├── FightController.cs └── CharacterController.cs ├── Properties └── launchSettings.json ├── dotnet-rpg.csproj ├── Migrations ├── 20210121053602_User.cs ├── 20210116121015_InitialCreate.cs ├── 20210324163731_SkillSeeding.cs ├── 20210326153529_FightProperties.cs ├── 20210121054232_UserCharacterRelationship.cs ├── 20210324153435_Weapon.cs ├── 20210116121015_InitialCreate.Designer.cs ├── 20210324162850_Skill.cs ├── 20210121053602_User.Designer.cs ├── 20210121054232_UserCharacterRelationship.Designer.cs ├── 20210324153435_Weapon.Designer.cs ├── 20210324162850_Skill.Designer.cs ├── 20210324163731_SkillSeeding.Designer.cs ├── DataContextModelSnapshot.cs └── 20210326153529_FightProperties.Designer.cs ├── .vscode ├── tasks.json └── launch.json ├── Startup.cs └── .gitignore /Dtos/Skill/GetSkillDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.Skill 2 | { 3 | public class GetSkillDto 4 | { 5 | public string Name { get; set; } 6 | public int Damage { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Dtos/Weapon/GetWeaponDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.Weapon 2 | { 3 | public class GetWeaponDto 4 | { 5 | public string Name { get; set; } 6 | public int Damage { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Dtos/User/UserLoginDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.User 2 | { 3 | public class UserLoginDto 4 | { 5 | public string Username { get; set; } 6 | public string Password { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Dtos/Fight/FightRequestDto.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace dotnet_rpg.Dtos.Fight 4 | { 5 | public class FightRequestDto 6 | { 7 | public List CharacterIds { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Dtos/Fight/WeaponAttackDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.Fight 2 | { 3 | public class WeaponAttackDto 4 | { 5 | public int AttackerId { get; set; } 6 | public int OpponentId { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Dtos/User/UserRegisterDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.User 2 | { 3 | public class UserRegisterDto 4 | { 5 | public string Username { get; set; } 6 | public string Password { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Dtos/Character/AddCharacterSkillDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.Character 2 | { 3 | public class AddCharacterSkillDto 4 | { 5 | public int CharacterId { get; set; } 6 | public int SkillId { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Dtos/Fight/FightResultDto.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace dotnet_rpg.Dtos.Fight 4 | { 5 | public class FightResultDto 6 | { 7 | public List Log { get; set; } = new List(); 8 | } 9 | } -------------------------------------------------------------------------------- /Dtos/Weapon/AddWeaponDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.Weapon 2 | { 3 | public class AddWeaponDto 4 | { 5 | public string Name { get; set; } 6 | public int Damage { get; set; } 7 | public int CharacterId { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Dtos/Fight/SkillAttackDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.Fight 2 | { 3 | public class SkillAttackDto 4 | { 5 | public int AttackerId { get; set; } 6 | public int OpponentId { get; set; } 7 | public int SkillId { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Models/ServiceResponse.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Models 2 | { 3 | public class ServiceResponse 4 | { 5 | public T Data { get; set; } 6 | public bool Success { get; set; } = true; 7 | public string Message { get; set; } = null; 8 | } 9 | } -------------------------------------------------------------------------------- /Models/RpgClass.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace dotnet_rpg.Models 4 | { 5 | [JsonConverter(typeof(JsonStringEnumConverter))] 6 | public enum RpgClass 7 | { 8 | Knight, 9 | Mage, 10 | Cleric 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Models/Skill.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace dotnet_rpg.Models 4 | { 5 | public class Skill 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | public int Damage { get; set; } 10 | public List Characters { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /Models/Weapon.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Models 2 | { 3 | public class Weapon 4 | { 5 | public int Id { get; set; } 6 | public string Name { get; set; } 7 | public int Damage { get; set; } 8 | public Character Character { get; set; } 9 | public int CharacterId { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /Dtos/Fight/HighscoreDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.Fight 2 | { 3 | public class HighscoreDto 4 | { 5 | public int Id { get; set; } 6 | public string Name { get; set; } 7 | public int Fights { get; set; } 8 | public int Defeats { get; set; } 9 | public int Victories { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /Dtos/Fight/AttackResultDto.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_rpg.Dtos.Fight 2 | { 3 | public class AttackResultDto 4 | { 5 | public string Attacker { get; set; } 6 | public string Opponent { get; set; } 7 | public int AttackerHP { get; set; } 8 | public int OpponentHP { get; set; } 9 | public int Damage { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace dotnet_rpg 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Services/WeaponService/IWeaponService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using dotnet_rpg.Dtos.Character; 3 | using dotnet_rpg.Dtos.Weapon; 4 | using dotnet_rpg.Models; 5 | 6 | namespace dotnet_rpg.Services.WeaponService 7 | { 8 | public interface IWeaponService 9 | { 10 | Task> AddWeapon(AddWeaponDto newWeapon); 11 | } 12 | } -------------------------------------------------------------------------------- /Data/IAuthRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using dotnet_rpg.Models; 3 | 4 | namespace dotnet_rpg.Data 5 | { 6 | public interface IAuthRepository 7 | { 8 | Task> Register(User user, string password); 9 | Task> Login(string username, string password); 10 | Task UserExists(string username); 11 | } 12 | } -------------------------------------------------------------------------------- /Models/User.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace dotnet_rpg.Models 4 | { 5 | public class User 6 | { 7 | public int Id { get; set; } 8 | public string Username { get; set; } 9 | public byte[] PasswordHash { get; set; } 10 | public byte[] PasswordSalt { get; set; } 11 | public List Characters { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=localhost\\SQLEXPRESS; Database=dotnet-rpg; Trusted_Connection=true;" 4 | }, 5 | "AppSettings": { 6 | "Token": "my top secret key" 7 | }, 8 | "Logging": { 9 | "LogLevel": { 10 | "Default": "Information", 11 | "Microsoft": "Warning", 12 | "Microsoft.Hosting.Lifetime": "Information" 13 | } 14 | }, 15 | "AllowedHosts": "*" 16 | } 17 | -------------------------------------------------------------------------------- /Dtos/Character/AddCharacterDto.cs: -------------------------------------------------------------------------------- 1 | using dotnet_rpg.Models; 2 | 3 | namespace dotnet_rpg.Dtos.Character 4 | { 5 | public class AddCharacterDto 6 | { 7 | public string Name { get; set; } = "Frodo"; 8 | public int HitPoints { get; set; } = 100; 9 | public int Strength { get; set; } = 10; 10 | public int Defense { get; set; } = 10; 11 | public int Intelligence { get; set; } = 10; 12 | public RpgClass Class { get; set; } = RpgClass.Knight; 13 | } 14 | } -------------------------------------------------------------------------------- /Dtos/Character/UpdateCharacterDto.cs: -------------------------------------------------------------------------------- 1 | using dotnet_rpg.Models; 2 | 3 | namespace dotnet_rpg.Dtos.Character 4 | { 5 | public class UpdateCharacterDto 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } = "Frodo"; 9 | public int HitPoints { get; set; } = 100; 10 | public int Strength { get; set; } = 10; 11 | public int Defense { get; set; } = 10; 12 | public int Intelligence { get; set; } = 10; 13 | public RpgClass Class { get; set; } = RpgClass.Knight; 14 | } 15 | } -------------------------------------------------------------------------------- /Services/FightService/IFightService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using dotnet_rpg.Dtos.Fight; 4 | using dotnet_rpg.Models; 5 | 6 | namespace dotnet_rpg.Services.FightService 7 | { 8 | public interface IFightService 9 | { 10 | Task> WeaponAttack(WeaponAttackDto request); 11 | Task> SkillAttack(SkillAttackDto request); 12 | Task> Fight(FightRequestDto request); 13 | Task>> GetHighscore(); 14 | } 15 | } -------------------------------------------------------------------------------- /AutoMapperProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using dotnet_rpg.Dtos.Character; 3 | using dotnet_rpg.Dtos.Fight; 4 | using dotnet_rpg.Dtos.Skill; 5 | using dotnet_rpg.Dtos.Weapon; 6 | using dotnet_rpg.Models; 7 | 8 | namespace dotnet_rpg 9 | { 10 | public class AutoMapperProfile : Profile 11 | { 12 | public AutoMapperProfile() 13 | { 14 | CreateMap(); 15 | CreateMap(); 16 | CreateMap(); 17 | CreateMap(); 18 | CreateMap(); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Models/Character.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace dotnet_rpg.Models 4 | { 5 | public class Character 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } = "Frodo"; 9 | public int HitPoints { get; set; } = 100; 10 | public int Strength { get; set; } = 10; 11 | public int Defense { get; set; } = 10; 12 | public int Intelligence { get; set; } = 10; 13 | public RpgClass Class { get; set; } = RpgClass.Knight; 14 | public User User { get; set; } 15 | public Weapon Weapon { get; set; } 16 | public List Skills { get; set; } 17 | public int Fights { get; set; } 18 | public int Victories { get; set; } 19 | public int Defeats { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace dotnet_rpg 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Services/CharacterService/ICharacterService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using dotnet_rpg.Dtos.Character; 4 | using dotnet_rpg.Models; 5 | 6 | namespace dotnet_rpg.Services.CharacterService 7 | { 8 | public interface ICharacterService 9 | { 10 | Task>> GetAllCharacters(); 11 | Task> GetCharacterById(int id); 12 | Task>> AddCharacter(AddCharacterDto newCharacter); 13 | Task> UpdateCharacter(UpdateCharacterDto updatedCharacter); 14 | Task>> DeleteCharacter(int id); 15 | Task> AddCharacterSkill(AddCharacterSkillDto newCharacterSkill); 16 | } 17 | } -------------------------------------------------------------------------------- /Dtos/Character/GetCharacterDto.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using dotnet_rpg.Dtos.Skill; 3 | using dotnet_rpg.Dtos.Weapon; 4 | using dotnet_rpg.Models; 5 | 6 | namespace dotnet_rpg.Dtos.Character 7 | { 8 | public class GetCharacterDto 9 | { 10 | public int Id { get; set; } 11 | public string Name { get; set; } = "Frodo"; 12 | public int HitPoints { get; set; } = 100; 13 | public int Strength { get; set; } = 10; 14 | public int Defense { get; set; } = 10; 15 | public int Intelligence { get; set; } = 10; 16 | public RpgClass Class { get; set; } = RpgClass.Knight; 17 | public GetWeaponDto Weapon { get; set; } 18 | public List Skills { get; set; } 19 | public int Fights { get; set; } 20 | public int Victories { get; set; } 21 | public int Defeats { get; set; } 22 | } 23 | } -------------------------------------------------------------------------------- /Controllers/WeaponController.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using dotnet_rpg.Dtos.Character; 3 | using dotnet_rpg.Dtos.Weapon; 4 | using dotnet_rpg.Models; 5 | using dotnet_rpg.Services.WeaponService; 6 | using Microsoft.AspNetCore.Authorization; 7 | using Microsoft.AspNetCore.Mvc; 8 | 9 | namespace dotnet_rpg.Controllers 10 | { 11 | [Authorize] 12 | [ApiController] 13 | [Route("[controller]")] 14 | public class WeaponController : ControllerBase 15 | { 16 | private readonly IWeaponService _weaponService; 17 | 18 | public WeaponController(IWeaponService weaponService) 19 | { 20 | _weaponService = weaponService; 21 | } 22 | 23 | [HttpPost] 24 | public async Task>> AddWeapon(AddWeaponDto newWeapon) 25 | { 26 | return Ok(await _weaponService.AddWeapon(newWeapon)); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:3721", 8 | "sslPort": 44395 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "dotnet_rpg": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Data/DataContext.cs: -------------------------------------------------------------------------------- 1 | using dotnet_rpg.Models; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace dotnet_rpg.Data 5 | { 6 | public class DataContext : DbContext 7 | { 8 | public DataContext(DbContextOptions options) : base(options) 9 | { 10 | 11 | } 12 | 13 | public DbSet Characters { get; set; } 14 | 15 | public DbSet Users { get; set; } 16 | 17 | public DbSet Weapons { get; set; } 18 | 19 | public DbSet Skills { get; set; } 20 | 21 | protected override void OnModelCreating(ModelBuilder modelBuilder) 22 | { 23 | modelBuilder.Entity().HasData( 24 | new Skill { Id = 1, Name = "Fireball", Damage = 30}, 25 | new Skill { Id = 2, Name = "Frenzy", Damage = 20}, 26 | new Skill { Id = 3, Name = "Blizzard", Damage = 50} 27 | ); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /dotnet-rpg.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | dotnet_rpg 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | all 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Migrations/20210121053602_User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace dotnet_rpg.Migrations 5 | { 6 | public partial class User : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "Users", 12 | columns: table => new 13 | { 14 | Id = table.Column(type: "int", nullable: false) 15 | .Annotation("SqlServer:Identity", "1, 1"), 16 | Username = table.Column(type: "nvarchar(max)", nullable: true), 17 | PasswordHash = table.Column(type: "varbinary(max)", nullable: true), 18 | PasswordSalt = table.Column(type: "varbinary(max)", nullable: true) 19 | }, 20 | constraints: table => 21 | { 22 | table.PrimaryKey("PK_Users", x => x.Id); 23 | }); 24 | } 25 | 26 | protected override void Down(MigrationBuilder migrationBuilder) 27 | { 28 | migrationBuilder.DropTable( 29 | name: "Users"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace dotnet_rpg.Controllers 9 | { 10 | [ApiController] 11 | [Route("[controller]")] 12 | public class WeatherForecastController : ControllerBase 13 | { 14 | private static readonly string[] Summaries = new[] 15 | { 16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 17 | }; 18 | 19 | private readonly ILogger _logger; 20 | 21 | public WeatherForecastController(ILogger logger) 22 | { 23 | _logger = logger; 24 | } 25 | 26 | [HttpGet] 27 | public IEnumerable Get() 28 | { 29 | var rng = new Random(); 30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 31 | { 32 | Date = DateTime.Now.AddDays(index), 33 | TemperatureC = rng.Next(-20, 55), 34 | Summary = Summaries[rng.Next(Summaries.Length)] 35 | }) 36 | .ToArray(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/dotnet-rpg.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/dotnet-rpg.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/dotnet-rpg.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /Migrations/20210116121015_InitialCreate.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace dotnet_rpg.Migrations 4 | { 5 | public partial class InitialCreate : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.CreateTable( 10 | name: "Characters", 11 | columns: table => new 12 | { 13 | Id = table.Column(type: "int", nullable: false) 14 | .Annotation("SqlServer:Identity", "1, 1"), 15 | Name = table.Column(type: "nvarchar(max)", nullable: true), 16 | HitPoints = table.Column(type: "int", nullable: false), 17 | Strength = table.Column(type: "int", nullable: false), 18 | Defense = table.Column(type: "int", nullable: false), 19 | Intelligence = table.Column(type: "int", nullable: false), 20 | Class = table.Column(type: "int", nullable: false) 21 | }, 22 | constraints: table => 23 | { 24 | table.PrimaryKey("PK_Characters", x => x.Id); 25 | }); 26 | } 27 | 28 | protected override void Down(MigrationBuilder migrationBuilder) 29 | { 30 | migrationBuilder.DropTable( 31 | name: "Characters"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Controllers/AuthController.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using dotnet_rpg.Data; 3 | using dotnet_rpg.Dtos.User; 4 | using dotnet_rpg.Models; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace dotnet_rpg.Controllers 8 | { 9 | [ApiController] 10 | [Route("[controller]")] 11 | public class AuthController : ControllerBase 12 | { 13 | private readonly IAuthRepository _authRepo; 14 | public AuthController(IAuthRepository authRepo) 15 | { 16 | _authRepo = authRepo; 17 | 18 | } 19 | 20 | [HttpPost("Register")] 21 | public async Task>> Register(UserRegisterDto request) 22 | { 23 | var response = await _authRepo.Register( 24 | new User { Username = request.Username }, request.Password 25 | ); 26 | 27 | if(!response.Success) 28 | { 29 | return BadRequest(response); 30 | } 31 | 32 | return Ok(response); 33 | } 34 | 35 | [HttpPost("Login")] 36 | public async Task>> Login(UserLoginDto request) 37 | { 38 | var response = await _authRepo.Login( 39 | request.Username, request.Password 40 | ); 41 | 42 | if(!response.Success) 43 | { 44 | return BadRequest(response); 45 | } 46 | 47 | return Ok(response); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Controllers/FightController.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using dotnet_rpg.Dtos.Fight; 3 | using dotnet_rpg.Models; 4 | using dotnet_rpg.Services.FightService; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace dotnet_rpg.Controllers 8 | { 9 | [ApiController] 10 | [Route("[controller]")] 11 | public class FightController : ControllerBase 12 | { 13 | private readonly IFightService _fightService; 14 | public FightController(IFightService fightService) 15 | { 16 | _fightService = fightService; 17 | } 18 | 19 | [HttpPost("Weapon")] 20 | public async Task>> WeaponAttack(WeaponAttackDto request) 21 | { 22 | return Ok(await _fightService.WeaponAttack(request)); 23 | } 24 | 25 | [HttpPost("Skill")] 26 | public async Task>> SkillAttack(SkillAttackDto request) 27 | { 28 | return Ok(await _fightService.SkillAttack(request)); 29 | } 30 | 31 | [HttpPost] 32 | public async Task>> Fight(FightRequestDto request) 33 | { 34 | return Ok(await _fightService.Fight(request)); 35 | } 36 | 37 | [HttpGet] 38 | public async Task>> GetHighscore() 39 | { 40 | return Ok(await _fightService.GetHighscore()); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Migrations/20210324163731_SkillSeeding.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace dotnet_rpg.Migrations 4 | { 5 | public partial class SkillSeeding : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.InsertData( 10 | table: "Skills", 11 | columns: new[] { "Id", "Damage", "Name" }, 12 | values: new object[] { 1, 30, "Fireball" }); 13 | 14 | migrationBuilder.InsertData( 15 | table: "Skills", 16 | columns: new[] { "Id", "Damage", "Name" }, 17 | values: new object[] { 2, 20, "Frenzy" }); 18 | 19 | migrationBuilder.InsertData( 20 | table: "Skills", 21 | columns: new[] { "Id", "Damage", "Name" }, 22 | values: new object[] { 3, 50, "Blizzard" }); 23 | } 24 | 25 | protected override void Down(MigrationBuilder migrationBuilder) 26 | { 27 | migrationBuilder.DeleteData( 28 | table: "Skills", 29 | keyColumn: "Id", 30 | keyValue: 1); 31 | 32 | migrationBuilder.DeleteData( 33 | table: "Skills", 34 | keyColumn: "Id", 35 | keyValue: 2); 36 | 37 | migrationBuilder.DeleteData( 38 | table: "Skills", 39 | keyColumn: "Id", 40 | keyValue: 3); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Migrations/20210326153529_FightProperties.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace dotnet_rpg.Migrations 4 | { 5 | public partial class FightProperties : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.AddColumn( 10 | name: "Defeats", 11 | table: "Characters", 12 | type: "int", 13 | nullable: false, 14 | defaultValue: 0); 15 | 16 | migrationBuilder.AddColumn( 17 | name: "Fights", 18 | table: "Characters", 19 | type: "int", 20 | nullable: false, 21 | defaultValue: 0); 22 | 23 | migrationBuilder.AddColumn( 24 | name: "Victories", 25 | table: "Characters", 26 | type: "int", 27 | nullable: false, 28 | defaultValue: 0); 29 | } 30 | 31 | protected override void Down(MigrationBuilder migrationBuilder) 32 | { 33 | migrationBuilder.DropColumn( 34 | name: "Defeats", 35 | table: "Characters"); 36 | 37 | migrationBuilder.DropColumn( 38 | name: "Fights", 39 | table: "Characters"); 40 | 41 | migrationBuilder.DropColumn( 42 | name: "Victories", 43 | table: "Characters"); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (web)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/bin/Debug/net5.0/dotnet-rpg.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}", 16 | "stopAtEntry": false, 17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser 18 | "serverReadyAction": { 19 | "action": "openExternally", 20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)" 21 | }, 22 | "env": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | }, 25 | "sourceFileMap": { 26 | "/Views": "${workspaceFolder}/Views" 27 | } 28 | }, 29 | { 30 | "name": ".NET Core Attach", 31 | "type": "coreclr", 32 | "request": "attach", 33 | "processId": "${command:pickProcess}" 34 | } 35 | ] 36 | } -------------------------------------------------------------------------------- /Migrations/20210121054232_UserCharacterRelationship.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace dotnet_rpg.Migrations 4 | { 5 | public partial class UserCharacterRelationship : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.AddColumn( 10 | name: "UserId", 11 | table: "Characters", 12 | type: "int", 13 | nullable: true); 14 | 15 | migrationBuilder.CreateIndex( 16 | name: "IX_Characters_UserId", 17 | table: "Characters", 18 | column: "UserId"); 19 | 20 | migrationBuilder.AddForeignKey( 21 | name: "FK_Characters_Users_UserId", 22 | table: "Characters", 23 | column: "UserId", 24 | principalTable: "Users", 25 | principalColumn: "Id", 26 | onDelete: ReferentialAction.Restrict); 27 | } 28 | 29 | protected override void Down(MigrationBuilder migrationBuilder) 30 | { 31 | migrationBuilder.DropForeignKey( 32 | name: "FK_Characters_Users_UserId", 33 | table: "Characters"); 34 | 35 | migrationBuilder.DropIndex( 36 | name: "IX_Characters_UserId", 37 | table: "Characters"); 38 | 39 | migrationBuilder.DropColumn( 40 | name: "UserId", 41 | table: "Characters"); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Migrations/20210324153435_Weapon.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace dotnet_rpg.Migrations 4 | { 5 | public partial class Weapon : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.CreateTable( 10 | name: "Weapons", 11 | columns: table => new 12 | { 13 | Id = table.Column(type: "int", nullable: false) 14 | .Annotation("SqlServer:Identity", "1, 1"), 15 | Name = table.Column(type: "nvarchar(max)", nullable: true), 16 | Damage = table.Column(type: "int", nullable: false), 17 | CharacterId = table.Column(type: "int", nullable: false) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_Weapons", x => x.Id); 22 | table.ForeignKey( 23 | name: "FK_Weapons_Characters_CharacterId", 24 | column: x => x.CharacterId, 25 | principalTable: "Characters", 26 | principalColumn: "Id", 27 | onDelete: ReferentialAction.Cascade); 28 | }); 29 | 30 | migrationBuilder.CreateIndex( 31 | name: "IX_Weapons_CharacterId", 32 | table: "Weapons", 33 | column: "CharacterId", 34 | unique: true); 35 | } 36 | 37 | protected override void Down(MigrationBuilder migrationBuilder) 38 | { 39 | migrationBuilder.DropTable( 40 | name: "Weapons"); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Migrations/20210116121015_InitialCreate.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using dotnet_rpg.Data; 8 | 9 | namespace dotnet_rpg.Migrations 10 | { 11 | [DbContext(typeof(DataContext))] 12 | [Migration("20210116121015_InitialCreate")] 13 | partial class InitialCreate 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .UseIdentityColumns() 20 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 21 | .HasAnnotation("ProductVersion", "5.0.2"); 22 | 23 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 24 | { 25 | b.Property("Id") 26 | .ValueGeneratedOnAdd() 27 | .HasColumnType("int") 28 | .UseIdentityColumn(); 29 | 30 | b.Property("Class") 31 | .HasColumnType("int"); 32 | 33 | b.Property("Defense") 34 | .HasColumnType("int"); 35 | 36 | b.Property("HitPoints") 37 | .HasColumnType("int"); 38 | 39 | b.Property("Intelligence") 40 | .HasColumnType("int"); 41 | 42 | b.Property("Name") 43 | .HasColumnType("nvarchar(max)"); 44 | 45 | b.Property("Strength") 46 | .HasColumnType("int"); 47 | 48 | b.HasKey("Id"); 49 | 50 | b.ToTable("Characters"); 51 | }); 52 | #pragma warning restore 612, 618 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Services/WeaponService/WeaponService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Claims; 3 | using System.Threading.Tasks; 4 | using AutoMapper; 5 | using dotnet_rpg.Data; 6 | using dotnet_rpg.Dtos.Character; 7 | using dotnet_rpg.Dtos.Weapon; 8 | using dotnet_rpg.Models; 9 | using Microsoft.AspNetCore.Http; 10 | using Microsoft.EntityFrameworkCore; 11 | 12 | namespace dotnet_rpg.Services.WeaponService 13 | { 14 | public class WeaponService : IWeaponService 15 | { 16 | private readonly DataContext _context; 17 | private readonly IHttpContextAccessor _httpContextAccessor; 18 | private readonly IMapper _mapper; 19 | 20 | public WeaponService(DataContext context, IHttpContextAccessor httpContextAccessor, IMapper mapper) 21 | { 22 | _mapper = mapper; 23 | _httpContextAccessor = httpContextAccessor; 24 | _context = context; 25 | } 26 | 27 | public async Task> AddWeapon(AddWeaponDto newWeapon) 28 | { 29 | var response = new ServiceResponse(); 30 | try 31 | { 32 | var character = await _context.Characters 33 | .FirstOrDefaultAsync(c => c.Id == newWeapon.CharacterId && 34 | c.User.Id == int.Parse(_httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier))); 35 | 36 | if (character == null) 37 | { 38 | response.Success = false; 39 | response.Message = "Character not found."; 40 | return response; 41 | } 42 | 43 | Weapon weapon = new Weapon 44 | { 45 | Name = newWeapon.Name, 46 | Damage = newWeapon.Damage, 47 | Character = character 48 | }; 49 | 50 | _context.Weapons.Add(weapon); 51 | await _context.SaveChangesAsync(); 52 | 53 | response.Data = _mapper.Map(character); 54 | } 55 | catch (Exception ex) 56 | { 57 | response.Success = false; 58 | response.Message = ex.Message; 59 | } 60 | return response; 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /Controllers/CharacterController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Security.Claims; 4 | using System.Threading.Tasks; 5 | using dotnet_rpg.Dtos.Character; 6 | using dotnet_rpg.Models; 7 | using dotnet_rpg.Services.CharacterService; 8 | using Microsoft.AspNetCore.Authorization; 9 | using Microsoft.AspNetCore.Mvc; 10 | 11 | namespace dotnet_rpg.Controllers 12 | { 13 | [Authorize] 14 | [ApiController] 15 | [Route("[controller]")] 16 | public class CharacterController : ControllerBase 17 | { 18 | private readonly ICharacterService _characterService; 19 | 20 | public CharacterController(ICharacterService characterService) 21 | { 22 | _characterService = characterService; 23 | } 24 | 25 | [HttpGet("GetAll")] 26 | public async Task>>> Get() 27 | { 28 | return Ok(await _characterService.GetAllCharacters()); 29 | } 30 | 31 | [HttpGet("{id}")] 32 | public async Task>> GetSingle(int id) 33 | { 34 | return Ok(await _characterService.GetCharacterById(id)); 35 | } 36 | 37 | [HttpPost] 38 | public async Task>>> AddCharacter(AddCharacterDto newCharacter) 39 | { 40 | return Ok(await _characterService.AddCharacter(newCharacter)); 41 | } 42 | 43 | [HttpPut] 44 | public async Task>> UpdateCharacter(UpdateCharacterDto updatedCharacter) 45 | { 46 | var response = await _characterService.UpdateCharacter(updatedCharacter); 47 | if(response.Data == null) 48 | { 49 | return NotFound(response); 50 | } 51 | return Ok(response); 52 | } 53 | 54 | [HttpDelete("{id}")] 55 | public async Task>>> Delete(int id) 56 | { 57 | var response = await _characterService.DeleteCharacter(id); 58 | if(response.Data == null) 59 | { 60 | return NotFound(response); 61 | } 62 | return Ok(response); 63 | } 64 | 65 | [HttpPost("Skill")] 66 | public async Task>> AddCharacterSkill(AddCharacterSkillDto newCharacterSkill) 67 | { 68 | return Ok(await _characterService.AddCharacterSkill(newCharacterSkill)); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Migrations/20210324162850_Skill.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace dotnet_rpg.Migrations 4 | { 5 | public partial class Skill : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.CreateTable( 10 | name: "Skills", 11 | columns: table => new 12 | { 13 | Id = table.Column(type: "int", nullable: false) 14 | .Annotation("SqlServer:Identity", "1, 1"), 15 | Name = table.Column(type: "nvarchar(max)", nullable: true), 16 | Damage = table.Column(type: "int", nullable: false) 17 | }, 18 | constraints: table => 19 | { 20 | table.PrimaryKey("PK_Skills", x => x.Id); 21 | }); 22 | 23 | migrationBuilder.CreateTable( 24 | name: "CharacterSkill", 25 | columns: table => new 26 | { 27 | CharactersId = table.Column(type: "int", nullable: false), 28 | SkillsId = table.Column(type: "int", nullable: false) 29 | }, 30 | constraints: table => 31 | { 32 | table.PrimaryKey("PK_CharacterSkill", x => new { x.CharactersId, x.SkillsId }); 33 | table.ForeignKey( 34 | name: "FK_CharacterSkill_Characters_CharactersId", 35 | column: x => x.CharactersId, 36 | principalTable: "Characters", 37 | principalColumn: "Id", 38 | onDelete: ReferentialAction.Cascade); 39 | table.ForeignKey( 40 | name: "FK_CharacterSkill_Skills_SkillsId", 41 | column: x => x.SkillsId, 42 | principalTable: "Skills", 43 | principalColumn: "Id", 44 | onDelete: ReferentialAction.Cascade); 45 | }); 46 | 47 | migrationBuilder.CreateIndex( 48 | name: "IX_CharacterSkill_SkillsId", 49 | table: "CharacterSkill", 50 | column: "SkillsId"); 51 | } 52 | 53 | protected override void Down(MigrationBuilder migrationBuilder) 54 | { 55 | migrationBuilder.DropTable( 56 | name: "CharacterSkill"); 57 | 58 | migrationBuilder.DropTable( 59 | name: "Skills"); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Migrations/20210121053602_User.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using dotnet_rpg.Data; 9 | 10 | namespace dotnet_rpg.Migrations 11 | { 12 | [DbContext(typeof(DataContext))] 13 | [Migration("20210121053602_User")] 14 | partial class User 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.2"); 23 | 24 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("int") 29 | .UseIdentityColumn(); 30 | 31 | b.Property("Class") 32 | .HasColumnType("int"); 33 | 34 | b.Property("Defense") 35 | .HasColumnType("int"); 36 | 37 | b.Property("HitPoints") 38 | .HasColumnType("int"); 39 | 40 | b.Property("Intelligence") 41 | .HasColumnType("int"); 42 | 43 | b.Property("Name") 44 | .HasColumnType("nvarchar(max)"); 45 | 46 | b.Property("Strength") 47 | .HasColumnType("int"); 48 | 49 | b.HasKey("Id"); 50 | 51 | b.ToTable("Characters"); 52 | }); 53 | 54 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 55 | { 56 | b.Property("Id") 57 | .ValueGeneratedOnAdd() 58 | .HasColumnType("int") 59 | .UseIdentityColumn(); 60 | 61 | b.Property("PasswordHash") 62 | .HasColumnType("varbinary(max)"); 63 | 64 | b.Property("PasswordSalt") 65 | .HasColumnType("varbinary(max)"); 66 | 67 | b.Property("Username") 68 | .HasColumnType("nvarchar(max)"); 69 | 70 | b.HasKey("Id"); 71 | 72 | b.ToTable("Users"); 73 | }); 74 | #pragma warning restore 612, 618 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Migrations/20210121054232_UserCharacterRelationship.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using dotnet_rpg.Data; 9 | 10 | namespace dotnet_rpg.Migrations 11 | { 12 | [DbContext(typeof(DataContext))] 13 | [Migration("20210121054232_UserCharacterRelationship")] 14 | partial class UserCharacterRelationship 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.2"); 23 | 24 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("int") 29 | .UseIdentityColumn(); 30 | 31 | b.Property("Class") 32 | .HasColumnType("int"); 33 | 34 | b.Property("Defense") 35 | .HasColumnType("int"); 36 | 37 | b.Property("HitPoints") 38 | .HasColumnType("int"); 39 | 40 | b.Property("Intelligence") 41 | .HasColumnType("int"); 42 | 43 | b.Property("Name") 44 | .HasColumnType("nvarchar(max)"); 45 | 46 | b.Property("Strength") 47 | .HasColumnType("int"); 48 | 49 | b.Property("UserId") 50 | .HasColumnType("int"); 51 | 52 | b.HasKey("Id"); 53 | 54 | b.HasIndex("UserId"); 55 | 56 | b.ToTable("Characters"); 57 | }); 58 | 59 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 60 | { 61 | b.Property("Id") 62 | .ValueGeneratedOnAdd() 63 | .HasColumnType("int") 64 | .UseIdentityColumn(); 65 | 66 | b.Property("PasswordHash") 67 | .HasColumnType("varbinary(max)"); 68 | 69 | b.Property("PasswordSalt") 70 | .HasColumnType("varbinary(max)"); 71 | 72 | b.Property("Username") 73 | .HasColumnType("nvarchar(max)"); 74 | 75 | b.HasKey("Id"); 76 | 77 | b.ToTable("Users"); 78 | }); 79 | 80 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 81 | { 82 | b.HasOne("dotnet_rpg.Models.User", "User") 83 | .WithMany("Characters") 84 | .HasForeignKey("UserId"); 85 | 86 | b.Navigation("User"); 87 | }); 88 | 89 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 90 | { 91 | b.Navigation("Characters"); 92 | }); 93 | #pragma warning restore 612, 618 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using dotnet_rpg.Data; 7 | using dotnet_rpg.Services.CharacterService; 8 | using dotnet_rpg.Services.FightService; 9 | using dotnet_rpg.Services.WeaponService; 10 | using Microsoft.AspNetCore.Authentication.JwtBearer; 11 | using Microsoft.AspNetCore.Builder; 12 | using Microsoft.AspNetCore.Hosting; 13 | using Microsoft.AspNetCore.Http; 14 | using Microsoft.AspNetCore.HttpsPolicy; 15 | using Microsoft.AspNetCore.Mvc; 16 | using Microsoft.EntityFrameworkCore; 17 | using Microsoft.Extensions.Configuration; 18 | using Microsoft.Extensions.DependencyInjection; 19 | using Microsoft.Extensions.Hosting; 20 | using Microsoft.Extensions.Logging; 21 | using Microsoft.IdentityModel.Tokens; 22 | using Microsoft.OpenApi.Models; 23 | using Swashbuckle.AspNetCore.Filters; 24 | 25 | namespace dotnet_rpg 26 | { 27 | public class Startup 28 | { 29 | public Startup(IConfiguration configuration) 30 | { 31 | Configuration = configuration; 32 | } 33 | 34 | public IConfiguration Configuration { get; } 35 | 36 | // This method gets called by the runtime. Use this method to add services to the container. 37 | public void ConfigureServices(IServiceCollection services) 38 | { 39 | services.AddDbContext(options => 40 | options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 41 | services.AddControllers(); 42 | services.AddSwaggerGen(c => 43 | { 44 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "dotnet_rpg", Version = "v1" }); 45 | c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme 46 | { 47 | Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", 48 | In = ParameterLocation.Header, 49 | Name = "Authorization", 50 | Type = SecuritySchemeType.ApiKey 51 | }); 52 | c.OperationFilter(); 53 | }); 54 | services.AddAutoMapper(typeof(Startup)); 55 | services.AddScoped(); 56 | services.AddScoped(); 57 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 58 | .AddJwtBearer(options => 59 | { 60 | options.TokenValidationParameters = new TokenValidationParameters 61 | { 62 | ValidateIssuerSigningKey = true, 63 | IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)), 64 | ValidateIssuer = false, 65 | ValidateAudience = false 66 | }; 67 | }); 68 | services.AddSingleton(); 69 | services.AddScoped(); 70 | services.AddScoped(); 71 | } 72 | 73 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 74 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 75 | { 76 | if (env.IsDevelopment()) 77 | { 78 | app.UseDeveloperExceptionPage(); 79 | app.UseSwagger(); 80 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "dotnet_rpg v1")); 81 | } 82 | 83 | app.UseHttpsRedirection(); 84 | 85 | app.UseRouting(); 86 | 87 | app.UseAuthentication(); 88 | 89 | app.UseAuthorization(); 90 | 91 | app.UseEndpoints(endpoints => 92 | { 93 | endpoints.MapControllers(); 94 | }); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Data/AuthRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IdentityModel.Tokens.Jwt; 3 | using System.Security.Claims; 4 | using System.Threading.Tasks; 5 | using dotnet_rpg.Models; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.IdentityModel.Tokens; 9 | 10 | namespace dotnet_rpg.Data 11 | { 12 | public class AuthRepository : IAuthRepository 13 | { 14 | private readonly DataContext _context; 15 | private readonly IConfiguration _configuration; 16 | public AuthRepository(DataContext context, IConfiguration configuration) 17 | { 18 | _configuration = configuration; 19 | _context = context; 20 | 21 | } 22 | 23 | public async Task> Login(string username, string password) 24 | { 25 | var response = new ServiceResponse(); 26 | var user = await _context.Users.FirstOrDefaultAsync(x => x.Username.ToLower().Equals(username.ToLower())); 27 | if (user == null) 28 | { 29 | response.Success = false; 30 | response.Message = "User not found."; 31 | } 32 | else if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt)) 33 | { 34 | response.Success = false; 35 | response.Message = "Wrong password."; 36 | } 37 | else 38 | { 39 | response.Data = CreateToken(user); 40 | } 41 | 42 | return response; 43 | } 44 | 45 | public async Task> Register(User user, string password) 46 | { 47 | ServiceResponse response = new ServiceResponse(); 48 | if (await UserExists(user.Username)) 49 | { 50 | response.Success = false; 51 | response.Message = "User already exists."; 52 | return response; 53 | } 54 | 55 | CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt); 56 | 57 | user.PasswordHash = passwordHash; 58 | user.PasswordSalt = passwordSalt; 59 | 60 | _context.Users.Add(user); 61 | await _context.SaveChangesAsync(); 62 | response.Data = user.Id; 63 | return response; 64 | } 65 | 66 | public async Task UserExists(string username) 67 | { 68 | if (await _context.Users.AnyAsync(x => x.Username.ToLower().Equals(username.ToLower()))) 69 | { 70 | return true; 71 | } 72 | return false; 73 | } 74 | 75 | private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt) 76 | { 77 | using (var hmac = new System.Security.Cryptography.HMACSHA512()) 78 | { 79 | passwordSalt = hmac.Key; 80 | passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); 81 | } 82 | } 83 | 84 | private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt) 85 | { 86 | using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)) 87 | { 88 | var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); 89 | for (int i = 0; i < computedHash.Length; i++) 90 | { 91 | if (computedHash[i] != passwordHash[i]) 92 | { 93 | return false; 94 | } 95 | } 96 | return true; 97 | } 98 | } 99 | 100 | private string CreateToken(User user) 101 | { 102 | var claims = new List 103 | { 104 | new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), 105 | new Claim(ClaimTypes.Name, user.Username) 106 | }; 107 | 108 | var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value)); 109 | 110 | var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); 111 | 112 | var tokendDescriptor = new SecurityTokenDescriptor 113 | { 114 | Subject = new ClaimsIdentity(claims), 115 | Expires = System.DateTime.Now.AddDays(1), 116 | SigningCredentials = creds 117 | }; 118 | 119 | var tokenHandler = new JwtSecurityTokenHandler(); 120 | var token = tokenHandler.CreateToken(tokendDescriptor); 121 | 122 | return tokenHandler.WriteToken(token); 123 | } 124 | } 125 | } -------------------------------------------------------------------------------- /Migrations/20210324153435_Weapon.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using dotnet_rpg.Data; 9 | 10 | namespace dotnet_rpg.Migrations 11 | { 12 | [DbContext(typeof(DataContext))] 13 | [Migration("20210324153435_Weapon")] 14 | partial class Weapon 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.2"); 23 | 24 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("int") 29 | .UseIdentityColumn(); 30 | 31 | b.Property("Class") 32 | .HasColumnType("int"); 33 | 34 | b.Property("Defense") 35 | .HasColumnType("int"); 36 | 37 | b.Property("HitPoints") 38 | .HasColumnType("int"); 39 | 40 | b.Property("Intelligence") 41 | .HasColumnType("int"); 42 | 43 | b.Property("Name") 44 | .HasColumnType("nvarchar(max)"); 45 | 46 | b.Property("Strength") 47 | .HasColumnType("int"); 48 | 49 | b.Property("UserId") 50 | .HasColumnType("int"); 51 | 52 | b.HasKey("Id"); 53 | 54 | b.HasIndex("UserId"); 55 | 56 | b.ToTable("Characters"); 57 | }); 58 | 59 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 60 | { 61 | b.Property("Id") 62 | .ValueGeneratedOnAdd() 63 | .HasColumnType("int") 64 | .UseIdentityColumn(); 65 | 66 | b.Property("PasswordHash") 67 | .HasColumnType("varbinary(max)"); 68 | 69 | b.Property("PasswordSalt") 70 | .HasColumnType("varbinary(max)"); 71 | 72 | b.Property("Username") 73 | .HasColumnType("nvarchar(max)"); 74 | 75 | b.HasKey("Id"); 76 | 77 | b.ToTable("Users"); 78 | }); 79 | 80 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 81 | { 82 | b.Property("Id") 83 | .ValueGeneratedOnAdd() 84 | .HasColumnType("int") 85 | .UseIdentityColumn(); 86 | 87 | b.Property("CharacterId") 88 | .HasColumnType("int"); 89 | 90 | b.Property("Damage") 91 | .HasColumnType("int"); 92 | 93 | b.Property("Name") 94 | .HasColumnType("nvarchar(max)"); 95 | 96 | b.HasKey("Id"); 97 | 98 | b.HasIndex("CharacterId") 99 | .IsUnique(); 100 | 101 | b.ToTable("Weapons"); 102 | }); 103 | 104 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 105 | { 106 | b.HasOne("dotnet_rpg.Models.User", "User") 107 | .WithMany("Characters") 108 | .HasForeignKey("UserId"); 109 | 110 | b.Navigation("User"); 111 | }); 112 | 113 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 114 | { 115 | b.HasOne("dotnet_rpg.Models.Character", "Character") 116 | .WithOne("Weapon") 117 | .HasForeignKey("dotnet_rpg.Models.Weapon", "CharacterId") 118 | .OnDelete(DeleteBehavior.Cascade) 119 | .IsRequired(); 120 | 121 | b.Navigation("Character"); 122 | }); 123 | 124 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 125 | { 126 | b.Navigation("Weapon"); 127 | }); 128 | 129 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 130 | { 131 | b.Navigation("Characters"); 132 | }); 133 | #pragma warning restore 612, 618 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /Migrations/20210324162850_Skill.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using dotnet_rpg.Data; 9 | 10 | namespace dotnet_rpg.Migrations 11 | { 12 | [DbContext(typeof(DataContext))] 13 | [Migration("20210324162850_Skill")] 14 | partial class Skill 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.2"); 23 | 24 | modelBuilder.Entity("CharacterSkill", b => 25 | { 26 | b.Property("CharactersId") 27 | .HasColumnType("int"); 28 | 29 | b.Property("SkillsId") 30 | .HasColumnType("int"); 31 | 32 | b.HasKey("CharactersId", "SkillsId"); 33 | 34 | b.HasIndex("SkillsId"); 35 | 36 | b.ToTable("CharacterSkill"); 37 | }); 38 | 39 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 40 | { 41 | b.Property("Id") 42 | .ValueGeneratedOnAdd() 43 | .HasColumnType("int") 44 | .UseIdentityColumn(); 45 | 46 | b.Property("Class") 47 | .HasColumnType("int"); 48 | 49 | b.Property("Defense") 50 | .HasColumnType("int"); 51 | 52 | b.Property("HitPoints") 53 | .HasColumnType("int"); 54 | 55 | b.Property("Intelligence") 56 | .HasColumnType("int"); 57 | 58 | b.Property("Name") 59 | .HasColumnType("nvarchar(max)"); 60 | 61 | b.Property("Strength") 62 | .HasColumnType("int"); 63 | 64 | b.Property("UserId") 65 | .HasColumnType("int"); 66 | 67 | b.HasKey("Id"); 68 | 69 | b.HasIndex("UserId"); 70 | 71 | b.ToTable("Characters"); 72 | }); 73 | 74 | modelBuilder.Entity("dotnet_rpg.Models.Skill", b => 75 | { 76 | b.Property("Id") 77 | .ValueGeneratedOnAdd() 78 | .HasColumnType("int") 79 | .UseIdentityColumn(); 80 | 81 | b.Property("Damage") 82 | .HasColumnType("int"); 83 | 84 | b.Property("Name") 85 | .HasColumnType("nvarchar(max)"); 86 | 87 | b.HasKey("Id"); 88 | 89 | b.ToTable("Skills"); 90 | }); 91 | 92 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 93 | { 94 | b.Property("Id") 95 | .ValueGeneratedOnAdd() 96 | .HasColumnType("int") 97 | .UseIdentityColumn(); 98 | 99 | b.Property("PasswordHash") 100 | .HasColumnType("varbinary(max)"); 101 | 102 | b.Property("PasswordSalt") 103 | .HasColumnType("varbinary(max)"); 104 | 105 | b.Property("Username") 106 | .HasColumnType("nvarchar(max)"); 107 | 108 | b.HasKey("Id"); 109 | 110 | b.ToTable("Users"); 111 | }); 112 | 113 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 114 | { 115 | b.Property("Id") 116 | .ValueGeneratedOnAdd() 117 | .HasColumnType("int") 118 | .UseIdentityColumn(); 119 | 120 | b.Property("CharacterId") 121 | .HasColumnType("int"); 122 | 123 | b.Property("Damage") 124 | .HasColumnType("int"); 125 | 126 | b.Property("Name") 127 | .HasColumnType("nvarchar(max)"); 128 | 129 | b.HasKey("Id"); 130 | 131 | b.HasIndex("CharacterId") 132 | .IsUnique(); 133 | 134 | b.ToTable("Weapons"); 135 | }); 136 | 137 | modelBuilder.Entity("CharacterSkill", b => 138 | { 139 | b.HasOne("dotnet_rpg.Models.Character", null) 140 | .WithMany() 141 | .HasForeignKey("CharactersId") 142 | .OnDelete(DeleteBehavior.Cascade) 143 | .IsRequired(); 144 | 145 | b.HasOne("dotnet_rpg.Models.Skill", null) 146 | .WithMany() 147 | .HasForeignKey("SkillsId") 148 | .OnDelete(DeleteBehavior.Cascade) 149 | .IsRequired(); 150 | }); 151 | 152 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 153 | { 154 | b.HasOne("dotnet_rpg.Models.User", "User") 155 | .WithMany("Characters") 156 | .HasForeignKey("UserId"); 157 | 158 | b.Navigation("User"); 159 | }); 160 | 161 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 162 | { 163 | b.HasOne("dotnet_rpg.Models.Character", "Character") 164 | .WithOne("Weapon") 165 | .HasForeignKey("dotnet_rpg.Models.Weapon", "CharacterId") 166 | .OnDelete(DeleteBehavior.Cascade) 167 | .IsRequired(); 168 | 169 | b.Navigation("Character"); 170 | }); 171 | 172 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 173 | { 174 | b.Navigation("Weapon"); 175 | }); 176 | 177 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 178 | { 179 | b.Navigation("Characters"); 180 | }); 181 | #pragma warning restore 612, 618 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /Services/CharacterService/CharacterService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Threading.Tasks; 6 | using AutoMapper; 7 | using dotnet_rpg.Data; 8 | using dotnet_rpg.Dtos.Character; 9 | using dotnet_rpg.Models; 10 | using Microsoft.AspNetCore.Http; 11 | using Microsoft.EntityFrameworkCore; 12 | 13 | namespace dotnet_rpg.Services.CharacterService 14 | { 15 | public class CharacterService : ICharacterService 16 | { 17 | private readonly IMapper _mapper; 18 | private readonly DataContext _context; 19 | private readonly IHttpContextAccessor _httpContextAccessor; 20 | 21 | public CharacterService(IMapper mapper, DataContext context, IHttpContextAccessor httpContextAccessor) 22 | { 23 | _httpContextAccessor = httpContextAccessor; 24 | _context = context; 25 | _mapper = mapper; 26 | } 27 | 28 | private int GetUserId() => int.Parse(_httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier)); 29 | 30 | public async Task>> AddCharacter(AddCharacterDto newCharacter) 31 | { 32 | var serviceResponse = new ServiceResponse>(); 33 | Character character = _mapper.Map(newCharacter); 34 | character.User = await _context.Users.FirstOrDefaultAsync(u => u.Id == GetUserId()); 35 | 36 | _context.Characters.Add(character); 37 | await _context.SaveChangesAsync(); 38 | serviceResponse.Data = await _context.Characters 39 | .Where(c => c.User.Id == GetUserId()) 40 | .Select(c => _mapper.Map(c)).ToListAsync(); 41 | return serviceResponse; 42 | } 43 | 44 | public async Task>> DeleteCharacter(int id) 45 | { 46 | var serviceResponse = new ServiceResponse>(); 47 | try 48 | { 49 | Character character = await _context.Characters 50 | .FirstOrDefaultAsync(c => c.Id == id && c.User.Id == GetUserId()); 51 | if (character != null) 52 | { 53 | _context.Characters.Remove(character); 54 | await _context.SaveChangesAsync(); 55 | 56 | serviceResponse.Data = _context.Characters 57 | .Where(c => c.User.Id == GetUserId()) 58 | .Select(c => _mapper.Map(c)).ToList(); 59 | } 60 | else 61 | { 62 | serviceResponse.Success = false; 63 | serviceResponse.Message = "Character not found."; 64 | } 65 | } 66 | catch (Exception ex) 67 | { 68 | serviceResponse.Success = false; 69 | serviceResponse.Message = ex.Message; 70 | } 71 | return serviceResponse; 72 | } 73 | 74 | public async Task>> GetAllCharacters() 75 | { 76 | var serviceResponse = new ServiceResponse>(); 77 | var dbCharacters = await _context.Characters 78 | .Include(c => c.Weapon) 79 | .Include(c => c.Skills) 80 | .Where(c => c.User.Id == GetUserId()).ToListAsync(); 81 | serviceResponse.Data = dbCharacters.Select(c => _mapper.Map(c)).ToList(); 82 | return serviceResponse; 83 | } 84 | 85 | public async Task> GetCharacterById(int id) 86 | { 87 | var serviceResponse = new ServiceResponse(); 88 | var dbCharacter = await _context.Characters 89 | .Include(c => c.Weapon) 90 | .Include(c => c.Skills) 91 | .FirstOrDefaultAsync(c => c.Id == id && c.User.Id == GetUserId()); 92 | serviceResponse.Data = _mapper.Map(dbCharacter); 93 | return serviceResponse; 94 | } 95 | 96 | public async Task> UpdateCharacter(UpdateCharacterDto updatedCharacter) 97 | { 98 | var serviceResponse = new ServiceResponse(); 99 | try 100 | { 101 | Character character = await _context.Characters 102 | .Include(c => c.User) 103 | .FirstOrDefaultAsync(c => c.Id == updatedCharacter.Id); 104 | if (character.User.Id == GetUserId()) 105 | { 106 | character.Name = updatedCharacter.Name; 107 | character.HitPoints = updatedCharacter.HitPoints; 108 | character.Strength = updatedCharacter.Strength; 109 | character.Defense = updatedCharacter.Defense; 110 | character.Intelligence = updatedCharacter.Intelligence; 111 | character.Class = updatedCharacter.Class; 112 | 113 | await _context.SaveChangesAsync(); 114 | serviceResponse.Data = _mapper.Map(character); 115 | } 116 | else 117 | { 118 | serviceResponse.Success = false; 119 | serviceResponse.Message = "Character not found."; 120 | } 121 | } 122 | catch (Exception ex) 123 | { 124 | serviceResponse.Success = false; 125 | serviceResponse.Message = ex.Message; 126 | } 127 | return serviceResponse; 128 | } 129 | 130 | public async Task> AddCharacterSkill(AddCharacterSkillDto newCharacterSkill) 131 | { 132 | var response = new ServiceResponse(); 133 | try 134 | { 135 | var character = await _context.Characters 136 | .Include(c => c.Weapon) 137 | .Include(c => c.Skills) 138 | .FirstOrDefaultAsync(c => c.Id == newCharacterSkill.CharacterId && c.User.Id == GetUserId()); 139 | if(character == null) 140 | { 141 | response.Success = false; 142 | response.Message = "Character not found."; 143 | return response; 144 | } 145 | 146 | var skill = await _context.Skills.FirstOrDefaultAsync(s => s.Id == newCharacterSkill.SkillId); 147 | if(skill == null) 148 | { 149 | response.Success = false; 150 | response.Message = "Skill not found."; 151 | return response; 152 | } 153 | 154 | character.Skills.Add(skill); 155 | await _context.SaveChangesAsync(); 156 | 157 | response.Data = _mapper.Map(character); 158 | } 159 | catch (Exception ex) 160 | { 161 | response.Success = false; 162 | response.Message = ex.Message; 163 | } 164 | return response; 165 | } 166 | } 167 | } -------------------------------------------------------------------------------- /Migrations/20210324163731_SkillSeeding.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using dotnet_rpg.Data; 9 | 10 | namespace dotnet_rpg.Migrations 11 | { 12 | [DbContext(typeof(DataContext))] 13 | [Migration("20210324163731_SkillSeeding")] 14 | partial class SkillSeeding 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.2"); 23 | 24 | modelBuilder.Entity("CharacterSkill", b => 25 | { 26 | b.Property("CharactersId") 27 | .HasColumnType("int"); 28 | 29 | b.Property("SkillsId") 30 | .HasColumnType("int"); 31 | 32 | b.HasKey("CharactersId", "SkillsId"); 33 | 34 | b.HasIndex("SkillsId"); 35 | 36 | b.ToTable("CharacterSkill"); 37 | }); 38 | 39 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 40 | { 41 | b.Property("Id") 42 | .ValueGeneratedOnAdd() 43 | .HasColumnType("int") 44 | .UseIdentityColumn(); 45 | 46 | b.Property("Class") 47 | .HasColumnType("int"); 48 | 49 | b.Property("Defense") 50 | .HasColumnType("int"); 51 | 52 | b.Property("HitPoints") 53 | .HasColumnType("int"); 54 | 55 | b.Property("Intelligence") 56 | .HasColumnType("int"); 57 | 58 | b.Property("Name") 59 | .HasColumnType("nvarchar(max)"); 60 | 61 | b.Property("Strength") 62 | .HasColumnType("int"); 63 | 64 | b.Property("UserId") 65 | .HasColumnType("int"); 66 | 67 | b.HasKey("Id"); 68 | 69 | b.HasIndex("UserId"); 70 | 71 | b.ToTable("Characters"); 72 | }); 73 | 74 | modelBuilder.Entity("dotnet_rpg.Models.Skill", b => 75 | { 76 | b.Property("Id") 77 | .ValueGeneratedOnAdd() 78 | .HasColumnType("int") 79 | .UseIdentityColumn(); 80 | 81 | b.Property("Damage") 82 | .HasColumnType("int"); 83 | 84 | b.Property("Name") 85 | .HasColumnType("nvarchar(max)"); 86 | 87 | b.HasKey("Id"); 88 | 89 | b.ToTable("Skills"); 90 | 91 | b.HasData( 92 | new 93 | { 94 | Id = 1, 95 | Damage = 30, 96 | Name = "Fireball" 97 | }, 98 | new 99 | { 100 | Id = 2, 101 | Damage = 20, 102 | Name = "Frenzy" 103 | }, 104 | new 105 | { 106 | Id = 3, 107 | Damage = 50, 108 | Name = "Blizzard" 109 | }); 110 | }); 111 | 112 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 113 | { 114 | b.Property("Id") 115 | .ValueGeneratedOnAdd() 116 | .HasColumnType("int") 117 | .UseIdentityColumn(); 118 | 119 | b.Property("PasswordHash") 120 | .HasColumnType("varbinary(max)"); 121 | 122 | b.Property("PasswordSalt") 123 | .HasColumnType("varbinary(max)"); 124 | 125 | b.Property("Username") 126 | .HasColumnType("nvarchar(max)"); 127 | 128 | b.HasKey("Id"); 129 | 130 | b.ToTable("Users"); 131 | }); 132 | 133 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 134 | { 135 | b.Property("Id") 136 | .ValueGeneratedOnAdd() 137 | .HasColumnType("int") 138 | .UseIdentityColumn(); 139 | 140 | b.Property("CharacterId") 141 | .HasColumnType("int"); 142 | 143 | b.Property("Damage") 144 | .HasColumnType("int"); 145 | 146 | b.Property("Name") 147 | .HasColumnType("nvarchar(max)"); 148 | 149 | b.HasKey("Id"); 150 | 151 | b.HasIndex("CharacterId") 152 | .IsUnique(); 153 | 154 | b.ToTable("Weapons"); 155 | }); 156 | 157 | modelBuilder.Entity("CharacterSkill", b => 158 | { 159 | b.HasOne("dotnet_rpg.Models.Character", null) 160 | .WithMany() 161 | .HasForeignKey("CharactersId") 162 | .OnDelete(DeleteBehavior.Cascade) 163 | .IsRequired(); 164 | 165 | b.HasOne("dotnet_rpg.Models.Skill", null) 166 | .WithMany() 167 | .HasForeignKey("SkillsId") 168 | .OnDelete(DeleteBehavior.Cascade) 169 | .IsRequired(); 170 | }); 171 | 172 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 173 | { 174 | b.HasOne("dotnet_rpg.Models.User", "User") 175 | .WithMany("Characters") 176 | .HasForeignKey("UserId"); 177 | 178 | b.Navigation("User"); 179 | }); 180 | 181 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 182 | { 183 | b.HasOne("dotnet_rpg.Models.Character", "Character") 184 | .WithOne("Weapon") 185 | .HasForeignKey("dotnet_rpg.Models.Weapon", "CharacterId") 186 | .OnDelete(DeleteBehavior.Cascade) 187 | .IsRequired(); 188 | 189 | b.Navigation("Character"); 190 | }); 191 | 192 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 193 | { 194 | b.Navigation("Weapon"); 195 | }); 196 | 197 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 198 | { 199 | b.Navigation("Characters"); 200 | }); 201 | #pragma warning restore 612, 618 202 | } 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /Migrations/DataContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using dotnet_rpg.Data; 8 | 9 | namespace dotnet_rpg.Migrations 10 | { 11 | [DbContext(typeof(DataContext))] 12 | partial class DataContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder 18 | .UseIdentityColumns() 19 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 20 | .HasAnnotation("ProductVersion", "5.0.2"); 21 | 22 | modelBuilder.Entity("CharacterSkill", b => 23 | { 24 | b.Property("CharactersId") 25 | .HasColumnType("int"); 26 | 27 | b.Property("SkillsId") 28 | .HasColumnType("int"); 29 | 30 | b.HasKey("CharactersId", "SkillsId"); 31 | 32 | b.HasIndex("SkillsId"); 33 | 34 | b.ToTable("CharacterSkill"); 35 | }); 36 | 37 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 38 | { 39 | b.Property("Id") 40 | .ValueGeneratedOnAdd() 41 | .HasColumnType("int") 42 | .UseIdentityColumn(); 43 | 44 | b.Property("Class") 45 | .HasColumnType("int"); 46 | 47 | b.Property("Defeats") 48 | .HasColumnType("int"); 49 | 50 | b.Property("Defense") 51 | .HasColumnType("int"); 52 | 53 | b.Property("Fights") 54 | .HasColumnType("int"); 55 | 56 | b.Property("HitPoints") 57 | .HasColumnType("int"); 58 | 59 | b.Property("Intelligence") 60 | .HasColumnType("int"); 61 | 62 | b.Property("Name") 63 | .HasColumnType("nvarchar(max)"); 64 | 65 | b.Property("Strength") 66 | .HasColumnType("int"); 67 | 68 | b.Property("UserId") 69 | .HasColumnType("int"); 70 | 71 | b.Property("Victories") 72 | .HasColumnType("int"); 73 | 74 | b.HasKey("Id"); 75 | 76 | b.HasIndex("UserId"); 77 | 78 | b.ToTable("Characters"); 79 | }); 80 | 81 | modelBuilder.Entity("dotnet_rpg.Models.Skill", b => 82 | { 83 | b.Property("Id") 84 | .ValueGeneratedOnAdd() 85 | .HasColumnType("int") 86 | .UseIdentityColumn(); 87 | 88 | b.Property("Damage") 89 | .HasColumnType("int"); 90 | 91 | b.Property("Name") 92 | .HasColumnType("nvarchar(max)"); 93 | 94 | b.HasKey("Id"); 95 | 96 | b.ToTable("Skills"); 97 | 98 | b.HasData( 99 | new 100 | { 101 | Id = 1, 102 | Damage = 30, 103 | Name = "Fireball" 104 | }, 105 | new 106 | { 107 | Id = 2, 108 | Damage = 20, 109 | Name = "Frenzy" 110 | }, 111 | new 112 | { 113 | Id = 3, 114 | Damage = 50, 115 | Name = "Blizzard" 116 | }); 117 | }); 118 | 119 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 120 | { 121 | b.Property("Id") 122 | .ValueGeneratedOnAdd() 123 | .HasColumnType("int") 124 | .UseIdentityColumn(); 125 | 126 | b.Property("PasswordHash") 127 | .HasColumnType("varbinary(max)"); 128 | 129 | b.Property("PasswordSalt") 130 | .HasColumnType("varbinary(max)"); 131 | 132 | b.Property("Username") 133 | .HasColumnType("nvarchar(max)"); 134 | 135 | b.HasKey("Id"); 136 | 137 | b.ToTable("Users"); 138 | }); 139 | 140 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 141 | { 142 | b.Property("Id") 143 | .ValueGeneratedOnAdd() 144 | .HasColumnType("int") 145 | .UseIdentityColumn(); 146 | 147 | b.Property("CharacterId") 148 | .HasColumnType("int"); 149 | 150 | b.Property("Damage") 151 | .HasColumnType("int"); 152 | 153 | b.Property("Name") 154 | .HasColumnType("nvarchar(max)"); 155 | 156 | b.HasKey("Id"); 157 | 158 | b.HasIndex("CharacterId") 159 | .IsUnique(); 160 | 161 | b.ToTable("Weapons"); 162 | }); 163 | 164 | modelBuilder.Entity("CharacterSkill", b => 165 | { 166 | b.HasOne("dotnet_rpg.Models.Character", null) 167 | .WithMany() 168 | .HasForeignKey("CharactersId") 169 | .OnDelete(DeleteBehavior.Cascade) 170 | .IsRequired(); 171 | 172 | b.HasOne("dotnet_rpg.Models.Skill", null) 173 | .WithMany() 174 | .HasForeignKey("SkillsId") 175 | .OnDelete(DeleteBehavior.Cascade) 176 | .IsRequired(); 177 | }); 178 | 179 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 180 | { 181 | b.HasOne("dotnet_rpg.Models.User", "User") 182 | .WithMany("Characters") 183 | .HasForeignKey("UserId"); 184 | 185 | b.Navigation("User"); 186 | }); 187 | 188 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 189 | { 190 | b.HasOne("dotnet_rpg.Models.Character", "Character") 191 | .WithOne("Weapon") 192 | .HasForeignKey("dotnet_rpg.Models.Weapon", "CharacterId") 193 | .OnDelete(DeleteBehavior.Cascade) 194 | .IsRequired(); 195 | 196 | b.Navigation("Character"); 197 | }); 198 | 199 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 200 | { 201 | b.Navigation("Weapon"); 202 | }); 203 | 204 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 205 | { 206 | b.Navigation("Characters"); 207 | }); 208 | #pragma warning restore 612, 618 209 | } 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /Migrations/20210326153529_FightProperties.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using dotnet_rpg.Data; 9 | 10 | namespace dotnet_rpg.Migrations 11 | { 12 | [DbContext(typeof(DataContext))] 13 | [Migration("20210326153529_FightProperties")] 14 | partial class FightProperties 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.2"); 23 | 24 | modelBuilder.Entity("CharacterSkill", b => 25 | { 26 | b.Property("CharactersId") 27 | .HasColumnType("int"); 28 | 29 | b.Property("SkillsId") 30 | .HasColumnType("int"); 31 | 32 | b.HasKey("CharactersId", "SkillsId"); 33 | 34 | b.HasIndex("SkillsId"); 35 | 36 | b.ToTable("CharacterSkill"); 37 | }); 38 | 39 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 40 | { 41 | b.Property("Id") 42 | .ValueGeneratedOnAdd() 43 | .HasColumnType("int") 44 | .UseIdentityColumn(); 45 | 46 | b.Property("Class") 47 | .HasColumnType("int"); 48 | 49 | b.Property("Defeats") 50 | .HasColumnType("int"); 51 | 52 | b.Property("Defense") 53 | .HasColumnType("int"); 54 | 55 | b.Property("Fights") 56 | .HasColumnType("int"); 57 | 58 | b.Property("HitPoints") 59 | .HasColumnType("int"); 60 | 61 | b.Property("Intelligence") 62 | .HasColumnType("int"); 63 | 64 | b.Property("Name") 65 | .HasColumnType("nvarchar(max)"); 66 | 67 | b.Property("Strength") 68 | .HasColumnType("int"); 69 | 70 | b.Property("UserId") 71 | .HasColumnType("int"); 72 | 73 | b.Property("Victories") 74 | .HasColumnType("int"); 75 | 76 | b.HasKey("Id"); 77 | 78 | b.HasIndex("UserId"); 79 | 80 | b.ToTable("Characters"); 81 | }); 82 | 83 | modelBuilder.Entity("dotnet_rpg.Models.Skill", b => 84 | { 85 | b.Property("Id") 86 | .ValueGeneratedOnAdd() 87 | .HasColumnType("int") 88 | .UseIdentityColumn(); 89 | 90 | b.Property("Damage") 91 | .HasColumnType("int"); 92 | 93 | b.Property("Name") 94 | .HasColumnType("nvarchar(max)"); 95 | 96 | b.HasKey("Id"); 97 | 98 | b.ToTable("Skills"); 99 | 100 | b.HasData( 101 | new 102 | { 103 | Id = 1, 104 | Damage = 30, 105 | Name = "Fireball" 106 | }, 107 | new 108 | { 109 | Id = 2, 110 | Damage = 20, 111 | Name = "Frenzy" 112 | }, 113 | new 114 | { 115 | Id = 3, 116 | Damage = 50, 117 | Name = "Blizzard" 118 | }); 119 | }); 120 | 121 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 122 | { 123 | b.Property("Id") 124 | .ValueGeneratedOnAdd() 125 | .HasColumnType("int") 126 | .UseIdentityColumn(); 127 | 128 | b.Property("PasswordHash") 129 | .HasColumnType("varbinary(max)"); 130 | 131 | b.Property("PasswordSalt") 132 | .HasColumnType("varbinary(max)"); 133 | 134 | b.Property("Username") 135 | .HasColumnType("nvarchar(max)"); 136 | 137 | b.HasKey("Id"); 138 | 139 | b.ToTable("Users"); 140 | }); 141 | 142 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 143 | { 144 | b.Property("Id") 145 | .ValueGeneratedOnAdd() 146 | .HasColumnType("int") 147 | .UseIdentityColumn(); 148 | 149 | b.Property("CharacterId") 150 | .HasColumnType("int"); 151 | 152 | b.Property("Damage") 153 | .HasColumnType("int"); 154 | 155 | b.Property("Name") 156 | .HasColumnType("nvarchar(max)"); 157 | 158 | b.HasKey("Id"); 159 | 160 | b.HasIndex("CharacterId") 161 | .IsUnique(); 162 | 163 | b.ToTable("Weapons"); 164 | }); 165 | 166 | modelBuilder.Entity("CharacterSkill", b => 167 | { 168 | b.HasOne("dotnet_rpg.Models.Character", null) 169 | .WithMany() 170 | .HasForeignKey("CharactersId") 171 | .OnDelete(DeleteBehavior.Cascade) 172 | .IsRequired(); 173 | 174 | b.HasOne("dotnet_rpg.Models.Skill", null) 175 | .WithMany() 176 | .HasForeignKey("SkillsId") 177 | .OnDelete(DeleteBehavior.Cascade) 178 | .IsRequired(); 179 | }); 180 | 181 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 182 | { 183 | b.HasOne("dotnet_rpg.Models.User", "User") 184 | .WithMany("Characters") 185 | .HasForeignKey("UserId"); 186 | 187 | b.Navigation("User"); 188 | }); 189 | 190 | modelBuilder.Entity("dotnet_rpg.Models.Weapon", b => 191 | { 192 | b.HasOne("dotnet_rpg.Models.Character", "Character") 193 | .WithOne("Weapon") 194 | .HasForeignKey("dotnet_rpg.Models.Weapon", "CharacterId") 195 | .OnDelete(DeleteBehavior.Cascade) 196 | .IsRequired(); 197 | 198 | b.Navigation("Character"); 199 | }); 200 | 201 | modelBuilder.Entity("dotnet_rpg.Models.Character", b => 202 | { 203 | b.Navigation("Weapon"); 204 | }); 205 | 206 | modelBuilder.Entity("dotnet_rpg.Models.User", b => 207 | { 208 | b.Navigation("Characters"); 209 | }); 210 | #pragma warning restore 612, 618 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /Services/FightService/FightService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using dotnet_rpg.Data; 7 | using dotnet_rpg.Dtos.Fight; 8 | using dotnet_rpg.Models; 9 | using Microsoft.EntityFrameworkCore; 10 | 11 | namespace dotnet_rpg.Services.FightService 12 | { 13 | public class FightService : IFightService 14 | { 15 | private readonly DataContext _context; 16 | private readonly IMapper _mapper; 17 | public FightService(DataContext context, IMapper mapper) 18 | { 19 | _mapper = mapper; 20 | _context = context; 21 | } 22 | 23 | public async Task> WeaponAttack(WeaponAttackDto request) 24 | { 25 | var response = new ServiceResponse(); 26 | try 27 | { 28 | var attacker = await _context.Characters 29 | .Include(c => c.Weapon) 30 | .FirstOrDefaultAsync(c => c.Id == request.AttackerId); 31 | 32 | var opponent = await _context.Characters 33 | .FirstOrDefaultAsync(c => c.Id == request.OpponentId); 34 | 35 | int damage = DoWeaponAttack(attacker, opponent); 36 | 37 | if (opponent.HitPoints <= 0) 38 | response.Message = $"{opponent.Name} has been defeated!"; 39 | 40 | await _context.SaveChangesAsync(); 41 | 42 | response.Data = new AttackResultDto 43 | { 44 | Attacker = attacker.Name, 45 | AttackerHP = attacker.HitPoints, 46 | Opponent = opponent.Name, 47 | OpponentHP = opponent.HitPoints, 48 | Damage = damage 49 | }; 50 | } 51 | catch (Exception ex) 52 | { 53 | response.Success = false; 54 | response.Message = ex.Message; 55 | } 56 | return response; 57 | } 58 | 59 | private static int DoWeaponAttack(Character attacker, Character opponent) 60 | { 61 | int damage = attacker.Weapon.Damage + (new Random().Next(attacker.Strength)); 62 | damage -= new Random().Next(opponent.Defense); 63 | 64 | if (damage > 0) 65 | opponent.HitPoints -= damage; 66 | return damage; 67 | } 68 | 69 | public async Task> SkillAttack(SkillAttackDto request) 70 | { 71 | var response = new ServiceResponse(); 72 | try 73 | { 74 | var attacker = await _context.Characters 75 | .Include(c => c.Skills) 76 | .FirstOrDefaultAsync(c => c.Id == request.AttackerId); 77 | 78 | var opponent = await _context.Characters 79 | .FirstOrDefaultAsync(c => c.Id == request.OpponentId); 80 | 81 | var skill = attacker.Skills.FirstOrDefault(s => s.Id == request.SkillId); 82 | if (skill == null) 83 | { 84 | response.Success = false; 85 | response.Message = $"{attacker.Name} doesn't know this skill."; 86 | return response; 87 | } 88 | 89 | int damage = DoSkillAttack(attacker, opponent, skill); 90 | 91 | if (opponent.HitPoints <= 0) 92 | response.Message = $"{opponent.Name} has been defeated!"; 93 | 94 | await _context.SaveChangesAsync(); 95 | 96 | response.Data = new AttackResultDto 97 | { 98 | Attacker = attacker.Name, 99 | AttackerHP = attacker.HitPoints, 100 | Opponent = opponent.Name, 101 | OpponentHP = opponent.HitPoints, 102 | Damage = damage 103 | }; 104 | } 105 | catch (Exception ex) 106 | { 107 | response.Success = false; 108 | response.Message = ex.Message; 109 | } 110 | return response; 111 | } 112 | 113 | private static int DoSkillAttack(Character attacker, Character opponent, Skill skill) 114 | { 115 | int damage = skill.Damage + (new Random().Next(attacker.Intelligence)); 116 | damage -= new Random().Next(opponent.Defense); 117 | 118 | if (damage > 0) 119 | opponent.HitPoints -= damage; 120 | return damage; 121 | } 122 | 123 | public async Task> Fight(FightRequestDto request) 124 | { 125 | var response = new ServiceResponse 126 | { 127 | Data = new FightResultDto() 128 | }; 129 | 130 | try 131 | { 132 | var characters = await _context.Characters 133 | .Include(c => c.Weapon) 134 | .Include(c => c.Skills) 135 | .Where(c => request.CharacterIds.Contains(c.Id)).ToListAsync(); 136 | 137 | bool defeated = false; 138 | while (!defeated) 139 | { 140 | foreach (var attacker in characters) 141 | { 142 | var opponents = characters.Where(c => c.Id != attacker.Id).ToList(); 143 | var opponent = opponents[new Random().Next(opponents.Count)]; 144 | 145 | int damage = 0; 146 | string attackUsed = string.Empty; 147 | 148 | bool useWeapon = new Random().Next(2) == 0; 149 | if (useWeapon) 150 | { 151 | attackUsed = attacker.Weapon.Name; 152 | damage = DoWeaponAttack(attacker, opponent); 153 | } 154 | else 155 | { 156 | var skill = attacker.Skills[new Random().Next(attacker.Skills.Count)]; 157 | attackUsed = skill.Name; 158 | damage = DoSkillAttack(attacker, opponent, skill); 159 | } 160 | 161 | response.Data.Log 162 | .Add($"{attacker.Name} attacks {opponent.Name} using {attackUsed} with {(damage >= 0 ? damage : 0)} damage."); 163 | 164 | if (opponent.HitPoints <= 0) 165 | { 166 | defeated = true; 167 | attacker.Victories++; 168 | opponent.Defeats++; 169 | response.Data.Log.Add($"{opponent.Name} has been defeated!"); 170 | response.Data.Log.Add($"{attacker.Name} wins with {attacker.HitPoints} HP left!"); 171 | break; 172 | } 173 | } 174 | } 175 | 176 | characters.ForEach(c => 177 | { 178 | c.Fights++; 179 | c.HitPoints = 100; 180 | }); 181 | 182 | await _context.SaveChangesAsync(); 183 | } 184 | catch (Exception ex) 185 | { 186 | 187 | response.Success = false; 188 | response.Message = ex.Message; 189 | } 190 | return response; 191 | } 192 | 193 | public async Task>> GetHighscore() 194 | { 195 | var characters = await _context.Characters 196 | .Where(c => c.Fights > 0) 197 | .OrderByDescending(c => c.Victories) 198 | .ThenBy(c => c.Defeats) 199 | .ToListAsync(); 200 | 201 | var response = new ServiceResponse> 202 | { 203 | Data = characters.Select(c => _mapper.Map(c)).ToList() 204 | }; 205 | 206 | return response; 207 | } 208 | } 209 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Coverlet is a free, cross platform Code Coverage Tool 141 | coverage*[.json, .xml, .info] 142 | 143 | # Visual Studio code coverage results 144 | *.coverage 145 | *.coveragexml 146 | 147 | # NCrunch 148 | _NCrunch_* 149 | .*crunch*.local.xml 150 | nCrunchTemp_* 151 | 152 | # MightyMoose 153 | *.mm.* 154 | AutoTest.Net/ 155 | 156 | # Web workbench (sass) 157 | .sass-cache/ 158 | 159 | # Installshield output folder 160 | [Ee]xpress/ 161 | 162 | # DocProject is a documentation generator add-in 163 | DocProject/buildhelp/ 164 | DocProject/Help/*.HxT 165 | DocProject/Help/*.HxC 166 | DocProject/Help/*.hhc 167 | DocProject/Help/*.hhk 168 | DocProject/Help/*.hhp 169 | DocProject/Help/Html2 170 | DocProject/Help/html 171 | 172 | # Click-Once directory 173 | publish/ 174 | 175 | # Publish Web Output 176 | *.[Pp]ublish.xml 177 | *.azurePubxml 178 | # Note: Comment the next line if you want to checkin your web deploy settings, 179 | # but database connection strings (with potential passwords) will be unencrypted 180 | *.pubxml 181 | *.publishproj 182 | 183 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 184 | # checkin your Azure Web App publish settings, but sensitive information contained 185 | # in these scripts will be unencrypted 186 | PublishScripts/ 187 | 188 | # NuGet Packages 189 | *.nupkg 190 | # NuGet Symbol Packages 191 | *.snupkg 192 | # The packages folder can be ignored because of Package Restore 193 | **/[Pp]ackages/* 194 | # except build/, which is used as an MSBuild target. 195 | !**/[Pp]ackages/build/ 196 | # Uncomment if necessary however generally it will be regenerated when needed 197 | #!**/[Pp]ackages/repositories.config 198 | # NuGet v3's project.json files produces more ignorable files 199 | *.nuget.props 200 | *.nuget.targets 201 | 202 | # Microsoft Azure Build Output 203 | csx/ 204 | *.build.csdef 205 | 206 | # Microsoft Azure Emulator 207 | ecf/ 208 | rcf/ 209 | 210 | # Windows Store app package directories and files 211 | AppPackages/ 212 | BundleArtifacts/ 213 | Package.StoreAssociation.xml 214 | _pkginfo.txt 215 | *.appx 216 | *.appxbundle 217 | *.appxupload 218 | 219 | # Visual Studio cache files 220 | # files ending in .cache can be ignored 221 | *.[Cc]ache 222 | # but keep track of directories ending in .cache 223 | !?*.[Cc]ache/ 224 | 225 | # Others 226 | ClientBin/ 227 | ~$* 228 | *~ 229 | *.dbmdl 230 | *.dbproj.schemaview 231 | *.jfm 232 | *.pfx 233 | *.publishsettings 234 | orleans.codegen.cs 235 | 236 | # Including strong name files can present a security risk 237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 238 | #*.snk 239 | 240 | # Since there are multiple workflows, uncomment next line to ignore bower_components 241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 242 | #bower_components/ 243 | 244 | # RIA/Silverlight projects 245 | Generated_Code/ 246 | 247 | # Backup & report files from converting an old project file 248 | # to a newer Visual Studio version. Backup files are not needed, 249 | # because we have git ;-) 250 | _UpgradeReport_Files/ 251 | Backup*/ 252 | UpgradeLog*.XML 253 | UpgradeLog*.htm 254 | ServiceFabricBackup/ 255 | *.rptproj.bak 256 | 257 | # SQL Server files 258 | *.mdf 259 | *.ldf 260 | *.ndf 261 | 262 | # Business Intelligence projects 263 | *.rdl.data 264 | *.bim.layout 265 | *.bim_*.settings 266 | *.rptproj.rsuser 267 | *- [Bb]ackup.rdl 268 | *- [Bb]ackup ([0-9]).rdl 269 | *- [Bb]ackup ([0-9][0-9]).rdl 270 | 271 | # Microsoft Fakes 272 | FakesAssemblies/ 273 | 274 | # GhostDoc plugin setting file 275 | *.GhostDoc.xml 276 | 277 | # Node.js Tools for Visual Studio 278 | .ntvs_analysis.dat 279 | node_modules/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # CodeRush personal settings 306 | .cr/personal 307 | 308 | # Python Tools for Visual Studio (PTVS) 309 | __pycache__/ 310 | *.pyc 311 | 312 | # Cake - Uncomment if you are using it 313 | # tools/** 314 | # !tools/packages.config 315 | 316 | # Tabs Studio 317 | *.tss 318 | 319 | # Telerik's JustMock configuration file 320 | *.jmconfig 321 | 322 | # BizTalk build output 323 | *.btp.cs 324 | *.btm.cs 325 | *.odx.cs 326 | *.xsd.cs 327 | 328 | # OpenCover UI analysis results 329 | OpenCover/ 330 | 331 | # Azure Stream Analytics local run output 332 | ASALocalRun/ 333 | 334 | # MSBuild Binary and Structured Log 335 | *.binlog 336 | 337 | # NVidia Nsight GPU debugger configuration file 338 | *.nvuser 339 | 340 | # MFractors (Xamarin productivity tool) working folder 341 | .mfractor/ 342 | 343 | # Local History for Visual Studio 344 | .localhistory/ 345 | 346 | # BeatPulse healthcheck temp database 347 | healthchecksdb 348 | 349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 350 | MigrationBackup/ 351 | 352 | # Ionide (cross platform F# VS Code tools) working folder 353 | .ionide/ 354 | 355 | ## 356 | ## Visual studio for Mac 357 | ## 358 | 359 | 360 | # globs 361 | Makefile.in 362 | *.userprefs 363 | *.usertasks 364 | config.make 365 | config.status 366 | aclocal.m4 367 | install-sh 368 | autom4te.cache/ 369 | *.tar.gz 370 | tarballs/ 371 | test-results/ 372 | 373 | # Mac bundle stuff 374 | *.dmg 375 | *.app 376 | 377 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 378 | # General 379 | .DS_Store 380 | .AppleDouble 381 | .LSOverride 382 | 383 | # Icon must end with two \r 384 | Icon 385 | 386 | 387 | # Thumbnails 388 | ._* 389 | 390 | # Files that might appear in the root of a volume 391 | .DocumentRevisions-V100 392 | .fseventsd 393 | .Spotlight-V100 394 | .TemporaryItems 395 | .Trashes 396 | .VolumeIcon.icns 397 | .com.apple.timemachine.donotpresent 398 | 399 | # Directories potentially created on remote AFP share 400 | .AppleDB 401 | .AppleDesktop 402 | Network Trash Folder 403 | Temporary Items 404 | .apdisk 405 | 406 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 407 | # Windows thumbnail cache files 408 | Thumbs.db 409 | ehthumbs.db 410 | ehthumbs_vista.db 411 | 412 | # Dump file 413 | *.stackdump 414 | 415 | # Folder config file 416 | [Dd]esktop.ini 417 | 418 | # Recycle Bin used on file shares 419 | $RECYCLE.BIN/ 420 | 421 | # Windows Installer files 422 | *.cab 423 | *.msi 424 | *.msix 425 | *.msm 426 | *.msp 427 | 428 | # Windows shortcuts 429 | *.lnk 430 | 431 | # JetBrains Rider 432 | .idea/ 433 | *.sln.iml 434 | 435 | ## 436 | ## Visual Studio Code 437 | ## 438 | .vscode/* 439 | !.vscode/settings.json 440 | !.vscode/tasks.json 441 | !.vscode/launch.json 442 | !.vscode/extensions.json 443 | --------------------------------------------------------------------------------