Procházet zdrojové kódy

adding giveaways logic and information to admin

Tigran před 4 roky
rodič
revize
11e6873987

+ 1 - 1
MafiaTelegramBot.sln.DotSettings.user

@@ -13,7 +13,7 @@
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fkeyboard/@EntryIndexedValue">False</s:Boolean>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fkeywords/@EntryIndexedValue">True</s:Boolean>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Froles/@EntryIndexedValue">False</s:Boolean>
-	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fstrings/@EntryIndexedValue">False</s:Boolean>
+	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fstrings/@EntryIndexedValue">True</s:Boolean>
 	
 	
 	

+ 1 - 0
MafiaTelegramBot/Models/Bot.cs

@@ -87,6 +87,7 @@ namespace MafiaTelegramBot.Models
                 new ConnectToNotRankedQuery(),
                 new GiveToSelectedQuery(),
                 new GiveRoleQuery(),
+                new GiveToAllQuery(),
             };
         }
         

+ 1 - 1
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/CreateRoomHandler.cs

@@ -29,7 +29,7 @@ namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
             if (resultCode == ResultCode.CodeOk && isPrivate)
                 await Bot.SendWithMarkdown2(ChatId, $"{strings.secret_key_is} _*{roomName}*_: ```{RoomEncrypter.GetCode(roomName)}```");
             if (resultCode == ResultCode.CodeOk)
-                await Bot.SendHyperLink(ChatId, $"<a href='https://t.me/{AppSettings.Name}?start={RoomEncrypter.GetCode(roomName)}'>{strings.link}</a>");
+                await Bot.SendHyperLink(ChatId, $"<a href='https://t.me/{AppSettings.Name}?start=room_key={RoomEncrypter.GetCode(roomName)}'>{strings.link}</a>");
             return result;
         }
     }

+ 2 - 1
MafiaTelegramBot/Models/Commands/ShowProfileCommand.cs

@@ -22,7 +22,8 @@ namespace MafiaTelegramBot.Models.Commands
                 $"__*{strings.statistics_for} _{user.NickName}_*__\n" +
                 $"{strings.games_count} {allStatsRow.Games}\n" +
                 $"{strings.wins_count} {allStatsRow.Wins}\n" +
-                $"{strings.winrate} {(int)(allStatsRow.GetWinrate()*100)}%\n \n";
+                $"{strings.winrate} {(int)(allStatsRow.GetWinrate()*100)}%\n" +
+                $"{strings.rate} {user.RankNumber}%";
             return await Bot.SendWithMarkdown2(ChatId, message, Keyboard.ProfileKeyboard(UserId));
             
         }

+ 38 - 8
MafiaTelegramBot/Models/Commands/StartCommand.cs

@@ -2,6 +2,8 @@ using System;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Other;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
@@ -15,16 +17,19 @@ namespace MafiaTelegramBot.Models.Commands
         {
             var command = update.Message.Text.Split(' ');
             var player = await UserDao.GetPlayerById(UserId);
-            Console.WriteLine(player.isAdmin);
+            if (command.Length == 2)
+            {
+                var values = command[1].Split('=');
+                return values[0] switch
+                {
+                    "giveaway_id" => await GiveawayCommand(player, int.Parse(values[1])),
+                    "room_key" => await ConnectToGameCommand(player, values[1]),
+                    _ => new Message()
+                };
+            }
             if (player.GetRoomName() != "")
                 return await Bot.SendWithMarkdown2(ChatId, $"{strings.prefer_leave_from_room} {player.GetRoomName()}");
-            if (command.Length <= 1)
-                return await Bot.SendWithMarkdown2(ChatId, strings.start_message, player.IsAdmin ? Keyboard.AdminMainMenu : Keyboard.MainMenu);
-            var code = await RoomController.ConnectToGame(player, command[1]);
-            var result = code == ResultCode.CodeOk
-                ? Bot.SendWithMarkdown2(ChatId, strings.successful_entry_into_room, Keyboard.PlayerGameMenu)
-                : Utilities.GetResultCodeMessage(code, ChatId);
-            return await result;
+            return await Bot.SendWithMarkdown2(ChatId, strings.start_message, player.IsAdmin ? Keyboard.AdminMainMenu : Keyboard.MainMenu);
         }
 
         protected override bool IsMatches(string command)
@@ -32,5 +37,30 @@ namespace MafiaTelegramBot.Models.Commands
             var commandPart = command.Split(' ')[0];
             return base.IsMatches(commandPart);
         }
