瀏覽代碼

Connect link to room

Tigran 4 年之前
父節點
當前提交
80b9cdffeb
共有 38 個文件被更改,包括 204 次插入208 次删除
  1. 24 41
      MafiaTelegramBot/Controllers/RoomController.cs
  2. 2 1
      MafiaTelegramBot/Game/GameRoles/CopRole.cs
  3. 2 1
      MafiaTelegramBot/Game/GameRoles/DoctorRole.cs
  4. 2 1
      MafiaTelegramBot/Game/GameRoles/DonRole.cs
  5. 2 1
      MafiaTelegramBot/Game/GameRoles/HookerRole.cs
  6. 2 1
      MafiaTelegramBot/Game/GameRoles/MafiaRole.cs
  7. 2 1
      MafiaTelegramBot/Game/GameRoles/Role.cs
  8. 2 1
      MafiaTelegramBot/Game/GameRoles/VillagerRole.cs
  9. 14 0
      MafiaTelegramBot/Game/GameRooms/ExtendedGameRoom.cs
  10. 12 43
      MafiaTelegramBot/Game/GameRooms/GameRoom.cs
  11. 38 0
      MafiaTelegramBot/Game/GameRooms/NormalGameRoom.cs
  12. 8 20
      MafiaTelegramBot/Game/Player.cs
  13. 0 7
      MafiaTelegramBot/Game/PrivateGameRoom.cs
  14. 12 44
      MafiaTelegramBot/Game/RoomEncrypter.cs
  15. 5 0
      MafiaTelegramBot/Models/Bot.cs
  16. 1 1
      MafiaTelegramBot/Models/Commands/Command.cs
  17. 1 2
      MafiaTelegramBot/Models/Commands/ConnectGameCommand.cs
  18. 1 2
      MafiaTelegramBot/Models/Commands/CreateGameCommand.cs
  19. 6 5
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/CreateRoomHandler.cs
  20. 2 3
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/EnterCodeHandler.cs
  21. 2 1
      MafiaTelegramBot/Models/Commands/DissolveRoomCommand.cs
  22. 3 1
      MafiaTelegramBot/Models/Commands/KickPlayerCommand.cs
  23. 1 1
      MafiaTelegramBot/Models/Commands/LeaveCommand.cs
  24. 3 3
      MafiaTelegramBot/Models/Commands/LookPlayersListCommand.cs
  25. 3 3
      MafiaTelegramBot/Models/Commands/RoomSettingsCommand.cs
  26. 26 5
      MafiaTelegramBot/Models/Commands/StartCommand.cs
  27. 3 2
      MafiaTelegramBot/Models/Commands/StartGameCommand.cs
  28. 1 2
      MafiaTelegramBot/Models/Inlines/ConnectToSelectedRoomQuery.cs
  29. 1 2
      MafiaTelegramBot/Models/Inlines/MakeExtendedGameQuery.cs
  30. 1 2
      MafiaTelegramBot/Models/Inlines/MakeNormalGameQuery.cs
  31. 1 2
      MafiaTelegramBot/Models/Inlines/MakePrivateRoomQuery.cs
  32. 1 2
      MafiaTelegramBot/Models/Inlines/MakePublicRoomQuery.cs
  33. 3 3
      MafiaTelegramBot/Models/Inlines/SetPlayersMaximumQuery.cs
  34. 4 3
      MafiaTelegramBot/Models/Inlines/TimerSwitchQuery.cs
  35. 2 0
      MafiaTelegramBot/Resources/Constants.cs
  36. 2 1
      MafiaTelegramBot/Resources/Keyboards.cs
  37. 6 0
      MafiaTelegramBot/Resources/strings.Designer.cs
  38. 3 0
      MafiaTelegramBot/Resources/strings.resx

+ 24 - 41
MafiaTelegramBot/Controllers/RoomController.cs

