예제 #1
0
파일: AGame.cs 프로젝트: TheIndra55/Sanara
        private async Task <IUserMessage> SaveScores(string reason)
        {
            Tuple <Db.Db.Comparaison, int> newScore;

            if (_guild == null && _contributors.Count == 0)
            {
                return(await PostText(reason)); // TODO
            }
            else
            {
                newScore = await Program.p.db.SetNewScore(_saveName, _score, _guild == null?_contributors[0] : _guild.Id, string.Join("|", _contributors));
            }
            if (newScore.Item1 == Db.Db.Comparaison.Best)
            {
                return(await PostText(reason + Environment.NewLine + Sentences.NewBestScore(_guild, newScore.Item2.ToString(), _score.ToString())));
            }
            else if (newScore.Item1 == Db.Db.Comparaison.Equal)
            {
                return(await PostText(reason + Environment.NewLine + Sentences.EqualizedScore(_guild, _score.ToString())));
            }
            else
            {
                return(await PostText(reason + Environment.NewLine + Sentences.DidntBeatScore(_guild, newScore.Item2.ToString(), _score.ToString())));
            }
        }
예제 #2
0
파일: AGame.cs 프로젝트: Kadantte/Sanara
 public async Task Start()
 {
     if (_gameState != GameState.WaitingForPlayers) // In case someone use the 'Start' command right when the game was about to be launched by itself
     {
         return;
     }
     _gameState = GameState.Running;
     if (HaveMultiplayerLobby())
     {
         // Setup for multiplayer:
         if (await _lobby.LoadNames(_chan)) // We try to load the nickname of everyone in the lobby
         {
             await _chan.SendMessageAsync(_lobby.GetReadyMessage(_chan.GuildId));
         }
         else
         {
             _gameState = GameState.Lost;
             await _chan.SendMessageAsync(Sentences.LobbyLeftChannel(_chan.GuildId));
         }
         if (_multiType == APreload.MultiplayerType.Elimination)
         {
             await PostText(Sentences.AnnounceTurn(_chan.GuildId, _lobby.GetTurnName()));
         }
     }
     await PostAsync();
 }
예제 #3
0
        protected override async Task <string> GetCheckCorrectAsync(string userAnswer)
        {
            string cleanUserAnswer = Utilities.CleanWord(userAnswer);

            foreach (string s in _toGuess)
            {
                if (cleanUserAnswer == Utilities.CleanWord(s))
                {
                    return(null);
                }
            }
            if (IsDictionnaryFull())
            {
                if (!_dictionnary.Any(x => Utilities.CleanWord(x) == cleanUserAnswer))
                {
                    return("❌");
                }
            }
            foreach (string s in _toGuess)
            {
                string cleanGuess = Utilities.CleanWord(s);
                if (cleanUserAnswer.Contains(cleanGuess) || cleanGuess.Contains(cleanUserAnswer))
                {
                    return(Sentences.BooruGuessClose(GetGuild(), userAnswer.Replace("@everyone", "@ everyone")));
                }
            }
            return("❌");
        }
예제 #4
0
파일: AGame.cs 프로젝트: TheIndra55/Sanara
        public async Task Start()
        {
            if (_gameState != GameState.WaitingForPlayers) // In case someone use the 'Start' command right when the game was about to be launched by itself
            {
                return;
            }
            _gameState = GameState.Running;
            if (HaveMultiplayerLobby())
            {
                // Setup for multiplayer:
                if (await _lobby.LoadNames(_chan as ITextChannel)) // We try to load the nickname of everyone in the lobby
                {
                    var msg = await _chan.SendMessageAsync(_lobby.GetReadyMessage(_guild));

                    var ids = _lobby.GetPlayersId();
                    foreach (var id in ids)
                    {
                        await Program.p.cm.ProgressAchievementAsync(Community.AchievementID.PlayWithFriends, ids.Count, null, msg, id);
                    }
                }
                else
                {
                    _gameState = GameState.Lost;
                    await _chan.SendMessageAsync(Sentences.LobbyLeftChannel(_guild));
                }
                if (_multiType == APreload.MultiplayerType.Elimination)
                {
                    await PostText(Sentences.AnnounceTurn(_guild, _lobby.GetTurnName()));
                }
            }
            await PostAsync();
        }