+
+        private async Task<Message> GiveawayCommand(Player player, int id)
+        {
+            try
+            {
+                var giveaway = GiveAway.OpenedGiveaways[id];
+                return await giveaway.GivePrizeTo(player) == ResultCode.NowYouGetPrizeFromThisGiveaway
+                    ? await Bot.SendWithMarkdown2(player.ChatId, strings.now_you_get_prize_from_this_giveaway)
+                    : new Message();
+            }
+            catch (Exception)
+            {
+                return await Bot.SendWithMarkdown2(ChatId, strings.giveaway_now_ended, Keyboard.PlayerGameMenu);
+            }
+        }
+
+        private async Task<Message> ConnectToGameCommand(Player player, string roomKey)
+        {
+            if (player.GetRoomName() != "")
+                return await Bot.SendWithMarkdown2(ChatId, $"{strings.prefer_leave_from_room} {player.GetRoomName()}");
+            var code = await RoomController.ConnectToGame(player, roomKey);
+            return code == ResultCode.CodeOk
+                ? await Bot.SendWithMarkdown2(ChatId, strings.successful_entry_into_room, Keyboard.PlayerGameMenu)
+                : await Utilities.GetResultCodeMessage(code, ChatId);
+        }
     }
 }

+ 34 - 0
MafiaTelegramBot/Models/Inlines/GiveToAllQuery.cs

@@ -0,0 +1,34 @@
+using System;
+using System.Linq;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Models.Inlines
+{
+    public class GiveToAllQuery : Query
+    {
+        protected override Callback Name => Callback.GiveToAll;
+        protected override async Task<Message> Execute(Update update)
+        {
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            var msg1 = String.Format(strings.giveaway_sample_message, keywords.giveaway,
+                keywords.message, keywords.picture, keywords.button, keywords.prize, keywords.count, keywords.to);
+            msg1 = msg1.Replace("\\n", "\\\n");
+            await Bot.SendWithMarkdown2(ChatId, msg1);
+            
+            var msg2 = String.Format(strings.giveaway_attentions, keywords.to, keywords.message,
+                keywords.picture, keywords.count, keywords.picture, keywords.prize);
+            msg2 = msg2.Replace("\\n", "\\\n");
+            await Bot.SendWithMarkdown2(ChatId, msg2);
+            
+            var msg3 = strings.list_of_roles;
+            var rolesList = Enum.GetValues(typeof(Roles)).Cast<Roles>().ToList();
+            rolesList.RemoveAll(role => role is Roles.All or Roles.None or Roles.Doctor or Roles.Don or Roles.Mafia or Roles.Cop or Roles.Villager);
+            msg3 += $"\n{Roles.All} - {strings.use_this_to_random_giveaway}";
+            foreach (var role in rolesList)
+                msg3 += $"\n{roles.ResourceManager.GetString(role.ToString())} - `{role}`";
+            return await Bot.SendWithMarkdown2(ChatId, msg3);
+        }
+    }
+}

+ 46 - 3
MafiaTelegramBot/Other/GiveAway.cs

@@ -1,6 +1,9 @@
 using System.Collections.Generic;
+using System.Linq;
 using System.Threading.Tasks;
+using MafiaTelegramBot.DataBase.Entity;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
@@ -56,13 +59,53 @@ namespace MafiaTelegramBot.Other
             return true;
         }
 
-        public async Task<ResultCode> GivePrizeTo(long id)
+        public async Task<ResultCode> GivePrizeTo(Player player)
         {
-            if (!await TryDecreaseCount(id)) return ResultCode.NowYouGetPrizeFromThisGiveaway;
-            var player = await UserDao.GetPlayerById(id);
+            if (!await TryDecreaseCount(player.Id)) return ResultCode.NowYouGetPrizeFromThisGiveaway;
+            var firstPrize = _prize != Roles.All ? _prize : await GetRandomBaseRole(player.OpenedRoles);
+            var secondPrize = _prize != Roles.All ? Roles.None : await GetRandomRole();
+            if (player.OpenedRoles.TryOpenRole(firstPrize))
+            {
+                await Bot.SendStickerAsync(player.ChatId, Stickers.Sticker[firstPrize.ToString()]);
+                await Bot.SendWithMarkdown2(player.ChatId,$"{strings.congratulations_you_open_role} {roles.ResourceManager.GetString(firstPrize.ToString())}");
+            }
+            else await Bot.SendWithMarkdown2(player.ChatId,$"{strings.you_got_role} {roles.ResourceManager.GetString(firstPrize.ToString())} ({strings.now_opened})");
+            if (secondPrize != Roles.None && player.OpenedRoles.TryOpenRole(secondPrize))
+            {
+                await Bot.SendStickerAsync(player.ChatId, Stickers.Sticker[secondPrize.ToString()]);
+                await Bot.SendWithMarkdown2(player.ChatId,$"{strings.congratulations_you_additionally_open_role} {roles.ResourceManager.GetString(secondPrize.ToString())}");
+            }
+            else if(secondPrize != Roles.None) await Bot.SendWithMarkdown2(player.ChatId,$"{strings.you_additionally_got_role} {roles.ResourceManager.GetString(secondPrize.ToString())} ({strings.now_opened})");
             return ResultCode.CodeOk;
         }
 