@@ -1,7 +1,9 @@
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Game.GameRooms;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 
@@ -11,19 +13,18 @@ namespace MafiaTelegramBot.Controllers
     {
         private static readonly Dictionary<string, GameRoom> OpenedGames = new();
 
-        public static async Task<ResultCode> CreateNewGame(Player owner, string roomName, bool extended, string secretPhrase = null)
+        public static async Task<ResultCode> CreateNewGame(Player creator, string roomName, bool isExtended, bool isPrivate)
         {
-            return await Task.Run(async () =>
+            return await Task.Run( () =>
             {
-                var gameExists = await Task.Run(() => OpenedGames.ContainsKey(roomName));
-                if (gameExists) return ResultCode.GameAlreadyExists;
-                if (!await owner.SetRoomKey(secretPhrase ?? roomName)) return ResultCode.UserAlreadyInGame;
-                var room = secretPhrase == null
-                    ? new GameRoom {Owner = owner, RoomName = roomName, IsExtended = extended}
-                    : new PrivateGameRoom {Owner = owner, RoomName = roomName, IsExtended = extended};
-                OpenedGames.Add(secretPhrase ?? roomName, room);
-                room.Players.Add(owner.Id, owner);
-                RoomEncrypter.CreateShortName(roomName);
+                var roomKey = RoomEncrypter.GetCode(roomName);
+                if (OpenedGames.ContainsKey(roomKey)) return ResultCode.GameAlreadyExists;
+                if (!creator.SetRoomName(roomName)) return ResultCode.UserAlreadyInGame;
+                GameRoom room = isExtended
+                    ? new ExtendedGameRoom {Owner = creator, RoomName = roomName, IsPrivate = isPrivate}
+                    : new NormalGameRoom {Owner = creator, RoomName = roomName, IsPrivate = isPrivate};
+                OpenedGames.Add(roomKey, room);
+                room.Players.Add(creator.Id, creator);
                 return ResultCode.CodeOk;
             });
         }
@@ -33,35 +34,31 @@ namespace MafiaTelegramBot.Controllers
             return await Task.Run(async () =>
             {
                 if (!OpenedGames.ContainsKey(roomKey)) return ResultCode.RoomDoesNotExist;
+                var roomName = RoomEncrypter.GetName(roomKey);
+                if (!player.SetRoomName(roomName)) return ResultCode.UserAlreadyInGame;
                 if (OpenedGames[roomKey].IsFilled()) return ResultCode.RoomIsFilled;
-                if (!await player.SetRoomKey(roomKey)) return ResultCode.UserAlreadyInGame;
                 OpenedGames[roomKey].Players.Add(player.Id, player);
                 await OpenedGames[roomKey].NotifyPlayersAbout(player.Id, $"{player.NickName} {strings.connected_to_game}");
                 return ResultCode.CodeOk;
             });
         }
 
-        public static async Task<List<Player>> GetPlayers(string roomKey)
+        public static List<Player> GetPlayers(string roomKey)
         {
-            return await Task.Run( ()=>
-            {
-                var room = OpenedGames[roomKey];
-                var users = room.Players.Values.ToList();
-                return users;
-            });
+                return OpenedGames[roomKey].Players.Values.ToList();
         }
         
         public static async Task<ResultCode> LeaveFromGame(Player player)
         {
             return await Task.Run(async () =>
             {
-                var roomKey = player.GetRoomKey();
+                var roomName = player.GetRoomName();
+                var roomKey = RoomEncrypter.GetCode(roomName);
                 if (!await player.RemoveGame()) return ResultCode.UserNotInGame;
                 OpenedGames[roomKey].Players.Remove(player.Id);
                 await OpenedGames[roomKey].NotifyPlayersAbout(player.Id, $"{player.NickName} {strings.leave_from_game}");
                 if (OpenedGames[roomKey].Players.Count >= 0) return ResultCode.CodeOk;
-                RoomEncrypter.RemoveShortName(OpenedGames[roomKey].RoomName);
-                if(OpenedGames[roomKey].IsPrivate) RoomEncrypter.Remove(OpenedGames[roomKey].RoomName);
+                RoomEncrypter.RemoveCode(roomName);
                 OpenedGames.Remove(roomKey);
                 return ResultCode.CodeOk;
             });
@@ -78,8 +75,7 @@ namespace MafiaTelegramBot.Controllers
                         await player.RemoveGame();
                         await Bot.SendWithMarkdown2(player.ChatId, strings.room_dissolved, Keyboards.MainMenu);
                     }
-                    RoomEncrypter.RemoveShortName(OpenedGames[roomKey].RoomName);
-                    if(OpenedGames[roomKey].IsPrivate) RoomEncrypter.Remove(OpenedGames[roomKey].RoomName);
+                    RoomEncrypter.RemoveCode(OpenedGames[roomKey].RoomName);
                     OpenedGames.Remove(roomKey);
                 }
             });
@@ -90,27 +86,14 @@ namespace MafiaTelegramBot.Controllers
             return await Task.Run(() =>
             {
                 var rooms = OpenedGames.Values.ToList();
-                List<GameRoom> publicRooms = new List<GameRoom>();
-                int countRooms = 0;
-                foreach (var room in rooms)
-                {
-                    if (room.IsPrivate) continue;
-                    if (room.IsFilled()) continue;
-                    publicRooms.Add(room);
-                    countRooms++;
-                    if (countRooms == 10) break;
-                }
-                return publicRooms;
+                foreach (var room in rooms.Where(room => room.IsPrivate || room.IsFilled())) rooms.Remove(room);
+                return rooms;
             });
         }
         
-        public static async Task<GameRoom> GetRoom(string roomKey)
+        public static GameRoom GetRoom(string roomKey)
         {
-            return await Task.Run( ()=>
-            {
-                var room = OpenedGames[roomKey];
-                return room;
-            });
+            return OpenedGames[roomKey];
         }
     }
 }

+ 2 - 1
MafiaTelegramBot/Game/GameRoles/CopRole.cs