예제 #5
0
        public string JoinGame(ulong guildId, ulong chanId, ulong playerId)
        {
            AGame game = _games.Find(x => x.IsSelf(chanId));

            if (game == null)
            {
                return(Sentences.LobbyNoWaiting(guildId));
            }
            if (!game.IsWaitingForPlayers())
            {
                return(Sentences.LobbyNoWaiting(guildId));
            }
            if (!game.HaveMultiplayerLobby())
            {
                return(Sentences.LobbySoloJoin(guildId));
            }
            if (game.IsFull())
            {
                return(Sentences.LobbyFull(guildId));
            }
            if (game.IsPlayerInLobby(playerId))
            {
                return(Sentences.LobbyAlreadyInThis(guildId));
            }
            if (_games.Any(x => x.IsPlayerInLobby(playerId)))
            {
                return(Sentences.LobbyAlreadyIn(guildId));
            }
            game.AddPlayerToLobby(playerId);
            return(Sentences.LobbyJoined(guildId, game.GetName()));
        }
예제 #6
0
파일: AGame.cs 프로젝트: TheIndra55/Sanara
        public async Task LooseAsync(string reason)
        {
            _gameState = GameState.Lost;
            if (HaveMultiplayerLobby()) // Multiplayer scores aren't saved
            {
                if (_multiType == APreload.MultiplayerType.Elimination)
                {
                    _lobby.RemoveCurrentPlayer();
                    if (_lobby.HaveEnoughPlayer())
                    {
                        _gameState = GameState.Running;
                        _startTime = DateTime.Now;
                        await PostText(Sentences.YouLost(_guild) + (reason == null ? "" : reason + Environment.NewLine) + Sentences.AnnounceTurn(_guild, _lobby.GetTurnName()));

                        _postImage = false;
                        return;
                    }
                    await PostText(Sentences.YouLost(_guild) + (reason == null ? "" : reason + Environment.NewLine) + await GetLoose() + Environment.NewLine + Sentences.WonMulti(_guild, _lobby.GetLastStanding()));

                    LeaveVocalChannel();
                }
                else
                {
                    LeaveVocalChannel();
                    throw new ArgumentException("Multiplayer game " + _gameName + " ended in an unexpected way: " + reason);
                }
            }
            else
            {
                IUserMessage gameOverMsg;
                if (reason == null)
                {
                    gameOverMsg = await SaveScores(Sentences.YouLost(_guild) + await GetLoose());
                }
                else
                {
                    gameOverMsg = await SaveScores(Sentences.YouLost(_guild) + reason + Environment.NewLine + await GetLoose());
                }
                if (this is AQuizz)
                {
                    foreach (ulong c in _contributors)
                    {
                        await Program.p.cm.ProgressAchievementAsync(Community.AchievementID.GoodScores, _score, null, gameOverMsg, c);
                    }
                    if (_isShaded != APreload.Shadow.None)
                    {
                        foreach (ulong c in _contributors)
                        {
                            await Program.p.cm.ProgressAchievementAsync(Community.AchievementID.GoodScoresShadow, _score, null, gameOverMsg, c);
                        }
                    }
                }
                LeaveVocalChannel();
            }
        }
예제 #7
0
        public async Task Cancel(params string[] _)
        {
            Utilities.CheckAvailability(Context.Guild, Program.Module.Game);
            await Program.p.DoAction(Context.User, Program.Module.Game);

            if (Program.p.gm.Cancel(Context.Channel.Id))
            {
                await ReplyAsync(Sentences.ResetDone(Context.Guild));
            }
            else
            {
                await ReplyAsync(Sentences.ResetNone(Context.Guild));
            }
        }
예제 #8
0
파일: AGame.cs 프로젝트: Kadantte/Sanara
        private async Task SaveScores(string reason)
        {
            var newScore = await Program.p.db.SetNewScore(_saveName, _score, _chan.GuildId, string.Join("|", _contributors));

            if (newScore.Item1 == Db.Db.Comparaison.Best)
            {
                await PostText(reason + Environment.NewLine + Sentences.NewBestScore(_chan.GuildId, newScore.Item2.ToString(), _score.ToString()));
            }
            else if (newScore.Item1 == Db.Db.Comparaison.Equal)
            {
                await PostText(reason + Environment.NewLine + Sentences.EqualizedScore(_chan.GuildId, _score.ToString()));
            }
            else
            {
                await PostText(reason + Environment.NewLine + Sentences.DidntBeatScore(_chan.GuildId, newScore.Item2.ToString(), _score.ToString()));
            }
        }
