private async Task ReplyAddPreyAsync(ISpecies predatorSpecies, IEnumerable <ISpecies> preySpecies, string notes) { IEnumerable <IPredationInfo> currentPrey = await Db.GetPreyAsync(predatorSpecies); IEnumerable <IPredationInfo> existingPrey = currentPrey.Where(info => preySpecies.Any(sp => sp.Id == info.Species.Id && (notes ?? "").Equals(info.Notes ?? "", StringComparison.OrdinalIgnoreCase))).ToArray(); // Prey should be added to the database even if it already exists in order to update the prey notes. foreach (ISpecies prey in preySpecies) { await Db.AddPreyAsync(predatorSpecies, prey, notes); } if (existingPrey.Any()) { string existingPreyStr = StringUtilities.ConjunctiveJoin(existingPrey.Select(info => info.Species.GetShortName().ToBold())); await ReplyWarningAsync($"{predatorSpecies.GetShortName().ToBold()} already preys upon {existingPreyStr}."); } preySpecies = preySpecies.Where(sp => !existingPrey.Any(info => info.Species.Id == sp.Id)).ToArray(); if (preySpecies.Count() > 0) { string preySpeciesStr = StringUtilities.ConjunctiveJoin(preySpecies.Select(x => x.GetShortName().ToBold())); await ReplySuccessAsync($"{predatorSpecies.GetShortName().ToBold()} now preys upon {preySpeciesStr}."); } }
public async Task MinusPic(string genusName, string speciesName, int pictureIndex) { // Decrease the picture index by 1 (since users are expected to use the indices as shown by the "gallery" command, which begin at 1). --pictureIndex; // Get the species. ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid()) { IEnumerable <IPicture> pictures = await Db.GetPicturesAsync(species); IPicture picture = (pictureIndex >= 0 && pictureIndex < pictures.Count()) ? pictures.ElementAt(pictureIndex) : null; // If the image was removed from anywhere (gallery or default species picture), this is set to "true". bool success = await Db.RemovePictureAsync(species, picture); if (success) { await ReplySuccessAsync($"Successfully removed {picture.Url.ToLink("picture")} from {species.GetShortName().ToBold()}."); } else { await ReplySuccessAsync($"{species.GetShortName().ToBold()} has no picture at this index."); } } }
private bool StringMatchesSpeciesName(string name, ISpecies species) { name = name.ToLower(); return(name == species.Name.ToLower() || name == species.GetShortName().ToLower() || name == species.GetFullName().ToLower() || (!string.IsNullOrEmpty(species.GetCommonName()) && name == species.GetCommonName().ToLower())); }
private async Task ReplyRemovePreyAsync(ISpecies predatorSpecies, ISpecies preySpecies) { if (predatorSpecies.IsValid() && preySpecies.IsValid()) { IEnumerable <IPredationInfo> existingPrey = await Db.GetPreyAsync(predatorSpecies); if (existingPrey.Any(info => info.Species.Id == preySpecies.Id)) { await Db.RemovePreyAsync(predatorSpecies, preySpecies); await ReplySuccessAsync(string.Format("**{0}** no longer preys upon **{1}**.", predatorSpecies.GetShortName(), preySpecies.GetShortName())); } else { await ReplyWarningAsync(string.Format("**{0}** does not prey upon **{1}**.", predatorSpecies.GetShortName(), preySpecies.GetShortName())); } } }
public async Task PlusRelationship(string genus1, string species1, string genus2, string species2, string relationship) { // Get the relationship from the DB. Relationship relation = await GetRelationshipFromDbAsync(relationship); if (!await ReplyValidateRelationshipAsync(Context, relation)) { return; } // Get the species from the DB. ISpecies sp1 = await GetSpeciesOrReplyAsync(genus1, species1); if (!sp1.IsValid()) { return; } ISpecies sp2 = await GetSpeciesOrReplyAsync(genus2, species2); if (!sp2.IsValid()) { return; } if (sp1.Id == sp2.Id) { await BotUtils.ReplyAsync_Warning(Context, "A species cannot be in a relationship with itself."); return; } // Create the new relationship. using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR REPLACE INTO SpeciesRelationships(species1_id, species2_id, relationship_id) VALUES($species1_id, $species2_id, $relationship_id)")) { cmd.Parameters.AddWithValue("$species1_id", sp1.Id); cmd.Parameters.AddWithValue("$species2_id", sp2.Id); cmd.Parameters.AddWithValue("$relationship_id", relation.id); await Db.ExecuteNonQueryAsync(cmd); } await BotUtils.ReplyAsync_Success(Context, string.Format("**{0}** has successfully been set as a {1} of **{2}**.", sp2.GetShortName(), relation.BeneficiaryName(), sp1.GetShortName())); }
private async Task <string> ResultToStringAsync(ISpecies species) { string result; if (formatter != null) { result = formatter.GetString(species); } else { result = species.GetShortName(); } return(await Task.FromResult(result)); }
public async Task MinusCommonName(string genusName, string speciesName, string commonName) { ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid()) { if (!species.CommonNames.Any(name => name.Equals(commonName, StringComparison.OrdinalIgnoreCase))) { // The species does not have the given common name. await ReplyWarningAsync($"{species.GetShortName().ToBold()} does not have the common name {commonName.ToTitle().ToBold()}."); } else { // Remove the common name. species.CommonNames.Remove(species.CommonNames.Where(name => name.Equals(commonName, StringComparison.OrdinalIgnoreCase)).First()); await Db.UpdateSpeciesAsync(species); await ReplySuccessAsync($"**{species.GetShortName()}** is no longer known as the **{commonName.ToTitle()}**."); } } }
public async Task PlusCommonName(string genusName, string speciesName, string commonName) { ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (string.IsNullOrWhiteSpace(commonName)) { await ReplyErrorAsync("Common name cannot be empty."); } else if (species.IsValid()) { if (species.CommonNames.Any(name => name.Equals(commonName, StringComparison.OrdinalIgnoreCase))) { await ReplyWarningAsync($"{species.GetShortName().ToBold()} is already known as the {species.CommonNames.Last().ToTitle().ToBold()}."); } else { species.CommonNames.Add(commonName); await Db.UpdateSpeciesAsync(species); await ReplySuccessAsync($"{species.GetShortName().ToBold()} is now commonly known as the {species.CommonNames.Last().ToTitle().ToBold()}."); } } }
// Private members private async Task ReplyRolesAsync(ISpecies species) { // Get the role(s) assigned to this species. IEnumerable <Common.Roles.IRole> roles = await Db.GetRolesAsync(species); if (roles.Count() > 0) { // Display the role(s) to the user. StringBuilder lines = new StringBuilder(); foreach (Common.Roles.IRole role in roles) { lines.Append(role.GetName()); if (!string.IsNullOrEmpty(role.Notes)) { lines.Append(string.Format(" ({0})", role.Notes)); } lines.AppendLine(); } Discord.Messaging.IEmbed embed = new Discord.Messaging.Embed { Title = $"{species.GetShortName().ToPossessive()} role(s) ({roles.Count()})", Description = lines.ToString() }; await ReplyAsync(embed); } else { await ReplyInfoAsync($"{species.GetShortName().ToBold()} has not been assigned any roles."); } }
public async Task Favs() { // Get all species fav'd by this user. List <string> lines = new List <string>(); using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM Species WHERE id IN (SELECT species_id FROM Favorites WHERE user_id = $user_id);")) { cmd.Parameters.AddWithValue("$user_id", Context.User.Id); foreach (DataRow row in await Db.GetRowsAsync(cmd)) { ISpecies sp = await Db.CreateSpeciesFromDataRowAsync(row); long fav_count = 0; // Get the number of times this species has been favorited. using (SQLiteCommand cmd2 = new SQLiteCommand("SELECT COUNT(*) FROM Favorites WHERE species_id = $species_id;")) { cmd2.Parameters.AddWithValue("$species_id", sp.Id); fav_count = await Db.GetScalarAsync <long>(cmd2); } lines.Add(sp.GetShortName() + (fav_count > 1 ? string.Format(" (+{0})", fav_count) : "")); } lines.Sort(); } // Display the species list. if (lines.Count() <= 0) { await BotUtils.ReplyAsync_Info(Context, string.Format("**{0}** has not favorited any species.", Context.User.Username)); } else { IPaginatedMessage message = new PaginatedMessage(); message.AddLines(lines); message.SetTitle($"β Species favorited by {Context.User.Username} ({lines.Count()})"); message.SetThumbnailUrl(Context.User.GetAvatarUrl(size: 32)); message.AddPageNumbers(); await ReplyAsync(message); } }
public async Task SetSpeciesCommonName(string genusName, string speciesName, string commonName) { ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid()) { if (string.IsNullOrWhiteSpace(commonName)) { // If the given common name is empty, erase all common names associated with this species. species.CommonNames.Clear(); await Db.UpdateSpeciesAsync(species); await ReplySuccessAsync($"Successfully removed all common names from **{species.GetShortName()}**."); } else { // Otherwise, add the common name to the database. // The difference between this and the "+common" command is that this one overwrites the value stored in the "Species" table with the first common name. // This field is deprected at this point. List <string> commonNames = new List <string> { commonName }; commonNames.AddRange(species.CommonNames); species.CommonNames.Clear(); species.CommonNames.AddRange(commonNames); await Db.UpdateSpeciesAsync(species); await ReplySuccessAsync($"**{species.GetShortName()}** is now commonly known as the **{species.GetCommonName().ToTitle()}**."); } } }
public async Task SetPic(string genusName, string speciesName, string imageUrl) { // Updates the default picture for the given species. // While any users can add pictures for species, only moderators can update the default picture. ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid()) { if (await ReplyValidateImageUrlAsync(imageUrl)) { IPictureGallery gallery = await Db.GetGalleryAsync(species) ?? new PictureGallery(); bool isFirstPicture = gallery.Count() <= 0; await Db.SetPictureAsync(species, new Picture { Url = imageUrl, Artist = isFirstPicture ? species.Creator : Context.User.ToCreator() }); await ReplySuccessAsync($"Successfully set the picture for {species.GetShortName().ToBold()}."); } } }
public async Task SetGenus(string genusName, string speciesName, string newGenusName) { // Get the specified species. ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid()) { // Get the specified genus. ITaxon genus = await GetTaxonOrReplyAsync(TaxonRankType.Genus, newGenusName); if (genus.IsValid()) { // Update the species. species.Genus = genus; await Db.UpdateSpeciesAsync(species); await ReplySuccessAsync($"**{species.GetShortName()}** has successfully been assigned to the genus **{genus.GetName().ToTitle()}**."); } } }
public async Task SetRole(string genusName, string speciesName, string roleName, string notes = "") { // Get the species. ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid()) { // Get the role. Common.Roles.IRole role = await Db.GetRoleAsync(roleName); if (await this.ReplyValidateRoleAsync(role)) { // Update the species. role.Notes = notes; await Db.AddRoleAsync(species, role); await ReplySuccessAsync($"{species.GetShortName().ToBold()} has successfully been assigned the role of {role.GetName().ToBold()}."); } } }
public async Task MinusFav(string genus, string species) { // Get the requested species. ISpecies sp = await GetSpeciesOrReplyAsync(genus, species); if (!sp.IsValid()) { return; } // Remove this species from the user's favorites list. using (SQLiteCommand cmd = new SQLiteCommand("DELETE FROM Favorites WHERE user_id = $user_id AND species_id = $species_id;")) { cmd.Parameters.AddWithValue("$user_id", Context.User.Id); cmd.Parameters.AddWithValue("$species_id", sp.Id); await Db.ExecuteNonQueryAsync(cmd); } await BotUtils.ReplyAsync_Success(Context, string.Format("Successfully removed **{0}** from **{1}**'s favorites list.", sp.GetShortName(), Context.User.Username)); }
public async Task SetArtist(string genusName, string speciesName, int pictureIndex, string artist) { // Decrease the picture index by 1 (since users are expected to use the indices as shown by the "gallery" command, which begin at 1). --pictureIndex; ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid()) { IEnumerable <IPicture> pictures = await Db.GetPicturesAsync(species); if (pictureIndex >= 0 && pictureIndex < pictures.Count()) { IPicture picture = pictures.ElementAt(pictureIndex); picture.Artist = new Creator(artist); await Db.AddPictureAsync(species, picture); await ReplySuccessAsync(string.Format("Successfully updated artist for {0} [picture]({1}) to **{2}**.", StringUtilities.ToPossessive(species.GetShortName()), picture.Url, artist)); } else { await ReplyErrorAsync(string.Format("**{0}** has no picture at this index.", species.GetShortName())); } } }
public async Task PlusPic(string genusName, string speciesName, string imageUrl, string description) { // Get the species. ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid() && await ReplyValidateImageUrlAsync(imageUrl)) { // Add the new picture to the gallery. // If this is the first picture we've added to the species, set the artist as the species' owner. // Otherwise, set the artist to the person submitting the image. IPictureGallery gallery = await Db.GetGalleryAsync(species) ?? new PictureGallery(); bool isFirstPicture = gallery.Count() <= 0; bool pictureAlreadyExists = gallery .Any(x => x.Url == imageUrl); IPicture picture = gallery .Where(p => p.Url == imageUrl) .FirstOrDefault() ?? new Picture(); picture.Url = imageUrl; picture.Description = description; if (string.IsNullOrEmpty(picture.Artist?.Name)) { picture.Artist = isFirstPicture ? species.Creator : Context.User.ToCreator(); } await Db.AddPictureAsync(species, picture); if (pictureAlreadyExists) { await ReplySuccessAsync($"Successfully updated {imageUrl.ToLink("picture")} for {species.GetShortName().ToBold()}."); } else { await ReplySuccessAsync($"Successfully added new {imageUrl.ToLink("picture")} for {species.GetShortName().ToBold()}."); } } }
public async Task Prey([Remainder] string speciesName) { speciesName = StringUtilities.StripOuterQuotes(speciesName); ISpecies species = await GetSpeciesOrReplyAsync(speciesName); if (species.IsValid()) { // Get the preyed-upon species. IEnumerable <IPredationInfo> preySpecies = (await Db.GetPreyAsync(species)) .OrderBy(info => info.Species.GetShortName()); if (preySpecies.Count() > 0) { List <string> lines = new List <string>(); foreach (IPredationInfo preyInfo in preySpecies) { string line = TaxonFormatter.GetString(preyInfo.Species); if (!string.IsNullOrEmpty(preyInfo.Notes)) { line += (string.Format(" ({0})", preyInfo.Notes.ToLowerInvariant())); } lines.Add(line); } string title = string.Format("Species preyed upon by {0} ({1})", TaxonFormatter.GetString(species, false), preySpecies.Count()); IEnumerable <Discord.Messaging.IEmbed> pages = EmbedUtilities.CreateEmbedPages(string.Empty, lines, columnsPerPage: 2, options: EmbedPaginationOptions.AddPageNumbers); Discord.Messaging.IPaginatedMessage message = new Discord.Messaging.PaginatedMessage(pages); message.SetTitle(title); await ReplyAsync(message); } else { await ReplyInfoAsync(string.Format("**{0}** does not prey upon any other species.", species.GetShortName())); } } }
public async Task Predates([Remainder] string speciesName) { speciesName = StringUtilities.StripOuterQuotes(speciesName); ISpecies species = await GetSpeciesOrReplyAsync(speciesName); if (species.IsValid()) { IEnumerable <IPredationInfo> predatorSpecies = (await Db.GetPredatorsAsync(species)) .Where(info => !info.Species.IsExtinct()) .OrderBy(info => info.Species.GetShortName()); if (predatorSpecies.Count() > 0) { Discord.Messaging.IEmbed embed = new Discord.Messaging.Embed(); List <string> lines = new List <string>(); foreach (IPredationInfo info in predatorSpecies) { string lineText = TaxonFormatter.GetString(info.Species); if (!string.IsNullOrEmpty(info.Notes)) { lineText += string.Format(" ({0})", info.Notes.ToLowerInvariant()); } lines.Add(lineText); } embed.Title = string.Format("Predators of {0} ({1})", TaxonFormatter.GetString(species, false), lines.Count()); embed.Description = string.Join(Environment.NewLine, lines); await ReplyAsync(embed); } else { await ReplyInfoAsync(string.Format("**{0}** has no extant natural predators.", species.GetShortName())); } } }
public CycleException(ISpecies species) : base(string.Format("This species' evolutionary line contains a cycle ({0} appeared twice).", species != null ? (species.IsValid() ? string.Format("**{0}**", species.GetShortName()) : species.Id.ToString()) : "a species")) { this.Species = species; }
public async Task MinusRelationship(string genus1, string species1, string genus2, string species2, string relationship) { // Get the relationship from the DB. Relationship relation = await GetRelationshipFromDbAsync(relationship); if (!await ReplyValidateRelationshipAsync(Context, relation)) { return; } // Get the species from the DB. ISpecies sp1 = await GetSpeciesOrReplyAsync(genus1, species1); if (!sp1.IsValid()) { return; } ISpecies sp2 = await GetSpeciesOrReplyAsync(genus2, species2); if (!sp2.IsValid()) { return; } // Check if the requested relationship exists. using (SQLiteCommand cmd = new SQLiteCommand("SELECT COUNT(*) FROM SpeciesRelationships WHERE (species1_id=$species1_id OR species1_id=$species2_id OR species2_id=$species1_id OR species2_id=$species2_id) AND relationship_id=$relationship_id;")) { cmd.Parameters.AddWithValue("$species1_id", sp1.Id); cmd.Parameters.AddWithValue("$species2_id", sp2.Id); cmd.Parameters.AddWithValue("$relationship_id", relation.id); if (await Db.GetScalarAsync <long>(cmd) <= 0) { await BotUtils.ReplyAsync_Error(Context, string.Format("No such relationship exists between **{0}** and **{1}**.", sp1.GetShortName(), sp2.GetShortName())); return; } } // Delete the relationship. using (SQLiteCommand cmd = new SQLiteCommand("DELETE FROM SpeciesRelationships WHERE (species1_id=$species1_id OR species1_id=$species2_id OR species2_id=$species1_id OR species2_id=$species2_id) AND relationship_id=$relationship_id;")) { cmd.Parameters.AddWithValue("$species1_id", sp1.Id); cmd.Parameters.AddWithValue("$species2_id", sp2.Id); cmd.Parameters.AddWithValue("$relationship_id", relation.id); await Db.ExecuteNonQueryAsync(cmd); } await BotUtils.ReplyAsync_Success(Context, string.Format("**{0}** and **{1}** no longer have a {2} relationship.", sp1.GetShortName(), sp2.GetShortName(), relation.DescriptorName())); }
public static async Task <BattleGotchi> GenerateGotchiAsync(this SQLiteDatabase database, GotchiGenerationParameters parameters) { BattleGotchi result = new BattleGotchi(); if (!(parameters.Base is null)) { // If a base gotchi was provided, copy over some of its characteristics. result.Gotchi.BornTimestamp = parameters.Base.BornTimestamp; result.Gotchi.DiedTimestamp = parameters.Base.DiedTimestamp; result.Gotchi.EvolvedTimestamp = parameters.Base.EvolvedTimestamp; result.Gotchi.FedTimestamp = parameters.Base.FedTimestamp; } // Select a random base species to start with. ISpecies species = parameters.Species; if (species is null) { IEnumerable <ISpecies> base_species_list = await database.GetBaseSpeciesAsync(); if (base_species_list.Count() > 0) { species = base_species_list.ElementAt(NumberUtilities.GetRandomInteger(0, base_species_list.Count())); } } if (species != null) { result.Gotchi.SpeciesId = (long)species.Id; } // Evolve it the given number of times. for (int i = 0; i < parameters.MaxEvolutions; ++i) { if (!await database.EvolveAndUpdateGotchiAsync(result.Gotchi)) { break; } } // Generate stats (if applicable). if (parameters.GenerateStats) { result.Gotchi.Experience = GotchiExperienceCalculator.ExperienceToLevel(result.Stats.ExperienceGroup, NumberUtilities.GetRandomInteger(parameters.MinLevel, parameters.MaxLevel + 1)); result.Stats = await new GotchiStatsCalculator(database, Global.GotchiContext).GetStatsAsync(result.Gotchi); } // Generate moveset (if applicable). if (parameters.GenerateMoveset) { result.Moves = await Global.GotchiContext.MoveRegistry.GetMoveSetAsync(database, result.Gotchi); } // Generate types. result.Types = await Global.GotchiContext.TypeRegistry.GetTypesAsync(database, result.Gotchi); // Generate a name for the gotchi. result.Gotchi.Name = (species is null ? "Wild Gotchi" : species.GetShortName()) + string.Format(" (Lv. {0})", result.Stats is null ? 1 : result.Stats.Level); return(result); }
public async Task Gotchi() { // Get this user's primary Gotchi. Gotchi gotchi = await Db.GetGotchiAsync(Context.User.ToCreator()); if (!await this.ReplyValidateGotchiAsync(gotchi)) { return; } // Create the gotchi GIF. string gifUrl = await this.ReplyUploadGotchiGifAsync(gotchi); if (string.IsNullOrEmpty(gifUrl)) { return; } // Get the gotchi's species. ISpecies species = await Db.GetSpeciesAsync(gotchi.SpeciesId); // Pick status text. string status = "{0} is feeling happy!"; switch (gotchi.State) { case GotchiState.Dead: status = "Oh no... {0} has died..."; break; case GotchiState.Evolved: status = "Congratulations, {0} " + string.Format("evolved into {0}!", species.GetShortName()); break; case GotchiState.Sleeping: long hours_left = gotchi.HoursOfSleepLeft(); status = "{0} is taking a nap. " + string.Format("Check back in {0} hour{1}.", hours_left, hours_left > 1 ? "s" : string.Empty); break; case GotchiState.Hungry: status = "{0} is feeling hungry!"; break; case GotchiState.Eating: status = "{0} is enjoying some delicious Suka-Flakesβ’!"; break; case GotchiState.Energetic: status = "{0} is feeling rowdy!"; break; case GotchiState.Tired: status = "{0} is getting a bit sleepy..."; break; } // Update the viewed timestamp. await Db.SetViewedTimestampAsync(gotchi, DateUtilities.GetCurrentTimestampUtc()); // Send the message. EmbedBuilder embed = new EmbedBuilder(); embed.WithTitle(string.Format("{0}'s \"{1}\"", Context.User.Username, gotchi.Name.ToTitle())); embed.WithDescription(string.Format("{0}, age {1}", species.GetShortName(), gotchi.Age)); embed.WithImageUrl(gifUrl); embed.WithFooter(string.Format(status, StringUtilities.ToTitleCase(gotchi.Name))); await ReplyAsync(embed : embed.Build()); }
public async Task AddFav(string genus, string species) { // Get the requested species. ISpecies sp = await GetSpeciesOrReplyAsync(genus, species); if (!sp.IsValid()) { return; } // Add this species to the user's favorites list. using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR IGNORE INTO Favorites(user_id, species_id) VALUES($user_id, $species_id);")) { cmd.Parameters.AddWithValue("$user_id", Context.User.Id); cmd.Parameters.AddWithValue("$species_id", sp.Id); await Db.ExecuteNonQueryAsync(cmd); } await BotUtils.ReplyAsync_Success(Context, string.Format("Successfully added **{0}** to **{1}**'s favorites list.", sp.GetShortName(), Context.User.Username)); }
public async Task Relationships([Remainder] string speciesName) { // Get the species from the DB. speciesName = StringUtilities.StripOuterQuotes(speciesName); ISpecies sp = await GetSpeciesOrReplyAsync(speciesName); if (!sp.IsValid()) { return; } // Get relationships and build the embed. SortedDictionary <string, List <string> > items = new SortedDictionary <string, List <string> >(); // Get relationships where this species is the one acting upon another. using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM SpeciesRelationships LEFT JOIN Relationships ON SpeciesRelationships.relationship_id = Relationships.id WHERE species1_id=$species_id;")) { cmd.Parameters.AddWithValue("$species_id", sp.Id); foreach (DataRow row in await Db.GetRowsAsync(cmd)) { long other_species_id = row.Field <long>("species2_id"); ISpecies other_species = await Db.GetSpeciesAsync(other_species_id); Relationship relationship = Relationship.FromDataRow(row); if (other_species is null) { continue; } if (!items.ContainsKey(relationship.BeneficiaryName(plural: true))) { items[relationship.BeneficiaryName(plural: true)] = new List <string>(); } items[relationship.BeneficiaryName(plural: true)].Add(TaxonFormatter.GetString(other_species)); } } // Get relationships where this species is the one being acted upon. using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM SpeciesRelationships LEFT JOIN Relationships ON SpeciesRelationships.relationship_id = Relationships.id WHERE species2_id=$species_id;")) { cmd.Parameters.AddWithValue("$species_id", sp.Id); foreach (DataRow row in await Db.GetRowsAsync(cmd)) { long other_species_id = row.Field <long>("species1_id"); ISpecies other_species = await Db.GetSpeciesAsync(other_species_id); Relationship relationship = Relationship.FromDataRow(row); if (other_species is null) { continue; } if (!items.ContainsKey(relationship.BenefactorName(plural: true))) { items[relationship.BenefactorName(plural: true)] = new List <string>(); } items[relationship.BenefactorName(plural: true)].Add(TaxonFormatter.GetString(other_species)); } } // Get any prey/predator relationships. using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM Predates WHERE species_id=$species_id;")) { cmd.Parameters.AddWithValue("$species_id", sp.Id); foreach (DataRow row in await Db.GetRowsAsync(cmd)) { long other_species_id = row.Field <long>("eats_id"); ISpecies other_species = await Db.GetSpeciesAsync(other_species_id); if (other_species is null) { continue; } if (!items.ContainsKey("prey")) { items["prey"] = new List <string>(); } items["prey"].Add(TaxonFormatter.GetString(other_species)); } } using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM Predates WHERE eats_id=$species_id;")) { cmd.Parameters.AddWithValue("$species_id", sp.Id); foreach (DataRow row in await Db.GetRowsAsync(cmd)) { long other_species_id = row.Field <long>("species_id"); ISpecies other_species = await Db.GetSpeciesAsync(other_species_id); if (other_species is null) { continue; } if (!items.ContainsKey("predators")) { items["predators"] = new List <string>(); } items["predators"].Add(TaxonFormatter.GetString(other_species)); } } // If the species does not have any relationships with other species, state so. if (items.Count() <= 0) { await BotUtils.ReplyAsync_Info(Context, string.Format("**{0}** does not have any relationships with other species.", sp.GetShortName())); return; } // Build the embed. EmbedBuilder embed = new EmbedBuilder(); int relationship_count = 0; foreach (string key in items.Keys) { items[key].Sort((lhs, rhs) => lhs.CompareTo(rhs)); embed.AddField(string.Format("{0} ({1})", StringUtilities.ToTitleCase(key), items[key].Count()), string.Join(Environment.NewLine, items[key]), inline: true); relationship_count += items[key].Count(); } embed.WithTitle(string.Format("Relationships involving {0} ({1})", TaxonFormatter.GetString(sp, false), relationship_count)); await ReplyAsync("", false, embed.Build()); }
public async Task RemoveRole(string genusName, string speciesName, string roleName) { // Get the species. ISpecies species = await GetSpeciesOrReplyAsync(genusName, speciesName); if (species.IsValid()) { // Get the role. Common.Roles.IRole role = await Db.GetRoleAsync(roleName); if (await this.ReplyValidateRoleAsync(role)) { // Update the species. await Db.RemoveRoleAsync(species, role); await ReplySuccessAsync($"Role {role.GetName().ToBold()} has successfully been unassigned from {species.GetShortName().ToBold()}."); } } }
private async Task _endBattle(ICommandContext context) { PlayerState winner = player1.Gotchi.Stats.Hp <= 0.0 ? player2 : player1; PlayerState loser = player1.Gotchi.Stats.Hp <= 0.0 ? player1 : player2; // Calculate the amount of EXP awarded to the winner. // The loser will get 50% of the winner's EXP. double exp = _getExpEarned(winner.Gotchi.Gotchi, loser.Gotchi.Gotchi, won: true); double exp1 = player2.Gotchi.Stats.Hp <= 0.0 ? exp : exp * .5; double exp2 = player1.Gotchi.Stats.Hp <= 0.0 ? exp : exp * .5; long levels1 = player1.Gotchi.Stats.AddExperience((int)exp1); long levels2 = player2.Gotchi.Stats.AddExperience((int)exp2); StringBuilder sb = new StringBuilder(); sb.AppendLine(battleText); // Show the winner's accomplishments, then the loser's. if (!IsCpuGotchi(winner.Gotchi.Gotchi)) { double winner_exp = winner.Gotchi.Gotchi.Id == player1.Gotchi.Gotchi.Id ? exp1 : exp2; long winner_levels = winner.Gotchi.Gotchi.Id == player1.Gotchi.Gotchi.Id ? levels1 : levels2; long winner_g = (long)Math.Round(loser.Gotchi.Stats.Level * (NumberUtilities.GetRandomInteger(150, 200) / 100.0)); sb.AppendLine(string.Format("π **{0}** won the battle! Earned **{1} EXP** and **{2}G**.", winner.Gotchi.Gotchi.Name, winner_exp, winner_g)); if (winner_levels > 0) { sb.AppendLine(string.Format("π **{0}** leveled up to level **{1}**!", winner.Gotchi.Gotchi.Name, winner.Gotchi.Stats.Level)); } if (((winner.Gotchi.Stats.Level - winner_levels) / 10) < (winner.Gotchi.Stats.Level / 10)) { if (await database.EvolveAndUpdateGotchiAsync(winner.Gotchi.Gotchi)) { ISpecies sp = await database.GetSpeciesAsync(winner.Gotchi.Gotchi.SpeciesId); sb.AppendLine(string.Format("π© Congratulations, **{0}** evolved into **{1}**!", winner.Gotchi.Gotchi.Name, sp.GetShortName())); } } // Update the winner's G. GotchiUserInfo user_data = await database.GetUserInfoAsync(winner.Gotchi.Gotchi.OwnerId); user_data.G += winner_g; await database.UpdateUserInfoAsync(user_data); sb.AppendLine(); } if (!IsCpuGotchi(loser.Gotchi.Gotchi)) { double loser_exp = loser.Gotchi.Gotchi.Id == player1.Gotchi.Gotchi.Id ? exp1 : exp2; long loser_levels = loser.Gotchi.Gotchi.Id == player1.Gotchi.Gotchi.Id ? levels1 : levels2; sb.AppendLine(string.Format("π **{0}** lost the battle... Earned **{1} EXP**.", loser.Gotchi.Gotchi.Name, loser_exp)); if (loser_levels > 0) { sb.AppendLine(string.Format("π **{0}** leveled up to level **{1}**!", loser.Gotchi.Gotchi.Name, loser.Gotchi.Stats.Level)); } if (((loser.Gotchi.Stats.Level - loser_levels) / 10) < (loser.Gotchi.Stats.Level / 10)) { if (await database.EvolveAndUpdateGotchiAsync(loser.Gotchi.Gotchi)) { ISpecies sp = await database.GetSpeciesAsync(loser.Gotchi.Gotchi.SpeciesId); sb.AppendLine(string.Format("π© Congratulations, **{0}** evolved into **{1}**!", loser.Gotchi.Gotchi.Name, sp.GetShortName())); } } } // Update exp in the database. using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET level=$level, exp=$exp WHERE id=$id;")) { cmd.Parameters.AddWithValue("$id", player1.Gotchi.Gotchi.Id); cmd.Parameters.AddWithValue("$level", DBNull.Value); cmd.Parameters.AddWithValue("$exp", player1.Gotchi.Stats.Experience); await database.ExecuteNonQueryAsync(cmd); } if (!IsCpuGotchi(player2.Gotchi.Gotchi)) { using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET level=$level, exp=$exp WHERE id=$id;")) { cmd.Parameters.AddWithValue("$id", player2.Gotchi.Gotchi.Id); cmd.Parameters.AddWithValue("$level", DBNull.Value); cmd.Parameters.AddWithValue("$exp", player2.Gotchi.Stats.Experience); await database.ExecuteNonQueryAsync(cmd); } } // Deregister the battle state. DeregisterBattle(context.User.Id); battleText = sb.ToString(); }