예제 #1
0
        public override bool MoveStep()
        {
            if (Program.NrPlayers == 1)
            {
                return(base.MoveStep());
            }
            else if (this.playerNr == 1)
            {
                int X = this.x;
                int Y = this.y;

                bool Result = base.MoveStep();

                if (this.x != X || this.y != Y || Result)
                {
                    BinaryOutput Output = new BinaryOutput();
                    Output.WriteByte(8);
                    Output.WriteInt(this.x);
                    Output.WriteInt(this.y);
                    Output.WriteInt(this.vx);
                    Output.WriteInt(this.vy);
                    Output.WriteBool(Result);

                    Program.MPE.SendUdpToAll(Output.GetPacket(), 3);
                }

                return(Result);
            }
            else
            {
                return(false);
            }
        }
예제 #2
0
        /// <summary>
        /// Sends a PING message to the server. This is automatically done to keep the connection alive. Only call this method
        /// if you want to send additional PING messages, apart from the ones sent to keep the connection alive.
        /// </summary>
        public void PING()
        {
            BinaryOutput Packet = new BinaryOutput();

            Packet.WriteByte((byte)MqttControlPacketType.PINGREQ << 4);
            Packet.WriteUInt(0);

            byte[] PacketData = Packet.GetPacket();

            this.BeginWrite(PacketData, 0);

            EventHandler h = this.OnPing;

            if (!(h is null))
            {
                try
                {
                    h(this, new EventArgs());
                }
                catch (Exception ex)
                {
#if LineListener
                    LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                }
            }
        }
예제 #3
0
        private void P2pNetwork_OnPeerConnected(object Listener, PeerConnection Peer)
        {
            IPEndPoint Endpoint = (IPEndPoint)Peer.Tcp.Client.RemoteEndPoint;

#if LineListener
            Console.Out.WriteLine("Receiving connection from " + Endpoint.ToString());
#endif

            lock (this.remotePlayersByEndpoint)
            {
                if (!this.remotePlayerIPs.ContainsKey(Endpoint.Address))
                {
                    Peer.Dispose();
                    return;
                }
            }

            Peer.OnClosed   += new EventHandler(Peer_OnClosed);
            Peer.OnReceived += new BinaryEventHandler(Peer_OnReceived);

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalEndpoint.Address.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            Peer.SendTcp(Output.GetPacket());
        }
예제 #4
0
        /// <summary>
        /// Unsubscribes from information earlier subscribed to. Topics can include wildcards.
        /// </summary>
        /// <param name="Topics">Topics</param>
        /// <returns>Packet identifier assigned to unsubscription.</returns>
        public ushort UNSUBSCRIBE(params string[] Topics)
        {
            BinaryOutput Payload = new BinaryOutput();
            ushort       PacketIdentifier;

            PacketIdentifier = this.packetIdentifier++;
            if (PacketIdentifier == 0)
            {
                PacketIdentifier = this.packetIdentifier++;
            }

            Payload.WriteUInt16(PacketIdentifier);

            foreach (string Topic in Topics)
            {
                Payload.WriteString(Topic);
            }

            byte[] PayloadData = Payload.GetPacket();

            BinaryOutput Packet = new BinaryOutput();
            byte         b      = (byte)((int)MqttControlPacketType.UNSUBSCRIBE << 4);

            b |= 2;

            Packet.WriteByte(b);
            Packet.WriteUInt((uint)PayloadData.Length);
            Packet.WriteBytes(PayloadData);

            byte[] PacketData = Packet.GetPacket();

            this.BeginWrite(PacketData, PacketIdentifier);

            return(PacketIdentifier);
        }
예제 #5
0
        public override void AfterMove()
        {
            Color DestPixel = RetroApplication.Raster[this.x, this.y];

            if (DestPixel.ToArgb() != Color.Black.ToArgb())
            {
                if (DestPixel.R == 255 && DestPixel.B == 0)
                {
                    RetroApplication.FillFlood(this.x, this.y, Color.Black);

                    if (this.playerNr == 1)
                    {
                        BinaryOutput Output = new BinaryOutput();
                        int          Gift   = RetroApplication.Random(0, 31);

                        Output.WriteByte(7);
                        Output.WriteInt(Gift);

                        this.GetGift(1, Gift, Output, null);

                        if (Program.NrPlayers > 1)
                        {
                            Program.MPE.SendUdpToAll(Output.GetPacket(), 3);
                        }
                    }
                }
                else if (!this.immortal)
                {
                    this.Die();
                    return;
                }
            }

            if (!this.invisible || this.playerNr == 2)
            {
                RetroApplication.Raster[this.x, this.y] = this.headColor;
            }

            if (this.immortal)
            {
                int SecondsLeft = 10 - (int)(DateTime.Now - this.immortalStart).TotalSeconds;

                if (SecondsLeft != this.immortalSecondsLeft)
                {
                    if (SecondsLeft < 0)
                    {
                        this.immortal = false;
                        Program.PlayerMsg(this.playerNr, string.Empty);
                    }
                    else
                    {
                        this.immortalSecondsLeft = SecondsLeft;
                        Program.PlayerMsg(this.playerNr, "Immortal " + SecondsLeft.ToString());
                    }
                }
            }
        }
