ClientServerGame.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // ClientServerGame.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using Microsoft.Xna.Framework;
  12. using Microsoft.Xna.Framework.GamerServices;
  13. using Microsoft.Xna.Framework.Graphics;
  14. using Microsoft.Xna.Framework.Input;
  15. using Microsoft.Xna.Framework.Net;
  16. #endregion
  17. namespace ClientServer
  18. {
  19. /// <summary>
  20. /// Sample showing how to implement a simple multiplayer
  21. /// network session, using a client/server network topology.
  22. /// </summary>
  23. public class ClientServerGame : Microsoft.Xna.Framework.Game
  24. {
  25. #region Fields
  26. const int screenWidth = 1067;
  27. const int screenHeight = 600;
  28. const int maxGamers = 16;
  29. const int maxLocalGamers = 4;
  30. GraphicsDeviceManager graphics;
  31. SpriteBatch spriteBatch;
  32. SpriteFont font;
  33. KeyboardState currentKeyboardState;
  34. GamePadState currentGamePadState;
  35. NetworkSession networkSession;
  36. PacketWriter packetWriter = new PacketWriter();
  37. PacketReader packetReader = new PacketReader();
  38. string errorMessage;
  39. #endregion
  40. #region Initialization
  41. public ClientServerGame()
  42. {
  43. graphics = new GraphicsDeviceManager(this);
  44. graphics.PreferredBackBufferWidth = screenWidth;
  45. graphics.PreferredBackBufferHeight = screenHeight;
  46. Content.RootDirectory = "Content";
  47. Components.Add(new GamerServicesComponent(this));
  48. }
  49. /// <summary>
  50. /// Load your content.
  51. /// </summary>
  52. protected override void LoadContent()
  53. {
  54. spriteBatch = new SpriteBatch(GraphicsDevice);
  55. font = Content.Load<SpriteFont>("Font");
  56. }
  57. #endregion
  58. #region Update
  59. /// <summary>
  60. /// Allows the game to run logic.
  61. /// </summary>
  62. protected override void Update(GameTime gameTime)
  63. {
  64. HandleInput();
  65. if (networkSession == null)
  66. {
  67. // If we are not in a network session, update the
  68. // menu screen that will let us create or join one.
  69. UpdateMenuScreen();
  70. }
  71. else
  72. {
  73. // If we are in a network session, update it.
  74. UpdateNetworkSession();
  75. }
  76. base.Update(gameTime);
  77. }
  78. /// <summary>
  79. /// Menu screen provides options to create or join network sessions.
  80. /// </summary>
  81. void UpdateMenuScreen()
  82. {
  83. if (IsActive)
  84. {
  85. if (Gamer.SignedInGamers.Count == 0)
  86. {
  87. // If there are no profiles signed in, we cannot proceed.
  88. // Show the Guide so the user can sign in.
  89. Guide.ShowSignIn(maxLocalGamers, false);
  90. }
  91. else if (IsPressed(Keys.A, Buttons.A))
  92. {
  93. // Create a new session?
  94. CreateSession();
  95. }
  96. else if (IsPressed(Keys.B, Buttons.B))
  97. {
  98. // Join an existing session?
  99. JoinSession();
  100. }
  101. }
  102. }
  103. /// <summary>
  104. /// Starts hosting a new network session.
  105. /// </summary>
  106. void CreateSession()
  107. {
  108. DrawMessage("Creating session...");
  109. try
  110. {
  111. networkSession = NetworkSession.Create(NetworkSessionType.SystemLink,
  112. maxLocalGamers, maxGamers);
  113. HookSessionEvents();
  114. }
  115. catch (Exception e)
  116. {
  117. errorMessage = e.Message;
  118. }
  119. }
  120. /// <summary>
  121. /// Joins an existing network session.
  122. /// </summary>
  123. void JoinSession()
  124. {
  125. DrawMessage("Joining session...");
  126. try
  127. {
  128. // Search for sessions.
  129. using (AvailableNetworkSessionCollection availableSessions =
  130. NetworkSession.Find(NetworkSessionType.SystemLink,
  131. maxLocalGamers, null))
  132. {
  133. if (availableSessions.Count == 0)
  134. {
  135. errorMessage = "No network sessions found.";
  136. return;
  137. }
  138. // Join the first session we found.
  139. networkSession = NetworkSession.Join(availableSessions[0]);
  140. HookSessionEvents();
  141. }
  142. }
  143. catch (Exception e)
  144. {
  145. errorMessage = e.Message;
  146. }
  147. }
  148. /// <summary>
  149. /// After creating or joining a network session, we must subscribe to
  150. /// some events so we will be notified when the session changes state.
  151. /// </summary>
  152. void HookSessionEvents()
  153. {
  154. networkSession.GamerJoined += GamerJoinedEventHandler;
  155. networkSession.SessionEnded += SessionEndedEventHandler;
  156. }
  157. /// <summary>
  158. /// This event handler will be called whenever a new gamer joins the session.
  159. /// We use it to allocate a Tank object, and associate it with the new gamer.
  160. /// </summary>
  161. void GamerJoinedEventHandler(object sender, GamerJoinedEventArgs e)
  162. {
  163. int gamerIndex = networkSession.AllGamers.IndexOf(e.Gamer);
  164. e.Gamer.Tag = new Tank(gamerIndex, Content, screenWidth, screenHeight);
  165. }
  166. /// <summary>
  167. /// Event handler notifies us when the network session has ended.
  168. /// </summary>
  169. void SessionEndedEventHandler(object sender, NetworkSessionEndedEventArgs e)
  170. {
  171. errorMessage = e.EndReason.ToString();
  172. networkSession.Dispose();
  173. networkSession = null;
  174. }
  175. /// <summary>
  176. /// Updates the state of the network session, moving the tanks
  177. /// around and synchronizing their state over the network.
  178. /// </summary>
  179. void UpdateNetworkSession()
  180. {
  181. // Read inputs for locally controlled tanks, and send them to the server.
  182. foreach (LocalNetworkGamer gamer in networkSession.LocalGamers)
  183. {
  184. UpdateLocalGamer(gamer);
  185. }
  186. // If we are the server, update all the tanks and transmit
  187. // their latest positions back out over the network.
  188. if (networkSession.IsHost)
  189. {
  190. UpdateServer();
  191. }
  192. // Pump the underlying session object.
  193. networkSession.Update();
  194. // Make sure the session has not ended.
  195. if (networkSession == null)
  196. return;
  197. // Read any incoming network packets.
  198. foreach (LocalNetworkGamer gamer in networkSession.LocalGamers)
  199. {
  200. if (gamer.IsHost)
  201. {
  202. ServerReadInputFromClients(gamer);
  203. }
  204. else
  205. {
  206. ClientReadGameStateFromServer(gamer);
  207. }
  208. }
  209. }
  210. /// <summary>
  211. /// Helper for updating a locally controlled gamer.
  212. /// </summary>
  213. void UpdateLocalGamer(LocalNetworkGamer gamer)
  214. {
  215. // Look up what tank is associated with this local player,
  216. // and read the latest user inputs for it. The server will
  217. // later use these values to control the tank movement.
  218. Tank localTank = gamer.Tag as Tank;
  219. ReadTankInputs(localTank, gamer.SignedInGamer.PlayerIndex);
  220. // Only send if we are not the server. There is no point sending packets
  221. // to ourselves, because we already know what they will contain!
  222. if (!networkSession.IsHost)
  223. {
  224. // Write our latest input state into a network packet.
  225. packetWriter.Write(localTank.TankInput);
  226. packetWriter.Write(localTank.TurretInput);
  227. // Send our input data to the server.
  228. gamer.SendData(packetWriter,
  229. SendDataOptions.InOrder, networkSession.Host);
  230. }
  231. }
  232. /// <summary>
  233. /// This method only runs on the server. It calls Update on all the
  234. /// tank instances, both local and remote, using inputs that have
  235. /// been received over the network. It then sends the resulting
  236. /// tank position data to everyone in the session.
  237. /// </summary>
  238. void UpdateServer()
  239. {
  240. // Loop over all the players in the session, not just the local ones!
  241. foreach (NetworkGamer gamer in networkSession.AllGamers)
  242. {
  243. // Look up what tank is associated with this player.
  244. Tank tank = gamer.Tag as Tank;
  245. // Update the tank.
  246. tank.Update();
  247. // Write the tank state into the output network packet.
  248. packetWriter.Write(gamer.Id);
  249. packetWriter.Write(tank.Position);
  250. packetWriter.Write(tank.TankRotation);
  251. packetWriter.Write(tank.TurretRotation);
  252. }
  253. // Send the combined data for all tanks to everyone in the session.
  254. LocalNetworkGamer server = (LocalNetworkGamer)networkSession.Host;
  255. server.SendData(packetWriter, SendDataOptions.InOrder);
  256. }
  257. /// <summary>
  258. /// This method only runs on the server. It reads tank inputs that
  259. /// have been sent over the network by a client machine, storing
  260. /// them for later use by the UpdateServer method.
  261. /// </summary>
  262. void ServerReadInputFromClients(LocalNetworkGamer gamer)
  263. {
  264. // Keep reading as long as incoming packets are available.
  265. while (gamer.IsDataAvailable)
  266. {
  267. NetworkGamer sender;
  268. // Read a single packet from the network.
  269. gamer.ReceiveData(packetReader, out sender);
  270. if (!sender.IsLocal)
  271. {
  272. // Look up the tank associated with whoever sent this packet.
  273. Tank remoteTank = sender.Tag as Tank;
  274. // Read the latest inputs controlling this tank.
  275. remoteTank.TankInput = packetReader.ReadVector2();
  276. remoteTank.TurretInput = packetReader.ReadVector2();
  277. }
  278. }
  279. }
  280. /// <summary>
  281. /// This method only runs on client machines. It reads
  282. /// tank position data that has been computed by the server.
  283. /// </summary>
  284. void ClientReadGameStateFromServer(LocalNetworkGamer gamer)
  285. {
  286. // Keep reading as long as incoming packets are available.
  287. while (gamer.IsDataAvailable)
  288. {
  289. NetworkGamer sender;
  290. // Read a single packet from the network.
  291. gamer.ReceiveData(packetReader, out sender);
  292. // This packet contains data about all the players in the session.
  293. // We keep reading from it until we have processed all the data.
  294. while (packetReader.Position < packetReader.Length)
  295. {
  296. // Read the state of one tank from the network packet.
  297. byte gamerId = packetReader.ReadByte();
  298. Vector2 position = packetReader.ReadVector2();
  299. float tankRotation = packetReader.ReadSingle();
  300. float turretRotation = packetReader.ReadSingle();
  301. // Look up which gamer this state refers to.
  302. NetworkGamer remoteGamer = networkSession.FindGamerById(gamerId);
  303. // This might come back null if the gamer left the session after
  304. // the host sent the packet but before we received it. If that
  305. // happens, we just ignore the data for this gamer.
  306. if (remoteGamer != null)
  307. {
  308. // Update our local state with data from the network packet.
  309. Tank tank = remoteGamer.Tag as Tank;
  310. tank.Position = position;
  311. tank.TankRotation = tankRotation;
  312. tank.TurretRotation = turretRotation;
  313. }
  314. }
  315. }
  316. }
  317. #endregion
  318. #region Draw
  319. /// <summary>
  320. /// This is called when the game should draw itself.
  321. /// </summary>
  322. protected override void Draw(GameTime gameTime)
  323. {
  324. GraphicsDevice.Clear(Color.CornflowerBlue);
  325. if (networkSession == null)
  326. {
  327. // If we are not in a network session, draw the
  328. // menu screen that will let us create or join one.
  329. DrawMenuScreen();
  330. }
  331. else
  332. {
  333. // If we are in a network session, draw it.
  334. DrawNetworkSession();
  335. }
  336. base.Draw(gameTime);
  337. }
  338. /// <summary>
  339. /// Draws the startup screen used to create and join network sessions.
  340. /// </summary>
  341. void DrawMenuScreen()
  342. {
  343. string message = string.Empty;
  344. if (!string.IsNullOrEmpty(errorMessage))
  345. message += "Error:\n" + errorMessage.Replace(". ", ".\n") + "\n\n";
  346. message += "A = create session\n" +
  347. "B = join session";
  348. spriteBatch.Begin();
  349. spriteBatch.DrawString(font, message, new Vector2(161, 161), Color.Black);
  350. spriteBatch.DrawString(font, message, new Vector2(160, 160), Color.White);
  351. spriteBatch.End();
  352. }
  353. /// <summary>
  354. /// Draws the state of an active network session.
  355. /// </summary>
  356. void DrawNetworkSession()
  357. {
  358. spriteBatch.Begin();
  359. // For each person in the session...
  360. foreach (NetworkGamer gamer in networkSession.AllGamers)
  361. {
  362. // Look up the tank object belonging to this network gamer.
  363. Tank tank = gamer.Tag as Tank;
  364. // Draw the tank.
  365. tank.Draw(spriteBatch);
  366. // Draw a gamertag label.
  367. string label = gamer.Gamertag;
  368. Color labelColor = Color.Black;
  369. Vector2 labelOffset = new Vector2(100, 150);
  370. if (gamer.IsHost)
  371. label += " (server)";
  372. // Flash the gamertag to yellow when the player is talking.
  373. if (gamer.IsTalking)
  374. labelColor = Color.Yellow;
  375. spriteBatch.DrawString(font, label, tank.Position, labelColor, 0,
  376. labelOffset, 0.6f, SpriteEffects.None, 0);
  377. }
  378. spriteBatch.End();
  379. }
  380. /// <summary>
  381. /// Helper draws notification messages before calling blocking network methods.
  382. /// </summary>
  383. void DrawMessage(string message)
  384. {
  385. if (!BeginDraw())
  386. return;
  387. GraphicsDevice.Clear(Color.CornflowerBlue);
  388. spriteBatch.Begin();
  389. spriteBatch.DrawString(font, message, new Vector2(161, 161), Color.Black);
  390. spriteBatch.DrawString(font, message, new Vector2(160, 160), Color.White);
  391. spriteBatch.End();
  392. EndDraw();
  393. }
  394. #endregion
  395. #region Handle Input
  396. /// <summary>
  397. /// Handles input.
  398. /// </summary>
  399. private void HandleInput()
  400. {
  401. currentKeyboardState = Keyboard.GetState();
  402. currentGamePadState = GamePad.GetState(PlayerIndex.One);
  403. // Check for exit.
  404. if (IsActive && IsPressed(Keys.Escape, Buttons.Back))
  405. {
  406. Exit();
  407. }
  408. }
  409. /// <summary>
  410. /// Checks if the specified button is pressed on either keyboard or gamepad.
  411. /// </summary>
  412. bool IsPressed(Keys key, Buttons button)
  413. {
  414. return (currentKeyboardState.IsKeyDown(key) ||
  415. currentGamePadState.IsButtonDown(button));
  416. }
  417. /// <summary>
  418. /// Reads input data from keyboard and gamepad, and stores
  419. /// it into the specified tank object.
  420. /// </summary>
  421. void ReadTankInputs(Tank tank, PlayerIndex playerIndex)
  422. {
  423. // Read the gamepad.
  424. GamePadState gamePad = GamePad.GetState(playerIndex);
  425. Vector2 tankInput = gamePad.ThumbSticks.Left;
  426. Vector2 turretInput = gamePad.ThumbSticks.Right;
  427. // Read the keyboard.
  428. KeyboardState keyboard = Keyboard.GetState(playerIndex);
  429. if (keyboard.IsKeyDown(Keys.Left))
  430. tankInput.X = -1;
  431. else if (keyboard.IsKeyDown(Keys.Right))
  432. tankInput.X = 1;
  433. if (keyboard.IsKeyDown(Keys.Up))
  434. tankInput.Y = 1;
  435. else if (keyboard.IsKeyDown(Keys.Down))
  436. tankInput.Y = -1;
  437. if (keyboard.IsKeyDown(Keys.A))
  438. turretInput.X = -1;
  439. else if (keyboard.IsKeyDown(Keys.D))
  440. turretInput.X = 1;
  441. if (keyboard.IsKeyDown(Keys.W))
  442. turretInput.Y = 1;
  443. else if (keyboard.IsKeyDown(Keys.S))
  444. turretInput.Y = -1;
  445. // Normalize the input vectors.
  446. if (tankInput.Length() > 1)
  447. tankInput.Normalize();
  448. if (turretInput.Length() > 1)
  449. turretInput.Normalize();
  450. // Store these input values into the tank object.
  451. tank.TankInput = tankInput;
  452. tank.TurretInput = turretInput;
  453. }
  454. #endregion
  455. }
  456. #region Entry Point
  457. /// <summary>
  458. /// The main entry point for the application.
  459. /// </summary>
  460. static class Program
  461. {
  462. static void Main()
  463. {
  464. using (ClientServerGame game = new ClientServerGame())
  465. {
  466. game.Run();
  467. }
  468. }
  469. }
  470. #endregion
  471. }