protected override void Update(GameTime gameTime) { // // Collect input // float xinput = 0; float yinput = 0; if (state != GameState.playing) { mouseState = Mouse.GetState(); if (mouseState.LeftButton == ButtonState.Pressed) { if (singlePlayerButton.isVisible()) { Rectangle recA = new Rectangle((int)singlePlayerButton.getPos().X, (int)singlePlayerButton.getPos().Y, singlePlayerButton.getImage().Width, singlePlayerButton.getImage().Height); Rectangle recB = new Rectangle(mouseState.X, mouseState.Y, 1, 1); if (recA.Contains(recB)) { gameType = "single"; server = new Server(); sfd = new SomeFunctionDelegate(server.launchServer); sfd.BeginInvoke(null, null); host = true; LAN = true; client.DiscoverLocalPeers(14242); state = GameState.lobby; } } if (multiplayerButton.isVisible()) { Rectangle recA = new Rectangle((int)multiplayerButton.getPos().X, (int)multiplayerButton.getPos().Y, multiplayerButton.getImage().Width, multiplayerButton.getImage().Height); Rectangle recB = new Rectangle(mouseState.X, mouseState.Y, 1, 1); if (recA.Contains(recB)) { state = GameState.multiplayerMenu; } } if (hostGame.isVisible()) { Rectangle recA = new Rectangle((int)hostGame.getPos().X, (int)hostGame.getPos().Y, hostGame.getImage().Width, hostGame.getImage().Height); Rectangle recB = new Rectangle(mouseState.X, mouseState.Y, 1, 1); if (recA.Contains(recB)) { gameType = "multi"; server = new Server(); sfd = new SomeFunctionDelegate(server.launchServer); sfd.BeginInvoke(null, null); host = true; LAN = true; client.DiscoverLocalPeers(14242); state = GameState.lobby; } } if (joinGame.isVisible()) { Rectangle recA = new Rectangle((int)joinGame.getPos().X, (int)joinGame.getPos().Y, joinGame.getImage().Width, joinGame.getImage().Height); Rectangle recB = new Rectangle(mouseState.X, mouseState.Y, 1, 1); if (recA.Contains(recB)) { state = GameState.joinOptions; } } if (joinIneternet.isVisible()) { Rectangle recA = new Rectangle((int)joinIneternet.getPos().X, (int)joinIneternet.getPos().Y, joinIneternet.getImage().Width, joinIneternet.getImage().Height); Rectangle recB = new Rectangle(mouseState.X, mouseState.Y, 1, 1); if (recA.Contains(recB)) { state = GameState.enterIp; gameType = "multi"; } } if (joinLan.isVisible()) { Rectangle recA = new Rectangle((int)joinLan.getPos().X, (int)joinLan.getPos().Y, joinLan.getImage().Width, joinLan.getImage().Height); Rectangle recB = new Rectangle(mouseState.X, mouseState.Y, 1, 1); if (recA.Contains(recB)) { client.DiscoverLocalPeers(14242); state = GameState.lobby; gameType = "multi"; LAN = true; } } if (startGame.isVisible() && host == true) { Rectangle recA = new Rectangle((int)startGame.getPos().X, (int)startGame.getPos().Y, startGame.getImage().Width, startGame.getImage().Height); Rectangle recB = new Rectangle(mouseState.X, mouseState.Y, 1, 1); if (recA.Contains(recB)) { state = GameState.playing; NetOutgoingMessage om = client.CreateMessage(); om.Write(player.getId()); om.Write(1); client.SendMessage(om, NetDeliveryMethod.UnreliableSequenced, 6); } } } if (state == GameState.lobby) { //Console.WriteLine(allPlayers.Count); NetIncomingMessage msg; while ((msg = client.ReadMessage()) != null) { bool playerFound = false; bool cookieFound = false; switch (msg.MessageType) { case NetIncomingMessageType.DiscoveryResponse: // just connect to first server discovered // Console.WriteLine("Received a request response"); if (LAN) { client.Connect(msg.SenderEndPoint); } break; case NetIncomingMessageType.Data: if (msg.SequenceChannel == 0) { // server sent a position update long who = msg.ReadInt64(); float x = msg.ReadFloat(); float y = msg.ReadFloat(); int playerNum = msg.ReadInt32(); Texture2D image; if (playerNum == 2) { image = truett_yellow; } else if (playerNum == 3) { image = truett_green; } else { image = truettFall; } Player newPlayer = null; foreach (var p in allPlayers) { if (who == p.getId()) { if (p.getId() == player.getId()) { if (firstPass == true && x > 0) { player.newPos(new Vector2(x, y)); firstPass = false; } if (player.getPlayerNum() != playerNum) { player.setPlayerNum(playerNum, image); } } playerFound = true; } } if (playerFound == false) { newPlayer = new Player(image, x, y, who, numPlayers); allPlayers.Add(newPlayer); numPlayers++; } positions[who] = new Vector2(x, y); } else if (msg.SequenceChannel == 1) { //cookies.Clear(); float x = msg.ReadFloat(); float y = msg.ReadFloat(); int id = msg.ReadInt32(); foreach (var c in cookies) { if (c.getId() == id) { cookieFound = true; } } if (cookieFound == false) { Object newCookie = new Object(cookieImage, x, y, id); cookies.Add(newCookie); } } else if (msg.SequenceChannel == 6) { int start = msg.ReadInt32(); if (start == 1) { state = GameState.playing; } } break; } } } } else { KeyboardState keyState = Keyboard.GetState(); // exit game if escape or Back is pressed if (keyState.IsKeyDown(Keys.Escape) || GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // use arrows or dpad to move avatar if (GamePad.GetState(PlayerIndex.One).DPad.Left == ButtonState.Pressed || keyState.IsKeyDown(Keys.Left)) if (player.getPos().X > 0) { xinput = -3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds; } if (GamePad.GetState(PlayerIndex.One).DPad.Right == ButtonState.Pressed || keyState.IsKeyDown(Keys.Right)) if (player.getPos().X < 1160) { xinput = 3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds; } //if (GamePad.GetState(PlayerIndex.One).DPad.Up == ButtonState.Pressed || keyState.IsKeyDown(Keys.Up)) //if (GamePad.GetState(PlayerIndex.One).DPad.Down == ButtonState.Pressed || keyState.IsKeyDown(Keys.Down)) if (player.getPos().Y < 480 && player.goingUp() == false) { yinput = 3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds; foreach (var tramp in trampolines) { Rectangle recA = new Rectangle((int)player.getPos().X, (int)player.getPos().Y, player.getImage().Width, player.getImage().Height); Rectangle recB = new Rectangle((int)tramp.getPos().X, (int)tramp.getPos().Y, tramp.getImage().Width, tramp.getImage().Height); if (collision.PerPixel(recA, player.getImage(), recB, tramp.getImage()) && (player.getPos().Y + 100 <= tramp.getPos().Y)) { player.updateDirection(); //player.updateImage(truettJump); break; } } //yinput = 3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds; } else if (player.getPos().Y >= 0 && player.goingUp() == true) { yinput = -3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds; if (player.getPos().Y <= 50) { player.updateDirection(); //player.updateImage(truettFall); } } foreach(var pl in allPlayers) { for (int x = 0; x < cookies.Count; x++) { Rectangle recA = new Rectangle((int)player.getPos().X, (int)player.getPos().Y, 114, 240); Rectangle recB = new Rectangle((int)cookies[x].getPos().X, (int)cookies[x].getPos().Y, 60, 60); Rectangle recC = new Rectangle((int)pl.getPos().X, (int)pl.getPos().Y, 114, 240); if (recA.Intersects(recB) || recC.Intersects(recB)) { if(recA.Intersects(recB)) { NetOutgoingMessage om = client.CreateMessage(); om.Write(player.getId()); om.Write(cookies[x].getId()); client.SendMessage(om, NetDeliveryMethod.UnreliableSequenced, 1); } cookies.RemoveAt(x); //We just removed an object, so we set x back by one to make sure we skip none //Just sit down and think about it, it makes sense x--; } } } if (xinput != 0 || yinput != 0) { player.updatePosX(xinput); player.updatePosY(yinput); //player.newPos(new Vector2(xinput, yinput)); //Console.WriteLine(player.getPos().X + " " + player.getPos().Y); // // If there's input; send it to server // NetOutgoingMessage om = client.CreateMessage(); om.Write(player.getId()); om.Write(xinput); // very inefficient to send a full Int32 (4 bytes) but we'll use this for simplicity om.Write(yinput); client.SendMessage(om, NetDeliveryMethod.UnreliableSequenced, 0); } //move all the other players foreach (var p in allPlayers) { if (player.getId() != p.getId()) { if (p.getMoveX() == 1) { p.updatePosX(3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds); } else if (p.getMoveX() == -1) { p.updatePosX(-3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds); } if (p.getMoveY() == 1) { p.updatePosY(3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds); //p.updateImage(truettJump); } else if (p.getMoveY() == -1) { p.updatePosY(-3 * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds); //p.updateImage(truettFall); } } } //move toby moveToby(gameTime); // read messages NetIncomingMessage msg; while ((msg = client.ReadMessage()) != null) { bool playerFound = false; bool cookieFound = false; switch (msg.MessageType) { case NetIncomingMessageType.DiscoveryResponse: // just connect to first server discovered Console.WriteLine("Received a request response"); if (gameType == "single") { client.Connect(msg.SenderEndPoint); } break; case NetIncomingMessageType.Data: if (msg.SequenceChannel == 0) { // server sent a position update long who = msg.ReadInt64(); float x = msg.ReadFloat(); float y = msg.ReadFloat(); int playerNum = msg.ReadInt32(); foreach (var p in allPlayers) { if (who == p.getId()) { if (p.getId() != player.getId()) { float xDiff = Math.Abs(x - p.getPos().X); float yDiff = Math.Abs(y - p.getPos().Y); if (xDiff <= 5) { p.setMoveX(0); } else if (x > p.getPos().X) { p.setMoveX(1); } else if (x < p.getPos().X) { p.setMoveX(-1); } if (y == p.getPos().Y) { p.setMoveY(0); } else if (y > p.getPos().Y) { p.setMoveY(1); } else { p.setMoveY(-1); } } } } positions[who] = new Vector2(x, y); } if (msg.SequenceChannel == 1) { //cookies.Clear(); float x = msg.ReadFloat(); float y = msg.ReadFloat(); int id = msg.ReadInt32(); foreach (var c in cookies) { if (c.getId() == id) { cookieFound = true; } } if (cookieFound == false) { Object newCookie = new Object(cookieImage, x, y, id); cookies.Add(newCookie); } } else if (msg.SequenceChannel == 2) { int cookieId = msg.ReadInt32(); List<Object> deleteCookies = new List<Object>(cookies); foreach (var c in deleteCookies) { if (c.getId() == cookieId) { cookies.Remove(c); } } } else if (msg.SequenceChannel == 4) { remoteLevel = msg.ReadInt32(); if (localLevel != remoteLevel) { localLevel = remoteLevel; Thread.Sleep(2000); } } break; } } textbox.Update(gameTime); base.Update(gameTime); } }
public void launchServer() { //populate cookies // run until escape is pressed while (true) { //Console.WriteLine(cookies.Count); if (currentLevel != previousLevel) { previousLevel = currentLevel; populateCookies(); foreach (NetConnection player in server.Connections) { foreach (var c in cookies) { NetOutgoingMessage om = server.CreateMessage(); om.Write(c.getPos().X); om.Write(c.getPos().Y); om.Write(c.getId()); server.SendMessage(om, player, NetDeliveryMethod.UnreliableSequenced, 1); } } } if (cookies.Count == 0 && previousLevel != 0) { currentLevel++; foreach (NetConnection player in server.Connections) { NetOutgoingMessage om = server.CreateMessage(); om.Write(currentLevel); server.SendMessage(om, player, NetDeliveryMethod.UnreliableSequenced, 4); } } NetIncomingMessage msg; while ((msg = server.ReadMessage()) != null) { switch (msg.MessageType) { case NetIncomingMessageType.DiscoveryRequest: // // Server received a discovery request from a client; send a discovery response (with no extra data attached) // server.SendDiscoveryResponse(null, msg.SenderEndPoint); break; case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: // // Just print diagnostic messages to console // //Console.WriteLine(msg.ReadString()); break; case NetIncomingMessageType.StatusChanged: NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte(); if (status == NetConnectionStatus.Connected) { // // A new player just connected! // //Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!"); numPlayers += 1; Player newPlayer = new Player(msg.SenderConnection.RemoteUniqueIdentifier, numPlayers); newPlayer.setConnection(msg.SenderConnection); // randomize his position and store in connection tag if (numPlayers == 1) { newPlayer.updatePosX(100.0f); newPlayer.updatePosY(150.0f); //populateCookies(); foreach (var c in cookies) { NetOutgoingMessage om = server.CreateMessage(); om.Write(c.getPos().X); om.Write(c.getPos().Y); om.Write(c.getId()); server.SendMessage(om, msg.SenderConnection, NetDeliveryMethod.UnreliableSequenced, 1); } } //else if (numPlayers == 3) //{ // msg.SenderConnection.Tag = new float[] { 950, 100 }; // foreach (var c in cookies) // { // NetOutgoingMessage om = server.CreateMessage(); // om.Write(c.getPos().X); // om.Write(c.getPos().Y); // om.Write(c.getId()); // server.SendMessage(om, msg.SenderConnection, NetDeliveryMethod.UnreliableSequenced, 1); // } //} else { newPlayer.updatePosX(550.0f); newPlayer.updatePosY(100.0f); foreach (var c in cookies) { NetOutgoingMessage om = server.CreateMessage(); om.Write(c.getPos().X); om.Write(c.getPos().Y); om.Write(c.getId()); server.SendMessage(om, msg.SenderConnection, NetDeliveryMethod.UnreliableSequenced, 1); } } //msg.SenderConnection.Tag = new float[] { // NetRandom.Instance.Next(10, 100), // NetRandom.Instance.Next(10, 100) //}; playerList.Add(newPlayer); } break; case NetIncomingMessageType.Data: // // The client sent input to the server // if (msg.SequenceChannel == 0) { long playerId = msg.ReadInt64(); float xinput = msg.ReadFloat(); float yinput = msg.ReadFloat(); foreach (var p in playerList) { if(playerId == p.getId()) { p.updatePosX(xinput); p.updatePosY(yinput); } } } else if (msg.SequenceChannel == 1) { long playerId = msg.ReadInt64(); int cookieId = msg.ReadInt32(); foreach (var p in playerList) { if (p.getId() == playerId) { p.increaseScore(1); } } List<Object> newCookies = new List<Object>(cookies); int count = 0; foreach (var c in newCookies) { if (c.getId() == cookieId) { cookies.RemoveAt(count); } count++; } foreach (NetConnection player in server.Connections) { if (player.RemoteUniqueIdentifier != playerId) { NetOutgoingMessage om = server.CreateMessage(); om.Write(cookieId); server.SendMessage(om, player, NetDeliveryMethod.UnreliableSequenced, 2); } } } else if (msg.SequenceChannel == 6) { long playerId = msg.ReadInt64(); int startGame = msg.ReadInt32(); if (startGame == 1) { foreach (var p in playerList) { if (p.getId() != playerId) { NetOutgoingMessage om = server.CreateMessage(); om.Write(startGame); server.SendMessage(om, p.getCon(), NetDeliveryMethod.UnreliableSequenced, 6); } } } } //Console.WriteLine(pos[0]); //Console.WriteLine(pos[1]); break; } // // send position updates 30 times per second // double now = NetTime.Now; if (now > nextSendUpdates) { // Yes, it's time to send position updates // for each player... //foreach (NetConnection player in server.Connections) //{ // // ... send information about every other player (actually including self) // foreach (NetConnection otherPlayer in server.Connections) // { // // send position update about 'otherPlayer' to 'player' // NetOutgoingMessage om = server.CreateMessage(); // // write who this position is for // om.Write(otherPlayer.RemoteUniqueIdentifier); // if (otherPlayer.Tag == null) // otherPlayer.Tag = new float[2]; // //Console.WriteLine(otherPlayer.Tag); // float[] pos = otherPlayer.Tag as float[]; // om.Write(pos[0]); // om.Write(pos[1]); // // send message // server.SendMessage(om, player, NetDeliveryMethod.UnreliableSequenced, 0); // } // //send information about the cookies //} foreach (var player in playerList) { // ... send information about every other player (actually including self) foreach (var otherPlayer in playerList) { // send position update about 'otherPlayer' to 'player' NetOutgoingMessage om = server.CreateMessage(); // write who this position is for om.Write(otherPlayer.getId()); om.Write(otherPlayer.getPosX()); om.Write(otherPlayer.getPosY()); om.Write(otherPlayer.getPlayerNum()); // send message server.SendMessage(om, player.getCon(), NetDeliveryMethod.UnreliableSequenced, 0); } //send information about the cookies } // schedule next update nextSendUpdates += (1.0 / 30.0); } } // sleep to allow other processes to run smoothly Thread.Sleep(1); } server.Shutdown("app exiting"); }
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); trampolines = new Object[3]; cookieImage = Content.Load<Texture2D>("cookie"); tobyLeft1 = Content.Load<Texture2D>("toby_left1"); tobyLeft2 = Content.Load<Texture2D>("toby_left2"); tobyRight1 = Content.Load<Texture2D>("toby_right1"); tobyRight2 = Content.Load<Texture2D>("toby_right2"); tobyStanding = Content.Load<Texture2D>("toby_stand"); trampolineImage1 = Content.Load<Texture2D>("trampoline"); trampolineImage2 = Content.Load<Texture2D>("trampoline_pressed"); truettFall = Content.Load<Texture2D>("Truett"); truettJump = Content.Load<Texture2D>("truett_jump"); background = Content.Load<Texture2D>("park"); single_player_button = Content.Load<Texture2D>("single_player"); multi_player_button = Content.Load<Texture2D>("multi_player"); host_button = Content.Load<Texture2D>("host"); join_button = Content.Load<Texture2D>("join"); internet_button = Content.Load<Texture2D>("internet"); lan_button = Content.Load<Texture2D>("lan"); start_button = Content.Load<Texture2D>("startGame"); truett_yellow = Content.Load<Texture2D>("Truett2"); truett_green = Content.Load<Texture2D>("Truett3"); textbox = new TextBox(GraphicsDevice, 400, Content.Load<SpriteFont>("Text")) { ForegroundColor = Color.White, BackgroundColor = Color.CornflowerBlue, Position = new Vector2(100, 300), HasFocus = true }; float xPosition = 150; for (int i = 0; i < 3; i++) { trampolines[i] = new Object(trampolineImage1, xPosition, 500); xPosition += 400; } Console.WriteLine(client.UniqueIdentifier); player = new Player(truettFall, 150, 100, client.UniqueIdentifier); toby = new Player(tobyRight1, 50, 550, -1); //allPlayers.Add(player); singlePlayerButton = new Button(single_player_button, 100, 100); multiplayerButton = new Button(multi_player_button, 100, 200); joinGame = new Button(join_button, 300, 100); hostGame = new Button(host_button, 300, 200); joinLan = new Button(lan_button, 100, 100); joinIneternet = new Button(internet_button, 100, 200); hostLan = new Button(lan_button, 100, 100); hostInternet = new Button(internet_button, 100, 200); startGame = new Button(start_button, 400, 100); }