コード例 #1
0
    void TestStartListening()
    {
        int listenPort = GetPort();

        listener = new UdpClient(listenPort);
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
        string     received_data;

        byte[]    receive_byte_array;
        TcpClient tcpClient = new TcpClient();

        try
        {
            while (stopListening == false)
            {
                receive_byte_array = listener.Receive(ref groupEP);
                ThreadSafeLog(string.Format("Received a broadcast from {0}", groupEP.ToString()));
                //received_data = Encoding.UTF8.GetString(receive_byte_array, 0, receive_byte_array.Length);
                LobbyMessage lobbyMessage = new LobbyMessage(receive_byte_array);
                ThreadSafeLog(string.Format("data follows \n{0}\n\n", lobbyMessage.ToString()));
            }
        }
        catch (System.Exception e)
        {
            ThreadSafeLog("network exception: " + e.ToString());
        }
        listener.Close();
    }
コード例 #2
0
    void OnNetworkMessage(byte[] udpMessage, IPEndPoint remoteEndPoint)
    {
        int    _appIdentifier;
        byte   _messageType;
        string _senderGuid;

        if (!NetworkProtocol.TryParseBasicInfo(udpMessage, out _appIdentifier, out _messageType))
        {
            return;
        }

        if (_appIdentifier != APP_IDENTIFIER)
        {
            return;
        }

        switch (_messageType)
        {
        case (int)NetworkMessageType.LobbyMessage:
            LobbyMessage lobbyMessage = new LobbyMessage();
            lobbyMessage.Parse(udpMessage);
            ProcessLobbyMessage(lobbyMessage, remoteEndPoint);
            break;

        default:
            ThreadSafeLog("unkown message type: " + _messageType);
            break;
        }
    }
コード例 #3
0
        public void SendLobbyMessage(Account account, string text)
        {
            User ex;

            if (client.ExistingUsers.TryGetValue(account.Name, out ex))
            {
                client.Say(SayPlace.User, account.Name, text, false);
            }
            else
            {
                var message = new LobbyMessage
                {
                    SourceLobbyID = client.MyUser != null ? client.MyUser.AccountID : 0,
                    SourceName    = client.UserName,
                    Created       = DateTime.UtcNow,
                    Message       = text,
                    TargetName    = account.Name,
                    TargetLobbyID = account.AccountID
                };
                using (var db = new ZkDataContext())
                {
                    db.LobbyMessages.InsertOnSubmit(message);
                    db.SubmitChanges();
                }
            }
        }
