Пример #1
0
 // 分享回调
 void ShareResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
 {
     if (state == ResponseState.Success)
     {
         WarnDialog.showWarnDialog("share result :" + MiniJSON.jsonEncode(result));
         print("share result :");
         print(MiniJSON.jsonEncode(result));
     }
     else if (state == ResponseState.Fail)
     {
         StringBuilder sb = new StringBuilder();
         foreach (DictionaryEntry de in result)
         {
             sb.Append(string.Format("{0}-{1}", de.Key, de.Value));
         }
         WarnDialog.showWarnDialog("fail! error code = " + sb.ToString());
         print("fail! error code = " + result ["error_code"] + "; error msg = " + result ["error_msg"]);
     }
     else if (state == ResponseState.Cancel)
     {
         WarnDialog.showWarnDialog("cancel !");
         print("cancel !");
     }
     else
     {
         WarnDialog.showWarnDialog("state:" + state);
     }
 }
Пример #2
0
    void Awake()
    {
        close = transform.Find("Canvas/Panel/close").GetComponent <Button> ();
        close.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            canvas.SetActive(false);
        });
        ok = transform.Find("Canvas/Panel/ok").GetComponent <Button> ();
//		ok.onClick.AddListener (delegate() {
//			canvas.SetActive(false);
//		Sound.playSound(SoundType.Click);
//			if(okAction != null){
//				okAction.Invoke();
//			}
//		});
        text      = transform.Find("Canvas/Panel/text").GetComponent <Text> ();
        instance  = this;
        canvas    = transform.Find("Canvas").gameObject;
        panelTras = transform.Find("Canvas/Panel").GetComponent <RectTransform>();
        closeDialog(0);
        // reward相关
        rewardCanvas = transform.Find("reward").gameObject;
        rewardTitle  = transform.Find("reward/showItem/bg/title").GetComponent <Text> ();
        item1        = transform.Find("reward/showItem/bg/showItem1").gameObject;
        item2        = transform.Find("reward/showItem/bg/showItem2").gameObject;
        item3        = transform.Find("reward/showItem/bg/showItem3").gameObject;
        item4        = transform.Find("reward/showItem/bg/showItem4").gameObject;
        rewardBt     = transform.Find("reward/showItem/bg/ok").GetComponent <Button>();
        rewardBtText = transform.Find("reward/showItem/bg/ok/text").GetComponent <Text>();
    }
Пример #3
0
    public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    {
        string arg = string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason);

        WarnDialog.showWarnDialog(arg);
        // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing
        // this reason with the user to guide their troubleshooting actions.
        Debug.Log(arg);
    }
Пример #4
0
    void Update()
    {
        if (dialogQueue.Count > 0 && !canvas.activeSelf)
        {
            ok.onClick.RemoveAllListeners();
            lock (dialogQueue) {
                ok.transform.Find("Text").GetComponent <Text>().text = Message.getText("ok");
                WarnDialogInfo w = dialogQueue.Dequeue();
                showButton(true, w.hideClose?false:true);
                instance.text.text = w.text;
//				instance.okAction = w.okAction;

                ok.onClick.AddListener(delegate() {
                    Sound.playSound(SoundType.Click);
                    canvas.SetActive(false);
                    if (w.okAction != null)
                    {
                        w.okAction.Invoke();
                    }
                });
                panelTras.localPosition = new Vector3(w.deltaX, w.deltaY, 0);
                openDialog();
                w.state = DialogState.Showing;
            }
        }
        if (waitDialogQueue.Count > 0 && !canvas.activeSelf)
        {
            ok.onClick.RemoveAllListeners();
            lock (waitDialogQueue) {
                ok.transform.Find("Text").GetComponent <Text>().text = Message.getText("cancel");
                showButton(true, false);
                WaitDialogInfo w = waitDialogQueue.Dequeue();
                if (w.state == DialogState.Cancel)
                {
                    return;
                }
                instance.text.text = w.text;
//				instance.okAction = w.afterWaitAction;

                ok.onClick.AddListener(delegate() {
                    Sound.playSound(SoundType.Click);
                    WarnDialog.closeWaitDialog(w.id);
                    if (w.cancelAction != null)
                    {
                        w.cancelAction.Invoke();
                    }
                });

                openDialog();
                w.state = DialogState.Showing;
                Job.startJob(new MyDelegate(afterWait), w.time, w);
            }
        }
    }
Пример #5
0
 private static void resoveSCException(SCException exception)
 {
     // 有些exception不弹窗,不报警
     if (exception.ErrCode == ErrorCode.RoomNotExist)
     {
         return;
     }
     Debug.LogError("error:errorCode = " + exception.ErrCode + ",errorMsg = " + exception.ErrMsg + ",csOpcode:" + exception.CsOpcode + ",scOpcode:" + exception.ScOpcode);
     WarnDialog.showWarnDialog(/*Message.getText("dataError")+*/ exception.ErrMsg, delegate() {
         //				ConnectServer();
     });
 }
