Esempio n. 1
0
        public async Task <IActionResult> CreateRoom([FromBody] RoomCreation roomCreation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            short mapSize = 6;

            short[] shipList = new short[] { 0, 2, 0, 0 };


            if (roomCreation.MapSize != null && roomCreation.MapSize >= 3 && roomCreation.MapSize <= 8)
            {
                mapSize = roomCreation.MapSize;
            }

            bool flag = true;

            if (roomCreation.ShipsList.Length != 4)
            {
                flag = false;
            }
            else
            {
                for (int i = 0; i < 4; i++)
                {
                    if (roomCreation.ShipsList[i] < 0 || roomCreation.ShipsList[i] >= (6 - i))
                    {
                        flag = false;
                    }
                }
            }

            if (flag)
            {
                shipList = roomCreation.ShipsList;
            }


            GameRoom newGameRoom = new GameRoom(_gameRooms.GenerateRoomId(), roomCreation.RoomName, mapSize, shipList);

            Battleships_MBernackiUser user = await GetCurrentUserAsync();

            int playerRoomKey = newGameRoom.AddPlayer(user.UserName, user.Id);

            _gameRooms.GameRoomsList.Add(newGameRoom);


            return(Ok(new JoinedRoomInfo()
            {
                PlayerRoomKey = playerRoomKey,
                RoomID = newGameRoom.RoomID,
                OponentName = "",
                RoomName = newGameRoom.RoomName,
                ShipsList = shipList,
                MapSize = mapSize
            }));
        }
        /// <summary>
        /// Join an existing game.
        /// </summary>
        /// <param name="mazeName">Maze name.</param>
        /// <param name="connectionId">Connection id.</param>
        /// <returns>Game room.</returns>
        public GameRoom JoinGame(string mazeName, string connectionId)
        {
            //Add player to game room.
            GameRoom room = GameRooms[mazeName];

            room.AddPlayer(connectionId);

            return(room);
        }