コード例 #4
0
            public async Task WhenAddFailsReturnsMessage()
            {
                var user         = TestUtils.GetRandomUser();
                var lobbyMessage = new LobbyMessage
                {
                    Id = 1,
                    MessageDateTime = DateTime.UtcNow,
                    MessageText     = "Test Message",
                    Sender          = user
                };

                UserServiceMock.Setup(us => us.GetUserFromUsernameAsync(It.IsAny <string>())).ReturnsAsync(user);
                MessageServiceMock.Setup(ms => ms.AddMessageAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(lobbyMessage);

                var result = await Controller.AddMessage(new AddMessageRequest());

                var response = TestUtils.GetResponseFromResult <AddMessageResponse>(result);

                Assert.IsTrue(response.Success);
                Assert.AreEqual(lobbyMessage.Id, response.NewMessage.Id);
                Assert.AreEqual(lobbyMessage.MessageText, response.NewMessage.Message);
                Assert.AreEqual(lobbyMessage.MessageDateTime, response.NewMessage.Time);
                Assert.AreEqual(lobbyMessage.Sender.UserName, response.NewMessage.User);

                SubscriberMock.Verify(s => s.PublishAsync(It.IsAny <RedisChannel>(), It.IsAny <RedisValue>(), It.IsAny <CommandFlags>()), Times.Once);
            }
コード例 #5
0
    //Server
    private void SendLobbyUpdates(string _lobbyMsg)
    {
        // Create msg for all clients
        LobbyMessage msg = new LobbyMessage();

        //msg.connectionId = _networkMessage.conn.connectionId;

        string[] names   = new string[maxConnections];
        Color[]  colours = new Color[maxConnections];
        for (int i = 0; i < maxConnections; i++)
        {
            if (this.isClientConnected[i])
            {
                names[i]   = this.playerInfoList[i].name;
                colours[i] = this.playerInfoList[i].colour;
            }
        }

        msg.playerNames   = names;
        msg.playerColours = colours;

        msg.isPlayerConnected = this.isClientConnected.ToArray();
        msg.isReadyList       = this.isPlayerReadyList.ToArray();

        msg.isLobbyCountingDown = this.isLobbyTimerCountingDown;
        msg.countDownTime       = this.lastLobbyCountDownTimeSent;

        msg.lobbyMsg = _lobbyMsg;

        // Send to all
        NetworkServer.SendToAll(CustomMsgType.Lobby, msg);
    }
コード例 #6
0
    void RequestRoomList()
    {
        LobbyMessage message = new LobbyMessage();

        FillBasicInfo(message);
        message.requestRoomList = true;
        BroadcastMessage(message);
    }
コード例 #7
0
    void RequestJoinLobby(Lobby targetLobby)
    {
        LobbyMessage message = new LobbyMessage();

        FillBasicInfo(message);
        message.iWantToJoin = true;
        message.masterGuid  = targetLobby.master.guid;
        SendUdpMessage(targetLobby.master.endPoint, message);
    }
コード例 #8
0
        public Task <bool> UpdateMessageAsync(LobbyMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            return(UpdateMessageInternalAsync(message));
        }
コード例 #9
0
    //evento propio S - se recive char info ID 908
    void OnClientInfo(NetworkMessage netMsg)
    {
        LobbyMessage msg = netMsg.ReadMessage <LobbyMessage>();

        print("servidor recibio info de cliente: heroID=" + msg.heroID + " / level=" + msg.level + ".... reenviando a clientes");
        var ms = new LobbyMessage();

        ms.level  = msg.level;
        ms.heroID = msg.heroID;
        NetworkServer.SendToAll(ClientInfoResponse, ms);
    }
コード例 #10
0
    //evento - me conecté satisfactoriamente a la partida
    public void OnConnected(NetworkMessage msg)
    {
        print("me conecte");

        var ms = new LobbyMessage();

        myClient.Send(OnConnectedPlayer, ms);

        ms.level  = 200;
        ms.heroID = 8;
        myClient.Send(ClientInfo, ms);
    }
コード例 #11
0
    void BroadcastLobby()
    {
        byte[]       send_buffer  = new byte[1000];
        LobbyMessage lobbyMessage = new LobbyMessage {
            appIdentifier = APP_IDENTIFIER, senderGuid = guidStr,
            messageType   = (byte)NetworkMessageType.LobbyMessage, currentPlayerCount = lobby.players.Count, maxPlayerCount = MAX_PLAYER_COUNT,
            masterGuid    = guidStr, myPort = GetPort()
        };
        int length = lobbyMessage.ToByteArray(send_buffer);

        BroadcastMessage(send_buffer, length);
    }
コード例 #12
0
        public void JoinLobby(int lobbyId)
        {
            var user = _userRepository.GetUser(1);

            _lobbyRepository.AddUserToLobby(lobbyId, user);
            var LobbyMessage = new LobbyMessage
            {
                Message = $"User {user.Name} has joined",
                Sent    = DateTime.Now,
            };

            _lobbyHubContext.Clients.All.InvokeAsync("UserJoined", LobbyMessage);
        }
コード例 #13
0
        private async Task <bool> UpdateMessageInternalAsync(LobbyMessage message)
        {
            try
            {
                await context.SaveChangesAsync().ConfigureAwait(false);
            }
            catch (DbUpdateException ex)
            {
                logger.LogError(ex, $"Failed to update message {message.Id}");

                return(false);
            }

            return(true);
        }
コード例 #14
0
        public static ApiLobbyMessage ToApiLobbyMessage(this LobbyMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            return(new ApiLobbyMessage
            {
                Id = message.Id,
                User = message.Sender.UserName,
                Message = message.MessageText,
                Time = message.MessageDateTime
            });
        }
コード例 #15
0
    void NotifyStartGame()
    {
        LobbyMessage message = new LobbyMessage();

        FillBasicInfo(message);
        message.masterGuid = lobby.master.guid;
        message.startGame  = true;
        if (lobby.isMaster)
        {
            BroadcastMessage(message);
        }
        else
        {
            SendUdpMessage(lobby.master.endPoint, message);
        }
    }
コード例 #16
0
    void NotifyJoinSuccess(LobbyPlayer targetPlayer)
    {
        LobbyMessage lobbyMessage = new LobbyMessage
        {
            appIdentifier      = APP_IDENTIFIER,
            senderGuid         = guidStr,
            messageType        = (byte)NetworkMessageType.LobbyMessage,
            currentPlayerCount = lobby.players.Count,
            maxPlayerCount     = MAX_PLAYER_COUNT,
            masterGuid         = guidStr,
            myPort             = GetPort(),
            iWantToJoin        = false,
            joinStatus         = 1
        };

        SendUdpMessage(targetPlayer.endPoint, lobbyMessage);
    }
コード例 #17
0
ファイル: UDPTest.cs プロジェクト: JamesBear/UnityLobbyTest
    void TestSend()
    {
        IPAddress  ip       = IPAddress.Parse("127.0.0.1");
        IPEndPoint endpoint = new IPEndPoint(ip, 10003);

        //string text_to_send = "呵呵";
        //byte[] send_buffer = Encoding.UTF8.GetBytes(text_to_send);
        byte[]       send_buffer  = new byte[1000];
        LobbyMessage lobbyMessage = new LobbyMessage {
            appIdentifier = 1234, senderGuid = "", messageType = 1, maxPlayerCount = 8, currentPlayerCount = 1
        };
        int length = lobbyMessage.ToByteArray(send_buffer);

        Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                                           ProtocolType.Udp);

        sending_socket.SendTo(send_buffer, length, SocketFlags.None, endpoint);
    }