예제 #6
0
        private void PINGRESP()
        {
            BinaryOutput Packet = new BinaryOutput();

            Packet.WriteByte((byte)MqttControlPacketType.PINGRESP << 4);
            Packet.WriteUInt(0);

            byte[] PacketData = Packet.GetPacket();

            this.BeginWrite(PacketData, 0);
        }
예제 #7
0
        private void PUBCOMP(ushort PacketIdentifier)
        {
            BinaryOutput Packet = new BinaryOutput();

            Packet.WriteByte((byte)MqttControlPacketType.PUBCOMP << 4);
            Packet.WriteUInt(2);
            Packet.WriteUInt16(PacketIdentifier);

            byte[] PacketData = Packet.GetPacket();

            this.BeginWrite(PacketData, 0);
        }
예제 #8
0
        private ushort PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, bool Duplicate, byte[] Data)
        {
            BinaryOutput Payload = new BinaryOutput();
            ushort       PacketIdentifier;

            Payload.WriteString(Topic);

            if (QoS > MqttQualityOfService.AtMostOne)
            {
                PacketIdentifier = this.packetIdentifier++;
                if (PacketIdentifier == 0)
                {
                    PacketIdentifier = this.packetIdentifier++;
                }

                Payload.WriteUInt16(PacketIdentifier);
            }
            else
            {
                PacketIdentifier = 0;
            }

            Payload.WriteBytes(Data);

            byte[] PayloadData = Payload.GetPacket();

            BinaryOutput Packet = new BinaryOutput();
            byte         b      = (byte)((int)MqttControlPacketType.PUBLISH << 4);

            if (Duplicate)
            {
                b |= 8;
            }

            b |= (byte)((int)QoS << 1);

            if (Retain)
            {
                b |= 1;
            }

            Packet.WriteByte(b);
            Packet.WriteUInt((uint)PayloadData.Length);
            Packet.WriteBytes(PayloadData);

            byte[] PacketData = Packet.GetPacket();

            this.BeginWrite(PacketData, PacketIdentifier);

            return(PacketIdentifier);
        }
예제 #9
0
        private void DISCONNECT()
        {
            BinaryOutput Packet = new BinaryOutput();

            Packet.WriteByte((byte)MqttControlPacketType.DISCONNECT << 4);
            Packet.WriteUInt(2);

            byte[] PacketData = Packet.GetPacket();

            ManualResetEvent Done = new ManualResetEvent(false);

            this.stream.BeginWrite(PacketData, 0, PacketData.Length, this.EndDisconnect, Done);

            Done.WaitOne(1000);
        }
예제 #10
0
        private void CONNECT(int KeepAliveSeconds)
        {
            this.State            = MqttState.Authenticating;
            this.keepAliveSeconds = KeepAliveSeconds;
            this.nextPing         = DateTime.Now.AddMilliseconds(KeepAliveSeconds * 500);
            this.secondTimer      = new Timer(this.secondTimer_Elapsed, null, 1000, 1000);

            BinaryOutput Payload = new BinaryOutput();

            Payload.WriteString("MQTT");
            Payload.WriteByte(4);               // v3.1.1

            byte b = 2;                         // Clean session.

            Payload.WriteByte(b);

            Payload.WriteByte((byte)(KeepAliveSeconds >> 8));
            Payload.WriteByte((byte)KeepAliveSeconds);

            Payload.WriteString(this.clientId);
            if (!string.IsNullOrEmpty(this.userName))
            {
                b |= 128;
                Payload.WriteString(this.userName);

                if (!string.IsNullOrEmpty(this.password))
                {
                    b |= 64;
                    Payload.WriteString(this.password);
                }
            }

            byte[] PayloadData = Payload.GetPacket();

            BinaryOutput Packet = new BinaryOutput();

            Packet.WriteByte((byte)MqttControlPacketType.CONNECT << 4);
            Packet.WriteUInt((uint)PayloadData.Length);
            Packet.WriteBytes(PayloadData);

            byte[] PacketData = Packet.GetPacket();

            this.BeginWrite(PacketData, 0);
            this.inputState = 0;
            this.BeginRead();
        }
