Exemplo n.º 1
0
        private void Sign_up_outB_Click(object sender, EventArgs e)
        {
            if (Sign_up_outB.Text == "Sign up")
            {
                this.Hide();
                Form SignUpForm = new SignUp(clientSocket, this);
                SignUpForm.Show();
            }
            else if (Sign_up_outB.Text == "Sign out")
            {
                string        signOutMsg   = "201";
                NetworkStream serverStream = clientSocket.GetStream();
                byte[]        outStream    = System.Text.Encoding.ASCII.GetBytes(signOutMsg);
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();

                Sign_up_outB.Text = "Sign up";
                UserNameLable.Show();
                PasswordLable.Show();
                userNameBox.Text = "";
                passwordBox.Text = "";
                userNameBox.Show();
                passwordBox.Show();
                SignIn.Show();
                GreetingsLable.Visible = false;
                JoinRoom.Hide();
                CreateRoom.Hide();
                MyStatus.Hide();
                BestScores.Hide();
            }
        }
Exemplo n.º 2
0
 public void OnClickJoinButton()
 {
     lobbyManager.StartMatchMaker();
     JoinRoomObj.SetActive(true);
     _joinRoom = JoinRoomObj.GetComponent <JoinRoom>();
     _joinRoom.RefreshList();
 }
Exemplo n.º 3
0
 // Start is called before the first frame update
 void Start()
 {
     playerName = "No Name";
     SceneManager.sceneLoaded += OnSceneFinishedLoading;
     _joinRoom = GetComponent <JoinRoom>();
     _lobby    = GetComponent <Lobby>();
 }
Exemplo n.º 4
0
 private void Menu_Load(object sender, EventArgs e)
 {
     JoinRoom.Hide();
     CreateRoom.Hide();
     MyStatus.Hide();
     BestScores.Hide();
 }
Exemplo n.º 5
0
 public void OnClickJoin()
 {
     lm.StartMatchMaker();
     joinRoomObject.SetActive(true);
     jr = joinRoomObject.GetComponent <JoinRoom> ();
     jr.refreshRoom();
 }
Exemplo n.º 6
0
        private void joinRoom(AdvancedNetworkLib.Client client, JoinRoom joinRoom)
        {
            ClientUserData userData = client.UserData as ClientUserData;

            // check password
            bool passwordIsValid = Server.Clients.Any(c =>
            {
                var u = c.UserData as ClientUserData;
                return(u != null && u.RoomName == joinRoom.Name && u.Password == joinRoom.Password);
            });

            if (!passwordIsValid)
            {
                client.send(new Error {
                    Job = Job.RoomJoin
                });
            }
            else
            {
                userData.RoomName = joinRoom.Name;
                userData.Password = joinRoom.Password;
                userData.Host     = false;

                client.send(new Success {
                    Job = Job.RoomJoin
                });
            }

            this.updateOverview();
        }
Exemplo n.º 7
0
    public void ConnectToLobby(String name, String roomCode)
    {
        JoinRoom joinRoom = new JoinRoom
        {
            name     = name,
            roomCode = roomCode
        };
        string  Message            = JsonConvert.SerializeObject(joinRoom, Formatting.Indented);
        String  serverResponse     = SendServerMessage(Message);
        JObject serverJSONResponse = JObject.Parse(serverResponse);

        if (serverJSONResponse.GetValue("response").ToString() == "Missing")
        {
            SceneManager.LoadScene("Lobby");
        }
        else
        {
            profile = new Profile
            {
                id         = long.Parse(serverJSONResponse.GetValue("id").ToString()),
                name       = name,
                enemyName  = serverJSONResponse.GetValue("enemyName").ToString(),
                isHost     = false,
                seed       = int.Parse(serverJSONResponse.GetValue("seed").ToString()),
                difficulty = int.Parse(serverJSONResponse.GetValue("difficulty").ToString()),
                roomCode   = roomCode
            };

            playerController.setMove(false);
            StartGame(profile.roomCode);
        }
    }
Exemplo n.º 8
0
 public void OnClickFindLobby()
 {
     lobbyManager.StartMatchMaker();
     joinRoomObj.SetActive(true);
     joinRoom = joinRoomObj.GetComponent <JoinRoom>();
     joinRoom.RefreshList();
 }
Exemplo n.º 9
0
 public void OnClickJoinButton()
 {
     lobbyJoin.SetActive(true);
     lobbyManager.StartMatchMaker();
     joinRoomObject.SetActive(true);
     joinRoom = joinRoomObject.GetComponent <JoinRoom>();
     joinRoom.RefreshRoom();
 }
Exemplo n.º 10
0
    private void OnHandShake()
    {
        JoinRoom joinRoom = new JoinRoom();

        joinRoom.roomID   = PhotonEngine.Instance.RoomID;
        joinRoom.userName = PhotonEngine.Instance.UserName;
        PhotonEngine.Instance.DoRequest(OperationCode.JoinRoom, joinRoom);
    }
Exemplo n.º 11
0
    public void JoinRoomRequest(int fd, int roomOwnerFd)
    {
        ProtocolNetRequest req = new ProtocolNetRequest();

        req.cmd = (int)NetRequestType.JOINROOM;
        JoinRoom joinRoom = new JoinRoom();

        joinRoom.fd = fd;
        socket.sendMSG(PBCSerialize.Serialize(req));
    }
Exemplo n.º 12
0
    public void JoinRoom(int room_id)
    {
//		Connect("10.0.6.156", 2000);
//		Connect("127.0.0.1", 2000);

        Connect("10.0.6.34", 2000);

        JoinRoom packet = new JoinRoom();

        packet.room_id = room_id;
        SendPacket(RequestId.JoinRoom, packet);
    }