+        private Task<Roles> GetRandomBaseRole(OpenedRolesEntity openedRoles)
+        {
+            return Task.Run(() =>
+            {
+                var allOpened = openedRoles.Hooker && openedRoles.Bodyguard && openedRoles.Elder && openedRoles.Werewolf;
+                if (allOpened)
+                    return Utilities.TierDictionary[2][Utilities.Rnd.Next(Utilities.TierDictionary[2].Count)];
+                var notOpened = Utilities.TierDictionary[2].Except(openedRoles.ToList()).ToArray();
+                return notOpened[Utilities.Rnd.Next(notOpened.Length)];
+            });
+        }
+
+        private Task<Roles> GetRandomRole()
+        {
+            return Task.Run(() =>
+            {
+                var chance = Utilities.Rnd.Next(100);
+                return chance switch
+                {
+                    <1 => Utilities.TierDictionary[5][Utilities.Rnd.Next(Utilities.TierDictionary[5].Count)],
+                    <5 => Utilities.TierDictionary[4][Utilities.Rnd.Next(Utilities.TierDictionary[4].Count)],
+                    <25 => Utilities.TierDictionary[3][Utilities.Rnd.Next(Utilities.TierDictionary[3].Count)],
+                    _ => Roles.None
+                };
+            });
+        }
+
         private async Task UpdateGiveAwayMessageOrDelete()
         {
             if (_count == 0)

+ 2 - 1
MafiaTelegramBot/Resources/Roles.cs

@@ -3,11 +3,13 @@ namespace MafiaTelegramBot.Resources
     public enum Roles
     {
         All,
+        None,
         Doctor, //Доктор
         Mafia, //Мафия
         Don, //Дон
         Cop, //Комиссар
         Villager, //Мирный житель
+        
         Hooker, //Проститутка
         Elder, //Старейшина
         Werewolf, //Оборотень
@@ -19,6 +21,5 @@ namespace MafiaTelegramBot.Resources
         Fool, //Дурачок
         Necromancer, //Некромант
         Bodyguard, //Телохранитель
-        None
     }
 }

+ 72 - 0
MafiaTelegramBot/Resources/strings.Designer.cs

@@ -1286,5 +1286,77 @@ namespace MafiaTelegramBot {
                 return ResourceManager.GetString("giveaway_link", resourceCulture);
             }
         }
+        
+        internal static string giveaway_now_ended {
+            get {
+                return ResourceManager.GetString("giveaway_now_ended", resourceCulture);
+            }
+        }
+        
+        internal static string congratulations_you_open_role {
+            get {
+                return ResourceManager.GetString("congratulations_you_open_role", resourceCulture);
+            }
+        }
+        
+        internal static string you_got_role {
+            get {
+                return ResourceManager.GetString("you_got_role", resourceCulture);
+            }
+        }
+        
+        internal static string now_opened {
+            get {
+                return ResourceManager.GetString("now_opened", resourceCulture);
+            }
+        }
+        
+        internal static string you_additionally_got_role {
+            get {
+                return ResourceManager.GetString("you_additionally_got_role", resourceCulture);
+            }
+        }
+        
+        internal static string congratulations_you_additionally_open_role {
+            get {
+                return ResourceManager.GetString("congratulations_you_additionally_open_role", resourceCulture);
+            }
+        }
+        
+        internal static string now_you_get_prize_from_this_giveaway {
+            get {
+                return ResourceManager.GetString("now_you_get_prize_from_this_giveaway", resourceCulture);
+            }
+        }
+        
+        internal static string giveaway_sample_message {
+            get {
+                return ResourceManager.GetString("giveaway_sample_message", resourceCulture);
+            }
+        }
+        
+        internal static string giveaway_attentions {
+            get {
+                return ResourceManager.GetString("giveaway_attentions", resourceCulture);
+            }
+        }
+        
+        internal static string list_of_roles {
+            get {
+                return ResourceManager.GetString("list_of_roles", resourceCulture);
+            }
+        }
+        
+        internal static string use_this_to_random_giveaway {
+            get {
+                return ResourceManager.GetString("use_this_to_random_giveaway", resourceCulture);
+            }
+        }
+        
+        internal static string rate {
+            get {
+                return ResourceManager.GetString("rate", resourceCulture);
+            }
+        }
     }
 }

