Inheritance: MonoBehaviour
	public void HoldEnd (GameMessage msg)
	{
        Debug.Log("HoldEnd");
        // TODO(oz) Differenciate hold end from hold start
        ChangeBehaviour(Behaviour.HoldStart);
		SoundController.instance.PlaySfx (SoundController.SfxType.FxTams2, msg.targetId);
	}
		public static byte[] EmtryMessage(GameMessage message){
			byte[] data =null;
			using(GameServerPacket packet=new GameServerPacket(message)){
				data = packet.Content;
			}
			return data;
		}
    public override void OnGameMessage(GameMessage gameMessage)
    {
        //requestedState = gameMessage.unityInstanceStatus.requestedState;
        gameMessage.unityInstanceStatus.state = gameMessage.unityInstanceStatus.requestedState;

        Reply(gameMessage);
    }
 public GameServerPacket(GameMessage message)
 {
     m_stream = new MemoryStream();
     m_writer = new BinaryWriter(m_stream);
     m_writer.Write((byte)(StocMessage.GameMsg));
     m_writer.Write((byte)message);
 }
 public MessageNode(GameMessage message, int start, int end)
 {
     this.gameMessage = message;
     this.mStart = start;
     this.mEnd = end;
     Text = String.Join(".", (message.GetType().ToString().Split('.').Skip(5)));
 }
	public static void Log(string txt, float life = 3.0f){
		GameMessage msg = new GameMessage ();
		msg.text = txt;
		msg.time = Time.time;
		msg.life = life;
		message_stream.OnNext(msg);
	}
		public GameServerPacket(GameMessage message):base(GamePacketByteLength)
		{
			Write((byte)(StocMessage.GameMsg));
			this.PacketMsg=StocMessage.GameMsg;
			Write((byte)message);
			this.GameMsg = message;
		}
 public GameMessageResult Message_TouchStarted(GameMessage msg)
 {
     ToggleSelected();
     GameMessenger.Reg("touchEnded", this, Message_TouchEnded);
     GameMessenger.Reg("touchMoved", this, Message_TouchMoved);
     return GameMessageResult.handledMessage;
 }
 public GameMessageResult Message_newTestInputRecording(GameMessage msg)
 {
     var testName = (string)msg.data;
     text.text = "[Test] " + testName;
     Clear();
     return GameMessageResult.handledMessage;
 }
Exemple #10
0
 public void BroadcastGlobal(GameMessage message)
 {
     foreach (var player in this.Players.Values)
     {
         player.InGameClient.SendMessageNow(message);
     }
 }
 /// <summary>
 /// Sends data to the <see cref="INetworkSender"/>. This method is thread-safe.
 /// </summary>
 /// <param name="sender">The <see cref="INetworkSender"/> to use to send the data.</param>
 /// <param name="message">GameMessage to send to the User.</param>
 /// <param name="messageType">The <see cref="ServerMessageType"/> to use for sending the <paramref name="message"/>.</param>
 /// <param name="parameters">Message parameters.</param>
 public static void Send(this INetworkSender sender, GameMessage message, ServerMessageType messageType,
                         params object[] parameters)
 {
     using (var pw = ServerPacket.SendMessage(message, parameters))
     {
         sender.Send(pw, messageType);
     }
 }
 public GameMessageResult Message_TouchMoved(GameMessage msg)
 {
     if (msg.data != null) {
         var position = (Ray)msg.data;
         gameObject.transform.position = position.origin;
     }
     return GameMessageResult.handledMessage;
 }
Exemple #13
0
 public static PacketWriter CreateAccount(bool successful, GameMessage failureReason)
 {
     var pw = GetWriter(ServerPacketID.CreateAccount);
     pw.Write(successful);
     if (!successful)
         pw.WriteEnum(failureReason);
     return pw;
 }
Exemple #14
0
 public override GameMessage getMessage()
 {
     GameMessage message = new GameMessage ();
     message.bPieceSelectionMessage = false;
     message.iIndex1 = (int)squareIndex.x;
     message.iIndex2 = (int)squareIndex.y;
     return message;
 }
Exemple #15
0
 public static GameMessage DespawnMessage(int index)
 {
     GameMessage msg = new GameMessage();
     msg.DataType = DataTypeDespawnEntity;
     msg.index = index;
     msg.MessageSize = 0;
     return msg;
 }