Exemplo n.º 13
0
        public void StartGame()
        {
            Connect        con        = new Connect();
            MenuAfterLogin cojg       = new MenuAfterLogin();
            Game           game       = new Game();
            CreateRoom     createRoom = new CreateRoom();
            JoinRoom       joinRoom   = new JoinRoom();
            Ranking        ranking    = new Ranking();

            ConnectController controller = new ConnectController(con, cojg, createRoom, joinRoom, ranking, game);

            controller.LoadViewConnect(con);
            con.ShowDialog();
            _view.Hide();
        }
Exemplo n.º 14
0
    //룸 정보를 읽어와서 화면에 뿌려주는 함수
    //룸 변화가 있을때마다 위에 OnReceivedRoomListUpdate 함수에서 실행시켜줌
    public void RoomDisplay()
    {
        foreach (GameObject item in GameObject.FindGameObjectsWithTag("Room"))
        {
            Destroy(item);
        }

        foreach (RoomInfo room in PhotonNetwork.GetRoomList())
        {
            //Debug.Log(room.Name);
            GameObject Rooms    = Instantiate(roomObject);
            JoinRoom   roomdata = Rooms.GetComponent <JoinRoom>();
            roomdata.NameSetting(room.Name);
            Rooms.transform.SetParent(GameObject.Find("Grid").transform, false);
        }
    }
Exemplo n.º 15
0
        public void JoinRoom(JoinRoom joinRoom)
        {
            var userId = GetUserId();

            if (userId == null)
            {
                return;
            }

            Groups.Add(Context.ConnectionId, joinRoom.RoomId.ToString());

            roomService.AddUser(joinRoom.RoomId, userId.Value, Context.ConnectionId, UnixTimeStampToDateTime(joinRoom.LastUpdated));

            Clients
            .Group(joinRoom.RoomId.ToString())
            .updateRoomUsers(GetSerializableRoomMembers(joinRoom.RoomId));
        }
Exemplo n.º 16
0
    public void ButtonClick()
    {
        ProtocolNetRequest req = new ProtocolNetRequest();

        req.cmd = (int)NetRequestType.JOINROOM;
        JoinRoom joinRoom = new JoinRoom();

        joinRoom.fd                  = GameGlobalData.fd;
        joinRoom.roomOwnerFd         = ownerFd;
        GameGlobalData.roomOwnerFd   = ownerFd;
        GameGlobalData.roomOwnerName = OwnerNameText.text;
        GameGlobalData.roomName      = RoomNameText.text;
        GameGlobalData.currentMan    = this.manCount;
        GameGlobalData.maxManCount   = this.maxManCount;
        req.joinRoom                 = joinRoom;
        ConnectSocket.getSocketInstance().sendMSG(PBCSerialize.Serialize(req));
    }
Exemplo n.º 17
0
        public override void OnOperateRequest(byte[] bytes, ClientPeer peer, SendParameters sendParameters)
        {
            JoinRoom joinRoom = PackageHelper.Desirialize <JoinRoom>(bytes);

            GameApplication application = GameApplication.Instance;

            if (application == null)
            {
                return;
            }

            Room room = application.GetRoom(joinRoom.roomID);

            if (room == null)
            {
                return;
            }
            room.JoinRoom(peer as GameClientPeer, joinRoom.userName);
        }
        static void OnRoomJoin(JoinRoom msg, IOperationContext context)
        {
            var newMember = new RoomMember
            {
                RoomName    = msg.RoomName,
                UserName    = msg.ClientName,
                UserChannel = context.ReplyChannel
            };
            List <RoomMember> members;

            if (!Rooms.TryGetValue(msg.RoomName, out members))
            {
                members = new List <RoomMember> {
                    newMember
                };
                Rooms.Add(msg.RoomName, members);
            }
            else
            {
                if (members.Any(x => x.UserName == msg.ClientName))
                {
                    context.ReplyChannel.Reply(context, new JoinRoomResponse()
                    {
                        RetCode = JoinRoomRetCode.NameIsTaken
                    });
                    return;
                }
                else
                {
                    members.ForEach((m) => m.UserChannel.Send(new RoomEvent()
                    {
                        UserName = msg.ClientName, Text = "Joined"
                    }));
                    members.Add(newMember);
                }
            }
            RoomMembers.Add(context.ReplyChannel, newMember);

            context.ReplyChannel.Reply(context, new JoinRoomResponse()
            {
                RetCode = JoinRoomRetCode.Ok
            });
        }
        public async Task HandleAsync(IWebSocketRemoteDevice remoteDevice, JoinRoom args)
        {
            Require.NotNull(args.RoomId);
            Require.NotNull(args.Username);

            var result = await _coreHandler.HandleAsync(remoteDevice, new JoinRoomRequest
            {
                Username = args.Username,
                RoomId   = RoomId.FromString(args.RoomId)
            });

            if (result.Success)
            {
                await remoteDevice.SendAsync("JoinRoomSuccess", null);
            }
            else
            {
                await remoteDevice.SendAsync("JoinRoomFailed", result.ErrorMessage);
            }
        }
        async Task<JoinRoomResponse> OnRoomJoin(JoinRoom msg, IOperationContext context)
        {
            var room = await _rooms.GetActor(new ActorKey(msg.RoomName));

            var callbackRef = _callbacksNode.ExposeAsCallbackChannel(this);
            var joinRoomOnServer = new JoinRoomS2S()
            {
                CallbackChannelRef = callbackRef,
                RoomName = msg.RoomName,
                UserName = msg.UserName
            };
            var reply = await room.SendAsync<JoinRoomResponse>(joinRoomOnServer, context);
            if (reply.RetCode == JoinRoomRetCode.Ok)
            {
                _room = room;
                _userName = msg.UserName;
            }

            return reply;
        }
        async Task<JoinRoomResponse> OnRoomJoin(JoinRoom msg, IOperationContext context)
        {
            var room = ActorProxy.Create<ISFRoomActor>(new ActorId(msg.RoomName));

            await room.SubscribeAsync(this);

            var joinRoomOnServer = new JoinRoomS2S()
            {
                RoomName = msg.RoomName,
                UserName = msg.UserName
            };
            var reply = await room.JoinRoom(joinRoomOnServer);
            if (reply.RetCode == JoinRoomRetCode.Ok)
            {
                _room = room;
                _userName = msg.UserName;
            }

            return reply;
        }