예제 #9
0
        public static string GetInformation(IGuild guild)
        {
            StringBuilder finalStr = new StringBuilder();

            foreach (var game in Constants.allDictionnaries)
            {
                finalStr.Append("**" + game.Item1(guild) + ":** ");
                if (game.Item2.Count == 0)
                {
                    finalStr.Append(Sentences.NotLoaded(guild));
                }
                else
                {
                    finalStr.Append(game.Item2.Count + " " + Sentences.Words(guild));
                }
                finalStr.Append(Environment.NewLine);
            }
            return(finalStr.ToString());
        }
예제 #10
0
        public string LeaveGame(ulong guildId, ulong chanId, ulong playerId)
        {
            AGame game = _games.Find(x => x.IsSelf(chanId));

            if (game == null)
            {
                return(Sentences.LobbyNoWaiting(guildId));
            }
            if (!game.IsWaitingForPlayers())
            {
                return(Sentences.LobbyAlreadyStarted(guildId));
            }
            if (!game.HaveMultiplayerLobby())
            {
                return(Sentences.LobbySoloLeave(guildId));
            }
            if (!game.IsPlayerInLobby(playerId))
            {
                return(Sentences.LobbyAlreadyOut(guildId));
            }
            game.RemovePlayerFromLobby(playerId);
            return(Sentences.LobbyLeaved(guildId) + (game.IsLobbyEmpty() ? Environment.NewLine + Sentences.LobbyEmpty(guildId) : ""));
        }
예제 #11
0
        public async Task <string> StartGame(ulong guildId, ulong chanId, ulong playerId)
        {
            AGame game = _games.Find(x => x.IsSelf(chanId));

            if (game == null)
            {
                return(Sentences.LobbyNoWaiting(guildId));
            }
            if (!game.IsWaitingForPlayers())
            {
                return(Sentences.LobbyNoWaiting(guildId));
            }
            if (!game.IsPlayerInLobby(playerId))
            {
                return(Sentences.LobbyAlreadyOut(guildId));
            }
            if (!game.HaveEnoughPlayer())
            {
                return(Sentences.LobbyNotEnoughPlayer(guildId));
            }
            await game.Start();

            return(null);
        }
예제 #12
0
파일: AGame.cs 프로젝트: Kadantte/Sanara
        public async Task LooseAsync(string reason)
        {
            _gameState = GameState.Lost;
            if (HaveMultiplayerLobby()) // Multiplayer scores aren't saved
            {
                if (_multiType == APreload.MultiplayerType.Elimination)
                {
                    _lobby.RemoveCurrentPlayer();
                    if (_lobby.HaveEnoughPlayer())
                    {
                        _gameState = GameState.Running;
                        _startTime = DateTime.Now;
                        await PostText(Sentences.YouLost(_chan.GuildId) + (reason == null ? "" : reason + Environment.NewLine) + Sentences.AnnounceTurn(_chan.GuildId, _lobby.GetTurnName()));

                        _postImage = false;
                        return;
                    }
                    await PostText(Sentences.YouLost(_chan.GuildId) + (reason == null ? "" : reason + Environment.NewLine) + await GetLoose() + Environment.NewLine + Sentences.WonMulti(_chan.GuildId, _lobby.GetLastStanding()));
                }
                else
                {
                    throw new ArgumentException("Multiplayer game " + _gameName + " ended in an unexpected way: " + reason);
                }
            }
            else
            {
                if (reason == null)
                {
                    await SaveScores(Sentences.YouLost(_chan.GuildId) + await GetLoose());
                }
                else
                {
                    await SaveScores(Sentences.YouLost(_chan.GuildId) + reason + Environment.NewLine + await GetLoose());
                }
            }
        }
예제 #13
0
파일: AGame.cs 프로젝트: TheIndra55/Sanara
        private async Task BestOfOutOfRound(bool didFindGuess)
        {
            List <string> bestName  = new List <string>();
            int           bestScore = 0;

            foreach (var name in _lobby.GetFullNames())
            {
                int currScore = _bestOfScore.ContainsKey(name) ? _bestOfScore[name] : 0;
                if (currScore == bestScore)
                {
                    bestName.Add(name);
                }
                else if (currScore > bestScore)
                {
                    bestName = new List <string>();
                    bestName.Add(name);
                    bestScore = currScore;
                }
            }
            string finalStr = "";

            if (didFindGuess)
            {
                finalStr += Sentences.GuessGood(_guild) + Environment.NewLine;
            }
            finalStr += Sentences.CurrentScore(_guild) + Environment.NewLine + GetBestOfScore() + Environment.NewLine + Environment.NewLine + Sentences.ReversiGameEnded(_guild) + Environment.NewLine;
            if (bestName.Count == _lobby.GetFullNames().Count)
            {
                await PostText(finalStr + Sentences.Draw(_guild));
            }
            else
            {
                await PostText(finalStr + Sentences.WonMulti(_guild, string.Join(", ", bestName)));
            }
            _gameState = GameState.Lost;
        }
