public ScriptRoom(RoomInfo roomInfo) : base(roomInfo) { Commands = new Dictionary<string, CommandHandler>(); _sourceFile = roomInfo["Script"]; _host = new ScriptHost(this); _timer = Stopwatch.StartNew(); _references = new List<string>(); _references.AddRange((roomInfo["References"] ?? "").Split(',')); if (Util.IsRunningOnMono()) { _references.AddRange(new List<string> { "System", "System.Collections.Generic", "System.Linq", "System.Text" }); } _references.AddRange(new List<string> { "log4net", "Newtonsoft.Json", "Npgsql", "SteamKit2", "EzSteam" }); _references = _references.Distinct().ToList(); Recompile(); }
/// <summary> /// Gets all the info from the room (ie. players, map, ect..) /// </summary> /// <param name="rn"></param> /// <param name="mn"></param> /// <param name="p"></param> /// <param name="mType"></param> public void GetInfo(RoomInfo roomInfo) { globalRoomInfo = roomInfo; //Receive the map and mode data from the rooms custom properties string map = (string)roomInfo.customProperties[ RoomProperty.Map ]; Gamemode mode = (Gamemode)( (int)roomInfo.customProperties[ RoomProperty.Mode ] ); RoomNameUI.text = roomInfo.name.ToString() + "["+ mode.ToString() + "]"; MapNameUI.text = map.ToString(); MaxPlayerUI.text = mode.ToString(); if (roomInfo.playerCount >= roomInfo.maxPlayers) { ButtonText.text = "Full"; StatusImg.color = FullColor; } else { ButtonText.text = "Join"; StatusImg.color = AvailableColor; } }
public SteamRoom(RoomInfo roomInfo) : base(roomInfo) { _lastMessage = Stopwatch.StartNew(); SteamId = new SteamID(ulong.Parse(RoomInfo["SteamId"])); EchoWebStates = (RoomInfo["EchoWebStates"] ?? "true").ToLower() == "true"; }
void OnConnectionCompleted(RoomInfo[] rooms) { loadingScreen.SetActive(false); modeSelectScreen.SetActive(true); photonConnected = true; Debug.Log("connected to photon"); }
/// <summary> /// Gets the room info. /// </summary> /// <returns>The room info.</returns> /// <param name="info">Info.</param> public string[] GetRoomInfo( RoomInfo info ) { string[] s = new string[4]; s[0] = info.name; s[1] = info.playerCount.ToString(); s[2] = info.maxPlayers.ToString(); s[3] = ( info.customProperties["index"] ).ToString(); return s; }
public void ShowRoom(RoomInfo[] roomInfo) { this.roomInfo = roomInfo; for (int i = 0; i < roomInfo.Length; i++) { rooms[i].SetActive(true); roomName[i].text = roomInfo[i].name; } }
private void DoJoinRoom(RoomInfo room) { //mSelectedLevelName = room.name; mSelectedLevelName = room.customProperties["levelName"].ToString(); Debug.Log("calling JoinRoom"); PhotonNetwork.JoinRoom(room.name); Debug.Log("called JoinRoom"); mMenuState = MenuState.ConnectingToRoom; }
void Start() { RoomListGUI rlg = (RoomListGUI) HospitalPrefabs.ScriptsObject.GetComponent<RoomListGUI>(); roomInfo = rlg.GetRoomInfo(ID); cost_label = (UILabel)transform.FindChild("Cost_Cell_Label").GetComponent<UILabel>(); cost_label.text = roomInfo.cost.ToString(); title = (UILabel)transform.FindChild("title").GetComponent<UILabel>(); title.text = roomInfo.title; }
public override int ReadFrom(byte[] Buffer, int StartIndex = 0) { int cursor = StartIndex; cursor += base.ReadFrom(Buffer, cursor); RoomInfo = new RoomInfo(Buffer, cursor); cursor += RoomInfo.ByteLength; return cursor - StartIndex; }
//public float volume { get { return m_volume ?? (m_volume = PlayerPrefs.GetFloat("volume", 600)).Value; } set { PlayerPrefs.SetFloat("volume", (m_volume = value).Value); } } //public float? m_volume; //public float musicVolume { get { return m_musicVolume ?? (m_musicVolume = PlayerPrefs.GetFloat("musicVolume", 600)).Value; } set { PlayerPrefs.SetFloat("musicVolume", (m_musicVolume = value).Value); } } //public float? m_musicVolume; public void RoomInfo(RoomInfo rom) { StringBuilder sb = new StringBuilder(); sb.AppendLine(room.name); sb.AppendLine("Players".PadRight(20) + room.playerCount + "/" + room.maxPlayers); foreach (var a in rom.customProperties) { var value = (ReferenceEquals(a.Key, "gameType") ? ((GameTypeEnum)a.Value) : a.Value); sb.AppendLine(a.Key.ToString().PadRight(20) + value); } gui.Label(sb.ToString(), skin.label); }
public void GetInfo(RoomInfo info) { cacheInfo = info; RoomNameText.text = info.name; MapNameText.text = (string)info.customProperties[PropiertiesKeys.SceneNameKey]; GameModeText.text = (string)info.customProperties[PropiertiesKeys.GameModeKey]; PlayersText.text = info.playerCount + "/" + info.maxPlayers; PingText.text = PhotonNetwork.GetPing().ToString(); bool _active = (info.playerCount < info.maxPlayers) ? true : false; JoinButton.SetActive(_active); FullText.SetActive(!_active); }
//Refreshes list of servers public void RefreshRoomList(RoomInfo[] roomList) { ClearServerList (); foreach (RoomInfo room in roomList) { GameObject instance = GameObject.Instantiate (serverInfoObject) as GameObject; instance.transform.SetParent (this.transform, false); Image serverPanel = instance.GetComponent<Image> (); serverPanel.rectTransform.anchoredPosition = new Vector2(0, -15 - serverCount*15); ServerInfo serverInfo = serverPanel.GetComponent<ServerInfo> (); serverInfo.Init(room.name, room.customProperties["map"].ToString (), room.playerCount, room.maxPlayers); serverList.Add (instance); ++serverCount; } }
/// <summary> /// /// </summary> /// <param name="rn"></param> /// <param name="mn"></param> /// <param name="p"></param> /// <param name="mType"></param> public void GetInfo(RoomInfo r) { m_Room = r; RoomNameUI.text = r.name; MapNameUI.text = r.RoomScene(); MaxPlayerUI.text = r.playerCount + " / " + r.maxPlayers; bool b = r.GetRoomState(); TypeUI.text = (b == true) ? "Playing" : "Waiting"; if (r.playerCount >= r.maxPlayers) { ButtonText.text = "Full"; StatusImg.color = FullColor; } else { ButtonText.text = "Join"; StatusImg.color = AvailableColor; } }
public void roomListCallback(RoomInfo[] roomInfos) { if (buttons != null) { for (int i = 0; i < buttons.Length; i++) { Destroy (buttons [i]); } } buttons = new GameObject[roomInfos.Length]; for (int i = 0; i < roomInfos.Length; i++) { if (roomInfos [i].playerCount < roomInfos[i].maxPlayers && roomInfos[i].open) { buttons [i] = (GameObject)Instantiate (Resources.Load ("GameListItem")); buttons [i].transform.Find ("Text").gameObject.GetComponent<Text> ().text = roomInfos [i].name + "(" + roomInfos [i].playerCount + "/" + roomInfos [i].maxPlayers + ")"; buttons [i].transform.SetParent (content); int itemp = i; buttons [i].GetComponent<Button> ().onClick.AddListener (delegate { buttonClicked (itemp); }); } } contentRect = content.GetComponent<RectTransform> (); }
/// <summary> /// Join room by room.Name. /// This fails if the room is either full or no longer available (might close at the same time). /// </summary> /// <param name="roomName">The room instance to join (only listedRoom.Name is used).</param> public static void JoinRoom(RoomInfo listedRoom) { if (listedRoom == null) { Debug.LogError("JoinRoom aborted: you passed a NULL room"); return; } JoinRoom(listedRoom.name); }
public void SetRoomInfo(RoomInfo val) { roomInfo = val; }
public void JoinRoom(RoomInfo game) { PhotonNetwork.JoinRoom (game.name); }
public void SetRoomInfo(RoomInfo roomInfo) { RoomInfo = roomInfo; _text.text = roomInfo.MaxPlayers + "," + roomInfo.Name; }
private void ReadRoomsXml(XmlReader reader) { reader.ReadStartElement(); // read start of "Rooms" element if (!reader.EOF && string.Equals("RoomInfo", reader.Name)) { // read an arbitrary number of "RoomInfo" nodes while (!reader.EOF && string.Equals("RoomInfo", reader.Name)) { reader.ReadStartElement(); string name = reader.ReadElementContentAsString("Name", ""); int id = reader.ReadElementContentAsInt("Id", ""); int lastMsgId = reader.ReadElementContentAsInt("LastMessageId", ""); RoomInfo r = new RoomInfo(name, id, lastMsgId); this.rooms.Add(r); reader.ReadEndElement(); } reader.ReadEndElement(); // read end of "Rooms" element } }
private void ReplaceRoom(RoomInfo old, string name, int lastMessageId) { // to maintain the read-only semantics of RoomInfo... can't modify it. Must delete old, and add new. if (this.rooms.Remove(old)) { RoomInfo newRoom = new RoomInfo(name, old.Id, lastMessageId); this.rooms.Add(newRoom); } else { throw new ApplicationException("oops"); } }
/** * ルームリスト取得レスポンスの受信 * * @param pResponseInfo レスポンス情報 */ protected void RecvResponse_GetRoomList( web.WebApiAgent.HttpResponseInfo pResponseInfo ) { Logger.MLNLOG_DEBUG( "code="+ pResponseInfo.code +" str="+ pResponseInfo.str ); if ( 200 != pResponseInfo.code ) return; LitJson.JsonData jsonData = LitJson.JsonMapper.ToObject( pResponseInfo.str ); do{ Logger.MLNLOG_DEBUG( "pu_num="+ jsonData[ "data" ][ "pu_num" ] ); Logger.MLNLOG_DEBUG( "room_hub_pu_high_list="+ jsonData[ "data" ][ "room_hub_pu_high_list" ] ); Logger.MLNLOG_DEBUG( "room_hub_pu_low_list="+ jsonData[ "data" ][ "room_hub_pu_low_list" ] ); Logger.MLNLOG_DEBUG( "battle_pu_high_list="+ jsonData[ "data" ][ "battle_pu_high_list" ] ); Logger.MLNLOG_DEBUG( "battle_pu_low_list="+ jsonData[ "data" ][ "battle_pu_low_list" ] ); Logger.MLNLOG_DEBUG( "ip_addr_list="+ jsonData[ "data" ][ "ip_addr_list" ] ); Logger.MLNLOG_DEBUG( "port_list="+ jsonData[ "data" ][ "port_list" ] ); Logger.MLNLOG_DEBUG( "entered_num_list="+ jsonData[ "data" ][ "entered_num_list" ] ); Logger.MLNLOG_DEBUG( "max_enter_num_list="+ jsonData[ "data" ][ "max_enter_num_list" ] ); Logger.MLNLOG_DEBUG( "status_list="+ jsonData[ "data" ][ "status_list" ] ); Int32 pu_num = Convert.ToInt32( (string)jsonData[ "data" ][ "pu_num" ] ); if ( 0 == pu_num ) break; char delimiter = ','; string[] roomHubPuHighList = ((string)jsonData[ "data" ][ "room_hub_pu_high_list" ]).Split ( delimiter ); string[] roomHubPuLowList = ((string)jsonData[ "data" ][ "room_hub_pu_low_list" ]).Split ( delimiter ); string[] battlePuHighList = ((string)jsonData[ "data" ][ "battle_pu_high_list" ]).Split ( delimiter ); string[] battlePuLowList = ((string)jsonData[ "data" ][ "battle_pu_low_list" ]).Split ( delimiter ); string[] ipAddrList = ((string)jsonData[ "data" ][ "ip_addr_list" ]).Split ( delimiter ); string[] portList = ((string)jsonData[ "data" ][ "port_list" ]).Split ( delimiter ); string[] enteredNumList = ((string)jsonData[ "data" ][ "entered_num_list" ]).Split ( delimiter ); string[] maxEnterNumList = ((string)jsonData[ "data" ][ "max_enter_num_list" ]).Split ( delimiter ); string[] statusList = ((string)jsonData[ "data" ][ "status_list" ]).Split ( delimiter ); List<RoomInfo> roomInfoList = new List<RoomInfo>(); for ( Int32 i = 0; i < pu_num; ++i ){ UInt64 puUid; RoomInfo info = new RoomInfo(); puUid = Convert.ToUInt64( roomHubPuHighList[ i ] ) << 32; puUid += Convert.ToUInt32( roomHubPuLowList[ i ] ); info.roomHubPuUid = puUid; puUid = Convert.ToUInt64( battlePuHighList[ i ] ) << 32; puUid += Convert.ToUInt32( battlePuLowList[ i ] ); info.battlePuUid = puUid; info.ipAddr = ipAddrList[ i ]; info.port = Convert.ToUInt16( portList[ i ] ); info.entered_num = Convert.ToByte( enteredNumList[ i ] ); info.max_enter_num = Convert.ToByte( maxEnterNumList[ i ] ); info.status = Convert.ToByte( statusList[ i ] ); roomInfoList.Add( info ); DebugManager.Instance.Log( "["+ i +"] "+ info.ipAddr +":"+ info.port +" 0x"+ Utility.ToHex( info.battlePuUid ) +" "+ info.entered_num +"/"+ info.max_enter_num +" "+ info.status ); } DebugManager.Instance.Log ( "RoomListNum="+ pu_num ); // TODO 本来はユーザーが任意のルームを選択する必要があるが、 // ひとまずランダムで選択したルームに入室しておく Int32 roomIndex = (Int32)m_pRandom.Next( pu_num ); m_pPU.SetRoomHubPU_PUUID( roomInfoList[ roomIndex ].roomHubPuUid ); if ( m_pPU.ConnectServer( roomInfoList[ roomIndex ].ipAddr, roomInfoList[ roomIndex ].port, roomInfoList[ roomIndex ].battlePuUid ) ){ SetPhase( PHASE.PHASE_BATTLE_ENTER_ROOM, Utility.GetSecond() + WAIT_TIME_CHANGE_PHASE ); DebugManager.Instance.Log ( "m_CharaId=0x"+ mln.Utility.ToHex( m_CharaId ) ); DebugManager.Instance.Log( "Choice ["+ roomIndex +"] "+ roomInfoList[ roomIndex ].ipAddr +":"+ roomInfoList[ roomIndex ].port +" 0x"+ Utility.ToHex( roomInfoList[ roomIndex ].battlePuUid ) + " "+ roomInfoList[ roomIndex ].entered_num +"/"+ roomInfoList[ roomIndex ].max_enter_num +" "+ roomInfoList[ roomIndex ].status ); } }while ( false ); }
public ConnectionResponse(RoomInfo activeRoom) { ActiveRoom = activeRoom; }
void SearchRoomResponse(int roomNum, RoomInfo[] rooms) { m_rooms.Clear(); for (int i = 0; i < roomNum; ++i) { RoomContent r = new RoomContent(); r.roomId = rooms[i].roomId; r.roomName = rooms[i].name; r.members[0] = rooms[i].members; m_rooms.Add(rooms[i].roomId, r); string str = "Room name[" + i + "]:" + rooms[i].name + " [id:" + rooms[i].roomId + ":" + rooms[i].members +"]"; Debug.Log(str); } }
public void SetRoomInfo(RoomInfo info) { _roomInfo = info; _textName.text = $"{_roomInfo.Name} - {_roomInfo.PlayerCount}/{_roomInfo.MaxPlayers} "; }
protected void bt_Save_Click(object sender, EventArgs e) { lb_Error.Text = ""; if (!string.IsNullOrEmpty(tb_RoomCode.Text.Trim())) { CY.GFive.Core.Business.RoomInfo ri = CY.GFive.Core.Business.RoomInfo.GetByCode(tb_RoomCode.Text.Trim()); if (ri != null) { lb_Error.Text = "已存在本编号的寝室!"; return; } } if (!string.IsNullOrEmpty(tb_BuildingCode.Text.Trim()) && !string.IsNullOrEmpty(tb_RoomNum.Text.Trim())) { CY.GFive.Core.Business.RoomInfo checkri = CY.GFive.Core.Business.RoomInfo.GetByBuildAndNo(tb_BuildingCode.Text.Trim(), tb_RoomNum.Text.Trim()); if (checkri != null) { lb_Error.Text = "本楼已存在相同寝室号的寝室"; return; } } try { RoomInfo ri = new RoomInfo(); ri.RoomCode = tb_RoomCode.Text; ri.BuildingCode = tb_BuildingCode.Text; ri.RoomNum = tb_RoomNum.Text; ri.TotalNum = Convert.ToInt32(tb_TotalNum.Text); //ri.ExistNum = Convert.ToInt32(tb_ExistNum.Text); ri.RoomState = ddlRoomState.SelectedValue; ri.Save(); lb_Error.Text = "添加成功"; tb_BuildingCode.Text = ""; tb_RoomCode.Text = ""; tb_RoomNum.Text = ""; tb_TotalNum.Text = ""; tb_ExistNum.Text = ""; } catch (Exception ex) { lb_Error.Text = "错误信息:" + ex.Message; tb_BuildingCode.Text = ""; tb_RoomCode.Text = ""; tb_RoomNum.Text = ""; tb_TotalNum.Text = ""; tb_ExistNum.Text = ""; } }
private static void createRoomPlayer12(HostManager host, out RoomPlayerInfo playerInfo1, out RoomPlayerInfo playerInfo2, out RoomInfo roomInfo) { playerInfo1 = new RoomPlayerInfo() { name = "测试名字1" }; playerInfo2 = new RoomPlayerInfo() { name = "测试名字2" }; playerInfo2.PlayerID = playerInfo1.PlayerID + 1; roomInfo = new RoomInfo() { ip = "127.0.0.1", port = host.port, OwnerID = playerInfo1.PlayerID }; }
public void OnStart(RoomInfo room){ string name = room.ToString(); lock(Rooms){ GameConfig config = Rooms[name]; if(config != null){ config.IsStart = true; } } BeginInvoke(new Action( ()=>{ lock(_lock) StartRoom(name); }) ); }
public void UpdateRoom(RoomInfo newRoomInfo) { OneRoomGroup oneGroup = _roomGroups[newRoomInfo.GameKey]; UpdateOneGroup(oneGroup, newRoomInfo.RoomId, newRoomInfo.UserCount); }
public void ShowHostRoomWindow() { //_Loader.ResetSettings(); hostRoom = new RoomInfo(bs._Loader.playerName + "'s room", null); Download("scripts/getMaps.php", delegate (WWW w) { var maps = LitJson.JsonMapper.ToObject<MapStat[]>(w.text); bs.settings.maps = maps.ToList(); //foreach (var map in maps) // if (!bs.settings.maps.Any(a => a.mapName == map.mapName)) // bs.settings.maps.Add(map); room.sets.mapStats = bs.settings.maps[0]; }); ShowWindow(HostRoomWindow); }
void connect(RoomInfo r) { OnEnable(); PhotonNetwork.JoinRoom(r.name); }
public bool JoinRoomCheckParam(string VersusHash, string playerJson, int lvRange, int floorRange, int lv, int floor) { if (this.mState != MyPhoton.MyState.LOBBY) { this.mError = MyPhoton.MyError.ILLEGAL_STATE; return(false); } string roomName = string.Empty; bool flag1 = false; PhotonNetwork.player.SetCustomProperties((Hashtable)null, (Hashtable)null, false); PhotonNetwork.SetPlayerCustomProperties((Hashtable)null); this.SetMyPlayerParam(playerJson); RoomInfo[] roomList = PhotonNetwork.GetRoomList(); List <RoomInfo> roomInfoList = new List <RoomInfo>(); foreach (RoomInfo roomInfo in roomList) { Hashtable customProperties = roomInfo.CustomProperties; if (((Dictionary <object, object>)customProperties).ContainsKey((object)"MatchType") && VersusHash == (string)customProperties.get_Item((object)"MatchType")) { roomInfoList.Add(roomInfo); } } if (lvRange != -1) { int num1 = lv - lvRange; int num2 = lv + lvRange; using (List <RoomInfo> .Enumerator enumerator = roomInfoList.GetEnumerator()) { while (enumerator.MoveNext()) { RoomInfo current = enumerator.Current; Hashtable customProperties = current.CustomProperties; if (((Dictionary <object, object>)customProperties).ContainsKey((object)"plv") && ((Dictionary <object, object>)customProperties).ContainsKey((object)nameof(floor))) { int num3 = (int)customProperties.get_Item((object)nameof(floor)); int num4 = (int)customProperties.get_Item((object)"plv"); if (num1 <= num4 && num4 <= num2 && num3 == floor) { roomName = current.Name; flag1 = true; break; } } } } } if (!flag1) { using (List <RoomInfo> .Enumerator enumerator = roomInfoList.GetEnumerator()) { while (enumerator.MoveNext()) { RoomInfo current = enumerator.Current; Hashtable customProperties = current.CustomProperties; if (((Dictionary <object, object>)customProperties).ContainsKey((object)nameof(floor)) && floor == (int)customProperties.get_Item((object)nameof(floor))) { roomName = current.Name; flag1 = true; break; } } } } if (floorRange != -1) { int num1 = floor - floorRange; int num2 = floor + floorRange; using (List <RoomInfo> .Enumerator enumerator = roomInfoList.GetEnumerator()) { while (enumerator.MoveNext()) { RoomInfo current = enumerator.Current; Hashtable customProperties = current.CustomProperties; if (((Dictionary <object, object>)customProperties).ContainsKey((object)nameof(floor))) { int num3 = (int)customProperties.get_Item((object)nameof(floor)); if (num1 <= num3 && num3 <= num2) { roomName = current.Name; flag1 = true; break; } } } } } bool flag2 = false; if (flag1) { flag2 = PhotonNetwork.JoinRoom(roomName); if (flag2) { this.mState = MyPhoton.MyState.JOINING; } else { this.mError = MyPhoton.MyError.UNKNOWN; } } return(flag2); }
public void JoinRoom(RoomInfo info) { PhotonNetwork.JoinRoom(info.Name); MenuManager.Instance.OpenMenu("Loading"); }
public IEnumerator joinRoomTest() { UnityLogger logger = new UnityLogger(); HostManager host = new GameObject(nameof(HostManager)).AddComponent <HostManager>(); host.logger = logger; host.start(); ClientManager client = new GameObject(nameof(ClientManager)).AddComponent <ClientManager>(); client.logger = logger; client.start(); RoomInfo room = new RoomInfo() { ip = "127.0.0.1", port = host.port, playerList = new List <RoomPlayerInfo>() }; Task task = client.joinRoom(room, new RoomPlayerInfo() { name = "测试名字" }); yield return(task.wait()); Assert.Null((task as Task <RoomInfo>).Result); host.openRoom(room); Assert.NotNull(host.room); client.findRoom(host.port); bool joinLock = false; client.onRoomFound += (r) => { if (!joinLock) { joinLock = true; room = r; } }; yield return(new WaitUntil(() => joinLock)); Assert.AreEqual(host.room.ip, room.ip); Assert.AreEqual(host.room.port, room.port); bool joinFlag = false; client.onJoinRoom += r => { if (!joinFlag) { joinFlag = true; } }; bool clientJoinFlag = false; host.onPlayerJoin += p => { if (!clientJoinFlag) { clientJoinFlag = true; } }; task = client.joinRoom(room, new RoomPlayerInfo() { name = "测试名字" }); yield return(task.wait()); Assert.True(joinFlag); Assert.True(clientJoinFlag); room = (task as Task <RoomInfo>).Result; Assert.AreEqual(1, room.playerList.Count); Assert.AreEqual("测试名字", room.playerList[0].name); }
public void SetRoomInfo(RoomInfo roomInfo) { RoomInfo = roomInfo; _text.text = $"{roomInfo.Name} [{roomInfo.MaxPlayers}]"; }
public IEnumerator checkRoomInfoTest() { UnityLogger logger = new UnityLogger(); HostManager host = new GameObject(nameof(HostManager) + "1").AddComponent <HostManager>(); host.logger = logger; host.start(); ClientManager client1 = new GameObject(nameof(ClientManager) + "1").AddComponent <ClientManager>(); client1.logger = logger; client1.start(); ClientManager client2 = new GameObject(nameof(ClientManager) + "2").AddComponent <ClientManager>(); client2.logger = logger; client2.start(); RoomPlayerInfo playerInfo1 = new RoomPlayerInfo() { name = "测试名字1" }; RoomPlayerInfo playerInfo2 = new RoomPlayerInfo() { name = "测试名字2" }; RoomInfo roomInfo = new RoomInfo() { ip = "127.0.0.1", port = host.port }; RoomInfo roomInfo2 = new RoomInfo() { ip = "127.0.0.1", port = host.port }; host.openRoom(roomInfo); yield return(new WaitForSeconds(0.5f)); bool roomFoundFlag = false; RoomInfo questRoomInfo = null; client1.onRoomFound += (info) => { if (!roomFoundFlag) { roomFoundFlag = true; questRoomInfo = info; } }; client1.findRoom(host.port); yield return(new WaitForSeconds(0.5f)); Assert.AreEqual(roomFoundFlag, true); var task = client1.checkRoomInfo(questRoomInfo); yield return(new WaitUntil(() => task.IsCompleted)); Assert.NotNull(task.Result); Assert.AreEqual(questRoomInfo.playerList.Count, task.Result.playerList.Count); Assert.AreEqual(questRoomInfo.ip, task.Result.ip); Assert.AreEqual(questRoomInfo.port, task.Result.port); yield return(new WaitForSeconds(0.5f)); var task2 = client2.joinRoom(roomInfo2, playerInfo2); yield return(new WaitUntil(() => task2.IsCompleted)); yield return(new WaitForSeconds(0.5f)); Assert.AreEqual(1, host.room.playerList.Count); task = client1.checkRoomInfo(questRoomInfo); yield return(new WaitUntil(() => task.IsCompleted)); Assert.NotNull(task.Result); Assert.AreEqual(1, task.Result.playerList.Count); Assert.AreEqual(playerInfo2.name, task.Result.playerList[0].name); host.closeRoom(); yield return(new WaitForSeconds(0.5f)); task = client1.checkRoomInfo(questRoomInfo); yield return(new WaitUntil(() => task.IsCompleted)); Assert.Null(task.Result); }
public void OnEvent(EventData photonEvent) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) Debug.Log(string.Format("OnEvent: {0}", photonEvent.ToString())); int actorNr = -1; PhotonPlayer originatingPlayer = null; if (photonEvent.Parameters.ContainsKey(ParameterCode.ActorNr)) { actorNr = (int)photonEvent[ParameterCode.ActorNr]; if (this.mActors.ContainsKey(actorNr)) { originatingPlayer = (PhotonPlayer)this.mActors[actorNr]; } //else //{ // // the actor sending this event is not in actorlist. this is usually no problem // if (photonEvent.Code != (byte)LiteOpCode.Join) // { // Debug.LogWarning("Received event, but we do not have this actor: " + actorNr); // } //} } switch (photonEvent.Code) { case EventCode.GameList: { this.mGameList = new Dictionary<string, RoomInfo>(); Hashtable games = (Hashtable)photonEvent[ParameterCode.GameList]; foreach (DictionaryEntry game in games) { string gameName = (string)game.Key; this.mGameList[gameName] = new RoomInfo(gameName, (Hashtable)game.Value); } mGameListCopy = new RoomInfo[mGameList.Count]; mGameList.Values.CopyTo(mGameListCopy, 0); SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate); break; } case EventCode.GameListUpdate: { Hashtable games = (Hashtable)photonEvent[ParameterCode.GameList]; foreach (DictionaryEntry room in games) { string gameName = (string)room.Key; RoomInfo game = new RoomInfo(gameName, (Hashtable)room.Value); if (game.removedFromList) { this.mGameList.Remove(gameName); } else { this.mGameList[gameName] = game; } } this.mGameListCopy = new RoomInfo[this.mGameList.Count]; this.mGameList.Values.CopyTo(this.mGameListCopy, 0); SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate); break; } case EventCode.QueueState: if (photonEvent.Parameters.ContainsKey(ParameterCode.Position)) { this.mQueuePosition = (int)photonEvent[ParameterCode.Position]; } else { Debug.LogError("Event QueueState must contain position!"); } if (this.mQueuePosition == 0) { // once we're un-queued, let's join the lobby or simply be "connected to master" if (PhotonNetwork.autoJoinLobby) { this.State = global::PeerState.Authenticated; this.OpJoinLobby(this.lobby); } else { this.State = global::PeerState.ConnectedToMaster; NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnConnectedToMaster); } } break; case EventCode.AppStats: // Debug.LogInfo("Received stats!"); this.mPlayersInRoomsCount = (int)photonEvent[ParameterCode.PeerCount]; this.mPlayersOnMasterCount = (int)photonEvent[ParameterCode.MasterPeerCount]; this.mGameCount = (int)photonEvent[ParameterCode.GameCount]; break; case EventCode.Join: // actorNr is fetched out of event above Hashtable actorProperties = (Hashtable)photonEvent[ParameterCode.PlayerProperties]; if (originatingPlayer == null) { bool isLocal = this.mLocalActor.ID == actorNr; this.AddNewPlayer(actorNr, new PhotonPlayer(isLocal, actorNr, actorProperties)); this.ResetPhotonViewsOnSerialize(); // This sets the correct OnSerializeState for Reliable OnSerialize } if (actorNr == this.mLocalActor.ID) { // in this player's 'own' join event, we get a complete list of players in the room, so check if we know all players int[] actorsInRoom = (int[])photonEvent[ParameterCode.ActorList]; foreach (int actorNrToCheck in actorsInRoom) { if (this.mLocalActor.ID != actorNrToCheck && !this.mActors.ContainsKey(actorNrToCheck)) { this.AddNewPlayer(actorNrToCheck, new PhotonPlayer(false, actorNrToCheck, string.Empty)); } } // joinWithCreateOnDemand can turn an OpJoin into creating the room. Then actorNumber is 1 and callback: OnCreatedRoom() if (this.mLastJoinType == JoinType.JoinOrCreateOnDemand && this.mLocalActor.ID == 1) { SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom); } SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); //Always send OnJoinedRoom } else { SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerConnected, this.mActors[actorNr]); } break; case EventCode.Leave: this.HandleEventLeave(actorNr); break; case EventCode.PropertiesChanged: int targetActorNr = (int)photonEvent[ParameterCode.TargetActorNr]; Hashtable gameProperties = null; Hashtable actorProps = null; if (targetActorNr == 0) { gameProperties = (Hashtable)photonEvent[ParameterCode.Properties]; } else { actorProps = (Hashtable)photonEvent[ParameterCode.Properties]; } this.ReadoutProperties(gameProperties, actorProps, targetActorNr); break; case PunEvent.RPC: //ts: each event now contains a single RPC. execute this this.ExecuteRPC(photonEvent[ParameterCode.Data] as Hashtable, originatingPlayer); break; case PunEvent.SendSerialize: case PunEvent.SendSerializeReliable: Hashtable serializeData = (Hashtable)photonEvent[ParameterCode.Data]; //Debug.Log(serializeData.ToStringFull()); int remoteUpdateServerTimestamp = (int)serializeData[(byte)0]; short remoteLevelPrefix = -1; short initialDataIndex = 1; if (serializeData.ContainsKey((byte)1)) { remoteLevelPrefix = (short)serializeData[(byte)1]; initialDataIndex = 2; } for (short s = initialDataIndex; s < serializeData.Count; s++) { this.OnSerializeRead(serializeData[s] as Hashtable, originatingPlayer, remoteUpdateServerTimestamp, remoteLevelPrefix); } break; case PunEvent.Instantiation: this.DoInstantiate((Hashtable)photonEvent[ParameterCode.Data], originatingPlayer, null); break; case PunEvent.CloseConnection: // MasterClient "requests" a disconnection from us if (originatingPlayer == null || !originatingPlayer.isMasterClient) { Debug.LogError("Error: Someone else(" + originatingPlayer + ") then the masterserver requests a disconnect!"); } else { PhotonNetwork.LeaveRoom(); } break; case PunEvent.DestroyPlayer: Hashtable evData = (Hashtable)photonEvent[ParameterCode.Data]; int targetPlayerId = (int)evData[(byte)0]; if (targetPlayerId >= 0) { this.DestroyPlayerObjects(targetPlayerId, true); } else { if (this.DebugOut >= DebugLevel.INFO) Debug.Log("Ev DestroyAll! By PlayerId: " + actorNr); this.DestroyAll(true); } break; case PunEvent.Destroy: evData = (Hashtable)photonEvent[ParameterCode.Data]; int instantiationId = (int)evData[(byte)0]; // Debug.Log("Ev Destroy for viewId: " + instantiationId + " sent by owner: " + (instantiationId / PhotonNetwork.MAX_VIEW_IDS == actorNr) + " this client is owner: " + (instantiationId / PhotonNetwork.MAX_VIEW_IDS == this.mLocalActor.ID)); GameObject goToDestroyLocally = null; this.instantiatedObjects.TryGetValue(instantiationId, out goToDestroyLocally); if (goToDestroyLocally == null || originatingPlayer == null) { if (this.DebugOut >= DebugLevel.ERROR) Debug.LogError("Can't execute received Destroy request for view ID=" + instantiationId + " as GO can't be found. From player/actorNr: " + actorNr + " GO to destroy=" + goToDestroyLocally + " originating Player=" + originatingPlayer); } else { this.RemoveInstantiatedGO(goToDestroyLocally, true); } break; case PunEvent.AssignMaster: evData = (Hashtable)photonEvent[ParameterCode.Data]; int newMaster = (int)evData[(byte)1]; this.SetMasterClient(newMaster, false); break; default: if (photonEvent.Code > 0 && photonEvent.Code < 200 && PhotonNetwork.OnEventCall != null) { object content = photonEvent[ParameterCode.Data]; PhotonNetwork.OnEventCall(photonEvent.Code, content, actorNr); } else { // actorNr might be null. it is fetched out of event on top of method // Hashtable eventContent = (Hashtable) photonEvent[ParameterCode.Data]; // this.mListener.customEventAction(actorNr, eventCode, eventContent); Debug.LogError("Error. Unhandled event: " + photonEvent); } break; } this.externalListener.OnEvent(photonEvent); }
public void CreatRoom(RoomInfo roomInfo) { _allRooms.Add(roomInfo.RoomId, roomInfo); }
void _serverConnection_DataReceived(object sender, EventArgs e) { _context.Post(new SendOrPostCallback(delegate(object state) { try { if (_serverConnection != null) { byte[] data = _serverConnection.ReadData(); while (data != null) { //parse data ChatMessage msg = ChatMessage.Parse(data); if (msg != null) { //handle data if (msg.Name == "signinfailed") { CloseConnection(); break; } else if (msg.Name == "signinsuccess") { _retryCount = 0; panel1.Enabled = true; splitContainer1.Enabled = true; toolStripStatusLabelConnectionStatus.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_CONNECTED); } else if (msg.Name == "txt") { AddMessage(msg.ID, msg.Parameters["msg"], Color.FromArgb(int.Parse(msg.Parameters["color"]))); if (checkBoxPlaySound.Checked && _sndWelcome != null) { _sndMessage.Play(); //System.Media.SystemSounds.Beep.Play(); } } else if (msg.Name == "usersinroom") { bool newUser = false; int i = 0; UserInRoomInfo[] curUsr = (from UserInRoomInfo a in listBox1.Items select a as UserInRoomInfo).ToArray(); foreach (var x in curUsr) { x.present = false; } bool wasempty = curUsr.Length == 0; while (msg.Parameters.ContainsKey(string.Format("name{0}", i))) { string id = msg.Parameters[string.Format("id{0}", i)]; UserInRoomInfo c = (from x in curUsr where x.ID == id select x).FirstOrDefault(); if (c == null) { c = new UserInRoomInfo(); c.ID = id; c.Username = msg.Parameters[string.Format("name{0}", i)]; c.present = true; c.FollowThisUser = false; c.SelectionCount = -1; if (msg.Parameters.ContainsKey(string.Format("sc{0}", i))) { string selCount = msg.Parameters[string.Format("sc{0}", i)]; if (!string.IsNullOrEmpty(selCount)) { c.SelectionCount = int.Parse(selCount); } } c.CanBeFollowed = bool.Parse(msg.Parameters[string.Format("cbf{0}", i)]); c.ActiveGeocache = msg.Parameters[string.Format("agc{0}", i)]; listBox1.Items.Add(c); if (!wasempty) { AddMessage("-1", string.Format("{0} {1}", c.Username, Utils.LanguageSupport.Instance.GetTranslation(STR_JOINED)), Color.Black); } newUser = true; } else { c.CanBeFollowed = bool.Parse(msg.Parameters[string.Format("cbf{0}", i)]); c.ActiveGeocache = msg.Parameters[string.Format("agc{0}", i)]; c.present = true; } i++; } foreach (var x in curUsr) { if (!x.present) { listBox1.Items.Remove(x); } } typeof(ListBox).InvokeMember("RefreshItems", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, listBox1, new object[] { }); listBox1_SelectedIndexChanged(this, EventArgs.Empty); if (checkBoxPlaySound.Checked && newUser && _sndWelcome != null) { _sndWelcome.Play(); //System.Media.SystemSounds.Beep.Play(); } } else if (msg.Name == "follow") { UserInRoomInfo[] curUsr = (from UserInRoomInfo a in listBox1.Items select a as UserInRoomInfo).ToArray(); UserInRoomInfo c = (from x in curUsr where x.ID == msg.ID select x).FirstOrDefault(); if (c != null) { c.CanBeFollowed = bool.Parse(msg.Parameters["canfollow"]); c.ActiveGeocache = msg.Parameters["cache"]; c.SelectionCount = -1; if (msg.Parameters.ContainsKey("selected")) { string selCount = msg.Parameters["selected"]; if (!string.IsNullOrEmpty(selCount)) { c.SelectionCount = int.Parse(selCount); } } if (c.FollowThisUser) { if (!c.CanBeFollowed) { c.FollowThisUser = false; linkLabelUnavailableCache.Visible = false; } else { if (!string.IsNullOrEmpty(c.ActiveGeocache)) { Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, c.ActiveGeocache); if (gc != null) { Core.ActiveGeocache = gc; linkLabelUnavailableCache.Visible = false; } else if (c.ActiveGeocache.StartsWith("GC") && Core.GeocachingComAccount.MemberTypeId > 1) { //offer to download linkLabelUnavailableCache.Links.Clear(); linkLabelUnavailableCache.Text = string.Format("{0}: {1}", Utils.LanguageSupport.Instance.GetTranslation(STR_MISSING), c.ActiveGeocache); linkLabelUnavailableCache.Links.Add(linkLabelUnavailableCache.Text.IndexOf(':') + 2, c.ActiveGeocache.Length, c.ActiveGeocache); linkLabelUnavailableCache.Visible = true; } else { linkLabelUnavailableCache.Visible = false; } } else { linkLabelUnavailableCache.Visible = false; } } } } typeof(ListBox).InvokeMember("RefreshItems", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, listBox1, new object[] { }); listBox1_SelectedIndexChanged(this, EventArgs.Empty); } else if (msg.Name == "rooms") { RoomInfo[] curRms = (from RoomInfo a in listBox2.Items select a as RoomInfo).ToArray(); foreach (var x in curRms) { x.present = false; } int i = 0; while (msg.Parameters.ContainsKey(string.Format("name{0}", i))) { string name = msg.Parameters[string.Format("name{0}", i)]; RoomInfo c = (from x in curRms where x.Name == name select x).FirstOrDefault(); if (c == null) { c = new RoomInfo(); c.present = true; c.Name = name; listBox2.Items.Add(c); } else { c.present = true; } i++; } foreach (var x in curRms) { if (!x.present) { listBox2.Items.Remove(x); } } typeof(ListBox).InvokeMember("RefreshItems", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, listBox2, new object[] { }); } else if (msg.Name == "reqsel") { StringBuilder sb = new StringBuilder(); UserInRoomInfo[] curUsr = (from UserInRoomInfo a in listBox1.Items select a as UserInRoomInfo).ToArray(); UserInRoomInfo c = (from x in curUsr where x.ID == msg.ID select x).FirstOrDefault(); if (c != null) { AddMessage("-1", string.Format("{0} {1}", c.Username, Utils.LanguageSupport.Instance.GetTranslation(STR_REQUESTEDSELECTION)), Color.Black); var gsel = from Framework.Data.Geocache g in Core.Geocaches where g.Selected select g; foreach (var g in gsel) { sb.AppendFormat("{0},", g.Code); } } ChatMessage bmsg = new ChatMessage(); bmsg.Name = "reqselresp"; bmsg.Parameters.Add("reqid", msg.Parameters["reqid"]); bmsg.Parameters.Add("clientid", msg.ID); bmsg.Parameters.Add("selection", sb.ToString()); sendMessage(bmsg); } else if (msg.Name == "reqselresp") { if (msg.Parameters["reqid"] == _currentCopySelectionRequestID) { //handle response string[] gcCodes = msg.Parameters["selection"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); Core.Geocaches.BeginUpdate(); foreach (Framework.Data.Geocache g in Core.Geocaches) { g.Selected = gcCodes.Contains(g.Code); } Core.Geocaches.EndUpdate(); //are we missing geocaches? _importGeocaches.Clear(); if (Core.GeocachingComAccount.MemberTypeId > 1) { foreach (string s in gcCodes) { if (Utils.DataAccess.GetGeocache(Core.Geocaches, s) == null && s.StartsWith("GC")) { _importGeocaches.Add(s); } } if (_importGeocaches.Count > 0) { _frameworkUpdater = new Utils.FrameworkDataUpdater(Core); _getGeocacheThread = new Thread(new ThreadStart(getCopiedSelectionGeocacheInbackgroundMethod)); _getGeocacheThread.IsBackground = true; _getGeocacheThread.Start(); } } //reset request prop. timerCopySelection.Enabled = false; _currentCopySelectionRequestID = null; _copySelectionRequestStarted = DateTime.MinValue; toolStripStatusLabelRequestSelection.Visible = false; } } } data = _serverConnection.ReadData(); } } } catch { CloseConnection(); } }), null); }
public static void Initialize(EFDomainDbContext cntxt) { if (!cntxt.BedTypes.Any()) { var bt = BedType.Create("TWN", "2 Twin Beds"); cntxt.BedTypes.AddAsync(bt); bt = BedType.Create("DBL", "1 King Bed"); cntxt.BedTypes.AddAsync(bt); bt = BedType.Create("HTW", "Hollywood Twin"); cntxt.BedTypes.AddAsync(bt); bt = BedType.Create("FAM", "1 Double & 1 Twin"); cntxt.BedTypes.AddAsync(bt); cntxt.SaveChangesAsync(); } if (!cntxt.RoomFacilities.Any()) { var f = RoomFacility.Create("TV", "TV"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("COT", "Baby Cot"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("HCH", "Baby High Chair"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("TRO", "Trolley"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("MAT", "Nursing Mat"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("BRC", "Baby Resting Chair"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("BBS", "Dumbo Baby Sitter"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("CCC", "Children's crockery & cutlery"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("BBT", "Baby Bathtub"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("NSM", "Non-slippery bath mat"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("STB", "Stool in the Bathroom"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("PLP", "Plastic Potty"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("SDL", "Safety drawer locks"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("BOI", "Boiler"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("INT", "Internet Connection"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("HAR", "Hair Dryer"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("BAB", "Bathrobes"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("SLP", "Slippers "); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("SAP", "Sun-beds and Parasol "); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("IRO", "Iron & Iron Board"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("BWS", "Bathtub with Shower & WC"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("SHW", "Shower Booth"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("SAF", "Safe Deposit Box"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("CAB", "Cable TV"); f = RoomFacility.Create("TEL", "Telephone"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("AIR", "Air Condition"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("WOR", "Working Desk"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("PAT", "Patch Cable"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("MIC", "Microwave Oven"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("FRD", "Refrigerator"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("MNB", "Mini Bar"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("SWC", "Shower & WC"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("HCW", "Hot &Cold Water"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("SOF", "Sofa Bed"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("RAI", "Rain-man Shower & WC"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("TOA", "Toaster"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("SUN", "5 Position(Sun Chairs)"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("WEL", "Welcome Package"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("DUX", "Dux Matress"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("CBA", "Children's Bathrobes"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("COS", "Cosmetic Mirror"); cntxt.RoomFacilities.AddAsync(f); f = RoomFacility.Create("BTH", "Bathtub and WC"); cntxt.RoomFacilities.AddAsync(f); cntxt.SaveChangesAsync(); } if (!cntxt.RoomExposures.Any()) { var re = RoomExposure.Create("GAV", "Garden View"); cntxt.RoomExposures.AddAsync(re); re = RoomExposure.Create("POV", "Pool View"); cntxt.RoomExposures.AddAsync(re); re = RoomExposure.Create("SFV", "Sea Facing View"); cntxt.RoomExposures.AddAsync(re); re = RoomExposure.Create("SSV", "Side Sea View"); cntxt.RoomExposures.AddAsync(re); re = RoomExposure.Create("PGV", "Pool and Garden View"); cntxt.RoomExposures.AddAsync(re); re = RoomExposure.Create("BKV", "Back View"); cntxt.RoomExposures.AddAsync(re); cntxt.SaveChangesAsync(); } if (!cntxt.RoomGroups.Any()) { var rg = RoomGroup.Create("STU", "Studio Type"); cntxt.RoomGroups.AddAsync(rg); rg = RoomGroup.Create("HBT", "Studio Happy Baby Type"); cntxt.RoomGroups.AddAsync(rg); rg = RoomGroup.Create("ROY", "Royal Studio Type"); cntxt.RoomGroups.AddAsync(rg); rg = RoomGroup.Create("ROP", "Royal Studio Pool Access Type"); cntxt.RoomGroups.AddAsync(rg); rg = RoomGroup.Create("FAM", "Family Suite Type"); cntxt.RoomGroups.AddAsync(rg); rg = RoomGroup.Create("ROF", "Royal Family Suite Type"); cntxt.RoomGroups.AddAsync(rg); rg = RoomGroup.Create("DLX", "Deluxe Room No Balcony Type"); cntxt.RoomGroups.AddAsync(rg); cntxt.SaveChangesAsync(); } if (!cntxt.RoomTypes.Any()) { var stu = cntxt.RoomGroups.Where(c => c.Code == "STU").FirstOrDefault(); var hbt = cntxt.RoomGroups.Where(c => c.Code == "HBT").FirstOrDefault(); var roy = cntxt.RoomGroups.Where(c => c.Code == "ROY").FirstOrDefault(); var rop = cntxt.RoomGroups.Where(c => c.Code == "ROP").FirstOrDefault(); var fam = cntxt.RoomGroups.Where(c => c.Code == "FAM").FirstOrDefault(); var rof = cntxt.RoomGroups.Where(c => c.Code == "ROF").FirstOrDefault(); var dlx = cntxt.RoomGroups.Where(c => c.Code == "DLX").FirstOrDefault(); var rt = RoomType.Create("12GAT", "Studio Garden View Terrace", stu, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("12GAB", "Studio Garden View Balcony", stu, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("12POT", "Studio Pool View Terrace", stu, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("12POB", "Studio Pool View Balcony", stu, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("12HBT", "Studio Happy Baby", hbt, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("12RPA", "Royal Studio Pool Access", rop, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("12ROT", "Royal Studio Terrace", roy, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("12ROB", "Royal Studio Balcony", roy, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("22POT", "Family Suite Pool View Terrace", fam, 6); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("22POB", "Family Suite Pool View Balcony", fam, 6); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("22RPA", "Royal Family Suite Pool Access", fam, 6); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("22GAB", "Family Suite Garden Balcony", fam, 6); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("22ROB", "Royal Family Suite Balcony", rof, 6); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("DLX", "Deluxe Room No Balcony", dlx, 4); cntxt.RoomTypes.AddAsync(rt); rt = RoomType.Create("22GAT", "Family Suite Garden Terrace", fam, 6); cntxt.RoomTypes.AddAsync(rt); cntxt.SaveChangesAsync(); } if (!cntxt.RoomLocations.Any()) { var rl = RoomLocation.Create("s", "south"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("n", "north"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B11", "Building 1 1st floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B12", "Building 1 2nd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B13", "Building 1 3rd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B14", "Building 1 4th floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B21", "Building 2 1st floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B22", "Building 2 2nd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B23", "Building 2 3rd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B24", "Building 2 4th floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B31", "Building 3 1st floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B32", "Building 3 2nd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B33", "Building 3 3rd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B41", "Building 4 1st floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B42", "Building 4 2nd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B43", "Building 4 3rd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B44", "Building 4 4th floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B51", "Building 5 1st floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B52", "Building 5 2nd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B53", "Building 5 3rd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B54", "Building 5 4th floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B61", "Building 6 1st floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B62", "Building 6 2nd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B63", "Building 6 3rd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B71", "Building 7 1st floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B72", "Building 7 2nd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B73", "Building 7 3rd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B74", "Building 7 4th floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B81", "Building 8 1st floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B82", "Building 8 2nd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("B83", "Building 8 3rd floor"); cntxt.RoomLocations.AddAsync(rl); rl = RoomLocation.Create("BL", "Lobby Building"); cntxt.RoomLocations.AddAsync(rl); cntxt.SaveChangesAsync(); } if (!cntxt.RoomInfos.Any()) { var rt = cntxt.RoomTypes.Where(r => r.Code == "DLX").FirstOrDefault(); var bt = cntxt.BedTypes.Where(B => B.Code == "DBL").FirstOrDefault(); var rl = cntxt.RoomLocations.Where(r => r.Code == "BL").FirstOrDefault(); var re = cntxt.RoomExposures.Where(e => e.Code == "POV").FirstOrDefault(); var bkv = cntxt.RoomExposures.Where(e => e.Code == "BKV").FirstOrDefault(); var gab = cntxt.RoomTypes.Where(r => r.Code == "22GAB").FirstOrDefault(); var fam = cntxt.BedTypes.Where(B => B.Code == "FAM").FirstOrDefault(); var b13 = cntxt.RoomLocations.Where(r => r.Code == "B13").FirstOrDefault(); var gv = cntxt.RoomExposures.Where(e => e.Code == "GV").FirstOrDefault(); var rf1 = RoomInfo.Create("1211", rt, bt, rl, re); cntxt.RoomInfos.AddAsync(rf1); var rf2 = RoomInfo.Create("1212", rt, bt, rl, bkv); cntxt.RoomInfos.AddAsync(rf2); var rf3 = RoomInfo.Create("1301", gab, fam, b13, gv); cntxt.RoomInfos.AddAsync(rf3); cntxt.SaveChangesAsync(); var facilities1 = cntxt.RoomFacilities.OrderBy(x => Guid.NewGuid()).Take(5).ToList(); var facilities2 = cntxt.RoomFacilities.OrderBy(x => Guid.NewGuid()).Take(5).ToList(); var facilities3 = cntxt.RoomFacilities.OrderBy(x => Guid.NewGuid()).Take(5).ToList(); rf1.AddRoomRoomFacility(facilities1); rf2.AddRoomRoomFacility(facilities2); rf3.AddRoomRoomFacility(facilities3); cntxt.SaveChangesAsync(); } }
/// <summary> /// Constructor /// </summary> public DataController() { // create lists roomObjects = new RoomObjectList(300); roomObjectsFiltered = new RoomObjectListFiltered(roomObjects); projectiles = new ProjectileList(50); onlinePlayers = new OnlinePlayerList(200); inventoryObjects = new InventoryObjectList(100); avatarCondition = new StatNumericList(5); avatarAttributes = new StatNumericList(10); avatarSkills = new SkillList(100); avatarSpells = new SkillList(100); avatarQuests = new SkillList(100); roomBuffs = new ObjectBaseList<ObjectBase>(30); avatarBuffs = new ObjectBaseList<ObjectBase>(30); spellObjects = new SpellObjectList(100); backgroundOverlays = new BackgroundOverlayList(5); playerOverlays = new ObjectBaseList<PlayerOverlay>(10); chatMessages = new BaseList<ServerString>(101); gameMessageLog = new BaseList<GameMessage>(100); visitedTargets = new List<RoomObject>(50); clickedTargets = new List<uint>(50); actionButtons = new ActionButtonList(); ignoreList = new List<string>(20); chatCommandHistory = new List<string>(20); // attach some listeners RoomObjects.ListChanged += OnRoomObjectsListChanged; Projectiles.ListChanged += OnProjectilesListChanged; ChatMessages.ListChanged += OnChatMessagesListChanged; // make some lists sorted OnlinePlayers.SortByName(); AvatarSkills.SortByResourceName(); AvatarSpells.SortByResourceName(); SpellObjects.SortByName(); // create single data objects roomInformation = new RoomInfo(); lightShading = new LightShading(0, new SpherePosition(0, 0)); backgroundMusic = new PlayMusic(); guildInfo = new GuildInfo(); guildShieldInfo = new GuildShieldInfo(); guildAskData = new GuildAskData(); diplomacyInfo = new DiplomacyInfo(); adminInfo = new AdminInfo(); tradeInfo = new TradeInfo(); buyInfo = new BuyInfo(); welcomeInfo = new WelcomeInfo(); charCreationInfo = new CharCreationInfo(); statChangeInfo = new StatChangeInfo(); newsGroup = new NewsGroup(); objectContents = new ObjectContents(); effects = new Effects(); lookPlayer = new PlayerInfo(); lookObject = new ObjectInfo(); clientPreferences = new PreferencesFlags(); // some values ChatMessagesMaximum = 100; ChatCommandHistoryMaximum = 20; ChatCommandHistoryIndex = -1; AvatarObject = null; IsResting = false; SelfTarget = false; IsNextAttackApplyCastOnHighlightedObject = false; AvatarID = UInt32.MaxValue; TargetID = UInt32.MaxValue; ViewerPosition = V3.ZERO; UIMode = UIMode.None; }
public PhotonSharingRoom(string name, RoomInfo info) { Name = name; RoomInfo = info; }
public List <GeneralObject> Load(PIK1.C_Flats_PIK1DataTable dbFlats, out ProjectInfo pi) { List <GeneralObject> gos = new List <GeneralObject>(); pi = null; dictRoomInfo = new Dictionary <string, RoomInfo>(); foreach (var dbFlat in dbFlats) { if (!dictRoomInfo.ContainsKey(dbFlat.Type)) { RoomInfo flat = new RoomInfo(); flat.Type = dbFlat.Type; flat.AreaLive = dbFlat.AreaLive; flat.AreaModules = dbFlat.AreaInModule; flat.AreaTotal = dbFlat.AreaTotalStandart; flat.FactorSmoke = dbFlat.FactorSmoke; flat.ShortType = dbFlat.ShortType; flat.SubZone = dbFlat.SubZone; flat.SelectedIndexBottom = Convert.ToInt32(dbFlat.IndexBottom); flat.SelectedIndexTop = Convert.ToInt32(dbFlat.IndexTop); dictRoomInfo.Add(dbFlat.Type, flat); } } var fileResult = PromptFileResult(); using (ZipArchive zip = ZipFile.OpenRead(fileResult)) { using (var stream = zip.GetEntry("gos").Open()) { using (reader = new BinaryReader(stream)) { pi = ReadProjectInfo(); pi.SpotOptions = ReadSpotOptions(); pi.InsModulesAll = ReadInsModules(); var countGos = reader.ReadInt32(); for (int i = 0; i < countGos; i++) { var go = new GeneralObject(); go.GUID = reader.ReadString(); go.Houses = new List <HouseInfo>(); var countHouse = reader.ReadInt32(); for (int h = 0; h < countHouse; h++) { var hi = new HouseInfo(); hi.Sections = ReadSections(); //hi.SpotInf = ReadSpotInfo(); go.Houses.Add(hi); } go.SpotInf = ReadProjectInfo(); go.SpotInf.InsModulesAll = pi.InsModulesAll; gos.Add(go); } } } } return(gos); }
public void Setup(RoomInfo info) { roomInfo = info; text.text = roomInfo.Name; }
public void SetRoomInfo(RoomInfo roomInfo) { room = roomInfo; roomName.text = roomInfo.Name; number.text = roomInfo.PlayerCount.ToString() + (roomInfo.PlayerCount >= 2 ? "Jogadores" : " Jogador"); }
public void LeaveRoomAsync(RoomInfo room) { ExecuteRequestAsync( string.Format("roominfo/?roomid={0}&userRoomCommand={1}", room.Id, (int)UserRoomCommand.Leave), Method.POST, restResponse => AsyncCompletedEventArgsExtensions.Raise(LeaveRoomCompleted, restResponse, room)); }
public void JoinLobby(RoomInfo info) { PhotonNetwork.JoinRoom(info.Name); btnDisable(true); }
private void PacketReceived(NetIncomingMessage msg) { if (msg == null) { DisconnectCommandReceived(null); return; } CommandType commandType = (CommandType)msg.ReadByte(); if (!joined) { if (commandType == CommandType.JoinRoom) { switch (msg.ReadByte()) { case 0: { Client.Instance.playerInfo.playerState = PlayerState.DownloadingSongs; Client.Instance.RequestRoomInfo(); Client.Instance.SendPlayerInfo(); Client.Instance.InRoom = true; joined = true; InGameOnlineController.Instance.needToSendUpdates = true; if (Config.Instance.EnableVoiceChat) { InGameOnlineController.Instance.VoiceChatStartRecording(); } } break; case 1: { _roomNavigationController.DisplayError("Unable to join room!\nRoom not found"); } break; case 2: { _roomNavigationController.DisplayError("Unable to join room!\nIncorrect password"); } break; case 3: { _roomNavigationController.DisplayError("Unable to join room!\nToo much players"); } break; default: { _roomNavigationController.DisplayError("Unable to join room!\nUnknown error"); } break; } } } else { try { switch (commandType) { case CommandType.GetRoomInfo: { Client.Instance.playerInfo.playerState = PlayerState.Room; roomInfo = new RoomInfo(msg); Client.Instance.isHost = Client.Instance.playerInfo.Equals(roomInfo.roomHost); UpdateUI(roomInfo.roomState); } break; case CommandType.SetSelectedSong: { if (msg.LengthBytes < 16) { roomInfo.roomState = RoomState.SelectingSong; roomInfo.selectedSong = null; PreviewPlayer.CrossfadeToDefault(); UpdateUI(roomInfo.roomState); if (songToDownload != null) { songToDownload.songQueueState = SongQueueState.Error; Client.Instance.playerInfo.playerState = PlayerState.Room; } } else { roomInfo.roomState = RoomState.Preparing; SongInfo selectedSong = new SongInfo(msg); roomInfo.selectedSong = selectedSong; if (roomInfo.startLevelInfo == null) { roomInfo.startLevelInfo = new StartLevelInfo(BeatmapDifficulty.Hard, GameplayModifiers.defaultModifiers, "Standard"); } if (songToDownload != null) { songToDownload.songQueueState = SongQueueState.Error; } UpdateUI(roomInfo.roomState); } } break; case CommandType.SetLevelOptions: { if (roomInfo.roomState == RoomState.SelectingSong) { roomInfo.startLevelInfo = new StartLevelInfo(msg); _playerManagementViewController.SetGameplayModifiers(roomInfo.startLevelInfo.modifiers); _difficultySelectionViewController.SetBeatmapCharacteristic(_beatmapCharacteristics.First(x => x.serializedName == roomInfo.startLevelInfo.characteristicName)); if (!roomInfo.perPlayerDifficulty) { _difficultySelectionViewController.SetBeatmapDifficulty(roomInfo.startLevelInfo.difficulty); } } } break; case CommandType.GetRandomSongInfo: { SongInfo random = new SongInfo(SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).ToArray().Random() as BeatmapLevelSO); Client.Instance.SetSelectedSong(random); } break; case CommandType.TransferHost: { roomInfo.roomHost = new PlayerInfo(msg); Client.Instance.isHost = Client.Instance.playerInfo.Equals(roomInfo.roomHost); if (Client.Instance.playerInfo.playerState == PlayerState.DownloadingSongs) { return; } UpdateUI(roomInfo.roomState); } break; case CommandType.StartLevel: { if (Client.Instance.playerInfo.playerState == PlayerState.DownloadingSongs) { return; } StartLevelInfo levelInfo = new StartLevelInfo(msg); BeatmapCharacteristicSO characteristic = _beatmapCharacteristics.First(x => x.serializedName == levelInfo.characteristicName); SongInfo songInfo = new SongInfo(msg); BeatmapLevelSO level = SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).FirstOrDefault(x => x.levelID.StartsWith(songInfo.levelId)) as BeatmapLevelSO; if (level == null) { Logger.Error("Unable to start level! Level is null! LevelID=" + songInfo.levelId); } if (roomInfo.perPlayerDifficulty && _difficultySelectionViewController != null) { StartLevel(level, characteristic, _difficultySelectionViewController.selectedDifficulty, levelInfo.modifiers); } else { StartLevel(level, characteristic, levelInfo.difficulty, levelInfo.modifiers); } } break; case CommandType.LeaveRoom: { LeaveRoom(); } break; case CommandType.UpdatePlayerInfo: { if (roomInfo != null) { currentTime = msg.ReadFloat(); totalTime = msg.ReadFloat(); int playersCount = msg.ReadInt32(); List <PlayerInfo> playerInfos = new List <PlayerInfo>(); for (int j = 0; j < playersCount; j++) { try { playerInfos.Add(new PlayerInfo(msg)); } catch (Exception e) { #if DEBUG Misc.Logger.Exception($"Unable to parse PlayerInfo! Excpetion: {e}"); #endif } } switch (roomInfo.roomState) { case RoomState.InGame: playerInfos = playerInfos.Where(x => x.playerScore > 0 && x.playerState == PlayerState.Game).ToList(); UpdateLeaderboard(playerInfos, currentTime, totalTime, false); break; case RoomState.Results: playerInfos = playerInfos.Where(x => x.playerScore > 0 && (x.playerState == PlayerState.Game || x.playerState == PlayerState.Room)).ToList(); UpdateLeaderboard(playerInfos, currentTime, totalTime, true); break; } _playerManagementViewController.UpdatePlayerList(playerInfos, roomInfo.roomState); } } break; case CommandType.PlayerReady: { int playersReady = msg.ReadInt32(); int playersTotal = msg.ReadInt32(); if (roomInfo.roomState == RoomState.Preparing && _difficultySelectionViewController != null) { _difficultySelectionViewController.SetPlayersReady(playersReady, playersTotal); } } break; case CommandType.Disconnect: { DisconnectCommandReceived(msg); } break; } }catch (Exception e) { Logger.Exception($"Unable to parse packet! Packet={commandType}, DataLength={msg.LengthBytes}\nException: {e}"); } } }
private string RoomInfoToString(RoomInfo roomInfo) { string roomInfoString = "Name:" + roomInfo.Name + " PlayerNumber:" + roomInfo.PlayerCount.ToString() + "/" + roomInfo.MaxPlayers.ToString(); return(roomInfoString); }
//界面打开 初始化 建一副牌 发牌 掷骰子(选首玩家) 开始执行逻辑(摸排(放置一边) //猜牌(选牌,选指定值,判定) 摊牌(归位) 下一位) 没牌直接猜 没有未知手牌(pass) 结束回合(回到房间界面) public override void DoCommand() { int command = BitConverter.ToInt32(bytes, 8); switch (command) { case 0: Initialize(); break; case 1: OpenGameScene(); Debug.Log("开始游戏,跳转场景"); break; case 2: byte[] sd = Decode.DecodSecondContendBtye(bytes); currentRoom = DataDo.Json2Object <RoomInfo>(sd); //必须在此时获取一次,里面携带玩家手牌信息 GamePanel.Get().DealWithCards(currentRoom); Debug.Log("显示手牌"); break; case 3: int[] dice = new int[2]; dice[0] = BitConverter.ToInt32(bytes, 12); dice[1] = BitConverter.ToInt32(bytes, 16); Debug.Log("dice[0] :" + dice[0] + " dice[1] :" + dice[1]); GamePanel.Get().SetForthgoer(dice[0] + dice[1]); GamePanel.Get().CreatDice(dice); break; case 4: Next(); //房间独立线程发出的 break; case 5: Debug.Log("接收到摸排结果"); byte[] content = Decode.DecodSecondContendBtye(bytes); GamePanel.Get().DisplayDraw(BitConverter.ToInt32(content, 0), DataDo.Json2Object <BaseCard>(content.Skip(4).ToArray())); break; case 6: Debug.Log("猜对了 将该牌公布"); GamePanel.Get().KitheCard_T(DataDo.Json2Object <GuessInfo>(Decode.DecodSecondContendBtye(bytes))); break; case 7: Debug.Log("猜错了 将该牌公布"); GuessInfo guessInfo = DataDo.Json2Object <GuessInfo>(Decode.DecodSecondContendBtye(bytes)); GamePanel.Get().KitheCard_F(guessInfo.whoIndex, guessInfo.delateIndex, guessInfo.lineCardSeatIndex); break; case 8: Debug.Log("-------------------公布玩家自选的手牌"); GamePanel.Get().OpenSelfSelect(DataDo.Json2Object <SingleDraw>(Decode.DecodSecondContendBtye(bytes))); break; case 9: Debug.Log("公布牌"); GamePanel.Get().OpenCards(BitConverter.ToInt32(bytes, 12)); break; case 10: Debug.Log("-----------------执行出局命令"); GamePanel.Get().DoOut(BitConverter.ToInt32(bytes, 12)); break; case 11: Debug.Log("-------------------游戏结束"); List <int> exitList = DataDo.Json2Object <List <int> >(Decode.DecodSecondContendBtye(bytes)); GamePanel.Get().GameOver(exitList); break; case 12: Debug.Log("-------------------创建自选计时器"); GamePanel.Get().CreatSelectSelfCardTimer(); break; case 13: Debug.Log("-------------------继续猜牌"); GamePanel.Get().DoContinue(); break; case 14: break; case 15: Debug.Log("-------------------接收到移动万能牌的命令"); Info info = DataDo.Json2Object <Info>(Decode.DecodSecondContendBtye(bytes)); GamePanel.Get().DoMoveLineCard(info.myId, DataDo.Json2Object <List <LineCardMoveInfo> >(info.content)); break; case 16: Debug.Log("-------------------玩家离线"); GamePanel.Get().OffLine(BitConverter.ToInt32(bytes, 12)); break; } }
private void CreateRoomButton(RoomInfo roomInfo) { GameObject roomButton = Instantiate(roomButtonPrefab, roomButtonContainer.transform); roomButton.GetComponent <RoomButton>().Refresh(roomInfo); }
public void SetUp(RoomInfo _info) { info = _info; text.text = _info.Name; }
/** * ルームリスト取得レスポンスの受信 * * @param pResponseInfo レスポンス情報 */ protected void RecvResponse_GetRoomList(web.WebApiAgent.HttpResponseInfo pResponseInfo) { Logger.MLNLOG_DEBUG("code=" + pResponseInfo.code + " str=" + pResponseInfo.str); if (200 != pResponseInfo.code) { return; } LitJson.JsonData jsonData = LitJson.JsonMapper.ToObject(pResponseInfo.str); do { Logger.MLNLOG_DEBUG("pu_num=" + jsonData["data"]["pu_num"]); Logger.MLNLOG_DEBUG("room_hub_pu_high_list=" + jsonData["data"]["room_hub_pu_high_list"]); Logger.MLNLOG_DEBUG("room_hub_pu_low_list=" + jsonData["data"]["room_hub_pu_low_list"]); Logger.MLNLOG_DEBUG("battle_pu_high_list=" + jsonData["data"]["battle_pu_high_list"]); Logger.MLNLOG_DEBUG("battle_pu_low_list=" + jsonData["data"]["battle_pu_low_list"]); Logger.MLNLOG_DEBUG("ip_addr_list=" + jsonData["data"]["ip_addr_list"]); Logger.MLNLOG_DEBUG("port_list=" + jsonData["data"]["port_list"]); Logger.MLNLOG_DEBUG("entered_num_list=" + jsonData["data"]["entered_num_list"]); Logger.MLNLOG_DEBUG("max_enter_num_list=" + jsonData["data"]["max_enter_num_list"]); Logger.MLNLOG_DEBUG("status_list=" + jsonData["data"]["status_list"]); Int32 pu_num = Convert.ToInt32((string)jsonData["data"]["pu_num"]); if (0 == pu_num) { break; } char delimiter = ','; string[] roomHubPuHighList = ((string)jsonData["data"]["room_hub_pu_high_list"]).Split(delimiter); string[] roomHubPuLowList = ((string)jsonData["data"]["room_hub_pu_low_list"]).Split(delimiter); string[] battlePuHighList = ((string)jsonData["data"]["battle_pu_high_list"]).Split(delimiter); string[] battlePuLowList = ((string)jsonData["data"]["battle_pu_low_list"]).Split(delimiter); string[] ipAddrList = ((string)jsonData["data"]["ip_addr_list"]).Split(delimiter); string[] portList = ((string)jsonData["data"]["port_list"]).Split(delimiter); string[] enteredNumList = ((string)jsonData["data"]["entered_num_list"]).Split(delimiter); string[] maxEnterNumList = ((string)jsonData["data"]["max_enter_num_list"]).Split(delimiter); string[] statusList = ((string)jsonData["data"]["status_list"]).Split(delimiter); List <RoomInfo> roomInfoList = new List <RoomInfo>(); for (Int32 i = 0; i < pu_num; ++i) { UInt64 puUid; RoomInfo info = new RoomInfo(); puUid = Convert.ToUInt64(roomHubPuHighList[i]) << 32; puUid += Convert.ToUInt32(roomHubPuLowList[i]); info.roomHubPuUid = puUid; puUid = Convert.ToUInt64(battlePuHighList[i]) << 32; puUid += Convert.ToUInt32(battlePuLowList[i]); info.battlePuUid = puUid; info.ipAddr = ipAddrList[i]; info.port = Convert.ToUInt16(portList[i]); info.entered_num = Convert.ToByte(enteredNumList[i]); info.max_enter_num = Convert.ToByte(maxEnterNumList[i]); info.status = Convert.ToByte(statusList[i]); roomInfoList.Add(info); DebugManager.Instance.Log("[" + i + "] " + info.ipAddr + ":" + info.port + " 0x" + Utility.ToHex(info.battlePuUid) + " " + info.entered_num + "/" + info.max_enter_num + " " + info.status); } DebugManager.Instance.Log("RoomListNum=" + pu_num); // TODO 本来はユーザーが任意のルームを選択する必要があるが、 // ひとまずランダムで選択したルームに入室しておく Int32 roomIndex = (Int32)m_pRandom.Next(pu_num); m_pPU.SetRoomHubPU_PUUID(roomInfoList[roomIndex].roomHubPuUid); if (m_pPU.ConnectServer(roomInfoList[roomIndex].ipAddr, roomInfoList[roomIndex].port, roomInfoList[roomIndex].battlePuUid)) { SetPhase(PHASE.PHASE_BATTLE_ENTER_ROOM, Utility.GetSecond() + WAIT_TIME_CHANGE_PHASE); DebugManager.Instance.Log("m_CharaId=0x" + mln.Utility.ToHex(m_CharaId)); DebugManager.Instance.Log("Choice [" + roomIndex + "] " + roomInfoList[roomIndex].ipAddr + ":" + roomInfoList[roomIndex].port + " 0x" + Utility.ToHex(roomInfoList[roomIndex].battlePuUid) + " " + roomInfoList[roomIndex].entered_num + "/" + roomInfoList[roomIndex].max_enter_num + " " + roomInfoList[roomIndex].status); } }while (false); }
public void OnClose(RoomInfo room){ string name = room.ToString(); lock(Rooms){ Rooms.Remove(name); } BeginInvoke(new Action( ()=>{ lock(_lock) RemoveRoom(name); }) ); }
public void SetUp(RoomInfo room) { roomInfo = room; _roomNameField.text = room.Name; }
private void PacketReceived(NetIncomingMessage msg) { if (msg == null) { DisconnectCommandReceived(null); return; } msg.Position = 0; CommandType commandType = (CommandType)msg.ReadByte(); if (!joined) { if (commandType == CommandType.JoinRoom) { switch (msg.ReadByte()) { case 0: { Client.Instance.playerInfo.updateInfo.playerState = PlayerState.DownloadingSongs; Client.Instance.RequestRoomInfo(); roomInfoRequestTime = Time.time; Client.Instance.SendPlayerInfo(true); Client.Instance.inRoom = true; joined = true; InGameOnlineController.Instance.needToSendUpdates = true; if (Config.Instance.EnableVoiceChat) { InGameOnlineController.Instance.VoiceChatStartRecording(); } } break; case 1: { _roomNavigationController.DisplayError("Unable to join room!\nRoom not found"); } break; case 2: { _roomNavigationController.DisplayError("Unable to join room!\nIncorrect password"); } break; case 3: { _roomNavigationController.DisplayError("Unable to join room!\nToo much players"); } break; default: { _roomNavigationController.DisplayError("Unable to join room!\nUnknown error"); } break; } } } else { try { if (roomInfo == null && commandType != CommandType.GetRoomInfo) { if (Time.time - roomInfoRequestTime < 1.5f) { return; } else { throw new ArgumentNullException("RoomInfo is null! Need to wait for it to arrive..."); } } switch (commandType) { case CommandType.GetRoomInfo: { roomInfo = new RoomInfo(msg); Client.Instance.playerInfo.updateInfo.playerState = PlayerState.Room; Client.Instance.isHost = Client.Instance.playerInfo.Equals(roomInfo.roomHost); UpdateUI(roomInfo.roomState); } break; case CommandType.SetSelectedSong: { if (msg.LengthBytes < 16) { roomInfo.roomState = RoomState.SelectingSong; roomInfo.selectedSong = null; PreviewPlayer.CrossfadeToDefault(); UpdateUI(roomInfo.roomState); if (songToDownload != null) { songToDownload.songQueueState = SongQueueState.Error; Client.Instance.playerInfo.updateInfo.playerState = PlayerState.Room; } } else { roomInfo.roomState = RoomState.Preparing; SongInfo selectedSong = new SongInfo(msg); roomInfo.selectedSong = selectedSong; if (roomInfo.startLevelInfo == null) { roomInfo.startLevelInfo = new LevelOptionsInfo(BeatmapDifficulty.Hard, GameplayModifiers.defaultModifiers, "Standard"); } if (songToDownload != null) { songToDownload.songQueueState = SongQueueState.Error; } UpdateUI(roomInfo.roomState); } } break; case CommandType.SetLevelOptions: { roomInfo.startLevelInfo = new LevelOptionsInfo(msg); _playerManagementViewController.SetGameplayModifiers(roomInfo.startLevelInfo.modifiers.ToGameplayModifiers()); if (roomInfo.roomState == RoomState.Preparing) { _difficultySelectionViewController.SetBeatmapCharacteristic(_beatmapCharacteristics.First(x => x.serializedName == roomInfo.startLevelInfo.characteristicName)); if (!roomInfo.perPlayerDifficulty) { _difficultySelectionViewController.SetBeatmapDifficulty(roomInfo.startLevelInfo.difficulty); } } } break; case CommandType.GetRandomSongInfo: { SongInfo random = new SongInfo(SongCore.Loader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).ToArray().Random()); Client.Instance.SetSelectedSong(random); } break; case CommandType.TransferHost: { roomInfo.roomHost = new PlayerInfo(msg); Client.Instance.isHost = Client.Instance.playerInfo.Equals(roomInfo.roomHost); if (Client.Instance.playerInfo.updateInfo.playerState == PlayerState.DownloadingSongs) { return; } UpdateUI(roomInfo.roomState); } break; case CommandType.StartLevel: { if (Client.Instance.playerInfo.updateInfo.playerState == PlayerState.DownloadingSongs) { return; } LevelOptionsInfo levelInfo = new LevelOptionsInfo(msg); BeatmapCharacteristicSO characteristic = _beatmapCharacteristics.First(x => x.serializedName == levelInfo.characteristicName); SongInfo songInfo = new SongInfo(msg); IPreviewBeatmapLevel level = SongCore.Loader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).FirstOrDefault(x => x.levelID.StartsWith(songInfo.levelId)); if (level == null) { Plugin.log.Error("Unable to start level! Level is null! LevelID=" + songInfo.levelId); } else { LoadBeatmapLevelAsync(level, (status, success, beatmapLevel) => { if (roomInfo.perPlayerDifficulty && _difficultySelectionViewController != null) { StartLevel(beatmapLevel, characteristic, _difficultySelectionViewController.selectedDifficulty, levelInfo.modifiers.ToGameplayModifiers()); } else { StartLevel(beatmapLevel, characteristic, levelInfo.difficulty, levelInfo.modifiers.ToGameplayModifiers()); } }); } } break; case CommandType.LeaveRoom: { LeaveRoom(); } break; case CommandType.UpdatePlayerInfo: { if (roomInfo != null) { currentTime = msg.ReadFloat(); totalTime = msg.ReadFloat(); if (roomInfo.roomState == RoomState.InGame || roomInfo.roomState == RoomState.Results) { UpdateLeaderboard(currentTime, totalTime, roomInfo.roomState == RoomState.Results); } _playerManagementViewController.UpdatePlayerList(roomInfo.roomState); } } break; case CommandType.PlayerReady: { int playersReady = msg.ReadInt32(); int playersTotal = msg.ReadInt32(); if (roomInfo.roomState == RoomState.Preparing && _difficultySelectionViewController != null) { _difficultySelectionViewController.SetPlayersReady(playersReady, playersTotal); } } break; case CommandType.Disconnect: { DisconnectCommandReceived(msg); } break; } }catch (Exception e) { Plugin.log.Error($"Unable to parse packet! Packet={commandType}, DataLength={msg.LengthBytes}\nException: {e}"); } } }
/// <summary> /// 增 /// </summary> /// <param name="entity">要插入的数据数据对象</param> /// <returns></returns> public bool Insert(RoomInfo entity) { return(roomInfoDAL.Insert(entity)); }
public void OnEvent(EventData photonEvent) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) Debug.Log(string.Format("OnEvent: {0}", photonEvent.ToString())); int actorNr = -1; PhotonPlayer originatingPlayer = null; if (photonEvent.Parameters.ContainsKey(ParameterCode.ActorNr)) { actorNr = (int)photonEvent[ParameterCode.ActorNr]; if (this.mActors.ContainsKey(actorNr)) { originatingPlayer = (PhotonPlayer)this.mActors[actorNr]; } //else //{ // // the actor sending this event is not in actorlist. this is usually no problem // if (photonEvent.Code != (byte)LiteOpCode.Join) // { // Debug.LogWarning("Received event, but we do not have this actor: " + actorNr); // } //} } switch (photonEvent.Code) { case PunEvent.OwnershipRequest: { int[] requestValues = (int[]) photonEvent.Parameters[ParameterCode.CustomEventContent]; int requestedViewId = requestValues[0]; int currentOwner = requestValues[1]; Debug.Log("Ev OwnershipRequest: " + photonEvent.Parameters.ToStringFull() + " ViewID: " + requestedViewId + " from: " + currentOwner + " Time: " + Environment.TickCount%1000); PhotonView requestedView = PhotonView.Find(requestedViewId); if (requestedView == null) { Debug.LogWarning("Can't find PhotonView of incoming OwnershipRequest. ViewId not found: " + requestedViewId); break; } Debug.Log("Ev OwnershipRequest PhotonView.ownershipTransfer: " + requestedView.ownershipTransfer + " .ownerId: " + requestedView.ownerId + " isOwnerActive: " + requestedView.isOwnerActive + ". This client's player: " + PhotonNetwork.player.ToStringFull()); switch (requestedView.ownershipTransfer) { case OwnershipOption.Fixed: Debug.LogWarning("Ownership mode == fixed. Ignoring request."); break; case OwnershipOption.Takeover: if (currentOwner == requestedView.ownerId) { // a takeover is successful automatically, if taken from current owner requestedView.ownerId = actorNr; } break; case OwnershipOption.Request: if (currentOwner == PhotonNetwork.player.ID || PhotonNetwork.player.isMasterClient) { if ((requestedView.ownerId == PhotonNetwork.player.ID) || (PhotonNetwork.player.isMasterClient && !requestedView.isOwnerActive)) { SendMonoMessage(PhotonNetworkingMessage.OnOwnershipRequest, new object[] {requestedView, originatingPlayer}); } } break; default: break; } } break; case PunEvent.OwnershipTransfer: { int[] transferViewToUserID = (int[]) photonEvent.Parameters[ParameterCode.CustomEventContent]; Debug.Log("Ev OwnershipTransfer. ViewID " + transferViewToUserID[0] + " to: " + transferViewToUserID[1] + " Time: " + Environment.TickCount%1000); int requestedViewId = transferViewToUserID[0]; int newOwnerId = transferViewToUserID[1]; PhotonView pv = PhotonView.Find(requestedViewId); pv.ownerId = newOwnerId; break; } case EventCode.GameList: { this.mGameList = new Dictionary<string, RoomInfo>(); Hashtable games = (Hashtable)photonEvent[ParameterCode.GameList]; foreach (DictionaryEntry game in games) { string gameName = (string)game.Key; this.mGameList[gameName] = new RoomInfo(gameName, (Hashtable)game.Value); } mGameListCopy = new RoomInfo[mGameList.Count]; mGameList.Values.CopyTo(mGameListCopy, 0); SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate); break; } case EventCode.GameListUpdate: { Hashtable games = (Hashtable)photonEvent[ParameterCode.GameList]; foreach (DictionaryEntry room in games) { string gameName = (string)room.Key; RoomInfo game = new RoomInfo(gameName, (Hashtable)room.Value); if (game.removedFromList) { this.mGameList.Remove(gameName); } else { this.mGameList[gameName] = game; } } this.mGameListCopy = new RoomInfo[this.mGameList.Count]; this.mGameList.Values.CopyTo(this.mGameListCopy, 0); SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate); break; } case EventCode.QueueState: // not used anymore break; case EventCode.AppStats: // Debug.LogInfo("Received stats!"); this.mPlayersInRoomsCount = (int)photonEvent[ParameterCode.PeerCount]; this.mPlayersOnMasterCount = (int)photonEvent[ParameterCode.MasterPeerCount]; this.mGameCount = (int)photonEvent[ParameterCode.GameCount]; break; case EventCode.Join: // actorNr is fetched out of event above Hashtable actorProperties = (Hashtable)photonEvent[ParameterCode.PlayerProperties]; if (originatingPlayer == null) { bool isLocal = this.mLocalActor.ID == actorNr; this.AddNewPlayer(actorNr, new PhotonPlayer(isLocal, actorNr, actorProperties)); this.ResetPhotonViewsOnSerialize(); // This sets the correct OnSerializeState for Reliable OnSerialize } if (actorNr == this.mLocalActor.ID) { // in this player's 'own' join event, we get a complete list of players in the room, so check if we know all players int[] actorsInRoom = (int[])photonEvent[ParameterCode.ActorList]; foreach (int actorNrToCheck in actorsInRoom) { if (this.mLocalActor.ID != actorNrToCheck && !this.mActors.ContainsKey(actorNrToCheck)) { this.AddNewPlayer(actorNrToCheck, new PhotonPlayer(false, actorNrToCheck, string.Empty)); } } // joinWithCreateOnDemand can turn an OpJoin into creating the room. Then actorNumber is 1 and callback: OnCreatedRoom() if (this.mLastJoinType == JoinType.JoinOrCreateOnDemand && this.mLocalActor.ID == 1) { SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom); } SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); //Always send OnJoinedRoom } else { SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerConnected, this.mActors[actorNr]); } break; case EventCode.Leave: this.HandleEventLeave(actorNr); break; case EventCode.PropertiesChanged: int targetActorNr = (int)photonEvent[ParameterCode.TargetActorNr]; Hashtable gameProperties = null; Hashtable actorProps = null; if (targetActorNr == 0) { gameProperties = (Hashtable)photonEvent[ParameterCode.Properties]; } else { actorProps = (Hashtable)photonEvent[ParameterCode.Properties]; } this.ReadoutProperties(gameProperties, actorProps, targetActorNr); break; case PunEvent.RPC: //ts: each event now contains a single RPC. execute this // Debug.Log("Ev RPC from: " + originatingPlayer); this.ExecuteRPC(photonEvent[ParameterCode.Data] as Hashtable, originatingPlayer); break; case PunEvent.SendSerialize: case PunEvent.SendSerializeReliable: Hashtable serializeData = (Hashtable)photonEvent[ParameterCode.Data]; //Debug.Log(serializeData.ToStringFull()); int remoteUpdateServerTimestamp = (int)serializeData[(byte)0]; short remoteLevelPrefix = -1; short initialDataIndex = 1; if (serializeData.ContainsKey((byte)1)) { remoteLevelPrefix = (short)serializeData[(byte)1]; initialDataIndex = 2; } for (short s = initialDataIndex; s < serializeData.Count; s++) { this.OnSerializeRead(serializeData[s] as Hashtable, originatingPlayer, remoteUpdateServerTimestamp, remoteLevelPrefix); } break; case PunEvent.Instantiation: this.DoInstantiate((Hashtable)photonEvent[ParameterCode.Data], originatingPlayer, null); break; case PunEvent.CloseConnection: // MasterClient "requests" a disconnection from us if (originatingPlayer == null || !originatingPlayer.isMasterClient) { Debug.LogError("Error: Someone else(" + originatingPlayer + ") then the masterserver requests a disconnect!"); } else { PhotonNetwork.LeaveRoom(); } break; case PunEvent.DestroyPlayer: Hashtable evData = (Hashtable)photonEvent[ParameterCode.Data]; int targetPlayerId = (int)evData[(byte)0]; if (targetPlayerId >= 0) { this.DestroyPlayerObjects(targetPlayerId, true); } else { if (this.DebugOut >= DebugLevel.INFO) Debug.Log("Ev DestroyAll! By PlayerId: " + actorNr); this.DestroyAll(true); } break; case PunEvent.Destroy: evData = (Hashtable)photonEvent[ParameterCode.Data]; int instantiationId = (int)evData[(byte)0]; // Debug.Log("Ev Destroy for viewId: " + instantiationId + " sent by owner: " + (instantiationId / PhotonNetwork.MAX_VIEW_IDS == actorNr) + " this client is owner: " + (instantiationId / PhotonNetwork.MAX_VIEW_IDS == this.mLocalActor.ID)); PhotonView pvToDestroy = null; if (this.photonViewList.TryGetValue(instantiationId, out pvToDestroy)) { this.RemoveInstantiatedGO(pvToDestroy.gameObject, true); } else { if (this.DebugOut >= DebugLevel.ERROR) Debug.LogError("Ev Destroy Failed. Could not find PhotonView with instantiationId " + instantiationId + ". Sent by actorNr: " + actorNr); } break; case PunEvent.AssignMaster: evData = (Hashtable)photonEvent[ParameterCode.Data]; int newMaster = (int)evData[(byte)1]; this.SetMasterClient(newMaster, false); break; default: if (photonEvent.Code < 200 && PhotonNetwork.OnEventCall != null) { object content = photonEvent[ParameterCode.Data]; PhotonNetwork.OnEventCall(photonEvent.Code, content, actorNr); } else { // actorNr might be null. it is fetched out of event on top of method // Hashtable eventContent = (Hashtable) photonEvent[ParameterCode.Data]; // this.mListener.customEventAction(actorNr, eventCode, eventContent); Debug.LogError("Error. Unhandled event: " + photonEvent); } break; } this.externalListener.OnEvent(photonEvent); }
/// <summary> /// 更新 /// </summary> /// <param name="entity">要更新的数据对象</param> /// <returns></returns> public bool Update(RoomInfo entity) { return(roomInfoDAL.Update(entity)); }
public static bool ValidateRoom(RoomInfo a) { return a.version <= bs.settings.mpVersion; }
public void UpdateUI(RoomInfo infos) { txtRoomName.text = infos.Name; txtRoomNbPlayers.text = string.Format("Players: {0}/{1}", infos.PlayerCount, infos.MaxPlayers); }