PeerToPeerGame.cs 14 KB

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