开始游戏按钮点击后干了什么
发表于2018-01-06
这篇文章给大家介绍下游戏运行的逻辑问题,例如玩家点击开始游戏按钮,游戏本身会做那些响应,一起来看看吧。
LoginWindow.cs
UIEventListener.Get(mPlaySubmitBtn.gameObject).onClick += OnPlaySubmit;
void OnPlaySubmit(GameObject go) { mWaitingParent.gameObject.SetActive(true); UIEventListener.Get(mPlaySubmitBtn.gameObject).onClick -= OnPlaySubmit; LoginCtrl.Instance.GamePlay(); }
LoginCtrl.cs
//开始游戏 public void GamePlay() { int index = SelectServerData.Instance.curSelectIndex; SelectServerData.ServerInfo info = SelectServerData.Instance.GetServerDicInfo().ElementAt(index).Value; NetworkManager.Instance.canReconnect = false; NetworkManager.Instance.Close(); NetworkManager.Instance.Init(info.addr, info.port, NetworkManager.ServerType.BalanceServer);//去连接选中的游戏服务器 PlayerPrefs.SetString(SelectServerData.serverKey, info.name); }
NetworkManager.cs
public void Init(string ip, Int32 port, ServerType type) { Debugger.Log("set network ip:" + ip + " port:" + port + " type:" + type); m_IP = ip; m_Port = port; serverType = type; m_n32ConnectTimes = 0; canReconnect = true; m_RecvPos = 0; #if UNITY_EDITOR mRecvOverDelayTime = 20000f; #endif }
public void OnConnected(object sender, EventArgs e) { switch (serverType) { case ServerType.BalanceServer: { CGLCtrl_GameLogic.Instance.BsOneClinetLogin(); //会执行这一行 } break; case ServerType.GateServer: { ++m_n32ConnectTimes; if (m_n32ConnectTimes > 1) { CGLCtrl_GameLogic.Instance.EmsgTocsAskReconnect(); } else { CGLCtrl_GameLogic.Instance.GameLogin(); } EventCenter.Broadcast(EGameEvent.eGameEvent_ConnectServerSuccess); } break; case ServerType.LoginServer: { CGLCtrl_GameLogic.Instance.EmsgToLs_AskLogin(); } break; } }
CGLCtrl_GameLogic.cs
public void BsOneClinetLogin() { GCToBS.OneClinetLogin pMsg = new GCToBS.OneClinetLogin() { uin = SelectServerData.Instance.serverUin, plat = (uint)SelectServerData.Instance.serverPlafrom, nsid = 0, login_success = 0, sessionid = SelectServerData.Instance.serverSionId }; //消息号:32770 NetworkManager.Instance.SendMsg(pMsg, (int)pMsg.msgnum); }
Int32 OnNet_OneClinetLoginCheckRet(Stream stream) { print ("OnNet_OneClinetLoginCheckRet"); BSToGC.ClinetLoginCheckRet pMsg = ProtoBuf.Serializer.Deserialize<BSToGC.ClinetLoginCheckRet>(stream); UInt32 loginSuccess = pMsg.login_success; if (loginSuccess != 1)//fail { LoginCtrl.Instance.LoginFail(); } return (Int32)EErrorCode.eNormal; }
Int32 OnNet_NotifyGateServerInfo(Stream stream) { print ("OnNet_NotifyGateServerInfo"); LoginCtrl.Instance.RecvGateServerInfo(stream); return (Int32)EErrorCode.eNormal; }
//接收GateServer信息 public void RecvGateServerInfo(Stream stream) { BSToGC.AskGateAddressRet pMsg = ProtoBuf.Serializer.Deserialize<BSToGC.AskGateAddressRet>(stream); SelectServerData.Instance.GateServerAdress = pMsg.ip; SelectServerData.Instance.GateServerPort = pMsg.port; Debug.Log (pMsg.token); SelectServerData.Instance.GateServerToken = pMsg.token; SelectServerData.Instance.SetGateServerUin(pMsg.user_name); NetworkManager.Instance.canReconnect = false; NetworkManager.Instance.Close(); NetworkManager.Instance.Init(pMsg.ip, pMsg.port, NetworkManager.ServerType.GateServer); EventCenter.Broadcast(EGameEvent.eGameEvent_LoginSuccess); //开始游戏按钮不能再点击 }
一旦连接上GateServer后做什么
public void OnConnected(object sender, EventArgs e) { switch (serverType) { case ServerType.BalanceServer: { CGLCtrl_GameLogic.Instance.BsOneClinetLogin(); } break; case ServerType.GateServer: { ++m_n32ConnectTimes; if (m_n32ConnectTimes > 1) { CGLCtrl_GameLogic.Instance.EmsgTocsAskReconnect(); } else { CGLCtrl_GameLogic.Instance.GameLogin(); } EventCenter.Broadcast(EGameEvent.eGameEvent_ConnectServerSuccess); //停止向当前连接发心跳 } break; case ServerType.LoginServer: { CGLCtrl_GameLogic.Instance.EmsgToLs_AskLogin(); } break; } }
public void GameLogin() { GCToCS.Login pMsg = new GCToCS.Login { sdk = (Int32)SdkManager.Instance.GetPlatFrom(), //ToReview 平台写死为10? #if UNITY_STANDALONE_WIN || UNITY_EDITOR || SKIP_SDK platform = 0, #elif UNITY_IPHONE platform = 1, #elif UNITY_ANDROID platform = 2, #endif equimentid = MacAddressIosAgent.GetMacAddressByDNet(), name = SelectServerData.Instance.gateServerUin, passwd = SelectServerData.Instance.GateServerToken, }; NetworkManager.Instance.SendMsg(pMsg, (int)pMsg.msgnum);
服务器响应处理
Int32 OnNetMsg_NotifyUserBaseInfo(System.IO.Stream stream) { print ("OnNetMsg_NotifyUserBaseInfo"); GSToGC.UserBaseInfo pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } UInt64 sGUID = pMsg.guid; if (pMsg.nickname.Count() > 1) //该玩家已经有呢称,直接进入游戏大厅 { GameUserModel.Instance.SetGameBaseInfo(pMsg); EventCenter.SendEvent(new CEvent(EGameEvent.eGameEvent_IntoLobby)); } else if (sGUID > 0) { //没有昵称,进入补充玩家信息界面 EventCenter.SendEvent(new CEvent(EGameEvent.eGameEvent_InputUserData)); } return (Int32)EErrorCode.eNormal; }
public void Enter() { SetStateTo(GameStateType.GS_Continue); //yaz修改 //mScenesRoot = GameObject.Instantiate(Resources.Load(GameConstDefine.GameLogin)) as GameObject; //mUIRoot = LoadUiResource.LoadRes(GameMethod.GetUiCamera.transform, GameConstDefine.LoadGameLoginUI); //AudioClip clip = Resources.Load(AudioDefine.PATH_UIBGSOUND) as AudioClip; ResourceUnit sceneRootUnit = ResourcesManager.Instance.loadImmediate(GameConstDefine.GameLogin, ResourceType.PREFAB); mScenesRoot = GameObject.Instantiate(sceneRootUnit.Asset) as GameObject; //mUIRoot = LoadUiResource.LoadRes(GameMethod.GetUiCamera.transform, GameConstDefine.LoadGameLoginUI); LoginCtrl.Instance.Enter(); ResourceUnit audioClipUnit = ResourcesManager.Instance.loadImmediate(AudioDefine.PATH_UIBGSOUND, ResourceType.ASSET); AudioClip clip = audioClipUnit.Asset as AudioClip; AudioManager.Instance.PlayBgAudio(clip); EventCenter.AddListener<CEvent>(EGameEvent.eGameEvent_InputUserData, OnEvent); //注册用户信息填写界面 EventCenter.AddListener<CEvent>(EGameEvent.eGameEvent_IntoLobby, OnEvent); EventCenter.AddListener(EGameEvent.eGameEvent_SdkLogOff, SdkLogOff); }
public void OnEvent(CEvent evt) { UIPlayMovie.PlayMovie("cg.mp4", Color.black, 2/* FullScreenMovieControlMode.Hidden*/, 3/*FullScreenMovieScalingMode.Fill*/); switch (evt.GetEventId()) { case EGameEvent.eGameEvent_InputUserData: SetStateTo(GameStateType.GS_User); break; case EGameEvent.eGameEvent_IntoLobby: GameStateManager.Instance.ChangeGameStateTo(GameStateType.GS_Lobby); break; } }
LoginState.cs中
public void SetStateTo(GameStateType gs) { stateTo = gs; }
GameStateManager.cs
public void Update(float fDeltaTime) //这一个函数会被逐帧调用 { GameStateType nextStateType = GameStateType.GS_Continue; if (currentState != null) { nextStateType = currentState.Update(fDeltaTime); } if (nextStateType > GameStateType.GS_Continue) { ChangeGameStateTo(nextStateType); } }
public void ChangeGameStateTo(GameStateType stateType) { if (currentState != null && currentState.GetStateType() != GameStateType.GS_Loading && currentState.GetStateType() == stateType) return; if (gameStates.ContainsKey(stateType)) { if (currentState != null) { currentState.Exit(); } currentState = gameStates[stateType]; currentState.Enter(); //切换状态 } }
UserState.cs脚本
public void Enter() { SetStateTo(GameStateType.GS_Continue); EventCenter.Broadcast(EGameEvent.eGameEvent_UserEnter); //关注这一行 //AudioClip clip = Resources.Load(AudioDefine.PATH_UIBGSOUND) as AudioClip; //AudioManager.Instance.PlayBgAudio(clip); ResourceUnit clipUnit = ResourcesManager.Instance.loadImmediate(AudioDefine.PATH_UIBGSOUND, ResourceType.ASSET); AudioClip clip = clipUnit.Asset as AudioClip; AudioManager.Instance.PlayBgAudio(clip); EventCenter.AddListener<CEvent>(EGameEvent.eGameEvent_IntoLobby, OnEvent); EventCenter.AddListener(EGameEvent.eGameEvent_SdkLogOff, SdkLogOff); }
UserInfoWindow.cs
////////////////////////////继承接口///////////////////////// //类对象初始化 public override void Init() { Debug.Log ("window :"+mResName); EventCenter.AddListener(EGameEvent.eGameEvent_UserEnter, Show); //关注这一行 EventCenter.AddListener(EGameEvent.eGameEvent_UserExit, Hide); }
//显示 public void Show() { if (mRoot == null) { if (Create()) { InitWidget(); } } if (mRoot && mRoot.gameObject.activeSelf == false) { mRoot.gameObject.SetActive(true); mVisible = true; OnEnable(); OnAddListener(); } }
//创建窗体 private bool Create() { if (mRoot) { Debug.LogError("Window Create Error Exist!"); return false; } if (mResName == null || mResName == "") { Debug.LogError("Window Create Error ResName is empty!"); return false; } if (GameMethod.GetUiCamera.transform== null) { Debug.LogError("Window Create Error GetUiCamera is empty! WindowName = " + mResName); return false; } GameObject obj = LoadUiResource.LoadRes(GameMethod.GetUiCamera.transform, mResName); if (obj == null) { Debug.LogError("Window Create Error LoadRes WindowName = " + mResName); return false; } mRoot = obj.transform; mRoot.gameObject.SetActive(false); return true; }
UserInfoWindow.cs脚本:
//窗口控件初始化 protected override void InitWidget() { spriteHead = mRoot.FindChild("Headselect/Background").GetComponent<UISprite>(); pass = mRoot.FindChild("Pass"); noPass = mRoot.FindChild("Nopass"); nickNameInput = mRoot.FindChild("Nickname").GetComponent<UIInput>(); Transform sexParent = mRoot.FindChild("Sex"); boySelect = mRoot.Find("Sex/Male").GetComponent<UIToggle>(); girlSelect = mRoot.Find("Sex/Female").GetComponent<UIToggle>(); boySelect.group = sexSelectGroup; girlSelect.group = sexSelectGroup; tip = mRoot.FindChild("Tips1").gameObject; labelTip = mRoot.FindChild("Tips1/Label").GetComponent<UILabel>(); labelTip2 = mRoot.FindChild("Tips2/Label").gameObject; view = mRoot.FindChild("Head"); selectObj = mRoot.FindChild("Head/Highlight").gameObject; arrowObj = mRoot.transform.FindChild("Head/Highlight/Arrow").gameObject; FindHeroHead(); CreateHead(); submitBtn = mRoot.FindChild("Commit").GetComponent<UIButton>(); submitBtn.isEnabled = false; scrollView = mRoot.FindChild("Head").GetComponent<UIScrollView>(); arrowLeftRight[0] = mRoot.FindChild("Arrow/Left"); arrowLeftRight[1] = mRoot.FindChild("Arrow/Right"); btnDice = mRoot.FindChild("RandomName").GetComponent<ButtonOnPress>(); UIEventListener.Get(scrollView.gameObject).onPress += OnPress; scrollView.onDragStarted += OnDragStart; UIEventListener.Get(nickNameInput.gameObject).onSelect += ResetDefaultInput; EventDelegate.Add(boySelect.onChange, SelectSex); EventDelegate.Add(girlSelect.onChange, SelectSex); /* * 当用户在选择了英雄的情况下,再去选择男女英雄时,清除之前的选中状态 * */ EventDelegate.Add(boySelect.onChange,ClearSelectStatue); EventDelegate.Add(girlSelect.onChange,ClearSelectStatue); for (int i = 0; i < headList.Count; i++) { headList.ElementAt(i).AddListener(i, SelectHead); } EventDelegate.Add(submitBtn.onClick, SubmitRegister); }
服务器接着又向客户端发送商城中商品信息:
/// <summary> /// 获得商城所要出售的商品的信息 /// </summary> /// <param name="stream"></param> /// <returns></returns> Int32 OnNetMsg_NotifyGoodsCfgInfo(Stream stream) { GSToGC.GoodsBuyCfgInfo pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } foreach (GSToGC.GoodsCfgInfo cfgInfo in pMsg.info) { int gsId = cfgInfo.goodid; if (GameDefine.GameConstDefine.IfHeroBuyCfg(gsId)) { if (ConfigReader.HeroBuyXmlInfoDict.ContainsKey(gsId)) { MarketHeroListModel.Instance.HeroListInfo(cfgInfo); //商品id和商品信息保存到一个字典中 } } else if (GameDefine.GameConstDefine.IfRuneBuyCfg(gsId)) { MarketRuneListModel.Instance.AddRuneCfgListInfo(cfgInfo); //符文和商品一起保存到字典中 } } return (Int32)EErrorCode.eNormal; }
紧接着,服务器就向客户端推送日常奖励信息:
Int32 OnNetMsg_NotifyCLdays(Stream stream) { GSToGC.NotifyUserCLDays pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } DailyBonusCtrl.Instance.SetDayAwards(pMsg.month, pMsg.today, pMsg.totalCldays, pMsg.cldays, pMsg.isTodayCan); return (Int32)EErrorCode.eNormal; }
接着服务器又向客户端推送信息,刷新帐号拥有的英雄信息数据
Int32 OnNetMsg_NotifyCSHeroList(Stream stream) { GSToGC.NotifyCSHeroList pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } foreach (GSToGC.NotifyCSHeroList.HeroListCfg hero in pMsg.herocfg) { CommodityInfos info = new CommodityInfos(); info.Expired_time = hero.expired_time; info.goodsId = (int)hero.heroid; info.If_free = hero.if_free; info.GoodsType = MarketGoodsType.GoodsTypeHero; if (ConfigReader.HeroBuyXmlInfoDict.ContainsKey(info.goodsId)) { GameUserCtrl.Instance.DeltGetHeroInfoData(info); } } return (Int32)EErrorCode.eNormal; }
接着,再向客户端发送如下信息:
Int32 OnNetMsg_NotifyRunesList(Stream stream) { GSToGC.NotifyRunesList pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } for (int i = 0; i < pMsg.runes_slot_info.Count; ++i) { GSToGC.RunesSlot sSlotInfo = pMsg.runes_slot_info[i]; RuneEquipModel.Instance.UpdateRuneSlotInfo(sSlotInfo.runeid, sSlotInfo.page, sSlotInfo.slotpos); } for (int i = 0; i < pMsg.runesbaginfo.Count; ++i) { GSToGC.RunesBagInfo sBagInfo = pMsg.runesbaginfo[i]; MarketRuneListCtrl.Instance.UpdateRuneBagInfo(sBagInfo.runeid, sBagInfo.num, sBagInfo.gottime); } return (Int32)EErrorCode.eNormal; }
Int32 OnNetMsg_NotifyOtherItemInfo(Stream stream) { GSToGC.NotifyOtherItemInfo pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } GoodsModel.Instance.AddOrChangeRuneBaptze(pMsg.item); return (Int32)EErrorCode.eNormal; }
接着服务器返回客户端 朋友列表和黑名单列表:
Int32 OnNetMsg_NotifyUserFriendsList(Stream stream) { GSToGC.NotifyUserSNSList pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } foreach (GSToGC.SNSInfo info in pMsg.info) { int headID = (int)info.headid; byte isOnLine = (byte)info.status; Friend friend = null; FRIENDTYPE type = (FRIENDTYPE)info.type; bool isFriend = true; if (type == FRIENDTYPE.FRIENDLIST) { isFriend = true; if (!FriendManager.Instance.AllFriends.TryGetValue(info.guididx, out friend)) { friend = new Friend(); friend.SetFriendInfo(info.guididx, info.nickname, headID, isOnLine == 1, info.viplv); FriendManager.Instance.AddFriend(info.guididx, friend); EventCenter.Broadcast<Friend>(EGameEvent.eGameEvent_CreateFriendPrefab, friend); } else { friend.SetFriendInfo(info.guididx, info.nickname, headID, isOnLine == 1, info.viplv); EventCenter.Broadcast(EGameEvent.eGameEvent_FriendChangeInfo, info.guididx); } } else if (type == FRIENDTYPE.BLACKLIST) { isFriend = false; if (!FriendManager.Instance.AllBlackDic.TryGetValue(info.guididx, out friend)) { friend = new Friend(); friend.SetFriendInfo(info.guididx, info.nickname, headID, false); FriendManager.Instance.AddOnLineBlackList(info.guididx, friend); EventCenter.Broadcast(EGameEvent.eGameEvent_CreateBlackPrefab); }//暂时先注掉。黑名单暂时无在线状态 //else //{ // friend.SetFriendInfo(info.guididx, info.nickname, headID, false); // EventCenter.Broadcast(EGameEvent.eGameEvent_FriendChangeInfo, info.guididx); //} } } return (Int32)EErrorCode.eNormal; }
服务器继续向客户端发送新手引导完成信息
/// <summary> /// 新手引导完成信息 /// </summary> /// <param name="stream"></param> /// <returns></returns> Int32 OnNetMsg_NotifyGuideResp(Stream stream) { GSToGC.GuideCSStepInfo pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } bool comp = pMsg.allcomp; UIGuideModel.Instance.mIsGuideComp = comp; if (!comp) { UIGuideCtrl.Instance.GuideRespStep(pMsg); } return (Int32)EErrorCode.eNormal; }
接着服务器继续向客户端推送 日常任务信息:
Int32 OnNetMsg_UpdateAllTask(Stream stream) { GSToGC.NotifyUpdateAllTask pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } DailyBonusCtrl.Instance.mDailyTaskDic.Clear(); DailyBonusCtrl.Instance.mInfiniteTaskDic.Clear(); foreach (GSToGC.TaskData one in pMsg.taskList) { STaskConfig taskConfig = null; taskConfig = ConfigReader.GetDailyTaskInfo(one.task_id); if (taskConfig != null) { CTask oneTask = new CTask(); oneTask.mGuid = one.task_guid; oneTask.mCurCount = one.task_curCount; oneTask.mConfig = taskConfig; if (oneTask.mCurCount == taskConfig.taskMaxCount) DailyBonusCtrl.Instance.mIsHadTaskFinished = true; DailyBonusCtrl.Instance.mDailyTaskDic.Add(oneTask.mGuid,oneTask); continue; } taskConfig = ConfigReader.GetInfiniteTaskInfo(one.task_id); if (taskConfig != null) { CTask oneTask = new CTask(); oneTask.mGuid = one.task_guid; oneTask.mCurCount = one.task_curCount; oneTask.mConfig = taskConfig; DailyBonusCtrl.Instance.mInfiniteTaskDic.Add(oneTask.mGuid, oneTask); continue; } } DailyBonusCtrl.Instance.mIsHadNewDailyTask = pMsg.IsHadNewDailyTask; EventCenter.Broadcast(EGameEvent.eGameEvent_NotifyAllTaskUpdate); return (Int32)EErrorCode.eNormal; }
此外,服务器一直在向客户端发送心跳:
Int32 OnNetMsg_NotifyPing(Stream stream) { print ("OnNetMsg_NotifyPing"); GSToGC.PingRet pMsg; if (!ProtoDes(out pMsg, stream)) { return PROTO_DESERIALIZE_ERROR; } Int64 n64NowTime = CGLCtrl_GameLogic.Instance.GetNowTime(); float ping = CGLCtrl_GameLogic.Instance.GetDuration(n64NowTime, pMsg.time); if (pMsg.flag == 0) { ShowFPS.Instance.cSPing = ping; } else { ShowFPS.Instance.sSPing = ping; CEvent eve = new CEvent(EGameEvent.eGameEvent_SSPingInfo); eve.AddParam("ping", ping); EventCenter.SendEvent(eve); } return (Int32)EErrorCode.eNormal; }