/JTacticalSim.DataContext/XMLDataContext.cs
C# | 1123 lines | 818 code | 220 blank | 85 comment | 25 complexity | 20f8603e956df84e27f96143444bbd41 MD5 | raw file
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Xml.Linq;
- using System.Dynamic;
- using System.IO;
- using System.Transactions;
- using JTacticalSim.API;
- using JTacticalSim.API.DTO;
- using JTacticalSim.Data.DTO;
- using JTacticalSim.API.Data;
- using JTacticalSim.API.Component;
- using JTacticalSim.Utility;
-
- namespace JTacticalSim.DataContext
- {
- /// <summary>
- /// File based data context
- /// </summary>
- public sealed class XMLDataContext : BaseDataContext
- {
- private DataFileFactory _dataFileFactory = DataFileFactory.Instance;
-
- private static volatile IDataContext _instance = null;
- static readonly object padlock = new object();
-
- public static IDataContext Instance
- {
- get
- {
- if (_instance == null)
- {
- lock (padlock)
- if (_instance == null) _instance = new XMLDataContext();
- }
-
- return _instance;
- }
- }
-
- // Initialize Context
- private XMLDataContext()
- {}
-
- #region Save
-
- public override IResult<IGameFileCopyable> SaveData(IGameFileCopyable currentData)
- {
- var r = new DataResult<IGameFileCopyable>{Status = ResultStatus.SUCCESS, Result = currentData};
-
- using (var txn = new TransactionScope())
- {
- // 1. Create a new file handler for the current game file directory
- IDataFileHandler<XDocument> dataFileHandler = null;
-
- try
- {
- dataFileHandler = new DataFileHandler<XDocument>(_dataFileFactory.GetDataFiles<XDocument>(currentData.GameFileDirectory, currentData.IsScenario));
-
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data not saved. DataFileHandler could not be created.");
- return r;
- }
-
- // 2. Backup Current Files
- if (dataFileHandler.GameDirectoryHasFiles())
- {
- try
- {
- BackupCurrentGameFiles(dataFileHandler);
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data not saved. Could not backup current game files.");
- return r;
- }
- }
-
- // 3. Save data
- try
- {
- SaveGameData(dataFileHandler);
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data not saved.");
- return r;
- }
-
- txn.Complete();
- }
-
- r.Messages.Add("Game data saved.");
- return r;
- }
-
- public override IResult<IGameFileCopyable> SaveDataAs(IGameFileCopyable currentData, IGameFileCopyable newData)
- {
- var r = new DataResult<IGameFileCopyable>{Status = ResultStatus.SUCCESS, Result = newData};
-
- using (var txn = new TransactionScope())
- {
- // 1. Create a new file handler for the current and new game file directories
- IDataFileHandler<XDocument> currentDataFileHandler = null;
- IDataFileHandler<XDocument> newDataFileHandler = null;
-
- try
- {
- currentDataFileHandler = new DataFileHandler<XDocument>(_dataFileFactory.GetDataFiles<XDocument>(currentData.GameFileDirectory, currentData.IsScenario));
- newDataFileHandler = new DataFileHandler<XDocument>(_dataFileFactory.GetDataFiles<XDocument>(newData.GameFileDirectory, newData.IsScenario));
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data not saved. DataFileHandlers could not be created.");
- return r;
- }
-
- // 2. Verify game directory. Create if it does not exists.
- if (!newDataFileHandler.GameDirectoryExists())
- {
- try
- {
- newDataFileHandler.CreateNewGameDirectory();
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data not saved. Could not create new game directory.");
- return r;
- }
- }
-
- // 3. Copy current files to new directory
- var result = (currentData.IsScenario)
- ? currentDataFileHandler.CopyScenarioFiles(newDataFileHandler.DataFiles.GameSaveDirectory)
- : currentDataFileHandler.CopyGameFiles(newDataFileHandler.DataFiles.GameSaveDirectory);
-
- if (result.Status == ResultStatus.EXCEPTION)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = result.ex;
- r.Messages.Add("Game data not saved. {0}.".F(result.Message));
- return r;
- }
-
- txn.Complete();
- }
-
- r.Messages.Add("Game data saved.");
- return r;
- }
-
- public override IResult<IGameFileCopyable> RemoveSavedGameData(IGameFileCopyable delData)
- {
- var r = new DataResult<IGameFileCopyable>{Status = ResultStatus.SUCCESS, Result = delData};
-
- using (var txn = new TransactionScope())
- {
-
- // 1. Create a new file handler for the game to be deleted.
- IDataFileHandler<XDocument> delDataFileHandler = null;
-
- try
- {
- delDataFileHandler = new DataFileHandler<XDocument>(_dataFileFactory.GetDataFiles<XDocument>(delData.GameFileDirectory, delData.IsScenario));
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data not saved. DataFileHandlers could not be created.");
- return r;
- }
-
- // 2. Verify game directory. Create if it does not exists.
- if (delDataFileHandler.GameRootDirectoryExists())
- {
- try
- {
- delDataFileHandler.DeleteGameDirectory();
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data not deleted. Could not delete game directory.");
- return r;
- }
- }
-
- // 3. Save data
- try
- {
- SaveSavedGameFile(delDataFileHandler);
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data file not saved.");
- return r;
- }
-
- txn.Complete();
- }
-
- r.Messages.Add("Game data removed.");
- return r;
- }
-
-
- private void BackupCurrentGameFiles(IDataFileHandler<XDocument> dataFileHandler)
- {
- dataFileHandler.DataFiles.ScenarioFilePaths.ForEach(path =>
- {
- File.Delete("{0}.BAK".F(path));
- File.Copy(path, "{0}.BAK".F(path));
- });
-
- // Back up the Saved Games file
- File.Delete("{0}.BAK".F(dataFileHandler.DataFiles.SavedGameDataFilePath));
- File.Copy(dataFileHandler.DataFiles.SavedGameDataFilePath, "{0}.BAK".F(dataFileHandler.DataFiles.SavedGameDataFilePath));
- }
-
- private void SaveGameData(IDataFileHandler<XDocument> dataFileHandler)
- {
- SaveBoardDataFile(dataFileHandler);
- SaveUnitDataFile(dataFileHandler);
- SaveGameDataFile(dataFileHandler);
- SaveSavedGameFile(dataFileHandler);
- }
-
- private void SaveBoardDataFile(IDataFileHandler<XDocument> dataFileHandler)
- {
- // Clear all nodes
- var nodes = dataFileHandler.DataFiles.BoardDataFile.Descendants("Nodes").Single();
- nodes.RemoveAll();
-
- var attributes = dataFileHandler.DataFiles.BoardDataFile.Descendants("Attributes").Single();
-
- // Clear the board
- var board = dataFileHandler.DataFiles.BoardDataFile.Descendants("GameBoard").Single();
- board.RemoveAll();
-
- // Update attributes
- attributes.Attribute("Title").SetValue(Board.Title);
- attributes.Attribute("Width").SetValue(Board.Width);
- attributes.Attribute("Height").SetValue(Board.Height);
- attributes.Attribute("CellSize").SetValue(Board.CellSize);
- attributes.Attribute("CellMaxUnits").SetValue(Board.CellMaxUnits);
-
- // Create Nodes for save
- foreach (var n in NodesTable.Records)
- {
- nodes.Add(n.ToXML());
- }
-
- board.Add(attributes);
- board.Add(nodes);
-
- // Save back file
- board.Document.Save(dataFileHandler.DataFiles.BoardDataFilePath);
- }
-
- private void SaveUnitDataFile(IDataFileHandler<XDocument> dataFileHandler)
- {
- // Remove all existing units
- var units = dataFileHandler.DataFiles.UnitDataFile.Descendants("Units").Single();
- units.RemoveAll();
-
- // Create units for save
- foreach (var u in UnitsTable.Records)
- {
- units.Add(u.ToXML());
- }
-
- units.Document.Save(dataFileHandler.DataFiles.UnitDataFilePath);
- }
-
- private void SaveGameDataFile(IDataFileHandler<XDocument> dataFileHandler)
- {
- // Remove all existing GameData
- var gameData = dataFileHandler.DataFiles.GameDataFile.Descendants("GameData").Single();
- gameData.RemoveAll();
-
- // Create Factions for save
- XElement fs = new XElement("Factions");
- foreach (var f in FactionsTable.Records)
- {
- fs.Add(f.ToXML());
- }
- gameData.Add(fs);
-
- // Create Countries for save
- XElement cs = new XElement("Countries");
- foreach (var c in CountriesTable.Records)
- {
- cs.Add(c.ToXML());
- }
- gameData.Add(cs);
-
- // Create Players for save
- XElement ps = new XElement("Players");
- foreach (var p in PlayersTable.Records)
- {
- ps.Add(p.ToXML());
- }
- gameData.Add(ps);
-
- gameData.Add(new XComment("Conditions for winning the game for a faction. Winning is an OR proposition"));
- XElement fvcs = new XElement("FactionVictoryConditions");
- foreach (var fvc in FactionVictoryConditions)
- {
- XElement vc = new XElement("VictoryCondition");
- vc.Add(new XAttribute("Faction", fvc.Faction));
- vc.Add(new XAttribute("Condition", fvc.Condition));
- vc.Add(new XAttribute("Value", fvc.Value));
-
- fvcs.Add(vc);
- }
- gameData.Add(fvcs);
-
- gameData.Add(new XComment("Unit Assignments"));
- XElement uas = new XElement("UnitAssignments");
- foreach (var a in UnitAssignments)
- {
- XElement ua = new XElement("UnitAssignment");
- ua.Add(new XAttribute("Unit", a.Unit));
- ua.Add(new XAttribute("AssignedToUnit", a.AssignedToUnit));
-
- uas.Add(ua);
- }
- gameData.Add(uas);
-
-
- gameData.Add(new XComment("Unit Transports"));
- XElement uts = new XElement("UnitTransports");
- foreach (var a in UnitTransports)
- {
- XElement ua = new XElement("UnitTransport");
- ua.Add(new XAttribute("Unit", a.Unit));
- ua.Add(new XAttribute("TransportUnit", a.TransportUnit));
-
- uts.Add(ua);
- }
- gameData.Add(uts);
-
- gameData.Document.Save(dataFileHandler.DataFiles.GameDataFilePath);
- }
-
- private void SaveSavedGameFile(IDataFileHandler<XDocument> dataFileHandler)
- {
- // Remove all existing GameData
- var gameData = dataFileHandler.DataFiles.SavedGameDataFile.Descendants("SavedGames").Single();
- gameData.RemoveAll();
-
- foreach(var game in SavedGames.Records)
- {
- gameData.Add(game.ToXML());
- }
-
- gameData.Document.Save(dataFileHandler.DataFiles.SavedGameDataFilePath);
- }
-
- #endregion
-
- #region Load
-
- public override IResult<string> LoadData(string gameFileDirectory, bool IsScenario)
- {
- var r = new DataResult<string>{Status = ResultStatus.SUCCESS, Result = gameFileDirectory};
-
- try
- {
- IDataFileHandler<XDocument> dataFileHandler = new DataFileHandler<XDocument>(_dataFileFactory.GetDataFiles<XDocument>(gameFileDirectory, IsScenario));
-
- // ~~~~~~~~~~~~~~~~~~~~ Load up context
- // (Order is important for dependant objects)
-
- LoadComponentData(dataFileHandler.DataFiles.ComponentDataFile);
- LoadLookupData(dataFileHandler.DataFiles.LookupDataFile);
- LoadGamedata(dataFileHandler.DataFiles.GameDataFile,
- dataFileHandler.DataFiles.BoardDataFile,
- dataFileHandler.DataFiles.UnitDataFile,
- dataFileHandler.DataFiles.ComponentDataFile);
-
- // We need to make sure we have the last played game set correctly in the data file for saved games
- SaveSavedGameFile(dataFileHandler);
- }
- catch (Exception ex)
- {
- r.Status = ResultStatus.EXCEPTION;
- r.ex = ex;
- r.Messages.Add("Game data not loaded.");
- }
-
- r.Messages.Add("Game data loaded.");
- return r;
-
- }
-
- /// <summary>
- /// Load all static code data tables into context
- /// </summary>
- /// <param name="componentDataFile"></param>
- private void LoadComponentData(XDocument componentDataFile)
- {
- LoadBasePointValues(componentDataFile);
- LoadUnitBaseTypes(componentDataFile);
- LoadUnitGroupTypes(componentDataFile);
- LoadUnitTypes(componentDataFile);
- LoadUnitClasses(componentDataFile);
- LoadDemographicClasses(componentDataFile);
- LoadDemographicTypes(componentDataFile);
- LoadVictoryConditions(componentDataFile);
-
- LoadMissionData(componentDataFile);
- }
-
- /// <summary>
- /// Load all the lookup tables for code game code data into context
- /// </summary>
- /// <param name="lookupDataFile"></param>
- private void LoadLookupData(XDocument lookupDataFile)
- {
- LoadUnitBaseTypeUnitClasses(lookupDataFile);
- LoadUnitBaseTypeUnitGeogTypes(lookupDataFile);
- LoadUnitGeogTypeDemographicClasses(lookupDataFile);
- LoadUnitGroupTypeUnitTasks(lookupDataFile);
- LoadMissionObjectiveUnitTasks(lookupDataFile);
- LoadUnitTaskUnitClasses(lookupDataFile);
- LoadUnitGeogTypeMovementOverrides(lookupDataFile);
- LoadUnitTypeUnitGeogTypeBattleEffectives(lookupDataFile);
- LoadUnitTransportUnitTypeUnitClasses(lookupDataFile);
- LoadHybridDemographicClasses(lookupDataFile);
- LoadMovementHinderancesInDirection(lookupDataFile);
- }
-
- private void LoadGamedata( XDocument gameDataFile,
- XDocument boardDataFile,
- XDocument unitDataFile,
- XDocument componentDataFile)
- {
- LoadBoard(boardDataFile);
- LoadUnits(unitDataFile);
- LoadFactions(gameDataFile);
- LoadCountries(gameDataFile);
- LoadPlayers(gameDataFile);
- LoadDemographics(gameDataFile, componentDataFile);
- LoadUnitAssignments(gameDataFile);
- LoadUnitTransports(gameDataFile);
- LoadFactionVictoryConditions(gameDataFile);
- }
-
- private void LoadBasePointValues(XDocument staticDataFile)
- {
- var data = staticDataFile.Descendants("BasePointValues").Single();
-
- var basePointValues = new BasePointValuesDTO
- (
- Convert.ToInt32(data.Attribute("Movement").Value),
- Convert.ToInt32(data.Attribute("CombatRoll").Value),
- Convert.ToInt32(data.Attribute("CombatBase").Value),
- Convert.ToInt32(data.Attribute("StealthRoll").Value),
- Convert.ToInt32(data.Attribute("StealthBase").Value),
- Convert.ToInt32(data.Attribute("MedicalSupportBase").Value),
- Convert.ToInt32(data.Attribute("WeightBase").Value),
- Convert.ToInt32(data.Attribute("CostBase").Value),
- Convert.ToInt32(data.Attribute("AIBaseRoll").Value),
- Convert.ToInt32(data.Attribute("AIAggressiveness").Value),
- Convert.ToInt32(data.Attribute("AIDefensiveness").Value),
- Convert.ToInt32(data.Attribute("AIIntelligence").Value),
- Convert.ToInt32(data.Attribute("ReinforcementCalcBaseCountry").Value),
- Convert.ToInt32(data.Attribute("ReinforcementCalcBaseFaction").Value),
- Convert.ToDouble(data.Attribute("ReinforcementCalcBaseVP").Value),
- Convert.ToDouble(data.Attribute("HQBonus").Value),
- Convert.ToDouble(data.Attribute("SuppliedBonus").Value),
- Convert.ToInt32(data.Attribute("MaxSupplyDistance").Value),
- Convert.ToDouble(data.Attribute("TargetAttachedUnitBonus").Value),
- Convert.ToDouble(data.Attribute("TargetMedicalUnitBonus").Value),
- Convert.ToDouble(data.Attribute("TargetSupplyUnitBonus").Value)
- ) as IBasePointValues;
-
- this._basePointValues = basePointValues;
- }
-
- private void LoadUnitBaseTypes(XDocument staticDataFile)
- {
- //Get base type with properties
- var unitBaseTypes = GetBaseComponentDTOs<UnitBaseTypeDTO>(staticDataFile.Descendants("UnitBaseType")).ToList();
-
- unitBaseTypes.ForEach(o =>
- {
- o.Item1.CanReceiveMedicalSupport = Convert.ToBoolean(o.Item2.Attribute("CanReceiveMedicalSupport").Value);
- });
-
- // Add to context
- this._unitBaseTypesTable.Records = unitBaseTypes.Select(p => p.Item1 as IUnitBaseTypeDTO).ToList();
- }
-
- private void LoadVictoryConditions(XDocument staticDataFile)
- {
- var victoryConditions = GetBaseComponentDTOs<VictoryConditionDTO>(staticDataFile.Descendants("Condition"));
- this._victoryConditionsTable.Records = victoryConditions.Select(vc => vc.Item1 as IVictoryConditionDTO).ToList();
- }
-
- private void LoadUnitGroupTypes(XDocument staticDataFile)
- {
- var unitGroupTypes = GetBaseComponentDTOs<UnitGroupTypeDTO>(staticDataFile.Descendants("UnitGroupType")).ToList();
-
- // Set type specific properties
- unitGroupTypes.ForEach(o =>
- {
- o.Item1.TextDisplay = o.Item2.Attribute("TextDisplay").Value;
- o.Item1.Level = Convert.ToInt32(o.Item2.Attribute("Level").Value);
- });
-
- // Add to context
- this._unitGroupTypesTable.Records = unitGroupTypes.Select(p => p.Item1 as IUnitGroupTypeDTO).ToList();
- }
-
- private void LoadUnitGeogTypes(XDocument staticDataFile)
- {
- var unitGeogTypes = GetBaseComponentDTOs<UnitGeogTypeDTO>(staticDataFile.Descendants("UnitGeogType")).ToList();
-
- // Add to context
- this._unitGeogTypesTable.Records = unitGeogTypes.Select(p => p.Item1 as IUnitGeogTypeDTO).ToList();
- }
-
- private void LoadUnitTypes(XDocument staticDataFile)
- {
- // Get base type with properties
- var unitTypes = GetBaseComponentDTOs<UnitTypeDTO>(staticDataFile.Descendants("UnitType")).ToList();
-
- // Set type specific properties
- unitTypes.ForEach(o =>
- {
- o.Item1.TextDisplay = o.Item2.Attribute("TextDisplay").Value;
- o.Item1.UnitBaseTypeID = Convert.ToInt32(o.Item2.Attribute("UnitBaseType").Value);
- });
-
- // Load stat modifier data
- unitTypes.ForEach(o => LoadStatModifierData(o.Item2, o.Item1));
-
- // Add to context
- this._unitTypesTable.Records = unitTypes.Select(p => p.Item1 as IUnitTypeDTO).ToList();
- }
-
- private void LoadUnitClasses(XDocument staticDataFile)
- {
- // Get base type with properties
- var unitClasses = GetBaseComponentDTOs<UnitClassDTO>(staticDataFile.Descendants("UnitClass")).ToList();
-
- // Set type specific properties
- unitClasses.ForEach(o =>
- {
- o.Item1.TextDisplay = o.Item2.Attribute("TextDisplay").Value;
- });
-
- // Load stat modifier data
- unitClasses.ForEach(o => LoadStatModifierData(o.Item2, o.Item1));
-
- // Add to context
- this._unitClassesTable.Records = unitClasses.Select(p => p.Item1 as IUnitClassDTO).ToList();
- }
-
-
- private void LoadMissionData(XDocument staticDataFile)
- {
- // UnitTasks
- var unitTasks = GetBaseComponentDTOs<UnitTaskDTO>(staticDataFile.Descendants("UnitTask")).ToList();
- this._unitTasksTable.Records = unitTasks.Select(p => p.Item1 as IUnitTaskDTO).ToList();
-
- //MissionObjectives
- var missionObjectives = GetBaseComponentDTOs<MissionObjectiveDTO>(staticDataFile.Descendants("MissionObjective")).ToList();
-
- missionObjectives.ForEach(o =>
- {
- o.Item1.Priority = Convert.ToInt32(o.Item2.Attribute("Priority").Value);
- o.Item1.TurnOrder = Convert.ToInt32(o.Item2.Attribute("TurnOrder").Value);
- });
-
- this._missionObjectivesTable.Records = missionObjectives.Select(mo => mo.Item1 as IMissionObjectiveDTO).ToList();
- }
-
- private void LoadDemographicClasses(XDocument staticDataFile)
- {
- // Get base type with properties
- var demographicClasses = GetBaseComponentDTOs<DemographicClassDTO>(staticDataFile.Descendants("DemographicClass")).ToList();
-
- // Set type specific properties
- demographicClasses.ForEach(o =>
- {
- o.Item1.TextDisplay = o.Item2.Attribute("TextDisplay").Value;
- o.Item1.DemographicType = Convert.ToInt32(o.Item2.Attribute("DemographicType").Value);
- });
-
- // Load stat modifier data
- demographicClasses.ForEach(o => LoadStatModifierData(o.Item2, o.Item1));
-
-
- // Add to context
- this._demographicClassesTable.Records = demographicClasses.Select(p => p.Item1 as IDemographicClassDTO).ToList();
- }
-
- private void LoadDemographicTypes(XDocument staticDataFile)
- {
- // Get base type with properties
- var demographicTypes = GetBaseComponentDTOs<DemographicTypeDTO>(staticDataFile.Descendants("DemographicType")).ToList();
-
- demographicTypes.ForEach(dt =>
- {
- dt.Item1.DisplayOrder = Convert.ToInt32(dt.Item2.Attribute("DisplayOrder").Value);
- });
-
- // Add to context
- this._demographicTypesTable.Records = demographicTypes.Select(p => p.Item1 as IDemographicTypeDTO).ToList();
- }
-
- private void LoadDemographics(XDocument gameDataFile, XDocument componentDataFile)
- {
- var defaultDemographicsList = GetBaseComponentDTOs<DemographicDTO>(componentDataFile.Descendants("Demographic")).ToList();
- var gameDemographicsList = GetBaseComponentDTOs<DemographicDTO>(gameDataFile.Descendants("Demographic")).ToList();
-
- var demographicsList = defaultDemographicsList.Concat(gameDemographicsList).ToList();
-
- // Set type specific properties
- demographicsList.ForEach(o =>
- {
- o.Item1.DemographicClass = Convert.ToInt32(o.Item2.Attribute("DemographicClass").Value);
- o.Item1.Value = o.Item2.Attribute("Value").Value;
- });
-
- // Add to context
- this._demographicsTable.Records = demographicsList.Select(p => p.Item1 as IDemographicDTO).ToList();
- }
-
-
- private void LoadFactions(XDocument gameDataFile)
- {
- // Get base type with properties
- var factionList = GetBaseComponentDTOs<FactionDTO>(gameDataFile.Descendants("Faction")).ToList();
-
- // Add to context
- this._factionsTable.Records = factionList.Select(p => p.Item1 as IFactionDTO).ToList();
- }
-
- private void LoadCountries(XDocument gameDataFile)
- {
- // Get base type with properties
- var countryList = GetBaseComponentDTOs<CountryDTO>(gameDataFile.Descendants("Country")).ToList();
-
- // Set type specific properties
- countryList.ForEach(o =>
- {
- o.Item1.Faction = Convert.ToInt32(o.Item2.Attribute("Faction").Value);
- });
-
-
- // Add to context
- this._countriesTable.Records = countryList.Select(p => p.Item1 as ICountryDTO).ToList();
- }
-
- private void LoadPlayers(XDocument gameDataFile)
- {
- // Get base type with properties
- var playerList = GetBaseComponentDTOs<PlayerDTO>(gameDataFile.Descendants("Player")).ToList();
-
- // Set type specific properties
- playerList.ForEach(o =>
- {
- var units = o.Item2.Descendants("Unit").ToList();
- units.ForEach(u => o.Item1.UnplacedReinforcements.Add(Convert.ToInt32(u.Attribute("ID").Value)));
- o.Item1.Country = Convert.ToInt32(o.Item2.Attribute("Country").Value);
- o.Item1.ReinforcementPoints = Convert.ToInt32(o.Item2.Attribute("ReinforcementPoints").Value);
- o.Item1.IsCurrentPlayer = (o.Item2.Attribute("IsCurrentPlayer") != null) && Convert.ToBoolean(o.Item2.Attribute(("IsCurrentPlayer")).Value);
- o.Item1.IsAIPlayer = (o.Item2.Attribute("IsAIPlayer") != null) && Convert.ToBoolean(o.Item2.Attribute(("IsAIPlayer")).Value);
- });
-
-
-
-
- // Add to context
- this._playersTable.Records = playerList.Select(p => p.Item1 as IPlayerDTO).ToList();
- }
-
- private void LoadBoard(XDocument boardDataFile)
- {
- // Board Data
- var dimension = boardDataFile.Descendants("Attributes").SingleOrDefault();
-
- var board = new BoardDTO
- {
- Title = dimension.Attribute("Title").Value,
- Height = Convert.ToInt32(dimension.Attribute("Height").Value),
- Width = Convert.ToInt32(dimension.Attribute("Width").Value),
- CellSize = Convert.ToInt32(dimension.Attribute("CellSize").Value),
- CellMaxUnits = Convert.ToInt32(dimension.Attribute("CellSize").Value),
- } as IBoardDTO;
-
- var nodeList = boardDataFile.Descendants("Node");
- var nodesToSave = new List<INodeDTO>();
- var tilesToSave = new List<ITileDTO>();
-
- foreach (var e in nodeList)
- {
- var c = new CoordinateDTO
- {
- X = Convert.ToInt32(e.Descendants("Coordinate").SingleOrDefault().Attribute("X").Value),
- Y = Convert.ToInt32(e.Descendants("Coordinate").SingleOrDefault().Attribute("Y").Value),
- Z = Convert.ToInt32(e.Descendants("Coordinate").SingleOrDefault().Attribute("Z").Value)
- } as ICoordinateDTO;
-
-
- var dgs = e.Descendants("Demographics").Descendants("Demographic")
- .Select(d =>
- new DemographicDTO
- {
- ID = Convert.ToInt32(d.Attribute("ID").Value),
- Orientation = (d.Attribute("Orientation") != null) ? d.Attribute("Orientation").Value : ""
- } as IDemographicDTO );
-
-
- var v = Convert.ToInt32(e.Descendants("Tile").SingleOrDefault().Attribute("VictoryPoints").Value);
-
- var t = new TileDTO
- {
- UID = Guid.NewGuid(),
- VictoryPoints = v,
- Location = c,
- Demographics = dgs
- } as ITileDTO;
-
- tilesToSave.Add(t);
-
-
- var n = new NodeDTO
- {
- Name = "Node - {0}".F(c.ToString()),
- UID = Guid.NewGuid(),
- Location = c,
- Country = Convert.ToInt32(e.Descendants("Country").SingleOrDefault().Attribute("ID").Value),
- DefaultTile = t
- } as INodeDTO;
-
-
- nodesToSave.Add(n);
-
- }
-
- // Add to context
- this._tilesTable.Records = tilesToSave;
- this._nodesTable.Records = nodesToSave;
- this._board = board;
- }
-
- private void LoadUnits(XDocument unitDataFile)
- {
- var unitUnitList = unitDataFile.Descendants("Unit");
- var unitsToSave = new List<IUnitDTO>();
-
- foreach (var e in unitUnitList)
- {
-
- // No Location indicates unplaced unit
- var c = (e.Descendants("Coordinate").SingleOrDefault() == null) ? null : new CoordinateDTO
- {
- X = Convert.ToInt32(e.Descendants("Coordinate").SingleOrDefault().Attribute("X").Value),
- Y = Convert.ToInt32(e.Descendants("Coordinate").SingleOrDefault().Attribute("Y").Value),
- Z = Convert.ToInt32(e.Descendants("Coordinate").SingleOrDefault().Attribute("Z").Value)
- };
-
-
-
- var m = new UnitDTO
- {
- ID = Convert.ToInt32(e.Attribute("ID").Value),
- UID = Guid.NewGuid(),
- Name = e.Attribute("Name").Value,
- SubNodeLocation = Convert.ToInt32(e.Descendants("SubNodeLocation").SingleOrDefault().Attribute("Value").Value),
- Location = c,
- Description = e.Attribute("Description").Value,
- Country = Convert.ToInt32(e.Descendants("Country").SingleOrDefault().Attribute("ID").Value),
- StackOrder = Convert.ToInt32(e.Attribute("StackOrder").Value),
- UnitClass = Convert.ToInt32(e.Descendants("UnitInfo").SingleOrDefault().Attribute("UnitClass").Value),
- UnitType = Convert.ToInt32(e.Descendants("UnitInfo").SingleOrDefault().Attribute("UnitType").Value),
- UnitGroupType = Convert.ToInt32(e.Descendants("UnitInfo").SingleOrDefault().Attribute("UnitGroupType").Value)
-
- };
-
- // Movement stats if this is a saved game
- // Data saved mid-turn
- if (e.Descendants("MovementStats").SingleOrDefault() != null)
- {
- m.CurrentHasPerformedAction =
- Convert.ToBoolean(e.Descendants("MovementStats").SingleOrDefault().Attribute("CurrentHasPerformedAction").Value);
- m.CurrentMovementPoints =
- Convert.ToInt32(e.Descendants("MovementStats").SingleOrDefault().Attribute("CurrentMovementPoints").Value);
- m.CurrentRemoteFirePoints =
- Convert.ToInt32(e.Descendants("MovementStats").SingleOrDefault().Attribute("CurrentRemoteFirePoints").Value);
- }
-
-
- var tu = new List<int>();
- unitsToSave.Add(m);
- }
-
-
- this._unitsTable.Records = unitsToSave;
- }
-
-
- private void LoadUnitAssignments(XDocument gameDataFile)
- {
- var lookupTmp = gameDataFile.Descendants("UnitAssignment");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.Unit = Convert.ToInt32(e.Attribute("Unit").Value);
- d.AssignedToUnit = Convert.ToInt32(e.Attribute("AssignedToUnit").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitAssignments = lookupListTmp;
- }
-
- private void LoadUnitTransports(XDocument gameDataFile)
- {
- var lookupTmp = gameDataFile.Descendants("UnitTransport");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.Unit = Convert.ToInt32(e.Attribute("Unit").Value);
- d.TransportUnit = Convert.ToInt32(e.Attribute("TransportUnit").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitTransports = lookupListTmp;
- }
-
- private void LoadUnitBaseTypeUnitClasses(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("UnitBaseTypeUnitClass");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.UnitBaseType = Convert.ToInt32(e.Attribute("UnitBaseType").Value);
- d.UnitClass = Convert.ToInt32(e.Attribute("UnitClass").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitBaseTypeUnitClassesLookup = lookupListTmp;
- }
-
- private void LoadUnitBaseTypeUnitGeogTypes(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("UnitBaseTypeUnitGeogType");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.UnitBaseType = Convert.ToInt32(e.Attribute("UnitBaseType").Value);
- d.UnitGeogType = Convert.ToInt32(e.Attribute("UnitGeogType").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitBaseTypeUnitGeogTypesLookup = lookupListTmp;
- }
-
- private void LoadHybridDemographicClasses(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("HybridDemographicClass");
- var lookupListTmp = new List<int>();
-
- foreach (var e in lookupTmp)
- {
- lookupListTmp.Add(Convert.ToInt32(e.Attribute("DemographicClass").Value));
- }
-
- this._hybridDemographicClasses = lookupListTmp;
- }
-
- private void LoadMovementHinderancesInDirection(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("MovementHinderance");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.DemographicClass = Convert.ToInt32(e.Attribute("DemographicClass").Value);
- d.UnitGeogType = Convert.ToInt32(e.Attribute("UnitGeogType").Value);
- d.Direction = (Direction)Convert.ToInt32(e.Attribute("Direction").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._movementHinderanceInDirection = lookupListTmp;
- }
-
- private void LoadUnitGeogTypeDemographicClasses(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("UnitGeogTypeDemographicClass");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.UnitGeogType = Convert.ToInt32(e.Attribute("UnitGeogType").Value);
- d.DemographicClass = Convert.ToInt32(e.Attribute("DemographicClass").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitGeogTypeDemographicClassesLookup = lookupListTmp;
- }
-
- private void LoadUnitGroupTypeUnitTasks(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("UnitGroupTypeUnitTask");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.UnitGroupType = Convert.ToInt32(e.Attribute("UnitGroupType").Value);
- d.UnitTask = Convert.ToInt32(e.Attribute("UnitTask").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitGroupTypeUnitTaskLookup = lookupListTmp;
- }
-
- private void LoadMissionObjectiveUnitTasks(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("MissionObjectiveUnitTask");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.MissionObjective = Convert.ToInt32(e.Attribute("MissionObjective").Value);
- d.UnitTask = Convert.ToInt32(e.Attribute("UnitTask").Value);
- d.StepOrder = Convert.ToInt32(e.Attribute("StepOrder").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._missionObjectiveUnitTasks = lookupListTmp;
- }
-
- private void LoadUnitTaskUnitClasses(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("UnitTaskUnitClass");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.UnitClass = Convert.ToInt32(e.Attribute("UnitClass").Value);
- d.UnitTask = Convert.ToInt32(e.Attribute("UnitTask").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitTaskUnitClassesLookup = lookupListTmp;
- }
-
- private void LoadUnitGeogTypeMovementOverrides(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("UnitGeogTypeMovementOverrides").First().Descendants("Override");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.UnitGeogType = Convert.ToInt32(e.Attribute("UnitGeogType").Value);
- d.Geography = Convert.ToInt32(e.Attribute("DemographicClassA").Value);
- d.Infrastructure = Convert.ToInt32(e.Attribute("DemographicClassB").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitGeogTypeMovementOverrides = lookupListTmp;
- }
-
- private void LoadUnitTypeUnitGeogTypeBattleEffectives(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("UnitTypeUnitGeogTypeBattleEffective").First().Descendants("BattleEffective");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.UnitType = Convert.ToInt32(e.Attribute("UnitType").Value);
- d.UnitGeogType = Convert.ToInt32(e.Attribute("UnitGeogType").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitBattleEffectiveLookup = lookupListTmp;
- }
-
- private void LoadUnitTransportUnitTypeUnitClasses(XDocument lookupDataFile)
- {
- var lookupTmp = lookupDataFile.Descendants("UnitTransportUnitTypeUnitClasses").First().Descendants("TransportEffective");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.TransportUnitType = Convert.ToInt32(e.Attribute("TransportUnitType").Value);
- d.CarriedUnitType = Convert.ToInt32(e.Attribute("CarriedUnitType").Value);
- d.CarriedUnitClass = Convert.ToInt32(e.Attribute("CarriedUnitClass").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._unitTransportUnitTypeUnitClasses = lookupListTmp;
- }
-
- private void LoadFactionVictoryConditions(XDocument gameDataFile)
- {
- var lookupTmp = gameDataFile.Descendants("VictoryCondition");
- var lookupListTmp = new List<dynamic>();
-
- foreach (var e in lookupTmp)
- {
- dynamic d = new ExpandoObject();
- d.Faction = Convert.ToInt32(e.Attribute("Faction").Value);
- d.Condition = Convert.ToInt32(e.Attribute("Condition").Value);
- d.Value = Convert.ToInt32(e.Attribute("Value").Value);
-
- lookupListTmp.Add(d);
- }
-
- this._factionVictoryConditions = lookupListTmp;
- }
-
- #endregion
-
- #region Helper Methods
-
- /// <summary>
- /// Returns a list of IBaseGameComponentDTO and matching source elements with the properties set from the data source
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="elements"></param>
- /// <returns></returns>
- private IEnumerable<Tuple<T, XElement>> GetBaseComponentDTOs<T>(IEnumerable<XElement> elements)
- where T : class, IBaseGameComponentDTO, new()
- {
- var retVal = elements
- .Select(c => new {element = c, pair = new Tuple<T, XElement>(GetBaseComponentDTO<T>(c), c)})
- .Select(p => p.pair);
-
- return retVal;
- }
-
- /// <summary>
- /// Returns an IBaseGameComponentDTO with the properties set from the data source
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="e"></param>
- /// <returns></returns>
- private T GetBaseComponentDTO<T>(XElement e)
- where T : class, IBaseGameComponentDTO, new()
- {
- var retVal = new T
- {
- UID = Guid.NewGuid(),
- Name = e.Attribute("Name").Value,
- Description = e.Attribute("Description").Value,
- ID = Convert.ToInt32(e.Attribute("ID").Value)
- } ;
-
- return retVal;
- }
-
-
- private void LoadStatModifierData(XElement e, IStatModifier dto)
- {
- dto.AttackModifier = (e.Attribute("AttackModifier") != null) ? Convert.ToDouble(e.Attribute("AttackModifier").Value) : 0;
- dto.AttackDistanceModifier = (e.Attribute("AttackDistanceModifier") != null) ? Convert.ToDouble(e.Attribute("AttackDistanceModifier").Value) : 0;
- dto.DefenceModifier = (e.Attribute("DefenceModifier") != null) ? Convert.ToDouble(e.Attribute("DefenceModifier").Value) : 0;
- dto.MovementModifier = (e.Attribute("MovementModifier") != null) ? Convert.ToDouble(e.Attribute("MovementModifier").Value) : 0;
- dto.UnitWeightModifier = (e.Attribute("UnitWeightModifier") != null) ? Convert.ToDouble(e.Attribute("UnitWeightModifier").Value) : 0;
- dto.AllowableWeightModifier = (e.Attribute("AllowableWeightModifier") != null) ? Convert.ToDouble(e.Attribute("AllowableWeightModifier").Value) : 0;
- dto.UnitCostModifier = (e.Attribute("UnitCostModifier") != null) ? Convert.ToDouble(e.Attribute("UnitCostModifier").Value) : 0;
- dto.StealthModifier = (e.Attribute("StealthModifier") != null) ? Convert.ToDouble(e.Attribute("StealthModifier").Value) : 0;
- }
-
- #endregion
-
-
- }
-
-
-
- }