예제 #14
0
파일: AGame.cs 프로젝트: TheIndra55/Sanara
        public async Task LooseTimerAsync()
        {
            if (_gameState != GameState.Running) // No need to check if we already lost
            {
                return;
            }
            if (_postImage || _checkingAnswer) // If we are already doing something (posting image or checking answer) we wait for it
            {
                return;
            }
            if (_startTime.AddSeconds(_timer).CompareTo(DateTime.Now) < 0)
            {
                if (HaveMultiplayerLobby() && _multiType == APreload.MultiplayerType.BestOf)
                {
                    _bestOfRemainingRounds--;
                    string finalStr = Sentences.TimeOut(_guild) + await GetLoose() + Environment.NewLine + Sentences.CurrentScore(_guild) + Environment.NewLine;

                    finalStr += GetBestOfScore();
                    await PostText(finalStr);

                    if (_bestOfRemainingRounds == 0)
                    {
                        await BestOfOutOfRound(false);
                    }
                    else
                    {
                        _bestOfTries = new Dictionary <string, int>();
                        await PostAsync();
                    }
                }
                else
                {
                    await LooseAsync(Sentences.TimeoutGame(_guild));
                }
            }
        }
예제 #15
0
 public string GetReadyMessage(IGuild guild)
 => Sentences.Participants(guild) + Environment.NewLine + string.Join(", ", _players.Select(x => "<@" + x + ">"));
