我正在创建一个基于文本的基础RPG,我正在尝试使用xml来保存游戏。这是从xml调用播放器数据的代码:
public class SuperAdventure() {
private Player _player;
private Monster _currentMonster;
private const string PLAYER_DATA_FILE_NAME = "PlayerData.xml";
public SuperAdventure()
{
InitializeComponent();
if (File.Exists(PLAYER_DATA_FILE_NAME))
{
_player = Player.CreatePlayerFromXmlString(File.ReadAllText(PLAYER_DATA_FILE_NAME));
}
else
{
_player = Player.CreateDefaultPlayer();
}
MoveTo(_player.CurrentLocation);
UpdatePlayerStats();
}
}
我也确定正确创建了xml。当我关闭游戏时,我可以手动找到xml。所有统计数据都已保存,但重新打开游戏后,播放器将重置为默认统计数据和项目。我不确定函数调用的顺序是否重要,或者xml的创建是否会影响游戏对xml的使用。
这里是CreatePlayerFromXmlString()函数:
public static Player CreatePlayerFromXmlString(string xmlPlayerData)
{
try
{
XmlDocument playerData = new XmlDocument();
playerData.LoadXml(xmlPlayerData);
int currentHitPoints = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/CurrentHItPoints").InnerText);
int maximumHitPoints = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/MaximumHitPoints").InnerText);
int gold = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/Gold").InnerText);
int experiencePoints = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/ExperiencePoints").InnerText);
Player player = new Player(currentHitPoints, maximumHitPoints, gold, experiencePoints);
int currentLocationID = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/CurrentLocation").InnerText);
player.CurrentLocation = World.LocationByID(currentLocationID);
foreach (XmlNode node in playerData.SelectNodes("/Player/InventoryItems/InventoryItem"))
{
int id = Convert.ToInt32(node.Attributes["ID"].Value);
int quantity = Convert.ToInt32(node.Attributes["Quantity"].Value);
for (int i = 0; i < quantity; i++)
{
player.AddItemToInventory(World.ItemByID(id));
}
}
foreach (XmlNode node in playerData.SelectNodes("/Player/PlayerQuests/PlayerQuest"))
{
int id = Convert.ToInt32(node.Attributes["ID"].Value);
bool isCompleted = Convert.ToBoolean(node.Attributes["IsCompleted"].Value);
PlayerQuest playerQuest = new PlayerQuest(World.QuestByID(id));
playerQuest.IsCompleted = isCompleted;
player.Quests.Add(playerQuest);
}
return player;
}
catch
{
//If there was an error with the XML data, return a default player object
return Player.CreateDefaultPlayer();
}
}
答案 0 :(得分:2)
问题是当游戏通过try代码块时出现错误。这导致它移动到catch块并改为创建默认播放器。搜索currentHitPoints的代码行中的字符串拼写错误 - visual studio没有将其视为错误,因为它是传递给XML函数的字符串。
int currentHitPoints = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/CurrentHItPoints").InnerText);
"/Player/Stats/CurrentHItPoints"
应为"/Player/Stats/CurrentHitPoints"