예제 #1
0
 public Merchants()
 {
     Routes  = new MessageRecived[] { Shop, Shop2 };
     Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
     {
         {
             null, new Dictionary <string, MessageRecived>
             {
                 {
                     "Закупиться", (user, message) =>
                     {
                         SwitchAction(user, Shop);
                         HandleAction(user, message);
                     }
                 },
                 {
                     "Ограбить", (user, message) =>
                     {
                         SendMessage(user,
                                     "Несмотря на их натренированные языки, сами купцы были довольно хилыми даже по твоим меркам. Поэтому на каждое из этих слащавых лиц пришлось всего по одному удару. Ты заработал немного монет и мое личное неуважение.");
                         user.Info.Gold += user.Random.Next(500, 850);
                         user.RoomManager.Leave();
                     }
                 },
                 {
                     "Уйти", (user, message) => user.RoomManager.Leave()
                 }
             }
         }
     };
 }
    public void Connected(WebSocket socket)
    {
        var guid = Guid.NewGuid().ToString();

        _webSockets.Add(guid, socket);

        socket.DataReceived     += (webSocket, frame) => MessageRecived?.Invoke(_webSockets.First(x => x.Value == webSocket).Key, webSocket, frame);
        socket.ConnectionClosed += (webSocket) =>
        {
            var connection = _webSockets.First(s => s.Value == webSocket);
            _webSockets.Remove(connection.Key);
        };
        if (_portMappings.IsBindingPosible())
        {
            _portMappings.Bind(guid);
            var message = new ServerMessage()
            {
                ClientID = guid,
                Command  = "Init",
                Value    = _portMappings.CheckBinding(guid).ToString()
            };
            SendMessage(guid, message);
        }
        else
        {
            var message = new ServerMessage()
            {
                ClientID = guid,
                Command  = "Init",
                Value    = "Max Number Of Clients Reached. Please close connection"
            };
            SendMessage(guid, message);
        }
    }
예제 #3
0
 private void OnMessageRecvied(Socket socket, byte[] buffer)
 {
     if (MessageRecived != null)
     {
         MessageRecived.Invoke(socket, buffer);
     }
 }
예제 #4
0
 public Mirror()
 {
     Routes  = new MessageRecived[] { EditStats, Inventory };
     Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
     {
         {
             null, new Dictionary <string, MessageRecived>
             {
                 {
                     "Перераспределить предметы", (user, message) =>
                     {
                         SwitchAction(user, EditStats);
                         SendMessage(user, "Ты начал тщательно рыться в карманах");
                         EditStats(user, message);
                     }
                 },
                 {
                     "Имущество", (user, message) =>
                     {
                         GetRoomVariables(user).Set("current_page", new Serializable.Int(0));
                         SwitchAction(user, Inventory);
                         Inventory(user, message);
                     }
                 },
                 {
                     "Уйти", (user, message) => user.RoomManager.Leave()
                 }
             }
         }
     };
 }
예제 #5
0
 public DarthVader()
 {
     Routes  = new MessageRecived[] { PreBattle, Battle };
     Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
     {
         {
             null, new Dictionary <string, MessageRecived>
             {
                 {
                     "— НЕЕЕЕЕЕЕЕЕЕЕЕЕЕЕЕЕТ!", (user, message) =>
                     {
                         SwitchAction(user, PreBattle);
                         user.Info.MakeDamage(15);
                         SendMessage(user, "Тебе отрубили руку. А теперь хорош рыдать и в бой.",
                                     GetButtons(user));
                     }
                 }
             }
         },
         {
             PreBattle, new Dictionary <string, MessageRecived>
             {
                 {
                     "Достать оружие", (user, message) =>
                     {
                         SendMessage(user, "<b>щелк</b>");
                         user.RoomManager.Go(VaderBattle.Id);
                     }
                 }
             }
         }
     };
 }