예제 #16
0
        private async Task <Func <ulong, string> > PlayInternal(string[] args, ITextChannel chan, ulong playerId)
        {
            if (args.Length == 0)
            {
                return(Sentences.InvalidGameName);
            }
            string     gameName   = args[0].ToLower();
            Difficulty difficulty = Difficulty.Normal;
            bool       isFull     = false;
            bool       sendImage  = false;
            bool       isCropped  = false;

            APreload.Shadow      isShaded      = APreload.Shadow.None;
            APreload.Multiplayer isMultiplayer = APreload.Multiplayer.SoloOnly;
            if (args.Length > 1)
            {
                foreach (string s in args.Skip(1).Select(x => x.ToLower()))
                {
                    switch (s)
                    {
                    case "full":
                        isFull = true;
                        break;

                    case "multi":
                    case "multiplayer":
                        isMultiplayer = APreload.Multiplayer.MultiOnly;
                        break;

                    case "easy":
                        difficulty = Difficulty.Easy;
                        break;

                    case "normal":
                    case "solo":
                        break;     // These case exist so the user can precise them, but they do nothing

                    case "crop":
                    case "cropped":
                        isCropped = true;
                        break;

                    case "shade":
                    case "shadow":
                    case "shaded":
                        isShaded = APreload.Shadow.Transparency;
                        break;

                    case "image":
                        sendImage = true;
                        break;

                    default:
                        return(Sentences.InvalidGameArgument);
                    }
                }
            }
            foreach (var game in Constants.allGames)
            {
                APreload preload = (APreload)Activator.CreateInstance(game.Item1);
                if (preload.ContainsName(gameName))
                {
                    if (!chan.IsNsfw && preload.IsNsfw())
                    {
                        return(Modules.Base.Sentences.ChanIsNotNsfw);
                    }
                    if (isMultiplayer == APreload.Multiplayer.MultiOnly && preload.DoesAllowMultiplayer() == APreload.Multiplayer.SoloOnly)
                    {
                        return(Sentences.MultiNotAvailable);
                    }
                    if (isMultiplayer == APreload.Multiplayer.SoloOnly && preload.DoesAllowMultiplayer() == APreload.Multiplayer.MultiOnly)
                    {
                        return(Sentences.SoloNotAvailable);
                    }
                    if (isFull && !preload.DoesAllowFull())
                    {
                        return(Sentences.FullNotAvailable);
                    }
                    if (sendImage && !preload.DoesAllowSendImage())
                    {
                        return(Sentences.SendImageNotAvailable);
                    }
                    if (isCropped && !preload.DoesAllowCropped())
                    {
                        return(Sentences.CropNotAvailable);
                    }
                    if (isCropped && preload.DoesAllowShadow() == APreload.Shadow.None)
                    {
                        return(Sentences.ShadowNotAvailable);
                    }
                    if (isShaded != APreload.Shadow.None)
                    {
                        isShaded = preload.DoesAllowShadow();
                    }
                    try
                    {
                        string introMsg = "";
                        if (isMultiplayer == APreload.Multiplayer.MultiOnly)
                        {
                            introMsg += Sentences.LobbyCreation(chan.GuildId, MultiplayerLobby.lobbyTime.ToString()) + Environment.NewLine + Environment.NewLine;
                        }
                        introMsg += "**" + Sentences.Rules(chan.GuildId) + ":**" + Environment.NewLine +
                                    preload.GetRules(chan.GuildId, isMultiplayer == APreload.Multiplayer.MultiOnly) + Environment.NewLine;
                        if (isMultiplayer == APreload.Multiplayer.MultiOnly)
                        {
                            if (preload.GetMultiplayerType() == APreload.MultiplayerType.Elimination)
                            {
                                introMsg += Sentences.RulesMultiElimination(chan.GuildId) + Environment.NewLine;
                            }
                            else
                            {
                                introMsg += Sentences.RulesMultiBestOf(chan.GuildId, AGame.nbMaxTry, AGame.nbQuestions) + Environment.NewLine;
                            }
                        }
                        introMsg += Sentences.RulesTimer(chan.GuildId, preload.GetTimer() * (int)difficulty) + Environment.NewLine + Environment.NewLine +
                                    Sentences.RulesReset(chan.GuildId);
                        await chan.SendMessageAsync(introMsg);

                        AGame newGame = (AGame)Activator.CreateInstance(game.Item2, chan, new Config(preload.GetTimer(), difficulty, preload.GetGameName(), isFull, sendImage, isCropped, isShaded, isMultiplayer, preload.GetMultiplayerType()), playerId);
                        _games.Add(newGame);
                        if (Program.p.sendStats)
                        {
                            await Program.p.UpdateElement(new Tuple <string, string>[] { new Tuple <string, string>("games", preload.GetGameName()) });
                        }
                        return(null);
                    }
                    catch (NoDictionnaryException)
                    {
                        return(Sentences.NoDictionnary);
                    }
                }
            }
            return(Sentences.InvalidGameName);
        }