Пример #6
0
    // 买完回调
    public void buyFinish(bool success, int shopType, int id, int num, int gold)
    {
        if (!success)
        {
            WarnDialog.showWarnDialog(Message.getText("buyFail"));
            return;
        }
        Params.gold   = gold;
        goldText.text = Params.gold.ToString();

//		WarnDialog.showWarnDialog("buy success,type = "+shopType+",itemId = "+id+",num = "+num);

        show.SetActive(true);

        ShopType type = (ShopType)shopType;

        if (type == ShopType.Item)         // 道具用的时候是实时获得的,所以,啥都不做
        {
            showItemByCount(1);
            showIn(id, num, 0);
        }
        else if (type == ShopType.Unit)          // 道具用的时候是实时获得的,所以,啥都不做
        {
            UnitTable unitTable = Params.unitTables[id];
            showItemByCount(unitTable.Items.Count);
            int index = 0;
            foreach (KeyValuePair <int, int> kv in unitTable.Items)
            {
                showIn(kv.Key, kv.Value * num, index++);
            }
        }
        else if (type == ShopType.Peck)          //
        {
            PeckTable peckTable = Params.peckTables[id];
            if (peckTable.gold > 0)
            {
                Sprite sp = ShopItem.getGoldSprite();
                showItemImage[0].sprite = sp;
                showItemText [0].text   = "x" + (peckTable.gold * num);
            }

            int index = peckTable.gold > 0?1:0;
            foreach (KeyValuePair <int, int> kv in peckTable.Items)
            {
                showIn(kv.Key, kv.Value * num, index++);
            }
            showItemByCount(index);
        }
    }
Пример #7
0
    // Use this for initialization

    void Start()
    {
        CSUserInfo userInfo = new CSUserInfo();

        SocketManager.SendMessageAsyc((int)AccountOpcode.CSUserInfo, CSUserInfo.SerializeToBytes(userInfo), delegate(int opcode, byte[] data){
            SCUserInfo ret = SCUserInfo.Deserialize(data);
            oldIcon        = ret.Icon;
            oldName        = ret.Name;
            this.id        = ret.Id;
            //
            showIcon(oldIcon, oldName);
        });

        for (int i = 0; i < icons.Length; i++)
        {
            GameObject go = icons[i];
            // 图片,按钮
            Button bt = go.GetComponent <Button>();
            bt.onClick.AddListener(delegate {
                string iconName = icons[i].transform.Find("iconName").GetComponent <Text>().text;
                showIcon(iconValues[i], iconName);
            });
        }

        changeNameButton.onClick.AddListener(delegate {
            if (oldName.Equals(nameText.text) && oldIcon.Equals(iconValue))
            {
                WarnDialog.showWarnDialog("qing shu ru mingzi ");
            }
            else if (nameText.text.Length == 0 && iconValue == null)
            {
            }
            else
            {
                if (nameText.text.Length > 50)
                {
                    WarnDialog.showWarnDialog("too long");
                    return;
                }
                //WarnDialog.showWarnDialog(text.text);
                CSChangeUserInfo changeUserInfo = new CSChangeUserInfo();
                changeUserInfo.Name             = nameText.text;
                changeUserInfo.Icon             = iconValue;
                SocketManager.SendMessageAsyc((int)AccountOpcode.CSChangeUserInfo, CSChangeUserInfo.SerializeToBytes(changeUserInfo), delegate(int opcode, byte[] data){
                });
            }
        });
    }
Пример #8
0
 // Update is called once per frame
 void Update()
 {
     if (isMatching)
     {
         currentTime += Time.deltaTime;
         if (currentTime >= maxTime)
         {
             WarnDialog.showWarnDialog(Message.getText("matchingFailWarning"));
             cancelMatching();
         }
         else
         {
             timeText.text = (int)currentTime + "s";
         }
     }
 }
Пример #9
0
 public void buyBack(string id, bool success, string token)
 {
     if (success)
     {
         // 请求发货
         CSMoneyBuy moneyBuy = new CSMoneyBuy();
         moneyBuy.Id    = int.Parse(id);
         moneyBuy.Num   = int.Parse(showNum.text);
         moneyBuy.Token = token;//System.DateTime.Now.Ticks.ToString();
         SocketManager.SendMessageAsyc((int)MiGongOpcode.CSMoneyBuy, CSMoneyBuy.SerializeToBytes(moneyBuy), delegate(int opcode2, byte[] data2) {
             SCMoneyBuy ret2 = SCMoneyBuy.Deserialize(data2);
             shop.buyFinish(ret2.Success > 0, (int)type, int.Parse(id), int.Parse(showNum.text), ret2.Gold);
         });
     }
     else
     {
         WarnDialog.showWarnDialog(Message.getText("buyFail"));
     }
 }