Exemplo n.º 22
0
        async Task <JoinRoomResponse> OnRoomJoin(JoinRoom msg, IOperationContext context)
        {
            var room = await _rooms.GetActor(new ActorKey(msg.RoomName));

            var callbackRef      = _callbacksNode.ExposeAsCallbackChannel(this);
            var joinRoomOnServer = new JoinRoomS2S()
            {
                CallbackChannelRef = callbackRef,
                RoomName           = msg.RoomName,
                UserName           = msg.UserName
            };
            var reply = await room.SendAsync <JoinRoomResponse>(joinRoomOnServer, context);

            if (reply.RetCode == JoinRoomRetCode.Ok)
            {
                _room     = room;
                _userName = msg.UserName;
            }

            return(reply);
        }
Exemplo n.º 23
0
        async Task <JoinRoomResponse> OnRoomJoin(JoinRoom msg, IOperationContext context)
        {
            var room = ActorProxy.Create <ISFRoomActor>(new ActorId(msg.RoomName));

            await room.SubscribeAsync(this);

            var joinRoomOnServer = new JoinRoomS2S()
            {
                RoomName = msg.RoomName,
                UserName = msg.UserName
            };
            var reply = await room.JoinRoom(joinRoomOnServer);

            if (reply.RetCode == JoinRoomRetCode.Ok)
            {
                _room     = room;
                _userName = msg.UserName;
            }

            return(reply);
        }
Exemplo n.º 24
0
 public void Update()
 {
     if (serverEvent.Count > 0)
     {
         MessageXieYi xieyi = serverEvent.Dequeue();
         if ((MessageConvention)xieyi.XieYiFirstFlag == MessageConvention.createRoom ||
             (MessageConvention)xieyi.XieYiFirstFlag == MessageConvention.joinRoom)
         {
             JoinRoom joinInfo = new JoinRoom();
             joinInfo = SerializeHelper.Deserialize <JoinRoom>(xieyi.MessageContent);
             ErrorType error = joinInfo.error;
             if (error != ErrorType.none)
             {
                 UIManager.instance.ShowAlertTip("加入房间失败" + error);
             }
             else
             {
                 //GameManager.GetRoomInfo();
             }
         }
         if ((MessageConvention)xieyi.XieYiFirstFlag == MessageConvention.getRoomInfo)
         {
             RoomUI.Show();
             CreateRoomUI.Close();
         }
         if ((MessageConvention)xieyi.XieYiFirstFlag == MessageConvention.updateRoom)
         {
             ErrorType error = ClassGroup.CheckIsError(xieyi);
             if (error != ErrorType.none)
             {
                 UIManager.instance.ShowAlertTip("更新房间失败:" + error);
             }
             else
             {
                 UIManager.instance.ShowAlertTip("更新房间成功");
             }
             Close();
         }
     }
 }
Exemplo n.º 25
0
        public override async Task OnConnectedAsync()
        {
            var context = Context.GetHttpContext();
            var id      = context.Request.Query["access_token"];

            await Subscribe(id);

            var command = new JoinRoom();

            command.RoomId       = Guid.Parse(id);
            command.ConnectionId = Context.ConnectionId;
            await DispatchAsync(command);

            await _roomListHub.SendToAllAsync("joined", new { roomId = command.Result.RoomId, numberOfPlayers = command.Result.NumberOfPlayers });

            await SendToGroupAsync(id, "joined", command.Result);

            if (command.Result.Players.Exists(x => x.ConnectionId == Context.ConnectionId))
            {
                await Clients.Caller.SendAsync("identity", command.Result.Players.Find(x => x.ConnectionId == Context.ConnectionId).Identity);
            }
        }
Exemplo n.º 26
0
        private void OnJoinRoom(byte[] data)
        {
            string roomName = Encoding.UTF8.GetString(data);

            JoinRoom?.Invoke(this, roomName);
        }
