LobbyScreen.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // LobbyScreen.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.Net;
  15. #endregion
  16. namespace NetRumble
  17. {
  18. /// <summary>
  19. /// The lobby screen is shows the players in the game, outside the gameplay.
  20. /// </summary>
  21. public class LobbyScreen : MenuScreen, IDisposable
  22. {
  23. #region Constants
  24. /// <summary>
  25. /// The instructions shown to the player at the bottom of the lobby screen.
  26. /// </summary>
  27. const string instructions =
  28. "Press X to mark/unmark ready, LB/RB to toggle color, LT/RT to toggle ship";
  29. #endregion
  30. #region Gameplay Data
  31. /// <summary>
  32. /// The primary object for this game.
  33. /// </summary>
  34. private World world;
  35. #endregion
  36. #region Networking Data
  37. /// <summary>
  38. /// The network session for this game.
  39. /// </summary>
  40. private NetworkSession networkSession;
  41. /// <summary>
  42. /// The packet writer used to send data from this screen.
  43. /// </summary>
  44. private PacketWriter packetWriter = new PacketWriter();
  45. /// <summary>
  46. /// Event handler for the session-ended event.
  47. /// </summary>
  48. EventHandler<NetworkSessionEndedEventArgs> sessionEndedHandler;
  49. /// <summary>
  50. /// Event handler for the game-ended event.
  51. /// </summary>
  52. EventHandler<GameStartedEventArgs> gameStartedHandler;
  53. /// <summary>
  54. /// Event handler for the gamer-left event.
  55. /// </summary>
  56. EventHandler<GamerJoinedEventArgs> gamerJoinedHandler;
  57. #endregion
  58. #region Initialization
  59. /// <summary>
  60. /// Constructs a new LobbyScreen object.
  61. /// </summary>
  62. public LobbyScreen(NetworkSession networkSession) : base()
  63. {
  64. // safety-check the parameter
  65. if (networkSession == null)
  66. {
  67. throw new ArgumentNullException("networkSession");
  68. }
  69. // apply the parameters
  70. this.networkSession = networkSession;
  71. // add the single menu entry
  72. MenuEntries.Add("");
  73. // set the transition time
  74. TransitionOnTime = TimeSpan.FromSeconds(1.0);
  75. TransitionOffTime = TimeSpan.FromSeconds(0.0);
  76. gamerJoinedHandler = new EventHandler<GamerJoinedEventArgs>(
  77. networkSession_GamerJoined);
  78. gameStartedHandler = new EventHandler<GameStartedEventArgs>(
  79. networkSession_GameStarted);
  80. sessionEndedHandler = new EventHandler<NetworkSessionEndedEventArgs>(
  81. networkSession_SessionEnded);
  82. }
  83. /// <summary>
  84. /// Load graphics content for the game.
  85. /// </summary>
  86. public override void LoadContent()
  87. {
  88. base.LoadContent();
  89. // create the world object
  90. world = new World(ScreenManager.GraphicsDevice, ScreenManager.Content,
  91. networkSession);
  92. // set the networking events
  93. networkSession.GamerJoined += gamerJoinedHandler;
  94. networkSession.GameStarted += gameStartedHandler;
  95. networkSession.SessionEnded += sessionEndedHandler;
  96. }
  97. #endregion
  98. #region Updating Methods
  99. /// <summary>
  100. /// Updates the lobby. This method checks the GameScreen.IsActive
  101. /// property, so the game will stop updating when the pause menu is active,
  102. /// or if you tab away to a different application.
  103. /// </summary>
  104. public override void Update(Microsoft.Xna.Framework.GameTime gameTime,
  105. bool otherScreenHasFocus, bool coveredByOtherScreen)
  106. {
  107. if (networkSession != null)
  108. {
  109. // update the network session
  110. try
  111. {
  112. networkSession.Update();
  113. }
  114. catch (NetworkException ne)
  115. {
  116. System.Console.WriteLine(
  117. "Network failed to update: " + ne.ToString());
  118. if (networkSession != null)
  119. {
  120. networkSession.Dispose();
  121. networkSession = null;
  122. }
  123. }
  124. }
  125. // update the world
  126. if ((world != null) && !otherScreenHasFocus && !coveredByOtherScreen)
  127. {
  128. if (world.GameWon)
  129. {
  130. // unload the existing world
  131. world.Dispose();
  132. world = null;
  133. // make sure that all of the ships have cleaned up
  134. foreach (NetworkGamer networkGamer in networkSession.AllGamers)
  135. {
  136. PlayerData playerData = networkGamer.Tag as PlayerData;
  137. if ((playerData != null) && (playerData.Ship != null))
  138. {
  139. playerData.Ship.Die(null, true);
  140. }
  141. }
  142. // make sure the collision manager is up-to-date
  143. CollisionManager.Collection.ApplyPendingRemovals();
  144. // create a new world
  145. world = new World(ScreenManager.GraphicsDevice,
  146. ScreenManager.Content, networkSession);
  147. }
  148. else if (world.GameExited)
  149. {
  150. if (!IsExiting)
  151. {
  152. ExitScreen();
  153. }
  154. if (world != null)
  155. {
  156. world.Dispose();
  157. world = null;
  158. }
  159. if (networkSession != null)
  160. {
  161. networkSession.Dispose();
  162. networkSession = null;
  163. }
  164. base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  165. return;
  166. }
  167. else
  168. {
  169. world.Update((float)gameTime.ElapsedGameTime.TotalSeconds, true);
  170. }
  171. }
  172. // update the menu entry text
  173. if (otherScreenHasFocus == false)
  174. {
  175. if ((networkSession.LocalGamers.Count > 0) &&
  176. (networkSession.SessionState == NetworkSessionState.Lobby))
  177. {
  178. if (!networkSession.LocalGamers[0].IsReady)
  179. {
  180. MenuEntries[0] = "Press X to Mark as Ready";
  181. }
  182. else if (!networkSession.IsEveryoneReady)
  183. {
  184. MenuEntries[0] = "Waiting for all players to mark as ready...";
  185. }
  186. else if (!networkSession.IsHost)
  187. {
  188. MenuEntries[0] = "Waiting for the host to start game...";
  189. }
  190. else
  191. {
  192. MenuEntries[0] = "Starting the game...";
  193. networkSession.StartGame();
  194. }
  195. }
  196. else if (networkSession.SessionState == NetworkSessionState.Playing)
  197. {
  198. MenuEntries[0] = "Game starting...";
  199. }
  200. // if the game is playing and the world is initialized, then start up
  201. if ((networkSession.SessionState == NetworkSessionState.Playing) &&
  202. (world != null) && world.Initialized)
  203. {
  204. GameplayScreen gameplayScreen =
  205. new GameplayScreen(networkSession, world);
  206. gameplayScreen.ScreenManager = this.ScreenManager;
  207. ScreenManager.AddScreen(gameplayScreen);
  208. }
  209. }
  210. base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  211. }
  212. /// <summary>
  213. /// Lets the game respond to player input. Unlike the Update method,
  214. /// this will only be called when the gameplay screen is active.
  215. /// </summary>
  216. public override void HandleInput(InputState input)
  217. {
  218. // safety-check the parameter
  219. if (input == null)
  220. {
  221. throw new ArgumentNullException("input");
  222. }
  223. if ((networkSession != null) && (networkSession.LocalGamers.Count > 0))
  224. {
  225. // update the ready state
  226. if (input.MarkReady)
  227. {
  228. networkSession.LocalGamers[0].IsReady =
  229. !networkSession.LocalGamers[0].IsReady;
  230. }
  231. // update the player data
  232. PlayerData playerData = networkSession.LocalGamers[0].Tag as PlayerData;
  233. if (playerData != null)
  234. {
  235. bool playerDataChanged = false;
  236. if (input.ShipColorChangeUp)
  237. {
  238. playerData.ShipColor = Ship.GetNextUniqueColorIndex(
  239. playerData.ShipColor, networkSession);
  240. playerDataChanged = true;
  241. }
  242. else if (input.ShipColorChangeDown)
  243. {
  244. playerData.ShipColor = Ship.GetPreviousUniqueColorIndex(
  245. playerData.ShipColor, networkSession);
  246. playerDataChanged = true;
  247. }
  248. if (input.ShipModelChangeUp)
  249. {
  250. playerData.ShipVariation =
  251. (byte)((playerData.ShipVariation + 1) % 4);
  252. playerDataChanged = true;
  253. }
  254. else if (input.ShipModelChangeDown)
  255. {
  256. if (playerData.ShipVariation == 0)
  257. {
  258. playerData.ShipVariation = 3;
  259. }
  260. else
  261. {
  262. playerData.ShipVariation--;
  263. }
  264. playerDataChanged = true;
  265. }
  266. // if the data changed, send an update to the others
  267. if (playerDataChanged)
  268. {
  269. packetWriter.Write((int)World.PacketTypes.PlayerData);
  270. playerData.Serialize(packetWriter);
  271. networkSession.LocalGamers[0].SendData(packetWriter,
  272. SendDataOptions.ReliableInOrder);
  273. }
  274. }
  275. }
  276. base.HandleInput(input);
  277. }
  278. /// <summary>
  279. /// Responds to user menu selections.
  280. /// </summary>
  281. protected override void OnSelectEntry(int entryIndex) { }
  282. /// <summary>
  283. /// Force the end of a network session so that a new one can be joined.
  284. /// </summary>
  285. public void EndSession()
  286. {
  287. if (networkSession != null)
  288. {
  289. networkSession.Dispose();
  290. networkSession = null;
  291. }
  292. }
  293. /// <summary>
  294. /// Exit this screen.
  295. /// </summary>
  296. public override void ExitScreen()
  297. {
  298. if (!IsExiting && (networkSession != null))
  299. {
  300. networkSession.GamerJoined -= gamerJoinedHandler;
  301. networkSession.GameStarted -= gameStartedHandler;
  302. networkSession.SessionEnded -= sessionEndedHandler;
  303. }
  304. base.ExitScreen();
  305. }
  306. /// <summary>
  307. /// Screen-specific update to gamer rich presence.
  308. /// </summary>
  309. public override void UpdatePresence()
  310. {
  311. if (!IsExiting && (networkSession != null))
  312. {
  313. foreach (LocalNetworkGamer localGamer in networkSession.LocalGamers)
  314. {
  315. SignedInGamer signedInGamer = localGamer.SignedInGamer;
  316. if (signedInGamer.IsSignedInToLive)
  317. {
  318. if (networkSession.IsHost)
  319. {
  320. signedInGamer.Presence.PresenceMode = GamerPresenceMode.WaitingForPlayers;
  321. }
  322. else
  323. {
  324. signedInGamer.Presence.PresenceMode = GamerPresenceMode.WaitingInLobby;
  325. }
  326. }
  327. }
  328. }
  329. }
  330. #endregion
  331. #region Drawing Methods
  332. /// <summary>
  333. /// Draw the lobby screen.
  334. /// </summary>
  335. /// <param name="gameTime"></param>
  336. public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
  337. {
  338. // draw in four columns
  339. Vector2[] columnPositions = new Vector2[4];
  340. columnPositions[0] = new Vector2(
  341. ScreenManager.GraphicsDevice.Viewport.Width * 0.2f,
  342. ScreenManager.GraphicsDevice.Viewport.Height * 0.70f);
  343. columnPositions[1] = new Vector2(
  344. ScreenManager.GraphicsDevice.Viewport.Width * 0.4f,
  345. ScreenManager.GraphicsDevice.Viewport.Height * 0.70f);
  346. columnPositions[2] = new Vector2(
  347. ScreenManager.GraphicsDevice.Viewport.Width * 0.6f,
  348. ScreenManager.GraphicsDevice.Viewport.Height * 0.70f);
  349. columnPositions[3] = new Vector2(
  350. ScreenManager.GraphicsDevice.Viewport.Width * 0.8f,
  351. ScreenManager.GraphicsDevice.Viewport.Height * 0.70f);
  352. ScreenManager.SpriteBatch.Begin();
  353. // draw all of the players data
  354. if (networkSession != null)
  355. {
  356. for (int i = 0; i < networkSession.AllGamers.Count; i++)
  357. {
  358. world.DrawPlayerData((float)gameTime.TotalGameTime.TotalSeconds,
  359. networkSession.AllGamers[i], columnPositions[i % 4],
  360. ScreenManager.SpriteBatch, true);
  361. columnPositions[i % 4].Y +=
  362. ScreenManager.GraphicsDevice.Viewport.Height * 0.03f;
  363. }
  364. }
  365. // draw the instructions
  366. ScreenManager.SpriteBatch.DrawString(ScreenManager.Font, instructions,
  367. new Vector2(ScreenManager.TitleSafeArea.X,
  368. ScreenManager.TitleSafeArea.Y + ScreenManager.TitleSafeArea.Height -
  369. ScreenManager.Font.LineSpacing), Color.White);
  370. ScreenManager.SpriteBatch.End();
  371. base.Draw(gameTime);
  372. }
  373. /// <summary>
  374. /// When the user cancels the main menu, ask if they want to exit the sample.
  375. /// </summary>
  376. protected override void OnCancel()
  377. {
  378. if (!IsExiting)
  379. {
  380. ExitScreen();
  381. }
  382. if (world != null)
  383. {
  384. world.Dispose();
  385. world = null;
  386. }
  387. if (networkSession != null)
  388. {
  389. networkSession.Dispose();
  390. networkSession = null;
  391. }
  392. }
  393. #endregion
  394. #region Networking Event Handlers
  395. /// <summary>
  396. /// Handle the end of the network session.
  397. /// </summary>
  398. void networkSession_SessionEnded(object sender, NetworkSessionEndedEventArgs e)
  399. {
  400. if (!IsExiting)
  401. {
  402. ExitScreen();
  403. }
  404. if (world != null)
  405. {
  406. world.Dispose();
  407. world = null;
  408. }
  409. if (networkSession != null)
  410. {
  411. networkSession.Dispose();
  412. networkSession = null;
  413. }
  414. }
  415. /// <summary>
  416. /// Handle the start of the game session.
  417. /// </summary>
  418. void networkSession_GameStarted(object sender, GameStartedEventArgs e)
  419. {
  420. // if we're the host, generate the data
  421. if ((networkSession != null) && networkSession.IsHost && (world != null))
  422. {
  423. world.GenerateWorld();
  424. }
  425. }
  426. /// <summary>
  427. /// Handle a new player joining the session.
  428. /// </summary>
  429. void networkSession_GamerJoined(object sender, GamerJoinedEventArgs e)
  430. {
  431. // make sure the data exists for the new gamer
  432. for (int i = 0; i < networkSession.AllGamers.Count; i++)
  433. {
  434. if (networkSession.AllGamers[i] == e.Gamer)
  435. {
  436. PlayerData playerData = new PlayerData();
  437. e.Gamer.Tag = playerData;
  438. playerData.ShipVariation = (byte)(i % 4);
  439. playerData.ShipColor = (byte)i;
  440. }
  441. }
  442. // send my own data to the new gamer
  443. if ((networkSession.LocalGamers.Count > 0) && !e.Gamer.IsLocal)
  444. {
  445. PlayerData playerData = networkSession.LocalGamers[0].Tag as PlayerData;
  446. if (playerData != null)
  447. {
  448. packetWriter.Write((int)World.PacketTypes.PlayerData);
  449. playerData.Serialize(packetWriter);
  450. networkSession.LocalGamers[0].SendData(packetWriter,
  451. SendDataOptions.ReliableInOrder, e.Gamer);
  452. }
  453. }
  454. }
  455. #endregion
  456. #region IDisposable Implementation
  457. /// <summary>
  458. /// Finalizes the LobbyScreen object, calls Dispose(false)
  459. /// </summary>
  460. ~LobbyScreen()
  461. {
  462. Dispose(false);
  463. }
  464. /// <summary>
  465. /// Disposes the LobbyScreen object.
  466. /// </summary>
  467. public void Dispose()
  468. {
  469. Dispose(true);
  470. GC.SuppressFinalize(this);
  471. }
  472. /// <summary>
  473. /// Disposes this object.
  474. /// </summary>
  475. /// <param name="disposing">
  476. /// True if this method was called as part of the Dispose method.
  477. /// </param>
  478. protected virtual void Dispose(bool disposing)
  479. {
  480. if (disposing)
  481. {
  482. lock (this)
  483. {
  484. if (world != null)
  485. {
  486. world.Dispose();
  487. world = null;
  488. }
  489. if (packetWriter != null)
  490. {
  491. packetWriter.Close();
  492. packetWriter = null;
  493. }
  494. }
  495. }
  496. }
  497. #endregion
  498. }
  499. }