コード例 #18
0
            public async Task WhenRemoveSucceedsReturnsSuccess()
            {
                var lobbyMessage = new LobbyMessage();

                UserServiceMock.Setup(us => us.GetUserFromUsernameAsync(It.IsAny <string>())).ReturnsAsync(TestUtils.GetRandomUser());
                MessageServiceMock.Setup(ms => ms.FindByIdAsync(It.IsAny <int>())).ReturnsAsync(lobbyMessage);
                MessageServiceMock.Setup(ms => ms.UpdateMessageAsync(It.IsAny <LobbyMessage>())).ReturnsAsync(true);

                var result = await Controller.RemoveMessage(1);

                var response = TestUtils.GetResponseFromResult <DeleteMessageResponse>(result);

                Assert.IsTrue(response.Success);
                Assert.IsTrue(lobbyMessage.Removed);
                Assert.AreEqual(DateTime.UtcNow.Date, lobbyMessage.RemovedDateTime.Date);
                Assert.AreEqual(1, response.MessageId);

                SubscriberMock.Verify(s => s.PublishAsync(It.IsAny <RedisChannel>(), It.IsAny <RedisValue>(), It.IsAny <CommandFlags>()), Times.Once);
            }
コード例 #19
0
    void TestSend()
    {
        IPAddress  ip                = IPAddress.Parse("127.0.0.1");
        IPEndPoint endpoint          = new IPEndPoint(ip, GetPort());
        IPEndPoint broadcastEndPoint = new IPEndPoint(IPAddress.Broadcast, GetPort());

        //string text_to_send = "呵呵";
        //byte[] send_buffer = Encoding.UTF8.GetBytes(text_to_send);
        byte[]       send_buffer  = new byte[1000];
        LobbyMessage lobbyMessage = new LobbyMessage {
            appIdentifier = 1234, senderGuid = guidStr, messageType = 1, currentPlayerCount = 1, maxPlayerCount = 9
        };
        int       length = lobbyMessage.ToByteArray(send_buffer);
        UdpClient sender = new UdpClient();

        //Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
        //ProtocolType.Udp);

        //sending_socket.SendTo(send_buffer, length, SocketFlags.Broadcast, broadcastEndPoint);
        sender.Send(send_buffer, length, broadcastEndPoint);
    }
コード例 #20
0
        private async Task <LobbyMessage> AddMessageInternalAsync(int userId, string message)
        {
            var newMessage = new LobbyMessage
            {
                MessageDateTime = DateTime.UtcNow,
                MessageText     = message,
                SenderId        = userId
            };

            context.LobbyMessage.Add(newMessage);

            try
            {
                await context.SaveChangesAsync().ConfigureAwait(false);
            }
            catch (DbUpdateException exception)
            {
                logger.LogError(exception, $"Error saving message '{message}' for user '{userId}'");
                return(null);
            }

            return(newMessage);
        }
コード例 #21
0
    //evento propio C - se recive respuesta de info ID 909
    void OnClientInfoResponse(NetworkMessage netMsg)
    {
        LobbyMessage msg = netMsg.ReadMessage <LobbyMessage>();

        print("cliente recibio info de cliente: heroID=" + msg.heroID + " / level=" + msg.level);
    }
