More common refactorings like renaming variables, removing empty statements and unused variables, etc

This commit is contained in:
Kwoth
2022-01-09 16:46:08 +01:00
parent 2ce3262d59
commit f07a855912
75 changed files with 447 additions and 465 deletions

View File

@@ -36,7 +36,7 @@ public partial class Gambling
[NadekoOptionsAttribute(typeof(RaceOptions))]
public partial Task Race(params string[] args)
{
var (options, success) = OptionsParser.ParseFrom(new RaceOptions(), args);
var (options, _) = OptionsParser.ParseFrom(new RaceOptions(), args);
var ar = new AnimalRace(options, _cs, _gamesConf.Data.RaceAnimals.Shuffle());
if (!_service.AnimalRaces.TryAdd(ctx.Guild.Id, ar))
@@ -46,7 +46,7 @@ public partial class Gambling
var count = 0;
Task _client_MessageReceived(SocketMessage arg)
Task ClientMessageReceived(SocketMessage arg)
{
_= Task.Run(() =>
{
@@ -61,9 +61,9 @@ public partial class Gambling
return Task.CompletedTask;
}
Task Ar_OnEnded(AnimalRace race)
Task ArOnEnded(AnimalRace race)
{
_client.MessageReceived -= _client_MessageReceived;
_client.MessageReceived -= ClientMessageReceived;
_service.AnimalRaces.TryRemove(ctx.Guild.Id, out _);
var winner = race.FinishedUsers[0];
if (race.FinishedUsers[0].Bet > 0)
@@ -77,9 +77,9 @@ public partial class Gambling
ar.OnStartingFailed += Ar_OnStartingFailed;
ar.OnStateUpdate += Ar_OnStateUpdate;
ar.OnEnded += Ar_OnEnded;
ar.OnEnded += ArOnEnded;
ar.OnStarted += Ar_OnStarted;
_client.MessageReceived += _client_MessageReceived;
_client.MessageReceived += ClientMessageReceived;
return SendConfirmAsync(GetText(strs.animal_race),
GetText(strs.animal_race_starting(options.StartTime)),

View File

@@ -34,7 +34,7 @@ public partial class Gambling
if (!await CheckBetMandatory(amount))
return;
var newBj = new Blackjack(_cs, _db);
var newBj = new Blackjack(_cs);
Blackjack bj;
if (newBj == (bj = _service.Games.GetOrAdd(ctx.Channel.Id, newBj)))
{

View File

@@ -21,16 +21,14 @@ public class Blackjack
public GameState State { get; set; } = GameState.Starting;
public User CurrentUser { get; private set; }
private TaskCompletionSource<bool> _currentUserMove;
private TaskCompletionSource<bool> currentUserMove;
private readonly ICurrencyService _cs;
private readonly DbService _db;
private readonly SemaphoreSlim _locker = new(1, 1);
public Blackjack(ICurrencyService cs, DbService db)
public Blackjack(ICurrencyService cs)
{
_cs = cs;
_db = db;
Dealer = new();
}
@@ -58,7 +56,7 @@ public class Blackjack
if (!Players.Any())
{
State = GameState.Ended;
var end = GameEnded?.Invoke(this);
_ = GameEnded?.Invoke(this);
return;
}
@@ -101,14 +99,14 @@ public class Blackjack
{
var pause = Task.Delay(20000); //10 seconds to decide
CurrentUser = usr;
_currentUserMove = new();
currentUserMove = new();
await PrintState();
// either wait for the user to make an action and
// if he doesn't - stand
var finished = await Task.WhenAny(pause, _currentUserMove.Task);
var finished = await Task.WhenAny(pause, currentUserMove.Task);
if (finished == pause) await Stand(usr);
CurrentUser = null;
_currentUserMove = null;
currentUserMove = null;
}
public async Task<bool> Join(IUser user, long bet)
@@ -156,7 +154,7 @@ public class Blackjack
return false;
u.State = User.UserState.Stand;
_currentUserMove.TrySetResult(true);
currentUserMove.TrySetResult(true);
return true;
}
finally
@@ -252,7 +250,7 @@ public class Blackjack
else
//with double you just get one card, and then you're done
u.State = User.UserState.Stand;
_currentUserMove.TrySetResult(true);
currentUserMove.TrySetResult(true);
return true;
}
@@ -292,7 +290,7 @@ public class Blackjack
// user busted
u.State = User.UserState.Bust;
_currentUserMove.TrySetResult(true);
currentUserMove.TrySetResult(true);
return true;
}

View File

@@ -59,7 +59,7 @@ public sealed class Connect4Game : IDisposable
private readonly ICurrencyService _cs;
private readonly NadekoRandom _rng;
private Timer _playerTimeoutTimer;
private Timer playerTimeoutTimer;
/* [ ][ ][ ][ ][ ][ ]
* [ ][ ][ ][ ][ ][ ]
@@ -133,7 +133,7 @@ public sealed class Connect4Game : IDisposable
}
CurrentPhase = Phase.P1Move; //start the game
_playerTimeoutTimer = new(async _ =>
playerTimeoutTimer = new(async _ =>
{
await _locker.WaitAsync();
try
@@ -330,7 +330,7 @@ public sealed class Connect4Game : IDisposable
}
private void ResetTimer()
=> _playerTimeoutTimer.Change(TimeSpan.FromSeconds(_options.TurnTimer),
=> playerTimeoutTimer.Change(TimeSpan.FromSeconds(_options.TurnTimer),
TimeSpan.FromSeconds(_options.TurnTimer));
private void EndGame(Result result, ulong? winId)
@@ -369,7 +369,7 @@ public sealed class Connect4Game : IDisposable
OnGameFailedToStart = null;
OnGameStateUpdated = null;
OnGameEnded = null;
_playerTimeoutTimer?.Change(Timeout.Infinite, Timeout.Infinite);
playerTimeoutTimer?.Change(Timeout.Infinite, Timeout.Infinite);
}

View File

@@ -11,19 +11,19 @@ public partial class Gambling
[Group]
public partial class Connect4Commands : GamblingSubmodule<GamblingService>
{
private static readonly string[] numbers =
private static readonly string[] _numbers =
{
":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:"
};
private int RepostCounter
{
get => _repostCounter;
get => repostCounter;
set
{
if (value is < 0 or > 7)
_repostCounter = 0;
else _repostCounter = value;
repostCounter = 0;
else repostCounter = value;
}
}
@@ -32,7 +32,7 @@ public partial class Gambling
private IUserMessage msg;
private int _repostCounter;
private int repostCounter;
public Connect4Commands(DiscordSocketClient client, ICurrencyService cs, GamblingConfigService gamb)
: base(gamb)
@@ -59,7 +59,7 @@ public partial class Gambling
newGame.Dispose();
//means game already exists, try to join
var joined = await game.Join(ctx.User.Id, ctx.User.ToString(), options.Bet);
await game.Join(ctx.User.Id, ctx.User.ToString(), options.Bet);
return;
}
@@ -73,9 +73,9 @@ public partial class Gambling
}
game.OnGameStateUpdated += Game_OnGameStateUpdated;
game.OnGameFailedToStart += Game_OnGameFailedToStart;
game.OnGameEnded += Game_OnGameEnded;
_client.MessageReceived += _client_MessageReceived;
game.OnGameFailedToStart += GameOnGameFailedToStart;
game.OnGameEnded += GameOnGameEnded;
_client.MessageReceived += ClientMessageReceived;
game.Initialize();
if (options.Bet == 0)
@@ -83,7 +83,7 @@ public partial class Gambling
else
await ReplyErrorLocalizedAsync(strs.connect4_created_bet(options.Bet + CurrencySign));
Task _client_MessageReceived(SocketMessage arg)
Task ClientMessageReceived(SocketMessage arg)
{
if (ctx.Channel.Id != arg.Channel.Id)
return Task.CompletedTask;
@@ -110,22 +110,22 @@ public partial class Gambling
return Task.CompletedTask;
}
Task Game_OnGameFailedToStart(Connect4Game arg)
Task GameOnGameFailedToStart(Connect4Game arg)
{
if (_service.Connect4Games.TryRemove(ctx.Channel.Id, out var toDispose))
{
_client.MessageReceived -= _client_MessageReceived;
_client.MessageReceived -= ClientMessageReceived;
toDispose.Dispose();
}
return ErrorLocalizedAsync(strs.connect4_failed_to_start);
}
Task Game_OnGameEnded(Connect4Game arg, Connect4Game.Result result)
Task GameOnGameEnded(Connect4Game arg, Connect4Game.Result result)
{
if (_service.Connect4Games.TryRemove(ctx.Channel.Id, out var toDispose))
{
_client.MessageReceived -= _client_MessageReceived;
_client.MessageReceived -= ClientMessageReceived;
toDispose.Dispose();
}
@@ -185,7 +185,7 @@ public partial class Gambling
sb.AppendLine();
}
for (var i = 0; i < Connect4Game.NUMBER_OF_COLUMNS; i++) sb.Append(numbers[i]);
for (var i = 0; i < Connect4Game.NUMBER_OF_COLUMNS; i++) sb.Append(_numbers[i]);
return sb.ToString();
}
}

View File

@@ -11,10 +11,10 @@ public partial class Gambling
[Group]
public partial class DiceRollCommands : NadekoSubmodule
{
private static readonly Regex dndRegex = new(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$",
private static readonly Regex _dndRegex = new(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$",
RegexOptions.Compiled);
private static readonly Regex fudgeRegex = new(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private static readonly Regex _fudgeRegex = new(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private static readonly char[] _fateRolls = { '-', ' ', '+' };
private readonly IImageCache _images;
@@ -115,7 +115,7 @@ public partial class Gambling
private async Task InternallDndRoll(string arg, bool ordered)
{
Match match;
if ((match = fudgeRegex.Match(arg)).Length != 0
if ((match = _fudgeRegex.Match(arg)).Length != 0
&& int.TryParse(match.Groups["n1"].ToString(), out var n1)
&& n1 is > 0 and < 500)
{
@@ -134,7 +134,7 @@ public partial class Gambling
await ctx.Channel.EmbedAsync(embed);
}
else if ((match = dndRegex.Match(arg)).Length != 0)
else if ((match = _dndRegex.Match(arg)).Length != 0)
{
var rng = new NadekoRandom();
if (int.TryParse(match.Groups["n1"].ToString(), out n1)

View File

@@ -117,7 +117,7 @@ public class GameStatusEvent : ICurrencyEvent
private async Task OnMessageDeleted(Cacheable<IMessage, ulong> message, Cacheable<IMessageChannel, ulong> cacheable)
{
if (message.Id == this.msg.Id) await StopEvent();
if (message.Id == msg.Id) await StopEvent();
}
public async Task StopEvent()

View File

@@ -99,11 +99,11 @@ public class ReactionEvent : ICurrencyEvent
public async Task StartEvent()
{
if (Emote.TryParse(_config.Currency.Sign, out var parsedEmote))
this.emote = parsedEmote;
emote = parsedEmote;
else
this.emote = new Emoji(_config.Currency.Sign);
emote = new Emoji(_config.Currency.Sign);
msg = await _channel.EmbedAsync(GetEmbed(_opts.PotSize));
await msg.AddReactionAsync(this.emote);
await msg.AddReactionAsync(emote);
_client.MessageDeleted += OnMessageDeleted;
_client.ReactionAdded += HandleReaction;
_t.Change(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));
@@ -114,7 +114,7 @@ public class ReactionEvent : ICurrencyEvent
private async Task OnMessageDeleted(Cacheable<IMessage, ulong> message, Cacheable<IMessageChannel, ulong> cacheable)
{
if (message.Id == this.msg.Id) await StopEvent();
if (message.Id == msg.Id) await StopEvent();
}
public async Task StopEvent()
@@ -151,7 +151,7 @@ public class ReactionEvent : ICurrencyEvent
if ((r.User.IsSpecified
? r.User.Value
: null) is not IGuildUser gu // no unknown users, as they could be bots, or alts
|| message.Id != this.msg.Id // same message
|| message.Id != msg.Id // same message
|| gu.IsBot // no bots
|| (DateTime.UtcNow - gu.CreatedAt).TotalDays <= 5 // no recently created accounts
|| (_noRecentlyJoinedServer

View File

@@ -22,7 +22,7 @@ public partial class Gambling
Tails = 2
}
private static readonly NadekoRandom rng = new();
private static readonly NadekoRandom _rng = new();
private readonly IImageCache _images;
private readonly ICurrencyService _cs;
@@ -47,9 +47,9 @@ public partial class Gambling
var imgs = new Image<Rgba32>[count];
for (var i = 0; i < count; i++)
{
var headsArr = _images.Heads[rng.Next(0, _images.Heads.Count)];
var tailsArr = _images.Tails[rng.Next(0, _images.Tails.Count)];
if (rng.Next(0, 10) < 5)
var headsArr = _images.Heads[_rng.Next(0, _images.Heads.Count)];
var tailsArr = _images.Tails[_rng.Next(0, _images.Tails.Count)];
if (_rng.Next(0, 10) < 5)
{
imgs[i] = Image.Load(headsArr);
headCount++;
@@ -90,21 +90,21 @@ public partial class Gambling
BetFlipGuess result;
Uri imageToSend;
var coins = _images.ImageUrls.Coins;
if (rng.Next(0, 1000) <= 499)
if (_rng.Next(0, 1000) <= 499)
{
imageToSend = coins.Heads[rng.Next(0, coins.Heads.Length)];
imageToSend = coins.Heads[_rng.Next(0, coins.Heads.Length)];
result = BetFlipGuess.Heads;
}
else
{
imageToSend = coins.Tails[rng.Next(0, coins.Tails.Length)];
imageToSend = coins.Tails[_rng.Next(0, coins.Tails.Length)];
result = BetFlipGuess.Tails;
}
string str;
if (guess == result)
{
var toWin = (long)(amount * _config.BetFlip.Multiplier);
var toWin = (long)(amount * Config.BetFlip.Multiplier);
str = Format.Bold(ctx.User.ToString()) + " " + GetText(strs.flip_guess(toWin + CurrencySign));
await _cs.AddAsync(ctx.User, "Betflip Gamble", toWin, false, true);
}

View File

@@ -100,8 +100,8 @@ public partial class Gambling : GamblingModule<GamblingService>
[Cmd]
public async partial Task Timely()
{
var val = _config.Timely.Amount;
var period = _config.Timely.Cooldown;
var val = Config.Timely.Amount;
var period = Config.Timely.Cooldown;
if (val <= 0 || period <= 0)
{
await ReplyErrorLocalizedAsync(strs.timely_none);
@@ -473,7 +473,7 @@ public partial class Gambling : GamblingModule<GamblingService>
return;
}
var br = new Betroll(_config.BetRoll);
var br = new Betroll(Config.BetRoll);
var result = br.Roll();
@@ -617,7 +617,7 @@ public partial class Gambling : GamblingModule<GamblingService>
|| (pick == RpsPick.Rock && nadekoPick == RpsPick.Scissors)
|| (pick == RpsPick.Scissors && nadekoPick == RpsPick.Paper))
{
amount = (long)(amount * _config.BetFlip.Multiplier);
amount = (long)(amount * Config.BetFlip.Multiplier);
await _cs.AddAsync(ctx.User.Id, "Rps-win", amount, true);
embed.WithOkColor();
embed.AddField(GetText(strs.won), n(amount));

View File

@@ -6,11 +6,12 @@ namespace NadekoBot.Modules.Gambling.Services;
public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
{
private const string FilePath = "data/gambling.yml";
private static readonly TypedKey<GamblingConfig> changeKey = new("config.gambling.updated");
public override string Name { get; } = "gambling";
private const string FILE_PATH = "data/gambling.yml";
private static readonly TypedKey<GamblingConfig> _changeKey = new("config.gambling.updated");
public override string Name
=> "gambling";
private readonly IEnumerable<WaifuItemModel> antiGiftSeed = new[]
private readonly IEnumerable<WaifuItemModel> _antiGiftSeed = new[]
{
new WaifuItemModel("🥀", 100, "WiltedRose", true), new WaifuItemModel("✂️", 1000, "Haircut", true),
new WaifuItemModel("🧻", 10000, "ToiletPaper", true)
@@ -18,7 +19,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
public GamblingConfigService(IConfigSeria serializer, IPubSub pubSub)
: base(FilePath, serializer, pubSub, changeKey)
: base(FILE_PATH, serializer, pubSub, _changeKey)
{
AddParsedProp("currency.name", gs => gs.Currency.Name, ConfigParsers.String, ConfigPrinters.ToString);
AddParsedProp("currency.sign", gs => gs.Currency.Sign, ConfigParsers.String, ConfigPrinters.ToString);
@@ -104,7 +105,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
if (data.Version < 2)
ModifyConfig(c =>
{
c.Waifu.Items = c.Waifu.Items.Concat(antiGiftSeed).ToList();
c.Waifu.Items = c.Waifu.Items.Concat(_antiGiftSeed).ToList();
c.Version = 2;
});

View File

@@ -5,14 +5,14 @@ namespace NadekoBot.Modules.Gambling.Common;
public abstract class GamblingModule<TService> : NadekoModule<TService>
{
protected GamblingConfig _config
protected GamblingConfig Config
=> _lazyConfig.Value;
protected string CurrencySign
=> _config.Currency.Sign;
=> Config.Currency.Sign;
protected string CurrencyName
=> _config.Currency.Name;
=> Config.Currency.Name;
private readonly Lazy<GamblingConfig> _lazyConfig;
@@ -22,15 +22,15 @@ public abstract class GamblingModule<TService> : NadekoModule<TService>
private async Task<bool> InternalCheckBet(long amount)
{
if (amount < 1) return false;
if (amount < _config.MinBet)
if (amount < Config.MinBet)
{
await ReplyErrorLocalizedAsync(strs.min_bet_limit(Format.Bold(_config.MinBet.ToString()) + CurrencySign));
await ReplyErrorLocalizedAsync(strs.min_bet_limit(Format.Bold(Config.MinBet.ToString()) + CurrencySign));
return false;
}
if (_config.MaxBet > 0 && amount > _config.MaxBet)
if (Config.MaxBet > 0 && amount > Config.MaxBet)
{
await ReplyErrorLocalizedAsync(strs.max_bet_limit(Format.Bold(_config.MaxBet.ToString()) + CurrencySign));
await ReplyErrorLocalizedAsync(strs.max_bet_limit(Format.Bold(Config.MaxBet.ToString()) + CurrencySign));
return false;
}

View File

@@ -9,11 +9,11 @@ public partial class Gambling
[Group]
public partial class PlantPickCommands : GamblingSubmodule<PlantPickService>
{
private readonly ILogCommandService logService;
private readonly ILogCommandService _logService;
public PlantPickCommands(ILogCommandService logService, GamblingConfigService gss)
: base(gss)
=> this.logService = logService;
=> this._logService = logService;
[Cmd]
[RequireContext(ContextType.Guild)]
@@ -32,7 +32,7 @@ public partial class Gambling
if (((SocketGuild)ctx.Guild).CurrentUser.GuildPermissions.ManageMessages)
try
{
logService.AddDeleteIgnore(ctx.Message.Id);
_logService.AddDeleteIgnore(ctx.Message.Id);
await ctx.Message.DeleteAsync();
}
catch { }
@@ -49,7 +49,7 @@ public partial class Gambling
if (((SocketGuild)ctx.Guild).CurrentUser.GuildPermissions.ManageMessages)
{
logService.AddDeleteIgnore(ctx.Message.Id);
_logService.AddDeleteIgnore(ctx.Message.Id);
await ctx.Message.DeleteAsync();
}
@@ -90,7 +90,7 @@ public partial class Gambling
return ctx.SendPaginatedConfirmAsync(page,
_ =>
{
var items = enabledIn.Skip(page * 9).Take(9);
var items = enabledIn.Skip(page * 9).Take(9).ToList();
if (!items.Any())
return _eb.Create().WithErrorColor().WithDescription("-");

View File

@@ -154,7 +154,7 @@ public partial class Gambling
{
await using (var uow = _db.GetDbContext())
{
var x = uow.Set<ShopEntryItem>().Remove(item);
uow.Set<ShopEntryItem>().Remove(item);
uow.SaveChanges();
}

View File

@@ -18,8 +18,8 @@ public partial class Gambling
[Group]
public partial class SlotCommands : GamblingSubmodule<GamblingService>
{
private static long _totalBet;
private static long _totalPaidOut;
private static long totalBet;
private static long totalPaidOut;
private static readonly HashSet<ulong> _runningUsers = new();
@@ -28,7 +28,7 @@ public partial class Gambling
//thanks to judge for helping me with this
private readonly IImageCache _images;
private FontProvider _fonts;
private readonly FontProvider _fonts;
private readonly DbService _db;
public SlotCommands(
@@ -51,8 +51,8 @@ public partial class Gambling
public async partial Task SlotStats()
{
//i remembered to not be a moron
var paid = _totalPaidOut;
var bet = _totalBet;
var paid = totalPaidOut;
var bet = totalBet;
if (bet <= 0)
bet = 1;
@@ -120,8 +120,8 @@ public partial class Gambling
return;
}
Interlocked.Add(ref _totalBet, amount);
Interlocked.Add(ref _totalPaidOut, result.Won);
Interlocked.Add(ref totalBet, amount);
Interlocked.Add(ref totalPaidOut, result.Won);
long ownedAmount;
await using (var uow = _db.GetDbContext())
@@ -130,12 +130,12 @@ public partial class Gambling
?? 0;
}
using (var bgImage = Image.Load<Rgba32>(_images.SlotBackground, out var format))
using (var bgImage = Image.Load<Rgba32>(_images.SlotBackground, out _))
{
var numbers = new int[3];
result.Rolls.CopyTo(numbers, 0);
Color fontColor = _config.Slots.CurrencyFontColor;
Color fontColor = Config.Slots.CurrencyFontColor;
bgImage.Mutate(x => x.DrawText(new()
{

View File

@@ -100,7 +100,7 @@ public class VoteRewardService : INService, IReadyExecutor
}
catch (Exception ex)
{
Log.Error(ex, "Critical error loading discords.com vote rewards.");
Log.Error(ex, "Critical error loading discords.com vote rewards");
}
}
}

View File

@@ -39,9 +39,9 @@ public partial class Gambling
[RequireContext(ContextType.Guild)]
public async partial Task WaifuClaim(int amount, [Leftover] IUser target)
{
if (amount < _config.Waifu.MinPrice)
if (amount < Config.Waifu.MinPrice)
{
await ReplyErrorLocalizedAsync(strs.waifu_isnt_cheap(_config.Waifu.MinPrice + CurrencySign));
await ReplyErrorLocalizedAsync(strs.waifu_isnt_cheap(Config.Waifu.MinPrice + CurrencySign));
return;
}
@@ -278,7 +278,7 @@ public partial class Gambling
[Priority(1)]
public async partial Task WaifuGift(int page = 1)
{
if (--page < 0 || page > (_config.Waifu.Items.Count - 1) / 9)
if (--page < 0 || page > (Config.Waifu.Items.Count - 1) / 9)
return;
var waifuItems = _service.GetWaifuItems();
@@ -294,7 +294,7 @@ public partial class Gambling
.ToList()
.ForEach(x => embed.AddField(
$"{(!x.Negative ? string.Empty : "\\💔")} {x.ItemEmoji} {x.Name}",
Format.Bold(x.Price.ToString()) + _config.Currency.Sign,
Format.Bold(x.Price.ToString()) + Config.Currency.Sign,
true));
return embed;

View File

@@ -37,7 +37,7 @@ public partial class Gambling
var result = await _service.WheelOfFortuneSpinAsync(ctx.User.Id, amount);
var wofMultipliers = _config.WheelOfFortune.Multipliers;
var wofMultipliers = Config.WheelOfFortune.Multipliers;
await SendConfirmAsync(Format.Bold($@"{ctx.User.ToString()} won: {result.Amount + CurrencySign}
『{wofMultipliers[1]}』 『{wofMultipliers[0]}』 『{wofMultipliers[7]}』

View File

@@ -28,7 +28,7 @@ public class Deck
{ 13, "King" }
};
private static Dictionary<string, Func<List<Card>, bool>> _handValues;
private static Dictionary<string, Func<List<Card>, bool>> handValues;
public List<Card> CardPool { get; set; }
private readonly Random _r = new NadekoRandom();
@@ -176,7 +176,7 @@ public class Deck
return HasStraightFlush(cards) && !IsRoyalFlush(cards);
}
_handValues = new()
handValues = new()
{
{ "Royal Flush", IsRoyalFlush },
{ "Straight Flush", IsStraightFlush },
@@ -192,9 +192,10 @@ public class Deck
public static string GetHandValue(List<Card> cards)
{
if (_handValues is null)
if (handValues is null)
InitHandValues();
foreach (var kvp in _handValues.Where(x => x.Value(cards))) return kvp.Key;
foreach (var kvp in handValues.Where(x => x.Value(cards))) return kvp.Key;
return "High card " + (cards.FirstOrDefault(c => c.Number == 1)?.GetValueText() ?? cards.Max().GetValueText());
}