예제 #6
0
 private void OnIpcDataRecived(object sender, EventArgs e)
 {
     while (m_IpcReceiver.ReciveQueue.Count > 0)
     {
         var resultItem = m_IpcReceiver.ReciveQueue.Dequeue();
         MessageRecived?.Invoke(this, resultItem);
     }
 }
예제 #7
0
        public void SendChatMessage(ChatMessage request)
        {
            MessageRecived?.Invoke(request.Nickname, request.StickerID);

            foreach (var queue in mChatListeners.Values)
            {
                queue.Enqueue(request);
            }
        }
예제 #8
0
        protected BetterRoomBase()
        {
            Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >();
            var routes  = new List <Tuple <int, ActionBase <T> > >();
            var indexes = new HashSet <int>();
            var self    = typeof(T);

            foreach (var type in self.GetNestedTypes())
            {
                var action = type.GetCustomAttribute <ActionAttribute>();
                if (action == null)
                {
                    continue;
                }

                if (!typeof(ActionBase <T>).IsAssignableFrom(type))
                {
                    throw new Exception("Action must inherit from ActionBase");
                }

                var ctor = type.GetConstructor(new[] { typeof(T) });
                if (ctor == null)
                {
                    throw new Exception("Action must have constructor with single BetterRoomBase argument");
                }

                var instance = (ActionBase <T>)ctor.Invoke(new object[] { this });

                MessageRecived handler = null;
                if (action.Index != null)
                {
                    var index = (int)action.Index;
                    if (indexes.Contains(index))
                    {
                        throw new Exception($"Muliply definition of action with index {action.Index}");
                    }

                    routes.Add(new Tuple <int, ActionBase <T> >(index, instance));
                    handler = instance.OnMessage;
                }
                else
                {
                    if (_rootAction != null)
                    {
                        throw new Exception("Muliply definition of default action");
                    }

                    _rootAction = instance.OnMessage;
                }

                _actions[type]   = handler;
                Buttons[handler] = instance.Buttons;
            }

            Routes = routes.OrderBy(r => r.Item1).Select(r => (MessageRecived)r.Item2.OnMessage).ToArray();
        }
예제 #9
0
        private void Modbus_DataReceived(SerialPort sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            // IMPORTANT: this catch the incoming message, if you want read what is incoming,
            // catch the message MessageReceive (b() as Byte) from this class, you will lease the whole buffer
            // inclusive sclave and CRC

            BytesCount = 5; // Sclave, function,count + crc 1 & 2
            int      i   = 0;
            TimeSpan tim = new TimeSpan();
            DateTime tmp = DateTime.Now;

            tim = tmp.Subtract(DateTime.Now);

            // the speed of pc is higher than Arduino send, therefore I force him to stay here for 200 ms, in order to be sure that read whole
            // msg

            while (BytesCount > 0 & tim.TotalMilliseconds < 200)
            {
                while (sender.BytesToRead > 0)
                {
                    tmp        = DateTime.Now;
                    aIn[i]     = (byte)sender.ReadByte();
                    BytesCount = BytesCount - 1;

                    // TODO: to improve, too much ReDim.
                    if (i == 1 && aIn[1] == 16)
                    {
                        BytesCount = BytesCount + 3;
                    }
                    else if (i == 2 && aIn[1] < 129 & aIn[1] != 16)
                    {
                        BytesCount = BytesCount + aIn[2];
                    }
                    i = i + 1;


                    if (BytesCount == 0)
                    {
                        i          = 0;
                        BytesCount = 5;
                        int j;
                        if (CheckResponse(aIn))
                        {
                            MessageRecived?.Invoke(aIn);
                        }
                    }
                }
                tim = DateTime.Now.Subtract(tmp);
            }
            return;
        }
예제 #10
0
        public override void OnMessage(string message)
        {
            if (!_isOpened)
            {
                _receiveMessages.WaitOne();
            }

            Console.WriteLine("Connection message string");

            MessageRecived.Invoke(this, new SimpleEventArgs <string>()
            {
                Value = message
            });
        }
