private static int RetrieveKeyIndex(StringKey key, Entry <StringKey, Item>[] table) { // PLEASE NOTE: this method is used for testing and may not be a valid way for students // to search their tables in the actual solution. Remember you need to handle collisions // and your look up should NOT be Big-O of N algorithm, unlike the below loop. for (int i = 0; i < table.Length; i++) { if (table[i] != null && table[i].Key.Equals(key)) { return(i); } } return(-1); // dummy value of -1 returned when no match found }
public static void Put_Adds_Value_To_Hash_Test() { HashMap <StringKey, Item> hashMap = new HashMap <StringKey, Item>(); StringKey key = new StringKey("item"); Item item = new Item("item", 1, 1.0); hashMap.Put(key, item); Entry <StringKey, Item>[] table = hashMap.Table; int bucket = key.GetHashCode() % table.Length; Assert.AreEqual(item, table[bucket].Value); }
public void PutTest() { StringKey newStringKey = new StringKey("Unique"); Item newItem = new Item("Item", 1, 0.75); HashMap <StringKey, Item> hashMap = new HashMap <StringKey, Item>(5, 0.75); hashMap.Put(newStringKey, newItem); Assert.AreEqual(1, hashMap.Size()); Assert.AreEqual(false, hashMap.IsEmpty()); Assert.AreEqual(newItem, hashMap.Get(newStringKey)); }
public static void ClearEmptiesTableTest() { HashMap <StringKey, Item> hashMap = new HashMap <StringKey, Item>(); StringKey key = new StringKey("item"); hashMap.Put(key, new Item("item", 1, 1.0)); // make sure to actually clear the hashmap before testing... :| hashMap.Clear(); Assert.AreEqual(null, hashMap.Get(key)); Assert.IsTrue(hashMap.IsEmpty()); Assert.AreEqual(0, hashMap.Size()); }
public EvadeData(string name, Dictionary <string, string> content, string path, List <string> sets = null) : base(name, content, path, type, sets) { // Get attack text if (content.ContainsKey("text")) { text = new StringKey(content["text"]); } // Get attack target if (content.ContainsKey("monster")) { monster = content["monster"]; } }
public void PEXPIRE_PTTL() { long dt = -1; StringKey key = "HENRY_EMAIL"; key.Set("*****@*****.**"); key.PExpire(2000); long value = key.PTTL(); Assert.AreNotEqual(value, 0); System.Threading.Thread.Sleep(2000); value = key.PTTL(); Assert.AreEqual(value, dt); }
public void Generate() { doWorldGen = !CanLoadSave(); updateText.gameObject.SetActive(false); percentText.gameObject.SetActive(false); doWorldGen |= debug; if (doWorldGen) { seedText.text = string.Format(UI.WORLDGEN.USING_PLAYER_SEED, seed); titleText.text = UI.FRONTEND.WORLDGENSCREEN.TITLE.ToString(); mainText.text = UI.WORLDGEN.CHOOSEWORLDSIZE.ToString(); for (int i = 0; i < this.validDimensions.Length; i++) { GameObject gameObject = UnityEngine.Object.Instantiate(buttonPrefab); gameObject.SetActive(true); RectTransform component = gameObject.GetComponent <RectTransform>(); component.SetParent(buttonRoot); component.localScale = Vector3.one; LocText componentInChildren = gameObject.GetComponentInChildren <LocText>(); ValidDimensions validDimensions = this.validDimensions[i]; componentInChildren.text = validDimensions.name.ToString(); int idx = i; KButton component2 = gameObject.GetComponent <KButton>(); component2.onClick += delegate { DoWorldGen(idx); ToggleGenerationUI(); }; } if (this.validDimensions.Length == 1) { DoWorldGen(0); ToggleGenerationUI(); } ScreenResize instance = ScreenResize.Instance; instance.OnResize = (System.Action)Delegate.Combine(instance.OnResize, new System.Action(OnResize)); OnResize(); } else { titleText.text = UI.FRONTEND.WORLDGENSCREEN.LOADINGGAME.ToString(); mainText.gameObject.SetActive(false); currentConvertedCurrentStage = UI.WORLDGEN.COMPLETE.key; currentPercent = 100f; updateText.gameObject.SetActive(false); percentText.gameObject.SetActive(false); RemoveButtons(); } buttonPrefab.SetActive(false); }
// Internal function to create the text from constructors void createDialog(Vector2 location, Vector2 size, StringKey textKey, Color fgColour, Color bgColour) { // Object name includes first 10 chars of text string objName = textKey.key; if (objName.Length > 10) { objName = objName.Substring(0, 10); } // Create an object textObj = new GameObject("text" + objName); background = new GameObject("buttonBg" + objName); // Mark it as dialog textObj.tag = "dialog"; background.tag = "dialog"; Game game = Game.Get(); background.transform.parent = game.uICanvas.transform; RectTransform transBg = background.AddComponent <RectTransform>(); transBg.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, location.y * UIScaler.GetPixelsPerUnit(), size.y * UIScaler.GetPixelsPerUnit()); transBg.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, location.x * UIScaler.GetPixelsPerUnit(), size.x * UIScaler.GetPixelsPerUnit()); textObj.transform.parent = background.transform; RectTransform transBt = textObj.AddComponent <RectTransform>(); transBt.SetParent(transBg); transBt.localPosition = Vector2.zero; transBt.localScale = transBg.localScale; transBt.sizeDelta = transBg.sizeDelta; transBt.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0.1f * UIScaler.GetPixelsPerUnit(), transBt.sizeDelta.x - (0.1f * UIScaler.GetPixelsPerUnit())); textObj.AddComponent <CanvasRenderer>(); background.AddComponent <CanvasRenderer>(); UnityEngine.UI.Image uiImage = background.AddComponent <UnityEngine.UI.Image>(); uiImage.color = bgColour; UnityEngine.UI.Text uiText = textObj.AddComponent <UnityEngine.UI.Text>(); uiText.color = fgColour; uiText.text = textKey.Translate(); uiText.alignment = TextAnchor.MiddleCenter; uiText.font = game.gameType.GetFont(); uiText.material = uiText.font.material; uiText.fontSize = UIScaler.GetSmallFont(); }
private (string connectionId, IKey key) GetUserInfo() { string connectionId = Context.ConnectionId; string userId = Context.User.FindFirstValue(ClaimTypes.NameIdentifier); if (userId == null) { throw new UnauthorizedAccessException(); } IKey userKey = StringKey.Create(userId, "User"); return(connectionId, userKey); }
// Create from ini data public UniqueMonster(string name, Dictionary <string, string> data, string pathIn) : base(name, data) { typeDynamic = type; path = pathIn; // Get base derived monster type if (data.ContainsKey("base")) { baseMonster = data["base"]; } monsterName = name; if (data.ContainsKey("name")) { monsterName = data["name"]; } traits = new string[0]; if (data.ContainsKey("traits")) { traits = data["traits"].Split(" ".ToCharArray()); } if (data.ContainsKey("image")) { imagePath = data["image"]; } if (data.ContainsKey("info")) { info = new StringKey(data["info"], false); } imagePlace = imagePath; if (data.ContainsKey("imageplace")) { imagePlace = data["imageplace"]; } activations = new string[0]; if (data.ContainsKey("activation")) { activations = data["activation"].Split(' '); } if (data.ContainsKey("health")) { healthDefined = true; int.TryParse(data["health"], out health); } }
private void UpdateStringTableFromHKey(string hkey) { if (hkey == null) { return; } // HKEY = Hierarchy Key int dotIndex = hkey.LastIndexOf('.'); if (dotIndex == -1) { return; } string directoryPath = hkey.Remove(dotIndex, hkey.Length - dotIndex); // Adds directory path to global strings StringKey directoryPathGlobalString = StringKey.FindCreate((long)crc.Compute(directoryPath, true)); directoryPathGlobalString.SetValue(directoryPath, Language.English); directoryPathGlobalString.SetValue(directoryPath, Language.French); directoryPathGlobalString.SetValue(directoryPath, Language.German); directoryPathGlobalString.SetValue(directoryPath, Language.Italian); directoryPathGlobalString.SetValue(directoryPath, Language.Japanese); directoryPathGlobalString.SetValue(directoryPath, Language.Spanish); StringKey.AddString(directoryPathGlobalString); // Adds string globally // All 6 languages found in DLC files string[] localization = { "enUS", "jaJP", "deDE", "itIT", "esES", "frFR" }; foreach (string local in localization) { string stringTablePath = directoryPath + ".stringTable@" + local; // Adds string table index path to global strings StringKey stringTablePathGlobalString = StringKey.FindCreate((long)crc.Compute(stringTablePath, true)); stringTablePathGlobalString.SetValue(stringTablePath, Language.English); stringTablePathGlobalString.SetValue(stringTablePath, Language.French); stringTablePathGlobalString.SetValue(stringTablePath, Language.German); stringTablePathGlobalString.SetValue(stringTablePath, Language.Italian); stringTablePathGlobalString.SetValue(stringTablePath, Language.Japanese); stringTablePathGlobalString.SetValue(stringTablePath, Language.Spanish); // Adds string globally StringKey.AddString(stringTablePathGlobalString); } }
public HorrorData(string name, Dictionary <string, string> content, string path) : base(name, content, path, type) { // Get attack text if (content.ContainsKey("text")) { text = new StringKey(content["text"]); } // Get attack target if (content.ContainsKey("monster")) { monster = content["monster"]; } }
// Get the text to display for the event virtual public string GetText() { string text = qEvent.text; if (qEvent is PerilData) { text = new StringKey(qEvent.text).Translate(); } // Default door text if (qEvent is QuestData.Door && text.Length == 0) { text = "You can open this door with an \"Open Door\" action."; } // Find and replace rnd:hero with a hero // replaces all occurances with the one hero text = text.Replace("{rnd:hero}", game.quest.GetRandomHero().heroData.name.Translate()); // Random numbers in events try { // Find first random number tag int index = text.IndexOf("{rnd:"); // loop through event text while (index != -1) { // find end of tag string rand = text.Substring(index, text.IndexOf("}", index) + 1 - index); // find separator int separator = rand.IndexOf(":", 5); // Parse min and max int min, max; int.TryParse(rand.Substring(5, separator - 5), out min); int.TryParse(rand.Substring(separator + 1, rand.Length - separator - 2), out max); // Replace with random number text = text.Replace(rand, Random.Range(min, max + 1).ToString()); //find next random tag index = text.IndexOf("{rnd:"); } } catch (System.Exception) { ValkyrieDebug.Log("Warning: Invalid random clause in event dialog: " + text + System.Environment.NewLine); } // Fix new lines and replace symbol text with special characters return(SymbolReplace(text).Replace("\\n", "\n")); }
public void StringKey_Equal() { StringKey key1 = StringKey.Create("1", "Product"); StringKey key2 = StringKey.Create("1", "Product"); Assert.AreEqual(key1, key2); key1 = StringKey.Create("1", "Product"); key2 = StringKey.Create("2", "Product"); Assert.AreNotEqual(key1, key2); key1 = StringKey.Create("1", "Product"); key2 = StringKey.Create("1", "Term"); Assert.AreNotEqual(key1, key2); }
public override int GetHashCode() { int hash = 1; if (typeCase_ == TypeOneofCase.StringKey) { hash ^= StringKey.GetHashCode(); } hash ^= (int)typeCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public void Load(IReadOnlyKeyValueCollection storage, object output) { // TODO: Not TryGet, UserKey is required! if (output is UserEvent payload) { if (storage.TryGet(Name.UserKey, out IKey userKey)) { payload.UserKey = userKey; } else { payload.UserKey = StringKey.Empty("User"); } } }
public static void Put_Does_Not_Increase_Size_On_Update_Test() { HashMap <StringKey, Item> hashMap = new HashMap <StringKey, Item>(); StringKey key = new StringKey("item"); Item item01 = new Item("item", 1, 1.0); Item item02 = new Item("item", 2, 2.0); hashMap.Put(key, item01); Assert.AreEqual(1, hashMap.Size()); hashMap.Put(key, item02); Assert.AreEqual(1, hashMap.Size()); }
/// <summary> /// Create editor selection clist with title, list, colour and callback. /// Creates a list of possible traits extracted from items /// </summary> /// <param name="newTitle">title of the dialog</param> /// <param name="list">list of selectable items</param> /// <param name="call">callback delegate</param> public EditorSelectionList(StringKey newTitle, List <SelectionListEntry> list, UnityEngine.Events.UnityAction call) { items = list; title = newTitle; returnCall = call; filter = new HashSet <string>(); traits = new HashSet <string>(); foreach (SelectionListEntry e in items) { foreach (string s in e.filter) { traits.Add(s); } } }
// generic constructor gets common things public GenericData(string name_ini, Dictionary <string, string> content, string path, string type) { sectionName = name_ini; sets = new List <string>(); // Has the name been specified? if (content.ContainsKey("name")) { name = new StringKey(content["name"]); } else { name = new StringKey(null, name_ini.Substring(type.Length)); } priority = 0; if (content.ContainsKey("priority")) { int.TryParse(content["priority"], out priority); } if (content.ContainsKey("traits")) { traits = content["traits"].Split(" ".ToCharArray()); } else // No traits is a valid condition { traits = new string[0]; } // If image specified it is relative to the path of the ini file // absolute paths are not supported if (content.ContainsKey("image")) { if (content["image"].IndexOf("{import}") == 0) { image = ContentData.ImportPath() + content["image"].Substring(8); } else { image = path + "/" + content["image"]; } } else // No image is a valid condition { image = ""; } }
public Sickness(string id, SicknessType type, Severity severity, float immune_attack_strength, List <InfectionVector> infection_vectors, float sickness_duration, string recovery_effect = null) : base(id, null, null) { name = new StringKey("STRINGS.DUPLICANTS.DISEASES." + id.ToUpper() + ".NAME"); this.id = id; sicknessType = type; this.severity = severity; infectionVectors = infection_vectors; sicknessDuration = sickness_duration; recoveryEffect = recovery_effect; descriptiveSymptoms = new StringKey("STRINGS.DUPLICANTS.DISEASES." + id.ToUpper() + ".DESCRIPTIVE_SYMPTOMS"); cureSpeedBase = new Attribute(id + "CureSpeed", false, Attribute.Display.Normal, false, 0f, null, null); cureSpeedBase.BaseValue = 1f; cureSpeedBase.SetFormatter(new ToPercentAttributeFormatter(1f, GameUtil.TimeSlice.None)); Db.Get().Attributes.Add(cureSpeedBase); }
public static void Remove_keeps_a_key_placeholder_Test() { HashMap <StringKey, Item> hashMap = new HashMap <StringKey, Item>(); StringKey key = new StringKey("item"); Item item = new Item("item", 1, 1.0); hashMap.Put(key, item); Item returnedItem = hashMap.Remove(key); Entry <StringKey, Item>[] table = hashMap.Table; int bucket = key.GetHashCode() % table.Length; // a placeholder will have an Entry with a null for the value, but the key is stil the same as the removed Assert.AreEqual(table[bucket].Key, key); Assert.AreEqual(table[bucket].Value, null); }
internal void AddChildFolder(StringKey key, [NotNull] CompressedBlobStoreSection folder) { if (folder == null) { throw new ArgumentNullException(nameof(folder)); } if (mChildFolders.ContainsKey(key.Normalize())) { mChildFolders[key.Normalize()] = folder; return; } mChildFolders.Add(key.Normalize(), folder); mOriginalChildFolderNames.Add(key); }
public T ReadSetting <T>(StringKey settingGroupKey, StringKey settingKey, T?defaultValue = null) where T : struct { var stringValue = ReadSetting(settingGroupKey, settingKey); if (string.IsNullOrEmpty(stringValue)) { return(defaultValue ?? default(T)); } if (!stringValue.TryDeserialize(typeof(T), out var typedValue, CultureInfo.InvariantCulture)) { return(defaultValue ?? default(T)); } return((T)typedValue); }
private static StringEntry GetInvalidString(params StringKey[] keys) { string text = "MISSING"; for (int i = 0; i < keys.Length; i++) { StringKey stringKey = keys[i]; if (text != string.Empty) { text += "."; } text += stringKey.String; } invalidKeys.Add(text); return(new StringEntry(text)); }
public EventButton(StringKey newLabel, string newColour) { label = newLabel; string colorRGB = ColorUtil.FromName(newColour); // Check format is valid if ((colorRGB.Length != 7) || (colorRGB[0] != '#')) { Game.Get().quest.log.Add(new Quest.LogEntry("Warning: Button color must be in #RRGGBB format or a known name", true)); } // Hexadecimal to float convert (0x00-0xFF -> 0.0-1.0) colour[0] = (float)System.Convert.ToInt32(colorRGB.Substring(1, 2), 16) / 255f; colour[1] = (float)System.Convert.ToInt32(colorRGB.Substring(3, 2), 16) / 255f; colour[2] = (float)System.Convert.ToInt32(colorRGB.Substring(5, 2), 16) / 255f; }
protected IKeyValueStore <string> LoadSettingGroup(StringKey settingGroupKey) { if (mSettingGroups.ContainsKey(settingGroupKey.Normalize())) { return(mSettingGroups[settingGroupKey.Normalize()]); } var settingGroupBlobStore = mStore .GetChildStore("Settings", false); var settingGroup = CreateKeyValueStore(settingGroupBlobStore, settingGroupKey); mSettingGroups.AddOrUpdate(settingGroupKey.Normalize(), settingGroup); return(settingGroup); }
/// <summary> /// Parse the downloaded remote manifest and start download of individual quest files /// </summary> public void DownloadManifest_callback(string data, bool error) { if (error) { // Hide loading screen Destroyer.Dialog(); // draw error message float error_string_width = 0; UIElement ui = new UIElement(); if (data == "ERROR NETWORK") { StringKey ERROR_NETWORK = new StringKey("val", "ERROR_NETWORK"); ui.SetText(ERROR_NETWORK, Color.red); error_string_width = ui.GetStringWidth(ERROR_NETWORK, UIScaler.GetMediumFont()); } else { StringKey ERROR_HTTP = new StringKey("val", "ERROR_HTTP", game.stats.error_download_description); ui.SetText(ERROR_HTTP, Color.red); error_string_width = ui.GetStringWidth(ERROR_HTTP, UIScaler.GetMediumFont()); } ui.SetLocation(UIScaler.GetHCenter() - (error_string_width / 2f), UIScaler.GetVCenter(), error_string_width, 2.4f); ui.SetTextAlignment(TextAnchor.MiddleCenter); ui.SetFontSize(UIScaler.GetLargeFont()); ui.SetBGColor(Color.clear); // draw return button ui = new UIElement(); ui.SetLocation(1, UIScaler.GetBottom(-3), 8, 2); ui.SetText(CommonStringKeys.BACK, Color.red); ui.SetButton(delegate { Cancel(); }); ui.SetFont(game.gameType.GetHeaderFont()); ui.SetFontSize(UIScaler.GetMediumFont()); new UIElementBorder(ui, Color.red); return; } IniData remoteManifest = IniRead.ReadFromString(data); foreach (KeyValuePair <string, Dictionary <string, string> > kv in remoteManifest.data) { remoteQuests.Add(new RemoteQuest(kv)); } DownloadQuestFiles(); }
public static void GetMatchingOrNextAvailableBucket_Retuns_next_index_when_collision_occurs_Test() { HashMap <StringKey, Item> hashMap = new HashMap <StringKey, Item>(); StringKey key = new StringKey("New Item"); StringKey collisionKey = new StringKey("item_COLLSION"); Item item = new Item("New Item", 1, 1.0); hashMap.Put(key, item); int index = RetrieveKeyIndex(key, hashMap.Table); // we overwrite the spot that item originally hashes to... hashMap.Table[index] = new Entry <StringKey, Item>(collisionKey, item); // test to see if putting the colliding item back retrieves index + 1 Assert.AreEqual(index + 1, hashMap.GetMatchingOrNextAvailableBucket(key)); }
internal static Persistable Deserialize(StringKey key, [NotNull] Type type, [NotNull] TextReader source, [NotNull] IInstancePool references, [NotNull] IEnumerable <JsonConverter> converters) { if (key.IsEmpty) { throw new ArgumentNullException(nameof(key)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } if (references == null) { throw new ArgumentNullException(nameof(references)); } if (converters == null) { throw new ArgumentNullException(nameof(converters)); } if (!type.IsSubclassOf(typeof(Persistable))) { throw new ArgumentOutOfRangeException(nameof(type)); } var jsonSerializer = GetSerializer(type); jsonSerializer.ReferenceResolver = references as IReferenceResolver; jsonSerializer.Converters.AddRange(converters); var obj = (Persistable)jsonSerializer.Deserialize(new JsonTextReader(source), type); if (obj != null) { obj.Key = key.RawData; } return(obj); }
// Construct from save data public Monster(Dictionary <string, string> data) { bool.TryParse(data["activated"], out activated); bool.TryParse(data["minionStarted"], out minionStarted); bool.TryParse(data["masterStarted"], out masterStarted); bool.TryParse(data["unique"], out unique); int.TryParse(data["damage"], out damage); int.TryParse(data["duplicate"], out duplicate); uniqueText = new StringKey(data["uniqueText"]); uniqueTitle = new StringKey(data["uniqueTitle"]); // Support old saves (deprectiated) if (data["type"].IndexOf("UniqueMonster") == 0) { data["type"] = "CustomMonster" + data["type"].Substring("UniqueMonster".Length); } // Find base type Game game = Game.Get(); if (game.cd.monsters.ContainsKey(data["type"])) { monsterData = game.cd.monsters[data["type"]]; } // Check if type is a special quest specific type if (game.quest.qd.components.ContainsKey(data["type"]) && game.quest.qd.components[data["type"]] is QuestData.CustomMonster) { monsterData = new QuestMonster(game.quest.qd.components[data["type"]] as QuestData.CustomMonster); } // If we have already selected an activation find it if (data.ContainsKey("activation")) { ActivationData saveActivation = null; if (game.cd.activations.ContainsKey(data["activation"])) { saveActivation = game.cd.activations[data["activation"]]; } // Activations can be specific to the quest if (game.quest.qd.components.ContainsKey(data["activation"])) { saveActivation = new QuestActivation(game.quest.qd.components[data["activation"]] as QuestData.Activation); } currentActivation = new ActivationInstance(saveActivation, monsterData.name.Translate()); } }