Esempio n. 3
0
        //CallBack->匹配成功一组玩家触发
        private static void MatchingQueue_SuccessGroup(Player[] plys)
        {
            //通知玩家匹配成功,随后相应客户端客户端发起ajax请求获取游戏界面
            var p1 = plys[0];
            var p2 = plys[1];
            //为他们创建房间,并添加到房间列表
            var      p3   = plys[2];
            GameRoom room = new GameRoom(p1, 100, RoomModel.Matched, "");

            room.AddPlayer(p2);
            room.AddPlayer(p3);
            room.RoomDestroy += Room_RoomDestroy;
            AddRoom(room);
            //绑定房间
            p1.RoomWhich = p2.RoomWhich = p3.RoomWhich = room;
            Log.Print("房间已生成:ID" + room.RoomID);
            //指示匹配成功的玩家进行页面跳转
            p1.HallWebsok.SendData(JsonConvert.SerializeObject(new { roomid = room.RoomID, pid = p1.PlayerID }), HallOrderType.房间创建完毕);
            p2.HallWebsok.SendData(JsonConvert.SerializeObject(new { roomid = room.RoomID, pid = p2.PlayerID }), HallOrderType.房间创建完毕);
            p3.HallWebsok.SendData(JsonConvert.SerializeObject(new { roomid = room.RoomID, pid = p3.PlayerID }), HallOrderType.房间创建完毕);
        }
        public void AddPlayerShouldReturnTrueIfPlayerIsAddedTest()
        {
            //Arrange
            GameRoom gameRoomTest = EmptyGameRoom;

            //Act
            bool result = gameRoomTest.AddPlayer(ConnIdPlayerOne, PlayerOne);

            //Assert
            Assert.IsTrue(result);
            Assert.AreEqual(this.PlayerOne, gameRoomTest.GetPlayers().ElementAt(0));
        }
        public void AddPlayerShouldReturnFalseIfGameIsStartedTest()
        {
            //Arrange
            GameRoom startedGame = EmptyGameRoom;

            startedGame.StartGame();

            //Act
            bool result = startedGame.AddPlayer(ConnIdPlayerOne, PlayerOne);

            //Assert
            Assert.IsFalse(result);
        }
        public void GetPlayerByConnectionIdTest()
        {
            //Arrange
            GameRoom gameRoomTest = EmptyGameRoom;

            gameRoomTest.AddPlayer(ConnIdPlayerOne, PlayerOne);

            //Act
            Player foundPlayer = EmptyGameRoom.GetPlayerByConnectionId(ConnIdPlayerOne);

            //Assert
            Assert.AreEqual(PlayerOne, foundPlayer);
        }
        public void GetPlayersShouldReturnAddedPlayersTest()
        {
            //Arrange
            GameRoom gameRoomTest = EmptyGameRoom;

            gameRoomTest.AddPlayer(ConnIdPlayerOne, PlayerOne);

            //Act
            IEnumerable <Player> listOfPlayers = gameRoomTest.GetPlayers();

            //Assert
            Assert.AreEqual(1, listOfPlayers.Count());
            Assert.AreEqual(PlayerOne, listOfPlayers.ElementAt(0));
        }
        public void StartGameCreatesPlayersHandsTest()
        {
            //Arrange
            GameRoom gameRoomTest = EmptyGameRoom;

            Player player1       = PlayerOne;
            Player player2       = new Player("Bo", 2, Color.Red);
            string player1ConnId = ConnIdPlayerOne;
            string player2ConnId = "connId2";

            gameRoomTest.AddPlayer(player1ConnId, player1);
            gameRoomTest.AddPlayer(player2ConnId, player2);

            //Act
            gameRoomTest.StartGame();

            bool player1HandFound = gameRoomTest.Piles.Exists((pile) => pile.PileType == PileType.Hand && pile.Owner == player1);
            bool player2HandFound = gameRoomTest.Piles.Exists((pile) => pile.PileType == PileType.Hand && pile.Owner == player2);

            //Assert
            Assert.AreEqual(PileType.Deck, gameRoomTest.Piles[0].PileType);
            Assert.IsTrue(player1HandFound);
            Assert.IsTrue(player2HandFound);
        }
        public static void OnCreateGame(GameSession client, GameClientPacket packet)
        {
            if (string.IsNullOrEmpty(client.Name) || client.Type != (int)PlayerType.Undefined)
            {
                return;
            }
            GameRoom room = null;

            byte[]         data = packet.ReadBytes(StructTransformer.SizeOf(typeof(CtosCreateGame)));
            CtosCreateGame roomconfig;
            GameConfig     config = null;

            try
            {
                roomconfig = (CtosCreateGame)StructTransformer.BytesToStruct(data, typeof(CtosCreateGame));
                config     = roomconfig.Build();
            }
            catch (Exception e)
            {
                Logger.Warn(e);
            }
            if (config == null)
            {
                client.CloseAsync();
                return;
            }
            room = RoomManager.CreateOrGetGame(config);

            if (room == null)
            {
                client.LobbyError(Messages.MSG_FULL);
                return;
            }
            client.Game = room;
            lock (room.AsyncRoot)
            {
                room.AddPlayer(client);
            }
            //IsAuthentified = CheckAuth();
            if (!client.IsAuthentified)
            {
                client.LobbyError(Messages.ERR_AUTH_FAIL);
            }
        }
        /// <summary>
        /// Start a new game.
        /// </summary>
        /// <param name="mazeName">Maze name.</param>
        /// <param name="rows">Rows.</param>
        /// <param name="columns">Columns.</param>
        /// <param name="connectionId"></param>
        /// <returns>Maze.</returns>
        public Maze StartGame(string mazeName, int rows, int columns,
                              string connectionId)
        {
            //Check if a game with the same already exists.
            if (StartedMazes.ContainsKey(mazeName))
            {
                return(null);
            }

            //Generates the maze with the required properties.
            Maze maze = this.mazeGenerator.Generate(rows, columns);

            maze.Name = mazeName;
            StartedMazes.Add(maze.Name, maze);

            //Create new game room.
            GameRoom room = new GameRoom(maze);

            room.AddPlayer(connectionId);
            GameRooms.Add(maze.Name, room);

            return(maze);
        }
        public static void OnJoinGame(GameSession client, GameClientPacket packet)
        {
            if (string.IsNullOrEmpty(client.Name) || client.Type != (int)PlayerType.Undefined)
            {
                Logger.Debug("join room fail:" + client.Name);
                return;
            }
            int version = packet.ReadInt16();

            if (version < Program.Config.ClientVersion)
            {
                client.LobbyError(Messages.ERR_LOW_VERSION);
                return;
            }
            else if (version > Program.Config.ClientVersion)
            {
                client.ServerMessage(Messages.MSG_HIGH_VERSION);
            }
            int gameid = packet.ReadInt32();            //gameid

            packet.ReadInt16();

            string joinCommand = packet.ReadUnicode(60);

            GameRoom room = null;

            //IsAuthentified = CheckAuth();
            if (!client.IsAuthentified)
            {
                client.LobbyError(Messages.ERR_AUTH_FAIL);
                return;
            }
            if (!RoomManager.CheckRoomPassword(joinCommand))
            {
                client.LobbyError(Messages.ERR_PASSWORD);
                return;
            }
            GameConfig config = GameConfigBuilder.Build(joinCommand);

            room = RoomManager.CreateOrGetGame(config);
            if (room == null)
            {
                client.LobbyError(Messages.MSG_FULL);
                return;
            }
            if (!room.IsOpen)
            {
                client.LobbyError(Messages.MSG_GAMEOVER);
                return;
            }
            if (room != null && room.Config != null)
            {
                if (room.Config.NoCheckDeck)
                {
                    client.ServerMessage(Messages.MSG_NOCHECKDECK);
                }
                if (room.Config.NoShuffleDeck)
                {
                    client.ServerMessage(Messages.MSG_NOSHUFFLEDECK);
                }
                if (room.Config.EnablePriority)
                {
                    client.ServerMessage(Messages.MSG_ENABLE_PROIORITY);
                }
            }
            client.Game = room;
            lock (room.AsyncRoot)
            {
                room.AddPlayer(client);
            }
        }
        public Status AddPlayerToGame(string gamePin, string nickName, string connectionId)
        {
            Status result = Status.None;

            //Add player to game
            GameRoom updatedGameRoom = GetGameRoomWithPin(gamePin);

            if (updatedGameRoom != null)
            {
#if !BREAK_JOIN
                lock (updatedGameRoom.PlayersLock) {
#else
                { //To match closing bracket
#endif
                    int amountOfPlayers = updatedGameRoom.GetPlayers().Count();


#if BREAK_JOIN || DELAY_JOIN
                    if (amountOfPlayers == 1 && Monitor.TryEnter(updatedGameRoom.PlayersLock))
                    {
                        Debug.WriteLine("Paused with player " + nickName);
                        Thread.Sleep(5000);
                        Debug.WriteLine("Player " + nickName + " continuing from pause");

                        Monitor.Exit(updatedGameRoom.PlayersLock);
                    }
                    else
                    {
                        Debug.WriteLine("Skipping pause for player " + nickName);
                    }
#endif

                    bool isDublicateNickName = false;
                    foreach (Player p in updatedGameRoom.GetPlayers())
                    {
                        if (p.Name.Equals(nickName))
                        {
                            isDublicateNickName = true;
                        }
                    }
                    if (updatedGameRoom.IsStarted)
                    {
                        result = Status.GameIsStartedError;
                    }
                    else if (isDublicateNickName)
                    {
                        result = Status.DuplicateNickNameError;
                    }
                    else if (amountOfPlayers >= 8)
                    {
                        result = Status.GameIsFullError;
                    }
                    else
                    {
                        Color  playerColor = Colors[amountOfPlayers];
                        Player newPlayer   = new Player(nickName, amountOfPlayers, playerColor);
                        if (updatedGameRoom.AddPlayer(connectionId, newPlayer))
                        {
                            result = Status.Success;
#if BREAK_JOIN || DELAY_JOIN
                            Debug.WriteLine("Player " + nickName + " joined the game with position: " + amountOfPlayers);
#endif
                        }
                        else
                        {
                            result = Status.UnknownError;
                        }
                    }
                }
            }
            else
            {
                result = Status.GameNotFoundError;
            }
            return(result);
        }
Esempio n. 13
0
        public void AddPlayer_PassesCorrectName_MethodReturnsNonNegativeInt()
        {
            int result = _gameRoom.AddPlayer("Nickname", "testId");

            Assert.Positive(result);
        }