Exemple #16
0
 public CoreMessage(GameMessage msg, BinaryReader reader, byte[] raw)
 {
     Message = msg;
     Reader = reader;
     m_raw = raw;
     m_stream = (MemoryStream)reader.BaseStream;
     m_startPosition = m_stream.Position;
 }
        public static void SendMessage(this GameObject sender, GameMessage msg, GameObject target)
        {
            if (msg == null)
            {
                Log.Game.WriteWarning("ExtMethodsGameObject: Tried to send a null message.\n{0}", Environment.StackTrace);
                return;
            }

            // if there is already a list on the stack then we have re-entered SendMessage i.e. a HandleMessage method has
            // called SendMessage
            if (_receiverStack.Count > 0)
                _currentReceivers = new List<ICmpHandlesMessages>();

            _receiverStack.Push(_currentReceivers);
            _currentReceivers.Clear();

            if (target != null)
            {
                if (!target.Active)
                {
                    _currentReceivers = _receiverStack.Pop();
                    return;
                }

                target.GetComponents(_currentReceivers);
            }
            else
            {
                Scene.Current.FindComponents(_currentReceivers);
            }

            try
            {
                for (int i = _currentReceivers.Count - 1; i >= 0; i--)
                {
                    var receiver = _currentReceivers[i];

                    if (receiver == null || ((Component)receiver).Disposed || ((Component)receiver).Active == false)
                        continue;

                    receiver.HandleMessage(sender, msg);

                    if (i > _currentReceivers.Count)
                        i = _currentReceivers.Count;

                    if (msg.Handled)
                        break;
                }
            }
            finally
            {
                _receiverStack.Pop();
                if (_receiverStack.Count > 0)
                    _currentReceivers = _receiverStack.Peek();
                else
                    _currentReceivers = _receivers;
            }
        }
	/// <summary>
	/// Adds the new messages to waiting queue.
	/// </summary>
	/// <param name="messages">Messages.</param>
	private void AddNewMessagesToWaitingQueue (List<string> messages)
	{
		foreach(string message in messages)
		{
			GameMessage newMessage = new GameMessage();
			newMessage.Message = message;
			waitingGameMessages.Enqueue(newMessage);
		}
	}
 public override GameMessage getMessage()
 {
     // PieceSelection function
     GameMessage message = new GameMessage ();
     message.bPieceSelectionMessage = true;
     message.iIndex1 = pieceIndex;
     message.belongsToAttacker = belongsToAttacker;
     return message;
 }
Exemple #20
0
        public void Consume(GameClient client, GameMessage message)
        {
            if (message is AssignActiveSkillMessage) OnAssignActiveSkill(client, (AssignActiveSkillMessage)message);
            else if (message is AssignPassiveSkillMessage) OnAssignPassiveSkill(client, (AssignPassiveSkillMessage)message);
            else if (message is PlayerChangeHotbarButtonMessage) OnPlayerChangeHotbarButtonMessage(client, (PlayerChangeHotbarButtonMessage)message);
            else return;

            UpdateClient(client);
            client.FlushOutgoingBuffer();
        }
Exemple #21
0
 public void BroadcastIfRevealed(GameMessage message, Actor actor)
 {
     foreach (var player in this.Players.Values)
     {
         if (player.RevealedObjects.ContainsKey(actor.DynamicID))
         {
             player.InGameClient.SendMessageNow(message);
         }
     }
 }
Exemple #22
0
		void ICmpMessageListener.OnMessage(GameMessage msg)
		{
			if (msg is TriggerEnteredMessage)
			{
				this.AddSignal();
			}
			else if (msg is TriggerLeftMessage)
			{
				this.RemoveSignal();
			}
		}
 public static void SendMessage(this Component sender, GameMessage msg, string targetName)
 {
     if (string.IsNullOrEmpty(targetName))
     {
         SendMessage(sender, msg);
     }
     else
     {
         SendMessage(sender, msg, Scene.Current.FindGameObject(targetName));
     }
 }
Exemple #24
0
 static bool compareMessage(GameMessage m1, GameMessage m2)
 {
     if (m1.MessageSize != m2.MessageSize)
         return false;
     for (int i = 0; i < m1.MessageSize; ++i)
     {
         if (m1.Message[i] != m2.Message[i])
             return false;
     }
     return (m1.DataType == m2.DataType && m1.index == m2.index);
 }
 // Process message
 public static void ChangeClientView(GameMessage message)
 {
     if (!CallbackActions.ContainsKey(message.actionType))
     {
         LogSaver.Log("Callback action for GameMessage.ActionType=" +
                                           message.actionType.ToString() + " not implemented");
         throw new NotImplementedException("Callback action for GameMessage.ActionType=" +
                                           message.actionType.ToString() + " not implemented");
     }
     //Call appropriate function
     CallbackActions[message.actionType](message.actionAgrument);
 }
        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spriteBatch = SCSServices.Instance.SpriteBatch;
            spriteBatch.Begin();

            IMessage<MessageType> updateMessage = new GameMessage(MessageType.FRAME_DRAW, this);
            updateMessage.DestinationObjectId = 0; // For every object
            objectManager.SendMessage(updateMessage, gameTime);

            base.Draw(gameTime);
            spriteBatch.End();
        }
Exemple #27
0
		public static void Send(Component source, GameObject target, GameMessage message)
		{
			// If the target is null or inactive, that's okay. It's just that nobody will receive anything.
			if (target == null) return;
			if (!target.Active) return;

			// Send the message to all the interested Components from the target object.
			message.Sender = source;
			target.IterateComponents<ICmpMessageListener>(
				l => l.OnMessage(message),
				l => (l as Component).Active);
		}
	static public void DisplayMessage(string str){
		if(!init){
			GameObject obj=new GameObject();
			obj.name="GameMessage";
			gameMessage=obj.AddComponent<GameMessage>();
			gameMessage.messageObj=obj;
		
			Init();
		}
		
		gameMessage.DisplayMsg(str);
	}
