Quellcode durchsuchen

Migrate to Enum

Tigran vor 4 Jahren
Ursprung
Commit
1e2aebb945

+ 15 - 29
MafiaTelegramBot/Controllers/RoomController.cs

@@ -1,4 +1,3 @@
-using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
@@ -12,30 +11,31 @@ namespace MafiaTelegramBot.Controllers
     {
         private static readonly Dictionary<string, GameRoom> OpenedGames = new();
 
-        public static async Task<int> CreateNewGame(User owner, string roomName, bool extended, string secretPhrase = null)
+        public static async Task<ResultCode> CreateNewGame(User owner, string roomName, bool extended, string secretPhrase = null)
         {
             var gameExists = await Task.Run(() => OpenedGames.ContainsKey(roomName));
             return await Task.Run(async () =>
             {
-                if (gameExists) return Constants.GAME_EXISTS;
-                if (!await owner.SetCurrentGame(roomName)) return Constants.USER_ALREADY_IN_GAME;
+                if (gameExists) return ResultCode.GameAlreadyExists;
+                if (!await owner.SetRoomKey(secretPhrase ?? roomName)) return ResultCode.UserAlreadyInGame;
                 var room = secretPhrase == null
                     ? new GameRoom {Creator = owner, RoomName = roomName, IsExtended = extended}
                     : new PrivateGameRoom {Creator = owner, RoomName = roomName, IsExtended = extended};
                 OpenedGames.Add(secretPhrase ?? roomName, room);
                 room.Players.Add(owner.Username, owner);
-                return Constants.CODE_OK;
+                return ResultCode.CodeOk;
             });
         }
 
-        public static async Task<int> ConnectToGame(User player, string roomKey)
+        public static async Task<ResultCode> ConnectToGame(User player, string roomKey)
         {
             return await Task.Run(async () =>
             {
-                if (OpenedGames[roomKey].IsFilled()) return Constants.ROOM_IS_FILLED;
-                if (! await player.SetCurrentGame(OpenedGames[roomKey].RoomName)) return Constants.USER_ALREADY_IN_GAME;
+                if (OpenedGames[roomKey].IsFilled()) return ResultCode.RoomIsFilled;
+                if (OpenedGames.ContainsKey(roomKey)) return ResultCode.RoomIsFilled;
+                if (! await player.SetRoomKey(OpenedGames[roomKey].RoomName)) return ResultCode.UserAlreadyInGame;
                 OpenedGames[roomKey].Players.Add(player.Username, player);
-                return Constants.CODE_OK;
+                return ResultCode.CodeOk;
             });
         }
 
@@ -49,29 +49,15 @@ namespace MafiaTelegramBot.Controllers
             });
         }
         
-        public static async Task<int> LeaveFromGame(User player)
+        public static async Task<ResultCode> LeaveFromGame(User player)
         {
             return await Task.Run(async () =>
             {
-                var current = player.GetCurrentGame();
-                if (current == "") return Constants.USER_NOT_IN_GAME;
-                await player.RemoveGame();
-                try
-                {
-                    OpenedGames[current].Players.Remove(player.Username);
-                    if (OpenedGames[current].Players.Count == 0) OpenedGames.Remove(current);
-                }
-                catch (Exception)
-                {
-                    var pass = RoomEncrypter.NameToCode(current);
-                    OpenedGames[pass].Players.Remove(player.Username);
-                    if (OpenedGames[pass].Players.Count == 0)
-                    {
-                        OpenedGames.Remove(pass);
-                        RoomEncrypter.Remove(current);
-                    }
-                }
-                return Constants.CODE_OK;
+                var roomKey = player.GetRoomKey();
+                if (!await player.RemoveGame()) return ResultCode.UserNotInGame;
+                OpenedGames[roomKey].Players.Remove(player.Username);
+                if (OpenedGames[roomKey].Players.Count == 0) OpenedGames.Remove(roomKey);
+                return ResultCode.CodeOk;
             });
         }
 

+ 19 - 10
MafiaTelegramBot/DataBase/User.cs

@@ -1,8 +1,7 @@
 #nullable enable
-using System;
 using System.Collections.Generic;
 using System.Threading.Tasks;