예제 #17
0
파일: AGame.cs 프로젝트: TheIndra55/Sanara
        public async Task CheckCorrectAsync(IUser user, string userAnswer, SocketUserMessage msg)
        {
            if (_gameState != GameState.Running || userAnswer.StartsWith("//") || userAnswer.StartsWith("#"))
            {
                return;
            }
            _checkingAnswer = true;
            if (HaveMultiplayerLobby())          // If is in multiplayer
            {
                if (!_lobby.IsPlayerIn(user.Id)) // Player isn't in the multiplayer lobby
                {
                    return;
                }
                // Check if it's the player's turn (elimination mode only)
                else if (_multiType == APreload.MultiplayerType.Elimination && !_lobby.IsMyTurn(user.Id))
                {
                    await msg.AddReactionAsync(new Emoji("🚫"));

                    _checkingAnswer = false;
                    return;
                }
                // Check if the player is out of tries
                else if (_multiType == APreload.MultiplayerType.BestOf && _bestOfTries.ContainsKey(user.ToString()) && _bestOfTries[user.ToString()] == nbMaxTry - 1)
                {
                    await msg.AddReactionAsync(new Emoji("🚫"));

                    _checkingAnswer = false;
                    return;
                }
            }
            if (_postImage) // Image is being posted
            {
                await msg.AddReactionAsync(new Emoji("❌"));

                _checkingAnswer = false;
                return;
            }
            string error;

            try
            {
                error = await GetCheckCorrectAsync(userAnswer);
            }
            catch (Exception e)
            {
                await _chan.SendMessageAsync("", false, new EmbedBuilder()
                {
                    Color       = Color.Red,
                    Title       = e.GetType().ToString(),
                    Description = Sentences.ExceptionGameCheck(_guild),
                    Footer      = new EmbedFooterBuilder()
                    {
                        Text = e.Message
                    }
                }.Build());

                await Program.p.LogError(new LogMessage(LogSeverity.Error, e.Source, e.Message, e));
                await LooseAsync(null);

                return;
            }
            if (error != null)
            {
                if (error.Length < 5)
                {
                    await msg.AddReactionAsync(new Emoji(error));

                    error = "";
                }
                if (HaveMultiplayerLobby() && _multiType == APreload.MultiplayerType.BestOf)
                {
                    if (_bestOfTries.ContainsKey(user.ToString()))
                    {
                        _bestOfTries[user.ToString()]++;
                    }
                    else
                    {
                        _bestOfTries.Add(user.ToString(), 1);
                    }
                    error += Environment.NewLine + Sentences.TurnsRemaining(_guild, nbMaxTry - _bestOfTries[user.ToString()], user.ToString());
                }
                if (error != "")
                {
                    await PostText(error);
                }
                _checkingAnswer = false;
                return;
            }
            if (!_contributors.Contains(user.Id))
            {
                _contributors.Add(user.Id);
            }
            string finalStr = AnnounceNextTurnInternal();

            if (CongratulateOnGuess())
            {
                finalStr += Sentences.GuessGood(_guild);
            }
            if (HaveMultiplayerLobby())
            {
                if (_multiType == APreload.MultiplayerType.Elimination)
                {
                    await NextTurn();

                    if (finalStr != "")
                    {
                        finalStr += Environment.NewLine;
                    }
                    finalStr += Sentences.AnnounceTurn(_guild, _lobby.GetTurnName());
                }
                else if (_multiType == APreload.MultiplayerType.BestOf)
                {
                    if (_bestOfScore.ContainsKey(user.ToString()))
                    {
                        _bestOfScore[user.ToString()]++;
                    }
                    else
                    {
                        _bestOfScore.Add(user.ToString(), 1);
                    }
                    _bestOfRemainingRounds--;
                    if (_bestOfRemainingRounds == 0)
                    {
                        await BestOfOutOfRound(true);

                        return;
                    }
                    _bestOfTries = new Dictionary <string, int>();
                    finalStr    += Environment.NewLine + Sentences.CurrentScore(_guild) + Environment.NewLine;
                    finalStr    += GetBestOfScore();
                }
            }
            if (_gameState != GameState.Running || _isFound)
            {
                return;
            }
            _isFound = true;
            if (!string.IsNullOrWhiteSpace(finalStr))
            {
                await PostText(finalStr);
            }
            _score++;
            await PostAsync();

            _checkingAnswer = false;
        }
예제 #18
0
파일: AGame.cs 프로젝트: TheIndra55/Sanara
        public async Task PostAsync()
        {
            if (_gameState != GameState.Running)
            {
                return;
            }
            _postImage = true;
            int counter = 0;

            while (true)
            {
                if (_gameState != GameState.Running) // Can happen if the game is canceled
                {
                    return;
                }
                string finding = ""; // For error handling
                try
                {
                    PostType type = GetPostType();
                    if (type == PostType.Text)
                    {
                        foreach (string s in await GetPostAsync())
                        {
                            if (s == null)
                            {
                                continue;
                            }
                            finding = s;
                            await PostText(s);
                        }
                    }
                    else if (type == PostType.Url)
                    {
                        foreach (string s in await GetPostAsync())
                        {
                            if (s == null)
                            {
                                continue;
                            }
                            finding = s;
                            var answer = await _http.SendAsync(new HttpRequestMessage(HttpMethod.Head, s));

                            if (!answer.IsSuccessStatusCode)
                            {
                                throw new HttpRequestException("Invalid code " + answer.StatusCode);
                            }
                            await PostFromUrl(s);
                        }
                    }
                    else if (type == PostType.LocalPath)
                    {
                        foreach (string s in await GetPostAsync())
                        {
                            if (s == null)
                            {
                                continue;
                            }
                            finding = s;
                            await PostFromLocalPath(s);

                            File.Delete(s);
                        }
                    }
                    else
                    {
                        if (_audioFilePath != null)
                        {
                            File.Delete(_audioFilePath);
                        }
                        string url = (await GetPostAsync()).First();
                        _audioFilePath = "Saves/" + _guild.Id + DateTime.Now.ToString("HHmmssff") + ".mp3";
                        File.WriteAllBytes(_audioFilePath, await _http.GetByteArrayAsync(url));
                        _audioStream = _voiceSession.CreatePCMStream(AudioApplication.Voice);
                        await PostText("Audio started, use the 'replay' command to play it again.");
                        await PlayAudioFile();
                    }
                    _startTime = DateTime.Now;
                    _isFound   = false;
                    break;
                }
                catch (LooseException le)
                {
                    _postImage = false;
                    await LooseAsync(le.Message);

                    break;
                }
                catch (Exception e)
                {
                    counter++;
                    string msg = "Error posting for game " + _gameName + ": " + finding;
                    if (counter == 3)
                    {
                        await _chan.SendMessageAsync("", false, new EmbedBuilder()
                        {
                            Color       = Color.Red,
                            Title       = e.GetType().ToString(),
                            Description = Sentences.ExceptionGameStop(_guild),
                            Footer      = new EmbedFooterBuilder()
                            {
                                Text = e.Message
                            }
                        }.Build());

                        await Program.p.LogError(new LogMessage(LogSeverity.Error, e.Source, e.Message, new GameException(msg, e)));

                        _postImage = false;
                        await LooseAsync(null);

                        break;
                    }
                    else
                    {
                        await _chan.SendMessageAsync("", false, new EmbedBuilder()
                        {
                            Color       = Color.Orange,
                            Title       = e.GetType().ToString(),
                            Description = Sentences.ExceptionGame(_guild, e.Message),
                            Footer      = new EmbedFooterBuilder()
                            {
                                Text = e.Message
                            }
                        }.Build());

                        await Program.p.LogError(new LogMessage(LogSeverity.Error, e.Source, e.Message, new GameException(msg, e)));
                    }
                }
            }
            string help = Help();

            if (help != null)
            {
                await PostText(help);
            }
            _postImage = false;
        }