Exemple #29
0
    public GameMessageResult Message_spawnActor(GameMessage msg)
    {
        string actorName = msg.data as string;
        var actorToSpawn = sceneActors.Find(actr => actr.name == actorName);
        if (actorToSpawn != null) {
            GameObject.Instantiate(actorToSpawn);
        }
        else {
            Debug.LogWarning("could not find actor " + actorName);
        }

        return GameMessageResult.handledMessage;
    }
Exemple #30
0
    public static void DisplayMessage(string str)
    {
        if(!gameMessage.init){
            GameObject obj=new GameObject();
            obj.name="GameMessage";
            gameMessage=obj.AddComponent<GameMessage>();
            gameMessage.messageObj=obj;

            Init();
        }

        if(gameMessage.uiFlag) UI.ShowMessage(str);
        else gameMessage.DisplayMsg(str);
    }
Exemple #31
0
        /// <summary>
        /// Handle a message from the recv messagebuffer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnSendReaderProcessMessage(object sender, MessageBufferEventArgs e)
        {
            if (e.Length > GameMessage.HEADERLENGTH)
            {
                try
                {
                    // set the direction as outgoing
                    e.Direction = MessageDirection.ClientToServer;

                    // parse the message
                    GameMessage typedMessage = ExtractMessage(e);
                    typedMessage.EncryptedPI        = typedMessage.PI;
                    typedMessage.MemoryStartAddress = e.MemoryAddress;

                    CheckServerSave(typedMessage);

                    // Advance the hashtable if encryption is enabled (3. TX packet) and if it's not a blacklisted packet
                    if (CRCCreatorEnabled &&
                        advanceHashTable &&
                        ((MessageTypeGameMode)typedMessage.PI != MessageTypeGameMode.Blacklisted))
                    {
                        CRCCreator.AdvanceHashTable();
                    }

                    OnNewMessageAvailable(new GameMessageEventArgs(typedMessage));
                }
                catch (Exception Error)
                {
                    byte[] dump = new byte[e.Length];
                    Array.Copy(e.MessageBuffer, 0, dump, 0, e.Length);
                    OnHandlerError(new HandlerErrorEventArgs(dump, Error.Message));
                }
            }
            else
            {
                OnEmptyPacketFound(new EmptyMessageFoundEventArgs());
            }
        }
    public void SetModel(R prop, UnitModel unit, bool canChange, string stringFormat = "N0", bool showMaxValue = false)
    {
        disposables.Clear();
        delta = 0;

        PropertyView.SetProperty(prop.ToString());
        PropertyView.StringFormat = stringFormat;

        unit.Props[prop]._Value
        .Subscribe(_ => PropertyView.SetValue(_))
        .AddTo(disposables);

        if (showMaxValue)
        {
            unit.Props[prop]._MaxValue
            .Subscribe(_ => PropertyView.SetDelta(_))
            .AddTo(disposables);
        }

        unit.Props[R.UpgradePoint]._Value
        .Subscribe(_ => UpgradeButton.interactable = _ > 0 ? true : false)
        .AddTo(disposables);

        if (canChange)
        {
            UpgradeButton.OnClickAsObservable()
            .Subscribe(_ =>
            {
                GameMessage.Send(new UnitPropUpgradeMessage(prop));
                PropertyView.SetDelta(++delta);
            })
            .AddTo(disposables);
        }
        else
        {
            UpgradeButton.gameObject.SetActive(false);
        }
    }
 public void readMessage(GameMessage message)
 {
     if (message.type == MessageType.OPEN_MAIN_MENU)
     {
         Debug.Log("opne main menu");
         enable();
     }
     if (isActive && message.type == MessageType.OPEN_INVENTORY)
     {
         navigation().closeActiveWindow();
         navigation().openInventory();
     }
     if (isActive && message.type == MessageType.OPEN_SHOP)
     {
         navigation().closeActiveWindow();
         navigation().openShop();
     }
     if (isActive && message.type == MessageType.OPEN_POSITIONS)
     {
         navigation().closeActiveWindow();
         navigation().openPositions();
     }
     if (isActive && message.type == MessageType.OPEN_SKILLS)
     {
         navigation().closeActiveWindow();
         navigation().openSkills();
     }
     if (isActive && message.type == MessageType.CLOSE_FIGHT_MAP)
     {
         navigation().closeActiveWindow();
         generateMessage(new GameMessage(MessageType.INIT_FIGHT_MAP));
         navigation().openFightMap();
     }
     if (isActive && message.type == MessageType.CLOSE_ACTIVE_WINDOW)
     {
         disable();
     }
 }