+ 36 - 0
MafiaTelegramBot/Resources/strings.resx

@@ -639,4 +639,40 @@
     <data name="giveaway_link" xml:space="preserve">
         <value>Ссылка на раздачу</value>
     </data>
+    <data name="giveaway_now_ended" xml:space="preserve">
+        <value>Раздача уже завершена</value>
+    </data>
+    <data name="congratulations_you_open_role" xml:space="preserve">
+        <value>Поздравляем! Вы открыли роль</value>
+    </data>
+    <data name="you_got_role" xml:space="preserve">
+        <value>Вы получили роль</value>
+    </data>
+    <data name="now_opened" xml:space="preserve">
+        <value>уже открыта</value>
+    </data>
+    <data name="you_additionally_got_role" xml:space="preserve">
+        <value>Вы дополнительно получили роль</value>
+    </data>
+    <data name="congratulations_you_additionally_open_role" xml:space="preserve">
+        <value>Поздравляем! Вы дополнительно открыли роль</value>
+    </data>
+    <data name="now_you_get_prize_from_this_giveaway" xml:space="preserve">
+        <value>Вы уже получили приз из данной раздачи</value>
+    </data>
+    <data name="giveaway_sample_message" xml:space="preserve">
+        <value>Чтобы создать раздачу опубликуйте в канале с ботом пост следующего содержания:\n```\n{0}\n{1} &lt;текст&gt;\n{2} &lt;ссылка&gt;\n{3} &lt;текст&gt;\n{4} &lt;приз&gt;\n{5} &lt;количество&gt;\n{6} &lt;имя пользователя без @, для отправки ссылки&gt;\n```</value>
+    </data>
+    <data name="giveaway_attentions" xml:space="preserve">
+        <value>Внимание! Все аргументы должны быть записаны в треугольных скобочках &lt;&gt;, иначе Бот не сможет разбить ваше сообщение на части корректно, также не используйте эти символы внутри аргументов. за работу данного функционала в случае несоблюдения требований разработчик ответственности не несет\nВнимание! В сообщении необходимо наличие всех параметров, кроме:\n{0} - при отсутствии этого аргумента, ссылка на раздачу отправлена не будет\n{1} и {2} - необходимо наличие одного из них, но можно использовать и совместно\nВнимание! В параметре {3} допустимо использование только целых неотрицательных чисел!\nВнимание! В параметре {4} Ссылка на изображение должна оканчиваться на .png или .jpg, изображение должно быть в открытом доступе и видно всему интернету, можно использовать сервис imgur для публикации изображений\nВнимание! В параметре {5} допускатеся использование только ключевых английских слов с большой буквы, список слов приведен ниже</value>
+    </data>
+    <data name="list_of_roles" xml:space="preserve">
+        <value>Список ролей:</value>
+    </data>
+    <data name="use_this_to_random_giveaway" xml:space="preserve">
+        <value>Используйте этот параметр для выдачи случайных ролей</value>
+    </data>
+    <data name="rate" xml:space="preserve">
+        <value>Ваш рейтинг</value>
+    </data>
 </root>

+ 21 - 0
MafiaTelegramBot/Utilities.cs

@@ -1,4 +1,5 @@
 using System;
+using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Models;
@@ -10,6 +11,26 @@ namespace MafiaTelegramBot
     public static class Utilities
     {
         public static readonly Random Rnd = new();
+
+        public static readonly Dictionary<int, List<Roles>> TierDictionary = new()
+        {
+            {
+                2,
+                new List<Roles> { Roles.Hooker, Roles.Elder, Roles.Bodyguard, Roles.Werewolf }
+            },
+            {
+                3,
+                new List<Roles> { Roles.Detective, Roles.Journalist, Roles.Dame }
+            },
+            {
+                4,
+                new List<Roles> { Roles.Lawyer, Roles.Necromancer }
+            },
+            {
+                5,
+                new List<Roles> { Roles.Parasite, Roles.Fool }
+            },
+        };
         
         public static Task<Message> GetResultCodeMessage(ResultCode code, long chatId)
         {