예제 #11
0
 public bool LoginStep2(string code)
 {
     this.code = code;
     try
     {
         var x = new Thread(() =>
         {
             Thread.CurrentThread.IsBackground = true;
             /* run your code here */
             ALogin2();
             Task.Delay(5000).Wait();
         });
         x.Start();
         x.Join();
         if (user != null)
         {
             var z = new Thread(() =>
             {
                 Thread.CurrentThread.IsBackground = true;
                 /* run your code here */
                 while (true)
                 {
                     if (users != null)
                     {
                         foreach (ChatterUser user in users)
                         {
                             var msgs = GetChatForUser(user, user.Messages.Count);
                             if (msgs.Any())
                             {
                                 user.Messages = msgs.ToList();
                                 MessageRecived?.Invoke(msgs, user);
                             }
                         }
                     }
                     Task.Delay(1000).Wait();
                 }
             });
             z.Start();
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
예제 #12
0
        protected ActionBase(T room)
        {
            Room = room;
            var self = GetType();

            Buttons   = new Dictionary <string, MessageRecived>();
            _fallback = null;

            foreach (var method in self.GetMethods())
            {
                var attr = method.GetCustomAttribute <MessageHandlerAttribute>();
                if (attr == null)
                {
                    continue;
                }

                var handler = (MessageRecived)Delegate.CreateDelegate(typeof(MessageRecived), this, method, false);

                switch (attr)
                {
                case ButtonAttribute button:
                {
                    if (Buttons.ContainsKey(button.Text))
                    {
                        throw new Exception($"Multiple handlers for button {button.Text}");
                    }

                    Buttons[button.Text] = handler;
                    break;
                }

                case FallbackAttribute _:
                {
                    if (_fallback != null)
                    {
                        throw new Exception("Multiple fallbacks found");
                    }

                    _fallback = handler;
                    break;
                }
                }
            }

            if (_fallback == null)
            {
                _fallback = Room.HandleButtonAlways;
            }
        }
예제 #13
0
 public RootRoom()
 {
     Routes  = new MessageRecived[] { ConfirmRestart };
     Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
     {
         {
             ConfirmRestart, new Dictionary <string, MessageRecived>
             {
                 { "Да", (user, message) => NewGame(user, "Ну раз вы так хотите, то ладно.") },
                 {
                     "Нет", (user, message) => { user.RoomManager.Leave(false); }
                 }
             }
         }
     };
 }
예제 #14
0
        public void SwitchAction(User.User user, MessageRecived handler)
        {
            if (handler == null)
            {
                GetRoomVariables(user).Remove("action");
                return;
            }

            var idx = Array.IndexOf(Routes, handler);

            if (idx == -1)
            {
                throw new ArgumentException("Unregistered handler! Every handler must be defined in _routes");
            }

            GetRoomVariables(user).Set("action", new Serializable.Int(idx));
        }
예제 #15
0
 /// <summary>
 /// In this funcion we read from the server in a thread as long
 /// as the client is connected
 /// </summary>
 private void Read()
 {
     new Task(() =>
     {
         while (_isConnect)
         {
             try
             {
                 string msg = _reader.ReadString();
                 MessageRecived?.Invoke(this, new DataCommandArgs(msg));
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
                 Close();
             }
         }
     }).Start();
 }
예제 #16
0
        public Connection(string uri)
        {
            _webSocket = new WebSocket(uri);

            _webSocket.Opened += (sender, args) =>
            {
                Console.WriteLine("OPENED");
                _reconnect.Reset();

                ConnectionStateChanged.Invoke(this, new SimpleEventArgs <bool>(true));
            };

            _webSocket.Error += (sender, args) =>
            {
                Console.WriteLine("ERROR");
                _reconnect.Set();
            };

            _webSocket.Closed += (sender, args) =>
            {
                Console.WriteLine("CLOSED");
                _reconnect.Set();

                ConnectionStateChanged.Invoke(this, new SimpleEventArgs <bool>(false));
            };

            _webSocket.MessageReceived += (sender, args) =>
            {
                MessageRecived.Invoke(this, new SimpleEventArgs <string>()
                {
                    Value = args.Message
                });
            };

            _webSocket.DataReceived += (sender, args) =>
            {
                DataRecived.Invoke(this, new SimpleEventArgs <byte[]>()
                {
                    Value = args.Data
                });
            };
        }
예제 #17
0
 public Wedding()
 {
     Routes  = new MessageRecived[] { TryLeave };
     Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
     {
         {
             null, new Dictionary <string, MessageRecived>
             {
                 { "Попытаться уйти", (user, message) => SwitchAndHandle(user, TryLeave, message) },
                 { "Выпить с ними", (user, message) => user.RoomManager.Leave() }
             }
         },
         {
             TryLeave, new Dictionary <string, MessageRecived>
             {
                 { "Выпить с ними", (user, message) => user.RoomManager.Leave() }
             }
         }
     };
 }
예제 #18
0
        public bool SendMessage(ref Message message)
        {
            message.Recived = false;
            string      msgText = message.Text;
            ChatterUser msgUser = message.User;

            if (msgText.StartsWith("reply", StringComparison.InvariantCultureIgnoreCase))
            {
                msgText = msgText.Substring(6);
                new Task(() =>
                {
                    Task.Delay(5000).Wait();
                    MessageRecived?.Invoke(new Message[] { new Message(msgUser)
                                                           {
                                                               Recived = true, Time = DateTime.Now.AddSeconds(5), Text = "Thanks for: " + msgText
                                                           } }, msgUser);
                }).Start();
            }
            return(true);
        }
        public ChatRoom(IHubProxy hub, string userName, string roomName)
        {
            this.room = roomName;
            this.user = userName;
            this.hub  = hub;

            // broadcast
            this.hub.On <string, string>(nameof(EnumAcciones.broadcast),
                                         (n, m) => MessageRecived?.Invoke(n, m)
                                         );

            //SendRoom
            this.hub.On <string, string>(nameof(EnumAcciones.sendRoom),
                                         (n, m) => MessageRecived?.Invoke(n, m)
                                         );

            //SendPrivate
            this.hub.On <string, string>(nameof(EnumAcciones.sendPrivate),
                                         (n, m) => PrivateMessageRecived?.Invoke(n, m)
                                         );

            hub.Invoke(nameof(EnumAcciones.joinRoom), room);
        }
예제 #20
0
 /// <summary>
 /// This function starts handling reading msg from the clients
 /// </summary>
 public void Start()
 {
     new Task(() =>
     {
         while (_isConnect)
         {
             try
             {
                 string data = _reader.ReadString();
                 if (data != "") // check if not an empty string
                 {
                     // raise the event
                     MessageRecived?.Invoke(this, new DataCommandArgs(data));
                 }
             }
             catch (Exception e)
             {
                 // close reader, writer and client connection
                 Close();
             }
         }
     }, _cancelToken.Token).Start();
 }
예제 #21
0
 public Adventures()
 {
     Routes  = new MessageRecived[] { RoomSelection };
     Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
     {
         {
             null, new Dictionary <string, MessageRecived>
             {
                 { "Налево", (user, message) => Go(user, Difficulity.Easy) },
                 { "Направо", (user, message) => Go(user, Difficulity.Medium) },
                 { "Прямо", (user, message) => Go(user, Difficulity.Hard) },
                 { "Назад", (user, message) => user.RoomManager.Leave() }
             }
         },
         {
             RoomSelection, new Dictionary <string, MessageRecived>
             {
                 { "Пойти в лес", (user, message) => RoomSelection(user, RoomSelectionMessage.Next) },
                 { "Пойти на поляну", (user, message) => RoomSelection(user, RoomSelectionMessage.Select) }
             }
         }
     };
 }
예제 #22
0
        public Market()
        {
            void Leave(User user, RecivedMessage message)
            {
                user.RoomManager.Leave();
            }

            Routes = new MessageRecived[]
            {
                Buy, Buy2, Sell, Sell2
            };

            Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
            {
                {
                    null, new Dictionary <string, MessageRecived>
                    {
                        { "Купить", Buy },
                        { "Продать", Sell },
                        { "Уйти", Leave }
                    }
                }
            };
        }
예제 #23
0
 private void GameServiceOnMessageRecived(string nickname, int stickerID)
 {
     MessageRecived?.Invoke(nickname, stickerID);
 }
예제 #24
0
 public MegaMonsterRoom()
 {
     Routes = new MessageRecived[]
     {
         Battle, Talk,
         GiveArtifact, ArtifactNotFound,
         GiveGold, NotEnoughGold,
         GiveKnowledge, NotEnoughKnowledge,
         SelectTarget
     };
     Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
     {
         {
             null, new Dictionary <string, MessageRecived>
             {
                 { "Сражаться", (user, message) => BeginBattle(user) },
                 { "Договориться", (user, message) => BeginTalk(user) }
             }
         },
         {
             SelectTarget, new Dictionary <string, MessageRecived>
             {
                 { "В голову", (user, message) => BattleTarget(user, Place.Head) },
                 { "В тело", (user, message) => BattleTarget(user, Place.Head) },
                 { "В ноги", (user, message) => BattleTarget(user, Place.Head) }
             }
         },
         {
             Talk, new Dictionary <string, MessageRecived>
             {
                 { "Артефакт", (user, message) => Artifact(user) },
                 { "Золото", (user, message) => Gold(user) },
                 { "Знания", (user, message) => Knowledge(user) },
                 { "Тут не о чем говорить. Битва!", (user, message) => BeginBattle(user) }
             }
         },
         {
             GiveArtifact, new Dictionary <string, MessageRecived>
             {
                 { "Отдать", (user, message) => ConfirmGiveArtifact(user) },
                 { "Он мне самому нужен", (user, message) => BeginTalk(user) }
             }
         },
         {
             ArtifactNotFound, new Dictionary <string, MessageRecived>
             {
                 { "У меня такого нет", (user, message) => BeginTalk(user) }
             }
         },
         {
             GiveGold, new Dictionary <string, MessageRecived>
             {
                 { "Отдать", (user, message) => ConfirmGiveGold(user) },
                 { "Я не готов к такому", (user, message) => BeginTalk(user) }
             }
         },
         {
             NotEnoughGold, new Dictionary <string, MessageRecived>
             {
                 { "У меня столько нет", (user, message) => BeginTalk(user) }
             }
         },
         {
             GiveKnowledge, new Dictionary <string, MessageRecived>
             {
                 { "Обучить", (user, message) => ConfirmGiveKnowledge(user) },
                 { "Монстр недостоин знаний!", (user, message) => BeginTalk(user) }
             }
         },
         {
             NotEnoughKnowledge, new Dictionary <string, MessageRecived>
             {
                 { "Я недостаточно умен", (user, message) => BeginTalk(user) }
             }
         }
     };
 }
예제 #25
0
 public void SwitchAndHandle(User.User user, MessageRecived handler, RecivedMessage message)
 {
     SwitchAction(user, handler);
     handler?.Invoke(user, message);
 }
예제 #26
0
        public Merchants()
        {
            Routes  = new MessageRecived[] { Shop, Shop2, Pay };
            Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
            {
                {
                    null, new Dictionary <string, MessageRecived>
                    {
                        {
                            "Закупиться", (user, message) =>
                            {
                                if (!Nothing(user))
                                {
                                    return;
                                }

                                SwitchAction(user, Shop);
                                HandleAction(user, message);
                            }
                        },
                        {
                            "Ограбить", (user, message) =>
                            {
                                if (!Nothing(user))
                                {
                                    return;
                                }

                                SendMessage(user,
                                            "Несмотря на их натренированные языки, сами купцы были довольно хилыми даже по твоим меркам. Поэтому на каждое из этих слащавых лиц пришлось всего по одному удару. Ты заработал немного монет и мое личное неуважение.");
                                var gold = user.Random.Next(500, 850);
                                user.Info.Gold += gold;
                                user.Info.ChangeStats(StatsProperty.Karma, -5);
                                user.VariableManager.UserVariables.Set("merchants_disabled",
                                                                       new Serializable.Decimal(gold));
                                user.RoomManager.Leave();
                            }
                        },
                        {
                            "Уйти", (user, message) => user.RoomManager.Leave()
                        }
                    }
                },
                {
                    Pay, new Dictionary <string, MessageRecived>
                    {
                        {
                            "Да", (user, message) =>
                            {
                                var paySize = (user.VariableManager.UserVariables
                                               .Get <Serializable.Decimal>("merchants_disabled") ?? 0M
                                               ) * 1.3M;
                                if (user.Info.TryDecreaseGold(paySize))
                                {
                                    SendMessage(user, "Отлично! Теперь торговцы могут торговать дальше.");
                                    user.VariableManager.UserVariables.Remove("merchants_disabled");
                                    user.Info.ChangeStats(StatsProperty.Karma, +2);
                                }
                                else
                                {
                                    SendMessage(user, "К сожалению, у тебя нет таких денег");
                                }

                                user.RoomManager.Leave();
                            }
                        },
                        {
                            "Нет", (user, message) =>
                            {
                                SendMessage(user, "Торговцы грустно поплелись дальше");
                                user.RoomManager.Leave();
                            }
                        }
                    }
                }
            };
        }
예제 #27
0
 public virtual void OnMesseageRecived(string message)
 => MessageRecived?.Invoke(this, new MessageEventArgs()
 {
     Message = message
 });
예제 #28
0
        public Mirror()
        {
            Routes  = new MessageRecived[] { EditStats, Inventory, ChangeName };
            Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >
            {
                {
                    null, new Dictionary <string, MessageRecived>
                    {
                        {
                            "Перераспределить предметы", (user, message) =>
                            {
                                SwitchAction(user, EditStats);
                                SendMessage(user, "Ты начал тщательно рыться в карманах");
                                EditStats(user, message);
                            }
                        },
                        {
                            "Имущество", (user, message) =>
                            {
                                GetRoomVariables(user).Set("current_page", new Serializable.Int(0));
                                SwitchAction(user, Inventory);
                                Inventory(user, message);
                            }
                        },
                        {
                            "Сменить имя", (user, message) =>
                            {
                                SwitchAction(user, ChangeName);
                                SendMessage(user, "Какое имя вы желаете?", GetButtons(user));
                            }
                        },
                        {
                            "Квесты", (user, message) =>
                            {
                                var found = false;
                                foreach (var quests in user.QuestManager.Quests.Values)
                                {
                                    foreach (var quest in quests.Values)
                                    {
                                        found = true;
                                        var msg = quest.Quest.GetName(user, quest.QuestId);
                                        msg += $"\nВыполнено {quest.Quest.GetProgress(user, quest.QuestId).Format()}%";
                                        SendMessage(user, msg, GetButtons(user));
                                    }
                                }

                                if (!found)
                                {
                                    SendMessage(user, "У вас нет квестов", GetButtons(user));
                                }
                            }
                        },
                        {
                            "Уйти", (user, message) => user.RoomManager.Leave()
                        }
                    }
                },
                {
                    ChangeName,
                    new Dictionary <string, MessageRecived>
                    {
                        {
                            "Сгенерировать случайное",
                            (user, message) => { user.Info.Name = Generator.Generate(user.Random); }
                        }
                    }
                }
            };
        }
예제 #29
0
 private void OnMessageRecvied(Socket socket, byte[] buffer)
 {
     MessageRecived?.Invoke(socket, buffer);
 }