コード例 #22
0
    // Client - Update player panels when a player joins/leaves - TODO: player leaving
    public void OnLobbyUpdateReceived(NetworkMessage _networkMessage)
    {
        Debug.Log("Lobby update received");

        // Read msg
        LobbyMessage msg = _networkMessage.ReadMessage <LobbyMessage>();

        //Debug.Log("Player " + msg.connectionId.ToString() + " has connected");

        // check for players connected
        for (int i = 0; i < msg.isPlayerConnected.Length; i++)
        {
            if (msg.isPlayerConnected[i])
            {
                this.playerColourImages[i].color = msg.playerColours[i];
                this.playerNameTexts[i].text     = msg.playerNames[i];
                this.playerPanels[i].SetActive(true);
            }
            else
            {
                this.playerPanels[i].SetActive(false);
            }
        }

        // Check ready up status
        for (int i = 0; i < msg.isReadyList.Length; i++)
        {
            if (msg.isReadyList[i])
            {
                this.playerReadyIcons[i].sprite = this.playerReadySprites[1];                 // set icon to ready
            }
            else
            {
                this.playerReadyIcons[i].sprite = this.playerReadySprites[0];                 // set icon to not ready
            }
        }

        // Check to update time text
        if (msg.isLobbyCountingDown)
        {
            // Enable text & update with the time
            this.lobbyTimeText.enabled = true;
            if (msg.countDownTime > -1)
            {
                this.lobbyTimeText.text = msg.countDownTime > 0 ? msg.countDownTime.ToString() : "WORDDD";
            }
            else
            {
                this.CloseMenu();
            }
        }
        else
        {
            this.lobbyTimeText.enabled = false;
        }

        // Display lobby update msg
        if (msg.lobbyMsg != "")
        {
            this.hasReceivedLobbyUpdateMsg = true;
            this.lobbyMsgText.enabled      = true;
            this.lobbyMsgText.text         = msg.lobbyMsg;
        }

        // Check if this is the first time receiving the panel update, if so, turn on the panel
        if (!this.lobbyPanel.activeSelf && this.isReadyForLobby)
        {
            this.lobbyPanel.SetActive(true);
            this.isReadyForLobby = false;
        }
    }
コード例 #23
0
ファイル: LobbyHub.cs プロジェクト: johndennismpls/Gulsevanya
 public Task SendMessage(LobbyMessage chatMessage)
 {
     return(Clients.All.InvokeAsync("Send", chatMessage));
 }
コード例 #24
0
ファイル: Lobby.cs プロジェクト: SettlersDev/S5Online
 public void Broadcast(Message msg)
 {
     LobbyMessage?.Invoke(this, msg);
 }
