Ver Fonte

Pack Logic

Tigran há 4 anos atrás
pai
commit
646a13f80f

+ 3 - 0
MafiaTelegramBot/DataBase/Entity/UserEntity.cs

@@ -2,6 +2,7 @@ using System.ComponentModel.DataAnnotations;
 using System.ComponentModel.DataAnnotations.Schema;
 using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase.EntityDao;
+using Telegram.Bot.Requests;
 
 namespace MafiaTelegramBot.DataBase.Entity
 {
@@ -19,5 +20,7 @@ namespace MafiaTelegramBot.DataBase.Entity
         [Column("rank_number") , MaxLength(127)] public int RankNumber { get; set; } = 0;
         
         [Column("is_admin"), MaxLength(127)] public int IsAdmin { get; set; } = 0;
+
+        [Column("pack_count"), MaxLength(127)] public int PackCount { get; set; } = 0;
     }
 }

+ 3 - 0
MafiaTelegramBot/Models/Bot.cs

@@ -91,6 +91,9 @@ namespace MafiaTelegramBot.Models
                 new GiveRoleQuery(),
                 new GiveToAllQuery(),
                 new ContinueQuery(),
+                new PackInfoQuery(),
+                new PackOpenQuery(),
+                new ShowMyPacksQuery(),
             };
         }
         

+ 1 - 0
MafiaTelegramBot/Models/Commands/Command.cs

@@ -34,6 +34,7 @@ namespace MafiaTelegramBot.Models.Commands
             if (!await UserDao.UserExists(userId)) await Bot.RegisterNewUser(update);
             
             var user = await UserDao.GetPlayerById(userId);
+            if (user.Username != update.Message.From.Username) user.Username = update.Message.From.Username;
             user.SetActive();
             var commands = Bot.Commands;
             var message = update.Message.Text;

+ 16 - 0
MafiaTelegramBot/Models/Inlines/PackInfoQuery.cs

@@ -0,0 +1,16 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Models.Inlines
+{
+    public class PackInfoQuery : Query
+    {
+        protected override Callback Name => Callback.PackInfo;
+        protected override async Task<Message> Execute(Update update)
+        {
+            var msg1 = strings.pack_information.Replace("\\n", "\\\n");
+            return await Bot.SendWithMarkdown2(ChatId, msg1);
+        }
+    }
+}

+ 66 - 0
MafiaTelegramBot/Models/Inlines/PackOpenQuery.cs

@@ -0,0 +1,66 @@
+using System.Linq;
+using System.Threading.Tasks;
+using MafiaTelegramBot.DataBase.Entity;
+using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Models.Inlines
+{
+    public class PackOpenQuery : Query
+    {
+        protected override Callback Name => Callback.PackOpen;
+        protected override async Task<Message> Execute(Update update)
+        {
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            var user = await UserDao.GetPlayerById(UserId);
+            if (user.User.PackCount <= 0) return await Bot.SendWithMarkdown2(ChatId, strings.you_havent_pack);
+            user.User.PackCount--;
+            var baseRole = await GetRandomBaseRole(user.OpenedRoles);
+            if (user.OpenedRoles.TryOpenRole(baseRole))
+            {
+                await Bot.SendStickerAsync(ChatId, Stickers.Sticker[baseRole.ToString()]);
+                await Bot.SendWithMarkdown2(ChatId,$"{strings.congratulations_you_open_role} {roles.ResourceManager.GetString(baseRole.ToString())}");
+            }
+            else await Bot.SendWithMarkdown2(ChatId,$"{strings.you_got_role} {roles.ResourceManager.GetString(baseRole.ToString())} ({strings.now_opened})");
+            var addRole = await GetRandomRole();
+            if (addRole != Roles.None)
+            {
+                if (user.OpenedRoles.TryOpenRole(addRole))
+                {
+                    await Bot.SendStickerAsync(ChatId, Stickers.Sticker[addRole.ToString()]);
+                    await Bot.SendWithMarkdown2(ChatId,$"{strings.congratulations_you_open_role} {roles.ResourceManager.GetString(addRole.ToString())}");
+                }
+                else await Bot.SendWithMarkdown2(ChatId,$"{strings.you_got_role} {roles.ResourceManager.GetString(addRole.ToString())} ({strings.now_opened})");
+            }
+            return new Message();
+        }
+        
+        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
+                };
+            });
+        }
+    }
+}

+ 19 - 0
MafiaTelegramBot/Models/Inlines/ShowMyPacksQuery.cs

