/* When I'm done processing received highscores, send an Ack to the other * end so he/she can send more data. */ protected virtual void SendAck(short tok, NetworkGamer from) { packetWriter.Write((byte)HighscoreItemsAck); packetWriter.Write((short)tok); session.LocalGamers[0].SendData(packetWriter, SendDataOptions.Reliable, from); packetWriter.Flush(); packetWriter.Seek(0, System.IO.SeekOrigin.Begin); }
internal JoinedGamer(NetworkGamer ng) { gamer = ng; ix = 0; clearToSend = true; pmw = new PacketMarshalWriter(); pmw.Writer = new PacketWriter(); }
public static Bullet fireBullet(Vector3 startPosition, Vector3 velocity, NetworkGamer shooter, int damage) { bullets[nextBullet].fire(startPosition, velocity, shooter, damage); Bullet bullet = bullets[nextBullet++]; nextBullet %= Constants.MAX_ALLOCATED_BULLETS; return(bullet); }
public NetClient(NetworkGamer g) { machine = g.Machine; gamer = g; serverState = 0; isPublicSlotRequest = false; playerSlots = new bool[16]; tileSection = new bool[127, 49]; }
protected void EffectExpired(GameTime gameTime) { bombEffectCoolDown -= gameTime.ElapsedGameTime.Milliseconds; if (bombEffectCoolDown <= 0) { NetworkGamer chaser = GetChaser(); UserControlledSprite realchaser = (UserControlledSprite)chaser.Tag; realchaser.speed = realchaser.originalSpeed; } }
public override void AddGamer(NetworkGamer gamer, int gamerIndex) { base.AddGamer(gamer, gamerIndex); if (gamer.IsLocal) { gamer.IsReady = true; } // todo: possible on the fly additions //CreatePlayer(gamer, gamerIndex); }
private void readBullet() { Vector3 startPos = reader.ReadVector3(); Vector3 vel = reader.ReadVector3(); string tag = reader.ReadString(); NetworkGamer shooter = findGamerWithTag(tag); int damage = reader.ReadInt32(); Global.BulletManager.fireBullet(startPos, vel, shooter, damage); }
public void disable() { startPosition = Vector3.Zero; position = Vector3.Zero; velocity = Vector3.Zero; shooter = null; damage = 0; timeLived = 0; state = State.Idle; }
protected virtual void AckFrom(NetworkGamer gamer, short ix) { /* Dispatch ack of highscores data from a given gamer. */ JoinedGamer jg; if (joinedGamers.TryGetValue(gamer, out jg)) { jg.Ack(ix); } }
/// <summary> /// Get the local player count from the gamer, or if not set, return the default /// </summary> public static int GetLocalPlayerCount(this NetworkGamer gamer) { if (gamer.Tag == null) { return(MIN_LOCAL_PLAYERS); } else { return((int)gamer.Tag); } }
private void readPlayerUpdate() { string tag = reader.ReadString(); NetworkGamer gamer = findGamerWithTag(tag); Vector3 newPos = reader.ReadVector3(); Vector3 newVel = reader.ReadVector3(); float pitch = reader.ReadSingle(); float yaw = reader.ReadSingle(); RemotePlayer player = gamer.Tag as RemotePlayer; player.receiveNewPacketUpdate(newPos, newVel, pitch, yaw); }
protected void HitBomb(int index) { bombList.Remove(bombList[index]); bombEffectCoolDown = 5000; NetworkGamer chaser = GetChaser(); UserControlledSprite realchaser = (UserControlledSprite)chaser.Tag; realchaser.speed *= .5f; }
private static void GamerLeftEventHandler(object sender, GamerLeftEventArgs e) { NetworkGamer networkGamer = e.Gamer; Player player = networkGamer.Tag as Player; if (networkGamer.IsLocal) { UI uI = Main.ui[(int)((LocalNetworkGamer)networkGamer).SignedInGamer.PlayerIndex]; if (Main.netMode == 0 && uI.wasRemovedFromSessionWithoutOurConsent) { return; } uI.LeaveSession(); } if (Main.netMode == 1) { return; } int whoAmI = player.whoAmI; player.active = 0; playerSlots[whoAmI] = false; if (Main.netMode != 2) { return; } if (networkGamer.IsLocal) { if (UI.main.isInviteOnly) { session.PrivateGamerSlots++; } } else { NetClient client = player.client; if (client.GamerLeft(player)) { clients.Remove(client); } else if (networkGamer == client.gamer) { client.gamer = client.machine.Gamers[0]; } } NetMessage.CreateMessage2(14, whoAmI, 0); NetMessage.SendMessage(); if (player.announced) { player.announced = false; NetMessage.SendText(player.oldName, 33, 255, 240, 20, -1); } }
public void fire(Vector3 startPosition, Vector3 velocity, NetworkGamer shooter, int damage) { this.startPosition = startPosition; position = startPosition; //need a brand new velocity vector so it doesn't take on player's residual velocity this.velocity = new Vector3(velocity.X, velocity.Y, velocity.Z); this.shooter = shooter; this.damage = damage; timeLived = 0; state = State.Active; Global.shot.Play(); }
/// <summary> /// Write requests to the host. /// </summary> /// <param name="gamers">Clients</param> /// <param name="host">Host</param> public void clientWritePackets(GamerCollection <LocalNetworkGamer> gamers, NetworkGamer host) { Command cmd; foreach (LocalNetworkGamer gamer in gamers) { // TODO: Reimpliment. if (_writer.Length > 0) { gamer.SendData(_writer, SendDataOptions.ReliableInOrder, host); } } }
private void UpdatePlayerData(NetworkGamer sender) { if (sender != null) { Player player = sender.Tag as Player; if (player != null) { player.Lives = packetReader.ReadInt32(); player.Score = packetReader.ReadInt32(); } } }
/// <summary> /// Helper draws the gamertag and status icons for a single NetworkGamer. /// </summary> void DrawGamer(NetworkGamer gamer, Vector2 position) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; Vector2 iconWidth = new Vector2(34, 0); Vector2 iconOffset = new Vector2(0, 12); Vector2 iconPosition = position + iconOffset; // Draw the "is ready" icon. if (gamer.IsReady) { spriteBatch.Draw(isReadyTexture, iconPosition, FadeAlphaDuringTransition(Color.Lime)); } iconPosition += iconWidth; // Draw the "is muted", "is talking", or "has voice" icon. if (gamer.IsMutedByLocalUser) { spriteBatch.Draw(voiceMutedTexture, iconPosition, FadeAlphaDuringTransition(Color.Red)); } else if (gamer.IsTalking) { spriteBatch.Draw(isTalkingTexture, iconPosition, FadeAlphaDuringTransition(Color.Yellow)); } else if (gamer.HasVoice) { spriteBatch.Draw(hasVoiceTexture, iconPosition, FadeAlphaDuringTransition(Color.White)); } // Draw the gamertag, normally in white, but yellow for local players. string text = gamer.Gamertag; if (gamer.IsHost) { text += Resources.HostSuffix; } text += " (" + gamer.GetLocalPlayerCount() + " players)"; Color color = (gamer.IsLocal) ? Color.Yellow : Color.White; spriteBatch.DrawString(font, text, position + iconWidth * 2, FadeAlphaDuringTransition(color)); }
public int GetGamerIndex(NetworkGamer gamer) { int result = -1; if (gamer is LocalNetworkGamer) { result = (int)((LocalNetworkGamer)gamer).SignedInGamer.PlayerIndex; } else { result = networkSession.AllGamers.IndexOf(gamer) + 0x10; } return(result); }
/// <summary> /// Creates a new piece of network information. /// </summary> /// <param name="dataName">The name identifying the information.</param> /// <param name="data">The actual data.</param> /// <param name="sender">The sender of network information.</param> public NetworkData(string dataName, object data, NetworkGamer sender) { if (dataName == null) { throw new ArgumentNullException("dataName"); } if (data == null) { throw new ArgumentNullException("data"); } Name = dataName; Data = data; Sender = sender; }
/// <summary> /// Set the local player count for the gamer to change by change (can be positive or negative). /// Any change past the min or max values is wrapped around (not clamped). /// </summary> public static void SetLocalPlayerCount(this NetworkGamer gamer, int change) { int newPlayerCount = gamer.GetLocalPlayerCount() + change; // wrap player count around (e.g. if currently on max players, an addition of one will result in being set to min players) if (newPlayerCount > MAX_LOCAL_PLAYERS) { newPlayerCount = MIN_LOCAL_PLAYERS; } else if (newPlayerCount < MIN_LOCAL_PLAYERS) { newPlayerCount = MAX_LOCAL_PLAYERS; } gamer.Tag = newPlayerCount; }
protected void Update_InGame(GameTime gameTime) { //will update your own player, must also send updates to other player too UpdateLocalPlayer(gameTime); //will update the other player ProcessIncomingData(gameTime); //you only want the host checking for collisions if (networkSession.IsHost) { //why check for collisions when you dont have >1 gamer :O if (networkSession.AllGamers.Count == 2) { UserControlledSprite sprite1 = (UserControlledSprite)networkSession.AllGamers[0].Tag; UserControlledSprite sprite2 = (UserControlledSprite)networkSession.AllGamers[1].Tag; //collision if (sprite1.collisionRect.Intersects(sprite2.collisionRect)) { //dont set enum GameState, just EndGame() since the method already does the enum stuff //you want to make sure the other player knows its game over though writer.Write((int)MessageType.EndGame); //reliable because you need it to go through networkSession.LocalGamers[0].SendData(writer, SendDataOptions.Reliable); EndGame(); } NetworkGamer chaser = GetChaser(); UserControlledSprite realchaser = (UserControlledSprite)chaser.Tag; for (int i = 0; i < bombList.Count; i++) { UserControlledSprite bomb = bombList[i]; if (realchaser.collisionRect.Intersects(bomb.collisionRect)) { HitBomb(i); writer.Write((int)MessageType.HitBomb); writer.Write(i); networkSession.LocalGamers[0].SendData(writer, SendDataOptions.InOrder); } } } } EffectExpired(gameTime); }
public static void SubmitStatistics(Statistics stats, NetworkGamer gamer) { if (Netplay.session.SessionState != NetworkSessionState.Playing) { return; } LeaderboardWriter leaderboardWriter = gamer.LeaderboardWriter; if (leaderboardWriter != null) { LeaderboardInfo[] lEADERBOARDS_INFO = LEADERBOARDS_INFO; foreach (LeaderboardInfo leaderboardInfo in lEADERBOARDS_INFO) { leaderboardInfo.Submit(leaderboardWriter, stats); } } }
/// <summary> /// Sends data for the specified <see cref="LocalNetworkGamer"/> across the network. /// </summary> /// <param name="senderIndex">The index of the <see cref="LocalNetworkGamer"/> that is in Session.LocalGamers to send data for.</param> /// <param name="recipient">The recipient of the data, or null if to send to everyone.</param> /// <param name="options">The <see cref="SendDataOptions"/> to send the data with.</param> public virtual void SendData(int senderIndex, NetworkGamer recipient, SendDataOptions options) { if (!IsNetworking) { throw new InvalidOperationException("This component is not currently active."); } if (senderIndex >= Session.LocalGamers.Count || senderIndex < 0) { throw new ArgumentOutOfRangeException("senderIndex", "The senderIndex parameter is outside of the bounds of Session.LocalGamers."); } if (recipient != null) { Session.LocalGamers[senderIndex].SendData(_dataWriters[Session.LocalGamers[senderIndex].Id], options, recipient); } else { Session.LocalGamers[senderIndex].SendData(_dataWriters[Session.LocalGamers[senderIndex].Id], options); } }
protected void UpdateOtherPlayer(GameTime gameTime) { NetworkGamer otherPlayer = GetOtherPlayer(); UserControlledSprite otherSprite = (UserControlledSprite)otherPlayer.Tag; //you will always need the packet reader to read a vector or int to update a remote player from another comp Vector2 otherPosition = reader.ReadVector2(); otherSprite.Position = otherPosition; if (!otherSprite.isChasing) { int score = reader.ReadInt32(); otherSprite.score = score; } //set moving to false because you dont want to move it, you already set position, only animate frame otherSprite.Update(gameTime, Window.ClientBounds, false); }
private void readNewJuggernaut() //Reads in who should be the new juggernaut. { string tag = reader.ReadString(); Global.msgNewJuggernaut(tag); //Fires off a message to the message displayer unit. NetworkGamer gamer = findGamerWithTag(tag); if (gamer.IsLocal) { LocalPlayer player = gamer.Tag as LocalPlayer; player.setAsJuggernaut(); for (int i = 0; i < Global.localPlayers.Count; i++) { if (Global.localPlayers[i] != player) { Global.localPlayers[i].setAsNotJuggernaut(); } } for (int i = 0; i < Global.remotePlayers.Count; i++) { Global.remotePlayers[i].setAsNotJuggernaut(); } } else { RemotePlayer rPlayer = gamer.Tag as RemotePlayer; rPlayer.setAsJuggernaut(); for (int i = 0; i < Global.localPlayers.Count; i++) { Global.localPlayers[i].setAsNotJuggernaut(); } for (int i = 0; i < Global.remotePlayers.Count; i++) //Loop for all remotes except the juggernaut { if (Global.remotePlayers[i] != rPlayer) { Global.remotePlayers[i].setAsNotJuggernaut(); } } } }
void GameStartedEventHandler(object sender, GameStartedEventArgs e) { if (hostSessionType == HostSessionType.Host) { int firstJugIndex = Global.rand.Next(0, Global.networkManager.networkSession.AllGamers.Count); NetworkGamer firstJug = networkSession.AllGamers[firstJugIndex]; newJuggernaut(firstJug); if (firstJug.IsLocal) { LocalPlayer player = firstJug.Tag as LocalPlayer; player.setAsJuggernaut(); } else { RemotePlayer player = firstJug.Tag as RemotePlayer; player.setAsJuggernaut(); } } Global.gameState = Global.GameState.Playing; Global.menusong.Stop(); Global.actionsong.Play(); }
/* Event handler for gamer joined; forward to the game if it's listening. */ void session_GamerJoined(object sender, GamerJoinedEventArgs e) { Trace.WriteLine(String.Format("Gamer joined: {0}", e.Gamer.Gamertag)); if (e.Gamer.IsLocal) { return; } if (session != null) { UpdateVoice(); if (sessionType == SessionType.HighscoresOnly) { // stay open for five minutes, or until the host kills it sessionCloseTime = Timing.NowTicks + 300 * 10000000L; } if (toSend.Count == 0 && storage.HasLoaded) { LoadHighscores(); } } if (sessionType == SessionType.HighscoresAndGame || sessionType == SessionType.HighscoresOnly) { if (e.Gamer is NetworkGamer) { NetworkGamer ng = e.Gamer as NetworkGamer; if (!ng.IsLocal) { joinedGamers.Add(e.Gamer, new JoinedGamer(ng)); } } } if (GamerJoined != null) { gea.Gamer = e.Gamer; gea.Joined = true; GamerJoined(this, gea); } }
/* Given a highscores packet sent to a local player, handle that. * The packet itself is in the PacketReader r. */ protected virtual void DoHighscoresPacket(LocalNetworkGamer to, PacketReader r, NetworkGamer from, byte type) { PMR.Reader = r; byte n = 0; short tok = 0; switch (type) { case HighscoreItems: if (!from.IsLocal) { tok = r.ReadInt16(); n = r.ReadByte(); Trace.WriteLine(String.Format("Received {0} highscores in a packet from {1} (token {2})", n, from, tok)); // this happens during runtime, so I better not do too many scores at one time for (int i = 0; i != n; ++i) { Highscore hs = new Highscore(); hs.MarshalThrough(PMR); Storage.Instance.AddHighscore(hs, true); } SendAck(tok, from); } break; case HighscoreItemsAck: tok = r.ReadInt16(); Trace.WriteLine(String.Format("Received ack for pos {0} from {1}", tok, from)); AckFrom(from, tok); break; default: Trace.WriteLine(String.Format("Swallowing packet type {0} from {1}", type, from)); break; } }
/// <summary> /// This method only runs on client machines. It reads /// tank position data that has been computed by the server. /// </summary> void ClientReadGameStateFromServer(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); // This packet contains data about all the players in the session. // We keep reading from it until we have processed all the data. while (packetReader.Position < packetReader.Length) { // Read the state of one tank from the network packet. byte gamerId = packetReader.ReadByte(); Vector2 position = packetReader.ReadVector2(); float tankRotation = packetReader.ReadSingle(); float turretRotation = packetReader.ReadSingle(); // Look up which gamer this state refers to. NetworkGamer remoteGamer = networkSession.FindGamerById(gamerId); // This might come back null if the gamer left the session after // the host sent the packet but before we received it. If that // happens, we just ignore the data for this gamer. if (remoteGamer != null) { // Update our local state with data from the network packet. Tank tank = remoteGamer.Tag as Tank; tank.Position = position; tank.TankRotation = tankRotation; tank.TurretRotation = turretRotation; } } } }
public void Dispose() { if (_netSession.IsHost) { _netSession.EndGame(); } _netSession.Dispose(); _netSession = null; _availableSessions = null; _hasLeft = true; _remoteMapName = ""; _packetReader.BaseStream.Flush(); _packetWriter.BaseStream.Flush(); _remoteItemList = null; _remoteMatch = null; _remoteMatchType = 999; _sender = null; _sessionList.Clear(); _isHost = false; _isClient = false; _failure = false; }
public CommandGamerStateChange(NetworkGamer gamer) { this.gamer = gamer; this.newState = gamer.State; this.oldState = gamer.OldState; }