コード例 #25
0
        /// <summary>
        /// Handles all actions for recieving data messages (Such as movement, block placing, etc)
        /// </summary>
        /// <param name="inc">The incoming message</param>
        private void ProcessDataMessage(NetIncomingMessage inc)
        {
            Player sender = Server.PlayerFromRUI(inc.SenderConnection.RemoteUniqueIdentifier, true);
            Map    map    = null;

            if (sender != null)
            {
                map = (Map)sender.Map;
            }
            MessageTypes type = (MessageTypes)Enum.Parse(typeof(MessageTypes), inc.ReadByte().ToString());

            switch (type)
            {
            //When a player request to recieve a message
            case MessageTypes.Request:
            {
                MessageTypes request = new RequestMessage(inc).RequestType;

                //Request to recieve lobby data
                if (request == MessageTypes.Lobby)
                {
                    List <LobbySaveData> rooms = new List <LobbySaveData>();
                    foreach (Map m in Maps)
                    {
                        rooms.Add(LobbySaveData.FromMap(m));
                    }
                    LobbyMessage msg = new LobbyMessage(Server.Config.Name, Server.Config.Decription, Server.Config.Intro, NetworkManager.NetServer.ConnectionsCount, rooms);
                    NetManager.Send(msg, inc.SenderConnection);
                }
                break;
            }

            //When a player exits to the lobby
            case MessageTypes.PlayerLeave:
            {
                PlayerLeaveMessage user = new PlayerLeaveMessage(inc);
                user.ID = sender.ID;
                Log.WriteLine(LogType.Room, "{0} has left: {1}", sender.Username, sender.Map.Name);
                //Remove player
                map.Players.Remove(sender);
                RebuildIndexes(map);
                //Send to players
                NetManager.Broadcast(sender.Map, new PlayerLeaveMessage(sender.ID));
                IO.SaveMap((Bricklayer.Server.World.Map)sender.Map);
                sender = null;
                break;
            }

            //When a player moves
            case MessageTypes.PlayerStatus:
            {
                PlayerStateMessage state = new PlayerStateMessage(inc);
                state.ID = sender.ID;
                //Clamp position in bounds
                state.Position = new Point((int)MathHelper.Clamp(state.Position.X, Tile.Width, (map.Width * Tile.Width) - (Tile.Width * 2)), (int)MathHelper.Clamp(state.Position.Y, Tile.Height, (map.Height * Tile.Height) - (Tile.Height * 2)));
                sender.SimulationState.Position = state.Position.ToVector2();
                sender.SimulationState.Velocity = state.Velocity.ToVector2();
                sender.SimulationState.Movement = state.Movement.ToVector2();
                sender.IsJumping = state.IsJumping;

                NetManager.BroadcastExcept(state, sender);
                break;
            }

            //When a player places a block
            case MessageTypes.Block:
            {
                BlockMessage state = new BlockMessage(inc);
                BlockType    block = BlockType.FromID(state.BlockID);
                //Verify Block (Make sure it is in bounds and it has changed, no use sending otherwise)
                //TODO: Punish players spamming invalid data (Because official client should never send it)
                if (map.InBounds(state.X, state.Y, state.Z) && map.Tiles[state.X, state.Y, state.Z].Block.ID != block.ID)
                {
                    map.Tiles[state.X, state.Y, state.Z].Block = block;
                    NetManager.Broadcast(sender.Map, state);
                }
                break;
            }

            //When a player sends a chat message
            case MessageTypes.Chat:
            {
                ChatMessage chat = new ChatMessage(inc);
                chat.ID = sender.ID;

                //Verify length
                if (chat.Message.Length > ChatMessage.MaxLength)
                {
                    chat.Message = chat.Message.Truncate(ChatMessage.MaxLength);
                }
                NetManager.BroadcastExcept(chat, sender);

                //Log message
                Log.WriteLine(LogType.Chat, ConsoleColor.Gray, "<{0}> {1}", sender.Username, chat.Message);
                break;
            }

            //When a player changes smiley
            case MessageTypes.PlayerSmiley:
            {
                PlayerSmileyMessage smiley = new PlayerSmileyMessage(inc);
                smiley.ID = sender.ID;
                if (sender.Smiley != smiley.Smiley)
                {
                    sender.Smiley = smiley.Smiley;
                    NetManager.BroadcastExcept(smiley, sender);
                }
                break;
            }

            //When a player changes mode (Ex: godmode to normal
            case MessageTypes.PlayerMode:
            {
                PlayerModeMessage mode = new PlayerModeMessage(inc);
                mode.ID = sender.ID;
                if (sender.Mode != mode.Mode)
                {
                    sender.Mode = mode.Mode;
                    NetManager.BroadcastExcept(mode, sender);
                }
                break;
            }

            //When a player requests to join a room
            case MessageTypes.JoinRoom:
            {
                if (sender == null)         //If the sender isn't null, then they are already in a room
                {
                    JoinRoomMessage msg    = new JoinRoomMessage(inc);
                    int             newMap = Maps.IndexOf(Server.MapFromID(msg.ID));
                    LoginMessage    login  = Server.Logins[inc.SenderConnection.RemoteUniqueIdentifier];     //Fetch stored login from dictionary
                    Maps[newMap].Players.Add(new Player(Maps[newMap], Maps[newMap].Spawn, login.Username, inc.SenderConnection.RemoteUniqueIdentifier, Server.FindEmptyID(Maps[newMap]))
                        {
                            Tint = login.Color
                        });
                    sender = Server.PlayerFromRUI(inc.SenderConnection.RemoteUniqueIdentifier, true);
                    NetManager.Send(new InitMessage(sender.Map), sender);
                    //Send message to player notifing he is connected and ready
                    NetManager.Send(new PlayerJoinMessage(sender.Username, sender.ID, true, sender.Tint), sender);

                    //Log message
                    Log.WriteLine(LogType.Room, "{0} joined: {1}", login.Username, Maps[newMap].Name);
                    //Send message to everyone notifying of new user
                    NetManager.BroadcastExcept(new PlayerJoinMessage(sender.Username, sender.ID, false, sender.Tint), sender);
                    //Let new player know of all existing players and their states (Mode, Position, Smiley)
                    foreach (Player player in sender.Map.Players)
                    {
                        if (player.ID != sender.ID)
                        {
                            NetManager.Send(new PlayerJoinMessage(player.Username, player.ID, false, player.Tint), sender);
                            NetManager.Send(new PlayerStateMessage(player), sender);
                            if (player.Mode != PlayerMode.Normal)
                            {
                                NetManager.Send(new PlayerModeMessage(player), sender);
                            }
                            if (player.Smiley != SmileyType.Default)
                            {
                                NetManager.Send(new PlayerSmileyMessage(player, player.Smiley), sender);
                            }
                        }
                    }
                }
                break;
            }

            //When a player requests to make a room
            case MessageTypes.CreateRoom:     //If the sender isn't null, then they are already in a room
            {
                if (sender == null)
                {
                    CreateRoomMessage msg = new CreateRoomMessage(inc);
                    Map          newMap   = Server.CreateMap(msg.Name, msg.Description);
                    LoginMessage login    = Server.Logins[inc.SenderConnection.RemoteUniqueIdentifier];      //Fetch stored login from dictionary
                    newMap.Players.Add(new Player(newMap, newMap.Spawn, login.Username, inc.SenderConnection.RemoteUniqueIdentifier, Server.FindEmptyID(newMap))
                        {
                            Tint = login.Color
                        });
                    sender = Server.PlayerFromRUI(inc.SenderConnection.RemoteUniqueIdentifier, true);
                    //Send message to player notifing he is connected and ready
                    NetManager.Send(new InitMessage(sender.Map), sender);
                    NetManager.Send(new PlayerJoinMessage(sender.Username, sender.ID, true, sender.Tint), sender);
                    //Log message
                    Log.WriteLine(LogType.Room, "{0} created room: {1}", login.Username, newMap.Name);
                }
                break;
            }
            }
        }
