public override Task <TypeReaderResult> ReadAsync(ICommandContext ctx, string input, IServiceProvider provider) { if (!(ctx is ArcadeContext context)) { return(Task.FromResult(TypeReaderResult.FromError(CommandError.Unsuccessful, "Invalid command context specified"))); } if (ulong.TryParse(input, out ulong uId)) { if (context.Data.Users.Values.ContainsKey(uId)) { return(Task.FromResult(TypeReaderResult.FromSuccess(context.Data.Users.Values[uId]))); } } ArcadeUser match = context.Data.Users.Values.Values.FirstOrDefault(x => x.Username.Equals(input, StringComparison.OrdinalIgnoreCase)); if (match != null) { return(Task.FromResult(TypeReaderResult.FromSuccess(match))); } TypeReaderResult result = base.ReadAsync(ctx, input, provider).ConfigureAwait(false).GetAwaiter().GetResult(); if (result.IsSuccess && result.BestMatch is SocketUser best && context.TryGetUser(best.Id, out match)) { return(Task.FromResult(TypeReaderResult.FromSuccess(match))); } return(Task.FromResult(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Could not find the specified account."))); }
private static IEnumerable <KeyValuePair <string, long> > GetVisibleStats(ArcadeUser user) => user.Stats.Where(x => x.Value != 0 && Var.TypeOf(x.Key) == VarType.Stat && !ItemHelper.Exists(Var.GetGroup(x.Key)) && !ShopHelper.Exists(Var.GetGroup(x.Key)) ).OrderBy(x => x.Key);
public void Apply(ArcadeUser user) { if (Money > 0) { user.Give(Money); } ulong oldExp = user.Exp; if (Exp > 0) { user.Exp += Exp; } if (user.Config.Notifier.HasFlag(NotifyAllow.Level)) { int oldLevel = ExpConvert.AsLevel(oldExp, user.Ascent); int level = user.Level; if (level > oldLevel) { user.Notifier.Append($"Level up! ({LevelViewer.GetLevel(oldLevel, user.Ascent)} to {LevelViewer.GetLevel(level, user.Ascent)})"); } } if (!Check.NotNullOrEmpty(ItemIds)) { return; } foreach ((string itemId, int amount) in ItemIds) { ItemHelper.GiveItem(user, itemId, amount); } }
public static bool Craft(ArcadeUser user, Recipe recipe) { if (GetRecipeStatus(user, recipe) == RecipeStatus.Unknown) { return(false); } if (!CanCraft(user, recipe)) { return(false); } if (recipe.Result == null) { throw new Exception("Expected recipe result but returned null"); } foreach ((string itemId, int amount) in recipe.Components) { ItemHelper.TakeItem(user, itemId, amount); } ItemHelper.GiveItem(user, recipe.Result.ItemId, recipe.Result.Amount); user.AddToVar(Stats.ItemsCrafted); return(true); }
public static void UpdateRecipeStatus(ArcadeUser user, Recipe recipe) { if (CanCraft(user, recipe)) { SetRecipeStatus(user, recipe, RecipeStatus.Known); } }
public static long BoostValue(ArcadeUser user, long value, BoostType type, bool isNegative = false) { float rate = 1; if (user.Boosters.Count == 0) { return(value); } var toRemove = new List <BoostData>(); foreach (BoostData booster in user.Boosters) { if (!CanApplyBooster(booster)) { toRemove.Add(booster); } if (booster.Type != type) { continue; } rate += booster.Rate; if (booster.UsesLeft.HasValue && --booster.UsesLeft <= 0) { toRemove.Add(booster); } } RemoveBoosts(user, ref toRemove); return(BoostConvert.GetValue(value, rate, isNegative)); }
private static IEnumerable <Merit> GetVisible(ArcadeUser user, string query) { bool isNumber = int.TryParse(query, out int number); Func <Merit, bool> comparer; if (!isNumber && Enum.TryParse(query, true, out MeritTag tag)) { comparer = x => x.Tag.HasFlag(tag); } else if (!isNumber && Enum.TryParse(query, true, out MeritRank rank)) { comparer = x => x.Rank == rank; } else { comparer = query switch { "hidden" => m => m.Hidden, "all" => m => true, _ => null }; } return(Assets.Merits.Where(x => CanView(user, x) && (comparer?.Invoke(x) ?? false))); }
public static string View(ArcadeUser user) { Var.SetIfEmpty(user, Stats.QuestCapacity, DefaultQuestCapacity); var result = new StringBuilder(); result.AppendLine("> 🧧 **Objectives**"); result.AppendLine("> View your currently assigned tasks."); int i = 0; foreach (QuestData data in user.Quests) { Quest quest = GetQuest(data.Id); result.AppendLine($"\n> **Slot {i + 1}: {quest.Name}** ({GetProgress(data)})"); if (Check.NotNull(quest.Summary)) { result.AppendLine($"> {quest.Summary}"); } i++; } if (i == 0) { result.AppendLine($"> {Icons.Warning} You do not have any currently assigned objectives."); } return(result.ToString()); }
public static string ViewAllTimers(ArcadeUser user) { var details = new StringBuilder(); // Cooldowns are for daily, objective assign, objective skip, and item usage cooldowns IEnumerable <string> cooldowns = GetCooldownList(user); IEnumerable <string> expiry = GetExpiryList(user); if (!cooldowns.Any() && !expiry.Any()) { details.AppendLine($"> 🕘 **Cooldowns**"); details.Append("> You don't have any pending cooldowns or expiration timers."); } else if (expiry.Any() && !cooldowns.Any()) { details.AppendLine($"> 💀 **Expiry**"); details.AppendJoin("\n", expiry); } else if (!expiry.Any() && cooldowns.Any()) { details.AppendLine($"> 🕘 **Cooldowns**"); details.AppendJoin("\n", cooldowns); } else { details.AppendLine($"> 🕘 **Cooldowns**"); details.AppendJoin("\n", cooldowns); details.AppendLine($"\n\n> 💀 **Expiry**"); details.AppendJoin("\n", expiry); } return(details.ToString()); }
public static bool IsOfferValid(ArcadeUser author, ArcadeUser target, TradeOffer offer) { if (DateTime.UtcNow - offer.CreatedAt >= TimeSpan.FromHours(24)) { return(false); } foreach ((string itemId, int amount) in offer.ItemIds) { if (ItemHelper.GetOwnedAmount(author, itemId) < amount) { return(false); } } foreach ((string itemId, int amount) in offer.RequestedItemIds) { if (ItemHelper.GetOwnedAmount(target, itemId) < amount) { return(false); } } return(true); }
public static void SetCooldown(ArcadeUser user, string id, TimeSpan duration) { if (!user.InternalCooldowns.TryAdd(id, DateTime.UtcNow.Add(duration))) { user.InternalCooldowns[id] = user.InternalCooldowns[id].Add(duration); } }
public static void UpdateKnownRecipes(ArcadeUser user) { foreach (Recipe recipe in Assets.Recipes.Where(x => CanCraft(user, x))) { SetRecipeStatus(user, recipe, RecipeStatus.Known); } }
// 35 / 25 => 1.23 public static string GetRandomStat(ArcadeUser user, IEnumerable <string> chosen) => Randomizer.ChooseOrDefault(user.Stats.Keys.Where(x => user.GetVar(x) != 0 && !x.EqualsAny(Vars.Balance, Vars.Debt, Vars.Chips, Vars.Tokens) && Var.TypeOf(x) == VarType.Stat && !ItemHelper.Exists(Var.GetGroup(x)) && !ShopHelper.Exists(Var.GetGroup(x)) && (Check.NotNullOrEmpty(chosen) ? !chosen.Contains(x) : true)));
private static bool MeetsCriteria(CasinoReply reply, ArcadeUser user, ICasinoResult result) { if (reply.Criteria == null) { return(true); } return(reply.Criteria(user, result)); }
private static bool IsValidQuery(ArcadeUser user, string query) { if (string.IsNullOrWhiteSpace(query)) { return(false); } return(GetQueryValues(user).Contains(query)); }
public static Merit GetNewestUnlocked(ArcadeUser user) { if (user.Merits.Count == 0) { return(null); } return(GetMerit(user.Merits.OrderByDescending(x => x.Value.AchievedAt).First().Key)); }
private string WriteOnCancel(ArcadeUser invoker) { if (LastState == TradeState.Invite && invoker.Equals(Participant)) { return($"> 💢 **Sorry.**\n> **{Participant.Username}** has denied the invitation to trade."); } return($"> 💢 **Oops!**\n> **{invoker.Username}** has cancelled the trade."); }
public static void SetRecipeStatus(ArcadeUser user, Recipe recipe, RecipeStatus status) { if (GetRecipeStatus(user, recipe) >= status) { return; } user.SetVar(GetRecipeId(recipe), (long)status); }
public static bool CanAssign(ArcadeUser user, Quest quest) { if (!CanAssign(user)) { return(false); } return(quest.ToAssign == null || quest.ToAssign(user)); }
public static string ViewMerit(Merit merit, ArcadeUser user = null) { var info = new StringBuilder(); bool allowTooltips = user?.Config?.Tooltips ?? true; bool hasUnlocked = user != null && HasUnlocked(user, merit); if (merit.Criteria == null) { info.AppendLine(Format.Warning("This is an exclusive merit.")); } if (allowTooltips) { var tooltips = new List <string>(); if (user != null && CanClaim(user, merit)) { tooltips.Add($"Type `claim {merit.Id}` to claim this merit."); } if (merit.Hidden) { tooltips.Add("This merit is excluded from completion progress."); } info.AppendLine(Format.Tooltip(tooltips)); } if (merit.Criteria == null || (allowTooltips && (merit.Hidden || user != null && CanClaim(user, merit)))) { info.AppendLine(); } info.AppendLine(GetPreview(merit)); string quote = GetQuote(merit, hasUnlocked); if (Check.NotNull(quote)) { info.AppendLine(quote); } if (hasUnlocked) { info.AppendLine($"> Unlocked: {Format.FullTime(user.Merits[merit.Id].AchievedAt, '.')}"); } info.AppendLine($"> Rank: **{merit.Rank.ToString()}**"); if (merit.Reward != null) { info.Append(ViewReward(merit.Reward, hasUnlocked && user.Merits[merit.Id]?.IsClaimed == true)); } return(info.ToString()); }
internal ArcadeUser GetOrAddUser(IUser user) { if (!Data.Users.TryGet(user.Id, out ArcadeUser value)) { value = new ArcadeUser(user); Data.Users.AddOrUpdate(user.Id, value); } return(value); }
private static QuestData GetSlot(ArcadeUser user, int index, bool clamp = true) { if (clamp) { int capacity = (int)Var.GetOrSet(user, Stats.QuestCapacity, DefaultQuestCapacity); index = index < 0 ? 0 : index >= capacity ? capacity - 1 : index; } return(user.Quests.ElementAtOrDefault(index)); }
public static void Assign(ArcadeUser user, Quest quest) { Var.SetIfEmpty(user, Stats.QuestCapacity, DefaultQuestCapacity); if (!CanAssign(user, quest)) { return; } user.Quests.Add(new QuestData(quest)); }
public static bool RemovePalette(ArcadeUser user) { if (user.Card.Palette == PaletteType.Default) { return(false); } GiveItem(user, IdFor(user.Card.Palette.Primary, user.Card.Palette.Secondary)); user.Card.Palette = PaletteType.Default; return(true); }
public static string DeclineOffer(ArcadeUser user, ArcadeUser author, TradeOffer offer) { if (offer.Author.Id != author.Id) { throw new Exception("Expected author to match offer author"); } user.Offers.RemoveAll(x => x.Id == offer.Id); author.Offers.RemoveAll(x => x.Id == offer.Id); return($"Successfully {(offer.Type == OfferType.Inbound ? "declined" : "canceled the pending")} offer `{offer.Id}`{(offer.Type == OfferType.Inbound ? $"from **{author.Username}**" : "")}."); }
public static long GetScore(ArcadeUser user) { long score = 0; foreach (string id in user.Merits.Keys) { Merit merit = GetMerit(id); score += merit.Score; } return(score); }
public TradeSession(ArcadeContext context, ArcadeUser participant) { Context = context; LastState = null; State = TradeState.Invite; CurrentId = null; Host = Context.Account; Participant = participant; HostReady = ParticipantReady = false; HostOffer = new Dictionary <string, int>(); ParticipantOffer = new Dictionary <string, int>(); }
public static string WriteFor(ArcadeUser user, string query, int page = 0, int pageSize = 15) { VarGroup group = Var.GetGroupDefiner(query); if (group == null) { return(Format.Warning("Unable to find the specified stat group.")); } var result = new StringBuilder(); if (group.Writer != null) { result.AppendLine($"> **Stats: {group.Name}**"); result.AppendLine(group.Writer.Invoke(user)); return(result.ToString()); } var stats = GetGroupStats(user, group.Id).ToList(); int pageCount = Paginate.GetPageCount(stats.Count, pageSize); page = Paginate.ClampIndex(page, pageCount); string counter = null; if (pageCount > 1) { counter = $" ({Format.PageCount(page + 1, pageCount)})"; } result.AppendLine($"> **Stats: {group.Name}**{counter}"); int i = 0; foreach ((string id, long value) in Paginate.GroupAt(stats, page, pageSize)) { if (i >= pageSize) { break; } result.AppendLine($"`{id}`: {value}"); i++; } if (i == 0) { result.AppendLine("An invalid group was specified or an unknown error has occurred."); } return(result.ToString()); }
private static string WriteLastUnlocked(ArcadeUser user) { Merit merit = GetNewestUnlocked(user); if (merit == null) { return($"The directory of all known milestones."); } string icon = Check.NotNull(merit.Icon) ? $"{merit.Icon}" : "•"; return($"Last Unlocked: {icon} **{merit.Name}** (**{merit.Score:##,0}**m)"); }
public ItemCatalog GetOrGenerateCatalog(Shop shop, ArcadeUser user = null) { if (Catalogs.ContainsKey(shop.Id) && DateTime.UtcNow.DayOfYear - Catalogs[shop.Id].GeneratedAt.DayOfYear == 0) { var catalog = new ItemCatalog(Catalogs[shop.Id]); if (user == null || !user.CatalogHistory.ContainsKey(shop.Id)) { return(catalog); } var toRemoveIds = new List <string>(); foreach ((string itemId, int amount) in user.CatalogHistory[shop.Id].PurchasedIds) { if (amount <= 0) { toRemoveIds.Add(itemId); continue; } if (catalog.ItemIds.ContainsKey(itemId)) { catalog.ItemIds[itemId] -= amount; if (catalog.ItemIds[itemId] <= 0) { catalog.ItemIds.Remove(itemId); } } } foreach (string removeId in toRemoveIds) { user.CatalogHistory[shop.Id].PurchasedIds.Remove(removeId); } return(catalog); } Catalogs[shop.Id] = shop.Catalog.Generate(Var.GetOrSet(user, ShopHelper.GetTierId(shop.Id), 1)); if (user != null && user.CatalogHistory.ContainsKey(shop.Id)) { user.CatalogHistory[shop.Id].Clear(); } return(new ItemCatalog(Catalogs[shop.Id])); }