Exemplo n.º 27
0
        private void SignIn_Click(object sender, EventArgs e)
        {
            try
            {
                if (userNameBox.Text.Length == 0 || passwordBox.Text.Length == 0)
                {
                    msgToUser.Text    = "Please fill all fields";
                    msgToUser.Visible = true;
                    return;
                }
                string signInMsg = "200" +
                                   userNameBox.Text.Length.ToString().PadLeft(2, '0') + userNameBox.Text +
                                   passwordBox.Text.Length.ToString().PadLeft(2, '0') + passwordBox.Text;
                NetworkStream serverStream = clientSocket.GetStream();
                byte[]        outStream    = System.Text.Encoding.ASCII.GetBytes(signInMsg);
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();

                byte[] inStream = new byte[4];
                serverStream.Read(inStream, 0, 4);
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                //msg(returndata);

                switch (returndata.Substring(0, 4))
                {
                case "1020":
                    //Success
                    Sign_up_outB.Text = "Sign out";
                    UserNameLable.Hide();
                    PasswordLable.Hide();
                    userNameBox.Hide();
                    passwordBox.Hide();
                    SignIn.Hide();
                    GreetingsLable.Text    = "Hello " + userNameBox.Text;
                    GreetingsLable.Visible = true;
                    TriviaLogoTop.Image    = Properties.Resources.Trivia;
                    TriviaLogoRight.Image  = Properties.Resources.Trivia;
                    TriviaLogoLeft.Image   = Properties.Resources.Trivia;
                    JoinRoom.Enabled       = true;
                    CreateRoom.Enabled     = true;
                    MyStatus.Enabled       = true;
                    BestScores.Enabled     = true;
                    JoinRoom.Show();
                    CreateRoom.Show();
                    MyStatus.Show();
                    BestScores.Show();
                    msgToUser.Text    = "";
                    msgToUser.Visible = false;
                    break;

                case "1021":
                    //Wrong Details
                    msgToUser.Text    = "Wrong Details";
                    msgToUser.Visible = true;
                    //set trivia to red
                    TriviaLogoTop.Image   = Properties.Resources.ErrorTriviaLogo;
                    TriviaLogoRight.Image = Properties.Resources.ErrorTriviaLogo;
                    TriviaLogoLeft.Image  = Properties.Resources.ErrorTriviaLogo;
                    break;

                case "1022":
                    //User is already connected
                    msgToUser.Text    = "User is already connected";
                    msgToUser.Visible = true;
                    //set trivia to red
                    TriviaLogoTop.Image   = Properties.Resources.ErrorTriviaLogo;
                    TriviaLogoRight.Image = Properties.Resources.ErrorTriviaLogo;
                    TriviaLogoLeft.Image  = Properties.Resources.ErrorTriviaLogo;
                    break;

                default:
                    msg("Got unknown code: " + returndata);
                    break;
                }
            }
            catch (Exception exc)
            {
                msg(exc.Message);
            }
        }
Exemplo n.º 28
0
        public void AddNewAccount(string serveripTextbox, string portTextbox, string userNameTextbox, string passwordTextbox, string emailTextbox, string yearComboBox, string genderComboBox, string captchaTextbox)
        {
            string connectionEstablish;

            connectionEstablish = "CREATE_ACCOUNT;" + userNameTextbox + ";" + passwordTextbox + ";" + emailTextbox + ";" + yearComboBox + ";" + genderComboBox;


            tcpClient = new TcpClient();
            tcpClient.Connect(serveripTextbox, int.Parse(portTextbox));
            isConnectedToServer = true;
            strWritter          = new StreamWriter(tcpClient.GetStream());
            strWritter.WriteLine(connectionEstablish);
            strWritter.Flush();


            Console.WriteLine("nowy Connection");

            incomingMessageHandler = new Thread(() => ReceiveMessages());
            incomingMessageHandler.IsBackground = true;
            incomingMessageHandler.Start();

            int interval = 3000;


            while (!ACCOUNT_CREATED_SUCCESFULLY)

            {
                Console.WriteLine("spie 3 sek: ");
                Thread.Sleep(interval);
                if (ACCOUNT_CREATED_SUCCESFULLY == true)
                {
                    Console.WriteLine("JEST JUZ OK, ZAMYKAMY!");

                    SaveSettings();

                    ConnectController c = new ConnectController();


                    Connect        con  = new Connect();
                    MenuAfterLogin cojg = new MenuAfterLogin();
                    Game           game = new Game();

                    CreateRoom createRoom = new CreateRoom();

                    JoinRoom joinRoom = new JoinRoom();

                    Ranking ranking = new Ranking();


                    ConnectController controller = new ConnectController(con, cojg, createRoom, joinRoom, ranking, game);
                    controller.LoadViewConnect(con);
                    con.ShowDialog();

                    _view.Hide();
                    _view.Close();
                    _view.DisposeForm();

                    Console.WriteLine(ACCOUNT_CREATED_SUCCESFULLY + "jest just tru!!");
                }
                Console.WriteLine("ja zyje");
            }
        }
