private void msgTicker_Tick(object sender, EventArgs e) { //Console.WriteLine(gameTime.TotalGameTime.TotalSeconds+" server"); if (server != null) { NetIncomingMessage msg; NetOutgoingMessage response; NetConnection msgCon; string msgString; int msgInt; // check for new messages (all messages in queu per update cycle) while ((msg = networkManager.getMessage()) != null) { switch (msg.MessageType) { // Client sucht nach einem Server case NetIncomingMessageType.DiscoveryRequest: this.WriteToLog("Discoveryanfrage von: " + msg.SenderEndpoint.Address.ToString()); // Create a response response = networkManager.createMessage(); // Send the response to the sender of the request try { server.SendDiscoveryResponse(response, msg.SenderEndpoint); this.WriteToLog("Antwort an " + msg.SenderEndpoint + " geschickt"); } catch (Exception) { this.WriteToLog("Antwort an " + msg.SenderEndpoint + " konnte nicht gesendet werden"); } break; // Es handelt sich um ein Datenpaket case NetIncomingMessageType.Data: msgString = msg.ReadString(); switch (msgString) { // Client startete Spiel und wartet nun auf Initialisierung vom Server case "startGame": string fileName = @"\Levels\level1.csv"; gameStateManager.Level = new LevelProcessor().LoadMap(fileName); this.WriteToLog("Level " + fileName + " loaded"); msgInt = msg.ReadInt32(); foreach (Client c in connectedClients) { if (c.getConnection() == msg.SenderConnection) { c.setFigureType(msgInt); switch (c.getFigureType()) { case 1: NetworkController networkController = new NetworkController(c.getUID(), EmptyController.Empty(c.getUID()), networkManager); PacMan pacMan = new PacMan(string.Empty, gameStateManager.Level.getCell(1, 1), gameStateManager.Level, EmptyController.Empty(c.getUID()), Direction.None, 0.9f, new Point(49, 49)); gameStateManager.AddPlayers(pacMan); break; default: WriteToLog("Ghost isn't implemented yet"); break; } // Remove Client from pending list pendingClients.Remove(c.getConnection()); //gameStateManager.AddPlayers(new PacMan()); this.WriteToLog("Set figureType " + msgInt + " to Client " + c.getConnection().RemoteEndpoint.Address); } } gameLoop = new GameLoop(5000); gameLoop.StartingSimulation += StartSimulation; gameLoop.FinishedSimulation += FinishedSimulation; //gameTime.Start(); break; // Got direction update from client deploy it to the rest case "newDirection": msgInt = msg.ReadInt32(); long msgLong = msg.ReadInt64(); msgCon = msg.SenderConnection; // calculate the UID from the sender of the message string msgUID = msgCon.RemoteUniqueIdentifier.ToString().Substring(msgCon.RemoteUniqueIdentifier.ToString().Length - 5); MovableObject toChange = gameStateManager.getFromId(Convert.ToInt32(msgUID)); WriteToLogDebug("UID " + toChange.ID + "s current direction: " + (Direction)msgInt); inputQueue.Add(new Command((Direction)msgInt, Convert.ToInt32(msgUID), gameTime.TotalGameTime.Milliseconds)); //toChange.Direction = (Direction)msgInt; // send direction updates to all clients except the sender foreach (Client c in connectedClients) { if (c.getConnection() != msgCon) { response = networkManager.createMessage(); response.Write("updateDirection;" + msgUID + ";" + msgInt); networkManager.sendMessage(response, c.getConnection()); this.WriteToLog("Sent direction update for uid " + msgUID + " to " + c.getConnection().RemoteEndpoint.Address + "Time: " + gameTime.TotalGameTime.TotalMilliseconds); } } MovableObject changed = gameStateManager.getFromId(Convert.ToInt32(msgUID)); //WriteToLogDebug("UID " + changed.ID + "s current direction: " + changed.Direction); break; // client is asking for the list of connected clients case "getPlayers": this.WriteToLog("Client asked for Players"); string players = ""; // create a string with all connected clients (example 15482/1;56847/2) foreach (Client c in connectedClients) { if (players == "") { players = c.getUID() + "/" + c.getFigureType() + ";"; } else { players = players + c.getUID() + "/" + c.getFigureType()+";"; } } response = networkManager.createMessage(); // add "getPlayser" to the string for message identification on the client and send the message response.Write("getPlayers;"+players); networkManager.sendMessage(response, msg.SenderConnection); this.WriteToLog("List of players " + players); break; case "latencyTime": //this.WriteToLogDebug("Got timesync request"); response = networkManager.createMessage(); response.Write(msgString); networkManager.sendMessage(response, msg.SenderConnection); break; case "syncTime": response = networkManager.createMessage(); response.Write(msgString); // serialize the current servertime and send it to the requesting client response.Write(networkManager.Serialize(gameTime.TotalGameTime)); this.WriteToLogDebug("Sent server time: " + gameTime.TotalGameTime.TotalSeconds); networkManager.sendMessage(response, msg.SenderConnection); break; } break; case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.StatusChanged: msgString = msg.ReadString(); msgCon = msg.SenderConnection; // Weil bei der connect-Nachricht vom Client spezielle escape-Zeichen // mitgesendet werden, muss der String angepasst werden, damit er // verglichen werden kann string corrString = msgString.Substring(msgString.Length - 2); if (corrString.CompareTo("Co") == 0) { try { response = networkManager.createMessage(); response.Write("connected"); networkManager.sendMessage(response, msgCon); // create new client Client c = new Client(msgCon); // add new client to the list of connected clients connectedClients.Add(c); // add new client to the list of pending clients (clients in this list are still configuring their game options) pendingClients.Add(msgCon); this.WriteToLog("Sent connection approval to" + msg.SenderEndpoint + " with UID: "+c.getUID()); } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); } } break; case NetIncomingMessageType.ErrorMessage: this.WriteToLog("Error: " + msg.ReadString()); break; default: this.WriteToLog("Unhandled type: " + msg.MessageType + " -> " + msg.ReadString()); break; } server.Recycle(msg); } // All Players are ready, send start message to all connected clients if (pendingClients.Count == 0 && gameRunning == false && connectedClients.Count > 0) { response = networkManager.createMessage(); response.Write("start"); foreach (Client c in connectedClients) { networkManager.sendMessage(response, c.getConnection()); } gameRunning = true; } } gameTime.Reset(); }
/// <summary> /// Initializes the current screen /// </summary> public override void Initialize() { //Store everything inside the gameStateManager gameStateManager = new GameStateManager(); gameStateManager.GameState = GameState.Loading; gameStateManager.Level = level; //Initialize the gameplay behaviours playBehaviour = new PlayBehaviour(); deathBehaviour = new DeathBehaviour(); var parser = new LevelParser(); gameStateManager.Level = parser.GenerateLevel(ScreenManager.Content.Load<List<String[]>>(@"Levels\level1")); guiElements = new List<GamePlayScreens.GUI.GUIElement>(); //camera = new Camera(1, Vector2.Zero, 0); camera = new Camera(0.4f, Vector2.Zero, 0, true, null); // ask server for List of connected and waiting clients networkManager.sendMessage("getPlayers"); // wait for the response to the request of available players NetIncomingMessage msg; bool waitingForServer = true; while (waitingForServer) { // check for messages as long the incoming messages queue has messages stored while ((msg = networkManager.getMessage()) != null) { switch (msg.MessageType) { case NetIncomingMessageType.Data: string msgStr = msg.ReadString(); // check if the message is the response to the request string[] clients = msgStr.Split(';'); if (clients[0] == "getPlayers") { int i = 1; foreach (string player in clients) { if (player != "" && player != "getPlayers") { string[] values = player.Split('/'); int localUID = networkManager.getUID(); int remoteUID = Convert.ToInt32(values[0]); switch (values[1]) { case "1": // Player is a PacMan // Check if it is a local or remote controlled gameobject if (localUID == remoteUID) // local controlled { PlayerController playerController = new PlayerController( Direction.None, values[0], remoteUID, PlayerIndex.One, MovObjType.LocalPacMan, ScreenManager.Input); NetworkController networkController = new NetworkController(playerController.ID, playerController, networkManager); gameStateManager.AddPlayers(new PacMan(@"Sprites\PacMan", gameStateManager.Level.getCell(1, 1), gameStateManager.Level, networkController, Direction.None, 1.3f, new Point(50, 50))); } else // remote controlled { EmptyController emptyController = new EmptyController(Direction.None, values[0], remoteUID, MovObjType. NetPacMan); gameStateManager.AddPlayers(new PacMan(@"Sprites\PacMan", gameStateManager.Level.getCell(1, 1), gameStateManager.Level, new NetworkController(emptyController.ID, emptyController, networkManager), Direction.None, 1.3f, new Point(50, 50))); } GUIString stringElement = new GUIString(gameStateManager.MovableObjects.Last(), Color.White, new Vector2(0, 0), new Vector2(10, i * 10)); guiElements.Add(stringElement); break; case "2": // Player is a Ghost Blinky blinky = new Blinky(gameStateManager.GetAllOfType<PacMan>()[0], new Point(0, 0), new Point(15, 15), new Point(17, 17)); GhostController ghostController = new GhostController(level, blinky, remoteUID); NetworkGhostController ghostNetworkController = new NetworkGhostController(networkManager, ghostController, ghostController.ID); gameStateManager.AddPlayers(new Ghost(@"Sprites\GhostBase", gameStateManager.Level.getCell(26, 1), gameStateManager.Level, Direction.Down, 0.8f, new Point(50, 50), Color.Crimson, ghostNetworkController)); // else // { // // // gameStateManager.AddPlayers(new Ghost(@"Sprites\GhostBase", gameStateManager.Level.getCell(26, 1), gameStateManager.Level, // Direction.Down, 0.8f, new Point(50, 50), Color.Crimson, new NetworkController(Direction.None, values[0], Convert.ToInt32(values[0]), // PlayerIndex.One, MovObjType.NetGhost, ScreenManager.Input, networkManager))); // } break; } i += 10; } } // All mvable objects are initialized, start game waitingForServer = false; } break; } } } gameStateManager.CreateTimestamp(0); }