public async Task BigAccounts(int seedForRandom) { //Arrange string serviceId = "serviceId"; Account originalAccount = await DefaultAccountFactoryService.CreateDefaultAccountAsync(serviceId); int originalAccountRating = originalAccount.GetAccountRating(); int originalAccountSoftCurrency = originalAccount.GetAccountSoftCurrency(); int originalAccountHardCurrency = originalAccount.GetAccountHardCurrency(); //Act AccountDbDto accountDbDto = await AccountDbReaderService.ReadAccountAsync(originalAccount.ServiceId); //Assert Assert.IsNotNull(accountDbDto); Assert.AreEqual(originalAccount.Username, accountDbDto.Username); Assert.AreEqual(originalAccount.ServiceId, accountDbDto.ServiceId); Assert.AreEqual(originalAccountRating, accountDbDto.Rating); Assert.AreEqual(originalAccountSoftCurrency, accountDbDto.SoftCurrency); Assert.AreEqual(originalAccountHardCurrency, accountDbDto.HardCurrency); foreach (var warship in originalAccount.Warships) { WarshipDbDto warshipDbDto = accountDbDto.Warships.Single(w => w.Id == warship.Id); int originalWarshipRating = originalAccount.GetWarshipRating(warship.Id); int originalWarshipPowerPoints = originalAccount.GetWarshipPowerPoints(warship.Id); Assert.AreEqual(originalWarshipRating, warshipDbDto.WarshipRating); Assert.AreEqual(originalWarshipPowerPoints, warshipDbDto.WarshipPowerPoints); } }
public async Task <bool> TryEnqueuePlayerAsync(string playerServiceId, int warshipId) { AccountDbDto accountDbDto = await dbAccountWarshipReaderService.ReadAsync(playerServiceId); if (accountDbDto == null) { return(false); } WarshipDbDto warship = accountDbDto.Warships.SingleOrDefault(dto => dto.Id == warshipId); if (warship == null) { Console.WriteLine("Корабль не принадлежит этому игроку"); return(false); } string warshipSkinName = warship.CurrentSkinType.Name; Console.WriteLine(warshipSkinName); MatchEntryRequest matchEntryRequest = new MatchEntryRequest(playerServiceId, accountDbDto.Id, warship.WarshipType.Name, warship.WarshipPowerLevel, warshipId, DateTime.UtcNow, accountDbDto.Username, warshipSkinName); return(battleRoyaleQueueSingletonServiceService.TryEnqueue(matchEntryRequest)); }
public async Task <LootboxModel> CreateLootboxModelAsync([NotNull] string playerServiceId) { //Достать аккаунт AccountDbDto accountDbDto = await accountDbReaderService.ReadAccountAsync(playerServiceId); if (accountDbDto == null) { Console.WriteLine("попытка купить лутбокс для аккаунта, которого не существует."); return(null); } //Ресурсов для покупки хватает? if (accountDbDto.LootboxPoints < 100) { Console.WriteLine("Не хватает ресурсов для покупки лутбокса"); return(null); } //Создать лутбокс LootboxModel lootboxModel = smallLootboxModelFactory.Create(accountDbDto.Warships); //Сохранить лутбокс await lootboxDbWriterService.WriteAsync(playerServiceId, lootboxModel); return(lootboxModel); }
public async Task <LobbyModel> CreateAsync([NotNull] string playerServiceId) { AccountDbDto account = await accountFacadeService.ReadOrCreateAccountAsync(playerServiceId); if (account == null) { throw new NullReferenceException(nameof(account)); } RewardsThatHaveNotBeenShown rewardsThatHaveNotBeenShown = await notShownRewardsReaderService .GetNotShownRewardAndMarkAsRead(playerServiceId); WarshipRatingScaleModel warshipRatingScaleModel = warshipRatingScale.GetWarshipRatingScaleModel(); if (warshipRatingScaleModel == null) { throw new Exception($"{nameof(warshipRatingScaleModel)} was null"); } AccountDto accountDto = accountMapperService.Map(account); LobbyModel lobbyModel = new LobbyModel { AccountDto = accountDto, RewardsThatHaveNotBeenShown = rewardsThatHaveNotBeenShown, WarshipRatingScaleModel = warshipRatingScaleModel }; lobbyModel.BundleVersion = bundleVersionService.GetBundleVersion(); return(lobbyModel); }
/// <summary> /// Создаёт список из id кораблей, для которых будут созданы улучшения /// </summary> /// <param name="accountDbDto"></param> /// <returns></returns> private List <TmpWarshipDich> GetWarshipModels(AccountDbDto accountDbDto) { //Обеспечит одинаковые товары для аккаунта на протяжении дня. int randomSeed = DateTime.UtcNow.Day; List <TmpWarshipDich> warshipIds = accountDbDto.Warships.Select(dto => new TmpWarshipDich() { warshipId = dto.Id, warshipType = dto.WarshipTypeId }).ToList(); //Если у аккаунта слишком мало кораблей, то они будут повторяться if (warshipIds.Count < NumberOfProducts) { Random random = new Random(randomSeed); int numberOfDeficientProducts = NumberOfProducts - warshipIds.Count; int warshipIdsCount = warshipIds.Count; for (int j = 0; j < numberOfDeficientProducts; j++) { warshipIds.Add(warshipIds[random.Next(warshipIdsCount)]); } } warshipIds.Shuffle(randomSeed); return(warshipIds); }
public async Task <SectionModel> Create([NotNull] AccountDbDto accountDbDto) { // ProductModel prizeProductModel = await prizeFactoryService.CreatePrizeProduct(accountDbDto.Id); List <ProductModel> warshipPowerPoints = wppProductsFactoryService .CreateWarshipPowerPointProducts(accountDbDto); // foreach (ProductModel warshipPowerPoint in warshipPowerPoints) // { // Console.WriteLine(warshipPowerPoint.WarshipPowerPointsProduct.WarshipId); // } List <ProductModel> productModels = new List <ProductModel>(); // productModels.Add(prizeProductModel); productModels.AddRange(warshipPowerPoints); if (productModels.Count % 2 != 0) { throw new Exception("Нечётное кол-во элементов"); } ProductModel[][] uiItems = new ProductModel[2][]; uiItems[0] = productModels.Take(3).ToArray(); uiItems[1] = productModels.TakeLast(3).ToArray(); SectionModel sectionModel = new SectionModel { HeaderName = "DAILY DEALS", NeedFooterPointer = true, UiItems = uiItems }; return(sectionModel); }
public AccountDto Map(AccountDbDto account) { AccountDto result = new AccountDto { Username = account.Username, AccountRating = account.Rating, SoftCurrency = account.SoftCurrency, HardCurrency = account.HardCurrency, BigLootboxPoints = 0, SmallLootboxPoints = account.LootboxPoints, Warships = new List <WarshipDto>(), AccountId = account.Id }; foreach (WarshipDbDto warshipDbDto in account.Warships) { WarshipDto warshipDto = new WarshipDto(); warshipDto.Rating = warshipDbDto.WarshipRating; warshipDto.CombatRoleName = warshipDbDto.WarshipType.WarshipCombatRole.Name; warshipDto.Description = warshipDbDto.WarshipType.Description; warshipDto.WarshipName = warshipDbDto.WarshipType.Name; warshipDto.PowerPoints = warshipDbDto.WarshipPowerPoints; warshipDto.Id = warshipDbDto.Id; warshipDto.PowerLevel = warshipDbDto.WarshipPowerLevel; warshipDto.WarshipCharacteristics = warshipsCharacteristicsService .GetWarshipCharacteristics(warshipDbDto.WarshipType.Id); warshipDto.WarshipTypeEnum = warshipDbDto.WarshipType.Id; List <SkinTypeDto> skinTypeDtos = new List <SkinTypeDto>(); foreach (SkinType skinType in warshipDbDto.Skins) { SkinTypeDto skinTypeDto = new SkinTypeDto() { Id = skinType.Id, Name = skinType.Name }; skinTypeDtos.Add(skinTypeDto); } warshipDto.Skins = skinTypeDtos; warshipDto.CurrentSkinIndex = warshipDto.Skins .FindIndex((skin) => skin.Id == warshipDbDto.CurrentSkinTypeId); result.Warships.Add(warshipDto); } return(result); }
public async Task <AccountDbDto> ReadAccountAsync([NotNull] string playerServiceId) { AccountDbDto accountDbDto = await dbAccountWarshipReaderService.ReadAsync(playerServiceId); if (accountDbDto == null) { return(null); } AccountResources accountResources = await accountResourcesDbReader.ReadAsync(playerServiceId); accountDbDto.HardCurrency = accountResources.HardCurrency; accountDbDto.SoftCurrency = accountResources.SoftCurrency; accountDbDto.LootboxPoints = accountResources.LootboxPoints; return(accountDbDto); }
public async Task <AccountDbDto> ReadAsync(string playerServiceId) { AccountDbDto accountDbDto = await dbWarshipsStatisticsReader.ReadAsync(playerServiceId); if (accountDbDto == null) { return(null); } // foreach (var warshipDbDto in accountDbDto.Warships) // { // Console.WriteLine("очки силы корабля "+warshipDbDto.WarshipPowerPoints); // } //заполнить список скинов для всех типов кораблей //warshipId, список скинов Dictionary <int, List <SkinType> > skinsDict = await skinsDbReaderService.ReadAsync(accountDbDto.Id); if (skinsDict == null || skinsDict.Count == 0) { throw new Exception("warship has no skin"); } foreach ((int warshipId, List <SkinType> list) in skinsDict) { WarshipDbDto warship = accountDbDto.Warships.Single(warship1 => warship1.Id == warshipId); warship.Skins.AddRange(list); warship.CurrentSkinType = list .Single(skinType => skinType.Id == warship.CurrentSkinTypeId); } foreach (WarshipDbDto warshipDbDto in accountDbDto.Warships) { if (warshipDbDto.WarshipPowerLevel == 0) { throw new Exception("Нулевой уровень " + nameof(AccountDbReaderService)); } if (warshipDbDto.Skins == null || warshipDbDto.Skins.Count == 0) { throw new Exception("Warship have no skins"); } } return(accountDbDto); }
public async Task <AccountDbDto> ReadOrCreateAccountAsync([NotNull] string serviceId) { AccountDbDto account = await accountDbReaderService.ReadAccountAsync(serviceId); if (account == null) { Console.WriteLine("Попытка создать аккаунт"); if (await accountRegistrationService.TryRegisterAccountAsync(serviceId)) { Console.WriteLine("Успешная регистрация"); account = await accountDbReaderService.ReadAccountAsync(serviceId); } else { throw new Exception("Не удалось выполнить регистрацию аккаунта"); } } return(account); }
public async Task <NetworkLibrary.NetworkLibrary.Http.ShopModel> Create([NotNull] string playerServiceId) { AccountDbDto accountDbDto = await accountDbReaderService.ReadAccountAsync(playerServiceId); if (accountDbDto == null) { throw new Exception("Игрок ещё не зарегистрирован"); } NetworkLibrary.NetworkLibrary.Http.ShopModel shopModel = new NetworkLibrary.NetworkLibrary.Http.ShopModel { UiSections = new List <SectionModel>() }; shopModel.UiSections.Add(await dailyDealsSectionFactory.Create(accountDbDto)); shopModel.UiSections.Add(hardCurrencySectionFactory.Create()); shopModel.UiSections.Add(softCurrencySectionFactory.Create()); // shopModel.UiSections.Add(new SkinsSectionFactory().Create()); // shopModel.UiSections.Add(new WarshipsSectionFactory().Create()); // shopModel.UiSections.Add(new LootboxSectionFactory().Create()); // shopModel.UiSections.Add(new SoftCurrencySectionFactory().Create()); //Присвоить продуктам уникальные id int startIndex = 1; foreach (ProductModel productModel in shopModel.UiSections .SelectMany(section => section.UiItems) .SelectMany(item => item)) { productModel.Id = startIndex++; } return(shopModel); }
/// <summary> /// Создаёт продукты, которые содержат улучшения для кораблей, которые есть в наличии у аккаунта /// </summary> /// <param name="accountDbDto"></param> /// <returns></returns> public List <ProductModel> CreateWarshipPowerPointProducts(AccountDbDto accountDbDto) { List <TmpWarshipDich> warshipIds = GetWarshipModels(accountDbDto); List <ProductModel> warshipPowerPoints = new List <ProductModel>(); for (int index = 0; index < NumberOfProducts; index++) { int warshipId = warshipIds[index].warshipId; WarshipTypeEnum warshipType = warshipIds[index].warshipType; WarshipDbDto warshipDbDto = accountDbDto.Warships .Single(dto => dto.Id == warshipId); string previewPath = warshipDbDto.WarshipType.Name.ToLower(); ProductModel wpp = factory.Create(140, previewPath, 42, warshipId, warshipType); warshipPowerPoints.Add(wpp); } foreach (var productModel in warshipPowerPoints) { WarshipPowerPointsProductModel model = productModel; } return(warshipPowerPoints); }
public async Task <bool> TryBuyLevel([NotNull] string serviceId, int warshipId) { //Аккаунт существует? AccountDbDto accountDbDto = await accountDbReaderService.ReadAccountAsync(serviceId); if (accountDbDto == null) { throw new Exception("Такого аккаунта не существует"); } //Корабль существует? WarshipDbDto warshipDbDto = accountDbDto.Warships.SingleOrDefault(dto => dto.Id == warshipId); if (warshipDbDto == null) { throw new Exception("Этому аккаунту не принаждлежит этот корабль"); } bool canAPurchaseBeMade = warshipImprovementCostChecker .CanAPurchaseBeMade(accountDbDto.SoftCurrency, warshipDbDto.WarshipPowerLevel, warshipDbDto.WarshipPowerPoints, out var faultReason); if (!canAPurchaseBeMade) { throw new Exception("Невозможно осуществить покупку улучшения для корабля по причине " + faultReason); } WarshipImprovementModel improvementModel = warshipImprovementCostChecker.GetImprovementModel(warshipDbDto.WarshipPowerLevel); Console.WriteLine("текущий wpp " + warshipDbDto.WarshipPowerLevel); //Записать транзакцию Transaction transaction = new Transaction { AccountId = accountDbDto.Id, DateTime = DateTime.UtcNow, TransactionTypeId = TransactionTypeEnum.WarshipImprovement, WasShown = false, Increments = new List <Increment> { new Increment { IncrementTypeId = IncrementTypeEnum.WarshipLevel, Amount = warshipDbDto.WarshipPowerLevel + 1, WarshipId = warshipId } }, Decrements = new List <Decrement> { new Decrement { DecrementTypeId = DecrementTypeEnum.SoftCurrency, Amount = improvementModel.SoftCurrencyCost }, new Decrement { DecrementTypeId = DecrementTypeEnum.WarshipPowerPoints, Amount = improvementModel.PowerPointsCost, WarshipId = warshipDbDto.Id } } }; await dbContext.Transactions.AddAsync(transaction); await dbContext.SaveChangesAsync(); return(true); }
public async Task BuyProduct(string playerServiceId, int productId, string base64ProductModelFromClient, int shopModelId) { //Аккаунт существует? AccountDbDto accountDbDto = await dbReaderService.ReadAccountAsync(playerServiceId); if (accountDbDto == null) { throw new Exception($"Такого аккаунта не существует {nameof(playerServiceId)} {playerServiceId}"); } //Модель магазина существует? ShopModelDb shopModelDb = await dbContext .ShopModels .Where(shopModelDb1 => shopModelDb1.Id == shopModelId) .SingleOrDefaultAsync(); if (shopModelDb == null) { throw new Exception($"Такой модели магазина не существует {nameof(shopModelId)} {shopModelId}"); } //Эта модель создана для этого аккаунта? if (accountDbDto.Id != shopModelDb.AccountId) { throw new Exception("Модель магазина не относится к этому аккаунту"); } //Эта модель не просрочена? if (DateTime.UtcNow - shopModelDb.CreationDateTime > TimeSpan.FromDays(3)) { throw new Exception("Модель магазина просрочена"); } //В модели магазина из БД есть продукт с таким же id? NetworkLibrary.NetworkLibrary.Http.ShopModel shopModel; try { shopModel = ZeroFormatterSerializer .Deserialize <NetworkLibrary.NetworkLibrary.Http.ShopModel>(shopModelDb.SerializedModel); } catch { throw new Exception("Не удалось десериализовать модель продукта при чтении из БД"); } if (shopModel == null) { throw new Exception("Не удалось достать модель магазина для игрока"); } ProductModel productModelFromDb = shopModel.UiSections .SelectMany(uiSection => uiSection.UiItems) .SelectMany(arr => arr) .SingleOrDefault(productModel1 => productModel1.Id == productId); if (productModelFromDb == null) { throw new Exception("В модели магазина такого продукта нет."); } //Продукт из БД совпадает с присланным с клиента? byte[] serializedProductModelFromClient = Convert.FromBase64String(base64ProductModelFromClient); byte[] serializedProductModelFromDb = ZeroFormatterSerializer.Serialize(productModelFromDb); var productModelFromClient = ZeroFormatterSerializer .Deserialize <ProductModel>(serializedProductModelFromClient); bool isEqual = new ProductChecker().IsEqual(productModelFromClient, productModelFromDb); if (!isEqual) { Console.WriteLine(serializedProductModelFromClient.Length.ToString()); Console.WriteLine(serializedProductModelFromDb.Length.ToString()); throw new Exception("Модели продуктов не совпадают"); } bool isResourcesEnough = costCheckerService .IsResourcesEnough(productModelFromClient, accountDbDto.SoftCurrency, accountDbDto.HardCurrency); if (!isResourcesEnough) { throw new Exception("Не хватает ресурсов."); } //создать транзакцию по модели продукта Transaction transaction = shopTransactionFactory.Create(productModelFromDb, accountDbDto.Id); //todo проверить транзакцию на адекватность //записать транзакцию await dbContext.Transactions.AddAsync(transaction); //перезаписать модель продукта if (productModelFromDb.ResourceTypeEnum == ResourceTypeEnum.WarshipPowerPoints) { productModelFromDb.IsDisabled = true; shopModelDb.SerializedModel = ZeroFormatterSerializer.Serialize(shopModel); } await dbContext.SaveChangesAsync(); }