Пример #10
0
    /// <summary>
    /// 连接指定IP和端口的服务器
    /// </summary>
    /// <param name="ip"></param>
    /// <param name="port"></param>
    private static bool ConnectServer()
    {
        bool   ret  = false;
        string ip   = SocketManager.ip;
        int    port = SocketManager.port;

        if (clientSocket == null)
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
        else
        {
            clientSocket.Close();
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
        IPAddress  mIp          = IPAddress.Parse(ip);
        IPEndPoint ip_end_point = new IPEndPoint(mIp, port);

        clientSocket.SendTimeout = 2000;
//		clientSocket.ReceiveTimeout = 10000; // TODO 加上这个会有问题,是谁没有正确放回呀?难道是因为网络线程是阻塞的,这个阻塞最多等待 ReceiveTimeout秒?
        clientSocket.SendBufferSize    = 81920;
        clientSocket.ReceiveBufferSize = 81920;
        try {
            clientSocket.Connect(ip_end_point);
            ret = true;
            Debug.Log("连接服务器成功");
        } catch (Exception e) {
            ret = false;
            Debug.Log("连接服务器失败" + e);
            WarnDialog.showWarnDialog(Message.getText("connectServerFail"), delegate() {
//				ConnectServer();
            });
            return(ret);
        }
        if (ret)
        {
            Thread receiveThread = new Thread(new ThreadStart(_onReceiveSocket));
            receiveThread.IsBackground = true;
            receiveThread.Start();
        }
        return(ret);
    }
Пример #11
0
    //购买商品调用的方法
    public void BuyProductID(string productId)
    {
        // If Purchasing has been initialized ...
        if (IsInitialized())
        {
            // ... look up the Product reference with the general product identifier and the Purchasing
            // system's products collection.
            Product product = m_StoreController.products.WithID(productId);

            // If the look up found a product for this device's store and that product is ready to be sold ...
            if (product != null && product.availableToPurchase)
            {
                Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));
                // ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed
                // asynchronously.
                m_StoreController.InitiatePurchase(product);
                //m_StoreController.
                //m_StoreController.
                //product.a
            }
            // Otherwise ...
            else
            {
                // ... report the product look-up failure situation
                Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
                WarnDialog.showWarnDialog("BuyProductID FAIL. Not initialized.");
            }
        }
        // Otherwise ...
        else
        {
            // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or
            // retrying initiailization.
            WarnDialog.showWarnDialog("BuyProductID FAIL. Not initialized.");
            Debug.Log("BuyProductID FAIL. Not initialized.");
        }
    }
Пример #12
0
    /**
     * if (length < 12)
     *                  {
     *                      continue;
     *                  }
     *
     *                  if (!isReadHead)
     *                  {
     *                      size = buf.ReadInt();
     *                      opcode = buf.ReadInt();
     *                      id = buf.ReadInt();
     *                      Debug.Log("size:" + size + ",opcode:" + opcode + ",id:" + id);
     *                      isReadHead = true;
     *                      if (size > length - 12)
     *                      {
     *                          continue;
     *                      }
     *                  }
     *                  if (size > length - 12)
     *                  {
     *                      continue;
     *                  }
     *                  Debug.Log(length + "------" + size);
     *                  if (length - size > 12)
     *                  {
     *                      Debug.Log("warn:--------------------------" + length + "------" + size);
     *                  }
     *                  byte[] data = new byte[size];
     *                  buf.ReadBytes(data, 0, size);
     *                  //buf.Clear();
     *                  buf.DiscardReadBytes();
     *                  isReadHead = false;
     *                  length = buf.ReadableBytes();
     *                  doReceivePacket(opcode, id, data);
     */

    /// <summary>
    /// 接受网络数据
    /// </summary>
    private static void _onReceiveSocket()
    {
        byte[]     _tmpReceiveBuff = new byte[1024];
        ByteBuffer buf             = ByteBuffer.Allocate(10240);
        int        length          = 0;
        bool       isReadHead      = false;

        int size = 0;
        //
        int opcode = 0;
        int id     = 0;

        while (true)
        {
            if (!clientSocket.Connected)
            {
                //				_isConnected = false;
                //				_ReConnect();

                break;
            }
            try
            {
                int receiveLength = clientSocket.Receive(_tmpReceiveBuff);
                if (receiveLength > 0)
                {
                    buf.WriteBytes(_tmpReceiveBuff, 0, receiveLength);
                    length += receiveLength;
                    while (true)
                    {
                        if (length < 12)
                        {
                            break;
                        }

                        if (!isReadHead)
                        {
                            size       = buf.ReadInt();
                            opcode     = buf.ReadInt();
                            id         = buf.ReadInt();
                            isReadHead = true;
                            if (size > length - 12)
                            {
                                break;
                            }
                        }
                        if (size > length - 12)
                        {
                            break;
                        }
                        //Debug.Log("size:" + size + ",opcode:" + opcode + ",id:" + id+","+length + "------" + size);
                        if (length - size > 12)
                        {
                            Debug.Log("warn:--------------------------" + length + "------" + size);
                        }
                        byte[] data = new byte[size];
                        buf.ReadBytes(data, 0, size);
                        doReceivePacket(opcode, id, data);
                        // 下一个做准备
                        if (length - size - 12 != buf.ReadableBytes())
                        {
                            Debug.LogError("hai xu yao yan jiu yan jiu a ! buf.ReadableBytes() = " + buf.ReadableBytes());
                        }

                        if (size == length - 12)
                        {
                            buf.Clear();
                            length = 0;
                        }
                        else
                        {
                            buf.DiscardReadBytes();
                            //length = length - 12 - size;//buf.ReadableBytes();
                            length = buf.ReadableBytes();
                        }
                        isReadHead = false;
                    }
                }
            }
            catch (System.Exception e)
            {
                WarnDialog.showWarnDialog(Message.getText("connectServerFail"), delegate() {
//									ConnectServer();
                });
                Debug.Log("e:" + e);
                IsConnected  = false;
                IsConnecting = false;
                clientSocket.Disconnect(true);
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
                break;
            }
        }
    }