예제 #19
0
 protected override async Task <string> GetLoose()
 => Sentences.GoodAnswerWas(GetGuild(), FormatAnswer());
예제 #20
0
파일: AGame.cs 프로젝트: TheIndra55/Sanara
        public async Task DisplayCantStart()
        {
            await _chan.SendMessageAsync(Sentences.LobbyNotEnoughPlayerFatal(_guild));

            _gameState = GameState.Lost;
        }
예제 #21
0
        public async Task Score(params string[] _)
        {
            if (Context.Guild == null)
            {
                await ReplyAsync(Modules.Base.Sentences.CommandDontPm(Context.Guild));

                return;
            }
            Utilities.CheckAvailability(Context.Guild, Program.Module.Game);
            await Program.p.DoAction(Context.User, Program.Module.Game);

            var scores = await Program.p.db.GetAllScores();

            if (!scores.Any(x => x.Key == Context.Guild.Id.ToString()))
            {
                await ReplyAsync(Sentences.NoScore(Context.Guild));

                return;
            }
            var           me         = scores[Context.Guild.Id.ToString()];
            StringBuilder finalStr   = new StringBuilder();
            float         finalScore = 0;
            bool          ranked     = false;
            int           nbGuilds   = scores.Count(x => x.Value.Count > 0);

            foreach (var game in Constants.allRankedGames)
            {
                APreload preload  = (APreload)Activator.CreateInstance(game.Item1);
                string   gameName = preload.GetGameName();
                if (!me.ContainsKey(preload.GetGameName()))
                {
                    finalStr.Append("**" + preload.GetGameSentence(Context.Guild) + "**:" + Environment.NewLine +
                                    Sentences.NotRanked(Context.Guild) + Environment.NewLine + Environment.NewLine);
                    continue;
                }
                ranked = true;
                string[] myElems = me[gameName].Split('|');
                var      users   = await Context.Guild.GetUsersAsync();

                int      myScore      = int.Parse(myElems[0]);
                string[] contributors = myElems.Skip(1).Select(x => users.Where(y => y.Id.ToString() == x).FirstOrDefault()?.ToString() ?? "(Unknown)").ToArray();
                int      rankedNumber = scores.Where(x => Program.p.client.GetGuild(ulong.Parse(x.Key)) != null && x.Value.ContainsKey(gameName)).Count();
                int      myRanking    = scores.Where(x => Program.p.client.GetGuild(ulong.Parse(x.Key)) != null && x.Value.ContainsKey(gameName) && int.Parse(x.Value[gameName].Split('|')[0]) > myScore).Count() + 1;
                int      bestScore    = scores.Where(x => x.Value.ContainsKey(gameName)).Max(x => int.Parse(x.Value[gameName].Split('|')[0]));
                finalStr.Append("**" + preload.GetGameSentence(Context.Guild) + "**:" + Environment.NewLine +
                                Sentences.ScoreText(Context.Guild, myRanking, rankedNumber, myScore, bestScore) + Environment.NewLine +
                                Sentences.ScoreContributors(Context.Guild) + " " + string.Join(", ", contributors) + Environment.NewLine + Environment.NewLine);
                finalScore += myScore * 100f / bestScore;
            }
            int myGlobalRanking = 1;

            if (ranked)
            {
                foreach (var s in scores)
                {
                    int sScore = 0;
                    foreach (var elem in s.Value)
                    {
                        int best = scores.Where(x => x.Value.ContainsKey(elem.Key)).Max(x => int.Parse(x.Value[elem.Key].Split('|')[0]));
                        sScore += int.Parse(elem.Value.Split('|')[0]) * 100 / best;
                    }
                    if (sScore > finalScore)
                    {
                        myGlobalRanking++;
                    }
                }
            }
            await ReplyAsync((ranked ? Sentences.GlobalRanking(Context.Guild, myGlobalRanking, nbGuilds, finalScore / Constants.allRankedGames.Length)
                : Sentences.NoGlobalRanking(Context.Guild)) + Environment.NewLine + Environment.NewLine +
                             finalStr.ToString());
        }