-using MafiaTelegramBot.Resources;
+using MafiaTelegramBot.Controllers;
 
 namespace MafiaTelegramBot.DataBase
 {
@@ -16,7 +15,7 @@ namespace MafiaTelegramBot.DataBase
         public Dictionary<string, int> RoleGames = new();
         public Dictionary<string, int> RoleWins = new();
 
-        private string _currentGame = "";
+        private string _roomKey = "";
         
         public string FirstName { get; init; } = "";
         
@@ -28,23 +27,33 @@ namespace MafiaTelegramBot.DataBase
             await UserDao.Update(this);
         }
 
-        public string GetCurrentGame()
+        public string GetRoomKey()
         {
-            return _currentGame;
+            return _roomKey;
         }
 
-        public async Task<bool> SetCurrentGame(string roomName)
+        public async Task<bool> SetRoomKey(string roomKey)
         {
-            if (_currentGame != "") return false;
-            _currentGame = roomName;
+            if (_roomKey != "") return false;
+            _roomKey = roomKey;
             await UserDao.Update(this);
             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 (_currentGame == "") return false;
-            _currentGame = "";
+            if (_roomKey == "") return false;
+            _roomKey = "";
             await UserDao.Update(this);
             return true;
         }

+ 11 - 11
MafiaTelegramBot/DataBase/UserDao.cs

@@ -1,5 +1,3 @@
-#nullable enable
-using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
@@ -9,10 +7,12 @@ namespace MafiaTelegramBot.DataBase
     public static class UserDao
     {
         private static readonly List<User> DataBase = new();
-        public static async Task<User?> GetUserById(long id)
+        private static readonly Dictionary<long,User> ActiveUsers = new();
+        public static async Task<User> GetUserById(long id)
         {
-            User? user = null;
-            await Task.Run(()=> user = DataBase.FirstOrDefault(user1 => user1.Id == id));
+            if (ActiveUsers.ContainsKey(id)) return ActiveUsers[id];
+            var user = await Task.Run(()=> DataBase.First(user1 => user1.Id == id));
+            ActiveUsers.Add(user.Id, user);
             return user;
         }
 
@@ -27,13 +27,13 @@ namespace MafiaTelegramBot.DataBase
             if (updateIndex != -1) DataBase[updateIndex] = user;
             else DataBase.Add(user);
         }
-        //Temporary method
-        public static async Task AddNewUser(User _user)
+
+        public static async Task<bool> UserExists(long id)
         {
-            var user = await GetUserById(_user.Id);
-            if (user == null) {
-                await Update(_user);
-            }
+            return await Task.Run(() =>
+            {
+                return DataBase.Exists(user => user.Id == id);
+            });
         }
     }
 }

+ 11 - 7
MafiaTelegramBot/Game/GameRoom.cs

@@ -1,4 +1,5 @@
 using System.Collections.Generic;
+using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 
@@ -17,14 +18,17 @@ namespace MafiaTelegramBot.Game
         public readonly Dictionary<string, User> Players = new();
         public readonly Dictionary<string, string> Settings = new();
 
-        public int Start()
+        public async Task<ResultCode> Start()
         {
-            if (Players.Count < _minPlayers) return Constants.TOO_FEW_PLAYERS;
-            if (Players.Count > MaxPlayers) return Constants.TOO_MANY_PLAYERS;
-            if (_isRunning) return Constants.GAME_ALREADY_RUNNING;
-            _isRunning = true;
-            //TODO game start logic
-            return Constants.CODE_OK;
+            return await Task.Run(() =>
+            {
+                if (Players.Count < _minPlayers) return ResultCode.TooFewPlayers;
+                if (Players.Count > MaxPlayers) return ResultCode.TooManyPlayers;
+                if (_isRunning) return ResultCode.GameAlreadyRunning;
+                _isRunning = true;
+                //TODO game start logic
+                return ResultCode.CodeOk;
+            });
         }
 
         public bool IsFilled()

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

@@ -17,8 +17,8 @@ namespace MafiaTelegramBot.Models.Commands
             var userId = update.Message.From.Id;
             
             var user = await UserDao.GetUserById(userId);