@@ -0,0 +1,19 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Models.Inlines
+{
+    public class ShowMyPacksQuery : Query
+    {
+        protected override Callback Name => Callback.ShowMyPacks;
+        protected override async Task<Message> Execute(Update update)
+        {
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            var player = await UserDao.GetPlayerById(UserId);
+            await Bot.SendStickerAsync(ChatId, Stickers.Sticker["Pool"]);
+            return await Bot.SendWithMarkdown2(ChatId, $"{strings.your_packs} {player.User.PackCount}", Keyboard.PackKeyboard(player.Id));
+        }
+    }
+}

+ 8 - 33
MafiaTelegramBot/Other/GiveAway.cs

@@ -62,55 +62,30 @@ namespace MafiaTelegramBot.Other
         public async Task<ResultCode> GivePrizeTo(Player player)
         {
             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 (_prize is Roles.All) return await GivePackToUser(player);
+            var firstPrize = _prize;
             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()
+        private static async Task<ResultCode> GivePackToUser(Player player)
         {
-            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
-                };
-            });
+            player.User.PackCount++;
+            await Bot.SendStickerAsync(player.ChatId, Stickers.Sticker["Pool"]);
+            await Bot.SendWithMarkdown2(player.ChatId, $"{strings.your_packs} {player.User.PackCount}", Keyboard.PackKeyboard(player.Id));
+            return ResultCode.CodeOk;
         }
 
         private async Task UpdateGiveAwayMessageOrDelete()
         {
             if (_count == 0)
             {
-                await Bot.Get().DeleteMessageAsync(_chatId, _messageId);
+                await Bot.Get().EditMessageTextAsync(_chatId, _messageId, strings.giveaway_ended);
                 OpenedGiveaways.Remove(_id);
                 _awardedIdList.Clear();
             }

+ 4 - 1
MafiaTelegramBot/Resources/Callback.cs

@@ -31,6 +31,9 @@ namespace MafiaTelegramBot.Resources
         GiveToAll,
         GiveToSelected,
         GiveRole,
-        Continue
+        Continue,
+        PackOpen,
+        PackInfo,
+        ShowMyPacks
     }
 }

+ 5 - 5
MafiaTelegramBot/Resources/Constants.cs

@@ -17,11 +17,11 @@ namespace MafiaTelegramBot.Resources
         public const int MINUTES_UNTIL_DISSOLVE = 10;
         public const int MAX_SHOWING_ROOMS = 10;
 
-        public const int TIME_TO_DECIDE = DEBUG ? 10*1000 : 30 * 1000;
+        public const int TIME_TO_DECIDE = DEBUG ? 20*1000 : 30 * 1000;
         
         public const int ACTIVE_MAFIA_CHANCE = 30;
         public const int ACTIVE_VILLAGER_CHANCE = 50;
-        public const int PLAYERS_TO_START_FAST_GAME = DEBUG ? 1 : 10;
+        public const int PLAYERS_TO_START_FAST_GAME = DEBUG ? 5 : 10;
         
         public const string SHOP_CURRENCY = "RUB";
         public static List<LabeledPrice> RANDOM_ROLE_PRICE = new()
@@ -32,9 +32,9 @@ namespace MafiaTelegramBot.Resources
         public const bool ENABLE_AUTO_VOTING = !DEBUG;
 
         public const int FIRST_NIGHT_INTERVAL = DEBUG ? 1*1000 : 10 * 1000;
-        public const int PUT_UP_VOTE_INTERVAL = DEBUG ? 1*1000 : 20 * 1000;
-        public const int VOTE_KILL_INTERVAL = DEBUG ? 1*1000 : 20 * 1000;
-        public const int NIGHT_ACTION_INTERVAL = DEBUG ? 1*1000 : 60 * 1000;
+        public const int PUT_UP_VOTE_INTERVAL = DEBUG ? 20*1000 : 20 * 1000;
+        public const int VOTE_KILL_INTERVAL = DEBUG ? 20*1000 : 20 * 1000;
+        public const int NIGHT_ACTION_INTERVAL = DEBUG ? 20*1000 : 60 * 1000;
         public const int DEFENCE_INTERVAL = DEBUG ? 1*1000 : 30 * 1000;
         public const int DAY_SPEAK_INTERVAL = DEBUG ? 1*1000 : 60 * 1000;
         public const int DISPATCH_SPEAK_INTERVAL = DEBUG ? 1*1000 : 60 * 1000;

+ 13 - 1
MafiaTelegramBot/Resources/Keyboard.cs

@@ -151,7 +151,10 @@ namespace MafiaTelegramBot.Resources
                     InlineKeyboardButton.WithCallbackData(strings.shop, $"{Callback.ShopMenu}|{userId}"),
                     InlineKeyboardButton.WithCallbackData(strings.settings, $"{Callback.SettingsProfile}|{userId}")
                 },