Пример #13
0
    IEnumerator PostReq()
    {
        Dictionary <string, string> headers = new Dictionary <string, string> ();

        headers.Add("opcode", (int)AccountOpcode.CSGetLoginInfo + "");
        headers.Add("localization", localization);
        CSGetLoginInfo loginInfo = new CSGetLoginInfo();

        NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface ni in nis)
        {
//			Debug.Log ("Name = " + ni.Name );
//			Debug.Log ("Description = " + ni.Description );
//			Debug.Log ("NetworkInterfaceType = " + ni.NetworkInterfaceType.ToString() );
//			Debug.Log ("Mac地址 = " + ni.GetPhysicalAddress().ToString() );  /// Ethernet 6C0B8490F3B5
            if ("Ethernet".Equals(ni.NetworkInterfaceType.ToString()))
            {
                loginInfo.DeviceId = "mac-" + ni.GetPhysicalAddress().ToString();
                break;
            }
        }
        if (loginInfo.DeviceId == null || loginInfo.DeviceId == "")
        {
            loginInfo.DeviceId = SystemInfo.deviceUniqueIdentifier;
        }
        if (loginInfo.DeviceId == null || loginInfo.DeviceId == "")
        {
            WarnDialog.showWarnDialog("can not get device id");
            yield return(0.1f);
        }
        Debug.Log("loginInfo.DeviceId = " + loginInfo.DeviceId);
        //		loginInfo.DeviceId = "shdfshksshfkk";
        //		WWW getData = new WWW("http://10.1.6.254:8083",CSGetLoginInfo.SerializeToBytes(loginInfo),headers);
        //		yield return getData;

        //		if(getData.error!= null){
        //			Debug.Log (getData.error);
        //			WarnDialog.showWarnDialog ("get server info fail !",null);
        //		}else{
        //			SCGetLoginInfo ret = SCGetLoginInfo.Deserialize (getData.bytes);
        //			serverId = ret.ServerId;
        //			accountId = ret.AccountId;
        //			ip = ret.Ip;
        //			port = ret.Port;
        //
        //			PlayerPrefs.SetInt (SERVER_ID_KEY,serverId);
        //			PlayerPrefs.SetString (SERVER_IP_KEY,ip);
        //			PlayerPrefs.SetInt (SERVER_PORT_KEY,port);
        //			PlayerPrefs.SetString (ACCOUNT_KEY,accountId);
        //			PlayerPrefs.Save ();
        //
        //			ConnectServerAndLogin ();
        //
        //			Debug.Log ("accountId = " + ret.AccountId);
        //			Debug.Log ("serverId = " + ret.ServerId);
        //			Debug.Log ("ip = " + ret.Ip);
        //			Debug.Log ("port = " + ret.Port);
        //		}
        //
//        string url = "http://127.0.0.1:8083";
        //		string url = "http://10.1.6.254:8083";
        //		string url = "http://111.230.144.111:8083";  // 腾讯云
        string          url     = "http://47.95.219.97:8083"; // 阿里云
        UnityWebRequest request = new UnityWebRequest(url, "POST");

        byte[] postBytes = CSGetLoginInfo.SerializeToBytes(loginInfo);
        Debug.Log(postBytes.Length);
        request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(postBytes);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        request.SetRequestHeader("opcode", (int)AccountOpcode.CSGetLoginInfo + "");
        //request.SetRequestHeader("Content-Length", ""+postBytes.Length);
        // 防止系统给出的request.getContentLength() = -1
        request.SetRequestHeader("contentLength", "" + postBytes.Length);
        yield return(request.Send());//.SendWebRequest();

        Debug.Log(request.uploadedBytes);
        if (request.responseCode == 200)
        {
            SCGetLoginInfo ret = SCGetLoginInfo.Deserialize(request.downloadHandler.data);
            serverId  = ret.ServerId;
            accountId = ret.AccountId;
            ip        = ret.Ip;
            port      = ret.Port;
            switch (ret.ServerState)
            {
            case 0: break;

            case 1:
                WarnDialog.showWarnDialog("服务器正在维护");
                break;
            }

            PlayerPrefs.SetInt(SERVER_ID_KEY, serverId);
            PlayerPrefs.SetString(SERVER_IP_KEY, ip);
            PlayerPrefs.SetInt(SERVER_PORT_KEY, port);
            PlayerPrefs.SetString(ACCOUNT_KEY, accountId);
            PlayerPrefs.Save();
            ConnectServerAndLogin();
//			Debug.Log ("accountId = " + ret.AccountId);
//			Debug.Log ("serverId = " + ret.ServerId);
//			Debug.Log ("ip = " + ret.Ip);
//			Debug.Log ("port = " + ret.Port);
        }
        else
        {
            Debug.Log("request.responseCode = " + request.responseCode);
            WarnDialog.showWarnDialog(Message.getText("getServerInfoFail"), null);
        }
    }