コード例 #26
0
        /// <summary>
        /// Handles a data message (The bulk of all messages recieved, containing player movements, block places, etc)
        /// </summary>
        private void HandleDataMessage(NetIncomingMessage im)
        {
            MessageTypes messageType = (MessageTypes)im.ReadByte(); //Find the type of data message sent

            switch (messageType)
            {
            case MessageTypes.Lobby:     //Lobby list packet
            {
                if (Game.CurrentGameState == GameState.Lobby)
                {
                    LobbyScreen  screen = MainWindow.ScreenManager.Current as LobbyScreen;
                    LobbyMessage msg    = new LobbyMessage(im);
                    screen.Name        = msg.ServerName;
                    screen.Description = msg.Description;
                    screen.Intro       = msg.Intro;
                    screen.Online      = msg.Online;
                    screen.Rooms       = msg.Rooms;
                    screen.Lobby.LoadRooms();
                }
                break;
            }

            case MessageTypes.PlayerJoin:     //Player join message
            {
                PlayerJoinMessage user = new PlayerJoinMessage(im);
                //Add player to map
                Map.Players.Add(new Player(Map, Map.Spawn, user.Username, user.ID)
                    {
                        Tint = user.Color
                    });
                //Add user to userlist
                (MainWindow.ScreenManager.Current as GameScreen).PlayerList.Items.Add(user.Username);
                if (user.ID != Game.MyID && recievedInit)         //Broadcast join message to chat
                {
                    (MainWindow.ScreenManager.Current as GameScreen).SystemChat(user.Username + " [color:LightGray]has[/color] [color:LightGreen]joined.[/color]");
                }
                if (user.Me)
                {
                    //Let game know of it's own player
                    Game.MyID    = user.ID;
                    Game.MyIndex = (byte)Map.Players.IndexOf(Map.Players.First(x => x.ID == Game.MyID));
                    Game.Me.Tint = Game.MyColor;
                }
                break;
            }

            case MessageTypes.PlayerLeave:     //Player leave message
            {
                PlayerLeaveMessage user = new PlayerLeaveMessage(im);
                //Remove player
                if (user.ID != Game.MyID)
                {
                    Player player = (Player)Map.PlayerFromID(user.ID);
                    Map.Players.Remove((Player)Map.PlayerFromID(user.ID));
                    (MainWindow.ScreenManager.Current as GameScreen).PlayerList.Items.Remove(player.Username);
                    (MainWindow.ScreenManager.Current as GameScreen).SystemChat(player.Username + " [color:LightGray]has[/color] [color:IndianRed]left.[/color]");
                    //Rebuild indexes
                    for (int i = 0; i < Map.Players.Count; i++)
                    {
                        Map.Players[i].Index = i;
                        if (Map.Players[i].ID == Game.MyID)
                        {
                            Game.MyIndex = (byte)i;
                        }
                    }
                }
                break;
            }

            case MessageTypes.PlayerStatus:     //Player move message
            {
                if (Game.CurrentGameState == GameState.Game)
                {
                    PlayerStateMessage user   = new PlayerStateMessage(im);
                    Player             player = (Player)Map.PlayerFromID(user.ID);
                    player.SimulationState.Position = user.Position.ToVector2();
                    player.SimulationState.Velocity = user.Velocity.ToVector2();
                    player.SimulationState.Movement = user.Movement.ToVector2();
                    if (!recievedInit)         //If we have not recieved init (meaning we are not in game yet), set the initial positions directly so interpolation doesn't mess with them
                    {
                        player.DisplayState.Position = player.SimulationState.Position;
                    }
                    player.VirtualJump = user.IsJumping;
                }
                break;
            }

            case MessageTypes.Block:     //Block place message
            {
                if (Game.CurrentGameState == GameState.Game)
                {
                    BlockMessage msg   = new BlockMessage(im);
                    BlockType    block = BlockType.FromID(msg.BlockID);
                    if (Map.CanPlaceBlock(msg.X, msg.Y, msg.Z, block))
                    {
                        Map.Tiles[msg.X, msg.Y, msg.Z].Block = block;
                    }
                }
                break;
            }

            case MessageTypes.PlayerSmiley:     //Smiley change message
            {
                if (Game.CurrentGameState == GameState.Game)
                {
                    PlayerSmileyMessage msg = new PlayerSmileyMessage(im);
                    Player p = (Player)Map.PlayerFromID(msg.ID);
                    p.Smiley = msg.Smiley;
                }
                break;
            }

            case MessageTypes.PlayerMode:     //Player mode change message
            {
                if (Game.CurrentGameState == GameState.Game)
                {
                    PlayerModeMessage mode = new PlayerModeMessage(im);
                    Map.PlayerFromID(mode.ID).Mode = (PlayerMode)mode.Mode;
                }
                break;
            }

            case MessageTypes.Chat:     //Chat message
            {
                if (Game.CurrentGameState == GameState.Game)
                {
                    ChatMessage chat = new ChatMessage(im);
                    (MainWindow.ScreenManager.Current as GameScreen).AddChat(Map.PlayerFromID(chat.ID).Username, chat.Message);
                }
                break;
            }

            case MessageTypes.Init:     //Initialization message with world data
            {
                Game.Map = new Bricklayer.Client.World.Map(game, 1, 1);
                InitMessage msg = new InitMessage(im, Map);

                Game.Map.Minimap = new Minimap(Game.Map, msg.Width, msg.Height)
                {
                    Position = new Microsoft.Xna.Framework.Vector2(8, 8)
                };
                Game.Map.CreateCamera();

                Game.CurrentGameState = GameState.Game;
                (MainWindow.ScreenManager.Current as GameScreen).Show();
                (MainWindow.ScreenManager.Current as GameScreen).SystemChat("Connected to [color:LightGray]" + Game.Host + ":" + Game.Port + "[/color]");
                recievedInit = true;
                break;
            }
            }
        }