예제 #11
0
        /// <summary>
        /// Subscribes to information from a set of topics. Topics can include wildcards.
        /// </summary>
        /// <param name="Topics">Topics together with Quality of Service levels for each topic.</param>
        /// <returns>Packet identifier assigned to subscription.</returns>
        public ushort SUBSCRIBE(params KeyValuePair <string, MqttQualityOfService>[] Topics)
        {
            BinaryOutput Payload = new BinaryOutput();
            ushort       PacketIdentifier;

            PacketIdentifier = this.packetIdentifier++;
            if (PacketIdentifier == 0)
            {
                PacketIdentifier = this.packetIdentifier++;
            }

            Payload.WriteUInt16(PacketIdentifier);

            foreach (KeyValuePair <string, MqttQualityOfService> Pair in Topics)
            {
                Payload.WriteString(Pair.Key);
                Payload.WriteByte((byte)Pair.Value);
            }

            byte[] PayloadData = Payload.GetPacket();

            BinaryOutput Packet = new BinaryOutput();
            byte         b      = (byte)((int)MqttControlPacketType.SUBSCRIBE << 4);

            b |= 2;

            Packet.WriteByte(b);
            Packet.WriteUInt((uint)PayloadData.Length);
            Packet.WriteBytes(PayloadData);

            byte[] PacketData = Packet.GetPacket();

            this.BeginWrite(PacketData, PacketIdentifier);

            return(PacketIdentifier);
        }
예제 #12
0
		/// <summary>
		/// Publishes information on a topic.
		/// </summary>
		/// <param name="Topic">Topic name</param>
		/// <param name="QoS">Quality of service</param>
		/// <param name="Retain">If topic shoudl retain information.</param>
		/// <param name="Data">Binary data to send.</param>
		/// <returns>Packet identifier assigned to data.</returns>
		public int PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, BinaryOutput Data)
		{
			return this.PUBLISH(Topic, QoS, Retain, false, Data.GetPacket());
		}
예제 #13
0
		private void PINGRESP()
		{
			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)MqttControlPacketType.PINGRESP << 4);
			Packet.WriteUInt(0);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, 0);
		}
예제 #14
0
		/// <summary>
		/// Sends a PING message to the server. This is automatically done to keep the connection alive. Only call this method
		/// if you want to send additional PING messages, apart from the ones sent to keep the connection alive.
		/// </summary>
		public void PING()
		{
			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)MqttControlPacketType.PINGREQ << 4);
			Packet.WriteUInt(0);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, 0);

			EventHandler h = this.OnPing;
			if (h != null)
			{
				try
				{
					h(this, new EventArgs());
				}
				catch (Exception ex)
				{
#if LineListener
					LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
				}
			}
		}
예제 #15
0
		private void CONNECT(int KeepAliveSeconds)
		{
			this.State = MqttState.Authenticating;
			this.keepAliveSeconds = KeepAliveSeconds;
			this.nextPing = DateTime.Now.AddMilliseconds(KeepAliveSeconds * 500);
			this.secondTimer = new Timer(this.secondTimer_Elapsed, null, 1000, 1000);

			BinaryOutput Payload = new BinaryOutput();
			Payload.WriteString("MQTT");
			Payload.WriteByte(4);	// v3.1.1

			byte b = 2;		// Clean session.

			Payload.WriteByte(b);

			Payload.WriteByte((byte)(KeepAliveSeconds >> 8));
			Payload.WriteByte((byte)KeepAliveSeconds);

			Payload.WriteString(this.clientId);
			if (!string.IsNullOrEmpty(this.userName))
			{
				b |= 128;
				Payload.WriteString(this.userName);

				if (!string.IsNullOrEmpty(this.password))
				{
					b |= 64;
					Payload.WriteString(this.password);
				}
			}

			byte[] PayloadData = Payload.GetPacket();

			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)MqttControlPacketType.CONNECT << 4);
			Packet.WriteUInt((uint)PayloadData.Length);
			Packet.WriteBytes(PayloadData);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, 0);
			this.inputState = 0;
			this.BeginRead();
		}
예제 #16
0
		private void DISCONNECT()
		{
			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)MqttControlPacketType.DISCONNECT << 4);
			Packet.WriteUInt(2);

			byte[] PacketData = Packet.GetPacket();

			ManualResetEvent Done = new ManualResetEvent(false);

			this.stream.BeginWrite(PacketData, 0, PacketData.Length, this.EndDisconnect, Done);

			Done.WaitOne(1000);
		}
