public override void PeerChangedState(GKSession session, string peerID, GKPeerConnectionState state) { LocalNetworkGamer lng = new LocalNetworkGamer(); switch (state) { case GKPeerConnectionState.Available : break; case GKPeerConnectionState.Connected : if ( !gamerList.Contains(lng) ) { gamerList.Add(lng); } break; case GKPeerConnectionState.Connecting : break; case GKPeerConnectionState.Disconnected : if ( gamerList.Contains(lng) ) { gamerList.Remove(lng); } break; case GKPeerConnectionState.Unavailable : break; } }
public GamerServicesComponent(Game game) : base(game) { lng = new LocalNetworkGamer(); Guide.Window = game.Window; Guide.Initialise(game); }
public override void PeerChangedState(GKSession session, string peerID, GKPeerConnectionState state) { LocalNetworkGamer lng = new LocalNetworkGamer(); switch (state) { case GKPeerConnectionState.Available: break; case GKPeerConnectionState.Connected: if (!gamerList.Contains(lng)) { gamerList.Add(lng); } break; case GKPeerConnectionState.Connecting: break; case GKPeerConnectionState.Disconnected: if (gamerList.Contains(lng)) { gamerList.Remove(lng); } break; case GKPeerConnectionState.Unavailable: break; } }
/// <summary> /// Read server data /// </summary> public NetworkGamer ReadServerData(LocalNetworkGamer gamer) { NetworkGamer sender; // Read a single packet from the network. gamer.ReceiveData(ServerPacketReader, out sender); return sender; }
public NetworkGamer ReadClientData(LocalNetworkGamer gamer) { NetworkGamer sender; // Read a single packet from the network gamer.ReceiveData(networkHelper.ClientPacketReader, out sender); return sender; }
private void ProcessGamerJoined(CommandGamerJoined command) { NetworkGamer gamer; if ((command.State & GamerStates.Local) != 0) { gamer = new LocalNetworkGamer(this, (byte)command.InternalIndex, command.State); _allGamers.AddGamer(gamer); _localGamers.AddGamer((LocalNetworkGamer)gamer); // Note - This might be in the wrong place for certain connections // Take a look at HoneycombRush tut for debugging later. if (Gamer.SignedInGamers.Count >= _localGamers.Count) { ((LocalNetworkGamer)gamer).SignedInGamer = Gamer.SignedInGamers[_localGamers.Count - 1]; } // We will attach a property change handler to local gamers // se that we can broadcast the change to other peers. gamer.PropertyChanged += HandleGamerPropertyChanged; } else { gamer = new NetworkGamer(this, (byte)command.InternalIndex, command.State); gamer.DisplayName = command.DisplayName; gamer.Gamertag = command.GamerTag; gamer.RemoteUniqueIdentifier = command.remoteUniqueIdentifier; _allGamers.AddGamer(gamer); _remoteGamers.AddGamer(gamer); } if ((command.State & GamerStates.Host) != 0) { hostingGamer = gamer; } gamer.Machine = new NetworkMachine(); gamer.Machine.Gamers.AddGamer(gamer); //gamer.IsReady = true; if (GamerJoined != null) { GamerJoined(this, new GamerJoinedEventArgs(gamer)); } #if !PORTABLE if (networkPeer != null && (command.State & GamerStates.Local) == 0) { networkPeer.SendPeerIntroductions(gamer); } if (networkPeer != null) { networkPeer.UpdateLiveSession(this); } #endif }
/// <summary> /// Creates a new instance /// </summary> /// <param name="playerInput"></param> internal LiveIdentifiedPlayer(PlayerInput playerInput, LocalNetworkGamer localNetworkGamer) : base(playerInput) { LiveGamer = localNetworkGamer; UniqueId = localNetworkGamer.Gamertag; DisplayName = localNetworkGamer.Gamertag; IsHost = localNetworkGamer.IsHost; }
public void AddLocalGamer(SignedInGamer gamer) { if (LocalGamers.Count == maxLocalGamers) { throw new InvalidOperationException("LocalGamer max limit!"); } LocalNetworkGamer adding = new LocalNetworkGamer(gamer, this); LocalGamers.collection.Add(adding); AllGamers.collection.Add(adding); }
public CommandSendData(byte[] data, int offset, int count, SendDataOptions options, NetworkGamer gamer, LocalNetworkGamer sender) { if (gamer != null) this.gamerInternalIndex = (int) gamer.Id; this.data = new byte[count]; Array.Copy((Array) data, offset, (Array) this.data, 0, count); this.offset = offset; this.count = count; this.options = options; this.gamer = gamer; this.sender = sender; }
private static void HandleData(LocalNetworkGamer aGamer, GameTime gameTime) { while (aGamer.IsDataAvailable) { NetworkGamer sender; aGamer.ReceiveData(packetReader, out sender); if (!sender.IsLocal) { Console.WriteLine("Button: " + packetReader.ReadChar() + " pressed by player: " + aGamer.Gamertag); } } }
public Player(PlayerSprite playerSprite, LocalNetworkGamer gamer) { m_state = new PlayerState(new Vector2(0, 0), FacingDirection.South); m_playerSprite = playerSprite; Position = new Vector2(1, 1); m_velocity = new Vector2(0, 0); m_collissionWidth = 32; m_collissionHeight = 44; m_playerSprite.SetAnimation(PlayerAnimation.IdleDown); m_networkGamer = gamer; if (gamer != null) gamer.Tag = this; }
public CommandSendData(byte[] data, int offset, int count, SendDataOptions options, NetworkGamer gamer, LocalNetworkGamer sender) { if (gamer != null) { this.gamerInternalIndex = (int)gamer.Id; } this.data = new byte[count]; Array.Copy((Array)data, offset, (Array)this.data, 0, count); this.offset = offset; this.count = count; this.options = options; this.gamer = gamer; this.sender = sender; }
public NetworkSession CreateSession() { session = NetworkSession.Create(NetworkSessionType.SystemLink, MAX_LOCAL_PLAYERS, MAX_TOTAL_PLAYERS); session.AllowHostMigration = true; session.AllowJoinInProgress = true; session.GamerJoined += new EventHandler<GamerJoinedEventArgs>(session_GamerJoined); session.GamerLeft += new EventHandler<GamerLeftEventArgs>(session_GamerLeft); session.GameStarted += new EventHandler<GameStartedEventArgs>(session_GameStarted); session.GameEnded += new EventHandler<GameEndedEventArgs>(session_GameEnded); session.SessionEnded += new EventHandler<NetworkSessionEndedEventArgs>(session_SessionEnded); pr = new PacketReader(); pw = new PacketWriter(); sender = session.LocalGamers[0]; return session; }
/// <summary> /// Helper for updating a locally controlled gamer. /// </summary> void UpdateLocalGamer (LocalNetworkGamer gamer) { // Look up what tank is associated with this local player. Tank localTank = gamer.Tag as Tank; if (localTank != null) { // Update the tank. ReadTankInputs(localTank, gamer.SignedInGamer.PlayerIndex); localTank.Update(); // Write the tank state into a network packet. packetWriter.Write(localTank.Position); packetWriter.Write(localTank.TankRotation); packetWriter.Write(localTank.TurretRotation); // Send the data to everyone in the session. gamer.SendData(packetWriter, SendDataOptions.InOrder); } }
public void JoinSession(AvailableNetworkSession hostSession) { session = NetworkSession.Join(hostSession); pr = new PacketReader(); pw = new PacketWriter(); sender = session.LocalGamers[0]; }
private void UpdateLocalGamer(LocalNetworkGamer gamer) { while (outQueue.Count > 0) { QueueHdr hdr = outQueue.Dequeue(); switch (hdr.type) { default: case HeaderType.Location: int lType = (int)hdr.type; LocationHdr lHdr = (LocationHdr)hdr.pHdr; packetWriter.Write(lType); packetWriter.Write(lHdr.goIndex); packetWriter.Write(lHdr.position); packetWriter.Write(lHdr.rotation); break; case HeaderType.Input: int iType = (int)hdr.type; InputHdr iHdr = (InputHdr)hdr.pHdr; packetWriter.Write(iType); packetWriter.Write((int)iHdr.input); packetWriter.Write((int)iHdr.player); if (iHdr.input == InputType.Collision) { ColHdr cHdr = (ColHdr)iHdr.colInfo; packetWriter.Write(cHdr.goID1); packetWriter.Write(cHdr.goID2); packetWriter.Write(cHdr.pos); } break; } gamer.SendData(packetWriter, SendDataOptions.InOrder, Game1.Network.Session.Host); } }
/// <summary> /// Helper for reading incoming network packets. /// </summary> void ReadIncomingPackets(LocalNetworkGamer gamer) { // Keep reading as long as incoming packets are available. while (gamer.IsDataAvailable) { NetworkGamer sender; // Read a single packet from the network. gamer.ReceiveData(packetReader, out sender); // Discard packets sent by local gamers: we already know their state! if (sender.IsLocal) continue; // Look up the tank associated with whoever sent this packet. Player remotePlayer = sender.Tag as Player; // Read the state of this tank from the network packet. Vector2 pos = packetReader.ReadVector2(); remotePlayer.X = pos.X; remotePlayer.Y = pos.Y; } }
protected virtual void UpdateLocalGamer(LocalNetworkGamer gamer, GameTime gameTime, bool sendPacketThisFrame) { Player p = gamer.Tag as Player; if (p != null) { //p.UpdateLocalPlayer(gameTime); // Periodically send our state to everyone in the session. if (sendPacketThisFrame) { p.WriteNetworkPacket(packetWriter, gameTime); gamer.SendData(packetWriter, SendDataOptions.InOrder); } } }
/// <summary> /// Helper for reading incoming network packets. /// </summary> void ReadIncomingPackets(LocalNetworkGamer gamer, GameTime gameTime) { // Keep reading as long as incoming packets are available. while (gamer.IsDataAvailable) { NetworkGamer sender; // Read a single packet from the network. gamer.ReceiveData(packetReader, out sender); // Discard packets sent by local gamers: we already know their state! if (sender.IsLocal) continue; // Look up the tank associated with whoever sent this packet. Tank tank = sender.Tag as Tank; // Estimate how long this packet took to arrive. TimeSpan latency = networkSession.SimulatedLatency + TimeSpan.FromTicks(sender.RoundtripTime.Ticks / 2); // Read the state of this tank from the network packet. tank.ReadNetworkPacket(packetReader, gameTime, latency, enablePrediction, enableSmoothing); } }
private void MGServer_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker backgroundWorker = sender as BackgroundWorker; NetPeerConfiguration peerConfiguration = new NetPeerConfiguration(MonoGamerPeer.applicationIdentifier); peerConfiguration.EnableMessageType((NetIncomingMessageType)32); peerConfiguration.EnableMessageType((NetIncomingMessageType)64); peerConfiguration.EnableMessageType((NetIncomingMessageType)2048); if (this.availableSession == null) { peerConfiguration.set_Port(MonoGamerPeer.port); } this.peer = new NetServer(peerConfiguration); ((NetPeer)this.peer).Start(); this.myLocalAddress = MonoGamerPeer.GetMyLocalIpAddress(); this.myLocalEndPoint = new IPEndPoint(IPAddress.Parse(this.myLocalAddress), MonoGamerPeer.port); while (this.session.LocalGamers.Count <= 0) { Thread.Sleep(10); } if (this.availableSession != null) { if (!this.online) { ((NetPeer)this.peer).Connect(this.availableSession.EndPoint); } else { MonoGamerPeer.RequestNATIntroduction(this.availableSession.EndPoint, (NetPeer)this.peer); } } else if (this.online) { IPAddress address = NetUtility.Resolve(MonoGamerPeer.masterServer); if (address == null) { throw new Exception("Could not resolve live host"); } MonoGamerPeer.m_masterServer = new IPEndPoint(address, MonoGamerPeer.masterserverport); LocalNetworkGamer localNetworkGamer = this.session.LocalGamers[0]; NetOutgoingMessage message = ((NetPeer)this.peer).CreateMessage(); message.Write((byte)0); message.Write(this.session.AllGamers.Count); message.Write(localNetworkGamer.Gamertag); message.Write(this.session.PrivateGamerSlots); message.Write(this.session.MaxGamers); message.Write(localNetworkGamer.IsHost); message.Write(this.myLocalEndPoint); message.Write(((NetPeer)this.peer).get_Configuration().get_AppIdentifier()); int[] propertyData = new int[this.session.SessionProperties.Count * 2]; NetworkSessionProperties.WriteProperties(this.session.SessionProperties, propertyData); for (int index = 0; index < propertyData.Length; ++index) { message.Write(propertyData[index]); } ((NetPeer)this.peer).SendUnconnectedMessage(message, MonoGamerPeer.m_masterServer); } do { NetIncomingMessage netIncomingMessage; while ((netIncomingMessage = ((NetPeer)this.peer).ReadMessage()) != null) { NetIncomingMessageType messageType = netIncomingMessage.get_MessageType(); if (messageType <= 128) { if (messageType <= 8) { switch (messageType - 1) { case 0: NetConnectionStatus connectionStatus = (NetConnectionStatus)(int)netIncomingMessage.ReadByte(); if (connectionStatus == 5) { this.session.commandQueue.Enqueue(new CommandEvent((ICommand) new CommandGamerLeft(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier()))); } if (connectionStatus == 3 && !this.pendingGamers.ContainsKey(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier())) { this.pendingGamers.Add(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier(), netIncomingMessage.get_SenderConnection()); this.SendProfileRequest(netIncomingMessage.get_SenderConnection()); break; } else { break; } case 1: break; default: if (messageType == 8) { switch (netIncomingMessage.ReadByte()) { case (byte)0: byte[] data = new byte[netIncomingMessage.get_LengthBytes() - 1]; netIncomingMessage.ReadBytes(data, 0, data.Length); this.session.commandQueue.Enqueue(new CommandEvent((ICommand) new CommandReceiveData(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier(), data))); break; case (byte)3: string endPoint1 = netIncomingMessage.ReadString(); try { IPEndPoint endPoint2 = MonoGamerPeer.ParseIPEndPoint(endPoint1); if (this.myLocalEndPoint.ToString() != endPoint2.ToString() && !this.AlreadyConnected(endPoint2)) { ((NetPeer)this.peer).Connect(endPoint2); break; } else { break; } } catch (Exception ex) { break; } case (byte)4: if (this.pendingGamers.ContainsKey(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier())) { this.pendingGamers.Remove(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier()); netIncomingMessage.ReadInt32(); string str = netIncomingMessage.ReadString(); netIncomingMessage.ReadInt32(); netIncomingMessage.ReadInt32(); GamerStates gamerStates = (GamerStates)(netIncomingMessage.ReadInt32() & -2); this.session.commandQueue.Enqueue(new CommandEvent((ICommand) new CommandGamerJoined(netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier()) { GamerTag = str, State = gamerStates })); break; } else { break; } case (byte)5: this.SendProfile(netIncomingMessage.get_SenderConnection()); break; case (byte)6: GamerStates gamerStates1 = (GamerStates)(netIncomingMessage.ReadInt32() & -2); using (IEnumerator <NetworkGamer> enumerator = this.session.RemoteGamers.GetEnumerator()) { while (enumerator.MoveNext()) { NetworkGamer current = enumerator.Current; if (current.RemoteUniqueIdentifier == netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier()) { current.State = gamerStates1; } } break; } case (byte)7: NetworkSessionState networkSessionState = (NetworkSessionState)netIncomingMessage.ReadInt32(); using (IEnumerator <NetworkGamer> enumerator = this.session.RemoteGamers.GetEnumerator()) { while (enumerator.MoveNext()) { NetworkGamer current = enumerator.Current; if (current.RemoteUniqueIdentifier == netIncomingMessage.get_SenderConnection().get_RemoteUniqueIdentifier() && (current.IsHost && networkSessionState == NetworkSessionState.Playing)) { this.session.StartGame(); } } break; } } } else { break; } } } else if (messageType != 32) { if (messageType == 128) { ; } } else { LocalNetworkGamer localNetworkGamer = this.session.LocalGamers[0]; NetOutgoingMessage message = ((NetPeer)this.peer).CreateMessage(); message.Write(this.session.RemoteGamers.Count); message.Write(localNetworkGamer.Gamertag); message.Write(this.session.PrivateGamerSlots); message.Write(this.session.MaxGamers); message.Write(localNetworkGamer.IsHost); int[] propertyData = new int[this.session.SessionProperties.Count * 2]; NetworkSessionProperties.WriteProperties(this.session.SessionProperties, propertyData); for (int index = 0; index < propertyData.Length; ++index) { message.Write(propertyData[index]); } ((NetPeer)this.peer).SendDiscoveryResponse(message, netIncomingMessage.get_SenderEndpoint()); } } else if (messageType <= 512) { if (messageType == 256 || messageType == 512) { ; } } else if (messageType != 1024 && messageType == 2048) { ((NetPeer)this.peer).Connect(netIncomingMessage.get_SenderEndpoint()); } } Thread.Sleep(1); if (backgroundWorker.CancellationPending) { e.Cancel = true; this.done = true; } }while (!this.done); }
private void handleChangeToTeam(LocalNetworkGamer gamer, int team) { if ((int)gamer.Tag == team) return; gamer.Tag = team; _packetWriter.Write(team); gamer.SendData(_packetWriter, SendDataOptions.InOrder); }
void ServerReadInputFromClients(LocalNetworkGamer gamer) { while (gamer.IsDataAvailable) { NetworkGamer sender; gamer.ReceiveData(network.PacketReader, out sender); if (!sender.IsLocal) { Tank t = sender.Tag as Tank; bool shotFired = network.PacketReader.ReadBoolean(); if (shotFired) { Bullet b = new Bullet(); b.Position = network.PacketReader.ReadVector2(); b.Velocity = network.PacketReader.ReadVector2(); t.bullets.Add(b); } t.Position = network.PacketReader.ReadVector2(); t.Rotation = network.PacketReader.ReadDouble(); t.Score = network.PacketReader.ReadInt32(); t.MapScreenX = network.PacketReader.ReadInt32(); t.MapScreenY = network.PacketReader.ReadInt32(); } } }
private void handleMenuSelected(LocalNetworkGamer gamer) { if (!gamer.IsReady) gamer.IsReady = true; else if (gamer.IsHost) { MessageBoxScreen messageBox = new MessageBoxScreen("Are you sure you want to start the game,\neven though not all players are ready?"); messageBox.Accepted += ConfirmStartGameMessageBoxAccepted; ScreenManager.AddScreen(messageBox, gamer.SignedInGamer.PlayerIndex); } }
void ClientReadGameStateFromServer(LocalNetworkGamer gamer) { while (gamer.IsDataAvailable) { NetworkGamer sender; gamer.ReceiveData(network.PacketReader, out sender); foreach (NetworkGamer remoteGamer in network.Session.AllGamers) { Tank t = remoteGamer.Tag as Tank; t.Position = network.PacketReader.ReadVector2(); t.Rotation = network.PacketReader.ReadDouble(); bool a = network.PacketReader.ReadBoolean(); if (a) { Bullet b = new Bullet(); b.Position = network.PacketReader.ReadVector2(); b.Velocity = network.PacketReader.ReadVector2(); t.bullets.Add(b); } Bullet c = new Bullet(); } } }
/// <summary> /// Init the Peer to peer Network agent. Note the restrictions on idToCarActorMap. /// </summary> /// <param name="idTocarActorMap"> /// This is a map with a Gamer's id as key, and an ordered linked list of the cars controlled by the gamer as the value. /// The order must be the same on all gamers playing this game. /// </param> public PeerToPeerNetworkAgent(Game game, Dictionary<byte, LinkedList<CarActor>> idTocarActorMap, LocalNetworkGamer localGamer) : base(game) { this.idTocarActorMap_ = idTocarActorMap; this.localGamer_ = localGamer; }
/// <summary> /// Helper for updating a locally controlled gamer. /// </summary> void UpdateLocalGamer(LocalNetworkGamer gamer) { // Look up what tank is associated with this local player. Player player = gamer.Tag as Player; GamePadState gamePad = GamePad.GetState(gamer.SignedInGamer.PlayerIndex); player.X = gamePad.ThumbSticks.Left.X; player.Y = gamePad.ThumbSticks.Left.Y; // Write the tank state into a network packet. packetWriter.Write(player.Position); // Send the data to everyone in the session. gamer.SendData(packetWriter, SendDataOptions.InOrder); }
/// <summary> /// Helper for reading incoming network packets. /// </summary> void ReadIncomingPackets (LocalNetworkGamer gamer) { // Keep reading as long as incoming packets are available. while (gamer.IsDataAvailable) { NetworkGamer sender; // Read a single packet from the network. gamer.ReceiveData (packetReader, out sender); // Discard packets sent by local gamers: we already know their state! if (sender.IsLocal) continue; // Look up the tank associated with whoever sent this packet. Tank remoteTank = sender.Tag as Tank; if (remoteTank != null) { // Read the state of this tank from the network packet. remoteTank.Position = packetReader.ReadVector2(); remoteTank.TankRotation = packetReader.ReadSingle(); remoteTank.TurretRotation = packetReader.ReadSingle(); } } }
/// <summary> /// Helper for reading incoming network packets. /// </summary> void ReadIncomingPackets (LocalNetworkGamer gamer) { // Keep reading as long as incoming packets are available. while (gamer.IsDataAvailable) { NetworkGamer sender; // Read a single packet from the network. gamer.ReceiveData (packetReader, out sender); // Discard packets sent by local gamers: we already know their state! if (sender.IsLocal) continue; MessageType msgType = (MessageType)packetReader.ReadInt32 (); switch (msgType) { case MessageType.NewGame: //ReceiveNewNetworkedGame(); break; case MessageType.CatapultAiming: if (isFirstPlayerTurn && !NetworkSession.IsHost) { playerOne.Catapult.CurrentState = CatapultState.Aiming; playerOne.isDragging = true; catapultInfoVector = packetReader.ReadVector3(); playerOne.Catapult.ShotStrength = catapultInfoVector.X; playerOne.Catapult.ShotVelocity = catapultInfoVector.Y; playerOne.ArrowScale = catapultInfoVector.Z; } if (!isFirstPlayerTurn && NetworkSession.IsHost) { playerTwo.Catapult.CurrentState = CatapultState.Aiming; playerTwo.isDragging = true; catapultInfoVector = packetReader.ReadVector3(); playerTwo.Catapult.ShotStrength = catapultInfoVector.X; playerTwo.Catapult.ShotVelocity = catapultInfoVector.Y; playerTwo.ArrowScale = catapultInfoVector.Z; } break; case MessageType.CatapultFiring: if (isFirstPlayerTurn && !NetworkSession.IsHost) { catapultInfoVector = packetReader.ReadVector3(); playerOne.Catapult.Fire (catapultInfoVector.Y); playerOne.Catapult.CurrentState = CatapultState.Firing; playerOne.ResetDragState(); } if (!isFirstPlayerTurn && NetworkSession.IsHost) { catapultInfoVector = packetReader.ReadVector3(); playerTwo.Catapult.Fire (catapultInfoVector.Y); playerTwo.Catapult.CurrentState = CatapultState.Firing; playerTwo.ResetDragState(); } break; case MessageType.UpdateEnvironment: wind = packetReader.ReadVector2(); cloud1Position = packetReader.ReadVector2(); cloud2Position = packetReader.ReadVector2(); // Set new wind value to the players and playerOne.Catapult.Wind = playerTwo.Catapult.Wind = wind.X > 0 ? wind.Y : -wind.Y; break; } } }
private void MGServer_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; NetPeerConfiguration config = new NetPeerConfiguration(applicationIdentifier); config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse); config.EnableMessageType(NetIncomingMessageType.NatIntroductionSuccess); if (availableSession == null) { config.Port = port; } // create and start server peer = new NetServer(config); peer.Start(); myLocalAddress = GetMyLocalIpAddress(); IPAddress adr = IPAddress.Parse(myLocalAddress); myLocalEndPoint = new IPEndPoint(adr, port); // force a little wait until we have a LocalGamer otherwise things // break. This is the first item in the queue so it shouldnt take long before we // can continue. while (session.LocalGamers.Count <= 0) { Thread.Sleep(10); } if (availableSession != null) { if (!this.online) { peer.Connect(availableSession.EndPoint); } else { RequestNATIntroduction(availableSession.EndPoint, peer); } } else { if (this.online) { IPAddress ipaddr = NetUtility.Resolve(masterServer); if (ipaddr != null) { m_masterServer = new IPEndPoint(ipaddr, masterserverport); LocalNetworkGamer localMe = session.LocalGamers [0]; NetOutgoingMessage om = peer.CreateMessage(); om.Write((byte)0); om.Write(session.AllGamers.Count); om.Write(localMe.Gamertag); om.Write(session.PrivateGamerSlots); om.Write(session.MaxGamers); om.Write(localMe.IsHost); om.Write(myLocalEndPoint); om.Write(peer.Configuration.AppIdentifier); // send up session properties int[] propertyData = new int[session.SessionProperties.Count * 2]; NetworkSessionProperties.WriteProperties(session.SessionProperties, propertyData); for (int x = 0; x < propertyData.Length; x++) { om.Write(propertyData [x]); } peer.SendUnconnectedMessage(om, m_masterServer); // send message to peer } else { throw new Exception("Could not resolve live host"); } } } // run until we are done do { NetIncomingMessage msg; while ((msg = peer.ReadMessage()) != null) { switch (msg.MessageType) { case NetIncomingMessageType.UnconnectedData: break; case NetIncomingMessageType.NatIntroductionSuccess: #if !WINDOWS_PHONE Game.Instance.Log("NAT punch through OK " + msg.SenderEndPoint); #endif peer.Connect(msg.SenderEndPoint); break; case NetIncomingMessageType.DiscoveryRequest: // // Server received a discovery request from a client; send a discovery response (with no extra data attached) // // Get the primary local gamer LocalNetworkGamer localMe = session.LocalGamers [0]; NetOutgoingMessage om = peer.CreateMessage(); om.Write(session.RemoteGamers.Count); om.Write(localMe.Gamertag); om.Write(session.PrivateGamerSlots); om.Write(session.MaxGamers); om.Write(localMe.IsHost); int[] propertyData = new int[session.SessionProperties.Count * 2]; NetworkSessionProperties.WriteProperties(session.SessionProperties, propertyData); for (int x = 0; x < propertyData.Length; x++) { om.Write(propertyData [x]); } peer.SendDiscoveryResponse(om, msg.SenderEndPoint); break; case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: // // Just print diagnostic messages to console // #if !WINDOWS_PHONE Game.Instance.Log(msg.ReadString()); #endif break; case NetIncomingMessageType.StatusChanged: NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte(); if (status == NetConnectionStatus.Disconnected) { #if !WINDOWS_PHONE Game.Instance.Log(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " disconnected! from " + msg.SenderEndPoint); #endif CommandGamerLeft cgj = new CommandGamerLeft(msg.SenderConnection.RemoteUniqueIdentifier); CommandEvent cmde = new CommandEvent(cgj); session.commandQueue.Enqueue(cmde); } if (status == NetConnectionStatus.Connected) { // // A new player just connected! // if (!pendingGamers.ContainsKey(msg.SenderConnection.RemoteUniqueIdentifier)) { #if !WINDOWS_PHONE Game.Instance.Log(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected! from " + msg.SenderEndPoint); #endif pendingGamers.Add(msg.SenderConnection.RemoteUniqueIdentifier, msg.SenderConnection); SendProfileRequest(msg.SenderConnection); } else { #if !WINDOWS_PHONE Game.Instance.Log("Already have a connection for that user, this is probably due to both NAT intro requests working"); #endif } } break; case NetIncomingMessageType.Data: NetworkMessageType mt = (NetworkMessageType)msg.ReadByte(); switch (mt) { case NetworkMessageType.Data: byte[] data = new byte[msg.LengthBytes - 1]; msg.ReadBytes(data, 0, data.Length); CommandEvent cme = new CommandEvent(new CommandReceiveData(msg.SenderConnection.RemoteUniqueIdentifier, data)); session.commandQueue.Enqueue(cme); break; case NetworkMessageType.Introduction: var introductionAddress = msg.ReadString(); try { IPEndPoint endPoint = ParseIPEndPoint(introductionAddress); if (myLocalEndPoint.ToString() != endPoint.ToString() && !AlreadyConnected(endPoint)) { #if !WINDOWS_PHONE Game.Instance.Log("Received Introduction for: " + introductionAddress + " and I am: " + myLocalEndPoint + " from: " + msg.SenderEndPoint); #endif peer.Connect(endPoint); } } catch (Exception exc) { #if !WINDOWS_PHONE Game.Instance.Log("Error parsing Introduction: " + introductionAddress + " : " + exc.Message); #endif } break; case NetworkMessageType.GamerProfile: #if !WINDOWS_PHONE Game.Instance.Log("Profile recieved from: " + NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier)); #endif if (pendingGamers.ContainsKey(msg.SenderConnection.RemoteUniqueIdentifier)) { pendingGamers.Remove(msg.SenderConnection.RemoteUniqueIdentifier); msg.ReadInt32(); string gamerTag = msg.ReadString(); msg.ReadInt32(); msg.ReadInt32(); GamerStates state = (GamerStates)msg.ReadInt32(); state &= ~GamerStates.Local; CommandGamerJoined cgj = new CommandGamerJoined(msg.SenderConnection.RemoteUniqueIdentifier); cgj.GamerTag = gamerTag; cgj.State = state; CommandEvent cmde = new CommandEvent(cgj); session.commandQueue.Enqueue(cmde); } else { #if !WINDOWS_PHONE Game.Instance.Log("We received a profile for an existing gamer. Need to update it."); #endif } break; case NetworkMessageType.RequestGamerProfile: #if !WINDOWS_PHONE Game.Instance.Log("Profile Request recieved from: " + msg.SenderEndPoint); #endif SendProfile(msg.SenderConnection); break; case NetworkMessageType.GamerStateChange: GamerStates gamerstate = (GamerStates)msg.ReadInt32(); gamerstate &= ~GamerStates.Local; #if !WINDOWS_PHONE Game.Instance.Log("State Change from: " + msg.SenderEndPoint + " new State: " + gamerstate); #endif foreach (var gamer in session.RemoteGamers) { if (gamer.RemoteUniqueIdentifier == msg.SenderConnection.RemoteUniqueIdentifier) { gamer.State = gamerstate; } } break; case NetworkMessageType.SessionStateChange: NetworkSessionState sessionState = (NetworkSessionState)msg.ReadInt32(); foreach (var gamer in session.RemoteGamers) { if (gamer.RemoteUniqueIdentifier == msg.SenderConnection.RemoteUniqueIdentifier) { #if !WINDOWS_PHONE Game.Instance.Log("Session State change from: " + NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " session is now: " + sessionState); #endif if (gamer.IsHost && sessionState == NetworkSessionState.Playing) { session.StartGame(); } } } break; } break; } } // sleep to allow other processes to run smoothly // This may need to be changed depending on network throughput Thread.Sleep(1); if (worker.CancellationPending) { #if !WINDOWS_PHONE Game.Instance.Log("worker CancellationPending"); #endif e.Cancel = true; done = true; } } while (!done); }
/// <summary> /// Handle MenuCancel inputs by clearing our ready status, or if it is /// already clear, prompting if the user wants to leave the session. /// </summary> void HandleMenuCancel(LocalNetworkGamer gamer) { if (gamer.IsReady) { gamer.IsReady = false; } else { PlayerIndex playerIndex = gamer.SignedInGamer.PlayerIndex; NetworkSessionComponent.LeaveSession(ScreenManager, playerIndex); } }
/// <summary> /// Helper for updating a locally controlled gamer. /// </summary> void UpdateLocalGamer(LocalNetworkGamer gamer, GameTime gameTime, bool sendPacketThisFrame) { // Look up what tank is associated with this local player. Tank tank = gamer.Tag as Tank; // Read the inputs controlling this tank. PlayerIndex playerIndex = gamer.SignedInGamer.PlayerIndex; Vector2 tankInput; Vector2 turretInput; ReadTankInputs(playerIndex, out tankInput, out turretInput); // Update the tank. tank.UpdateLocal(tankInput, turretInput); // Periodically send our state to everyone in the session. if (sendPacketThisFrame) { tank.WriteNetworkPacket(packetWriter, gameTime); gamer.SendData(packetWriter, SendDataOptions.InOrder); } }
/// <summary> /// Handle MenuSelect inputs by marking ourselves as ready. /// </summary> void HandleMenuSelect(LocalNetworkGamer gamer) { if (!gamer.IsReady) { gamer.IsReady = true; } else if (gamer.IsHost) { // The host has an option to force starting the game, even if not // everyone has marked themselves ready. If they press select twice // in a row, the first time marks the host ready, then the second // time we ask if they want to force start. MessageBoxScreen messageBox = new MessageBoxScreen( Resources.ConfirmForceStartGame); messageBox.Accepted += ConfirmStartGameMessageBoxAccepted; ScreenManager.AddScreen(messageBox, gamer.SignedInGamer.PlayerIndex); } }
protected virtual void ReadIncomingPackets(LocalNetworkGamer gamer, GameTime gameTime) { while (gamer.IsDataAvailable) { NetworkGamer sender; gamer.ReceiveData(packetReader, out sender); if (!sender.IsLocal && sender.Tag != null) { Player p = sender.Tag as Player; TimeSpan latency = NetworkManager.Session.SimulatedLatency + TimeSpan.FromTicks(sender.RoundtripTime.Ticks / 2); // Read the state of this tank from the network packet. p.ReadNetworkPacket(packetReader, gameTime, latency); } } }
private void PushToNetwork(LocalNetworkGamer gamer) { if (Game1.Network.Session.IsHost) { UpdateServer(gamer); } else { UpdateLocalGamer(gamer); } }
void UpdateLocalGamer(LocalNetworkGamer gamer, Tank t, GameTime gameTime) { hostFireShot = false; timer = timer + (float)gameTime.ElapsedGameTime.TotalMilliseconds; singleShotTimer = singleShotTimer + (float)gameTime.ElapsedGameTime.TotalMilliseconds; if (timer > interval) { shotCount = 0; timer = 0; } bool shotFired = false; Bullet bul = null; t.Velocity = Vector2.Zero; if (input.IsButtonDown(Buttons.A)) { buttonADown = true; } if (!input.IsButtonDown(Buttons.A)) { buttonADown = false; } // east if (input.IsButtonDown(Buttons.LeftThumbstickRight)) { // north east if (input.IsButtonDown(Buttons.LeftThumbstickUp)) { t.Velocity = new Vector2(3.0f, -3.0f); t.Rotation = -(Math.PI / 4); } // south east else if (input.IsButtonDown(Buttons.LeftThumbstickDown)) { t.Velocity = new Vector2(3.0f, 3.0f); t.Rotation = (Math.PI / 4); } // east else { t.Velocity = new Vector2(3.0f, 0.0f); t.Rotation = 0; } } // west if (input.IsButtonDown(Buttons.LeftThumbstickLeft)) { // north west if (input.IsButtonDown(Buttons.LeftThumbstickUp)) { t.Velocity = new Vector2(-3.0f, -3.0f); t.Rotation = -(3 * Math.PI / 4); } // south west else if (input.IsButtonDown(Buttons.LeftThumbstickDown)) { t.Velocity = new Vector2(-3.0f, 3.0f); t.Rotation = (3 * Math.PI / 4); } // west else { t.Velocity = new Vector2(-3.0f, 0.0f); t.Rotation = Math.PI; } } if (input.IsButtonDown(Buttons.LeftThumbstickDown) && (!input.IsButtonDown(Buttons.LeftThumbstickLeft)) && (!input.IsButtonDown(Buttons.LeftThumbstickRight))) { t.Velocity = new Vector2(0.0f, 3.0f); t.Rotation = Math.PI / 2; } if (input.IsButtonDown(Buttons.LeftThumbstickUp) && (!input.IsButtonDown(Buttons.LeftThumbstickLeft)) && (!input.IsButtonDown(Buttons.LeftThumbstickRight))) { t.Velocity = new Vector2(0.0f, -3.0f); t.Rotation = -Math.PI / 2; } if (input.IsButtonDown(Buttons.B)) { if (singleShotTimer > singleShotInterval && shotCount <= 2) { shotFired = true; double a = Math.Cos(t.Rotation); double c = Math.Sin(t.Rotation); Bullet b = new Bullet(); b.Position = t.Position; b.Velocity = new Vector2((float)(3 * a), (float)(3 * c)); b.Position += 5 * b.Velocity; t.bullets.Add(b); bul = b; singleShotTimer = 0; shotCount++; totalShotsFired++; hostFireShot = true; hostBulletPosition = b.Position; hostBulletVelocity = b.Velocity; } } foreach (Bullet b in t.bullets) { b.Position += b.Velocity; } foreach (NetworkGamer g in network.Session.AllGamers) { if (!g.IsLocal) { Tank t2 = g.Tag as Tank; foreach (Bullet b in t2.bullets) { b.Position += b.Velocity; } } } Vector2 newPos = t.Position + t.Velocity; bool changePosX = true; bool changePosY = true; if (t.PositionX <= 26) { if (map.map[(int)t.MapScreenX, (int)t.MapScreenY].WestWall == 49) { changePosX = false; t.PositionX = 27; } } if (t.PositionX >= 240 - 26) { if (map.map[(int)t.MapScreenX, (int)t.MapScreenY].EastWall == 49) { changePosX = false; t.PositionX = 240 - 27; } } if (t.positionY <= 26) { if (map.map[(int)t.MapScreenX, (int)t.MapScreenY].NorthWall == 49) { changePosY = false; t.positionY = 27; } } if (t.positionY >= 240 - 27) { if (map.map[(int)t.MapScreenX, (int)t.MapScreenY].SouthWall == 49) { changePosY = false; t.positionY = 240 - 28; } } if (changePosX) t.PositionX = t.PositionX + t.Velocity.X; if (changePosY) t.positionY = t.positionY + t.Velocity.Y; if ((t.Position.X > (240 - 16))) // on the right edge of the screen { t.PositionX = 16; t.GlobalPositionX = t.GlobalPositionX + 16; t.MapScreenX++; } if ((t.Position.X < (16))) // on the left edge of the screen { t.PositionX = 240 - 16; t.GlobalPositionX = t.GlobalPositionX - 16; t.MapScreenX--; } if ((t.Position.Y > (240 - 16))) // on the bottom edge of the screen { t.positionY = 16; t.GlobalPositionY = t.GlobalPositionY + 16; t.MapScreenY++; } if ((t.positionY < 16)) { t.positionY = 240 - 16; t.GlobalPositionY = t.GlobalPositionY - 16; t.MapScreenY--; } t.GlobalPosition = t.GlobalPosition + t.Velocity; Bullet bulletToDelete = new Bullet(); bool bulletHit = false; foreach (NetworkGamer gamer2 in network.Session.AllGamers) { if (!gamer2.IsLocal) { Tank gamerTank = gamer2.Tag as Tank; Rectangle tankRect = new Rectangle((int)gamerTank.PositionX, (int)gamerTank.positionY, 32, 32); boundRect = new Rectangle((int)gamerTank.PositionX - 16, (int)gamerTank.positionY - 16, 32, 32); foreach (Bullet b in t.bullets) { Rectangle bulletRect = new Rectangle((int)b.PositionX, (int)b.positionY, 5, 5); if (tankRect.Intersects(bulletRect) && !bulletHit) { b.PositionX = b.positionY = 400; bulletToDelete = b; t.Score++; bulletHit = true; } } } } t.bullets.Remove(bulletToDelete); if (buttonADown) { WorldView = true; } else { WorldView = false; } network.PacketWriter.Write(shotFired); if (shotFired) { network.PacketWriter.Write(bul.Position); network.PacketWriter.Write(bul.Velocity); } network.PacketWriter.Write(t.Position); network.PacketWriter.Write(t.Rotation); network.PacketWriter.Write(t.Score); network.PacketWriter.Write(t.MapScreenX); network.PacketWriter.Write(t.MapScreenY); gamer.SendData(network.PacketWriter, SendDataOptions.InOrder); }
private void ReadIncomingPackets(LocalNetworkGamer gamer) { while (gamer.IsDataAvailable) { NetworkGamer sender; gamer.ReceiveData(_packetReader, out sender); if (sender.IsLocal) continue; int newTeam = _packetReader.ReadByte(); sender.Tag = newTeam; } }