LobbyScreen.cs 19 KB

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