public static CharacterItem GetAvailableWeapon(this ICharacterData data, ref bool isLeftHand) { CharacterItem rightHand = data.EquipWeapons.rightHand; Item rightWeaponItem = rightHand.GetWeaponItem(); CharacterItem leftHand = data.EquipWeapons.leftHand; Item leftWeaponItem = leftHand.GetWeaponItem(); if (!isLeftHand) { if (rightWeaponItem != null) { return(rightHand); } if (rightWeaponItem == null && leftWeaponItem != null) { isLeftHand = true; return(leftHand); } } else { if (leftWeaponItem != null) { return(leftHand); } if (leftWeaponItem == null && rightWeaponItem != null) { isLeftHand = false; return(rightHand); } } isLeftHand = false; return(CharacterItem.Create(GameInstance.Singleton.DefaultWeaponItem)); }
protected virtual void OnSelectCharacterClass(BaseCharacter baseCharacter) { eventOnSelectCharacterClass.Invoke(baseCharacter); PlayerCharacterByDataId.TryGetValue(baseCharacter.DataId, out selectedPlayerCharacter); if (SelectedPlayerCharacter != null) { // Set creating player character data SelectedDataId = baseCharacter.DataId; // Prepare equip items List <CharacterItem> equipItems = new List <CharacterItem>(); foreach (Item armorItem in SelectedPlayerCharacter.armorItems) { if (armorItem == null) { continue; } equipItems.Add(CharacterItem.Create(armorItem)); } // Set model equip items SelectedModel.SetEquipItems(equipItems); // Prepare equip weapons EquipWeapons equipWeapons = new EquipWeapons(); if (SelectedPlayerCharacter.rightHandEquipItem != null) { equipWeapons.rightHand = CharacterItem.Create(SelectedPlayerCharacter.rightHandEquipItem); } if (SelectedPlayerCharacter.leftHandEquipItem != null) { equipWeapons.leftHand = CharacterItem.Create(SelectedPlayerCharacter.leftHandEquipItem); } // Set model equip weapons SelectedModel.SetEquipWeapons(equipWeapons); } }
protected virtual void NetFuncBuyNpcItem(short itemIndex, short amount) { if (currentNpcDialog == null) { return; } NpcSellItem[] sellItems = currentNpcDialog.sellItems; if (sellItems == null || itemIndex >= sellItems.Length) { return; } NpcSellItem sellItem = sellItems[itemIndex]; if (!gameplayRule.CurrenciesEnoughToBuyItem(this, sellItem, amount)) { gameManager.SendServerGameMessage(ConnectionId, GameMessage.Type.NotEnoughGold); return; } int dataId = sellItem.item.DataId; if (this.IncreasingItemsWillOverwhelming(dataId, amount)) { gameManager.SendServerGameMessage(ConnectionId, GameMessage.Type.CannotCarryAnymore); return; } gameplayRule.DecreaseCurrenciesWhenBuyItem(this, sellItem, amount); this.IncreaseItems(CharacterItem.Create(dataId, 1, amount)); }
public static CharacterItem GetRandomedWeapon(this ICharacterData data, out bool isLeftHand) { isLeftHand = false; // Find right hand and left and to set result weapon var rightHand = data.EquipWeapons.rightHand; var leftHand = data.EquipWeapons.leftHand; var rightWeaponItem = rightHand.GetWeaponItem(); var leftWeaponItem = leftHand.GetWeaponItem(); if (rightWeaponItem != null && leftWeaponItem != null) { // Random right hand or left hand weapon isLeftHand = Random.Range(0, 1) == 1; return(!isLeftHand ? rightHand : leftHand); } else if (rightWeaponItem != null) { isLeftHand = false; return(rightHand); } else if (leftWeaponItem != null) { isLeftHand = true; return(leftHand); } return(CharacterItem.Create(GameInstance.Singleton.DefaultWeaponItem)); }
protected override void UpdateData() { var skill = Data; if (uiCraftingItem != null) { if (skill == null || skill.craftingItem == null) { uiCraftingItem.Hide(); } else { uiCraftingItem.Show(); uiCraftingItem.Data = new CharacterItemLevelTuple(CharacterItem.Create(skill.craftingItem), 1); } } if (uiRequireItemAmounts != null) { if (skill == null) { uiRequireItemAmounts.Hide(); } else { uiRequireItemAmounts.Show(); uiRequireItemAmounts.Data = skill.CacheCraftRequirements; } } }
private IEnumerator HandleRequestCashShopBuyRoutine(LiteNetLibMessageHandler messageHandler) { var connectionId = messageHandler.connectionId; var message = messageHandler.ReadMessage <RequestCashShopBuyMessage>(); var error = ResponseCashShopBuyMessage.Error.None; var dataId = message.dataId; var cash = 0; BasePlayerCharacterEntity playerCharacter; UserCharacterData userData; if (!playerCharacters.TryGetValue(connectionId, out playerCharacter) || !usersById.TryGetValue(playerCharacter.Id, out userData)) { error = ResponseCashShopBuyMessage.Error.UserNotFound; } else { // Request cash, reduce, send item info messages to map server var job = new GetCashJob(Database, userData.userId); job.Start(); yield return(StartCoroutine(job.WaitFor())); cash = job.result; CashShopItem cashShopItem; if (!GameInstance.CashShopItems.TryGetValue(dataId, out cashShopItem)) { error = ResponseCashShopBuyMessage.Error.ItemNotFound; } else if (cash < cashShopItem.sellPrice) { error = ResponseCashShopBuyMessage.Error.NotEnoughCash; } else { var decreaseCashJob = new DecreaseCashJob(Database, userData.userId, cashShopItem.sellPrice); decreaseCashJob.Start(); yield return(StartCoroutine(decreaseCashJob.WaitFor())); cash = decreaseCashJob.result; playerCharacter.Gold += cashShopItem.receiveGold; foreach (var receiveItem in cashShopItem.receiveItems) { if (receiveItem.item == null) { continue; } var characterItem = CharacterItem.Create(receiveItem.item, 1, receiveItem.amount); playerCharacter.NonEquipItems.Add(characterItem); } } } var responseMessage = new ResponseCashShopBuyMessage(); responseMessage.ackId = message.ackId; responseMessage.responseCode = error == ResponseCashShopBuyMessage.Error.None ? AckResponseCode.Success : AckResponseCode.Error; responseMessage.error = error; responseMessage.cash = cash; ServerSendPacket(connectionId, SendOptions.ReliableOrdered, MsgTypes.CashShopBuy, responseMessage); }
protected override void UpdateData() { BasePlayerCharacterEntity owningCharacter = BasePlayerCharacterController.OwningCharacter; if (uiCraftingItem != null) { if (CraftingItem == null) { // Hide if crafting item is null uiCraftingItem.Hide(); } else { uiCraftingItem.Show(); uiCraftingItem.Data = new CharacterItemTuple(CharacterItem.Create(CraftingItem), 1, InventoryType.NonEquipItems); } } if (uiRequireItemAmounts != null) { if (CraftingItem == null) { // Hide if crafting item is null uiRequireItemAmounts.Hide(); } else { uiRequireItemAmounts.showAsRequirement = true; uiRequireItemAmounts.Show(); uiRequireItemAmounts.Data = ItemCraft.CacheCraftRequirements; } } if (uiTextRequireGold != null) { if (CraftingItem == null) { uiTextRequireGold.text = string.Format( LanguageManager.GetText(formatKeyRequireGold), "0", "0"); } else { int currentAmount = 0; if (owningCharacter != null) { currentAmount = owningCharacter.Gold; } uiTextRequireGold.text = string.Format( currentAmount >= ItemCraft.RequireGold ? LanguageManager.GetText(formatKeyRequireGold) : LanguageManager.GetText(formatKeyRequireGoldNotEnough), currentAmount.ToString("N0"), ItemCraft.RequireGold.ToString("N0")); } } }
private void GiveGuildBattleRewardTo(int winnerGuildId) { GuildWarMapInfo mapInfo = CurrentMapInfo as GuildWarMapInfo; string mailTitle; string mailContent; int rewardGold; CurrencyAmount[] rewardCurrencies; ItemAmount[] rewardItems; Mail tempMail; foreach (IPlayerCharacterData participant in ServerUserHandlers.GetPlayerCharacters()) { if (participant.GuildId == winnerGuildId) { mailTitle = mapInfo.winMailTitle; mailContent = mapInfo.winMailContent; rewardGold = mapInfo.winRewardGold; rewardCurrencies = mapInfo.winRewardCurrencies; rewardItems = mapInfo.winRewardItems; } else { mailTitle = mapInfo.participantMailTitle; mailContent = mapInfo.participantMailContent; rewardGold = mapInfo.participantRewardGold; rewardCurrencies = mapInfo.participantRewardCurrencies; rewardItems = mapInfo.participantRewardItems; } tempMail = new Mail() { SenderId = guildWarMailSenderId, SenderName = guildWarMailSenderName, ReceiverId = participant.UserId, Title = mailTitle, Content = mailContent, Gold = rewardGold, }; foreach (CurrencyAmount currencyAmount in rewardCurrencies) { if (currencyAmount.currency == null) { continue; } tempMail.Currencies.Add(CharacterCurrency.Create(currencyAmount.currency.DataId, currencyAmount.amount)); } foreach (ItemAmount itemAmount in rewardItems) { if (itemAmount.item == null) { continue; } tempMail.Items.Add(CharacterItem.Create(itemAmount.item, 1, itemAmount.amount)); } ServerMailHandlers.SendMail(tempMail); } }
public override void ReceiveDamage(IAttackerEntity attacker, CharacterItem weapon, Dictionary <DamageElement, MinMaxFloat> allDamageAmounts, CharacterBuff debuff, uint hitEffectsId) { if (!IsServer || IsDead() || weapon == null) { return; } base.ReceiveDamage(attacker, weapon, allDamageAmounts, debuff, hitEffectsId); BaseCharacterEntity attackerCharacter = attacker as BaseCharacterEntity; // Play hit effect if (hitEffectsId == 0) { hitEffectsId = gameInstance.DefaultHitEffects.Id; } if (hitEffectsId > 0) { RequestPlayEffect(hitEffectsId); } // Apply damages int totalDamage = 0; Item weaponItem = weapon.GetWeaponItem(); HarvestEffectiveness harvestEffectiveness; WeightedRandomizer <ItemDropByWeight> itemRandomizer; if (harvestable.CacheHarvestEffectivenesses.TryGetValue(weaponItem.weaponType, out harvestEffectiveness) && harvestable.CacheHarvestItems.TryGetValue(weaponItem.weaponType, out itemRandomizer)) { totalDamage = (int)(weaponItem.harvestDamageAmount.GetAmount(weapon.level).Random() * harvestEffectiveness.damageEffectiveness); ItemDropByWeight receivingItem = itemRandomizer.TakeOne(); int dataId = receivingItem.item.DataId; short amount = (short)(receivingItem.amountPerDamage * totalDamage); bool droppingToGround = collectType == HarvestableCollectType.DropToGround; if (attackerCharacter.IncreasingItemsWillOverwhelming(dataId, amount)) { droppingToGround = true; } if (!droppingToGround) { attackerCharacter.IncreaseItems(CharacterItem.Create(dataId, 1, amount)); } else { ItemDropEntity.DropItem(this, CharacterItem.Create(dataId, 1, amount), new uint[0]); } } CurrentHp -= totalDamage; ReceivedDamage(attackerCharacter, CombatAmountType.NormalDamage, totalDamage); if (IsDead()) { CurrentHp = 0; CallNetFunction(NetFuncOnHarvestableDestroy, FunctionReceivers.All); DestroyAndRespawn(); } }
protected virtual void NetFuncCompleteQuest(int questDataId) { int indexOfQuest = this.IndexOfQuest(questDataId); Quest quest; if (indexOfQuest < 0 || !GameInstance.Quests.TryGetValue(questDataId, out quest)) { return; } CharacterQuest characterQuest = quests[indexOfQuest]; if (!characterQuest.IsAllTasksDone(this)) { return; } if (characterQuest.isComplete) { return; } QuestTask[] tasks = quest.tasks; foreach (QuestTask task in tasks) { switch (task.taskType) { case QuestTaskType.CollectItem: this.DecreaseItems(task.itemAmount.item.DataId, task.itemAmount.amount); break; } } Reward reward = gameplayRule.MakeQuestReward(quest); RewardExp(reward, 1f, RewardGivenType.Quest); RewardCurrencies(reward, 1f, RewardGivenType.Quest); ItemAmount[] rewardItems = quest.rewardItems; if (rewardItems != null && rewardItems.Length > 0) { foreach (ItemAmount rewardItem in rewardItems) { if (rewardItem.item != null && rewardItem.amount > 0) { this.IncreaseItems(CharacterItem.Create(rewardItem.item, 1, rewardItem.amount)); } } } characterQuest.isComplete = true; if (!quest.canRepeat) { quests[indexOfQuest] = characterQuest; } else { quests.RemoveAt(indexOfQuest); } }
public void CraftItem(IPlayerCharacterData character) { if (character.IncreaseItems(CharacterItem.Create(craftingItem))) { // Reduce item when able to increase craft item foreach (ItemAmount craftRequirement in craftRequirements) { if (craftRequirement.item != null && craftRequirement.amount > 0) { character.DecreaseItems(craftRequirement.item.DataId, craftRequirement.amount); } } // Decrease required gold GameInstance.Singleton.GameplayRule.DecreaseCurrenciesWhenCraftItem(character, this); } }
public static ItemDropEntity DropItem(RpgNetworkEntity dropper, int itemDataId, short level, short amount) { var gameInstance = GameInstance.Singleton; var dropPosition = dropper.CacheTransform.position + new Vector3(Random.Range(-1f, 1f) * gameInstance.dropDistance, 0, Random.Range(-1f, 1f) * gameInstance.dropDistance); // Raycast to find hit floor Vector3? aboveHitPoint = null; Vector3? underHitPoint = null; var raycastLayerMask = ~(gameInstance.characterLayer.Mask | gameInstance.itemDropLayer.Mask); RaycastHit tempHit; if (Physics.Raycast(dropPosition, Vector3.up, out tempHit, 100f, raycastLayerMask)) { aboveHitPoint = tempHit.point; } if (Physics.Raycast(dropPosition, Vector3.down, out tempHit, 100f, raycastLayerMask)) { underHitPoint = tempHit.point; } // Set drop position to nearest hit point if (aboveHitPoint.HasValue && underHitPoint.HasValue) { if (Vector3.Distance(dropPosition, aboveHitPoint.Value) < Vector3.Distance(dropPosition, underHitPoint.Value)) { dropPosition = aboveHitPoint.Value; } else { dropPosition = underHitPoint.Value; } } else if (aboveHitPoint.HasValue) { dropPosition = aboveHitPoint.Value; } else if (underHitPoint.HasValue) { dropPosition = underHitPoint.Value; } // Random rotation var dropRotation = Vector3.up * Random.Range(0, 360); var identity = dropper.Manager.Assets.NetworkSpawn(gameInstance.itemDropEntityPrefab.gameObject, dropPosition, Quaternion.Euler(dropRotation)); var itemDropEntity = identity.GetComponent <ItemDropEntity>(); var dropData = CharacterItem.Create(itemDataId, level, amount); itemDropEntity.dropData = dropData; return(itemDropEntity); }
/// <summary> /// Returns a random collection of item drops. /// </summary> /// <returns>list of random item drops</returns> public List <CharacterItem> GetRandomItems() { List <CharacterItem> items = new List <CharacterItem>(); if (CacheRandomLootItems.Count == 0) { return(items); } int randomDropCount = 0; // Add certain loot rate items certainLootItems.Shuffle(); for (int i = 0; i < certainLootItems.Count && (maxLootItems == 0 || randomDropCount < maxLootItems); ++i) { short amount = (short)Random.Range(certainLootItems[i].minAmount <= 0 ? 1 : certainLootItems[i].minAmount, certainLootItems[i].maxAmount); items.Add(CharacterItem.Create(certainLootItems[i].item, 1, amount)); randomDropCount++; } // Reached max loot items? if (randomDropCount >= maxLootItems) { return(items); } // Add uncertain loot rate items uncertainLootItems.Shuffle(); for (int i = 0; i < uncertainLootItems.Count && (maxLootItems == 0 || randomDropCount < maxLootItems); ++i) { if (Random.value >= uncertainLootItems[i].dropRate) { continue; } short amount = (short)Random.Range(uncertainLootItems[i].minAmount <= 0 ? 1 : uncertainLootItems[i].minAmount, uncertainLootItems[i].maxAmount); items.Add(CharacterItem.Create(uncertainLootItems[i].item, 1, amount)); randomDropCount++; } return(items); }
protected override void UpdateData() { if (uiCharacterItem != null) { if (Data.item == null) { uiCharacterItem.Hide(); } else { uiCharacterItem.Setup(new CharacterItemTuple(CharacterItem.Create(Data.item), 1, string.Empty), null, -1); uiCharacterItem.Show(); } } if (uiTextSellPrice != null) { uiTextSellPrice.text = string.Format(sellPriceFormat, Data.sellPrice.ToString("N0")); } }
protected override void UpdateData() { if (uiCraftingItem != null) { if (ItemCraft.craftingItem == null) { uiCraftingItem.Hide(); } else { uiCraftingItem.Show(); uiCraftingItem.Data = new CharacterItemTuple(CharacterItem.Create(ItemCraft.craftingItem), 1, string.Empty); } } if (uiRequireItemAmounts != null) { if (ItemCraft.craftingItem == null) { uiRequireItemAmounts.Hide(); } else { uiRequireItemAmounts.Show(); uiRequireItemAmounts.Data = ItemCraft.CacheCraftRequirements; } } if (uiTextRequireGold != null) { if (ItemCraft.craftingItem == null) { uiTextRequireGold.text = string.Format(requireGoldFormat, 0.ToString("N0")); } else { uiTextRequireGold.text = string.Format(requireGoldFormat, ItemCraft.requireGold.ToString("N0")); } } }
protected override void UpdateData() { if (uiCharacterItem != null) { if (Data.item == null) { uiCharacterItem.Hide(); } else { uiCharacterItem.Setup(new CharacterItemTuple(CharacterItem.Create(Data.item), 1, InventoryType.NonEquipItems), null, -1); uiCharacterItem.Show(); } } if (uiTextSellPrice != null) { uiTextSellPrice.text = string.Format( LanguageManager.GetText(formatKeySellPrice), Data.sellPrice.ToString("N0")); } }
public void UnSummon(BaseCharacterEntity summoner) { if (type == SummonType.Pet) { var newItem = CharacterItem.Create(dataId, Level, 1); newItem.exp = Exp; if (CacheEntity == null || CacheEntity.CurrentHp <= 0) { newItem.Lock(GameInstance.Singleton.petDeadLockDuration); } else { newItem.Lock(GameInstance.Singleton.petUnSummonLockDuration); } summoner.NonEquipItems.Add(newItem); } if (CacheEntity != null) { CacheEntity.UnSummon(); } }
public async UniTaskVoid HandleRequestClaimMailItems(RequestHandlerData requestHandler, RequestClaimMailItemsMessage request, RequestProceedResultDelegate <ResponseClaimMailItemsMessage> result) { #if UNITY_STANDALONE && !CLIENT_BUILD IPlayerCharacterData playerCharacter; if (GameInstance.ServerUserHandlers.TryGetPlayerCharacter(requestHandler.ConnectionId, out playerCharacter)) { UITextKeys message = UITextKeys.NONE; GetMailResp mailResp = await DbServiceClient.GetMailAsync(new GetMailReq() { MailId = request.id, UserId = playerCharacter.UserId, }); Mail mail = mailResp.Mail; if (mail.IsClaim) { message = UITextKeys.UI_ERROR_MAIL_CLAIM_ALREADY_CLAIMED; } else if (mail.IsDelete) { message = UITextKeys.UI_ERROR_CANNOT_ACCESS_STORAGE; } else { if (mail.Items.Count > 0) { List <CharacterItem> increasingItems = new List <CharacterItem>(); foreach (KeyValuePair <int, short> mailItem in mail.Items) { increasingItems.Add(CharacterItem.Create(mailItem.Key, amount: mailItem.Value)); } if (playerCharacter.IncreasingItemsWillOverwhelming(increasingItems)) { message = UITextKeys.UI_ERROR_WILL_OVERWHELMING; } else { playerCharacter.IncreaseItems(increasingItems); } } if (message == UITextKeys.NONE && mail.Currencies.Count > 0) { List <CurrencyAmount> increasingCurrencies = new List <CurrencyAmount>(); Currency tempCurrency; foreach (KeyValuePair <int, int> mailCurrency in mail.Currencies) { if (!GameInstance.Currencies.TryGetValue(mailCurrency.Key, out tempCurrency)) { continue; } increasingCurrencies.Add(new CurrencyAmount() { currency = tempCurrency, amount = mailCurrency.Value }); } playerCharacter.IncreaseCurrencies(increasingCurrencies); } if (message == UITextKeys.NONE && mail.Gold > 0) { playerCharacter.Gold = playerCharacter.Gold.Increase(mail.Gold); } } if (message != UITextKeys.NONE) { result.Invoke(AckResponseCode.Error, new ResponseClaimMailItemsMessage() { message = message, }); return; } UpdateClaimMailItemsStateResp resp = await DbServiceClient.UpdateClaimMailItemsStateAsync(new UpdateClaimMailItemsStateReq() { MailId = request.id, UserId = playerCharacter.UserId, }); message = resp.Error; result.Invoke( message == UITextKeys.NONE ? AckResponseCode.Success : AckResponseCode.Error, new ResponseClaimMailItemsMessage() { message = message, mail = resp.Mail, }); } else { result.Invoke(AckResponseCode.Error, new ResponseClaimMailItemsMessage() { message = UITextKeys.UI_ERROR_SERVICE_NOT_AVAILABLE, }); } #endif }
protected override void UpdateData() { bool isComplete = CharacterQuest.isComplete; bool isAllTasksDone = CharacterQuest.IsAllTasksDone(Character); string titleFormat = isComplete ? LanguageManager.GetText(formatKeyTitleComplete) : (isAllTasksDone ? LanguageManager.GetText(formatKeyTitleTasksComplete) : LanguageManager.GetText(formatKeyTitleOnGoing)); if (uiTextTitle != null) { uiTextTitle.text = string.Format(titleFormat, Quest == null ? LanguageManager.GetUnknowTitle() : Quest.Title); } if (uiTextDescription != null) { uiTextDescription.text = string.Format( LanguageManager.GetText(formatKeyDescription), Quest == null ? LanguageManager.GetUnknowDescription() : Quest.Description); } if (uiTextRewardExp != null) { uiTextRewardExp.text = string.Format( LanguageManager.GetText(formatKeyRewardExp), Quest == null ? "0" : Quest.rewardExp.ToString("N0")); } if (uiTextRewardGold != null) { uiTextRewardGold.text = string.Format( LanguageManager.GetText(formatKeyRewardGold), Quest == null ? "0" : Quest.rewardGold.ToString("N0")); } if (Quest != null && showRewardItemList) { CacheRewardItemList.Generate(Quest.rewardItems, (index, rewardItem, ui) => { CharacterItem characterItem = CharacterItem.Create(rewardItem.item); characterItem.amount = rewardItem.amount; UICharacterItem uiCharacterItem = ui.GetComponent <UICharacterItem>(); uiCharacterItem.Setup(new CharacterItemTuple(characterItem, characterItem.level, InventoryType.NonEquipItems), null, -1); uiCharacterItem.Show(); }); } if (uiRewardItemRoot != null) { uiRewardItemRoot.SetActive(showRewardItemList && Quest.rewardItems.Length > 0); } if (uiQuestTaskRoot != null) { uiQuestTaskRoot.SetActive(showQuestTaskList && Quest.tasks.Length > 0); } if (questCompleteStatusObject != null) { questCompleteStatusObject.SetActive(isComplete); } if (questTasksCompleteStatusObject != null) { questTasksCompleteStatusObject.SetActive(!isComplete && isAllTasksDone); } if (questOnGoingStatusObject != null) { questOnGoingStatusObject.SetActive(!isComplete && !isAllTasksDone); } }
public void HandleGMCommand(string sender, string command) { if (string.IsNullOrEmpty(command)) { return; } string[] splited = command.Split(' '); string commandKey = splited[0]; string receiver; BasePlayerCharacterEntity playerCharacter; if (GMCommands.IsSplitedLengthValid(commandKey, splited.Length)) { if (commandKey.Equals(GMCommands.Level)) { receiver = sender; short amount; if (TryGetPlayerCharacterByName(receiver, out playerCharacter) && short.TryParse(splited[1], out amount) && amount > 0) { playerCharacter.Level = amount; } } if (commandKey.Equals(GMCommands.StatPoint)) { receiver = sender; short amount; if (TryGetPlayerCharacterByName(receiver, out playerCharacter) && short.TryParse(splited[1], out amount) && amount >= 0) { playerCharacter.StatPoint = amount; } } if (commandKey.Equals(GMCommands.SkillPoint)) { receiver = sender; short amount; if (TryGetPlayerCharacterByName(receiver, out playerCharacter) && short.TryParse(splited[1], out amount) && amount >= 0) { playerCharacter.SkillPoint = amount; } } if (commandKey.Equals(GMCommands.Gold)) { receiver = sender; short amount; if (TryGetPlayerCharacterByName(receiver, out playerCharacter) && short.TryParse(splited[1], out amount) && amount >= 0) { playerCharacter.Gold = amount; } } if (commandKey.Equals(GMCommands.AddItem)) { receiver = sender; Item item; short amount; if (TryGetPlayerCharacterByName(receiver, out playerCharacter) && GameInstance.Items.TryGetValue(splited[1].GenerateHashId(), out item) && short.TryParse(splited[2], out amount)) { if (amount > item.maxStack) { amount = item.maxStack; } CharacterItem newItem = CharacterItem.Create(item, 1, amount); playerCharacter.NonEquipItems.Add(newItem); } } if (commandKey.Equals(GMCommands.GiveGold)) { receiver = splited[1]; short amount; if (TryGetPlayerCharacterByName(receiver, out playerCharacter) && short.TryParse(splited[2], out amount)) { playerCharacter.Gold += amount; } } if (commandKey.Equals(GMCommands.GiveItem)) { receiver = splited[1]; Item item; short amount; if (TryGetPlayerCharacterByName(receiver, out playerCharacter) && GameInstance.Items.TryGetValue(splited[2].GenerateHashId(), out item) && short.TryParse(splited[3], out amount)) { if (amount > item.maxStack) { amount = item.maxStack; } CharacterItem newItem = CharacterItem.Create(item, 1, amount); playerCharacter.NonEquipItems.Add(newItem); } } } }
public static ItemDropEntity DropItem(BaseGameEntity dropper, int itemDataId, short level, short amount, IEnumerable <uint> looters) { var gameInstance = GameInstance.Singleton; if (gameInstance.itemDropEntityPrefab == null) { return(null); } var dropPosition = dropper.CacheTransform.position; var dropRotation = Quaternion.identity; switch (gameInstance.itemDropEntityPrefab.dimensionType) { case DimensionType.Dimension3D: // Random drop position around character dropPosition = dropper.CacheTransform.position + new Vector3(Random.Range(-1f, 1f) * gameInstance.dropDistance, 0, Random.Range(-1f, 1f) * gameInstance.dropDistance); // Raycast to find hit floor Vector3? aboveHitPoint = null; Vector3? underHitPoint = null; var raycastLayerMask = gameInstance.GetItemDropGroundDetectionLayerMask(); RaycastHit tempHit; if (Physics.Raycast(dropPosition, Vector3.up, out tempHit, GROUND_DETECTION_DISTANCE, raycastLayerMask)) { aboveHitPoint = tempHit.point; } if (Physics.Raycast(dropPosition, Vector3.down, out tempHit, GROUND_DETECTION_DISTANCE, raycastLayerMask)) { underHitPoint = tempHit.point; } // Set drop position to nearest hit point if (aboveHitPoint.HasValue && underHitPoint.HasValue) { if (Vector3.Distance(dropPosition, aboveHitPoint.Value) < Vector3.Distance(dropPosition, underHitPoint.Value)) { dropPosition = aboveHitPoint.Value; } else { dropPosition = underHitPoint.Value; } } else if (aboveHitPoint.HasValue) { dropPosition = aboveHitPoint.Value; } else if (underHitPoint.HasValue) { dropPosition = underHitPoint.Value; } // Random rotation dropRotation = Quaternion.Euler(Vector3.up * Random.Range(0, 360)); break; case DimensionType.Dimension2D: dropPosition = dropper.CacheTransform.position + new Vector3(Random.Range(-1f, 1f) * gameInstance.dropDistance, Random.Range(-1f, 1f) * gameInstance.dropDistance); break; } var identity = dropper.Manager.Assets.NetworkSpawn(gameInstance.itemDropEntityPrefab.Identity, dropPosition, dropRotation); var itemDropEntity = identity.GetComponent <ItemDropEntity>(); var dropData = CharacterItem.Create(itemDataId, level, amount); itemDropEntity.dropData = dropData; itemDropEntity.looters = new HashSet <uint>(looters); return(itemDropEntity); }
protected override void UpdateData() { var isComplete = CharacterQuest.isComplete; var isAllTasksDone = CharacterQuest.IsAllTasksDone(character); var titleFormat = isComplete ? questCompleteTitleFormat : (isAllTasksDone ? questTasksCompleteTitleFormat : questOnGoingTitleFormat); if (uiTextTitle != null) { uiTextTitle.text = string.Format(titleFormat, Quest == null ? "Unknow" : Quest.title); } if (uiTextDescription != null) { uiTextDescription.text = string.Format(descriptionFormat, Quest == null ? "N/A" : Quest.description); } if (uiTextRewardExp != null) { uiTextRewardExp.text = string.Format(rewardExpFormat, Quest == null ? "0" : Quest.rewardExp.ToString("N0")); } if (uiTextRewardGold != null) { uiTextRewardGold.text = string.Format(rewardGoldFormat, Quest == null ? "0" : Quest.rewardGold.ToString("N0")); } if (Quest != null && showRewardItemList) { CacheRewardItemList.Generate(Quest.rewardItems, (index, rewardItem, ui) => { var characterItem = CharacterItem.Create(rewardItem.item); characterItem.amount = rewardItem.amount; var uiCharacterItem = ui.GetComponent <UICharacterItem>(); uiCharacterItem.Setup(new CharacterItemTuple(characterItem, characterItem.level, string.Empty), null, -1); uiCharacterItem.Show(); }); } if (uiRewardItemRoot != null) { uiRewardItemRoot.SetActive(showRewardItemList && Quest.rewardItems.Length > 0); } if (uiQuestTaskRoot != null) { uiQuestTaskRoot.SetActive(showQuestTaskList && Quest.tasks.Length > 0); } if (questCompleteStatusObject != null) { questCompleteStatusObject.SetActive(isComplete); } if (questTasksCompleteStatusObject != null) { questTasksCompleteStatusObject.SetActive(!isComplete && isAllTasksDone); } if (questOnGoingStatusObject != null) { questOnGoingStatusObject.SetActive(!isComplete && !isAllTasksDone); } }
public static bool IncreaseItems(this ICharacterData data, int dataId, short level, short amount, float?durability = null) { Item itemData; // If item not valid if (amount <= 0 || !GameInstance.Items.TryGetValue(dataId, out itemData)) { return(false); } var maxStack = itemData.maxStack; var emptySlots = new Dictionary <int, CharacterItem>(); var changes = new Dictionary <int, CharacterItem>(); // Loop to all slots to add amount to any slots that item amount not max in stack for (var i = 0; i < data.NonEquipItems.Count; ++i) { var nonEquipItem = data.NonEquipItems[i]; if (!nonEquipItem.IsValid()) { // If current entry is not valid, add it to empty list, going to replacing it later emptySlots[i] = nonEquipItem; } else if (nonEquipItem.dataId == dataId) { // If same item id, increase its amount if (nonEquipItem.amount + amount <= maxStack) { nonEquipItem.amount += amount; changes[i] = nonEquipItem; amount = 0; break; } else if (maxStack - nonEquipItem.amount >= 0) { amount = (short)(amount - (maxStack - nonEquipItem.amount)); nonEquipItem.amount = maxStack; changes[i] = nonEquipItem; } } } if (changes.Count == 0 && emptySlots.Count > 0) { // If there are no changes and there are an empty entries, fill them foreach (var emptySlot in emptySlots) { var value = emptySlot.Value; var newItem = CharacterItem.Create(dataId, level); short addAmount = 0; if (amount - maxStack >= 0) { addAmount = maxStack; amount -= maxStack; } else { addAmount = amount; amount = 0; } newItem.amount = addAmount; changes[emptySlot.Key] = newItem; } } // Apply all changes foreach (var change in changes) { data.NonEquipItems[change.Key] = change.Value; } // Add new items while (amount > 0) { var newItem = CharacterItem.Create(dataId, level); short addAmount = 0; if (amount - maxStack >= 0) { addAmount = maxStack; amount -= maxStack; } else { addAmount = amount; amount = 0; } newItem.amount = addAmount; if (durability.HasValue) { newItem.durability = durability.Value; } data.NonEquipItems.Add(newItem); } return(true); }
public async UniTaskVoid HandleRequestCashShopBuy( RequestHandlerData requestHandler, RequestCashShopBuyMessage request, RequestProceedResultDelegate<ResponseCashShopBuyMessage> result) { #if UNITY_STANDALONE && !CLIENT_BUILD // Set response data UITextKeys message = UITextKeys.NONE; int dataId = request.dataId; int userCash = 0; int userGold = 0; IPlayerCharacterData playerCharacter; if (!GameInstance.ServerUserHandlers.TryGetPlayerCharacter(requestHandler.ConnectionId, out playerCharacter)) { // Cannot find user message = UITextKeys.UI_ERROR_NOT_LOGGED_IN; } else { // Get user cash amount CashResp getCashResp = await DbServiceClient.GetCashAsync(new GetCashReq() { UserId = playerCharacter.UserId }); userCash = getCashResp.Cash; // Get user gold amount GoldResp getGoldResp = await DbServiceClient.GetGoldAsync(new GetGoldReq() { UserId = playerCharacter.UserId }); userGold = getGoldResp.Gold; CashShopItem cashShopItem; if (!GameInstance.CashShopItems.TryGetValue(dataId, out cashShopItem)) { // Cannot find item message = UITextKeys.UI_ERROR_ITEM_NOT_FOUND; } else if (userCash < cashShopItem.sellPriceCash) { // Not enough cash message = UITextKeys.UI_ERROR_NOT_ENOUGH_CASH; } else if (userGold < cashShopItem.sellPriceGold) { // Not enough cash message = UITextKeys.UI_ERROR_NOT_ENOUGH_GOLD; } else if (playerCharacter.IncreasingItemsWillOverwhelming(cashShopItem.receiveItems)) { // Cannot carry all rewards message = UITextKeys.UI_ERROR_WILL_OVERWHELMING; } else { // Decrease cash amount CashResp changeCashResp = await DbServiceClient.ChangeCashAsync(new ChangeCashReq() { UserId = playerCharacter.UserId, ChangeAmount = -cashShopItem.sellPriceCash }); userCash = changeCashResp.Cash; playerCharacter.UserCash = userCash; // Decrease gold amount GoldResp changeGoldResp = await DbServiceClient.ChangeGoldAsync(new ChangeGoldReq() { UserId = playerCharacter.UserId, ChangeAmount = -cashShopItem.sellPriceGold }); userGold = changeGoldResp.Gold; playerCharacter.UserGold = userGold; // Increase character gold playerCharacter.Gold = playerCharacter.Gold.Increase(cashShopItem.receiveGold); // Increase currencies playerCharacter.IncreaseCurrencies(cashShopItem.receiveCurrencies); // Increase character item if (cashShopItem.receiveItems != null && cashShopItem.receiveItems.Length > 0) { foreach (ItemAmount receiveItem in cashShopItem.receiveItems) { if (receiveItem.item == null || receiveItem.amount <= 0) continue; playerCharacter.AddOrSetNonEquipItems(CharacterItem.Create(receiveItem.item, 1, receiveItem.amount)); } playerCharacter.FillEmptySlots(); } } } // Send response message result.Invoke( message == UITextKeys.NONE ? AckResponseCode.Success : AckResponseCode.Error, new ResponseCashShopBuyMessage() { message = message, dataId = dataId, userCash = userCash, userGold = userGold, }); #endif await UniTask.Yield(); }
public static T SetNewPlayerCharacterData <T>(this T character, string characterName, int dataId, int entityId) where T : IPlayerCharacterData { var gameInstance = GameInstance.Singleton; PlayerCharacter database; if (!GameInstance.PlayerCharacters.TryGetValue(dataId, out database)) { return(character); } // Player character database var playerCharacter = database as PlayerCharacter; // Attributes var attributes = GameInstance.Attributes.Values; foreach (var attribute in attributes) { var characterAttribute = new CharacterAttribute(); characterAttribute.dataId = attribute.DataId; characterAttribute.amount = 0; character.Attributes.Add(characterAttribute); } var skillLevels = playerCharacter.CacheSkillLevels; foreach (var skillLevel in skillLevels) { var characterSkill = new CharacterSkill(); characterSkill.dataId = skillLevel.Key.DataId; characterSkill.level = skillLevel.Value; character.Skills.Add(characterSkill); } // Right hand & left hand items var rightHandEquipItem = playerCharacter.rightHandEquipItem; var leftHandEquipItem = playerCharacter.leftHandEquipItem; var equipWeapons = new EquipWeapons(); // Right hand equipped item if (rightHandEquipItem != null) { var newItem = CharacterItem.Create(rightHandEquipItem); equipWeapons.rightHand = newItem; } // Left hand equipped item if (leftHandEquipItem != null) { var newItem = CharacterItem.Create(leftHandEquipItem); equipWeapons.leftHand = newItem; } character.EquipWeapons = equipWeapons; // Armors var armorItems = playerCharacter.armorItems; foreach (var armorItem in armorItems) { if (armorItem == null) { continue; } var newItem = CharacterItem.Create(armorItem); character.EquipItems.Add(newItem); } // General data character.DataId = dataId; character.EntityId = entityId; character.CharacterName = characterName; character.Level = 1; var stats = character.GetStats(); character.CurrentHp = (int)stats.hp; character.CurrentMp = (int)stats.mp; character.CurrentStamina = (int)stats.stamina; character.CurrentFood = (int)stats.food; character.CurrentWater = (int)stats.water; character.Gold = gameInstance.startGold; // Inventory var startItems = gameInstance.startItems; foreach (var startItem in startItems) { if (startItem.item == null || startItem.amount <= 0) { continue; } var amount = startItem.amount; if (amount > startItem.item.maxStack) { amount = startItem.item.maxStack; } var newItem = CharacterItem.Create(startItem.item, 1, amount); character.NonEquipItems.Add(newItem); } // Position var startMap = playerCharacter.StartMap; character.CurrentMapName = startMap.scene.SceneName; character.RespawnMapName = startMap.scene.SceneName; character.CurrentPosition = startMap.startPosition; character.RespawnPosition = startMap.startPosition; DevExtUtils.InvokeStaticDevExtMethods(ClassType, "SetNewCharacterData", character, characterName, dataId, entityId); return(character); }
public override sealed void Killed(BaseCharacterEntity lastAttacker) { base.Killed(lastAttacker); // If this summoned by someone, don't give reward to killer if (IsSummoned) { return; } Reward reward = gameplayRule.MakeMonsterReward(monsterCharacter); HashSet <uint> looters = new HashSet <uint>(); BasePlayerCharacterEntity lastPlayer = null; if (lastAttacker != null) { lastPlayer = lastAttacker as BasePlayerCharacterEntity; } GuildData tempGuildData; PartyData tempPartyData; BasePlayerCharacterEntity tempPlayerCharacter; BaseMonsterCharacterEntity tempMonsterCharacter; bool givenRewardExp; bool givenRewardCurrency; float shareGuildExpRate; if (receivedDamageRecords.Count > 0) { float tempHighRewardRate = 0f; foreach (BaseCharacterEntity enemy in receivedDamageRecords.Keys) { givenRewardExp = false; givenRewardCurrency = false; shareGuildExpRate = 0f; ReceivedDamageRecord receivedDamageRecord = receivedDamageRecords[enemy]; float rewardRate = (float)receivedDamageRecord.totalReceivedDamage / (float)CacheMaxHp; if (rewardRate > 1f) { rewardRate = 1f; } if (enemy is BasePlayerCharacterEntity) { bool makeMostDamage = false; tempPlayerCharacter = enemy as BasePlayerCharacterEntity; // Clear looters list when it is found new player character who make most damages if (rewardRate > tempHighRewardRate) { tempHighRewardRate = rewardRate; looters.Clear(); makeMostDamage = true; } // Try find guild data from player character if (tempPlayerCharacter.GuildId > 0 && gameManager.TryGetGuild(tempPlayerCharacter.GuildId, out tempGuildData)) { // Calculation amount of Exp which will be shared to guild shareGuildExpRate = (float)tempGuildData.ShareExpPercentage(tempPlayerCharacter.Id) * 0.01f; // Will share Exp to guild when sharing amount more than 0 if (shareGuildExpRate > 0) { // Increase guild exp gameManager.IncreaseGuildExp(tempPlayerCharacter, (int)(reward.exp * shareGuildExpRate * rewardRate)); } } // Try find party data from player character if (tempPlayerCharacter.PartyId > 0 && gameManager.TryGetParty(tempPlayerCharacter.PartyId, out tempPartyData)) { BasePlayerCharacterEntity partyPlayerCharacter; // Loop party member to fill looter list / increase gold / increase exp foreach (SocialCharacterData member in tempPartyData.GetMembers()) { if (gameManager.TryGetPlayerCharacterById(member.id, out partyPlayerCharacter)) { // If share exp, every party member will receive devided exp // If not share exp, character who make damage will receive non-devided exp if (tempPartyData.shareExp) { partyPlayerCharacter.RewardExp(reward, (1f - shareGuildExpRate) / (float)tempPartyData.CountMember() * rewardRate, RewardGivenType.PartyShare); } // If share item, every party member will receive devided gold // If not share item, character who make damage will receive non-devided gold if (tempPartyData.shareItem) { if (makeMostDamage) { // Make other member in party able to pickup items looters.Add(partyPlayerCharacter.ObjectId); } partyPlayerCharacter.RewardCurrencies(reward, 1f / (float)tempPartyData.CountMember() * rewardRate, RewardGivenType.PartyShare); } } } // Shared exp has been given, so do not give it to character again if (tempPartyData.shareExp) { givenRewardExp = true; } // Shared gold has been given, so do not give it to character again if (tempPartyData.shareItem) { givenRewardCurrency = true; } } // Add reward to current character in damage record list if (!givenRewardExp) { // Will give reward when it was not given int petIndex = tempPlayerCharacter.IndexOfSummon(SummonType.Pet); if (petIndex >= 0) { tempMonsterCharacter = tempPlayerCharacter.Summons[petIndex].CacheEntity; if (tempMonsterCharacter != null) { // Share exp to pet, set multiplier to 0.5, because it will be shared to player tempMonsterCharacter.RewardExp(reward, (1f - shareGuildExpRate) * 0.5f * rewardRate, RewardGivenType.KillMonster); } // Set multiplier to 0.5, because it was shared to monster tempPlayerCharacter.RewardExp(reward, (1f - shareGuildExpRate) * 0.5f * rewardRate, RewardGivenType.KillMonster); } else { // No pet, no share, so rate is 1f tempPlayerCharacter.RewardExp(reward, (1f - shareGuildExpRate) * rewardRate, RewardGivenType.KillMonster); } } if (!givenRewardCurrency) { // Will give reward when it was not given tempPlayerCharacter.RewardCurrencies(reward, rewardRate, RewardGivenType.KillMonster); } if (makeMostDamage) { // Make current character able to pick up item because it made most damage looters.Add(tempPlayerCharacter.ObjectId); } } // End is `BasePlayerCharacterEntity` condition } // End for-loop } // End count recived damage record count receivedDamageRecords.Clear(); foreach (ItemDrop randomItem in monsterCharacter.randomItems) { if (Random.value <= randomItem.dropRate) { Item item = randomItem.item; short amount = randomItem.amount; if (item != null && GameInstance.Items.ContainsKey(item.DataId)) { // Drop item to the ground if (amount > item.maxStack) { amount = item.maxStack; } CharacterItem dropData = CharacterItem.Create(item, 1); dropData.amount = amount; ItemDropEntity.DropItem(this, dropData, looters); } } } if (lastPlayer != null) { // Increase kill progress lastPlayer.OnKillMonster(this); } if (!IsSummoned) { // If not summoned by someone, destroy and respawn it DestroyAndRespawn(); } }