2
0

PeerToPeerGame.cs 16 KB

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