void Present(ItemManager manager) { for (var i = 1; i < items.Length; i++) items[i].ServerInfo = null; foreach (var item in manager.Where(ItemLocation.PackageType.Equip)) items[item.TableInfo.Type.equipPos].ServerInfo = item; }
protected void Awake() { SetItemType(this.GetType().FullName); _player = GameObject.Find("Players") as GameObject; _manager = GameObject.Find("Manager").GetComponent<PartAManager>(); item_manager = GameObject.Find("Manager").GetComponent<ItemManager>(); }
/// <summary> /// Init this instance. /// </summary> protected virtual void Init() { counterText = GetComponent<Text> (); if (itemManager == null) { itemManager = FindObjectOfType<ItemManager>(); if (itemManager == null) { characterLoader = FindObjectOfType<CharacterLoader>(); if (characterLoader != null) characterLoader.CharacterLoaded += HandleCharacterLoaded; else Debug.LogError("UIStackable_ItemCounter could not find an ItemManager or Character Loader."); } else { itemManager.ItemCollected += HandleItemCollected; itemManager.ItemConsumed += HandleItemCollected; itemManager.Loaded += HandleItemCollected; LevelManager.Instance.Respawned += HandleRespawned; } } else { itemManager.ItemCollected += HandleItemCollected; itemManager.ItemConsumed += HandleItemCollected; itemManager.Loaded += HandleItemCollected; LevelManager.Instance.Respawned += HandleRespawned; } }
/* * Initializes empty inventory slot containing empty item objects */ void Start() { _item_manager = GetComponent<ItemManager>(); _inventory_panel = GameObject.Find("Inventory Panel"); _slot_panel = _inventory_panel.transform.FindChild("Slot Panel").gameObject; _inv_full_text = _inventory_panel.transform.FindChild("Inventory Full").gameObject; _inv_full_text.SetActive(false); for (int i = 0; i < Constants.SLOT_AMOUNT; i++) { inventory_item_list.Add(new Item()); slot_list.Add(Instantiate(inventory_slot)); slot_list[i].GetComponent<InventorySlot>().slot_pos = i; slot_list[i].transform.SetParent(_slot_panel.transform); // Sets scaling factor of gridlayout component to 1 to work with // the unity "Scale With Screen Size" ui scale mode slot_list[i].transform.localScale = new Vector3(1, 1, 1); } // TODO: Remove this. Adding initial items to the inventory (testing) //AddItem(1); //AddItem(2); //AddItem(2, 200); //AddItem(3, 10); //AddItem(0); //AddItem(1); //AddItem(5, 5); //AddItem(6); //AddItem(7); }
void Start () { momSearched = false; dadSearcehed = false; itemManager = GameObject.FindGameObjectWithTag ("IM"); itemScript = itemManager.GetComponent<ItemManager> (); }
void Awake() { //hide message text gameOverText.gameObject.SetActive(false); isGameOver = false; //get manager mItemManager = GetComponent<ItemManager>(); mMonsterManager = GetComponent<MonsterManager>(); mMapManager = GetComponent<MapManager>(); //get character setting mSetUp = (SetUpManager)FindObjectOfType<SetUpManager> (); mPlayerData = new List<CharacterSetupManager>(mSetUp.transform.GetComponentsInChildren<CharacterSetupManager>()); PlayerCount = mPlayerData.Count; PlayerLeft = PlayerCount; Debug.Log ("playerCount: " + PlayerCount); //get map setting mMapManager.setMapList (mSetUp.mapList); //build player list mPlayerList = new List<Damagable> (); mPlayerPositionIndex = new List<int>(); //build item list mItemOnMapList = new List<Item>(); mItemOnMapPositionIndex = new List<int>(); mItemSpawnCounters = new List<float>(); //build monster list //.... mGameStage = GameStage.Init; }
// Use this for initialization void Start() { bike = this.transform.FindChild("Bike").gameObject; manager = GameObject.Find("Manager").GetComponent<ItemManager>(); bike_anim = bike.GetComponent<Animator>(); center = new Vector3(0,-3.8f,0); }
void Start() { item_manager = GameObject.Find("Manager").GetComponent<ItemManager>(); damageSE = Resources.Load("Sound/bike_damage") as AudioClip; bombSE = Resources.Load("Sound/bomb") as AudioClip; AudioSource.PlayClipAtPoint(bombSE,this.transform.position,0.5f); }
// Use this for initialization void Awake() { stage = PlayerPrefs.GetInt("Stage"); anim = this.GetComponent<Animator>(); anim.SetInteger("Stage",stage); Debug.Log(stage); item_mng = GameObject.Find("Manager").GetComponent<ItemManager>(); }
void Awake() { if (!instance) { Debug.Log("Setting up item manarger Instance"); instance = this; } }
public void Initialize(Menu menu, ItemManager itemManager) { menu.AddMItem("Enemy min HP %", new Slider(20), (sender, args) => _minEnemyHealth = args.GetNewValue<Slider>().Value).ProcStoredValueChanged<Slider>(); if (ObjectManager.Player.ChampionName == "Twitch") { menu.AddMItem("Only in Twitch ult", true, (sender, args) => _onlyTwitchUlt = args.GetNewValue<bool>()).ProcStoredValueChanged<bool>(); } }
public void Initialize() { TShock.Config = new ConfigFile(); TShock.Config.StorageType = "sqlite"; DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", "tshock.test.sqlite")); DB.Open(); manager = new ItemManager(DB); }
public override void OnEnable() { base.OnEnable(); craftingCategoryID = serializedObject.FindProperty("craftingCategoryID"); itemManager = Editor.FindObjectOfType<ItemManager>(); if (itemManager == null) Debug.LogError("No item manager found in scene, cannot edit item."); }
/// <summary> /// Model -> View /// </summary> void Present(ItemManager manager) { if (this.gameObject.activeSelf == false || items == null) return; var i = 0; foreach (var item in manager.Where(ItemLocation.PackageType.Main).Take(items.Length)) items[i++].ServerInfo = item; for (; i < items.Length; i++) items[i].ServerInfo = null; }
public ClassicMaze(int displayWidth, int displayHeight, IMazeGameHost host) : base(displayWidth, displayHeight, new GuestProfile()) { timeScoreIncrement = 1.67; maxTimeScore = 1000; this.gameHost = host; timeToCompleteMaze = new TimeKeeper(); itemManager = new ItemManager(); camCol = null; camRow = null; }
// Use this for initialization void Start () { ItemPrefabs = new Dictionary<string, GameObject> (); if (ItemNames.Length == ItemObjects.Length && ItemNames.Length > 0) { for (int i = 0; i < ItemNames.Length; i++) { if(ItemNames[i] != null && ItemObjects[i] != null) ItemPrefabs.Add(ItemNames[i],ItemObjects[i]); } } Instance = this; }
public ClassicMaze(int displayWidth, int displayHeight, IMazeGameHost host, UserProfile profile, GameDifficulty difficulty = GameDifficulty.Normal) : base(displayWidth, displayHeight, profile, difficulty) { timeScoreIncrement = 1.67; maxTimeScore = 1000; this.gameHost = host; timeToCompleteMaze = new TimeKeeper(); itemManager = new ItemManager(); camRow = null; camCol = null; }
public static void InitializeManager() { ActionMgr = ActionManager.GetInstance(); AddonMgr = AddonManager.GetInstance(); SkillMgr = SkillManager.GetInstance(); SpellMgr = SpellManager.GetInstance(); SpecializationMgr = SpecializationManager.GetInstance(); ItemMgr = ItemManager.GetInstance(); DataMgr = DataManager.GetInstance(); SpawnMgr = SpawnManager.GetInstance(); GossipMgr = GossipManager.GetInstance(); ObjectMgr = ObjectManager.GetInstance(); WorldMgr = WorldManager.GetInstance(); LevelStatMgr = LevelStatManager.GetInstance(); }
public void AddToList(Item item, int amount) { bool found = false; for(int i = 0;i < listSellItem.Count;i++){ if(listSellItem[i].item.Equals(item)){ listSellItem[i].amount += amount; found = true; break; } } if(!found){ ItemManager newItemManager = new ItemManager(item,amount); listSellItem.Add(newItemManager); } }
/// <summary> /// Handles the character loaded event. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event.</param> protected virtual void HandleCharacterLoaded(object sender, CharacterEventArgs e) { itemManager = e.Character.GetComponentInChildren<ItemManager>(); if (itemManager != null) { itemManager.ItemCollected += HandleItemCollected; itemManager.Loaded += HandleItemCollected; itemManager.ItemConsumed += HandleItemCollected; LevelManager.Instance.Respawned += HandleRespawned; UpdateText (); } else { Debug.LogError ("Character was loaded but not ItemManager was found"); } UpdateText (); }
// Use this for initialization void Start() { itempattern = PatternLoad.ReadExcelPattern(path); center = Vector3.zero; itemzones = new GameObject[]{ this.transform.FindChild("ItemzoneRight").gameObject, this.transform.FindChild("ItemzoneLeft").gameObject }; item_manager = GameObject.Find("Manager").GetComponent<ItemManager>(); kindobject = new GameObject[]{ Resources.Load("Prefabs/Item") as GameObject, Resources.Load("Prefabs/ExplosionAOE") as GameObject }; ObjectUpdate(); }
protected virtual void Init() { barImage = GetComponent<Image> (); if (itemManager == null) { itemManager = FindObjectOfType<ItemManager>(); if (itemManager == null) { Debug.LogError("UIStackable_PercentageBar could not find an ItemManager."); } else { Debug.LogWarning("No ItemManager assigned, using the first one found."); } } }
private void Awake() { orderMgr = FindObjectOfType<SpriteOrderLayerManager>(); battleMgr = FindObjectOfType<BattleManager>(); itemMgr = FindObjectOfType<ItemManager>(); bgmMgr = FindObjectOfType<BgmManager>(); isRun = true; pauseUI = FindObjectOfType<Pause>(); isDefenceTurn = true; PlayerData.instance.CheckInstance(); GameEventManager.instance.CheckInstance(); StartCoroutine(SceneFader.Instance.FadeIn(0.6f)); GameObject.FindObjectOfType<SceneFader>().transform.SetParent(Camera.main.transform, true); }
public override void OnEnable() { base.OnEnable(); item = (ItemCollectionBase)target; //serializer = new SerializedObject(target); serializer = serializedObject; collectionName = serializer.FindProperty("collectionName"); restrictByWeight = serializer.FindProperty("restrictByWeight"); restrictMaxWeight = serializer.FindProperty("restrictMaxWeight"); itemButtonPrefab = serializer.FindProperty("itemButtonPrefab"); items = serializer.FindProperty("_items"); filters = serializer.FindProperty("filters"); useReferences = serializer.FindProperty("useReferences"); canContainCurrencies = serializer.FindProperty("canContainCurrencies"); canDropFromCollection = serializer.FindProperty("canDropFromCollection"); canUseItemsFromReference = serializer.FindProperty("canUseItemsFromReference"); canUseFromCollection = serializer.FindProperty("canUseFromCollection"); canDragInCollection = serializer.FindProperty("canDragInCollection"); canPutItemsInCollection = serializer.FindProperty("canPutItemsInCollection"); canStackItemsInCollection = serializer.FindProperty("canStackItemsInCollection"); canUnstackItemsInCollection = serializer.FindProperty("canUnstackItemsInCollection"); manuallyDefineCollection = serializer.FindProperty("manuallyDefineCollection"); container = serializer.FindProperty("container"); itemManager = Editor.FindObjectOfType<ItemManager>(); if (itemManager == null) Debug.LogError("No item manager found in scene, cannot edit item."); manualItemsList = new UnityEditorInternal.ReorderableList(serializer, items, true, true, true, true); manualItemsList.drawHeaderCallback += rect => { EditorGUI.LabelField(rect, "Select items"); }; manualItemsList.drawElementCallback += (rect, index, active, focused) => { rect.height = 16; rect.y += 2; EditorGUI.PropertyField(rect, items.GetArrayElementAtIndex(index)); }; }
void Start() { _item_manager = GetComponent<ItemManager>(); _inventory_panel = GameObject.Find("Inventory Panel"); _slot_panel = _inventory_panel.transform.FindChild("Slot Panel").gameObject; for (int i = 0; i < Constants.SLOT_AMOUNT; i++) { inventory_item_list.Add(new Item()); //Debug.Log(i); slot_list.Add(Instantiate(inventory_slot)); slot_list[i].GetComponent<InventorySlot>().slot_pos = i; slot_list[i].transform.SetParent(_slot_panel.transform); } AddItem(0); AddItem(1); AddItem(1); }
public void SQLiteItemTest_RemoveBan() { manager = new ItemManager(DB); Assert.IsNotNull(manager); Assert.AreEqual(2, manager.ItemBans.Count); manager.AddNewBan("Dirt Block"); Assert.AreEqual(2, manager.ItemBans.Count); Assert.AreEqual(true, manager.ItemIsBanned("Dirt Block")); manager.RemoveBan("Dirt Block"); manager.UpdateItemBans(); Assert.AreEqual(1, manager.ItemBans.Count); Assert.AreEqual(false, manager.ItemIsBanned("Dirt Block")); manager.RemoveBan("Dirt Block"); Assert.AreEqual(false, manager.ItemIsBanned("Dirt Block")); Assert.AreEqual(true, manager.ItemIsBanned("Green Brick")); manager.RemoveBan("Green Brick"); Assert.AreEqual(false, manager.ItemIsBanned("Green Brick")); }
// Use this for initialization void Awake() { Instance = this; items = new List<Item>() { new Weapon((int)ItemIDs.Gun , "Gun" , 'w' , 1 , 0 , false , false, -1 ), new Weapon((int)ItemIDs.Magnum , "Magnum" , 'w' , 2 , 0 , false , true , 6 ), new Weapon((int)ItemIDs.Shotgun , "Shotgun" , 'w' , 0 , 0 , true , false, 20 ), new Item ((int)ItemIDs.Grenades , "Granades" , 'g' ), new Item ((int)ItemIDs.Razor , "Razor" , 'r' ), new Weapon((int)ItemIDs.AK47 , "AK47" , 'w' , 2 , 1 , false , false, 30 ), new Weapon((int)ItemIDs.Laser , "Laser" , 'w' , 2 , 3 , false , true, 400 ), new Weapon((int)ItemIDs.Rocketlauncher , "Rocketlauncher" , 'w' , 2 ,-1 , false , false, 3 ), new Weapon((int)ItemIDs.Minigun , "Minigun" , 'w' , 2 , 2 , true , false, 200 ) }; foreach (Transform child in GameObject.Find("Brockules").transform) if (child.name == "Gun") ActivateItem(child.gameObject); }
public void AddToSellList(Item item, int amount) { bool found = false; if(amount > fighterInventory.amounts[fighterInventory.items.IndexOf(item)]){ amount = fighterInventory.amounts[fighterInventory.items.IndexOf(item)]; } for(int i = 0;i < listSellItemManager.Count;i++){ if(listSellItemManager[i].item.Equals(item)){ listSellItemManager[i].amount += amount; found = true; break; } } if(!found){ ItemManager newItemManager = new ItemManager(item,amount); listSellItemManager.Add(newItemManager); } fighterInventory.RemoveFromInventory (item, amount); }
/* * Retrives the ItemManager script, the Inventory script and the player id */ void Start() { NetworkingManager.Subscribe(ReceiveItemPickupPacket, DataType.Item, (int)ItemUpdate.Pickup); NetworkingManager.Subscribe(ReceiveItemDropPacket, DataType.Item, (int)ItemUpdate.Drop); NetworkingManager.Subscribe(ReceiveCreateWorldItemPacket, DataType.Item, (int)ItemUpdate.Create); NetworkingManager.Subscribe(ReceiveItemMagnetizePacket, DataType.Item, (int)ItemUpdate.Magnetize); _item_manager = GetComponent<ItemManager>(); _inventory = GameObject.Find("Inventory").GetComponent<Inventory>(); _my_player_id = GameData.MyPlayer.PlayerID; // Adding initial world items (testing) CreateWorldItem(101, 1, 1, 35, 25); // CreateWorldItem(102, 2, 1, 36, 30); // commented out because gold makes sound whenever created // CreateWorldItem(103, 2, 100, 30, 20); CreateWorldItem(1050, 4, 1, 67, 104); //CreateWorldItem(102, 3, 1, 67, 104); CreateWorldItem(104, 0, 1, 36, 20); audioSource = (AudioSource)gameObject.GetComponent<AudioSource>(); }
public void Initialize(Menu menu, ItemManager itemManager) { menu.AddMItem("Min duration in ms", new Slider(1000, 0, 3000), (sender, args) => _minDuration = args.GetNewValue<Slider>()); menu.AddMItem("1000 ms = 1 sec"); var typeMenu = menu.CreateSubmenu("Use on"); typeMenu.AddMItem("Blind", false, (sender, args) => _blind = args.GetNewValue<bool>()); typeMenu.AddMItem("Silence", false, (sender, args) => _silence = args.GetNewValue<bool>()); typeMenu.AddMItem("Stun", true, (sender, args) => _stun = args.GetNewValue<bool>()); typeMenu.AddMItem("Surpress", true, (sender, args) => _supress = args.GetNewValue<bool>()); typeMenu.AddMItem("Fear", true, (sender, args) => _fear = args.GetNewValue<bool>()); typeMenu.AddMItem("Snare", true, (sender, args) => _snare = args.GetNewValue<bool>()); typeMenu.AddMItem("Polymorph", true, (sender, args) => _polymorph = args.GetNewValue<bool>()); typeMenu.AddMItem("Charm", true, (sender, args) => _charm = args.GetNewValue<bool>()); typeMenu.AddMItem("Sleep", true, (sender, args) => _sleep = args.GetNewValue<bool>()); typeMenu.AddMItem("Taunt", true, (sender, args) => _taunt = args.GetNewValue<bool>()); var miscMenu = menu.CreateSubmenu("Misc"); miscMenu.AddMItem("Don't use on Alistar W (is a stun)", true, (sender, args) => _noAliW = args.GetNewValue<bool>()); miscMenu.AddMItem("Use on killable Ignite", true, (sender, args) => _ignite = args.GetNewValue<bool>()); miscMenu.AddMItem("Use on Exhaust", true, (sender, args) => _exhaust = args.GetNewValue<bool>()); }
// Asks the mighty RNG for an item private Item MightyRNG() { bool blueprint = rng.NextDouble() < blueprintProbability; List <string> selectFrom; int limit = 0; string itemName; Item item; int maxRetry = 20; do { selectFrom = null; item = null; if (blueprint) { var r = rng.Next(totalBlueprintWeight); for (var i = 0; i < 4; ++i) { limit += blueprintWeights[i]; if (r < limit) { selectFrom = blueprints[i]; break; } } } else { var r = rng.Next(totalItemWeight); for (var i = 0; i < 4; ++i) { limit += itemWeights[i]; if (r < limit) { selectFrom = items[i]; break; } } } if (selectFrom == null) { if (--maxRetry <= 0) { Error("Endless loop detected: ABORTING"); break; } Warn("Item list to select from is empty (trying another one)"); continue; } itemName = selectFrom[rng.Next(0, selectFrom.Count)]; item = ItemManager.CreateByName(itemName, 1); if (item == null) { Warn("Failed to create item: " + itemName + " (trying another one)"); continue; } if (item.info == null) { Warn("Item has no definition: " + itemName + " (trying another one)"); continue; } break; } while (true); if (item == null) { return(null); } if (blueprint) { item.isBlueprint = true; } else if (item.info.stackable > 1 && dropLimits.TryGetValue(item.info.shortname, out limit)) { item.amount = rng.Next(1, Math.Min(limit, item.info.stackable) + 1); } return(item); }
// Populates a container with loot private void PopulateContainer(LootContainer container) { if (container.inventory == null) { Warn("Container " + ContainerName(container) + " has no inventory (skipping)"); return; } int min = 1; int max = 0; bool refresh = false; if (container is SupplyDrop) { SuppressRefresh(container); var inv = container.inventory.itemList.ToArray(); foreach (var item in inv) { if (itemBlacklist.Contains(item.info.shortname)) { item.RemoveFromContainer(); item.Remove(0f); ++max; } } if (max == 0) { return; } } else if (barrelEx.IsMatch(container.gameObject.name)) { SuppressRefresh(container); ClearContainer(container); min = minItemsPerBarrel; max = maxItemsPerBarrel; } else if (crateEx.IsMatch(container.gameObject.name)) { SuppressRefresh(container); ClearContainer(container); min = minItemsPerCrate; max = maxItemsPerCrate; refresh = true; // In case someone puts trash in it } else { #if DEBUG Log("Container " + ContainerName(container) + " does not match any override"); #endif return; } var n = min + rng.Next(0, max - min + 1); var sb = new StringBuilder(); var items = new List <Item>(); bool hasAmmo = false; for (int i = 0; i < n; ++i) { var item = MightyRNG(); if (item == null) { Error("Failed to obtain item: Is the plugin initialized yet?"); return; } items.Add(item); if (sb.Length > 0) { sb.Append(", "); } if (item.amount > 1) { sb.Append(item.amount).Append("x "); } sb.Append(item.info.shortname); if (item.isBlueprint) { sb.Append(" (BP)"); } else if (dropWeaponsWithAmmo && !hasAmmo && items.Count < container.inventorySlots) // Drop some ammunition with first weapon { string ammo; int limit; if (weaponAmmunition.TryGetValue(item.info.shortname, out ammo) && dropLimits.TryGetValue(ammo, out limit)) { try { item = ItemManager.CreateByName(ammo, rng.Next(2, limit + 1)); items.Add(item); sb.Append(" + "); if (item.amount > 1) { sb.Append(item.amount).Append("x "); } sb.Append(item.info.shortname); hasAmmo = true; } catch (Exception) { Warn("Failed to obtain ammo item: " + ammo); } } } } #if DEBUG Log("Populating " + ContainerName(container) + " with " + sb.ToString()); #endif foreach (var item in items) { item.MoveToContainer(container.inventory, -1, false); } container.inventory.MarkDirty(); if (refresh) { refreshList.Add(new ContainerToRefresh() { container = container, time = DateTime.UtcNow.AddMinutes(refreshMinutes) }); } }
public IActionResult List() { var items = ItemManager.GetAll().Select(c => c.ToModel()).ToList(); return(View(items)); }
public Ship(ItemManager itemManager, Zone zone, EquippableItem hull, EntitySettings settings) : base(itemManager, zone, hull, settings) { ItemDestroyed.Where(item => _thrusterItems.Contains(item)).Subscribe(RemoveThruster); ItemDestroyed.Where(item => _aetherDriveItems.Contains(item)).Subscribe(RemoveAetherDrive); }
void Awake() { singleton = this; }
void cmdQLock(BasePlayer player, string command, string[] args) { if (args.Length == 0 || args.Length >= 5) { SendReplyHelp(player); return; } switch (args[0]) { case "friends": if (args.Length >= 2 || args.Length == 0) { SendReplyHelp(player); return; } if (quarryData.QD[player.userID].HasAccess.Count >= 1) { foreach (var friend in quarryData.QD[player.userID].HasAccess) { SendReply(player, string.Format(GetMessage("QL_FRIENDS", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], friend)); return; } } else { SendReply(player, string.Format(GetMessage("QL_NOFRIENDS", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); return; } break; case "blocked": if (args.Length >= 2 || args.Length == 0) { SendReplyHelp(player); return; } if (quarryData.QD[player.userID].PlayersBlocked.Count >= 1) { foreach (var block in quarryData.QD[player.userID].PlayersBlocked) { SendReply(player, string.Format(GetMessage("QL_ISBLOCKED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], block)); return; } } else { SendReply(player, string.Format(GetMessage("QL_NOBLOCKED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); return; } break; case "code": if (args.Length >= 2 || args.Length == 0) { SendReplyHelp(player); return; } if (quarryData.QD[player.userID].Code != 1111) { SendReply(player, string.Format(GetMessage("QL_CODE", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], quarryData.QD[player.userID].Code)); return; } else { SendReply(player, string.Format(GetMessage("QL_DCODE", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); return; } break; case "setcode": if (args.Length >= 3 || args.Length == 0 || args.Length == 1) { SendReplyHelp(player); return; } if (quarryData.QD[player.userID].CodeEnabled == false) { SendReply(player, string.Format(GetMessage("QL_CODENENABLED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); return; } if (quarryData.QD[player.userID].Code == Convert.ToInt32(args[1])) { SendReply(player, string.Format(GetMessage("QL_CANNOTSETTOCURRENT", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], args[1])); return; } if (args[1].Length >= 5) { SendReply(player, string.Format(GetMessage("QL_TOOMANYNUMBERS", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], args[1].Length, 4)); return; } var newCode = args[1]; quarryData.QD[player.userID].Code = Convert.ToInt32(newCode); quarryData.QD[player.userID].HasAccess.Clear(); SaveData(); SendReply(player, string.Format(GetMessage("QL_NEWPASSCODE", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], newCode)); break; case "entercode": if (args.Length >= 4 || args.Length == 0 || args.Length == 2 || args.Length == 1) { SendReplyHelp(player); return; } object addPlayer = FindPlayer(args[1]); BasePlayer target = (BasePlayer)addPlayer; if (quarryData.QD[target.userID].HasAccess.ContainsKey(player.userID)) { SendReply(player, string.Format(GetMessage("QL_ALREADYFRIEND", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], target.displayName)); return; } var targetCode = quarryData.QD[target.userID].Code.ToString(); var guessCode = args[2]; if (target == player || player == target) { Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.denied.prefab", player.transform.position); SendReply(player, string.Format(GetMessage("You may not enter your own code!", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); return; } if (quarryData.QD[target.userID].CodeEnabled) { if (guessCode == targetCode) { quarryData.QD[target.userID].HasAccess.Add(player.userID, player.displayName); SaveData(); SendReply(target, string.Format(GetMessage("QL_JUSTGUESSED", target.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], target.displayName)); SendReply(player, string.Format(GetMessage("QL_CORRECTCODE", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.updated.prefab", player.transform.position); Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.updated.prefab", target.transform.position); return; } else { SendReply(target, string.Format(GetMessage("QL_INCORRECTCODE", target.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); timer.Repeat(0.1f, Convert.ToInt32(Config["HealthWrong"]), () => player.health--); Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.denied.prefab", player.transform.position); foreach (var p in BasePlayer.activePlayerList) { try { if (target = p) { SendReply(target, string.Format(GetMessage("QL_GUESSED", target.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], player.displayName)); return; } else { return; } } catch { messageData.MD[target.userID].AttemptedAccess.Add(string.Format(GetMessage("GL_AAADD", target.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], player.displayName, DateTime.Now.ToString("h:mm tt"))); messageData.MD[target.userID].Messages++; return; } } } } else { SendReply(target, string.Format(GetMessage("QL_NOTENABLED", target.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], target.displayName)); return; } break; case "createcode": if (args.Length >= 2 || args.Length == 0) { SendReplyHelp(player); return; } if (quarryData.QD[player.userID].CodeEnabled) { SendReply(player, string.Format(GetMessage("QL_ISENABLED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); return; } else { int codelocks = player.inventory.GetAmount(-975723312); if (codelocks >= Convert.ToInt32(Config["CodeLocksNeeded"])) { player.inventory.Take(null, -975723312, Convert.ToInt32(Config["CodeLocksNeeded"])); SendReply(player, string.Format(GetMessage("QL_ENABLED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], Config["CodeLocksNeeded"].ToString())); quarryData.QD[player.userID].CodeEnabled = true; SaveData(); return; } else { SendReply(player, string.Format(GetMessage("QL_NOTENOUGHLOCKS", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], codelocks, Convert.ToInt32(Config["CodeLocksNeeded"]))); return; } } break; case "block": if (args.Length >= 3 || args.Length == 0 || args.Length == 1) { SendReplyHelp(player); return; } object newPlayer = FindPlayer(args[1]); BasePlayer blocker = (BasePlayer)newPlayer; if (blocker == player || player == blocker) { Effect.server.Run("assets/prefabs/locks/keypad/effects/lock.code.denied.prefab", player.transform.position); SendReply(player, string.Format(GetMessage("QL_CANNOTBLOCKSELF", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); return; } if (quarryData.QD[player.userID].PlayersBlocked.ContainsKey(player.userID)) { SendReply(player, string.Format(GetMessage("QL_ALREADYBLOCKED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], blocker.displayName)); return; } else { quarryData.QD[player.userID].PlayersBlocked.Add(player.userID, player.displayName); SendReply(player, string.Format(GetMessage("QL_BLOCKED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], blocker.displayName)); SaveData(); } break; case "rmessage": if (args.Length >= 2 || args.Length == 0) { SendReplyHelp(player); return; } SendReply(player, "<color='#66ff33'>Tried Access:</color>"); foreach (var m in messageData.MD[player.userID].AttemptedAccess) { SendReply(player, string.Format(GetMessage("QL_MESSAGE", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], m)); } SendReply(player, "<color='#66ff33'>Has Accessed:</color>"); foreach (var mm in messageData.MD[player.userID].HasAccessed) { SendReply(player, string.Format(GetMessage("QL_MESSAGE", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], mm)); } break; case "unblock": if (args.Length >= 3 || args.Length == 0 || args.Length == 1) { SendReplyHelp(player); return; } else { object removePlayer = FindPlayer(args[1]); BasePlayer unblock = (BasePlayer)removePlayer; if (quarryData.QD[player.userID].PlayersBlocked.ContainsKey(unblock.userID)) { SendReply(player, string.Format(GetMessage("QL_REMOVEDFROMBLOCKED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], unblock.displayName)); quarryData.QD[player.userID].PlayersBlocked.Remove(unblock.userID); SaveData(); } else { SendReply(player, string.Format(GetMessage("QL_NOTINBLOCKED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], args[1])); return; } } break; case "setmaxlogs": if (args.Length >= 3 || args.Length == 0 || args.Length == 1) { SendReplyHelp(player); return; } quarryData.QD[player.userID].MaxLogsAllowed = Convert.ToInt32(args[1]); SaveData(); SendReply(player, string.Format(GetMessage("QL_MAXLOGSET", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], args[1])); break; case "setmaxlogs(p)": if (args.Length >= 3 || args.Length == 0 || args.Length == 1) { SendReplyHelp(player); return; } quarryData.QD[player.userID].MaxLogsFromPlayer = Convert.ToInt32(args[1]); SaveData(); SendReply(player, string.Format(GetMessage("QL_MAXPLAYERLOGSET", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"], args[1])); break; case "disablecode": if (quarryData.QD[player.userID].CodeEnabled == false) { SendReply(player, string.Format(GetMessage("QL_CODENENABLED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); return; } else { SendReply(player, string.Format(GetMessage("QL_CODEDISABLED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); quarryData.QD[player.userID].CodeEnabled = false; SaveData(); player.inventory.GiveItem(ItemManager.CreateByName("lock.code", Convert.ToInt32(Config["CodeLocksNeeded"])), player.inventory.containerMain); return; } break; case "clearmessages": messageData.MD[player.userID].AttemptedAccess.Clear(); messageData.MD[player.userID].HasAccessed.Clear(); quarryData.QD[player.userID].LogsFromPlayer.Clear(); SendReply(player, string.Format(GetMessage("QL_MESSAGESCLEARED", player.UserIDString), Config["ChatPrefixColor"], Config["ChatPrefix"], Config["ChatColor"])); SaveData(); break; case "help": SendReplyHelp(player); return; break; case "help2": SendReplyHelp2(player); return; break; default: SendReplyHelp(player); return; break; } }
void IChainedCommandHandler <TypeCharCommandArgs> .ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); // When a character is typed it is *always* sent through to the editor. This way the // editor always represents what would have been typed had completion not been involved // at this point. That means that if we decide to commit, then undo'ing the commit will // return you to the code that you would have typed if completion was not up. // // The steps we follow for commit are as follows: // // 1) send the commit character through to the buffer. // 2) open a transaction. // 2a) roll back the text to before the text was sent through // 2b) commit the item. // 2c) send the commit character through again.* // 2d) commit the transaction. // // 2c is very important. it makes sure that post our commit all our normal features // run depending on what got typed. For example if the commit character was ( // then brace completion may run. If it was ; then formatting may run. But, importantly // this code doesn't need to know anything about that. Furthermore, because that code // runs within this transaction, then the user can always undo and get to what the code // would have been if completion was not involved. // // 2c*: note sending the commit character through to the buffer again can be controlled // by the completion item. For example, completion items that want to totally handle // what gets output into the buffer can ask for this not to happen. An example of this // is override completion. If the user types "override Method(" then we'll want to // spit out the entire method and *not* also spit out "(" again. // In order to support 2a (rolling back), we capture hte state of the buffer before // we send the character through. We then just apply the edits in reverse order to // roll us back. var initialTextSnapshot = this.SubjectBuffer.CurrentSnapshot; var initialCaretPosition = GetCaretPointInViewBuffer(); // Note: while we're doing this, we don't want to hear about buffer changes (since we // know they're going to happen). So we disconnect and reconnect to the event // afterwards. That way we can hear about changes to the buffer that don't happen // through us. // Automatic Brace Completion may also move the caret, so unsubscribe from that too this.TextView.TextBuffer.PostChanged -= OnTextViewBufferPostChanged; this.TextView.Caret.PositionChanged -= OnCaretPositionChanged; // In Venus/Razor, the user might be typing on the buffer's seam. This means that, // depending on the character typed, the character may not go into our buffer. var isOnSeam = IsOnSeam(); try { nextHandler(); } finally { this.TextView.TextBuffer.PostChanged += OnTextViewBufferPostChanged; this.TextView.Caret.PositionChanged += OnCaretPositionChanged; } var typedChar = args.TypedChar; // We only want to process typechar if it is a normal typechar and no one else is // involved. i.e. if there was a typechar, but someone processed it and moved the caret // somewhere else then we don't want completion. Also, if a character was typed but // something intercepted and placed different text into the editor, then we don't want // to proceed. if (this.TextView.TypeCharWasHandledStrangely(this.SubjectBuffer, typedChar)) { if (sessionOpt != null) { // If we're on a seam (razor) with a computation, and the user types a character // that goes into the other side of the seam, the character may be a commit character. // If it's a commit character, just commit without trying to check caret position, // since the caret is no longer in our buffer. if (isOnSeam) { var model = this.WaitForModel(); if (this.CommitIfCommitCharacter(typedChar, model, initialTextSnapshot, nextHandler)) { return; } } if (_autoBraceCompletionChars.Contains(typedChar) && this.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.AutomaticPairCompletion)) { var model = this.WaitForModel(); if (this.CommitIfCommitCharacter(typedChar, model, initialTextSnapshot, nextHandler)) { // I don't think there is any better way than this. if typed char is one of auto brace completion char, // we don't do multiple buffer change check return; } } // If we were computing anything, we stop. We only want to process a typechar // if it was a normal character. this.DismissSessionIfActive(); } return; } var completionService = this.GetCompletionService(); if (completionService == null) { return; } var options = GetOptions(); Contract.ThrowIfNull(options); var isTextuallyTriggered = IsTextualTriggerCharacter(completionService, typedChar, options); var isPotentialFilterCharacter = ItemManager.IsPotentialFilterCharacter(typedChar); var trigger = CompletionTrigger.CreateInsertionTrigger(typedChar); if (sessionOpt == null) { // No computation at all. If this is not a trigger character, we just ignore it and // stay in this state. Otherwise, if it's a trigger character, start up a new // computation and start computing the model in the background. if (isTextuallyTriggered) { // First create the session that represents that we now have a potential // completion list. Then tell it to start computing. StartNewModelComputation(completionService, trigger); return; } else { // No need to do anything. Just stay in the state where we have no session. return; } } else { sessionOpt.UpdateModelTrackingSpan(initialCaretPosition); // If the session is up, it may be in one of many states. It may know nothing // (because it is currently computing the list of completions). Or it may have a // list of completions that it has filtered. // If the user types something which is absolutely known to be a filter character // then we can just proceed without blocking. if (isPotentialFilterCharacter) { if (isTextuallyTriggered) { // The character typed was something like "a". It can both filter a list if // we have computed one, or it can trigger a new list. Ask the computation // to compute again. If nothing has been computed, then it will try to // compute again, otherwise it will just ignore this request. sessionOpt.ComputeModel(completionService, trigger, _roles, options); } // Now filter whatever result we have. sessionOpt.FilterModel(CompletionFilterReason.Insertion, filterState: null); } else { // It wasn't a trigger or filter character. At this point, we make our // determination on what to do based on what has actually been computed and // what's being typed. This means waiting on the session and will effectively // block the user. var model = WaitForModel(); // What they type may end up filtering, committing, or else will dismiss. // // For example, we may filter in cases like this: "Color." // // "Color" will have already filtered the list down to some things like // "Color", "Color.Red", "Color.Blue", etc. When we process the 'dot', we // actually want to filter some more. But we can't know that ahead of time until // we have computed the list of completions. if (this.IsFilterCharacter(typedChar, model)) { // Known to be a filter character for the currently selected item. So just // filter the session. sessionOpt.FilterModel(CompletionFilterReason.Insertion, filterState: null); return; } // It wasn't a filter character. We'll either commit what's selected, or we'll // dismiss the completion list. First, ensure that what was typed is in the // buffer. // Now, commit if it was a commit character. this.CommitIfCommitCharacter(typedChar, model, initialTextSnapshot, nextHandler); // At this point we don't want a session anymore (either because we committed, or // because we got a character we don't know how to handle). Unilaterally dismiss // the session. DismissSessionIfActive(); // The character may commit/dismiss and then trigger completion again. So check // for that here. if (isTextuallyTriggered) { StartNewModelComputation( completionService, trigger); return; } } } }
//Constructor. public ContainView(string name, ItemManager im, Point startPoint, UserSettings u) { InitializeComponent(); this.MaximumSize = this.Size; this.MinimumSize = this.Size; this.Icon = Resources.Gnome_child_chathead; this.u = u; this.DoubleBuffered = true; this.filledVal = name; StartPosition = FormStartPosition.Manual; Location = startPoint; this.im = im; valueItems = im.itemGroups[im.getValueByName(name)]; deleteOne = new MenuItem("Drop one of item"); deleteAll = new MenuItem("Drop items"); editValue = new MenuItem("Edit amount"); deleteAll.Click += deleteAll_Click; deleteOne.Click += removeNumber; editValue.Click += editValue_Click; cm.MenuItems.Add(editValue); cm.MenuItems.Add(deleteOne); cm.MenuItems.Add(deleteAll); FontManager.setFont(14F); textfont = FontManager.customFont; TitleLabel.Font = new Font(textfont.FontFamily, 18F); TitleLabel.Text = name; itemslabel.Font = textfont; itemslabel.Text = "Select a set:"; TipLabel.Font = new Font(textfont.FontFamily, 12F); itemComboBox.Font = new Font(textfont.FontFamily, 12F); returnBT.Font = textfont; foreach (ItemContainer valueItem in valueItems) { string catName = valueItem.CategoryName; catName = catName.Replace("_", " "); if (catName == "Vetion") { catName = "Vet'ion"; } itemComboBox.Items.Add(catName); //valueItem.items; } if (name != "Pets" && name != "Achievement Diaries" && name != "Treasure Trials") { itemComboBox.Sorted = true; } else { itemComboBox.Sorted = false; } if (name == "Capes" && u.useUserName) { setskillCapeValues(im); } if (name == "Achievement Diaries") { TipLabel.Text = "Tip: Use higher tier diaries to tick off lower ones!"; } else { TipLabel.Text = string.Empty; } itemComboBox.SelectedValueChanged += itemComboBox_SelectedValueChanged; }
void LoadAllContainers() { try { lootTable = getFile("LootTables"); } catch (JsonReaderException e) { PrintWarning($"JSON error in 'LootTables' > Line: {e.LineNumber} | {e.Path}"); Interface.GetMod().UnloadPlugin(this.Title); return; } lootTables = new Dictionary <string, object>(); lootTables = lootTable["LootTables"] as Dictionary <string, object>; if (lootTables == null) { lootTables = new Dictionary <string, object>(); } bool wasAdded = false; foreach (var lootPrefab in lootPrefabsToUse) { if (!lootTables.ContainsKey((string)lootPrefab)) { var loot = GameManager.server.FindPrefab((string)lootPrefab)?.GetComponent <LootContainer>(); if (loot == null) { continue; } var container = new Dictionary <string, object>(); container.Add("Enabled", ((((string)lootPrefab).Contains("bradley_crate")) || (((string)lootPrefab).Contains("heli_crate"))) ? false : true); container.Add("Scrap", loot.scrapAmount); int slots = 0; if (loot.LootSpawnSlots.Length > 0) { LootContainer.LootSpawnSlot[] lootSpawnSlots = loot.LootSpawnSlots; for (int i = 0; i < lootSpawnSlots.Length; i++) { slots += lootSpawnSlots[i].numberToSpawn; } } else { slots = loot.maxDefinitionsToSpawn; } container.Add("ItemsMin", slots); container.Add("ItemsMax", slots); container.Add("MaxBPs", 1); var itemList = new Dictionary <string, object>(); if (loot.lootDefinition != null) { GetLootSpawn(loot.lootDefinition, ref itemList); } else if (loot.LootSpawnSlots.Length > 0) { LootContainer.LootSpawnSlot[] lootSpawnSlots = loot.LootSpawnSlots; for (int i = 0; i < lootSpawnSlots.Length; i++) { LootContainer.LootSpawnSlot lootSpawnSlot = lootSpawnSlots[i]; GetLootSpawn(lootSpawnSlot.definition, ref itemList); } } container.Add("ItemList", itemList); lootTables.Add((string)lootPrefab, container); wasAdded = true; } } if (wasAdded) { lootTable.Set("LootTables", lootTables); lootTable.Save(); } wasAdded = false; bool wasRemoved = false; int activeTypes = 0; foreach (var lootTable in lootTables.ToList()) { var loot = GameManager.server.FindPrefab(lootTable.Key)?.GetComponent <LootContainer>(); if (loot == null) { lootTables.Remove(lootTable.Key); wasRemoved = true; continue; } var container = lootTable.Value as Dictionary <string, object>; if (!container.ContainsKey("Enabled")) { container.Add("Enabled", true); wasAdded = true; } if ((bool)container["Enabled"]) { activeTypes++; } if (!container.ContainsKey("Scrap")) { container.Add("Scrap", loot.scrapAmount); wasAdded = true; } int slots = 0; if (loot.LootSpawnSlots.Length > 0) { LootContainer.LootSpawnSlot[] lootSpawnSlots = loot.LootSpawnSlots; for (int i = 0; i < lootSpawnSlots.Length; i++) { slots += lootSpawnSlots[i].numberToSpawn; } } else { slots = loot.maxDefinitionsToSpawn; } if (!container.ContainsKey("MaxBPs")) { container.Add("MaxBPs", 1); wasAdded = true; } if (!container.ContainsKey("ItemsMin")) { container.Add("ItemsMin", slots); wasAdded = true; } if (!container.ContainsKey("ItemsMax")) { container.Add("ItemsMax", slots); wasAdded = true; } if (!container.ContainsKey("ItemsMax")) { container.Add("ItemsMax", slots); wasAdded = true; } if (!container.ContainsKey("ItemList")) { var itemList = new Dictionary <string, object>(); if (loot.lootDefinition != null) { GetLootSpawn(loot.lootDefinition, ref itemList); } else if (loot.LootSpawnSlots.Length > 0) { LootContainer.LootSpawnSlot[] lootSpawnSlots = loot.LootSpawnSlots; for (int i = 0; i < lootSpawnSlots.Length; i++) { LootContainer.LootSpawnSlot lootSpawnSlot = lootSpawnSlots[i]; GetLootSpawn(lootSpawnSlot.definition, ref itemList); } } container.Add("ItemList", itemList); wasAdded = true; } Items.Add(lootTable.Key, new List <string> [5]); Blueprints.Add(lootTable.Key, new List <string> [5]); for (var i = 0; i < 5; ++i) { Items[lootTable.Key][i] = new List <string>(); Blueprints[lootTable.Key][i] = new List <string>(); } foreach (var itemEntry in container["ItemList"] as Dictionary <string, object> ) { bool isBP = itemEntry.Key.EndsWith(".blueprint") ? true : false; var def = ItemManager.FindItemDefinition(itemEntry.Key.Replace(".blueprint", "")); if (def != null) { if (isBP && def.Blueprint != null && def.Blueprint.isResearchable) { int index = (int)def.rarity; if (!Blueprints[lootTable.Key][index].Contains(def.shortname)) { Blueprints[lootTable.Key][index].Add(def.shortname); } } else { int index = 0; object indexoverride; if (rarityItemOverride.TryGetValue(def.shortname, out indexoverride)) { index = Convert.ToInt32(indexoverride); } else { index = (int)def.rarity; } if (!Items[lootTable.Key][index].Contains(def.shortname)) { Items[lootTable.Key][index].Add(def.shortname); } } } } totalItemWeight.Add(lootTable.Key, 0); totalBlueprintWeight.Add(lootTable.Key, 0); itemWeights.Add(lootTable.Key, new int[5]); blueprintWeights.Add(lootTable.Key, new int[5]); for (var i = 0; i < 5; ++i) { totalItemWeight[lootTable.Key] += (itemWeights[lootTable.Key][i] = ItemWeight(baseItemRarity, i) * Items[lootTable.Key][i].Count); totalBlueprintWeight[lootTable.Key] += (blueprintWeights[lootTable.Key][i] = ItemWeight(baseItemRarity, i) * Blueprints[lootTable.Key][i].Count); } } if (wasAdded || wasRemoved) { lootTable.Set("LootTables", lootTables); lootTable.Save(); } lootTable.Clear(); Puts($"Using '{activeTypes}' active of '{lootTables.Count}' supported containertypes"); }
private void Awake() { _self = this; }
public void Initialize(Menu menu, ItemManager itemManager) { menu.AddMItem("After attack", true, (sender, args) => _afterAttack = args.GetNewValue <bool>()); menu.ProcStoredValueChanged <bool>(); Orbwalking.AfterAttack += (sender, args) => _justAttacked = true; }
public override void Initialize() { HandleCommandLine(Environment.GetCommandLineArgs()); if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } #if DEBUG Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All, false); #else Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All & ~LogLevel.Debug, false); #endif AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; try { if (File.Exists(Path.Combine(SavePath, "tshock.pid"))) { Log.ConsoleInfo("TShock was improperly shut down. Please avoid this in the future, world corruption may result from this."); File.Delete(Path.Combine(SavePath, "tshock.pid")); } File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString()); ConfigFile.ConfigRead += OnConfigRead; FileTools.SetupConfig(); HandleCommandLine_Port(Environment.GetCommandLineArgs()); if (Config.StorageType.ToLower() == "sqlite") { string sql = Path.Combine(SavePath, "tshock.sqlite"); DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql)); } else if (Config.StorageType.ToLower() == "mysql") { try { var hostport = Config.MySqlHost.Split(':'); DB = new MySqlConnection(); DB.ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", hostport[0], hostport.Length > 1 ? hostport[1] : "3306", Config.MySqlDbName, Config.MySqlUsername, Config.MySqlPassword ); } catch (MySqlException ex) { Log.Error(ex.ToString()); throw new Exception("MySql not setup correctly"); } } else { throw new Exception("Invalid storage type"); } Backups = new BackupManager(Path.Combine(SavePath, "backups")); Backups.KeepFor = Config.BackupKeepFor; Backups.Interval = Config.BackupInterval; Bans = new BanManager(DB); Warps = new WarpManager(DB); Users = new UserManager(DB); Groups = new GroupManager(DB); Groups.LoadPermisions(); Regions = new RegionManager(DB); Itembans = new ItemManager(DB); RememberedPos = new RemeberedPosManager(DB); InventoryDB = new InventoryManager(DB); RestApi = new SecureRest(Netplay.serverListenIP, 8080); RestApi.Verify += RestApi_Verify; RestApi.Port = Config.RestApiPort; RestManager = new RestManager(RestApi); RestManager.RegisterRestfulCommands(); var geoippath = Path.Combine(SavePath, "GeoIP.dat"); if (Config.EnableGeoIP && File.Exists(geoippath)) { Geo = new MaxMind.GeoIPCountry(geoippath); } Log.ConsoleInfo(string.Format("TerrariaShock Version {0} ({1}) now running.", Version, VersionCodename)); GameHooks.PostInitialize += OnPostInit; GameHooks.Update += OnUpdate; ServerHooks.Join += OnJoin; ServerHooks.Leave += OnLeave; ServerHooks.Chat += OnChat; ServerHooks.Command += ServerHooks_OnCommand; NetHooks.GetData += OnGetData; NetHooks.SendData += NetHooks_SendData; NetHooks.GreetPlayer += OnGreetPlayer; NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc; ProjectileHooks.SetDefaults += OnProjectileSetDefaults; WorldHooks.StartHardMode += OnStartHardMode; GetDataHandlers.InitGetDataHandler(); Commands.InitCommands(); //RconHandler.StartThread(); if (Config.BufferPackets) { PacketBuffer = new PacketBufferer(); } Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled")); Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled")); if (Initialized != null) { Initialized(); } } catch (Exception ex) { Log.Error("Fatal Startup Exception"); Log.Error(ex.ToString()); Environment.Exit(1); } }
bool PopulateContainer(LootContainer container) { Dictionary <string, object> con; object containerobj; int lootitemcount; if (!lootTables.TryGetValue(container.PrefabName, out containerobj)) { return(false); } con = containerobj as Dictionary <string, object>; if (!(bool)con["Enabled"]) { return(false); } lootitemcount = (int)(con["ItemList"] as Dictionary <string, object>).Count(); int itemCount = Mathf.RoundToInt(UnityEngine.Random.Range(Convert.ToSingle(Mathf.Min((int)con["ItemsMin"], (int)con["ItemsMax"])) * 100f, Convert.ToSingle(Mathf.Max((int)con["ItemsMin"], (int)con["ItemsMax"])) * 100f) / 100f); if (lootitemcount > 0 && itemCount > lootitemcount && lootitemcount < 36) { itemCount = lootitemcount; } if (container.inventory == null) { container.inventory = new ItemContainer(); container.inventory.ServerInitialize(null, 36); container.inventory.GiveUID(); } else { while (container.inventory.itemList.Count > 0) { var item = container.inventory.itemList[0]; item.RemoveFromContainer(); item.Remove(0f); } container.inventory.capacity = 36; } var items = new List <Item>(); var itemNames = new List <string>(); var itemBlueprints = new List <int>(); var maxRetry = 10; for (int i = 0; i < itemCount; ++i) { if (maxRetry == 0) { break; } var item = MightyRNG(container.PrefabName, itemCount, (bool)(itemBlueprints.Count >= (int)con["MaxBPs"])); if (item == null) { --maxRetry; --i; continue; } if (itemNames.Contains(item.info.shortname) || (item.IsBlueprint() && itemBlueprints.Contains(item.blueprintTarget))) { item.Remove(0f); --maxRetry; --i; continue; } else if (item.IsBlueprint()) { itemBlueprints.Add(item.blueprintTarget); } else { itemNames.Add(item.info.shortname); } items.Add(item); } foreach (var item in items.Where(x => x != null && x.IsValid())) { item.MoveToContainer(container.inventory, -1, false); } if ((int)con["Scrap"] > 0) { int scrapCount = (int)con["Scrap"]; Item item = ItemManager.Create(ItemManager.FindItemDefinition("scrap"), scrapCount, 0uL); item.MoveToContainer(container.inventory, -1, false); } container.inventory.capacity = container.inventory.itemList.Count; container.inventory.MarkDirty(); container.SendNetworkUpdate(); populatedContainers++; return(true); }
private void Start() { GetComponent <SpriteRenderer>().sprite = ItemManager.GetInstance().GetIcon(state.ItemId); }
// Updates the internal probability matrix and optionally logs the result private void UpdateInternals(bool doLog) { Log("Updating internals ..."); originalItems = new List <ItemDefinition>(ItemManager.Instance.itemList); originalBlueprints = new List <ItemBlueprint>(ItemManager.Instance.bpList); if (originalItems.Count < 20 || originalBlueprints.Count < 10) { Error("Resources did not contain a sane amount of items and/or blueprints: " + originalItems.Count + " / " + originalBlueprints.Count); return; } if (doLog) { Log("There are " + originalItems.Count + " items and " + originalBlueprints.Count + " blueprints in the game."); } for (var i = 0; i < 4; ++i) { items[i] = new List <string>(); blueprints[i] = new List <string>(); } totalItems = 0; totalBlueprints = 0; var allItems = ItemManager.GetItemDefinitions(); if (allItems == null || allItems.Count < 20) { Error("ItemManager did not return a sane amount of items. Is the game broken?"); return; } var notExistingItems = 0; var notExistingBlueprints = 0; var itemsWithNoRarity = 0; foreach (var item in allItems) { if (doesNotDrop.Contains(item.shortname)) { continue; } int index = RarityIndex(item.rarity); if (index >= 0) { if (ItemExists(item.shortname)) { if (!itemBlacklist.Contains(item.shortname)) { items[index].Add(item.shortname); ++totalItems; } } else { ++notExistingItems; } if (BlueprintExists(item.shortname)) { if (!blueprintBlacklist.Contains(item.shortname)) { blueprints[index].Add(item.shortname); ++totalBlueprints; } } else { ++notExistingBlueprints; } } else { ++itemsWithNoRarity; } } if (totalItems < 20 || totalBlueprints < 10) { Error("Failed to categorize items: " + notExistingItems + " items and " + notExistingBlueprints + " blueprints did not exist and " + itemsWithNoRarity + " items had no rarity"); if (itemsWithNoRarity > 10) { Error("THIS IS MOST LIKELY CAUSED BY A MISCONFIGURED (OR BROKEN) PLUGIN THAT MODIFIES ITEMS!"); } else { Error("PLEASE REPORT THIS ON THE DEDICATED DISCUSSION THREAD! http://oxidemod.org/threads/betterloot.7063"); } return; } if (doLog) { Log("We are going to use " + totalItems + " items and " + totalBlueprints + " blueprints of them."); } totalItemWeight = 0; totalBlueprintWeight = 0; for (var i = 0; i < 4; ++i) { totalItemWeight += (itemWeights[i] = ItemWeight(baseItemRarity, i) * items[i].Count); totalBlueprintWeight += (blueprintWeights[i] = ItemWeight(baseBlueprintRarity, i) * blueprints[i].Count); } if (doLog) { Log(string.Format("Base item rarity is {0} and base blueprint rarity is {1}.", baseItemRarity, baseBlueprintRarity)); Log(string.Format("With a {0:0.0}% chance that any drop is a blueprint we get:", 100 * blueprintProbability)); double total = 0; for (var i = 0; i < 4; ++i) { double prob = (1 - blueprintProbability) * 100d * itemWeights[i] / totalItemWeight; Log(string.Format("There is a {0:0.000}% chance to get one of {1} " + RarityName(i) + " items (w={2}, {3}/{4}).", prob, items[i].Count, ItemWeight(baseItemRarity, i), itemWeights[i], totalItemWeight)); total += prob; } for (var i = 0; i < 4; ++i) { double prob = blueprintProbability * 100d * blueprintWeights[i] / totalBlueprintWeight; Log(string.Format("There is a {0:0.000}% chance to get one of {1} " + RarityName(i) + " blueprints (w={2}, {3}/{4}).", prob, blueprints[i].Count, ItemWeight(baseBlueprintRarity, i), blueprintWeights[i], totalBlueprintWeight)); total += prob; } // Log("Total chance: " + total + "% == 100%"); } // Update containers accordingly var containers = UnityEngine.Object.FindObjectsOfType <LootContainer>(); foreach (var container in containers) { try { PopulateContainer(container); } catch (Exception ex) { Warn("Failed to populate container " + ContainerName(container) + ": " + ex.Message + "\n" + ex.StackTrace); } } initialized = true; Log("Internals have been updated"); }
public AdminForm() { InitializeComponent(); userManager = new UserManager(); itemManager = new ItemManager(); }
public Item Duplicate(ClientPipelineArgs args) { Item result = null; Assert.ArgumentNotNull(args, "args"); var database = Factory.GetDatabase(args.Parameters["database"]); Assert.IsNotNull(database, args.Parameters["database"]); var itemId = args.Parameters["id"]; var sourceItem = database.Items[itemId]; if (sourceItem == null) { SheerResponse.Alert(Translate.Text("Item not found.")); } else { Item parent = sourceItem.Parent; if (parent == null) { SheerResponse.Alert(Translate.Text("Cannot duplicate the root item.")); } else if (parent.Access.CanCreate()) { Log.Audit(this, "Duplicate item: {0}", new string[1] { AuditFormatter.FormatItem(sourceItem) }); var bucketItemOrSiteRoot = ItemExtensions.GetParentBucketItemOrSiteRoot(sourceItem); if (BucketManager.IsBucket(bucketItemOrSiteRoot) && BucketManager.IsBucketable(sourceItem)) { if (!EventDisabler.IsActive) { EventResult eventResult = Event.RaiseEvent("item:bucketing:duplicating", args, this); if (eventResult != null && eventResult.Cancel) { Log.Info(string.Format("Event {0} was cancelled", "item:bucketing:duplicating"), this); args.AbortPipeline(); return(null); } } result = Context.Workflow.DuplicateItem(sourceItem, args.Parameters["name"]); Item destination = CreateAndReturnBucketFolderDestination(bucketItemOrSiteRoot, DateUtil.ToUniversalTime(DateTime.Now), sourceItem); if (!IsBucketTemplateCheck(sourceItem)) { destination = bucketItemOrSiteRoot; } ItemManager.MoveItem(result, destination); if (!EventDisabler.IsActive) { Event.RaiseEvent("item:bucketing:duplicated", args, this); } } else { result = Context.Workflow.DuplicateItem(sourceItem, args.Parameters["name"]); } } else { SheerResponse.Alert(Translate.Text("You do not have permission to duplicate \"{0}\".", sourceItem.DisplayName)); } } args.AbortPipeline(); return(result); }
private static void MakeHelperLists() { { randomizedLocations = ItemManager.GetRandomizedLocations(); obtainedLocations = new HashSet <string>(RandomizerMod.Instance.Settings.GetLocationsFound()); uncheckedLocations = new HashSet <string>(); pm = new ProgressionManager(RandomizerState.HelperLog); if (RandomizerMod.Instance.Settings.RandomizeRooms) { pm.Add(LogicManager.GetStartLocation(RandomizerMod.Instance.Settings.StartName).roomTransition); } else { pm.Add(LogicManager.GetStartLocation(RandomizerMod.Instance.Settings.StartName).waypoint); if (RandomizerMod.Instance.Settings.RandomizeAreas) { pm.Add(LogicManager.GetStartLocation(RandomizerMod.Instance.Settings.StartName).areaTransition); } } foreach (string item in RandomizerMod.Instance.Settings.GetItemsFound()) { if (LogicManager.GetItemDef(item).progression) { pm.Add(LogicManager.RemoveDuplicateSuffix(item)); } } if (RandomizerMod.Instance.Settings.RandomizeTransitions) { obtainedTransitions = new HashSet <string>(); uncheckedTransitions = new HashSet <string>(); randomizedTransitions = new HashSet <string>(LogicManager.TransitionNames()); foreach (string transition in RandomizerMod.Instance.Settings.GetTransitionsFound()) { obtainedTransitions.Add(transition); pm.Add(transition); } } } foreach (string location in randomizedLocations) { string altLocation = location; // clumsy way to be able to switch out items without spoiling their costs if (obtainedLocations.Contains(location)) { continue; } if (!LogicManager.ShopNames.Contains(location)) { if (LogicManager.GetItemDef(location).costType == Actions.AddYNDialogueToShiny.CostType.Essence) { altLocation = "Seer"; } else if (LogicManager.GetItemDef(location).costType == Actions.AddYNDialogueToShiny.CostType.Grub) { altLocation = "Grubfather"; } } if (pm.CanGet(altLocation)) { uncheckedLocations.Add(altLocation); } } if (!RandomizerMod.Instance.Settings.RandomizeTransitions) { return; } foreach (string transition in randomizedTransitions) { if (obtainedTransitions.Contains(transition)) { continue; } if (pm.Has(transition)) { obtainedTransitions.Add(transition); } else if (pm.CanGet(transition)) { uncheckedTransitions.Add(transition); } } }
public override void UpdateMachine(SegmentEntity targetEntity) { FreightCartStation station = targetEntity as FreightCartStation; //Catch for when the window is called on an inappropriate machine if (station == null) { GenericMachinePanelScript.instance.Hide(); UIManager.RemoveUIRules("Machine"); return; } GenericMachinePanelScript.instance.Scroll_Bar.GetComponent <UIScrollBar>().scrollValue -= Input.GetAxis("Mouse ScrollWheel"); if (networkredraw) { this.manager.RedrawWindow(); } if (!dirty) { return; } if (!SetFreightItems && !ItemSearchWindow && !SetNetworkID && !SetName && !SetInventoryName && !string.IsNullOrEmpty(station.NetworkID)) { this.manager.UpdateLabel("assignedcarts", "Assigned Carts: " + station.AssignedCarts.ToString(), Color.white); this.manager.UpdateLabel("loadstatus", "Wait for " + (station.mbWaitForFullLoad ? "Full" : "Any"), Color.white); this.manager.UpdateLabel("offerlabel", (station.OfferAll ? "Offer All" : "Use Offer List"), Color.white); this.manager.UpdateLabel("carttier", "Cart Tier: " + station.CartTierLabel(), Color.white); } else if (SetFreightItems && !ItemSearchWindow && !SetNetworkID && !SetName && !SetInventoryName && station.NetworkID != null) { if (station.massStorageCrate != null) { List <FreightRegistry> registries = new List <FreightRegistry>(); registries = FreightCartManager.instance.GetFreightEntries(station.NetworkID, station.massStorageCrate); for (int index = 0; index < registries.Count; index++) { ItemBase item = registries[index].FreightItem; int lowstock = registries[index].LowStock; int highstock = registries[index].HighStock; string itemname = ItemManager.GetItemName(item); string iconname = ItemManager.GetItemIcon(item); this.manager.UpdateIcon("registry" + index, iconname, Color.white); this.manager.UpdateLabel("registrytitle" + index, itemname, Color.white); this.manager.UpdateLabel("lowstock" + index, registries[index].LowStock.ToString(), this.ChooseLowStock == true ? Color.white : Color.gray); this.manager.UpdateLabel("highstock" + index, registries[index].HighStock.ToString(), this.ChooseLowStock == false ? Color.white : Color.gray); this.manager.UpdateLabel("lowstocktitle" + index, "Request if below", this.ChooseLowStock == true ? Color.white : Color.gray); this.manager.UpdateLabel("highstocktitle" + index, "Offer if above", this.ChooseLowStock == false ? Color.white : Color.gray); } } else if (station.HopperInterface != null) { ItemBase item = station.HopperInterface.OfferItem; string itemname; string iconname; if (item != null) { itemname = ItemManager.GetItemName(item); iconname = ItemManager.GetItemIcon(item); this.manager.UpdateIcon("hopitemoffer", iconname, Color.white); this.manager.UpdateLabel("registrytitle0", itemname, Color.white); } this.manager.UpdateLabel("highstock", station.HopperInterface.OfferLimit.ToString(), Color.white); item = station.HopperInterface.RequestItem; if (item != null) { itemname = ItemManager.GetItemName(item); iconname = ItemManager.GetItemIcon(item); this.manager.UpdateIcon("hopitemrequest", iconname, Color.white); this.manager.UpdateLabel("registrytitle1", itemname, Color.white); } this.manager.UpdateLabel("lowstock", station.HopperInterface.RequestLimit.ToString(), Color.white); } else { this.manager.UpdateLabel("registrytitle-1", "Connect to Freight provider", Color.red); return; } } else if (ItemSearchWindow) { if (this.SearchResults == null) { this.Counter++; foreach (char c in Input.inputString) { if (c == "\b"[0]) //Backspace { if (this.EntryString.Length != 0) { this.EntryString = this.EntryString.Substring(0, this.EntryString.Length - 1); } } else if (c == "\n"[0] || c == "\r"[0]) //Enter or Return { this.SearchResults = new List <ItemBase>(); for (int n = 0; n < ItemEntry.mEntries.Length; n++) { if (ItemEntry.mEntries[n] == null) { continue; } if (ItemEntry.mEntries[n].Name.ToLower().Contains(this.EntryString.ToLower())) { this.SearchResults.Add(ItemManager.SpawnItem(ItemEntry.mEntries[n].ItemID)); } } for (int n = 0; n < TerrainData.mEntries.Length; n++) { bool foundvalue = false; TerrainDataEntry entry = TerrainData.mEntries[n]; if (entry == null) { continue; } if (entry.Name.ToLower().Contains(this.EntryString.ToLower())) { int count = entry.Values.Count; for (int m = 0; m < count; m++) { if (entry.Values[m].Name.ToLower().Contains(this.EntryString.ToLower())) { if (string.IsNullOrEmpty(entry.PickReplacement)) { this.SearchResults.Add(ItemManager.SpawnCubeStack(entry.CubeType, entry.Values[m].Value, 1)); foundvalue = true; } } } if (!foundvalue && string.IsNullOrEmpty(entry.PickReplacement)) { this.SearchResults.Add(ItemManager.SpawnCubeStack(entry.CubeType, entry.DefaultValue, 1)); } } if ((this.EntryString.ToLower().Contains("component") || this.EntryString.ToLower().Contains("placement") || this.EntryString.ToLower().Contains("multi")) && entry.CubeType == 600) { int count = entry.Values.Count; for (int m = 0; m < count; m++) { this.SearchResults.Add(ItemManager.SpawnCubeStack(600, entry.Values[m].Value, 1)); } } } if (this.SearchResults.Count == 0) { this.SearchResults = null; } UIManager.mbEditingTextField = false; UIManager.RemoveUIRules("TextEntry"); this.manager.RedrawWindow(); return; } else { this.EntryString += c; } } this.manager.UpdateLabel("searchtext", this.EntryString + (this.Counter % 20 > 10 ? "_" : ""), Color.cyan); dirty = true; return; } else { this.manager.UpdateLabel("searchtitle", "Searching for:", Color.white); this.manager.UpdateLabel("searchtext", this.EntryString, Color.cyan); int count = this.SearchResults.Count; for (int n = 0; n < count; n++) { ItemBase item = this.SearchResults[n]; string itemname = ItemManager.GetItemName(item); string iconname = ItemManager.GetItemIcon(item); this.manager.UpdateIcon("itemicon" + n, iconname, Color.white); this.manager.UpdateLabel("iteminfo" + n, itemname, Color.white); } } } else if (SetNetworkID || string.IsNullOrEmpty(station.NetworkID) || SetName || SetInventoryName) { this.Counter++; foreach (char c in Input.inputString) { if (c == "\b"[0]) //Backspace { if (this.EntryString.Length != 0) { this.EntryString = this.EntryString.Substring(0, this.EntryString.Length - 1); } } else if (c == "\n"[0] || c == "\r"[0]) //Enter or Return { if (SetName) { FreightCartWindow.SetStationName(station, this.EntryString); this.SetName = false; } else if (SetInventoryName) { FreightCartWindow.NameInventory(station, this.EntryString); this.SetInventoryName = false; } else { FreightCartWindow.SetNetwork(station, this.EntryString); this.SetNetworkID = false; } this.EntryString = ""; UIManager.mbEditingTextField = false; UIManager.RemoveUIRules("TextEntry"); return; } else { this.EntryString += c; } } this.manager.UpdateLabel("networkentry", this.EntryString + (this.Counter % 20 > 10 ? "_" : ""), Color.cyan); dirty = true; return; } dirty = false; }
public override string getTitle() { return(ItemManager.CanPlayerSetThingsOnFire() ? "Set on fire" : base.title); }
public void Setup(IUserInterface userInterface, ItemManager itemManager, PlayerStatus playerStatus) { this.userInterface = userInterface; this.itemManager = itemManager; this.playerStatus = playerStatus; }
public static Item GetItem(ID itemId, Database database) { return(ItemManager.GetItem(itemId, Language.Current, Version.Latest, database, SecurityCheck.Disable)); }
private object OnRecycleItem(Recycler recycler, Item item) { if (!ingredientList.ContainsKey(item.info.shortname) || blacklistedItems.Contains(item.info.shortname)) { item.Drop(recycler.transform.TransformPoint(new Vector3(-0.3f, 1.7f, 1f)), Vector3.up, new Quaternion()); return(false); } bool flag = false; int usedItems = 1; if (item.amount > 1) { usedItems = item.amount; } if (usedItems > maxItemsPerRecycle) { usedItems = maxItemsPerRecycle; } item.UseItem(usedItems); foreach (ItemInfo ingredient in ingredientList[item.info.shortname]) { double multi = 1; if (multiplyList.ContainsKey("*")) { multi = Convert.ToDouble(multiplyList["*"]); } if (multiplyList.ContainsKey(ingredient.itemName)) { multi = Convert.ToDouble(multiplyList[ingredient.itemName]); } int outputamount = Convert.ToInt32(usedItems * Convert.ToDouble(ingredient.itemAmount) * multi); if (outputamount < 1) { continue; } if (!recycler.MoveItemToOutput(ItemManager.CreateByName(ingredient.itemName, outputamount))) { flag = true; } } if (flag || !recycler.HasRecyclable()) { recycler.StopRecycling(); for (int i = 5; i <= 11; i++) { Item _item = recycler.inventory.GetSlot(i); if (_item == null) { continue; } if (_item.IsValid()) { if (outputBlacklistedItems.Contains(_item.info.shortname)) { _item.Remove(); _item.RemoveFromContainer(); } } } } return(true); }
public IActionResult Delete(int id) { ItemManager.Delete(id); return(RedirectToAction(nameof(List))); }
Item MightyRNG(string type, int itemCount, bool blockBPs = false) { bool asBP = (rng.NextDouble() < blueprintProbability && !blockBPs); List <string> selectFrom; int limit = 0; string itemName; Item item; int maxRetry = 10 * itemCount; do { selectFrom = null; item = null; if (asBP) { var r = rng.Next(totalBlueprintWeight[type]); for (var i = 0; i < 5; ++i) { limit += blueprintWeights[type][i]; if (r < limit) { selectFrom = Blueprints[type][i]; break; } } } else { var r = rng.Next(totalItemWeight[type]); for (var i = 0; i < 5; ++i) { limit += itemWeights[type][i]; if (r < limit) { selectFrom = Items[type][i]; break; } } } if (selectFrom == null) { if (--maxRetry <= 0) { break; } continue; } itemName = selectFrom[rng.Next(0, selectFrom.Count)]; ItemDefinition itemDef = ItemManager.FindItemDefinition(itemName); if (asBP && itemDef.Blueprint != null && itemDef.Blueprint.isResearchable) { var blueprintBaseDef = ItemManager.FindItemDefinition("blueprintbase"); item = ItemManager.Create(blueprintBaseDef, 1, 0uL); item.blueprintTarget = itemDef.itemid; } else { item = ItemManager.CreateByName(itemName, 1); } if (item == null || item.info == null) { continue; } break; } while (true); if (item == null) { return(null); } object itemLimit; if (((lootTables[type] as Dictionary <string, object>)["ItemList"] as Dictionary <string, object>).TryGetValue(item.info.shortname, out itemLimit)) { Dictionary <string, object> limits = itemLimit as Dictionary <string, object>; item.amount = UnityEngine.Random.Range(Math.Min((int)limits["Min"], (int)limits["Max"]), Math.Max((int)limits["Min"], (int)limits["Max"])); } item.OnVirginSpawn(); return(item); }
private Item GetStateItem(ID stateId) { return(ItemManager.GetItem(stateId, Language.Current, Version.Latest, Database, SecurityCheck.Disable)); }
public AdminMainForm() { InitializeComponent(); _itemManager = ItemManager.CreateAsSingleton(PathHelper.ItemPathModel); _customerManager = CustomerManager.CreateAsSingleton(PathHelper.CustomerPathModel); }
// Update is called once per frame void Update() { updateCounter++; if (updateCounter >= Settings.statusUpdateNumber) { string status = "invalid"; string objectName; string[] nameSubstrings; objectName = gameObject.transform.parent.name; nameSubstrings = objectName.Split('_'); int pos = objectName.IndexOf('_'); string cleanedName = objectName.Substring(pos + 1); Item i = ItemManager.getInstance().getItem(cleanedName); if (i != null) { status = i.state; if (i.type.Equals("Sensor")) { status += " " + ((Sensor)i).unit; if (cleanedName.Contains("idscan")) { status = ((NfcReader)i).getName(); } } updateCounter = 0; this.transform.GetChild(0).GetChild(1).GetComponent <Text>().text = i.shortName; //if(objectName.Contains("dimmer")) // Debug.Log("shortname of " + objectName + " is " + i.shortName + " with status " + status); } if (i is ColorSensor || i is HueDimmer || i is CoffeeMachineActuator) { if (i is ColorSensor || i is HueDimmer) { byte r, g, b; if (i is ColorSensor) { ColorSensor c = (ColorSensor)i; r = Convert.ToByte(c.r); g = Convert.ToByte(c.g); b = Convert.ToByte(c.b); this.transform.GetChild(0).GetChild(1).GetChild(0).GetComponent <Image>().color = new Color32(r, g, b, 255); } else { HueDimmer hd = (HueDimmer)i; HueColor c = hd.hueColor; float hf = (float)c.h / 360; float sf = (float)c.s / 100; float vf = (float)c.v / 100; Color rgbColor = Color.HSVToRGB(hf, sf, vf, false); this.transform.GetChild(0).GetChild(1).GetChild(0).GetComponent <Image>().color = rgbColor; string RGBstring = rgbColor.ToString(); int Ri = (int)(rgbColor.r * 255); int Bi = (int)(rgbColor.b * 255); int Gi = (int)(rgbColor.g * 255); string RGBstr = Ri.ToString() + "," + Gi.ToString() + "," + Bi.ToString(); Debug.Log(RGBstr); this.transform.GetChild(0).GetChild(1).GetChild(1).GetComponent <Text>().text = RGBstr; } this.transform.GetChild(0).GetChild(2).GetComponent <Text>().text = status; } else { CoffeeMachineActuator c = (CoffeeMachineActuator)i; this.transform.GetChild(0).GetChild(3).GetChild(1).GetComponent <Text>().text = c.getWaterLevel(); this.transform.GetChild(0).GetChild(2).GetComponent <Text>().text = status; } } else { this.transform.GetChild(0).GetChild(2).GetComponent <Text>().text = status; } } }
public override void Execute() { if (Player.Instance.ManaPercent <= Settings.Mana) { return; } if (Settings.UseW && W.IsReady()) { var minion = EntityManager.MinionsAndMonsters.EnemyMinions.FirstOrDefault(m => m.IsValidTarget(W.Range)); if (minion == null) { return; } W.Cast(); if (Settings.UseTiamatHydra) { ItemManager.useHydra(minion); } } if (Settings.UseQ && Q.IsReady()) { var minion = EntityManager.MinionsAndMonsters.EnemyMinions.FirstOrDefault(m => m.IsValidTarget(Q.Range)); if (minion == null) { return; } if (Q.IsInRange(minion) && minion.Health <= Player.Instance.GetSpellDamage(minion, Q.Slot)) { Q.Cast(minion); } } if (Settings.UseE && E.IsReady()) { var minions = EntityManager.MinionsAndMonsters.GetLaneMinions() .Where( m => m.IsValidTarget(E.Range)).ToArray(); if (minions.Length == 0) { return; } if (E.Name == "FizzJump") { var castPos = Prediction.Position.PredictCircularMissileAoe(minions, E.Range, E.Width, E.CastDelay, E.Speed).OrderByDescending(r => r.GetCollisionObjects <Obj_AI_Minion>().Length).FirstOrDefault(); if (castPos != null) { var predictMinion = castPos.GetCollisionObjects <Obj_AI_Minion>(); if (predictMinion.Length >= Settings.UseEMinion) { //var castPos = E.GetPrediction(target).CastPosition; E.Cast(castPos.CastPosition); Player.IssueOrder(GameObjectOrder.MoveTo, castPos.CastPosition); } } } } }
void OnServerInitialized() { ItemManager.Initialize(); LoadAllContainers(); UpdateInternals(listUpdatesOnLoaded); }