Пример #14
0
    // Use this for initialization
    void Start()
    {
        // 设置button
        closeButton.onClick.AddListener(delegate {
            Sound.playSound(SoundType.Click);
            WarnDialog.showWarnDialog(Message.getText("exit?"), delegate {
                selfArrive(false, null, false);
                Destroy(transform.parent.parent.gameObject);
                GameObject mainGo   = GameObject.Find("main");
                MainPanel mainPanel = mainGo.GetComponent <MainPanel>();
                mainPanel.showUi(this.Mode);
            });
        });
        okButton.onClick.AddListener(delegate {
            Sound.playSound(SoundType.Click);
            Destroy(transform.parent.parent.gameObject);
            GameObject mainGo   = GameObject.Find("main");
            MainPanel mainPanel = mainGo.GetComponent <MainPanel>();
            mainPanel.showUi(this.Mode);
        });
        // 0.21 碰撞体的宽,1.9碰撞体的长
        wallWidth = 0.13f * myScale;
        nodeX     = 1.9f * myScale - wallWidth * 2; nodeY = 1.9f * myScale - wallWidth * 2;

        // 显示当前的道具数量
        showSkillCountAndAddClick("addSpeed", ItemType.AddSpeed);
        showSkillCountAndAddClick("addTime", ItemType.AddTime);
        showSkillCountAndAddClick("mulBean", ItemType.MulBean);
        showSkillCountAndAddClick("showRoute", ItemType.ShowRoute);
        //
        if (Mode == MapMode.Online)
        {
            // 屏蔽
            starSlider.transform.parent.gameObject.SetActive(false);
            transform.parent.parent.Find("Canvas/skills").gameObject.SetActive(false);
            transform.parent.parent.Find("Canvas/score").gameObject.SetActive(false);
            // time居中
            Vector3 old = transform.parent.parent.Find("Canvas/time").localPosition;
            transform.parent.parent.Find("Canvas/time").localPosition = new Vector3(0, old.y, old.z);
            //
            foreach (KeyValuePair <string, Pacman> kv in pacmanMap)
            {
                int       x = kv.Value.inX;
                int       y = kv.Value.inY;
                Transform scoreShowtransform = null;
                if (x < 2 && y < 2)
                {
                    scoreShowtransform = transform.parent.parent.Find("Canvas/onlineScoreShow/blue");
                }
                else if (y > 2 && x < 2)
                {
                    scoreShowtransform = transform.parent.parent.Find("Canvas/onlineScoreShow/green");
                }
                else if (y > 2 && x > 2)
                {
                    scoreShowtransform = transform.parent.parent.Find("Canvas/onlineScoreShow/red");
                }
                else if (x > 2 && y < 2)
                {
                    scoreShowtransform = transform.parent.parent.Find("Canvas/onlineScoreShow/yellow");
                }
                scoreShowtransform.gameObject.SetActive(true);
                scoreText.Add(kv.Key, scoreShowtransform.Find("Text").GetComponent <Text>());
            }

            //
            SocketManager.AddServerSendReceive((int)MiGongOpcode.SCSendEatBean, delegate(int opcode, byte[] data) {
                SCSendEatBean ret = SCSendEatBean.Deserialize(data);
                foreach (PBEatBeanInfo bean in ret.Beans)
                {
                    _checkEatBean(bean.UserId, bean.BeanPos);                    // 谁吃的
                }
            });
        }
        // 注册玩家到达的信息
        SocketManager.AddServerSendReceive((int)MiGongOpcode.SCUserArrived, userArrived);
        SocketManager.AddServerSendReceive((int)MiGongOpcode.SCGameOver, doGameOver);

        // 联网模式
        SocketManager.AddServerSendReceive((int)MiGongOpcode.SCUserMove, userMoveAction);

        currentTime = totalTime;

        createMap();
    }