コード例 #27
0
        void client_Said(object sender, TasSayEventArgs e)
        {
            User user;

            if (!client.ExistingUsers.TryGetValue(e.UserName, out user))
            {
                return;
            }
            if (e.Place == SayPlace.Channel && e.Channel != "main")
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        using (var db = new ZkDataContext())
                        {
                            Channel channel;
                            if (!client.JoinedChannels.TryGetValue(e.Channel, out channel))
                            {
                                return;
                            }
                            foreach (var s in db.LobbyChannelSubscriptions.Where(x => x.Channel == e.Channel).Select(x => x.Account))
                            {
                                if (!channel.Users.ContainsKey(s.Name))
                                {
                                    var fac = db.Factions.FirstOrDefault(x => x.Shortcut == e.Channel);
                                    // if faction channel check if allowed
                                    if (fac == null || (fac.FactionID == s.AccountID && s.Level >= GlobalConst.FactionChannelMinLevel))
                                    {
                                        var message = new LobbyMessage()
                                        {
                                            SourceLobbyID = user.AccountID,
                                            SourceName    = e.UserName,
                                            Created       = DateTime.UtcNow,
                                            Message       = e.Text,
                                            TargetName    = s.Name,
                                            Channel       = e.Channel
                                        };
                                        db.LobbyMessages.InsertOnSubmit(message);
                                    }
                                }
                            }
                            db.SubmitChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error storing message: {0}", ex);
                    }
                });
            }
            else if (e.Place == SayPlace.User)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        if (e.Place == SayPlace.User)
                        {
                            if (e.Text.StartsWith("!pm"))
                            {
                                var regex = Regex.Match(e.Text, "!pm ([^ ]+) (.+)");
                                if (regex.Success)
                                {
                                    var name = regex.Groups[1].Value;
                                    var text = regex.Groups[2].Value;

                                    var message = new LobbyMessage()
                                    {
                                        SourceLobbyID = user.AccountID, SourceName = e.UserName, Created = DateTime.UtcNow, Message = text, TargetName = name
                                    };
                                    using (var db = new ZkDataContext())
                                    {
                                        db.LobbyMessages.InsertOnSubmit(message);
                                        db.SubmitChanges();
                                    }
                                }
                            }
                            else if (e.Text.StartsWith("!subscribe"))
                            {
                                var regex = Regex.Match(e.Text, "!subscribe #([^ ]+)");
                                if (regex.Success)
                                {
                                    var chan = regex.Groups[1].Value;
                                    if (chan != "main")
                                    {
                                        using (var db = new ZkDataContext()) {
                                            Account account = Account.AccountByName(db, e.UserName);
                                            if (chan == AuthService.ModeratorChannel && !(account.IsZeroKAdmin))
                                            {
                                                client.Say(SayPlace.User, user.Name, "Not authorized to subscribe to this channel", false);
                                            }
                                            else
                                            {
                                                var accountID = account.AccountID;
                                                var subs      = db.LobbyChannelSubscriptions.FirstOrDefault(x => x.AccountID == accountID && x.Channel == chan);
                                                if (subs == null)
                                                {
                                                    subs = new LobbyChannelSubscription()
                                                    {
                                                        AccountID = accountID, Channel = chan
                                                    };
                                                    db.LobbyChannelSubscriptions.InsertOnSubmit(subs);
                                                    db.SubmitChanges();
                                                    client.JoinChannel(chan);
                                                }
                                                client.Say(SayPlace.User, user.Name, "Subscribed", false);
                                            }
                                        }
                                    }
                                }
                            }
                            else if (e.Text.StartsWith("!unsubscribe"))
                            {
                                var regex = Regex.Match(e.Text, "!unsubscribe #([^ ]+)");
                                if (regex.Success)
                                {
                                    var chan = regex.Groups[1].Value;

                                    using (var db = new ZkDataContext()) {
                                        var accountID = Account.AccountByName(db, e.UserName).AccountID;
                                        var subs      = db.LobbyChannelSubscriptions.FirstOrDefault(x => x.AccountID == accountID && x.Channel == chan);
                                        if (subs != null)
                                        {
                                            db.LobbyChannelSubscriptions.DeleteOnSubmit(subs);
                                            db.SubmitChanges();
                                        }
                                        client.Say(SayPlace.User, user.Name, "Unsubscribed", false);
                                    }
                                }
                            }
                            else if (e.Text.Equals("!listsubscriptions"))
                            {
                                using (var db = new ZkDataContext())
                                {
                                    var accountID        = Account.AccountByName(db, e.UserName).AccountID;
                                    var subscriptionList = "No channels subscribed.";
                                    var subs             = db.LobbyChannelSubscriptions.Where(x => x.AccountID == accountID).OrderBy(x => x.Channel).Select(x => x.Channel);
                                    if (subs != null)
                                    {
                                        subscriptionList = "Subscribed to: " + String.Join(", ", subs);
                                    }
                                    client.Say(SayPlace.User, user.Name, subscriptionList, false);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error sending stored message: {0}", ex);
                    }
                });
            }
        }