예제 #17
0
		/// <summary>
		/// Unsubscribes from information earlier subscribed to. Topics can include wildcards.
		/// </summary>
		/// <param name="Topics">Topics</param>
		/// <returns>Packet identifier assigned to unsubscription.</returns>
		public ushort UNSUBSCRIBE(params string[] Topics)
		{
			BinaryOutput Payload = new BinaryOutput();
			ushort PacketIdentifier;

			PacketIdentifier = this.packetIdentifier++;
			if (PacketIdentifier == 0)
				PacketIdentifier = this.packetIdentifier++;

			Payload.WriteUInt16(PacketIdentifier);

			foreach (string Topic in Topics)
				Payload.WriteString(Topic);

			byte[] PayloadData = Payload.GetPacket();

			BinaryOutput Packet = new BinaryOutput();
			byte b = (byte)((int)MqttControlPacketType.UNSUBSCRIBE << 4);
			b |= 2;

			Packet.WriteByte(b);
			Packet.WriteUInt((uint)PayloadData.Length);
			Packet.WriteBytes(PayloadData);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, PacketIdentifier);

			return PacketIdentifier;
		}
예제 #18
0
		private ushort PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, bool Duplicate, byte[] Data)
		{
			BinaryOutput Payload = new BinaryOutput();
			ushort PacketIdentifier;

			Payload.WriteString(Topic);

			if (QoS > MqttQualityOfService.AtMostOne)
			{
				PacketIdentifier = this.packetIdentifier++;
				if (PacketIdentifier == 0)
					PacketIdentifier = this.packetIdentifier++;

				Payload.WriteUInt16(PacketIdentifier);
			}
			else
				PacketIdentifier = 0;

			Payload.WriteBytes(Data);

			byte[] PayloadData = Payload.GetPacket();

			BinaryOutput Packet = new BinaryOutput();
			byte b = (byte)((int)MqttControlPacketType.PUBLISH << 4);
			if (Duplicate)
				b |= 8;

			b |= (byte)((int)QoS << 1);

			if (Retain)
				b |= 1;

			Packet.WriteByte(b);
			Packet.WriteUInt((uint)PayloadData.Length);
			Packet.WriteBytes(PayloadData);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, PacketIdentifier);

			return PacketIdentifier;
		}
예제 #19
0
 /// <summary>
 /// Publishes information on a topic.
 /// </summary>
 /// <param name="Topic">Topic name</param>
 /// <param name="QoS">Quality of service</param>
 /// <param name="Retain">If topic shoudl retain information.</param>
 /// <param name="Data">Binary data to send.</param>
 /// <returns>Packet identifier assigned to data.</returns>
 public int PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, BinaryOutput Data)
 {
     return(this.PUBLISH(Topic, QoS, Retain, false, Data.GetPacket()));
 }
예제 #20
0
		private void PUBREL(ushort PacketIdentifier)
		{
			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)(((int)MqttControlPacketType.PUBREL << 4) | 2));
			Packet.WriteUInt(2);
			Packet.WriteUInt16(PacketIdentifier);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, PacketIdentifier);
		}
