User:Gadren/blah

using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage;

namespace HW3 { ///    /// This is the main type for your game ///    public class Pinball : Microsoft.Xna.Framework.Game { NetworkSession networkSession; AvailableNetworkSessionCollection availableSessions; int selectedSessionIndex; PacketReader packetReader = new PacketReader; PacketWriter packetWriter = new PacketWriter;

GraphicsDeviceManager graphics; SpriteBatch spriteBatch; int boardWidth = 1280; int boardHeight = 800; int initialVelocity = 0; float rightRotation; float leftRotation; Boolean leftDown; Boolean rightDown; Boolean rightFlipperMoving; Boolean leftFlipperMoving; public static Boolean rollingSoundPlaying = false;

public static int ballsLeft = 5; public static Boolean ballStarted = false; public static Vector2 startPosition;

//Sprites Sprite ball; Sprite Bumper1; Sprite Bumper2; Sprite Bumper3; Sprite LeftBumper1; Sprite RightBumper1; Sprite LeftBumper2; Sprite RightBumper2; Sprite leftFlipper2; Sprite rightFlipper2; Sprite corner; Sprite rightWall; Sprite middleWall; Sprite leftFlipper1; Sprite rightFlipper1;

//Sounds SoundEffect flipper; SoundEffect spring; SoundEffect bumper; SoundEffect rolling; public static SoundEffectInstance instance;

KeyboardState oldState;

SpriteFont kootenay; int hostScore; int clientScore; Vector2 scorePosition = new Vector2(300, 50); Vector2 rightOrigin; Vector2 leftOrigin;

public Pinball { graphics = new GraphicsDeviceManager(this); hostScore = 0; scorePosition = new Vector2(20, 20); graphics.PreferredBackBufferWidth = boardWidth; graphics.PreferredBackBufferHeight = boardHeight; Content.RootDirectory = "Content"; // Add Gamer Services Components.Add(new GamerServicesComponent(this));

// Respond to the SignedInGamer event SignedInGamer.SignedIn += new EventHandler(SignedInGamer_SignedIn);

}       ///         /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. ///        protected override void Initialize { // TODO: Add your initialization logic here oldState = Keyboard.GetState; base.Initialize; }       ///         /// LoadContent will be called once per game and is the place to load /// all of your content. ///        protected override void LoadContent { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice);

// TODO: use this.Content to load your game content here ball = new Sprite(Content.Load("ball"), false); startPosition = new Vector2(boardWidth - ball.Image.Width - 5, boardHeight - (ball.Image.Width)); //startPosition = new Vector2(10, 600); ball.Position = startPosition; Bumper1 = new Sprite(Content.Load("Bumper"), false); Bumper1.Position = new Vector2((float)(boardWidth - 60 - Bumper1.BS.Radius) / 2 + Bumper1.Image.Width * 1.5f, 100.0f); Bumper2 = new Sprite(Content.Load("Bumper"), false); Bumper2.Position = new Vector2((float)(boardWidth - 60) / 2 - Bumper2.BS.Radius, 250); Bumper3 = new Sprite(Content.Load("Bumper"), false); Bumper3.Position = new Vector2((float)(boardWidth - 60 - Bumper3.BS.Radius) / 2 - Bumper3.Image.Width * 2, 100); corner = new Sprite(Content.Load("Corner"), true); corner.Position = new Vector2(boardWidth - corner.Image.Width, 0); rightWall = new Sprite(Content.Load("RightWall"), true); rightWall.Position = new Vector2(boardWidth - ball.Image.Width - 30, boardHeight - rightWall.Image.Height); LeftBumper1 = new Sprite(Content.Load("LeftBumper"), true); LeftBumper1.Position = new Vector2(50, boardHeight - (LeftBumper1.Image.Height + 50)); RightBumper1 = new Sprite(Content.Load("RightBumper"), true); RightBumper1.Position = new Vector2(LeftBumper1.Position.X + LeftBumper1.Image.Width + 250, boardHeight - (RightBumper1.Image.Height + 50)); middleWall = new Sprite(Content.Load("RightWall"), true); middleWall.Position = new Vector2(RightBumper1.Position.X + RightBumper1.Image.Width, boardHeight - middleWall.Image.Height); LeftBumper2 = new Sprite(Content.Load("LeftBumper"), true); LeftBumper2.Position = new Vector2(middleWall.Position.X + 10, boardHeight - (LeftBumper2.Image.Height +50)); RightBumper2 = new Sprite(Content.Load("RightBumper"), true); RightBumper2.Position = new Vector2(LeftBumper2.Position.X + LeftBumper2.Image.Width + 250, boardHeight - (RightBumper2.Image.Height + 50)); rightFlipper1 = new Sprite(Content.Load("RightFlipper"), true); rightFlipper1.Position = new Vector2(RightBumper1.Position.X + 15, RightBumper1.Position.Y + RightBumper1.Image.Height + 14); leftFlipper1 = new Sprite(Content.Load("LeftFlipper"), true); leftFlipper1.Position = new Vector2(LeftBumper1.Position.X + LeftBumper1.Image.Width - 15, LeftBumper1.Position.Y + LeftBumper1.Image.Height + 14); rightOrigin = new Vector2(rightFlipper1.Position.X + rightFlipper1.Image.Width,                                 rightFlipper1.Position.Y + rightFlipper1.Image.Height / 2); leftOrigin = new Vector2(leftFlipper1.Position.X, rightFlipper1.Position.Y + rightFlipper1.Image.Height / 2); rightRotation = -.3f; leftRotation = .3f; flipper = Content.Load("audio\\flipper"); spring = Content.Load("audio\\spring"); bumper = Content.Load<SoundEffect>("audio\\bumper"); rolling = Content.Load<SoundEffect>("audio\\ballmoving"); kootenay = Content.Load<SpriteFont>("fonts\\Kootenay");

}       ///         /// UnloadContent will be called once per game and is the place to unload /// all content. ///        protected override void UnloadContent { // TODO: Unload any non ContentManager content here }       ///         /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. ///        /// <param name="gameTime">Provides a snapshot of timing values. protected override void Update(GameTime gameTime) { if (!Guide.IsVisible) { foreach (SignedInGamer signedInGamer in SignedInGamer.SignedInGamers) { Player player = signedInGamer.Tag as Player; player.CaptureKeyboard; player.CaptureGamePad; if (networkSession != null) { if (networkSession.SessionState == NetworkSessionState.Lobby) HandleLobbyInput(player); else HandleGameplayInput(player, gameTime); }                   else if (availableSessions != null) { HandleAvailableSessionsInput(player); }                   else { HandleTitleScreenInput(player); }               }            }            base.Update(gameTime);

}       private void UpdateInput(Player player, GameTime gameTime) { foreach (LocalNetworkGamer gamer in networkSession.LocalGamers) { ReceiveNetworkData(gamer, gameTime);

if (player.IsKeyPressed(Keys.S) || player.IsButtonPressed(Buttons.A)) { if (player.isHost) { ballsLeft = 5; hostScore = 0; }               }                if (player.isKeyDown(Keys.Down) || player.isButtonDown(Buttons.DPadDown)) { // If not down last update, key has just been pressed. initialVelocity += 10;

}               else if (player.isOldKeyDown(Keys.Down) || player.isOldButtonDown(Buttons.DPadDown)) { if (!ballStarted && ballsLeft > 0) { ball.Speed = new Vector2(0, -initialVelocity); spring.Play(1f); }                   ballStarted = true; initialVelocity = 0; }               if (player.IsKeyPressed(Keys.Up) || player.IsButtonPressed(Buttons.DPadUp)) { //Nudge Capability if (ballStarted) ball.Speed = new Vector2(ball.Speed.X + 50, ball.Speed.Y - 50);

}               //XBOX if (player.isButtonDown(Buttons.RightTrigger)) { if (!player.isOldButtonDown(Buttons.RightTrigger)) flipper.Play; rightDown = true; }               else if (player.isOldButtonDown(Buttons.RightTrigger)) { flipper.Play; rightDown = false; }               if (player.isButtonDown(Buttons.LeftTrigger)) { if (!player.isOldButtonDown(Buttons.LeftTrigger)) flipper.Play; leftDown = true; }               else if (player.isOldButtonDown(Buttons.LeftTrigger)) { flipper.Play; leftDown = false; }               //Keyboard if (player.isKeyDown(Keys.Right) && player.isHost) { if (!player.isOldKeyDown(Keys.Right)) flipper.Play; rightDown = true; }               else if (player.isOldKeyDown(Keys.Right) && player.isHost) { flipper.Play; rightDown = false; }               if (player.isKeyDown(Keys.Left) && player.isHost) { if (!player.isOldKeyDown(Keys.Left)) flipper.Play; leftDown = true; }               else if (player.isOldKeyDown(Keys.Left) && player.isHost) { flipper.Play; leftDown = false;

}               if (ballStarted) { if (!rollingSoundPlaying) { if (instance == null) instance = rolling.Play(1f, 0.0f, 0.0f, true); else instance.Resume; rollingSoundPlaying = true; }               }

updateFlippers;

packetWriter.Write(player.isHost); //packetWriter.Write(rightDown); //packetWriter.Write(leftDown); //packetWriter.Write(player.IsKeyPressed(Keys.Up)); packetWriter.Write(player.isKeyDown(Keys.Right)); packetWriter.Write(player.isKeyDown(Keys.Left)); packetWriter.Write(ball.Position);

gamer.SendData(packetWriter, SendDataOptions.None); }       }        ///         /// This is called when the game should draw itself. ///        /// <param name="gameTime">Provides a snapshot of timing values. protected override void Draw(GameTime gameTime) { if (networkSession != null) { // Draw the Lobby if (networkSession.SessionState == NetworkSessionState.Lobby) DrawLobby; else DrawGamePlay(gameTime);

}           else if (availableSessions != null) { DrawAvailableSessions; }           else { DrawTitleScreen; }           base.Draw(gameTime); }       protected void checkForCollisions(Vector2 ballPos) { if (ball.BS.Intersects(Bumper1.BS)) { bumper.Play; hostScore += 100; Collide(ball, Bumper1); }           if (ball.BS.Intersects(Bumper2.BS)) { bumper.Play; hostScore += 100; Collide(ball, Bumper2); }           if (ball.BS.Intersects(Bumper3.BS)) { bumper.Play; hostScore += 100; Collide(ball, Bumper3); }           if (ball.BS.Intersects(RightBumper1.BB) && ball.prevPos.X > RightBumper1.Position.X + RightBumper1.Image.Width) { hostScore += 10; wallBounce(ball, RightBumper1); }           if (ball.BS.Intersects(LeftBumper1.BB) && ball.prevPos.X < LeftBumper1.Position.X - ball.Image.Width) { hostScore += 10; wallBounce(ball, LeftBumper1); }           if (ball.BS.Intersects(LeftBumper2.BB) && ball.prevPos.X < LeftBumper2.Position.X - ball.Image.Width) { hostScore += 10; wallBounce(ball, LeftBumper2); }           if (ball.BS.Intersects(RightBumper2.BB) && ball.prevPos.X > RightBumper2.Position.X + RightBumper2.Image.Width) { hostScore += 10; wallBounce(ball, RightBumper2); }           //Corner float dist = util.linePointDist(corner.Position, new Vector2(corner.Position.X + 40, corner.Position.Y + 40),               ballPos); if (dist < ball.BS.Radius) { hostScore += 10; Collide(ball, new Vector2(550, 0), new Vector2(600, 50), null); }           //Player 1 RightBumper dist = util.linePointDist(new Vector2(RightBumper1.Position.X, RightBumper1.Position.Y + RightBumper1.Image.Height),                   new Vector2(RightBumper1.Position.X + RightBumper1.Image.Width, RightBumper1.Position.Y),                    ballPos); if (dist < ball.BS.Radius) { hostScore += 10; Collide(ball, new Vector2(RightBumper1.Position.X, RightBumper1.Position.Y + RightBumper1.Image.Height),                   new Vector2(RightBumper1.Position.X + RightBumper1.Image.Width, RightBumper1.Position.Y), null); }           //Player 1 LeftBumper dist = util.linePointDist(new Vector2(LeftBumper1.Position.X, LeftBumper1.Position.Y),                   new Vector2(LeftBumper1.Position.X + LeftBumper1.Image.Width, LeftBumper1.Position.Y + LeftBumper1.Image.Height),                    ballPos); if (dist < ball.BS.Radius) { hostScore += 10; Collide(ball, new Vector2(LeftBumper1.Position.X, LeftBumper1.Position.Y),                   new Vector2(LeftBumper1.Position.X + LeftBumper1.Image.Width, LeftBumper1.Position.Y + LeftBumper1.Image.Height),                    null); }           //Player 2 RightBumper dist = util.linePointDist(new Vector2(RightBumper2.Position.X, RightBumper2.Position.Y + RightBumper2.Image.Height),                   new Vector2(RightBumper2.Position.X + RightBumper2.Image.Width, RightBumper2.Position.Y),                    ballPos); if (dist < ball.BS.Radius) { hostScore += 10; Collide(ball, new Vector2(RightBumper2.Position.X, RightBumper2.Position.Y + RightBumper2.Image.Height),                   new Vector2(RightBumper2.Position.X + RightBumper2.Image.Width, RightBumper2.Position.Y), null); }           //Player 2 LeftBumper dist = util.linePointDist(new Vector2(LeftBumper2.Position.X, LeftBumper2.Position.Y),                   new Vector2(LeftBumper2.Position.X + LeftBumper2.Image.Width, LeftBumper2.Position.Y + LeftBumper2.Image.Height),                    ballPos); if (dist < ball.BS.Radius) { hostScore += 10; Collide(ball, new Vector2(LeftBumper2.Position.X, LeftBumper2.Position.Y),                   new Vector2(LeftBumper2.Position.X + LeftBumper2.Image.Width, LeftBumper2.Position.Y + LeftBumper2.Image.Height),                    null); }

if (rightWall.BB.Intersects(ball.BS)) { wallBounce(ball, rightWall); }           if (middleWall.BB.Intersects(ball.BS)) { wallBounce(ball, middleWall); }           Matrix rightMatrix = Matrix.CreateRotationZ(rightRotation); Vector2 rotatedVector = Vector2.Transform(rightFlipper1.Position - rightOrigin, rightMatrix); Vector2 right1 = rightFlipper1.Position + rotatedVector; rotatedVector = Vector2.Transform(new Vector2(rightFlipper1.Position.X + rightFlipper1.Image.Width, rightFlipper1.Position.Y) - rightOrigin, rightMatrix); Vector2 right2 = rightFlipper1.Position + rotatedVector; float rightDist2 = util.linePointDist(right1, right2, ballPos); if (rightDist2 < ball.BS.Radius) { Collide(ball, right1, right2, rightFlipper1); if (rightFlipperMoving) { ball.Speed *= 1 + (rightFlipper1.Position.X + 100 - ball.Position.X) / 50; ball.Position = new Vector2(ball.Position.X, ball.Position.Y - 10); }           }

Matrix leftMatrix = Matrix.CreateRotationZ(leftRotation); rotatedVector = Vector2.Transform(leftFlipper1.Position - leftOrigin, leftMatrix); Vector2 left1 = leftFlipper1.Position + rotatedVector; rotatedVector = Vector2.Transform(new Vector2(leftFlipper1.Position.X + leftFlipper1.Image.Width, leftFlipper1.Position.Y) - leftOrigin, leftMatrix); Vector2 left2 = leftFlipper1.Position + rotatedVector; float leftDist2 = util.linePointDist(left1, left2, ballPos); if (leftDist2 < ball.BS.Radius) { Collide(ball, left1, left2, leftFlipper1); if (leftFlipperMoving) { ball.Speed *= 1 + (ball.Position.X - leftFlipper1.Position.X) / 50; ball.Position = new Vector2(ball.Position.X, ball.Position.Y - 10); }           }        }        protected void Collide(Sprite ball, Sprite circle) { float n_x = ball.BS.Center.X - circle.BS.Center.X;           float n_y = ball.BS.Center.Y - circle.BS.Center.Y;            float n_length = (float)Math.Sqrt((n_x * n_x) + (n_y * n_y)); // normalize n           if (n_length > 0) { n_x /= n_length; n_y /= n_length; }

// tangent of the collision float t_x = n_y; float t_y = -n_x;

float e = 0.99f; // elasticity of the collision

float vain = (ball.Speed.X * n_x) + (ball.Speed.Y * n_y); //Vector2.Dot(ball1.Velocity, N); float vait = (ball.Speed.X * t_x) + (ball.Speed.Y * t_y); //Vector2.Dot(ball1.Velocity, T); float vbin = (circle.Speed.X * n_x) + (circle.Speed.Y * n_y); //Vector2.Dot(ball2.Velocity, N); float vbit = (circle.Speed.X * t_x) + (circle.Speed.Y * t_y); //Vector2.Dot(ball2.Velocity, T);

float vafn = ((e + 1.0f) * vbin + vain * (1 - e)) / 2; float vbfn = ((e + 1.0f) * vain - vbin * (1 - e)) / 2; float vaft = vait; float vbft = vbit; Random gen = new Random; int random = gen.Next(100, 250); ball.Speed = new Vector2((-(vbfn * n_x + vbft * t_x) + vafn * n_x + vaft * t_x) * random / 100,               (-(vbfn * n_y + vbft * t_y) + vafn * n_y + vaft * t_y) * random / 100); }       protected void Collide(Sprite ball, Vector2 p1, Vector2 p2, Sprite flipper) { Vector2 p = p2 - p1; Vector2 temp1 = (new Vector2(ball.BS.Center.X - p1.X, ball.BS.Center.Y - p1.Y)); Vector2 temp2 = (new Vector2(ball.BS.Center.X - p2.X, ball.BS.Center.Y - p2.Y)); float length = temp1.Length; float length2 = temp2.Length; p.Normalize; ball.Position = ball.prevPos; if (temp1.Length < ball.BS.Radius + 2 || temp2.Length < ball.BS.Radius + 2) { if (ball.BS.Center.Y < RightBumper1.Position.Y || flipper != null) { ball.Speed *= -1; return; }               else ball.Speed = Vector2.Reflect(ball.Speed, new Vector2(-p.Y, p.X));

}           else ball.Speed = Vector2.Reflect(ball.Speed, new Vector2(-p.Y, p.X)); if (flipper == rightFlipper1 && rightFlipperMoving) { float energy = (flipper.Position.X + 100 - ball.Position.X) * 3; ball.Speed = new Vector2((ball.Speed.X + energy) * (-p.Y), (ball.Speed.Y + energy) * p.X); }           if (flipper == leftFlipper1 && leftFlipperMoving) { float energy = (ball.Position.X - flipper.Position.X) * 3; ball.Speed = new Vector2(ball.Speed.X + (energy * (p.Y)), ball.Speed.Y + (energy * (p.X))); }       }        protected void wallBounce(Sprite ball, Sprite wall) { if (ball.prevPos.Y < wall.Position.Y - 40) { ball.Position = new Vector2(ball.prevPos.X, wall.Position.Y - 40); ball.Speed = new Vector2(ball.Speed.X, -1 * ball.Speed.Y); }           else { if (ball.prevPos.X < wall.Position.X)                   ball.Position = new Vector2(wall.Position.X - ball.Image.Width, ball.prevPos.Y); else ball.Position = new Vector2(wall.Position.X + wall.Image.Width, ball.prevPos.Y); ball.Speed = new Vector2(-1 * ball.Speed.X, ball.Speed.Y); }       }        protected void updateFlippers { //Rotate Flippers rightFlipperMoving = true; leftFlipperMoving = true; if (rightDown) { rightRotation += .15f; }           else rightRotation -= .15f;

if (leftDown) leftRotation -= .15f; else leftRotation += .15f;

//Check bounds if (rightRotation > .3f) { rightFlipperMoving = false; rightRotation = .3f; }           if (rightRotation < -.3f) { rightFlipperMoving = false; rightRotation = -0.3f; }

if (leftRotation > .3f) { leftFlipperMoving = false; leftRotation = .3f; }           if (leftRotation < -.3f) { leftFlipperMoving = false; leftRotation = -.3f; }       }        void SignedInGamer_SignedIn(object sender, SignedInEventArgs e) { e.Gamer.Tag = new Player; }       private void DrawTitleScreen { GraphicsDevice.Clear(Color.CornflowerBlue); string message = "";

if (SignedInGamer.SignedInGamers.Count == 0) { message = "No profile signed in! \nPress the Home key on the keyboard or \nthe Xbox Guide Button on the controller to sign in."; }           else { message += "Press A to create a new session\nX to search for sessions\nB to quit\n\n"; }           spriteBatch.Begin; spriteBatch.DrawString(kootenay, message, new Vector2(101, 101), Color.Black); spriteBatch.DrawString(kootenay, message, new Vector2(100, 100), Color.White); spriteBatch.End; }       private void HandleGameplayInput(Player player, GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit;

// TODO: Add your update logic here

if (ballStarted && ballsLeft > 0) ball.Update(gameTime, graphics); Vector2 ballPos = new Vector2(ball.BS.Center.X, ball.BS.Center.Y); checkForCollisions(ballPos); UpdateInput(player, gameTime); networkSession.Update; }       private void DrawGamePlay(GameTime gameTime) {

graphics.GraphicsDevice.Clear(Color.CornflowerBlue); if (networkSession != null) { // TODO: Add your drawing code here spriteBatch.Begin(SpriteBlendMode.AlphaBlend); if (ballsLeft > 0) spriteBatch.Draw(ball.Image, ball.Position, Color.White); spriteBatch.Draw(Bumper1.Image, Bumper1.Position, Color.White); spriteBatch.Draw(Bumper2.Image, Bumper2.Position, Color.White); spriteBatch.Draw(corner.Image, corner.Position, Color.White); spriteBatch.Draw(rightWall.Image, rightWall.Position, Color.White); spriteBatch.Draw(middleWall.Image, middleWall.Position, Color.White); spriteBatch.Draw(RightBumper1.Image, RightBumper1.Position, Color.White); spriteBatch.Draw(LeftBumper1.Image, LeftBumper1.Position, Color.White); spriteBatch.Draw(RightBumper2.Image, RightBumper2.Position, Color.White); spriteBatch.Draw(LeftBumper2.Image, LeftBumper2.Position, Color.White); spriteBatch.Draw(Bumper3.Image, Bumper3.Position, Color.White); spriteBatch.Draw(rightFlipper1.Image, rightFlipper1.Position,                   null, Color.White, rightRotation, new Vector2(100, 14), 1, SpriteEffects.None, 0); spriteBatch.Draw(leftFlipper1.Image, leftFlipper1.Position,                   null, Color.White, leftRotation, new Vector2(0, 14), 1, SpriteEffects.None, 0); spriteBatch.DrawString(kootenay, "Score: " + hostScore.ToString, scorePosition, Color.White, 0, Vector2.Zero, 3, SpriteEffects.None, 0); spriteBatch.DrawString(kootenay, "Balls: " + ballsLeft.ToString, new Vector2(400, 20), Color.White, 0, Vector2.Zero, 3, SpriteEffects.None, 0); spriteBatch.End; }

}       protected void HandleTitleScreenInput(Player player) { if (player.IsButtonPressed(Buttons.A)) { CreateSession; player.isHost = true; }           else if (player.IsButtonPressed(Buttons.X)) { availableSessions = NetworkSession.Find(NetworkSessionType.Local, 2, null); selectedSessionIndex = 0; }           else if (player.IsButtonPressed(Buttons.B)) { Exit; }           if (player.IsKeyPressed(Keys.A)) { CreateSession; player.isHost = true; }           else if (player.IsKeyPressed(Keys.X)) { availableSessions = NetworkSession.Find(                   NetworkSessionType.SystemLink, 1, null); selectedSessionIndex = 0; }           else if (player.IsKeyPressed(Keys.Escape)) { Exit; }       }        void CreateSession { networkSession = NetworkSession.Create(               NetworkSessionType.SystemLink,                1, 8, 2,                null);

networkSession.AllowHostMigration = true; networkSession.AllowJoinInProgress = true;

HookSessionEvents; }       private void HookSessionEvents { networkSession.GamerJoined += new EventHandler<GamerJoinedEventArgs>(networkSession_GamerJoined); }       void networkSession_GamerJoined(object sender, GamerJoinedEventArgs e) { if (!e.Gamer.IsLocal) { e.Gamer.Tag = new Player; }           else { e.Gamer.Tag = GetPlayer(e.Gamer.Gamertag); }       }        Player GetPlayer(String gamertag) { foreach (SignedInGamer signedInGamer in SignedInGamer.SignedInGamers) { if (signedInGamer.Gamertag == gamertag) { return signedInGamer.Tag as Player; }           }

return new Player; }       private void DrawLobby { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin; float y = 100;

spriteBatch.DrawString(kootenay, "This is the Lobby (A=ready, B=leave)", new Vector2(101, y + 1), Color.Black); spriteBatch.DrawString(kootenay, "This is the Lobby (A=ready, B=leave)", new Vector2(101, y), Color.White);

y += kootenay.LineSpacing * 2;

foreach (NetworkGamer gamer in networkSession.AllGamers) { string text = gamer.Gamertag;

Player player = gamer.Tag as Player;

if (player.picture == null) { try { GamerProfile gamerProfile = gamer.GetProfile; player.picture = gamerProfile.GamerPicture; }                   catch { player.picture = null; }               }

if (gamer.IsReady) text += " - ready!"; if (player.picture != null) { spriteBatch.Draw(player.picture, new Vector2(100, y), Color.White); }               spriteBatch.DrawString(kootenay, text, new Vector2(170, y), Color.White);

y += kootenay.LineSpacing + 64; }           spriteBatch.End;

}       protected void HandleLobbyInput(Player player) { // Signal I'm ready to play! if (player.IsButtonPressed(Buttons.A)) { foreach (LocalNetworkGamer gamer in networkSession.LocalGamers) gamer.IsReady = true; }           if (player.IsButtonPressed(Buttons.B)) { networkSession = null; availableSessions = null; }           if (player.IsKeyPressed(Keys.A)) { foreach (LocalNetworkGamer gamer in networkSession.LocalGamers) gamer.IsReady = true; }           if (player.IsKeyPressed(Keys.B)) { networkSession = null; availableSessions = null; }           // The host checks if everyone is ready, and moves to game play if true. if (networkSession.IsHost) { if (networkSession.IsEveryoneReady) networkSession.StartGame; }           // Pump the underlying session object. networkSession.Update; }       private void DrawAvailableSessions { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin; float y = 100;

spriteBatch.DrawString(kootenay, "Available sessions (A=join, B=back)", new Vector2(101, y + 1), Color.Black); spriteBatch.DrawString(kootenay, "Available sessions (A=join, B=back)", new Vector2(100, y), Color.White);

y += kootenay.LineSpacing * 2;

int selectedSessionIndex = 0;

for (               int sessionIndex = 0;                sessionIndex < availableSessions.Count;                sessionIndex++) { Color color = Color.Black;

if (sessionIndex == selectedSessionIndex) color = Color.Yellow;

spriteBatch.DrawString(kootenay, availableSessions[sessionIndex].HostGamertag, new Vector2(100, y), color);

y += kootenay.LineSpacing; }           spriteBatch.End; }       protected void HandleAvailableSessionsInput(Player player) { if (player.IsKeyPressed(Keys.A)) { // Join the selected session. if (availableSessions.Count > 0) { networkSession = NetworkSession.Join(availableSessions[selectedSessionIndex]); HookSessionEvents; availableSessions.Dispose; availableSessions = null; }           }            else if (player.IsKeyPressed(Keys.Up)) { // Select the previous session from the list. if (selectedSessionIndex > 0) selectedSessionIndex--; }           else if (player.IsKeyPressed(Keys.Down)) { // Select the next session from the list. if (selectedSessionIndex < availableSessions.Count - 1) selectedSessionIndex++; }           else if (player.IsKeyPressed(Keys.B)) { // Go back to the title screen. availableSessions.Dispose; availableSessions = null; }       }        void ReceiveNetworkData(LocalNetworkGamer gamer, GameTime gameTime) { while (gamer.IsDataAvailable) { NetworkGamer sender; gamer.ReceiveData(packetReader, out sender); if (!sender.IsLocal) { Player player = sender.Tag as Player; //player.changeDirection = packetReader.ReadBoolean; if (player.isHost) { player.isHost = packetReader.ReadBoolean; rightDown = packetReader.ReadBoolean; leftDown = packetReader.ReadBoolean; ball.Position = packetReader.ReadVector2; }               }            }        }    }    public class Sprite { public Sprite(Texture2D anImage, Boolean square) { this.square = square; Image = anImage; if (square) BB = new BoundingBox(new Vector3(0, 0, 0),               new Vector3(10, 700, 0)); else BS = new BoundingSphere(new Vector3(Image.Width / 2, Image.Height / 2, 0), Image.Width / 2); }       Boolean square; Vector2 position; public Vector2 prevPos; public BoundingSphere BS { get; set; } public Texture2D Image { get; set; } public BoundingBox BB { get; set; } public Vector2 Position { get { return position; } set { position = value; if (square) BB = new BoundingBox(new Vector3(position.X, position.Y, 0),                   new Vector3(position.X + Image.Width, position.Y + Image.Height, 0)); else BS = new BoundingSphere(new Vector3(position.X + (Image.Width / 2), position.Y + (Image.Height / 2), 0), Image.Width / 2); }       }        public Vector2 Speed { get; set; }

public void Update(GameTime gameTime, GraphicsDeviceManager graphics) { // Move the sprite by speed, scaled by elapsed time. prevPos = Position; Position += Speed * (float)gameTime.ElapsedGameTime.TotalSeconds; if (Speed.Y > 500) Speed = new Vector2(Speed.X * (float).997, Speed.Y * (float).997 + 8); else Speed = new Vector2(Speed.X * (float).999, Speed.Y * (float).999 + 8); if (Speed.X > 1200) Speed = new Vector2(1200, Speed.Y); if (Speed.Y > 1200) Speed = new Vector2(Speed.X, 1200); if (Speed.X < -1200) Speed = new Vector2(-1200, Speed.Y); if (Speed.Y < -1200) Speed = new Vector2(Speed.X, -1200); int MaxX = graphics.GraphicsDevice.Viewport.Width - Image.Width; int MinX = 0; int MaxY = graphics.GraphicsDevice.Viewport.Height - Image.Height; int MinY = 0;

// Check for bounce. if (Position.X > MaxX) { Speed = new Vector2(Speed.X * -1, Speed.Y); Position = new Vector2(MaxX, Position.Y); }           else if (Position.X < MinX) { Speed = new Vector2(Speed.X * -1, Speed.Y); Position = new Vector2(MinX, Position.Y); }

if (Position.Y > MaxY) { Pinball.instance.Pause; Pinball.ballStarted = false; Position = Pinball.startPosition; Pinball.ballsLeft -= 1; Pinball.rollingSoundPlaying = false; }           else if (Position.Y < MinY) { Speed = new Vector2(Speed.X, Speed.Y * -1); Position = new Vector2(Position.X, MinY); }       }    }    static public class util { public static float dotProduct(Vector2 A, Vector2 B, Vector2 C) { Vector2 AB = B - A;           Vector2 BC = C - B;            return AB.X * BC.X + AB.Y * BC.Y;        }

public static float crossProduct(Vector2 A, Vector2 B, Vector2 C) { Vector2 AB = B - A;           Vector2 AC = C - A;            return AB.X * AC.Y - AB.Y * AC.X;        }

// Ref: http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry1 //Compute the distance from AB to C       public static float linePointDist(Vector2 A, Vector2 B, Vector2 C) { if (dotProduct(A, B, C) > 0) { return Vector2.Distance(B, C); }           if (dotProduct(B, A, C) > 0) { return Vector2.Distance(A, C); }           return Math.Abs(crossProduct(A, B, C) / Vector2.Distance(A, B)); }   }

}