コード例 #28
0
    void ProcessLobbyMessage(LobbyMessage lobbyMessage, IPEndPoint remoteEndPoint)
    {
        if (lobbyMessage.requestRoomList)
        {
            if (lobby != null && lobby.isMaster && lobbyState == LobbyState.InLobby)
            {
                BroadcastLobby();
            }
        }
        else if (lobbyMessage.startGame && lobbyState == LobbyState.InLobby)
        {
            if (lobbyMessage.senderGuid == lobby.master.guid)
            {
                StartGame();
                NotifyStartGame();
            }
        }
        else if (lobbyMessage.startGame && lobbyState == LobbyState.InGame && lobby.isMaster)
        {
            var targetPlayer = lobby.players.Find(item => item.guid == lobbyMessage.senderGuid);
            if (targetPlayer != null)
            {
                targetPlayer.started = true;
            }
            CheckReady();
        }
        else if (lobby != null && lobby.isMaster) // I am the lobby master
        {
            if (lobbyMessage.masterGuid != guidStr)
            {
                return;
            }

            if (lobbyMessage.iWantToJoin)
            {
                var targetPlayer = lobby.players.Find(item => item.guid == lobbyMessage.senderGuid);
                if (targetPlayer == null && lobby.players.Count < MAX_PLAYER_COUNT)
                {
                    targetPlayer = new LobbyPlayer {
                        guid     = lobbyMessage.senderGuid,
                        endPoint = new IPEndPoint(remoteEndPoint.Address, lobbyMessage.myPort), isMaster = false
                    };
                    lobby.players.Add(targetPlayer);
                    NotifyJoinSuccess(targetPlayer);
                    ThreadSafeLog(string.Format("player on {0} joined.", targetPlayer.endPoint));
                }
            }
        }
        else if (lobbyState == LobbyState.NoLobby) // then I'm just a guest player
        {
            if (lobbyMessage.iWantToJoin == false)
            {
                var targetLobby = lobbyList.Find(item => item.master.guid == lobbyMessage.senderGuid);
                if (targetLobby == null)
                {
                    var newLobby = new Lobby
                    {
                        currentCount = lobbyMessage.currentPlayerCount,
                        maxCount     = lobbyMessage.maxPlayerCount,
                        isMaster     = false,
                        master       = new LobbyPlayer {
                            guid = lobbyMessage.senderGuid, endPoint = new IPEndPoint(remoteEndPoint.Address, lobbyMessage.myPort), isMaster = true
                        }
                    };
                    lobbyList.Add(newLobby);
                    ThreadSafeLog("Found lobby on " + newLobby.master.endPoint.ToString());
                    if (autoJoin)
                    {
                        RequestJoinLobby(newLobby);
                    }
                }
                else if (targetLobby.master.guid == lobbyMessage.senderGuid)
                {
                    targetLobby.currentCount = lobbyMessage.currentPlayerCount;
                    if (lobbyMessage.joinStatus == 1)
                    {
                        lobby      = targetLobby;
                        master     = lobby.master;
                        lobbyState = LobbyState.InLobby;
                        ThreadSafeLog("Successfully joined lobby: " + lobby.master.endPoint.ToString());
                    }
                }
            }
        }
    }