- More code cleanup and codestyle updates

- Fixed some possible nullref exceptions
- Methods signatures now have up to 3 parameters before breakaing down each parameter in a separate line
- Method invocations have the same rule, except the first parameter will be in the same line as the invocation to prevent some ugliness when passing lambas as arguments
- Applied many more codestyles
- Extensions folder fully reformatted
This commit is contained in:
Kwoth
2021-12-26 17:28:39 +01:00
parent b85ba177cd
commit d5fd6aae8e
217 changed files with 1017 additions and 1494 deletions

View File

@@ -89,7 +89,7 @@ public partial class Gambling
dealerIcon = "🏁 ";
}
var cStr = string.Concat(c.Select(x => x.Substring(0, x.Length - 1) + " "));
var cStr = string.Concat(c.Select(x => x[..^1] + " "));
cStr += "\n" + string.Concat(c.Select(x => x.Last() + " "));
var embed = _eb.Create()
.WithOkColor()
@@ -104,7 +104,7 @@ public partial class Gambling
foreach (var p in bj.Players)
{
c = p.Cards.Select(x => x.GetEmojiString());
cStr = "-\t" + string.Concat(c.Select(x => x.Substring(0, x.Length - 1) + " "));
cStr = "-\t" + string.Concat(c.Select(x => x[..^1] + " "));
cStr += "\n-\t" + string.Concat(c.Select(x => x.Last() + " "));
var full = $"{p.DiscordUser.ToString().TrimTo(20)} | Bet: {p.Bet} | Value: {p.GetHandValue()}";
if (bj.State == Blackjack.GameState.Ended)

View File

@@ -18,14 +18,10 @@ public class AnimalRacingUser
}
public override bool Equals(object obj)
{
return obj is AnimalRacingUser x
=> obj is AnimalRacingUser x
? x.UserId == this.UserId
: false;
}
public override int GetHashCode()
{
return this.UserId.GetHashCode();
}
=> this.UserId.GetHashCode();
}

View File

@@ -9,7 +9,7 @@ public class RaceOptions : INadekoCommandOptions
public void NormalizeOptions()
{
if (this.StartTime < 10 || this.StartTime > 120)
if (this.StartTime is < 10 or > 120)
this.StartTime = 20;
}
}

View File

@@ -203,7 +203,7 @@ public class Blackjack
{
foreach (var usr in Players)
{
if (usr.State == User.UserState.Stand || usr.State == User.UserState.Blackjack)
if (usr.State is User.UserState.Stand or User.UserState.Blackjack)
usr.State = User.UserState.Won;
else
usr.State = User.UserState.Lost;
@@ -226,7 +226,7 @@ public class Blackjack
foreach (var usr in Players)
{
if (usr.State == User.UserState.Won || usr.State == User.UserState.Blackjack)
if (usr.State is User.UserState.Won or User.UserState.Blackjack)
{
await _cs.AddAsync(usr.DiscordUser.Id, "BlackJack-win", usr.Bet * 2, gamble: true).ConfigureAwait(false);
}

View File

@@ -20,9 +20,7 @@ public abstract class Player
}
public int GetRawHandValue()
{
return Cards.Sum(x => x.Number == 1 ? 11 : x.Number >= 10 ? 10 : x.Number);
}
=> Cards.Sum(x => x.Number == 1 ? 11 : x.Number >= 10 ? 10 : x.Number);
}
public class Dealer : Player

View File

@@ -13,16 +13,12 @@ public class CurrencyRaffleGame
public long Amount { get; set; }
public override int GetHashCode()
{
return DiscordUser.GetHashCode();
}
=> DiscordUser.GetHashCode();
public override bool Equals(object obj)
{
return obj is User u
=> obj is User u
? u.DiscordUser == DiscordUser
: false;
}
}
private readonly HashSet<User> _users = new();
@@ -30,9 +26,7 @@ public class CurrencyRaffleGame
public Type GameType { get; }
public CurrencyRaffleGame(Type type)
{
GameType = type;
}
=> GameType = type;
public bool AddUser(IUser usr, long amount)
{

View File

@@ -166,13 +166,11 @@ public class Deck
/// Creates a new instance of the BlackJackGame, this allows you to create multiple games running at one time.
/// </summary>
public Deck()
{
RefillPool();
}
=> RefillPool();
static Deck()
{
InitHandValues();
}
=> InitHandValues();
/// <summary>
/// Restart the game of blackjack. It will only refill the pool for now. Probably wont be used, unless you want to have only 1 bjg running at one time,
/// then you will restart the same game every time.

View File

@@ -1,5 +1,4 @@
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Gambling.Common.Events;
@@ -115,9 +114,7 @@ public class GameStatusEvent : ICurrencyEvent
}
private IEmbedBuilder GetEmbed(long pot)
{
return _embedFunc(CurrencyEvent.Type.GameStatus, _opts, pot);
}
=> _embedFunc(CurrencyEvent.Type.GameStatus, _opts, pot);
private async Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, Cacheable<IMessageChannel, ulong> cacheable)
{

View File

@@ -1,5 +1,4 @@
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Gambling.Common.Events;
@@ -118,9 +117,7 @@ public class ReactionEvent : ICurrencyEvent
}
private IEmbedBuilder GetEmbed(long pot)
{
return _embedFunc(CurrencyEvent.Type.Reaction, _opts, pot);
}
=> _embedFunc(CurrencyEvent.Type.Reaction, _opts, pot);
private async Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, Cacheable<IMessageChannel, ulong> cacheable)
{

View File

@@ -105,14 +105,12 @@ Doesn't have to be ordered.")]
public BetRollPair[] Pairs { get; set; } = Array.Empty<BetRollPair>();
public BetRollConfig()
{
Pairs = new BetRollPair[]
=> Pairs = new BetRollPair[]
{
new() { WhenAbove = 99, MultiplyBy = 10 },
new() { WhenAbove = 90, MultiplyBy = 4 },
new() { WhenAbove = 66, MultiplyBy = 2 }
};
}
}
[Cloneable]
@@ -163,8 +161,7 @@ public partial class WheelOfFortuneSettings
public decimal[] Multipliers { get; set; }
public WheelOfFortuneSettings()
{
Multipliers = new decimal[]
=> Multipliers = new decimal[]
{
1.7M,
1.5M,
@@ -175,7 +172,6 @@ public partial class WheelOfFortuneSettings
1.2M,
2.4M,
};
}
}
[Cloneable]
@@ -191,8 +187,7 @@ If negative is true, gift will instead reduce waifu value.")]
public List<WaifuItemModel> Items { get; set; } = new();
public WaifuConfig()
{
Items = new()
=> Items = new()
{
new("🥔", 5, "Potato"),
new("🍪", 10, "Cookie"),
@@ -231,7 +226,6 @@ If negative is true, gift will instead reduce waifu value.")]
new("🚀", 30000, "Spaceship"),
new("🌕", 50000, "Moon")
};
}
}
[Cloneable]