@@ -12,7 +12,8 @@ namespace MafiaTelegramBot.Game.GameRoles
         
         protected override async Task<Message> NightAction(Player player)
         {
-            var room = await RoomController.GetRoom(player.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(player.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             //TODO this is what user can do in night phase
             return await Bot.SendWithMarkdown2(player.ChatId, strings.unexpected_error);
         }

+ 2 - 1
MafiaTelegramBot/Game/GameRoles/DoctorRole.cs

@@ -13,7 +13,8 @@ namespace MafiaTelegramBot.Game.GameRoles
         
         protected override async Task<Message> NightAction(Player player)
         {
-            var room = await RoomController.GetRoom(player.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(player.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             //TODO this is what user can do in night phase
             return await Bot.SendWithMarkdown2(player.ChatId, strings.unexpected_error);
         }

+ 2 - 1
MafiaTelegramBot/Game/GameRoles/DonRole.cs

@@ -13,7 +13,8 @@ namespace MafiaTelegramBot.Game.GameRoles
         
         protected override async Task<Message> NightAction(Player player)
         {
-            var room = await RoomController.GetRoom(player.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(player.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             //TODO this is what user can do in night phase
             return await Bot.SendWithMarkdown2(player.ChatId, strings.unexpected_error);
         }

+ 2 - 1
MafiaTelegramBot/Game/GameRoles/HookerRole.cs

@@ -13,7 +13,8 @@ namespace MafiaTelegramBot.Game.GameRoles
         
         protected override async Task<Message> NightAction(Player player)
         {
-            var room = await RoomController.GetRoom(player.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(player.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             //TODO this is what user can do in night phase
             return await Bot.SendWithMarkdown2(player.ChatId, strings.unexpected_error);
         }

+ 2 - 1
MafiaTelegramBot/Game/GameRoles/MafiaRole.cs

@@ -13,7 +13,8 @@ namespace MafiaTelegramBot.Game.GameRoles
         
         protected override async Task<Message> NightAction(Player player)
         {
-            var room = await RoomController.GetRoom(player.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(player.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             //TODO this is what user can do in night phase
             return await Bot.SendWithMarkdown2(player.ChatId, strings.unexpected_error);
         }

+ 2 - 1
MafiaTelegramBot/Game/GameRoles/Role.cs

@@ -13,7 +13,8 @@ namespace MafiaTelegramBot.Game.GameRoles
 
         protected async Task<Message> DayAction(Player player)
         {
-            var room = await RoomController.GetRoom(player.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(player.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             //TODO user telling anything in one minute and vote
             return await Bot.SendWithMarkdown2(player.ChatId, strings.unexpected_error);
         }

+ 2 - 1
MafiaTelegramBot/Game/GameRoles/VillagerRole.cs

@@ -13,7 +13,8 @@ namespace MafiaTelegramBot.Game.GameRoles
         
         protected override async Task<Message> NightAction(Player player)
         {
-            var room = await RoomController.GetRoom(player.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(player.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             //TODO this is what user can do in night phase
             return await Bot.SendWithMarkdown2(player.ChatId, strings.unexpected_error);
         }

+ 14 - 0
MafiaTelegramBot/Game/GameRooms/ExtendedGameRoom.cs

@@ -0,0 +1,14 @@
+using System.Threading.Tasks;
+
+namespace MafiaTelegramBot.Game.GameRooms
+{
+    public class ExtendedGameRoom : GameRoom
+    {
+        public override bool IsExtended { get; protected set; } = true;
+        
+        protected override Task ReadSettings()
+        {
+            throw new System.NotImplementedException();
+        }
+    }
+}

+ 12 - 43
MafiaTelegramBot/Game/GameRoom.cs → MafiaTelegramBot/Game/GameRooms/GameRoom.cs

@@ -10,16 +10,15 @@ using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types.ReplyMarkups;
 
-namespace MafiaTelegramBot.Game
+namespace MafiaTelegramBot.Game.GameRooms
 {
-    public class GameRoom
+    public abstract class GameRoom
     {
-        private bool _isRunning;
-
+        protected bool IsRunning;
         public int MaxPlayers = 10;
         private int _minPlayers = Constants.PLAYER_LIMITS_MIN;
-        public virtual bool IsPrivate { get; protected set; } = false;
-        public bool IsExtended { get; init; }
+        public bool IsPrivate { get; init; } = false;
+        public abstract bool IsExtended { get; protected set; }
         public bool TimerEnabled { get; set; } = true;
         public string RoomName { get; init; } = "NoNameRoom";
         public Player Owner { get; init; } = new();
@@ -42,7 +41,7 @@ namespace MafiaTelegramBot.Game
         {
             new Task(async () =>
             {
-                _isRunning = true;
+                IsRunning = true;
                 await FirstDay();
                 await GameCycle();
                 await EndOfGame();
@@ -77,11 +76,11 @@ namespace MafiaTelegramBot.Game
             {
                 foreach (var (_, player) in Players)
                     player.CurrentRole = Role.GetNewRoleInstance(Roles.None);
-                _isRunning = false;
+                IsRunning = false;
                 _turnOrder.Clear();
                 Thread.Sleep(10000);//TODO just for tests
                 if (!Players.ContainsKey(Owner.Id) || Players.Count == 0) new Task(async() => 
-                    await RoomController.DissolveRoom(IsPrivate ? RoomEncrypter.NameToCode(RoomName) : RoomName)).Start();
+                    await RoomController.DissolveRoom(RoomEncrypter.GetCode(RoomName))).Start();
                 else
                 {
                     await Bot.SendWithMarkdown2(Owner.ChatId, strings.thanks_for_game, Keyboards.OwnerGameMenu);
@@ -90,44 +89,13 @@ namespace MafiaTelegramBot.Game
             });
         }
 
-        private async Task ReadSettings()
-        {
-            if (!IsExtended) await SetNormalRoles();
-        }
+        protected abstract Task ReadSettings();
 
         private ResultCode CanStartGame()
         {
             if (Players.Count < _minPlayers) return ResultCode.TooFewPlayers;
             if (Players.Count > MaxPlayers) return ResultCode.TooManyPlayers;
-            return _isRunning ? ResultCode.GameAlreadyRunning : ResultCode.CodeOk;
-        }
-
-        private async Task SetNormalRoles()
-        {
-            await Task.Run(() =>
-            {
-                Settings[Roles.Villager] = Players.Count;
-                Settings[Roles.Cop] = 1;
-                if (Players.Count != 8) Settings[Roles.Doctor] = 1;
-                else Settings[Roles.Doctor] = 0;
-                if (Players.Count % 3 == 0)
-                {
-                    Settings[Roles.Mafia] = Players.Count / 3;
-                    Settings[Roles.Don] = 0;
-                }
-                else
-                {
-                    Settings[Roles.Mafia] = (Players.Count / 3) - 1;
-                    Settings[Roles.Don] = 1;
-                }
-
-                foreach (var (key, value) in Settings)
-                    if (key != Roles.Villager)
-                        Settings[Roles.Villager] -= value;
-                foreach (var (key, value) in Settings)
-                    if (value < 1)
-                        Settings.Remove(key);
-            });
+            return IsRunning ? ResultCode.GameAlreadyRunning : ResultCode.CodeOk;
         }
 
         public async Task<List<Player>> GetPlayers()
@@ -150,7 +118,8 @@ namespace MafiaTelegramBot.Game
                 for (var i = 0; i < _turnOrder.Count; ++i)
                 {
                     var user = _turnOrder.Dequeue();
-                    var next = roles.GetAndRemove(random.Next(roles.Count));
+                    var value = roles.Count == 1 ? 1 : random.Next(roles.Count - 1);
+                    var next = roles.GetAndRemove(value);
                     user.CurrentRole = (Role.GetNewRoleInstance(next));
                     _turnOrder.Enqueue(user);
                 }

+ 38 - 0
MafiaTelegramBot/Game/GameRooms/NormalGameRoom.cs

@@ -0,0 +1,38 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Resources;
+
+namespace MafiaTelegramBot.Game.GameRooms
+{
+    public class NormalGameRoom : GameRoom
+    {
+        public override bool IsExtended { get; protected set; } = false;
+
+        protected override async Task ReadSettings()
+        {
+            await Task.Run(() =>
+            {
+                Settings[Roles.Villager] = Players.Count;
+                Settings[Roles.Cop] = 1;
+                if (Players.Count != 8) Settings[Roles.Doctor] = 1;
+                else Settings[Roles.Doctor] = 0;
+                if (Players.Count % 3 == 0)
+                {
+                    Settings[Roles.Mafia] = Players.Count / 3;
+                    Settings[Roles.Don] = 0;
+                }
+                else
+                {
+                    Settings[Roles.Mafia] = (Players.Count / 3) - 1;
+                    Settings[Roles.Don] = 1;
+                }
+
+                foreach (var (key, value) in Settings)
+                    if (key != Roles.Villager)
+                        Settings[Roles.Villager] -= value;
+                foreach (var (key, value) in Settings)
+                    if (value < 1)
+                        Settings.Remove(key);
+            });
+        }
+    }
+}

+ 8 - 20
MafiaTelegramBot/Game/Player.cs

@@ -1,6 +1,5 @@
 #nullable enable
 using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase.Entity;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game.GameRoles;
@@ -13,7 +12,7 @@ namespace MafiaTelegramBot.Game
     {
         public Role CurrentRole = new NoneRole();
         public int TurnOrder = -1;
-        private string _roomKey = "";
+        private string _roomName = "";
         public static Player FromUserEntity(UserEntity b)
         {
             var serialized = JsonConvert.SerializeObject(b);
@@ -21,33 +20,22 @@ namespace MafiaTelegramBot.Game
             return a;
         }
 
-        public string GetRoomKey()
+        public string GetRoomName()
         {
-            return _roomKey;
+            return _roomName;
         }
 
-        public async Task<bool> SetRoomKey(string roomKey)
+        public bool SetRoomName(string roomName)
         {
-            if (_roomKey != "") return false;
-            _roomKey = roomKey;
-            await UserDao.Update(this);
+            if (_roomName != "") return false;
+            _roomName = roomName;
             return true;
         }
-
-        public async Task<string> GetRoomName()
-        {
-            return await Task.Run( async() =>
-            {
-                if (_roomKey == "") return "";
-                var room = await RoomController.GetRoom(_roomKey);
-                return room.RoomName;
-            });
-        }
         
         public async Task<bool> RemoveGame()
         {
-            if (_roomKey == "") return false;
-            _roomKey = "";
+            if (_roomName == "") return false;
+            _roomName = "";
             await UserDao.Update(this);
             return true;
         }

+ 0 - 7
MafiaTelegramBot/Game/PrivateGameRoom.cs

@@ -1,7 +0,0 @@
-namespace MafiaTelegramBot.Game
-{
-    public class PrivateGameRoom : GameRoom
-    {
-        public override bool IsPrivate { get; protected set; } = true;
-    }
-}

+ 12 - 44
MafiaTelegramBot/Game/RoomEncrypter.cs

@@ -1,75 +1,43 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using MafiaTelegramBot.Resources;
 
 namespace MafiaTelegramBot.Game
 {
     public static class RoomEncrypter
     {
-        private static readonly Dictionary<string, string> ToPassword = new();
-        private static readonly Dictionary<string, string> ToName = new();
-        
         private static readonly Dictionary<string, string> ShortName = new();
         private static readonly Dictionary<string, string> FullName = new();
         
-        public static string Encrypt(string roomName)
-        {
-            var pass = RandomString();
-            while (ToName.ContainsKey(pass)) pass = RandomString();
-            ToPassword.Add(roomName, pass);
-            ToName.Add(pass,roomName);
-            return pass;
-        }
-        
-        public static void CreateShortName(string roomName)
+        public static string GetCode(string roomName)
         {
+            if (ShortName.ContainsKey(roomName)) return ShortName[roomName];
             var shortName = RandomString();
             while (ShortName.ContainsKey(shortName)) shortName = RandomString();
             ShortName.Add(roomName, shortName);
-            FullName.Add(shortName,roomName);
+            FullName.Add(shortName, roomName);
+            return shortName;
         }
 
-        public static string CodeToName(string pass)
+        public static string GetName(string roomKey)
         {
-            return ToName.GetValueOrDefault(pass);
+            return FullName[roomKey];
         }
         
-        public static string FullToShort(string roomName)
-        {
-            return ShortName.GetValueOrDefault(roomName);
-        }
-
-        public static string NameToCode(string name)
-        {
-            return ToPassword.GetValueOrDefault(name);
-        }
-
-        public static string ShortToFull(string shortName)
+        public static void RemoveCode(string roomName)
         {
-            return FullName.GetValueOrDefault(shortName);
+            FullName.Remove(GetCode(roomName));
+            ShortName.Remove(roomName);
         }
         
-        private static readonly Random Random = new Random();
+        private static readonly Random Random = new();
 
-        private static string RandomString(int length = 6)
+        private static string RandomString(int length = Constants.ROOM_CODE_LENGTH)
         {
             const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
             return new string(Enumerable.Repeat(chars, length)
                 .Select(s => s[Random.Next(s.Length)]).ToArray());
         }
-
-        public static void Remove(string name)
-        {
-            var pass = NameToCode(name);
-            ToName.Remove(pass);
-            ToPassword.Remove(name);
-        }
-        
-        public static void RemoveShortName(string roomName)
-        {
-            var shortName = FullToShort(roomName);
-            FullName.Remove(shortName);
-            ShortName.Remove(roomName);
-        }
     }
 }

+ 5 - 0
MafiaTelegramBot/Models/Bot.cs

@@ -91,6 +91,11 @@ namespace MafiaTelegramBot.Models
         {
             return await Get().SendStickerAsync(chatId: chatId, sticker: url);
         }
+
+        public static async Task<Message> SendHyperLink(long chatId, string message)
+        {
+            return await Get().SendTextMessageAsync(chatId, message, ParseMode.Html);
+        }
         
         public static async Task<Message> SendWithMarkdown2(long chatId, string message, IReplyMarkup replyMarkup = null)
         {

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

@@ -13,7 +13,7 @@ namespace MafiaTelegramBot.Models.Commands
         {
             {"UsersThatChangesNickname", new ChangeNicknameHandler()},
             {"UsersThatCreatesRoom", new CreateRoomHandler()},
-            {"UserThatEntersPrivateCode", new EnterPrivateCodeHandler()},
+            {"UserThatEntersPrivateCode", new EnterCodeHandler()},
         };
 
         protected override bool IsMatches(string command)

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

@@ -1,5 +1,4 @@
 using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
@@ -13,7 +12,7 @@ namespace MafiaTelegramBot.Models.Commands
         protected override async Task<Message> Execute(Update update)
         {
             var user = await UserDao.GetPlayerById(UserId);
-            if (user.GetRoomKey() != "")
+            if (user.GetRoomName() != "")
                 return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
             return await Bot.SendWithMarkdown2(ChatId, strings.choose_type_room, 
                 Keyboards.RoomTypeKeyboard(UserId, Callback.ConnectToPrivateRoom, Callback.ConnectToPublicRoom));

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

@@ -1,5 +1,4 @@
 using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
@@ -14,7 +13,7 @@ namespace MafiaTelegramBot.Models.Commands
         {
             var user = await UserDao.GetPlayerById(UserId);
             await Bot.SendStickerWithoutPackAsync(ChatId, "https://github.com/TelegramBots/book/raw/master/src/docs/sticker-fred.webp");
-            if (user.GetRoomKey() != "")
+            if (user.GetRoomName() != "")
                 return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
             return await Bot.SendWithMarkdown2(ChatId, strings.choose_type_room, 
                 Keyboards.RoomTypeKeyboard(UserId, Callback.MakePrivateRoom, Callback.MakePublicRoom));

+ 6 - 5
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/CreateRoomHandler.cs

@@ -18,14 +18,15 @@ namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
             Bot.UsersThatCreatesRoom.Remove(UserId);
             var user = await UserDao.GetPlayerById(UserId);
             var roomName = update.Message.Text;
-            var resultCode = param[0] == "public"
-                ? await RoomController.CreateNewGame(user, roomName, isExtended)
-                : await RoomController.CreateNewGame(user, roomName, isExtended, RoomEncrypter.Encrypt(roomName));
+            var resultCode = await RoomController.CreateNewGame(user, roomName, isExtended, param[0] == "private");
             var result = resultCode == ResultCode.CodeOk
-                ? await Bot.SendWithMarkdown2(ChatId, $"{strings.room_with_name} _*{roomName}*_ {strings.was_created}", Keyboards.OwnerGameMenu)
+                ? await Bot.SendWithMarkdown2(ChatId, 
+                    $"{strings.room_with_name} _*{roomName}*_ {strings.was_created}\n", Keyboards.OwnerGameMenu)
                 : await Utilities.GetResultCodeMessage(resultCode, ChatId);
             if (resultCode == ResultCode.CodeOk && param[0] == "private")
-                await Bot.SendWithMarkdown2(ChatId, $"{strings.secret_key_is} _*{roomName}*_: ```{RoomEncrypter.NameToCode(roomName)}```");
+                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>");
             return result;
         }
     }

+ 2 - 3
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/EnterPrivateCodeHandler.cs → MafiaTelegramBot/Models/Commands/CustomMessageHandlers/EnterCodeHandler.cs

@@ -1,15 +1,14 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
 namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
 {
-    public class EnterPrivateCodeHandler : Command
+    public class EnterCodeHandler : Command
     {
-        protected override string Name => "EnterPrivateCodeHandler";
+        protected override string Name => "EnterCodeHandler";
 
         protected override async Task<Message> Execute(Update update)
         {

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

@@ -2,6 +2,7 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
@@ -13,7 +14,7 @@ namespace MafiaTelegramBot.Models.Commands
         protected override async Task<Message> Execute(Update update)
         { 
             var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = user.GetRoomKey();
+            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
             var resultCode = await RoomController.LeaveFromGame(user);
             var result = resultCode == ResultCode.CodeOk
                 ? await Bot.SendWithMarkdown2(ChatId, strings.room_dissolved, Keyboards.MainMenu)

+ 3 - 1
MafiaTelegramBot/Models/Commands/KickPlayerCommand.cs

@@ -1,6 +1,7 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
@@ -12,7 +13,8 @@ namespace MafiaTelegramBot.Models.Commands
         protected override async Task<Message> Execute(Update update)
         {
             var user = await UserDao.GetPlayerById(UserId);
-            var room = await RoomController.GetRoom(user.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             var players = await room.GetPlayers();
             if (players.Count > 0)
                 return await Bot.SendWithMarkdown2(ChatId, strings.kick_user, Keyboards.KickKeyboard(players));

+ 1 - 1
MafiaTelegramBot/Models/Commands/LeaveCommand.cs

@@ -14,7 +14,7 @@ namespace MafiaTelegramBot.Models.Commands
         protected override async Task<Message> Execute(Update update)
         {
             var user = await UserDao.GetPlayerById(UserId);
-            var roomName = await user.GetRoomName();
+            var roomName = user.GetRoomName();
             var resultCode = await RoomController.LeaveFromGame(user);
             return resultCode == ResultCode.CodeOk
                 ? await Bot.SendWithMarkdown2(ChatId, $"{strings.leave_from_game} _*{roomName}*_", Keyboards.MainMenu)

+ 3 - 3
MafiaTelegramBot/Models/Commands/LookPlayersListCommand.cs

@@ -1,8 +1,8 @@
 using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
@@ -15,8 +15,8 @@ namespace MafiaTelegramBot.Models.Commands
         protected override async Task<Message> Execute(Update update)
         {
             var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = user.GetRoomKey();
-            var users = await RoomController.GetPlayers(roomKey);
+            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
+            var users = RoomController.GetPlayers(roomKey);
             var list = users.Count > 1
                 ? users.Where(player => !player.Equals(user))
                     .Aggregate(strings.users_list, (current, player) => current + $"\n \n@{player.Username}\n{player.NickName}")

+ 3 - 3
MafiaTelegramBot/Models/Commands/RoomSettingsCommand.cs

@@ -1,7 +1,7 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
@@ -14,8 +14,8 @@ namespace MafiaTelegramBot.Models.Commands
         protected override async Task<Message> Execute(Update update)
         {
             var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = user.GetRoomKey();
-            var room = await RoomController.GetRoom(roomKey);
+            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             var roomMaxCapacity = room.MaxPlayers;
             var status = room.TimerEnabled ? strings.enabled : strings.disabled;
             await Bot.SendWithMarkdown2(ChatId, $"{strings.timer}: {status}", Keyboards.TimerSwitchKeyboard(UserId, room.TimerEnabled ? strings.disable : strings.enable));

+ 26 - 5
MafiaTelegramBot/Models/Commands/StartCommand.cs

@@ -1,4 +1,5 @@
 using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
@@ -12,13 +13,21 @@ namespace MafiaTelegramBot.Models.Commands
 
         protected override async Task<Message> Execute(Update update)
         {
+            var command = update.Message.Text.Split(' ');
+            Task<Message> result;
             if (await UserDao.UserExists(UserId))
             {
                 var player = await UserDao.GetPlayerById(UserId);
-                if (player.GetRoomKey() != "")
-                    return await Bot.SendWithMarkdown2(ChatId, $"{strings.prefer_leave_from_room} {await player.GetRoomName()}");
-                return await Bot.SendWithMarkdown2(ChatId, strings.start_message, Keyboards.MainMenu);
-            } 
+                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, Keyboards.MainMenu);
+                var code = await RoomController.ConnectToGame(player, command[1]);
+                result = code == ResultCode.CodeOk
+                    ? Bot.SendWithMarkdown2(ChatId, strings.successful_entry_into_room, Keyboards.PlayerGameMenu)
+                    : Utilities.GetResultCodeMessage(code, ChatId);
+                return await result;
+            }
             var username = await Utilities.EscapeSpecific(update.Message.From.Username);
             var firstName = await Utilities.EscapeSpecific(update.Message.From.FirstName);
             var lastName = await Utilities.EscapeSpecific(update.Message.From.LastName);
@@ -27,7 +36,19 @@ namespace MafiaTelegramBot.Models.Commands
                 Id = UserId, ChatId = ChatId, Username = username, NickName =  $"{firstName} {lastName}"
             };
             await UserDao.Update(user);
-            return await Bot.SendWithMarkdown2(ChatId, strings.start_message, Keyboards.MainMenu);
+            if (command.Length <= 1)
+                return await Bot.SendWithMarkdown2(ChatId, strings.start_message, Keyboards.MainMenu);
+            var resultCode = await RoomController.ConnectToGame(user, command[1]);
+            result = resultCode == ResultCode.CodeOk
+                ? Bot.SendWithMarkdown2(ChatId, strings.successful_entry_into_room, Keyboards.PlayerGameMenu)
+                : Utilities.GetResultCodeMessage(resultCode, ChatId);
+            return await result;
+        }
+
+        protected override bool IsMatches(string command)
+        {
+            var commandPart = command.Split(' ')[0];
+            return base.IsMatches(commandPart);
         }
     }
 }

+ 3 - 2
MafiaTelegramBot/Models/Commands/StartGameCommand.cs

@@ -1,7 +1,7 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
@@ -13,7 +13,8 @@ namespace MafiaTelegramBot.Models.Commands
         protected override async Task<Message> Execute(Update update)
         {
             var owner = await UserDao.GetPlayerById(UserId);
-            var room = await RoomController.GetRoom(owner.GetRoomKey());
+            var roomKey = RoomEncrypter.GetCode(owner.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             var result = await Bot.SendWithMarkdown2(owner.ChatId, strings.game_process_started);
             var resultCode = await room.Prepare();
             if (resultCode != ResultCode.CodeOk) return await Utilities.GetResultCodeMessage(resultCode, ChatId);

+ 1 - 2
MafiaTelegramBot/Models/Inlines/ConnectToSelectedRoomQuery.cs

@@ -1,6 +1,5 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
@@ -18,7 +17,7 @@ namespace MafiaTelegramBot.Models.Inlines
             var data = update.CallbackQuery.Data;
             var param = data.Split('|');
             var shortName = param[2];
-            var roomName = RoomEncrypter.ShortToFull(shortName);
+            var roomName = RoomEncrypter.GetName(shortName);
             var user = await UserDao.GetPlayerById(UserId);
             var resultCode = await RoomController.ConnectToGame(user, roomName);
             if (resultCode != ResultCode.CodeOk) return await Utilities.GetResultCodeMessage(resultCode, ChatId);

+ 1 - 2
MafiaTelegramBot/Models/Inlines/MakeExtendedGameQuery.cs

@@ -1,5 +1,4 @@
 using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
@@ -16,7 +15,7 @@ namespace MafiaTelegramBot.Models.Inlines
             var data = update.CallbackQuery.Data;
             var param = data.Split('|');
             var user = await UserDao.GetPlayerById(UserId);
-            if (user.GetRoomKey() != "")
+            if (user.GetRoomName() != "")
                 return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
             if (Bot.UsersThatCreatesRoom.TryAdd(UserId, new[] {param[2], Name.ToString()}))
                 Bot.UsersThatCreatesRoom[UserId] = new[] {param[2], Name.ToString()};

+ 1 - 2
MafiaTelegramBot/Models/Inlines/MakeNormalGameQuery.cs

@@ -1,5 +1,4 @@
 using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
@@ -16,7 +15,7 @@ namespace MafiaTelegramBot.Models.Inlines
             var data = update.CallbackQuery.Data;
             var param = data.Split('|');
             var user = await UserDao.GetPlayerById(UserId);
-            if (user.GetRoomKey() != "")
+            if (user.GetRoomName() != "")
                 return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
             if (Bot.UsersThatCreatesRoom.TryAdd(UserId, new[] {param[2], Name.ToString()}))
                 Bot.UsersThatCreatesRoom[UserId] = new[] {param[2], Name.ToString()};

+ 1 - 2
MafiaTelegramBot/Models/Inlines/MakePrivateRoomQuery.cs

@@ -1,5 +1,4 @@
 using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
@@ -14,7 +13,7 @@ namespace MafiaTelegramBot.Models.Inlines
         {
             await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var user = await UserDao.GetPlayerById(UserId);
-            if (user.GetRoomKey() != "")
+            if (user.GetRoomName() != "")
                 return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
             return await Bot.SendWithMarkdown2(ChatId, strings.choose_game_type, Keyboards.NormalExtendedKeyboard(UserId, "private"));
         }

+ 1 - 2
MafiaTelegramBot/Models/Inlines/MakePublicRoomQuery.cs

@@ -1,5 +1,4 @@
 using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
@@ -14,7 +13,7 @@ namespace MafiaTelegramBot.Models.Inlines
         { 
             await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var user = await UserDao.GetPlayerById(UserId);
-            if (user.GetRoomKey() != "")
+            if (user.GetRoomName() != "")
                 return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
             return await Bot.SendWithMarkdown2(ChatId, strings.choose_game_type, Keyboards.NormalExtendedKeyboard(UserId, "public"));
         }

+ 3 - 3
MafiaTelegramBot/Models/Inlines/SetPlayersMaximumQuery.cs

@@ -1,7 +1,7 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
@@ -17,8 +17,8 @@ namespace MafiaTelegramBot.Models.Inlines
             var data = update.CallbackQuery.Data;
             var count = int.Parse(data.Split('|')[2]);
             var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = user.GetRoomKey();
-            var room = await RoomController.GetRoom(roomKey);
+            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
             room.MaxPlayers = count;
             var message = $"{strings.maximum_was_set_to}: _*{count}*_ {strings.players}";
             return await Bot.SendWithMarkdown2(ChatId, message);

+ 4 - 3
MafiaTelegramBot/Models/Inlines/TimerSwitchQuery.cs

@@ -1,7 +1,7 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 
@@ -14,8 +14,9 @@ namespace MafiaTelegramBot.Models.Inlines
         {
             await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = user.GetRoomKey();
-            var room = await RoomController.GetRoom(roomKey);
+            var roomName = user.GetRoomName();
+            var roomKey = RoomEncrypter.GetCode(roomName);
+            var room = RoomController.GetRoom(roomKey);
             room.TimerEnabled = !room.TimerEnabled;
             var status = room.TimerEnabled ? strings.enabled : strings.disabled;
             return await Bot.SendWithMarkdown2(ChatId, $"{strings.timer}: {status}");

+ 2 - 0
MafiaTelegramBot/Resources/Constants.cs

@@ -5,5 +5,7 @@ namespace MafiaTelegramBot.Resources
         public const int PLAYER_LIMITS_MIN = 1;
         public const int PLAYER_LIMITS_MAX = 16;
         public const int MAX_SHOWING_ROOMS = 10;
+
+        public const int ROOM_CODE_LENGTH = 6;
     }
 }

+ 2 - 1
MafiaTelegramBot/Resources/Keyboards.cs

@@ -2,6 +2,7 @@ using System.Collections.Generic;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.Entity;
 using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Game.GameRooms;
 using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Resources
@@ -110,7 +111,7 @@ namespace MafiaTelegramBot.Resources
                 inlineButtons[i] = new InlineKeyboardButton
                 {
                     Text = $"[{s}] {rooms[i].RoomName} ({rooms[i].Players.Values.Count.ToString()}/{rooms[i].MaxPlayers.ToString()})",
-                    CallbackData = $"{Callback.ConnectToSelectedRoom}|{userId}|{RoomEncrypter.FullToShort(rooms[i].RoomName)}"
+                    CallbackData = $"{Callback.ConnectToSelectedRoom}|{userId}|{RoomEncrypter.GetCode(rooms[i].RoomName)}"
                 };
             }
             return new InlineKeyboardMarkup(inlineButtons);

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

@@ -422,5 +422,11 @@ namespace MafiaTelegramBot {
                 return ResourceManager.GetString("thanks_for_game", resourceCulture);
             }
         }
+        
+        internal static string link {
+            get {
+                return ResourceManager.GetString("link", resourceCulture);
+            }
+        }
     }
 }

+ 3 - 0
MafiaTelegramBot/Resources/strings.resx

@@ -207,4 +207,7 @@
     <data name="thanks_for_game" xml:space="preserve">
         <value>Игра окончена, спасибо за игру!</value>
     </data>
+    <data name="link" xml:space="preserve">
+        <value>Ссылка для подключения к комнате</value>
+    </data>
 </root>