예제 #21
0
        public static void Main(string[] _)
        {
            Initialize();

            Guid   PlayerId = Guid.NewGuid();
            string Player1Name;
            string Player2Name;

            Console.Out.WriteLine("Welcome to Mask! (Worms/Tron)");
            Console.Out.WriteLine(new string('-', 70));
            Console.Out.WriteLine("You control the work using the cursor keys.");
            Console.Out.WriteLine("Fire, using SPACE.");
            Console.Out.WriteLine("If you die, press ENTER to restart the game.");
            Console.Out.WriteLine("You can chat during the game.");
            Console.Out.WriteLine("Remember to try to fetch the gifts. You do that by moving into them.");
            Console.Out.WriteLine();
            Console.Out.WriteLine("Hello. What is your name?");
            Player1Name = Player2Name = Console.ReadLine();

            using (MPE = new MultiPlayerEnvironment("Mask", false, "iot.eclipse.org", 1883, false, string.Empty, string.Empty,
                                                    "RetroSharp/Examples/Games/Mask", 2, PlayerId, new KeyValuePair <string, string>("NAME", Player1Name)))
            {
                MPE.OnStateChange += (sender, state) =>
                {
                    switch (state)
                    {
                    case MultiPlayerState.SearchingForGateway:
                        Console.Out.WriteLine("Searching for Internet Gateway.");
                        break;

                    case MultiPlayerState.RegisteringApplicationInGateway:
                        Console.Out.WriteLine("Registering game in gateway.");
                        break;

                    case MultiPlayerState.FindingPlayers:
                        Console.Out.WriteLine("Waiting for another player to connect.");
                        Console.Out.WriteLine("Press ESC to play in single player mode.");
                        OnKeyDown += new KeyEventHandler(MPE_Wait_OnKeyDown);
                        break;

                    case MultiPlayerState.ConnectingPlayers:
                        Console.Out.WriteLine("Connecting to players.");
                        break;
                    }
                };

                MPE.OnPlayerAvailable += (sender, player) =>
                {
                    Console.Out.WriteLine("New player available: " + player["NAME"]);
                    MPE.ConnectPlayers();
                };

                MPE.OnPlayerConnected += (sender, player) =>
                {
                    Player2Name = player["NAME"];
                };

                MPE.OnPlayerDisconnected += (sender, player) =>
                {
                    PlayerMsg(2, "Disconnected");
                    NrPlayers = 1;
                    LocalMachineIsGameServer = true;
                };

                if (MPE.Wait(int.MaxValue))
                {
                    NrPlayers = MPE.PlayerCount;
                    LocalMachineIsGameServer = MPE.LocalPlayerIsFirst;
                }
                else
                {
                    PlayerMsg(2, "Network error");
                    NrPlayers = 1;
                }

                OnKeyDown -= new KeyEventHandler(MPE_Wait_OnKeyDown);

                ManualResetEvent            Done             = new ManualResetEvent(false);
                LinkedList <Shot>           Shots            = new LinkedList <Shot>();
                LinkedList <Explosion>      Explosions       = new LinkedList <Explosion>();
                LinkedList <Present>        Presents         = new LinkedList <Present>();
                LinkedList <PlayerPosition> Player2Positions = new LinkedList <PlayerPosition>();
                Player Player1      = new Player(1, 20, 28, 1, 0, 3, Color.Green, Color.LightGreen, 15);
                Player Player2      = new Player(2, 299, 179, -1, 0, 3, Color.Blue, Color.LightBlue, 15);
                bool   Player1Up    = false;
                bool   Player1Down  = false;
                bool   Player1Left  = false;
                bool   Player1Right = false;
                bool   Player1Fire  = false;
                bool   Player2Up    = false;
                bool   Player2Down  = false;
                bool   Player2Left  = false;
                bool   Player2Right = false;
                bool   Player2Fire  = false;

                Player1.Opponent = Player2;
                Player2.Opponent = Player1;

                Clear();
                FillRectangle(0, 0, 319, 7, Color.FromKnownColor(KnownColor.DimGray));
                SetClipArea(0, 8, 319, 199);

                string s = Player1Name.Length <= 10 ? Player1Name : Player1Name.Substring(0, 10);
                Console.Out.Write(s);

                s = Player2Name.Length <= 10 ? Player2Name : Player2Name.Substring(0, 10);
                GotoXY(ConsoleWidth - s.Length, 0);
                Console.Out.Write(s);

                OnKeyDown += (sender, e) =>
                {
                    switch (e.Key)
                    {
                    case Key.Escape:
                        if (MPE.State == MultiPlayerState.FindingPlayers)
                        {
                            MPE.ConnectPlayers();
                        }
                        else
                        {
                            Done.Set();
                        }
                        break;

                    case Key.C:
                        if (e.Control)
                        {
                            Done.Set();
                        }
                        break;

                    case Key.Up:
                        if (!Player1.Dead && Player1.VY != 1)
                        {
                            Player1Up = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Down = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 0 }, 3);
                            }
                        }
                        break;

                    case Key.Down:
                        if (!Player1.Dead && Player1.VY != -1)
                        {
                            Player1Down = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Up = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 1 }, 3);
                            }
                        }
                        break;

                    case Key.Left:
                        if (!Player1.Dead && Player1.VX != 1)
                        {
                            Player1Left = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Right = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 2 }, 3);
                            }
                        }
                        break;

                    case Key.Right:
                        if (!Player1.Dead && Player1.VX != -1)
                        {
                            Player1Right = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Left = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 3 }, 3);
                            }
                        }
                        break;

                    case Key.Space:
                        if (!Player1.Dead)
                        {
                            Player1Fire = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Fire = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 4 }, 3);
                            }
                        }
                        break;

                    case Key.Enter:
                        if (Player1.Dead)
                        {
                            if (NrPlayers > 1)
                            {
                                MPE.SendUdpToAll(new byte[] { 5 }, 3);
                            }
                            else
                            {
                                lock (Player2Positions)
                                {
                                    Player2Positions.Clear();
                                }

                                Shots.Clear();
                                Explosions.Clear();
                                Presents.Clear();
                                Player1      = new Player(1, 20, 28, 1, 0, 3, Color.Green, Color.LightGreen, 15);
                                Player2      = new Player(2, 299, 179, -1, 0, 3, Color.Blue, Color.LightBlue, 15);
                                Player1Up    = false;
                                Player1Down  = false;
                                Player1Left  = false;
                                Player1Right = false;
                                Player1Fire  = false;

                                Player1.Opponent = Player2;
                                Player2.Opponent = Player1;

                                FillRectangle(0, 8, 319, 199, Color.Black);
                                PlayerMsg(1, string.Empty);
                                PlayerMsg(2, string.Empty);
                            }
                        }
                        break;
                    }
                };

                OnKeyPressed += (sender, e) =>
                {
                    ChatCharacter(1, e.Character);
                    MPE.SendTcpToAll(new byte[] { 10, (byte)(e.Character >> 8), (byte)(e.Character) });
                };

                OnUpdateModel += (sender, e) =>
                {
                    if (LocalMachineIsGameServer && Random() < 0.005)
                    {
                        int x1, y1;

                        do
                        {
                            x1 = Random(30, 285);
                            y1 = Random(38, 165);
                        }while (!Present.CanPlace(x1, y1, x1 + 5, y1 + 5));

                        Presents.AddLast(new Present(x1, y1, x1 + 5, y1 + 5));

                        if (NrPlayers > 1)
                        {
                            BinaryOutput Output = new BinaryOutput();

                            Output.WriteByte(6);
                            Output.WriteInt(x1);
                            Output.WriteInt(y1);

                            MPE.SendUdpToAll(Output.GetPacket(), 3);
                        }
                    }

                    LinkedListNode <Present> PresentObj, NextPresentObj;

                    PresentObj = Presents.First;
                    while (!(PresentObj is null))
                    {
                        NextPresentObj = PresentObj.Next;
                        if (PresentObj.Value.Move())
                        {
                            Presents.Remove(PresentObj);
                        }

                        PresentObj = NextPresentObj;
                    }

                    if (Player1Up)
                    {
                        Player1.Up();
                        Player1Up = false;
                    }
                    else if (Player1Down)
                    {
                        Player1.Down();
                        Player1Down = false;
                    }
                    else if (Player1Left)
                    {
                        Player1.Left();
                        Player1Left = false;
                    }
                    else if (Player1Right)
                    {
                        Player1.Right();
                        Player1Right = false;
                    }

                    if (Player2Up)
                    {
                        Player2.Up();
                        Player2Up = false;
                    }
                    else if (Player2Down)
                    {
                        Player2.Down();
                        Player2Down = false;
                    }
                    else if (Player2Left)
                    {
                        Player2.Left();
                        Player2Left = false;
                    }
                    else if (Player2Right)
                    {
                        Player2.Right();
                        Player2Right = false;
                    }

                    if (!Player1.Dead && Player1.Move())
                    {
                        Explosions.AddLast(new Explosion(Player1.X, Player1.Y, 30, Color.White));
                    }

                    if (!Player2.Dead)
                    {
                        if (NrPlayers == 1)
                        {
                            if (Player2.Move())
                            {
                                Explosions.AddLast(new Explosion(Player2.X, Player2.Y, 30, Color.White));
                            }
                        }
                        else
                        {
                            lock (Player2Positions)
                            {
                                try
                                {
                                    foreach (PlayerPosition P in Player2Positions)
                                    {
                                        Player2.BeforeMove();
                                        Player2.SetPosition(P.X, P.Y, P.VX, P.VY);
                                        Player2.AfterMove();

                                        if (P.Dead)
                                        {
                                            Player2.Die();
                                            Explosions.AddLast(new Explosion(Player2.X, Player2.Y, 30, Color.White));
                                        }
                                    }
                                }
                                finally
                                {
                                    Player2Positions.Clear();
                                }
                            }
                        }
                    }

                    if (Player1Fire)
                    {
                        Player1.Fire(Shots);
                        Player1Fire = false;
                    }

                    if (Player2Fire)
                    {
                        Player2.Fire(Shots);
                        Player2Fire = false;
                    }

                    LinkedListNode <Shot> ShotObj, NextShotObj;

                    ShotObj = Shots.First;
                    while (!(ShotObj is null))
                    {
                        NextShotObj = ShotObj.Next;
                        if (ShotObj.Value.Move())
                        {
                            Shots.Remove(ShotObj);
                            Explosions.AddLast(new Explosion(ShotObj.Value.X, ShotObj.Value.Y, ShotObj.Value.Power, Color.White));
                        }

                        ShotObj = NextShotObj;
                    }

                    LinkedListNode <Explosion> ExplosionObj, NextExplosionObj;

                    ExplosionObj = Explosions.First;
                    while (!(ExplosionObj is null))
                    {
                        NextExplosionObj = ExplosionObj.Next;
                        if (ExplosionObj.Value.Move())
                        {
                            Explosions.Remove(ExplosionObj);
                        }

                        ExplosionObj = NextExplosionObj;
                    }
                };

                MPE.OnGameDataReceived += (sender, e) =>
                {
                    byte Command = e.Data.ReadByte();

                    switch (Command)
                    {
                    case 0:                             // Remote player presses UP
                        if (!Player2.Dead)
                        {
                            Player2Down = true;
                        }
                        break;

                    case 1:                             // Remote player presses DOWN
                        if (!Player2.Dead)
                        {
                            Player2Up = true;
                        }
                        break;

                    case 2:                             // Remote player presses LEFT
                        if (!Player2.Dead)
                        {
                            Player2Right = true;
                        }
                        break;

                    case 3:                             // Remote player presses RIGHT
                        if (!Player2.Dead)
                        {
                            Player2Left = true;
                        }
                        break;

                    case 4:                             // Remote player presses SPACE (Fire)
                        if (!Player2.Dead)
                        {
                            Player2Fire = true;
                        }
                        break;

                    case 5:                             // Remote player presses ENTER (Restart)
                    case 9:                             // Acknowledgement of remote player presses ENTER (Restart)

                        if (Command == 5)
                        {
                            MPE.SendUdpToAll(new byte[] { 9 }, 3);
                        }

                        lock (Player2Positions)
                        {
                            Player2Positions.Clear();
                        }

                        Shots.Clear();
                        Explosions.Clear();
                        Presents.Clear();
                        Player1      = new Player(1, 20, 28, 1, 0, 3, Color.Green, Color.LightGreen, 15);
                        Player2      = new Player(2, 299, 179, -1, 0, 3, Color.Blue, Color.LightBlue, 15);
                        Player1Up    = false;
                        Player1Down  = false;
                        Player1Left  = false;
                        Player1Right = false;
                        Player1Fire  = false;

                        Player1.Opponent = Player2;
                        Player2.Opponent = Player1;

                        FillRectangle(0, 8, 319, 199, Color.Black);
                        PlayerMsg(1, string.Empty);
                        PlayerMsg(2, string.Empty);

                        BorderColor = Color.FromKnownColor(KnownColor.DimGray);
                        break;

                    case 6:                             // New Present
                        int x1 = 315 - (int)e.Data.ReadInt();
                        int y1 = 203 - (int)e.Data.ReadInt();

                        Presents.AddLast(new Present(x1, y1, x1 + 5, y1 + 5));
                        break;

                    case 7:                             // Gift
                        x1 = (int)e.Data.ReadInt();
                        Player2.GetGift(2, x1, null, e.Data);
                        break;

                    case 8:                             // Move player 2
                        lock (Player2Positions)
                        {
                            Player2Positions.AddLast(new PlayerPosition(e.Data));
                        }
                        break;

                    case 10:                                    // chat character
                        char ch = (char)e.Data.ReadUInt16();
                        ChatCharacter(2, ch);
                        break;
                    }
                };

                while (!Done.WaitOne(1000))
                {
                    ;
                }
            }

            Terminate();
        }