-                new [] {InlineKeyboardButton.WithCallbackData(strings.my_roles, $"{Callback.ShowMyRoles}|{userId}")},
+                new[] {
+                    InlineKeyboardButton.WithCallbackData(strings.my_roles, $"{Callback.ShowMyRoles}|{userId}"),
+                    InlineKeyboardButton.WithCallbackData(strings.my_packs, $"{Callback.ShowMyPacks}|{userId}")
+                },
                 new [] {InlineKeyboardButton.WithCallbackData(strings.extended_stats, $"{Callback.ShowMyExtendedStats}|{userId}")}
             });
         }
@@ -354,5 +357,14 @@ namespace MafiaTelegramBot.Resources
                 }
             );
         }
+
+        public static InlineKeyboardMarkup PackKeyboard(long userId)
+        {
+            return new InlineKeyboardMarkup(new[]
+            {
+                new[]{ InlineKeyboardButton.WithCallbackData(strings.pack_open, $"{Callback.PackOpen}|{userId}") },
+                new[]{ InlineKeyboardButton.WithCallbackData(strings.pack_info, $"{Callback.PackInfo}|{userId}") },
+            });
+        }
     }
 }

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

@@ -1418,5 +1418,47 @@ namespace MafiaTelegramBot {
                 return ResourceManager.GetString("you_continued_the_game", resourceCulture);
             }
         }
+        
+        internal static string giveaway_ended {
+            get {
+                return ResourceManager.GetString("giveaway_ended", resourceCulture);
+            }
+        }
+        
+        internal static string your_packs {
+            get {
+                return ResourceManager.GetString("your_packs", resourceCulture);
+            }
+        }
+        
+        internal static string pack_open {
+            get {
+                return ResourceManager.GetString("pack_open", resourceCulture);
+            }
+        }
+        
+        internal static string pack_info {
+            get {
+                return ResourceManager.GetString("pack_info", resourceCulture);
+            }
+        }
+        
+        internal static string you_havent_pack {
+            get {
+                return ResourceManager.GetString("you_havent_pack", resourceCulture);
+            }
+        }
+        
+        internal static string pack_information {
+            get {
+                return ResourceManager.GetString("pack_information", resourceCulture);
+            }
+        }
+        
+        internal static string my_packs {
+            get {
+                return ResourceManager.GetString("my_packs", resourceCulture);
+            }
+        }
     }
 }

+ 21 - 0
MafiaTelegramBot/Resources/strings.resx

@@ -705,4 +705,25 @@
     <data name="you_continued_the_game" xml:space="preserve">
         <value>Вы остались в комнате</value>
     </data>
+    <data name="giveaway_ended" xml:space="preserve">
+        <value>Раздача закончилась. Вам повезет в следующий раз.</value>
+    </data>
+    <data name="your_packs" xml:space="preserve">
+        <value>Ваши наборы</value>
+    </data>
+    <data name="pack_open" xml:space="preserve">
+        <value>Открыть набор</value>
+    </data>
+    <data name="pack_info" xml:space="preserve">
+        <value>Информация о наборе</value>
+    </data>
+    <data name="you_havent_pack" xml:space="preserve">
+        <value>У вас нет наборов</value>
+    </data>
+    <data name="pack_information" xml:space="preserve">
+        <value>Это наборы, из которых могут выпасть роли, согласно правилам:\nВыпадает гарантированно одна из "Редких" ролей:\nРедкость: Редкие\nПроститутка\nСтарейшниа\nТелохранитель\nОборотень\n\nДополнительно выпадает одна из ролей с вероятностью: 25%\nРедкость: Мифические\nДетектив\nЖурналист\nДама\n\nДополнительно выпадает одна из ролей с вероятностью: 5%\nРедкость: Эпические\nАдвокат\nНекромант\n\nДополнительно выпадает одна из ролей с вероятностью: 1%\nРедкость: Легендарные\nПаразит\nДурачок\n\nРоль "Редкой" редкости выпадает гарантированно. Сначала будут выпадать одни из тех, которая отсутствует у игрока. Когда будут все из этих ролей, то выпадать будет любая\nРоли редкостей выше будут выпадать дополнительно (выпадает любая, даже та, которая у игрока есть)\nТаким образом, открывая набор, игрок гарантированно получает одну "Редкую" роль и с определенным шансом одну роль редкости "Мифическая" и выше</value>
+    </data>
+    <data name="my_packs" xml:space="preserve">
+        <value>Мои наборы</value>
+    </data>
 </root>