mirror of
https://gitlab.com/Kwoth/nadekobot.git
synced 2025-09-11 17:58:26 -04:00
Fixed some crashes in response strings source generator, reorganized more submodules into their folders
This commit is contained in:
200
src/NadekoBot/Modules/Games/Acrophobia/Acrophobia.cs
Normal file
200
src/NadekoBot/Modules/Games/Acrophobia/Acrophobia.cs
Normal file
@@ -0,0 +1,200 @@
|
||||
#nullable disable
|
||||
using CommandLine;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace NadekoBot.Modules.Games.Common.Acrophobia;
|
||||
|
||||
public sealed class AcrophobiaGame : IDisposable
|
||||
{
|
||||
public enum Phase
|
||||
{
|
||||
Submission,
|
||||
Voting,
|
||||
Ended
|
||||
}
|
||||
|
||||
public enum UserInputResult
|
||||
{
|
||||
Submitted,
|
||||
SubmissionFailed,
|
||||
Voted,
|
||||
VotingFailed,
|
||||
Failed
|
||||
}
|
||||
|
||||
public event Func<AcrophobiaGame, Task> OnStarted = delegate { return Task.CompletedTask; };
|
||||
|
||||
public event Func<AcrophobiaGame, ImmutableArray<KeyValuePair<AcrophobiaUser, int>>, Task> OnVotingStarted =
|
||||
delegate { return Task.CompletedTask; };
|
||||
|
||||
public event Func<string, Task> OnUserVoted = delegate { return Task.CompletedTask; };
|
||||
|
||||
public event Func<AcrophobiaGame, ImmutableArray<KeyValuePair<AcrophobiaUser, int>>, Task> OnEnded = delegate
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
public Phase CurrentPhase { get; private set; } = Phase.Submission;
|
||||
public ImmutableArray<char> StartingLetters { get; private set; }
|
||||
public Options Opts { get; }
|
||||
|
||||
private readonly Dictionary<AcrophobiaUser, int> submissions = new();
|
||||
private readonly SemaphoreSlim locker = new(1, 1);
|
||||
private readonly NadekoRandom _rng;
|
||||
|
||||
private readonly HashSet<ulong> _usersWhoVoted = new();
|
||||
|
||||
public AcrophobiaGame(Options options)
|
||||
{
|
||||
Opts = options;
|
||||
_rng = new();
|
||||
InitializeStartingLetters();
|
||||
}
|
||||
|
||||
public async Task Run()
|
||||
{
|
||||
await OnStarted(this);
|
||||
await Task.Delay(Opts.SubmissionTime * 1000);
|
||||
await locker.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (submissions.Count == 0)
|
||||
{
|
||||
CurrentPhase = Phase.Ended;
|
||||
await OnVotingStarted(this, ImmutableArray.Create<KeyValuePair<AcrophobiaUser, int>>());
|
||||
return;
|
||||
}
|
||||
|
||||
if (submissions.Count == 1)
|
||||
{
|
||||
CurrentPhase = Phase.Ended;
|
||||
await OnVotingStarted(this, submissions.ToArray().ToImmutableArray());
|
||||
return;
|
||||
}
|
||||
|
||||
CurrentPhase = Phase.Voting;
|
||||
|
||||
await OnVotingStarted(this, submissions.ToArray().ToImmutableArray());
|
||||
}
|
||||
finally { locker.Release(); }
|
||||
|
||||
await Task.Delay(Opts.VoteTime * 1000);
|
||||
await locker.WaitAsync();
|
||||
try
|
||||
{
|
||||
CurrentPhase = Phase.Ended;
|
||||
await OnEnded(this, submissions.ToArray().ToImmutableArray());
|
||||
}
|
||||
finally { locker.Release(); }
|
||||
}
|
||||
|
||||
private void InitializeStartingLetters()
|
||||
{
|
||||
var wordCount = _rng.Next(3, 6);
|
||||
|
||||
var lettersArr = new char[wordCount];
|
||||
|
||||
for (var i = 0; i < wordCount; i++)
|
||||
{
|
||||
var randChar = (char)_rng.Next(65, 91);
|
||||
lettersArr[i] = randChar == 'X' ? (char)_rng.Next(65, 88) : randChar;
|
||||
}
|
||||
|
||||
StartingLetters = lettersArr.ToImmutableArray();
|
||||
}
|
||||
|
||||
public async Task<bool> UserInput(ulong userId, string userName, string input)
|
||||
{
|
||||
var user = new AcrophobiaUser(userId, userName, input.ToLowerInvariant().ToTitleCase());
|
||||
|
||||
await locker.WaitAsync();
|
||||
try
|
||||
{
|
||||
switch (CurrentPhase)
|
||||
{
|
||||
case Phase.Submission:
|
||||
if (submissions.ContainsKey(user) || !IsValidAnswer(input))
|
||||
break;
|
||||
|
||||
submissions.Add(user, 0);
|
||||
return true;
|
||||
case Phase.Voting:
|
||||
AcrophobiaUser toVoteFor;
|
||||
if (!int.TryParse(input, out var index)
|
||||
|| --index < 0
|
||||
|| index >= submissions.Count
|
||||
|| (toVoteFor = submissions.ToArray()[index].Key).UserId == user.UserId
|
||||
|| !_usersWhoVoted.Add(userId))
|
||||
break;
|
||||
++submissions[toVoteFor];
|
||||
var _ = Task.Run(() => OnUserVoted(userName));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
locker.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsValidAnswer(string input)
|
||||
{
|
||||
input = input.ToUpperInvariant();
|
||||
|
||||
var inputWords = input.Split(' ');
|
||||
|
||||
if (inputWords.Length
|
||||
!= StartingLetters.Length) // number of words must be the same as the number of the starting letters
|
||||
return false;
|
||||
|
||||
for (var i = 0; i < StartingLetters.Length; i++)
|
||||
{
|
||||
var letter = StartingLetters[i];
|
||||
|
||||
if (!inputWords[i]
|
||||
.StartsWith(letter.ToString(), StringComparison.InvariantCulture)) // all first letters must match
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
CurrentPhase = Phase.Ended;
|
||||
OnStarted = null;
|
||||
OnEnded = null;
|
||||
OnUserVoted = null;
|
||||
OnVotingStarted = null;
|
||||
_usersWhoVoted.Clear();
|
||||
submissions.Clear();
|
||||
locker.Dispose();
|
||||
}
|
||||
|
||||
public class Options : INadekoCommandOptions
|
||||
{
|
||||
[Option('s',
|
||||
"submission-time",
|
||||
Required = false,
|
||||
Default = 60,
|
||||
HelpText = "Time after which the submissions are closed and voting starts.")]
|
||||
public int SubmissionTime { get; set; } = 60;
|
||||
|
||||
[Option('v',
|
||||
"vote-time",
|
||||
Required = false,
|
||||
Default = 60,
|
||||
HelpText = "Time after which the voting is closed and the winner is declared.")]
|
||||
public int VoteTime { get; set; } = 30;
|
||||
|
||||
public void NormalizeOptions()
|
||||
{
|
||||
if (SubmissionTime is < 15 or > 300)
|
||||
SubmissionTime = 60;
|
||||
if (VoteTime is < 15 or > 120)
|
||||
VoteTime = 30;
|
||||
}
|
||||
}
|
||||
}
|
22
src/NadekoBot/Modules/Games/Acrophobia/AcrophobiaUser.cs
Normal file
22
src/NadekoBot/Modules/Games/Acrophobia/AcrophobiaUser.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
#nullable disable
|
||||
namespace NadekoBot.Modules.Games.Common.Acrophobia;
|
||||
|
||||
public class AcrophobiaUser
|
||||
{
|
||||
public string UserName { get; }
|
||||
public ulong UserId { get; }
|
||||
public string Input { get; }
|
||||
|
||||
public AcrophobiaUser(ulong userId, string userName, string input)
|
||||
{
|
||||
UserName = userName;
|
||||
UserId = userId;
|
||||
Input = input;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
=> UserId.GetHashCode();
|
||||
|
||||
public override bool Equals(object obj)
|
||||
=> obj is AcrophobiaUser x ? x.UserId == UserId : false;
|
||||
}
|
138
src/NadekoBot/Modules/Games/Acrophobia/AcropobiaCommands.cs
Normal file
138
src/NadekoBot/Modules/Games/Acrophobia/AcropobiaCommands.cs
Normal file
@@ -0,0 +1,138 @@
|
||||
#nullable disable
|
||||
using NadekoBot.Modules.Games.Common.Acrophobia;
|
||||
using NadekoBot.Modules.Games.Services;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace NadekoBot.Modules.Games;
|
||||
|
||||
public partial class Games
|
||||
{
|
||||
[Group]
|
||||
public partial class AcropobiaCommands : NadekoSubmodule<GamesService>
|
||||
{
|
||||
private readonly DiscordSocketClient _client;
|
||||
|
||||
public AcropobiaCommands(DiscordSocketClient client)
|
||||
=> _client = client;
|
||||
|
||||
[Cmd]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[NadekoOptions(typeof(AcrophobiaGame.Options))]
|
||||
public async partial Task Acrophobia(params string[] args)
|
||||
{
|
||||
var (options, _) = OptionsParser.ParseFrom(new AcrophobiaGame.Options(), args);
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
var game = new AcrophobiaGame(options);
|
||||
if (_service.AcrophobiaGames.TryAdd(channel.Id, game))
|
||||
try
|
||||
{
|
||||
game.OnStarted += Game_OnStarted;
|
||||
game.OnEnded += Game_OnEnded;
|
||||
game.OnVotingStarted += Game_OnVotingStarted;
|
||||
game.OnUserVoted += Game_OnUserVoted;
|
||||
_client.MessageReceived += _client_MessageReceived;
|
||||
await game.Run();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_client.MessageReceived -= _client_MessageReceived;
|
||||
_service.AcrophobiaGames.TryRemove(channel.Id, out game);
|
||||
game.Dispose();
|
||||
}
|
||||
else
|
||||
await ReplyErrorLocalizedAsync(strs.acro_running);
|
||||
|
||||
Task _client_MessageReceived(SocketMessage msg)
|
||||
{
|
||||
if (msg.Channel.Id != ctx.Channel.Id)
|
||||
return Task.CompletedTask;
|
||||
|
||||
var _ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var success = await game.UserInput(msg.Author.Id, msg.Author.ToString(), msg.Content);
|
||||
if (success)
|
||||
await msg.DeleteAsync();
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private Task Game_OnStarted(AcrophobiaGame game)
|
||||
{
|
||||
var embed = _eb.Create()
|
||||
.WithOkColor()
|
||||
.WithTitle(GetText(strs.acrophobia))
|
||||
.WithDescription(
|
||||
GetText(strs.acro_started(Format.Bold(string.Join(".", game.StartingLetters)))))
|
||||
.WithFooter(GetText(strs.acro_started_footer(game.Opts.SubmissionTime)));
|
||||
|
||||
return ctx.Channel.EmbedAsync(embed);
|
||||
}
|
||||
|
||||
private Task Game_OnUserVoted(string user)
|
||||
=> SendConfirmAsync(GetText(strs.acrophobia), GetText(strs.acro_vote_cast(Format.Bold(user))));
|
||||
|
||||
private async Task Game_OnVotingStarted(
|
||||
AcrophobiaGame game,
|
||||
ImmutableArray<KeyValuePair<AcrophobiaUser, int>> submissions)
|
||||
{
|
||||
if (submissions.Length == 0)
|
||||
{
|
||||
await SendErrorAsync(GetText(strs.acrophobia), GetText(strs.acro_ended_no_sub));
|
||||
return;
|
||||
}
|
||||
|
||||
if (submissions.Length == 1)
|
||||
{
|
||||
await ctx.Channel.EmbedAsync(_eb.Create()
|
||||
.WithOkColor()
|
||||
.WithDescription(GetText(
|
||||
strs.acro_winner_only(
|
||||
Format.Bold(submissions.First().Key.UserName))))
|
||||
.WithFooter(submissions.First().Key.Input));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
var i = 0;
|
||||
var embed = _eb.Create()
|
||||
.WithOkColor()
|
||||
.WithTitle(GetText(strs.acrophobia) + " - " + GetText(strs.submissions_closed))
|
||||
.WithDescription(GetText(strs.acro_nym_was(
|
||||
Format.Bold(string.Join(".", game.StartingLetters))
|
||||
+ "\n"
|
||||
+ $@"--
|
||||
{submissions.Aggregate("", (agg, cur) => agg + $"`{++i}.` **{cur.Key.Input}**\n")}
|
||||
--")))
|
||||
.WithFooter(GetText(strs.acro_vote));
|
||||
|
||||
await ctx.Channel.EmbedAsync(embed);
|
||||
}
|
||||
|
||||
private async Task Game_OnEnded(AcrophobiaGame game, ImmutableArray<KeyValuePair<AcrophobiaUser, int>> votes)
|
||||
{
|
||||
if (!votes.Any() || votes.All(x => x.Value == 0))
|
||||
{
|
||||
await SendErrorAsync(GetText(strs.acrophobia), GetText(strs.acro_no_votes_cast));
|
||||
return;
|
||||
}
|
||||
|
||||
var table = votes.OrderByDescending(v => v.Value);
|
||||
var winner = table.First();
|
||||
var embed = _eb.Create()
|
||||
.WithOkColor()
|
||||
.WithTitle(GetText(strs.acrophobia))
|
||||
.WithDescription(GetText(strs.acro_winner(Format.Bold(winner.Key.UserName),
|
||||
Format.Bold(winner.Value.ToString()))))
|
||||
.WithFooter(winner.Key.Input);
|
||||
|
||||
await ctx.Channel.EmbedAsync(embed);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user