예제 #22
0
        public static void Main(string[] args)
        {
            Initialize();

            try
            {
                DateTime Start    = DateTime.Now;
                Guid     PlayerId = Guid.NewGuid();
                string   Name;

                Console.Out.WriteLine("Hello. What is your name?");
                Name = Console.ReadLine();

                using (MultiPlayerEnvironment MPE = new MultiPlayerEnvironment("MultiPlayerSetup", true,
                                                                               "iot.eclipse.org", 1883, false, string.Empty, string.Empty, "RetroSharp/Examples/Networking/MultiPlayerSetup",
                                                                               5, PlayerId, new KeyValuePair <string, string>("NAME", Name)))
                {
                    MPE.OnStateChange += (sender, newstate) => Console.Out.WriteLine(newstate.ToString());

                    MPE.OnPlayerAvailable += (sender, player) =>
                    {
                        Console.Out.WriteLine("New player available: " + player["NAME"]);
                        if (sender.PlayerCount >= 5 || (DateTime.Now - Start).TotalSeconds >= 20)
                        {
                            MPE.ConnectPlayers();
                        }
                    };

                    MPE.OnPlayerConnected += (sender, player) => Console.Out.WriteLine("Player connected: " + player["NAME"]);

                    MPE.OnGameDataReceived += (sender, e) => Console.Out.WriteLine(e.FromPlayer["NAME"] + ": " + e.Data.ReadString());

                    MPE.OnPlayerDisconnected += (sender, player) => Console.Out.WriteLine("Player disconnected: " + player["NAME"]);

                    if (!MPE.Wait(20000))
                    {
                        if (MPE.State == MultiPlayerState.FindingPlayers)
                        {
                            MPE.ConnectPlayers();
                        }
                        else
                        {
                            throw new Exception("Unable to setup multi-player environment.");
                        }
                    }

                    Console.Out.WriteLine(MPE.PlayerCount.ToString() + " player(s) now connected.");
                    Console.Out.WriteLine("Write anything and send it to the others.");
                    Console.Out.WriteLine("An empty row will quit the application.");
                    Console.Out.WriteLine();

                    string s = Console.In.ReadLine();

                    while (!string.IsNullOrEmpty(s))
                    {
                        BinaryOutput Msg = new BinaryOutput();
                        Msg.WriteString(s);
                        MPE.SendTcpToAll(Msg.GetPacket());

                        s = Console.In.ReadLine();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                Console.In.ReadLine();
            }

            Terminate();
        }
예제 #23
0
		/// <summary>
		/// Subscribes to information from a set of topics. Topics can include wildcards.
		/// </summary>
		/// <param name="Topics">Topics together with Quality of Service levels for each topic.</param>
		/// <returns>Packet identifier assigned to subscription.</returns>
		public ushort SUBSCRIBE(params KeyValuePair<string, MqttQualityOfService>[] Topics)
		{
			BinaryOutput Payload = new BinaryOutput();
			ushort PacketIdentifier;

			PacketIdentifier = this.packetIdentifier++;
			if (PacketIdentifier == 0)
				PacketIdentifier = this.packetIdentifier++;

			Payload.WriteUInt16(PacketIdentifier);

			foreach (KeyValuePair<string, MqttQualityOfService> Pair in Topics)
			{
				Payload.WriteString(Pair.Key);
				Payload.WriteByte((byte)Pair.Value);
			}

			byte[] PayloadData = Payload.GetPacket();

			BinaryOutput Packet = new BinaryOutput();
			byte b = (byte)((int)MqttControlPacketType.SUBSCRIBE << 4);
			b |= 2;

			Packet.WriteByte(b);
			Packet.WriteUInt((uint)PayloadData.Length);
			Packet.WriteBytes(PayloadData);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, PacketIdentifier);

			return PacketIdentifier;
		}
예제 #24
0
        private void Connection_OnReceived(object Sender, byte[] Packet)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Guid           PlayerId;
            IPAddress      PlayerRemoteAddress;
            IPEndPoint     PlayerRemoteEndpoint;

            try
            {
                BinaryInput Input = new BinaryInput(Packet);

                PlayerId             = Input.ReadGuid();
                PlayerRemoteAddress  = IPAddress.Parse(Input.ReadString());
                PlayerRemoteEndpoint = new IPEndPoint(PlayerRemoteAddress, Input.ReadUInt16());
            }
            catch (Exception)
            {
                Connection.Dispose();
                return;
            }

            Player Player = (Player)Connection.StateObject;

            lock (this.remotePlayersByEndpoint)
            {
                if (!this.playersById.TryGetValue(PlayerId, out Player Player2) || Player2.PlayerId != Player.PlayerId)
                {
                    Connection.Dispose();
                    return;
                }

                Player.Connection = Connection;
            }

            Connection.RemoteEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

            Connection.OnReceived -= new BinaryEventHandler(Connection_OnReceived);
            Connection.OnReceived += new BinaryEventHandler(Peer_OnReceived);

            Connection.OnSent += new BinaryEventHandler(Connection_OnSent);

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalAddress.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            Connection.SendTcp(Output.GetPacket());

            MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;

            if (h != null)
            {
                try
                {
                    h(this, Player);
                }
                catch (Exception ex)
                {
                    Events.Log.Critical(ex);
                }
            }
        }