예제 #22
0
파일: AGame.cs 프로젝트: Kadantte/Sanara
        public async Task PostAsync()
        {
            if (_gameState != GameState.Running)
            {
                return;
            }
            _postImage = true;
            int counter = 0;

            while (true)
            {
                if (_gameState != GameState.Running) // Can happen if the game is canceled
                {
                    return;
                }
                string finding = ""; // For error handling
                try
                {
                    PostType type = GetPostType();
                    if (type == PostType.Text)
                    {
                        foreach (string s in await GetPostAsync())
                        {
                            if (s == null)
                            {
                                continue;
                            }
                            finding = s;
                            await PostText(s);
                        }
                    }
                    else if (type == PostType.Url)
                    {
                        foreach (string s in await GetPostAsync())
                        {
                            if (s == null)
                            {
                                continue;
                            }
                            finding = s;
                            using (HttpClient hc = new HttpClient())
                            {
                                var answer = await hc.SendAsync(new HttpRequestMessage(HttpMethod.Head, s));

                                if (!answer.IsSuccessStatusCode)
                                {
                                    throw new HttpRequestException("Invalid code " + answer.StatusCode);
                                }
                            }
                            await PostFromUrl(s);
                        }
                    }
                    else
                    {
                        foreach (string s in await GetPostAsync())
                        {
                            if (s == null)
                            {
                                continue;
                            }
                            finding = s;
                            await PostFromLocalPath(s);

                            File.Delete(s);
                        }
                    }
                    _startTime = DateTime.Now;
                    _isFound   = false;
                    break;
                }
                catch (LooseException le)
                {
                    _postImage = false;
                    await LooseAsync(le.Message);

                    break;
                }
                catch (Exception e)
                {
                    counter++;
                    string msg = "Error posting " + finding;
                    if (counter == 3)
                    {
                        await _chan.SendMessageAsync("", false, new EmbedBuilder()
                        {
                            Color       = Color.Red,
                            Title       = e.GetType().ToString(),
                            Description = Sentences.ExceptionGameStop(_chan.GuildId),
                            Footer      = new EmbedFooterBuilder()
                            {
                                Text = e.Message
                            }
                        }.Build());

                        await Program.p.LogError(new LogMessage(LogSeverity.Error, e.Source, e.Message, new GameException(msg, e)));

                        _postImage = false;
                        await LooseAsync(null);

                        break;
                    }
                    else
                    {
                        await _chan.SendMessageAsync("", false, new EmbedBuilder()
                        {
                            Color       = Color.Orange,
                            Title       = e.GetType().ToString(),
                            Description = Sentences.ExceptionGame(_chan.GuildId, e.Message),
                            Footer      = new EmbedFooterBuilder()
                            {
                                Text = e.Message
                            }
                        }.Build());

                        await Program.p.LogError(new LogMessage(LogSeverity.Error, e.Source, e.Message, new GameException(msg, e)));
                    }
                }
            }
            string help = Help();

            if (help != null)
            {
                await PostText(help);
            }
            _postImage = false;
        }