View File

@@ -10,9 +10,7 @@ public abstract class GamblingModule<TService> : NadekoModule<TService>
protected string CurrencyName => _config.Currency.Name;
protected GamblingModule(GamblingConfigService gambService)
{
_lazyConfig = new(() => gambService.Data);
}
=> _lazyConfig = new(() => gambService.Data);
private async Task<bool> InternalCheckBet(long amount)
{

View File

@@ -151,14 +151,14 @@ public sealed class Connect4Game : IDisposable
try
{
inputCol -= 1;
if (CurrentPhase == Phase.Ended || CurrentPhase == Phase.Joining)
if (CurrentPhase is Phase.Ended or Phase.Joining)
return false;
if (!((_players[0].Value.UserId == userId && CurrentPhase == Phase.P1Move)
|| (_players[1].Value.UserId == userId && CurrentPhase == Phase.P2Move)))
return false;
if (inputCol < 0 || inputCol > NumberOfColumns) //invalid input
if (inputCol is < 0 or > NumberOfColumns) //invalid input
return false;
if (IsColumnFull(inputCol)) //can't play there event?
@@ -259,9 +259,9 @@ public sealed class Connect4Game : IDisposable
var curCol = col - i;
//check if current values are in range
if (curRow >= NumberOfRows || curRow < 0)
if (curRow is >= NumberOfRows or < 0)
break;
if (curCol < 0 || curCol >= NumberOfColumns)
if (curCol is < 0 or >= NumberOfColumns)
break;
var cur = _gameState[curRow + (curCol * NumberOfRows)];
@@ -286,9 +286,9 @@ public sealed class Connect4Game : IDisposable
var curCol = col + i;
//check if current values are in range
if (curRow >= NumberOfRows || curRow < 0)
if (curRow is >= NumberOfRows or < 0)
break;
if (curCol < 0 || curCol >= NumberOfColumns)
if (curCol is < 0 or >= NumberOfColumns)
break;
var cur = _gameState[curRow + (curCol * NumberOfRows)];
@@ -328,9 +328,7 @@ public sealed class Connect4Game : IDisposable
}
private void ResetTimer()
{
_playerTimeoutTimer.Change(TimeSpan.FromSeconds(_options.TurnTimer), TimeSpan.FromSeconds(_options.TurnTimer));
}
=> _playerTimeoutTimer.Change(TimeSpan.FromSeconds(_options.TurnTimer), TimeSpan.FromSeconds(_options.TurnTimer));
private void EndGame(Result result, ulong? winId)
{
@@ -378,7 +376,7 @@ public sealed class Connect4Game : IDisposable
{
public void NormalizeOptions()
{
if (TurnTimer < 5 || TurnTimer > 60)
if (TurnTimer is < 5 or > 60)
TurnTimer = 15;
if (Bet < 0)

View File

@@ -86,8 +86,7 @@ public partial class Gambling
try { await arg.DeleteAsync().ConfigureAwait(false); } catch { }
else
{
if (game.CurrentPhase == Connect4Game.Phase.Joining
|| game.CurrentPhase == Connect4Game.Phase.Ended)
if (game.CurrentPhase is Connect4Game.Phase.Joining or Connect4Game.Phase.Ended)
{
return;
}
@@ -145,7 +144,7 @@ public partial class Gambling
get => _repostCounter;
set
{
if (value < 0 || value > 7)
if (value is < 0 or > 7)
_repostCounter = 0;
else _repostCounter = value;
}
@@ -169,8 +168,7 @@ public partial class Gambling
{
var sb = new StringBuilder();
if (game.CurrentPhase == Connect4Game.Phase.P1Move ||
game.CurrentPhase == Connect4Game.Phase.P2Move)
if (game.CurrentPhase is Connect4Game.Phase.P1Move or Connect4Game.Phase.P2Move)
sb.AppendLine(GetText(strs.connect4_player_to_move(Format.Bold(game.CurrentPlayer.Username))));
for (var i = Connect4Game.NumberOfRows; i > 0; i--)

View File

@@ -32,8 +32,7 @@ public partial class Gambling
}
private IEmbedBuilder GetEmbed(CurrencyEvent.Type type, EventOptions opts, long currentPot)
{
return type switch
=> type switch
{
CurrencyEvent.Type.Reaction => _eb.Create()
.WithOkColor()
@@ -47,7 +46,6 @@ public partial class Gambling
.WithFooter(GetText(strs.event_duration_footer(opts.Hours))),
_ => throw new ArgumentOutOfRangeException(nameof(type))
};
}
private string GetReactionDescription(long amount, long potSize)
{

View File

@@ -17,9 +17,7 @@ public partial class Gambling
private readonly IImageCache _images;
public DiceRollCommands(IDataCache data)
{
_images = data.LocalImages;
}
=> _images = data.LocalImages;
[NadekoCommand, Aliases]
public async Task Roll()
@@ -42,35 +40,27 @@ public partial class Gambling
[NadekoCommand, Aliases]
[Priority(1)]
public async Task Roll(int num)
{
await InternalRoll(num, true).ConfigureAwait(false);
}
=> await InternalRoll(num, true).ConfigureAwait(false);
[NadekoCommand, Aliases]
[Priority(1)]
public async Task Rolluo(int num = 1)
{
await InternalRoll(num, false).ConfigureAwait(false);
}
=> await InternalRoll(num, false).ConfigureAwait(false);
[NadekoCommand, Aliases]
[Priority(0)]
public async Task Roll(string arg)
{
await InternallDndRoll(arg, true).ConfigureAwait(false);
}
=> await InternallDndRoll(arg, true).ConfigureAwait(false);
[NadekoCommand, Aliases]
[Priority(0)]
public async Task Rolluo(string arg)
{
await InternallDndRoll(arg, false).ConfigureAwait(false);
}
=> await InternallDndRoll(arg, false).ConfigureAwait(false);
private async Task InternalRoll(int num, bool ordered)
{
if (num < 1 || num > 30)
if (num is < 1 or > 30)
{
await ReplyErrorLocalizedAsync(strs.dice_invalid_number(1, 30));
return;
@@ -201,7 +191,7 @@ public partial class Gambling
private Image<Rgba32> GetDice(int num)
{
if (num < 0 || num > 10)
if (num is < 0 or > 10)
throw new ArgumentOutOfRangeException(nameof(num));
if (num == 10)

View File

@@ -14,13 +14,11 @@ public partial class Gambling
private readonly IImageCache _images;
public DrawCommands(IDataCache data)
{
_images = data.LocalImages;
}
=> _images = data.LocalImages;
private async Task<(Stream ImageStream, string ToSend)> InternalDraw(int num, ulong? guildId = null)
{
if (num < 1 || num > 10)
if (num is < 1 or > 10)
throw new ArgumentOutOfRangeException(nameof(num));
var cards = guildId is null ? new() : _allDecks.GetOrAdd(ctx.Guild, s => new());

View File

@@ -24,7 +24,7 @@ public partial class Gambling
[NadekoCommand, Aliases]
public async Task Flip(int count = 1)
{
if (count > 10 || count < 1)
if (count is > 10 or < 1)
{
await ReplyErrorLocalizedAsync(strs.flip_invalid(10));
return;

View File

@@ -201,9 +201,7 @@ public partial class Gambling : GamblingModule<GamblingService>
[NadekoCommand, Aliases]
[Priority(0)]
public async Task Cash(ulong userId)
{
await ReplyConfirmLocalizedAsync(strs.has(Format.Code(userId.ToString()), $"{GetCurrency(userId)}"));
}
=> await ReplyConfirmLocalizedAsync(strs.has(Format.Code(userId.ToString()), $"{GetCurrency(userId)}"));
[NadekoCommand, Aliases]
[Priority(1)]

View File

@@ -12,9 +12,7 @@ public partial class Gambling
private readonly ILogCommandService logService;
public PlantPickCommands(ILogCommandService logService, GamblingConfigService gss) : base(gss)
{
this.logService = logService;
}
=> this.logService = logService;
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]

View File

@@ -38,7 +38,7 @@ public class GamblingService : INService
{
var config = _gss.Data;
var maxDecay = config.Decay.MaxDecay;
if (config.Decay.Percent <= 0 || config.Decay.Percent > 1 || maxDecay < 0)
if (config.Decay.Percent is <= 0 or > 1 || maxDecay < 0)
return;
using var uow = _db.GetDbContext();
@@ -156,7 +156,5 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU
}
public Task<WheelOfFortuneGame.Result> WheelOfFortuneSpinAsync(ulong userId, long bet)
{
return new WheelOfFortuneGame(userId, bet, _gss.Data, _cs).SpinAsync();
}
=> new WheelOfFortuneGame(userId, bet, _gss.Data, _cs).SpinAsync();
}

View File

@@ -11,9 +11,7 @@ public class ShopService : IShopService, INService
private readonly DbService _db;
public ShopService(DbService db)
{
_db = db;
}
=> _db = db;
private IndexedCollection<ShopEntry> GetEntriesInternal(NadekoContext uow, ulong guildId) =>
uow.GuildConfigsForId(

View File

@@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
using SixLabors.Fonts;
using SixLabors.ImageSharp;

View File

@@ -6,7 +6,5 @@ public class TestGamblingService : InteractionModuleBase
{
[SlashCommand("test", "uwu")]
public async Task Test(string input1, int input2)
{
await RespondAsync("Bravo " + input1 + input2);
}
=> await RespondAsync("Bravo " + input1 + input2);
}

View File

@@ -257,20 +257,21 @@ public partial class Gambling
var nobody = GetText(strs.nobody);
var itemsStr = !wi.Items.Any()
? "-"
: string.Join("\n", wi.Items
.Where(x => waifuItems.TryGetValue(x.ItemEmoji, out _))
.OrderBy(x => waifuItems[x.ItemEmoji].Price)
.GroupBy(x => x.ItemEmoji)
.Select(x => $"{x.Key} x{x.Count(),-3}")
.Chunk(2)
.Select(x => string.Join(" ", x)));
: string.Join("\n",
wi.Items.Where(x => waifuItems.TryGetValue(x.ItemEmoji, out _))
.OrderBy(x => waifuItems[x.ItemEmoji].Price)
.GroupBy(x => x.ItemEmoji)
.Select(x => $"{x.Key} x{x.Count(),-3}")
.Chunk(2)
.Select(x => string.Join(" ", x))
);
var fansStr = wi
.Fans
.Shuffle()
.Take(30)
.Select(x => wi.Claims.Contains(x) ? $"{x} 💞" : x)
.JoinWith('\n');
.Join('\n');
if (string.IsNullOrWhiteSpace(fansStr))
fansStr = "-";
@@ -309,15 +310,16 @@ public partial class Gambling
.WithTitle(GetText(strs.waifu_gift_shop))
.WithOkColor();
waifuItems
.OrderBy(x => x.Negative)
waifuItems.OrderBy(x => x.Negative)
.ThenBy(x => x.Price)
.Skip(9 * cur)
.Take(9)
.ForEach(x => embed
.AddField($"{(!x.Negative ? string.Empty : "\\💔")} {x.ItemEmoji} {x.Name}",
.ToList()
.ForEach(x => embed.AddField($"{(!x.Negative ? string.Empty : "\\💔")} {x.ItemEmoji} {x.Name}",
Format.Bold(x.Price.ToString()) + _config.Currency.Sign,
true));
true
)
);
return embed;
}, waifuItems.Count, 9);