Session.cs 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // Session.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 System.Collections.Generic;
  12. using System.Diagnostics;
  13. using System.IO;
  14. using System.Reflection;
  15. using System.Xml;
  16. using System.Xml.Serialization;
  17. using Microsoft.Xna.Framework;
  18. using Microsoft.Xna.Framework.Content;
  19. using Microsoft.Xna.Framework.GamerServices;
  20. using Microsoft.Xna.Framework.Graphics;
  21. using Microsoft.Xna.Framework.Storage;
  22. using RolePlayingGameData;
  23. #endregion
  24. namespace RolePlaying
  25. {
  26. class Session
  27. {
  28. #region Singleton
  29. /// <summary>
  30. /// The single Session instance that can be active at a time.
  31. /// </summary>
  32. private static Session singleton;
  33. #endregion
  34. #region Party
  35. /// <summary>
  36. /// The party that is playing the game right now.
  37. /// </summary>
  38. private Party party;
  39. /// <summary>
  40. /// The party that is playing the game right now.
  41. /// </summary>
  42. public static Party Party
  43. {
  44. get { return (singleton == null ? null : singleton.party); }
  45. }
  46. #endregion
  47. #region Map
  48. /// <summary>
  49. /// Change the current map, arriving at the given portal if any.
  50. /// </summary>
  51. /// <param name="contentName">The asset name of the new map.</param>
  52. /// <param name="originalPortal">The portal from the previous map.</param>
  53. public static void ChangeMap(string contentName, Portal originalPortal)
  54. {
  55. // make sure the content name is valid
  56. string mapContentName = contentName;
  57. if (!mapContentName.StartsWith(@"Maps\"))
  58. {
  59. mapContentName = Path.Combine(@"Maps", mapContentName);
  60. }
  61. // check for trivial movement - typically intra-map portals
  62. if ((TileEngine.Map != null) && (TileEngine.Map.AssetName == mapContentName))
  63. {
  64. TileEngine.SetMap(TileEngine.Map, originalPortal == null ? null :
  65. TileEngine.Map.FindPortal(originalPortal.DestinationMapPortalName));
  66. }
  67. // load the map
  68. ContentManager content = singleton.screenManager.Game.Content;
  69. Map map = content.Load<Map>(mapContentName).Clone() as Map;
  70. // modify the map based on the world changes (removed chests, etc.).
  71. singleton.ModifyMap(map);
  72. // start playing the music for the new map
  73. AudioManager.PlayMusic(map.MusicCueName);
  74. // set the new map into the tile engine
  75. TileEngine.SetMap(map, originalPortal == null ? null :
  76. map.FindPortal(originalPortal.DestinationMapPortalName));
  77. }
  78. /// <summary>
  79. /// Perform any actions associated withe the given tile.
  80. /// </summary>
  81. /// <param name="mapPosition">The tile to check.</param>
  82. /// <returns>True if anything was encountered, false otherwise.</returns>
  83. public static bool EncounterTile(Point mapPosition)
  84. {
  85. // look for fixed-combats from the quest
  86. if ((singleton.quest != null) &&
  87. ((singleton.quest.Stage == Quest.QuestStage.InProgress) ||
  88. (singleton.quest.Stage == Quest.QuestStage.RequirementsMet)))
  89. {
  90. MapEntry<FixedCombat> fixedCombatEntry =
  91. singleton.quest.FixedCombatEntries.Find(
  92. delegate(WorldEntry<FixedCombat> worldEntry)
  93. {
  94. return
  95. TileEngine.Map.AssetName.EndsWith(
  96. worldEntry.MapContentName) &&
  97. worldEntry.MapPosition == mapPosition;
  98. });
  99. if (fixedCombatEntry != null)
  100. {
  101. Session.EncounterFixedCombat(fixedCombatEntry);
  102. return true;
  103. }
  104. }
  105. // look for fixed-combats from the map
  106. MapEntry<FixedCombat> fixedCombatMapEntry =
  107. TileEngine.Map.FixedCombatEntries.Find(
  108. delegate(MapEntry<FixedCombat> mapEntry)
  109. {
  110. return mapEntry.MapPosition == mapPosition;
  111. });
  112. if (fixedCombatMapEntry != null)
  113. {
  114. Session.EncounterFixedCombat(fixedCombatMapEntry);
  115. return true;
  116. }
  117. // look for chests from the current quest
  118. if (singleton.quest != null)
  119. {
  120. MapEntry<Chest> chestEntry = singleton.quest.ChestEntries.Find(
  121. delegate(WorldEntry<Chest> worldEntry)
  122. {
  123. return
  124. TileEngine.Map.AssetName.EndsWith(
  125. worldEntry.MapContentName) &&
  126. worldEntry.MapPosition == mapPosition;
  127. });
  128. if (chestEntry != null)
  129. {
  130. Session.EncounterChest(chestEntry);
  131. return true;
  132. }
  133. }
  134. // look for chests from the map
  135. MapEntry<Chest> chestMapEntry =
  136. TileEngine.Map.ChestEntries.Find(delegate(MapEntry<Chest> mapEntry)
  137. {
  138. return mapEntry.MapPosition == mapPosition;
  139. });
  140. if (chestMapEntry != null)
  141. {
  142. Session.EncounterChest(chestMapEntry);
  143. return true;
  144. }
  145. // look for player NPCs from the map
  146. MapEntry<Player> playerNpcEntry =
  147. TileEngine.Map.PlayerNpcEntries.Find(delegate(MapEntry<Player> mapEntry)
  148. {
  149. return mapEntry.MapPosition == mapPosition;
  150. });
  151. if (playerNpcEntry != null)
  152. {
  153. Session.EncounterPlayerNpc(playerNpcEntry);
  154. return true;
  155. }
  156. // look for quest NPCs from the map
  157. MapEntry<QuestNpc> questNpcEntry =
  158. TileEngine.Map.QuestNpcEntries.Find(delegate(MapEntry<QuestNpc> mapEntry)
  159. {
  160. return mapEntry.MapPosition == mapPosition;
  161. });
  162. if (questNpcEntry != null)
  163. {
  164. Session.EncounterQuestNpc(questNpcEntry);
  165. return true;
  166. }
  167. // look for portals from the map
  168. MapEntry<Portal> portalEntry =
  169. TileEngine.Map.PortalEntries.Find(delegate(MapEntry<Portal> mapEntry)
  170. {
  171. return mapEntry.MapPosition == mapPosition;
  172. });
  173. if (portalEntry != null)
  174. {
  175. Session.EncounterPortal(portalEntry);
  176. return true;
  177. }
  178. // look for inns from the map
  179. MapEntry<Inn> innEntry =
  180. TileEngine.Map.InnEntries.Find(delegate(MapEntry<Inn> mapEntry)
  181. {
  182. return mapEntry.MapPosition == mapPosition;
  183. });
  184. if (innEntry != null)
  185. {
  186. Session.EncounterInn(innEntry);
  187. return true;
  188. }
  189. // look for stores from the map
  190. MapEntry<Store> storeEntry =
  191. TileEngine.Map.StoreEntries.Find(delegate(MapEntry<Store> mapEntry)
  192. {
  193. return mapEntry.MapPosition == mapPosition;
  194. });
  195. if (storeEntry != null)
  196. {
  197. Session.EncounterStore(storeEntry);
  198. return true;
  199. }
  200. // nothing encountered
  201. return false;
  202. }
  203. /// <summary>
  204. /// Performs the actions associated with encountering a FixedCombat entry.
  205. /// </summary>
  206. public static void EncounterFixedCombat(MapEntry<FixedCombat> fixedCombatEntry)
  207. {
  208. // check the parameter
  209. if ((fixedCombatEntry == null) || (fixedCombatEntry.Content == null))
  210. {
  211. throw new ArgumentNullException("fixedCombatEntry");
  212. }
  213. if (!CombatEngine.IsActive)
  214. {
  215. // start combat
  216. CombatEngine.StartNewCombat(fixedCombatEntry);
  217. }
  218. }
  219. /// <summary>
  220. /// Performs the actions associated with encountering a Chest entry.
  221. /// </summary>
  222. public static void EncounterChest(MapEntry<Chest> chestEntry)
  223. {
  224. // check the parameter
  225. if ((chestEntry == null) || (chestEntry.Content == null))
  226. {
  227. throw new ArgumentNullException("chestEntry");
  228. }
  229. // add the chest screen
  230. singleton.screenManager.AddScreen(new ChestScreen(chestEntry));
  231. }
  232. /// <summary>
  233. /// Performs the actions associated with encountering a player-NPC entry.
  234. /// </summary>
  235. public static void EncounterPlayerNpc(MapEntry<Player> playerEntry)
  236. {
  237. // check the parameter
  238. if ((playerEntry == null) || (playerEntry.Content == null))
  239. {
  240. throw new ArgumentNullException("playerEntry");
  241. }
  242. // add the player-NPC screen
  243. singleton.screenManager.AddScreen(new PlayerNpcScreen(playerEntry));
  244. }
  245. /// <summary>
  246. /// Performs the actions associated with encountering a QuestNpc entry.
  247. /// </summary>
  248. public static void EncounterQuestNpc(MapEntry<QuestNpc> questNpcEntry)
  249. {
  250. // check the parameter
  251. if ((questNpcEntry == null) || (questNpcEntry.Content == null))
  252. {
  253. throw new ArgumentNullException("questNpcEntry");
  254. }
  255. // add the quest-NPC screen
  256. singleton.screenManager.AddScreen(new QuestNpcScreen(questNpcEntry));
  257. }
  258. /// <summary>
  259. /// Performs the actions associated with encountering an Inn entry.
  260. /// </summary>
  261. public static void EncounterInn(MapEntry<Inn> innEntry)
  262. {
  263. // check the parameter
  264. if ((innEntry == null) || (innEntry.Content == null))
  265. {
  266. throw new ArgumentNullException("innEntry");
  267. }
  268. // add the inn screen
  269. singleton.screenManager.AddScreen(new InnScreen(innEntry.Content));
  270. }
  271. /// <summary>
  272. /// Performs the actions associated with encountering a Store entry.
  273. /// </summary>
  274. public static void EncounterStore(MapEntry<Store> storeEntry)
  275. {
  276. // check the parameter
  277. if ((storeEntry == null) || (storeEntry.Content == null))
  278. {
  279. throw new ArgumentNullException("storeEntry");
  280. }
  281. // add the store screen
  282. singleton.screenManager.AddScreen(new StoreScreen(storeEntry.Content));
  283. }
  284. /// <summary>
  285. /// Performs the actions associated with encountering a Portal entry.
  286. /// </summary>
  287. public static void EncounterPortal(MapEntry<Portal> portalEntry)
  288. {
  289. // check the parameter
  290. if ((portalEntry == null) || (portalEntry.Content == null))
  291. {
  292. throw new ArgumentNullException("portalEntry");
  293. }
  294. // change to the new map
  295. ChangeMap(portalEntry.Content.DestinationMapContentName,
  296. portalEntry.Content);
  297. }
  298. /// <summary>
  299. /// Check if a random combat should start. If so, start combat immediately.
  300. /// </summary>
  301. /// <returns>True if combat was started, false otherwise.</returns>
  302. public static bool CheckForRandomCombat(RandomCombat randomCombat)
  303. {
  304. // check the parameter
  305. if ((randomCombat == null) || (randomCombat.CombatProbability <= 0))
  306. {
  307. return false;
  308. }
  309. // check to see if combat has already started
  310. if (CombatEngine.IsActive)
  311. {
  312. return false;
  313. }
  314. // check to see if the random combat starts
  315. int randomCombatCheck = random.Next(100);
  316. if (randomCombatCheck < randomCombat.CombatProbability)
  317. {
  318. // start combat immediately
  319. CombatEngine.StartNewCombat(randomCombat);
  320. return true;
  321. }
  322. // combat not started
  323. return false;
  324. }
  325. #endregion
  326. #region Quests
  327. /// <summary>
  328. /// The main quest line for this session.
  329. /// </summary>
  330. private QuestLine questLine;
  331. /// <summary>
  332. /// The main quest line for this session.
  333. /// </summary>
  334. public static QuestLine QuestLine
  335. {
  336. get { return (singleton == null ? null : singleton.questLine); }
  337. }
  338. /// <summary>
  339. /// If true, the main quest line for this session is complete.
  340. /// </summary>
  341. public static bool IsQuestLineComplete
  342. {
  343. get
  344. {
  345. if ((singleton == null) || (singleton.questLine == null) ||
  346. (singleton.questLine.QuestContentNames == null))
  347. {
  348. return false;
  349. }
  350. return singleton.currentQuestIndex >=
  351. singleton.questLine.QuestContentNames.Count;
  352. }
  353. }
  354. /// <summary>
  355. /// The current quest in this session.
  356. /// </summary>
  357. private Quest quest;
  358. /// <summary>
  359. /// The current quest in this session.
  360. /// </summary>
  361. public static Quest Quest
  362. {
  363. get { return (singleton == null ? null : singleton.quest); }
  364. }
  365. /// <summary>
  366. /// The index of the current quest into the quest line.
  367. /// </summary>
  368. private int currentQuestIndex = 0;
  369. /// <summary>
  370. /// The index of the current quest into the quest line.
  371. /// </summary>
  372. public static int CurrentQuestIndex
  373. {
  374. get { return (singleton == null ? -1 : singleton.currentQuestIndex); }
  375. }
  376. /// <summary>
  377. /// Update the current quest and quest line for this session.
  378. /// </summary>
  379. public void UpdateQuest()
  380. {
  381. // check the singleton's state to see if we should care about quests
  382. if ((party == null) || (questLine == null))
  383. {
  384. return;
  385. }
  386. // if we don't have a quest, then take the next one from teh list
  387. if ((quest == null) && (questLine.Quests.Count > 0) &&
  388. !Session.IsQuestLineComplete)
  389. {
  390. quest = questLine.Quests[currentQuestIndex];
  391. quest.Stage = Quest.QuestStage.NotStarted;
  392. // clear the monster-kill record
  393. party.MonsterKills.Clear();
  394. // clear the modified-quest lists
  395. modifiedQuestChests.Clear();
  396. removedQuestChests.Clear();
  397. removedQuestFixedCombats.Clear();
  398. }
  399. // handle quest-stage transitions
  400. if ((quest != null) && !Session.IsQuestLineComplete)
  401. {
  402. switch (quest.Stage)
  403. {
  404. case Quest.QuestStage.NotStarted:
  405. // start the new quest
  406. quest.Stage = Quest.QuestStage.InProgress;
  407. if (!quest.AreRequirementsMet)
  408. {
  409. // show the announcement of the quest and the requirements
  410. ScreenManager.AddScreen(new QuestLogScreen(quest));
  411. }
  412. break;
  413. case Quest.QuestStage.InProgress:
  414. // update monster requirements
  415. foreach (QuestRequirement<Monster> monsterRequirement in
  416. quest.MonsterRequirements)
  417. {
  418. monsterRequirement.CompletedCount = 0;
  419. Monster monster = monsterRequirement.Content;
  420. if (party.MonsterKills.ContainsKey(monster.AssetName))
  421. {
  422. monsterRequirement.CompletedCount =
  423. party.MonsterKills[monster.AssetName];
  424. }
  425. }
  426. // update gear requirements
  427. foreach (QuestRequirement<Gear> gearRequirement in
  428. quest.GearRequirements)
  429. {
  430. gearRequirement.CompletedCount = 0;
  431. foreach (ContentEntry<Gear> entry in party.Inventory)
  432. {
  433. if (entry.Content == gearRequirement.Content)
  434. {
  435. gearRequirement.CompletedCount += entry.Count;
  436. }
  437. }
  438. }
  439. // check to see if the requirements have been met
  440. if (quest.AreRequirementsMet)
  441. {
  442. // immediately remove the gear
  443. foreach (QuestRequirement<Gear> gearRequirement in
  444. quest.GearRequirements)
  445. {
  446. Gear gear = gearRequirement.Content;
  447. party.RemoveFromInventory(gear,
  448. gearRequirement.Count);
  449. }
  450. // check to see if there is a destination
  451. if (String.IsNullOrEmpty(
  452. quest.DestinationMapContentName))
  453. {
  454. // complete the quest
  455. quest.Stage = Quest.QuestStage.Completed;
  456. // show the completion dialogue
  457. if (!String.IsNullOrEmpty(quest.CompletionMessage))
  458. {
  459. DialogueScreen dialogueScreen = new DialogueScreen();
  460. dialogueScreen.TitleText = "Quest Complete";
  461. dialogueScreen.BackText = String.Empty;
  462. dialogueScreen.DialogueText =
  463. quest.CompletionMessage;
  464. ScreenManager.AddScreen(dialogueScreen);
  465. }
  466. }
  467. else
  468. {
  469. quest.Stage = Quest.QuestStage.RequirementsMet;
  470. // remind the player about the destination
  471. screenManager.AddScreen(new QuestLogScreen(quest));
  472. }
  473. }
  474. break;
  475. case Quest.QuestStage.RequirementsMet:
  476. break;
  477. case Quest.QuestStage.Completed:
  478. // show the quest rewards screen
  479. RewardsScreen rewardsScreen =
  480. new RewardsScreen(RewardsScreen.RewardScreenMode.Quest,
  481. Quest.ExperienceReward, Quest.GoldReward, Quest.GearRewards);
  482. screenManager.AddScreen(rewardsScreen);
  483. // advance to the next quest
  484. currentQuestIndex++;
  485. quest = null;
  486. break;
  487. }
  488. }
  489. }
  490. #endregion
  491. #region Modified/Removed Content
  492. /// <summary>
  493. /// The chests removed from the map asset by player actions.
  494. /// </summary>
  495. private List<WorldEntry<Chest>> removedMapChests =
  496. new List<WorldEntry<Chest>>();
  497. /// <summary>
  498. /// The chests removed from the current quest asset by player actions.
  499. /// </summary>
  500. private List<WorldEntry<Chest>> removedQuestChests =
  501. new List<WorldEntry<Chest>>();
  502. /// <summary>
  503. /// Remove the given chest entry from the current map or quest.
  504. /// </summary>
  505. public static void RemoveChest(MapEntry<Chest> mapEntry)
  506. {
  507. // check the parameter
  508. if (mapEntry == null)
  509. {
  510. return;
  511. }
  512. // check the map for the item first
  513. if (TileEngine.Map != null)
  514. {
  515. int removedEntries = TileEngine.Map.ChestEntries.RemoveAll(
  516. delegate(MapEntry<Chest> entry)
  517. {
  518. return ((entry.ContentName == mapEntry.ContentName) &&
  519. (entry.MapPosition == mapEntry.MapPosition));
  520. });
  521. if (removedEntries > 0)
  522. {
  523. WorldEntry<Chest> worldEntry = new WorldEntry<Chest>();
  524. worldEntry.Content = mapEntry.Content;
  525. worldEntry.ContentName = mapEntry.ContentName;
  526. worldEntry.Count = mapEntry.Count;
  527. worldEntry.Direction = mapEntry.Direction;
  528. worldEntry.MapContentName = TileEngine.Map.AssetName;
  529. worldEntry.MapPosition = mapEntry.MapPosition;
  530. singleton.removedMapChests.Add(worldEntry);
  531. return;
  532. }
  533. }
  534. // look for the map entry within the quest
  535. if (singleton.quest != null)
  536. {
  537. int removedEntries = singleton.quest.ChestEntries.RemoveAll(
  538. delegate(WorldEntry<Chest> entry)
  539. {
  540. return ((entry.ContentName == mapEntry.ContentName) &&
  541. (entry.MapPosition == mapEntry.MapPosition) &&
  542. TileEngine.Map.AssetName.EndsWith(entry.MapContentName));
  543. });
  544. if (removedEntries > 0)
  545. {
  546. WorldEntry<Chest> worldEntry = new WorldEntry<Chest>();
  547. worldEntry.Content = mapEntry.Content;
  548. worldEntry.ContentName = mapEntry.ContentName;
  549. worldEntry.Count = mapEntry.Count;
  550. worldEntry.Direction = mapEntry.Direction;
  551. worldEntry.MapContentName = TileEngine.Map.AssetName;
  552. worldEntry.MapPosition = mapEntry.MapPosition;
  553. singleton.removedQuestChests.Add(worldEntry);
  554. return;
  555. }
  556. }
  557. }
  558. /// <summary>
  559. /// The fixed-combats removed from the map asset by player actions.
  560. /// </summary>
  561. private List<WorldEntry<FixedCombat>> removedMapFixedCombats =
  562. new List<WorldEntry<FixedCombat>>();
  563. /// <summary>
  564. /// The fixed-combats removed from the current quest asset by player actions.
  565. /// </summary>
  566. private List<WorldEntry<FixedCombat>> removedQuestFixedCombats =
  567. new List<WorldEntry<FixedCombat>>();
  568. /// <summary>
  569. /// Remove the given fixed-combat entry from the current map or quest.
  570. /// </summary>
  571. public static void RemoveFixedCombat(MapEntry<FixedCombat> mapEntry)
  572. {
  573. // check the parameter
  574. if (mapEntry == null)
  575. {
  576. return;
  577. }
  578. // check the map for the item first
  579. if (TileEngine.Map != null)
  580. {
  581. int removedEntries = TileEngine.Map.FixedCombatEntries.RemoveAll(
  582. delegate(MapEntry<FixedCombat> entry)
  583. {
  584. return ((entry.ContentName == mapEntry.ContentName) &&
  585. (entry.MapPosition == mapEntry.MapPosition));
  586. });
  587. if (removedEntries > 0)
  588. {
  589. WorldEntry<FixedCombat> worldEntry = new WorldEntry<FixedCombat>();
  590. worldEntry.Content = mapEntry.Content;
  591. worldEntry.ContentName = mapEntry.ContentName;
  592. worldEntry.Count = mapEntry.Count;
  593. worldEntry.Direction = mapEntry.Direction;
  594. worldEntry.MapContentName = TileEngine.Map.AssetName;
  595. worldEntry.MapPosition = mapEntry.MapPosition;
  596. singleton.removedMapFixedCombats.Add(worldEntry);
  597. return;
  598. }
  599. }
  600. // look for the map entry within the quest
  601. if (singleton.quest != null)
  602. {
  603. int removedEntries = singleton.quest.FixedCombatEntries.RemoveAll(
  604. delegate(WorldEntry<FixedCombat> entry)
  605. {
  606. return ((entry.ContentName == mapEntry.ContentName) &&
  607. (entry.MapPosition == mapEntry.MapPosition) &&
  608. TileEngine.Map.AssetName.EndsWith(entry.MapContentName));
  609. });
  610. if (removedEntries > 0)
  611. {
  612. WorldEntry<FixedCombat> worldEntry = new WorldEntry<FixedCombat>();
  613. worldEntry.Content = mapEntry.Content;
  614. worldEntry.ContentName = mapEntry.ContentName;
  615. worldEntry.Count = mapEntry.Count;
  616. worldEntry.Direction = mapEntry.Direction;
  617. worldEntry.MapContentName = TileEngine.Map.AssetName;
  618. worldEntry.MapPosition = mapEntry.MapPosition;
  619. singleton.removedQuestFixedCombats.Add(worldEntry);
  620. return;
  621. }
  622. }
  623. }
  624. /// <summary>
  625. /// The player NPCs removed from the map asset by player actions.
  626. /// </summary>
  627. private List<WorldEntry<Player>> removedMapPlayerNpcs =
  628. new List<WorldEntry<Player>>();
  629. /// <summary>
  630. /// Remove the given player NPC entry from the current map or quest.
  631. /// </summary>
  632. public static void RemovePlayerNpc(MapEntry<Player> mapEntry)
  633. {
  634. // check the parameter
  635. if (mapEntry == null)
  636. {
  637. return;
  638. }
  639. // check the map for the item
  640. if (TileEngine.Map != null)
  641. {
  642. int removedEntries = TileEngine.Map.PlayerNpcEntries.RemoveAll(
  643. delegate(MapEntry<Player> entry)
  644. {
  645. return ((entry.ContentName == mapEntry.ContentName) &&
  646. (entry.MapPosition == mapEntry.MapPosition));
  647. });
  648. if (removedEntries > 0)
  649. {
  650. WorldEntry<Player> worldEntry = new WorldEntry<Player>();
  651. worldEntry.Content = mapEntry.Content;
  652. worldEntry.ContentName = mapEntry.ContentName;
  653. worldEntry.Count = mapEntry.Count;
  654. worldEntry.Direction = mapEntry.Direction;
  655. worldEntry.MapContentName = TileEngine.Map.AssetName;
  656. worldEntry.MapPosition = mapEntry.MapPosition;
  657. singleton.removedMapPlayerNpcs.Add(worldEntry);
  658. return;
  659. }
  660. }
  661. // quests don't have a list of player NPCs
  662. }
  663. /// <summary>
  664. /// The chests that have been modified, but not emptied, by player action.
  665. /// </summary>
  666. private List<ModifiedChestEntry> modifiedMapChests =
  667. new List<ModifiedChestEntry>();
  668. /// <summary>
  669. /// The chests belonging to the current quest that have been modified,
  670. /// but not emptied, by player action.
  671. /// </summary>
  672. private List<ModifiedChestEntry> modifiedQuestChests =
  673. new List<ModifiedChestEntry>();
  674. /// <summary>
  675. /// Stores the entry for a chest on the current map or quest that has been
  676. /// modified but not emptied.
  677. /// </summary>
  678. public static void StoreModifiedChest(MapEntry<Chest> mapEntry)
  679. {
  680. // check the parameter
  681. if ((mapEntry == null) || (mapEntry.Content == null))
  682. {
  683. throw new ArgumentNullException("mapEntry");
  684. }
  685. Predicate<ModifiedChestEntry> checkModifiedChests =
  686. delegate(ModifiedChestEntry entry)
  687. {
  688. return
  689. (TileEngine.Map.AssetName.EndsWith(
  690. entry.WorldEntry.MapContentName) &&
  691. (entry.WorldEntry.ContentName == mapEntry.ContentName) &&
  692. (entry.WorldEntry.MapPosition == mapEntry.MapPosition));
  693. };
  694. // check the map for the item first
  695. if ((TileEngine.Map != null) && TileEngine.Map.ChestEntries.Exists(
  696. delegate(MapEntry<Chest> entry)
  697. {
  698. return ((entry.ContentName == mapEntry.ContentName) &&
  699. (entry.MapPosition == mapEntry.MapPosition));
  700. }))
  701. {
  702. singleton.modifiedMapChests.RemoveAll(checkModifiedChests);
  703. ModifiedChestEntry modifiedChestEntry = new ModifiedChestEntry();
  704. modifiedChestEntry.WorldEntry.Content = mapEntry.Content;
  705. modifiedChestEntry.WorldEntry.ContentName = mapEntry.ContentName;
  706. modifiedChestEntry.WorldEntry.Count = mapEntry.Count;
  707. modifiedChestEntry.WorldEntry.Direction = mapEntry.Direction;
  708. modifiedChestEntry.WorldEntry.MapContentName =
  709. TileEngine.Map.AssetName;
  710. modifiedChestEntry.WorldEntry.MapPosition = mapEntry.MapPosition;
  711. Chest chest = mapEntry.Content;
  712. modifiedChestEntry.ChestEntries.AddRange(chest.Entries);
  713. modifiedChestEntry.Gold = chest.Gold;
  714. singleton.modifiedMapChests.Add(modifiedChestEntry);
  715. return;
  716. }
  717. // look for the map entry within the quest
  718. if ((singleton.quest != null) && singleton.quest.ChestEntries.Exists(
  719. delegate(WorldEntry<Chest> entry)
  720. {
  721. return ((entry.ContentName == mapEntry.ContentName) &&
  722. (entry.MapPosition == mapEntry.MapPosition) &&
  723. TileEngine.Map.AssetName.EndsWith(entry.MapContentName));
  724. }))
  725. {
  726. singleton.modifiedQuestChests.RemoveAll(checkModifiedChests);
  727. ModifiedChestEntry modifiedChestEntry = new ModifiedChestEntry();
  728. modifiedChestEntry.WorldEntry.Content = mapEntry.Content;
  729. modifiedChestEntry.WorldEntry.ContentName = mapEntry.ContentName;
  730. modifiedChestEntry.WorldEntry.Count = mapEntry.Count;
  731. modifiedChestEntry.WorldEntry.Direction = mapEntry.Direction;
  732. modifiedChestEntry.WorldEntry.MapContentName = TileEngine.Map.AssetName;
  733. modifiedChestEntry.WorldEntry.MapPosition = mapEntry.MapPosition;
  734. Chest chest = mapEntry.Content;
  735. modifiedChestEntry.ChestEntries.AddRange(chest.Entries);
  736. modifiedChestEntry.Gold = chest.Gold;
  737. singleton.modifiedQuestChests.Add(modifiedChestEntry);
  738. return;
  739. }
  740. }
  741. /// <summary>
  742. /// Remove the specified content from the map, typically from an earlier session.
  743. /// </summary>
  744. private void ModifyMap(Map map)
  745. {
  746. // check the parameter
  747. if (map == null)
  748. {
  749. throw new ArgumentNullException("map");
  750. }
  751. // remove all chests that were emptied already
  752. if ((removedMapChests != null) && (removedMapChests.Count > 0))
  753. {
  754. // check each removed-content entry
  755. map.ChestEntries.RemoveAll(delegate(MapEntry<Chest> mapEntry)
  756. {
  757. return (removedMapChests.Exists(
  758. delegate(WorldEntry<Chest> removedEntry)
  759. {
  760. return
  761. (map.AssetName.EndsWith(removedEntry.MapContentName) &&
  762. (removedEntry.ContentName == mapEntry.ContentName) &&
  763. (removedEntry.MapPosition == mapEntry.MapPosition));
  764. }));
  765. });
  766. }
  767. // remove all fixed-combats that were defeated already
  768. if ((removedMapFixedCombats != null) && (removedMapFixedCombats.Count > 0))
  769. {
  770. // check each removed-content entry
  771. map.FixedCombatEntries.RemoveAll(delegate(MapEntry<FixedCombat> mapEntry)
  772. {
  773. return (removedMapFixedCombats.Exists(
  774. delegate(WorldEntry<FixedCombat> removedEntry)
  775. {
  776. return
  777. (map.AssetName.EndsWith(removedEntry.MapContentName) &&
  778. (removedEntry.ContentName == mapEntry.ContentName) &&
  779. (removedEntry.MapPosition == mapEntry.MapPosition));
  780. }));
  781. });
  782. }
  783. // remove the player NPCs that have already joined the party
  784. if ((removedMapPlayerNpcs != null) && (removedMapPlayerNpcs.Count > 0))
  785. {
  786. // check each removed-content entry
  787. map.PlayerNpcEntries.RemoveAll(delegate(MapEntry<Player> mapEntry)
  788. {
  789. return (removedMapPlayerNpcs.Exists(
  790. delegate(WorldEntry<Player> removedEntry)
  791. {
  792. return
  793. (map.AssetName.EndsWith(removedEntry.MapContentName) &&
  794. (removedEntry.ContentName == mapEntry.ContentName) &&
  795. (removedEntry.MapPosition == mapEntry.MapPosition));
  796. }));
  797. });
  798. }
  799. // replace the chest entries of modified chests - they are already clones
  800. if ((modifiedMapChests != null) && (modifiedMapChests.Count > 0))
  801. {
  802. foreach (MapEntry<Chest> entry in map.ChestEntries)
  803. {
  804. ModifiedChestEntry modifiedEntry = modifiedMapChests.Find(
  805. delegate(ModifiedChestEntry modifiedTestEntry)
  806. {
  807. return
  808. (map.AssetName.EndsWith(
  809. modifiedTestEntry.WorldEntry.MapContentName) &&
  810. (modifiedTestEntry.WorldEntry.ContentName ==
  811. entry.ContentName) &&
  812. (modifiedTestEntry.WorldEntry.MapPosition ==
  813. entry.MapPosition));
  814. });
  815. // if the chest has been modified, apply the changes
  816. if (modifiedEntry != null)
  817. {
  818. ModifyChest(entry.Content, modifiedEntry);
  819. }
  820. }
  821. }
  822. }
  823. /// <summary>
  824. /// Remove the specified content from the map, typically from an earlier session.
  825. /// </summary>
  826. private void ModifyQuest(Quest quest)
  827. {
  828. // check the parameter
  829. if (quest == null)
  830. {
  831. throw new ArgumentNullException("quest");
  832. }
  833. // remove all chests that were emptied arleady
  834. if ((removedQuestChests != null) && (removedQuestChests.Count > 0))
  835. {
  836. // check each removed-content entry
  837. quest.ChestEntries.RemoveAll(
  838. delegate(WorldEntry<Chest> worldEntry)
  839. {
  840. return (removedQuestChests.Exists(
  841. delegate(WorldEntry<Chest> removedEntry)
  842. {
  843. return
  844. (removedEntry.MapContentName.EndsWith(
  845. worldEntry.MapContentName) &&
  846. (removedEntry.ContentName ==
  847. worldEntry.ContentName) &&
  848. (removedEntry.MapPosition ==
  849. worldEntry.MapPosition));
  850. }));
  851. });
  852. }
  853. // remove all of the fixed-combats that have already been defeated
  854. if ((removedQuestFixedCombats != null) &&
  855. (removedQuestFixedCombats.Count > 0))
  856. {
  857. // check each removed-content entry
  858. quest.FixedCombatEntries.RemoveAll(
  859. delegate(WorldEntry<FixedCombat> worldEntry)
  860. {
  861. return (removedQuestFixedCombats.Exists(
  862. delegate(WorldEntry<FixedCombat> removedEntry)
  863. {
  864. return
  865. (removedEntry.MapContentName.EndsWith(
  866. worldEntry.MapContentName) &&
  867. (removedEntry.ContentName ==
  868. worldEntry.ContentName) &&
  869. (removedEntry.MapPosition ==
  870. worldEntry.MapPosition));
  871. }));
  872. });
  873. }
  874. // replace the chest entries of modified chests - they are already clones
  875. if ((modifiedQuestChests != null) && (modifiedQuestChests.Count > 0))
  876. {
  877. foreach (WorldEntry<Chest> entry in quest.ChestEntries)
  878. {
  879. ModifiedChestEntry modifiedEntry = modifiedQuestChests.Find(
  880. delegate(ModifiedChestEntry modifiedTestEntry)
  881. {
  882. return
  883. ((modifiedTestEntry.WorldEntry.MapContentName ==
  884. entry.MapContentName) &&
  885. (modifiedTestEntry.WorldEntry.ContentName ==
  886. entry.ContentName) &&
  887. (modifiedTestEntry.WorldEntry.MapPosition ==
  888. entry.MapPosition));
  889. });
  890. // if the chest has been modified, apply the changes
  891. if (modifiedEntry != null)
  892. {
  893. ModifyChest(entry.Content, modifiedEntry);
  894. }
  895. }
  896. }
  897. }
  898. /// <summary>
  899. /// Modify a Chest object based on the data in a ModifiedChestEntry object.
  900. /// </summary>
  901. private void ModifyChest(Chest chest, ModifiedChestEntry modifiedChestEntry)
  902. {
  903. // check the parameters
  904. if ((chest == null) || (modifiedChestEntry == null))
  905. {
  906. return;
  907. }
  908. // set the new gold amount
  909. chest.Gold = modifiedChestEntry.Gold;
  910. // remove all contents not found in the modified version
  911. chest.Entries.RemoveAll(delegate(ContentEntry<Gear> contentEntry)
  912. {
  913. return !modifiedChestEntry.ChestEntries.Exists(
  914. delegate(ContentEntry<Gear> modifiedTestEntry)
  915. {
  916. return (contentEntry.ContentName ==
  917. modifiedTestEntry.ContentName);
  918. });
  919. });
  920. // set the new counts on the remaining content items
  921. foreach (ContentEntry<Gear> contentEntry in chest.Entries)
  922. {
  923. ContentEntry<Gear> modifiedGearEntry =
  924. modifiedChestEntry.ChestEntries.Find(
  925. delegate(ContentEntry<Gear> modifiedTestEntry)
  926. {
  927. return (contentEntry.ContentName ==
  928. modifiedTestEntry.ContentName);
  929. });
  930. if (modifiedGearEntry != null)
  931. {
  932. contentEntry.Count = modifiedGearEntry.Count;
  933. }
  934. }
  935. }
  936. #endregion
  937. #region User Interface Data
  938. /// <summary>
  939. /// The ScreenManager used to manage all UI in the game.
  940. /// </summary>
  941. private ScreenManager screenManager;
  942. /// <summary>
  943. /// The ScreenManager used to manage all UI in the game.
  944. /// </summary>
  945. public static ScreenManager ScreenManager
  946. {
  947. get { return (singleton == null ? null : singleton.screenManager); }
  948. }
  949. /// <summary>
  950. /// The GameplayScreen object that created this session.
  951. /// </summary>
  952. private GameplayScreen gameplayScreen;
  953. /// <summary>
  954. /// The heads-up-display menu shown on the map and combat screens.
  955. /// </summary>
  956. private Hud hud;
  957. /// <summary>
  958. /// The heads-up-display menu shown on the map and combat screens.
  959. /// </summary>
  960. public static Hud Hud
  961. {
  962. get { return (singleton == null ? null : singleton.hud); }
  963. }
  964. #endregion
  965. #region State Data
  966. /// <summary>
  967. /// Returns true if there is an active session.
  968. /// </summary>
  969. public static bool IsActive
  970. {
  971. get { return singleton != null; }
  972. }
  973. #endregion
  974. #region Initialization
  975. /// <summary>
  976. /// Private constructor of a Session object.
  977. /// </summary>
  978. /// <remarks>
  979. /// The lack of public constructors forces the singleton model.
  980. /// </remarks>
  981. private Session(ScreenManager screenManager, GameplayScreen gameplayScreen)
  982. {
  983. // check the parameter
  984. if (screenManager == null)
  985. {
  986. throw new ArgumentNullException("screenManager");
  987. }
  988. if (gameplayScreen == null)
  989. {
  990. throw new ArgumentNullException("gameplayScreen");
  991. }
  992. // assign the parameter
  993. this.screenManager = screenManager;
  994. this.gameplayScreen = gameplayScreen;
  995. // create the HUD interface
  996. this.hud = new Hud(screenManager);
  997. this.hud.LoadContent();
  998. }
  999. #endregion
  1000. #region Updating
  1001. /// <summary>
  1002. /// Update the session for this frame.
  1003. /// </summary>
  1004. /// <remarks>This should only be called if there are no menus in use.</remarks>
  1005. public static void Update(GameTime gameTime)
  1006. {
  1007. // check the singleton
  1008. if (singleton == null)
  1009. {
  1010. return;
  1011. }
  1012. if (CombatEngine.IsActive)
  1013. {
  1014. CombatEngine.Update(gameTime);
  1015. }
  1016. else
  1017. {
  1018. singleton.UpdateQuest();
  1019. TileEngine.Update(gameTime);
  1020. }
  1021. }
  1022. #endregion
  1023. #region Drawing
  1024. /// <summary>
  1025. /// Draws the session environment to the screen
  1026. /// </summary>
  1027. public static void Draw(GameTime gameTime)
  1028. {
  1029. SpriteBatch spriteBatch = singleton.screenManager.SpriteBatch;
  1030. if (CombatEngine.IsActive)
  1031. {
  1032. // draw the combat background
  1033. if (TileEngine.Map.CombatTexture != null)
  1034. {
  1035. spriteBatch.Begin();
  1036. spriteBatch.Draw(TileEngine.Map.CombatTexture, Vector2.Zero,
  1037. Color.White);
  1038. spriteBatch.End();
  1039. }
  1040. // draw the combat itself
  1041. spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
  1042. CombatEngine.Draw(gameTime);
  1043. spriteBatch.End();
  1044. }
  1045. else
  1046. {
  1047. singleton.DrawNonCombat(gameTime);
  1048. }
  1049. singleton.hud.Draw();
  1050. }
  1051. /// <summary>
  1052. /// Draws everything related to the non-combat part of the screen
  1053. /// </summary>
  1054. /// <param name="gameTime">Provides a snapshot of timing values</param>
  1055. private void DrawNonCombat(GameTime gameTime)
  1056. {
  1057. SpriteBatch spriteBatch = screenManager.SpriteBatch;
  1058. // draw the background
  1059. spriteBatch.Begin();
  1060. if (TileEngine.Map.Texture != null)
  1061. {
  1062. // draw the ground layer
  1063. TileEngine.DrawLayers(spriteBatch, true, true, false);
  1064. // draw the character shadows
  1065. DrawShadows(spriteBatch);
  1066. }
  1067. spriteBatch.End();
  1068. // Sort the object layer and player according to depth
  1069. spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
  1070. float elapsedSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
  1071. // draw the party leader
  1072. {
  1073. Player player = party.Players[0];
  1074. Vector2 position = TileEngine.PartyLeaderPosition.ScreenPosition;
  1075. player.Direction = TileEngine.PartyLeaderPosition.Direction;
  1076. player.ResetAnimation(TileEngine.PartyLeaderPosition.IsMoving);
  1077. switch (player.State)
  1078. {
  1079. case Character.CharacterState.Idle:
  1080. if (player.MapSprite != null)
  1081. {
  1082. player.MapSprite.UpdateAnimation(elapsedSeconds);
  1083. player.MapSprite.Draw(spriteBatch, position,
  1084. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1085. }
  1086. break;
  1087. case Character.CharacterState.Walking:
  1088. if (player.WalkingSprite != null)
  1089. {
  1090. player.WalkingSprite.UpdateAnimation(elapsedSeconds);
  1091. player.WalkingSprite.Draw(spriteBatch, position,
  1092. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1093. }
  1094. else if (player.MapSprite != null)
  1095. {
  1096. player.MapSprite.UpdateAnimation(elapsedSeconds);
  1097. player.MapSprite.Draw(spriteBatch, position,
  1098. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1099. }
  1100. break;
  1101. }
  1102. }
  1103. // draw the player NPCs
  1104. foreach (MapEntry<Player> playerEntry in TileEngine.Map.PlayerNpcEntries)
  1105. {
  1106. if (playerEntry.Content == null)
  1107. {
  1108. continue;
  1109. }
  1110. Vector2 position =
  1111. TileEngine.GetScreenPosition(playerEntry.MapPosition);
  1112. playerEntry.Content.ResetAnimation(false);
  1113. switch (playerEntry.Content.State)
  1114. {
  1115. case Character.CharacterState.Idle:
  1116. if (playerEntry.Content.MapSprite != null)
  1117. {
  1118. playerEntry.Content.MapSprite.UpdateAnimation(
  1119. elapsedSeconds);
  1120. playerEntry.Content.MapSprite.Draw(spriteBatch, position,
  1121. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1122. }
  1123. break;
  1124. case Character.CharacterState.Walking:
  1125. if (playerEntry.Content.WalkingSprite != null)
  1126. {
  1127. playerEntry.Content.WalkingSprite.UpdateAnimation(
  1128. elapsedSeconds);
  1129. playerEntry.Content.WalkingSprite.Draw(spriteBatch, position,
  1130. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1131. }
  1132. else if (playerEntry.Content.MapSprite != null)
  1133. {
  1134. playerEntry.Content.MapSprite.UpdateAnimation(
  1135. elapsedSeconds);
  1136. playerEntry.Content.MapSprite.Draw(spriteBatch, position,
  1137. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1138. }
  1139. break;
  1140. }
  1141. }
  1142. // draw the quest NPCs
  1143. foreach (MapEntry<QuestNpc> questNpcEntry in TileEngine.Map.QuestNpcEntries)
  1144. {
  1145. if (questNpcEntry.Content == null)
  1146. {
  1147. continue;
  1148. }
  1149. Vector2 position =
  1150. TileEngine.GetScreenPosition(questNpcEntry.MapPosition);
  1151. questNpcEntry.Content.ResetAnimation(false);
  1152. switch (questNpcEntry.Content.State)
  1153. {
  1154. case Character.CharacterState.Idle:
  1155. if (questNpcEntry.Content.MapSprite != null)
  1156. {
  1157. questNpcEntry.Content.MapSprite.UpdateAnimation(
  1158. elapsedSeconds);
  1159. questNpcEntry.Content.MapSprite.Draw(spriteBatch, position,
  1160. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1161. }
  1162. break;
  1163. case Character.CharacterState.Walking:
  1164. if (questNpcEntry.Content.WalkingSprite != null)
  1165. {
  1166. questNpcEntry.Content.WalkingSprite.UpdateAnimation(
  1167. elapsedSeconds);
  1168. questNpcEntry.Content.WalkingSprite.Draw(spriteBatch,
  1169. position,
  1170. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1171. }
  1172. else if (questNpcEntry.Content.MapSprite != null)
  1173. {
  1174. questNpcEntry.Content.MapSprite.UpdateAnimation(
  1175. elapsedSeconds);
  1176. questNpcEntry.Content.MapSprite.Draw(spriteBatch, position,
  1177. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1178. }
  1179. break;
  1180. }
  1181. }
  1182. // draw the fixed-combat monsters NPCs from the TileEngine.Map
  1183. // -- since there may be many of the same FixedCombat object
  1184. // on the TileEngine.Map, but their animations are handled differently
  1185. foreach (MapEntry<FixedCombat> fixedCombatEntry in
  1186. TileEngine.Map.FixedCombatEntries)
  1187. {
  1188. if ((fixedCombatEntry.Content == null) ||
  1189. (fixedCombatEntry.Content.Entries.Count <= 0))
  1190. {
  1191. continue;
  1192. }
  1193. Vector2 position =
  1194. TileEngine.GetScreenPosition(fixedCombatEntry.MapPosition);
  1195. fixedCombatEntry.MapSprite.UpdateAnimation(elapsedSeconds);
  1196. fixedCombatEntry.MapSprite.Draw(spriteBatch, position,
  1197. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1198. }
  1199. // draw the fixed-combat monsters NPCs from the current quest
  1200. // -- since there may be many of the same FixedCombat object
  1201. // on the TileEngine.Map, their animations are handled differently
  1202. if ((quest != null) && ((quest.Stage == Quest.QuestStage.InProgress) ||
  1203. (quest.Stage == Quest.QuestStage.RequirementsMet)))
  1204. {
  1205. foreach (WorldEntry<FixedCombat> fixedCombatEntry
  1206. in quest.FixedCombatEntries)
  1207. {
  1208. if ((fixedCombatEntry.Content == null) ||
  1209. (fixedCombatEntry.Content.Entries.Count <= 0) ||
  1210. !TileEngine.Map.AssetName.EndsWith(
  1211. fixedCombatEntry.MapContentName))
  1212. {
  1213. continue;
  1214. }
  1215. Vector2 position =
  1216. TileEngine.GetScreenPosition(fixedCombatEntry.MapPosition);
  1217. fixedCombatEntry.MapSprite.UpdateAnimation(elapsedSeconds);
  1218. fixedCombatEntry.MapSprite.Draw(spriteBatch, position,
  1219. 1f - position.Y / (float)TileEngine.Viewport.Height);
  1220. }
  1221. }
  1222. // draw the chests from the TileEngine.Map
  1223. foreach (MapEntry<Chest> chestEntry in TileEngine.Map.ChestEntries)
  1224. {
  1225. if (chestEntry.Content == null)
  1226. {
  1227. continue;
  1228. }
  1229. Vector2 position = TileEngine.GetScreenPosition(chestEntry.MapPosition);
  1230. spriteBatch.Draw(chestEntry.Content.Texture,
  1231. position, null, Color.White, 0f, Vector2.Zero, 1f,
  1232. SpriteEffects.None,
  1233. MathHelper.Clamp(1f - position.Y /
  1234. (float)TileEngine.Viewport.Height, 0f, 1f));
  1235. }
  1236. // draw the chests from the current quest
  1237. if ((quest != null) && ((quest.Stage == Quest.QuestStage.InProgress) ||
  1238. (quest.Stage == Quest.QuestStage.RequirementsMet)))
  1239. {
  1240. foreach (WorldEntry<Chest> chestEntry in quest.ChestEntries)
  1241. {
  1242. if ((chestEntry.Content == null) ||
  1243. !TileEngine.Map.AssetName.EndsWith(chestEntry.MapContentName))
  1244. {
  1245. continue;
  1246. }
  1247. Vector2 position =
  1248. TileEngine.GetScreenPosition(chestEntry.MapPosition);
  1249. spriteBatch.Draw(chestEntry.Content.Texture,
  1250. position, null, Color.White, 0f, Vector2.Zero, 1f,
  1251. SpriteEffects.None,
  1252. MathHelper.Clamp(1f - position.Y /
  1253. (float)TileEngine.Viewport.Height, 0f, 1f));
  1254. }
  1255. }
  1256. spriteBatch.End();
  1257. // draw the foreground
  1258. spriteBatch.Begin();
  1259. if (TileEngine.Map.Texture != null)
  1260. {
  1261. TileEngine.DrawLayers(spriteBatch, false, false, true);
  1262. }
  1263. spriteBatch.End();
  1264. }
  1265. /// <summary>
  1266. /// Draw the shadows that appear under all characters.
  1267. /// </summary>
  1268. private void DrawShadows(SpriteBatch spriteBatch)
  1269. {
  1270. // draw the shadow of the party leader
  1271. Player player = party.Players[0];
  1272. if (player.ShadowTexture != null)
  1273. {
  1274. spriteBatch.Draw(player.ShadowTexture,
  1275. TileEngine.PartyLeaderPosition.ScreenPosition, null, Color.White, 0f,
  1276. new Vector2(
  1277. (player.ShadowTexture.Width - TileEngine.Map.TileSize.X) / 2,
  1278. (player.ShadowTexture.Height - TileEngine.Map.TileSize.Y) / 2 -
  1279. player.ShadowTexture.Height / 6),
  1280. 1f, SpriteEffects.None, 1f);
  1281. }
  1282. // draw the player NPCs' shadows
  1283. foreach (MapEntry<Player> playerEntry in TileEngine.Map.PlayerNpcEntries)
  1284. {
  1285. if (playerEntry.Content == null)
  1286. {
  1287. continue;
  1288. }
  1289. if (playerEntry.Content.ShadowTexture != null)
  1290. {
  1291. Vector2 position =
  1292. TileEngine.GetScreenPosition(playerEntry.MapPosition);
  1293. spriteBatch.Draw(playerEntry.Content.ShadowTexture, position,
  1294. null, Color.White, 0f,
  1295. new Vector2(
  1296. (playerEntry.Content.ShadowTexture.Width -
  1297. TileEngine.Map.TileSize.X) / 2,
  1298. (playerEntry.Content.ShadowTexture.Height -
  1299. TileEngine.Map.TileSize.Y) / 2 -
  1300. playerEntry.Content.ShadowTexture.Height / 6),
  1301. 1f, SpriteEffects.None, 1f);
  1302. }
  1303. }
  1304. // draw the quest NPCs' shadows
  1305. foreach (MapEntry<QuestNpc> questNpcEntry in TileEngine.Map.QuestNpcEntries)
  1306. {
  1307. if (questNpcEntry.Content == null)
  1308. {
  1309. continue;
  1310. }
  1311. if (questNpcEntry.Content.ShadowTexture != null)
  1312. {
  1313. Vector2 position =
  1314. TileEngine.GetScreenPosition(questNpcEntry.MapPosition);
  1315. spriteBatch.Draw(questNpcEntry.Content.ShadowTexture, position,
  1316. null, Color.White, 0f,
  1317. new Vector2(
  1318. (questNpcEntry.Content.ShadowTexture.Width -
  1319. TileEngine.Map.TileSize.X) / 2,
  1320. (questNpcEntry.Content.ShadowTexture.Height -
  1321. TileEngine.Map.TileSize.Y) / 2 -
  1322. questNpcEntry.Content.ShadowTexture.Height / 6),
  1323. 1f, SpriteEffects.None, 1f);
  1324. }
  1325. }
  1326. // draw the fixed-combat monsters NPCs' shadows
  1327. foreach (MapEntry<FixedCombat> fixedCombatEntry in
  1328. TileEngine.Map.FixedCombatEntries)
  1329. {
  1330. if ((fixedCombatEntry.Content == null) ||
  1331. (fixedCombatEntry.Content.Entries.Count <= 0))
  1332. {
  1333. continue;
  1334. }
  1335. Monster monster = fixedCombatEntry.Content.Entries[0].Content;
  1336. if (monster.ShadowTexture != null)
  1337. {
  1338. Vector2 position =
  1339. TileEngine.GetScreenPosition(fixedCombatEntry.MapPosition);
  1340. spriteBatch.Draw(monster.ShadowTexture, position,
  1341. null, Color.White, 0f,
  1342. new Vector2(
  1343. (monster.ShadowTexture.Width - TileEngine.Map.TileSize.X) / 2,
  1344. (monster.ShadowTexture.Height - TileEngine.Map.TileSize.Y) / 2 -
  1345. monster.ShadowTexture.Height / 6),
  1346. 1f, SpriteEffects.None, 1f);
  1347. }
  1348. }
  1349. }
  1350. #endregion
  1351. #region Starting a New Session
  1352. /// <summary>
  1353. /// Start a new session based on the data provided.
  1354. /// </summary>
  1355. public static void StartNewSession(GameStartDescription gameStartDescription,
  1356. ScreenManager screenManager, GameplayScreen gameplayScreen)
  1357. {
  1358. // check the parameters
  1359. if (gameStartDescription == null)
  1360. {
  1361. throw new ArgumentNullException("gameStartDescripton");
  1362. }
  1363. if (screenManager == null)
  1364. {
  1365. throw new ArgumentNullException("screenManager");
  1366. }
  1367. if (gameplayScreen == null)
  1368. {
  1369. throw new ArgumentNullException("gameplayScreen");
  1370. }
  1371. // end any existing session
  1372. EndSession();
  1373. // create a new singleton
  1374. singleton = new Session(screenManager, gameplayScreen);
  1375. // set up the initial map
  1376. ChangeMap(gameStartDescription.MapContentName, null);
  1377. // set up the initial party
  1378. ContentManager content = singleton.screenManager.Game.Content;
  1379. singleton.party = new Party(gameStartDescription, content);
  1380. // load the quest line
  1381. singleton.questLine = content.Load<QuestLine>(
  1382. Path.Combine(@"Quests\QuestLines",
  1383. gameStartDescription.QuestLineContentName)).Clone() as QuestLine;
  1384. }
  1385. #endregion
  1386. #region Ending a Session
  1387. /// <summary>
  1388. /// End the current session.
  1389. /// </summary>
  1390. public static void EndSession()
  1391. {
  1392. // exit the gameplay screen
  1393. // -- store the gameplay session, for re-entrance
  1394. if (singleton != null)
  1395. {
  1396. GameplayScreen gameplayScreen = singleton.gameplayScreen;
  1397. singleton.gameplayScreen = null;
  1398. // pop the music
  1399. AudioManager.PopMusic();
  1400. // clear the singleton
  1401. singleton = null;
  1402. if (gameplayScreen != null)
  1403. {
  1404. gameplayScreen.ExitScreen();
  1405. }
  1406. }
  1407. }
  1408. #endregion
  1409. #region Loading a Session
  1410. /// <summary>
  1411. /// Start a new session, using the data in the given save game.
  1412. /// </summary>
  1413. /// <param name="saveGameDescription">The description of the save game.</param>
  1414. /// <param name="screenManager">The ScreenManager for the new session.</param>
  1415. public static void LoadSession(SaveGameDescription saveGameDescription,
  1416. ScreenManager screenManager, GameplayScreen gameplayScreen)
  1417. {
  1418. // check the parameters
  1419. if (saveGameDescription == null)
  1420. {
  1421. throw new ArgumentNullException("saveGameDescription");
  1422. }
  1423. if (screenManager == null)
  1424. {
  1425. throw new ArgumentNullException("screenManager");
  1426. }
  1427. if (gameplayScreen == null)
  1428. {
  1429. throw new ArgumentNullException("gameplayScreen");
  1430. }
  1431. // end any existing session
  1432. EndSession();
  1433. // create the new session
  1434. singleton = new Session(screenManager, gameplayScreen);
  1435. // get the storage device and load the session
  1436. GetStorageDevice(
  1437. delegate(StorageDevice storageDevice)
  1438. {
  1439. LoadSessionResult(storageDevice, saveGameDescription);
  1440. });
  1441. }
  1442. /// <summary>
  1443. /// Receives the storage device and starts a new session,
  1444. /// using the data in the given save game.
  1445. /// </summary>
  1446. /// <remarks>The new session is created in LoadSessionResult.</remarks>
  1447. /// <param name="storageDevice">The chosen storage device.</param>
  1448. /// <param name="saveGameDescription">The description of the save game.</param>
  1449. public static void LoadSessionResult(StorageDevice storageDevice,
  1450. SaveGameDescription saveGameDescription)
  1451. {
  1452. // check the parameters
  1453. if (saveGameDescription == null)
  1454. {
  1455. throw new ArgumentNullException("saveGameDescription");
  1456. }
  1457. // check the parameter
  1458. if ((storageDevice == null) || !storageDevice.IsConnected)
  1459. {
  1460. return;
  1461. }
  1462. // open the container
  1463. using (StorageContainer storageContainer = OpenContainer(storageDevice))
  1464. {
  1465. using (Stream stream =
  1466. storageContainer.OpenFile(saveGameDescription.FileName, FileMode.Open))
  1467. {
  1468. using (XmlReader xmlReader = XmlReader.Create(stream))
  1469. {
  1470. // <rolePlayingGameData>
  1471. xmlReader.ReadStartElement("rolePlayingGameSaveData");
  1472. // read the map information
  1473. xmlReader.ReadStartElement("mapData");
  1474. string mapAssetName =
  1475. xmlReader.ReadElementString("mapContentName");
  1476. PlayerPosition playerPosition = new XmlSerializer(
  1477. typeof(PlayerPosition)).Deserialize(xmlReader)
  1478. as PlayerPosition;
  1479. singleton.removedMapChests = new XmlSerializer(
  1480. typeof(List<WorldEntry<Chest>>)).Deserialize(xmlReader)
  1481. as List<WorldEntry<Chest>>;
  1482. singleton.removedMapFixedCombats = new XmlSerializer(
  1483. typeof(List<WorldEntry<FixedCombat>>)).Deserialize(xmlReader)
  1484. as List<WorldEntry<FixedCombat>>;
  1485. singleton.removedMapPlayerNpcs = new XmlSerializer(
  1486. typeof(List<WorldEntry<Player>>)).Deserialize(xmlReader)
  1487. as List<WorldEntry<Player>>;
  1488. singleton.modifiedMapChests = new XmlSerializer(
  1489. typeof(List<ModifiedChestEntry>)).Deserialize(xmlReader)
  1490. as List<ModifiedChestEntry>;
  1491. ChangeMap(mapAssetName, null);
  1492. TileEngine.PartyLeaderPosition = playerPosition;
  1493. xmlReader.ReadEndElement();
  1494. // read the quest information
  1495. ContentManager content = Session.ScreenManager.Game.Content;
  1496. xmlReader.ReadStartElement("questData");
  1497. singleton.questLine = content.Load<QuestLine>(
  1498. xmlReader.ReadElementString("questLineContentName")).Clone()
  1499. as QuestLine;
  1500. singleton.currentQuestIndex = Convert.ToInt32(
  1501. xmlReader.ReadElementString("currentQuestIndex"));
  1502. for (int i = 0; i < singleton.currentQuestIndex; i++)
  1503. {
  1504. singleton.questLine.Quests[i].Stage =
  1505. Quest.QuestStage.Completed;
  1506. }
  1507. singleton.removedQuestChests = new XmlSerializer(
  1508. typeof(List<WorldEntry<Chest>>)).Deserialize(xmlReader)
  1509. as List<WorldEntry<Chest>>;
  1510. singleton.removedQuestFixedCombats = new XmlSerializer(
  1511. typeof(List<WorldEntry<FixedCombat>>)).Deserialize(xmlReader)
  1512. as List<WorldEntry<FixedCombat>>;
  1513. singleton.modifiedQuestChests = new XmlSerializer(
  1514. typeof(List<ModifiedChestEntry>)).Deserialize(xmlReader)
  1515. as List<ModifiedChestEntry>;
  1516. Quest.QuestStage questStage = (Quest.QuestStage)Enum.Parse(
  1517. typeof(Quest.QuestStage),
  1518. xmlReader.ReadElementString("currentQuestStage"), true);
  1519. if ((singleton.questLine != null) && !IsQuestLineComplete)
  1520. {
  1521. singleton.quest =
  1522. singleton.questLine.Quests[CurrentQuestIndex];
  1523. singleton.ModifyQuest(singleton.quest);
  1524. singleton.quest.Stage = questStage;
  1525. }
  1526. xmlReader.ReadEndElement();
  1527. // read the party data
  1528. singleton.party = new Party(new XmlSerializer(
  1529. typeof(PartySaveData)).Deserialize(xmlReader)
  1530. as PartySaveData, content);
  1531. // </rolePlayingGameSaveData>
  1532. xmlReader.ReadEndElement();
  1533. }
  1534. }
  1535. }
  1536. }
  1537. #endregion
  1538. #region Saving the Session
  1539. /// <summary>
  1540. /// Save the current state of the session.
  1541. /// </summary>
  1542. /// <param name="overwriteDescription">
  1543. /// The description of the save game to over-write, if any.
  1544. /// </param>
  1545. public static void SaveSession(SaveGameDescription overwriteDescription)
  1546. {
  1547. // retrieve the storage device, asynchronously
  1548. GetStorageDevice(delegate(StorageDevice storageDevice)
  1549. {
  1550. SaveSessionResult(storageDevice, overwriteDescription);
  1551. });
  1552. }
  1553. /// <summary>
  1554. /// Save the current state of the session, with the given storage device.
  1555. /// </summary>
  1556. /// <param name="storageDevice">The chosen storage device.</param>
  1557. /// <param name="overwriteDescription">
  1558. /// The description of the save game to over-write, if any.
  1559. /// </param>
  1560. private static void SaveSessionResult(StorageDevice storageDevice,
  1561. SaveGameDescription overwriteDescription)
  1562. {
  1563. // check the parameter
  1564. if ((storageDevice == null) || !storageDevice.IsConnected)
  1565. {
  1566. return;
  1567. }
  1568. // open the container
  1569. using (StorageContainer storageContainer =
  1570. OpenContainer(storageDevice))
  1571. {
  1572. string filename;
  1573. string descriptionFilename;
  1574. // get the filenames
  1575. if (overwriteDescription == null)
  1576. {
  1577. int saveGameIndex = 0;
  1578. string testFilename;
  1579. do
  1580. {
  1581. saveGameIndex++;
  1582. testFilename = "SaveGame" + saveGameIndex.ToString() + ".xml";
  1583. }
  1584. while (storageContainer.FileExists(testFilename));
  1585. filename = testFilename;
  1586. descriptionFilename = "SaveGameDescription" +
  1587. saveGameIndex.ToString() + ".xml";
  1588. }
  1589. else
  1590. {
  1591. filename = overwriteDescription.FileName;
  1592. descriptionFilename = "SaveGameDescription" +
  1593. Path.GetFileNameWithoutExtension(
  1594. overwriteDescription.FileName).Substring(8) + ".xml";
  1595. }
  1596. using (Stream stream = storageContainer.OpenFile(filename, FileMode.Create))
  1597. {
  1598. using (XmlWriter xmlWriter = XmlWriter.Create(stream))
  1599. {
  1600. // <rolePlayingGameData>
  1601. xmlWriter.WriteStartElement("rolePlayingGameSaveData");
  1602. // write the map information
  1603. xmlWriter.WriteStartElement("mapData");
  1604. xmlWriter.WriteElementString("mapContentName",
  1605. TileEngine.Map.AssetName);
  1606. new XmlSerializer(typeof(PlayerPosition)).Serialize(
  1607. xmlWriter, TileEngine.PartyLeaderPosition);
  1608. new XmlSerializer(typeof(List<WorldEntry<Chest>>)).Serialize(
  1609. xmlWriter, singleton.removedMapChests);
  1610. new XmlSerializer(
  1611. typeof(List<WorldEntry<FixedCombat>>)).Serialize(
  1612. xmlWriter, singleton.removedMapFixedCombats);
  1613. new XmlSerializer(typeof(List<WorldEntry<Player>>)).Serialize(
  1614. xmlWriter, singleton.removedMapPlayerNpcs);
  1615. new XmlSerializer(typeof(List<ModifiedChestEntry>)).Serialize(
  1616. xmlWriter, singleton.modifiedMapChests);
  1617. xmlWriter.WriteEndElement();
  1618. // write the quest information
  1619. xmlWriter.WriteStartElement("questData");
  1620. xmlWriter.WriteElementString("questLineContentName",
  1621. singleton.questLine.AssetName);
  1622. xmlWriter.WriteElementString("currentQuestIndex",
  1623. singleton.currentQuestIndex.ToString());
  1624. new XmlSerializer(typeof(List<WorldEntry<Chest>>)).Serialize(
  1625. xmlWriter, singleton.removedQuestChests);
  1626. new XmlSerializer(
  1627. typeof(List<WorldEntry<FixedCombat>>)).Serialize(
  1628. xmlWriter, singleton.removedQuestFixedCombats);
  1629. new XmlSerializer(typeof(List<ModifiedChestEntry>)).Serialize(
  1630. xmlWriter, singleton.modifiedQuestChests);
  1631. xmlWriter.WriteElementString("currentQuestStage",
  1632. IsQuestLineComplete ?
  1633. Quest.QuestStage.NotStarted.ToString() :
  1634. singleton.quest.Stage.ToString());
  1635. xmlWriter.WriteEndElement();
  1636. // write the party data
  1637. new XmlSerializer(typeof(PartySaveData)).Serialize(xmlWriter,
  1638. new PartySaveData(singleton.party));
  1639. // </rolePlayingGameSaveData>
  1640. xmlWriter.WriteEndElement();
  1641. }
  1642. }
  1643. // create the save game description
  1644. SaveGameDescription description = new SaveGameDescription();
  1645. description.FileName = Path.GetFileName(filename);
  1646. description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" :
  1647. Quest.Name;
  1648. description.Description = DateTime.Now.ToString();
  1649. using (Stream stream =
  1650. storageContainer.OpenFile(descriptionFilename, FileMode.Create))
  1651. {
  1652. new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream,
  1653. description);
  1654. }
  1655. }
  1656. }
  1657. #endregion
  1658. #region Deleting a Save Game
  1659. /// <summary>
  1660. /// Delete the save game specified by the description.
  1661. /// </summary>
  1662. /// <param name="saveGameDescription">The description of the save game.</param>
  1663. public static void DeleteSaveGame(SaveGameDescription saveGameDescription)
  1664. {
  1665. // check the parameters
  1666. if (saveGameDescription == null)
  1667. {
  1668. throw new ArgumentNullException("saveGameDescription");
  1669. }
  1670. // get the storage device and load the session
  1671. GetStorageDevice(
  1672. delegate(StorageDevice storageDevice)
  1673. {
  1674. DeleteSaveGameResult(storageDevice, saveGameDescription);
  1675. });
  1676. }
  1677. /// <summary>
  1678. /// Delete the save game specified by the description.
  1679. /// </summary>
  1680. /// <param name="storageDevice">The chosen storage device.</param>
  1681. /// <param name="saveGameDescription">The description of the save game.</param>
  1682. public static void DeleteSaveGameResult(StorageDevice storageDevice,
  1683. SaveGameDescription saveGameDescription)
  1684. {
  1685. // check the parameters
  1686. if (saveGameDescription == null)
  1687. {
  1688. throw new ArgumentNullException("saveGameDescription");
  1689. }
  1690. // check the parameter
  1691. if ((storageDevice == null) || !storageDevice.IsConnected)
  1692. {
  1693. return;
  1694. }
  1695. // open the container
  1696. using (StorageContainer storageContainer =
  1697. OpenContainer(storageDevice))
  1698. {
  1699. storageContainer.DeleteFile(saveGameDescription.FileName);
  1700. storageContainer.DeleteFile("SaveGameDescription" +
  1701. Path.GetFileNameWithoutExtension(
  1702. saveGameDescription.FileName).Substring(8) + ".xml");
  1703. }
  1704. // refresh the save game descriptions
  1705. Session.RefreshSaveGameDescriptions();
  1706. }
  1707. #endregion
  1708. #region Save Game Descriptions
  1709. /// <summary>
  1710. /// Save game descriptions for the current set of save games.
  1711. /// </summary>
  1712. private static List<SaveGameDescription> saveGameDescriptions = null;
  1713. /// <summary>
  1714. /// Save game descriptions for the current set of save games.
  1715. /// </summary>
  1716. public static List<SaveGameDescription> SaveGameDescriptions
  1717. {
  1718. get { return saveGameDescriptions; }
  1719. }
  1720. /// <summary>
  1721. /// The maximum number of save-game descriptions that the list may hold.
  1722. /// </summary>
  1723. public const int MaximumSaveGameDescriptions = 5;
  1724. /// <summary>
  1725. /// XML serializer for SaveGameDescription objects.
  1726. /// </summary>
  1727. private static XmlSerializer saveGameDescriptionSerializer =
  1728. new XmlSerializer(typeof(SaveGameDescription));
  1729. /// <summary>
  1730. /// Refresh the list of save-game descriptions.
  1731. /// </summary>
  1732. public static void RefreshSaveGameDescriptions()
  1733. {
  1734. // clear the list
  1735. saveGameDescriptions = null;
  1736. // retrieve the storage device, asynchronously
  1737. GetStorageDevice(RefreshSaveGameDescriptionsResult);
  1738. }
  1739. /// <summary>
  1740. /// Asynchronous storage-device callback for
  1741. /// refreshing the save-game descriptions.
  1742. /// </summary>
  1743. private static void RefreshSaveGameDescriptionsResult(
  1744. StorageDevice storageDevice)
  1745. {
  1746. // check the parameter
  1747. if ((storageDevice == null) || !storageDevice.IsConnected)
  1748. {
  1749. return;
  1750. }
  1751. // open the container
  1752. using (StorageContainer storageContainer =
  1753. OpenContainer(storageDevice))
  1754. {
  1755. saveGameDescriptions = new List<SaveGameDescription>();
  1756. // get the description list
  1757. string[] filenames =
  1758. storageContainer.GetFileNames("SaveGameDescription*.xml");
  1759. // add each entry to the list
  1760. foreach (string filename in filenames)
  1761. {
  1762. SaveGameDescription saveGameDescription;
  1763. // check the size of the list
  1764. if (saveGameDescriptions.Count >= MaximumSaveGameDescriptions)
  1765. {
  1766. break;
  1767. }
  1768. // open the file stream
  1769. using (Stream fileStream = storageContainer.OpenFile(filename, FileMode.Open))
  1770. {
  1771. // deserialize the object
  1772. saveGameDescription =
  1773. saveGameDescriptionSerializer.Deserialize(fileStream)
  1774. as SaveGameDescription;
  1775. // if it's valid, add it to the list
  1776. if (saveGameDescription != null)
  1777. {
  1778. saveGameDescriptions.Add(saveGameDescription);
  1779. }
  1780. }
  1781. }
  1782. }
  1783. }
  1784. #endregion
  1785. #region Storage
  1786. /// <summary>
  1787. /// The stored StorageDevice object.
  1788. /// </summary>
  1789. private static StorageDevice storageDevice;
  1790. /// <summary>
  1791. /// The container name used for save games.
  1792. /// </summary>
  1793. public static string SaveGameContainerName = "RolePlayingGame";
  1794. /// <summary>
  1795. /// A delegate for receiving StorageDevice objects.
  1796. /// </summary>
  1797. public delegate void StorageDeviceDelegate(StorageDevice storageDevice);
  1798. /// <summary>
  1799. /// Asynchronously retrieve a storage device.
  1800. /// </summary>
  1801. /// <param name="retrievalDelegate">
  1802. /// The delegate called when the device is available.
  1803. /// </param>
  1804. /// <remarks>
  1805. /// If there is a suitable cached storage device,
  1806. /// the delegate may be called directly by this function.
  1807. /// </remarks>
  1808. public static void GetStorageDevice(StorageDeviceDelegate retrievalDelegate)
  1809. {
  1810. // check the parameter
  1811. if (retrievalDelegate == null)
  1812. {
  1813. throw new ArgumentNullException("retrievalDelegate");
  1814. }
  1815. // check the stored storage device
  1816. if ((storageDevice != null) && storageDevice.IsConnected)
  1817. {
  1818. retrievalDelegate(storageDevice);
  1819. return;
  1820. }
  1821. // the storage device must be retrieved
  1822. if (!Guide.IsVisible)
  1823. {
  1824. // Reset the device
  1825. storageDevice = null;
  1826. StorageDevice.BeginShowSelector(GetStorageDeviceResult, retrievalDelegate);
  1827. }
  1828. }
  1829. /// <summary>
  1830. /// Asynchronous callback to the guide's BeginShowStorageDeviceSelector call.
  1831. /// </summary>
  1832. /// <param name="result">The IAsyncResult object with the device.</param>
  1833. private static void GetStorageDeviceResult(IAsyncResult result)
  1834. {
  1835. // check the parameter
  1836. if ((result == null) || !result.IsCompleted)
  1837. {
  1838. return;
  1839. }
  1840. // retrieve and store the storage device
  1841. storageDevice = StorageDevice.EndShowSelector(result);
  1842. // check the new storage device
  1843. if ((storageDevice != null) && storageDevice.IsConnected)
  1844. {
  1845. // it passes; call the stored delegate
  1846. StorageDeviceDelegate func = result.AsyncState as StorageDeviceDelegate;
  1847. if (func != null)
  1848. {
  1849. func(storageDevice);
  1850. }
  1851. }
  1852. }
  1853. /// <summary>
  1854. /// Synchronously opens storage container
  1855. /// </summary>
  1856. private static StorageContainer OpenContainer(StorageDevice storageDevice)
  1857. {
  1858. IAsyncResult result =
  1859. storageDevice.BeginOpenContainer(Session.SaveGameContainerName, null, null);
  1860. // Wait for the WaitHandle to become signaled.
  1861. result.AsyncWaitHandle.WaitOne();
  1862. StorageContainer container = storageDevice.EndOpenContainer(result);
  1863. // Close the wait handle.
  1864. result.AsyncWaitHandle.Close();
  1865. return container;
  1866. }
  1867. #endregion
  1868. #region Random
  1869. /// <summary>
  1870. /// The random-number generator used with game events.
  1871. /// </summary>
  1872. private static Random random = new Random();
  1873. /// <summary>
  1874. /// The random-number generator used with game events.
  1875. /// </summary>
  1876. public static Random Random
  1877. {
  1878. get { return random; }
  1879. }
  1880. #endregion
  1881. }
  1882. }