Exemple #34
0
        /// <summary>
        /// Routers incoming GameMessage to it's proper consumer.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="message"></param>
        public void Route(GameClient client, GameMessage message)
        {
            lock (this)
            {
                try
                {
                    switch (message.Consumer)
                    {
                    case Consumers.Game:
                        this.Consume(client, message);
                        break;

                    case Consumers.Inventory:
                        client.Player.Inventory.Consume(client, message);
                        break;

                    case Consumers.Player:
                        client.Player.Consume(client, message);
                        break;

                    case Consumers.Conversations:
                        client.Player.Conversations.Consume(client, message);
                        break;

                    case Consumers.SelectedNPC:
                        if (client.Player.SelectedNPC != null)
                        {
                            client.Player.SelectedNPC.Consume(client, message);
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    Logger.DebugException(e, "Unhandled exception caught:");
                }
            }
        }
    // Establishes the connection's lifecycle callbacks.
    // Once the connection is established, OnOpen, it automatically attempts to create or join a game through the RequestStartOp code.
    private void SetupWebsocketCallbacks()
    {
        _websocket.OnOpen += () =>
        {
            Debug.Log("Connection open!");
            intentionalClose = false;
            GameMessage startRequest = new GameMessage("OnMessage", RequestStartOp);
            SendWebSocketMessage(JsonUtility.ToJson(startRequest));
        };

        _websocket.OnClose += (e) =>
        {
            Debug.Log("Connection closed!");

            // only do this if someone quit the game session, and not for a game ending event
            if (!intentionalClose)
            {
                UnityMainThreadHelper.wkr.AddJob(() =>
                {
                    _menu.Disconnected();
                });
            }
        };

        _websocket.OnMessage += (bytes) =>
        {
            // Debug.Log("OnMessage!");
            string message = System.Text.Encoding.UTF8.GetString(bytes);
            // Debug.Log(message.ToString());

            ProcessReceivedMessage(message);
        };

        _websocket.OnError += (e) =>
        {
            Debug.Log("Error! " + e);
        };
    }
        private void OnMessageShopBuyReq(TcpSession session, GameMessage message)
        {
            string scode = message.Get <string>("session");
            string uid   = GetUidBySession(scode);

            if (string.IsNullOrEmpty(uid) || scode != session.ID)
            {
                session.Write(new GameMessage("error").With("message", "unknown session key"));
                return;
            }

            // item
            var item = gamedb.Items.Select(message.Get <string>("itemcode"));

            if (null == item)
            {
                session.Write(new GameMessage("error").With("message", "unknown item code"));
                return;
            }

            // user's balance -> shop address
            string signer = web4b.GetUserKey(uid);
            string txid   = web4b.SendTransferAsync(signer, shopAddress, web4b.ToBeryl(item.Price)).Result.txid;

            if (string.IsNullOrEmpty(txid))
            {
                session.Write(new GameMessage("error").With("message", "txid not found"));
                return;
            }

            // item to user inventory
            var inventory = gamedb.Inventories.Select(uid);

            inventory.Add(item.Code);
            gamedb.Inventories.Update(uid, inventory);

            session.Write(new GameMessage("shop.buy.res").With("item", JObject.FromObject(item)));
        }
Exemple #37
0
 public void Consume(GameClient client, GameMessage message)
 {
     if (message is NPCSelectConversationMessage)
     {
         OnSelectConversation(client.Player, message as NPCSelectConversationMessage);
     }
     if (message is HirelingHireMessage)
     {
         OnHire(client.Player);
     }
     if (message is HirelingInventoryMessage)
     {
         OnInventory(client.Player);
     }
     if (message is CraftInteractionMessage)
     {
         OnCraft(client.Player);
     }
     else
     {
         return;
     }
 }
Exemple #38
0
        /// <summary>
        /// 更新比分
        /// </summary>
        public void UpdateScore(Player player)
        {
            if (player.tempData.team == 1)
            {
                scoreT1++;
            }

            else if (player.tempData.team == 2)
            {
                scoreT2++;
            }

            // 广播更新比分的消息
            GameMessage broadMsg = new GameMessage();

            broadMsg.type = BitConverter.GetBytes((int)Protocol.UpdateScore);
            BattleScore battleScore = new BattleScore();

            battleScore.scoreT1 = scoreT1;
            battleScore.scoreT2 = scoreT2;
            broadMsg.data       = ProtoTransfer.Serialize(battleScore);
            BroadcastTcp(broadMsg);
        }
    void OnModifyResource(GameMessage msg)
    {
        if (resourceItem == msg.resourceItem)
        {
            //Debug.Log("resource: "+msg.resourceItem);
            GameObject newTextGO = Instantiate(textGO, transform);
            newTextGO.transform.localPosition = textGO.transform.localPosition;
            TMPro.TextMeshProUGUI tmpText = newTextGO.GetComponent <TMPro.TextMeshProUGUI>();

            NumberPopDissolveFx fx = newTextGO.AddComponent <NumberPopDissolveFx>();
            if (msg.floatMessage < 0)
            {
                tmpText.text  = (Mathf.Round(msg.floatMessage * 10f) / 10f).ToString();
                tmpText.color = GameConstantsBucket.ResourceColorNegative;
            }
            else
            {
                tmpText.text  = "+" + (Mathf.Round(msg.floatMessage * 10f) / 10f).ToString();
                tmpText.color = GameConstantsBucket.ResourceColorPositive;
            }
            fx.Init(tmpText);
        }
    }
    void AmountLootedChanged(GameMessage msg)
    {
        int filledSlots = msg.intMessage;

        for (int i = 0; i < slots.Count; i++)
        {
            if (i < Mathf.RoundToInt(filledSlots / 2f))
            {
                if (!slots[i].gameObject.active)
                {
                    slots[i].gameObject.SetActive(true);
                    slots[i].sprite = itemSprites[Random.Range(0, itemSprites.Count)];
                }
            }
            else
            {
                if (slots[i].gameObject.active)
                {
                    slots[i].gameObject.SetActive(false);
                }
            }
        }
    }
Exemple #41
0
        public void ReceiveGameCancel(GameMessage message)
        {
            try
            {
                ConnectedPlayers[message.SenderNick].Client.GameCancel();
                ConnectedPlayers[message.ReceiverNick].Client.GameCancel();

                AllGames.Remove(message.GameId);

                ConnectedPlayers[message.SenderNick].IsPlaying = false;
                SendMessageToAll(new TextMessage {
                    SenderNick = message.SenderNick, Type = MessageType.PlayerFinishedMessage
                });
                ConnectedPlayers[message.ReceiverNick].IsPlaying = false;
                SendMessageToAll(new TextMessage {
                    SenderNick = message.ReceiverNick, Type = MessageType.PlayerFinishedMessage
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        private void sendChatMessage()
        {
            string message = txtTypeInChat.Text;

            message = message.Replace("\r", "");
            message = message.Replace("\n", "");

            if (ctrl.notEmpty(message))
            {
                Models.GameMessage gm = new GameMessage();

                gm.GameID          = ctrl.GameRoomID;
                gm.Command         = "INGAMECHATMESSAGE";
                gm.stringArguments = new List <string>()
                {
                    message
                };

                ctrl.send(gm);

                txtTypeInChat.Clear();
            }
        }
        private void OnMessageKeyExportTokenReq(TcpSession session, GameMessage message)
        {
            string scode = message.Get <string>("session");
            string uid   = GetUidBySession(scode);

            if (string.IsNullOrEmpty(uid) || scode != session.ID)
            {
                session.Write(new GameMessage("error").With("message", "unknown session key"));
                return;
            }

            Task.Run(async() =>
            {
                (string token, string error) = await web4b.GetUserKeyExportTokenAsync(uid);
                BConsole.WriteLine("token: ", token, ", error: ", error);

                // AES encrypt with session key
                if (Aes256.TryEncrypt(Encoding.UTF8.GetBytes(scode), Hex.ToByteArray(token), out var encrypted))
                {
                    session.Write(new GameMessage("key.export.token.res").With("token", Hex.ToString(encrypted)));
                }
            });
        }
Exemple #44
0
    private void OnData(int connId, int channelId, int recHostId, GameMessage message)
    {
        switch (message.Code)
        {
        case OperationCode.None:
            break;

        case OperationCode.CreateAccount:
            CreateAccount(connId, channelId, recHostId, (Message_CreateAccount)message);
            break;

        case OperationCode.Move:
            break;

        case OperationCode.Shoot:
            break;

        case OperationCode.Spawn:
            SpawnPlayer(connId, channelId, recHostId, (Message_Spawn)message);
            ShowHazards(connId, channelId, recHostId, (Message_Spawn)message);
            break;
        }
    }
    /// <summary>
    /// 开始战斗协议回调
    /// </summary>
    /// <param name="protocol"></param>
    public void OnStartBack(GameMessage msg)
    {
        Start2Fight ret = (Start2Fight)msg.data[0];

        switch (ret)
        {
        case Start2Fight.NotOwner:
            PanelMgr._instance.OpenPanel <TipPanel>("", "开始游戏失败!\n只有队长可以开始战斗");
            break;

        case Start2Fight.Fighting:
            PanelMgr._instance.OpenPanel <TipPanel>("", "开始游戏失败!\n当前房间正在战斗中\n只有队长可以开始战斗");
            break;

        case Start2Fight.NotExitBattle:
            PanelMgr._instance.OpenPanel <TipPanel>("", "开始游戏失败!\n还有玩家未退出战斗");
            break;

        case Start2Fight.NotEnoughPlayer:
            PanelMgr._instance.OpenPanel <TipPanel>("", "开始游戏失败!\n两队至少都需要一名玩家");
            break;
        }
    }
        private void BestiaryEntryChanged(Object p_sender, EventArgs p_args)
        {
            BestiaryEntryEventArgs bestiaryEntryEventArgs = p_args as BestiaryEntryEventArgs;

            if (bestiaryEntryEventArgs == null)
            {
                return;
            }
            String text      = LocaManager.GetText(bestiaryEntryEventArgs.MonsterNameKey);
            String p_message = String.Empty;

            if (bestiaryEntryEventArgs.EntryState == BestiaryEntryEventArgs.EEntryState.ENTRY_NEW)
            {
                p_message = LocaManager.GetText("GAME_MESSAGE_BESTIARY_ENTRY_NEW", text);
            }
            else
            {
                p_message = LocaManager.GetText("GAME_MESSAGE_BESTIARY_ENTRY_CHANGED", text);
            }
            GameMessage item = new GameMessage(p_message);

            m_queuedMessages.Enqueue(item);
        }
Exemple #47
0
        private static void Handshake(NetworkGameServer server)
        {
            string guid      = Guid.NewGuid().ToString();
            var    handshake = new HandshakeEvent(guid);

            server.Send(new GameMessage(handshake));

            GameMessage received = server.Receive();

            if (received.ContentType != typeof(HandshakeEvent))
            {
                throw new Exception("server expected handshake.");
            }

            HandshakeEvent internalEvent = received.DeserializeContent <HandshakeEvent>();

            if (internalEvent.HandshakeMessage != guid)
            {
                throw new Exception($"The client did not respond with the expected handshake message. Expected: {guid}\nSaw: {internalEvent.HandshakeMessage}");
            }

            Debug.Log("Handshake succeeded.");
        }
Exemple #48
0
    /// <summary>
    /// Sends the message.
    /// 发送结构体过去;
    /// </summary>
    /// <param name="msgID">Message I.</param>
    /// <param name="URL">UR.</param>
    /// <param name="protoSt">Proto st.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public void SendMsg <T> (GameMessage msgID, string URL, T protoSt, bool isNeedTipWaite = false) where T : class, ProtoBuf.IExtensible
    {
        Debuger.LogWarning("向服务器发送 http " + msgID + "  ");
        using (MemoryStream ms = new MemoryStream()) {
            bool isNeed = MsgSet.IsNeedTipByMsgID((int)msgID);
            if (isNeedTipWaite || isNeed)
            {
                GTSenceManage.Instance().StartLoadData();
            }
            new PBMessageSerializer().Serialize(ms, protoSt);
            byte[] bytes = ms.ToArray();

            NetPacket pack = new NetPacket((int)msgID, bytes.Length);
            pack.setData(bytes);

            GameObject  oneObj  = new GameObject("http_" + msgID);
            HttpDataCmp httpCmp = oneObj.AddComponent <HttpDataCmp> ();
            httpCmp.isNeedTipWaite   = isNeedTipWaite;
            httpCmp.transform.parent = transform;

            httpCmp.GET(msgID, URL, GetDataCallFun, pack);
        }
    }
Exemple #49
0
        /// <summary>
        /// Internally handle some GameModeMessages
        /// </summary>
        /// <param name="Message"></param>
        protected void HandleGameModeMessage(GameMessage Message)
        {
            switch ((MessageTypeGameMode)Message.PI)
            {
            case MessageTypeGameMode.EchoPing:
                rtt = (DateTime.Now - lastPingSent).Milliseconds;
                break;

            case MessageTypeGameMode.Wait:
                timPing.Stop();
                connectionState = ConnectionState.Waiting;

                Logger.Log(MODULENAME, LogType.Info, "ConnectionState: Waiting");
                break;

            case MessageTypeGameMode.Unwait:
                timPing.Start();
                connectionState = ConnectionState.Playing;

                Logger.Log(MODULENAME, LogType.Info, "ConnectionState: Playing");
                break;
            }
        }
        public void OnPacket(GameServerPacket packet)
        {
            StocMessage id = packet.ReadStoc();

            if (id == StocMessage.GameMsg)
            {
                GameMessage msg = packet.ReadGameMsg();

                if (_messages.ContainsKey(msg))
                {
                    _messages[msg](packet);
                                        #if DEBUG
                    Logger.WriteLine("GameMessage deal " + msg);
                                        #endif
                }
                else
                {
                                        #if DEBUG
                    Logger.WriteLine("GameMessage don't deal " + msg);
                                        #endif
                }
                return;
            }
            if (_packets.ContainsKey(id))
            {
                _packets[id](packet);
                                #if DEBUG
                Logger.WriteLine("id deal " + id);
                                #endif
            }
            else
            {
                                #if DEBUG
                Logger.WriteLine("id don't deal " + id);
                                #endif
            }
        }
        public Response processBrokenSafeguards(GameMessage message, Socket sender)
        {
            Response response = new Response(sender);

            Models.Game game    = onGoingGamesData.getGameByID(message.GameID);
            List <int>  cardIDs = new List <int>();

            message.intArguments.Reverse();

            if (game.isPlayer1(sender))
            {
                foreach (int index in message.intArguments)
                {
                    cardIDs.Add(game.breakSafeguard(index, 1));
                }
            }
            else
            {
                foreach (int index in message.intArguments)
                {
                    cardIDs.Add(game.breakSafeguard(index, 2));
                }
            }

            response.responseCommandToSender = "YOURGUARDSBROKE";
            response.commandIntArgumentsToSender.Add(cardIDs.Count);
            foreach (int index in message.intArguments)
            {
                response.commandIntArgumentsToSender.Add(index);
            }
            foreach (int cardID in cardIDs)
            {
                response.commandIntArgumentsToSender.Add(cardID);
            }

            return(response);
        }
Exemple #52
0
    public void ShowMessage(string msg, float time, MessageType t)
    {
        GameObject  o       = GameObject.Instantiate(messageUi, Vector2.zero, Quaternion.identity);
        GameMessage message = o.GetComponent <GameMessage>();

        message.Init(msg, time);

        if (messageQueue.Count != 0)
        {
            //messageQueue.Enqueue(message);
            switch (t)
            {
            case MessageType.Commmon:
                messageQueue.Enqueue(message);
                break;

            case MessageType.Important:
                while (messageQueue.Count != 0)
                {
                    GameMessage gm = messageQueue.Dequeue();
                    if (gm != null)
                    {
                        Destroy(gm.gameObject);
                    }
                }

                message.Show();
                messageQueue.Enqueue(message);
                break;
            }
        }
        else
        {
            message.Show();
            messageQueue.Enqueue(message);
        }
    }
Exemple #53
0
        private static void GameEnd(GameMessage message)
        {
            Int64 clientId  = message.ClientId;
            Int64 matchedId = 0;

            if (matched.ContainsKey(clientId))
            {
                matchedId = matched[clientId];
                // 游戏结束时将双方移出游戏队列
                matched.Remove(clientId);
            }
            else if (matched.ContainsValue(clientId))
            {
                matchedId = matched.First(m => m.Value == clientId).Key;
                matched.Remove(matchedId);
            }
            connected.Remove(clientId);
            connected.Remove(matchedId);
            var draw = (Boolean)message.ExtraData["Draw"];
            var msg  = server.CreateGameMessage <GameEndMessage>();

            if (draw)
            {
                msg.ExtraData["Draw"] = true;
                server.SendMessage(msg, server.GetClient(clientId));
                server.SendMessage(msg, server.GetClient(matchedId));
            }
            else
            {
                msg.ExtraData["Draw"] = false;
                // 发送方为胜利者
                msg.ExtraData["Win"] = true;
                server.SendMessage(msg, server.GetClient(clientId));
                msg.ExtraData["Win"] = false;
                server.SendMessage(msg, server.GetClient(matchedId));
            }
        }
Exemple #54
0
        private void OnRevealCard(GameMessage message)
        {
            if (Turn)
            {
                return;
            }

            var card = Board[message.Row, message.Column];

            if (!CheckCard(card))
            {
                return;
            }

            card.Label.Content = Board[card.Row, card.Column];

            if (FirstCard != null && SecondCard != null)
            {
                if (FirstCard.Value != SecondCard.Value)
                {
                    ShowCards(true);
                }
                else
                {
                    OpponentScoreL.Content = ++OpponentScore;

                    if (CheckEndOfGame())
                    {
                        SetTurn(false);
                        EndOfTheGame(message);
                    }

                    FirstCard  = null;
                    SecondCard = null;
                }
            }
        }
Exemple #55
0
    // 开始战斗
    public void StartBattle(GameMessage message)
    {
        Protocol msgType = (Protocol)message.type[0];

        if (msgType != Protocol.Fight)
        {
            return;
        }
        byte[] tempbytes = new byte[sizeof(Int32)];
        System.Array.Copy(message.data, 0, tempbytes, 0, sizeof(Int32));
        // 对局时间
        int battleLimitTime = System.BitConverter.ToInt32(tempbytes, 0);

        // 显示主UI
        PanelMgr._instance.OpenPanel <BattleMainPanel>("", battleLimitTime);
        byte[] data = new byte[message.data.Length - tempbytes.Length];
        System.Array.Copy(message.data, tempbytes.Length, data, 0, data.Length);
        // 清理场景
        ClearBattle();
        List <BattlePlayer> battlePlayers = ProtoTransfer.Deserialize <List <BattlePlayer> >(data);

        foreach (var bp in battlePlayers)
        {
            string id     = bp.id;
            int    team   = bp.team;
            int    swopID = bp.swopId;
            int    hp     = bp.playerHp;
            GeneratePlayer(id, team, swopID, hp);
        }

        NetMgr.GetInstance().tcpSock.msgDist.AddListener(Protocol.UpdateUnitInfo, RecvUpdateUnitInfo);
        NetMgr.GetInstance().tcpSock.msgDist.AddListener(Protocol.Shooting, RecvShooting);
        NetMgr.GetInstance().tcpSock.msgDist.AddListener(Protocol.Reload, RecvReload);
        NetMgr.GetInstance().tcpSock.msgDist.AddListener(Protocol.Hit, RecvHit);
        NetMgr.GetInstance().tcpSock.msgDist.AddListener(Protocol.GameResult, RecvResult);
        NetMgr.GetInstance().tcpSock.msgDist.AddListener(Protocol.RelifePlayer, RecvRelifePlayer);
    }
    public override void OnShowing()
    {
        base.OnShowing();

        InitUI();
        listPageTran.localPosition       += new Vector3(485, 0, 0);
        playerinfoPageTran.localPosition += new Vector3(-312, 0, 0);

        playerinfoPageTran.DOLocalMoveX(-388, 0.5f);
        listPageTran.DOLocalMoveX(385, 0.5f).OnComplete(() => {
            logoutBtn.onClick.AddListener(OnLogoutClick);
            createBtn.onClick.AddListener(OnCreateClick);
            reflashBtn.onClick.AddListener(OnReflashClick);
        });
        // 生成
        GameObject roomUICamera = Resources.Load <GameObject>("UIPrefab/RoomUICamera");

        roomUICameraGo = Instantiate(roomUICamera);

        //监听
        NetMgr.GetInstance().tcpSock.msgDist.AddListener(Protocol.GetAchieve, RecvGetAchieve);
        NetMgr.GetInstance().tcpSock.msgDist.AddListener(Protocol.GetRoomList, RecvGetRoomList);

        //发送查询
        // 查询房间列表
        GameMessage message = new GameMessage();

        message.type = BitConverter.GetBytes((int)Protocol.GetRoomList);
        message.data = BitConverter.GetBytes(1);
        NetMgr.GetInstance().tcpSock.Send(message);

        // 查询玩家信息
        message      = new GameMessage();
        message.type = BitConverter.GetBytes((int)Protocol.GetAchieve);
        message.data = BitConverter.GetBytes(1);
        NetMgr.GetInstance().tcpSock.Send(message);
    }
Exemple #57
0
    public void RenameRequest(MessagePack pack)
    {
        var data    = pack.gameMessage.renameRequest;
        var message = new GameMessage()
        {
            cmd = (int)CMD.RenameRespond
        };

        //拿到重命名的数据包后要做的事
        //在数据库中查询是否有重名的
        if (cacheService.IsNameExit(data.name))
        {   //如果有重名的, 发送重名错误码
            message.err = (int)ErrorCode.NameExit;
        }
        else  //没有重名的, 将传入的名字更新到缓存与数据库
        {
            //试着从缓存层中获取到玩家数据,
            var playerData = cacheService.GetPlayerDataBySession(pack.serverSession);
            playerData.name = data.name;

            //如果更新名称失败
            if (!cacheService.UpdatePlayerDataToDataBase(playerData.id, playerData))
            {   //发送错误码
                message.err = (int)ErrorCode.UpdateDataBaseError;
            }
            else
            {   // 创建重命名的回应, 将数据库认可的名字发回打包后发回客户端.
                message.renameRespond = new RenameRespond()
                {
                    name = data.name
                };
            }
            //通过传递的会话信息获取缓存中的玩家信息并更新
        }
        //将名字打包发送给客户端.
        pack.serverSession.SendMsg(message);
    }
Exemple #58
0
        public void ChatReq(string text)
        {
            var player = State.Instance.GetPlayer(_sender);

            if (player.IsSpectator && _gameSettings.MuteSpectators)
            {
                player.Rpc.Error(L.D.ServerMessage__SpectatorsMuted);
                return;
            }
            _broadcaster.Chat(player.Id, text);
            if (State.Instance.Engine.IsLocal != false)
            {
                return;
            }
            var mess = new GameMessage();

            // don't send if we join our own room...that'd be annoying
            //if (player.Nick.Equals(State.Instance.Engine.Game.HostUserName, StringComparison.InvariantCultureIgnoreCase)) return;
            mess.Message   = string.Format("{0} has left your game", player.Nick);
            mess.Sent      = DateTime.Now;
            mess.SessionId = State.Instance.Engine.Game.Id;
            mess.Type      = GameMessageType.Chat;
            //new Octgn.Site.Api.ApiClient().GameMessage(State.Instance.Engine.ApiKey, mess);
        }
Exemple #59
0
        public void SendMessage(int opAction, byte[] toBytes)
        {
            ByteString data = null;

            if (toBytes != null)
            {
                data = ByteString.CopyFrom(toBytes);
            }
            else
            {
                data = ByteString.Empty;
            }

            var gmsg = new GameMessage
            {
                Code = opAction,
                Data = data
            };


            var msgBytes = gmsg.ToBytes();

            Ws?.Send(msgBytes);
        }
        public void OnCharacterSkillLevelChanged(Object p_sender, EventArgs p_args)
        {
            SkillTierChangedEventArgs skillTierChangedEventArgs = p_args as SkillTierChangedEventArgs;

            if (skillTierChangedEventArgs == null)
            {
                return;
            }
            Int32 tier = (Int32)skillTierChangedEventArgs.ChangedSkill.Tier;

            if (tier == 0)
            {
                return;
            }
            if (IngameController.Instance.IsAnyScreenOpen())
            {
                return;
            }
            String      text  = LocaManager.GetText("SKILL_TIER_" + tier.ToString());
            String      text2 = LocaManager.GetText(skillTierChangedEventArgs.ChangedSkill.Name);
            GameMessage item  = new GameMessage(LocaManager.GetText("GAME_MESSAGE_NEW_SKILL_TIER_REACHED", skillTierChangedEventArgs.SkillOwner.Name, text, text2));

            m_queuedMessages.Enqueue(item);
        }