private static void Extract(PlayerItem player, int playerNumber, BitmapImage imageBmp, int imageNumber) { int posX = PlayerStartImageX + imageNumber*(PlayerWidth+SpaceBetweenImages); int posY = PlayerStartImageY + playerNumber*(PlayerHeight + SpaceBetweenPlayer); Brush brush = ExtractBackground(imageBmp, posX, posY, PlayerWidth, PlayerHeight); switch (imageNumber) { case 0: case 1: case 2: player.Textures.Down.Add(brush); break; case 3: case 4: case 5: player.Textures.Left.Add(brush); break; case 6: case 7: case 8: player.Textures.Right.Add(brush); break; default: player.Textures.Up.Add(brush); break; } if (imageNumber == StartedImage) player.ImageInUse = player.Textures.Down[1];//every player will start with face down }
public static void InitializeItem() { Player1Item = new PlayerItem(); Player2Item = new PlayerItem(); Player3Item = new PlayerItem(); Player4Item = new PlayerItem(); DestructibleWallItem = new WallItem { WallType = WallType.Destructible }; UndestructibleWallItem = new WallItem { WallType = WallType.Undestructible }; BombItem = new BombItem(); ExplodedBombItem = new BombItem(); GetSpriteForPlayer(Player1Item, 0); GetSpriteForPlayer(Player2Item, 1); GetSpriteForPlayer(Player3Item, 2); GetSpriteForPlayer(Player4Item, 3); GetSpriteForWall(DestructibleWallItem); GetSpriteForWall(UndestructibleWallItem); GetSpriteForBomb(BombItem); GetSpriteForExplodedBomb(ExplodedBombItem); }
public void Init(PlayerItem playerItem,bool WithButtons) { base.Init(playerItem,true, WithButtons); SetEnchant(playerItem.enchant, playerItem.enchant > 0); bool enchanted = false; foreach (var p in playerItem.parameters) { var count = p.Value; if (!enchanted) { enchanted = true; count = count * ( 1 + playerItem.enchant / PlayerItem.ENCHANT_PLAYER_COEF); } var element = DataBaseController.GetItem<ParameterElement>(DataBaseController.Instance.DataStructs.PrefabsStruct.ParameterElement); element.Init(p.Key, count); element.transform.SetParent(layoutParam,false); } var haveSpec = playerItem.specialAbilities != SpecialAbility.none; SpecIcon.transform.parent.gameObject.SetActive(haveSpec); if (haveSpec) { SpecIcon.gameObject.SetActive(true); SpecName.text = playerItem.specialAbilities.ToString(); SpecIcon.sprite = DataBaseController.Instance.SpecialAbilityIcon(playerItem.specialAbilities); SpecIcon.transform.parent.transform.SetAsLastSibling(); } mainIcon.sprite = playerItem.IconSprite; NameLabel.text = playerItem.name; }
public static PlayerItem CreatMainSlot(Slot slot, int levelResult) { var totalPoints = GetPointsByLvl(levelResult)*GetSlotCoef(slot); float diff = Utils.RandomNormal(0.5f, 1f); //Debug.Log("iffff " + diff); bool isRare = diff > 0.95f; totalPoints *= diff; float contest = UnityEngine.Random.Range(0.60f, 1f); if (contest > 0.9f) contest = 1f; var pparams = new Dictionary<ParamType,float>(); var primary = Connections.GetPrimaryParamType(slot); var primaryValue = totalPoints*contest; pparams.Add(primary,primaryValue); if (contest < 0.95f) { var secondary = Connections.GetSecondaryParamType(slot); var secondaryValue = totalPoints*(1f - contest); pparams.Add(secondary, secondaryValue); } PlayerItem item = new PlayerItem(pparams,slot,isRare, totalPoints); if (contest < 0.85f && (slot == Slot.magic_weapon || slot == Slot.physical_weapon))//.65f { var spec = ShopController.AllSpecialAbilities.RandomElement(); item.specialAbilities = spec; Debug.Log("WITH SPEC::: " + item.specialAbilities); } return item; }
public void Init(Unit owner,PlayerItem PlayerItem) { nexAttackTime = 0; this.PlayerItem = PlayerItem; if (pSystemOnShot != null) { pSystemOnShot.Stop(); } this.owner = owner; }
public void Init(Unit owner,PlayerItem PlayerItem) { pool = DataBaseController.Instance.Pool; pool.RegisterBullet(bullet); bulletParent = Map.Instance.bulletContainer; nexAttackTime = 0; this.PlayerItem = PlayerItem; if (pSystemOnShot != null) { pSystemOnShot.Stop(); } this.owner = owner; }
public void addItem(PlayerItem item, int itemCount) { if (itemExists(item.itemName)){ PlayerItem b = getItem (item.itemName); b.itemCount = b.itemCount + itemCount; } else{ item.itemCount = itemCount; playerItemList.Add(item); } if(getItem (item.itemName).itemCount<0){ getItem (item.itemName).itemCount=0; } }
private void GiveToLeftName_Click(object sender, RoutedEventArgs e) { selectedItemIndexes = new List<PlayerItem>(); foreach (object o in playerItemsRight.SelectedItems) { selectedItemIndexes.Add((PlayerItem)o); } initialval = playerItemsLeft.SelectedItems.Count; invcheck = 0; foreach (Weapon wep in playerLeft.Inventory.getInv()) { invcheck++; } foreach (Weapon wep in playerItemsRight.SelectedItems) { invcheck++; } if (playerItemsRight.SelectedItem == null) { MessageBox.Show("Please select and item to give!"); } else { if (invcheck < 6) { for (int i = 0; i < initialval; i++) { item = (PlayerItem)playerItemsRight.SelectedItems[0]; playerLeft.addToInventory(item); playerRight.removeFromInventory(selectedItemIndexes[i]); } } else { MessageBox.Show("Cannot exceed 5 weapons!"); } } }
public void addPlayerItem(PlayerItem item) { playerItems.Add(item); item.doItemEffect(this); print(defense); }
public void ItemEnchantReq(GameSession session, ItemEnchantReqMessage message) { // Todo !! Enchant For Costumes - Only need to fill the xml containing effects and levels Player player = session.Player; if (player == null) { return; } if (player.PEN < 200) { session.SendAsync(new EnchantItemAckMessage(EnchantResult.NotEnoughMoney)); return; } PlayerItem item = player.Inventory[(ulong)message.ItemId]; // Checks if item not equal null and enchant lvl is less than 16 and is a weapon if (item == null || item.ItemNumber.Category != ItemCategory.Weapon || item.EnchantLvl >= 16) { session.SendAsync(new EnchantItemAckMessage(EnchantResult.ErrorItemEnchant)); } else { try { EnchantSys enchantSystems = GameServer.Instance.ResourceCache.GetEnchantSystem()[item.EnchantLvl]; uint num = (new uint[25] { 200, 200, 300, 300, 500, 500, 600, 600, 800, 800, 1100, 1100, 1300, 1500, 1800, 2300, 2900, 3500, 4200, 5200, 5200, 5200, 5200, 5200, 5200 })[item.EnchantLvl]; EnchantGroup[] array = enchantSystems.EnchantGroup.Where(delegate(EnchantGroup i) { return((i.Category == item.ItemNumber.Category) & (i.SubCategory == item.ItemNumber.SubCategory)); }).ToArray(); // Checks if player's pen is less than cost if (player.PEN < num) { session.SendAsync(new EnchantItemAckMessage(EnchantResult.NotEnoughMoney)); return; } EnchantSystem enchantSystem = array[0].Eff(); EnchantResult result = EnchantResult.Success; uint num2 = enchantSystem.Effect; List <EffectNumber> list = item.Effects.ToList(); if (list.Contains(num2 - 1)) { list.Remove(num2 - 1); list.Add(num2); } else if (list.Contains(num2 - 2)) { list.Remove(num2 - 2); list.Add(num2); } else if (list.Contains(num2 - 3)) { list.Remove(num2 - 3); list.Add(num2); } else if (list.Contains(num2 - 4)) { list.Remove(num2 - 4); list.Add(num2); } else if (!list.Contains(num2) && !list.Contains(num2 + 1) && !list.Contains(num2 + 2) && !list.Contains(num2 + 3) && !list.Contains(num2 + 4)) { list.Add(num2); } else { list = new List <EffectNumber>(); if (item.ItemNumber.Category == ItemCategory.Weapon) { if (item.Effects[0].Equals(1299600007)) { list.Add(1299600007); list.Add(1299602002); list.Add(1208300005); list.Add(1208301005); } else if (item.Effects[0].Equals(1203300005)) { list.Add(1203300005); list.Add(1203301005); list.Add(1299600007); } else if (item.Effects[0].Equals(1299600006)) { list.Add(1299600006); } else { list.Add(1299600001); } } } item.EnchantLvl++; item.Effects = list.ToArray(); item.EnchantMP = 0; player.PEN -= num; session.SendAsync(new EnchantItemAckMessage { Result = result, ItemId = (ulong)message.ItemId, Effect = num2 }); session.SendAsync(new ItemUpdateInventoryAckMessage(InventoryAction.Update, item.Map <PlayerItem, ItemDto>())); session.SendAsync(new MoneyRefreshCashInfoAckMessage(player.PEN, player.AP)); Logger.ForAccount(session).Information(string.Format("Enchanted {0} With {1} PEN", item.ItemNumber, num)); } catch (Exception ex) { session.SendAsync(new EnchantItemAckMessage(EnchantResult.ErrorItemEnchant)); //Logger.Information(ex.StackTrace); } } return; }
public void ShowItemDescription(PlayerItem showing, Button bataum) { DescriptionText.text = showing.Description; }
//读取Json信息 PlayerItem ReadJson(ref PlayerItem playerItem) { TextAsset TA = Resources.Load("Json/PlayerData", typeof(TextAsset)) as TextAsset; return(playerItem = JsonUtility.FromJson <PlayerItem>(TA.text)); }
public static GameObject MainHook(GameObject objectToInstantiate, RoomHandler targetRoom, IntVector2 location, bool deferConfiguration, AIActor.AwakenAnimationType awakenAnimType = AIActor.AwakenAnimationType.Default, bool autoEngage = false) { //hooks into InstantiateDungeonPlaceable GameObject result; System.Random rnd = new System.Random(); int nu = 0; string enemyGuid; GRandomHook.wasBoss = false; bool isbossroom = false; if (targetRoom.area.PrototypeRoomCategory == PrototypeDungeonRoom.RoomCategory.BOSS && targetRoom.area.PrototypeRoomBossSubcategory == PrototypeDungeonRoom.RoomBossSubCategory.FLOOR_BOSS) { isbossroom = true; } else if (GRandomRoomDatabaseHelper.AllSpecificDeathRooms.Contains(targetRoom.GetRoomName())) { isbossroom = true; } try { if (objectToInstantiate != null) { Vector3 vector = location.ToVector3(0f) + targetRoom.area.basePosition.ToVector3(); vector.z = vector.y + vector.z; AIActor component = objectToInstantiate.GetComponent <AIActor>(); //notused AIActor ogcomponent = component; if (component is AIActorDummy) { objectToInstantiate = (component as AIActorDummy).realPrefab; component = objectToInstantiate.GetComponent <AIActor>(); } SpeculativeRigidbody component2 = objectToInstantiate.GetComponent <SpeculativeRigidbody>(); //notused if (component && component2) { if (component.EnemyGuid != null) { //Here gets enemyGuid based on room. Pulls from EnemyDatabase /////////////////////// if (isbossroom) { if (component.healthHaver.IsBoss) { GRandomHook.wasBoss = true; if (component.healthHaver.GetMaxHealth() != 60) //sometimes gets health as regular enemy health, 60 { GRandomHook.boss_health = component.healthHaver.GetMaxHealth(); //getting boss health to set for replacement boss } //replacement for Boss nu = rnd.Next(0, GRandomEnemyDataBaseHelper.UsedBossRoomDatabase.Count); enemyGuid = GRandomEnemyDataBaseHelper.UsedBossRoomDatabase[nu]; } else { //normal enemies as bosses is off and the enemy is not a boss; pull from no bosses database for enemy spawnings nu = rnd.Next(0, GRandomEnemyDataBaseHelper.BossRoomRegularEnemiesOnly.Count); enemyGuid = GRandomEnemyDataBaseHelper.BossRoomRegularEnemiesOnly[nu]; } } else if (targetRoom.GetRoomName() == "ResourcefulRat_PitEntrance_01" | targetRoom.GetRoomName() == "ResourcefulRat_Entrance") { nu = rnd.Next(0, GRandomEnemyDataBaseHelper.HarmlessEnemyDatabase.Count); enemyGuid = GRandomEnemyDataBaseHelper.HarmlessEnemyDatabase[nu]; } else { nu = rnd.Next(0, GRandomEnemyDataBaseHelper.UsedRegularRoomDatabase.Count); enemyGuid = GRandomEnemyDataBaseHelper.UsedRegularRoomDatabase[nu]; } if (component.EnemyGuid == "479556d05c7c44f3b6abb3b2067fc778") //wallmimic { enemyGuid = "479556d05c7c44f3b6abb3b2067fc778"; } // //can add specific Guid here for debugging // if (enemyGuid == "465da2bb086a4a88a803f79fe3a27677") //replace DraGun, can't remove him from database or forge dragunroom breaks { enemyGuid = "05b8afe0b6cc4fffa9dc6036fa24c8ec"; } // End getting guid ////////////////////////////// //initializing new AIActor, not sure why they do it again below AIActor prefabActor = EnemyDatabase.GetOrLoadByGuid(enemyGuid); objectToInstantiate = prefabActor.gameObject; component = objectToInstantiate.GetComponent <AIActor>(); component2 = objectToInstantiate.GetComponent <SpeculativeRigidbody>(); //bool specificdeathdoer = prefabActor.healthHaver.ManualDeathHandling; GenericIntroDoer genericIntroDoer = component.GetComponent <GenericIntroDoer>(); //if (genericIntroDoer) // is boss // handles initiated boss settings if (component.healthHaver.IsBoss) { if (isbossroom) { prefabActor.healthHaver.SetHealthMaximum(GRandomHook.boss_health); ETGModConsole.Log("Newbosshealth " + prefabActor.healthHaver.GetMaxHealth()); } else { prefabActor.healthHaver.SetHealthMaximum(60f); } objectToInstantiate = RandomHandleEnemyInfo.RemoveBossIntros(objectToInstantiate); objectToInstantiate = RandomHandleEnemyInfo.ReplaceSpecificBossDeathController(objectToInstantiate); objectToInstantiate = RandomHandleEnemyInfo.AttackBehaviorManipulator(objectToInstantiate); DemonWallController dwc = objectToInstantiate.GetComponent <DemonWallController>(); if (dwc) { Destroy(dwc); } } if (!component.IsNormalEnemy) { objectToInstantiate = RandomHandleEnemyInfo.HandleCompanions(objectToInstantiate); } } PixelCollider pixelCollider = component2.GetPixelCollider(ColliderType.Ground); if (pixelCollider.ColliderGenerationMode != PixelCollider.PixelColliderGeneration.Manual) { Debug.LogErrorFormat("Trying to spawn an AIActor who doesn't have a manual ground collider... do we still do this? Name: {0}", new object[] { objectToInstantiate.name }); } Vector2 a = PhysicsEngine.PixelToUnit(new IntVector2(pixelCollider.ManualOffsetX, pixelCollider.ManualOffsetY)); Vector2 vector2 = PhysicsEngine.PixelToUnit(new IntVector2(pixelCollider.ManualWidth, pixelCollider.ManualHeight)); Vector2 vector3 = new Vector2((float)Mathf.CeilToInt(vector2.x), (float)Mathf.CeilToInt(vector2.y)); Vector2 b = new Vector2((vector3.x - vector2.x) / 2f, 0f).Quantize(0.0625f); if (targetRoom.GetRoomName() == "DraGunRoom01" | targetRoom.GetRoomName() == "LichRoom02" | targetRoom.GetRoomName() == "LichRoom03" | targetRoom.GetRoomName() == "Bullet_End_Room_04" | targetRoom.GetRoomName() == "ResourcefulRatRoom01") { b -= new Vector2(0.0f, 5.0f); } Vector3 v3 = a - b; vector -= v3; //vector -= a - b; //Vector3 } if (component) { component.AwakenAnimType = awakenAnimType; } GameObject NewEnemyObject = UnityEngine.Object.Instantiate <GameObject>(objectToInstantiate, vector, Quaternion.identity); if (!deferConfiguration) { Component[] componentsInChildren = NewEnemyObject.GetComponentsInChildren(typeof(IPlaceConfigurable)); for (int i = 0; i < componentsInChildren.Length; i++) { IPlaceConfigurable placeConfigurable = componentsInChildren[i] as IPlaceConfigurable; if (placeConfigurable != null) { placeConfigurable.ConfigureOnPlacement(targetRoom); } } } ObjectVisibilityManager component3 = NewEnemyObject.GetComponent <ObjectVisibilityManager>(); if (component3 != null) { component3.Initialize(targetRoom, autoEngage); } MinorBreakable componentInChildren = NewEnemyObject.GetComponentInChildren <MinorBreakable>(); if (componentInChildren != null) { IntVector2 key = location + targetRoom.area.basePosition; CellData cellData = GameManager.Instance.Dungeon.data[key]; if (cellData != null) { cellData.cellVisualData.containsObjectSpaceStamp = true; } } PlayerItem component4 = NewEnemyObject.GetComponent <PlayerItem>(); if (component4 != null) { component4.ForceAsExtant = true; } //[Randomizer] Add AIActor GameObjectInfo AIActor enemy_component = NewEnemyObject.GetComponent <AIActor>(); if (enemy_component) { if (enemy_component.healthHaver.IsBoss) { if (isbossroom) { //Boss Room enemy_component.healthHaver.bossHealthBar = HealthHaver.BossBarType.MainBar; } else { enemy_component.healthHaver.bossHealthBar = HealthHaver.BossBarType.None; autoEngage = true; } NewEnemyObject = RandomHandleEnemyInfo.ReinstateBossObjectInfo(NewEnemyObject); //removes boss status if regular boss, needs hitbox stuff reinstated } if (GRandomEnemyDataBaseHelper.SpecificEnemyDatabase.Contains(enemy_component.EnemyGuid)) { NewEnemyObject = RandomHandleEnemyInfo.SpecificEnemyHelper(NewEnemyObject); } NewEnemyObject = UniqueBossRoomDeathHandler.SpecificRoomHandler(targetRoom, NewEnemyObject); } result = NewEnemyObject; } else { result = null; //return null; } } catch (Exception message) { Debug.Log("[RANDOMIZER ERROR] " + message.ToString()); result = null; } return(result); }
bool BuyItem(PlayerItem skin) { if (PersistentData.Coins >= skin.price) { PersistentData.Coins -= skin.price; return true; } return false; }
public void KillDropWeirdActive(PlayerItem item) { DebrisObject debrisObject = LastOwner.DropActiveItem(item); UnityEngine.Object.Destroy(debrisObject.gameObject, 0.01f); }
public void Start() { // Queue any existing files foreach (var file in Directory.EnumerateFiles(GlobalPaths.CsvLocation)) { _queue.Enqueue(new QueuedCsv { Filename = file, Cooldown = new ActionCooldown(0) }); } // Process any newly added files. Threaded to ensure a proper delay between write and read. var t = new Thread(() => { ExceptionReporter.EnableLogUnhandledOnThread(); while (!_isCancelled) { Thread.Sleep(500); if (!_queue.TryDequeue(out var entry)) { continue; } try { if (entry.Cooldown.IsReady) { PlayerItem item = Parse(File.ReadAllText(entry.Filename)); if (item == null) { continue; } // CSV probably wont have stackcount item.StackCount = Math.Max(item.StackCount, 1); item.CreationDate = DateTime.UtcNow.ToTimestamp(); var classificationService = new ItemClassificationService(_cache, _playerItemDao); classificationService.Add(item); // Items to loot if (classificationService.Remaining.Count > 0) { _playerItemDao.Save(item); File.Delete(entry.Filename); // Update replica reference var hash = ItemReplicaService.GetHash(item); _replicaItemDao.UpdatePlayerItemId(hash, item.Id); } else if (classificationService.Duplicates.Count > 0 && _settings.GetPersistent().DeleteDuplicates) { Logger.Info("Deleting duplicate item file"); File.Delete(entry.Filename); } else { // Transfer back in-game, should never have been looted. // TODO: Separate transfer logic.. no delete-from-db etc.. if (RuntimeSettings.StashStatus == StashAvailability.CLOSED) { string stashfile = _itemTransferController.GetTransferFile(); _transferStashService.Deposit(stashfile, new List <PlayerItem> { item }, out string error); if (string.IsNullOrEmpty(error)) { Logger.Info("Deposited item back in-game, did not pass item classification."); File.Delete(entry.Filename); } else { Logger.Warn("Failed re-depositing back into GD"); _queue.Enqueue(entry); } } else { _queue.Enqueue(entry); } } } else { _queue.Enqueue(entry); } } catch (Exception ex) { Logger.Warn("Error handling CSV item file", ex); } } }); t.Start(); }
public async Task <List <NetworkAuctionInfo.ItemModel> > SearchPlayerUsingPlayerItemAsync(PlayerItem playerItem) { var pageNumber = 0; var allPagesResults = new List <NetworkAuctionInfo.ItemModel>(); while (true) { Sleep(); PlayerURL = new PlayerURL(playerItem); var url = PlayerURL.GenerateUsingPageNumber(pageNumber++); var getResponse = await NetworkTasks.Get(url); var deserialisedResponse = JsonConvert.DeserializeObject <NetworkAuctionInfo>(getResponse.ResponseString).auctionInfo; allPagesResults.AddRange(deserialisedResponse); if (deserialisedResponse.Count() < 21) { break; } } return(allPagesResults); }
public IActionResult Update(Guid id, PlayerItem item) { return(NoContent()); }
public void addToInventory(PlayerItem item) { Inventory.addToInv(item); }
public void removeFromInventory(PlayerItem item) { Inventory.remove(item); }
//Only parsed so we can block it protected override void Parse(EndianBinaryReader r) { //Console.WriteLine("Player List Item:"); //Console.WriteLine(BitConverter.ToString(PacketBuffer)); return; //Ignore the data, we just want to block the package #if !DEBUG #else #pragma warning disable 162 Action = (Actions)ReadVarInt(r); int count = ReadVarInt(r); Players = new List<PlayerItem>(count); switch (Action) { case Actions.AddPlayer: for (int n = 0; n < count; n++) { var i = new PlayerItem(); i.UUID = new Guid(r.ReadBytesOrThrow(16)); i.Name = ReadString8(r); int props = ReadVarInt(r); for (int p = 0; p < props; p++) { string name = ReadString8(r); string value = ReadString8(r); bool signed = r.ReadBoolean(); if (signed) { string sign = ReadString8(r); } throw new NotImplementedException(); } i.Gamemode = (GameMode)ReadVarInt(r); i.Ping = ReadVarInt(r); Players.Add(i); } break; case Actions.UpdateGamemode: for (int n = 0; n < count; n++) { var i = new PlayerItem(); i.UUID = new Guid(r.ReadBytesOrThrow(16)); i.Gamemode = (GameMode)ReadVarInt(r); Players.Add(i); } break; case Actions.UpdateLatency: for (int n = 0; n < count; n++) { var i = new PlayerItem(); i.UUID = new Guid(r.ReadBytesOrThrow(16)); i.Ping = ReadVarInt(r); Players.Add(i); } break; case Actions.RemovePlayer: for (int n = 0; n < count; n++) { var i = new PlayerItem(); i.UUID = new Guid(r.ReadBytesOrThrow(16)); Players.Add(i); } break; default: throw new NotImplementedException("Action: " + Action); } #pragma warning restore 162 #endif }
private static void GetSpriteForPlayer(PlayerItem player, int playerNumber) { string imagePath = String.Format(@"{0}\{1}", GlobalImagePath, GlobalImageName); BitmapImage imageBmp = new BitmapImage(new Uri(imagePath)); //initialize textures player.Textures = new Sprite(); for (int i = 0; i < NumberImagesPerPlayer; i++) { Extract(player, playerNumber, imageBmp, i); } }
public void AddItem(string id, int quantity) { PlayerItem catalogItem = catalog[id]; PlayerItem playerItem = new PlayerItem(); playerItem.quantity = 1; playerItem.name = catalogItem.name; playerItem.id = catalogItem.id; AddPlayerItem addPlayerItem = new AddPlayerItem(); addPlayerItem.playerItem = playerItem; messageHandler.SendReliable(addPlayerItem, Destination.Inventory); }
public RewardInfo RandomReward(Player player, int randomId, string reason) { DRandom di = _drandoms[randomId]; RewardInfo ri = new RewardInfo(); ri.items = new List <RewardItem>(); ri.res = new List <ResInfo>(); if (di.weight.Object.Length <= 0)//必掉 { if (di.gid.Object.Length > 0) { for (int i = 0; i < di.gid.Object.Length; i++) { PlayerItem item = this.AddItem(player, di.gid.Object[i], di.count.Object[i], reason); DItem d = _ditems[di.gid.Object[i]]; RewardItem rii = new RewardItem(); rii.count = di.count.Object[i]; rii.icon = d.icon; rii.id = di.gid.Object[i]; rii.name = d.name; rii.quality = d.quality; rii.type = d.type; ri.items.Add(rii); } } if (di.res_type.Object.Length > 0) { for (int i = 0; i < di.res_type.Object.Length; i++) { //Support su = Spring.bean(PlayerService.class).getSupport(pid); var playerController = Server.GetController <PlayerController>(); playerController.AddCurrency(player, di.res_type.Object[i], di.res_count.Object[i], reason); ResInfo res = new ResInfo() { type = di.res_type.Object[i], count = di.res_count.Object[i] }; ri.res.Add(res); } } } else//随机一个 { int index = MathUtil.RandomIndex(di.weight.Object); if (di.gid.Object.Length > 0) { //约定,如果随机的话,随机到小于等于0的id就是没随到东西 int itemId = di.gid.Object[index]; if (itemId > 0) { PlayerItem item = this.AddItem(player, di.gid.Object[index], di.count.Object[index], reason); DItem d = _ditems[di.gid.Object[index]]; RewardItem rii = new RewardItem(); rii.count = di.count.Object[index]; rii.icon = d.icon; rii.id = di.gid.Object[index]; rii.name = d.name; rii.quality = d.quality; rii.type = d.type; ri.items.Add(rii); } } else if (di.res_type.Object.Length > 0) { //约定,如果随机的话,随机到小于等于0的id就是没随到东西 int resType = di.res_type.Object[index]; if (resType > 0) { var playerController = Server.GetController <PlayerController>(); playerController.AddCurrency(player, di.res_type.Object[index], di.res_count.Object[index], reason); ResInfo res = new ResInfo() { type = di.res_type.Object[index], count = di.res_count.Object[index] }; ri.res.Add(res); } } } return(ri); }
private void SetStaff() { activeItem = staffPrefab; hammerPrefab.gameObject.SetActive(false); staffPrefab.gameObject.SetActive(true); }
public void addPlayerItem(PlayerItem item) { playerItems.Add (item); item.doItemEffect (this); print (defense); }
//根据玩家和容器类别获取容器 public GameContainerItem GetGameContainerItemByPlayerItemAndGameContainerType(PlayerItem playerItem, string gameContainerType) { GameContainerItem returnGameContainerItem = null; foreach (GameContainerItem gameContainerItem in gameContainerItemList) { if (gameContainerItem.controllerPlayerItem == playerItem && gameContainerItem.gameContainerType == gameContainerType) { returnGameContainerItem = gameContainerItem; } } return(returnGameContainerItem); }
public void Add(PlayerItem item) { items[item.name] = item; }
// /admin movefrom x y z x y z radius public override bool HandleCommand(ulong userId, string[] words) { HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); HashSet <long> playerOwners = new HashSet <long>(); foreach (IMyEntity entity in entities) { IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBlock = (MyObjectBuilder_CubeGrid)grid.GetObjectBuilder(); foreach (MyObjectBuilder_CubeBlock block in gridBlock.CubeBlocks) { if (block.Owner == 0) { continue; } if (!playerOwners.Contains(block.Owner)) { playerOwners.Add(block.Owner); } } } Communication.SendPrivateInformation(userId, string.Format("Total block owners: {0}", playerOwners.Count)); int count = 0; foreach (long owner in playerOwners) { ulong steamId = PlayerMap.Instance.GetPlayerItemFromPlayerId(owner).SteamId; if (steamId == 0) { count++; } } Communication.SendPrivateInformation(userId, string.Format("Total owners without a steam Id: {0}", count)); HashSet <long> badPlayers = new HashSet <long>(); HashSet <long> noLogin = new HashSet <long>(); foreach (long owner in playerOwners) { MyObjectBuilder_Checkpoint.PlayerItem item = PlayerMap.Instance.GetPlayerItemFromPlayerId(owner); if (item.SteamId == 0) { continue; } if (!Players.Instance.PlayerLogins.ContainsKey(item.SteamId)) { Communication.SendPrivateInformation(userId, string.Format("No login information: {0}", item.Name)); noLogin.Add(owner); continue; } PlayerItem playerItem = Players.Instance.PlayerLogins[item.SteamId]; if (DateTime.Now - playerItem.LastLogin > TimeSpan.FromDays(20)) { Communication.SendPrivateInformation(userId, string.Format("Player hasn't logged in 20 days: {0}", item.Name)); badPlayers.Add(owner); } } Communication.SendPrivateInformation(userId, string.Format("Users not logged in the last 20 days: {0}", badPlayers.Count)); Communication.SendPrivateInformation(userId, string.Format("Users with no login information: {0}", noLogin.Count)); /* * count = 0; * List<CubeGridEntity> grids = SectorObjectManager.Instance.GetTypedInternalData<CubeGridEntity>(); * foreach(CubeGridEntity grid in grids) * { * Thread.Sleep(100); * foreach (CubeBlockEntity block in grid.CubeBlocks) * { * MyObjectBuilder_CubeBlock blockBuilder = (MyObjectBuilder_CubeBlock)block.Export(); * if (badPlayers.Contains(blockBuilder.Owner) || noLogin.Contains(blockBuilder.Owner)) * { * //grid.DeleteCubeBlock(block); * block.Dispose(); * count++; * } * } * } */ Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); foreach (IMyEntity entity in entities) { IMyCubeGrid grid = (IMyCubeGrid)entity; List <IMySlimBlock> blocks = new List <IMySlimBlock>(); grid.GetBlocks(blocks, x => x.FatBlock != null && x.FatBlock.OwnerId != 0); foreach (IMySlimBlock block in blocks) { IMyCubeBlock cubeBlock = (IMyCubeBlock)block.FatBlock; if (badPlayers.Contains(cubeBlock.OwnerId) || noLogin.Contains(cubeBlock.OwnerId)) { grid.RazeBlock(cubeBlock.Min); count++; } } } }); Communication.SendPrivateInformation(userId, string.Format("Blocks disposed: {0}", count)); return(true); }
private void Start() { playerItem = GetComponent <PlayerItem>(); }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string[] words) { if (words.Count() > 3) { return(false); } if (!words.Any()) { Communication.SendPrivateInformation(userId, GetHelp()); return(true); } int days = -1; if (!int.TryParse(words[0], out days) || days < 0) { Communication.SendPrivateInformation(userId, string.Format("Invalid argument. Days argument must be an integer that is 0 or greater.")); return(true); } // Just assume that anything after the days is going to "ignorenologin" bool removeNoLoginInformation = true; bool removeOwnerless = true; if (words.Any()) { foreach (string word in words) { if (word.ToLower() == "ignorenologin") { removeNoLoginInformation = false; } if (word.ToLower() == "ignoreownerless") { removeOwnerless = false; } } } Communication.SendPrivateInformation(userId, string.Format("Scanning for grids with owners that haven't logged in {0} days. (Must Have Login Info={1})", days, removeNoLoginInformation)); HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>(); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(grid.EntityId); MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) { continue; } // This entity is protected by whitelist if (PluginSettings.Instance.LoginEntityWhitelist.Length > 0 && PluginSettings.Instance.LoginEntityWhitelist.Contains(grid.EntityId.ToString())) { continue; } if (CubeGrids.GetAllOwners(gridBuilder).Count < 1 && removeOwnerless) { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) not owned by anyone.", gridEntity.Name, entity.EntityId)); entitiesFound.Add(entity); continue; } foreach (long player in CubeGrids.GetBigOwners(gridBuilder)) { // This playerId is protected by whitelist if (PluginSettings.Instance.LoginPlayerIdWhitelist.Length > 0 && PluginSettings.Instance.LoginPlayerIdWhitelist.Contains(player.ToString())) { continue; } MyObjectBuilder_Checkpoint.PlayerItem checkItem = PlayerMap.Instance.GetPlayerItemFromPlayerId(player); if (checkItem.IsDead || checkItem.Name == "") { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by dead player - ID: {2}", gridEntity.Name, entity.EntityId, player)); entitiesFound.Add(entity); continue; } PlayerItem item = Players.Instance.GetPlayerById(player); if (item == null) { if (removeNoLoginInformation) { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by a player with no login info: {2}", gridEntity.Name, entity.EntityId, checkItem.Name)); entitiesFound.Add(entity); } } else if (item.LastLogin < DateTime.Now.AddDays(days * -1)) { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by inactive player: {2}", gridEntity.Name, entity.EntityId, PlayerMap.Instance.GetPlayerItemFromPlayerId(player).Name)); entitiesFound.Add(entity); } } } Communication.SendPrivateInformation(userId, string.Format("Found {0} grids owned by inactive users", entitiesFound.Count)); return(true); }
private void CalculateBattle(PlayerItem.Ship attackerShip, PlayerItem.Vik defenderVik) { List<PlayerItem.Warrior>.Enumerator defenderWarriors = defenderVik.warriors.GetEnumerator(); foreach (PlayerItem.Warrior attacker in attackerShip.UnitsAboard) { PlayerItem.Warrior defender = defenderWarriors.Current; Random god = new Random(); if (defenderWarriors.MoveNext()) { if (god.Next(2) == 0) { defender.Alive = false; } else { attacker.Alive = false; } } if (attacker.Alive) { int foodLoot = god.Next(100); if (defenderVik.resources.food < foodLoot) foodLoot = defenderVik.resources.food; defenderVik.resources.food -= foodLoot; attackerShip.foodLoot += foodLoot; int woodLoot = god.Next(100); if (defenderVik.resources.wood < woodLoot) woodLoot = defenderVik.resources.wood; defenderVik.resources.wood -= woodLoot; attackerShip.woodLoot += woodLoot; int stoneLoot = god.Next(100); if (defenderVik.resources.stone < stoneLoot) stoneLoot = defenderVik.resources.stone; defenderVik.resources.stone -= stoneLoot; attackerShip.stoneLoot += stoneLoot; int goldLoot = god.Next(100); if (defenderVik.resources.gold < goldLoot) goldLoot = defenderVik.resources.gold; defenderVik.resources.gold -= goldLoot; attackerShip.goldLoot += goldLoot; } } }
public static PlayerItem Creat(string item) { Debug.Log("Creat from: " + item); var Part1 = item.Split(MDEL); var Part2 = Part1[1].Split(DELEM); Slot slot = (Slot) Convert.ToInt32(Part2[0]); bool isRare = Convert.ToBoolean(Part2[1]); string icon = Part2[2]; string name = Part2[3]; int cost = Convert.ToInt32(Part2[4]); bool isEquped = Convert.ToBoolean(Part2[5]); var firstPart = Part1[0].Split(DELEM); Dictionary<ParamType, float> itemParameters = new Dictionary<ParamType, float>(); //Debug.Log(">>>Part1[0] " + Part1[0]); foreach (var s in firstPart) { if (s.Length < 3) break; var pp = s.Split(DPAR); ParamType type = (ParamType)Convert.ToInt32(pp[0]); float value = Convert.ToSingle(pp[1]); itemParameters.Add(type,value); } PlayerItem playerItem = new PlayerItem(itemParameters, slot, isRare, cost, isEquped, name, icon); //Debug.Log(">>>Part3[0] :" + Part3.ToString()); var Part3 = Part1[2]; var spec = (SpecialAbility) Convert.ToInt32(Part3.ToString()); playerItem.specialAbilities = spec; playerItem.LoadTexture(); return playerItem; }
public static void SavePosition(this PlayerItem player, Vector3 position, Quaternion rotation, int index) { player.LastLocation.Update(position, rotation, index); }
private void RaiseItemUsed(PlayerItem item) { ItemUsed?.Invoke(this, item); }
public static void ResetAndSavePosition(this PlayerItem player, Vector3 position, Quaternion rotation, int index) { player.SavePosition(); player.Client.svPlayer.SvReset(position, rotation, index); }
public DieState(PlayerItem player) { _player = player; }
public static void ResetAndSavePosition(this PlayerItem player, ShPlayer targetPlayer) { player.SavePosition(); player.Client.svPlayer.SvReset(targetPlayer.GetPosition(), targetPlayer.GetRotation(), targetPlayer.GetPlaceIndex()); }
public async Task <GameListData> GetGameList(bool admin) { using (var http = new HttpClient()) { var res = await http.GetStringAsync(queryUrl).ConfigureAwait(false); var gamelist = JsonConvert.DeserializeObject <BZCCRaknetData>(res); SessionItem DefaultSession = new SessionItem(); DefaultSession.Type = GAMELIST_TERMS.TYPE_LISTEN; DataCache Metadata = new DataCache(); foreach (var proxyStatus in gamelist.proxyStatus) { Metadata.AddObjectPath($"{GAMELIST_TERMS.ATTRIBUTE_LISTSERVER}:{proxyStatus.Key}:Status", proxyStatus.Value.status); Metadata.AddObjectPath($"{GAMELIST_TERMS.ATTRIBUTE_LISTSERVER}:{proxyStatus.Key}:Success", proxyStatus.Value.success); Metadata.AddObjectPath($"{GAMELIST_TERMS.ATTRIBUTE_LISTSERVER}:{proxyStatus.Key}:Timestamp", proxyStatus.Value.updated); } DataCache DataCache = new DataCache(); DataCache Mods = new DataCache(); List <SessionItem> Sessions = new List <SessionItem>(); List <Task> Tasks = new List <Task>(); SemaphoreSlim DataCacheLock = new SemaphoreSlim(1); SemaphoreSlim ModsLock = new SemaphoreSlim(1); SemaphoreSlim SessionsLock = new SemaphoreSlim(1); foreach (var raw in gamelist.GET) { Tasks.Add(Task.Run(async() => { SessionItem game = new SessionItem(); game.Address["NAT"] = raw.g; //if (!raw.Passworded) //{ // game.Address["Rich"] = string.Join(null, $"N,{raw.Name.Length},{raw.Name},{raw.mm.Length},{raw.mm},{raw.g},0,".Select(dr => $"{((int)dr):x2}")); //} game.Name = raw.Name; if (!string.IsNullOrWhiteSpace(raw.MOTD)) { game.Message = raw.MOTD; } game.PlayerTypes.Add(new PlayerTypeData() { Types = new List <string>() { GAMELIST_TERMS.PLAYERTYPE_PLAYER }, Max = raw.MaxPlayers }); game.PlayerCount.Add(GAMELIST_TERMS.PLAYERTYPE_PLAYER, raw.CurPlayers); if (!string.IsNullOrWhiteSpace(raw.MapFile)) { game.Level["MapFile"] = raw.MapFile + @".bzn"; } string modID = (raw.Mods?.FirstOrDefault() ?? @"0"); string mapID = raw.MapFile?.ToLowerInvariant(); game.Level["ID"] = $"{modID}:{mapID}"; Task <MapData> mapDataTask = null; if (!string.IsNullOrWhiteSpace(raw.MapFile)) { mapDataTask = mapDataInterface.GetJson($"{mapUrl.TrimEnd('/')}/getdata.php?map={mapID}&mod={modID}"); } game.Status.Add(GAMELIST_TERMS.STATUS_LOCKED, raw.Locked); game.Status.Add(GAMELIST_TERMS.STATUS_PASSWORD, raw.Passworded); string ServerState = null; if (raw.ServerInfoMode.HasValue) { switch (raw.ServerInfoMode) { case 0: // ServerInfoMode_Unknown ServerState = Enum.GetName(typeof(ESessionState), ESessionState.Unknown); break; case 1: // ServerInfoMode_OpenWaiting case 2: // ServerInfoMode_ClosedWaiting (full) ServerState = Enum.GetName(typeof(ESessionState), ESessionState.PreGame); break; case 3: // ServerInfoMode_OpenPlaying case 4: // ServerInfoMode_ClosedPlaying (full) ServerState = Enum.GetName(typeof(ESessionState), ESessionState.InGame); break; case 5: // ServerInfoMode_Exiting ServerState = Enum.GetName(typeof(ESessionState), ESessionState.PostGame); break; } } if (!string.IsNullOrWhiteSpace(ServerState)) { game.Status.Add("State", ServerState); } int ModsLen = (raw.Mods?.Length ?? 0); if (ModsLen > 0 && raw.Mods[0] != "0") { game.Game.Add("Mod", raw.Mods[0]); } if (ModsLen > 1) { game.Game.Add("Mods", JArray.FromObject(raw.Mods.Skip(1))); } if (!string.IsNullOrWhiteSpace(raw.v)) { game.Game["Version"] = raw.v; } if (raw.TPS.HasValue && raw.TPS > 0) { game.Attributes.Add("TPS", raw.TPS); } if (raw.MaxPing.HasValue && raw.MaxPing > 0) { game.Attributes.Add("MaxPing", raw.MaxPing); } if (raw.TimeLimit.HasValue && raw.TimeLimit > 0) { game.Level.AddObjectPath("Attributes:TimeLimit", raw.TimeLimit); } if (raw.KillLimit.HasValue && raw.KillLimit > 0) { game.Level.AddObjectPath("Attributes:KillLimit", raw.KillLimit); } if (!string.IsNullOrWhiteSpace(raw.t)) { switch (raw.t) { case "0": game.Address.Add("NAT_TYPE", $"NONE"); /// Works with anyone break; case "1": game.Address.Add("NAT_TYPE", $"FULL CONE"); /// Accepts any datagrams to a port that has been previously used. Will accept the first datagram from the remote peer. break; case "2": game.Address.Add("NAT_TYPE", $"ADDRESS RESTRICTED"); /// Accepts datagrams to a port as long as the datagram source IP address is a system we have already sent to. Will accept the first datagram if both systems send simultaneously. Otherwise, will accept the first datagram after we have sent one datagram. break; case "3": game.Address.Add("NAT_TYPE", $"PORT RESTRICTED"); /// Same as address-restricted cone NAT, but we had to send to both the correct remote IP address and correct remote port. The same source address and port to a different destination uses the same mapping. break; case "4": game.Address.Add("NAT_TYPE", $"SYMMETRIC"); /// A different port is chosen for every remote destination. The same source address and port to a different destination uses a different mapping. Since the port will be different, the first external punchthrough attempt will fail. For this to work it requires port-prediction (MAX_PREDICTIVE_PORT_RANGE>1) and that the router chooses ports sequentially. break; case "5": game.Address.Add("NAT_TYPE", $"UNKNOWN"); /// Hasn't been determined. NATTypeDetectionClient does not use this, but other plugins might break; case "6": game.Address.Add("NAT_TYPE", $"DETECTION IN PROGRESS"); /// In progress. NATTypeDetectionClient does not use this, but other plugins might break; case "7": game.Address.Add("NAT_TYPE", $"SUPPORTS UPNP"); /// Didn't bother figuring it out, as we support UPNP, so it is equivalent to NAT_TYPE_NONE. NATTypeDetectionClient does not use this, but other plugins might break; default: game.Address.Add("NAT_TYPE", $"[" + raw.t + "]"); break; } } if (string.IsNullOrWhiteSpace(raw.proxySource)) { game.Attributes.Add(GAMELIST_TERMS.ATTRIBUTE_LISTSERVER, $"IonDriver"); } else { game.Attributes.Add(GAMELIST_TERMS.ATTRIBUTE_LISTSERVER, raw.proxySource); } bool m_TeamsOn = false; bool m_OnlyOneTeam = false; switch (raw.GameType) { case 0: game.Level["GameType"] = $"All"; break; case 1: { int GetGameModeOutput = raw.GameSubType.Value % (int)GameMode.GAMEMODE_MAX; // extract if we are team or not int detailed = raw.GameSubType.Value / (int)GameMode.GAMEMODE_MAX; // ivar7 bool RespawnSameRace = (detailed & 256) == 256; bool RespawnAnyRace = (detailed & 512) == 512; game.Level.AddObjectPath("Attributes:Respawn", RespawnSameRace ? "Race" : RespawnAnyRace ? "Any" : "One"); detailed = (detailed & 0xff); switch ((GameMode)GetGameModeOutput) { case GameMode.GAMEMODE_TEAM_DM: case GameMode.GAMEMODE_TEAM_KOTH: case GameMode.GAMEMODE_TEAM_CTF: case GameMode.GAMEMODE_TEAM_LOOT: case GameMode.GAMEMODE_TEAM_RACE: m_TeamsOn = true; break; case GameMode.GAMEMODE_DM: case GameMode.GAMEMODE_KOTH: case GameMode.GAMEMODE_CTF: case GameMode.GAMEMODE_LOOT: case GameMode.GAMEMODE_RACE: default: m_TeamsOn = false; break; } switch (detailed) // first byte of ivar7? might be all of ivar7 // Deathmatch subtype (0 = normal; 1 = KOH; 2 = CTF; add 256 for random respawn on same race, or add 512 for random respawn w/o regard to race) { case 0: game.Level["GameType"] = "DM"; game.Level["GameMode"] = (m_TeamsOn ? "Team " : String.Empty) + "Deathmatch"; break; case 1: game.Level["GameType"] = "KOTH"; game.Level["GameMode"] = (m_TeamsOn ? "Team " : String.Empty) + "King of the Hill"; break; case 2: game.Level["GameType"] = "CTF"; game.Level["GameMode"] = (m_TeamsOn ? "Team " : String.Empty) + "Capture the Flag"; break; case 3: game.Level["GameType"] = "Loot"; game.Level["GameMode"] = (m_TeamsOn ? "Team " : String.Empty) + "Loot"; break; case 4: // DM [RESERVED] game.Level["GameType"] = "DM"; break; case 5: game.Level["GameType"] = "Race"; game.Level["GameMode"] = (m_TeamsOn ? "Team " : String.Empty) + "Race"; break; case 6: // Race (Vehicle Only) game.Level["GameType"] = "Race"; game.Level["GameMode"] = (m_TeamsOn ? "Team " : String.Empty) + "Race"; game.Level.AddObjectPath("Attributes:VehicleOnly", true); break; case 7: // DM (Vehicle Only) game.Level["GameType"] = "DM"; game.Level["GameMode"] = (m_TeamsOn ? "Team " : String.Empty) + "Deathmatch"; game.Level.AddObjectPath("Attributes:VehicleOnly", true); break; default: game.Level["GameType"] = "DM"; //game.Level["GameMode"] = (m_TeamsOn ? "TEAM " : String.Empty) + "DM [UNKNOWN {raw.GameSubType}]"; break; } } break; case 2: { int GetGameModeOutput = raw.GameSubType.Value % (int)GameMode.GAMEMODE_MAX; // extract if we are team or not switch ((GameMode)GetGameModeOutput) { case GameMode.GAMEMODE_TEAM_STRAT: game.Level["GameType"] = "STRAT"; game.Level["GameMode"] = "STRAT"; m_TeamsOn = true; m_OnlyOneTeam = false; break; case GameMode.GAMEMODE_STRAT: game.Level["GameType"] = "STRAT"; game.Level["GameMode"] = "FFA"; m_TeamsOn = false; m_OnlyOneTeam = false; break; case GameMode.GAMEMODE_MPI: game.Level["GameType"] = "MPI"; game.Level["GameMode"] = "MPI"; m_TeamsOn = true; m_OnlyOneTeam = true; break; default: //game.Level["GameType"] = $"STRAT [UNKNOWN {GetGameModeOutput}]"; game.Level["GameType"] = "STRAT"; //game.Level["GameMode"] = null; break; } } break; case 3: // impossible, BZCC limits to 0-2 game.Level["GameType"] = "MPI"; // "MPI [Invalid]"; break; } if (!string.IsNullOrWhiteSpace(raw.d)) { game.Game.Add("ModHash", raw.d); // base64 encoded CRC32 } foreach (var dr in raw.pl) { PlayerItem player = new PlayerItem(); player.Name = dr.Name; player.Type = GAMELIST_TERMS.PLAYERTYPE_PLAYER; if ((dr.Team ?? 255) != 255) // 255 means not on a team yet? could be understood as -1 { player.Team = new PlayerTeam(); if (m_TeamsOn) { if (!m_OnlyOneTeam) { if (dr.Team >= 1 && dr.Team <= 5) { player.Team.ID = "1"; } if (dr.Team >= 6 && dr.Team <= 10) { player.Team.ID = "2"; } if (dr.Team == 1 || dr.Team == 6) { player.Team.Leader = true; } } } player.Team.SubTeam = new PlayerTeam() { ID = dr.Team.Value.ToString() }; player.GetIDData("Slot").Add("ID", dr.Team); } if (dr.Kills.HasValue) { player.Stats.Add("Kills", dr.Kills); } if (dr.Deaths.HasValue) { player.Stats.Add("Deaths", dr.Deaths); } if (dr.Score.HasValue) { player.Stats.Add("Score", dr.Score); } if (!string.IsNullOrWhiteSpace(dr.PlayerID)) { player.GetIDData("BZRNet").Add("ID", dr.PlayerID); switch (dr.PlayerID[0]) { case 'S': { player.GetIDData("Steam").Add("Raw", dr.PlayerID.Substring(1)); try { ulong playerID = 0; if (ulong.TryParse(dr.PlayerID.Substring(1), out playerID)) { player.GetIDData("Steam").Add("ID", playerID.ToString()); await DataCacheLock.WaitAsync(); try { if (!DataCache.ContainsPath($"Players:IDs:Steam:{playerID.ToString()}")) { PlayerSummaryModel playerData = await steamInterface.Users(playerID); DataCache.AddObjectPath($"Players:IDs:Steam:{playerID.ToString()}:AvatarUrl", playerData.AvatarFullUrl); DataCache.AddObjectPath($"Players:IDs:Steam:{playerID.ToString()}:Nickname", playerData.Nickname); DataCache.AddObjectPath($"Players:IDs:Steam:{playerID.ToString()}:ProfileUrl", playerData.ProfileUrl); } } finally { DataCacheLock.Release(); } } } catch { } } break; case 'G': { player.GetIDData("Gog").Add("Raw", dr.PlayerID.Substring(1)); try { ulong playerID = 0; if (ulong.TryParse(dr.PlayerID.Substring(1), out playerID)) { playerID = GogInterface.CleanGalaxyUserId(playerID); player.GetIDData("Gog").Add("ID", playerID.ToString()); await DataCacheLock.WaitAsync(); try { if (!DataCache.ContainsPath($"Players:IDs:Gog:{playerID.ToString()}")) { GogUserData playerData = await gogInterface.Users(playerID); DataCache.AddObjectPath($"Players:IDs:Gog:{playerID.ToString()}:AvatarUrl", playerData.Avatar.sdk_img_184 ?? playerData.Avatar.large_2x ?? playerData.Avatar.large); DataCache.AddObjectPath($"Players:IDs:Gog:{playerID.ToString()}:Username", playerData.username); DataCache.AddObjectPath($"Players:IDs:Gog:{playerID.ToString()}:ProfileUrl", $"https://www.gog.com/u/{playerData.username}"); } } finally { DataCacheLock.Release(); } } } catch { } } break; } } game.Players.Add(player); } if (raw.GameTimeMinutes.HasValue) { game.Time.AddObjectPath("Seconds", raw.GameTimeMinutes * 60); game.Time.AddObjectPath("Resolution", 60); game.Time.AddObjectPath("Max", raw.GameTimeMinutes.Value == 255); // 255 appears to mean it maxed out? Does for currently playing. if (!string.IsNullOrWhiteSpace(ServerState)) { game.Time.AddObjectPath("Context", ServerState); } } MapData mapData = null; if (mapDataTask != null) { mapData = await mapDataTask; } if (mapData != null) { game.Level["Image"] = $"{mapUrl.TrimEnd('/')}/{mapData.image ?? "nomap.png"}"; game.Level["Name"] = mapData?.title; game.Level["Description"] = mapData?.description; //game.Level.AddObjectPath("Attributes:Vehicles", new JArray(mapData.map.vehicles.Select(dr => $"{modID}:{dr}").ToArray())); await ModsLock.WaitAsync(); if (mapData?.mods != null) { foreach (var mod in mapData.mods) { if (!Mods.ContainsKey(mod.Key)) { Mods.AddObjectPath($"{mod.Key}:Name", mod.Value?.name ?? mod.Value?.workshop_name); Mods.AddObjectPath($"{mod.Key}:ID", mod.Key); if (UInt64.TryParse(mod.Key, out _)) { Mods.AddObjectPath($"{mod.Key}:Url", $"http://steamcommunity.com/sharedfiles/filedetails/?id={mod.Key}"); } } } } ModsLock.Release(); } await SessionsLock.WaitAsync(); try { Sessions.Add(game); } finally { SessionsLock.Release(); } })); } Task.WaitAll(Tasks.ToArray()); return(new GameListData() { Metadata = Metadata, SessionDefault = DefaultSession, DataCache = DataCache, Sessions = Sessions, Mods = Mods, Raw = admin ? res : null, }); } }
public static void SavePosition(this PlayerItem player) { player.SavePosition(player.Client.GetPosition(), player.Client.GetRotation(), player.Client.GetPlaceIndex()); }
public void MPRefill(GameSession session, ItemMPRefillReqMessage message) { // Todo Some improvements Player player = session.Player; PlayerItem playerItem = player.Inventory[message.ItemId2]; PlayerItem playerItem2 = player.Inventory[message.ItemId]; uint[] array = new uint[25] { 168, 168, 336, 336, 504, 504, 672, 672, 840, 840, 1176, 1176, 1512, 1680, 2016, 2688, 3360, 4032, 4872, 6048, 6048, 6048, 6048, 6048, 6048 }; if (playerItem.EnchantMP >= array[playerItem.EnchantLvl]) { session.SendAsync(new ItemMPRefillAckMessage { Result = 1 }); return; } if (playerItem == null || playerItem2 == null || player == null || playerItem.PeriodType == ItemPeriodType.Units || (int)playerItem.ItemNumber.Category > 2) { session.SendAsync(new ItemMPRefillAckMessage { Result = 1 }); return; } playerItem2.Count--; if (playerItem2.Count == 0) { player.Inventory.Remove(playerItem2.Id); } else { session.SendAsync(new ItemUpdateInventoryAckMessage(InventoryAction.Update, playerItem2.Map <PlayerItem, ItemDto>())); } playerItem.EnchantMP += 6048; if (playerItem.EnchantMP > array[playerItem.EnchantLvl]) { playerItem.EnchantMP = array[playerItem.EnchantLvl]; } session.SendAsync(new ItemMPRefillAckMessage { Result = 0 }); session.SendAsync(new ItemUpdateInventoryAckMessage(InventoryAction.Update, playerItem.Map <PlayerItem, ItemDto>())); return; }
public List <PlayerItem> Read() { List <PlayerItem> items = new List <PlayerItem>(); byte[] bytes = File.ReadAllBytes(filename); int pos = 0; int file_ver = IOHelper.GetShort(bytes, pos); pos += 2; if (file_ver != SUPPORTED_FILE_VER) { throw new InvalidDataException($"This format of IAStash files is not supported, expected {SUPPORTED_FILE_VER}, got {file_ver}"); } Func <string> readString = () => { var s = IOHelper.GetBytePrefixedString(bytes, pos); pos += 1 + s?.Length ?? 0; return(s); }; int numItems = IOHelper.GetInt(bytes, pos); pos += 4; for (int i = 0; i < numItems; i++) { PlayerItem pi = new PlayerItem(); pi.BaseRecord = readString(); pi.PrefixRecord = readString(); pi.SuffixRecord = readString(); pi.ModifierRecord = readString(); pi.TransmuteRecord = readString(); pi.Seed = IOHelper.GetUInt(bytes, pos); pos += 4; pi.MateriaRecord = readString(); pi.RelicCompletionBonusRecord = readString(); pi.RelicSeed = IOHelper.GetUInt(bytes, pos); pos += 4; pi.EnchantmentRecord = readString(); //seed is ok, stack count is not pi.UNKNOWN = IOHelper.GetUInt(bytes, pos); pos += 4; pi.EnchantmentSeed = IOHelper.GetUInt(bytes, pos); pos += 4; pi.MateriaCombines = IOHelper.GetShort(bytes, pos); pos += 2; pi.StackCount = IOHelper.GetUInt(bytes, pos); pos += 4; pi.IsHardcore = bytes[pos++] == 1; pos++; // isExpansion //pi.IsExpansion1 = bytes[pos++] == 1; pi.Mod = readString(); pi.OnlineId = IOHelper.GetLong(bytes, pos); if (pi.OnlineId == 0) { pi.OnlineId = null; } pos += 8; items.Add(pi); } return(items); }
//读取模式并做出一定的设置 public void GameInterfacePreparationByGameModel(GameModelProxy gameModelProxy, PlayerGroupProxy playerGroupProxy, QuestStageCircuitProxy questStageCircuitProxy, EffectInfoProxy effectInfoProxy, GameContainerProxy gameContainerProxy, string gameModelName) { gameModelProxy.setGameModelNow(gameModelName); HexGridProxy hexGridProxy = Facade.RetrieveProxy(HexGridProxy.NAME) as HexGridProxy; hexGridProxy.InitializeTheProxy(gameModelProxy.hexModelInfoNow); int number = 0; foreach (PlayerItem playerItem in playerGroupProxy.playerGroup.playerItems.Values) { GM_PlayerSite playerSiteOne = gameModelProxy.gameModelNow.playerSiteList[number]; playerItem.LoadingGameModelPlayerSet(playerSiteOne); gameContainerProxy.CreateNecessaryContainer(playerItem, gameModelProxy.gameModelNow.gameContainerTypeList); number++; } //初始化流程信息 //将流程需要的监听放入到监听效果集合中 for (int n = 0; n < gameModelProxy.gameModelNow.turnStage.Length; n++) { GM_OneStageSite oneStageSite = gameModelProxy.stageSiteMap[gameModelProxy.gameModelNow.turnStage[n]]; questStageCircuitProxy.circuitItem.questOneTurnStageList.Add(oneStageSite); foreach (string effectCode in oneStageSite.effectNeedExeList) { //创建空的实体信息,在执行的时候会用到 EffectInfo oneEffectInfo = effectInfoProxy.GetDepthCloneEffectByName(effectCode); CardEntry cardEntry = new CardEntry(); PlayerItem player = new PlayerItem("NONE"); oneEffectInfo.cardEntry = cardEntry; oneEffectInfo.player = player; if (oneEffectInfo.impactType == "GameModelRule") { questStageCircuitProxy.circuitItem.putOneEffectInfoInActiveMap(oneEffectInfo, effectInfoProxy.effectSysItem.impactTimeTriggerMap); } } } //通知渲染战场 SendNotification(HexSystemEvent.HEX_VIEW_SYS, null, HexSystemEvent.HEX_VIEW_SYS_SHOW_START); //渲染费用栏 SendNotification( UIViewSystemEvent.UI_VIEW_CURRENT, null, StringUtil.GetNTByNotificationTypeAndUIViewName( UIViewSystemEvent.UI_VIEW_CURRENT_OPEN_ONE_VIEW, UIViewConfig.getNameStrByUIViewName(UIViewName.ManaInfoView) ) ); //渲染科技栏 SendNotification( UIViewSystemEvent.UI_VIEW_CURRENT, null, StringUtil.GetNTByNotificationTypeAndUIViewName( UIViewSystemEvent.UI_VIEW_CURRENT_OPEN_ONE_VIEW, UIViewConfig.getNameStrByUIViewName(UIViewName.TraitCombinationView) ) ); //渲染船只栏 SendNotification( UIViewSystemEvent.UI_VIEW_CURRENT, null, StringUtil.GetNTByNotificationTypeAndUIViewName( UIViewSystemEvent.UI_VIEW_CURRENT_OPEN_ONE_VIEW, UIViewConfig.getNameStrByUIViewName(UIViewName.ShipComponentView) ) ); //打开回合控制栏 SendNotification( UIViewSystemEvent.UI_VIEW_CURRENT, questStageCircuitProxy.circuitItem.questOneTurnStageList, StringUtil.GetNTByNotificationTypeAndUIViewName( UIViewSystemEvent.UI_VIEW_CURRENT_OPEN_ONE_VIEW, UIViewConfig.getNameStrByUIViewName(UIViewName.TurnSysProgressBarView) ) ); }
public static PlayerItem CreatMainSlot(Slot slot, int level) { var totalPoints = Formuls.GetPlayerItemPointsByLvl(level) * Formuls.GetSlotCoef(slot); float diff = Utils.RandomNormal(0.5f, 1f); var primaryValue = totalPoints * diff; var rarity = GetRarity(); var pparams = new Dictionary<ParamType, float>(); bool addSpecial = false; var special = GetSpecial(slot); Action paramInit = () => { if ((special == SpecialAbility.none || UnityEngine.Random.Range(0, 10) < 5) || addSpecial) { var secondaryParam = GetSecondaryParam(totalPoints, slot); if (pparams.ContainsKey(secondaryParam.Key)) { pparams[secondaryParam.Key] += secondaryParam.Value; } else { pparams.Add(secondaryParam.Key, secondaryParam.Value); } } else { addSpecial = true; } }; switch (rarity) { case Rarity.Magic: paramInit(); break; case Rarity.Rare: paramInit(); paramInit(); break; } var primary = Connections.GetPrimaryParamType(slot); pparams.Add(primary,primaryValue); PlayerItem item = new PlayerItem(pparams,slot, rarity, totalPoints); if (addSpecial) { item.specialAbilities = special; } return item; }
public override void Execute(Session session, CommandContext context) { /* * order of arguments: * 0. weapon|armor * 1. name * 2. description * 3. wear location * 4. weight * 5. value * 6. min damage|hp bonus * 7. max damage|armor bonus */ try { if (context.CommandName.ToLower() == "template" && context.Arguments.Count != args.Max(v => v.Value) + 1) { session.WriteLine("template command expecets {0} arguments.", args.Max(v => v.Value) + 1); PrintSyntax(session); return; } // if only one arg, will be assumed to be "item key" bool isGenericMakeitem = context.CommandName.ToLower() == "makeitem" && context.Arguments.Count == 1; Template newItem = null; // check whether item already exists newItem = Server.Current.Database.Get <Template>(context.Arguments[args[ItemArgType.Name]]); if (newItem != null && context.CommandName.ToLower() == "template") { session.WriteLine("Aborting: item already templated: {0}", newItem.Key); return; } if (context.CommandName.ToLower() == "template" || !isGenericMakeitem) { Validate(context.Arguments); } if (context.CommandName.ToLower() == "template" || newItem == null) { newItem = BuildItem(context.Arguments); Server.Current.Database.Save(newItem); // notify session.WriteLine("Info: item templated: {0}...", newItem.Name); } if (context.CommandName.ToLower() == "makeitem") { //PlayerItem dupedItem = newItem.Copy(); PlayerItem dupedItem = Mapper.Map <PlayerItem>(newItem); if (!isGenericMakeitem) { dupedItem.Name = context.Arguments[args[ItemArgType.Name]]; dupedItem.Description = context.Arguments[args[ItemArgType.Description]]; dupedItem.Keywords = context.Arguments[args[ItemArgType.Keywords]].Split(' '); dupedItem.Weight = Convert.ToInt32(context.Arguments[args[ItemArgType.Weight]]); dupedItem.Value = Convert.ToInt32(context.Arguments[args[ItemArgType.Value]]); dupedItem.WearLocation = (Wearlocation)Enum.Parse(typeof(Wearlocation), context.Arguments[args[ItemArgType.WearLocation]]); dupedItem.ArmorBonus = Convert.ToInt32(context.Arguments[args[ItemArgType.ArmorBonus]]); dupedItem.HpBonus = Convert.ToInt32(context.Arguments[args[ItemArgType.HpBonus]]); } Server.Current.Database.Save(dupedItem); // add to inventory session.Player.Inventory[dupedItem.Key] = dupedItem.Name; session.WriteLine("Info: item duplicated in inventory..."); } } catch { PrintSyntax(session); } }
private static async Task RefreshPlayerItem(Players player) { PlayerItem item = await Player.GetItem(player); GlobalVariables.CurrentPlayerState.CurrentPlayerItem = item; }
private void CheckIfFirstLevel() { var money = playerInv[ItemId.money] == 0; var lvl = Level == 1; var items = playerItems.Count == 0; if (money && lvl && items) { PlayerItem item1 = new PlayerItem(new Dictionary<ParamType, float>() { {ParamType.PPower, 15} },Slot.physical_weapon, false,1); PlayerItem item2 = new PlayerItem(new Dictionary<ParamType, float>() { { ParamType.MPower, 10 } }, Slot.magic_weapon, false, 1); var talisman = new TalismanItem(10,TalismanType.doubleDamage); var talisman2 = new TalismanItem(10, TalismanType.heal); item1.specialAbilities = SpecialAbility.vampire; AddAndEquip(item1); AddAndEquip(item2); AddAndEquip(talisman); AddAndEquip(talisman2); listOfOpendBornPositions[1].Add(1); foreach (var a in listOfOpendBornPositions[1]) { Debug.Log(">>>>>>>>>>>>>>>>>>>>>>>> " + a); } SaveListOfBornPosition(); } }
protected override void DoRender(HtmlTextWriter output) { Database db = Sitecore.Context.Database; StringBuilder sbOut = new StringBuilder(); StringBuilder sbError = new StringBuilder(); //get the player long playerid = -1; //check to see if the guid is there if (long.TryParse(this.Attributes["player"], out playerid)) { //get player obj PlayerItem p = PlayerLibraryItem.GetPlayer(playerid); if (p != null) { //parse wmode WMode wmode = WMode.Window; try { wmode = (WMode)Enum.Parse(wmode.GetType(), this.Attributes["wmode"], true); }catch {} //get background color string bgcolor = this.Attributes["bgcolor"]; bgcolor = (bgcolor == "") ? "#ffffff" : bgcolor; //parse autostart bool autostart = false; try { bool.Parse(this.Attributes["autostart"]); }catch {} //determine which embed code to display if (p.PlaylistType.Equals(PlayerPlaylistType.None)) { //get the video id long videoid = -1; if (long.TryParse(this.Attributes["video"], out videoid)) { //try parse the id and get the item VideoItem v = VideoLibraryItem.GetVideo(videoid); if (v != null) { sbOut.Append(p.GetEmbedCode(v, bgcolor, autostart, wmode)); } } } else if (p.PlaylistType.Equals(PlayerPlaylistType.VideoList)) { long videolist = -1; if (long.TryParse(this.Attributes["videolist"], out videolist)) { sbOut.Append(p.GetEmbedCode(videolist, bgcolor, autostart, wmode)); } } else if (p.PlaylistType.Equals(PlayerPlaylistType.ComboBox) || p.PlaylistType.Equals(PlayerPlaylistType.Tabbed)) { //get both the lists and build a string list string tabs = this.Attributes["playlisttabs"]; string combo = this.Attributes["playlistcombo"]; List <string> t = tabs.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); t.AddRange(combo.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList()); //convert to a list of long List <long> playlists = new List <long>(); foreach (string s in t) { long temp = -1; if (long.TryParse(s, out temp)) { playlists.Add(temp); } } //get the embed code sbOut.Append(p.GetEmbedCode(playlists, bgcolor, autostart, wmode)); } //if nothing then just get embed for player with nothing if (sbOut.Length.Equals(0)) { sbOut.Append(p.GetEmbedCode(bgcolor, autostart, wmode)); } } else { sbError.AppendLine("Player doesn't exist in Sitecore."); } } else { sbError.AppendLine("Player value is not a long."); } //determine if it's an error or not if (sbError.Length > 0) { output.WriteLine("<div style=\"display:none;\">" + sbError.ToString() + "</div>"); } else { output.WriteLine(sbOut.ToString()); } }
//public Dictionary<int, Animation> animationUse; public void Start() { controller = GetComponentInChildren <PlayerController>(); playerItem = new PlayerItem(); animator = this.GetComponent <Animator>(); }
void Awake() { _transform = transform; _animator = GetComponent<Animator>(); _cPlayerItem = FindObjectOfType(typeof(PlayerItem)) as PlayerItem; }