예제 #25
0
        private async Task <bool> Connection_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Guid           PlayerId;
            IPAddress      PlayerRemoteAddress;
            IPEndPoint     PlayerRemoteEndpoint;

            try
            {
                BinaryInput Input = new BinaryInput(BinaryTcpClient.ToArray(Buffer, Offset, Count));

                PlayerId             = Input.ReadGuid();
                PlayerRemoteAddress  = IPAddress.Parse(Input.ReadString());
                PlayerRemoteEndpoint = new IPEndPoint(PlayerRemoteAddress, Input.ReadUInt16());
            }
            catch (Exception)
            {
                Connection.Dispose();
                return(true);
            }

            Player Player = (Player)Connection.StateObject;

            lock (this.remotePlayersByEndpoint)
            {
                if (!this.playersById.TryGetValue(PlayerId, out Player Player2) || Player2.PlayerId != Player.PlayerId)
                {
                    Connection.Dispose();
                    return(true);
                }

                Player.Connection = Connection;
            }

            Connection.RemoteEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

            Connection.OnReceived -= this.Connection_OnReceived;
            Connection.OnReceived += this.Peer_OnReceived;
            Connection.OnSent     += this.Connection_OnSent;

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalAddress.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            await Connection.SendTcp(Output.GetPacket());

            MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;

            if (!(h is null))
            {
                try
                {
                    await h(this, Player);
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }

            return(true);
        }