Пример #15
0
    void Start()
    {
        show(uiMain);
        // 给主界面按钮加事件
        string canvasPath = "main/ui/uiMain/Canvas/buttons/";

        levelButton = GameObject.Find(canvasPath + "level2").GetComponent <Button>();
        levelButton.onClick.AddListener(delegate() {
            // 打开level 界面
//			Debug.Log("open level window");
            Sound.playSound(SoundType.Click);
            openLevelWindow();
        });
        unlimitButton = GameObject.Find(canvasPath + "unlimit2").GetComponent <Button>();
        unlimitButton.onClick.AddListener(delegate() {
            // 打开unlimit 界面
            Debug.Log("open unlimit window");
            Sound.playSound(SoundType.Click);
            openUnlimitWindow();
        });
        onlineButton = GameObject.Find(canvasPath + "online2").GetComponent <Button>();
        onlineButton.onClick.AddListener(delegate() {
            //Job.startJob(Params.energyJobKey, delegate() {
            //	Debug.Log("sdfsdfsdfs");
            //},10);
            // 打开online 界面
            Debug.Log("open online window");
            Sound.playSound(SoundType.Click);
            openOnlineWindow();
        });
        // uiLevel 关闭按钮
        GameObject closeGo     = GameObject.Find("main/ui/uiLevel/Canvas/close");
        Button     closeButton = closeGo.GetComponent <Button> ();

        closeButton.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            show(uiMain);
        });
        // uiUnlimit 关闭按钮和进入按钮
        Button go = GameObject.Find("main/ui/uiUnlimit/Canvas/go").GetComponent <Button>();

        go.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            CSUnlimitedGo unlimitedGo = new CSUnlimitedGo();
            SocketManager.SendMessageAsyc((int)MiGongOpcode.CSUnlimitedGo, CSUnlimitedGo.SerializeToBytes(unlimitedGo), delegate(int opcode, byte[] data) {
                ui.SetActive(false);
                SCUnlimitedGo ret = SCUnlimitedGo.Deserialize(data);
                // 剩余精力
                Params.startEnergySchedule(ret.Energy.Energy, ret.Energy.RefreshTime);
                int[] stars = { ret.Star1, ret.Star2, ret.Star3, ret.Star4 };
                createMap(MapMode.Unlimited, ret.Map.ToArray(), ret.Beans, ret.Time, ret.Speed, ret.Start, ret.End, ret.Pass, ret.EnemyCount, null, stars, null, null);
            });
        });
        closeButton = GameObject.Find("main/ui/uiUnlimit/Canvas/close").GetComponent <Button>();
        closeButton.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            show(uiMain);
        });
        // uiOnline 关闭按钮和进入按钮
        go = GameObject.Find("main/ui/uiOnline/Canvas/go").GetComponent <Button>();
        go.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            OnPvpClick();
        });
        closeButton = GameObject.Find("main/ui/uiOnline/Canvas/close").GetComponent <Button>();
        closeButton.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            show(uiMain);
        });
        // 获取登陆基本信息
        CSBaseInfo baseInfo = new CSBaseInfo();

        SocketManager.SendMessageAsyc((int)MiGongOpcode.CSBaseInfo, CSBaseInfo.SerializeToBytes(baseInfo), delegate(int opcode, byte[] data) {
            SCBaseInfo ret = SCBaseInfo.Deserialize(data);
            // TODO 显示精力
            // 系统参数
            foreach (PBSysPara sp in ret.SysParas)
            {
                sysParas.Add(sp.Key, sp.Value);
            }
            Params.sysParas = sysParas;

            Params.energyRecoverTime = int.Parse(sysParas["energyRecoverTime"]);
            // 精力相关
            Params.startEnergySchedule(ret.Energy.Energy, ret.Energy.RefreshTime);

            foreach (PBNewGuide newGuide in ret.NewGuide)
            {
                guideStep.Add(newGuide.Id, newGuide.Step);
            }
            this.openPass = ret.OpenPass;
            // 道具表
            Params.init(ret);
            // 无尽版和pvp是否开启
            doShowLock();
            // 初始化无尽版的每日星数奖励
            //string para = sysParas["unlimitedAwardStar"];
            //string[] paras = para.Split(';');
            Slider slider       = unlimitedAwardGo.transform.Find("starSlider").GetComponent <Slider>();
            RectTransform buRec = unlimitedAwardGo.transform.Find("starSlider").GetComponent <RectTransform> ();
            int len             = ret.UnlimitedRewardTable.Count;
            slider.maxValue     = ret.UnlimitedRewardTable[len - 1].Star;
            Object ob           = Resources.Load("chest");

            unlimitedAwardSegs = new UnlimitedAwardSeg[len];
            for (int i = 0; i < len; i++)
            {
                GameObject chestGo = Instantiate(ob) as GameObject;
                chestGo.transform.localPosition = new Vector3(
                    buRec.rect.width / slider.maxValue * ret.UnlimitedRewardTable[i].Star - buRec.rect.width / 2, 0, 0);
                chestGo.transform.SetParent(unlimitedAwardGo.transform, false);
                UnlimitedAwardSeg unlimitedAward = unlimitedAwardSegs[i] = new UnlimitedAwardSeg();
                unlimitedAward.star          = ret.UnlimitedRewardTable[i].Star;
                unlimitedAward.image         = chestGo.GetComponent <Image>();
                Button bt                    = chestGo.GetComponent <Button>();
                int index                    = i;
                PBUnlimitedRewardTable table = ret.UnlimitedRewardTable[i];
                bt.onClick.AddListener(delegate
                {
                    Sound.playSound(SoundType.Click);
                    // 如果达到了,就直接领取了,然后就是确定,否则就是显示,然后是确定
                    if (unlimitedAward.state == 1)
                    {
                        // 领取
                        Sound.playSound(SoundType.Click);
                        CSUnlimitedAward award = new CSUnlimitedAward();
                        award.Index            = index;
                        SocketManager.SendMessageAsyc((int)MiGongOpcode.CSUnlimitedAward, CSUnlimitedAward.SerializeToBytes(award), (opcode2, data2) => {
                            SCUnlimitedAward retAward   = SCUnlimitedAward.Deserialize(data2);
                            unlimitedAward.image.sprite = SpriteCache.getSprite("box/open");
                            unlimitedAward.state        = 2;
                            // 显示
                            WarnDialog.reward(Message.getText("gainReward"), Message.getText("ok"), table.Gold, table.Reward, null);
                        });
                    }
                    else
                    {
                        // 显示
                        WarnDialog.reward(Message.getText("dailyReward"), Message.getText("ok"), table.Gold, table.Reward, null);
                    }
                });
            }
        });

        // 账号,分享,帮助

        Button accountButton = GameObject.Find(canvasPath + "more/account").GetComponent <Button>();

        accountButton.onClick.AddListener(delegate() {
            Debug.Log("account");
            Sound.playSound(SoundType.Click);
            closeMorePanel();
            doAccount();
        });
        ssdk.showUserHandler = GetUserInfoResultHandler;
        Button shareButton = GameObject.Find(canvasPath + "more/share").GetComponent <Button>();

        shareButton.onClick.AddListener(delegate() {
            Debug.Log("share");
//			doShare();
            Sound.playSound(SoundType.Click);
            closeMorePanel();
            shareWeChat1.transform.parent.gameObject.SetActive(true);
        });
        ssdk.shareHandler = ShareResultHandler;
        // 分享的三个按钮就
        shareWeChat1.onClick.AddListener(delegate() {
            Debug.Log("share WeChat");
            Sound.playSound(SoundType.Click);
            doShare(PlatformType.WeChat);
        });
        shareWeChat2.onClick.AddListener(delegate() {
            Debug.Log("share WeChatMoments");
            Sound.playSound(SoundType.Click);
            doShare(PlatformType.WeChatMoments);
        });
        closeShare.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            shareWeChat1.transform.parent.gameObject.SetActive(false);
        });

        exit.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            Application.Quit();
        });

        // show more
        Button moreButton = GameObject.Find(canvasPath + "moreBt").GetComponent <Button>();

        moreButton.onClick.AddListener(delegate() {
            GameObject moreGo = GameObject.Find(canvasPath + "more");
            moreGo.SetActive(!moreGo.activeSelf);
        });
        // hide more
        Button hideMoreButton = GameObject.Find(canvasPath + "more/clickPanel").GetComponent <Button>();

        hideMoreButton.onClick.AddListener(delegate() {
            closeMorePanel();
        });
        //
        Button helpButton = GameObject.Find(canvasPath + "more/help").GetComponent <Button>();

        helpButton.onClick.AddListener(delegate() {
            Debug.Log("help");
//			WarnDialog.showWarnDialog("test",null,false,10,20);
            Sound.playSound(SoundType.Click);
            closeMorePanel();
            Help guideControl = uiHelp.GetComponent <Help>();
            guideControl.showHelp();
        });

        // 背包,商店
        Button packetButton = GameObject.Find(canvasPath + "packet").GetComponent <Button>();

        packetButton.onClick.AddListener(delegate() {
            Debug.Log("backet");
            Sound.playSound(SoundType.Click);
            uiPacket.GetComponent <Packet>().showPacket();
        });
        Button shopButton = GameObject.Find(canvasPath + "shop").GetComponent <Button>();

        shopButton.onClick.AddListener(delegate() {
            Debug.Log("shop");
            Sound.playSound(SoundType.Click);
            uiShop.GetComponent <Shop>().showShop();
        });

        // 对战中显示奖励界面的进入地图按钮
        Button showRewardOk = uiLevel.transform.Find("Canvas/showReward/dialog/ok").GetComponent <Button>();

        showRewardOk.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            onIntoPassClick();
        });
        Button showRewardClose = uiLevel.transform.Find("Canvas/showReward/dialog/close").GetComponent <Button>();

        showRewardClose.onClick.AddListener(delegate() {
            Sound.playSound(SoundType.Click);
            uiLevel.transform.Find("Canvas/showReward").gameObject.SetActive(false);
        });

        // 联网对战按钮
        //
        SocketManager.AddServerSendReceive((int)MiGongOpcode.SCMatchingSuccess, matchSuccess);
        SocketManager.AddServerSendReceive((int)MiGongOpcode.SCMatchingFail, delegate(int opcode, byte[] receiveData) {
            Debug.Log("");
            matching.matchFail();
        });
        SocketManager.AddServerSendReceive((int)MiGongOpcode.SCBegin, delegate(int opcode, byte[] receiveData) {
            Debug.Log("");
        });
        SocketManager.AddServerSendReceive((int)AccountOpcode.SCBeTakePlace, delegate(int opcode, byte[] receiveData) {
            WarnDialog.showWarnDialog("你的账号在其它地方登录!", delegate() {
                Application.Quit();
            }, true);
        });
    }