-            if (user?.GetCurrentGame() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{user?.GetCurrentGame()}*_");
+            if (user.GetRoomKey() != "")
+                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {
                 new[] {InlineKeyboardButton.WithCallbackData(strings.connect_to_public_room, $"{strings.connect_to_public_room_callback}|{userId}")},

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

@@ -15,8 +15,8 @@ namespace MafiaTelegramBot.Models.Commands
             var userId = update.Message.From.Id;
             await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
             var user = await UserDao.GetUserById(userId);
-            if (user?.GetCurrentGame() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{user?.GetCurrentGame()}*_");
+            if (user.GetRoomKey() != "")
+                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {
                 new[] {InlineKeyboardButton.WithCallbackData(strings.make_public_room, $"{strings.make_public_room_callback}|{userId}")},

+ 9 - 10
MafiaTelegramBot/Models/Commands/CustomMessageHandlingCommand.cs

@@ -1,3 +1,4 @@
+using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
@@ -42,12 +43,11 @@ namespace MafiaTelegramBot.Models.Commands
             var resultCode = await RoomController.ConnectToGame(user, message);
             switch (resultCode)
             {
-                case Constants.CODE_OK:
+                case ResultCode.CodeOk:
                 {
                     var users = await RoomController.GetPlayers(message);
-                    foreach (var player in users)
+                    foreach (var player in users.Where(player => userId != player.Id))
                     {
-                        if (userId == player.Id) continue;
                         await Bot.SendWithMarkdown2(player.ChatId, $"{strings.entry_another_user} _*{user?.Username}*_");
                     }
                     var keyboard = new InlineKeyboardMarkup(new []
@@ -59,9 +59,9 @@ namespace MafiaTelegramBot.Models.Commands
                     });
                     return await Bot.SendWithMarkdown2(chatId, strings.successful_entry_into_room, keyboard);
                 }
-                case Constants.ROOM_IS_FILLED:
+                case ResultCode.RoomIsFilled:
                     return await Bot.SendWithMarkdown2(chatId, strings.room_is_filled);
-                case Constants.USER_ALREADY_IN_GAME:
+                case ResultCode.UserAlreadyInGame:
                     return await Bot.SendWithMarkdown2(chatId, strings.user_already_in_game);
                 default:
                     return await Bot.SendWithMarkdown2(chatId, strings.unexpected_error);
@@ -90,15 +90,14 @@ namespace MafiaTelegramBot.Models.Commands
                 },
                 true
             );
-
             var result = resultCode switch
             {
-                Constants.CODE_OK => await Bot.SendWithMarkdown2(chatId, $"{strings.room_with_name} _*{roomName}*_ {strings.was_created}", keyboard),
-                Constants.USER_ALREADY_IN_GAME => await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{user?.GetCurrentGame()}*_"),
-                Constants.GAME_EXISTS => await Bot.SendWithMarkdown2(chatId, $"{strings.room} _*{roomName}*_ {strings.already_exists}"),
+                ResultCode.CodeOk => await Bot.SendWithMarkdown2(chatId, $"{strings.room_with_name} _*{roomName}*_ {strings.was_created}", keyboard),
+                ResultCode.UserAlreadyInGame => await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_"),
+                ResultCode.GameAlreadyExists => await Bot.SendWithMarkdown2(chatId, $"{strings.room} _*{roomName}*_ {strings.already_exists}"),
                 _ => await Bot.SendWithMarkdown2(chatId, strings.unexpected_error)
             };
-            if (resultCode == Constants.CODE_OK && param[0] == "private")
+            if (resultCode == ResultCode.CodeOk && param[0] == "private")
             {
                 await Bot.SendWithMarkdown2(chatId,
                     $"{strings.secret_key_is} _*{roomName}*_: ```{RoomEncrypter.NameToCode(roomName)}```");

+ 3 - 4
MafiaTelegramBot/Models/Commands/LeaveCommand.cs

@@ -1,7 +1,6 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
-using MafiaTelegramBot.Models.Inlines;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 using Telegram.Bot.Types.Enums;
@@ -19,7 +18,7 @@ namespace MafiaTelegramBot.Models.Commands
 
             var userId = update.Message.From.Id;
             var user = await UserDao.GetUserById(userId);
-            var game = user!.GetCurrentGame();
+            var roomName = await user.GetRoomName();
             var result = await RoomController.LeaveFromGame(user);
             
             ReplyKeyboardMarkup keyboard = new(
@@ -34,8 +33,8 @@ namespace MafiaTelegramBot.Models.Commands
             
             return result switch
             {
-                Constants.CODE_OK => await Bot.SendWithMarkdown2(chatId, $"{strings.leave_from_game} _*{game}*_", keyboard),
-                Constants.USER_NOT_IN_GAME => await Bot.SendWithMarkdown2(chatId, strings.not_in_game),
+                ResultCode.CodeOk => await Bot.SendWithMarkdown2(chatId, $"{strings.leave_from_game} _*{roomName}*_", keyboard),
+                ResultCode.UserNotInGame => await Bot.SendWithMarkdown2(chatId, strings.not_in_game),
                 _ => await Bot.SendWithMarkdown2(chatId, strings.unexpected_error)
             };
         }

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

@@ -15,11 +15,11 @@ namespace MafiaTelegramBot.Models.Commands
             var userId = update.Message.From.Id;
 
             var user = await UserDao.GetUserById(userId);
-            var room_name = user.GetCurrentGame();
-            var room = await RoomController.GetRoom(room_name);
-            var room_max_capacity = room.MaxPlayers;
+            var roomKey = user.GetRoomKey();
+            var room = await RoomController.GetRoom(roomKey);
+            var roomMaxCapacity = room.MaxPlayers;
             
-            var message = $"{strings.max_capacity_message}: {room_max_capacity}";
+            var message = $"{strings.max_capacity_message}: {roomMaxCapacity}";
             
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {

+ 2 - 4
MafiaTelegramBot/Models/Commands/StartCommand.cs

@@ -3,7 +3,6 @@ using MafiaTelegramBot.DataBase;
 using Telegram.Bot.Types;
 using Telegram.Bot.Types.Enums;
 using Telegram.Bot.Types.ReplyMarkups;
-using User = Telegram.Bot.Types.User;
 
 namespace MafiaTelegramBot.Models.Commands
 {
@@ -65,13 +64,12 @@ namespace MafiaTelegramBot.Models.Commands
                 .Replace("~", "\\~")
                 .Replace("[", "\\[")
             ):"";
-            
+            if (await UserDao.UserExists(userId)) return message;
             var user = new DataBase.User
             {
                 Id = userId, ChatId = chatId, Username = username, FirstName =  firstName, LastName = lastName
             };
-            
-            await UserDao.AddNewUser(user);
+            await UserDao.Update(user);
             return message;
         }
     }

+ 6 - 6
MafiaTelegramBot/Models/Inlines/DecreaseRoomMaxCapacity.cs

@@ -19,16 +19,16 @@ namespace MafiaTelegramBot.Models.Inlines
             var userId = long.Parse(data.Split('|')[1]);
 
             var user = await UserDao.GetUserById(userId);
-            var room_name = user.GetCurrentGame();
-            var room = await RoomController.GetRoom(room_name);
-            var room_max_capacity = room.MaxPlayers;
+            var roomKey = user.GetRoomKey();
+            var room = await RoomController.GetRoom(roomKey);
+            var roomMaxCapacity = room.MaxPlayers;
             
-            if (room_max_capacity > Constants.PLAYER_LIMITS_MIN)
+            if (roomMaxCapacity > Constants.PLAYER_LIMITS_MIN)
             {
-                room_max_capacity = --room.MaxPlayers;
+                roomMaxCapacity = --room.MaxPlayers;
             }
             
-            var message = $"{strings.max_capacity_message}: {room_max_capacity}";
+            var message = $"{strings.max_capacity_message}: {roomMaxCapacity}";
             
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {

+ 6 - 6
MafiaTelegramBot/Models/Inlines/IncreaseRoomMaxCapacityQuery.cs

@@ -20,17 +20,17 @@ namespace MafiaTelegramBot.Models.Inlines
             var userId = long.Parse(data.Split('|')[1]);
 
             var user = await UserDao.GetUserById(userId);
-            var room_name = user.GetCurrentGame();
-            var room = await RoomController.GetRoom(room_name);
-            var room_max_capacity = room.MaxPlayers;
+            var roomKey = user.GetRoomKey();
+            var room = await RoomController.GetRoom(roomKey);
+            var roomMaxCapacity = room.MaxPlayers;
 
 
-            if (room_max_capacity < Constants.PLAYER_LIMITS_MAX)
+            if (roomMaxCapacity < Constants.PLAYER_LIMITS_MAX)
             {
-                room_max_capacity = ++room.MaxPlayers;
+                roomMaxCapacity = ++room.MaxPlayers;
             }
             
-            var message = $"{strings.max_capacity_message}: {room_max_capacity}";
+            var message = $"{strings.max_capacity_message}: {roomMaxCapacity}";
             
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {

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

@@ -17,8 +17,8 @@ namespace MafiaTelegramBot.Models.Inlines
             var param = data.Split('|');
             var userId = long.Parse(param[1]);
             var user = await UserDao.GetUserById(userId);
-            if (user?.GetCurrentGame() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{user?.GetCurrentGame()}*_");
+            if (user.GetRoomKey() != "")
+                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
             if (Bot.UsersThatCreatesRoom.TryAdd(userId, new[] {param[2], Name}))
             {
                 Bot.UsersThatCreatesRoom[userId] = new[] {param[2], Name};

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

@@ -17,8 +17,8 @@ namespace MafiaTelegramBot.Models.Inlines
             var data = update.CallbackQuery.Data;
             var userId = long.Parse(data.Split('|')[1]);
             var user = await UserDao.GetUserById(userId);
-            if (user?.GetCurrentGame() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{user?.GetCurrentGame()}*_");
+            if (user.GetRoomKey() != "")
+                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {
                 new[] {

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

@@ -17,8 +17,8 @@ namespace MafiaTelegramBot.Models.Inlines
             var data = update.CallbackQuery.Data;
             var userId = long.Parse(data.Split('|')[1]);
             var user = await UserDao.GetUserById(userId);
-            if (user?.GetCurrentGame() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{user?.GetCurrentGame()}*_");
+            if (user.GetRoomKey() != "")
+                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {
                 new[] {

+ 2 - 2
MafiaTelegramBot/Models/Inlines/MakeStandartGameQuery.cs

@@ -17,8 +17,8 @@ namespace MafiaTelegramBot.Models.Inlines
             var param = data.Split('|');
             var userId = long.Parse(param[1]);
             var user = await UserDao.GetUserById(userId);
-            if (user?.GetCurrentGame() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{user?.GetCurrentGame()}*_");
+            if (user.GetRoomKey() != "")
+                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
             if (Bot.UsersThatCreatesRoom.TryAdd(userId, new[] {param[2], Name}))
             {
                 Bot.UsersThatCreatesRoom[userId] = new[] {param[2], Name};

+ 0 - 13
MafiaTelegramBot/Resources/Constants.cs

@@ -2,20 +2,7 @@ namespace MafiaTelegramBot.Resources
 {
     public static class Constants
     {
-        public const int CODE_OK = 0; //only this can be zero
-        
         public const int PLAYER_LIMITS_MIN = 1;
         public const int PLAYER_LIMITS_MAX = 16;
-
-
-        public const int TOO_MANY_PLAYERS = 1;
-        public const int TOO_FEW_PLAYERS = -1;
-        public const int GAME_ALREADY_RUNNING = 2;
-
-        public const int GAME_EXISTS = 1;
-        public const int USER_ALREADY_IN_GAME = 2;
-        public const int USER_NOT_IN_GAME = 2;
-
-        public const int ROOM_IS_FILLED = 1;
     }
 }

+ 15 - 0
MafiaTelegramBot/Resources/ResultCode.cs

@@ -0,0 +1,15 @@
+namespace MafiaTelegramBot.Resources
+{
+    public enum ResultCode
+    {
+        TooManyPlayers,
+        TooFewPlayers,
+        GameAlreadyRunning,
+        GameAlreadyExists,
+        UserAlreadyInGame,
+        UserNotInGame,
+        RoomIsFilled,
+        RoomDoesNotExist,
+        CodeOk,
+    }
+}