Exemplo n.º 29
0
    /// <summary>
    /// 判断并通知事件回调
    /// </summary>
    /// <param name="buff"></param>
    private void DealXieYi(MessageXieYi xieyi, AsyncUserToken userToken)
    {
        //Debug.LogError("处理协议:" + (MessageConvention)xieyi.XieYiFirstFlag);
        byte[]          tempMessageContent = xieyi.MessageContent;
        string          messageInfo        = "";
        ErrorType       error           = ErrorType.none;
        RoomActor       actor           = null;
        RoomActorUpdate roomActorUpdate = new RoomActorUpdate();

        //if (tempMessageContent.Length > 200)
        //{
        //    Debug.Log((MessageConvention)xieyi.XieYiFirstFlag + "单次接收数据超过200/" + tempMessageContent.Length);
        //}
        try
        {
            //处理数值到DataController
            switch ((MessageConvention)xieyi.XieYiFirstFlag)
            {
            case MessageConvention.error:
                break;

            case MessageConvention.login:
                error = ClassGroup.CheckIsError(xieyi);
                if (error == ErrorType.none)
                {
                    actor = SerializeHelper.Deserialize <RoomActor>(xieyi.MessageContent);
                    DataController.instance.myInfo = actor;
                }
                break;

            case MessageConvention.getHeartBeatTime:
                HeartbeatTime beatTime = SerializeHelper.Deserialize <HeartbeatTime>(xieyi.MessageContent);
                heartbeatSecondTime = beatTime.time - 1;    //-1防止和服务器心跳时间一致的时候会导致偏差
                //Debug.Log("心跳间隔:" + heartbeatSecondTime);
                break;

            case MessageConvention.reConnectCheck:
                break;

            case MessageConvention.reConnectIndex:
                int index = int.Parse(SerializeHelper.ConvertToString(xieyi.MessageContent));
                GameManager.instance.reConnectIndex = index;
                break;

            case MessageConvention.heartBeat:
                break;

            case MessageConvention.updateName:
                actor = SerializeHelper.Deserialize <RoomActor>(xieyi.MessageContent);
                DataController.instance.myInfo = actor;
                break;

            case MessageConvention.createRoom:
            case MessageConvention.joinRoom:
                JoinRoom joinInfo = new JoinRoom();
                joinInfo = SerializeHelper.Deserialize <JoinRoom>(tempMessageContent);
                DataController.instance.MyLocateIndex = joinInfo.unique;
                break;

            case MessageConvention.updateRoom:
                //Debug.Log((MessageConvention)xieyi.XieYiFirstFlag + "数据长度:" + xieyi.MessageContent.Length);
                error = ClassGroup.CheckIsError(xieyi);
                if (error == ErrorType.none)
                {
                    DataController.instance.MyRoomInfo = SerializeHelper.Deserialize <RoomInfo>(tempMessageContent);
                }
                break;

            case MessageConvention.getRoomInfo:
                DataController.instance.MyRoomInfo = SerializeHelper.Deserialize <RoomInfo>(tempMessageContent);
                Debug.LogError("得到房间号:" + DataController.instance.MyRoomInfo.RoomID);
                break;

            case MessageConvention.quitRoom:
                QuitInfo qInfo = SerializeHelper.Deserialize <QuitInfo>(xieyi.MessageContent);
                if (qInfo.isQuit)
                {
                    DataController.instance.MyRoomInfo = null;
                    DataController.instance.ActorList  = null;
                }
                break;

            case MessageConvention.getRoommateInfo:
                List <RoomActor> rActors = SerializeHelper.Deserialize <List <RoomActor> >(tempMessageContent);
                for (int i = 0; i < rActors.Count; i++)
                {
                    if (DataController.instance.ActorList == null)
                    {
                        DataController.instance.ActorList = new Dictionary <int, RoomActor>();
                    }
                    lock (DataController.instance.ActorList)
                    {
                        if (!DataController.instance.ActorList.ContainsKey(rActors[i].UniqueID))
                        {
                            DataController.instance.ActorList.Add(rActors[i].UniqueID, null);
                        }
                        DataController.instance.ActorList[rActors[i].UniqueID] = rActors[i];
                    }
                }
                Debug.Log("得到房间人物列表。");
                break;

            case MessageConvention.rotateDirection:

                break;

            case MessageConvention.updateActorAnimation:
                messageInfo = SerializeHelper.ConvertToString(xieyi.MessageContent);
                ActorNetAnimation getNetAnimation = new ActorNetAnimation();
                getNetAnimation.SetSendInfo(messageInfo);
                //if (GameManager.instance.memberGroup.ContainsKey(getNetAnimation.userIndex))
                //{
                //    if (GameManager.instance.memberGroup[getNetAnimation.userIndex] != null)
                //    {
                //        //此处需要修改
                //        //GameManager.instance.memberGroup[getNetAnimation.userIndex].NetAnimation = getNetAnimation;
                //    }
                //    //else if (getNetAnimation.userIndex == DataController.instance.myRoomInfo.MyLocateIndex)//服务器给我设置了
                //    //{
                //    //    MyController.instance.InitNetSaveInfo(null, null, getNetAnimation);
                //    //}
                //}
                break;

            case MessageConvention.updateActorState:
                messageInfo = SerializeHelper.ConvertToString(tempMessageContent);
                roomActorUpdate.SetSendInfo(messageInfo);
                //Debug.Log("更新用户->" + roomActorUpdate.userIndex + " 状态为:" + (RoomActorState)int.Parse(roomActorUpdate.update));
                lock (DataController.instance.ActorList)
                {
                    DataController.instance.ActorList[roomActorUpdate.userIndex].CurState = (RoomActorState)int.Parse(roomActorUpdate.update);
                }
                break;

            case MessageConvention.prepareLocalModel:
                messageInfo = SerializeHelper.ConvertToString(tempMessageContent);
                roomActorUpdate.SetSendInfo(messageInfo);
                break;

            case MessageConvention.updateModelInfo:

                break;

            case MessageConvention.getPreGameData:
                //Debug.Log("getPreGameData已收到。");
                break;

            case MessageConvention.startGaming:
                string time = SerializeHelper.ConvertToString(tempMessageContent);
                Debug.Log("开始游戏时间:" + time);
                startGamTime = DateTime.Parse(time);
                break;

            case MessageConvention.shootBullet:
                break;

            case MessageConvention.bulletInfo:
                break;

            case MessageConvention.endGaming:
                messageInfo = SerializeHelper.ConvertToString(tempMessageContent);
                Debug.Log("胜利队伍是:" + (TeamType)int.Parse(messageInfo));
                break;

            case MessageConvention.moveDirection:    //GameManager中处理帧同步相应协议

                break;

            case MessageConvention.frameData:

                break;

            default:
                Debug.LogError("没有协议:" + xieyi.XieYiFirstFlag + "/MesageLength:" + xieyi.MessageContentLength);
                break;
            }

            //在数据处理后再执行委托响应脚本
            lock (allHandle)
            {
                if (allHandle.ContainsKey((MessageConvention)xieyi.XieYiFirstFlag))
                {
                    allHandle[(MessageConvention)xieyi.XieYiFirstFlag](xieyi);
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError("处理协议错误:" + e.Message + "/协议:" + (MessageConvention)xieyi.XieYiFirstFlag);
        }
    }
Exemplo n.º 30
0
        private void ReceiveMessages()
        {
            strReader = new StreamReader(tcpClient.GetStream());
            string numCardsInSet = "0";

            // While we are successfully connected, read incoming lines from the server
            while (isConnectedToServer)
            {
                string   serverResponse = strReader.ReadLine();
                string[] data           = serverResponse.Split(';');


                if (data[0].Equals("AVALIABLE_NICK"))
                {
                    // Console.WriteLine("Test = nick was avaliable. OK");
                }
                if (data[0].Equals("LOGIN_FAILED"))
                {
                    string message = data[1];
                    //ZMIENIC NA CONNECT
                    _viewConnect.ShowInformation(message, "Login failed");
                    _viewConnect.Hide();


                    Connect con = new Connect();
                    con.Visible = false;

                    MenuAfterLogin cojg = new MenuAfterLogin();
                    cojg.Visible = false;

                    Game game = new Game();
                    game.Visible = false;

                    CreateRoom createRoom = new CreateRoom();
                    createRoom.Visible = false;

                    JoinRoom joinRoom = new JoinRoom();
                    joinRoom.Visible = false;

                    Ranking ranking = new Ranking();
                    ranking.Visible = false;


                    ConnectController controller = new ConnectController(con, cojg, createRoom, joinRoom, ranking, game);


                    controller.LoadViewConnect(con);

                    con.ShowDialog();
                }

                if (data[0].Equals("WRONG_NICK"))
                {
                    string message = data[1];
                    _viewGame.ShowInformation(message, "Wrong nick");


                    Connect        con  = new Connect();
                    MenuAfterLogin cojg = new MenuAfterLogin();
                    Game           game = new Game();

                    CreateRoom createRoom = new CreateRoom();

                    JoinRoom joinRoom = new JoinRoom();

                    Ranking ranking = new Ranking();


                    ConnectController controller = new ConnectController(con, cojg, createRoom, joinRoom, ranking, game);
                    controller.LoadViewConnect(con);
                    con.ShowDialog();
                    _viewConnect.Hide();
                    Console.WriteLine("od nowa");
                    _viewGame.ShowInformation(message, "Wrong nick");

                    _viewConnect.SetClientMessage("[Log]:" + message);
                }



                if (data[0].Equals("INCOMING_MSG"))
                {
                    string source  = data[1];
                    string message = data[2];
                    _viewGame.SetClientMessage(source + ": " + message);
                }
                if (data[0].Equals("INCOMING_NUM_OF_PLAYERS"))
                {
                    string message = data[1];
                }
                if (data[0].Equals("INCOMING_SYMBOLS_NAMES"))
                {
                    string message = data[1];
                    cards.PathToImages = message;
                }


                if (data[0].Equals("ROOM_FOUND"))
                {
                    string message = data[1];
                    _viewGame.ShowInformation(message, "Room found");

                    _viewGame.SetClientMessage("[Log]:" + message);
                }

                if (data[0].Equals("ROOM_NOT_FOUND"))
                {
                    string message = data[1];
                    _viewGame.ShowInformation(message, "Room not found");
                }

                if (data[0].Equals("ROOM_FULL"))
                {
                    string message = data[1];
                    _viewGame.ShowInformation(message, "Room full");
                }


                if (data[0].Equals("START_GAME"))
                {
                    string message = data[1];

                    _viewGame.ShowInformation(message, "Start game!");


                    _viewGame.SetClientMessage("[Log]:" + message);
                }
                if (data[0].Equals("WAITING"))
                {
                    string message = data[1];
                    _viewGame.ShowInformation(message, "Waiting...");

                    _viewGame.SetClientMessage("[Log]:" + message);
                }

                if (data[0].Equals("MAIN_CARD"))
                {
                    if (data.Length == 9)
                    {
                        mainCard8(data);
                    }
                    if (data.Length == 7)
                    {
                        mainCard6(data);
                    }
                }


                if (data[0].Equals("PLAYER_CARD"))
                {
                    if (data.Length == 9)
                    {
                        symbols8(data);
                    }
                    if (data.Length == 7)
                    {
                        symbols6(data);
                    }
                }
                if (data[0].Equals("NUM_CARDS_IN_SET"))
                {
                    string message = data[1];
                    numCardsInSet = message;
                }


                if (data[0].Equals("NUM_CURRENT_CARD"))
                {
                    string message = data[1];
                    string text    = message + "/" + numCardsInSet;
                    _viewGame.NumCurrentCard(text);
                }

                if (data[0].Equals("LAST_NICK"))
                {
                    string message = data[1];
                    _viewGame.LastNick(message);
                }

                if (data[0].Equals("BAN"))
                {
                    string message = data[1];
                    _viewGame.ShowInformation(message, "Ban!");
                    _viewGame.SetClientMessage(message);
                    _viewGame.Ban();
                }
                if (data[0].Equals("UNBAN"))
                {
                    string message = data[1];
                    _viewGame.ShowInformation(message, "Unban");
                    _viewGame.SetClientMessage(message);
                    _viewGame.Unban();
                }
                if (data[0].Equals("WIN"))
                {
                    string message = data[1];
                    _viewGame.ShowInformation(message, "Win!");

                    _viewGame.SetClientMessage(message);
                    _viewGame.Win();
                }


                if (data[0].Equals("ROOM_LIST"))
                {
                    string message = data[1] + data[2];
                    _viewJoinRoom.RoomList(message);
                }

                if (data[0].Equals("STATUS_CLEAR"))
                {
                    string nick   = "Nick";
                    string status = "Status";
                    int    a      = 150;
                    int    b      = 56;

                    _viewGame.StatusClear(nick, status, a, b);
                }

                if (data[0].Equals("ROOM_CLEAR"))
                {
                    _viewJoinRoom.Clear();
                }

                if (data[0].Equals("STATUS_PLAYERS"))
                {
                    string col1 = data[1];
                    string col2 = data[2] + "/" + data[3];
                    _viewGame.StatusPlayers(col1, col2);
                }
                if (data[0].Equals("RANKING_ROW"))
                {
                    string col1 = data[1];
                    string col2 = data[2];
                    string col3 = data[3];

                    _viewRanking.AddRowRanking(col1, col2, col3);
                }

                if (data[0].Equals("RANKING_ROW_LOWER"))
                {
                    string col1 = data[1];
                    string col2 = data[2];
                    string col3 = data[3];

                    _viewRanking.AddRowRankingLower(col1, col2, col3);
                }



                _viewGame.AutoscrollingList();
            }
        }
Exemplo n.º 31
0
 public async Task Post([FromBody] JoinRoom command)
 {
     await DispatchAsync(command);
 }
Exemplo n.º 32
0
        private void Server_ObjectReceived(object sender, AdvancedNetworkLib.ObjectReceivedEventArgs e)
        {
            AdvancedNetworkLib.Client client   = (sender as AdvancedNetworkLib.Client);
            ClientUserData            userData = client.UserData as ClientUserData;
            RoomInfo roomInfo = this.rooms.Find(c => c.Name == userData?.RoomName);

            var obj = e.Object;

            if (obj is ServerPassword)
            {
                ServerPassword serverPassword = obj as ServerPassword;
                this.checkServerPassword(client, serverPassword);
            }
            else if (obj is ChangeState)
            {
                var         oldState    = userData.State;
                ChangeState changeState = obj as ChangeState;
                userData.State = changeState.State;

                if (userData.State == State.RoomChoice)
                {
                    userData.PlayerName = string.Empty;
                    userData.RoomName   = string.Empty;
                    userData.Password   = 0;
                    userData.IsDrawing  = false;
                    userData.Points     = 0;
                    userData.Host       = false;

                    // if player was in lobby
                    if (oldState == State.Lobby || oldState == State.LobbyReady)
                    {
                        this.sendLobbyListToAll(roomInfo);
                    }

                    // if player was in game
                    if (oldState == State.Game)
                    {
                        // check if only one player is left in game
                        var playersInGame = this.getPlayersInGame(roomInfo);
                        if (playersInGame.Count() == 1)
                        {
                            // kick last player in game
                            playersInGame.First().send(new KickedNoMorePlayer());
                        }
                        else if (playersInGame.Count() > 1)
                        {
                            // update ranklist for players in game
                            this.sendRankListToAll(roomInfo);
                        }
                    }

                    // update and send roomlist
                    this.sendRoomListToAll();
                }
                else if (userData.State == State.RoomCreation)
                {
                    string randomRoomName = string.Empty;

                    // generate random room name
                    // TODO: better performance when checking host boolean first
                    int i = 1000;
                    while (Server.Clients.Count(c => (c.UserData as ClientUserData).RoomName == (randomRoomName = $"Room{Server.rand.Next(0, 999).ToString().PadLeft(3, '0')}") && (c.UserData as ClientUserData).Host) > 0 && i-- > 0)
                    {
                    }

                    client.send(new RandomRoomName {
                        Name = randomRoomName
                    });
                }
                else if (userData.State == State.LobbyReady || userData.State == State.Lobby)
                {
                    if (userData.PlayerName == string.Empty)
                    {
                        string randomPlayerName = string.Empty;

                        // generate random room name

                        var players = this.getPlayers(roomInfo);
                        while (players.Any(p =>
                        {
                            return((p.UserData as ClientUserData).PlayerName == (randomPlayerName = $"Player{Server.rand.Next(0, 999).ToString().PadLeft(3, '0')}"));
                        }))
                        {
                        }

                        userData.PlayerName = randomPlayerName;

                        client.send(new RandomPlayerName {
                            Name = randomPlayerName
                        });

                        // update and send lobbylist
                        this.sendLobbyListToAll(roomInfo);
                    }
                    else
                    {
                        string newPlayerName = changeState.Data as string;

                        // check if any player has already the same name
                        int playerWithSameName = Server.Clients.Count(c => c.UserData != null && c != client && (c.UserData as ClientUserData).RoomName == userData.RoomName && (c.UserData as ClientUserData).PlayerName == newPlayerName);

                        if (playerWithSameName > 0)
                        {
                            client.send(new Error {
                                Job = Job.NameChange
                            });
                        }
                        else
                        {
                            // name is free and will be used
                            userData.PlayerName = newPlayerName;

                            if (userData.Host)
                            {
                                client.send(new Success {
                                    Job = Job.NameChange
                                });
                            }
                            else
                            {
                                bool hostIsPlaying = Server.Clients.Count(c => c.UserData != null && (c.UserData as ClientUserData).RoomName == userData.RoomName && (c.UserData as ClientUserData).Host && (c.UserData as ClientUserData).State == State.Game) > 0;

                                client.send(new Success {
                                    Job = hostIsPlaying ? Job.GameStart : Job.NameChange
                                });
                            }

                            // update and send lobbylist
                            this.sendLobbyListToAll(roomInfo);
                        }
                    }

                    // update and send roomlist
                    this.sendRoomListToAll();
                }
                else if (userData.State == State.Game)
                {
                    if (userData.Host)
                    {
                        // send ranklist
                        this.sendRankListToAll(roomInfo);

                        // tell other players that the game starts
                        var players = this.getPlayersInLobbyAndReady(roomInfo);
                        this.sendObjectToPlayers(players, new StartGame());
                    }
                    else
                    {
                        // check if player joins later
                        if (this.rooms.Exists(c => c.Name == userData.RoomName && c.Started))
                        {
                            // this player joins later
                            // send ranklist
                            this.sendRankListToAll(roomInfo);

                            // get current drawer and send drawing request
                            var currentDrawer = this.getCurrentDrawer(roomInfo);
                            if (currentDrawer != null)
                            {
                                currentDrawer.send(new DrawingRequest());
                            }
                        }
                        else
                        {
                            // count players in lobby
                            var playersInLobbyCount = this.getPlayersInLobbyAndReady(roomInfo).Count();

                            // start game when all players are in the game
                            if (playersInLobbyCount == 0)
                            {
                                // start game for the first time
                                roomInfo.Started = true;

                                // start first round
                                this.startRound(roomInfo);
                            }
                        }
                    }

                    this.sendRoomListToAll();
                }

                this.updateCountLabels();
            }
            else if (obj is CreateRoom)
            {
                CreateRoom createRoom = obj as CreateRoom;
                this.createRoom(client, createRoom);
            }
            else if (obj is JoinRoom)
            {
                JoinRoom joinRoom = obj as JoinRoom;
                this.joinRoom(client, joinRoom);
            }
            else if (obj is StartGame)
            {
                int playerCount      = this.getPlayers(roomInfo).Count();
                int playerCountReady = this.getPlayersInLobbyAndReady(roomInfo).Count();
                if (playerCount != playerCountReady || playerCount < 2)
                {
                    client.send(new Error {
                        Job = Job.GameStart
                    });
                }
                else
                {
                    client.send(new Success {
                        Job = Job.GameStart
                    });
                }
            }
            else if (obj is ChatMessage)
            {
                var chatMessage = obj as ChatMessage;
                chatMessage.PlayerName = userData.PlayerName;

                // get all clients in the same room and that are playing
                var players = this.getPlayersInGame(roomInfo);

                // check if entered word is equal to searched word
                bool foundWord = (roomInfo.CurrentWord.ToLower() == chatMessage.Text.ToLower());

                if (foundWord && (roomInfo.RoundInfo.PlayerTimes.ContainsKey(userData.PlayerName) || userData.IsDrawing))
                {
                    client.send(new WhatDoYouWantInfo());
                }
                else
                {
                    var foundWordInfo = foundWord ? new FoundWordInfo {
                        PlayerName = userData.PlayerName
                    } : null;

                    if (foundWord)
                    {
                        // give points
                        roomInfo.RoundInfo.PlayerTimes.Add(userData.PlayerName, 500 * ((players.Count() - 1) - roomInfo.RoundInfo.PlayerTimes.Count));
                    }

                    foreach (var player in players)
                    {
                        if (foundWord)
                        {
                            player.send(foundWordInfo);
                        }
                        else
                        {
                            player.send(chatMessage);
                        }
                    }

                    // check if this is the last player that found the word
                    if (foundWord && roomInfo.RoundInfo.PlayerTimes.Count == players.Count() - 1)
                    {
                        // end round
                        roomInfo.RoundInfo.WordUpdateTimer.Stop();

                        // send revealed word
                        string revealedWord    = string.Join(" ", roomInfo.CurrentWord);
                        var    choosedWordInfo = new ChoosedWordInfo {
                            Word = revealedWord
                        };

                        this.sendObjectToPlayers(players, choosedWordInfo);

                        this.nextDrawer(roomInfo);
                    }
                }
            }
            else if (obj is Drawing)
            {
                // get every player in the same room, except drawer
                var players = this.getPlayersInGameExceptDrawer(roomInfo);
                this.sendObjectToPlayers(players, obj);
            }
            else if (obj is ChoosedWord)
            {
                var choosenWord = obj as ChoosedWord;

                roomInfo.CurrentWord = choosenWord.Word;
                roomInfo.CurrentWordRevealed.Clear();

                // store choosen word to list with choosen words => solution is a bit ugly
                roomInfo.ChoosenWordIndices.Add(this.wordList.IndexOf(this.wordList.First(w => w.Word == choosenWord.Word)));

                var timer = roomInfo.RoundInfo.WordUpdateTimer = new Timer();
                timer.Interval = (int)((this.roundDuration * 1000.0) / choosenWord.Word.Length);
                timer.Tick    += (s2, e2) => this.revealCharOfWord(s2, roomInfo);
                this.revealCharOfWord(timer, roomInfo);
                timer.Start();
            }
            else if (obj is KickedByHost)
            {
                var playerName = (obj as KickedByHost).PlayerName;
                var player     = this.getPlayerByName(playerName);
                player?.send(obj);
            }
        }