Пример #16
0
    private void openLevelWindow()
    {
        show(uiLevel);
        //



        GameObject content = GameObject.Find("main/ui/uiLevel/Canvas/scrollView/Viewport/Content");

        for (int i = 0; i < content.transform.childCount; i++)
        {
            Destroy(content.transform.GetChild(i).gameObject);
        }
        // 获取当前关卡
        CSGetMiGongLevel getMiGongLevel = new CSGetMiGongLevel();

        Debug.Log("send getMiGongLevel:");
        SocketManager.SendMessageAsyc((int)MiGongOpcode.CSGetMiGongLevel, CSGetMiGongLevel.SerializeToBytes(getMiGongLevel), delegate(int opcode, byte[] data) {
            Debug.Log("receive SCGetMiGongLevel:");
            SCGetMiGongLevel level = SCGetMiGongLevel.Deserialize(data);
            int count = level.PassCount;
            // 体力
            //GameObject energyTextGo = GameObject.Find ("main/ui/uiLevel/Canvas/energy/Text");
            //Text energyText = energyTextGo.GetComponent<Text>();
            //energyText.text = Params.energy.ToString();

            //获取游戏对象
            Object levelItem = Resources.Load("levelItem");

            GameObject up       = Instantiate(levelItem) as GameObject;
            RectTransform buRec = up.GetComponent <RectTransform> ();
            Destroy(up);

            Debug.Log("count:" + count);

            RectTransform canvas = GameObject.Find("main/ui/uiLevel/Canvas").GetComponent <RectTransform>();
            float scale          = canvas.rect.width / Params.uiWidth;
            float be             = (canvas.rect.width - (buRec.rect.width * 3)) / 4;
            float step           = be + buRec.rect.width;
//			Debug.LogError(canvas.rect.width+","+Screen.width+","+buRec.rect.width+","+step+","+be);

            RectTransform contentTrans = content.GetComponent <RectTransform> ();
            float sizeHeight           = be + (step * (count / 3 + (count % 3 > 0?1:0)));
            Debug.Log("sizeHeight:" + sizeHeight);
            contentTrans.sizeDelta = new Vector2(0, sizeHeight);
            int allStarCount       = 0;
            Object lockPic         = Resources.Load("lock");
            for (int i = 0; i < count; i++)               // todo 这个地方要分段显示
            {
                int x = i % 3;
                int y = i / 3;
                up    = Instantiate(levelItem) as GameObject;

                up.transform.localPosition = new Vector3(be + x * step, -be - y * step, 0);
                up.transform.localScale    = new Vector3(1, 1, 1);
                up.transform.SetParent(content.transform, false);

                Button b1 = up.GetComponent <Button> ();

                ButtonIndex buttonIndex = up.GetComponent <ButtonIndex> ();
                buttonIndex.pass        = i + 1;
                buttonIndex.star        = 0;
                buttonIndex.isOpen      = true;
                if (level.StarInLevel.Count > i)
                {
                    buttonIndex.star = level.StarInLevel[i];
                    allStarCount    += buttonIndex.star;
                }
                else if (level.StarInLevel.Count < i)
                {
                    GameObject lockOb = Instantiate(lockPic) as GameObject;
                    //lockOb.transform.localPosition = new Vector3(0,0, 0);
                    //lockOb.transform.localScale = new Vector3(1, 1, 1);
                    lockOb.transform.SetParent(up.transform, false);
                    buttonIndex.isOpen = false;
                }
                if (level.StarInLevel.Count >= i)
                {
                    b1.onClick.AddListener(delegate()
                    {
                        Sound.playSound(SoundType.Click);
                        OnClick(buttonIndex);
                    });
                }
                else
                {
                    b1.onClick.AddListener(delegate()
                    {
                        Sound.playSound(SoundType.Click);
                        WarnDialog.showWarnDialog(Message.getText("passNotOpen"));
                    });
                }


//				GameObject textGo = up.transform.Find ("Text").gameObject;
//				Text text = textGo.GetComponent<Text> ();
//				text.text = Message.getText("levelItem",buttonIndex.pass,buttonIndex.star);
            }
            // 星数
            GameObject starTextGo = GameObject.Find("main/ui/uiLevel/Canvas/star/Text");
            Text starText         = starTextGo.GetComponent <Text>();
            starText.text         = allStarCount.ToString();
        });
    }